Metadata-Version: 2.4
Name: esp-iot-ci
Version: 0.0.1
Summary: Project-oriented ESP-IDF CI planning, analysis and execution
Author: laride
Author-email: laride <git@laride.dev>
License-Expression: MPL-2.0
License-File: LICENSE
Requires-Dist: tomli>=2 ; python_full_version < '3.11'
Requires-Dist: packaging>=23
Requires-Dist: esp-bool-parser>=0.2.3
Requires-Dist: pytest>=8
Requires-Dist: pytest-embedded-idf>=2
Requires-Dist: pytest-embedded-serial-esp>=2
Requires-Dist: pytest-timeout>=2
Requires-Dist: idf-component-manager>=2
Requires-Dist: pytest>=8 ; extra == 'test'
Requires-Python: >=3.10
Provides-Extra: test
Description-Content-Type: text/markdown

# iot-ci

Project-oriented ESP-IDF CI planning, Python >= 3.10.

The CLI covers candidate planning, IDF-aware matrix analysis, GitLab child
pipeline generation, isolated builds, pytest artifact binding, JSON/JUnit
reports and selective retry plans. The distribution name is **esp-iot-ci**;
`iot-ci` remains the command and `iot_ci` the Python import. Generated jobs use
the future PyPI package as requested; publish it before running those jobs.

## Run

```sh
python -m pip install -e '.[test]'
iot-ci plan --root /path/to/repository --base <MR_BASE_SHA> -o plan.json
iot-ci plan --all -o plan.json
iot-ci plan --force-path components/example -o plan.json
```

`--base` overrides `CI_MERGE_REQUEST_DIFF_BASE_SHA`, then
`CI_COMMIT_BEFORE_SHA`. The comparison is the supplied base to HEAD (not an
implicit new merge-base). `CI_BUILD_ALL=1` selects all projects.
`CI_FORCE_CHANGED_PATHS` is a JSON array of repository-relative paths; these
subtrees are treated as changed and combined with the real diff. Explicit
`--changed` adds changed files. Candidate selection never overrides later build
compatibility rules. Missing selection context exits 3; invalid configuration
exits 2. The eventual analysis job should use:

```yaml
allow_failure:
  exit_codes: [3]
```

This is an integration fragment, not a complete pipeline. No pipeline is
submitted by these commands.

## Root `.iot-ci.toml`

```toml
discover = ["@/components", "@/examples", "@/tools"]
global_dependencies = ["@/tools/ci"]

[idf.matrices]
default = ["v5.5", "latest"]
regression = ["tag:v5.5.5", "branch:release/v5.5,v5.5"]

[idf.overrides]
"v5.5" = "tag:v5.5.5"

[images.build_tags]
"5.5" = "2"

[images.test_tags]
"5.5" = "1"

[dependencies]
build_tools = ["@/tools/cmake_utilities"]

[sdkconfig]
defaults = ["sdkconfig.defaults"]
config_rules = ["sdkconfig.ci.*=", "=defaults"]
```

Overrides are exact after canonicalizing `vX.X` to `release:vX.X`, applied once.
A string `idf` selects a named matrix (omitted means `default`); an array contains
literal references. Supported references:

- `vX.X` / `release:vX.X`: `espressif/idf:release-vX.X`
- `tag:vX.X[.X]`: `espressif/idf:vX.X[.X]`
- `commit:<hex-sha>,vX.X`: internal build image, exact checkout to be performed
  by the execution environment initializer
- `branch:<name>,vX.X`: internal build image, branch checkout
- `latest`: `espressif/idf:latest`
- `docker:<image>`: explicit Docker image

Only internal image tags use the global major.minor mappings; omitted tags are
`1`. Project-level internal image tag suffixes are rejected. Later analysis must
check the actual IDF series against commit/branch hints. Test images default to
`$CI_REGISTRY/ci/images/idf-vX.X-target-test:<tag>` for every source kind. First
release has no project-specific test image override. Digests and SHA metadata
will be recorded by later environment analysis, without subsequent enforcement.

