> This page is for Remediation Orchestrator.

> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.nvidia.com/remediation-orchestrator/llms.txt.

# Writing Scripts

> How to write Remediation Orchestrator scripts in Starlark

This guide covers script development: calling modules, registering
entrypoints, scheduling, sharing code, managing inventory, and enabling
modules for real remediation. It assumes you have already uploaded and run a
first script — if not, start with [Your First Script](/remediation-orchestrator/guides/first-scripts-checklist).

A Remediation Orchestrator script is a small Starlark file that wires external services into a
deterministic workflow. Remediation Orchestrator exposes each registered function as an HTTP
endpoint, handles retries and auth, and records every execution in Temporal.

## Calling modules

Real scripts call modules — pre-built Go packages exposed to Starlark that
handle auth, retries, and external service integration:

```starlark
def check_node(node_id):
    """Run a health check on a node and return the output.

    Args:
        node_id: string, the node serial number to check

    Returns:
        dict: result containing exit code and output
    """
    result = command.execute(node_id, "nvidia-smi", timeout="2m")
    return {
        "exit_code": result.exit_code,
        "output": result.stdout,
    }

register_workflow(check_node)
```

`command.execute` is a module call. The `command` module handles SSH, retries,
and timeout enforcement — the script only contains business logic.

## Enabling modules

