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

Marketing Analytics v0.2.1 · generic

Archive SHA-256 8e33c2b8ecf72e82b9edc3bf24453b7c7f30311d425df18c285750c66a34b408 · 48.8 KB · built Nov 27, 2026

tests/marketing-analytics.test.ts

import { describe, it, expect, vi } from "vitest";
// @ts-expect-error -- plain JavaScript agent module without type declarations
import agentModule, { handleMcpMessage, makeContext, manifest, validateManifest } from "../src/index.js";

const agent: any = agentModule;
const now = () => new Date("2026-11-25T12:00:00Z");

// Fixture exports (synthetic). 2026-10-05 is a Monday (ISO week 2026-W41).
const SESSIONS = [
  "session_id,user_id,timestamp,utm_source,utm_medium,utm_campaign",
  "s1,u1,2026-10-05T10:00:00Z,google,cpc,spring",
  "s2,u2,2026-10-05T11:00:00Z,newsletter,email,launch",
  "s3,u3,2026-10-06T09:00:00Z,google,cpc,spring",
  "s4,u1,2026-10-07T09:00:00Z,newsletter,email,launch",
  "s5,u4,2026-10-12T09:00:00Z,(direct),(none),",
  "s6,u5,2026-10-13T09:00:00Z, Google ,CPC,Spring",
].join("\r\n");
const EVENTS = [
  "user_id,timestamp,event",
  "u1,2026-10-05T10:01:00Z,page_view",
  "u1,2026-10-05T10:05:00Z,signup",
  "u1,2026-10-08T10:00:00Z,download",
  "u2,2026-10-05T11:02:00Z,page_view",
  "u3,2026-10-06T09:10:00Z,page_view",
  "u3,2026-10-06T09:20:00Z,signup",
  "u4,2026-10-12T09:01:00Z,page_view",
  "u4,2026-10-12T09:05:00Z,signup",
  "u5,2026-10-13T09:10:00Z,page_view",
  "u5,2026-10-20T09:00:00Z,page_view",
  "u2,not-a-date,page_view",
  ",2026-10-14T00:00:00Z,page_view",
  "u2,2026-02-30T00:00:00Z,page_view",
].join("\n");
const DOWNLOADS = "user_id;created_at\nu3;2026-10-15 08:00:00\n";
const DATA = [
  { name: "sessions.csv", csv: SESSIONS, default_event: "session" },
  { name: "events.csv", csv: EVENTS },
  { name: "downloads.csv", csv: DOWNLOADS, default_event: "download" },
];

describe("marketing-analytics: manifest", () => {
  it("passes validateManifest and is fully offline", () => {
    expect(validateManifest(manifest)).toEqual([]);
    expect(manifest.id).toBe("agentrove.marketing-analytics");
    expect(manifest.permissions).toMatchObject({ filesystem: "none", network: [], credentials: [] });
    expect(manifest.tools.every((t: any) => t.side_effects === "none" && t.requires_confirmation === false)).toBe(true);
    expect(manifest.io_types.csv_files.description).toMatch(/CSV/);
  });

  it("has no network access at all (empty allowlist)", async () => {
    const fetch = vi.fn();
    const ctx = makeContext(manifest, { fetch });
    await expect(ctx.fetch("https://analytics.example.com/collect")).rejects.toMatchObject({ code: "network_denied" });
    expect(fetch).not.toHaveBeenCalled();
  });
});