## Node `ci.toml`

```toml
type = "project"
idf = "default"
dependencies = ["@/components/sensor", "&build_tools"]

[sdkconfig]
# Explicit lists replace global lists; extend_* appends.
extend_defaults = ["sdkconfig.extra"]
```

Board Manager nodes use `type = "board-manager"` and a nonempty `boards` array.
Board location resolution belongs to Board Manager. Future execution order is
base defaults -> board defaults -> selected CI config. `config_rules` discovers
separate configurations; it does not concatenate every matching CI file.

Dependency-only nodes use `type = "component"`. Their `dependencies` propagate
changes transitively but they do not create build tasks. Relative paths are
relative to the node; `@/` denotes repository root. Root dependency groups resolve
relative to repository root. Groups can reference other groups; unknown groups
and group-reference cycles are errors. Component dependency cycles are allowed.

A dependency on a node directory creates a graph edge. A dependency on a parent
directory includes descendant nodes. A dependency on a file inherits the closest
owning node's dependencies (conservative selection). File changes belong to the
closest node, while explicit directory dependencies also match all descendants.
Paths are literal file/directory paths, not globs. Paths cannot escape the repo.
Deleted paths are valid dependency inputs and are not required to exist.

CI discovers tracked `ci.toml` files. `--include-untracked` also discovers local
untracked files not excluded by Git ignore rules. Tracked files remain visible
even when ignored. Submodules and directory symlinks are not traversed by Git's
file listing. Baseline configuration is loaded from Git without checkout; old
and new dependency graphs are unioned for selection. Deleted projects cannot
produce new tasks but can propagate changes. Root configuration changes select
all current projects conservatively.

## Development

```sh
PYTEST_DISABLE_PLUGIN_AUTOLOAD=1 python -m pytest tests -q
```

## Analyze and execute

The candidate plan is not a build matrix. Run analysis in the selected IDF image
(or an exported local IDF environment):

```sh
iot-ci analyze --plan plan.json --reference latest -o tasks.json
iot-ci run --plan tasks.json --task <task-id>
iot-ci test --plan tasks.json --case <case-id>
iot-ci report --plan tasks.json -o report.json
iot-ci retry --plan tasks.json --report report.json -o retry.json
```

For branch/commit environments, `iot-ci checkout --reference branch:release/v5.5,v5.5
--destination /tmp/idf --repository <git-url>` fetches the revision, initializes
submodules, checks the actual series, and runs install.sh. Source export.sh in
the calling shell afterwards. Destination must be new; existing checkouts are
never overwritten. Generated jobs do this automatically and reinstall esp-iot-ci
inside the activated environment. All job images must provide Python >=3.10.

Analysis records full IDF version, SHA if available, and `CI_JOB_IMAGE_DIGEST` if
provided by the runner. It does not query a registry to manufacture a digest.
These are provenance records, not enforced identity locks.

Targets default to the current IDF's supported targets; root/project `targets`
can narrow them. Build `enable` clauses are OR, `disable` takes precedence.
Expressions support comparisons, and/or/not, lists and membership. Available
names include IDF_TARGET, IDF_VERSION (semantic version), IDF_VERSION_MAJOR/MINOR/
PATCH, CONFIG_NAME, BOARD, INCLUDE_DEFAULT and macros parsed by esp-bool-parser.
Unknown variable names emit a warning and evaluate as 0, including names in short-circuited expressions. Arbitrary Python,
function calls and attribute access are not supported.

Builds copy the repository into a temporary workspace so relative component
paths remain valid and board-generated files cannot contaminate another task.
Each job runs one variant. `build.commands` is an argv list of idf.py actions
(default `["build"]`), not a shell script. Build outputs live under
`.iot-ci/artifacts/<task-id>/build`; compiler object/static-library caches are
excluded. JSON and JUnit results live under `.iot-ci/results`. Reports include
missing tasks separately from failed tasks. No build/test submits a pipeline.

