# The decision language

The language a decision is written in, what it receives, every built-in, what is refused, and worked examples.

A decision is written in Starlark, a small language that reads like Python. A decision must define one function, `decide(ctx)`. It receives one value, `ctx`, and must return `show(...)`.

A decision is pure. It reads only what `ctx` holds. It has no clock, no files, no network and no random numbers. The same input always gives the same answer, which is why a past decision can be [replayed](https://withmestra.com/docs/topos/decision-live/#replay-a-logged-decision).

## What a decision receives

`ctx` holds everything a decision can see. Text values are always text. A fact that isn't known is `None`.

| Name                                     | What it is                                                                                                                                                                                          |
| ---------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `ctx.time`                               | The screen's local time as text, `"15:04"`.                                                                                                                                                         |
| `ctx.day`                                | The screen's local day, `"mon"` to `"sun"`.                                                                                                                                                         |
| `ctx.date`                               | The screen's local date, `"2026-11-14"`.                                                                                                                                                            |
| `ctx.screen.id`                          | The screen's id.                                                                                                                                                                                    |
| `ctx.screen.tags`                        | The screen's tags, as one comma-separated text.                                                                                                                                                     |
| `ctx.screen.city`, `.state`, `.postcode` | Where the screen is.                                                                                                                                                                                |
| `ctx.screen.size`                        | The screen's size as `"1920x1080"`.                                                                                                                                                                 |
| `ctx.screen.lat`, `.lon`                 | Its position, as text.                                                                                                                                                                              |
| `ctx.signals`                            | A dictionary of text values from your data feeds, by field name. Use `ctx.signals.get("temp")`, which is `None` when the field is missing. Only the feed fields the campaign's table uses are here. |
| `ctx.place`                              | The screen's place in your model, or `None`. An item with `.id`, `.type`, `.name` and `.attrs`.                                                                                                     |
| `ctx.objects("type")`                    | A list of the items of that type that belong to the screen's place. Empty when there are none.                                                                                                      |
| `ctx.item("type", attr = value, ...)`    | The one item of that type whose attributes match every pair, or `None` if none or more than one matches. A value is a string, number, `True`, `False` or `None`.                                    |
| `ctx.rows`                               | Every variant of the campaign's table. Each has `.id`, `.label`, `.active`, `.ready` and `.default`.                                                                                                |
| `ctx.default`                            | The id of the default variant, or `None`.                                                                                                                                                           |

The time is in the screen's own time zone. When you test with no screen, time, day and date are read in UTC.

An item (`ctx.place` and each of `ctx.objects(...)`) has:

- `.id`, `.type` and `.name`, as text.
- `.attrs`, a dictionary of its attributes. Use `.attrs.get("stock")` so a missing attribute is `None`, not an error.

Items come from [mappings](https://withmestra.com/docs/topos/mappings/). A screen sees only its place and the items linked to that place. A screen that has no place in your model has `ctx.place` of `None`, and `ctx.objects("anything")` is empty. Everything a decision reads for one screen can be at most 256 KiB. If it's more, the decision fails and the default shows. The test says "What this screen can see is too large for a decision to read."

## What it returns

Return `show(row, why)`.

- `row` is a variant: its id as text, or a variant from `ctx.rows`. The variant must be active and ready.
- `why` is optional text, up to 200 characters. It is kept in the log as the reason.

```python
return show("breakfast", "Weekday morning")
return show(ctx.default)
```

Returning anything else, such as a bare string, is the error "decide must return show(row)".

## Built-ins

These test a value against a cell the way the table's conditions do. Each returns `True` or `False`. A value that is missing, not text or a number, or a cell that isn't well formed gives `False`, never an error.

| Built-in                          | True when                                                                                                           | Example                                             |
| --------------------------------- | ------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------- |
| `in_window(value, "HH:MM-HH:MM")` | The time is in the window. A window can cross midnight, such as `"22:00-02:00"`. The start counts, the end doesn't. | `in_window(ctx.time, "06:00-11:00")`                |
| `in_days(value, "mon,tue,...")`   | The day is in the list.                                                                                             | `in_days(ctx.day, "sat,sun")`                       |
| `in_dates(value, "from..to")`     | The date is in the range. Either end can be left out.                                                               | `in_dates(ctx.date, "2027-12-01..2027-12-24")`      |
| `in_range(value, "low..high")`    | The number is in the range. Either end can be left out.                                                             | `in_range(ctx.signals.get("temp"), "28..")`         |
| `in_list(value, "a,b,c")`         | The value is one of the words, ignoring case.                                                                       | `in_list(ctx.signals.get("weather"), "rain,storm")` |
| `has_tag(value, "a,b")`           | The value and the list share a tag.                                                                                 | `has_tag(ctx.screen.tags, "food-court")`            |
| `money(minor, "AUD")`             | Not a test. Writes whole minor units as text. `money(2400, "AUD")` is `"$24.00"`.                                   |                                                     |

`money` writes `$` for AUD, NZD and USD. Any other currency is written after the amount, such as `24.00 EUR`. A negative amount starts with `-`.

`show` is the only way to make an answer.

You can also use the standard functions of the language, such as `len`, `range`, `sorted`, `reversed`, `enumerate`, `zip`, `min`, `max`, `abs`, `any`, `all`, `str`, `int`, `float`, `bool`, `list`, `dict` and `tuple`. A `for` loop, `if`, list comprehensions and your own helper functions inside the file all work.

## What is refused

| Not allowed                                                                    | What happens                                                                                 |
| ------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------- |
| Importing (`load`)                                                             | The decision doesn't compile.                                                                |
| Reading the time, files, the network or random numbers                         | There are none. `time`, `os` and `open` aren't defined.                                      |
| `while` loops                                                                  | Refused. Use `for` over a list or `range`.                                                   |
| Sets (`set(...)`)                                                              | Refused. Use a list or a dictionary.                                                         |
| Code at the top level other than definitions, such as a `for` loop or `x += 1` | Refused. Put it inside a function.                                                           |
| Changing a top-level name again after it is set                                | Refused.                                                                                     |
| Recursion (a function that calls itself)                                       | Stops with an error when it runs.                                                            |
| No `decide` function, or one that doesn't take exactly one argument            | "define a function decide(ctx)" or "decide must be a function of one argument: decide(ctx)". |
| `print`                                                                        | Does nothing.                                                                                |
| A source over 64 KiB                                                           | "the function is too long".                                                                  |
| More than 100,000 steps, or more than 16 MiB of memory                         | The run stops and the default shows.                                                         |

A mistake at runtime, such as `int("abc")`, shows as "line N: the function raised an error" in the log. It never quotes your data. In your own test, the real message shows as well.

Top-level names are fixed once the file loads. Constants at the top level, such as `LIMIT = 30`, are fine as long as you don't change them.

## Examples

Always show the default:

```python
def decide(ctx):
    return show(ctx.default, "Default")
```

Hot weather. `in_range` returns `False` when the feed field is missing, so it is safe. `float("abc")` would stop the decision.

```python
def decide(ctx):
    if in_range(ctx.signals.get("temp"), "30.."):
        return show("hot", "30 degrees or more")
    return show(ctx.default, "Default")
```

Weekday mornings:

```python
def decide(ctx):
    if in_window(ctx.time, "06:00-11:00") and in_days(ctx.day, "mon,tue,wed,thu,fri"):
        return show("breakfast", "Weekday morning")
    return show(ctx.default)
```

An item at the screen's place. This one reads a Point of sale menu item and switches to a "sold-out" variant when it isn't available:

```python
def decide(ctx):
    latte = ctx.item("menu_item", item_id = "latte")
    if latte != None and latte.attrs.get("available") == False:
        return show("sold-out", latte.name + " is not available")
    return show(ctx.default)
```

Loop over the place's items, and name the place in the reason:

```python
def decide(ctx):
    for o in ctx.objects("menu_item"):
        if o.attrs.get("stock") == 0:
            where = ctx.place.name if ctx.place else "this place"
            return show("sold-out", o.name + " is out of stock at " + where)
    return show(ctx.default)
```

Write a price in the reason:

```python
def decide(ctx):
    p = ctx.item("menu_item", item_id = "latte")
    if p == None:
        return show(ctx.default)
    return show(ctx.default, "Latte " + money(p.attrs["price_minor"], p.attrs["currency"]))
```

Choose a variant from `ctx.rows`, only if it is active and ready:

```python
def decide(ctx):
    for r in ctx.rows:
        if r.id == "hot" and r.active and r.ready:
            return show(r)
    return show(ctx.default)
```