describe("marketing-analytics: data loading", () => {
  it("parses quoted CSV, semicolons, BOM and reports skipped rows instead of guessing", async () => {
    const out = await agent.call("funnel", { data: DATA, steps: ["page_view", "signup"] });
    const ev = out.data_quality.datasets.find((d: any) => d.name === "events.csv");
    expect(ev).toMatchObject({ rows: 13, used: 10, skipped: { missing_user: 1, bad_timestamp: 2, missing_event: 0 } });
    expect(out.data_quality.datasets.find((d: any) => d.name === "downloads.csv").columns).toEqual({ user_id: "user_id", timestamp: "created_at" });
    expect(out.warnings.join(" ")).toMatch(/events\.csv: skipped 3 of 13 rows/);
    expect(out.warnings.join(" ")).toMatch(/1 timestamp\(s\) had no time zone and were read as UTC/);
    expect(out.data_quality.users).toBe(5);

    const quoted = '\ufeffuser_id,timestamp,event,note\n"u,1",2026-10-01T00:00:00+02:00,signup,"said ""hi""\nthen left"\n';
    const q = await agent.call("funnel", { data: [{ name: "q", csv: quoted }], steps: ["signup", "download"] });
    expect(q.steps[0].users).toBe(1);
    expect(q.data_quality.date_range.start).toBe("2026-09-30T22:00:00.000Z");
  });

  it("rejects invalid input", async () => {
    await expect(agent.call("funnel", { data: [], steps: ["a", "b"] })).rejects.toMatchObject({ code: "invalid_input" });
    await expect(agent.call("funnel", { data: DATA, steps: ["a"] })).rejects.toMatchObject({ code: "invalid_input" });
    await expect(agent.call("funnel", { data: DATA, steps: ["a", "a"] })).rejects.toMatchObject({ code: "invalid_input" });
    await expect(agent.call("funnel", { data: [{ name: "x", csv: "foo,bar\n1,2" }], steps: ["a", "b"] })).rejects.toMatchObject({ code: "invalid_input" });
    await expect(agent.call("funnel", { data: [{ name: "x", csv: "user_id,timestamp\nu1,2026-01-01" }], steps: ["a", "b"] })).rejects.toMatchObject({ code: "invalid_input", message: expect.stringMatching(/default_event/) });
    await expect(agent.call("funnel", { data: [{ name: "x", csv: 'user_id,timestamp,event\n"u1,2026' }], steps: ["a", "b"] })).rejects.toMatchObject({ code: "invalid_input", message: expect.stringMatching(/unterminated/) });
    await expect(agent.call("funnel", { data: [DATA[1], DATA[1]], steps: ["a", "b"] })).rejects.toMatchObject({ code: "invalid_input", message: expect.stringMatching(/Duplicate/) });
    await expect(agent.call("funnel", { data: DATA, steps: ["page_view", "signup"], columns: { user_id: "uid" } })).rejects.toMatchObject({ code: "invalid_input" });
  });
});

describe("marketing-analytics: funnel", () => {
  it("counts ordered distinct-user conversion with Wilson intervals", async () => {
    const out = await agent.call("funnel", { data: DATA, steps: ["page_view", "signup", "download"] });
    expect(out.steps.map((s: any) => s.users)).toEqual([5, 3, 2]);
    expect(out.steps[1].conversion_from_previous).toBe(0.6);
    expect(out.steps[2].conversion_from_previous).toBe(0.6667);
    expect(out.steps[2].conversion_from_first).toBe(0.4);
    expect(out.steps[1].drop_off_from_previous).toBe(2);
    const [lo, hi] = out.steps[2].ci95_from_first;
    expect(lo).toBeGreaterThan(0.1);
    expect(hi).toBeLessThan(0.8);
    expect(out.overall).toMatchObject({ entered: 5, completed: 2, conversion: 0.4 });
    expect(out.notes.join(" ")).toMatch(/Only 5 users/);
    // u3's download comes 9 days after page_view: outside a 7-day window.
    const windowed = await agent.call("funnel", { data: DATA, steps: ["page_view", "signup", "download"], window_days: 7 });
    expect(windowed.steps.map((s: any) => s.users)).toEqual([5, 3, 1]);
  });

  it("returns n/a (null), not 0%, when nobody enters the funnel", async () => {
    const out = await agent.call("funnel", { data: DATA, steps: ["purchase", "refund"] });
    expect(out.steps[0].users).toBe(0);
    expect(out.steps[1].conversion_from_previous).toBeNull();
    expect(out.overall.conversion).toBeNull();
    expect(out.warnings.join(" ")).toMatch(/No rows have these step events: purchase, refund/);
  });
});

