portaki-cli 10.7.0

Portaki module CLI (portaki) — init, build, test, hosted sandbox, OCI publish and registry announcement
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
//! `changelog` of the published manifest: what is new in this version, for hosts on an older one.
//!
//! One entry per line, every language side by side: `[{ "fr": "…", "en": "…" }, …]`. For each
//! language, `portaki release --notes` wins (`--notes fr:"…"`, or unprefixed in `--notes-lang`);
//! otherwise the version's section of `CHANGELOG.<lang>.md`, and of `CHANGELOG.md` in English
//! (Keep a Changelog or release-please: `## [x.y.z]` or `## x.y.z`, then bullets). Nothing said
//! in any language: the field stays as `portaki.module.json` has it.
//!
//! Untagged `--notes` are in the listing's first language (`publishedLangs[0]` of
//! `listing.json`), else `fr` — the registry's fallback language.
//!
//! A line that reads like a commit message (`chore: bump deps`) is refused in `--notes`, written
//! by hand. In a `CHANGELOG*.md` — often generated — it is dropped with a warning: a language left
//! without a line then counts as absent, and the registry keeps a stable version as a draft.
//!
//! A stable version stays pending at the registry until its changelog covers every language of
//! the module's listing — writing each `CHANGELOG.<lang>.md` is what keeps a CI green and live.

use std::collections::BTreeMap;
use std::path::Path;

use anyhow::{Context, Result};

/// Bounds of `schema/module.v1.json` and of the release-notes contract — a host reads two or
/// three lines, not a release note.
pub const MAX_LINES: usize = 5;
pub const MAX_CHARS: usize = 160;

/// One changelog line, by language.
pub type Line = BTreeMap<String, String>;

/// The registry's fallback language (`ModuleListing.FALLBACK_LANGUAGE`).
pub const FALLBACK_LANG: &str = "fr";

/// The language of `CHANGELOG.md`, unsuffixed — release-please writes it in English.
pub const UNSUFFIXED_LANG: &str = "en";

/// The changelog file that holds `lang`.
pub fn file_for(lang: &str) -> String {
    if lang == UNSUFFIXED_LANG {
        "CHANGELOG.md".to_string()
    } else {
        format!("CHANGELOG.{lang}.md")
    }
}

/// The language of untagged `--notes`: the listing's first, else `fr`.
pub fn default_lang(module_root: &Path) -> String {
    std::fs::read_to_string(module_root.join("listing.json"))
        .ok()
        .and_then(|raw| serde_json::from_str::<serde_json::Value>(&raw).ok())
        .and_then(|listing| {
            listing
                .pointer("/publishedLangs/0")
                .and_then(serde_json::Value::as_str)
                .map(str::to_string)
        })
        .filter(|lang| lang.len() == 2 && lang.chars().all(|c| c.is_ascii_lowercase()))
        .unwrap_or_else(|| FALLBACK_LANG.to_string())
}

/// Synced copy of portaki-platform's `contracts/release-notes-rules.json`: the registry
/// (`ReleaseNotes`), the console's « Compléter la version » drawer and this CLI apply the same
/// rules. Replace the file when the platform's changes — the tests replay its examples.
const RULES: &str = include_str!("../contracts/release-notes-rules.json");

#[derive(serde::Deserialize)]
struct Rules {
    commit: CommitRules,
}

#[derive(serde::Deserialize)]
#[serde(rename_all = "camelCase")]
struct CommitRules {
    conventional_types: Vec<String>,
    words: Vec<String>,
}

fn rules() -> &'static Rules {
    static PARSED: std::sync::OnceLock<Rules> = std::sync::OnceLock::new();
    PARSED.get_or_init(|| serde_json::from_str(RULES).expect("release-notes-rules.json is JSON"))
}

/// A commit message, not a line a host reads — the contract's `commit.rule`.
///
/// Trimmed and lowercased, it starts with (a) a conventional type, an optional `(scope)`, an
/// optional `!`, then `:` right away — « fix: x », « feat(ui)!: x »; or (b) one of the words,
/// followed by the end of the line or a character that is neither a letter nor a digit. A type
/// alone stays prose: « Style des cartes revu », « Chorégraphie des arrivées ».
pub fn looks_like_commit(line: &str) -> bool {
    let line = line.trim().to_lowercase();
    let rules = &rules().commit;
    let conventional = rules.conventional_types.iter().any(|kind| {
        let Some(mut rest) = line.strip_prefix(kind.as_str()) else {
            return false;
        };
        if let Some(scoped) = rest.strip_prefix('(') {
            match scoped.split_once(')') {
                Some((_, after)) => rest = after,
                None => return false,
            }
        }
        rest.strip_prefix('!').unwrap_or(rest).starts_with(':')
    });
    conventional
        || rules.words.iter().any(|word| {
            line.strip_prefix(word.as_str())
                .is_some_and(|rest| !rest.chars().next().is_some_and(char::is_alphanumeric))
        })
}

