> ## Documentation Index
> Fetch the complete documentation index at: https://docs.runtm.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Deterministic fraud monitoring from spreadsheets

> Build a scheduled agent that reads the day's fraud report and sales volume exports (xlsx) and a plain-text watchlist from one SharePoint folder, scores every merchant with scripts instead of the model, reconciles the result, appends it to a tracker workbook and posts a summary. Read this when the job is the same calculation every run and the output must be identical for identical inputs.

## What you will have

A roster agent called **Monitor Agent** that runs every weekday morning, finds that day's exports in a SharePoint folder, and turns them into one row per merchant in a tracker workbook plus a short summary in `#fraud-monitoring`. Every number in the output comes from three Python scripts bundled with its skill: they parse the files, compute each merchant's fraud-to-sales ratios against fixed thresholds, and reconcile the totals before anything is written. The model decides only what a script can't: which folder is today's, whether an input is missing, and one sentence on why each new breach matters. Run it twice on the same files and you get the same rows.

This guide follows the six steps of [Build an agent](https://docs.runtm.com/build/overview.md). It is the worked example for [Code or prompt](https://docs.runtm.com/build/how-it-works/code-or-prompt.md): the whole job is a fixed sequence of parsing, arithmetic and lookups, so it lives in scripts and the agent runs them.

## The agent spec

| # | Question | Monitor Agent |
| - | - | - |
| 1 | What is the job? | Each weekday, score every merchant in the processor's fraud report against its month-to-date sales, flag `watch` and `breach` tiers, append the rows to the tracker and post a summary. Never act on a merchant. |
| 2 | How is success measured? | Categories `daily-run` and `missing-input`. Pass when the appended rows equal the scripts' output and the summary matches it, or when a missing file stops the run before anything is written. \$20 and 45 minutes of analyst time per run. \$150 monthly budget. |
| 3 | What can it reach? | Template **Fraud Monitoring** (blank environment). Microsoft 365, agent-scoped, granted one SharePoint folder. Tooling: `uv`, which runs the scripts with a pinned `openpyxl`. |
| 4 | How does it work? | Skill `fraud-monitoring` with `scripts/parse_inputs.py`, `scripts/score.py`, `scripts/validate.py` and `assets/thresholds.json`. Trigger: a weekday schedule posting to `#fraud-monitoring`. |
| 5 | Does it work? | Unit tests: a skill eval suite of fixture days with exact expected rows, checked by script. Integration: three past days run with **Run now**; the rows must match exactly. |
| 6 | Now lock it down | Allow only the helper's read, download and append commands and `uv run` of the bundled scripts; deny writes, sends and deletes; network rules for Microsoft Graph and PyPI. |

## Inputs and output

The processor drops three files into `Fraud monitoring/in/<YYYY-MM-DD>/` every morning:

| File | Format | One row is |
| - | - | - |
| `fraud_reports.xlsx` | Excel, header row: `merchant_id`, `report_date`, `txn_date`, `amount`, `card_bin`, `reason_code` | One transaction the card networks reported as fraud |
| `sales_volume.xlsx` | Excel, header row: `merchant_id`, `sales_count`, `sales_amount` | One merchant's month-to-date settled sales |
| `watchlist.txt` | Text, one merchant per line: the merchant id, a pipe, then the reason; `#` lines are comments | A merchant risk already has an eye on |

The output goes to the `Daily` table of `Fraud monitoring tracker.xlsx`, one row per merchant with reports: `date`, `merchant_id`, `fraud_count`, `fraud_amount`, `sales_count`, `count_ratio`, `amount_ratio`, `tier`, `watchlist`, `new`. A merchant is `breach` when it has at least 10 reports and \$5,000 reported and either ratio reaches 0.90%, `watch` when either ratio reaches 0.65%, `no-volume` when it has reports but no sales this month, and `ok` otherwise. `new` marks a `watch` or `breach` that differs from the merchant's last tier in the tracker. The thresholds here are illustrative; put your own program's in `assets/thresholds.json`.

## 1. Define the job

Read [Define the job](https://docs.runtm.com/build/define-the-job.md) first. Decide what is code and what is judgment before you write a word of instructions: here every count, sum, ratio and tier is code, and the agent only orchestrates.

**1. Create the roster agent**

Go to **Agents** and click **New Agent**. On **Profile** name it `Monitor Agent`. On **Instructions**, use this description:

> Scores the day's fraud report against merchant sales volume with fixed scripts, appends the results to the fraud monitoring tracker and posts a summary. Never acts on a merchant.

And these system instructions:

```markdown theme={null}
You are the Monitor Agent for Northstar Payments.

Every run follows the fraud-monitoring skill exactly. Its scripts do
all parsing, arithmetic and scoring. You never compute, round, edit or
re-derive a number, a ratio or a tier yourself: you copy the scripts'
output.

Your judgment is limited to:
- Finding today's input folder and its three files.
- Stopping, with nothing written, when a file is missing or a script
  exits non-zero, and saying which file or check failed.
- One sentence per new breach saying what stands out in its rows.

Never:
- Edit the skill's scripts or thresholds, or work around a failed check.
- Write anywhere except the Daily table of the tracker workbook.
- Contact a merchant, or hold, limit or close an account.
```

Skip **Triggers** for now and click **Create agent**.

```text theme={null}
cli: runtm-api agents create --name "Monitor Agent" --description "Scores the day's fraud report against merchant sales volume with fixed scripts, appends the results to the fraud monitoring tracker and posts a summary. Never acts on a merchant." --instructions "$(cat monitor-agent-instructions.md)"
```

**2. Point it at a template**

Open the agent's card. Under **Default template** pick **Fraud Monitoring** (created in step 3; come back and set it if the template does not exist yet). Leave **Coding agent** on Claude Code. Click **Save profile**.

```text theme={null}
cli: runtm-api agents update <agent_id> --template "Fraud Monitoring" --agent claude-code
cli-verify: runtm-api agents get <agent_id> | jq '{name, default_template, default_agent}'
```

## 2. Measure success

Read [Measure success](https://docs.runtm.com/build/measure-success.md). A deterministic job has an unusually sharp criterion: the output either equals the scripts' output or it doesn't.

**1. Add two evaluation categories**

On the agent's **Performance** tab, add:

| Key | When to use | Success criteria |
| - | - | - |
| `daily-run` | All three inputs were present | `validate.py` printed OK; the rows appended to `Daily` are exactly the rows in `rows.json`, in order; the posted summary is `summary.md` plus at most one sentence per new breach; no number in the message differs from the scripts' output |
| `missing-input` | An input file was missing or a script exited non-zero | Nothing was appended; the message names the missing file or the failed check |

Set **Human cost** to \$20 and **Human time** to 45 minutes for both, and a monthly budget of \$150.

```text theme={null}
cli: runtm-api agents update <agent_id> --evaluator-criteria "$(cat rubric.json)" --economics '{"tasks":{"daily-run":{"value_usd":20,"minutes":45},"missing-input":{"value_usd":20,"minutes":45}},"budget":{"monthly_usd_cap":150}}'
cli-verify: runtm-api agents get <agent_id> | jq '.evaluator_criteria.categories[].key'
```

Session grades tell you whether a run did its job. The scripts have their own tests in the skill's eval suite, run before you publish a change to them: see [Skill evals and session evals](https://docs.runtm.com/build/skill-and-session-evals.md).

## 3. Give it tools

Read [Give it tools](https://docs.runtm.com/build/give-it-tools.md). One system, scoped to one folder.

**1. Create the Fraud Monitoring template**

Go to **Templates**, click **New Template**, choose **Blank environment**, name it `Fraud Monitoring`, keep **Basic** and click **Create Template**. Nothing is cloned; the template carries the connection and the skill.

```text theme={null}
cli: runtm-api template list
```

**2. Microsoft 365, agent-scoped, one folder**

Open **Monitor Agent**'s sheet and connect **Microsoft 365** there, signed in as the risk team's service account, so the connection belongs to this agent only. Then, in the agent's Microsoft 365 access settings, paste the SharePoint link of the `Fraud monitoring` folder (**Copy link** in SharePoint). The agent can open that folder and everything in it, and nothing else on the site. Put the tracker workbook inside the folder too.

```text theme={null}
cli-handoff: https://app.runtm.com/connect?provider=microsoft-365&agent=<monitor_agent_id>&method=microsoft_oauth
cli-verify: runtm-api tools list --provider microsoft-365
```

## 4. Define how it works

Read [Define how it works](https://docs.runtm.com/build/how-it-works/overview.md) and [Code or prompt](https://docs.runtm.com/build/how-it-works/code-or-prompt.md). The runbook is a skill whose steps are commands, and the scripts are files in that skill.

**1. Write the fraud-monitoring skill**

Under **Settings > Context > Skills**, click **New skill** and create `fraud-monitoring` with this `SKILL.md`:

```markdown theme={null}
---
name: fraud-monitoring
description: Score the day's fraud report against merchant sales volume, append the results to the fraud monitoring tracker and summarize. Use on every scheduled monitoring run.
---

# Fraud monitoring

## Requires
microsoft-365 (one SharePoint folder), uv. Scripts run with
`uv run`, which installs their pinned dependencies.

## Steps
Set `H=~/.claude/skills/microsoft-365/scripts/msgraph.py`,
`S=~/.claude/skills/fraud-monitoring` and `DAY=<today, YYYY-MM-DD>`.

1. Find the inputs. `python3 $H search "Fraud monitoring"`, then list
   `in/$DAY` with `python3 $H get "/drives/<drive_id>/items/<folder_id>/children"`.
   Download `fraud_reports.xlsx`, `sales_volume.xlsx` and
   `watchlist.txt` into `in/` with `python3 $H download`, and the
   tracker workbook to `tracker.xlsx`. If any of the three inputs is
   missing, say which and stop. Write nothing.
2. Parse: `uv run $S/scripts/parse_inputs.py in inputs.json`
3. Score: `uv run $S/scripts/score.py inputs.json $S/assets/thresholds.json tracker.xlsx $DAY out`
4. Validate: `uv run $S/scripts/validate.py inputs.json out`.
   If it does not print OK, stop and quote its message. Write nothing.
5. Append: `python3 $H append <drive_id> <tracker_item_id> Daily "$(cat out/rows.json)"`.
   Append once, the whole file. Never edit or re-order rows.
6. Your last message is `out/summary.md` verbatim, then one sentence
   per line under "New this run" saying what stands out in that
   merchant's rows (reason codes, amounts, watchlist note).
   The grader reads your last message.

## Never
Edit anything in this skill, change a threshold, compute a number
yourself, or write to any file other than the Daily table.
```

Then add the scripts and the thresholds file. Each script declares its own dependencies in a [PEP 723](https://peps.python.org/pep-0723/) header, so `uv run` uses the same `openpyxl` on every run.

`scripts/parse_inputs.py` reads the three inputs into one JSON file and puts every row it can't read in `exceptions`, with its file and row number:

```python theme={null}
# /// script
# requires-python = ">=3.11"
# dependencies = ["openpyxl==3.1.5"]
# ///
"""Read one day's inputs into inputs.json. Rows that can't be read go to exceptions."""

import json
import sys
from decimal import Decimal, InvalidOperation
from pathlib import Path

from openpyxl import load_workbook

REPORTS = ("fraud_reports.xlsx", ["merchant_id", "txn_date", "amount", "reason_code"])
VOLUME = ("sales_volume.xlsx", ["merchant_id", "sales_count", "sales_amount"])


def sheet_rows(path, columns):
    ws = load_workbook(path, read_only=True, data_only=True).active
    it = ws.iter_rows(values_only=True)
    header = [str(c).strip().lower() if c is not None else "" for c in next(it)]
    missing = [c for c in columns if c not in header]
    if missing:
        sys.exit(f"{path.name}: missing columns {missing}")
    for n, row in enumerate(it, start=2):
        if any(v is not None for v in row):
            yield n, {c: row[header.index(c)] for c in columns}


def money(value):
    return Decimal(str(value)).quantize(Decimal("0.01"))


def main(day_dir, out):
    day = Path(day_dir)
    reports, volume, watchlist, exceptions, counts = [], {}, {}, [], {}

    name, cols = REPORTS
    for n, r in sheet_rows(day / name, cols):
        counts[name] = counts.get(name, 0) + 1
        try:
            if not r["merchant_id"]:
                raise ValueError("no merchant_id")
            reports.append({"merchant_id": str(r["merchant_id"]).strip(),
                            "amount": str(money(r["amount"])),
                            "reason_code": str(r["reason_code"]).strip()})
        except InvalidOperation:
            exceptions.append({"file": name, "row": n, "reason": "amount is not a number"})
        except (TypeError, ValueError) as e:
            exceptions.append({"file": name, "row": n, "reason": str(e)})

    name, cols = VOLUME
    for n, r in sheet_rows(day / name, cols):
        counts[name] = counts.get(name, 0) + 1
        try:
            volume[str(r["merchant_id"]).strip()] = {
                "sales_count": int(r["sales_count"]),
                "sales_amount": str(money(r["sales_amount"])),
            }
        except (InvalidOperation, TypeError, ValueError):
            exceptions.append({"file": name, "row": n, "reason": "bad sales figures"})

    # watchlist.txt: one merchant per line, "MID|reason"; blank lines and # comments skipped
    for n, line in enumerate((day / "watchlist.txt").read_text().splitlines(), start=1):
        line = line.strip()
        if not line or line.startswith("#"):
            continue
        counts["watchlist.txt"] = counts.get("watchlist.txt", 0) + 1
        mid, sep, reason = line.partition("|")
        if not sep or not mid.strip():
            exceptions.append({"file": "watchlist.txt", "row": n, "reason": "expected MID|reason"})
            continue
        watchlist[mid.strip()] = reason.strip()

    Path(out).write_text(json.dumps({"reports": reports, "volume": volume,
                                     "watchlist": watchlist, "exceptions": exceptions,
                                     "input_rows": counts}, indent=2))
    print(f"{len(reports)} reports, {len(volume)} merchants with volume, "
          f"{len(watchlist)} on watchlist, {len(exceptions)} exceptions")


if __name__ == "__main__":
    main(*sys.argv[1:3])
```

`scripts/score.py` aggregates reports per merchant, computes both ratios with `Decimal`, assigns the tier, compares it with the tracker's last tier for that merchant, and writes `rows.json` (sorted, most severe first) and `summary.md`:

```python theme={null}
# /// script
# requires-python = ">=3.11"
# dependencies = ["openpyxl==3.1.5"]
# ///
"""Score every merchant with fraud reports and write tracker rows plus a summary."""

import json
import sys
from decimal import Decimal
from pathlib import Path

from openpyxl import load_workbook

TIERS = ["breach", "watch", "no-volume", "ok"]  # sort order, most severe first


def tier(m, count_ratio, amount_ratio, t):
    """Compare the exact ratios: rounding first would push 0.89686% up to a 0.90% breach."""
    if m["sales_count"] == 0:
        return "no-volume"
    over = lambda level: (count_ratio >= Decimal(t[level]["count_ratio"])
                          or amount_ratio >= Decimal(t[level]["amount_ratio"]))
    floors = (m["fraud_count"] >= t["breach"]["min_fraud_count"]
              and Decimal(m["fraud_amount"]) >= Decimal(t["breach"]["min_fraud_amount"]))
    return "breach" if floors and over("breach") else "watch" if over("watch") else "ok"


def previous_tiers(tracker, day):
    """Each merchant's latest tier before ``day`` in the tracker's Daily sheet."""
    ws = load_workbook(tracker, read_only=True, data_only=True)["Daily"]
    it = ws.iter_rows(values_only=True)
    header = [str(c).strip().lower() for c in next(it)]
    tiers = {}
    for row in it:
        r = dict(zip(header, row))
        if r.get("date") and str(r["date"])[:10] < day:
            tiers[str(r["merchant_id"])] = r["tier"]
    return tiers


def main(inputs_path, thresholds_path, tracker_path, day, out_dir):
    data = json.loads(Path(inputs_path).read_text())
    t = json.loads(Path(thresholds_path).read_text())
    previous = previous_tiers(tracker_path, day)

    merchants = {}
    for r in data["reports"]:
        m = merchants.setdefault(r["merchant_id"], {"fraud_count": 0, "fraud_amount": Decimal("0")})
        m["fraud_count"] += 1
        m["fraud_amount"] += Decimal(r["amount"])

    rows = []
    for mid, m in merchants.items():
        v = data["volume"].get(mid, {"sales_count": 0, "sales_amount": "0.00"})
        m.update(sales_count=v["sales_count"], fraud_amount=str(m["fraud_amount"]))
        sales = Decimal(v["sales_amount"])
        count_ratio = Decimal(m["fraud_count"]) / v["sales_count"] if v["sales_count"] else Decimal(0)
        amount_ratio = Decimal(m["fraud_amount"]) / sales if sales else Decimal(0)
        m["tier"] = tier(m, count_ratio, amount_ratio, t)
        # rounded for the tracker only, after the tier is decided
        m["count_ratio"] = str(count_ratio.quantize(Decimal("0.0001")))
        m["amount_ratio"] = str(amount_ratio.quantize(Decimal("0.0001")))
        m["new"] = m["tier"] in ("breach", "watch") and previous.get(mid) != m["tier"]
        rows.append([day, mid, m["fraud_count"], m["fraud_amount"], m["sales_count"],
                     m["count_ratio"], m["amount_ratio"], m["tier"],
                     "yes" if mid in data["watchlist"] else "no", "yes" if m["new"] else "no"])
    rows.sort(key=lambda r: (TIERS.index(r[7]), r[1]))

    out = Path(out_dir)
    out.mkdir(parents=True, exist_ok=True)
    (out / "merchants.json").write_text(json.dumps(merchants, indent=2))
    (out / "rows.json").write_text(json.dumps(rows))
    by_tier = {k: sum(1 for r in rows if r[7] == k) for k in TIERS}
    lines = [f"# Fraud monitoring, {day}", "",
             " · ".join(f"{k}: {n}" for k, n in by_tier.items()), "",
             "## New this run"]
    lines += [f"- {r[1]}: {r[7]}, {r[2]} reports, ${r[3]}, count ratio {r[5]}, amount ratio {r[6]}"
              + (f" (watchlist: {data['watchlist'][r[1]]})" if r[8] == "yes" else "")
              for r in rows if r[9] == "yes"] or ["- none"]
    lines += ["", f"## Exceptions ({len(data['exceptions'])})"]
    lines += [f"- {e['file']} row {e['row']}: {e['reason']}" for e in data["exceptions"]] or ["- none"]
    (out / "summary.md").write_text("\n".join(lines) + "\n")
    print(f"{len(rows)} merchants scored: {by_tier}")


if __name__ == "__main__":
    main(*sys.argv[1:6])
```

`scripts/validate.py` reconciles the run before anything is written: every input row is either parsed or an exception, the amounts and counts in the rows add up to the parsed reports, and each merchant appears once:

```python theme={null}
# /// script
# requires-python = ">=3.11"
# ///
"""Reconcile the run before anything is written. Exit 1 with the first mismatch."""

import json
import sys
from decimal import Decimal
from pathlib import Path


def fail(msg):
    sys.exit(f"VALIDATION FAILED: {msg}")


def main(inputs_path, out_dir):
    data = json.loads(Path(inputs_path).read_text())
    out = Path(out_dir)
    merchants = json.loads((out / "merchants.json").read_text())
    rows = json.loads((out / "rows.json").read_text())

    bad = sum(1 for e in data["exceptions"] if e["file"] == "fraud_reports.xlsx")
    if data["input_rows"].get("fraud_reports.xlsx", 0) != len(data["reports"]) + bad:
        fail("fraud_reports.xlsx rows != parsed + exceptions")
    total_in = sum(Decimal(r["amount"]) for r in data["reports"])
    total_out = sum(Decimal(r[3]) for r in rows)
    if total_in != total_out:
        fail(f"fraud amount in {total_in} != amount in rows {total_out}")
    if sum(r[2] for r in rows) != len(data["reports"]):
        fail("report count in rows != parsed reports")
    if sorted(r[1] for r in rows) != sorted(merchants) or len(rows) != len(set(r[1] for r in rows)):
        fail("every merchant with reports must appear exactly once")
    print(f"OK: {len(data['reports'])} reports, ${total_in}, {len(rows)} merchants reconcile")


if __name__ == "__main__":
    main(*sys.argv[1:3])
```

`assets/thresholds.json`:

```json theme={null}
{
  "watch": { "count_ratio": "0.0065", "amount_ratio": "0.0065" },
  "breach": {
    "count_ratio": "0.0090",
    "amount_ratio": "0.0090",
    "min_fraud_count": 10,
    "min_fraud_amount": "5000.00"
  }
}
```

Set **Requires integrations** to `microsoft-365` and **Required tooling** to `uv: latest`. Then attach the skill to the **Fraud Monitoring** template.

```text theme={null}
cli: runtm-api skills create --name fraud-monitoring --display-name "Fraud monitoring" --description "Score the day's fraud report against merchant sales volume and append the results to the tracker" --content "$(jq -n --rawfile md ./SKILL.md '{entry_md:"SKILL.md",files:[{path:"SKILL.md",mode:"text",inline:$md}],requires:{integrations:["microsoft-365"],tooling:{mise:{uv:"latest"}}}}')"
cli: runtm-api skills upload-file <skill_id> --file ./scripts/parse_inputs.py --path scripts/parse_inputs.py --mode text
cli: runtm-api skills upload-file <skill_id> --file ./scripts/score.py --path scripts/score.py --mode text
cli: runtm-api skills upload-file <skill_id> --file ./scripts/validate.py --path scripts/validate.py --mode text
cli: runtm-api skills upload-file <skill_id> --file ./assets/thresholds.json --path assets/thresholds.json --mode text
cli: runtm-api skills attach <skill_id> --template <template_id>
cli-verify: runtm-api skills get <skill_id> | jq '[.directive.content.files[].path]'
```

**2. Build the template once**

On **Templates**, open **Fraud Monitoring** and click **Build** on the **Build** tab. Wait for `ready`. The build installs `uv`; the first run downloads `openpyxl` once.

```text theme={null}
cli: runtm-api template build <template_id>
cli-verify: runtm-api template get <template_id> | jq '{build_status, skills: [.skills[].name], stale: .attachments_changed_since_build}'
```

**3. Create the schedule, disabled**

On **Agents**, open the **Scheduled** tab and click **New scheduled agent**. Name it `Fraud monitoring`. For the prompt, write:

> Run the fraud-monitoring skill for today's inputs. If an input is missing or a check fails, say which and write nothing.

Set run-as to **Agent** and pick **Monitor Agent**, so the agent-scoped Microsoft 365 connection applies and the run is graded. Set the schedule to weekdays at 13:00 UTC, after the processor's drop. Under **Post**, pick `#fraud-monitoring`. Create it, then flip the toggle off until step 5 proves it.

```text theme={null}
cli: runtm-api scheduled-agents create --name "Fraud monitoring" --cron "0 13 * * 1-5" --prompt "Run the fraud-monitoring skill for today's inputs. If an input is missing or a check fails, say which and write nothing." --template <template_id> --agent claude-code --agent-id <monitor_agent_id> --disabled --slack-integration <slack_integration_id> --slack-channel <channel_id>
cli-verify: runtm-api scheduled-agents get <scheduled_agent_id> | jq '{enabled, cron, next_run_at, slack_channel_id}'
```

## 5. Prove it works and iterate

Read [Prove it works and iterate](https://docs.runtm.com/build/launch-and-iterate.md) and [Skill evals and session evals](https://docs.runtm.com/build/skill-and-session-evals.md). Test it like software: many skill evals at the bottom (unit tests against fixed files), a few scheduled runs at the top (integration tests against SharePoint).

**1. Give the skill its unit tests**

Open the skill with **Edit** and build its eval suite in the editor session. Each case is a folder of input files and the exact rows they must produce, so a ratio that drifts by one digit fails:

```text theme={null}
evals/
  evals.json
  files/
    breach-crossing/    fraud_reports.xlsx  sales_volume.xlsx  watchlist.txt  tracker.xlsx
    just-below-breach/  ...a count ratio of 0.8969%, a hair under the 0.90% line
    bad-rows/           ...a non-numeric amount and a malformed watchlist line
    missing-volume/     fraud_reports.xlsx  watchlist.txt   (no sales_volume.xlsx)
  expected/
    breach-crossing/rows.json
    bad-rows/rows.json
  checks/
    same_json.py
```

Take the inputs from days an analyst already checked, or ask the agent to build them: "Make a day where one merchant crosses from watch to breach, one is on the watchlist, and one has no sales; save the expected rows." One case per rule: each tier boundary and a value just under it (rounding before comparing would tip it over), the minimum-count floor, a bad row, a missing file, a merchant with no previous tier. `same_json.py` is the comparison script from [Fixtures and expected outcomes](https://docs.runtm.com/build/skill-and-session-evals.md#fixtures-and-expected-outcomes). A case in `evals.json`:

```json theme={null}
{
  "id": 1,
  "prompt": "Run the fraud-monitoring skill on the files in evals/files/breach-crossing for 2026-11-18, without appending to the tracker.",
  "expected_output": "validate.py prints OK and out/rows.json equals the expected rows",
  "files": ["evals/files/breach-crossing/fraud_reports.xlsx", "evals/files/breach-crossing/sales_volume.xlsx", "evals/files/breach-crossing/watchlist.txt", "evals/files/breach-crossing/tracker.xlsx"],
  "expectations": [
    "validate.py printed OK",
    "python3 evals/checks/same_json.py evals/expected/breach-crossing/rows.json out/rows.json prints MATCH",
    "Every number in the reply appears in out/rows.json"
  ]
}
```

Click **Run evals**. The suite needs no Microsoft 365 connection and runs in minutes, so run it on every change to a script or a threshold, and publish only when it passes. The fixtures are spreadsheets, which Publish would save as text: after publishing, add each one with `runtm-api skills upload-file <skill_id> --file <path> --path <same path> --mode binary`.

**2. Run three known days**

For each day, change the schedule's prompt to name it ("Run the fraud-monitoring skill for 2026-11-18."), click **Run now**, and compare the appended rows with the checked ones. They must match exactly, every ratio and tier. Then run one day with `sales_volume.xlsx` removed: the run must stop, name the file and append nothing.

```text theme={null}
cli: runtm-api scheduled-agents update <scheduled_agent_id> --prompt "Run the fraud-monitoring skill for 2026-11-18."
cli: runtm-api scheduled-agents run-now <scheduled_agent_id>
cli-verify: runtm-api session grade <session_id>
```

**3. Fix the script, not the prompt**

A mismatch is a script bug or a threshold question, never an instruction to "be more careful". Turn the failing day into a fixture with its correct rows, add the case, fix the script until the suite passes, publish, and rerun the day. The case now guards every later edit.

**4. Restore the prompt**

Put the prompt back to today's inputs before enabling.

```text theme={null}
cli: runtm-api scheduled-agents update <scheduled_agent_id> --prompt "Run the fraud-monitoring skill for today's inputs. If an input is missing or a check fails, say which and write nothing."
cli-verify: runtm-api agents scorecard --days 7
```

## 6. Add guardrails and approvals

Read [Add guardrails and approvals](https://docs.runtm.com/build/guardrails-and-approvals.md). The proven runs used a handful of commands; allow those and deny the rest of what the helper can do.

**1. Command rules**

On the template's **Guardrails** tab, add allow rules for `uv run */skills/fraud-monitoring/scripts/*` and for the helper's `search`, `get`, `download` and `append`, and deny rules for its `write`, `patch`, `post`, `send`, `reply` and `chat-send`. Set the default policy to `ask`.

```text theme={null}
cli: runtm-api guardrails rules create --template <template_id> --name allow-scripts --kind allow --pattern "uv run *skills/fraud-monitoring/scripts/*" --purpose "The bundled scripts only"
cli: runtm-api guardrails rules create --template <template_id> --name allow-graph-reads --kind allow --pattern "python3 *msgraph.py search*" --purpose "Find the input folder"
cli: runtm-api guardrails rules create --template <template_id> --name allow-graph-list --kind allow --pattern "python3 *msgraph.py get*" --purpose "List the day's folder"
cli: runtm-api guardrails rules create --template <template_id> --name allow-graph-download --kind allow --pattern "python3 *msgraph.py download*" --purpose "Download inputs and the tracker"
cli: runtm-api guardrails rules create --template <template_id> --name allow-tracker-append --kind allow --pattern "python3 *msgraph.py append*" --purpose "Append the validated rows"
cli: runtm-api guardrails rules create --template <template_id> --name deny-graph-write --kind deny --pattern "python3 *msgraph.py write*" --purpose "No cell overwrites"
cli: runtm-api guardrails rules create --template <template_id> --name deny-graph-send --kind deny --pattern "python3 *msgraph.py send*" --purpose "No mail from the agent"
cli: runtm-api guardrails rules create --template <template_id> --name deny-graph-patch --kind deny --pattern "python3 *msgraph.py patch*" --purpose "No raw Graph edits"
```

**2. Network rules**

Add host rules for `graph.microsoft.com` and `login.microsoftonline.com` (Microsoft 365), `pypi.org` and `files.pythonhosted.org` (the pinned `openpyxl`), and `app.runtm.com` and `docs.runtm.com`.

```text theme={null}
cli: runtm-api guardrails network create --template <template_id> --name graph --kind host --value graph.microsoft.com --purpose "SharePoint files and the tracker"
cli: runtm-api guardrails network create --template <template_id> --name microsoft-login --kind host --value login.microsoftonline.com --purpose "Microsoft token refresh"
cli: runtm-api guardrails network create --template <template_id> --name pypi --kind host --value pypi.org --purpose "Script dependencies"
cli: runtm-api guardrails network create --template <template_id> --name pypi-files --kind host --value files.pythonhosted.org --purpose "Script dependencies"
cli: runtm-api guardrails network create --template <template_id> --name runtm-app --kind host --value app.runtm.com --purpose "runtm CLI"
cli: runtm-api guardrails network create --template <template_id> --name runtm-docs --kind host --value docs.runtm.com --purpose "Agent reads the docs"
cli-verify: runtm-api template guardrails resolve <template_id>
```

**3. Enable the schedule**

Run one known day again with **Run now** to confirm the rules allow everything the job needs, then flip the schedule on.

```text theme={null}
cli: runtm-api scheduled-agents run-now <scheduled_agent_id>
cli: runtm-api scheduled-agents update <scheduled_agent_id> --enabled
cli-verify: runtm-api scheduled-agents get <scheduled_agent_id> | jq '{enabled, next_run_at, last_run_at, last_session_id}'
```

## What stays human

* **Every action on a merchant.** Outreach, holds, limit changes and closures are decided by an analyst reading the tracker. The agent's connection can only reach one folder, and its rules deny sending.
* **The thresholds.** `assets/thresholds.json` changes through a skill edit, reviewed and tested against the eval suite, never during a run.
* **A failed check.** When `validate.py` fails, a person looks at the inputs; the agent never retries with a workaround.

## Gotchas

* **The model doing arithmetic.** If a summary ever shows a ratio that isn't in `rows.json`, the agent computed it. Tighten the instruction to copy `summary.md` verbatim and grade `daily-run` on the numbers.
* **Floats.** Ratios and money are `Decimal` and quantized; a float version of the same script gives different last digits on some inputs and breaks the exact comparison in step 5.
* **Rounding before comparing.** Tiers compare the exact ratios and only the tracker gets the rounded ones. Rounding first turns 0.89686% into a 0.90% breach, and the totals still reconcile, so only a just-below-boundary fixture catches it.
* **Unpinned dependencies.** Without the PEP 723 header, `openpyxl` floats to whatever is newest. Pin it, and bump the pin through a skill edit.
* **A header renamed upstream.** `parse_inputs.py` exits naming the missing column instead of guessing. The run stops with nothing written, which is the point.
* **Appending twice.** The append is one call with the whole `rows.json`. A retried run on the same day appends again; check the tracker for the date before appending if your schedule retries.
* **Network rules without PyPI.** The first run after a build can't fetch `openpyxl` and every script fails. Add `pypi.org` and `files.pythonhosted.org`, or install the dependency in the template.

> [card] [Fraud and risk review agent](https://docs.runtm.com/guides/payments/fraud-risk-agent.md)
>
> A scheduled agent that assembles a review packet for each Radar alert and leaves every block to a human.

> [card] [Code or prompt](https://docs.runtm.com/build/how-it-works/code-or-prompt.md)
>
> When a step should be a script instead of an instruction.

> [card] [Build an agent](https://docs.runtm.com/build/overview.md)
>
> The six steps this example follows.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.