describe("marketing-analytics: attribution", () => {
  it("credits first and last UTM touch within the lookback and reports unattributed conversions", async () => {
    const out = await agent.call("attribution", { data: DATA, conversion_events: ["signup", "download"] });
    expect(out).toMatchObject({ conversions: 5, attributed: 4, unattributed: 1, lookback_days: 30 });
    const g = out.rows.find((r: any) => r.channel === "google / cpc / spring");
    const n = out.rows.find((r: any) => r.channel === "newsletter / email / launch");
    expect(g).toMatchObject({ first_touch: 4, last_touch: 3, first_touch_share: 1, last_touch_share: 0.75 });
    expect(g.by_event.download).toEqual({ first_touch: 2, last_touch: 1 });
    expect(n).toMatchObject({ first_touch: 0, last_touch: 1 });
    expect(out.notes.join(" ")).toMatch(/1 of 5 conversions had no UTM-tagged touch/);
    // Direct traffic is never a touch; u5's mixed-case UTM values were normalised into the google row.
    expect(out.rows.some((r: any) => r.channel.includes("direct"))).toBe(false);
    const bySource = await agent.call("attribution", { data: DATA, conversion_events: ["signup"], group_by: "source", lookback_days: 1 });
    expect(bySource.rows).toHaveLength(1);
    expect(bySource.rows[0]).toMatchObject({ channel: "google", source: "google", first_touch: 2, last_touch: 2 });
  });
});

describe("marketing-analytics: cohort_retention", () => {
  it("builds ISO-week cohorts and marks unobserved and partial weeks", async () => {
    const out = await agent.call("cohort_retention", { data: DATA, weeks: 3 });
    expect(out.cohorts.map((c: any) => [c.cohort_week, c.week_start_date, c.size])).toEqual([
      ["2026-W41", "2026-10-05", 3],
      ["2026-W42", "2026-10-12", 2],
    ]);
    const w41 = out.cohorts[0].retention;
    expect(w41.map((x: any) => x.active)).toEqual([3, 1, 0, null]);
    expect(w41[1].rate).toBe(0.3333);
    expect(w41[2]).toMatchObject({ observed: true, partial: true });
    expect(w41[3]).toMatchObject({ observed: false, rate: null });
    expect(out.cohorts[1].retention.map((x: any) => x.rate)).toEqual([1, 0.5, null, null]);
    expect(out.data_end).toBe("2026-10-20T09:00:00.000Z");
    expect(out.notes.join(" ")).toMatch(/fewer than 20 users/);
    const bySignup = await agent.call("cohort_retention", { data: DATA, cohort_event: "signup", activity_events: ["download"], weeks: 1 });
    expect(bySignup.cohorts.map((c: any) => c.size)).toEqual([2, 1]);
    expect(bySignup.cohorts[0].retention.map((x: any) => x.active)).toEqual([1, 1]);
    expect(bySignup.notes.join(" ")).toMatch(/2 user\(s\) never had "signup"/);
  });
});