/// Refuses a commit-like `--notes` line: it was written by hand, for this purpose.
fn refuse_commit(text: &str) -> Result<()> {
    if looks_like_commit(text) {
        anyhow::bail!(
            "--notes: « {text} » reads like a commit message, not a line for hosts — say what \
             changes for them (e.g. « Le code clavier arrive la veille »); the registry keeps a \
             stable version with such a line invisible to hosts"
        );
    }
    Ok(())
}

/// `fr:Nouveau` → `("fr", "Nouveau")`. Two lowercase letters, a colon, then text right after:
/// `ui: fix` stays a line of its own, not a line in « ui ».
pub fn split_lang(value: &str) -> Option<(&str, &str)> {
    let (lang, text) = value.split_once(':')?;
    let tagged = lang.len() == 2
        && lang.chars().all(|c| c.is_ascii_lowercase())
        && text.chars().next().is_some_and(|c| !c.is_whitespace());
    tagged.then_some((lang, text))
}

/// A `[lang:]text` flag value, in `default_lang` when untagged.
pub fn tagged(value: &str, default_lang: &str) -> (String, String) {
    match split_lang(value) {
        Some((lang, text)) => (lang.to_string(), text.trim().to_string()),
        None => (default_lang.to_string(), value.trim().to_string()),
    }
}

/// 1 to [`MAX_CHARS`] characters, or the flag's name and the culprit.
pub fn check_text(flag: &str, text: &str) -> Result<()> {
    if text.is_empty() || text.chars().count() > MAX_CHARS {
        anyhow::bail!("{flag}: each text holds 1 to {MAX_CHARS} characters — « {text} »");
    }
    Ok(())
}

/// The lines to publish, one entry per line with every language that has one.
///
/// `--notes` is written for this purpose, so a line off bounds is refused. A `CHANGELOG.md` is
/// written for developers: its first lines are kept and long ones shortened.
pub fn lines(
    notes: &[String],
    default_lang: &str,
    module_root: &Path,
    version: &str,
) -> Result<Vec<Line>> {
    let mut by_lang: BTreeMap<String, Vec<String>> = BTreeMap::new();
    for note in notes {
        let (lang, text) = tagged(note, default_lang);
        check_text("--notes", &text)?;
        refuse_commit(&text)?;
        by_lang.entry(lang).or_default().push(text);
    }
    if let Some((lang, many)) = by_lang.iter().find(|(_, lines)| lines.len() > MAX_LINES) {
        anyhow::bail!(
            "--notes: at most {MAX_LINES} lines per language, got {} in {lang}",
            many.len()
        );
    }
    for (lang, path) in changelog_files(module_root)? {
        if by_lang.contains_key(&lang) {
            continue;
        }
        let markdown =
            std::fs::read_to_string(&path).with_context(|| format!("read {}", path.display()))?;
        // Generated most of the time: a commit line is dropped from it, never a blocker.
        let (commits, kept): (Vec<String>, Vec<String>) = section(&markdown, version)
            .into_iter()
            .partition(|line| looks_like_commit(line));
        if !commits.is_empty() {
            let source = path.file_name().unwrap_or_default().to_string_lossy();
            crate::ui::warn(format!(
                "{source} {version}: dropped {} line(s) that read like commit messages — {}",
                commits.len(),
                commits.join(" · ")
            ));
        }
        let found: Vec<String> = kept
            .into_iter()
            .take(MAX_LINES)
            .map(|line| shorten(&line))
            .collect();
        if !found.is_empty() {
            by_lang.insert(lang, found);
        }
    }
    let count = by_lang.values().map(Vec::len).max().unwrap_or(0);
    Ok((0..count)
        .map(|index| {
            by_lang
                .iter()
                .filter_map(|(lang, lines)| Some((lang.clone(), lines.get(index)?.clone())))
                .collect()
        })
        .collect())
}