Remediation Orchestrator boots with zero modules enabled. The baseline deployment runs scripts
that perform pure logic, but real breakfix requires modules: `command` for SSH
execution, `noderegistry` for inventory, and `bcm`, `teleport`, or `slurm` as
the environment requires. Each module is enabled at deploy time by the Remediation Orchestrator
operator; add only the modules a given script actually calls. Ask your operator to enable a
module rather than redeploying yourself; with Helm, operators set module configuration as
described in [Helm configuration](/remediation-orchestrator/deployment/helm/reference/application-chart#configuration-and-scripts).

The steps in [Your First Script](/remediation-orchestrator/guides/first-scripts-checklist) work with no
modules. Real breakfix does not.

## Docstring format

The docstring is required whenever a function takes arguments or returns a
value. Remediation Orchestrator rejects functions that are missing required sections.

```starlark
def my_workflow(node_id, retries):
    """One-line description.

    Args:
        node_id: string, the node to operate on
        retries: int, number of times to retry

    Returns:
        dict: result summary
    """
    ...
```

Supported return types: `dict`, `list`, `tuple`, `int`, `int64`, `float`, `float64`, `bool`, `string`, `any`.

## Registering entrypoints

`register_workflow` exposes a function as an HTTP-triggerable workflow. All
optional arguments are functions that receive the same parameters as the main
function.

```starlark
register_workflow(
    myFunction,
    workflow_id=myIDFunc,      # generates the execution ID; used for deduplication
    on_failure=myFailureFunc,  # called if the workflow fails; also receives
                               # an optional `errors: list[string]` argument
    on_cancel=myCancelFunc,    # called if the workflow is canceled
    query=myQueryFunc,         # called to return status while the workflow runs
    max_concurrency=5,         # max concurrent executions; 0 = unlimited (best-effort)
)
```

## Choose a trigger

Decide how workflows start. The three mechanisms compose:

- **On demand / API:** `POST /api/v1/script/{name}/{function}`. Good for
  operators, CI, and manual remediation.
- **Scheduled:** declare a schedule with `temporal.schedule()` in your script;
  Remediation Orchestrator reconciles it on startup. See [Cron schedules](#cron-schedules).
- **External events:** drive workflows from outside signals (alerts, webhooks).
  See [Receiving External Events](/remediation-orchestrator/guides/receiving-external-events).

## Cron schedules

To run a workflow on a schedule instead of (or in addition to) HTTP trigger:

```starlark
temporal.schedule(
    "my-schedule-name",        # unique name for the schedule
    myFunction,
    crons=["0 * * * *"],       # one or more cron expressions
    args={},                   # optional arguments passed to myFunction
    skip_indexing=False,       # if True, scheduled runs are not indexed
)
```

## Getting results back

When you trigger a workflow via `POST`, Remediation Orchestrator responds immediately with a
workflow ID and does the work asynchronously:

```json
{ "workflow_id": "http/a1b2c3d4-..." }
```

Poll for the result using that ID:

```bash
# Status only
curl "$MAESTRO_URL/api/v1/script/greet.star/workflow/status?workflow_id=$WF_ID" \
  -H "Authorization: Bearer $TOKEN"

# Return value (available after the workflow completes)
curl "$MAESTRO_URL/api/v1/script/greet.star/greet/workflow/query?workflow_id=$WF_ID" \
  -H "Authorization: Bearer $TOKEN"
```

The query response includes `queryResult`, `workflow_id`, `run_id`, and `status`.

You can also watch the execution in the Temporal UI. Open it at port 8080 on a
local instance (or wherever your deployment exposes it), find the workflow by
ID, and you'll see a step-by-step timeline of every activity — inputs, outputs,
retries, and errors — as the workflow runs.

To expose state before the workflow completes, register an explicit query function:

```starlark
def current_status():
    return "running phase 2"

register_workflow(myFunction, query=current_status)
```

The query function can be called at any point during execution.

## Sharing code with `load()`

Split reusable logic into a separate `.star` file and import it:

```starlark
load("shared_utils.star", "classify_node", "RETRY_LIMIT")

def my_workflow(node_id):
    """Run workflow using shared utilities.

    Args:
        node_id: string, the node to classify

    Returns:
        string: node classification
    """
    return classify_node(node_id, RETRY_LIMIT)

register_workflow(my_workflow)
```

Rules:
- `load()` must appear at the top level, not inside functions.
- Script names are paths from the tenant's `scripts/` folder, such as `plans/network/healthcheck.star`. They end in `.star` and contain exactly one period.
- Private symbols (names starting with `_`) cannot be loaded.
- Circular dependencies are rejected.
- Inside a running workflow, all dependencies are pre-resolved at start — no dynamic fetches are allowed.

When uploading scripts that depend on each other, use the batch endpoint so the
server can resolve and validate the dependency graph in one operation:

```bash
curl -X POST "$MAESTRO_URL/api/v1/script/batch" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"scripts":[{"name":"my-check.star","content":"<starlark source>"}]}'
```

The server parses `load()` dependencies, validates every script, topologically
sorts in-batch dependencies, and persists them in order. If any script fails
validation the whole batch is rejected; dependencies not in the batch must
already exist in storage. Pushing scripts from CI uses this same endpoint.

## Build node inventory

Breakfix scripts act on nodes identified by serial number. Inventory is not
automatic — it comes from the `noderegistry` module, which must be enabled at
Remediation Orchestrator deploy time and pointed at your environment's node source.

Nodes are populated into noderegistry by running a populator script that reads
and writes entries through the `noderegistry` module. Run it once to seed
initial inventory, then on a schedule to keep it current. The populator is a normal
Starlark script: it calls your inventory system, builds a list of node dicts,
and registers itself with `scriptnoderegistrypopulator`.

Here is a starting template:

```starlark
# script_noderegistry_populator.star
#
# Populate the node registry from your environment's source of truth.
# Upload this script to Remediation Orchestrator and run it once to seed inventory,
# then schedule it to keep inventory current.
#
# Required modules: noderegistry, scriptnoderegistrypopulator

CLUSTER_ID = "your-cluster-id"  # e.g. "us-east-gpu-cluster-1"

def populate_noderegistry():
    """Return the list of nodes to register.

    Each node is a dict with at minimum:
      datacenter_node_id  str   Stable unique ID for this node (serial number or equivalent)
      cluster_id          str   The cluster this node belongs to
      hostname            str   The node's hostname
      ip                  str   Management IP address; set to "" if not applicable
      identifiers         dict  Map of system name to system-specific identifier dict
                                e.g. {"teleport": {"system_node_id": node.name}}, where
                                node comes from teleport.get_nodes(); Monitor console
                                links need the Teleport node name

    Returning an empty list clears inventory for this cluster.
    """

    # Replace this with a call to your source of truth.
    # Common patterns:
    #   - A BCM module for cluster-manager-managed nodes
    #   - An HTTP call to your inventory API
    #   - A static list for small or fixed-size clusters

    nodes = []

    # Example — build a node entry manually:
    # nodes.append({
    #     "datacenter_node_id": "SN1234567890",
    #     "cluster_id": CLUSTER_ID,
    #     "hostname": "node-001.example.com",
    #     "ip": "192.0.2.10",
    #     "identifiers": {},
    # })

    return nodes

wf_pnr = register_workflow(populate_noderegistry)
scriptnoderegistrypopulator.set_noderegistry_populator(
    "populate_noderegistry", wf_pnr, data_source = "custom",
)
```

## Best practices

- Put only business logic in scripts. Let modules handle retries, auth, timeouts, and error recovery.
- One script, one purpose. Avoid general-purpose scripts that try to handle many unrelated cases.
- Only reference modules your script actually calls — module config blocks with missing env vars prevent Remediation Orchestrator from starting.
- Scripts live in Remediation Orchestrator's database after upload. Deleting the source file does not remove the script. Use `DELETE /api/v1/script/{name}` to remove it.
- Circuit breakers limit how many times a workflow can run in a given window. They are configured through the Remediation Orchestrator UI on the Workflows page, not in script code.

## Repairing a broken workflow

When a deployed workflow breaks, the owning team works through the steps below in order.

This section covers breaks caused by the workflow script itself. If the root cause is a Remediation Orchestrator module or service bug, fix and redeploy the service through [Contributing](https://github.com/dsx-ai-factory/remediation-orchestrator/blob/1785e695a8bff76c910115b3c96398a5a59a7183/docs/docs/contributing/index.md) instead. If it is platform health - PostgreSQL, Temporal, the API, or the script indexer - see [Platform SLOs](/remediation-orchestrator/ops/platform-slos).

- **Diagnose**: find the failing run in the Remediation Orchestrator UI (Automation > Workflow Runs, or the node's monitor page) to see its status, history events, and logs, then open the Temporal UI (proxied at `/temporal/`) to walk the activity timeline - inputs, outputs, retries, and the error - and pinpoint where it broke.
- **Owner**: resolve the owning team from the script's path in `CODEOWNERS`, or from the "created by" uploader on the script in the Remediation Orchestrator UI. That team owns the fix.
- **Stop the bleeding**: disable the workflow or trip its circuit breaker from the Workflows page in the Remediation Orchestrator UI so no new runs start on the broken version, and cancel any running instance that is actively causing harm.
- **Roll back if a proper fix will take time**: to restore service now instead of fixing forward, revert to the last-known-good version - re-upload the previous script through the same batch flow (this adds a new version, it does not delete the bad one) or shift traffic back with blue/green. Like a fix, this only affects new runs, so in-flight runs still need the restart below.
- **Fix tracking**: track the break and its fix so the repair is traceable from report to deploy - typically a Jira issue linked to the `fix(...)` merge request.
- **Deploy the fix**: review the change in your script repository, then deploy the updated tenant bundle through your delivery pipeline. See [Deploying Scripts from CI](/remediation-orchestrator/guides/deploying-scripts) for an example pipeline.
- **Repair in-flight workflows**: a running workflow keeps the script version it started with, so a deployed fix does not reach it automatically. To move an existing run onto the fix, restart it - this spawns a fresh instance on the latest script. A restart replays the script from the top against the current node, ticket, and reservation state and does not reconcile whatever changed while the original run was live, so first check it will actually make progress rather than re-enter a stale wait or bail out. If a clean restart is not safe, either repair that external state (tickets, tags, reservations) by hand first, or let the stuck run drain and rely on new runs already using the fixed script.

<a id="appendix-can-maestro-run-without-modules"></a>

## Appendix: Can Remediation Orchestrator run without modules?

Yes. Remediation Orchestrator boots with zero `[modules.*]` blocks — the baseline deployment does
exactly that. The script runtime always provides core builtins (`param`,
`result`/`ok`/`err`, `struct`, `print`, `load()`), so a script that performs
pure logic runs with no modules.

The limits of a module-less deployment:

- No infrastructure access — no SSH, BCM, Teleport, or Slurm.
- No node inventory — inventory requires the `noderegistry` module.

So a Remediation Orchestrator deployment without modules is useful for smoke tests and pure-compute helpers, not
for remediation. Enable modules as scripts need them.