Public Beta
Not set

Experience

Changes how pages explain things, never what you can do.

More

Experience

Changes how pages explain things, never what you can do.

Sign inGet started

Workflow Automation v0.1.2 · claude-code

Archive SHA-256 85be31abe46644f344964c8b1d4b56f6d7218b34a58fd31ffb075c5e5b587476 · 89.5 KB · built Dec 1, 2026

tests/workflow-automation.test.ts

// Tests for the workflow-automation agent. Every test works in its own temporary workspace folder
// with synthetic files; nothing outside those folders is read or written.
import { describe, it, expect, beforeEach, afterEach } from "vitest";
import { mkdtempSync, writeFileSync, mkdirSync, readFileSync, readdirSync, lstatSync, rmSync, symlinkSync, existsSync, linkSync, unlinkSync, rmdirSync, utimesSync } from "node:fs";
import { tmpdir } from "node:os";
import { join, dirname, parse as parsePath } from "node:path";
import { spawn, execFileSync } from "node:child_process";
import { fileURLToPath } from "node:url";
// @ts-expect-error -- plain JavaScript agent module without type declarations
import agentModule, { manifest, buildPlan, checkRecipe, parseTemplate, renderTemplate, parseCsv, toCsv, compileGlob, normalizeRel, validateManifest, workspaceRoot, STEP_TYPE_NAMES } from "../src/index.js";

const agent: any = agentModule;
const AGENT_DIR = fileURLToPath(new URL("..", import.meta.url));
const NOW = new Date("2026-11-26T15:00:00Z");
const IS_WIN = process.platform === "win32";

let ws = "";
let outside = "";
const roots: string[] = [];

function makeDir(prefix: string) {
  const d = mkdtempSync(join(tmpdir(), prefix));
  roots.push(d);
  return d;
}
function put(root: string, files: Record<string, string | Buffer>) {
  for (const [rel, content] of Object.entries(files)) {
    const p = join(root, ...rel.split("/"));
    mkdirSync(dirname(p), { recursive: true });
    writeFileSync(p, content);
  }
}
const read = (rel: string) => readFileSync(join(ws, ...rel.split("/")), "utf8");
const exists = (rel: string) => existsSync(join(ws, ...rel.split("/")));
function snapshot(root: string): string[] {
  const out: string[] = [];
  const walk = (dir: string, prefix: string) => {
    for (const e of readdirSync(dir, { withFileTypes: true })) {
      const rel = prefix ? `${prefix}/${e.name}` : e.name;
      const st = lstatSync(join(dir, e.name));
      out.push(`${rel}|${st.isDirectory() ? "dir" : st.size}|${st.mtimeMs}`);
      if (e.isDirectory() && !e.isSymbolicLink()) walk(join(dir, e.name), rel);
    }
  };
  walk(root, "");
  return out.sort();
}
const call = (tool: string, input: any) => agent.call(tool, input, { now: () => NOW });
const plan = (recipe: any, extra: any = {}) => call("plan_recipe", { recipe, ...extra });
const run = (recipe: any, extra: any = {}) => call("run_recipe", { recipe, confirm: true, ...extra });
async function codeOf(p: Promise<unknown>) {
  try {
    await p;
    return "ok";
  } catch (e: any) {
    return e.code;
  }
}
async function errOf(p: Promise<unknown>): Promise<any> {
  try {
    await p;
  } catch (e) {
    return e;
  }
  throw new Error("expected an error");
}
/** Directory link that needs no admin rights on Windows (junction); a symlink elsewhere. */
function linkDir(target: string, at: string) {
  symlinkSync(target, at, IS_WIN ? "junction" : "dir");
}
function removeLink(p: string) {
  try {
    unlinkSync(p);
  } catch {
    rmdirSync(p);
  }
}