## Board Manager

A board project declares `type = "board-manager"` and `boards = ["board_name"]`.
The bridge installs esp-bmgr-assist in the active IDF Python environment when missing, resolves component dependencies if necessary, locates the installed
Board Manager component, and delegates discovery to
`BoardConfigGenerator.config_generator.scan_board_directories`. It uses the
returned board chip to expand targets; ambiguous selectors fail. It does not
parse board directory layouts. At execution it invokes the unified legacy
compatibility command `idf.py bmgr -b <name>` and passes generated
board defaults before the selected CI config. The Board Manager version must
provide this discovery API and its chip metadata. No custom project commands
or hardcoded board directories are used.

## Tests

See `examples/pytest.ini` and `examples/pytest_example.py`. Projects with a
`pytest_*.py` in their root automatically enable test discovery; otherwise use
`[test] enabled = true` with `paths`. `enabled = false` disables tests. `test.idf`
uses the same reference/matrix syntax. `test.enable`/`disable` filters variant
eligibility with the same rules as build.

Parameterize target/config/board/app_path/count. Defaults are config `defaults`,
no board, count 1, current project. Multiple DUT parameters use `|` separators
or arrays. Explicit relative app_path values are repository-relative. Every DUT
must map to an eligible task in the selected plan; cases for excluded variants
are omitted. A target must be explicit. Environment markers must be registered
in pytest.ini's `env_markers`; tags are their union with target names (or
`<target>_<count>` for multiple devices). This plugin is loaded explicitly;
remove legacy repository hooks that filter target/env or override build_dir.
The unrelated idf-ci pytest plugin is disabled during collection and execution.

## GitLab

`examples/gitlab-ci.yml` is the parent integration template. `examples/root.toml`
and `examples/project.toml` illustrate the schema. JSON output is also valid YAML:

```sh
iot-ci pipeline analysis --plan .iot-ci/plan.json -o .iot-ci/analysis.json
iot-ci pipeline execution --plan tasks.json --producer analyze-job -o execution.json
```

The parent triggers analysis, then each IDF analysis job triggers an execution
pipeline containing build/test/report stages. There is no third nesting level.
Job names include a readable prefix and stable variant hash. Source/type/version
identities remain distinct even if they report the same major.minor.

`retry` selects failed/missing builds and affected/failed tests. Local execution
can reuse successful `.iot-ci/artifacts`. For a new remote retry pipeline use
`pipeline execution --reuse-pipeline <original-execution-pipeline-id>` to generate
cross-pipeline artifact dependencies for successful build jobs. The retry-plan
producer must publish the plan artifact and be supplied via `--producer`.
Start retries from the parent or a new pipeline, not as another child beneath
execution. Retry success does not retroactively change old failed job statuses;
the integration's merge policy must choose how it accepts retry results.

## Validation boundary

Tests cover planning, expressions, config enumeration, pytest metadata collection,
subprocess build execution (fake idf.py), artifact retention, reports and generated
pipeline dependencies. Local IDF source analysis is exercised separately. Real
GitLab runner scheduling, Docker authentication, hardware flashing and Board
Manager downloads require infrastructure acceptance testing. These tests do not
claim a successful hardware run.

## Lint, format and type checks

Install project dependencies and development tools with `uv sync --group dev`.
Ruff checks Python syntax, common errors and imports; its formatter uses single
quotes and a 120-column line length. Pyrefly checks `src` and `tests` against
Python 3.10 with explicit import roots. Type errors are not globally suppressed.

```sh
uv run --group dev ruff check .
uv run --group dev ruff format --check .
uv run --group dev pyrefly check
```

Apply formatting with `uv run --group dev ruff format .`. Review proposed lint
fixes before using `ruff check --fix`; type-check findings require source review.