describe("marketing-analytics: campaign_comparison", () => {
  it("compares campaigns with intervals, small-sample notes and a z-test", async () => {
    const out = await agent.call("campaign_comparison", { data: DATA, conversion_events: ["signup"] });
    expect(out.rows.map((r: any) => [r.group, r.visitors, r.sessions, r.conversions.signup.users])).toEqual([
      ["spring", 3, 3, 2],
      ["launch", 2, 2, 0],
    ]);
    expect(out.rows[0].conversions.signup.rate).toBe(0.6667);
    expect(out.rows.every((r: any) => r.confidence === "low")).toBe(true);
    expect(out.rows[0].confidence_notes[0]).toMatch(/Small sample: 3 visitor/);
    const c = out.comparisons[0];
    expect(c).toMatchObject({ event: "signup", best: "spring", runner_up: "launch", significant: null });
    expect(c.p_value).toBeCloseTo(0.136, 2);
    expect(c.note).toMatch(/Too few conversions/);
    expect(out.markdown_table).toContain("| spring | 3 | 3 | 2 \u00b7 66.7% (");
    expect(out.markdown_table.split("\n")[0]).toBe("| campaign | Visitors | Sessions | signup rate (95% CI) | Confidence |");
  });

  it("finds a significant difference on a larger synthetic sample", async () => {
    const rows = ["user_id,timestamp,event,utm_campaign"];
    for (let i = 0; i < 200; i++) {
      const camp = i < 100 ? "a" : "b";
      rows.push(`u${i},2026-10-01T00:00:00Z,visit,${camp}`);
      const converts = camp === "a" ? i % 2 === 0 : i % 10 === 0;
      if (converts) rows.push(`u${i},2026-10-02T00:00:00Z,signup,`);
    }
    const out = await agent.call("campaign_comparison", { data: [{ name: "big", csv: rows.join("\n") }], conversion_events: ["signup"] });
    expect(out.rows.map((r: any) => r.conversions.signup.rate)).toEqual([0.5, 0.1]);
    expect(out.rows.every((r: any) => r.confidence === "ok")).toBe(true);
    expect(out.comparisons[0]).toMatchObject({ best: "a", significant: true });
    expect(out.comparisons[0].p_value).toBeLessThan(0.001);
    expect(out.notes.join(" ")).toMatch(/No session_id column/);
  });
});

describe("marketing-analytics: build_report", () => {
  it("returns a JSON report and an escaped Markdown summary", async () => {
    const evil = { name: "evil|<script>.csv", csv: "user_id,timestamp,event,utm_campaign\nu9,2026-10-05T00:00:00Z,visit,<img src=x onerror=alert(1)>|x\n" };
    const out = await agent.call("build_report", { data: [...DATA, evil], funnel_steps: ["page_view", "signup"], conversion_events: ["signup"], weeks: 2, title: "Q4 *launch*" }, { now });
    expect(Object.keys(out.report.sections).sort()).toEqual(["attribution", "campaigns", "funnel", "retention"]);
    expect(out.report.generated_at).toBe("2026-11-25T12:00:00Z");
    expect(out.markdown).toMatch(/^# Q4 \\\*launch\\\*/);
    expect(out.markdown).toContain("## Funnel");
    expect(out.markdown).toContain("## Attribution (lookback 30 days)");
    expect(out.markdown).toContain("## Weekly retention");
    expect(out.markdown).toContain("nothing is estimated");
    expect(out.markdown).not.toContain("<img");
    expect(out.markdown).not.toContain("<script>");
    expect(out.markdown).toContain("evil\\|&lt;script&gt;.csv");
    expect(out.markdown).toContain("| &lt;img src=x onerror=alert(1)&gt;\\|x | 1 | 1 |");
    const minimal = await agent.call("build_report", { data: DATA, cohorts: false }, { now });
    expect(minimal.report.sections).toEqual({});
    expect(minimal.report.notes.join(" ")).toMatch(/Pass funnel_steps/);
  });
});

describe("marketing-analytics: MCP", () => {
  it("lists and calls tools over JSON-RPC", async () => {
    const list = await handleMcpMessage(agent, { jsonrpc: "2.0", id: 1, method: "tools/list" });
    expect(list.result.tools.map((t: any) => t.name)).toEqual(["funnel", "attribution", "cohort_retention", "campaign_comparison", "build_report", "channel_performance"]);
    const call = await handleMcpMessage(agent, { jsonrpc: "2.0", id: 2, method: "tools/call", params: { name: "funnel", arguments: { data: DATA, steps: ["page_view", "signup"] } } });
    expect(call.result.isError).toBe(false);
    expect(call.result.structuredContent.overall.completed).toBe(3);
    const bad = await handleMcpMessage(agent, { jsonrpc: "2.0", id: 3, method: "tools/call", params: { name: "funnel", arguments: { data: DATA } } });
    expect(bad.result.isError).toBe(true);
    expect(bad.result.content[0].text).toMatch(/^invalid_input: /);
  });
});

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).