gram/packages/analyzer/tests/diff.test.ts
abiwab 9a09465335
All checks were successful
CI / Build & Test (pull_request) Successful in 5m38s
fix(kitchen): keep one composite shopping entry per parent unit
2026-11-22 17:16:47 +01:00

511 lines
19 KiB
TypeScript

import { describe, it, expect } from "bun:test";
import { getAST } from "@gram-lang/parser";
import { scheduleFor, compile } from "@gram-lang/kitchen";
import { diffRecipes } from "../src/diff";
// The three timelines of a compiled recipe, laid out from its task graph.
const schedulesOf = (c: Parameters<typeof scheduleFor>[0]) => ({
perSection: scheduleFor(c, "perSection")!,
upfront: scheduleFor(c, "upfront")!,
perDay: scheduleFor(c, "perDay")!,
});
const compileRecipe = (src: string) => compile(getAST(src));
describe("diffRecipes — temperature ranges", () => {
it("detects a range change even when the average stays the same ({2-3} -> {1-4})", () => {
const a = compileRecipe("## Section\nBake at ^{200-300C}.\n");
const b = compileRecipe("## Section\nBake at ^{100-400C}.\n");
const { temperatures } = diffRecipes(a, b);
expect(temperatures).toHaveLength(1);
expect(temperatures[0]?.change).toBe("changed");
expect(temperatures[0]?.from?.range).toEqual({ min: 200, max: 300 });
expect(temperatures[0]?.to?.range).toEqual({ min: 100, max: 400 });
});
it("detects a change of note on the same value (1.5)", () => {
const a = compileRecipe("## Section\n\nBake at ^{180C}(fan).\n");
const b = compileRecipe("## Section\n\nBake at ^{180C}(grill).\n");
const { temperatures } = diffRecipes(a, b);
expect(temperatures).toHaveLength(1);
expect(temperatures[0]?.from).toMatchObject({ value: 180, note: "fan" });
expect(temperatures[0]?.to).toMatchObject({ value: 180, note: "grill" });
const c = compileRecipe("## Section\n\nBake at ^{180C}.\n");
const added = diffRecipes(c, a).temperatures;
expect(added).toHaveLength(1);
expect(added[0]?.from && "note" in added[0].from).toBe(false);
});
it("reports no change when both value and range are identical", () => {
const a = compileRecipe("## Section\nBake at ^{200-300C}.\n");
const b = compileRecipe("## Section\nBake at ^{200-300C}.\n");
const { temperatures } = diffRecipes(a, b);
expect(temperatures).toHaveLength(0);
});
});
// An ingredient bought in two units is two shopping entries of one id: the
// diff kept only the last one, and missed a change to the other.
describe("diffRecipes — an ingredient in two units", () => {
const source = (grams: string, cups: string) =>
`## Section\n\nMix @flour{${grams} g} and @flour{${cups} cups}.\n`;
it("sees a change to the first unit", () => {
const { ingredients } = diffRecipes(
compileRecipe(source("100", "1")),
compileRecipe(source("150", "1")),
);
expect(ingredients).toHaveLength(1);
expect(ingredients[0]).toMatchObject({
id: "flour",
change: "changed",
fromQty: 100,
toQty: 150,
fromUnit: "g",
toUnit: "g",
percentChange: 50,
});
});
it("reports nothing when only the spelling of a unit changed", () => {
const a = compileRecipe("## Section\n\nMix @flour{2 cups}.\n");
const b = compileRecipe("## Section\n\nMix @flour{2 cup}.\n");
expect(diffRecipes(a, b).ingredients).toEqual([]);
});
it("still reports a change of unit as a change, not a removal", () => {
const a = compileRecipe("## Section\n\nMix @flour{200 g}.\n");
const b = compileRecipe("## Section\n\nMix @flour{1 cup}.\n");
const { ingredients } = diffRecipes(a, b);
expect(ingredients).toHaveLength(1);
expect(ingredients[0]).toMatchObject({
change: "changed",
fromUnit: "g",
toUnit: "cup",
});
});
it("reports a unit only one side has as added", () => {
const a = compileRecipe("## Section\n\nMix @flour{100 g}.\n");
const b = compileRecipe(source("100", "1"));
const { ingredients } = diffRecipes(a, b);
expect(ingredients).toHaveLength(1);
expect(ingredients[0]).toMatchObject({
change: "added",
toQty: 1,
toUnit: "cups",
});
});
});
describe("diffRecipes — duplicate section titles", () => {
it("does not lose the first section's tokens when two sections share a title", () => {
const a = compileRecipe(
"## Filling\nWhisk at ^{160C}.\n\n## Filling\nBake at ^{180C}.\n",
);
const b = compileRecipe(
"## Filling\nWhisk at ^{170C}.\n\n## Filling\nBake at ^{180C}.\n",
);
const { temperatures } = diffRecipes(a, b);
// Only the first (unnamed, positionally-matched) temperature changed
// (160 -> 170); the second (180 -> 180) did not. Both must be visible
// to matchTokenPairs — if the first section's tokens were overwritten
// instead of accumulated, this change would be invisible or mispaired.
expect(temperatures).toHaveLength(1);
expect(temperatures[0]?.from?.value).toBe(160);
expect(temperatures[0]?.to?.value).toBe(170);
});
// Regression test for the audit (2026-07-22, finding B3): the exact same
// overwrite-instead-of-accumulate bug as above, but in diffSections
// itself rather than extractTokensByType — a section title used to be
// keyed through a plain Map.set, so the first of two same-titled
// sections silently vanished from the section-level diff.
it("does not lose the first section's own delta in diffSections when two sections share a title", () => {
const a = compileRecipe(
"## Filling\nOne step here.\n\n## Filling\nBake at ^{180C}.\n",
);
const b = compileRecipe(
"## Filling\nOne step here.\n\nAnother step.\n\n## Filling\nBake at ^{180C}.\n",
);
const { sections } = diffRecipes(a, b);
expect(sections).toHaveLength(1);
expect(sections[0]?.title).toBe("Filling");
expect(sections[0]?.fromStepCount).toBe(1);
expect(sections[0]?.toStepCount).toBe(2);
});
});
// Regression tests for the audit (2026-07-22, finding B2): composite and
// alternative groups were excluded from diffIngredients entirely, so a
// quantity change inside either produced `hasChanges: false` — a diff tool
// asserting "nothing changed" is worse than no diff tool at all.
describe("diffRecipes — composites and alternatives are diffable (finding B2)", () => {
const compositeSource = (zestQty: string, juiceQty: string) => `
Add @lemon zest{${zestQty}}<@lemon.
Add @lemon juice{100ml}<@lemon{${juiceQty}}.
`;
it("detects a quantity change on a composite parent's own total", () => {
const a = compileRecipe(compositeSource("1", "2"));
const b = compileRecipe(compositeSource("1", "7"));
const result = diffRecipes(a, b);
expect(result.hasChanges).toBe(true);
const lemon = result.ingredients.find((d) => d.id === "lemon");
expect(lemon?.change).toBe("changed");
expect(lemon?.fromQty).toBe(2);
expect(lemon?.toQty).toBe(7);
});
it("detects a quantity change on a composite's nested child, even when the parent's total is unaffected", () => {
// juice{2} stays the max, so the parent's own total (2) doesn't
// change — only the nested zest child does (1 -> 1.5).
const a = compileRecipe(compositeSource("1", "2"));
const b = compileRecipe(compositeSource("1.5", "2"));
const result = diffRecipes(a, b);
expect(result.hasChanges).toBe(true);
const lemon = result.ingredients.find((d) => d.id === "lemon");
expect(lemon).toBeUndefined(); // parent total genuinely unchanged
const zest = result.ingredients.find((d) => d.id === "lemon-zest");
expect(zest?.change).toBe("changed");
expect(zest?.fromQty).toBe(1);
expect(zest?.toQty).toBe(1.5);
});
it("pairs the entries of a composite parent drawn in two units by unit", () => {
// One entry per unit of the parent (since 1.5.2): written in another
// order, `50 g` still pairs with `80 g`, and `2` with `2`.
const a = compileRecipe(
"Add @lemon zest{1}<@lemon{50 g}.\n\nAdd @lemon juice{1}<@lemon{2}.\n",
);
const b = compileRecipe(
"Add @lemon juice{1}<@lemon{2}.\n\nAdd @lemon zest{1}<@lemon{80 g}.\n",
);
const lemon = diffRecipes(a, b).ingredients.filter((d) => d.id === "lemon");
expect(lemon).toHaveLength(1);
expect(lemon[0]?.fromQty).toBe(50);
expect(lemon[0]?.toQty).toBe(80);
});
it("detects a quantity change on either option inside an alternative group", () => {
const a = compileRecipe("Add @egg{2}|@tofu{200g}.\n");
const b = compileRecipe("Add @egg{9}|@tofu{900g}.\n");
const result = diffRecipes(a, b);
expect(result.hasChanges).toBe(true);
expect(result.ingredients.find((d) => d.id === "egg")?.toQty).toBe(9);
expect(result.ingredients.find((d) => d.id === "tofu")?.toQty).toBe(900);
});
});
// Regression test for the audit (2026-07-22, finding B3): matchTokenPairs
// used to key named tokens through a plain `Map.set`, so two same-named
// timers in one section had the first silently overwritten and vanish from
// the diff (distinct from the section-title duplication above — this is a
// duplicate *token name within* a single section).
describe("diffRecipes — same-named tokens within a single section (finding B3)", () => {
it("does not lose the first timer's change when two timers share a name", () => {
const a = compileRecipe("Wait ~oven{10min}.\n\nWait ~oven{20min}.\n");
const b = compileRecipe("Wait ~oven{15min}.\n\nWait ~oven{20min}.\n");
const { timers } = diffRecipes(a, b);
expect(timers).toHaveLength(1);
expect(timers[0]?.from).toBe("10 min");
expect(timers[0]?.to).toBe("15 min");
});
});
// A refused timer (`~{1:30}`) keeps only what was written: the diff shows
// that writing, never "?".
describe("diffRecipes — refused timers", () => {
it("shows the writing of a refused timer", () => {
const a = compileRecipe("Bake ~oven{1:30}.\n");
const b = compileRecipe("Bake ~oven{1:30 h}.\n");
const { timers } = diffRecipes(a, b);
expect(timers).toHaveLength(1);
expect(timers[0]?.from).toBe("1:30");
expect(timers[0]?.to).toBe("90 min");
});
});
// Generative-style sweep for the audit's stated closure criterion (2026-07-22,
// §4.1 finding 6-bis): "a test that mutates a random field in the compiled
// JSON and requires hasChanges === true" — enumerated here over every shape
// of Usage the shopping list can hold, rather than hand-picking the two
// cases the audit happened to find, per the report's own "class not site"
// principle.
describe("diffRecipes — every quantity mutation is visible (finding 6-bis)", () => {
const baseSource = `
Add @flour{500g}.
Add @lemon zest{1}<@lemon.
Add @lemon juice{100ml}<@lemon{2}.
Add @egg{2}|@tofu{200g}.
`;
const base = compileRecipe(baseSource);
const mutations: Record<string, string> = {
"plain ingredient": baseSource.replace("flour{500g}", "flour{999g}"),
"composite parent total": baseSource.replace("lemon{2}", "lemon{77}"),
"composite nested child": baseSource.replace("zest{1}", "zest{9}"),
"alternative option A": baseSource.replace("egg{2}", "egg{99}"),
"alternative option B": baseSource.replace("tofu{200g}", "tofu{999g}"),
};
for (const [label, mutatedSource] of Object.entries(mutations)) {
it(`detects a mutation of: ${label}`, () => {
const mutated = compileRecipe(mutatedSource);
expect(diffRecipes(base, mutated).hasChanges).toBe(true);
});
}
});
// module-imports RFC §F.0.2: a spliced-in module section always lands at the
// head of `sections[]`, so title/position-keyed diffing must ignore it —
// otherwise adding a single `@use` line would look like the whole recipe's
// sections shifted. `CompilationResult.modules` isn't produced by compile()
// itself (only by @gram-lang/modules' finalizeComposed after composing) —
// stamped by hand here, the same way the renderer's module-badge tests do,
// to exercise diffRecipes in isolation from the whole compose pipeline.
describe("diffRecipes — module-imports RFC §F.0.2", () => {
const moduleInfo = (overrides: Partial<Record<string, unknown>> = {}) => ({
binding: "pate",
uri: "./bases/pate.gram",
title: "Pate",
mode: "inline" as const,
...overrides,
});
it("does not treat a newly-added module section as the host's own sections shifting", () => {
const a = compileRecipe("## Montage\nUse the base.\n");
const b = compileRecipe(
"## Pate\n\nMix @flour{200g}.\n\n## Montage\n\nUse the base.\n",
);
Object.assign(b.sections[0]!, { module: moduleInfo() });
const { sections } = diffRecipes(a, b);
expect(sections).toEqual([]);
});
it("ignores a module section's own preparations/temperatures/timers", () => {
const a = compileRecipe("## Montage\nUse the base.\n");
const b = compileRecipe(
"## Pate\n\nBake @flour{200g} at ^{180C} for ~{10min}.\n\n## Montage\n\nUse the base.\n",
);
Object.assign(b.sections[0]!, { module: moduleInfo() });
const result = diffRecipes(a, b);
expect(result.preparations).toEqual([]);
expect(result.temperatures).toEqual([]);
expect(result.timers).toEqual([]);
});
it("reports a newly-added import in the modules delta", () => {
const a = compileRecipe("## Montage\nUse the base.\n");
const b = compileRecipe("## Montage\nUse the base.\n");
Object.assign(b, { modules: [moduleInfo({ scaleFactor: 1 })] });
const { modules } = diffRecipes(a, b);
expect(modules).toEqual([
{
uri: "./bases/pate.gram",
change: "added",
toBinding: "pate",
toFactor: 1,
},
]);
});
it("reports a removed import in the modules delta", () => {
const a = compileRecipe("## Montage\nUse the base.\n");
const b = compileRecipe("## Montage\nUse the base.\n");
Object.assign(a, { modules: [moduleInfo({ scaleFactor: 1 })] });
const { modules } = diffRecipes(a, b);
expect(modules).toEqual([
{
uri: "./bases/pate.gram",
change: "removed",
fromBinding: "pate",
fromFactor: 1,
},
]);
});
it("reports a changed scale factor for the same import", () => {
const a = compileRecipe("## Montage\nUse the base.\n");
const b = compileRecipe("## Montage\nUse the base.\n");
Object.assign(a, { modules: [moduleInfo({ scaleFactor: 1 })] });
Object.assign(b, { modules: [moduleInfo({ scaleFactor: 2 })] });
const { modules, hasChanges } = diffRecipes(a, b);
expect(hasChanges).toBe(true);
expect(modules).toEqual([
{
uri: "./bases/pate.gram",
change: "changed",
fromBinding: "pate",
toBinding: "pate",
fromFactor: 1,
toFactor: 2,
},
]);
});
it("reports no module delta when nothing about the import changed", () => {
const a = compileRecipe("## Montage\nUse the base.\n");
const b = compileRecipe("## Montage\nUse the base.\n");
Object.assign(a, { modules: [moduleInfo({ scaleFactor: 1 })] });
Object.assign(b, { modules: [moduleInfo({ scaleFactor: 1 })] });
expect(diffRecipes(a, b).modules).toEqual([]);
});
});
describe("diffRecipes — timings follow the per-section schedule", () => {
const base =
"## Pastry\n\nMix @flour{200g}(sifted).\n\n## Assembly\n\nCombine with @filling{300g}(chopped).\n";
// A retro-planning offset moves total and idle time — and only those two —
// apart between the per-section schedule and the legacy (upfront) total.
const shifted = base.replace("## Pastry", "## Pastry ~{-2d}");
it("reports the change of the per-section total, not of the legacy one", () => {
const a = compileRecipe(base);
const b = compileRecipe(shifted);
const { timings } = diffRecipes(a, b);
const total = timings.find((t) => t.field === "totalTime");
expect(total?.from).toBe(schedulesOf(a).perSection.totalTime);
expect(total?.to).toBe(schedulesOf(b).perSection.totalTime);
// Would differ if it read the deprecated metric instead.
expect(total?.to).not.toBe(b.metrics.totalTime);
});
it("reports idle time from the same schedule", () => {
const a = compileRecipe(base);
const b = compileRecipe(shifted);
const idle = diffRecipes(a, b).timings.find((t) => t.field === "idleTime");
expect(idle?.from).toBe(schedulesOf(a).perSection.idleTime);
expect(idle?.to).toBe(schedulesOf(b).perSection.idleTime);
});
it("compares the preparation time of the schedule, the sum of the mise en place", () => {
const a = compileRecipe(base);
const b = compileRecipe(base.replace("(sifted)", ""));
const { timings } = diffRecipes(a, b);
expect(timings.find((t) => t.field === "preparationTime")).toEqual({
field: "preparationTime",
from: a.metrics.preparationTime,
to: b.metrics.preparationTime,
});
});
it("reports nothing when nothing changed", () => {
expect(
diffRecipes(compileRecipe(base), compileRecipe(base)).timings,
).toEqual([]);
});
it("compares JSON stored before 1.4.0 (no tasks) through its old metrics, not as zero", () => {
const current = compileRecipe(base);
const { schedule: _s, tasks: _t, ...stored } = compileRecipe(base);
const timings = diffRecipes(current, stored as never).timings;
// Never the "150 -> 0" a missing schedule used to read as.
for (const field of ["totalTime", "idleTime"] as const) {
const delta = timings.find((t) => t.field === field);
expect(delta === undefined || delta.to > 0).toBe(true);
}
expect(diffRecipes(stored as never, stored as never).timings).toEqual([]);
});
});
describe("diffRecipes — the active time is the schedule's", () => {
const cook = (range: string) =>
`## Roast\n\nRoast @chicken{1kg} for ~{${range}}.\n`;
it("shows a change of the range of a cooking time, planned on its longest figure", () => {
const a = compileRecipe(cook("40-50min"));
const b = compileRecipe(cook("40-60min"));
const active = diffRecipes(a, b).timings.find(
(t) => t.field === "activeTime",
);
expect(active).toEqual({ field: "activeTime", from: 50, to: 60 });
// The deprecated metric is the average: 45 and 50.
expect(a.metrics.activeTime).toBe(45);
});
it("falls back on the old metric for JSON stored before 1.4.0", () => {
const a = compileRecipe(cook("40-50min"));
const {
schedule: _s,
tasks: _t,
...stored
} = compileRecipe(cook("40-70min"));
const active = diffRecipes(a, stored as never).timings.find(
(t) => t.field === "activeTime",
);
expect(active).toEqual({ field: "activeTime", from: 50, to: 55 });
});
});
describe("diffRecipes — target states (1.5)", () => {
const recipe = (line: string) => compileRecipe(`## Crème\n\n${line}\n`);
it("reports an added and a removed target state", () => {
const a = recipe("Cuire la crème.");
const b = recipe("Cuire la crème jusqu'à ={la nappe}(test).");
const added = diffRecipes(a, b);
expect(added.hasChanges).toBe(true);
expect(added.checkpoints).toEqual([
{
section: "Crème",
change: "added",
to: { state: "la nappe", note: "test" },
},
]);
expect(diffRecipes(b, a).checkpoints).toEqual([
{
section: "Crème",
change: "removed",
from: { state: "la nappe", note: "test" },
},
]);
});
it("reports a change of state or of note", () => {
const a = recipe("Cuire jusqu'à ={la nappe}(test).");
expect(
diffRecipes(a, recipe("Cuire jusqu'à ={épais}(test).")).checkpoints,
).toEqual([
{
section: "Crème",
change: "changed",
from: { state: "la nappe", note: "test" },
to: { state: "épais", note: "test" },
},
]);
expect(
diffRecipes(a, recipe("Cuire jusqu'à ={la nappe}.")).checkpoints[0]?.to,
).toEqual({ state: "la nappe" });
});
it("reports nothing when the target states are the same", () => {
const a = recipe("Cuire jusqu'à ={la nappe}(test).");
const result = diffRecipes(a, recipe("Cuire jusqu'à ={la nappe}(test)."));
expect(result.checkpoints).toEqual([]);
expect(result.preparations).toEqual([]);
expect(result.hasChanges).toBe(false);
});
});