## Git hooks (prek)

The `.pre-commit-config.yaml` runs Ruff lint with safe fixes, Ruff formatting,
and whole-project Pyrefly checks. Local hooks use `uv run` so they share the
project's development dependencies rather than maintaining separate hook
versions. Install `uv` first, then:

```sh
uv sync --group dev
uv run --group dev prek install
uv run --group dev prek run --all-files
```

After hooks modify files, review and stage those changes before committing.
In CI, run `uv run --group dev prek run --all-files`. Pyrefly receives no
filename arguments, so it checks both `src` and `tests` together.

## Task hooks and environment variables

Root `.iot-ci.toml` and project `ci.toml` accept the same build/test settings:

```toml
[build.env]
IDF_PY_BUILD_JOBS = "2"
CMAKE_BUILD_PARALLEL_LEVEL = "2"

[build]
hook_timeout = 300

[build.hooks]
before = [["python", "scripts/prepare_assets.py"]]
after = [["python", "scripts/check_firmware.py"]]
finally = [["python", "scripts/cleanup.py"]]

[test.env]
TEST_SERVER_URL = "https://example.test"

[test.hooks]
before = [["python", "scripts/start_server.py"]]
after = [["python", "scripts/export_metrics.py"]]
finally = [["python", "scripts/stop_server.py"]]
```

These scripts are illustrative and must be supplied by the project. Commands
are argv arrays, not shell strings. Use `["bash", "-euo", "pipefail",
"scripts/setup.sh"]` when shell semantics are needed. `$VARIABLE` is not
expanded inside argv or env values: scripts read their inherited environment.
An `export` in one hook cannot change later processes. Secret values should
remain in GitLab variables, not TOML. Full process environments are not copied
into result reports (scripts can of course expose them in their own logs).

Global environment keys are merged with project keys; project keys win. For
hooks, a project-provided list replaces that global stage's list; an omitted
stage inherits it, and an empty list disables it. Numeric/bool env values are
converted to strings. Project hook_timeout overrides the global value, default
300 seconds **per command**. These options are serialized into task plans and
preserved by retries.

Build order: isolated workspace -> Board Manager -> before -> idf.py -> compiler
warning policy -> after -> finally -> artifact collection. Defaults are resolved
after before hooks, allowing a hook to generate a defaults file. The main build
has its own timeout; GitLab job timeouts include hook budgets plus setup margin.

Test order: artifact validation -> before -> pytest -> after -> finally. Test
hooks run in the owning project directory; pytest runs at repository root to
keep collected node IDs and firmware bindings consistent. Test hook changes are
not copied into an isolated build checkout. Each test case runs its own hooks.

A failed before skips the main action and after. After only runs on success and
its failure fails the task. Finally attempts **all** cleanup commands even after
one fails. A cleanup failure fails an otherwise successful task; if a primary
failure already occurred, its stage/error remain primary and cleanup_errors are
recorded separately. Finally cannot run after a runner hard kill, and cannot
run when workspace/environment setup has failed before the lifecycle starts.
Timeout handling kills subprocess groups on POSIX to avoid orphaned children.

Available execution-time paths: IOT_CI_PROJECT_DIR, IOT_CI_REPO_ROOT,
IOT_CI_TASK_ID, and (build only) IOT_CI_BUILD_DIR. These framework variables are
set after project env, so binding paths cannot be accidentally overwritten.
Build before/after/finally run in the isolated project directory. A daemon
started by a hook must detach/return and be stopped by a finally hook.

Result JSON contains ordered stages, timings, status, failed_stage and cleanup
errors. Build hook logs are under artifacts/<id>/hooks; test hook logs under
results/<id>-hooks. Both pytest JUnit and the task lifecycle JUnit are published
so an after-hook failure is visible even when pytest passed. Hooks are task-level,
not job-level package initialization or matrix-discovery callbacks.
