Metadata-Version: 2.4
Name: flowa-core
Version: 0.4.0
Summary: Flowa — lightweight pipeline orchestration
Author: gustavosegre
License: MIT
Project-URL: Homepage, https://github.com/gustavosegre/flowa
Project-URL: Documentation, https://github.com/gustavosegre/flowa#readme
Project-URL: Changelog, https://github.com/gustavosegre/flowa/blob/main/CHANGELOG.md
Project-URL: Issues, https://github.com/gustavosegre/flowa/issues
Keywords: pipeline,orchestration,workflow,scheduler,airflow
Classifier: Development Status :: 4 - Beta
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Operating System :: Microsoft :: Windows
Classifier: Operating System :: POSIX :: Linux
Classifier: Framework :: FastAPI
Classifier: Topic :: System :: Monitoring
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: typer>=0.12
Requires-Dist: pyyaml>=6.0
Requires-Dist: ruamel.yaml>=0.18
Requires-Dist: apscheduler<4,>=3.10
Requires-Dist: pydantic>=2
Requires-Dist: fastapi>=0.110
Requires-Dist: uvicorn[standard]>=0.29
Requires-Dist: requests>=2.31
Requires-Dist: urllib3>=2
Requires-Dist: psutil>=5.9
Requires-Dist: tzdata; sys_platform == "win32"
Provides-Extra: dev
Requires-Dist: pytest>=8; extra == "dev"
Requires-Dist: pytest-timeout>=2.3; extra == "dev"
Requires-Dist: ruff>=0.6; extra == "dev"
Requires-Dist: httpx>=0.27; extra == "dev"
Provides-Extra: holidays
Requires-Dist: holidays>=0.50; extra == "holidays"
Dynamic: license-file

<img width="1252" height="336" alt="flowa_banner" src="https://github.com/user-attachments/assets/0ebc7d12-5bf1-4d64-bacb-4e0ab52e215d" />

A lightweight pipeline orchestration tool inspired by Apache Airflow.
Define workflows in YAML, run them from the CLI, schedule them with cron, and monitor everything through a REST API and web UI.

<img width="1180" height="45" alt="flowa_div" src="https://github.com/user-attachments/assets/0be78671-c192-41b7-9f27-510f159b0044" />

## Features

- **DAG-based execution** — topological sort with cycle detection
- **Parallel steps** — independent steps run concurrently via thread pool
- **Retry & timeout** — configurable per step
- **Continue on error** — mark steps as non-blocking for their dependents
- **Scheduling** — once a day, specific times, interval windows or cron, per time zone
- **SQLite history** — every run and step is recorded automatically
- **REST API** — trigger, stop and query pipelines programmatically
- **Web UI** — dashboard, pipeline health, run view with the logs side by side, Gantt,
  execution calendar and metrics; works offline (no CDN)
- **Visual editor** — create and edit pipelines on a whiteboard: blocks are scripts,
  arrows are dependencies, the YAML file stays the source of truth
- **Hardware monitor** — live CPU/RAM/disk charts plus a per-script CPU & memory consumption log
- **Script support** — run `.py`, `.sh` and `.bat` files natively
- **Workspaces** — group pipelines by team or domain directly in the YAML
- **Microsoft Teams notifications** — Adaptive Card alerts with optional AI error analysis
- **AI error analysis** — automatic error diagnosis via Groq, Claude, Gemini or OpenAI
- **Stop running pipelines** — cancel an active run from the UI or API
- **Auto-reload** — pipeline changes are picked up without restarting the server

---

## What's New

