﻿<!-- SPDX-FileCopyrightText: PoppyCake, s.r.o. -->
<!-- SPDX-License-Identifier: GPL-3.0-or-later -->

# RunWisp agent reference

Dense reference for agents authoring/operating RunWisp. Human-readable prose lives at https://docs.runwisp.com (each page also at `<url>.md`). This file is the schema/CLI/REST surface only.

Notation in schema blocks: `key: type =default — note`. `=default` omitted means no default (unset). `dur` = duration string (`300ms`,`5s`,`10m`,`1h`,`2d`,`1w` — every duration field accepts day/week suffixes). `size` = byte size (`100mb`,`2gb`). `req` = required.

## Model

- `runwisp.toml` is the ONLY source of task definitions. REST/UI/TUI can read + trigger/stop/restart runs and pause/resume a cron schedule, never create or edit definitions.
- Config reload is explicit: `runwisp reload` / `SIGHUP` / `POST /api/daemon/reload` re-read the whole TOML and reconcile the live task set (add/change/remove tasks, services, `[defaults]`) and apply daemon-wide settings live (`[notify]`, `[notifiers.*]`, `[[route]]`, `[storage]`, and `[daemon]` including [`timezone`](/configuration/daemon/#timezone)). Validate-first/atomic: a parse/validation failure, or a change to a restart-only setting (`[daemon]` `tls`, `tls_cert`, `tls_key`, `metrics_enabled`, `metrics_listen`, `allow_station_dispatch`, `allow_station_upgrade`; bind host/port are CLI flags), is rejected and leaves the running daemon untouched. A timezone change re-bases every schedule and health check that has no timezone of its own, from now on (no catch-up); with `timezone` unset the daemon keeps the host zone it booted with until restart. Reload is NOT a restart: added tasks get no [`run_on_start`](/configuration/tasks/#run_on_start)/catch-up, in-flight runs finish under their old definition, and a running service restarts only for a change to its command, shell, working_dir, user, umask, env/secrets, env_base, timeout, graceful_stop, stop_signal, log_max_size, log_on_full, failures, health_check or instances (any other edit applies live). The daemon never auto-watches the file. Restart-only settings (and re-firing [`run_on_start`](/configuration/tasks/#run_on_start)/catch-up) need `runwisp restart`.
- Two unit kinds: `[tasks.<name>]` run-to-exit (cron or manual); `[services.<name>]` long-running, `restart` defaults to `always`. Names must be unique across both tables. `name` validated by RunWisp's task-name rules.
- `run =` is shell, executed from disk only — never from an HTTP/WS body.
- Inheritance: `[defaults]` → each task/service → per-key override. [`env`](/configuration/tasks/#env) merges (task wins); `[compose.<alias>.<svc>]` overrides per imported service.
- IDs are ULIDs. Logs are per-task files on disk; SQLite holds run metadata only.

## runwisp.toml

Machine-readable JSON Schema (draft 2020-12): `runwisp schema` (offline) or https://docs.runwisp.com/config.schema.json. Scaffolded/imported configs carry a `#:schema` directive so editors validate them. After editing, `runwisp validate --json` reports errors with structured `key`/`line`/`column`.

### [storage] (daemon-wide log disk safeguards)

```
max_size:       size =0(no cap)   — hard cap on total log bytes across all tasks
min_free_space: size =0(no check) — stop accepting log lines when partition free < this
```

### [daemon]

```
name:                 string      — display label shown instead of the fingerprint (TUI, Web UI, tab title, notification footers); ${HOSTNAME} falls back to os hostname
allow_station_dispatch: bool =false — accept peer-dispatched ad-hoc shell/container/compose runs (opt-in; one-shot, never edits TOML; HTTP & existing-task triggers always allowed)
allow_station_upgrade: bool =false — let the Station upgrade the daemon to a release (from GitHub releases, checksum-verified) and restart it; only for self-replaced release binaries under systemd/launchd; restart-only (since 1.11)
shutdown_timeout:     dur  =10s   — SIGTERM→SIGKILL drain budget for in-flight runs on shutdown
timezone:             IANA string =host system zone — TZ for cron eval when a task pins none
external_url:         string =last signed-in Web UI address — public Web UI base for notification deep-links; absolute http(s) w/ host; unset = detected from the latest browser password sign-in to the Web UI (persisted; `--url` clients and TUI-opened tabs don't count; never with RUNWISP_AUTH=off)
check_updates:        bool =true  — poll concierge.runwisp.com for a newer release; shows an indicator, never auto-updates; also gates the Web UI feedback prompt; skipped when env CI is set; false = fully offline
heartbeat_url:        string       — dead man's switch (e.g. healthchecks.io ping URL); GET at start + every 60s, 10s timeout, non-2xx = failed ping; absolute http(s) w/ host; secret: never logged (host only, failure/recovery logged once) and not in the API; reloadable; unset = off; since 1.8
log_output:           bool =false — print each run output line to the daemon stdout as `task | line` (stderr lines to stderr; JSON under --log-format=json); RUNWISP_LOG_OUTPUT overrides; headless only (a TUI session ignores it); bounded buffer drops overflow and reports the count; reloadable; the Docker image sets it true. since 1.7
metrics_enabled:      bool =false — master switch for /metrics
metrics_listen:       host:port   — dedicated metrics listener; setting it enables metrics on its own
trusted_proxies:      []string    — CIDR allowlist of reverse proxies whose X-Forwarded-For is trusted; catch-all
                                    (0.0.0.0/0, ::/0) rejected at load; RUNWISP_TRUSTED_PROXIES env overrides
api_tokens:           []string    - static REST API bearer tokens (`Authorization: Bearer <token>`) with full operator rights; each >= 32 chars, no whitespace, not starting `<digits>.` (session-token shape), unique across both lists; 20 wrong API tokens per client IP per minute -> 429 for that IP's API tokens (valid included) until the window slides, sessions unaffected; use ${VAR} substitution; secret, never logged; reloadable; since 1.9
viewer_api_tokens:    []string    - like api_tokens but read-only (state changes get 403); either list with RUNWISP_AUTH=off is refused at boot and reload; since 1.9
include:              []string    — glob(s) of extra TOML files merged at load; root config only, no nesting
include_cron:         []string    — glob(s) of REAL crontabs read as live task defs at every load/reload; root
                                    config only. Format is PATH-DERIVED, never flagged: /etc/crontab + **/cron.d/*
                                    = system format (6th field = user, job runs as them);
                                    /var/spool/cron/crontabs/<u>, /var/spool/cron/<u>, /etc/crontabs/<u> (Alpine)
                                    = per-user spool, jobs run
                                    as <u> taken from the FILENAME (requires a root daemon unless <u> IS the
                                    daemon's account; the file must also be owned by <u>, which is what makes the
                                    filename safe to trust); any other path = `crontab -l` dump, runs as the daemon.
                                    Glob hits are filtered to what crond itself reads, and the rule depends on
                                    the dir: in /etc/cron.d-style dirs, regular files named [A-Za-z0-9_-]+ only, so
                                    *.dpkg-old / *.disabled / README / subdirs are skipped and reported (a symlink
                                    is never followed: reported as skipped, and `takeover` blocks on it); in a spool
                                    dir, any plausible account name (letters, digits, - _ . $) EXCEPT tmp.* (the
                                    temp file `crontab -e` writes). A LITERAL path (no glob metachars) is never
                                    filtered.
                                    Hard errors: unreadable file, a file also matched by [daemon].include,
                                    world-writable file/dir, group-writable file (or non-sticky dir — a sticky
                                    group-writable dir is accepted, that's what a real cron spool is), owner
                                    neither root nor the daemon's euid nor the run-as account, unresolvable run-as
                                    account, spool file the daemon can't become. A job RunWisp can't reproduce is
                                    SKIPPED (rest of the file still runs) and reported via config.Warnings by
                                    file:line. Task name = a <=4-word comment on the line above, slugged, else
                                    the command's program (skipping wrappers, guards, `sleep`, and an echo/printf
                                    piped into another program); jobs from a non-root user's spool crontab or a
                                    cron.d file always get -<user|file basename> (unless the name contains it);
                                    root's crontab and /etc/crontab stay bare. Repeats in one file get -2, -3. A
                                    bare name another source already took gets -<crontab basename> (root's crontab
                                    reads first, then /etc/crontab). Renames are not config warnings. File-level
                                    notes are reported the same way: a non-empty MAILTO= (one line + docs link,
                                    suppressed once a sendmail/smtp notifier exists) and a non-absolute SHELL=.
                                    Cron-sourced tasks never count toward the same-second pile-up warning.
                                    Emitted per job for crond parity: env_base="clean", working_dir="~",
                                    catch_up=0 (crond never re-fires a missed tick; the missed row is still
                                    recorded), on_overlap="queue" (deliberately NOT crond's unbounded overlap).
                                    No ${...} expansion on cron text. A file named `anacrontab` is ANACRONTAB
                                    format: each `period delay job-id command` -> task named after job-id (dots
                                    -> '-'), cron at START_HOURS_RANGE start hour (default 7) + delay minutes
                                    (1=daily, 7=Mondays, @monthly=1st, @yearly=Jan 1, N=*/N dom), catch_up=1,
                                    RANDOM_DELAY ignored; /etc/anacrontab jobs run as root.
                                    Guard lines whose own `test -x|-e|-d|-f /abs ||` or `if [ … ] && …; then`
                                    test says they skip on THIS host (e.g. `test -x /usr/sbin/anacron || …`,
                                    `test -e /run/systemd/system || …`) are left out, not skipped-as-error:
                                    note kind noop-here, listed by import/takeover, no boot warning.
                                    Names: `run-parts DIR` -> basename of DIR with dots as '-' (cron-daily);
                                    `invoke-rc.d X` / `service X` -> X; `php[N.N] artisan|bin/console|spark
                                    SUB` -> SUB with ':' as '-' (payments-reconcile); shell keywords
                                    (if/then/!/…) skipped.
                                    Glob hits that are directories or dotfiles are dropped without a finding.
                                    Tasks report "source": "cron" + "source_file" in list/status --json;
                                    `runwisp promote` graduates them.
                                    HELD GATE: while a system cron daemon is live (systemctl is-active OR
                                    is-enabled on cron.service/crond.service/cronie.service, else a live pidfile
                                    naming a process that is actually alive), every task
                                    whose source_file is a path cron itself reads (/etc/crontab, **/cron.d/*,
                                    /var/spool/cron[/crontabs]/*, /etc/crontabs/*) is HELD (so are /etc/anacrontab tasks
                                    while anacron.timer/anacron.service is active or enabled; without systemd,
                                    while cron is live). HELD means: loaded, listed, schedule shown, but
                                    NOT registered with the scheduler — no cron firing, no jitter plan, no
                                    catch-up, no run_on_start/@reboot, no missed-run rows, no FirstSeenAt anchor.
                                    Reported as "held_by": "cron" on each task in list/status --json and
                                    /api/daemon. Manual triggers (run, API, TUI) STILL RUN a held task.
                                    The gate is self-healing: the daemon re-probes cron liveness every 60s (only
                                    when include_cron is set) and releases or re-takes holds on its own, so
                                    retiring cron needs NO reload. `runwisp reload`/SIGHUP re-probes too. Either
                                    way catch-up is re-anchored to the moment of release, so a hold window leaves
                                    no history and no missed-tick alerts.
                                    A crontab-format file OUTSIDE cron's own paths is NOT held (nothing to hand
                                    over) and keeps a fire-twice warning instead. `runwisp takeover` is the
                                    one-command way out.
```

### [defaults] (inherited by every task & service)

```
timeout:             dur          — per-attempt wall-clock cap; unset = no timeout (TASKS only)
jitter:              dur          — start-spread window inherited by cron tasks; off when unset (TASKS only)
warn_after:          dur          — one long_running notification when a run is still going this long after it started (queue wait excluded); the run keeps going; off when unset, "0s" turns off an inherited value; since 1.7 (TASKS only)
shell:               path =/bin/sh — interpreter for run scripts (absolute path); see FAIL-FAST
stop_signal:         enum =SIGTERM — stop-ladder signal: SIGTERM|SIGINT|SIGQUIT|SIGHUP|SIGKILL|SIGUSR1|SIGUSR2
failures:            []str        — outcomes classified as a failure (stats/UI/notify, and gates retry/restart); tokens are reason names (failed,timeout,crashed,log_overflow,start_failed,unhealthy,missed,stopped,daemon_stopped,skipped,queue_full,dst_skipped; not succeeded), exit codes ("42","1-23"; 1..255), or output patterns ("output:<RE2>", matched per stdout/stderr line after secret redaction; a match turns an exit-0 run into reason failed and writes a system log line). Default [failed,timeout,crashed,log_overflow,start_failed,unhealthy,missed]. is_failure = reason∈tokens OR (reason==failed AND (exit∈ranges OR output matched)). Bare list replaces; all-+/- tokens ("-missed","+stopped") adjust the inherited set (task adjusts [defaults], [defaults] adjusts built-in); mixing bare & +/- rejected ("-output:X" drops only an identical pattern). exit 0 = success unless an output pattern matched. retry_attempts/restart=on_failure fire only when reason∈{failed,timeout,crashed,log_overflow,start_failed,unhealthy} AND is_failure — narrowing failures narrows retry/restart; promoting stopped/missed never makes them retry
log_max_size:        size =100mb  — per-run log cap (effective task default)
log_on_full:         enum =drop_old — drop_new | drop_old | kill
keep_runs:           int          — row-count retention; 0..1000000 (0 = keep none; unset = no limit)
keep_for:            dur          — age retention; positive (unset = no limit; both unset = keep every run)
healthy_after:       dur  =60s    — service uptime that counts as healthy: resets the restart counter and clears the failed-start streak (SERVICES only); 0 = healthy immediately, kept literally if set
restart_attempts:       int  =10     — consecutive failed starts (any exit, exit 0 included, before healthy_after) before a service instance goes FATAL (SERVICES only); 0 = give up after the first failure, kept literally if set
restart_delay:       dur  =1s     — base delay before a service restart (SERVICES only)
restart_backoff:     enum =exponential — restart backoff curve (SERVICES only): constant|linear|exponential
catch_up:            int  =1       — default missed-tick replay count for cron tasks (TASKS only); 0..10000
graceful_stop:       dur  =5s      — grace before SIGKILL on stop; 0s = immediate SIGKILL, kept literally if set
env:                 map<str,str> — inline env merged into every task; key ^[A-Za-z_][A-Za-z0-9_]*$, <=256 entries, value <=32KiB, no NUL
env_file:            path         — dotenv file merged into every task; relative to runwisp.toml dir
secrets:             map<str,str> — inline secrets merged into every task; never shown in API/UI
secrets_file:        path         — dotenv file merged beneath secrets; only the path is visible
```

### [tasks.&lt;name&gt;] (run-to-exit)

Required: the table + [`run`](/configuration/tasks/#run) (unless [`compose_file`](/configuration/tasks/#compose_file), where [`run`](/configuration/tasks/#run) is optional and selects [`compose_mode`](/configuration/tasks/#compose_mode), or [`sdk`](/configuration/tasks/#sdk)). `restart`, [`restart_attempts`](/configuration/services/#restart_attempts), and [`instances`](/configuration/services/#instances) are rejected on tasks (use `[services.*]`); a task re-runs a failed run via `retry_*`.

```
group:             string =Tasks   — UI grouping label
description:        string          — human description
sdk:               bool =false      — tasks + services; run the unit in the SDK app connected over the local socket that defines it, instead of run (SDKs set it); rejects run, compose_file, shell, umask, user, env_base, working_dir, stop_signal; waits up to 10s for an app, then fails the run (runs queued behind it run late once the app is back)
cron:              string          — 5- or 6-field cron (optional leading seconds); ranges may wrap (22-2, FRI-MON); day of month takes L, L-3, LW, 15W, day of week FRI#3, FRI#L; also @hourly, @every 1h30m; omit => manual-only
timezone:          IANA string      — per-task TZ override (else [daemon] timezone)
jitter:            dur              — cap how far this cron task's start may slip; needs cron (inherits [defaults])
warn_after:        dur              — one long_running notification when a run is still going this long, without stopping it; goes to notify/global_notifiers/[[route]] kinds=["long_running"]; not a failure (inherits [defaults]; "0s" turns off)
run_on_start:      bool|enum =false — fire once at start, on top of any cron: true|"daemon" = every daemon start; "boot" = once per machine/container boot (@reboot; Linux boot_id + PID 1 start time, macOS kern.bootsessionuuid, else every start); import cron @reboot + systemd oneshot write "boot", supervisord autorestart=false writes true
manual_trigger:    bool =true       — allow CLI/API/UI trigger; false = cron-only
autostart:         bool =true       - false: the cron schedule starts paused the first time the task is registered (first boot, reload add, takeover un-hold) until resumed (UI, TUI p, `runwisp resume`); stays resumed across restarts (unlike services, not re-read each boot); needs cron; rejected with manual_trigger=false or run_on_start; setting it on a known task only warns on reload
hook_tokens:       [](str|{token,allow}) — tasks + services (rejected in [defaults]); bearer tokens for POST /api/hooks/tasks/{name}/{run,start,stop,restart} without a session; plain string = every action, table `allow` = subset (services: no run); each ≥32 chars, no whitespace; use ${VAR}/${file:...}; never shown in API/UI; manual_trigger does NOT apply
catch_up:          int  =1          — missed-tick replay count: 0 none | 1 latest | N up to N; >1 requires on_overlap=queue (rejected otherwise); 0..10000
timeout:           dur              — per-attempt cap (inherits [defaults])
graceful_stop:     dur  =5s         — grace before SIGKILL on stop; 0s = immediate SIGKILL, kept literally if set
stop_signal:       enum =SIGTERM    — stop-ladder signal (inherits [defaults]); SIGTERM|SIGINT|SIGQUIT|SIGHUP|SIGKILL|SIGUSR1|SIGUSR2
max_concurrent:    int  =1          — concurrent run cap; 1..1024
max_queued:        int  =100        — queued-run depth; 0..10000; 0 = no queue (busy → queue_full)
on_overlap:        enum =queue      — queue | skip | kill
retry_attempts:    int  =0          — retries after a failed attempt; 0..100
retry_delay:       dur  =5s         — delay between retries; 0s = no delay, kept literally if set
retry_backoff:     enum =constant   — constant | linear | exponential
failures:          []str           — outcomes classified as a failure (inherits [defaults]); see [defaults].failures
working_dir:       path             — process cwd; relative to runwisp.toml dir; ~ = home of whoever the
                                     task runs as (daemon's, or `user`'s — resolved at run time). Default: daemon cwd
shell:             path =/bin/sh    — interpreter for run (absolute path); invoked as <shell> -e -c <script>; see FAIL-FAST
umask:             string           — octal file-creation mask, e.g. "027" (else daemon umask)
env_base:          enum =inherit    — inherit (daemon's env, minus RUNWISP_*) | clean (PATH=/usr/bin:/bin,
                                      SHELL, HOME, USER/LOGNAME only, as crond gives a job). Host shell runs
                                      only — rejected on compose. env/secrets/params layer over either.
user:              string           — run as user or user:group (name/numeric id); needs daemon as root
log_max_size:      size =100mb      — per-run log cap
log_on_full:       enum =drop_old   — drop_new | drop_old | kill
keep_runs:         int              — row retention (inherits [defaults]); 0..1000000 (0 = keep none)
keep_for:          dur              — age retention (inherits [defaults])
run:               string (req)     — shell command; with compose_file it is the command run in the service (see compose_mode)
compose_file:      path             — run a compose service instead of run=; runs in the file's own compose project (COMPOSE_PROJECT_NAME > top-level name: > dir name), like `docker compose up` there
compose_service:   string =taskname — which compose service; must exist in compose_file (validate rejects unknown). Without compose_file (since 1.7): exec mode only, project read from RunWisp's own container labels (docker socket only); validate warns when not in a container
compose_mode:      enum             — exec | run. exec = `docker compose exec` into the service's RUNNING container (requires run);
                                      run = `docker compose run --rm` fresh container (runs `run` if set, else the service's own
                                      command). Default: exec when run is set, else run. Command runs as `/bin/sh -e -c` inside the
                                      target; `shell` is rejected on compose units. exec ignores pull/with_deps/instances naming and
                                      never removes the container. Docker cannot cancel an exec: `timeout` kills only the local
                                      client, so bound long work inside (`timeout N …`); exec on a [services.*] unit emits a
                                      startup warning
env:               map<str,str>     — inline env (merged over defaults.env)
env_file:          path             — dotenv file
secrets:           map<str,str>     — inline secrets (merged over defaults.secrets); never shown in API/UI
secrets_file:      path             — dotenv file merged beneath secrets; only the path is visible
params:            []table          — per-run inputs (TASKS only, rejected on services); one [[tasks.<name>.params]] entry per input, exactly one
                                     kind keyword: env=NAME | arg=NAME | option=--name | flag=--name. Also: default (any scalar; required if
                                     required=true and cron is set), required bool, type=string(default)|number, choices=[]str, allow_custom bool
                                     (needs choices), description string. Scheduled runs (cron/run_on_start/catch_up) use default; a retry uses the
                                     original run's values; values are passed as real args/env, never pasted into the shell string. See
                                     /configuration/tasks/#params
notify: []string         — sugar → route on any classified failure (see failures), on recovered (since 1.8), and, on a task, on long_running (see warn_after); notifier ids, "id:override", or "inapp". Non-failure outcomes use an explicit [[route]].
```

### [services.&lt;name&gt;] (long-running)

Not allowed (rejected by the strict loader): [`cron`](/configuration/tasks/#cron), [`timezone`](/configuration/tasks/#timezone), [`jitter`](/configuration/tasks/#jitter), [`run_on_start`](/configuration/tasks/#run_on_start), [`catch_up`](/configuration/tasks/#catch_up), [`on_overlap`](/configuration/tasks/#on_overlap), [`max_concurrent`](/configuration/tasks/#max_concurrent), [`max_queued`](/configuration/tasks/#max_queued), `retry_*`, [`params`](/configuration/tasks/#params). Shares the core task keys (including [`restart_attempts`](/configuration/services/#restart_attempts), see above): [`group`](/configuration/tasks/#group) (default `Services`), [`description`](/configuration/tasks/#description), [`graceful_stop`](/configuration/tasks/#graceful_stop), [`stop_signal`](/configuration/tasks/#stop_signal), [`working_dir`](/configuration/tasks/#working_dir), [`shell`](/configuration/tasks/#shell), [`umask`](/configuration/tasks/#umask), [`env_base`](/configuration/tasks/#env_base), [`user`](/configuration/tasks/#user), [`failures`](/configuration/tasks/#failures), [`log_max_size`](/configuration/tasks/#log_max_size), [`log_on_full`](/configuration/tasks/#log_on_full), [`keep_runs`](/configuration/tasks/#keep_runs), [`keep_for`](/configuration/tasks/#keep_for), [`run`](/configuration/tasks/#run)/`compose_*`, [`env`](/configuration/tasks/#env)/[`env_file`](/configuration/tasks/#env_file), [`secrets`](/configuration/tasks/#secrets)/[`secrets_file`](/configuration/tasks/#secrets_file), [`notify`](/configuration/tasks/#notify), [`hook_tokens`](/configuration/tasks/#hook_tokens), [`manual_trigger`](/configuration/tasks/#manual_trigger) (bool =true; here it gates manual stop/restart/start from CLI/API/UI/TUI/station instead of run-triggering). Service-only:

```
restart:             enum =always     — never | on_failure | always
instances:           int  =1           — parallel instances; 1..64
restart_delay:       dur  =1s          — delay before a restart; 0 = restart instantly, kept literally if set
restart_backoff:     enum =exponential — constant | linear | exponential
healthy_after:       dur  =60s         — uptime that counts as healthy: resets the restart counter and clears the failed-start streak; 0 = healthy immediately, kept literally if set. With health_check: deadline for the first passing check (0 rejected); missing it stops the instance as unhealthy and counts as a failed start
priority:            int  =0           — boot start order across services; lower starts first, ties break on name
autostart:           bool =true        — start at boot; false boots it stopped until started from UI/API
depends_on:          []string          — services that must be healthy before this one starts at boot (order only)
health_check:        table             — optional probe deciding health (see below)
```

`[services.<name>.health_check]` is a shell probe run next to each live instance; no run row, log file, or notification of its own (its results are SYSTEM lines in the instance's log). The first pass makes the instance healthy (satisfies depends_on, resets restart backoff and the failed-start streak); failures before it are ignored until `healthy_after` runs out. After that, a failed check is retried per `retry_*` and, when the retries run out, the instance is stopped with end reason `unhealthy` (then `restart` applies). Keys, all task keys with task semantics:

```
run:                 string (required) — the probe command; non-zero exit = failed check
cron:                string =@every 10s — when to check; ticks during a running check are skipped
timezone:            string =[daemon] timezone
timeout:             dur  =[defaults].timeout, else 5s — 0 rejected; a timed-out probe is killed immediately
failures:            []str =[defaults]/built-in (not the service's) — which probe outcomes fail the check
retry_attempts:      int  =2           — extra checks after a failed one before the instance is unhealthy; 0 = first failed check
retry_delay:         dur  =5s
retry_backoff:       enum =constant
working_dir, shell, umask, env_base, user — unset = the service's value
env, secrets         — merged key by key over the service's ([defaults] < service < probe; each side's *_file beneath its inline table)
env_file, secrets_file — the probe's own layer
compose_file, compose_service, compose_mode — never inherited; set compose_file (or run inside the same compose project) to exec into a running container (compose_mode "exec" only). A compose probe inherits nothing from the service
```

Any other key is rejected. `health_check` on `[tasks.*]` is rejected.

### [compose.&lt;alias&gt;] (import docker-compose services)

Expands to one observable service-task per imported compose service (or one task for the whole stack). Imported tasks default `restart=on_failure`, `instances=1`. Reserved scalar keys (any other key = a per-service override sub-table `[compose.<alias>.<svc>]`):

```
file:         path =auto-discover  — compose.yaml/.yml/docker-compose.yaml/.yml
services:     []string             — filter imported services: bare/"+name" keeps only those, "-name" drops those; polarities mutually exclusive; omit to import all
import:       enum =services       — services (per-service tasks) | stack (one task). services: an instance whose container already runs from `docker compose up` (labels project+service, oneoff=False; Nth instance = Nth by name) attaches via `docker logs -f --since now` instead of starting a second one, ends with the container's exit code; a stop/restart (or daemon stop) docker-stops it, so the next start is RunWisp's own compose run (since 1.8; tasks never attach; probe errors fail open)
group:        string =alias        — UI group
project_name: string =file own project — compose project name (-p); unset = COMPOSE_PROJECT_NAME > top-level name: > dir name, like `docker compose up`. Block-imported services get --service-ports --use-aliases; task-level compose_mode="run" does not
profiles:     []string             — compose profiles
env_file:     []string             — compose env files
working_dir:  string =dir of file  — CLI working dir
with_deps:    bool =false          — start dependencies
pull:         enum =missing        — missing | always | never
name_format:  string ={alias}.{service} — generated task name; must contain {service} when import="services"
```

Per-service override `[compose.<alias>.<svc>]` accepts: [`group`](/configuration/tasks/#group), [`description`](/configuration/tasks/#description), [`timeout`](/configuration/tasks/#timeout), [`graceful_stop`](/configuration/tasks/#graceful_stop), [`stop_signal`](/configuration/tasks/#stop_signal), `restart`, [`instances`](/configuration/services/#instances), [`restart_delay`](/configuration/services/#restart_delay), [`restart_backoff`](/configuration/services/#restart_backoff), [`healthy_after`](/configuration/services/#healthy_after), [`restart_attempts`](/configuration/services/#restart_attempts), [`priority`](/configuration/services/#priority), [`autostart`](/configuration/services/#autostart), [`failures`](/configuration/tasks/#failures), [`log_max_size`](/configuration/tasks/#log_max_size), [`log_on_full`](/configuration/tasks/#log_on_full), [`keep_runs`](/configuration/tasks/#keep_runs), [`keep_for`](/configuration/tasks/#keep_for), [`manual_trigger`](/configuration/tasks/#manual_trigger), [`env`](/configuration/tasks/#env), [`env_file`](/configuration/tasks/#env_file), [`secrets`](/configuration/tasks/#secrets), [`secrets_file`](/configuration/tasks/#secrets_file), [`notify`](/configuration/tasks/#notify). Not allowed: [`run`](/configuration/tasks/#run)/[`compose_file`](/configuration/tasks/#compose_file)/[`compose_service`](/configuration/tasks/#compose_service) (the parent block owns the backend), [`on_overlap`](/configuration/tasks/#on_overlap) (task-only concept), and the host-process keys [`shell`](/configuration/tasks/#shell)/[`umask`](/configuration/tasks/#umask)/[`env_base`](/configuration/tasks/#env_base)/[`user`](/configuration/tasks/#user). `import="stack"` forbids overrides and the [`services`](/configuration/compose/#services) filter. Per-service [`notify`](/configuration/tasks/#notify) desugars into notify routes keyed by the generated task name, exactly like `[services.*]`. The reserved sub-table `[compose.<alias>.defaults]` accepts the same keys and applies them to every imported service before the per-service override wins (precedence: compose-import default → `defaults` → `<svc>`); its [`notify`](/configuration/tasks/#notify) adds routes to all services. A compose service literally named `defaults` is rejected (rename hint); `import="stack"` forbids `defaults` too.

### [notify] (global notification settings)

```
global_notifiers:  []string =["inapp"] — channels added to every notify list + catch-all on failures, recovered and long_running; [] opts out
retry_budget:   dur                  — total retry budget per delivery
keep_notifications:      int  =1024           — in-app bell row cap
keep_for:  dur  =90d            — max bell row age
coalesce_window:   dur  =1h             — collapse repeat (kind+task) into one bell row; also coalesces outbound bursts. "0s" = one outbound message per event (bell still coalesces on its default window). Since 1.8 a success of the task closes its failure (and recovered) groups: held summary sent at once, next failure pages and gets a new bell row
coalesce_limit:   int  =10             — recent timestamps kept per coalesced bell row; also the count of suppressed events after which an outbound delivery (Slack/Telegram/etc) is force-forwarded instead of waiting for coalesce_window to close
```

### [notifiers.&lt;id&gt;] (outbound channel; map keyed by id)

Common: `<id>` (map key; non-empty, not "inapp", no ":"), `type` (req: `slack`|`discord`|`telegram`|`ntfy`|`gotify`|`pushover`|`smtp`|`sendmail`|`webhook`), `template_path` (optional).

```
slack:    webhook_url (req); channel (optional; starts # or @)
discord:  webhook_url (req; http/https)
telegram: bot_token (req); chat_id (req); parse_mode (MarkdownV2 needs template_path)
ntfy:     topic (req; [A-Za-z0-9_-]{1,64}); url (optional http/https server base, default https://ntfy.sh);
          token (optional access token, sent as Authorization: Bearer)
gotify:   url (req; http/https server base, posts to <url>/message); token (req; app token, X-Gotify-Key)
pushover: token (req; app token); user (req; user or group key)
smtp:     host(req); port 0..65535; tls_mode starttls|implicit|off (default: 465→implicit else starttls);
          tls_skip_verify bool; from(req email); reply_to(email); to(req,>=1) + cc/bcc(emails);
          username + password (set together or both omitted); tls_mode=off forbids credentials
sendmail: from(req email); to(req,>=1) + cc/bcc(emails); reply_to(email);
          sendmail_path (optional, must be absolute; default: /usr/sbin/sendmail,
          /usr/lib/sendmail, /usr/bin/sendmail, then $PATH — resolved at send time, not load).
          Pipes a text/plain RFC 5322 message to `<bin> -t -i`; no address on argv.
          Retries exit 75 (EX_TEMPFAIL) only; every other exit is permanent.
webhook:  url (req; http/https); headers (optional map<str,str>)
```

Secret-bearing values (`webhook_url`, `bot_token`, `password`, …) arrive final — use `${VAR}` / `${file:...}` substitution for indirection; never inline a secret you don't control. Secrets are never logged or sent over the station integration.

### [[route]] (route events to channels; repeatable)

```
match.failure: bool     — match any run classified as a failure (same axis as [tasks.*] failures) (optional)
match.kinds:   []string — outcomes (same vocab as failures): started | succeeded | failed | timeout | crashed | log_overflow | unhealthy | queue_full | stopped | daemon_stopped | missed | service.fatal | log.disk_pressure | long_running | recovered (notify.delivery_failed rejected; long_running/recovered + match.failure rejected). recovered (since 1.8) = a success whose previous ended run of the task failed; sent as run.recovered alongside run.succeeded, severity info
match.task:    string   — glob over task name (optional)
notifiers:      []string (req, non-empty) — notifier ids (or "inapp"); "id:#override" inline target (slack #/@, telegram chat_id, smtp/sendmail email)
```

### FAIL-FAST (run script execution)

```
invocation      <shell> -e -c <script>   — POSIX shells (sh bash dash ash busybox ksh mksh zsh yash ...)
                <shell> -c <script>      — anything else (python3, perl, fish, ...); warned at boot + validate
effect          multi-line run stops at the first failing command; that command's exit code is the run's
NOT set         -u (write `set -u` yourself); -o pipefail (not POSIX — needs shell="/bin/bash")
opt out         `set +e` as the script's first line; no TOML key exists for this
```

## CLI

Persistent flags: `-c/--config` (=`runwisp.toml`, or `/etc/runwisp/runwisp.toml` at euid 0), `--data` (=`.runwisp`, or `/var/lib/runwisp` at euid 0), `-p/--port` (=`9477`), `--host` (=`127.0.0.1`), `--log-level` (debug|info|warn|error), `--log-format` (auto|text|json). Each has an env fallback the flag wins over: `RUNWISP_CONFIG`, `RUNWISP_DATA`, `RUNWISP_PORT`, `RUNWISP_HOST`, `RUNWISP_LOG_LEVEL`, `RUNWISP_LOG_FORMAT`.
Precedence for `-c`/`--data`: explicit flag > `RUNWISP_CONFIG`/`RUNWISP_DATA` env var > euid-derived default. Client commands (not `daemon`) with neither set and no socket in the default data dir use the first of `storage/runwisp`, `var/runwisp`, `writable/runwisp` (cwd-relative, the PHP SDK's framework data dirs) that holds a socket.
Env: `RUNWISP_PASSWORD` (else ephemeral per-boot), `RUNWISP_VIEWER_PASSWORD` (optional read-only password; off when unset; sessions opened with it get 403 on every non-GET /api request incl. trigger/stop/reload, UI hides those controls; must differ from RUNWISP_PASSWORD; incompatible with RUNWISP_AUTH=off), `RUNWISP_AUTH` (`off` disables auth, default on; mutually exclusive with RUNWISP_PASSWORD), `RUNWISP_TLS` (auto|off; overrides `[daemon] tls`, default `off`, applied on every load incl. reload), `RUNWISP_TRUSTED_PROXIES` (CIDRs), `RUNWISP_LOG_OUTPUT` (true|false; overrides `[daemon] log_output`, the image sets true), `RUNWISP_STATION_TOKEN`, `RUNWISP_STATION_URL`.

Official Docker image: `runwisp/runwisp` (alpine default + `-debian` variant, amd64/arm64; runs under tini as PID 1). Plain tags carry no Docker CLI; add `-docker` to the tag (e.g. `latest-docker`, `latest-debian-docker`) for a build with a Docker CLI + Compose plugin baked in, needed if `[compose.*]` or a task's `run =` shells out to `docker`/`docker compose` from inside the RunWisp container itself. Binds `0.0.0.0`, plain HTTP (daemon's `[daemon] tls` default of `off`; set `-e RUNWISP_TLS=auto` to opt into self-signed HTTPS), requires `RUNWISP_PASSWORD` or `RUNWISP_AUTH=off` set or the entrypoint refuses to start; mount a config directory at `/etc/runwisp` (the entrypoint writes a starter `runwisp.toml` into it when the file is missing, the directory is a writable mount point, and the data dir has no `runwisp.db` yet) and data at `/var/lib/runwisp`. See https://docs.runwisp.com/getting-started/docker/.

```
runwisp                      — no subcommand: attach TUI to running daemon (quit leaves it running), else scaffold toml + run the daemon in-process with the TUI (quit stops it; confirms if task runs are active)
                             — scaffold prompt (TTY only) also detects an adjacent compose file and/or a readable
                               crontab (DefaultCronPatterns: root gets /etc/crontab + /etc/cron.d/* + /etc/anacrontab + every spool,
                               others get only their own spool file) and offers to wire either/both into the starter (a compose-only directory defaults to a starter that schedules jobs in the stack's services, with the import-the-services starter as the second choice);
                               a Blocked cron source falls back to the plain starter instead
                             — CRON CUTOVER: when the box also has a live cron unit and the install would be
                               system-scoped root-on-a-TTY, that one prompt does all three (scaffold include_cron,
                               install the system service, mask cron) and the caller attaches to the systemd
                               daemon instead of spawning its own. When the take-over isn't possible the prompt
                               says so and offers the plain scaffold; those jobs are then held (see include_cron)
runwisp daemon               — start headless daemon (no TUI); --app reads the config as a JSON document on stdin instead of runwisp.toml (what SDKs run); --no-http skips the HTTP port (no web UI/remote API; TUI and CLI keep working over the socket; also on bare `runwisp` and `demo`)
runwisp tui                  — attach a TUI to a running daemon
runwisp validate             — validate runwisp.toml without starting anything; --json for the structured document (see above); --app validates a JSON document on stdin;
                               --explain adds each schedule in words + next 3 firings (zone-aware, DST marked; `schedules` in --json)
runwisp list                 — list configured tasks and schedules; --json for a machine-readable document; services show their live state (`state` in --json) when a local daemon answers;
                               --url (env RUNWISP_URL) + --password list a remote daemon's tasks instead of the local runwisp.toml
runwisp status               — is the daemon alive?; --json for daemon health + every task's last run (+ pausedAt when its schedule is paused) + externalUrl/externalUrlSource (config|detected); human output lists paused schedules, FATAL services and the Web UI address; --url/--password check a remote daemon; --json carries each service's `service` state
runwisp run <task>          — run a task and stream output;  --daemon (via running daemon) | --standalone (in-process), mutually exclusive
                             — exit code = the process's exit code; 1 when the run failed (failures pattern, timeout, stop) but the process exited 0
                             — --param key=value (repeatable) supplies task parameter values; a param not mentioned uses its declared default
                             — --json prints the outcome as one JSON document on stdout once the run ends; log lines go to stderr instead
                             — --url (env RUNWISP_URL) dispatches to a remote daemon over HTTP; --password (env RUNWISP_PASSWORD) authenticates it;
                               --detach prints the run ID and exits without following the log stream (--url only)
runwisp reload               — re-read runwisp.toml + reconcile live (== SIGHUP); validate-first, no run_on_start/catch-up
                             — prints the diff, then the newly-live config's warnings on `!` lines
                               (ReloadResult.warnings). Same set as boot / `validate` / status /
                               GET /api/daemon's config_warnings, re-derived per request so a reload's
                               replace boot's. A crontab job include_cron skipped is NOT a task
                               change — it only appears here.
runwisp start <target...>    — start one or more tasks/services via the local socket (or --url); target = name or quoted glob ('*' = all controllable);
                                service: un-parks + fills empty slots, running instances untouched; task: triggers a run, no-op if one is already active/queued
runwisp restart              — stop + fresh start the daemon (applies restart-only settings, re-fires run_on_start (except "boot" tasks already run this boot)/catch-up); delegates to systemd/launchd if service-installed, otherwise restarts in place (SIGUSR2: graceful shutdown, then re-exec under the same PID, so a Docker container or terminal keeps it); --local to pin the per-user unit
runwisp restart <target...>  — restart one or more tasks/services via the local socket (or --url); target = name or quoted glob; daemon untouched, never delegates to systemd
                                service: bounces every instance (starts it if stopped); task: cancels the active run, waits for it to end, triggers exactly one fresh run (409 if it doesn't drain in time)
runwisp stop                 — shut the daemon down (delegates to systemd/launchd if service-installed); --local to pin the per-user unit
runwisp stop <target...>     — stop one or more tasks/services/run IDs via the local socket (or --url); target = name, quoted glob, or a run ULID; daemon keeps running, never delegates to systemd
                                service: cancels every instance, stops refilling slots; task: cancels the active run and drops anything queued, cron schedule keeps firing; run ID: stops just that run
runwisp pause <task...>      — pause cron schedules via the local socket (or --url): ticks skipped, no run rows, never caught up; manual runs still work; persisted in SQLite (survives reload/restart);
                                needs manual_trigger=true; 409 for a service, a task without cron, a held task. A reload that makes the task unpausable (cron removed, service, manual_trigger=false, task removed) clears it with a warning
runwisp resume <task...>     — lift a pause; fires from the next tick, skipped ticks not caught up; no-op if not paused; a glob matches only paused tasks
runwisp logs <target...>     — print run output via the local socket (or --url); target = name, quoted glob (includes manual_trigger=false), or a run ULID; name → its active runs, else its last ended run
                                full log by default; -n N = last N lines, -n +N = first N; task stderr stays on stderr; lines prefixed "name | " (services with instances>1: "name#k | ") when >1 target or a multi-instance service
                                outcome of ended runs logged to stderr ("run succeeded"; "run failed" if the failures policy counts it, else "run ended"); exit code = could the logs be shown, never the run's exit code
                             — -f follows: replays last 10 lines (or -n N; -n +N rejected), then streams; names/globs also follow new runs (globs match tasks a reload adds) until Ctrl+C; run IDs only → exits when they end
                             — --json: NDJSON on stdout; {"type":"line",task,runId,n,ts,stream,text,continued?} per line, {"type":"end", ...same fields as run --json} when a run ends
runwisp start/restart/stop/pause/resume — a target locked with manual_trigger=false 403s when named directly; a glob silently skips it (pause's glob also skips services, cron-less and held tasks). --url (env RUNWISP_URL) + --password (env RUNWISP_PASSWORD) dispatch to a remote daemon,
                                same CHAP login/session cache as `run --url`. An unknown name or empty glob fails before anything runs; otherwise each target is attempted and failures print per-target, exit non-zero
runwisp start/restart/stop --token <t> <name...> — (since 1.8; env RUNWISP_HOOK_TOKEN) act through POST /api/hooks/tasks/{name}/{action} with a unit's hook token instead of a session; needs --url/RUNWISP_URL; literal names only (glob, run ID, --attach and the daemon-wide no-target form rejected); 401 = token not one of the unit's hook_tokens, 403 = allow list omits the verb. For a task with user= that must restart a service (it can't open the root socket). Inside a task, the no-daemon error points at --token instead of sudo
runwisp start/restart/stop --attach <target...> — then follow, like `logs -f`, only the targets that succeeded (a glob's skipped/locked entries and failed targets excluded; exit non-zero if any failed): live runs from their last 10 lines, every run the action starts from line 0 (subscribed before dispatch, so fast runs aren't missed), no earlier finished runs; Ctrl+C ends it, run IDs only → exits when they end; rejected without a target
runwisp import cron [FILE]   — convert a crontab to runwisp.toml; -o/--output --write --force --dry-run --quiet --system
runwisp import supervisord [FILE...] — convert supervisord config to runwisp.toml; -o/--output --write --force --dry-run --quiet
runwisp import systemd [UNIT...] — convert systemd .service and .timer units to runwisp.toml; -o/--output --write --force --dry-run --quiet
                             — Restart= → [services.*], Type=oneshot → [tasks.*]; name from filename. Reject-as-note:
                               multiple ExecStart/ExecStartPre/Post, Type=notify|forking, sandboxing, socket activation,
                               %i templates. NO `takeover systemd` (disable units yourself: systemctl disable --now)
runwisp import ofelia [FILE...] — convert Ofelia jobs (INI config, or a .yml/.yaml compose file with ofelia.* labels, or stdin) to tasks: job-exec (compose label -> compose_file+compose_service+run; INI container -> docker exec), job-run (docker run --rm --init), job-local; no-overlap -> on_overlap=skip; job-service-run/job-compose unsupported; since 1.7
                             — -o writes one standalone file; --write installs the two-tier layout
                               (tasks → machine-owned runwisp.d/imported.toml, root runwisp.toml's
                               [daemon].include wired to load it; both written atomically or rolled back;
                               refused, non-zero, nothing written, if the result would not load).
                               Tasks from the staging file report "source": "staged" in list/status --json.
                             — stderr summary gives every source job one row (name, schedule, the full command,
                               wrapped not truncated) marked ✓ clean / ~ changed / ! needs a fix / - skipped,
                               plus file-level notes and a verdict line. A job that emitted no TOML still gets
                               a row. --quiet keeps only the ! rows; --quiet with a clean import prints nothing.
                             — --dry-run: same summary + the files a real run would touch, writes nothing.
                               Rejects --quiet (contradiction). No-op in stdout mode (already writes nothing).
                               Proves the generated content loads + reports a root that already
                               fails to load; prints that the merge is unchecked (needs the files
                               on disk). Two-tier plan comes from configedit.PlanStage.
                             — both crontab formats: working_dir = "~" (crond runs a job in the running
                               user's home). ~ resolves against whoever the task runs as — the daemon's
                               account when no `user` is emitted, the user column's when one is. A ~ on a
                               task with `user` stays literal through config.Load and is joined in
                               executor.resolveWorkingDir from the resolved credential's home.
                               A leading `cd DIR &&` (DIR a plain absolute, `~` or `~/` path, no quoting
                               or $) becomes working_dir = DIR and is cut from run.
                             — every imported task gets env_base = "clean"; the crontab's own PATH= lands in
                               the task's env and layers over it.
                             — cron's '%' rules are applied, not copied: an unescaped % ends the command
                               (rest = stdin, further % = newline), \% is a literal %. run is emitted as
                               crond would run it; lost stdin input is quoted in a # TODO on the run line
                               and blocks the row (!). A \%-only translation is a ~ row, no TODO.
                             — import COPIES; it never disables the source. Every summary ends with a "!" warning
                               that cron/supervisord still runs these jobs and each will run twice until the
                               operator turns the old one off. Suppressed only when there is no duplication yet
                               (nothing emitted, or the generated config doesn't validate).
runwisp promote [TASK...]    — put a derived task's block in the root runwisp.toml; --all --reload --dry-run
                             — acts on Task.Source.Promotable(): staged (MOVED out of
                               runwisp.d/imported.toml, file deleted when emptied) and cron (block COPIED from
                               config.CronBlockTOML, exact source line COMMENTED OUT in the crontab via
                               config.CronSourceLine + configedit.PlanCronCommentOuts). A cron-sourced task is
                               only ever held (HeldBy) while Task.Source == cron, so leaving the line live
                               after promote would mean RunWisp and a still-live, unmasked cron both run it —
                               commenting it out (cron ignores '#') is what makes the move safe, not tidy-up.
                               The line is commented, not deleted: it stays visible with a note pointing at the
                               runwisp.toml it moved to. Refuses (writing nothing on either file) if the recorded
                               file:line no longer matches the crontab byte-for-byte — moved, changed, or gone since load.
                             — surgical text move: the block's comments/formatting/# TODOs travel byte-for-byte.
                               Every file involved is written as one transaction gated on the merged load, else
                               nothing changes. No atomic primitive spans the crontab and runwisp.toml themselves —
                               a hard kill between their two renames is the one unclosed gap; the crontab write is
                               ordered first so that gap leaves the job commented-out (cron won't fire it) but not
                               yet in root — recoverable by hand — rather than double-fired.
                               Refuses (writing nothing) an unknown name, an already-native name, a compose-generated
                               task, or a config that doesn't load. --all with nothing staged exits 0.
                               Staged promotion (or a cron task already taken over, so it was unheld and scheduled
                               already) changes no behaviour — only which file defines the task — so a following
                               reload reports no task changes, a promoted service is not restarted, and only the
                               provenance flag refreshes. Promoting a cron task while cron is still live flips it
                               from held to unheld (HeldBy cron→none): the diff reports it Changed(ReasonSchedule),
                               so that reload has RunWisp take over its schedule. Emptied staging file is deleted.
runwisp password             — print the daemon's ephemeral password (local socket; exit 5 under RUNWISP_AUTH=off, refuses if RUNWISP_PASSWORD set)
                             — as root against the system service's data dir, a daemon that withholds the password
                               falls back to the `password.conf` drop-in `service install` saved. A non-root caller
                               while only the system service runs gets "Use `sudo runwisp password`".
                             — --viewer: print the read-only password instead, minting a random in-memory one on first call (refuses if RUNWISP_VIEWER_PASSWORD set)
runwisp openapi              — print the OpenAPI 3.1 spec (JSON) to stdout
runwisp schema               — print the runwisp.toml JSON Schema (draft 2020-12) to stdout; published at https://docs.runwisp.com/config.schema.json
runwisp station              — start in station mode; --token --url --env-file(=.env) --no-tui
runwisp demo                 — boot a throwaway, fully-populated instance; --no-tui (foreground, Ctrl+C stops it) --seed-only --station --token --url --env-file
runwisp upgrade              — upgrade to the latest stable release via the install channel: homebrew → brew upgrade; deb/rpm package → [sudo] apt-get update + install --only-upgrade / dnf upgrade --refresh; global npm/bun/pnpm/yarn → that manager; script/tar.gz → download from GitHub, verify SHA-256, atomic in-place swap; docker/npx/project-local npm → refuses with instructions; dev build refuses. -y/--yes (needed without a TTY), --restart now|idle|later (idle = wait until no task runs are pending/running, services ignored; no TTY + no flag = later)
runwisp service install      — install autostart; -y --print --dry-run --force --local --binary <path> --station --token <t> --url <u>
                             — DEFAULT scope is the system-wide singleton /etc/systemd/system/runwisp.service
                               (Linux, root, no fingerprint in the name). Run as non-root it re-execs itself
                               through sudo (same forwarding as takeover); without sudo on PATH it refuses, naming
                               `sudo` and `--local`. macOS has no system scope yet: --local is required.
                             — --local installs ~/.config/systemd/user/runwisp-<fingerprint>.service (Linux,
                               + loginctl enable-linger) or ~/Library/LaunchAgents/com.runwisp.daemon.<fp>.plist.
                               Refused as root on Linux (systemctl --user has no bus for root under sudo).
                             — --data/--config override paths but never the scope; a system install also
                               requires the resolved config to be root-owned and not group/world-writable.
                               An auto-detected binary that isn't root-trusted (e.g. ~/.local/bin/runwisp) is
                               copied to /usr/local/bin/runwisp first and the unit runs the copy (--binary is
                               never copied). A same-content copy under the sudo user's home is then replaced
                               by a symlink to it (chowned to that user), so `runwisp` and `sudo runwisp` agree.
                               Read-only systemctl probes never use sudo.
                             — unit lifecycle ONLY: it never touches cron. When a `takeover` would do something,
                               a successful install prints a note naming the live cron unit, its job count, and
                               `runwisp takeover`. There is no --take-over-cron flag.
                             — Web UI password: when auth is on and RUNWISP_PASSWORD is unset, generates one into a
                               0600 `<unit>.d/password.conf` drop-in (NOT the world-readable unit) BEFORE
                               daemon-reload + enable --now, so the first start already has it (no restart), and
                               prints it once. Idempotent: an existing drop-in or a set RUNWISP_PASSWORD is left
                               untouched (re-install never rotates). `sudo runwisp password` prints it again.
                               launchd: no drop-in, skipped.
runwisp takeover             — retire cron in one step; --dry-run --force -y --allow-skipped-cron-jobs --binary
                             — works from NOTHING: no runwisp.toml needed. Computes one plan (internal/cutover),
                               prints it, asks once, executes. Steps: write runwisp.toml reading the crontabs it
                               found (or insert [daemon] include_cron into an existing config, surgically; an
                               include_cron still byte-identical to RunWisp's own scaffold that lists only default
                               patterns gets the missing defaults added, any other declared one blocks with a paste) ->
                               install the system service -> stop+mask cron (+ anacron.timer anacron.service when
                               loaded; one space-separated list in the runwisp-masked-cron / -prior-state markers,
                               priors paired by position) -> start RunWisp -> reload a daemon
                               that was already running (so tasks the cron gate held go live immediately;
                               `enable --now` on an already-active unit is a no-op). Needs root + systemd; run as
                               non-root (--dry-run included: reading every crontab needs root) it re-execs
                               `sudo <abs binary> takeover <args>`, forwarding non-secret RUNWISP_* settings.
                               Without sudo on PATH it only reports "needs root". Ends by printing the dashboard
                               URL, an `ssh -L` tunnel line when run over SSH (SSH_CONNECTION is forwarded through
                               sudo), `sudo runwisp password` and `sudo runwisp upgrade`.
                             — when cron was running, tasks from @reboot lines (run_on_start="boot") are marked as
                               already run for the current boot, so the first start doesn't fire them twice.
                             — a failed start restores cron to its pre-take-over state rather than leaving no
                               scheduler. Later crash loops: unit has StartLimitBurst=5/300s + OnFailure=
                               runwisp-cron-failsafe.service, which unmasks+starts cron only when runwisp.service
                               is "failed" and Result != timeout (so stop never triggers it). Uninstall restores
                               the recorded `# runwisp-cron-prior-state:` (masked stays masked, stopped stays stopped).
                             — the plan lists each live job as `task ← file:line  command` (command cut to
                               fit 80 cols) and says overlapping runs now queue (on_overlap="queue").
                               --dry-run prints the same plan, then exits non-zero if blocked. A blocked plan
                               prints what it found and the blockers, never the steps; with no cron jobs at
                               all it prints only the blocker (no cron unit and no `crontab` binary: "no cron
                               on this machine", pointing at `runwisp` / `runwisp service install`).
                               A finished take-over re-runs as a no-op (exit 0), so it is script-safe.
                             — blocked by (all reported at once, nothing written): not Linux/systemd; not root;
                               no cron jobs on the box; the config does not load; the config is not trusted for a
                               system-wide install; an operator-maintained include_cron that misses crontabs
                               (never rewritten — it prints the array to paste); a cron source that failed to
                               load (--allow-skipped-cron-jobs overrides only this one).
                             — a port held by RunWisp's OWN service is not a conflict (that daemon is the one being
                               handed the jobs); a hand-started daemon on that data dir must be stopped first.
                             — re-running it repairs a cron that came back: unit already installed -> re-mask only.
                             — off Linux it is blocked and names the manual route (`runwisp import cron
                               --write`, then `crontab -r`); masking cron needs systemd.
runwisp service uninstall    — remove autostart; -y --purge (also data dir) --force --local
                             — the system unit re-execs itself through sudo when not root. Cron is restored
                               even when a later step (unit removal, daemon-reload) fails.
runwisp service status       — show autostart status; --local
                             — for the system unit, with no explicit flags or RUNWISP_* env, it checks the unit
                               against the settings parsed from its own ExecStart (binary/config/data/host/port).
                             — install/status/uninstall/stop/restart all detect the installed scope; --local is
                               only needed to disambiguate when a system AND a per-user unit both exist
```

## REST API

Base `/api`. Auth (enforced at middleware, not declared in the OpenAPI doc): Web/TCP clients log in via CHAP → signed session token (cookie or Bearer), or send a static `[daemon] api_tokens` / `viewer_api_tokens` value as Bearer (viewer: 403 on any non-GET); the local Unix socket bypasses auth for the CLI/TUI. `/api/local/credentials` is Unix-socket-only. `POST /api/hooks/<x>` mirrors session route `POST /api/<x>` (same query/body/response) outside the session: it takes `Authorization: Bearer <token>` (or `?token=`, insecure: URLs get logged; header wins if both) matching one of the unit's `hook_tokens` (401 for unknown unit / no tokens / wrong token alike; 403 if the token's `allow` omits the action; enforced even with RUNWISP_AUTH=off; manual_trigger ignored). Only rejected tokens are rate-limited: 20 per client IP per minute, then 429 for that IP (valid token included) until the window slides. Login: only wrong passwords count per client IP; the first 5 are free, then each doubles the wait before the next try (2s up to 90s), sooner gets 429 + `Retry-After` (correct password included); success or 15 quiet minutes clears it. Launch-ticket redemption is not limited; `/api/auth/challenge` is capped at 60 per IP per minute. SSE endpoints stream `text/event-stream`. None of these mutate TOML task definitions.

Read (GET):

```
/api/daemon                                     daemon info
/api/system                                     system stats
/api/system/metrics                             historical system metrics
/api/daemon/log/stream                          daemon log (SSE)
/api/tasks                                       list tasks; each carries live state: nextRunAt, pausedAt, usage, lastRun (newest started run), run (command), service (per-instance state, startFails, lastExitCode)
/api/tasks/{task}                                one task
/api/runs/{runId}                               one run
/api/runs/{runId}/log                           log-lines page
/api/runs/{runId}/log/raw                       full log download (text/plain)
/api/runs/{runId}/log/stream                    run log (SSE)
/api/tasks/{task}/log/search                     search log lines across runs
/api/runs                                        list runs; filter with query params (taskName, status, triggeredBy, …), no separate per-task route
/api/runs/summary                               aggregate run stats
/api/events/stream                              run lifecycle + system + config-stale + notification + tasks.changed (reload, pause/resume: refetch /api/tasks) events (SSE)
/api/notifications                              in-app notifications
/api/notifications/unread-count                 unread count
/api/local/credentials                          ephemeral password (Unix socket only)
```

Trigger / stop / mutate runs (POST/DELETE — never touches definitions):

```
POST   /api/daemon/reload                        re-read runwisp.toml + reconcile live task set (validate-first; reads from disk, never edits definitions)
POST   /api/tasks/{task}/run                     trigger a new run (tasks only)
POST   /api/tasks/{task}/start                   service: un-park + fill empty slots; task: trigger a run unless one is already active/queued (no-op then)
POST   /api/tasks/{task}/stop                    service: stop for daemon lifetime; task: cancel active run + drop anything queued (cron schedule untouched)
POST   /api/tasks/{task}/restart                 service: restart all instances; task: cancel active run, wait for it to end, trigger exactly one fresh run (409 if it doesn't drain in time)
POST   /api/tasks/{task}/pause                   pause the cron schedule (204, idempotent, keeps first pausedAt); 403 manual_trigger=false; 409 service / no cron / held / station mode. Task gains pausedAt, loses nextRunAt
POST   /api/tasks/{task}/resume                  lift a pause (204, idempotent); skipped ticks not caught up
         ?wait=true&waitTimeout=N (1..240, default 120) on run/start/restart: task returns the finished run (start follows an already-active run); service start/restart → 400. On stop: returns once drained, 409 on timeout
POST   /api/hooks/tasks/{task}/{run,start,stop,restart}  same as the session routes above, authed by a hook token instead of a session (triggeredBy=hook); run also takes ?tail=N (0..1000, since 1.8): the response adds log=[{n,stream,text}] with the run's last N log lines (a hook token can't read /api/runs/{id}/log)
POST   /api/runs/{runId}/stop                   stop a running task
DELETE /api/runs/{runId}                        delete a run
POST   /api/runs/bulk/stop                       stop runs by selector
POST   /api/runs/bulk/delete                     soft-delete runs by selector
POST   /api/runs/bulk/restore                    restore soft-deleted runs
POST   /api/runs/bulk/rerun                      re-run tasks behind selector
POST   /api/notifications/read                   mark all read
POST   /api/notifications/{id}/read              mark one read
POST   /api/notifications/{id}/unread            mark one unread
```

Full machine-readable schema: https://docs.runwisp.com/openapi.json