beforeEach(() => {
  ws = makeDir("wfa-test-");
  outside = makeDir("wfa-outside-");
  put(outside, { "secret.csv": "a,b\n1,2\n", "notes.md": "# Outside\n" });
  process.env.AGENTROVE_WORKFLOW_ROOT = ws;
});
afterEach(() => {
  delete process.env.AGENTROVE_WORKFLOW_ROOT;
  for (const r of roots.splice(0)) {
    // Remove links first so cleanup never follows them.
    const walk = (dir: string) => {
      for (const e of readdirSync(dir, { withFileTypes: true })) {
        const p = join(dir, e.name);
        if (lstatSync(p).isSymbolicLink()) removeLink(p);
        else if (e.isDirectory()) walk(p);
      }
    };
    try {
      walk(r);
    } catch {
      /* ignore */
    }
    rmSync(r, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
  }
});

const ORDERS = [
  "order_id,date,region,customer,status,amount",
  "1001,2026-11-02,North,Fixture Bakery,paid,\"$1,250.00\"",
  "1002,2026-11-03,South,Example Florist,paid,310.50",
  "1003,2026-11-03,North,Fixture Bakery,refunded,99.00",
  "1004,2026-11-05,West,\"Sample Co, Ltd\",paid,480",
  "1005,2026-11-09,South,Example Florist,paid,120.25",
  "1004,2026-11-05,West,\"Sample Co, Ltd\",paid,480",
  "1006,2026-11-12,East,Test Garage,pending,700",
].join("\n");

const salesRecipe = (extra: any = {}) => ({
  name: "Monthly sales",
  vars: { month: "2026-11" },
  steps: [
    { id: "orders", type: "read_csv", path: "data/orders-{{vars.month}}.csv" },
    { id: "unique", type: "dedupe", by: ["order_id"] },
    { id: "paid", type: "filter", where: [{ field: "status", op: "eq", value: "paid" }] },
    { id: "by_region", type: "summarize", group_by: ["region"], metrics: [{ op: "count", as: "orders" }, { op: "sum", field: "amount", as: "revenue" }] },
    { id: "ranked", type: "sort", by: "-revenue" },
    { id: "report", type: "template", escape: "markdown", template: "# Sales {{vars.month}}\n{{#rows}}\n{{@number}}. {{region}}: {{orders}} orders, {{revenue | fixed:2}}\n{{/rows}}\n" },
    { id: "save", type: "write_file", from: "report", path: "reports/sales-{{vars.month}}.md", ...extra },
  ],
});

// ------------------------------------------------------------------------------------------------
describe("manifest and code safety", () => {
  it("has a valid manifest: confirmed local writes, no network, no credentials, typed IO", () => {
    expect(validateManifest(manifest)).toEqual([]);
    expect(manifest.id).toBe("agentrove.workflow-automation");
    expect(manifest.version).toMatch(/^0\.1\.\d+$/);
    const byName = Object.fromEntries(manifest.tools.map((t: any) => [t.name, t]));
    expect(byName.validate_recipe).toMatchObject({ side_effects: "none", requires_confirmation: false });
    expect(byName.plan_recipe).toMatchObject({ side_effects: "none", requires_confirmation: false });
    expect(byName.run_recipe).toMatchObject({ side_effects: "writes_local_files", requires_confirmation: true });
    expect(manifest.permissions).toMatchObject({ filesystem: "read_write", network: [], credentials: [] });
    // sdk/types.json sits next to src/ in a downloaded pack and two levels up (native/sdk) in the repository.
    const typesFile = [join(AGENT_DIR, "sdk", "types.json"), join(AGENT_DIR, "..", "..", "sdk", "types.json")].find((p) => existsSync(p));
    expect(typesFile, "sdk/types.json").toBeDefined();
    const types = JSON.parse(readFileSync(typesFile!, "utf8")).types;
    for (const p of [...manifest.io.inputs, ...manifest.io.outputs]) expect(types[p.type], p.type).toBeDefined();
    expect(manifest.external_costs).toMatch(/^None/);
    const pkg = JSON.parse(readFileSync(join(AGENT_DIR, "package.json"), "utf8"));
    expect(pkg.version).toBe(manifest.version);
    expect(readFileSync(join(AGENT_DIR, "README.md"), "utf8")).toContain(`\`agentrove.workflow-automation\` ${manifest.version}`);
  });

  it("source has no process, network or code-evaluation APIs, and removes only its own temporary file", () => {
    const dir = join(AGENT_DIR, "src");
    for (const f of readdirSync(dir)) {
      const src = readFileSync(join(dir, f), "utf8");
      expect(src, f).not.toMatch(/child_process|node:net|node:http|node:https|node:dgram|node:vm|worker_threads/);
      expect(src, f).not.toMatch(/(?<![.\w$])eval\s*\(|new\s+Function\s*\(|(?<![.\w$])fetch\s*\(|\bimport\s*\(/);
      const removals = src.match(/\b(?:unlink|unlinkSync|rm|rmSync|rmdir|rmdirSync)\s*\(/g) ?? [];
      if (f === "apply.js") expect(removals).toEqual(["rmSync("]);
      else expect(removals, f).toEqual([]);
    }
    expect(readFileSync(join(dir, "apply.js"), "utf8")).toMatch(/function removeOwnTemp\(path\) \{\n\s+try \{\n\s+rmSync\(path/);
  });
});

// ------------------------------------------------------------------------------------------------
describe("validate_recipe (no file access)", () => {
  it("accepts a valid recipe and summarises what each step reads and writes, without touching files", async () => {
    const before = snapshot(ws);
    const r = await call("validate_recipe", { recipe: salesRecipe() });
    expect(r.valid).toBe(true);
    expect(r.errors).toEqual([]);
    expect(r.steps[0]).toMatchObject({ id: "orders", group: "source", reads: ["data/orders-{{vars.month}}.csv"] });
    expect(r.steps[1].from).toBe("orders");
    expect(r.steps.at(-1)).toMatchObject({ id: "save", group: "file", writes: ["reports/sales-{{vars.month}}.md"] });
    expect(r.step_types).toEqual(STEP_TYPE_NAMES);
    expect(snapshot(ws)).toEqual(before); // the data file does not even exist: validation never looks
  });

  it("rejects unknown step types and says there are no shell, network or delete steps", async () => {
    for (const type of ["shell", "run_command", "exec", "http_get", "download", "delete_files", "eval", "script"]) {
      const r = await call("validate_recipe", { recipe: { steps: [{ id: "x", type }] } });
      expect(r.valid, type).toBe(false);
      expect(r.errors[0].message).toMatch(/unknown step type/);
      expect(r.errors[0].message).toMatch(/no shell, script, network, download, delete or code steps/);
    }
  });

  it("reports structural problems with their location", async () => {
    const r = await call("validate_recipe", {
      recipe: {
        name: "Broken",
        timezone: "Mars/Olympus",
        limits: { max_rows: 10_000_000, nope: 1 },
        extra: true,
        steps: [
          { id: "a", type: "read_csv", path: "data/x.csv", pth: "typo" },
          { id: "a", type: "read_text", path: "x.txt" },
          { type: "read_text", path: "y.txt" },
          { id: "f", type: "filter", from: "later", where: [{ field: "x", op: "matches", value: "." }] },
          { id: "t", type: "template", template: "{{#rows}}unclosed" },
          { id: "p", type: "template", template: "{{> partial}}" },
          { id: "w", type: "write_file", from: "a", path: "out.md" },
          { id: "s", type: "sort", from: "a", by: [{ field: "x", order: "sideways" }] },
          { id: "m", type: "summarize", from: "a", metrics: [{ op: "median", field: "x" }] },
          { id: "g", type: "read_csv", glob: "data/**x/*.csv" },
        ],
      },
    });
    expect(r.valid).toBe(false);
    const at = r.errors.map((e: any) => `${e.path} ${e.message}`).join("\n");
    expect(at).toMatch(/recipe\.extra unknown property/);
    expect(at).toMatch(/recipe\.timezone .*not an IANA time zone/);
    expect(at).toMatch(/recipe\.limits\.max_rows must be a whole number from 1 to 100000/);
    expect(at).toMatch(/recipe\.limits\.nope unknown limit/);
    expect(at).toMatch(/steps\[0\] \(a\)\.pth unknown property for read_csv/);
    expect(at).toMatch(/steps\[1\] \(a\)\.id "a" is used by an earlier step/);
    expect(at).toMatch(/steps\[2\]\.id is required/);
    expect(at).toMatch(/steps\[3\] \(f\)\.from "later" is not an earlier step/);
    expect(at).toMatch(/where\[0\]\.op must be one of eq/);
    expect(at).toMatch(/steps\[4\] \(t\)\.template .*section \{\{#rows\}\} is not closed/);
    expect(at).toMatch(/partials .* are not supported/);
    expect(at).toMatch(/steps\[6\] \(w\)\.from write_file needs text but a produces rows .*to_csv/);
    expect(at).toMatch(/order must be "asc" or "desc"/);
    expect(at).toMatch(/op must be one of count/);
    expect(at).toMatch(/"\*\*" must be a whole path segment/);
  });

  it("rejects unsafe paths statically", async () => {
    const bad: [string, RegExp][] = [
      ["../outside.csv", /contains "\.\."/],
      ["data/../../x.csv", /contains "\.\."/],
      ["..\\x.csv", /contains "\.\."/],
      ["C:/Windows/win.ini", /absolute path/],
      ["/etc/passwd", /absolute path/],
      ["\\\\server\\share\\x.csv", /absolute path/],
      [".env", /hidden file or folder/],
      ["data/.git/config", /hidden file or folder/],
      ["con.txt", /reserved Windows device name/],
      ["data/file.csv:secret", /not allowed in paths/],
      ["data/x.csv ", /ends with a dot or space/],
      ["a\u0000b.csv", /not allowed in paths/],
    ];
    for (const [p, re] of bad) {
      const r = await call("validate_recipe", { recipe: { steps: [{ id: "a", type: "read_text", path: p }] } });
      expect(r.valid, p).toBe(false);
      expect(r.errors[0].message, p).toMatch(re);
    }
    const w = await call("validate_recipe", { recipe: { steps: [{ id: "a", type: "write_file", content: "x", path: "../{{vars.n}}.md" }] } });
    expect(w.errors[0].message).toMatch(/must not contain "\.\."/);
    const abs = await call("validate_recipe", { recipe: { steps: [{ id: "a", type: "write_file", content: "x", path: "/tmp/{{vars.n}}.md" }] } });
    expect(abs.errors[0].message).toMatch(/must be relative/);
  });

  it("catches templates that use a later step's output, and paths with a missing value", async () => {
    const r = await call("validate_recipe", { recipe: { steps: [{ id: "t", type: "template", template: "{{{steps.table}}}" }, { id: "table", type: "literal", value: [] }] } });
    expect(r.errors).toEqual([{ path: "steps[0] (t).template", message: '{{steps.table}} refers to step "table", which is not an earlier step.' }]);
    const e = await errOf(plan({ steps: [{ id: "w", type: "write_file", content: "x", path: "out/{{vars.missing}}.md" }] }));
    expect(e.code).toBe("missing_value");
    expect(exists("out")).toBe(false);
  });

  it("limits recipe size and step count", async () => {
    const many = Array.from({ length: 51 }, (_, i) => ({ id: `s${i}`, type: "literal", value: i }));
    expect((await call("validate_recipe", { recipe: { steps: many } })).errors[0].message).toMatch(/has 51 steps; the limit is 50/);
    const big = { steps: [{ id: "a", type: "literal", value: "x".repeat(600 * 1024) }] };
    expect((await call("validate_recipe", { recipe: big })).errors[0].message).toMatch(/the limit is 524288/);
    expect(checkRecipe({ steps: [{ id: "a", type: "literal", value: 1 }] }).warnings.join(" ")).toMatch(/no write_file, move_files or copy_files step/);
  });

  it("plan_recipe and run_recipe refuse invalid recipes with the error list", async () => {
    const e = await errOf(plan({ steps: [{ id: "a", type: "shell", command: "rm -rf /" }] }));
    expect(e.code).toBe("invalid_recipe");
    expect(e.message).toMatch(/unknown step type "shell"/);
    expect(await codeOf(run({ steps: [{ id: "a", type: "delete_files", path: "x" }] }))).toBe("invalid_recipe");
  });
});

// ------------------------------------------------------------------------------------------------
describe("templates", () => {
  const t = (src: string, ctx: any, opts: any = {}) => renderTemplate(parseTemplate(src), ctx, opts).text;

  it("escapes values (HTML by default, Markdown or none on request; triple braces are raw)", () => {
    const v = { x: `<a href="x">Q&A</a>`, m: "[click](http://example.test) *now* | cell", n: "-5", l: "- item", h: "# title", o: "1. one", d: "430.75" };
    expect(t("{{x}}", v)).toBe("&lt;a href=&quot;x&quot;&gt;Q&amp;A&lt;/a&gt;");
    expect(t("{{{x}}}|{{& x}}", v)).toBe(`${v.x}|${v.x}`);
    expect(t("{{x}}", v, { escape: "none" })).toBe(v.x);
    expect(t("{{m}}", v, { escape: "markdown" })).toBe("\\[click\\](http://example.test) \\*now\\* \\| cell");
    expect(t("{{n}} {{l}} {{h}} {{o}} {{d}}", v, { escape: "markdown" }).split(" ")).toEqual(["-5", "\\-", "item", "\\#", "title", "1\\.", "one", "430.75"]);
    expect(t("{{v}}", { v: "line1\nline2" }, { escape: "markdown" })).toBe("line1 line2");
  });

  it("renders sections, inverted sections, @number and standalone tag lines without blank lines", () => {
    const src = "Items:\n{{#rows}}\n{{@number}}. {{name}}{{#@last}}.{{/@last}}\n{{/rows}}\n{{^rows}}\nnone\n{{/rows}}\n";
    expect(t(src, { rows: [{ name: "a" }, { name: "b" }] }, { escape: "none" })).toBe("Items:\n1. a\n2. b.\n");
    expect(t(src, { rows: [] }, { escape: "none" })).toBe("Items:\nnone\n");
    expect(t("{{#user}}{{name}} ({{vars.x}}){{/user}}", [{ vars: { x: 1 } }, { user: { name: "Ann" } }])).toBe("Ann (1)");
    expect(t("{{#flag}}yes{{/flag}}{{^flag}}no{{/flag}}", { flag: "false" })).toBe("no");
  });

  it("applies the fixed filter list", () => {
    const v = { title: "Ünïcode Report: Q4/2026!", n: "1234567.891", z: "", d: "2026-11-30T23:30:00-05:00", day: "2026-11-30", i: 7, list: ["a", "b"] };
    expect(t("{{title | slug}}", v)).toBe("unicode-report-q4-2026");
    expect(t("{{n | fixed:2}} {{n | thousands}} {{i | pad:3}}", v)).toBe("1234567.89 1,234,567.891 007");
    expect(t('{{z | default:"n/a"}} {{title | lower | truncate:8}}', v, { escape: "none" })).toBe("n/a ünïcode…");
    expect(t('{{d | date:"YYYY-MM-DD HH:mm"}}', v)).toBe("2026-12-01 04:30");
    expect(t('{{d | date:"YYYY-MM-DD HH:mm"}}', v, { timezone: "America/Toronto" })).toBe("2026-11-30 23:30");
    expect(t('{{day | date:"DD/MM/YYYY"}}', v, { timezone: "Asia/Tokyo" })).toBe("30/11/2026"); // dates without a zone are not shifted
    expect(t("{{list | join:\" + \"}} {{list | length}} {{list | json}}", v, { escape: "none" })).toBe('a + b 2 ["a","b"]');
  });

  it("refuses unsafe or unknown syntax and limits output", () => {
    expect(() => parseTemplate("{{> other}}")).toThrow(/partials/);
    expect(() => parseTemplate("{{=<% %>=}}")).toThrow(/delimiters/);
    expect(() => parseTemplate("{{x | exec}}")).toThrow(/unknown filter/);
    expect(() => parseTemplate("{{constructor.name}}")).toThrow(/not allowed/);
    expect(() => parseTemplate("{{a}")).toThrow(/not closed/);
    expect(() => parseTemplate("{{/a}}")).toThrow(/never opened/);
    expect(() => parseTemplate("{{#a}}x{{/b}}")).toThrow(/does not match/);
    expect(() => parseTemplate("{{#a}}".repeat(11) + "{{/a}}".repeat(11))).toThrow(/nested more than 10/);
    expect(t("{{toString}}{{hasOwnProperty}}", {})).toBe(""); // only own properties are looked up
    const r = renderTemplate(parseTemplate("{{missing}}"), {});
    expect(r.missing).toEqual(["missing"]);
    expect(() => renderTemplate(parseTemplate("{{#rows}}{{#rows}}xxxxxxxxxx{{/rows}}{{/rows}}"), { rows: Array.from({ length: 300 }, () => ({})) }, { maxChars: 100_000 })).toThrow(/longer than 100000/);
    expect(t("{{v}}", { v: "../../etc/pass:wd" }, { escape: "path" })).toBe("-..-etc-pass-wd");
    expect(t("{{{v}}}", { v: "a/b" }, { escape: "path" })).toBe("a-b"); // paths: raw values are made safe too
  });
});

describe("CSV", () => {
  it("reads quoted fields, embedded line breaks, BOM, ; delimiters and repeated headers", () => {
    const r = parseCsv('\uFEFFname;note;name\r\n"Smith; J.";"line1\nline2 ""quoted""";x\r\n\r\nshort\r\n');
    expect(r.delimiter).toBe(";");
    expect(r.columns).toEqual(["name", "note", "name_2"]);
    expect(r.rows[0]).toMatchObject({ name: "Smith; J.", note: 'line1\nline2 "quoted"', name_2: "x" });
    expect(r.rows[1]).toMatchObject({ name: "short", note: "" });
    expect(r.warnings.join(" ")).toMatch(/fewer fields/);
    expect(() => parseCsv('a\n"open')).toThrow(/not closed/);
  });

  it("writes quoted CSV and neutralises spreadsheet formulas but not negative numbers", () => {
    const csv = toCsv([{ a: "=SUM(A1:A9)", b: "-12.5", c: "say \"hi\", ok", d: "@cmd", e: "+1 555" }], ["a", "b", "c", "d", "e"]);
    expect(csv).toBe("a,b,c,d,e\r\n'=SUM(A1:A9),-12.5,\"say \"\"hi\"\", ok\",'@cmd,'+1 555\r\n");
  });
});

// ------------------------------------------------------------------------------------------------
describe("plan_recipe is a dry run; run_recipe applies exactly the plan", () => {
  beforeEach(() => put(ws, { "data/orders-2026-11.csv": ORDERS }));

  it("plans a report without writing anything, with a stable plan_hash", async () => {
    const before = snapshot(ws);
    const p = await plan(salesRecipe());
    expect(snapshot(ws)).toEqual(before);
    expect(p.executed).toBe(false);
    expect(p.ready).toBe(true);
    expect(p.operations.map((o: any) => [o.op, o.path, o.mode ?? null, o.status])).toEqual([
      ["create_folder", "reports", null, "planned"],
      ["write_file", "reports/sales-2026-11.md", "create", "planned"],
    ]);
    expect(p.operations[1].preview).toBe("# Sales 2026-11\n1. North: 1 orders, 1250.00\n2. West: 1 orders, 480.00\n3. South: 2 orders, 430.75\n");
    expect(p.diff).toMatch(/nothing has been written/);
    expect(p.diff).toMatch(/create folder\s+reports/);
    expect(p.steps.find((s: any) => s.id === "unique").rows).toBe(6);
    expect(p.warnings.join(" ")).toMatch(/removed 1 duplicate/);
    expect(p.report).toMatch(/ready to run \(nothing written yet\)/);
    expect((await plan(salesRecipe())).plan_hash).toBe(p.plan_hash);
  });

  it("needs confirm: true, writes the planned content, and is idempotent", async () => {
    expect(await codeOf(call("run_recipe", { recipe: salesRecipe() }))).toBe("confirmation_required");
    expect(exists("reports")).toBe(false);
    const p = await plan(salesRecipe());
    const r = await run(salesRecipe(), { expected_plan_hash: p.plan_hash });
    expect(r.executed).toBe(true);
    expect(r.results.map((x: any) => x.status)).toEqual(["done", "done"]);
    expect(read("reports/sales-2026-11.md")).toBe(p.operations[1].preview);
    expect(r.warnings.join(" ")).not.toMatch(/without expected_plan_hash/);
    const again = await plan(salesRecipe());
    expect(again.operations.map((o: any) => o.status)).toEqual(["conflict"]); // default if_exists is "error"
    const over = await plan(salesRecipe({ if_exists: "overwrite" }));
    expect(over.operations[0]).toMatchObject({ status: "unchanged", mode: "overwrite" });
  });

  it("stops with plan_changed when files changed after the review, and writes nothing", async () => {
    const p = await plan(salesRecipe());
    put(ws, { "data/orders-2026-11.csv": ORDERS + "\n1007,2026-11-20,East,Test Garage,paid,5" });
    const e = await errOf(run(salesRecipe(), { expected_plan_hash: p.plan_hash }));
    expect(e.code).toBe("plan_changed");
    expect(e.message).toMatch(/Nothing was written/);
    expect(exists("reports")).toBe(false);
    const p2 = await plan(salesRecipe());
    expect(p2.plan_hash).not.toBe(p.plan_hash);
    expect(await codeOf(run(salesRecipe(), { expected_plan_hash: p2.plan_hash }))).toBe("ok");
  });

  it("warns when run without expected_plan_hash", async () => {
    const r = await run(salesRecipe());
    expect(r.warnings.join(" ")).toMatch(/Ran without expected_plan_hash/);
  });
});

describe("if_exists for write_file", () => {
  beforeEach(() => put(ws, { "out/report.md": "line 1\nline 2\nline 3\n", "out/log.md": "# Log\n" }));
  const writeRecipe = (content: string, extra: any = {}, path = "out/report.md") => ({ steps: [{ id: "w", type: "write_file", content, path, escape: "none", ...extra }] });

  it("error (default): conflict; run refuses and writes nothing", async () => {
    const p = await plan(writeRecipe("new"));
    expect(p.ready).toBe(false);
    expect(p.operations[0]).toMatchObject({ status: "conflict", reason: 'already exists (if_exists: "error")' });
    expect(p.diff).toMatch(/CONFLICT\s+out\/report\.md/);
    const e = await errOf(run(writeRecipe("new")));
    expect(e.code).toBe("plan_has_conflicts");
    expect(e.message).toMatch(/Nothing was written/);
    expect(read("out/report.md")).toBe("line 1\nline 2\nline 3\n");
  });

  it("skip, suffix, overwrite (with a line diff) and append", async () => {
    expect((await run(writeRecipe("x", { if_exists: "skip" }))).results[0].status).toBe("skipped");
    expect(read("out/report.md")).toBe("line 1\nline 2\nline 3\n");

    const s = await run(writeRecipe("copy", { if_exists: "suffix" }));
    expect(s.operations[0]).toMatchObject({ path: "out/report-2.md", renamed_from: "out/report.md" });
    expect(read("out/report-2.md")).toBe("copy");

    const p = await plan(writeRecipe("line 1\nline two\nline 3\nline 4\n", { if_exists: "overwrite" }));
    expect(p.operations[0].diff).toMatchObject({ added: 2, removed: 1, lines: ["- line 2", "+ line two", "+ line 4"] });
    expect(p.diff).toMatch(/overwrite\s+out\/report\.md \(\+2 -1 lines\)/);
    expect(read("out/report.md")).toBe("line 1\nline 2\nline 3\n"); // still a dry run
    await run(writeRecipe("line 1\nline two\nline 3\nline 4\n", { if_exists: "overwrite" }), { expected_plan_hash: p.plan_hash });
    expect(read("out/report.md")).toBe("line 1\nline two\nline 3\nline 4\n");
    expect(readdirSync(join(ws, "out")).filter((f) => f.endsWith(".tmp"))).toEqual([]);

    await run(writeRecipe("- {{run.date}} ran\n", { if_exists: "append" }, "out/log.md"));
    expect(read("out/log.md")).toBe("# Log\n- 2026-11-26 ran\n");
  });

  it("refuses to append to a hard-linked file and to write one path twice", async () => {
    linkSync(join(ws, "out", "log.md"), join(ws, "out", "log-link.md"));
    const p = await plan(writeRecipe("x", { if_exists: "append" }, "out/log.md"));
    expect(p.operations[0]).toMatchObject({ status: "conflict", reason: expect.stringMatching(/hard links/) });
    const twice = await plan({ steps: [{ id: "a", type: "write_file", content: "1", path: "new.md" }, { id: "b", type: "write_file", content: "2", path: "NEW.md".toLowerCase() }] });
    expect(twice.operations[1]).toMatchObject({ status: "conflict", reason: expect.stringMatching(/another operation in this recipe/) });
    const appendAfterWrite = await run({ steps: [{ id: "a", type: "write_file", content: "1\n", path: "n.md" }, { id: "b", type: "write_file", content: "2\n", path: "n.md", if_exists: "append" }] });
    expect(appendAfterWrite.results.map((r: any) => r.detail)).toEqual(["created", "appended"]);
    expect(read("n.md")).toBe("1\n2\n");
  });
});

describe("one file per row (for_each)", () => {
  it("writes a note per CSV row, keeping every value a single safe file name", async () => {
    put(ws, { "clients.csv": "name,owner,notes\nAcme Ltd,Sam,Renewal in March\n../../escape,Kim,<script>x</script>\nBeta/Gamma: AG,Lee,\n" });
    const recipe = {
      steps: [
        { id: "clients", type: "read_csv", path: "clients.csv" },
        { id: "notes", type: "write_file", for_each: "clients", path: "clients/{{name}}/README.md", content: "# {{name}}\n\nOwner: {{owner}}\n\n{{notes}}\n", escape: "markdown" },
      ],
    };
    const p = await plan(recipe);
    expect(p.operations.filter((o: any) => o.op === "write_file").map((o: any) => o.path)).toEqual(["clients/Acme Ltd/README.md", "clients/-..-escape/README.md", "clients/Beta-Gamma- AG/README.md"]);
    await run(recipe, { expected_plan_hash: p.plan_hash });
    expect(read("clients/-..-escape/README.md")).toBe("# ../../escape\n\nOwner: Kim\n\n\\<script\\>x\\</script\\>\n");
    expect(existsSync(join(ws, "..", "escape"))).toBe(false);
    expect(readdirSync(join(ws, "clients")).sort()).toEqual(["-..-escape", "Acme Ltd", "Beta-Gamma- AG"]);
  });
});

describe("organising files (list_files + move_files / copy_files)", () => {
  beforeEach(() => {
    put(ws, {
      "inbox/invoice-001.pdf": "%PDF fixture 1",
      "inbox/IMG_0001.JPG": "jpeg fixture",
      "inbox/notes.txt": "text",
      "inbox/sub/deep.pdf": "%PDF fixture 2",
      "inbox/.hidden.pdf": "hidden",
      "sorted/pdf/2026-10/invoice-001.pdf": "an older, different file",
    });
    const t = new Date("2026-10-15T12:00:00Z");
    for (const f of ["inbox/invoice-001.pdf", "inbox/IMG_0001.JPG", "inbox/notes.txt", "inbox/sub/deep.pdf"]) utimesSync(join(ws, ...f.split("/")), t, t);
  });
  const organise = (ifExists = "error", pattern = "**/*") => ({
    timezone: "America/Toronto",
    steps: [
      { id: "files", type: "list_files", folder: "inbox", pattern },
      { id: "movable", type: "filter", where: [{ field: "ext", op: "in", value: ["pdf", "jpg"] }] },
      { id: "move", type: "move_files", to: 'sorted/{{ext}}/{{modified | date:"YYYY-MM"}}/{{name}}', if_exists: ifExists },
      { id: "log", type: "template", from: "move", escape: "none", template: "{{#rows}}\n{{status}} {{from}} -> {{path}}\n{{/rows}}\n" },
      { id: "save_log", type: "write_file", from: "log", path: "sorted/moves-{{run.date}}.log", if_exists: "append" },
    ],
  });

  it("plans moves without moving, skips hidden files, and reports the existing destination as a conflict", async () => {
    const before = snapshot(ws);
    const p = await plan(organise());
    expect(snapshot(ws)).toEqual(before);
    expect(p.steps[0].rows).toBe(4); // .hidden.pdf is not listed
    const moves = p.operations.filter((o: any) => o.op === "move_file");
    expect(moves.map((o: any) => [o.from, o.path, o.status])).toEqual([
      ["inbox/IMG_0001.JPG", "sorted/jpg/2026-10/IMG_0001.JPG", "planned"],
      ["inbox/invoice-001.pdf", "sorted/pdf/2026-10/invoice-001.pdf", "conflict"],
      ["inbox/sub/deep.pdf", "sorted/pdf/2026-10/deep.pdf", "planned"],
    ]);
    expect(p.ready).toBe(false);
    expect(await codeOf(run(organise()))).toBe("plan_has_conflicts");
    expect(snapshot(ws)).toEqual(before);
  });

  it("moves with suffix on collision, never replaces or deletes, and logs the moves", async () => {
    const countFiles = () => snapshot(ws).filter((l) => !l.includes("|dir|")).length;
    const n = countFiles();
    const p = await plan(organise("suffix"));
    const r = await run(organise("suffix"), { expected_plan_hash: p.plan_hash });
    expect(r.results.filter((x: any) => x.op === "move_file").every((x: any) => x.status === "done")).toBe(true);
    expect(read("sorted/pdf/2026-10/invoice-001.pdf")).toBe("an older, different file");
    expect(read("sorted/pdf/2026-10/invoice-001-2.pdf")).toBe("%PDF fixture 1");
    expect(read("sorted/jpg/2026-10/IMG_0001.JPG")).toBe("jpeg fixture");
    expect(exists("inbox/invoice-001.pdf")).toBe(false);
    expect(read("inbox/notes.txt")).toBe("text");
    expect(read("inbox/.hidden.pdf")).toBe("hidden");
    expect(read("sorted/moves-2026-11-26.log")).toBe(
      "planned inbox/IMG_0001.JPG -> sorted/jpg/2026-10/IMG_0001.JPG\nplanned inbox/invoice-001.pdf -> sorted/pdf/2026-10/invoice-001-2.pdf\nplanned inbox/sub/deep.pdf -> sorted/pdf/2026-10/deep.pdf\n",
    );
    expect(countFiles()).toBe(n + 1); // the log is the only new file; nothing was deleted
  });

  it("skip leaves the colliding file in place; copy_files keeps the source; case-only renames work", async () => {
    await run(organise("skip"));
    expect(read("inbox/invoice-001.pdf")).toBe("%PDF fixture 1");
    expect(read("sorted/pdf/2026-10/invoice-001.pdf")).toBe("an older, different file");
    put(ws, { "docs/a.md": "A" });
    const copy = { steps: [{ id: "f", type: "list_files", folder: "docs" }, { id: "c", type: "copy_files", to: "backup/{{name}}" }] };
    await run(copy);
    expect(read("docs/a.md")).toBe("A");
    expect(read("backup/a.md")).toBe("A");
    expect((await plan(copy)).operations[0]).toMatchObject({ status: "conflict" });
    put(ws, { "pics/PHOTO.JPG": "p" });
    const lower = { steps: [{ id: "f", type: "list_files", folder: "pics" }, { id: "m", type: "move_files", to: "pics/{{name | lower}}" }] };
    const r = await run(lower);
    expect(r.results[0].status).toBe("done");
    expect(readdirSync(join(ws, "pics"))).toEqual(["photo.jpg"]);
  });
});

describe("Markdown notes digest", () => {
  it("collects open tasks across notes with front matter", async () => {
    put(ws, {
      "notes/2026-11-20-planning.md": "---\ntitle: Planning sync\ntags: [ops, q4]\n---\n# Planning\n\n## Actions\n- [ ] Send budget draft (Sam)\n- [x] Book room\n\n```\n- [ ] not a task (code)\n```\n",
      "notes/2026-11-24-retro.md": "# Retro\n\n- [ ] Fix flaky export\n* [ ] Update runbook\n",
      "notes/draft.txt": "- [ ] ignored, not markdown",
    });
    const recipe = {
      steps: [
        { id: "notes", type: "read_markdown", glob: "notes/*.md" },
        { id: "tasks", type: "unnest", field: "tasks", as: "task" },
        { id: "open", type: "filter", where: [{ field: "task.done", op: "eq", value: false }] },
        { id: "digest", type: "template", escape: "markdown", template: "# Open tasks ({{count}})\n{{#rows}}\n- [ ] {{task.text}} ({{title}}, line {{task.line}})\n{{/rows}}\n" },
        { id: "save", type: "write_file", from: "digest", path: "digests/open-tasks.md", if_exists: "overwrite" },
      ],
    };
    const p = await plan(recipe);
    expect(p.steps[0].rows).toBe(2);
    expect(p.steps[0].preview[0]).toMatchObject({ title: "Planning sync", tags: ["ops", "q4"], open_tasks: 1 });
    await run(recipe, { expected_plan_hash: p.plan_hash });
    expect(read("digests/open-tasks.md")).toBe("# Open tasks (3)\n- [ ] Send budget draft (Sam) (Planning sync, line 8)\n- [ ] Fix flaky export (Retro, line 3)\n- [ ] Update runbook (Retro, line 4)\n");
  });
});

describe("transforms", () => {
  it("map, join, concat, sort, limit, summarize, literal, read_json and to_csv work together", async () => {
    put(ws, { "plans.json": JSON.stringify({ meta: { v: 1 }, plans: [{ code: "PRO", label: "Pro", price: 20 }, { code: "TEAM", label: "Team", price: 50 }] }) });
    const recipe = {
      steps: [
        { id: "users", type: "literal", value: [{ email: "A@Example.test", plan: "pro", seats: "1", joined: "2026-11-03" }, { email: "b@example.test", plan: "team", seats: "4", joined: "" }, { email: "c@example.test", plan: "free", seats: "x", joined: "2026-10-01" }] },
        { id: "plans", type: "read_json", path: "plans.json", pointer: "/plans" },
        { id: "clean", type: "map", from: "users", rename: { seats: "seat_count" }, set: { email: "{{email | lower}}", domain: "example" }, cast: { seat_count: "integer", joined: "date" }, omit: ["domain"] },
        { id: "priced", type: "join", with: "plans", left_on: "plan", right_on: "code", ignore_case: true, fields: ["label", "price"] },
        { id: "more", type: "literal", value: [{ email: "d@example.test", plan: "pro", seat_count: 2, joined: "2026-11-20", label: "Pro", price: 20 }] },
        { id: "all", type: "concat", from: ["priced", "more"] },
        { id: "by_joined", type: "sort", by: [{ field: "joined", order: "desc", type: "date" }] },
        { id: "top", type: "limit", count: 3 },
        { id: "stats", type: "summarize", from: "all", metrics: [{ op: "count", as: "users" }, { op: "sum", field: "price", as: "mrr" }, { op: "avg", field: "seat_count", as: "avg_seats" }, { op: "max", field: "joined", as: "latest" }, { op: "count_distinct", field: "plan", as: "plans" }] },
        { id: "csv", type: "to_csv", from: "top", columns: ["email", "plan", "seat_count", "joined", "label", "price"] },
        { id: "save", type: "write_file", from: "csv", path: "users.csv" },
      ],
    };
    const p = await plan(recipe, { preview_rows: 10 });
    expect(p.warnings.join(" ")).toMatch(/1 value\(s\) could not be converted/);
    expect(p.steps.find((s: any) => s.id === "stats").preview).toEqual([{ users: 4, mrr: 90, avg_seats: 2.3333333333, latest: "2026-11-20", plans: 3 }]);
    expect(p.steps.find((s: any) => s.id === "top").preview.map((r: any) => r.email)).toEqual(["d@example.test", "a@example.test", "c@example.test"]);
    expect(p.operations[0].preview).toBe("email,plan,seat_count,joined,label,price\r\nd@example.test,pro,2,2026-11-20,Pro,20\r\na@example.test,pro,1,2026-11-03,Pro,20\r\nc@example.test,free,,2026-10-01,,\r\n");
  });

  it("filters with numbers, dates, lists, like and vars", async () => {
    const rows = [{ n: "10", d: "2026-11-01", tags: ["a", "b"], name: "Report Q4.pdf" }, { n: "9", d: "2026-12-01", tags: [], name: "photo.jpg" }, { n: "", d: "", tags: ["b"], name: "Q4 notes.md" }];
    const f = async (where: any[], match = "all") => (await plan({ vars: { since: "2026-11-15" }, steps: [{ id: "r", type: "literal", value: rows }, { id: "f", type: "filter", where, match }] }, { preview_rows: 10 })).steps[1].preview.map((r: any) => r.name);
    expect(await f([{ field: "n", op: "gt", value: 9 }])).toEqual(["Report Q4.pdf"]); // numeric, not text, comparison; empty never matches
    expect(await f([{ field: "d", op: "gte", value: "{{vars.since}}", type: "date" }])).toEqual(["photo.jpg"]);
    expect(await f([{ field: "tags", op: "contains", value: "b" }])).toEqual(["Report Q4.pdf", "Q4 notes.md"]);
    expect(await f([{ field: "name", op: "like", value: "*q4*" }])).toEqual(["Report Q4.pdf", "Q4 notes.md"]);
    expect(await f([{ field: "n", op: "empty" }, { field: "name", op: "ends_with", value: ".jpg" }], "any")).toEqual(["photo.jpg", "Q4 notes.md"]);
  });

  it("read_input reads the tool's input_text (for example another agent's output)", async () => {
    const recipe = { steps: [{ id: "in", type: "read_input", format: "text" }, { id: "w", type: "write_file", from: "in", path: "captions/{{vars.slug}}.srt" }] };
    const r = await run(recipe, { vars: { slug: "Episode 1" }, input_text: "1\n00:00:00,000 --> 00:00:02,000\nHello\n" });
    expect(r.results.at(-1).status).toBe("done");
    expect(read("captions/Episode 1.srt")).toMatch(/Hello/);
    expect(await codeOf(plan(recipe))).toBe("missing_input");
    const csv = await plan({ steps: [{ id: "in", type: "read_input", format: "csv" }, { id: "s", type: "summarize", metrics: [{ op: "sum", field: "x" }] }] }, { input_text: "x\n1\n2.5\n" });
    expect(csv.steps[1].preview).toEqual([{ sum_x: 3.5 }]);
  });
});

// ------------------------------------------------------------------------------------------------
describe("workspace confinement", () => {
  it("refuses paths that leave the workspace, including through rendered values", async () => {
    put(ws, { "data/a.csv": "x\n1\n" });
    for (const p of ["../x.csv", "data/../../x.csv"]) expect(await codeOf(plan({ steps: [{ id: "a", type: "read_csv", path: p }] }))).toBe("invalid_recipe");
    // A var cannot add "..": the value becomes one file name ("-..-secret.csv"), which does not exist.
    const e = await errOf(plan({ steps: [{ id: "a", type: "read_text", path: "data/{{vars.f}}" }] }, { vars: { f: "../../secret.csv" } }));
    expect(e.code).toBe("not_found");
    expect(e.message).toMatch(/data\/-\.\.-secret\.csv was not found/);
    const w = await plan({ steps: [{ id: "w", type: "write_file", content: "x", path: "out/{{vars.f}}.md" }] }, { vars: { f: "../../../evil" } });
    expect(w.operations.map((o: any) => o.path)).toEqual(["out", "out/-..-..-evil.md"]);
  });

  it("refuses a drive or file-system root as the workspace", () => {
    expect(() => workspaceRoot(parsePath(process.cwd()).root)).toThrow(/it is a drive or file-system root/);
    expect(() => workspaceRoot(join(ws, "missing"))).toThrow(/does not exist/);
  });

  it("normalises recipe paths", () => {
    expect(normalizeRel("./data\\x.csv", "p")).toBe("data/x.csv");
    expect(normalizeRel("data/", "p")).toBe("data");
    expect(() => normalizeRel("data//x", "p")).toThrow(/empty/);
    expect(compileGlob("exports/*.{csv,tsv}").base).toBe("exports");
    expect(compileGlob("exports/*.{csv,tsv}").match("exports/A.CSV")).toBe(true);
    expect(compileGlob("notes/**/*.md").match("notes/a/b/c.md")).toBe(true);
    expect(compileGlob("notes/*.md").match("notes/a/c.md")).toBe(false);
  });
});

describe("links (symlink / junction) never lead outside", () => {
  beforeEach(() => {
    put(ws, { "data/ok.csv": "x\n1\n" });
    linkDir(outside, join(ws, "linked"));
  });

  it("does not read through a linked folder that points outside", async () => {
    const e = await errOf(plan({ steps: [{ id: "a", type: "read_csv", path: "linked/secret.csv" }] }));
    expect(e.code).toBe("path_outside_workspace");
    expect(e.message).toMatch(/resolves \(through a link\)/);
  });

  it("does not list links, nor follow linked folders", async () => {
    const p = await plan({ steps: [{ id: "f", type: "list_files", pattern: "**/*" }] }, { preview_rows: 20 });
    expect(p.steps[0].preview.map((r: any) => r.path)).toEqual(["data/ok.csv"]);
    expect(p.warnings.join(" ")).toMatch(/skipped 1 link/);
    const g = await plan({ steps: [{ id: "a", type: "read_csv", glob: "**/*.csv" }] });
    expect(g.steps[0].rows).toBe(1);
  });

  it("does not write, move or copy into or out of a linked folder", async () => {
    const before = snapshot(outside);
    expect(await codeOf(plan({ steps: [{ id: "w", type: "write_file", content: "x", path: "linked/new.md" }] }))).toBe("unsafe_path");
    expect(await codeOf(plan({ steps: [{ id: "w", type: "write_file", content: "x", path: "linked/notes.md", if_exists: "overwrite" }] }))).toBe("unsafe_path");
    expect(await codeOf(plan({ steps: [{ id: "f", type: "list_files", folder: "data" }, { id: "m", type: "move_files", to: "linked/{{name}}" }] }))).toBe("unsafe_path");
    expect(await codeOf(plan({ steps: [{ id: "r", type: "literal", value: [{ path: "linked/secret.csv" }] }, { id: "c", type: "copy_files", to: "copied.csv" }] }))).toBe("unsafe_path");
    expect(await codeOf(plan({ steps: [{ id: "w", type: "write_file", content: "x", path: "linked" }] }))).toBe("unsafe_path");
    expect(snapshot(outside)).toEqual(before);
    expect(read("data/ok.csv")).toBe("x\n1\n");
  });

  it("file symlinks pointing outside are refused (skipped where the OS needs admin rights for them)", async (t) => {
    try {
      symlinkSync(join(outside, "secret.csv"), join(ws, "data", "evil.csv"), "file");
    } catch (e: any) {
      if (e.code === "EPERM") return t.skip();
      throw e;
    }
    expect(await codeOf(plan({ steps: [{ id: "a", type: "read_csv", path: "data/evil.csv" }] }))).toBe("path_outside_workspace");
    expect(await codeOf(plan({ steps: [{ id: "w", type: "write_file", content: "x", path: "data/evil.csv", if_exists: "overwrite" }] }))).toBe("unsafe_path");
    expect(readFileSync(join(outside, "secret.csv"), "utf8")).toBe("a,b\n1,2\n");
  });
});

describe("limits", () => {
  it("refuses oversized and binary inputs", async () => {
    put(ws, { "big.csv": "x\n" + "1\n".repeat(2000), "bin.dat": Buffer.from([0x50, 0x4b, 0x03, 0x04, 0x00, 0x00, 0x14]) });
    expect((await errOf(plan({ limits: { max_file_bytes: 1024 }, steps: [{ id: "a", type: "read_csv", path: "big.csv" }] }))).message).toMatch(/the limit is 1024 bytes per file/);
    expect((await errOf(plan({ limits: { max_rows: 100 }, steps: [{ id: "a", type: "read_csv", path: "big.csv" }] }))).message).toMatch(/more than 100 rows/);
    expect((await errOf(plan({ steps: [{ id: "a", type: "read_text", path: "bin.dat" }] }))).message).toMatch(/binary/);
    expect(await codeOf(plan({ steps: [{ id: "a", type: "read_input", format: "text" }] }, { input_text: "x".repeat(5_000_001) }))).toBe("invalid_input");
  });

  it("limits planned operations, output size and bytes written", async () => {
    const many = { limits: { max_operations: 5 }, steps: [{ id: "r", type: "literal", value: Array.from({ length: 6 }, (_, i) => ({ i })) }, { id: "w", type: "write_file", for_each: "r", path: "n/{{i}}.md", content: "x" }] };
    expect((await errOf(plan(many))).message).toMatch(/more than 5 file operations/);
    const huge = { limits: { max_output_chars: 1000 }, steps: [{ id: "r", type: "literal", value: Array.from({ length: 200 }, () => ({ a: "xxxxxxxxxx" })) }, { id: "t", type: "template", template: "{{#rows}}{{a}}{{/rows}}" }] };
    expect((await errOf(plan(huge))).message).toMatch(/longer than 1000 characters/);
    const bytes = { limits: { max_write_bytes: 10 }, steps: [{ id: "w", type: "write_file", content: "more than ten bytes", path: "x.md" }] };
    expect((await errOf(plan(bytes))).message).toMatch(/more than 10 bytes in total/);
    expect(exists("x.md")).toBe(false);
  });

  it("stops when the time limit is exceeded, before writing anything", () => {
    put(ws, { "a.csv": "x\n1\n" });
    const recipe = { steps: [{ id: "a", type: "read_csv", path: "a.csv" }, { id: "w", type: "to_csv" }, { id: "s", type: "write_file", path: "b.csv" }] };
    expect(() => buildPlan({ recipe }, { root: ws, now: NOW, deadlineMs: Date.now() - 1 })).toThrow(/time limit/);
    expect(exists("b.csv")).toBe(false);
  });

  it("does not let a step read what an earlier step of the same recipe changes", async () => {
    const e = await errOf(plan({ steps: [{ id: "w", type: "write_file", content: "x", path: "a.txt" }, { id: "r", type: "read_text", path: "a.txt" }] }));
    expect(e.message).toMatch(/changed by an earlier step/);
    put(ws, { "in/a.txt": "a" });
    const e2 = await errOf(plan({ steps: [{ id: "f", type: "list_files", folder: "in" }, { id: "m", type: "move_files", to: "in/sub/{{name}}" }, { id: "g", type: "list_files", folder: "in" }] }));
    expect(e2.message).toMatch(/list files before the file steps/);
  });
});

// ------------------------------------------------------------------------------------------------
function runCli(args: string[], cwd: string) {
  const env = { ...process.env };
  delete env.AGENTROVE_WORKFLOW_ROOT;
  try {
    return { code: 0, out: execFileSync(process.execPath, [join(AGENT_DIR, "bin", "cli.js"), ...args], { cwd, env, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }) };
  } catch (e: any) {
    return { code: e.status, out: String(e.stdout), err: String(e.stderr) };
  }
}

describe("CLI and MCP stdio", () => {
  it("CLI: plans in the start folder, then runs with confirm and the plan hash", () => {
    put(ws, { ".agentrove-workspace": "", "data/orders-2026-11.csv": ORDERS, "plan.json": JSON.stringify({ recipe: salesRecipe() }) });
    const p = runCli(["plan_recipe", "--input", "plan.json"], ws);
    expect(p.code).toBe(0);
    const planOut = JSON.parse(p.out);
    expect(planOut.workspace.toLowerCase()).toBe(workspaceRoot(ws).toLowerCase());
    put(ws, { "run.json": JSON.stringify({ recipe: salesRecipe(), confirm: true, expected_plan_hash: planOut.plan_hash }) });
    // The run is a different day for the CLI clock only if the date changed; the report has no run.date, so the hash matches.
    const r = runCli(["run_recipe", "--input", "run.json"], ws);
    expect(r.code, r.err).toBe(0);
    expect(read("reports/sales-2026-11.md")).toMatch(/^# Sales 2026-11/);
    const bad = runCli(["run_recipe", "--json", JSON.stringify({ recipe: salesRecipe() })], ws);
    expect(bad.code).toBe(1);
    expect(bad.err).toMatch(/confirmation_required/);
  });

  it("MCP: lists the three tools, plans, refuses run without confirm, and runs with it", async () => {
    put(ws, { ".agentrove-workspace": "", "data/orders-2026-11.csv": ORDERS });
    const env = { ...process.env };
    delete env.AGENTROVE_WORKFLOW_ROOT;
    const child = spawn(process.execPath, [join(AGENT_DIR, "bin", "mcp.js")], { cwd: ws, env, stdio: ["pipe", "pipe", "pipe"] });
    const replies: any[] = [];
    let buf = "";
    child.stdout.on("data", (d) => {
      buf += d;
      let i;
      while ((i = buf.indexOf("\n")) >= 0) {
        replies.push(JSON.parse(buf.slice(0, i)));
        buf = buf.slice(i + 1);
      }
    });
    const send = (m: any) => child.stdin.write(JSON.stringify(m) + "\n");
    const waitFor = async (id: number) => {
      for (let k = 0; k < 200; k++) {
        const r = replies.find((x) => x.id === id);
        if (r) return r;
        await new Promise((res) => setTimeout(res, 25));
      }
      throw new Error(`no reply ${id}`);
    };
    try {
      send({ jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2025-06-18", capabilities: {}, clientInfo: { name: "test", version: "0" } } });
      expect((await waitFor(1)).result.serverInfo).toMatchObject({ name: "agentrove.workflow-automation", version: manifest.version });
      send({ jsonrpc: "2.0", method: "notifications/initialized" });
      send({ jsonrpc: "2.0", id: 2, method: "tools/list" });
      expect((await waitFor(2)).result.tools.map((t: any) => t.name)).toEqual(["validate_recipe", "plan_recipe", "run_recipe"]);
      send({ jsonrpc: "2.0", id: 3, method: "tools/call", params: { name: "plan_recipe", arguments: { recipe: salesRecipe() } } });
      const planned = (await waitFor(3)).result;
      expect(planned.isError).toBe(false);
      expect(planned.structuredContent.operations).toHaveLength(2);
      expect(exists("reports")).toBe(false);
      send({ jsonrpc: "2.0", id: 4, method: "tools/call", params: { name: "run_recipe", arguments: { recipe: salesRecipe() } } });
      const refused = (await waitFor(4)).result;
      expect(refused.isError).toBe(true);
      expect(refused.content[0].text).toMatch(/confirmation_required/);
      send({ jsonrpc: "2.0", id: 5, method: "tools/call", params: { name: "run_recipe", arguments: { recipe: salesRecipe(), confirm: true, expected_plan_hash: planned.structuredContent.plan_hash } } });
      const ran = (await waitFor(5)).result;
      expect(ran.isError, ran.content[0].text).toBe(false);
      expect(read("reports/sales-2026-11.md")).toMatch(/North: 1 orders, 1250\.00/);
    } finally {
      child.kill();
    }
  });
});

Find an agent

Do not include passwords, keys, customer data or other confidential details.
Rule-based matching is free during the public beta (fair use).