Skip to main content

lex_vcs/
diff_to_ops.rs

1//! Convert a `DiffReport` (+ import set deltas + old head info)
2//! into a sequence of typed operations.
3//!
4//! NOTE: `lex-cli`'s `compute_diff` (the only producer of `DiffReport`
5//! today) only diffs `Stage::FnDecl` — types are not yet surfaced.
6//! The `RemoveType`, `AddType`, and `ModifyType` branches below are
7//! forward-looking placeholders that will activate when type-decl
8//! diffing lands. The fn-vs-type heuristic uses
9//! `signature.starts_with("type ")` which depends on the renderer
10//! in `lex-cli/src/diff.rs::render_signature` for `TypeDecl` to
11//! produce strings beginning with "type ". When types come online,
12//! consider extending `AddRemove` with a `kind: SymbolKind` field
13//! to make this typed rather than string-prefix-based.
14
15use crate::diff_report::DiffReport;
16use crate::operation::{default_import_alias, EffectSet, OperationKind, SigId, StageId};
17use lex_ast::{sig_id, stage_id, Effect, Stage};
18use std::collections::{BTreeMap, BTreeSet};
19
20/// One import as the diff sees it: the module reference plus the alias
21/// it is bound under. The alias is part of the set key, so re-aliasing
22/// an already-imported module (`as sql` → `as db`) reads as a
23/// remove + add, which is exactly the pair of ops that reproduces it.
24#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize)]
25pub struct ImportRef {
26    pub reference: String,
27    pub alias: String,
28}
29
30pub type ImportMap = BTreeMap<String, BTreeSet<ImportRef>>;
31
32#[derive(Debug, thiserror::Error)]
33pub enum DiffMappingError {
34    #[error("diff mentions removed/modified name `{0}` but no old_sig_id was resolved for it")]
35    MissingOldSigForName(String),
36    #[error("diff mentions added/renamed name `{0}` but new_stages has no matching stage")]
37    MissingNewStageForName(String),
38    #[error("sig `{0}` is in the diff's old_sig_id but not in old_head")]
39    MissingOldHeadForSig(SigId),
40    #[error("stage for `{0}` produces no sig_id (likely an Import that slipped through)")]
41    NoSigIdForStage(String),
42    #[error("stage for `{0}` produces no stage_id (likely an Import that slipped through)")]
43    NoStageIdForStage(String),
44}
45
46#[derive(Debug)]
47pub struct DiffInputs<'a> {
48    /// Current head SigId → StageId map.
49    pub old_head: &'a BTreeMap<SigId, StageId>,
50    /// Effect set per sig at the current head.
51    pub old_effects: &'a BTreeMap<SigId, EffectSet>,
52    /// Per-file imports at the current head.
53    pub old_imports: &'a ImportMap,
54    /// Stages of the new program (post-canonicalize).
55    pub new_stages: &'a [Stage],
56    /// Per-file imports of the new program.
57    pub new_imports: &'a ImportMap,
58    /// AST-diff between old and new sources, by name. Each removed/
59    /// renamed/modified entry carries its own resolved `old_sig_id`
60    /// (see `diff_report`'s doc comments) rather than this module
61    /// re-deriving one from a name-keyed lookup: a bare function name
62    /// is not unique across a package's files (#818 — e.g. two files
63    /// legitimately both declaring a local `validate` helper with
64    /// different signatures), so a `name -> SigId` map here would
65    /// silently collapse distinct functions onto one SigId.
66    pub diff: &'a DiffReport,
67    /// Mangling prefix → package source file (`schema_a1b2` →
68    /// `src/schema.lex`), for a multi-module package publish. A
69    /// declaration's mangled name is `<prefix>.<local>`, so this maps
70    /// each `AddFunction`/`AddType` to its origin file, recorded as the
71    /// op's `in_file` so `export-git` can de-flatten the package (#894).
72    /// Empty for a single-file publish (then `in_file` stays `None` and
73    /// OpIds are unchanged).
74    pub module_prefixes: &'a BTreeMap<String, String>,
75}
76
77pub fn diff_to_ops(inputs: DiffInputs<'_>) -> Result<Vec<OperationKind>, DiffMappingError> {
78    let mut out = Vec::new();
79    let new_by_name: BTreeMap<&str, &Stage> = inputs.new_stages.iter()
80        .filter_map(|s| {
81            let n = match s {
82                Stage::FnDecl(fd) => fd.name.as_str(),
83                Stage::TypeDecl(td) => td.name.as_str(),
84                Stage::Import(_) => return None,
85            };
86            Some((n, s))
87        })
88        .collect();
89
90    // 1. Imports — separate from stage ops; emit first so importer
91    //    state is consistent before any sig ops apply.
92    for (file, modules) in inputs.new_imports {
93        let old = inputs.old_imports.get(file).cloned().unwrap_or_default();
94        for m in modules.difference(&old) {
95            out.push(OperationKind::AddImport {
96                in_file: file.clone(),
97                module: m.reference.clone(),
98                alias: explicit_alias(m),
99            });
100        }
101        for m in old.difference(modules) {
102            out.push(OperationKind::RemoveImport {
103                in_file: file.clone(),
104                module: m.reference.clone(),
105            });
106        }
107    }
108    for (file, old) in inputs.old_imports {
109        if !inputs.new_imports.contains_key(file) {
110            for m in old {
111                out.push(OperationKind::RemoveImport {
112                    in_file: file.clone(),
113                    module: m.reference.clone(),
114                });
115            }
116        }
117    }
118
119    // 2. Removed → RemoveFunction / RemoveType.
120    for r in &inputs.diff.removed {
121        let Some(sig) = r.old_sig_id.as_ref() else {
122            return Err(DiffMappingError::MissingOldSigForName(r.name.clone()));
123        };
124        let Some(last) = inputs.old_head.get(sig) else {
125            return Err(DiffMappingError::MissingOldHeadForSig(sig.clone()));
126        };
127        // Decide fn vs type by looking at the diff signature string:
128        // type signatures start with "type ".
129        if r.signature.starts_with("type ") {
130            out.push(OperationKind::RemoveType {
131                sig_id: sig.clone(),
132                last_stage_id: last.clone(),
133            });
134        } else {
135            out.push(OperationKind::RemoveFunction {
136                sig_id: sig.clone(),
137                last_stage_id: last.clone(),
138            });
139        }
140    }
141
142    // 3. Added → AddFunction / AddType.
143    for a in &inputs.diff.added {
144        let Some(stage) = new_by_name.get(a.name.as_str()) else {
145            return Err(DiffMappingError::MissingNewStageForName(a.name.clone()));
146        };
147        let Some(sig) = sig_id(stage) else {
148            return Err(DiffMappingError::NoSigIdForStage(a.name.clone()));
149        };
150        let Some(stg) = stage_id(stage) else {
151            return Err(DiffMappingError::NoStageIdForStage(a.name.clone()));
152        };
153        let in_file = origin_file(&a.name, inputs.module_prefixes);
154        match stage {
155            Stage::FnDecl(fd) => {
156                let effects = effect_set(&fd.effects);
157                // #247: extract the function's declared `[budget(N)]`
158                // from its effect set so the op log carries the
159                // initial cost without rehydrating the stage at
160                // query time.
161                let budget_cost = crate::operation::budget_from_effects(&effects);
162                out.push(OperationKind::AddFunction {
163                    sig_id: sig, stage_id: stg, effects, budget_cost, in_file,
164                });
165            }
166            Stage::TypeDecl(_) => {
167                out.push(OperationKind::AddType { sig_id: sig, stage_id: stg, in_file });
168            }
169            Stage::Import(_) => unreachable!(),
170        }
171    }
172
173    // 4. Renamed → RenameSymbol.
174    for r in &inputs.diff.renamed {
175        let from_sig = &r.old_sig_id;
176        let Some(stage) = new_by_name.get(r.to.as_str()) else {
177            return Err(DiffMappingError::MissingNewStageForName(r.to.clone()));
178        };
179        let Some(to_sig) = sig_id(stage) else {
180            return Err(DiffMappingError::NoSigIdForStage(r.to.clone()));
181        };
182        let Some(body_id) = stage_id(stage) else {
183            return Err(DiffMappingError::NoStageIdForStage(r.to.clone()));
184        };
185        out.push(OperationKind::RenameSymbol {
186            from: from_sig.clone(),
187            to: to_sig,
188            body_stage_id: body_id,
189        });
190    }
191
192    // 5. Modified → ChangeEffectSig | ModifyBody | ModifyType.
193    for m in &inputs.diff.modified {
194        let sig = &m.old_sig_id;
195        let Some(from_id) = inputs.old_head.get(sig) else {
196            return Err(DiffMappingError::MissingOldHeadForSig(sig.clone()));
197        };
198        let Some(stage) = new_by_name.get(m.name.as_str()) else {
199            return Err(DiffMappingError::MissingNewStageForName(m.name.clone()));
200        };
201        let Some(to_id) = stage_id(stage) else {
202            return Err(DiffMappingError::NoStageIdForStage(m.name.clone()));
203        };
204        let effects_changed =
205            !m.effect_changes.added.is_empty() || !m.effect_changes.removed.is_empty();
206        match stage {
207            Stage::FnDecl(fd) if effects_changed => {
208                let from_effects = inputs.old_effects.get(sig).cloned().unwrap_or_default();
209                let to_effects = effect_set(&fd.effects);
210                // #247: the budget delta. ChangeEffectSig fires
211                // because the effect set changed, which often
212                // includes the `[budget(N)]` declaration itself.
213                let from_budget = crate::operation::budget_from_effects(&from_effects);
214                let to_budget = crate::operation::budget_from_effects(&to_effects);
215                out.push(OperationKind::ChangeEffectSig {
216                    sig_id: sig.clone(),
217                    from_stage_id: from_id.clone(),
218                    to_stage_id: to_id,
219                    from_effects,
220                    to_effects,
221                    from_budget,
222                    to_budget,
223                });
224            }
225            Stage::FnDecl(fd) => {
226                // #247: ModifyBody fires when only the body changed
227                // — effects (including budget) are unchanged. Pull
228                // the budget from the new stage's effect set; the
229                // old effect set in `old_effects[sig]` would yield
230                // the same value.
231                let to_effects = effect_set(&fd.effects);
232                let budget = crate::operation::budget_from_effects(&to_effects);
233                out.push(OperationKind::ModifyBody {
234                    sig_id: sig.clone(),
235                    from_stage_id: from_id.clone(),
236                    to_stage_id: to_id,
237                    from_budget: budget,
238                    to_budget: budget,
239                });
240            }
241            Stage::TypeDecl(_) => {
242                out.push(OperationKind::ModifyType {
243                    sig_id: sig.clone(),
244                    from_stage_id: from_id.clone(),
245                    to_stage_id: to_id,
246                });
247            }
248            Stage::Import(_) => unreachable!(),
249        }
250    }
251
252    Ok(out)
253}
254
255/// Project a slice of effects into the canonical `EffectSet` (sorted
256/// label strings).
257///
258/// Effect args are preserved via the canonical pretty-print form
259/// (e.g. `fs_read("/tmp")`, `net("wttr.in")`) — see
260/// `compute_diff::effect_label`. This makes `[net]` → `[net("wttr.in")]`
261/// a real `ChangeEffectSig` op (the strings differ), satisfying #207's
262/// third acceptance criterion via #223.
263///
264/// **OpId stability**: bare effects still produce just `"net"` (not
265/// `"net()"` or any other suffix), so every pre-#223 op log retains
266/// its existing OpIds. Only ops *introducing* parameterized effects
267/// see new hashes — and those are by definition new ops.
268fn effect_set(effs: &[Effect]) -> EffectSet {
269    effs.iter().map(crate::compute_diff::effect_label).collect()
270}
271
272/// The package source file a declaration came from, or `None`. A
273/// package-mangled name is `<prefix>.<local>` (e.g.
274/// `schema_a1b2.validate`); `module_prefixes` maps the prefix to its
275/// file. A single-file publish leaves names unmangled and passes an
276/// empty map, so this is `None` and the op's `in_file` is omitted.
277fn origin_file(name: &str, module_prefixes: &BTreeMap<String, String>) -> Option<String> {
278    let prefix = name.split_once('.')?.0;
279    module_prefixes.get(prefix).cloned()
280}
281
282/// The alias to record on an `AddImport`, or `None` when it is just the
283/// module's default alias. Omitting the default keeps the common-case
284/// `AddImport` byte-identical to its pre-alias form, so its `OpId` does
285/// not rotate; only a deliberately-renamed import (`as e`) carries the
286/// alias explicitly.
287fn explicit_alias(m: &ImportRef) -> Option<String> {
288    if m.alias == default_import_alias(&m.reference) {
289        None
290    } else {
291        Some(m.alias.clone())
292    }
293}
294
295#[cfg(test)]
296mod tests {
297    use super::*;
298    use crate::diff_report::{DiffReport, EffectChanges, Modified, Renamed};
299
300    fn dr() -> DiffReport { DiffReport::default() }
301
302    #[test]
303    fn empty_diff_yields_no_ops() {
304        let head: BTreeMap<SigId, StageId> = BTreeMap::new();
305        let eff: BTreeMap<SigId, EffectSet> = BTreeMap::new();
306        let oi: ImportMap = ImportMap::new();
307        let ni: ImportMap = ImportMap::new();
308        let stages: Vec<Stage> = Vec::new();
309        let d = dr();
310        let ops = diff_to_ops(DiffInputs {
311            old_head: &head,
312            old_effects: &eff,
313            old_imports: &oi,
314            new_stages: &stages,
315            new_imports: &ni,
316            diff: &d,
317            module_prefixes: &BTreeMap::new(),
318        }).expect("ok");
319        assert!(ops.is_empty());
320    }
321
322    #[test]
323    fn rename_emits_a_single_rename_op() {
324        // Build a tiny new program with one fn under the new name.
325        let src = "fn parse_int(s :: Str) -> Int { 0 }";
326        let prog = lex_syntax::load_program_from_str(src).unwrap();
327        let stages = lex_ast::canonicalize_program(&prog);
328        let parse_int = stages.iter()
329            .find(|s| matches!(s, Stage::FnDecl(fd) if fd.name == "parse_int"))
330            .cloned().unwrap();
331        let to_sig = sig_id(&parse_int).unwrap();
332        let to_stage = stage_id(&parse_int).unwrap();
333
334        let mut head = BTreeMap::new();
335        head.insert("parse-old-sig".to_string(), to_stage.clone());
336
337        let mut diff = dr();
338        diff.renamed.push(Renamed {
339            from: "parse".into(),
340            to: "parse_int".into(),
341            signature: "fn parse_int(s :: Str) -> Int".into(),
342            old_sig_id: "parse-old-sig".into(),
343        });
344
345        let eff = BTreeMap::new();
346        let oi = ImportMap::new();
347        let ni = ImportMap::new();
348        let ops = diff_to_ops(DiffInputs {
349            old_head: &head,
350            old_effects: &eff,
351            old_imports: &oi,
352            new_stages: &[parse_int],
353            new_imports: &ni,
354            diff: &diff,
355            module_prefixes: &BTreeMap::new(),
356        }).expect("ok");
357        assert_eq!(ops.len(), 1);
358        match &ops[0] {
359            OperationKind::RenameSymbol { from, to, body_stage_id } => {
360                assert_eq!(from, "parse-old-sig");
361                assert_eq!(to, &to_sig);
362                assert_eq!(body_stage_id, &to_stage);
363            }
364            other => panic!("expected RenameSymbol, got {other:?}"),
365        }
366    }
367
368    #[test]
369    fn body_only_modify_emits_modify_body() {
370        let src = "fn fac(n :: Int) -> Int { 1 }";
371        let prog = lex_syntax::load_program_from_str(src).unwrap();
372        let stages = lex_ast::canonicalize_program(&prog);
373        let fac = stages.iter().find(|s| matches!(s, Stage::FnDecl(fd) if fd.name == "fac"))
374            .cloned().unwrap();
375        let sig = sig_id(&fac).unwrap();
376        let new_stg = stage_id(&fac).unwrap();
377
378        let mut head = BTreeMap::new();
379        head.insert(sig.clone(), "old-stage-id".to_string());
380
381        let mut diff = dr();
382        diff.modified.push(Modified {
383            name: "fac".into(),
384            signature_before: "fn fac(n :: Int) -> Int".into(),
385            signature_after:  "fn fac(n :: Int) -> Int".into(),
386            signature_changed: false,
387            effect_changes: EffectChanges::default(),
388            body_patches: Vec::new(),
389            old_sig_id: sig.clone(),
390        });
391
392        let eff = BTreeMap::new();
393        let oi = ImportMap::new();
394        let ni = ImportMap::new();
395        let ops = diff_to_ops(DiffInputs {
396            old_head: &head, old_effects: &eff,
397            old_imports: &oi, new_stages: &[fac], new_imports: &ni, diff: &diff,
398            module_prefixes: &BTreeMap::new(),
399        }).expect("ok");
400        assert_eq!(ops.len(), 1);
401        match &ops[0] {
402            OperationKind::ModifyBody { sig_id: s, from_stage_id, to_stage_id, .. } => {
403                assert_eq!(s, &sig);
404                assert_eq!(from_stage_id, "old-stage-id");
405                assert_eq!(to_stage_id, &new_stg);
406            }
407            other => panic!("expected ModifyBody, got {other:?}"),
408        }
409    }
410
411    #[test]
412    fn import_added_emits_add_import() {
413        let mut new_imports = ImportMap::new();
414        new_imports.insert("main.lex".into(),
415            std::iter::once(ImportRef { reference: "std.io".into(), alias: "io".into() }).collect());
416        let head = BTreeMap::new();
417        let eff = BTreeMap::new();
418        let oi = ImportMap::new();
419        let stages: Vec<Stage> = Vec::new();
420        let diff = dr();
421        let ops = diff_to_ops(DiffInputs {
422            old_head: &head, old_effects: &eff,
423            old_imports: &oi, new_stages: &stages, new_imports: &new_imports, diff: &diff,
424            module_prefixes: &BTreeMap::new(),
425        }).expect("ok");
426        assert_eq!(ops.len(), 1);
427        match &ops[0] {
428            OperationKind::AddImport { in_file, module, alias } => {
429                assert_eq!(in_file, "main.lex");
430                assert_eq!(module, "std.io");
431                // "io" is the default alias of "std.io", so it's omitted.
432                assert_eq!(alias, &None);
433            }
434            other => panic!("expected AddImport, got {other:?}"),
435        }
436    }
437
438    #[test]
439    fn import_with_nondefault_alias_carries_it() {
440        let mut new_imports = ImportMap::new();
441        new_imports.insert("main.lex".into(),
442            std::iter::once(ImportRef { reference: "./error".into(), alias: "e".into() }).collect());
443        let head = BTreeMap::new();
444        let eff = BTreeMap::new();
445        let oi = ImportMap::new();
446        let stages: Vec<Stage> = Vec::new();
447        let diff = dr();
448        let ops = diff_to_ops(DiffInputs {
449            old_head: &head, old_effects: &eff,
450            old_imports: &oi, new_stages: &stages, new_imports: &new_imports, diff: &diff,
451            module_prefixes: &BTreeMap::new(),
452        }).expect("ok");
453        match &ops[0] {
454            OperationKind::AddImport { module, alias, .. } => {
455                assert_eq!(module, "./error");
456                // "e" != default alias "error", so it's carried explicitly.
457                assert_eq!(alias, &Some("e".to_string()));
458            }
459            other => panic!("expected AddImport, got {other:?}"),
460        }
461    }
462
463    #[test]
464    fn missing_old_sig_for_removed_name_errors() {
465        let head: BTreeMap<SigId, StageId> = BTreeMap::new();
466        let eff: BTreeMap<SigId, EffectSet> = BTreeMap::new();
467        let oi = ImportMap::new();
468        let ni = ImportMap::new();
469        let stages: Vec<Stage> = Vec::new();
470        let mut diff = dr();
471        // No `old_sig_id` was resolved for this removal — the caller
472        // (e.g. a hand-assembled report, or a bug in the resolver)
473        // failed to find the old side.
474        diff.removed.push(crate::diff_report::AddRemove {
475            name: "ghost".into(),
476            signature: "fn ghost() -> Int".into(),
477            old_sig_id: None,
478        });
479        let err = diff_to_ops(DiffInputs {
480            old_head: &head, old_effects: &eff,
481            old_imports: &oi, new_stages: &stages, new_imports: &ni, diff: &diff,
482            module_prefixes: &BTreeMap::new(),
483        }).unwrap_err();
484        match err {
485            DiffMappingError::MissingOldSigForName(n) => assert_eq!(n, "ghost"),
486            other => panic!("expected MissingOldSigForName, got {other:?}"),
487        }
488    }
489
490    // ----------------------------- #223 acceptance ---------------------
491
492    /// Bare effects must produce identical strings to pre-#223
493    /// behavior — preserves OpId stability for every existing op log.
494    /// Pre-#223 `effect_set` was `effs.iter().map(|e| e.name.clone())`,
495    /// so the canonical form for `[net]` was `"net"`. Confirm that.
496    #[test]
497    fn bare_effect_set_string_is_unchanged_from_pre_223() {
498        let src = "fn f() -> [net] Int { 0 }";
499        let prog = lex_syntax::load_program_from_str(src).unwrap();
500        let stages = lex_ast::canonicalize_program(&prog);
501        let fd = match &stages[0] {
502            Stage::FnDecl(fd) => fd,
503            other => panic!("{other:?}"),
504        };
505        let set = effect_set(&fd.effects);
506        assert_eq!(set, ["net".to_string()].into_iter().collect::<EffectSet>(),
507            "bare [net] must canonicalize to {{\"net\"}} so existing \
508             op logs keep their OpIds across the #223 change");
509    }
510
511    /// Parameterized effects produce a distinct, parens-quoted string
512    /// — `[net("wttr.in")]` becomes `"net(\"wttr.in\")"`. This is the
513    /// fulcrum that makes `[net]` → `[net("wttr.in")]` a real
514    /// `ChangeEffectSig` op rather than a no-op.
515    #[test]
516    fn parameterized_effect_label_is_distinct_from_bare() {
517        let bare_src = "fn f() -> [net] Int { 0 }";
518        let scoped_src = r#"fn f() -> [net("wttr.in")] Int { 0 }"#;
519        for (src, expected) in [
520            (bare_src, vec!["net"]),
521            (scoped_src, vec!["net(\"wttr.in\")"]),
522        ] {
523            let prog = lex_syntax::load_program_from_str(src).unwrap();
524            let stages = lex_ast::canonicalize_program(&prog);
525            let fd = match &stages[0] {
526                Stage::FnDecl(fd) => fd,
527                other => panic!("{other:?}"),
528            };
529            let want: EffectSet = expected.into_iter().map(String::from).collect();
530            assert_eq!(effect_set(&fd.effects), want);
531        }
532    }
533
534    /// End-to-end: when a function's effect declaration changes from
535    /// `[net]` to `[net("wttr.in")]`, `diff_to_ops` must emit a
536    /// `ChangeEffectSig` op carrying the parameterized form in
537    /// `to_effects`. Pre-#223 this was a no-op (both flattened to
538    /// `{"net"}`), defeating #207's reason to exist.
539    #[test]
540    fn changing_bare_to_parameterized_emits_change_effect_sig() {
541        let bare_src   = "fn weather() -> [net] Str { \"\" }";
542        let scoped_src = r#"fn weather() -> [net("wttr.in")] Str { "" }"#;
543
544        let bare_stage = match &lex_ast::canonicalize_program(
545            &lex_syntax::load_program_from_str(bare_src).unwrap())[0] {
546            Stage::FnDecl(fd) => fd.clone(),
547            _ => unreachable!(),
548        };
549        let scoped_stage = match &lex_ast::canonicalize_program(
550            &lex_syntax::load_program_from_str(scoped_src).unwrap())[0] {
551            Stage::FnDecl(fd) => fd.clone(),
552            _ => unreachable!(),
553        };
554
555        let sig = sig_id(&Stage::FnDecl(bare_stage.clone())).unwrap();
556        let from_stage_id = stage_id(&Stage::FnDecl(bare_stage.clone())).unwrap();
557
558        let mut head = BTreeMap::new();
559        head.insert(sig.clone(), from_stage_id.clone());
560        let mut eff = BTreeMap::new();
561        eff.insert(sig.clone(), effect_set(&bare_stage.effects));
562
563        let mut diff = dr();
564        diff.modified.push(Modified {
565            name: "weather".into(),
566            signature_before: "fn weather() -> [net] Str".into(),
567            signature_after:  "fn weather() -> [net(\"wttr.in\")] Str".into(),
568            signature_changed: true,
569            body_patches: Vec::new(),
570            effect_changes: EffectChanges {
571                before: vec!["net".into()],
572                after: vec!["net(\"wttr.in\")".into()],
573                added: vec!["net(\"wttr.in\")".into()],
574                removed: vec!["net".into()],
575            },
576            old_sig_id: sig.clone(),
577        });
578
579        let oi = ImportMap::new();
580        let ni = ImportMap::new();
581        let new_stage = Stage::FnDecl(scoped_stage);
582        let ops = diff_to_ops(DiffInputs {
583            old_head: &head,
584            old_effects: &eff,
585            old_imports: &oi,
586            new_stages: &[new_stage],
587            new_imports: &ni,
588            diff: &diff,
589            module_prefixes: &BTreeMap::new(),
590        }).expect("diff_to_ops should succeed");
591
592        let change = ops.iter().find(|op| matches!(op, OperationKind::ChangeEffectSig { .. }));
593        let change = change.expect(
594            "expected a ChangeEffectSig op when going [net] → [net(\"wttr.in\")] — \
595             pre-#223 both sides flattened to {\"net\"} and the op was incorrectly \
596             skipped");
597        match change {
598            OperationKind::ChangeEffectSig { from_effects, to_effects, .. } => {
599                let from: Vec<_> = from_effects.iter().cloned().collect();
600                let to:   Vec<_> = to_effects.iter().cloned().collect();
601                assert_eq!(from, vec!["net".to_string()]);
602                assert_eq!(to,   vec!["net(\"wttr.in\")".to_string()]);
603            }
604            _ => unreachable!(),
605        }
606    }
607}