### v0.4.0
- **Dependencies between pipelines**: `trigger.after` runs a pipeline when others finish; draw
  them on the new **map** screen. See [Dependencies](#dependencies-between-pipelines).
- **Run parameters** (`flowa run --param`, API, UI) and context variables (`FLOWA_RUN_ID`,
  `FLOWA_LOGICAL_DATE`, ...); **`flowa backfill`** reruns a date range.
- **Holidays**: `exclude_holidays: BR-SP` (extra `[holidays]`).
- **Alert** when a run takes longer than usual (p95 × factor), `/metrics` for Prometheus.
- **`flowa service install`**: systemd on Linux, Task Scheduler or NSSM on Windows.

### v0.3.0
- **New web UI** (React), served at `/ui/` and bundled in the package — no Node needed to
  install. See [Web UI](#web-ui).
- **Visual pipeline editor** with live validation, schedule preview, diff before saving and
  version history.
- **Run view with the logs side by side**: Gantt of steps and attempts, live log (SSE), search,
  error highlighting, CPU/RAM per step.
- **Execution calendar**, pipeline metrics (p50/p95, per-step stats, top errors).
- **Security**: access token required by the API and the UI, TLS verification on by default,
  secrets masked in logs and API responses, personal data masked before AI analysis.
- Schedule modes `once`, `times`, `interval` (windows may cross midnight) and `cron`;
  `until_success`; `exclude_dates`; `.env` with `${VAR}` in pipeline files.

### v0.2.3
- Bug-fix release: invalid pipelines are rejected with clear errors (`flowa validate`),
  timeouts and stops kill the whole process tree, no duplicated or ghost schedules, runs left
  `RUNNING` after a crash become `ABORTED`, `flowa run` returns a non-zero exit code on
  failure, `timezone` is honored, logs keep every retry. See the [CHANGELOG](https://github.com/gustavosegre/flowa/blob/main/CHANGELOG.md).

### v0.2.2
- **Hardware monitor tab** — new `monitor` tab in the web UI with live CPU (overall + per-core), RAM and disk usage, ~5 min history charts, and a resource consumption log showing how much CPU/RAM each pipeline step used
- **System processes box** — live list of the top system processes by CPU/memory, with the flowa server process itself pinned at the top
- Smooth, flicker-free auto-refresh on the monitor tab (in-place DOM patching instead of a full re-render)
- Browser tab favicon

### v0.2.1
- **AI error analysis** — on failure, flowa sends the step log to an LLM (Groq, Claude, Gemini or OpenAI) and includes the diagnosis in the Teams notification
- **Multi-provider AI config** — `flowa-core/config.yaml` centralizes all API keys and provider settings
- **Teams customization** — `flowa teams-init` generates `flowa-core/teams_config.py` with all card options (images, colors, icons, timeouts) ready to edit
- **Leaf background animation** — subtle animated leaves in the web UI
- **Enhanced UI animations** — card entrance, hover effects, glow on status dots, button feedback
- **`global` syntax fix** — fixed a silent SyntaxError in `teams_notifier.py` that prevented notifications from being sent

### v0.1.6 — v0.2.0
- Workspaces, Teams integration, stop runs, dependency tree on cards, encoding fix, exit code detection, auto-reload

---

## Installation

**Requirements:** Python 3.11+ on Windows or Linux. Nothing else: no Node, no database server,
no Docker. The web UI is bundled in the package.

```bash
pip install flowa-core

# with holiday calendars for exclude_holidays
pip install "flowa-core[holidays]"

# upgrade an existing installation
pip install --upgrade flowa-core
```

With [uv](https://docs.astral.sh/uv/), as an isolated tool: `uv tool install flowa-core`.

The latest unreleased code, straight from GitHub (no git needed): `pip install https://github.com/gustavosegre/flowa/archive/refs/heads/main.zip`.

Behind a corporate proxy: `pip install --proxy http://proxy.company:8080 ...`; if the proxy
inspects TLS, add `--cert C:\certs\corporate-ca.pem` (see also
[TLS and corporate proxies](#tls-and-corporate-proxies)).

### Development install

To work on flowa itself:

```bash
git clone https://github.com/gustavosegre/flowa.git
cd flowa
pip install -e ".[dev,holidays]"
pytest -q
```

The web UI is already built in `flowa/ui/dist`. Only to change it you need Node 20+:

```bash
cd frontend
npm ci
npm run dev        # http://localhost:5173/ui/ with the API proxied to :8000
npm run build      # writes ../flowa/ui/dist (commit it)
npm run lint && npm run test
npx playwright install chromium && npm run e2e
npm run screenshots   # regenerates docs/screenshots from a demo project
```

---

## Tutorial — Install and Create Your First Pipeline

In this tutorial you install flowa, create a project and build a pipeline with three Python
scripts (**extract → transform → load**) that runs on weekdays at 07:30. You can create the
pipeline in a YAML file ([Part 4](#part-4--create-the-pipeline-in-yaml)) or in the visual
editor ([Part 5](#part-5--or-create-it-in-the-visual-editor)); both produce the same file.

### Part 1 — Install flowa in a virtual environment

A virtual environment keeps flowa and your scripts' packages apart from the rest of the
machine. Create one in the folder of your project.

**Windows** (Command Prompt or PowerShell):

```bat
mkdir C:\projects\my-etl
cd C:\projects\my-etl
python -m venv .venv
.venv\Scripts\activate
pip install flowa-core
flowa --version
```

**Linux:**

```bash
mkdir -p ~/projects/my-etl && cd ~/projects/my-etl
python3 -m venv .venv
source .venv/bin/activate
pip install flowa-core
flowa --version
```

`flowa --version` prints `flowa 0.4.0`. Every new terminal needs the `activate` line again
before using `flowa`.

### Part 2 — Create the project

```bash
flowa init
```

```
my-etl/
├── .venv/
└── flowa-core/
    ├── pipelines/
    │   └── etl.yaml       ← example pipeline
    ├── logs/              ← one folder per run, one log file per step
    ├── data/              ← flowa.db (history) and the access token
    └── config.yaml        ← time zone, retention, Teams, AI, TLS...
```

Two things to do now:

1. **Delete `flowa-core/pipelines/etl.yaml`.** It is only an example, it is scheduled every
   hour and its scripts do not exist. Every `.yaml`/`.yml` file in `flowa-core/pipelines/` is a
   pipeline.
2. **Set your time zone** in `flowa-core/config.yaml` (schedules and the dates in the UI use
   it; without it, flowa uses the system time zone):

   ```yaml
   timezone: America/Sao_Paulo
   ```

Always run `flowa` commands from the project folder (the one that contains `flowa-core/`).

### Part 3 — Write the scripts

flowa runs any command: Python, `.bat`, `.ps1`, `.sh` or a program. A step **succeeds when
the command exits with code 0**; anything else (an exception, `sys.exit(1)`) is a failure.
Everything the command prints goes to the step's log.

Create the folder `scripts/` with three files:

`scripts/extract.py`

```python
import os

day = os.environ["FLOWA_LOGICAL_DATE"]  # e.g. 2026-10-26, set by flowa
print(f"extracting sales of {day}")
os.makedirs("data", exist_ok=True)
with open(f"data/sales_{day}.csv", "w", encoding="utf-8") as f:
    f.write("store,amount\nA,100\nB,250\n")
print("3 rows written")
```

`scripts/transform.py`

```python
import os

day = os.environ["FLOWA_LOGICAL_DATE"]
with open(f"data/sales_{day}.csv", encoding="utf-8") as f:
    rows = f.read().splitlines()[1:]
total = sum(int(line.split(",")[1]) for line in rows)
print(f"total of {day}: {total}")
```

`scripts/load.py`

```python
print("loading into the data warehouse... done")
```

Commands run **from the project folder**, so `data/` and `scripts/` are relative to it.
flowa also gives every step `FLOWA_RUN_ID`, `FLOWA_PIPELINE_ID`, `FLOWA_SCHEDULED_FOR`,
`FLOWA_LOGICAL_DATE` and one `FLOWA_PARAM_<NAME>` per run parameter
([details](#run-parameters-and-context-variables)).

### Part 4 — Create the pipeline in YAML

Create `flowa-core/pipelines/sales_daily.yaml`. The file name is the pipeline **ID**
(`sales_daily`); `name` is what the UI shows.

```yaml
name: Sales Daily
workspace: Sales                # groups pipelines in the UI
description: Daily sales load

schedule:
  days: weekdays                # Mon-Fri
  mode: once
  at: "07:30"                   # always quote times

steps:
  - name: extract
    run: python scripts/extract.py
    retries: 2                  # try up to 3 times...
    retry_delay_seconds: 30     # ...waiting 30 s, then 60 s
    timeout_seconds: 600        # kill it after 10 minutes

  - name: transform
    run: python scripts/transform.py
    depends_on: extract         # runs only after extract succeeded

  - name: load
    run: python scripts/load.py
    depends_on: transform
```

Steps without a dependency between them run in parallel (up to `max_parallel`, default 4).
If a step fails, the steps that depend on it are skipped and the run is `FAILED`.

**Check the file:**

```bash
flowa validate --all
```

```
✓ sales_daily.yaml  (Sales Daily, 3 steps)
```

A mistake is reported with the file, the step and the field, and the exit code is `1`:

```
✗ sales_daily.yaml
    sales_daily.yaml: step 'transform': depends_on: 'extrct' does not match any step
```

**Run it once, in the foreground:**

```bash
flowa run flowa-core/pipelines/sales_daily.yaml
flowa run flowa-core/pipelines/sales_daily.yaml -p logical_date=2026-10-01   # another day
```

The last line shows the result (`run #1: SUCCESS`); the exit code is `0` on success and `1`
otherwise, so `flowa run` also works from the Windows Task Scheduler, cron or a CI job.

**Look at the result:**

```bash
flowa history          # recent runs
flowa logs 1           # the steps of run #1
```

The full output of each step is in `flowa-core/logs/sales_daily/<date>_run<id>/<step>.log`.
Every option of the file is in the [YAML reference](#complete-pipeline-yaml-reference).

### Part 5 — Or create it in the visual editor

Start the server:

```bash
flowa server
```

It prints an address with an access token, `http://127.0.0.1:8000/ui/#token=...`. Open it
in the browser (the UI keeps the token and removes it from the address bar). Then:

1. Go to **pipelines** and click **+ new pipeline**.
2. With nothing selected on the canvas, the right panel shows the **pipeline**: type the
   name `Sales Daily` (the ID `sales_daily` is generated from it and cannot change later) and
   the workspace `Sales`.
3. In the **blocks** palette, click (or drag to the canvas) **python script** three times.
4. Select each block and fill in the right panel: name (`extract`, `transform`, `load`) and
   the command. **browse** lists the files of the project: picking `scripts/extract.py`
   writes `python scripts/extract.py`. Set retries, retry delay and timeout on `extract`.
5. **Connect the blocks:** drag from the dot on the right of `extract` to the dot on the left
   of `transform`, then from `transform` to `load`. An arrow A → B means *B runs after A*.
   Arrows that would create a cycle are refused. `Delete` removes the selected block or
   arrow; `Ctrl+Z` / `Ctrl+Shift+Z` undo and redo; **auto-arrange** tidies the canvas.
6. Click an empty spot of the canvas to get back to the pipeline panel, click
   **+ schedule**, choose **weekdays**, mode **once a day**, time `07:30`. The panel lists the
   **next 10 runs** as you type.
7. Optional: select a block and click **test this step** to run only that step and watch its
   log live at the bottom of the screen.
8. Click **save**. A window shows the YAML that will be written; confirm with **save**.

![Editor](https://raw.githubusercontent.com/gustavosegre/flowa/main/docs/screenshots/editor.png)

Errors (an empty command, a missing schedule time...) appear on the field and on the block,
and **save** stays disabled until they are fixed. The editor writes
`flowa-core/pipelines/sales_daily.yaml`: the YAML file is always the source of truth, so you
can keep editing it by hand, and the editor keeps your comments when it saves. Each save
keeps the previous version (pipeline page → versions → restore).

### Part 6 — Run, follow and keep it scheduled

- On the **pipelines** screen, **run** starts the pipeline now; the run page opens with the
  log of each step next to the list of steps. If a step fails, its log is already open.
- **calendar** shows past runs per day and the predicted runs of the coming days.
- **pause** stops the schedule without deleting anything (manual runs still work).

**Scheduled runs only happen while `flowa server` is running.** To keep it running after
you close the terminal and after a reboot, install it as a service (from the project folder,
with the virtual environment active):

```bash
flowa service install
```

On Linux it creates a systemd unit; on Windows a Task Scheduler task that starts at logon
(or a real service with NSSM). See [Running as a Service](#running-as-a-service).

> **Which Python runs `python scripts/x.py`?** The first `python` on the PATH of the flowa
> process. In a terminal with the virtual environment active, that is the venv's Python. A
> service does not activate the venv, so if your scripts need packages installed in it, write
> the interpreter path in `run`: `.venv\Scripts\python scripts/extract.py` (Windows) or
> `.venv/bin/python scripts/extract.py` (Linux).

### Part 7 — Going further

| To... | See |
|---|---|
| Get a Teams message when a pipeline fails (or recovers) | [Teams Notifications](#teams-notifications) |
| Have an AI explain the error in that message | [AI Error Analysis](#ai-error-analysis) |
| Keep passwords and webhook URLs out of the YAML (`${VAR}` + `.env`) | [Secrets in pipelines](#secrets-in-pipelines-env-and-var) |
| Run a pipeline after another one finishes | [Dependencies Between Pipelines](#dependencies-between-pipelines) |
| Pass parameters, reprocess past days (`flowa backfill`) | [Run parameters](#run-parameters-and-context-variables) |
| Skip holidays, specific dates, or run every N minutes in a window | [YAML reference](#complete-pipeline-yaml-reference) |
| Open the UI from other machines | [Security](#security) |

---

## Web UI

Open the address printed by `flowa server`. Every screen uses the configured time zone,
works offline and uses a dark theme by default (light theme and the leaf animation are in
**settings**; the animation is off when the system asks for reduced motion).

| Screen | What it shows |
|---|---|
| **dashboard** | Runs today, success rate (7/30 days), failures and missed fires, avg/p95 duration, next runs with countdown, runs in progress with live CPU/RAM, charts |
| **pipelines** | Pipelines by workspace: schedule, next run, last 20 runs (click to open), mini DAG, run/pause/edit |
| **pipeline** | Next runs, duration per run with the p50/p95 band, per-step stats, DAG colored by the last run, YAML versions with diff and restore |
| **history** | Every run with filters (pipeline, workspace, status, trigger, period) and CSV export |
| **run** | Logs next to the steps: the failing step is selected on open; Gantt, live log, search, CPU/RAM chart, stop/rerun |
| **map** | Pipelines by workspace with arrows for `trigger.after`: draw, retarget or remove dependencies |
| **calendar** | Month, week and year views: runs by status per local day, missed and predicted fires |
| **monitor** | CPU, memory and disk of the host, with run start/end marks; top processes |
| **settings** | Time zone, retention, Teams, AI provider and keys (write-only), theme, animation |

![Dashboard](https://raw.githubusercontent.com/gustavosegre/flowa/main/docs/screenshots/dashboard.png)

**Run with the logs side by side** — no "view logs" click: the step that failed is already open.

![Run view](https://raw.githubusercontent.com/gustavosegre/flowa/main/docs/screenshots/run.png)

**Visual editor** — drag blocks from the palette, connect a block's output to another block's
input to make the second depend on the first. Cycles are refused. The schedule editor shows
the next 10 fire times as you type; saving shows the diff of the YAML file first.

![Editor](https://raw.githubusercontent.com/gustavosegre/flowa/main/docs/screenshots/editor.png)

<details>
<summary>More screenshots</summary>

![Pipelines](https://raw.githubusercontent.com/gustavosegre/flowa/main/docs/screenshots/pipelines.png)
![Pipeline detail](https://raw.githubusercontent.com/gustavosegre/flowa/main/docs/screenshots/pipeline-detail.png)
![Calendar](https://raw.githubusercontent.com/gustavosegre/flowa/main/docs/screenshots/calendar.png)
![History](https://raw.githubusercontent.com/gustavosegre/flowa/main/docs/screenshots/history.png)
![Monitor](https://raw.githubusercontent.com/gustavosegre/flowa/main/docs/screenshots/monitor.png)

</details>

Keyboard: `↑`/`↓` switch steps in the run view; `Delete` removes the selected block or
arrow; `Ctrl+Z` / `Ctrl+Shift+Z` undo and redo in the editor.

---

## Complete Pipeline YAML Reference

Below is a fully annotated example covering every option. Files written for flowa 0.2.x keep
working unchanged (see [Older pipeline files](#older-pipeline-files)).

```yaml
# The pipeline ID is the file name without extension (finance_etl.yaml → finance_etl).
# It is used by the API, the scheduler and the log folders; two files cannot share it.

name: Finance ETL               # display name (required)
workspace: Finance              # groups pipelines in the UI
description: Daily finance load
enabled: true                   # false = paused: not scheduled, manual runs still allowed
timezone: America/Sao_Paulo     # default: `timezone` in config.yaml, else the system zone
max_parallel: 3                 # steps running at the same time (>= 1, default 4)
max_active_runs: 1              # runs of THIS pipeline at the same time (default 1)
timeout_minutes: 120            # stop the whole run after N minutes (status TIMEOUT)

env:                            # passed to every step; ${VAR} and ${VAR:-default} accepted
  DB_HOST: ${FINANCE_DB_HOST:-localhost}

notifications:
  teams: ${TEAMS_WEBHOOK_FINANCE}   # Workflows webhook URL (keep it in flowa-core/.env)
  on: [failure, recovery]           # success | failure | recovery | always
  ai_analysis: true                 # send failed logs to the AI provider (opt-in)

schedule:
  days: Mon-Fri                 # "All Days" | "Mon,Wed" | [Mon, Tue] | "Mon-Fri" | weekdays
                                # | weekends — any case; seg,ter,qua,qui,sex,sab,dom too
  mode: interval                # once | times | interval | cron
  # once:     at: "07:30"
  # times:    times: ["08:00", "12:30", "18:00"]
  # cron:     cron: "*/15 8-18 * * 1-5"      (standard crontab: 0/7 = Sunday)
  start: "08:00"                # interval: window start...
  end: "18:00"                  # ...and end (end < start = the window crosses midnight)
  interval_minutes: 60
  until_success: false          # interval/times: stop for the day after the first success
  exclude_dates: ["2026-12-25"]
  exclude_holidays: BR-SP       # skip public holidays: country code, optional subdivision
                                # (needs: pip install "flowa-core[holidays]")

trigger:                        # also run after other pipelines (with or without a schedule)
  after: [crm_extract]          # pipeline IDs; with several, after ALL of them
  on: success                   # success | failure | always

steps:
  - name: extract               # unique within the pipeline
    run: python scripts/extract.py
    working_dir: .              # relative to the project root (the folder with flowa-core/)
    retries: 2                  # total attempts = retries + 1; all kept in one log file
    retry_delay_seconds: 30     # backoff: 30, 60, 120...
    timeout_seconds: 600

  - name: validate
    run: scripts/validate.py    # .py → python, .sh → bash, .bat → cmd /c, .ps1 → powershell
    depends_on: extract         # a name or a list of names

  - name: report
    run: python scripts/report.py
    depends_on: [validate]
    continue_on_error: true     # if it fails (FAILED_IGNORED), dependents still run

  - name: heavy_transform
    run: python scripts/transform.py
    depends_on: extract
    use_uv: true                # run as `uv run python ...`
    env:
      CHUNK_SIZE: "50000"
```

Check a file with `flowa validate flowa-core/pipelines/finance_etl.yaml`: unknown keys (typos
such as `depend_on`), invalid values, unknown dependencies and cycles are reported with the
file, the step and the field.

### Older pipeline files

Files written for flowa 0.2.x are still valid:

- `teams_chat: <url>` is the same as `notifications: {teams: <url>, on: [success, failure]}`;
  those pipelines keep following `ai.analyze_errors` from `config.yaml` for the AI analysis.
- A `schedule` without `mode` means `once` when it has `at`, otherwise `interval`.
- `days: "All Days"` and `"AllDays"` are accepted; so is `use_uv` at the pipeline level.

When such a file is saved from the web UI it is converted to the format above; the editor shows
the diff before writing, and comments in the file are kept.

---

## Security

Editing or triggering a pipeline means running commands on the server, so flowa protects
its API even on a single machine.

### Access token

Every API call needs `Authorization: Bearer <token>` (only `/health` is public). The token is:

1. the `FLOWA_TOKEN` environment variable, or
2. `server.auth_token` in `flowa-core/config.yaml`, or
3. a random token generated on the first start and saved in `flowa-core/data/token`
   (readable only by its owner on Linux/macOS).

```bash
TOKEN=$(cat flowa-core/data/token)
curl -H "Authorization: Bearer $TOKEN" http://127.0.0.1:8000/pipelines
```

`flowa server --no-auth` disables the token, but only on a loopback host (`127.0.0.1`,
`localhost`). The server refuses to start on `0.0.0.0` without a token.

Requests whose `Host` header is unknown are rejected (protection against DNS rebinding).
Loopback names and the machine's own names/addresses are accepted; add others, such as a
DNS alias, in `config.yaml`:

```yaml
server:
  allowed_hosts: [flowa.mycompany.local]
```

### Secrets in pipelines: `.env` and `${VAR}`

Keep webhook URLs, passwords and keys out of the YAML files: put them in `flowa-core/.env`
(ignored by git) and reference them with `${VAR}` or `${VAR:-default}`:

```bash
# flowa-core/.env
TEAMS_WEBHOOK_FINANCE=https://prod-00.westus.logic.azure.com:443/workflows/...
FINANCE_DB_PASSWORD=...
```

```yaml
notifications:
  teams: ${TEAMS_WEBHOOK_FINANCE}
env:
  DB_PASSWORD: ${FINANCE_DB_PASSWORD}
  DB_HOST: ${FINANCE_DB_HOST:-localhost}
```

- Variables already set in the environment win over `.env`.
- A `${VAR}` without value and without default is a validation error (`flowa validate`).
- `run:` commands are **not** interpolated: use your shell's own syntax there (`$VAR`,
  `%VAR%`); every variable of `.env`, `env:` (pipeline) and `env:` (step) reaches the process.
- Write `$${` for a literal `${`.

The API never returns webhook URLs (only `has_teams` and the host), and logs mask API keys,
tokens, passwords and webhook URLs.

### TLS and corporate proxies

Certificates are always verified for Teams and AI calls. Behind a proxy that re-signs TLS
traffic, point flowa to the proxy's CA instead of disabling verification:

```yaml
tls:
  ca_bundle: "C:/certs/corporate-ca.pem"   # or set REQUESTS_CA_BUNDLE / SSL_CERT_FILE
```

`ssl_verify: false` under `teams:` or `ai:` still works (with a warning in the log).

### Personal data (LGPD) and AI analysis

AI analysis is **opt-in per pipeline** (`notifications.ai_analysis: true`). Before a log is
sent to a provider, CPF, CNPJ, e-mails, phone numbers, keys, tokens and passwords are masked
(`ai.redact: true`, the default). For analysis that never leaves your network, use the
`ollama` provider with a local model.

---

## Teams Notifications

### Setup

**1. Create a Workflows webhook in Microsoft Teams.**

Office 365 connectors ("Incoming Webhook") were retired by Microsoft in May 2026: their
`*.webhook.office.com` URLs no longer deliver messages. Use a **Workflows** (Power Automate)
webhook instead — it accepts the Adaptive Card flowa sends:

- In Teams, open the channel → `...` → **Workflows**
- Pick the template **"Post to a channel when a webhook request is received"**
- Choose the team and channel, finish the wizard and copy the URL it shows

Notes about Workflows: messages are posted by the Workflows bot (not a custom name/icon), and the
flow belongs to the person who created it — add a co-owner or use a service account so it keeps
working if that person leaves.

**2. Add the URL to your pipeline:**

```yaml
name: my_pipeline
teams_chat: https://prod-00.westus.logic.azure.com:443/workflows/...
```

**3. (Optional) Customize the card appearance:**

```bash
flowa teams-init
```

This adds a `teams:` section to `flowa-core/config.yaml`. Edit it to change images, colors,
icons and more:

```yaml
teams:
  app_name: My Company ETL     # name shown on the card header
  hostname: prod-server-01     # machine identifier (default: system hostname)
  icons:
    success: "✅"
    failure: "❌"
    ai: "🤖"
  images:
    success: "https://..."     # "" hides the image
    failure: "https://..."
    size: Large                # Small | Medium | Large | ExtraLarge
    style: Person              # Default (rectangle) | Person (circle)
  colors:
    success: good              # good | accent | dark | light | default
    failure: attention         # attention | warning | dark | default
  show_details: true           # show the error log excerpt in the card
  max_details_chars: 700
  show_ai_analysis: true       # show the AI analysis section (if configured)
  timeout: 10                  # seconds before giving up on the request
```

> **Upgrading from 0.2.x:** `flowa-core/teams_config.py` still works but is deprecated, because
> it is executed as Python code. Run `flowa teams-init`, copy your values into the new
> `teams:` section and delete the `.py` file. Values in `config.yaml` win over the `.py` file.

### Using different channels per team

Each pipeline can notify a different channel. Just set a different `teams_chat` URL:

```yaml
# finance_etl.yaml
name: Finance ETL
teams_chat: https://...webhook-finance...

# ops_monitor.yaml
name: Ops Monitor
teams_chat: https://...webhook-ops...
```

### Alert: run taking longer than usual

While the server runs, flowa checks the active runs every minute. When a run has been going for
longer than the **p95** of the pipeline's successful runs of the last 30 days times a factor, it
logs a warning and, if the pipeline has a Teams webhook, sends a card (once per run):

```yaml
# flowa-core/config.yaml
alerts:
  duration_factor: 2   # default 2; 0 turns the alert off
  min_runs: 5          # successful runs needed before alerting (default 5)
```

The factor can also be changed in **settings**.

---

## AI Error Analysis

When a pipeline fails, flowa can send the error log to an LLM and include the diagnosis in the Teams notification. Pipelines opt in with `notifications.ai_analysis: true`; pipelines that still use the legacy `teams_chat` field follow `ai.analyze_errors`. Personal data and secrets are masked first (see [Security](#security)).

### Setup

Edit `flowa-core/config.yaml` (created by `flowa init`):

```yaml
ai:
  # Which provider to use. Options: groq | claude | gemini | openai | ollama | none
  provider: groq

  # Set false to disable analysis without changing the provider.
  analyze_errors: true

  groq:
    api_key: "gsk_..."
    model: "openai/gpt-oss-120b"   # default model
    max_tokens: 2000               # includes the model's reasoning
    timeout: 30

  claude:
    api_key: "sk-ant-..."
    model: "claude-haiku-5-5"

  gemini:
    api_key: "AIza..."
    model: "gemini-3.8-flash"

  openai:
    api_key: "sk-..."
    model: "gpt-6-luna"

  ollama:                          # local, no key needed
    base_url: "http://localhost:11434/v1"
    model: "llama3.2"
```

Only configure the provider you want to use. The others are ignored. `model`, `max_tokens`
and `timeout` are optional; the defaults above were checked against each provider's
documentation in October 2026. Providers retire models often: when a call fails, the log says
which provider and model failed, the provider's error message and which setting to change.
Model IDs that were already shut down and were written by older `flowa init` templates
(`gemini-1.5-flash`, `llama-3.3-70b-versatile`) are replaced automatically, with a warning.

### What the AI receives

When a step fails, flowa reads the step's log file and sends the last 3000 characters to the LLM with this context:

> *"You are a senior Python engineer. Analyze the pipeline failure below and return: 1. Probable cause, 2. How to fix it, 3. Suspicious line, 4. Fix example."*

The response is included in the Teams card under the "👾 Análise automática (IA)" section.

---

## Dependencies Between Pipelines

A pipeline can run after others finish. Draw an arrow on the **map** screen (from the right
handle of A to B), or write it in B's file:

```yaml
# sales_report.yaml
name: Sales Report
trigger:
  after: [finance_etl, crm_sync]
  on: success
steps:
  - name: build
    run: python scripts/report.py
```

- `on: success` (default) starts B when the upstream run ends `SUCCESS`; `failure` when it ends
  `FAILED` or `TIMEOUT`; `always` in both cases. A stopped run never triggers anything.
- With several pipelines in `after`, B starts when **all** of them have finished that way since
  B's last dependency-triggered run.
- B receives the upstream's logical date (`FLOWA_LOGICAL_DATE`, see
  [Run parameters](#run-parameters-and-context-variables)); its run shows
  **trigger: dependency, by: run #N**.
- B can also have its own `schedule`. A paused B (`enabled: false`) is not triggered. If B is
  still running, the trigger is recorded as a missed run (`overlap`).
- Triggers work when the scheduler runs (`flowa server`, `flowa start`); `flowa run` and
  `flowa server --no-scheduler` never start other pipelines.
- Cycles between pipelines (A after B after A) and unknown IDs are validation errors.

![Map](https://raw.githubusercontent.com/gustavosegre/flowa/main/docs/screenshots/map.png)

---

## Workspaces

Add `workspace` to any pipeline to group it in the UI. Flowa automatically collects all pipelines with the same workspace into a collapsible section:

```yaml
# etl_vendas.yaml
name: ETL Vendas
workspace: Comercial

# etl_estoque.yaml
name: ETL Estoque
workspace: Comercial

# folha_pagamento.yaml
name: Folha de Pagamento
workspace: RH
```

Result in the UI: two collapsible groups — `Comercial` (2 pipelines) and `RH` (1 pipeline). Pipelines without `workspace` appear below the groups.

---

## CLI Reference

```bash
flowa --version                     # Installed version
flowa init                          # Create flowa-core/ structure + config templates
flowa teams-init                    # Add the Teams card options (teams:) to config.yaml
flowa validate --all                # Validate every pipeline file (exit 1 on errors)
flowa validate <pipeline.yaml>      # Validate one file
flowa run <pipeline.yaml>           # Run a pipeline in the foreground
flowa run <file> -p data=2026-10-01 # ... with parameters (FLOWA_PARAM_DATA)
flowa backfill <id> --from 2026-10-01 --to 2026-10-07   # one run per logical date
flowa start                         # Start the scheduler only (blocking, no API)
flowa server                        # Start API + web UI + scheduler
flowa history                       # Show recent runs (all pipelines, local time)
flowa history <pipeline_name>       # Filter history by pipeline name
flowa logs <run_id>                 # Show step results for a specific run
flowa cleanup --older-than 30d      # Delete old runs, logs and samples (--dry-run to preview)
flowa service install               # Run flowa server in the background (systemd / Windows)
```

`flowa run` exit codes, for Task Scheduler, cron or CI: `0` success, `1` the pipeline did not
succeed, `2` invalid pipeline file, `130` interrupted (Ctrl+C stops the run and its processes).

### Run parameters and context variables

Every step receives these environment variables:

| Variable | Value |
|---|---|
| `FLOWA_RUN_ID` | ID of the run |
| `FLOWA_PIPELINE_ID` | Pipeline ID (file name) |
| `FLOWA_SCHEDULED_FOR` | Fire time in the pipeline's time zone (`2026-10-21T23:30:00-03:00`); empty for manual runs |
| `FLOWA_LOGICAL_DATE` | The `logical_date` parameter if given, else the local date of the scheduled fire, else the local date the run started |
| `FLOWA_PARAM_<NAME>` | One per parameter (name upper-cased) |

Parameters come from `flowa run --param name=value` (repeatable), the `params` object of
`POST /api/pipelines/{id}/run`, or **run with params…** in the UI. Names use letters, digits
and `_`. A rerun keeps the parameters and the logical date of the original run.

**Backfill** — reprocess past days, one run per logical date:

```bash
flowa backfill finance_etl --from 2026-10-01 --to 2026-10-07           # 7 runs
flowa backfill finance_etl --from 2026-10-01 --to 2026-10-07 --dry-run # list the dates
flowa backfill finance_etl --from 2026-10-01 --to 2026-10-02 -p region=south
```

Each run gets `FLOWA_LOGICAL_DATE` (and `logical_date` in its parameters) and appears in the
history as **manual, by backfill**. At most `max_active_runs` run at the same time, in date
order. The command waits for every run; exit code `0` when all succeed, `1` otherwise, `2`
for invalid input (at most 366 days). It runs in its own process: when `flowa server` is
running the same pipeline at that moment, both can overlap.

```python
import os

day = os.environ["FLOWA_LOGICAL_DATE"]  # "2026-10-01"
region = os.environ.get("FLOWA_PARAM_REGION", "all")
```

### `flowa server` options

| Flag | Default | Description |
|---|---|---|
| `--host` | `127.0.0.1` | Bind address |
| `--port` | `8000` | Port |
| `--no-scheduler` | off | Disable the background scheduler (API + UI only) |
| `--no-auth` | off | Disable the access token (loopback host only) |
| `--hide-token` | off | Print the address without the token (the token stays in its file) |
| `--log-file` | — | Append the output to a file (implies `--hide-token`) |

---

## Running as a Service

`flowa service install` keeps `flowa server` running in the background for the project in the
current folder (run it where `flowa-core/` is). The service never prints the access token: open
the address and paste the token from `flowa-core/data/token` (or use `FLOWA_TOKEN`).

```bash
flowa service install                 # detect the method, install and start
flowa service install --port 8080 --dry-run   # show the unit / task / commands only
flowa service status
flowa service uninstall
```

**Linux (systemd).** By default a user unit in `~/.config/systemd/user/flowa.service`, no
root needed. To keep it running without being logged in, run `loginctl enable-linger $USER`
once. `--system` writes `/etc/systemd/system/flowa.service` instead (run with `sudo`; the
service runs as the user who installed it). Logs: `journalctl --user -u flowa -f`. Stopping the
service (`systemctl --user stop flowa`) stops the active runs and their processes; they are
recorded as `STOPPED`.

**Windows.** Without extra tools, flowa creates a Task Scheduler task that starts the server
(without a console window) when you log in; `--system` starts it at boot as SYSTEM instead (run
from an administrator prompt). Output goes to `flowa-core/logs/server.log`. Ending the task
also ends every process of the active runs.

**Windows with NSSM (alternative).** For a real Windows service (starts at boot, appears in
`services.msc`, restarts on failure), install [NSSM](https://nssm.cc/) and put `nssm.exe` on the
PATH; `flowa service install` then uses it automatically (or `--method nssm`). Run it from an
administrator prompt. NSSM stops the server with Ctrl+C, so runs end cleanly. To set it up by
hand:

```bat
nssm install flowa "C:\path\to\.venv\Scripts\python.exe" -m flowa.cli.main server --hide-token
nssm set flowa AppDirectory "C:\path\to\project"
nssm set flowa AppStdout "C:\path\to\project\flowa-core\logs\server.log"
nssm set flowa AppStderr "C:\path\to\project\flowa-core\logs\server.log"
nssm set flowa AppStopMethodConsole 30000
nssm start flowa
```

---

## REST API

All endpoints live under `/api/` and need `Authorization: Bearer <token>`
(see [Security](#security)); `/health` is public. Interactive docs with every parameter:
`http://localhost:8000/docs` (use the **Authorize** button).

| Method | Endpoint | Description |
|---|---|---|
| `GET` | `/api/pipelines` | Pipelines with schedule summary, next run, last 20 runs, success rates, avg/p95 duration |
| `GET` | `/api/pipelines/{id}` | Definition (v2, secrets masked), validation issues, next runs |
| `GET` | `/api/pipelines/{id}/yaml` | The YAML file (secrets masked) |
| `POST` | `/api/pipelines/validate` | Validate a definition (JSON) or YAML text; returns issues, YAML and diff |
| `POST` | `/api/pipelines` | Create `<id>.yaml` |
| `PUT` | `/api/pipelines/{id}` | Save (comments kept, atomic write, previous version kept) |
| `DELETE` | `/api/pipelines/{id}` | Move the file to `pipelines/.trash/` |
| `POST` | `/api/pipelines/{id}/pause` · `/resume` | Write `enabled: false/true` |
| `PUT` | `/api/pipelines/{id}/trigger` | `{"after": [...], "on": "success"}` — run after other pipelines; empty `after` removes it |
| `GET` | `/api/pipelines/{id}/versions` | Previous versions; `/versions/{n}` shows the diff; `POST /versions/{n}/restore` |
| `POST` | `/api/pipelines/{id}/run` | Trigger a run; body `{"only_steps": [...], "params": {...}}` optional; `409` when busy |
| `GET` | `/api/pipelines/{id}/stats?days=30` | Durations p50/p95, daily success rate, per-step stats, top errors |
| `POST` | `/api/schedules/preview` | Next fire times and summary of a `schedule` |
| `GET` | `/api/runs` | History: `pipeline_id`, `status`, `trigger`, `workspace`, `from`, `to`, `limit`, `cursor` |
| `GET` | `/api/runs/{id}` | Run with steps, attempts, Gantt data and resource usage |
| `POST` | `/api/runs/{id}/stop` | Stop an active run (kills its processes) |
| `POST` | `/api/runs/{id}/rerun?from=failed` | New run with failed/skipped steps and their dependents (`from=all`: everything) |
| `GET` | `/api/runs/{id}/steps/{step}/logs` | Log page (`offset`, `limit`; default the last 256 KB) |
| `GET` | `/api/runs/{id}/steps/{step}/logs/stream` | Live log (Server-Sent Events) |
| `GET` | `/api/steps/{step_run_id}/resources` | CPU/RAM time series of a step |
| `GET` | `/api/missed-runs` | Scheduled fires that did not run (busy, too late, server down) |
| `GET` | `/api/calendar?from=&to=` | Per local day: runs by status, missed and predicted fires |
| `GET` | `/api/calendar/{date}` | Runs, missed and predicted fires of one day, by pipeline |
| `GET` | `/api/dashboard` | Every KPI and chart of the dashboard |
| `GET` | `/api/system` · `/api/system/history` | Hardware monitor |
| `GET` | `/metrics` | Prometheus metrics (see [Prometheus Metrics](#prometheus-metrics)) |
| `GET` | `/api/fs?path=` | Names of files/folders inside the project (script picker) |
| `GET`/`PUT` | `/api/layout/{pipeline\|map}/{id}` | Block positions of the visual editor |
| `GET`/`PUT` | `/api/settings` | Editable part of `config.yaml`; API keys are write-only (`has_key`) |

The 0.2.x endpoints (`/pipelines`, `/runs`, `/stats`, `/system`) still answer, now with the
token, and will be removed in 0.5.

**Examples:**

```bash
AUTH="Authorization: Bearer $(cat flowa-core/data/token)"

# Trigger a pipeline (the ID is the yaml file name without extension)
curl -X POST -H "$AUTH" http://localhost:8000/api/pipelines/finance_etl/run
# → {"run_id": 42, "status": "RUNNING", "pipeline_id": "finance_etl"}

# Run status, steps and Gantt data
curl -H "$AUTH" http://localhost:8000/api/runs/42

# Last 256 KB of a step log
curl -H "$AUTH" http://localhost:8000/api/runs/42/steps/extract/logs

# Rerun only what failed
curl -X POST -H "$AUTH" "http://localhost:8000/api/runs/42/rerun?from=failed"

# Failed runs of one pipeline in October (local days)
curl -H "$AUTH" "http://localhost:8000/api/runs?pipeline_id=finance_etl&status=FAILED&from=2026-10-01&to=2026-10-31"
```

<img width="1132" height="739" alt="image" src="https://github.com/user-attachments/assets/0ad298bb-ce4b-441a-ad91-6a3d13e25436" />

<img width="1133" height="248" alt="image" src="https://github.com/user-attachments/assets/fe0e4b50-83f3-427d-bc33-abe2a269ba41" />

<img width="1135" height="477" alt="image" src="https://github.com/user-attachments/assets/858ec210-bd10-4520-b44c-c9fed7d541e4" />

---

## Prometheus Metrics

`GET /metrics` returns the Prometheus text format. It needs the access token, which Prometheus
sends as a bearer token:

```yaml
# prometheus.yml
scrape_configs:
  - job_name: flowa
    metrics_path: /metrics
    authorization:
      credentials_file: /etc/prometheus/flowa_token   # the content of flowa-core/data/token
    static_configs:
      - targets: ["flowa-host:8000"]
```

| Metric | Type | Labels |
|---|---|---|
| `flowa_runs_total` | counter | `pipeline_id`, `status` |
| `flowa_run_duration_seconds` (`_sum`, `_count`) | summary | `pipeline_id` |
| `flowa_last_run_duration_seconds`, `flowa_last_run_success` | gauge | `pipeline_id` |
| `flowa_step_runs_total` | counter | `pipeline_id`, `status` |
| `flowa_missed_runs_total` | counter | `pipeline_id`, `reason` |
| `flowa_active_runs`, `flowa_queued_runs` | gauge | `pipeline_id` |
| `flowa_pipelines` | gauge | `state` (`enabled`, `paused`, `invalid`) |
| `flowa_info` | gauge | `version` |

Counters are computed from the history in the database, so they drop when old runs are
deleted by retention (Prometheus treats that as a counter reset).

---

## Environment Variables

Flowa finds the project root (the folder that contains `flowa-core/`) from `FLOWA_HOME`, or by
walking up from the current directory. Individual paths can still be overridden:

| Variable | Default | Description |
|---|---|---|
| `FLOWA_HOME` | auto | Project root (folder that contains `flowa-core/`) |
| `FLOWA_PIPELINES_DIR` | `flowa-core/pipelines` | Directory scanned for `.yaml`/`.yml` files |
| `FLOWA_LOGS_DIR` | `flowa-core/logs` | Where step log files are stored |
| `FLOWA_DB_PATH` | `flowa-core/data/flowa.db` | SQLite database path |
| `FLOWA_CONFIG_PATH` | `flowa-core/config.yaml` | Global config file path |
| `FLOWA_TOKEN` | — | API access token (see [Security](#security)) |
| `FLOWA_LOG_LEVEL` | `INFO` | Log verbosity (`DEBUG`, `INFO`, `WARNING`, `ERROR`) |
| `FLOWA_DISK_PATH` | `/` (or drive root on Windows) | Disk/partition whose usage is shown in the monitor tab |

---

## Project Layout

```
my-project/
├── flowa-core/
│   ├── pipelines/
│   │   ├── finance_etl.yaml       ← your pipeline definitions
│   │   └── ops_monitor.yaml
│   ├── logs/
│   │   └── finance_etl/                 ← pipeline ID (file name)
│   │       └── 20260618_090000_run42/   ← start time + run ID
│   │           ├── extract.log    ← one log file per step per run (all attempts)
│   │           └── transform.log
│   ├── data/
│   │   ├── flowa.db               ← SQLite, created and migrated automatically
│   │   └── token                  ← API access token (generated on first start)
│   ├── .env                       ← secrets for ${VAR} (keep out of git)
│   └── config.yaml                ← time zone, scheduler, retention, Teams, AI, TLS
└── scripts/
    ├── extract.py
    ├── transform.py
    └── cleanup.sh
```

---

## Status Reference

Steps:

| Status | Meaning |
|---|---|
| `SUCCESS` | Step exited with code 0 |
| `FAILED` | Step failed after all retries — downstream steps are skipped |
| `FAILED_IGNORED` | Step failed but `continue_on_error: true` — downstream continues (shown as "failed (ignored)"; was `FAILED (ignored)` before 0.2.3) |
| `TIMEOUT` | Step exceeded `timeout_seconds` on its last attempt (or the run hit `timeout_minutes`) |
| `SKIPPED` | A required dependency failed, so this step never ran |
| `RUNNING` | Step is currently executing |
| `STOPPED` | Run was cancelled via the UI, the API or a server shutdown |
| `ABORTED` | Flowa stopped unexpectedly while the step ran (marked at the next start) |

Runs: `QUEUED`, `RUNNING`, `SUCCESS`, `FAILED`, `STOPPED`, `TIMEOUT` (run-level
`timeout_minutes`) and `ABORTED`.

---

## License

MIT