/// `CHANGELOG.md` in English, `CHANGELOG.<lang>.md` in its own.
fn changelog_files(module_root: &Path) -> Result<Vec<(String, std::path::PathBuf)>> {
    let entries = match std::fs::read_dir(module_root) {
        Ok(entries) => entries,
        Err(failure) if failure.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
        Err(failure) => {
            return Err(failure).with_context(|| format!("read {}", module_root.display()))
        }
    };
    let mut files = Vec::new();
    for entry in entries {
        let path = entry?.path();
        let Some(name) = path.file_name().and_then(|name| name.to_str()) else {
            continue;
        };
        let lang = match name
            .strip_prefix("CHANGELOG")
            .and_then(|rest| rest.strip_suffix(".md"))
        {
            Some("") => UNSUFFIXED_LANG.to_string(),
            Some(rest) => match rest.strip_prefix('.') {
                Some(lang) if lang.len() == 2 && lang.chars().all(|c| c.is_ascii_lowercase()) => {
                    lang.to_string()
                }
                _ => continue,
            },
            None => continue,
        };
        files.push((lang, path));
    }
    Ok(files)
}

/// The top-level bullets under `## [version]` / `## version`, cleaned of release-please's
/// `**scope:**` prefix and trailing commit link.
fn section(markdown: &str, version: &str) -> Vec<String> {
    let mut inside = false;
    let mut bullets = Vec::new();
    for line in markdown.lines() {
        if let Some(heading) = line.strip_prefix("## ") {
            if inside {
                break;
            }
            inside = heading_version(heading) == version;
            continue;
        }
        let bullet = line.strip_prefix("* ").or_else(|| line.strip_prefix("- "));
        if let (true, Some(bullet)) = (inside, bullet) {
            let cleaned = clean(bullet);
            if !cleaned.is_empty() {
                bullets.push(cleaned);
            }
        }
    }
    bullets
}

/// `[0.6.1](https://…) (2026-09-24)` → `0.6.1`; `v1.2.0 - 2026-09-24` → `1.2.0`.
fn heading_version(heading: &str) -> &str {
    let heading = heading.trim();
    let token = match heading.strip_prefix('[') {
        Some(rest) => rest.split(']').next().unwrap_or(""),
        None => heading.split_whitespace().next().unwrap_or(""),
    };
    token.strip_prefix('v').unwrap_or(token)
}

/// `**access-guide:** add listing ([2b27528](https://…))` → `add listing`.
fn clean(bullet: &str) -> String {
    let mut text = bullet.trim();
    if let Some(rest) = text.strip_prefix("**") {
        if let Some((_, after)) = rest.split_once(":**") {
            text = after.trim_start();
        }
    }
    if text.ends_with(')') {
        if let Some(at) = text.rfind(" ([") {
            text = &text[..at];
        }
    }
    text.trim().to_string()
}

fn shorten(line: &str) -> String {
    if line.chars().count() <= MAX_CHARS {
        return line.to_string();
    }
    let kept: String = line.chars().take(MAX_CHARS - 1).collect();
    format!("{}…", kept.trim_end())
}

/// Writes `changelog` into the manifest, one entry per line. No line, no change.
pub fn stamp(raw: &str, lines: &[Line]) -> Result<String> {
    if lines.is_empty() {
        return Ok(raw.to_string());
    }
    let mut manifest: serde_json::Value =
        serde_json::from_str(raw).context("parse publish manifest")?;
    manifest
        .as_object_mut()
        .context("publish manifest is not a JSON object")?
        .insert("changelog".to_string(), serde_json::to_value(lines)?);
    serde_json::to_string_pretty(&manifest).context("serialise publish manifest")
}

/// What the registry is told beside the manifest, for this release only: why a permission is
/// added (`--permission-reason <permission>=[lang:]text`) and whether the host has to act
/// (`--host-action-required`, `--host-action [lang:]text`). Sent with the announcement, not
/// stamped into the manifest: the console can complete it later, and an older SDK schema would
/// refuse the extra keys.
pub fn release_notes(
    permission_reasons: &[String],
    host_action_required: bool,
    host_action: &[String],
    default_lang: &str,
) -> Result<serde_json::Value> {
    let mut reasons: BTreeMap<String, BTreeMap<String, String>> = BTreeMap::new();
    for value in permission_reasons {
        let Some((permission, reason)) = value.split_once('=') else {
            anyhow::bail!("--permission-reason: expected <permission>=[lang:]text — « {value} »");
        };
        let permission = permission.trim();
        if !portaki_sdk::permission::is_known(permission) {
            anyhow::bail!("--permission-reason: unknown permission « {permission} »");
        }
        let (lang, text) = tagged(reason, default_lang);
        check_text("--permission-reason", &text)?;
        reasons
            .entry(permission.to_string())
            .or_default()
            .insert(lang, text);
    }
    let mut action = BTreeMap::new();
    for value in host_action {
        let (lang, text) = tagged(value, default_lang);
        check_text("--host-action", &text)?;
        action.insert(lang, text);
    }
    Ok(serde_json::json!({
        "permissionReasons": reasons,
        "hostActionRequired": host_action_required || !action.is_empty(),
        "hostAction": action,
    }))
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::tempdir;

    const RELEASE_PLEASE: &str = "# Changelog

## [0.6.1](https://github.com/o/r/compare/a-v0.6.0...a-v0.6.1) (2026-09-24)


### Bug Fixes

* **deps:** build against portaki-sdk 6.11 ([18cec5f](https://github.com/o/r/commit/18cec5f))

## [0.6.0](https://github.com/o/r/compare/a-v0.5.1...a-v0.6.0) (2026-09-23)


### Features

* **access-guide:** add catalogue listing ([2b27528](https://github.com/o/r/commit/2b27528))
* show the keypad code the day before arrival
  * a nested detail that is not a line of its own
";

    /// The English lines alone — what the single-language tests look at.
    fn en(notes: &[String], root: &Path, version: &str) -> Result<Vec<String>> {
        Ok(lines(notes, "en", root, version)?
            .into_iter()
            .filter_map(|line| line.get("en").cloned())
            .collect())
    }

    fn module(changelog: Option<&str>) -> tempfile::TempDir {
        let dir = tempdir().unwrap();
        if let Some(changelog) = changelog {
            fs::write(dir.path().join("CHANGELOG.md"), changelog).unwrap();
        }
        dir
    }

    #[test]
    fn the_version_section_is_found_and_cleaned() {
        let dir = module(Some(RELEASE_PLEASE));

        assert_eq!(
            en(&[], dir.path(), "0.6.0").unwrap(),
            vec![
                "add catalogue listing",
                "show the keypad code the day before arrival"
            ]
        );
        assert_eq!(
            en(&[], dir.path(), "0.6.1").unwrap(),
            vec!["build against portaki-sdk 6.11"]
        );
    }

    #[test]
    fn keep_a_changelog_headings_are_read_too() {
        let dir = module(Some(
            "## [Unreleased]\n- later\n## v1.2.0 - 2026-09-24\n- faster sync\n## 1.1.0\n- older\n",
        ));

        assert_eq!(en(&[], dir.path(), "1.2.0").unwrap(), vec!["faster sync"]);
    }

    #[test]
    fn another_version_or_no_file_gives_nothing() {
        assert!(en(&[], module(Some(RELEASE_PLEASE)).path(), "0.7.0")
            .unwrap()
            .is_empty());
        assert!(en(&[], module(None).path(), "0.6.0").unwrap().is_empty());
    }

    #[test]
    fn a_long_section_is_cut_to_the_schema_bounds() {
        let many: String = (0..8).map(|i| format!("* line {i}\n")).collect();
        let long = format!("* {}\n", "x".repeat(300));
        let dir = module(Some(&format!("## 1.0.0\n{long}{many}")));

        let found = en(&[], dir.path(), "1.0.0").unwrap();
        assert_eq!(found.len(), MAX_LINES);
        assert_eq!(found[0].chars().count(), MAX_CHARS);
        assert!(found[0].ends_with('…'));
    }

    #[test]
    fn notes_win_over_the_file() {
        let dir = module(Some(RELEASE_PLEASE));
        let notes = vec!["Nouveau : code clavier".to_string()];

        assert_eq!(en(&notes, dir.path(), "0.6.0").unwrap(), notes);
    }

    #[test]
    fn notes_off_bounds_are_refused() {
        let dir = module(None);
        let six: Vec<String> = (0..6).map(|i| i.to_string()).collect();

        assert!(lines(&six, "en", dir.path(), "1.0.0").is_err());
        assert!(lines(&["x".repeat(MAX_CHARS + 1)], "en", dir.path(), "1.0.0").is_err());
        assert!(lines(&[" ".to_string()], "en", dir.path(), "1.0.0").is_err());
    }

    /// The contract's examples, replayed as the registry replays them.
    #[test]
    fn the_release_notes_contract_is_applied_as_written() {
        let contract: serde_json::Value = serde_json::from_str(RULES).unwrap();
        assert_eq!(contract["maxLines"], MAX_LINES);
        assert_eq!(contract["maxChars"], MAX_CHARS);
        let examples = |kind: &str| -> Vec<String> {
            contract["commit"]["examples"][kind]
                .as_array()
                .unwrap()
                .iter()
                .map(|example| example.as_str().unwrap().to_string())
                .collect()
        };
        for commit in examples("commit") {
            assert!(looks_like_commit(&commit), "a commit: {commit}");
        }
        for prose in examples("prose") {
            assert!(!looks_like_commit(&prose), "prose: {prose}");
        }
        assert!(!examples("prose").is_empty());
    }

    #[test]
    fn a_commit_message_is_refused_in_notes_and_dropped_from_files() {
        for commit in [
            "chore: bump deps",
            "  Bump portaki-sdk",
            "fix(ui): wrap",
            "feat(x): y",
            "Fix: typo",
            "FEAT: new",
            "refactor the view",
            "deps: bump portaki-sdk to 8.8.1",
        ] {
            assert!(looks_like_commit(commit), "{commit}");
            let dir = module(None);
            assert!(lines(&[commit.to_string()], "en", dir.path(), "1.0.0").is_err());
            let dir = module(Some(&format!("## 1.0.0\n- {commit}\n- keypad code\n")));
            assert_eq!(en(&[], dir.path(), "1.0.0").unwrap(), vec!["keypad code"]);
        }
        for fine in [
            "Fixes the keypad code",
            "Featured on arrival",
            "Code clavier",
        ] {
            assert!(!looks_like_commit(fine), "{fine}");
        }
    }

    /// A release-please deps bump leaves the language without a line: absent, not an error.
    #[test]
    fn a_file_left_with_commits_only_counts_as_absent() {
        let dir = module(Some(
            "## [0.8.2](https://x) (2026-09-26)\n\n### Bug Fixes\n\n* **deps:** bump portaki-sdk to 8.8.1 ([474417d](https://x))\n",
        ));

        assert!(lines(&[], "fr", dir.path(), "0.8.2").unwrap().is_empty());
    }

    /// `CHANGELOG.md` stays English whatever the notes language: no English text tagged `fr`.
    #[test]
    fn the_unsuffixed_changelog_is_english() {
        let dir = module(Some("## 1.0.0\n- keypad code\n"));

        let found = lines(&[], "fr", dir.path(), "1.0.0").unwrap();
        assert_eq!(
            found,
            vec![Line::from([("en".into(), "keypad code".into())])]
        );
        assert_eq!(file_for("en"), "CHANGELOG.md");
        assert_eq!(file_for("fr"), "CHANGELOG.fr.md");
    }

    #[test]
    fn the_default_language_is_the_listings_first_else_french() {
        let dir = module(None);
        assert_eq!(default_lang(dir.path()), "fr");
        fs::write(
            dir.path().join("listing.json"),
            r#"{"publishedLangs":["en","fr"]}"#,
        )
        .unwrap();
        assert_eq!(default_lang(dir.path()), "en");
        fs::write(dir.path().join("listing.json"), r#"{"publishedLangs":[]}"#).unwrap();
        assert_eq!(default_lang(dir.path()), "fr");
    }

    #[test]
    fn no_line_leaves_the_manifest_alone() {
        let raw = r#"{"id":"a","changelog":[{"fr":"déclaré"}]}"#;

        assert_eq!(stamp(raw, &[]).unwrap(), raw);
    }

    #[test]
    fn every_language_file_lands_on_the_same_lines() {
        let dir = module(Some("## 1.0.0\n- keypad code\n- faster sync\n"));
        fs::write(
            dir.path().join("CHANGELOG.fr.md"),
            "## 1.0.0\n- code clavier\n",
        )
        .unwrap();
        fs::write(dir.path().join("CHANGELOG.old.md"), "## 1.0.0\n- ignored\n").unwrap();

        assert_eq!(
            lines(&[], "en", dir.path(), "1.0.0").unwrap(),
            vec![
                Line::from([
                    ("en".into(), "keypad code".into()),
                    ("fr".into(), "code clavier".into())
                ]),
                Line::from([("en".into(), "faster sync".into())]),
            ]
        );
    }

    #[test]
    fn tagged_notes_win_for_their_language_only() {
        let dir = module(Some("## 1.0.0\n- from the file\n"));
        fs::write(
            dir.path().join("CHANGELOG.fr.md"),
            "## 1.0.0\n- du fichier\n",
        )
        .unwrap();
        fs::write(
            dir.path().join("CHANGELOG.de.md"),
            "## 1.0.0\n- aus der Datei\n",
        )
        .unwrap();
        let notes = vec!["fr:Code clavier".to_string(), "ui: untagged".to_string()];

        let found = lines(&notes, "en", dir.path(), "1.0.0").unwrap();

        assert_eq!(found.len(), 1);
        assert_eq!(found[0]["fr"], "Code clavier");
        assert_eq!(found[0]["en"], "ui: untagged");
        assert_eq!(found[0]["de"], "aus der Datei");
    }

    #[test]
    fn more_than_five_notes_in_one_language_are_refused() {
        let dir = module(None);
        let mut notes: Vec<String> = (0..5).map(|i| format!("fr:ligne {i}")).collect();
        notes.push("en:one".into());
        assert!(lines(&notes, "en", dir.path(), "1.0.0").is_ok());
        notes.push("fr:sixième".into());
        assert!(lines(&notes, "en", dir.path(), "1.0.0").is_err());
    }

    #[test]
    fn release_notes_group_reasons_by_permission_and_language() {
        let notes = release_notes(
            &[
                "email=fr:Pour envoyer le code".into(),
                "email=To send the code".into(),
            ],
            false,
            &["fr:Reconnecter la serrure".into()],
            "en",
        )
        .unwrap();

        assert_eq!(
            notes,
            serde_json::json!({
                "permissionReasons": { "email": { "en": "To send the code", "fr": "Pour envoyer le code" } },
                "hostActionRequired": true,
                "hostAction": { "fr": "Reconnecter la serrure" },
            })
        );
    }

    #[test]
    fn release_notes_refuse_what_the_registry_would() {
        for bad in [
            "email",
            "nope=why",
            "email=",
            &format!("email={}", "x".repeat(MAX_CHARS + 1)),
        ] {
            assert!(
                release_notes(&[bad.to_string()], false, &[], "en").is_err(),
                "{bad}"
            );
        }
    }

    fn schema_errors(manifest: &serde_json::Value) -> Vec<String> {
        let schema: serde_json::Value =
            serde_json::from_str(portaki_test_utils::conformance::MODULE_SCHEMA_V1).unwrap();
        jsonschema::validator_for(&schema)
            .unwrap()
            .iter_errors(manifest)
            .map(|error| error.to_string())
            .collect()
    }

    fn manifest_with(changelog: serde_json::Value) -> serde_json::Value {
        serde_json::json!({
            "id": "access-guide", "name": { "fr": "Accès" }, "description": { "fr": "d" },
            "version": "1.0.0", "author": { "name": "Portaki", "type": "official" },
            "icon": "key", "type": "official", "changelog": changelog
        })
    }

    #[test]
    fn the_stamped_manifest_follows_the_schema() {
        let raw = manifest_with(serde_json::Value::Null).to_string();
        let stamped = stamp(&raw, &[Line::from([("en".into(), "add listing".into())])]).unwrap();
        let stamped: serde_json::Value = serde_json::from_str(&stamped).unwrap();

        assert_eq!(
            stamped["changelog"],
            serde_json::json!([{ "en": "add listing" }])
        );
        assert!(schema_errors(&stamped).is_empty());
    }

    #[test]
    fn the_schema_refuses_a_changelog_off_bounds() {
        let six: Vec<_> = (0..6).map(|_| serde_json::json!({ "fr": "x" })).collect();
        for changelog in [
            serde_json::json!(six),
            serde_json::json!([{ "fr": "x".repeat(MAX_CHARS + 1) }]),
            serde_json::json!([{ "fr": "" }]),
            serde_json::json!([{}]),
            serde_json::json!(["plain string"]),
        ] {
            assert!(
                !schema_errors(&manifest_with(changelog.clone())).is_empty(),
                "{changelog}"
            );
        }
        assert!(schema_errors(&manifest_with(serde_json::json!([
            { "fr": "Code clavier la veille", "en": "Keypad code the day before" }
        ])))
        .is_empty());
    }
}