Skip to content

API reference

The public Python API is intentionally small at this stage.

CLI entrypoint

automax.cli.cli

Command-line interface for Automax engine.

approval()

Create and verify approval gate files.

Source code in src/automax/cli/cli.py
814
815
816
@cli.group()
def approval() -> None:
    """Create and verify approval gate files."""

approval_create(job_path, inventory_path, vars_path, secrets_path, cli_vars, limit, exclude, tags, skip_tags, plugin_path, approved_by, reason, expires_at, output_path)

Create an approval gate file from the current secret-free review.

Source code in src/automax/cli/cli.py
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
@approval.command("create")
@_apply_common_options
@click.option("--limit", multiple=True, help="Limit targets. Accepts server, group or group:name.")
@click.option("--exclude", multiple=True, help="Exclude targets. Accepts server, group or group:name.")
@click.option("--tags", multiple=True, help="Approve only substeps matching one of these tags.")
@click.option("--skip-tags", multiple=True, help="Exclude substeps matching one of these tags.")
@click.option("--plugin-path", multiple=True, help="External plugin file, directory or ZIP package.")
@click.option("--approved-by", required=True, help="Operator, ticket or approval identity.")
@click.option("--reason", default="", help="Short approval reason or ticket reference.")
@click.option("--expires-at", help="Optional ISO datetime after which the approval is invalid.")
@click.option("--output", "output_path", required=True, type=click.Path(dir_okay=False), help="Approval JSON file to write.")
def approval_create(
    job_path: str,
    inventory_path: str,
    vars_path: str | None,
    secrets_path: str | None,
    cli_vars: tuple[str, ...],
    limit: tuple[str, ...],
    exclude: tuple[str, ...],
    tags: tuple[str, ...],
    skip_tags: tuple[str, ...],
    plugin_path: tuple[str, ...],
    approved_by: str,
    reason: str,
    expires_at: str | None,
    output_path: str,
) -> None:
    """Create an approval gate file from the current secret-free review."""
    if secrets_path:
        raise click.ClickException("approval files are secret-free; omit --secrets when creating approvals")
    try:
        payload = build_approval_payload(
            _engine(plugin_path),
            approved_by=approved_by,
            reason=reason,
            expires_at=expires_at,
            job_path=job_path,
            inventory_path=inventory_path,
            vars_path=vars_path,
            limit=_split_selectors(limit),
            exclude=_split_selectors(exclude),
            tags=_split_selectors(tags),
            skip_tags=_split_selectors(skip_tags),
            cli_vars=_parse_vars(cli_vars),
        )
        output = write_approval_file(payload, output_path)
    except (AutomaxError, ApprovalError, ValueError, RuntimeError) as exc:
        raise click.ClickException(str(exc)) from exc
    click.echo(f"Wrote approval gate {output}")

approval_verify(job_path, inventory_path, vars_path, secrets_path, cli_vars, limit, exclude, tags, skip_tags, plugin_path, approval_path, output_format)

Verify that an approval gate file matches the current review.

Source code in src/automax/cli/cli.py
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
@approval.command("verify")
@_apply_common_options
@click.option("--limit", multiple=True, help="Limit targets. Accepts server, group or group:name.")
@click.option("--exclude", multiple=True, help="Exclude targets. Accepts server, group or group:name.")
@click.option("--tags", multiple=True, help="Verify only substeps matching one of these tags.")
@click.option("--skip-tags", multiple=True, help="Exclude substeps matching one of these tags.")
@click.option("--plugin-path", multiple=True, help="External plugin file, directory or ZIP package.")
@click.option("--approval", "approval_path", required=True, type=click.Path(exists=True, dir_okay=False), help="Approval JSON file to verify.")
@click.option("--format", "output_format", type=click.Choice(["text", "json"]), default="text", show_default=True, help="Output format.")
def approval_verify(
    job_path: str,
    inventory_path: str,
    vars_path: str | None,
    secrets_path: str | None,
    cli_vars: tuple[str, ...],
    limit: tuple[str, ...],
    exclude: tuple[str, ...],
    tags: tuple[str, ...],
    skip_tags: tuple[str, ...],
    plugin_path: tuple[str, ...],
    approval_path: str,
    output_format: str,
) -> None:
    """Verify that an approval gate file matches the current review."""
    if secrets_path:
        raise click.ClickException("approval verification is secret-free; omit --secrets")
    try:
        result = verify_approval_file(
            approval_path,
            _engine(plugin_path),
            job_path=job_path,
            inventory_path=inventory_path,
            vars_path=vars_path,
            limit=_split_selectors(limit),
            exclude=_split_selectors(exclude),
            tags=_split_selectors(tags),
            skip_tags=_split_selectors(skip_tags),
            cli_vars=_parse_vars(cli_vars),
        )
    except (AutomaxError, ApprovalError, ValueError, RuntimeError) as exc:
        raise click.ClickException(str(exc)) from exc
    if output_format == "json":
        click.echo(json.dumps(result, indent=2, sort_keys=True))
        return
    click.echo(f"Approval gate OK: {result['review_sha256']}")
    click.echo(f"Approved by: {result['approved_by']}")

artifacts()

Inspect files captured during a run.

Source code in src/automax/cli/cli.py
2257
2258
2259
@cli.group()
def artifacts() -> None:
    """Inspect files captured during a run."""

artifacts_list(run_id, state_dir)

List artifacts captured for one run.

Source code in src/automax/cli/cli.py
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
@artifacts.command("list")
@click.argument("run_id")
@click.option("--state-dir", default=".automax/runs", show_default=True, help="Run state directory.")
def artifacts_list(run_id: str, state_dir: str) -> None:
    """List artifacts captured for one run."""
    store = StateStore.open_existing(state_dir, run_id)
    for item in store.list_artifacts():
        click.echo(
            f"{item['target']} {item['node_id']} {item['kind']} {item['name']} "
            f"{item['size']}B {item['path']}"
        )

artifacts_path(run_id, state_dir)

Print the artifact directory for one run.

Source code in src/automax/cli/cli.py
2262
2263
2264
2265
2266
2267
2268
@artifacts.command("path")
@click.argument("run_id")
@click.option("--state-dir", default=".automax/runs", show_default=True, help="Run state directory.")
def artifacts_path(run_id: str, state_dir: str) -> None:
    """Print the artifact directory for one run."""
    store = StateStore.open_existing(state_dir, run_id)
    click.echo(str(store.artifacts_dir))

audit_plugins(plugin_path, output_format)

Audit registered plugins for preview, dry-run and manual recovery coverage.

Source code in src/automax/cli/cli.py
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
@plugins.command("audit")
@click.option("--plugin-path", multiple=True, help="External plugin file, directory or ZIP package.")
@click.option(
    "--format",
    "output_format",
    type=click.Choice(["text", "json"]),
    default="text",
    show_default=True,
    help="Output format.",
)
def audit_plugins(plugin_path: tuple[str, ...], output_format: str) -> None:
    """Audit registered plugins for preview, dry-run and manual recovery coverage."""
    payload = audit_plugin_registry(build_builtin_registry(plugin_path))
    if output_format == "json":
        click.echo(json.dumps(payload, indent=2, sort_keys=True))
    else:
        click.echo("Plugin audit:")
        click.echo(f"  checked:  {payload['checked']}")
        click.echo(f"  failures: {payload['failure_count']}")
        if payload["failures"]:
            click.echo("Failures:")
            for failure in payload["failures"]:
                click.echo(f"  - {failure}")
        click.echo(f"Result: {'OK' if payload['ok'] else 'FAILED'}")
    if not payload["ok"]:
        raise click.exceptions.Exit(1)

bundle_run_evidence(run_id, state_dir, output_path)

Write a ZIP evidence bundle for one stored run.

Source code in src/automax/cli/cli.py
1818
1819
1820
1821
1822
1823
1824
1825
1826
@runs.command("bundle")
@click.argument("run_id")
@click.option("--state-dir", default=".automax/runs", show_default=True, help="Run state directory.")
@click.option("--output", "output_path", required=True, type=click.Path(dir_okay=False), help="ZIP bundle output path.")
def bundle_run_evidence(run_id: str, state_dir: str, output_path: str) -> None:
    """Write a ZIP evidence bundle for one stored run."""
    store = StateStore.open_existing(state_dir, run_id)
    output = write_run_evidence_bundle(store, output_path)
    click.echo(f"Wrote {output}")

capabilities()

Inspect job-scoped remote capability requirements.

Source code in src/automax/cli/cli.py
1522
1523
1524
@cli.group()
def capabilities() -> None:
    """Inspect job-scoped remote capability requirements."""

capability_install(job_path, inventory_path, vars_path, secrets_path, cli_vars, limit, exclude, tags, skip_tags, plugin_path, sudo_password_env, verbose, output_format)

Install missing packages for job-scoped capability requirements.

Source code in src/automax/cli/cli.py
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
@capabilities.command("install")
@_apply_common_options
@click.option("--limit", multiple=True, help="Limit targets. Accepts server, group or group:name.")
@click.option("--exclude", multiple=True, help="Exclude targets. Accepts server, group or group:name.")
@click.option("--tags", multiple=True, help="Install dependencies for substeps matching one of these tags.")
@click.option("--skip-tags", multiple=True, help="Skip substeps matching one of these tags.")
@click.option("--plugin-path", multiple=True, help="External plugin file, directory or ZIP package.")
@click.option("--sudo-password-env", help="Environment variable containing the sudo password for package-manager installs.")
@click.option("--verbose", is_flag=True, help="Show successful install command stdout/stderr.")
@click.option(
    "--format",
    "output_format",
    type=click.Choice(["text", "json"]),
    default="text",
    show_default=True,
    help="Output format.",
)
def capability_install(
    job_path: str,
    inventory_path: str,
    vars_path: str | None,
    secrets_path: str | None,
    cli_vars: tuple[str, ...],
    limit: tuple[str, ...],
    exclude: tuple[str, ...],
    tags: tuple[str, ...],
    skip_tags: tuple[str, ...],
    plugin_path: tuple[str, ...],
    sudo_password_env: str | None,
    verbose: bool,
    output_format: str,
) -> None:
    """Install missing packages for job-scoped capability requirements."""
    try:
        payload = _engine(plugin_path).install_capability_requirements_job(
            job_path=job_path,
            inventory_path=inventory_path,
            vars_path=vars_path,
            secrets_path=secrets_path,
            limit=_split_selectors(limit),
            exclude=_split_selectors(exclude),
            tags=_split_selectors(tags),
            skip_tags=_split_selectors(skip_tags),
            cli_vars=_parse_vars(cli_vars),
            sudo_password_env=sudo_password_env,
            progress_callback=_echo_capability_install_event if output_format == "text" else None,
        )
    except (AutomaxError, ValueError, RuntimeError) as exc:
        raise click.ClickException(str(exc)) from exc
    _echo_capability_install_payload(payload, output_format, verbose=verbose)
    if not payload["ok"]:
        raise click.ClickException("one or more targets could not install all missing capability packages")

capability_requirements(job_path, inventory_path, vars_path, secrets_path, cli_vars, limit, exclude, tags, skip_tags, plugin_path, output_format)

Render tool requirements derived from the selected job plan.

Source code in src/automax/cli/cli.py
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
@capabilities.command("requirements")
@_apply_common_options
@click.option("--limit", multiple=True, help="Limit targets. Accepts server, group or group:name.")
@click.option("--exclude", multiple=True, help="Exclude targets. Accepts server, group or group:name.")
@click.option("--tags", multiple=True, help="Show requirements for substeps matching one of these tags.")
@click.option("--skip-tags", multiple=True, help="Hide requirements for substeps matching one of these tags.")
@click.option("--plugin-path", multiple=True, help="External plugin file, directory or ZIP package.")
@click.option(
    "--format",
    "output_format",
    type=click.Choice(["text", "json"]),
    default="text",
    show_default=True,
    help="Output format.",
)
def capability_requirements(
    job_path: str,
    inventory_path: str,
    vars_path: str | None,
    secrets_path: str | None,
    cli_vars: tuple[str, ...],
    limit: tuple[str, ...],
    exclude: tuple[str, ...],
    tags: tuple[str, ...],
    skip_tags: tuple[str, ...],
    plugin_path: tuple[str, ...],
    output_format: str,
) -> None:
    """Render tool requirements derived from the selected job plan."""
    try:
        payload = _engine(plugin_path).capability_requirements_job(
            job_path=job_path,
            inventory_path=inventory_path,
            vars_path=vars_path,
            secrets_path=secrets_path,
            limit=_split_selectors(limit),
            exclude=_split_selectors(exclude),
            tags=_split_selectors(tags),
            skip_tags=_split_selectors(skip_tags),
            cli_vars=_parse_vars(cli_vars),
            check_missing=output_format == "text",
        )
    except (AutomaxError, ValueError, RuntimeError) as exc:
        raise click.ClickException(str(exc)) from exc
    _echo_capabilities_payload(payload, output_format)

check_plugin(path, output_format)

Validate external plugin loading and metadata.

Source code in src/automax/cli/cli.py
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
@plugins.command("check")
@click.argument("path", type=click.Path(exists=True))
@click.option(
    "--format",
    "output_format",
    type=click.Choice(["text", "json"]),
    default="text",
    show_default=True,
    help="Output format.",
)
def check_plugin(path: str, output_format: str) -> None:
    """Validate external plugin loading and metadata."""
    try:
        payload = check_external_plugin_path(path)
    except ValueError as exc:
        raise click.ClickException(str(exc)) from exc
    if output_format == "json":
        click.echo(json.dumps(payload, indent=2, sort_keys=True))
    else:
        click.echo(render_plugin_check_text(payload))
    if not payload["ok"]:
        raise click.exceptions.Exit(1)

check_secrets(job_path, inventory_path, vars_path, secrets_path, cli_vars, limit, exclude, tags, skip_tags, plugin_path, include_all, output_format)

Check the secrets needed by one resolved job without printing values.

Source code in src/automax/cli/cli.py
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
@secrets.command("check")
@_apply_common_options
@click.option("--limit", multiple=True, help="Limit targets. Accepts server, group or group:name.")
@click.option("--exclude", multiple=True, help="Exclude targets. Accepts server, group or group:name.")
@click.option("--tags", multiple=True, help="Check secrets for substeps matching one of these tags.")
@click.option("--skip-tags", multiple=True, help="Skip substeps matching one of these tags.")
@click.option("--plugin-path", multiple=True, help="External plugin file, directory or ZIP package.")
@click.option("--all", "include_all", is_flag=True, help="Include declared secrets not used by the selected job plan.")
@click.option(
    "--format",
    "output_format",
    type=click.Choice(["text", "json"]),
    default="text",
    show_default=True,
    help="Output format.",
)
def check_secrets(
    job_path: str,
    inventory_path: str,
    vars_path: str | None,
    secrets_path: str | None,
    cli_vars: tuple[str, ...],
    limit: tuple[str, ...],
    exclude: tuple[str, ...],
    tags: tuple[str, ...],
    skip_tags: tuple[str, ...],
    plugin_path: tuple[str, ...],
    include_all: bool,
    output_format: str,
) -> None:
    """Check the secrets needed by one resolved job without printing values."""
    try:
        payload = _engine(plugin_path).check_secrets(
            job_path=job_path,
            inventory_path=inventory_path,
            vars_path=vars_path,
            secrets_path=secrets_path,
            limit=_split_selectors(limit),
            exclude=_split_selectors(exclude),
            tags=_split_selectors(tags),
            skip_tags=_split_selectors(skip_tags),
            cli_vars=_parse_vars(cli_vars),
            include_all=include_all,
        )
    except (AutomaxError, ValueError, RuntimeError) as exc:
        raise click.ClickException(str(exc)) from exc

    if output_format == "json":
        click.echo(json.dumps(payload, indent=2, sort_keys=True))
    else:
        click.echo(f"Job: {payload['job']}")
        click.echo(f"Secrets: {payload['secrets_path'] or '-'}")
        for item in payload["secrets"]:
            used = "used" if item.get("used") else "unused"
            click.echo(
                f"{item['name']}  {item['provider']}  "
                f"{item['status']}  {used}  {item['detail']}"
            )
        if not payload["secrets"]:
            click.echo("No secrets referenced by selected job plan")
    if not payload["ok"]:
        raise click.ClickException("one or more secrets failed checks")

cli()

Automax - YAML-driven SSH automation engine.

Source code in src/automax/cli/cli.py
424
425
426
427
@click.group(context_settings={"help_option_names": ["-h", "--help"]})
@click.version_option(version=__version__, prog_name="Automax")
def cli() -> None:
    """Automax - YAML-driven SSH automation engine."""

cli_main()

Console-script entry point.

Source code in src/automax/cli/cli.py
2339
2340
2341
def cli_main() -> None:
    """Console-script entry point."""
    cli()

commands()

Render manual commands for job recovery.

Source code in src/automax/cli/cli.py
1354
1355
1356
@cli.group()
def commands() -> None:
    """Render manual commands for job recovery."""

coverage_plugins(plugin_path, output_format, output_path, strict)

Print plugin coverage and quality gate results.

Source code in src/automax/cli/cli.py
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
@plugins.command("coverage")
@click.option("--plugin-path", multiple=True, help="External plugin file, directory or ZIP package.")
@click.option(
    "--format",
    "output_format",
    type=click.Choice(["text", "json", "markdown"]),
    default="text",
    show_default=True,
    help="Output format.",
)
@click.option("--output", "output_path", type=click.Path(), help="Write coverage output to a file.")
@click.option("--strict", is_flag=True, help="Exit with status 1 when quality gates fail.")
def coverage_plugins(plugin_path: tuple[str, ...], output_format: str, output_path: str | None, strict: bool) -> None:
    """Print plugin coverage and quality gate results."""
    payload = build_plugin_coverage(build_builtin_registry(plugin_path))
    if output_format == "json":
        rendered = json.dumps(payload, indent=2, sort_keys=True) + "\n"
    elif output_format == "markdown":
        rendered = render_plugin_coverage_markdown(payload)
    else:
        rendered = render_plugin_coverage_text(payload) + "\n"

    if output_path:
        Path(output_path).write_text(rendered, encoding="utf-8")
    else:
        click.echo(rendered, nl=False)
    if strict and not payload["ok"]:
        raise click.exceptions.Exit(1)

describe_plugin(name, plugin_path, as_json)

Describe one registered plugin and its parameters.

Source code in src/automax/cli/cli.py
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
@plugins.command("describe")
@click.argument("name")
@click.option("--plugin-path", multiple=True, help="External plugin file, directory or ZIP package.")
@click.option("--json", "as_json", is_flag=True, help="Print structured JSON metadata.")
def describe_plugin(name: str, plugin_path: tuple[str, ...], as_json: bool) -> None:
    """Describe one registered plugin and its parameters."""
    try:
        description = build_builtin_registry(plugin_path).describe(name)
    except ValueError as exc:
        raise click.ClickException(str(exc)) from exc

    if as_json:
        click.echo(json.dumps(description, indent=2, sort_keys=True))
        return

    click.echo(f"Name: {description['name']}")
    click.echo(f"Category: {description['category']}")
    click.echo(f"Description: {description['description'] or '-'}")
    click.echo(f"Remote session: {str(description['opens_remote_session']).lower()}")
    click.echo(f"Dry-run support: {str(description['supports_dry_run']).lower()}")
    click.echo(f"Check mode support: {str(description['supports_check_mode']).lower()}")

    required = description['required_params'] or []
    optional = description['optional_params'] or []
    aliases = description['aliases'] or []
    click.echo("Required params:")
    for item in required:
        click.echo(f"  - {item}")
    if not required:
        click.echo("  - none")

    click.echo("Optional params:")
    for item in optional:
        click.echo(f"  - {item}")
    if not optional:
        click.echo("  - none")

    parameters = description.get("parameters") or []
    if parameters:
        click.echo("Parameters:")
        for parameter in parameters:
            marker = "required" if parameter.get("required") else "optional"
            default = parameter.get("default")
            default_text = f", default={default}" if default is not None else ""
            desc = parameter.get("description") or "-"
            click.echo(
                f"  - {parameter['name']} ({marker}, {parameter.get('type', 'any')}{default_text}): {desc}"
            )

    result_fields = description.get("result_fields") or {}
    if result_fields:
        click.echo("Result fields:")
        for key, value in result_fields.items():
            click.echo(f"  - {key}: {value}")

    examples = description.get("examples") or []
    if examples:
        click.echo("Examples:")
        for item in examples:
            click.echo("---")
            click.echo(item)

    if aliases:
        click.echo("Aliases:")
        for item in aliases:
            click.echo(f"  - {item}")

docs()

Generate documentation from runtime metadata.

Source code in src/automax/cli/cli.py
2284
2285
2286
@cli.group()
def docs() -> None:
    """Generate documentation from runtime metadata."""

doctor(state_dir, as_json)

Inspect the local Automax runtime environment.

Source code in src/automax/cli/cli.py
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
@cli.command()
@click.option("--state-dir", default=".automax/runs", show_default=True, help="Run state directory to check.")
@click.option("--json", "as_json", is_flag=True, help="Print structured JSON diagnostics.")
def doctor(state_dir: str, as_json: bool) -> None:
    """Inspect the local Automax runtime environment."""
    checks = []

    def add(name: str, ok: bool, detail: str) -> None:
        checks.append({"name": name, "ok": bool(ok), "detail": detail})

    version = sys.version_info
    add("python", version >= (3, 9), platform.python_version())
    add("automax", True, __version__)
    add("paramiko", importlib.util.find_spec("paramiko") is not None, "installed" if importlib.util.find_spec("paramiko") else "missing")
    for module, label in (("sqlite3", "sqlite"), ("psycopg", "postgres"), ("pymysql", "mysql"), ("oracledb", "oracle")):
        add(f"database.{label}", importlib.util.find_spec(module) is not None, "installed" if importlib.util.find_spec(module) else "optional driver missing")
    add("mkdocs", importlib.util.find_spec("mkdocs") is not None, "installed" if importlib.util.find_spec("mkdocs") else "optional docs extra missing")
    path = Path(state_dir).expanduser().resolve()
    try:
        path.mkdir(parents=True, exist_ok=True)
        probe = path / ".doctor-write-test"
        probe.write_text("ok", encoding="utf-8")
        probe.unlink()
        add("state-dir", True, str(path))
    except Exception as exc:
        add("state-dir", False, f"{path}: {exc}")
    add("ssh", shutil.which("ssh") is not None, shutil.which("ssh") or "ssh executable not found")
    add("plugins", True, f"{len(build_builtin_registry().names())} builtin plugins")

    blocking = {"python", "state-dir", "plugins"}
    payload = {
        "ok": all(item["ok"] for item in checks if item["name"] in blocking),
        "checks": checks,
    }
    if as_json:
        click.echo(json.dumps(payload, indent=2, sort_keys=True))
    else:
        click.echo("Automax doctor")
        for item in checks:
            status = "OK" if item["ok"] else "WARN"
            click.echo(f"  {status:<4} {item['name']}: {item['detail']}")
    if not payload["ok"]:
        raise click.ClickException("doctor found blocking issues")

explain(job_path, inventory_path, vars_path, secrets_path, cli_vars, limit, exclude, tags, skip_tags, plugin_path, output_format)

Explain the resolved job flow, targets and resume points without creating run state.

Source code in src/automax/cli/cli.py
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
@cli.command()
@_apply_common_options
@click.option("--limit", multiple=True, help="Limit targets. Accepts server, group or group:name.")
@click.option("--exclude", multiple=True, help="Exclude targets. Accepts server, group or group:name.")
@click.option("--tags", multiple=True, help="Explain only substeps matching one of these tags.")
@click.option("--skip-tags", multiple=True, help="Hide substeps matching one of these tags.")
@click.option("--plugin-path", multiple=True, help="External plugin file, directory or ZIP package.")
@click.option("--format", "output_format", type=click.Choice(["text", "json"]), default="text", show_default=True, help="Explanation output format.")
def explain(
    job_path: str,
    inventory_path: str,
    vars_path: str | None,
    secrets_path: str | None,
    cli_vars: tuple[str, ...],
    limit: tuple[str, ...],
    exclude: tuple[str, ...],
    tags: tuple[str, ...],
    skip_tags: tuple[str, ...],
    plugin_path: tuple[str, ...],
    output_format: str,
) -> None:
    """Explain the resolved job flow, targets and resume points without creating run state."""
    try:
        view = _engine(plugin_path).inspect_job(
            job_path=job_path,
            inventory_path=inventory_path,
            vars_path=vars_path,
            secrets_path=secrets_path,
            limit=_split_selectors(limit),
            exclude=_split_selectors(exclude),
            tags=_split_selectors(tags),
            skip_tags=_split_selectors(skip_tags),
            cli_vars=_parse_vars(cli_vars),
        )
    except (AutomaxError, ValueError, RuntimeError) as exc:
        raise click.ClickException(str(exc)) from exc
    if output_format == "json":
        click.echo(json.dumps(view, indent=2, sort_keys=True))
        return
    click.echo(render_explain_text(view), nl=False)

export_run_events(run_id, state_dir, output_format, output_path)

Export the append-only event stream for one stored run.

Source code in src/automax/cli/cli.py
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
@runs.command("events")
@click.argument("run_id")
@click.option("--state-dir", default=".automax/runs", show_default=True, help="Run state directory.")
@click.option(
    "--format",
    "output_format",
    type=click.Choice(["jsonl", "json"]),
    default="jsonl",
    show_default=True,
    help="Event stream output format.",
)
@click.option("--output", "output_path", type=click.Path(dir_okay=False), help="Write event stream to this file instead of stdout.")
def export_run_events(run_id: str, state_dir: str, output_format: str, output_path: str | None) -> None:
    """Export the append-only event stream for one stored run."""
    store = StateStore.open_existing(state_dir, run_id)
    events = store.list_events()
    if output_format == "json":
        rendered = json.dumps(events, indent=2, sort_keys=True, default=str) + "\n"
    else:
        rendered = "".join(json.dumps(event, sort_keys=True, default=str) + "\n" for event in events)
    if output_path:
        output = Path(output_path).expanduser().resolve()
        output.parent.mkdir(parents=True, exist_ok=True)
        output.write_text(rendered, encoding="utf-8")
        click.echo(f"Wrote {output}")
    else:
        click.echo(rendered, nl=False)

export_run_evidence(run_id, state_dir, output_format, output_path)

Export a portable evidence report for one stored run.

Source code in src/automax/cli/cli.py
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
@runs.command("export")
@click.argument("run_id")
@click.option("--state-dir", default=".automax/runs", show_default=True, help="Run state directory.")
@click.option(
    "--format",
    "output_format",
    type=click.Choice(["markdown", "json"]),
    default="markdown",
    show_default=True,
    help="Evidence output format.",
)
@click.option("--output", "output_path", type=click.Path(dir_okay=False), help="Write evidence to this file instead of stdout.")
def export_run_evidence(run_id: str, state_dir: str, output_format: str, output_path: str | None) -> None:
    """Export a portable evidence report for one stored run."""
    store = StateStore.open_existing(state_dir, run_id)
    payload = build_run_evidence(store)
    if output_format == "json":
        rendered = json.dumps(payload, indent=2, sort_keys=True, default=str) + "\n"
    else:
        rendered = render_run_evidence_markdown(payload)
    if output_path:
        output = Path(output_path).expanduser().resolve()
        output.parent.mkdir(parents=True, exist_ok=True)
        output.write_text(rendered, encoding="utf-8")
        click.echo(f"Wrote {output}")
    else:
        click.echo(rendered, nl=False)

export_runbook(job_path, inventory_path, vars_path, secrets_path, cli_vars, limit, exclude, tags, skip_tags, plugin_path, output_format, output_path)

Export a Markdown runbook from a resolved job.

Source code in src/automax/cli/cli.py
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
@runbook.command("export")
@_apply_common_options
@click.option("--limit", multiple=True, help="Limit targets. Accepts server, group or group:name.")
@click.option("--exclude", multiple=True, help="Exclude targets. Accepts server, group or group:name.")
@click.option("--tags", multiple=True, help="Export only substeps matching one of these tags.")
@click.option("--skip-tags", multiple=True, help="Hide substeps matching one of these tags.")
@click.option("--plugin-path", multiple=True, help="External plugin file, directory or ZIP package.")
@click.option("--format", "output_format", type=click.Choice(["markdown"]), default="markdown", show_default=True, help="Runbook output format.")
@click.option("--output", "output_path", type=click.Path(dir_okay=False), help="Output file path. Defaults to stdout.")
def export_runbook(
    job_path: str,
    inventory_path: str,
    vars_path: str | None,
    secrets_path: str | None,
    cli_vars: tuple[str, ...],
    limit: tuple[str, ...],
    exclude: tuple[str, ...],
    tags: tuple[str, ...],
    skip_tags: tuple[str, ...],
    plugin_path: tuple[str, ...],
    output_format: str,
    output_path: str | None,
) -> None:
    """Export a Markdown runbook from a resolved job."""
    try:
        view = _engine(plugin_path).inspect_job(
            job_path=job_path,
            inventory_path=inventory_path,
            vars_path=vars_path,
            secrets_path=secrets_path,
            limit=_split_selectors(limit),
            exclude=_split_selectors(exclude),
            tags=_split_selectors(tags),
            skip_tags=_split_selectors(skip_tags),
            cli_vars=_parse_vars(cli_vars),
        )
    except (AutomaxError, ValueError, RuntimeError) as exc:
        raise click.ClickException(str(exc)) from exc
    if output_format != "markdown":
        raise click.ClickException(f"unsupported runbook format: {output_format}")
    rendered = render_runbook_markdown(view)
    if output_path:
        output = Path(output_path)
        output.parent.mkdir(parents=True, exist_ok=True)
        output.write_text(rendered, encoding="utf-8")
        click.echo(f"Wrote {output}")
        return
    click.echo(rendered, nl=False)

export_schema_command(kind, output_format, output_path)

Export the Automax YAML contract as JSON Schema.

Source code in src/automax/cli/cli.py
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
@schema.command("export")
@click.option(
    "--kind",
    type=click.Choice(["job", "inventory", "vars", "secrets", "all"]),
    default="job",
    show_default=True,
    help="Schema kind to export.",
)
@click.option(
    "--format",
    "output_format",
    type=click.Choice(["json"]),
    default="json",
    show_default=True,
    help="Schema output format. JSON is currently supported; the option is reserved for future formats.",
)
@click.option("--output", "output_path", type=click.Path(dir_okay=False), help="Output file path. Defaults to stdout.")
def export_schema_command(kind: str, output_format: str, output_path: str | None) -> None:
    """Export the Automax YAML contract as JSON Schema."""
    if output_format != "json":
        raise click.ClickException(f"unsupported schema format: {output_format}")
    schema_document = export_schema(kind)
    if output_path:
        output = Path(output_path)
        output.parent.mkdir(parents=True, exist_ok=True)
        with output.open("w", encoding="utf-8") as handle:
            json.dump(schema_document, handle, indent=2, sort_keys=True)
            handle.write("\n")
        click.echo(f"Wrote {output}")
        return
    click.echo(json.dumps(schema_document, indent=2, sort_keys=True) + "\n", nl=False)

generate_plugin_docs(output_path, plugin_path)

Generate Markdown plugin reference from structured metadata.

Source code in src/automax/cli/cli.py
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
@docs.command("generate-plugins")
@click.option("--output", "output_path", required=True, type=click.Path(dir_okay=False), help="Markdown output path.")
@click.option("--plugin-path", multiple=True, help="External plugin file, directory or ZIP package.")
def generate_plugin_docs(output_path: str, plugin_path: tuple[str, ...]) -> None:
    """Generate Markdown plugin reference from structured metadata."""
    registry = build_builtin_registry(plugin_path)
    output = Path(output_path)
    output.parent.mkdir(parents=True, exist_ok=True)
    output.write_text(render_plugin_reference(registry.describe_all()), encoding="utf-8")
    click.echo(f"Wrote {output}")

graph(job_path, inventory_path, vars_path, secrets_path, cli_vars, limit, exclude, tags, skip_tags, plugin_path, output_format, output_path)

Render the resolved job flow as Mermaid, DOT, SVG or PNG.

Source code in src/automax/cli/cli.py
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
@cli.command()
@_apply_common_options
@click.option("--limit", multiple=True, help="Limit targets. Accepts server, group or group:name.")
@click.option("--exclude", multiple=True, help="Exclude targets. Accepts server, group or group:name.")
@click.option("--tags", multiple=True, help="Graph only substeps matching one of these tags.")
@click.option("--skip-tags", multiple=True, help="Hide substeps matching one of these tags.")
@click.option("--plugin-path", multiple=True, help="External plugin file, directory or ZIP package.")
@click.option("--format", "output_format", type=click.Choice(["mermaid", "dot", "svg", "png"]), default="mermaid", show_default=True, help="Graph output format.")
@click.option("--output", "output_path", type=click.Path(dir_okay=False), help="Output path. Defaults to stdout for text formats.")
def graph(
    job_path: str,
    inventory_path: str,
    vars_path: str | None,
    secrets_path: str | None,
    cli_vars: tuple[str, ...],
    limit: tuple[str, ...],
    exclude: tuple[str, ...],
    tags: tuple[str, ...],
    skip_tags: tuple[str, ...],
    plugin_path: tuple[str, ...],
    output_format: str,
    output_path: str | None,
) -> None:
    """Render the resolved job flow as Mermaid, DOT, SVG or PNG."""
    try:
        view = _engine(plugin_path).inspect_job(
            job_path=job_path,
            inventory_path=inventory_path,
            vars_path=vars_path,
            secrets_path=secrets_path,
            limit=_split_selectors(limit),
            exclude=_split_selectors(exclude),
            tags=_split_selectors(tags),
            skip_tags=_split_selectors(skip_tags),
            cli_vars=_parse_vars(cli_vars),
        )
    except (AutomaxError, ValueError, RuntimeError) as exc:
        raise click.ClickException(str(exc)) from exc
    if output_format == "mermaid":
        rendered = render_mermaid(view)
    elif output_format == "dot":
        rendered = render_dot(view)
    elif output_format == "svg":
        rendered = render_svg(view)
    else:
        dot = shutil.which("dot")
        if not dot:
            raise click.ClickException("PNG graph output requires Graphviz 'dot' in PATH")
        if not output_path:
            raise click.ClickException("--output is required for PNG graph output")
        subprocess.run([dot, "-Tpng", "-o", output_path], input=render_dot(view), text=True, check=True)
        click.echo(f"Wrote {output_path}")
        return
    if output_path:
        output = Path(output_path)
        output.parent.mkdir(parents=True, exist_ok=True)
        output.write_text(rendered, encoding="utf-8")
        click.echo(f"Wrote {output}")
        return
    click.echo(rendered, nl=False)

index_plugin_packages(packages, output_path, output_format)

Build a verified external plugin package index.

Source code in src/automax/cli/cli.py
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
@plugins.command("index")
@click.argument("packages", nargs=-1, required=True, type=click.Path(exists=True, dir_okay=False))
@click.option("--output", "output_path", required=True, type=click.Path(dir_okay=False), help="Write the package index JSON file.")
@click.option(
    "--format",
    "output_format",
    type=click.Choice(["text", "json"]),
    default="text",
    show_default=True,
    help="Output format.",
)
def index_plugin_packages(packages: tuple[str, ...], output_path: str, output_format: str) -> None:
    """Build a verified external plugin package index."""
    payload = build_plugin_package_index(list(packages))
    written = write_plugin_package_index(payload, output_path)
    payload = {**payload, "output": str(written)}
    if output_format == "json":
        click.echo(json.dumps(payload, indent=2, sort_keys=True))
    else:
        click.echo(render_plugin_package_index_text(payload))
        click.echo(f"Wrote {written}")
    if not payload["ok"]:
        raise click.exceptions.Exit(1)

init(path, force)

Create an external Automax workspace skeleton.

Source code in src/automax/cli/cli.py
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
@cli.command()
@click.argument("path", type=click.Path(file_okay=False, dir_okay=True))
@click.option("--force", is_flag=True, help="Overwrite generated files when they already exist.")
def init(path: str, force: bool) -> None:
    """Create an external Automax workspace skeleton."""
    root = Path(path).expanduser().resolve()
    files = {
        "jobs/local-smoke.yaml": """apiVersion: automax.io/v1
kind: Job
metadata:
  name: local-smoke
tasks:
  - id: smoke
    targets: all
    steps:
      - id: local
        substeps:
          - id: echo
            use: command.local.run
            with:
              command: \"printf 'hello from automax\\n'\"
""",
        "inventory/local.yaml": """servers:
  controller:
    host: 127.0.0.1
""",
        "vars/local.yaml": """vars:
  message: hello
""",
        "secrets/local.example.yaml": """secrets:
  demo:
    provider: env
    name: AUTOMAX_DEMO_SECRET
""",
        "templates/example.conf.j2": """message={{ vars.message }}
""",
        "README.md": """# Automax workspace

Run the local smoke job with:

```bash
automax validate --strict \
  --job jobs/local-smoke.yaml \
  --inventory inventory/local.yaml \
  --vars vars/local.yaml

automax run \
  --job jobs/local-smoke.yaml \
  --inventory inventory/local.yaml \
  --vars vars/local.yaml
```
""",
    }
    created = []
    for relative, content in files.items():
        destination = root / relative
        if destination.exists() and not force:
            raise click.ClickException(f"refusing to overwrite existing file: {destination}")
        destination.parent.mkdir(parents=True, exist_ok=True)
        destination.write_text(content, encoding="utf-8")
        created.append(destination)
    click.echo(f"Initialized Automax workspace: {root}")
    for item in created:
        click.echo(f"  {item.relative_to(root)}")

init_plugin(name, output_path, force)

Create an external plugin skeleton.

Source code in src/automax/cli/cli.py
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
@plugins.command("init")
@click.argument("name")
@click.option("--output", "output_path", required=True, type=click.Path(), help="Plugin .py file or output directory.")
@click.option("--force", is_flag=True, help="Overwrite the generated plugin file if it already exists.")
def init_plugin(name: str, output_path: str, force: bool) -> None:
    """Create an external plugin skeleton."""
    try:
        output = create_plugin_skeleton(name, output_path, force=force)
    except ValueError as exc:
        raise click.ClickException(str(exc)) from exc
    click.echo(f"Wrote {output}")

install_plugin_package(package, dest_dir, force)

Install a verified external plugin package into a local plugin directory.

Source code in src/automax/cli/cli.py
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
@plugins.command("install")
@click.argument("package", type=click.Path(exists=True, dir_okay=False))
@click.option(
    "--dest",
    "dest_dir",
    default=".automax/plugins",
    show_default=True,
    type=click.Path(file_okay=False),
    help="Local plugin package directory.",
)
@click.option("--force", is_flag=True, help="Overwrite an installed package with the same file name.")
def install_plugin_package(package: str, dest_dir: str, force: bool) -> None:
    """Install a verified external plugin package into a local plugin directory."""
    try:
        payload = install_external_plugin_package(package, dest_dir, force=force)
    except ValueError as exc:
        raise click.ClickException(str(exc)) from exc
    click.echo(render_plugin_install_text(payload))

installed_plugin_packages(dest_dir, output_format)

List installed external plugin packages and verification state.

Source code in src/automax/cli/cli.py
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
@plugins.command("installed")
@click.option(
    "--dest",
    "dest_dir",
    default=".automax/plugins",
    show_default=True,
    type=click.Path(file_okay=False),
    help="Local plugin package directory.",
)
@click.option(
    "--format",
    "output_format",
    type=click.Choice(["text", "json"]),
    default="text",
    show_default=True,
    help="Output format.",
)
def installed_plugin_packages(dest_dir: str, output_format: str) -> None:
    """List installed external plugin packages and verification state."""
    try:
        payload = list_installed_plugin_packages(dest_dir)
    except ValueError as exc:
        raise click.ClickException(str(exc)) from exc
    if output_format == "json":
        click.echo(json.dumps(payload, indent=2, sort_keys=True))
    else:
        click.echo(render_installed_plugin_packages_text(payload))
    if not payload["ok"]:
        raise click.exceptions.Exit(1)

inventory()

Inspect job-scoped inventory resolution.

Source code in src/automax/cli/cli.py
1679
1680
1681
@cli.group()
def inventory() -> None:
    """Inspect job-scoped inventory resolution."""

known_hosts()

Collect known_hosts entries without trusting them automatically.

Source code in src/automax/cli/cli.py
923
924
925
@ssh.group("known-hosts")
def known_hosts() -> None:
    """Collect known_hosts entries without trusting them automatically."""

list_plugins(plugin_path, include_aliases)

List canonical registered builtin and external plugin names.

Source code in src/automax/cli/cli.py
1922
1923
1924
1925
1926
1927
1928
1929
@plugins.command("list")
@click.option("--plugin-path", multiple=True, help="External plugin file, directory or ZIP package.")
@click.option("--include-aliases", is_flag=True, help="Also show plugin aliases, when external plugins define them.")
def list_plugins(plugin_path: tuple[str, ...], include_aliases: bool) -> None:
    """List canonical registered builtin and external plugin names."""
    registry = build_builtin_registry(plugin_path)
    for name in registry.names(include_aliases=include_aliases):
        click.echo(name)

list_runs(state_dir)

List known runs from a state directory.

Source code in src/automax/cli/cli.py
1752
1753
1754
1755
1756
1757
@runs.command("list")
@click.option("--state-dir", default=".automax/runs", show_default=True, help="Run state directory.")
def list_runs(state_dir: str) -> None:
    """List known runs from a state directory."""
    for run in StateStore.list_all_runs(state_dir):
        click.echo(f"{run['run_id']} {run['status']} {run['created_at']} {run['job_path']}")

os()

Inspect target operating-system facts.

Source code in src/automax/cli/cli.py
1475
1476
1477
@cli.group()
def os() -> None:
    """Inspect target operating-system facts."""

os_info(inventory_path, vars_path, secrets_path, cli_vars, limit, exclude, plugin_path, output_format)

Detect OS release facts for selected inventory targets.

Source code in src/automax/cli/cli.py
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
@os.command("info")
@click.option("--inventory", "inventory_path", required=True, type=click.Path(exists=True), help="External inventory YAML path.")
@click.option("--vars", "vars_path", type=click.Path(exists=True), help="External variables YAML path.")
@click.option("--secrets", "secrets_path", type=click.Path(exists=True), help="External secrets YAML path.")
@click.option("--var", "cli_vars", multiple=True, help="Override variable, format KEY=VALUE.")
@click.option("--limit", multiple=True, help="Limit targets. Accepts server, group or group:name.")
@click.option("--exclude", multiple=True, help="Exclude targets. Accepts server, group or group:name.")
@click.option("--plugin-path", multiple=True, help="External plugin file, directory or ZIP package.")
@click.option(
    "--format",
    "output_format",
    type=click.Choice(["text", "json"]),
    default="text",
    show_default=True,
    help="Output format.",
)
def os_info(
    inventory_path: str,
    vars_path: str | None,
    secrets_path: str | None,
    cli_vars: tuple[str, ...],
    limit: tuple[str, ...],
    exclude: tuple[str, ...],
    plugin_path: tuple[str, ...],
    output_format: str,
) -> None:
    """Detect OS release facts for selected inventory targets."""
    try:
        payload = _os_info_payload(
            inventory_path=inventory_path,
            vars_path=vars_path,
            secrets_path=secrets_path,
            cli_vars=cli_vars,
            limit=limit,
            exclude=exclude,
            plugin_path=plugin_path,
        )
    except (AutomaxError, ValueError, RuntimeError) as exc:
        raise click.ClickException(str(exc)) from exc
    _echo_os_info_payload(payload, output_format)

package_plugin(path, output_path, force, automax_requires)

Package checked external plugin sources.

Source code in src/automax/cli/cli.py
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
@plugins.command("package")
@click.argument("path", type=click.Path(exists=True))
@click.option("--output", "output_path", required=True, type=click.Path(dir_okay=False), help="ZIP package path.")
@click.option("--force", is_flag=True, help="Overwrite the package if it already exists.")
@click.option("--automax-requires", default=">=1.0.0", show_default=True, help="Automax version range written to the package manifest.")
def package_plugin(path: str, output_path: str, force: bool, automax_requires: str) -> None:
    """Package checked external plugin sources."""
    try:
        output = package_external_plugin_path(
            path,
            output_path,
            force=force,
            automax_requires=automax_requires,
        )
    except ValueError as exc:
        raise click.ClickException(str(exc)) from exc
    click.echo(f"Wrote {output}")

plan(job_path, inventory_path, vars_path, secrets_path, cli_vars, limit, exclude, tags, skip_tags, plugin_path, check_mode, diff_mode, output_format)

Print the execution plan without running the job.

Source code in src/automax/cli/cli.py
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
@cli.command()
@_apply_common_options
@click.option("--limit", multiple=True, help="Limit targets. Accepts server, group or group:name.")
@click.option("--exclude", multiple=True, help="Exclude targets. Accepts server, group or group:name.")
@click.option("--tags", multiple=True, help="Show only substeps matching one of these tags.")
@click.option("--skip-tags", multiple=True, help="Hide substeps matching one of these tags.")
@click.option("--plugin-path", multiple=True, help="External plugin file, directory or ZIP package.")
@click.option("--check", "check_mode", is_flag=True, help="Render a check-mode preview instead of the execution plan.")
@click.option("--diff", "diff_mode", is_flag=True, help="Render file-oriented diff previews instead of the execution plan.")
@click.option("--format", "output_format", type=click.Choice(["text", "json"]), default="text", show_default=True, help="Output format for the execution plan.")
def plan(
    job_path: str,
    inventory_path: str,
    vars_path: str | None,
    secrets_path: str | None,
    cli_vars: tuple[str, ...],
    limit: tuple[str, ...],
    exclude: tuple[str, ...],
    tags: tuple[str, ...],
    skip_tags: tuple[str, ...],
    plugin_path: tuple[str, ...],
    check_mode: bool,
    diff_mode: bool,
    output_format: str,
) -> None:
    """Print the execution plan without running the job."""
    try:
        engine = _engine(plugin_path)
        if check_mode and diff_mode:
            raise click.ClickException("--check and --diff are mutually exclusive")
        if check_mode:
            payload = engine.check_job(
                job_path=job_path,
                inventory_path=inventory_path,
                vars_path=vars_path,
                secrets_path=secrets_path,
                limit=_split_selectors(limit),
                exclude=_split_selectors(exclude),
                tags=_split_selectors(tags),
                skip_tags=_split_selectors(skip_tags),
                cli_vars=_parse_vars(cli_vars),
            )
            _echo_check_payload(payload, output_format)
            if not payload["ok"]:
                raise click.ClickException("check-mode preview found errors")
            return
        if diff_mode:
            payload = engine.diff_job(
                job_path=job_path,
                inventory_path=inventory_path,
                vars_path=vars_path,
                secrets_path=secrets_path,
                limit=_split_selectors(limit),
                exclude=_split_selectors(exclude),
                tags=_split_selectors(tags),
                skip_tags=_split_selectors(skip_tags),
                cli_vars=_parse_vars(cli_vars),
            )
            _echo_diff_payload(payload, output_format)
            return
        rc = engine.run(
            job_path=job_path,
            inventory_path=inventory_path,
            vars_path=vars_path,
            secrets_path=secrets_path,
            plan_only=True,
            limit=_split_selectors(limit),
            exclude=_split_selectors(exclude),
            tags=_split_selectors(tags),
            skip_tags=_split_selectors(skip_tags),
            cli_vars=_parse_vars(cli_vars),
            output_format=output_format,
        )
    except (AutomaxError, ValueError, RuntimeError) as exc:
        raise click.ClickException(str(exc)) from exc
    sys.exit(rc)

plugins()

Inspect plugins.

Source code in src/automax/cli/cli.py
1917
1918
1919
@cli.group()
def plugins() -> None:
    """Inspect plugins."""

render_commands(job_path, inventory_path, vars_path, secrets_path, cli_vars, limit, exclude, tags, skip_tags, plugin_path, output_format)

Render copy/pasteable commands for selected job substeps.

Source code in src/automax/cli/cli.py
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
@commands.command("render")
@_apply_common_options
@click.option("--limit", multiple=True, help="Limit targets. Accepts server, group or group:name.")
@click.option("--exclude", multiple=True, help="Exclude targets. Accepts server, group or group:name.")
@click.option("--tags", multiple=True, help="Render commands for substeps matching one of these tags.")
@click.option("--skip-tags", multiple=True, help="Skip substeps matching one of these tags.")
@click.option("--plugin-path", multiple=True, help="External plugin file, directory or ZIP package.")
@click.option(
    "--format",
    "output_format",
    type=click.Choice(["text", "json"]),
    default="text",
    show_default=True,
    help="Output format.",
)
def render_commands(
    job_path: str,
    inventory_path: str,
    vars_path: str | None,
    secrets_path: str | None,
    cli_vars: tuple[str, ...],
    limit: tuple[str, ...],
    exclude: tuple[str, ...],
    tags: tuple[str, ...],
    skip_tags: tuple[str, ...],
    plugin_path: tuple[str, ...],
    output_format: str,
) -> None:
    """Render copy/pasteable commands for selected job substeps."""
    try:
        payload = _engine(plugin_path).manual_commands_job(
            job_path=job_path,
            inventory_path=inventory_path,
            vars_path=vars_path,
            secrets_path=secrets_path,
            limit=_split_selectors(limit),
            exclude=_split_selectors(exclude),
            tags=_split_selectors(tags),
            skip_tags=_split_selectors(skip_tags),
            cli_vars=_parse_vars(cli_vars),
        )
    except (AutomaxError, ValueError, RuntimeError) as exc:
        raise click.ClickException(str(exc)) from exc
    _echo_manual_commands_payload(payload, output_format)

render_vars(job_path, inventory_path, vars_path, secrets_path, cli_vars, limit, exclude, tags, skip_tags, plugin_path, output_format)

Render final vars, masked secrets and selected nodes for a job.

Source code in src/automax/cli/cli.py
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
@vars.command("render")
@_apply_common_options
@click.option("--limit", multiple=True, help="Limit targets. Accepts server, group or group:name.")
@click.option("--exclude", multiple=True, help="Exclude targets. Accepts server, group or group:name.")
@click.option("--tags", multiple=True, help="Render context for substeps matching one of these tags.")
@click.option("--skip-tags", multiple=True, help="Skip substeps matching one of these tags.")
@click.option("--plugin-path", multiple=True, help="External plugin file, directory or ZIP package.")
@click.option(
    "--format",
    "output_format",
    type=click.Choice(["text", "json"]),
    default="text",
    show_default=True,
    help="Output format.",
)
def render_vars(
    job_path: str,
    inventory_path: str,
    vars_path: str | None,
    secrets_path: str | None,
    cli_vars: tuple[str, ...],
    limit: tuple[str, ...],
    exclude: tuple[str, ...],
    tags: tuple[str, ...],
    skip_tags: tuple[str, ...],
    plugin_path: tuple[str, ...],
    output_format: str,
) -> None:
    """Render final vars, masked secrets and selected nodes for a job."""
    try:
        payload = _engine(plugin_path).render_vars_job(
            job_path=job_path,
            inventory_path=inventory_path,
            vars_path=vars_path,
            secrets_path=secrets_path,
            limit=_split_selectors(limit),
            exclude=_split_selectors(exclude),
            tags=_split_selectors(tags),
            skip_tags=_split_selectors(skip_tags),
            cli_vars=_parse_vars(cli_vars),
        )
    except (AutomaxError, ValueError, RuntimeError) as exc:
        raise click.ClickException(str(exc)) from exc
    _echo_vars_payload(payload, output_format)

resume(run_id, state_dir, from_node, limit, exclude, tags, skip_tags, cli_vars, skip_successful, only_failed, dry_run, check_mode, lock, lock_scope, lock_timeout, preflight_capabilities, sudo_password_env, output_format)

Resume an existing run from failed or explicit checkpoint.

Source code in src/automax/cli/cli.py
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
@cli.command()
@click.argument("run_id")
@click.option("--state-dir", default=".automax/runs", show_default=True, help="Run state directory.")
@click.option("--from", "from_node", help="Override restart checkpoint node.")
@click.option("--limit", multiple=True, help="Limit targets. Accepts server, group or group:name.")
@click.option("--exclude", multiple=True, help="Exclude targets. Accepts server, group or group:name.")
@click.option("--tags", multiple=True, help="Resume only substeps matching one of these tags.")
@click.option("--skip-tags", multiple=True, help="Skip substeps matching one of these tags.")
@click.option("--var", "cli_vars", multiple=True, help="Override variable, format KEY=VALUE.")
@click.option("--skip-successful", is_flag=True, help="Do not rerun nodes already marked successful in this run.")
@click.option("--only-failed", is_flag=True, help="Rerun only nodes currently marked failed in this run.")
@click.option("--dry-run", is_flag=True, help="Validate and simulate actions without changing targets.")
@click.option("--check", "check_mode", is_flag=True, help="Render a check-mode preview without creating run state.")
@click.option("--lock", is_flag=True, help="Acquire job/target locks before executing.")
@click.option("--lock-scope", type=click.Choice(["job", "target", "both"]), default="both", show_default=True, help="Lock job, targets or both.")
@click.option("--lock-timeout", type=float, default=0.0, show_default=True, help="Seconds to wait for locks.")
@click.option("--preflight-capabilities", is_flag=True, help="Check remote tools required by the selected job before execution.")
@click.option("--sudo-password-env", help="Environment variable containing the sudo password for sudo-enabled remote substeps.")
@click.option("--format", "output_format", type=click.Choice(["text", "json"]), default="text", show_default=True, help="Output format for the final resume summary.")
def resume(
    run_id: str,
    state_dir: str,
    from_node: str | None,
    limit: tuple[str, ...],
    exclude: tuple[str, ...],
    tags: tuple[str, ...],
    skip_tags: tuple[str, ...],
    cli_vars: tuple[str, ...],
    skip_successful: bool,
    only_failed: bool,
    dry_run: bool,
    check_mode: bool,
    lock: bool,
    lock_scope: str,
    lock_timeout: float,
    preflight_capabilities: bool,
    sudo_password_env: str | None,
    output_format: str,
) -> None:
    """Resume an existing run from failed or explicit checkpoint."""
    try:
        rc = _engine().resume(
            run_id=run_id,
            state_dir=state_dir,
            from_node=from_node,
            dry_run=dry_run,
            limit=_split_selectors(limit),
            exclude=_split_selectors(exclude),
            tags=_split_selectors(tags),
            skip_tags=_split_selectors(skip_tags),
            cli_vars=_parse_vars(cli_vars),
            skip_successful=skip_successful,
            only_failed=only_failed,
            output_format=output_format,
            sudo_password_env=sudo_password_env,
        )
    except (AutomaxError, ValueError, RuntimeError) as exc:
        raise click.ClickException(str(exc)) from exc
    sys.exit(rc)

review(job_path, inventory_path, vars_path, secrets_path, cli_vars, limit, exclude, tags, skip_tags, plugin_path, output_format, output_path)

Build a masked pre-run operator review report.

Source code in src/automax/cli/cli.py
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
@cli.command()
@_apply_common_options
@click.option("--limit", multiple=True, help="Limit targets. Accepts server, group or group:name.")
@click.option("--exclude", multiple=True, help="Exclude targets. Accepts server, group or group:name.")
@click.option("--tags", multiple=True, help="Review only substeps matching one of these tags.")
@click.option("--skip-tags", multiple=True, help="Hide substeps matching one of these tags.")
@click.option("--plugin-path", multiple=True, help="External plugin file, directory or ZIP package.")
@click.option("--format", "output_format", type=click.Choice(["markdown", "json"]), default="markdown", show_default=True, help="Review output format.")
@click.option("--output", "output_path", type=click.Path(dir_okay=False), help="Write the review report to this file. Defaults to stdout.")
def review(
    job_path: str,
    inventory_path: str,
    vars_path: str | None,
    secrets_path: str | None,
    cli_vars: tuple[str, ...],
    limit: tuple[str, ...],
    exclude: tuple[str, ...],
    tags: tuple[str, ...],
    skip_tags: tuple[str, ...],
    plugin_path: tuple[str, ...],
    output_format: str,
    output_path: str | None,
) -> None:
    """Build a masked pre-run operator review report."""
    selectors = {
        "limit": _split_selectors(limit),
        "exclude": _split_selectors(exclude),
        "tags": _split_selectors(tags),
        "skip_tags": _split_selectors(skip_tags),
    }
    parsed_cli_vars = _parse_vars(cli_vars)

    if output_path:
        if secrets_path:
            raise click.ClickException(
                "--output cannot be used together with --secrets. "
                "Print the review report to stdout, or run without --secrets for a saved report."
            )
        try:
            saved_payload = build_saved_operator_review(
                _engine(plugin_path),
                job_path=job_path,
                inventory_path=inventory_path,
                vars_path=vars_path,
                cli_vars=parsed_cli_vars,
                **selectors,
            )
        except (AutomaxError, ValueError, RuntimeError) as exc:
            raise click.ClickException(str(exc)) from exc
        saved_report = _render_saved_operator_review_payload(saved_payload, output_format)
        output = Path(output_path)
        output.parent.mkdir(parents=True, exist_ok=True)
        output.write_text(saved_report, encoding="utf-8")
        click.echo(f"Wrote {output}")
        return

    try:
        payload = build_operator_review(
            _engine(plugin_path),
            job_path=job_path,
            inventory_path=inventory_path,
            vars_path=vars_path,
            secrets_path=secrets_path,
            cli_vars=parsed_cli_vars,
            **selectors,
        )
    except (AutomaxError, ValueError, RuntimeError) as exc:
        raise click.ClickException(str(exc)) from exc
    click.echo(_render_operator_review_payload(payload, output_format), nl=False)

run(job_path, inventory_path, vars_path, secrets_path, cli_vars, state_dir, from_node, limit, exclude, tags, skip_tags, plugin_path, dry_run, check_mode, verbose, lock, lock_scope, lock_timeout, preflight_capabilities, sudo_password_env, approval_path, output_format)

Run a job from external YAML definitions.

Source code in src/automax/cli/cli.py
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
@cli.command()
@_apply_common_options
@click.option("--state-dir", default=".automax/runs", show_default=True, help="Run state directory.")
@click.option("--from", "from_node", help="Start from task/step/substep checkpoint node.")
@click.option("--limit", multiple=True, help="Limit targets. Accepts server, group or group:name.")
@click.option("--exclude", multiple=True, help="Exclude targets. Accepts server, group or group:name.")
@click.option("--tags", multiple=True, help="Run only substeps matching one of these tags.")
@click.option("--skip-tags", multiple=True, help="Skip substeps matching one of these tags.")
@click.option("--plugin-path", multiple=True, help="External plugin file, directory or ZIP package.")
@click.option("--dry-run", is_flag=True, help="Validate and simulate actions without changing targets.")
@click.option("--check", "check_mode", is_flag=True, help="Render a check-mode preview without creating run state.")
@click.option("--verbose", is_flag=True, help="Show per-target substep details in check mode.")
@click.option("--lock", is_flag=True, help="Acquire job/target locks before executing.")
@click.option("--lock-scope", type=click.Choice(["job", "target", "both"]), default="both", show_default=True, help="Lock job, targets or both.")
@click.option("--lock-timeout", type=float, default=0.0, show_default=True, help="Seconds to wait for locks.")
@click.option("--preflight-capabilities", is_flag=True, help="Compatibility flag; capability preflight is implicit for normal runs.")
@click.option("--sudo-password-env", help="Environment variable containing the sudo password for sudo-enabled remote substeps.")
@click.option("--approval", "approval_path", type=click.Path(exists=True, dir_okay=False), help="Approval gate JSON file to verify before execution.")
@click.option("--format", "output_format", type=click.Choice(["text", "json"]), default="text", show_default=True, help="Output format for the final run summary.")
def run(
    job_path: str,
    inventory_path: str,
    vars_path: str | None,
    secrets_path: str | None,
    cli_vars: tuple[str, ...],
    state_dir: str,
    from_node: str | None,
    limit: tuple[str, ...],
    exclude: tuple[str, ...],
    tags: tuple[str, ...],
    skip_tags: tuple[str, ...],
    plugin_path: tuple[str, ...],
    dry_run: bool,
    check_mode: bool,
    verbose: bool,
    lock: bool,
    lock_scope: str,
    lock_timeout: float,
    preflight_capabilities: bool,
    sudo_password_env: str | None,
    approval_path: str | None,
    output_format: str,
) -> None:
    """Run a job from external YAML definitions."""
    try:
        engine = _engine(plugin_path)
        if check_mode:
            payload = engine.check_job(
                job_path=job_path,
                inventory_path=inventory_path,
                vars_path=vars_path,
                secrets_path=secrets_path,
                limit=_split_selectors(limit),
                exclude=_split_selectors(exclude),
                tags=_split_selectors(tags),
                skip_tags=_split_selectors(skip_tags),
                cli_vars=_parse_vars(cli_vars),
            )
            _echo_check_payload(payload, output_format, verbose=verbose)
            if not payload["ok"]:
                raise click.ClickException("check-mode preview found errors")
            return
        if approval_path and not dry_run:
            verify_approval_file(
                approval_path,
                engine,
                job_path=job_path,
                inventory_path=inventory_path,
                vars_path=vars_path,
                limit=_split_selectors(limit),
                exclude=_split_selectors(exclude),
                tags=_split_selectors(tags),
                skip_tags=_split_selectors(skip_tags),
                cli_vars=_parse_vars(cli_vars),
            )
        rc = engine.run(
            job_path=job_path,
            inventory_path=inventory_path,
            vars_path=vars_path,
            secrets_path=secrets_path,
            state_dir=state_dir,
            dry_run=dry_run,
            from_node=from_node,
            limit=_split_selectors(limit),
            exclude=_split_selectors(exclude),
            tags=_split_selectors(tags),
            skip_tags=_split_selectors(skip_tags),
            cli_vars=_parse_vars(cli_vars),
            output_format=output_format,
            lock=lock,
            lock_scope=lock_scope,
            lock_timeout=lock_timeout,
            preflight_capabilities=preflight_capabilities,
            sudo_password_env=sudo_password_env,
        )
    except (AutomaxError, ApprovalError, ValueError, RuntimeError) as exc:
        raise click.ClickException(str(exc)) from exc
    sys.exit(rc)

runbook()

Generate operator runbooks from resolved jobs.

Source code in src/automax/cli/cli.py
1073
1074
1075
@cli.group()
def runbook() -> None:
    """Generate operator runbooks from resolved jobs."""

runs()

Inspect stored run states.

Source code in src/automax/cli/cli.py
1747
1748
1749
@cli.group()
def runs() -> None:
    """Inspect stored run states."""

scan_known_hosts_command(hosts, inventory_path, vars_path, secrets_path, cli_vars, limit, exclude, port, timeout, key_types, output_path, append, output_format)

Scan SSH host keys and print fingerprints for operator verification.

Source code in src/automax/cli/cli.py
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
@known_hosts.command("scan")
@click.option("--host", "hosts", multiple=True, help="Host to scan without an inventory file.")
@click.option("--inventory", "inventory_path", type=click.Path(exists=True), help="Inventory YAML path to scan.")
@click.option("--vars", "vars_path", type=click.Path(exists=True), help="External variables YAML path.")
@click.option("--secrets", "secrets_path", type=click.Path(exists=True), help="External secrets YAML path.")
@click.option("--var", "cli_vars", multiple=True, help="Override variable, format KEY=VALUE.")
@click.option("--limit", multiple=True, help="Limit inventory targets. Accepts server, group or group:name.")
@click.option("--exclude", multiple=True, help="Exclude inventory targets. Accepts server, group or group:name.")
@click.option("--port", default=22, show_default=True, type=int, help="SSH port for --host entries.")
@click.option("--timeout", default=5, show_default=True, type=int, help="ssh-keyscan timeout in seconds.")
@click.option("--key-type", "key_types", multiple=True, help="Restrict key type, e.g. ed25519 or rsa.")
@click.option("--output", "output_path", type=click.Path(dir_okay=False), help="Write scanned known_hosts lines to this file.")
@click.option("--append", is_flag=True, help="Append to --output instead of overwriting it.")
@click.option(
    "--format",
    "output_format",
    type=click.Choice(["text", "json"]),
    default="text",
    show_default=True,
    help="Output format.",
)
def scan_known_hosts_command(
    hosts: tuple[str, ...],
    inventory_path: str | None,
    vars_path: str | None,
    secrets_path: str | None,
    cli_vars: tuple[str, ...],
    limit: tuple[str, ...],
    exclude: tuple[str, ...],
    port: int,
    timeout: int,
    key_types: tuple[str, ...],
    output_path: str | None,
    append: bool,
    output_format: str,
) -> None:
    """Scan SSH host keys and print fingerprints for operator verification."""
    try:
        targets = _known_host_targets(
            hosts=hosts,
            inventory_path=inventory_path,
            vars_path=vars_path,
            secrets_path=secrets_path,
            cli_vars=_parse_vars(cli_vars),
            limit=_split_selectors(limit),
            exclude=_split_selectors(exclude),
            port=port,
        )
        entries = scan_known_hosts(targets, timeout=timeout, key_types=key_types)
        output_exists = Path(output_path).expanduser().exists() if output_path else False
        written = write_known_hosts(entries, output_path, append=append) if output_path else None
    except (AutomaxError, KnownHostsError, InventoryError, ValueError, RuntimeError) as exc:
        raise click.ClickException(str(exc)) from exc

    payload = {
        "entries": [entry.__dict__ for entry in entries],
        "output": str(written) if written else None,
        "warning": "Verify fingerprints over a trusted channel before using these host keys.",
    }
    if output_format == "json":
        click.echo(json.dumps(payload, indent=2, sort_keys=True))
        return
    _echo_known_hosts_scan(entries, written=written, append=append, output_exists=output_exists)

schema()

Export machine-readable Automax schemas.

Source code in src/automax/cli/cli.py
2301
2302
2303
@cli.group()
def schema() -> None:
    """Export machine-readable Automax schemas."""

secrets()

Inspect job-scoped secret definitions.

Source code in src/automax/cli/cli.py
1405
1406
1407
@cli.group()
def secrets() -> None:
    """Inspect job-scoped secret definitions."""

show_inventory(job_path, inventory_path, vars_path, secrets_path, cli_vars, limit, exclude, tags, skip_tags, plugin_path, output_format)

Show inventory targets selected by the resolved job.

Source code in src/automax/cli/cli.py
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
@inventory.command("show")
@_apply_common_options
@click.option("--limit", multiple=True, help="Limit targets. Accepts server, group or group:name.")
@click.option("--exclude", multiple=True, help="Exclude targets. Accepts server, group or group:name.")
@click.option("--tags", multiple=True, help="Show targets for substeps matching one of these tags.")
@click.option("--skip-tags", multiple=True, help="Hide substeps matching one of these tags.")
@click.option("--plugin-path", multiple=True, help="External plugin file, directory or ZIP package.")
@click.option(
    "--format",
    "output_format",
    type=click.Choice(["text", "json"]),
    default="text",
    show_default=True,
    help="Output format.",
)
def show_inventory(
    job_path: str,
    inventory_path: str,
    vars_path: str | None,
    secrets_path: str | None,
    cli_vars: tuple[str, ...],
    limit: tuple[str, ...],
    exclude: tuple[str, ...],
    tags: tuple[str, ...],
    skip_tags: tuple[str, ...],
    plugin_path: tuple[str, ...],
    output_format: str,
) -> None:
    """Show inventory targets selected by the resolved job."""
    try:
        payload = _engine(plugin_path).inspect_inventory(
            job_path=job_path,
            inventory_path=inventory_path,
            vars_path=vars_path,
            secrets_path=secrets_path,
            limit=_split_selectors(limit),
            exclude=_split_selectors(exclude),
            tags=_split_selectors(tags),
            skip_tags=_split_selectors(skip_tags),
            cli_vars=_parse_vars(cli_vars),
        )
    except (AutomaxError, ValueError, RuntimeError) as exc:
        raise click.ClickException(str(exc)) from exc

    if output_format == "json":
        click.echo(json.dumps(payload, indent=2, sort_keys=True))
        return

    click.echo(f"Job: {payload['job']}")
    click.echo(f"Inventory: {payload['inventory_path']}")
    click.echo(
        f"Targets: {payload['target_count']} selected, "
        f"{payload['node_count']} planned node(s)"
    )
    for target in payload["targets"]:
        groups = ",".join(target["groups"]) if target["groups"] else "-"
        user = target["user"] or "-"
        click.echo(
            f"{target['name']}  {target['host']}:{target['port']}  "
            f"user={user} groups={groups} nodes={target['nodes']}"
        )

show_run(run_id, state_dir, failed_only, server_name, as_json)

Show one run summary, failed checkpoints and optional node details.

Source code in src/automax/cli/cli.py
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
@runs.command("show")
@click.argument("run_id")
@click.option("--state-dir", default=".automax/runs", show_default=True, help="Run state directory.")
@click.option("--failed", "failed_only", is_flag=True, help="Show only failed nodes in the node table.")
@click.option("--server", "server_name", help="Show node details for one target/server.")
@click.option("--json", "as_json", is_flag=True, help="Print structured JSON output.")
def show_run(run_id: str, state_dir: str, failed_only: bool, server_name: str | None, as_json: bool) -> None:
    """Show one run summary, failed checkpoints and optional node details."""
    store = StateStore.open_existing(state_dir, run_id)
    summary = store.summarize()
    statuses = {NodeStatus.FAILED.value} if failed_only else None
    nodes = store.list_nodes(statuses=statuses, target=server_name) if (failed_only or server_name) else []

    if as_json:
        payload: Dict[str, Any] = dict(summary)
        payload["nodes"] = nodes
        click.echo(json.dumps(payload, indent=2, sort_keys=True, default=str))
        return

    run = summary["run"]
    click.echo(f"Run: {run_id}")
    click.echo(f"Status: {run['status']}")
    click.echo(f"Job: {run['job_path']}")
    click.echo(f"Inventory: {run.get('inventory_path') or '-'}")
    click.echo(f"Vars: {run.get('vars_path') or '-'}")
    click.echo(f"Secrets: {run.get('secrets_path') or '-'}")
    click.echo(f"Created: {run['created_at']}")
    click.echo(f"Updated: {run['updated_at']}")
    click.echo(f"State: {store.run_dir}")
    click.echo("Summary:")
    click.echo(f"  targets: {summary['targets_total']}")
    click.echo(f"  nodes: {summary['nodes_total']}")
    click.echo(f"  success: {summary['status_counts'].get(NodeStatus.SUCCESS.value, 0)}")
    click.echo(f"  warning: {summary['status_counts'].get(NodeStatus.WARNING.value, 0)}")
    click.echo(f"  failed: {summary['status_counts'].get(NodeStatus.FAILED.value, 0)}")
    click.echo(f"  skipped: {summary['status_counts'].get(NodeStatus.SKIPPED.value, 0)}")
    click.echo(f"  changed: {summary['changed_nodes']}")
    click.echo(f"  artifacts: {summary['artifacts_count']}")

    if summary["targets"]:
        click.echo("Targets:")
        for target in summary["targets"]:
            counts = target["status_counts"]
            click.echo(
                "  "
                f"{target['target']} {target['status']} "
                f"changed={target['changed']} "
                f"success={counts.get(NodeStatus.SUCCESS.value, 0)} "
                f"warning={counts.get(NodeStatus.WARNING.value, 0)} "
                f"failed={counts.get(NodeStatus.FAILED.value, 0)} "
                f"skipped={counts.get(NodeStatus.SKIPPED.value, 0)}"
            )

    warning_nodes = summary.get("warning_nodes", [])
    if warning_nodes:
        click.echo("Warning nodes:")
        for node in warning_nodes:
            message = f" {node['message']}" if node.get("message") else ""
            click.echo(f"  {node['target']} {node['node_id']} rc={node['rc']}{message}".rstrip())

    failed_nodes = summary["failed_nodes"]
    if failed_nodes:
        click.echo("Failed nodes:")
        for node in failed_nodes:
            message = f" {node['message']}" if node.get("message") else ""
            click.echo(f"  {node['target']} {node['node_id']} rc={node['rc']}{message}".rstrip())
        first_failed = failed_nodes[0]["node_id"]
        click.echo("Resume:")
        click.echo(f"  automax resume {run_id} --state-dir {state_dir} --skip-successful")
        click.echo(f"  automax resume {run_id} --state-dir {state_dir} --only-failed")
        click.echo(f"  automax resume {run_id} --state-dir {state_dir} --from {first_failed}")

    if failed_only or server_name:
        click.echo("Nodes:")
        if not nodes:
            click.echo("  - none")
        for node in nodes:
            message = f" {node['message']}" if node.get("message") else ""
            click.echo(
                f"  {node['target']} {node['status']} {node['node_id']} "
                f"changed={str(node['changed']).lower()} rc={node['rc']}{message}".rstrip()
            )

    if summary["artifacts_count"]:
        click.echo("Artifacts:")
        click.echo(f"  automax artifacts list {run_id} --state-dir {state_dir}")

ssh()

SSH helper commands.

Source code in src/automax/cli/cli.py
918
919
920
@cli.group()
def ssh() -> None:
    """SSH helper commands."""

uninstall_plugin_package(package, dest_dir, missing_ok)

Remove an installed external plugin package and lock entry.

Source code in src/automax/cli/cli.py
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
@plugins.command("uninstall")
@click.argument("package")
@click.option(
    "--dest",
    "dest_dir",
    default=".automax/plugins",
    show_default=True,
    type=click.Path(file_okay=False),
    help="Local plugin package directory.",
)
@click.option("--missing-ok", is_flag=True, help="Succeed when the package is already absent.")
def uninstall_plugin_package(package: str, dest_dir: str, missing_ok: bool) -> None:
    """Remove an installed external plugin package and lock entry."""
    try:
        payload = uninstall_external_plugin_package(package, dest_dir, missing_ok=missing_ok)
    except ValueError as exc:
        raise click.ClickException(str(exc)) from exc
    click.echo(render_plugin_uninstall_text(payload))

update_plugin_package(package, dest_dir)

Replace an installed external plugin package after verification.

Source code in src/automax/cli/cli.py
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
@plugins.command("update")
@click.argument("package", type=click.Path(exists=True, dir_okay=False))
@click.option(
    "--dest",
    "dest_dir",
    default=".automax/plugins",
    show_default=True,
    type=click.Path(file_okay=False),
    help="Local plugin package directory.",
)
def update_plugin_package(package: str, dest_dir: str) -> None:
    """Replace an installed external plugin package after verification."""
    try:
        payload = update_external_plugin_package(package, dest_dir)
    except ValueError as exc:
        raise click.ClickException(str(exc)) from exc
    click.echo(render_plugin_update_text(payload))

validate(job_path, inventory_path, vars_path, secrets_path, cli_vars, tags, skip_tags, plugin_path, strict)

Validate job, inventory, variables, secrets and plugin parameters.

Source code in src/automax/cli/cli.py
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
@cli.command()
@_apply_common_options
@click.option("--tags", multiple=True, help="Validate plan after keeping only these tags.")
@click.option("--skip-tags", multiple=True, help="Validate plan after skipping these tags.")
@click.option("--plugin-path", multiple=True, help="External plugin file, directory or ZIP package.")
@click.option("--strict", is_flag=True, help="Also reject unknown DSL keys and validate the resolved plan scope.")
def validate(
    job_path: str,
    inventory_path: str,
    vars_path: str | None,
    secrets_path: str | None,
    cli_vars: tuple[str, ...],
    tags: tuple[str, ...],
    skip_tags: tuple[str, ...],
    plugin_path: tuple[str, ...],
    strict: bool,
) -> None:
    """Validate job, inventory, variables, secrets and plugin parameters."""
    try:
        _engine(plugin_path).validate(
            job_path=job_path,
            inventory_path=inventory_path,
            vars_path=vars_path,
            secrets_path=secrets_path,
            cli_vars=_parse_vars(cli_vars),
            tags=_split_selectors(tags),
            skip_tags=_split_selectors(skip_tags),
            strict=strict,
        )
    except (AutomaxError, ValueError, RuntimeError) as exc:
        raise click.ClickException(str(exc)) from exc
    suffix = " strict" if strict else ""
    click.echo(f"Validation{suffix} successful")

vars()

Inspect job-scoped rendered variables.

Source code in src/automax/cli/cli.py
1628
1629
1630
@cli.group()
def vars() -> None:
    """Inspect job-scoped rendered variables."""

verify_plugin_package(package, output_format)

Verify an external plugin package manifest and file checksums.

Source code in src/automax/cli/cli.py
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
@plugins.command("verify-package")
@click.argument("package", type=click.Path(exists=True, dir_okay=False))
@click.option(
    "--format",
    "output_format",
    type=click.Choice(["text", "json"]),
    default="text",
    show_default=True,
    help="Output format.",
)
def verify_plugin_package(package: str, output_format: str) -> None:
    """Verify an external plugin package manifest and file checksums."""
    try:
        payload = verify_external_plugin_package(package)
    except ValueError as exc:
        raise click.ClickException(str(exc)) from exc
    if output_format == "json":
        click.echo(json.dumps(payload, indent=2, sort_keys=True))
    else:
        click.echo(render_plugin_package_verify_text(payload))
    if not payload["ok"]:
        raise click.exceptions.Exit(1)

Core models

automax.core.models

Typed runtime models for the new Automax execution engine.

ExecutionContext dataclass

Runtime context passed to plugins.

Source code in src/automax/core/models.py
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
@dataclass
class ExecutionContext:
    """Runtime context passed to plugins."""

    run_id: str
    dry_run: bool
    job: Dict[str, Any]
    task: Dict[str, Any]
    step: Dict[str, Any]
    substep: Dict[str, Any]
    target: Target
    vars: Dict[str, Any]
    outputs: Dict[str, Any]
    secrets: Dict[str, Any]
    ssh_client: Any = None
    logger: Any = None
    command_timeout: int | None = None
    sudo_password: str | None = None
    step_state: Dict[str, Any] = field(default_factory=dict)

NodeStatus

Bases: str, Enum

Persisted execution status for job nodes.

Source code in src/automax/core/models.py
15
16
17
18
19
20
21
22
23
class NodeStatus(str, Enum):
    """Persisted execution status for job nodes."""

    PENDING = "pending"
    RUNNING = "running"
    SUCCESS = "success"
    WARNING = "warning"
    FAILED = "failed"
    SKIPPED = "skipped"

PluginResult dataclass

Normalized result returned by every plugin.

Source code in src/automax/core/models.py
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
@dataclass
class PluginResult:
    """Normalized result returned by every plugin."""

    ok: bool
    changed: bool = False
    skipped: bool = False
    warning: bool = False
    rc: int = 0
    stdout: str = ""
    stderr: str = ""
    message: str = ""
    data: Dict[str, Any] = field(default_factory=dict)

    @classmethod
    def success(
        cls,
        *,
        changed: bool = False,
        stdout: str = "",
        stderr: str = "",
        rc: int = 0,
        message: str = "",
        data: Optional[Dict[str, Any]] = None,
    ) -> "PluginResult":
        return cls(
            ok=True,
            changed=changed,
            rc=rc,
            stdout=stdout,
            stderr=stderr,
            message=message,
            data=data or {},
        )

    @classmethod
    def failure(
        cls,
        *,
        rc: int = 1,
        stdout: str = "",
        stderr: str = "",
        message: str = "",
        data: Optional[Dict[str, Any]] = None,
    ) -> "PluginResult":
        return cls(
            ok=False,
            changed=False,
            rc=rc,
            stdout=stdout,
            stderr=stderr,
            message=message,
            data=data or {},
        )

    @classmethod
    def skipped_result(cls, message: str = "") -> "PluginResult":
        return cls(ok=True, skipped=True, message=message)


    @classmethod
    def warning_result(
        cls,
        *,
        changed: bool = False,
        rc: int = 0,
        stdout: str = "",
        stderr: str = "",
        message: str = "",
        data: Optional[Dict[str, Any]] = None,
    ) -> "PluginResult":
        return cls(
            ok=True,
            changed=changed,
            warning=True,
            rc=rc,
            stdout=stdout,
            stderr=stderr,
            message=message,
            data=data or {},
        )

Target dataclass

Resolved server target from inventory.

Source code in src/automax/core/models.py
26
27
28
29
30
31
32
33
34
35
36
37
38
39
@dataclass(frozen=True)
class Target:
    """Resolved server target from inventory."""

    name: str
    host: str
    port: int = 22
    user: Optional[str] = None
    password: Optional[str] = None
    key_file: Optional[str] = None
    key_content: Optional[str] = None
    groups: tuple[str, ...] = ()
    vars: Dict[str, Any] = field(default_factory=dict)
    ssh: Dict[str, Any] = field(default_factory=dict)

Engine

automax.core.engine

Automax execution engine.

AutomaxEngine

Load external definitions, validate and execute one job.

Source code in src/automax/core/engine.py
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
class AutomaxEngine:
    """Load external definitions, validate and execute one job."""

    def __init__(
        self,
        *,
        plugin_registry: Optional[PluginRegistry] = None,
        secret_manager: Optional[SecretManager] = None,
        ssh_manager: Optional[SshSessionManager] = None,
        logger: Optional[logging.Logger] = None,
    ):
        self.plugin_registry = plugin_registry or build_builtin_registry()
        self.secret_manager = secret_manager or SecretManager()
        self.ssh_manager = ssh_manager or SshSessionManager()
        self.logger = logger or logging.getLogger("automax")
        self._output_lock = Lock()
        self._print_lock = Lock()

    def run(
        self,
        *,
        job_path: str,
        inventory_path: str,
        vars_path: str | None = None,
        secrets_path: str | None = None,
        state_dir: str = ".automax/runs",
        run_id: str | None = None,
        dry_run: bool = False,
        plan_only: bool = False,
        from_node: str | None = None,
        limit: Iterable[str] = (),
        exclude: Iterable[str] = (),
        tags: Iterable[str] = (),
        skip_tags: Iterable[str] = (),
        cli_vars: Optional[Dict[str, Any]] = None,
        extra_plugin_paths: Iterable[str] = (),
        skip_successful: bool = False,
        only_failed: bool = False,
        output_format: str = "text",
        lock: bool = False,
        lock_scope: str = "both",
        lock_timeout: float = 0,
        preflight_capabilities: bool = False,
        sudo_password_env: str | None = None,
    ) -> int:
        """Execute a new run from external YAML files."""
        self._validate_output_format(output_format)
        registry = self.plugin_registry
        if extra_plugin_paths:
            registry.load_from_paths(extra_plugin_paths)

        documents = self._load_documents(
            job_path=job_path,
            inventory_path=inventory_path,
            vars_path=vars_path,
            secrets_path=secrets_path,
        )
        secrets = self.secret_manager.resolve_all(
            documents["secrets"],
            base_dir=Path(secrets_path).expanduser().resolve().parent if secrets_path else None,
        )
        variables = self._merge_variables(
            documents["vars"], documents["job"].get("vars", {}), cli_vars or {}
        )
        context = {"vars": variables, "secrets": secrets}
        inventory_document = load_inventory_document(inventory_path, context)
        inventory = Inventory(inventory_document, context)
        job = documents["job"]
        self.validate_job(job)
        sudo_password = self._resolve_sudo_password(sudo_password_env)

        run_id = run_id or self._build_run_id(job)
        store = StateStore(state_dir, run_id)
        store.create_run(
            job_path=str(Path(job_path).expanduser()),
            inventory_path=str(Path(inventory_path).expanduser()),
            vars_path=str(Path(vars_path).expanduser()) if vars_path else None,
            secrets_path=str(Path(secrets_path).expanduser()) if secrets_path else None,
            metadata={
                "dry_run": dry_run,
                "from": from_node,
                "limit": list(limit),
                "tags": list(tags),
                "skip_tags": list(skip_tags),
                "skip_successful": skip_successful,
                "only_failed": only_failed,
                "lock": lock,
                "lock_scope": lock_scope,
                "lock_timeout": lock_timeout,
                "preflight_capabilities": preflight_capabilities,
                "sudo_password_env": sudo_password_env,
            },
        )
        store.record_event("job_started", payload={"job": self._job_name(job)})

        try:
            plan = self._build_plan(
                job,
                inventory,
                limit=limit,
                exclude=exclude,
                tags=tags,
                skip_tags=skip_tags,
            )
            if plan_only:
                store.update_run_status(NodeStatus.SUCCESS)
                self._print_plan(run_id, plan, output_format=output_format)
                return 0

            variables = dict(variables)
            os_by_target: Dict[str, TargetOS] = {}
            if not dry_run and self._plan_requires_capability_preflight(job=job, plan=plan, variables=variables, secrets=secrets):
                os_by_target = self._detect_os_for_plan(plan, secrets)
                variables["__automax_os_by_target"] = {name: self._os_to_mapping(info) for name, info in os_by_target.items()}
                self._run_capability_preflight(job=job, plan=plan, variables=variables, secrets=secrets, os_by_target=os_by_target)
                store.record_event("capability_preflight_ok", payload={"targets": len({item["target"].name for item in plan})})

            lock_manager = LockManager.for_state_dir(state_dir) if lock else None
            acquired_locks = []
            try:
                if lock_manager:
                    acquired_locks = lock_manager.acquire_many(
                        self._lock_names(job, plan, scope=lock_scope), timeout=lock_timeout
                    )
                    store.record_event(
                        "locks_acquired",
                        payload={"locks": [item.name for item in acquired_locks]},
                    )
                rc = self._execute_plan(
                    job=job,
                    plan=plan,
                    store=store,
                    run_id=run_id,
                    dry_run=dry_run,
                    variables=variables,
                    secrets=secrets,
                    from_node=from_node,
                    skip_successful=skip_successful,
                    only_failed=only_failed,
                    output_format=output_format,
                    sudo_password=sudo_password,
                )
            finally:
                if lock_manager:
                    lock_manager.release_many(acquired_locks)
            store.update_run_status(self._final_run_status(store, rc))
            store.record_event("job_finished", payload={"rc": rc})
            self._print_run_summary(store, rc=rc, state_dir=state_dir, output_format=output_format)
            return rc
        except Exception as exc:
            store.update_run_status(NodeStatus.FAILED)
            store.record_event("job_failed", payload={"error": self._mask_text(str(exc), secrets)})
            raise

    def resume(
        self,
        *,
        run_id: str,
        state_dir: str = ".automax/runs",
        from_node: str | None = None,
        dry_run: bool = False,
        limit: Iterable[str] = (),
        exclude: Iterable[str] = (),
        tags: Iterable[str] = (),
        skip_tags: Iterable[str] = (),
        cli_vars: Optional[Dict[str, Any]] = None,
        skip_successful: bool = False,
        only_failed: bool = False,
        output_format: str = "text",
        lock: bool = False,
        lock_scope: str = "both",
        lock_timeout: float = 0,
        sudo_password_env: str | None = None,
    ) -> int:
        """Resume a previous run using paths stored in the run state."""
        self._validate_output_format(output_format)
        store = StateStore(state_dir, run_id)
        run = store.get_run()
        if not run:
            raise AutomaxError(f"run not found: {run_id}")
        if only_failed:
            failed = store.node_keys_by_status({NodeStatus.FAILED.value})
            if not failed:
                raise AutomaxError(f"run has no failed nodes: {run_id}")
        else:
            from_node = from_node or store.first_failed_node_id()
            if not from_node:
                raise AutomaxError(f"run has no failed checkpoint: {run_id}")
        return self.run(
            job_path=run["job_path"],
            inventory_path=run["inventory_path"],
            vars_path=run.get("vars_path"),
            secrets_path=run.get("secrets_path"),
            state_dir=state_dir,
            run_id=run_id,
            dry_run=dry_run,
            from_node=from_node,
            limit=limit,
            exclude=exclude,
            tags=tags,
            skip_tags=skip_tags,
            cli_vars=cli_vars,
            skip_successful=skip_successful,
            only_failed=only_failed,
            output_format=output_format,
            lock=lock,
            lock_scope=lock_scope,
            lock_timeout=lock_timeout,
            sudo_password_env=sudo_password_env,
        )

    def inspect_job(
        self,
        *,
        job_path: str,
        inventory_path: str,
        vars_path: str | None = None,
        secrets_path: str | None = None,
        limit: Iterable[str] = (),
        exclude: Iterable[str] = (),
        tags: Iterable[str] = (),
        skip_tags: Iterable[str] = (),
        cli_vars: Optional[Dict[str, Any]] = None,
    ) -> Dict[str, Any]:
        """Return a resolved, serializable view of a job without creating run state."""
        resolved = self.resolve_job_context(
            job_path=job_path,
            inventory_path=inventory_path,
            vars_path=vars_path,
            secrets_path=secrets_path,
            limit=limit,
            exclude=exclude,
            tags=tags,
            skip_tags=skip_tags,
            cli_vars=cli_vars,
        )
        return build_job_view(resolved.job, resolved.plan)

    def resolve_job_context(
        self,
        *,
        job_path: str,
        inventory_path: str,
        vars_path: str | None = None,
        secrets_path: str | None = None,
        limit: Iterable[str] = (),
        exclude: Iterable[str] = (),
        tags: Iterable[str] = (),
        skip_tags: Iterable[str] = (),
        cli_vars: Optional[Dict[str, Any]] = None,
    ) -> ResolvedJobContext:
        """Resolve job, inventory, vars, secrets and selected plan once."""
        documents = self._load_documents(
            job_path=job_path,
            inventory_path=inventory_path,
            vars_path=vars_path,
            secrets_path=secrets_path,
        )
        secrets = self.secret_manager.resolve_all(
            documents["secrets"],
            base_dir=self._path_parent(secrets_path),
        )
        variables = self._merge_variables(
            documents["vars"], documents["job"].get("vars", {}), cli_vars or {}
        )
        context = {"vars": variables, "secrets": secrets}
        inventory_document = load_inventory_document(inventory_path, context)
        inventory = Inventory(inventory_document, context)
        job = documents["job"]
        self.validate_job(job)
        plan = self._build_plan(
            job,
            inventory,
            limit=limit,
            exclude=exclude,
            tags=tags,
            skip_tags=skip_tags,
        )
        return ResolvedJobContext(
            job_path=str(Path(job_path).expanduser()),
            inventory_path=str(Path(inventory_path).expanduser()),
            vars_path=str(Path(vars_path).expanduser()) if vars_path else None,
            secrets_path=str(Path(secrets_path).expanduser()) if secrets_path else None,
            documents=documents,
            job=job,
            inventory=inventory,
            variables=variables,
            secrets=secrets,
            plan=plan,
        )

    def iter_rendered_plan_items(
        self, resolved: ResolvedJobContext, *, dry_run: bool = True
    ) -> Iterable[Dict[str, Any]]:
        """Yield rendered plan items for safe operator inspections."""
        outputs: Dict[str, Any] = {}
        step_states: Dict[tuple[str, str], Dict[str, Any]] = {}
        for item in resolved.plan:
            step_key = (str(item["target"].name), str(item["step"]["id"]))
            step_state = step_states.setdefault(step_key, {})
            yield from self._iter_rendered_substep_items(
                resolved=resolved,
                item=item,
                dry_run=dry_run,
                outputs=outputs,
                step_state=step_state,
                flow_vars={},
            )

    def _iter_rendered_substep_items(
        self,
        *,
        resolved: ResolvedJobContext,
        item: Dict[str, Any],
        dry_run: bool,
        outputs: Dict[str, Any],
        step_state: Dict[str, Any],
        flow_vars: Dict[str, Any],
    ) -> Iterable[Dict[str, Any]]:
        target: Target = item["target"]
        substep = item["substep"]
        template_context = self._template_context(
            job=resolved.job,
            task=item["task"],
            step=item["step"],
            substep=substep,
            target=target,
            variables=resolved.variables,
            outputs=outputs,
            secrets=resolved.secrets,
            step_state=step_state,
            flow_vars=flow_vars,
        )
        try:
            if not self._is_condition_true(substep.get("when"), template_context):
                return
        except Exception:
            # Operator previews do not execute previous substeps, so unresolved outputs may
            # make dynamic conditions unavailable. Keep walking nested plugin leaves so
            # capability preflight and manual previews still see the possible operations.
            pass
        if self._is_if_substep(substep):
            try:
                branches = [self._selected_if_branch(substep, template_context)]
            except Exception:
                branches = self._if_branches(substep)
            for branch in branches:
                for child in branch["then"]:
                    yield from self._iter_rendered_substep_items(
                        resolved=resolved,
                        item=self._child_item(item, child, branch["segment"]),
                        dry_run=dry_run,
                        outputs=outputs,
                        step_state=step_state,
                        flow_vars=flow_vars,
                    )
            return
        if self._is_switch_substep(substep):
            try:
                branches = [self._selected_switch_branch(substep, template_context)]
            except Exception:
                branches = self._switch_branches(substep)
            for branch in branches:
                for child in branch["then"]:
                    yield from self._iter_rendered_substep_items(
                        resolved=resolved,
                        item=self._child_item(item, child, branch["segment"]),
                        dry_run=dry_run,
                        outputs=outputs,
                        step_state=step_state,
                        flow_vars=flow_vars,
                    )
            return
        if self._is_retry_flow_substep(substep):
            for child in substep.get("retry", {}).get("do", []) or []:
                yield from self._iter_rendered_substep_items(
                    resolved=resolved,
                    item=self._child_item(item, child, "retry"),
                    dry_run=dry_run,
                    outputs=outputs,
                    step_state=step_state,
                    flow_vars=flow_vars,
                )
            return
        if self._is_for_substep(substep):
            loop_var = str(substep.get("for", "item"))
            try:
                values = self._loop_values(evaluate_value(substep.get("in"), template_context))
            except Exception:
                values = ["__automax_loop_item__"]
            if not values:
                values = ["__automax_loop_item__"]
            for index, value in enumerate(values):
                loop_vars = dict(flow_vars)
                loop_vars[loop_var] = value
                loop_vars["item"] = value
                loop_vars["loop"] = {"index": index + 1, "index0": index, "first": index == 0, "last": index == len(values) - 1, "length": len(values)}
                for child in substep.get("do", []) or []:
                    yield from self._iter_rendered_substep_items(
                        resolved=resolved,
                        item=self._child_item(item, child, f"for.{index}"),
                        dry_run=dry_run,
                        outputs=outputs,
                        step_state=step_state,
                        flow_vars=loop_vars,
                    )
            return
        if self._is_try_substep(substep):
            for branch in ("try", "rescue", "always"):
                for child in substep.get(branch, []) or []:
                    yield from self._iter_rendered_substep_items(
                        resolved=resolved,
                        item=self._child_item(item, child, branch),
                        dry_run=dry_run,
                        outputs=outputs,
                        step_state=step_state,
                        flow_vars=flow_vars,
                    )
            return
        if self._is_block_substep(substep):
            for child in substep.get("block", []) or []:
                yield from self._iter_rendered_substep_items(
                    resolved=resolved,
                    item=self._child_item(item, child, "block"),
                    dry_run=dry_run,
                    outputs=outputs,
                    step_state=step_state,
                    flow_vars=flow_vars,
                )
            return
        if self._is_assignment_substep(substep):
            try:
                assignments = substep.get("set", substep.get("let"))
                values = {}
                local_context = deepcopy(template_context)
                for name, value in assignments.items():
                    evaluated = evaluate_value(value, local_context)
                    values[name] = evaluated
                    local_context[name] = evaluated
                    local_context.setdefault("vars", {})[name] = evaluated
                    local_context.setdefault("outputs", {})[name] = evaluated
            except Exception:
                values = {}
            step_state.setdefault("vars", {}).update(values)
            flow_vars.update(values)
            for name, value in values.items():
                outputs[name] = value
                outputs.setdefault("targets", {}).setdefault(target.name, {})[name] = value
            return
        if self._is_terminal_flow_substep(substep):
            return

        rendered_substep = render_mapping(substep, template_context)
        plugin_name = rendered_substep.get("use") or rendered_substep.get("plugin")
        params = rendered_substep.get("with", rendered_substep.get("params", {})) or {}
        plugin = self.plugin_registry.get(str(plugin_name))
        plugin.validate(params)
        effective_vars = deepcopy(resolved.variables)
        effective_vars.update(target.vars)
        effective_vars.update(flow_vars)
        context = ExecutionContext(
            run_id="operator-preview",
            dry_run=dry_run,
            job=resolved.job,
            task=item["task"],
            step=item["step"],
            substep=rendered_substep,
            target=target,
            vars=effective_vars,
            outputs=outputs,
            secrets=resolved.secrets,
            ssh_client=None,
            logger=self.logger,
            command_timeout=self._resolve_command_timeout(
                resolved.job, item["task"], item["step"], item["substep"]
            ),
            step_state=step_state,
        )
        yield {
            **item,
            "plugin": plugin,
            "plugin_name": str(plugin_name),
            "params": params,
            "context": context,
            "rendered_substep": rendered_substep,
        }


    def render_vars_job(
        self,
        *,
        job_path: str,
        inventory_path: str,
        vars_path: str | None = None,
        secrets_path: str | None = None,
        limit: Iterable[str] = (),
        exclude: Iterable[str] = (),
        tags: Iterable[str] = (),
        skip_tags: Iterable[str] = (),
        cli_vars: Optional[Dict[str, Any]] = None,
    ) -> Dict[str, Any]:
        """Render the final job-scoped variable context without exposing secrets."""
        resolved = self.resolve_job_context(
            job_path=job_path,
            inventory_path=inventory_path,
            vars_path=vars_path,
            secrets_path=secrets_path,
            limit=limit,
            exclude=exclude,
            tags=tags,
            skip_tags=skip_tags,
            cli_vars=cli_vars,
        )
        targets: Dict[str, Dict[str, Any]] = {}
        for item in self.iter_rendered_plan_items(resolved, dry_run=True):
            target: Target = item["target"]
            entry = targets.setdefault(
                target.name,
                {
                    "name": target.name,
                    "host": target.host,
                    "port": target.port,
                    "groups": list(target.groups),
                    "vars": self._mask_mapping(item["context"].vars, resolved.secrets),
                    "secrets": {key: "***" for key in sorted(resolved.secrets)},
                    "nodes": [],
                },
            )
            entry["nodes"].append(
                {
                    "node_id": item["node_id"],
                    "task_id": str(item["task"]["id"]),
                    "step_id": str(item["step"]["id"]),
                    "substep_id": str(item["substep"]["id"]),
                    "plugin": item["plugin_name"],
                }
            )
        return {
            "job": self._job_name(resolved.job),
            "vars_path": resolved.vars_path,
            "secrets_path": resolved.secrets_path,
            "targets": [targets[name] for name in sorted(targets)],
            "target_count": len(targets),
            "node_count": sum(len(target["nodes"]) for target in targets.values()),
        }

    def inspect_inventory(
        self,
        *,
        job_path: str,
        inventory_path: str,
        vars_path: str | None = None,
        secrets_path: str | None = None,
        limit: Iterable[str] = (),
        exclude: Iterable[str] = (),
        tags: Iterable[str] = (),
        skip_tags: Iterable[str] = (),
        cli_vars: Optional[Dict[str, Any]] = None,
    ) -> Dict[str, Any]:
        """Return inventory targets selected by one resolved job."""
        resolved = self.resolve_job_context(
            job_path=job_path,
            inventory_path=inventory_path,
            vars_path=vars_path,
            secrets_path=secrets_path,
            limit=limit,
            exclude=exclude,
            tags=tags,
            skip_tags=skip_tags,
            cli_vars=cli_vars,
        )
        selected: Dict[str, Dict[str, Any]] = {}
        for item in resolved.plan:
            target: Target = item["target"]
            entry = selected.setdefault(
                target.name,
                {
                    "name": target.name,
                    "host": target.host,
                    "port": target.port,
                    "user": target.user,
                    "groups": list(target.groups),
                    "vars": sorted(target.vars),
                    "nodes": 0,
                },
            )
            entry["nodes"] += 1

        return {
            "job": self._job_name(resolved.job),
            "inventory_path": resolved.inventory_path,
            "targets": [selected[name] for name in sorted(selected)],
            "target_count": len(selected),
            "node_count": len(resolved.plan),
        }

    def check_secrets(
        self,
        *,
        job_path: str,
        inventory_path: str,
        vars_path: str | None = None,
        secrets_path: str | None = None,
        limit: Iterable[str] = (),
        exclude: Iterable[str] = (),
        tags: Iterable[str] = (),
        skip_tags: Iterable[str] = (),
        cli_vars: Optional[Dict[str, Any]] = None,
        include_all: bool = False,
    ) -> Dict[str, Any]:
        """Check secret definitions referenced by one selected job plan."""
        documents = self._load_documents(
            job_path=job_path,
            inventory_path=inventory_path,
            vars_path=vars_path,
            secrets_path=secrets_path,
        )
        job = documents["job"]
        self.validate_job(job)
        raw_inventory = load_yaml_file(inventory_path)
        declared = self._declared_secret_names(documents["secrets"])
        known_refs = self._secret_references(job) | self._secret_references(raw_inventory)
        placeholder_secrets = {name: f"__automax_secret_{name}__" for name in declared | known_refs}
        variables = self._merge_variables(documents["vars"], job.get("vars", {}), cli_vars or {})
        context = {"vars": variables, "secrets": placeholder_secrets}
        inventory_document = load_inventory_document(inventory_path, context)
        inventory = Inventory(inventory_document, context)
        plan = self._build_plan(
            job,
            inventory,
            limit=limit,
            exclude=exclude,
            tags=tags,
            skip_tags=skip_tags,
        )
        referenced = set()
        for item in plan:
            referenced.update(
                self._secret_references(
                    {key: value for key, value in item["task"].items() if key != "steps"}
                )
            )
            referenced.update(
                self._secret_references(
                    {key: value for key, value in item["step"].items() if key != "substeps"}
                )
            )
            referenced.update(self._secret_references(item["substep"]))

        checks = self.secret_manager.check_all(documents["secrets"], base_dir=self._path_parent(secrets_path))
        checks_by_name = {item["name"]: item for item in checks}
        rows = []
        for name in sorted(declared | referenced):
            used = name in referenced
            if not include_all and not used:
                continue
            row = dict(
                checks_by_name.get(
                    name,
                    {
                        "name": name,
                        "provider": "undeclared",
                        "status": "MISSING",
                        "ok": False,
                        "detail": "referenced by job but not declared in secrets file",
                    },
                )
            )
            row["used"] = used
            rows.append(row)

        return {
            "job": self._job_name(job),
            "secrets_path": str(Path(secrets_path).expanduser()) if secrets_path else None,
            "checked": len(rows),
            "ok": all(item["ok"] for item in rows),
            "secrets": rows,
        }

    @classmethod
    def _secret_references(cls, value: Any) -> set[str]:
        """Collect Jinja-style secrets.NAME references from nested values."""
        found: set[str] = set()
        if isinstance(value, dict):
            for child in value.values():
                found.update(cls._secret_references(child))
        elif isinstance(value, list):
            for child in value:
                found.update(cls._secret_references(child))
        elif isinstance(value, str):
            for match in re.finditer(r"secrets\.([A-Za-z_][A-Za-z0-9_]*)", value):
                found.add(match.group(1))
            for match in re.finditer(r"secrets\[[\'\"]([^\'\"]+)[\'\"]\]", value):
                found.add(match.group(1))
        return found

    @staticmethod
    def _declared_secret_names(document: Dict[str, Any] | None) -> set[str]:
        if not document:
            return set()
        raw_secrets = document.get("secrets", document)
        if not isinstance(raw_secrets, dict):
            raise AutomaxError("secrets root must be a mapping")
        return {str(key) for key in raw_secrets}

    def check_job(
        self,
        *,
        job_path: str,
        inventory_path: str,
        vars_path: str | None = None,
        secrets_path: str | None = None,
        limit: Iterable[str] = (),
        exclude: Iterable[str] = (),
        tags: Iterable[str] = (),
        skip_tags: Iterable[str] = (),
        cli_vars: Optional[Dict[str, Any]] = None,
    ) -> Dict[str, Any]:
        """Render a safe check-mode preview for one resolved job."""
        resolved = self.resolve_job_context(
            job_path=job_path,
            inventory_path=inventory_path,
            vars_path=vars_path,
            secrets_path=secrets_path,
            limit=limit,
            exclude=exclude,
            tags=tags,
            skip_tags=skip_tags,
            cli_vars=cli_vars,
        )
        rows = []
        for item in self.iter_rendered_plan_items(resolved, dry_run=True):
            plugin = item["plugin"]
            params = item["params"]
            try:
                result = plugin.dry_run(params, item["context"])
            except Exception as exc:  # pragma: no cover - defensive plugin boundary
                result = PluginResult.failure(message=str(exc))
            rows.append(
                {
                    "target": item["target"].name,
                    "node_id": item["node_id"],
                    "task_id": str(item["task"]["id"]),
                    "step_id": str(item["step"]["id"]),
                    "substep_id": str(item["substep"]["id"]),
                    "plugin": item["plugin_name"],
                    "supports_dry_run": bool(plugin.supports_dry_run),
                    "supports_check_mode": bool(plugin.supports_check_mode),
                    "ok": result.ok,
                    "changed": result.changed,
                    "message": self._mask_text(result.message, resolved.secrets),
                    "params": self._mask_mapping(params, resolved.secrets),
                }
            )
        return {
            "job": self._job_name(resolved.job),
            "mode": "check",
            "ok": all(row["ok"] for row in rows),
            "nodes": rows,
        }

    def diff_job(
        self,
        *,
        job_path: str,
        inventory_path: str,
        vars_path: str | None = None,
        secrets_path: str | None = None,
        limit: Iterable[str] = (),
        exclude: Iterable[str] = (),
        tags: Iterable[str] = (),
        skip_tags: Iterable[str] = (),
        cli_vars: Optional[Dict[str, Any]] = None,
    ) -> Dict[str, Any]:
        """Render safe diff previews for one resolved job."""
        resolved = self.resolve_job_context(
            job_path=job_path,
            inventory_path=inventory_path,
            vars_path=vars_path,
            secrets_path=secrets_path,
            limit=limit,
            exclude=exclude,
            tags=tags,
            skip_tags=skip_tags,
            cli_vars=cli_vars,
        )
        rows = []
        for item in self.iter_rendered_plan_items(resolved, dry_run=True):
            plugin = item["plugin"]
            try:
                previews = plugin.diff_preview(item["params"], item["context"])
            except Exception as exc:  # pragma: no cover - defensive plugin boundary
                previews = []
                reason = str(exc)
            else:
                reason = plugin.diff_preview_reason(item["params"], item["context"])
            if not previews:
                rows.append(
                    {
                        "target": item["target"].name,
                        "node_id": item["node_id"],
                        "plugin": item["plugin_name"],
                        "available": False,
                        "reason": self._mask_text(reason, resolved.secrets),
                    }
                )
                continue
            for preview in previews:
                row = dict(preview)
                row.update(
                    {
                        "target": item["target"].name,
                        "node_id": item["node_id"],
                        "plugin": item["plugin_name"],
                        "available": True,
                    }
                )
                if "diff" in row:
                    row["diff"] = self._mask_text(str(row["diff"]), resolved.secrets)
                rows.append(row)
        return {
            "job": self._job_name(resolved.job),
            "mode": "diff",
            "diffs": rows,
        }

    def manual_commands_job(
        self,
        *,
        job_path: str,
        inventory_path: str,
        vars_path: str | None = None,
        secrets_path: str | None = None,
        limit: Iterable[str] = (),
        exclude: Iterable[str] = (),
        tags: Iterable[str] = (),
        skip_tags: Iterable[str] = (),
        cli_vars: Optional[Dict[str, Any]] = None,
    ) -> Dict[str, Any]:
        """Render manual recovery commands for selected job substeps."""
        resolved = self.resolve_job_context(
            job_path=job_path,
            inventory_path=inventory_path,
            vars_path=vars_path,
            secrets_path=secrets_path,
            limit=limit,
            exclude=exclude,
            tags=tags,
            skip_tags=skip_tags,
            cli_vars=cli_vars,
        )
        rows = []
        uses_sudo = False
        for item in self.iter_rendered_plan_items(resolved, dry_run=True):
            commands = item["plugin"].manual_commands(item["params"], item["context"])
            node_uses_sudo = any("sudo -n" in command for command in commands)
            uses_sudo = uses_sudo or node_uses_sudo
            rows.append(
                {
                    "target": item["target"].name,
                    "host": item["target"].host,
                    "node_id": item["node_id"],
                    "plugin": item["plugin_name"],
                    "commands": [self._mask_text(command, resolved.secrets) for command in commands],
                    "available": bool(commands),
                    "uses_sudo": node_uses_sudo,
                    "reason": "" if commands else self._mask_text(
                        item["plugin"].manual_commands_reason(item["params"], item["context"]),
                        resolved.secrets,
                    ),
                }
            )
        return {
            "job": self._job_name(resolved.job),
            "mode": "manual-commands",
            "uses_sudo": uses_sudo,
            "sudo_note": (
                "Rendered manual commands containing sudo -n require an existing sudo timestamp "
                "when pasted manually; normal automax run/resume can use "
                "--sudo-password-env ENV_NAME instead."
            ) if uses_sudo else "",
            "nodes": rows,
        }

    def os_info_inventory(
        self,
        *,
        inventory_path: str,
        vars_path: str | None = None,
        secrets_path: str | None = None,
        limit: Iterable[str] = (),
        exclude: Iterable[str] = (),
        cli_vars: Optional[Dict[str, Any]] = None,
    ) -> Dict[str, Any]:
        """Detect and report operating-system facts for inventory targets."""
        vars_document = load_yaml_file(vars_path, required=False) if vars_path else {}
        secrets_document = load_yaml_file(secrets_path, required=False) if secrets_path else {}
        secrets = self.secret_manager.resolve_all(
            secrets_document,
            base_dir=self._path_parent(secrets_path),
        )
        variables = self._merge_variables(vars_document, cli_vars or {})
        context = {"vars": variables, "secrets": secrets}
        inventory_document = load_inventory_document(inventory_path, context)
        inventory = Inventory(inventory_document, context)
        targets = inventory.select("all", limit=list(limit), exclude=list(exclude))
        os_by_target = self._detect_os_for_targets(targets, secrets)
        rows = []
        for target in targets:
            os_info = os_by_target[target.name]
            rows.append(
                {
                    "target": target.name,
                    "host": target.host,
                    "port": target.port,
                    "user": target.user,
                    "os": self._os_to_mapping(os_info),
                }
            )
        return {
            "mode": "os-info",
            "inventory": str(Path(inventory_path).expanduser()),
            "target_count": len(rows),
            "targets": rows,
        }

    def capability_requirements_job(
        self,
        *,
        job_path: str,
        inventory_path: str,
        vars_path: str | None = None,
        secrets_path: str | None = None,
        limit: Iterable[str] = (),
        exclude: Iterable[str] = (),
        tags: Iterable[str] = (),
        skip_tags: Iterable[str] = (),
        cli_vars: Optional[Dict[str, Any]] = None,
        check_missing: bool = False,
    ) -> Dict[str, Any]:
        """Return job-scoped remote capability requirements from the selected plan."""
        resolved = self.resolve_job_context(
            job_path=job_path,
            inventory_path=inventory_path,
            vars_path=vars_path,
            secrets_path=secrets_path,
            limit=limit,
            exclude=exclude,
            tags=tags,
            skip_tags=skip_tags,
            cli_vars=cli_vars,
        )
        os_by_target = self._detect_os_for_plan(resolved.plan, resolved.secrets)
        requirements = collect_requirements(self.iter_rendered_plan_items(resolved, dry_run=True), os_by_target)
        if check_missing:
            self._annotate_missing_capabilities(requirements, resolved.plan)
        return {
            "job": self._job_name(resolved.job),
            "mode": "capability-requirements",
            "targets": [requirements[name] for name in sorted(requirements)],
            "target_count": len(requirements),
            "tool_count": len({tool for item in requirements.values() for tool in item["tools"]}),
            "package_count": len({package for item in requirements.values() for package in item.get("packages", [])}),
            "missing_tool_count": len({tool for item in requirements.values() for tool in item.get("missing_tools", [])}),
            "missing_package_count": len({package for item in requirements.values() for package in item.get("missing_packages", [])}),
        }

    def install_capability_requirements_job(
        self,
        *,
        job_path: str,
        inventory_path: str,
        vars_path: str | None = None,
        secrets_path: str | None = None,
        limit: Iterable[str] = (),
        exclude: Iterable[str] = (),
        tags: Iterable[str] = (),
        skip_tags: Iterable[str] = (),
        cli_vars: Optional[Dict[str, Any]] = None,
        sudo_password_env: str | None = None,
        progress_callback: Callable[[Dict[str, Any]], None] | None = None,
    ) -> Dict[str, Any]:
        """Install missing target packages required by the selected job plan."""
        resolved = self.resolve_job_context(
            job_path=job_path,
            inventory_path=inventory_path,
            vars_path=vars_path,
            secrets_path=secrets_path,
            limit=limit,
            exclude=exclude,
            tags=tags,
            skip_tags=skip_tags,
            cli_vars=cli_vars,
        )
        os_by_target = self._detect_os_for_plan(resolved.plan, resolved.secrets)
        requirements = collect_requirements(self.iter_rendered_plan_items(resolved, dry_run=True), os_by_target)
        sudo_password = self._resolve_sudo_password(sudo_password_env)
        targets = []
        ok = True
        emit = progress_callback or (lambda event: None)
        emit({"event": "job", "job": self._job_name(resolved.job)})
        for target_name in sorted(requirements):
            entry = requirements[target_name]
            target = next(item["target"] for item in resolved.plan if item["target"].name == target_name)
            emit({"event": "target-check", "target": target_name, "host": entry["host"], "os": entry["os"]})
            missing_tools = self._missing_tools(target, entry["tools"])
            packages = self._packages_for_tools(missing_tools, entry["os"]["family"])
            unresolved = self._unresolved_tools(missing_tools, entry["os"]["family"])
            emit({
                "event": "target-missing",
                "target": target_name,
                "host": entry["host"],
                "os": entry["os"],
                "missing_tools": missing_tools,
                "packages": packages,
                "unresolved_tools": unresolved,
            })
            rc = 0
            stdout = ""
            stderr = ""
            changed = False
            if packages:
                emit({"event": "target-install", "target": target_name, "host": entry["host"], "os": entry["os"], "packages": packages})
                rc, stdout, stderr = self._install_packages_for_os(
                    target=target,
                    os_family=entry["os"]["family"],
                    packages=packages,
                    sudo_password=sudo_password,
                )
                changed = rc == 0
            target_ok = rc == 0 and not unresolved
            ok = ok and target_ok
            emit({
                "event": "target-done",
                "target": target_name,
                "host": entry["host"],
                "os": entry["os"],
                "rc": rc,
                "ok": target_ok,
                "changed": changed,
                "packages": packages,
                "unresolved_tools": unresolved,
            })
            targets.append(
                {
                    "target": target_name,
                    "host": entry["host"],
                    "os": entry["os"],
                    "missing_tools": missing_tools,
                    "packages": packages,
                    "unresolved_tools": unresolved,
                    "changed": changed,
                    "ok": target_ok,
                    "rc": rc,
                    "stdout": self._mask_text(stdout, resolved.secrets),
                    "stderr": self._mask_text(stderr, resolved.secrets),
                }
            )
        return {
            "job": self._job_name(resolved.job),
            "mode": "capability-install",
            "ok": ok,
            "targets": targets,
        }

    def validate(
        self,
        *,
        job_path: str,
        inventory_path: str,
        vars_path: str | None = None,
        secrets_path: str | None = None,
        cli_vars: Optional[Dict[str, Any]] = None,
        tags: Iterable[str] = (),
        skip_tags: Iterable[str] = (),
        strict: bool = False,
    ) -> None:
        """Validate external YAML files without executing."""
        documents = self._load_documents(
            job_path=job_path,
            inventory_path=inventory_path,
            vars_path=vars_path,
            secrets_path=secrets_path,
        )
        secrets = self.secret_manager.resolve_all(
            documents["secrets"],
            base_dir=Path(secrets_path).expanduser().resolve().parent if secrets_path else None,
        )
        variables = self._merge_variables(
            documents["vars"], documents["job"].get("vars", {}), cli_vars or {}
        )
        context = {"vars": variables, "secrets": secrets}
        inventory_document = load_inventory_document(inventory_path, context)
        inventory = Inventory(inventory_document, context)
        job = documents["job"]
        self.validate_job(job, strict=strict)
        plan = self._build_plan(job, inventory, limit=(), exclude=(), tags=tags, skip_tags=skip_tags)
        if strict:
            self._validate_plan_strict(plan)

    def validate_job(self, job: Dict[str, Any], *, strict: bool = False) -> None:
        """Validate the canonical three-level job DSL."""
        if job.get("apiVersion") != "automax.io/v1":
            raise AutomaxError("job apiVersion must be 'automax.io/v1'")
        if job.get("kind") != "Job":
            raise AutomaxError("job kind must be 'Job'")
        if strict:
            self._validate_known_keys(
                job,
                "job",
                {
                    "apiVersion",
                    "kind",
                    "metadata",
                    "vars",
                    "targets",
                    "strategy",
                    "failurePolicy",
                    "errorPolicy",
                    "timeouts",
                    "retry",
                    "tags",
                    "tasks",
                },
            )
        self._validate_strategy(job.get("strategy"), "job")
        self._validate_failure_policy(job.get("failurePolicy"), "job")
        self._validate_error_policy(job.get("errorPolicy"), "job")
        self._validate_timeouts(job.get("timeouts"), "job")
        self._validate_retry_policy(job.get("retry"), "job")
        tasks = job.get("tasks")
        if not isinstance(tasks, list) or not tasks:
            raise AutomaxError("job requires non-empty tasks list")

        seen_tasks = set()
        for task in tasks:
            task_id = self._require_id(task, "task")
            if strict:
                self._validate_known_keys(
                    task,
                    f"task '{task_id}'",
                    {
                        "id",
                        "name",
                        "description",
                        "vars",
                        "targets",
                        "strategy",
                        "failurePolicy",
                        "errorPolicy",
                        "timeouts",
                        "retry",
                        "tags",
                        "steps",
                    },
                )
            self._validate_strategy(task.get("strategy"), f"task '{task_id}'")
            self._validate_failure_policy(task.get("failurePolicy"), f"task '{task_id}'")
            self._validate_error_policy(task.get("errorPolicy"), f"task '{task_id}'")
            self._validate_timeouts(task.get("timeouts"), f"task '{task_id}'")
            self._validate_retry_policy(task.get("retry"), f"task '{task_id}'")
            self._validate_tags(task.get("tags"), f"task '{task_id}'")
            if task_id in seen_tasks:
                raise AutomaxError(f"duplicate task id: {task_id}")
            seen_tasks.add(task_id)
            steps = task.get("steps")
            if not isinstance(steps, list) or not steps:
                raise AutomaxError(f"task '{task_id}' requires non-empty steps")
            seen_steps = set()
            for step in steps:
                step_id = self._require_id(step, "step")
                if strict:
                    self._validate_known_keys(
                        step,
                        f"step '{task_id}:{step_id}'",
                        {
                            "id",
                            "name",
                            "description",
                            "vars",
                            "targets",
                            "strategy",
                            "failurePolicy",
                            "errorPolicy",
                            "timeouts",
                            "retry",
                            "tags",
                            "substeps",
                        },
                    )
                self._validate_strategy(step.get("strategy"), f"step '{task_id}:{step_id}'")
                self._validate_failure_policy(step.get("failurePolicy"), f"step '{task_id}:{step_id}'")
                self._validate_error_policy(step.get("errorPolicy"), f"step '{task_id}:{step_id}'")
                self._validate_timeouts(step.get("timeouts"), f"step '{task_id}:{step_id}'")
                self._validate_retry_policy(step.get("retry"), f"step '{task_id}:{step_id}'")
                self._validate_tags(step.get("tags"), f"step '{task_id}:{step_id}'")
                if step_id in seen_steps:
                    raise AutomaxError(f"duplicate step id in task '{task_id}': {step_id}")
                seen_steps.add(step_id)
                substeps = step.get("substeps")
                if not isinstance(substeps, list) or not substeps:
                    raise AutomaxError(
                        f"step '{task_id}:{step_id}' requires non-empty substeps"
                    )
                self._validate_substep_list(
                    substeps,
                    label=f"{task_id}:{step_id}",
                    strict=strict,
                )

    def _validate_plan_strict(self, plan: List[Dict[str, Any]]) -> None:
        """Validate plugin parameters after target/tag resolution."""
        for item in plan:
            self._validate_substep_strict(item["substep"], item["node_id"])

    def _validate_substep_list(self, substeps: Any, *, label: str, strict: bool) -> None:
        if not isinstance(substeps, list) or not substeps:
            raise AutomaxError(f"substep list '{label}' must be a non-empty list")
        seen_substeps = set()
        for substep in substeps:
            substep_id = self._require_id(substep, "substep")
            substep_label = f"substep '{label}:{substep_id}'"
            if substep_id in seen_substeps:
                raise AutomaxError(f"duplicate substep id in '{label}': {substep_id}")
            seen_substeps.add(substep_id)
            self._validate_substep_common(substep, substep_label, strict=strict)
            if self._is_if_substep(substep):
                self._validate_flow_if_substep(substep, substep_label, strict=strict)
                continue
            if self._is_for_substep(substep):
                self._validate_flow_for_substep(substep, substep_label, strict=strict)
                continue
            if self._is_switch_substep(substep):
                self._validate_flow_switch_substep(substep, substep_label, strict=strict)
                continue
            if self._is_retry_flow_substep(substep):
                self._validate_flow_retry_substep(substep, substep_label, strict=strict)
                continue
            if self._is_try_substep(substep):
                self._validate_flow_try_substep(substep, substep_label, strict=strict)
                continue
            if self._is_block_substep(substep):
                self._validate_flow_block_substep(substep, substep_label, strict=strict)
                continue
            if self._is_assignment_substep(substep):
                self._validate_assignment_substep(substep, substep_label)
                continue
            if self._is_terminal_flow_substep(substep):
                self._validate_terminal_flow_substep(substep, substep_label)
                continue
            self._validate_plugin_substep(substep, substep_label)

    def _validate_substep_common(self, substep: Dict[str, Any], label: str, *, strict: bool) -> None:
        if strict:
            self._validate_known_keys(substep, label, self._allowed_substep_keys())
        self._validate_tags(substep.get("tags"), label)
        self._validate_timeouts(substep.get("timeouts"), label)
        if not self._is_retry_flow_substep(substep):
            self._validate_retry_policy(substep.get("retry"), label)
        self._validate_error_policy(substep.get("errorPolicy"), label)

    def _validate_flow_if_substep(self, substep: Dict[str, Any], label: str, *, strict: bool) -> None:
        if "use" in substep or "plugin" in substep:
            raise AutomaxError(f"{label} cannot combine 'if' flow control with 'use'")
        branches = self._if_branches(substep, label=label)
        if not branches:
            raise AutomaxError(f"{label} if flow requires at least one branch")
        for branch in branches:
            self._validate_substep_list(branch["then"], label=f"{label}:{branch['segment']}", strict=strict)

    def _validate_flow_switch_substep(self, substep: Dict[str, Any], label: str, *, strict: bool) -> None:
        if "use" in substep or "plugin" in substep:
            raise AutomaxError(f"{label} cannot combine 'switch' flow control with 'use'")
        branches = self._switch_branches(substep, label=label)
        if not branches:
            raise AutomaxError(f"{label} switch flow requires at least one case or default")
        for branch in branches:
            self._validate_substep_list(branch["then"], label=f"{label}:{branch['segment']}", strict=strict)

    def _validate_flow_retry_substep(self, substep: Dict[str, Any], label: str, *, strict: bool) -> None:
        if "use" in substep or "plugin" in substep:
            raise AutomaxError(f"{label} cannot combine 'retry' flow control with 'use'")
        policy = substep.get("retry")
        if not isinstance(policy, dict):
            raise AutomaxError(f"{label} retry flow requires a mapping")
        self._validate_substep_list(policy.get("do"), label=f"{label}:retry", strict=strict)
        attempts = int(policy.get("attempts", 1) or 1)
        if attempts < 1:
            raise AutomaxError(f"{label} retry attempts must be >= 1")
        self._duration_seconds(policy.get("interval", policy.get("delay", 0)), f"{label} retry interval")
        backoff = str(policy.get("backoff", "fixed"))
        if backoff not in {"fixed", "exponential"}:
            raise AutomaxError(f"{label} retry backoff must be fixed or exponential")

    def _validate_flow_for_substep(self, substep: Dict[str, Any], label: str, *, strict: bool) -> None:
        if "use" in substep or "plugin" in substep:
            raise AutomaxError(f"{label} cannot combine 'for' flow control with 'use'")
        variable = substep.get("for")
        if not isinstance(variable, str) or not re.match(r"^[A-Za-z_][A-Za-z0-9_]*$", variable):
            raise AutomaxError(f"{label} for flow requires a valid loop variable name")
        if "in" not in substep:
            raise AutomaxError(f"{label} for flow requires 'in'")
        self._validate_substep_list(substep.get("do"), label=f"{label}:do", strict=strict)

    def _validate_flow_try_substep(self, substep: Dict[str, Any], label: str, *, strict: bool) -> None:
        if "use" in substep or "plugin" in substep:
            raise AutomaxError(f"{label} cannot combine 'try' flow control with 'use'")
        if "try" not in substep:
            raise AutomaxError(f"{label} try flow requires 'try'")
        self._validate_substep_list(substep["try"], label=f"{label}:try", strict=strict)
        if "rescue" in substep:
            self._validate_substep_list(substep["rescue"], label=f"{label}:rescue", strict=strict)
        if "always" in substep:
            self._validate_substep_list(substep["always"], label=f"{label}:always", strict=strict)

    def _validate_flow_block_substep(self, substep: Dict[str, Any], label: str, *, strict: bool) -> None:
        if "use" in substep or "plugin" in substep:
            raise AutomaxError(f"{label} cannot combine 'block' flow control with 'use'")
        self._validate_substep_list(substep.get("block"), label=f"{label}:block", strict=strict)

    def _validate_assignment_substep(self, substep: Dict[str, Any], label: str) -> None:
        if "use" in substep or "plugin" in substep:
            raise AutomaxError(f"{label} cannot combine set/let flow control with 'use'")
        if "set" in substep and "let" in substep:
            raise AutomaxError(f"{label} cannot define both 'set' and 'let'")
        assignments = substep.get("set", substep.get("let"))
        if not isinstance(assignments, dict) or not assignments:
            raise AutomaxError(f"{label} set/let flow requires a non-empty mapping")
        for name in assignments:
            if not isinstance(name, str) or not re.match(r"^[A-Za-z_][A-Za-z0-9_]*$", name):
                raise AutomaxError(f"{label} set/let variable names must be valid identifiers")

    def _validate_terminal_flow_substep(self, substep: Dict[str, Any], label: str) -> None:
        if "use" in substep or "plugin" in substep:
            raise AutomaxError(f"{label} cannot combine flow control with 'use'")
        terminal_keys = [key for key in ("assert", "sleep", "noop", "fail", "break", "continue", "echo") if key in substep]
        if len(terminal_keys) != 1:
            raise AutomaxError(f"{label} must define exactly one terminal flow command")

    def _validate_plugin_substep(self, substep: Dict[str, Any], label: str) -> None:
        plugin_name = substep.get("use") or substep.get("plugin")
        if not plugin_name:
            raise AutomaxError(f"{label} requires 'use'")
        plugin = self.plugin_registry.get(str(plugin_name))
        params = substep.get("with", substep.get("params", {})) or {}
        if not isinstance(params, dict):
            raise AutomaxError(f"{label} params must be mapping")
        plugin.validate(params)

    def _validate_substep_strict(self, substep: Dict[str, Any], node_id: str) -> None:
        if self._is_if_substep(substep):
            for branch in self._if_branches(substep):
                for child in branch["then"]:
                    self._validate_substep_strict(child, f"{node_id}:{branch['segment']}.{child.get('id')}")
            return
        if self._is_for_substep(substep):
            for child in substep.get("do", []) or []:
                self._validate_substep_strict(child, f"{node_id}:do.{child.get('id')}")
            return
        if self._is_switch_substep(substep):
            for branch in self._switch_branches(substep):
                for child in branch["then"]:
                    self._validate_substep_strict(child, f"{node_id}:{branch['segment']}.{child.get('id')}")
            return
        if self._is_retry_flow_substep(substep):
            for child in substep.get("retry", {}).get("do", []) or []:
                self._validate_substep_strict(child, f"{node_id}:retry.{child.get('id')}")
            return
        if self._is_try_substep(substep):
            for branch in ("try", "rescue", "always"):
                for child in substep.get(branch, []) or []:
                    self._validate_substep_strict(child, f"{node_id}:{branch}.{child.get('id')}")
            return
        if self._is_block_substep(substep):
            for child in substep.get("block", []) or []:
                self._validate_substep_strict(child, f"{node_id}:block.{child.get('id')}")
            return
        if self._is_assignment_substep(substep) or self._is_terminal_flow_substep(substep):
            return
        plugin_name = str(substep.get("use") or substep.get("plugin"))
        plugin = self.plugin_registry.get(plugin_name)
        params = substep.get("with", substep.get("params", {})) or {}
        if not isinstance(params, dict):
            raise AutomaxError(f"substep '{node_id}' params must be mapping")
        allowed = set(plugin.required_params) | set(plugin.optional_params)
        unknown = sorted(set(params) - allowed)
        if unknown:
            raise AutomaxError(
                f"substep '{node_id}' plugin '{plugin.name}' unknown params: "
                + ", ".join(unknown)
            )

    @staticmethod
    def _allowed_substep_keys() -> set[str]:
        return {
            "id",
            "name",
            "description",
            "targets",
            "tags",
            "timeouts",
            "retry",
            "errorPolicy",
            "when",
            "if",
            "then",
            "else",
            "switch",
            "case",
            "default",
            "for",
            "in",
            "do",
            "set",
            "let",
            "echo",
            "sleep",
            "noop",
            "assert",
            "message",
            "fail",
            "try",
            "rescue",
            "always",
            "block",
            "break",
            "continue",
            "use",
            "plugin",
            "with",
            "params",
            "register",
            "artifacts",
            "artifact",
        }

    @staticmethod
    def _validate_known_keys(node: Dict[str, Any], label: str, allowed: set[str]) -> None:
        unknown = sorted(set(node) - allowed)
        if unknown:
            raise AutomaxError(
                f"{label} has unsupported keys: {', '.join(unknown)}. "
                f"Allowed keys: {', '.join(sorted(allowed))}"
            )

    def _load_documents(self, **paths: str | None) -> Dict[str, Dict[str, Any]]:
        return {
            "job": load_yaml_file(paths["job_path"]),
            "vars": load_yaml_file(paths.get("vars_path"), required=False)
            if paths.get("vars_path")
            else {},
            "secrets": load_yaml_file(paths.get("secrets_path"), required=False)
            if paths.get("secrets_path")
            else {},
        }

    @staticmethod
    def _path_parent(path: str | None) -> Path | None:
        if not path:
            return None
        return Path(path).expanduser().resolve().parent

    @staticmethod
    def _merge_variables(*sources: Dict[str, Any]) -> Dict[str, Any]:
        merged: Dict[str, Any] = {}
        for source in sources:
            if not source:
                continue
            values = source.get("vars", source)
            if not isinstance(values, dict):
                raise AutomaxError("vars file/root must be a mapping")
            merged.update(values)
        return merged

    def _build_plan(
        self,
        job: Dict[str, Any],
        inventory: Inventory,
        *,
        limit: Iterable[str],
        exclude: Iterable[str],
        tags: Iterable[str] = (),
        skip_tags: Iterable[str] = (),
    ) -> List[Dict[str, Any]]:
        selected_tags = {str(tag) for tag in tags}
        skipped_tags = {str(tag) for tag in skip_tags}
        plan = []
        for task in job["tasks"]:
            task_selector = task.get("targets", job.get("targets", "all"))
            task_targets = inventory.select(
                task_selector,
                limit=list(limit),
                exclude=list(exclude),
            )
            if not task_targets:
                raise AutomaxError(f"task '{task['id']}' resolved no targets")
            for step in task["steps"]:
                step_selector = step.get("targets", task_selector)
                step_targets = inventory.select(
                    step_selector,
                    limit=list(limit),
                    exclude=list(exclude),
                )
                if not step_targets:
                    raise AutomaxError(
                        f"step '{task['id']}:{step['id']}' resolved no targets"
                    )
                for substep in step["substeps"]:
                    effective_tags = self._effective_tags(job, task, step, substep)
                    if not self._tag_selected(effective_tags, selected_tags, skipped_tags):
                        continue
                    substep_selector = substep.get("targets", step_selector)
                    substep_targets = inventory.select(
                        substep_selector,
                        limit=list(limit),
                        exclude=list(exclude),
                    )
                    if not substep_targets:
                        raise AutomaxError(
                            f"substep '{task['id']}:{step['id']}:{substep['id']}' resolved no targets"
                        )
                    for target in substep_targets:
                        plan.append(
                            {
                                "node_id": self._node_id(task, step, substep),
                                "target": target,
                                "task": task,
                                "step": step,
                                "substep": substep,
                                "tags": tuple(sorted(effective_tags)),
                            }
                        )
        if not plan:
            raise AutomaxError("job plan is empty after target/tag filtering")
        return plan

    def _plan_requires_capability_preflight(
        self,
        *,
        job: Dict[str, Any],
        plan: List[Dict[str, Any]],
        variables: Dict[str, Any],
        secrets: Dict[str, Any],
    ) -> bool:
        resolved = ResolvedJobContext(
            job_path="",
            inventory_path="",
            vars_path=None,
            secrets_path=None,
            documents={},
            job=job,
            inventory=None,  # type: ignore[arg-type]
            variables=variables,
            secrets=secrets,
            plan=plan,
        )
        requirements = collect_requirements(self.iter_rendered_plan_items(resolved, dry_run=True))
        return any(item["tools"] for item in requirements.values())

    def _detect_os_for_plan(self, plan: List[Dict[str, Any]], secrets: Dict[str, Any]) -> Dict[str, TargetOS]:
        """Detect target OS once per target before capability preflight or install."""
        targets = {item["target"].name: item["target"] for item in plan}.values()
        return self._detect_os_for_targets(targets, secrets)

    def _detect_os_for_targets(self, targets: Iterable[Target], secrets: Dict[str, Any]) -> Dict[str, TargetOS]:
        """Detect operating-system facts once for each target."""
        detected: Dict[str, TargetOS] = {}
        for target in targets:
            with self.ssh_manager.connect(target) as client:
                _stdin, stdout, stderr = client.exec_command(DETECT_OS_COMMAND)
                rc = stdout.channel.recv_exit_status()
                out = stdout.read().decode("utf-8", errors="replace")
                err = stderr.read().decode("utf-8", errors="replace")
            if rc != 0 or not out.strip():
                detail = self._mask_text((out + "\n" + err).strip(), secrets)
                raise AutomaxError(f"OS detection failed for {target.name}: {detail}")
            detected[target.name] = parse_os_release(out)
        return detected

    @staticmethod
    def _os_to_mapping(os_info: TargetOS) -> Dict[str, Any]:
        return {
            "id": os_info.id,
            "id_like": list(os_info.id_like),
            "name": os_info.name,
            "pretty_name": os_info.pretty_name,
            "version": os_info.version,
            "version_id": os_info.version_id,
            "version_codename": os_info.version_codename,
            "family": os_info.family,
            "package_manager": os_info.package_manager,
        }

    def _plan_target_by_name(self, plan: Iterable[Dict[str, Any]], target_name: str) -> Target:
        return next(item["target"] for item in plan if item["target"].name == target_name)

    def _packages_for_tools(self, tools: Iterable[str], os_family: str) -> list[str]:
        return sorted({package for tool in tools if (package := package_for_tool(tool, os_family))})

    def _unresolved_tools(self, tools: Iterable[str], os_family: str) -> list[str]:
        return sorted(tool for tool in tools if package_for_tool(tool, os_family) is None)

    def _annotate_missing_capabilities(self, requirements: Dict[str, Dict[str, Any]], plan: Iterable[Dict[str, Any]]) -> None:
        for target_name in sorted(requirements):
            entry = requirements[target_name]
            target = self._plan_target_by_name(plan, target_name)
            missing_tools = self._missing_tools(target, entry["tools"])
            missing_set = set(missing_tools)
            entry["present_tools"] = sorted(tool for tool in entry["tools"] if tool not in missing_set)
            entry["missing_tools"] = missing_tools
            entry["missing_packages"] = self._packages_for_tools(missing_tools, entry["os"]["family"])
            entry["unresolved_tools"] = self._unresolved_tools(missing_tools, entry["os"]["family"])

    def _missing_tools(self, target: Target, tools: Iterable[str]) -> list[str]:
        if not tools:
            return []
        command = "missing=0; " + " ".join(
            f"command -v {tool} >/dev/null 2>&1 || {{ echo {tool}; missing=1; }};"
            for tool in sorted(set(tools))
        ) + " exit 0"
        with self.ssh_manager.connect(target) as client:
            _stdin, stdout, _stderr = client.exec_command(command)
            stdout.channel.recv_exit_status()
            out = stdout.read().decode("utf-8", errors="replace")
        return sorted({line.strip() for line in out.splitlines() if line.strip()})

    @staticmethod
    def _resolve_sudo_password(sudo_password_env: str | None) -> str | None:
        if not sudo_password_env:
            return None
        if sudo_password_env not in os.environ:
            raise AutomaxError(f"sudo password environment variable is not set: {sudo_password_env}")
        return os.environ[sudo_password_env]

    def _install_packages_for_os(
        self,
        *,
        target: Target,
        os_family: str,
        packages: list[str],
        sudo_password: str | None,
    ) -> tuple[int, str, str]:
        if not packages:
            return 0, "", ""
        package_args = " ".join(shlex.quote(package) for package in packages)
        sudo = "sudo -n"
        if os_family == "debian":
            apt_env = "DEBIAN_FRONTEND=noninteractive APT_LISTCHANGES_FRONTEND=none"
            apt_opts = "-o Dpkg::Use-Pty=0 -o APT::Color=0"
            command = (
                f"{sudo} env {apt_env} apt-get {apt_opts} update -qq && "
                f"{sudo} env {apt_env} apt-get {apt_opts} install -y -qq {package_args}"
            )
        elif os_family == "rhel":
            command = (
                f"if command -v dnf >/dev/null 2>&1; then {sudo} dnf -q install -y {package_args}; "
                f"else {sudo} yum -q install -y {package_args}; fi"
            )
        else:
            return 2, "", f"unsupported OS family for dependency install: {os_family}"
        command, sudo_stdin = prepare_sudo_password_command(command, sudo_password)
        with self.ssh_manager.connect(target) as client:
            stdin, stdout, stderr = client.exec_command(command, get_pty=False)
            if sudo_stdin:
                stdin.write(sudo_stdin)
                stdin.channel.shutdown_write()
            rc = stdout.channel.recv_exit_status()
            out = stdout.read().decode("utf-8", errors="replace")
            err = stderr.read().decode("utf-8", errors="replace")
        return rc, out, err

    def _run_capability_preflight(
        self,
        *,
        job: Dict[str, Any],
        plan: List[Dict[str, Any]],
        variables: Dict[str, Any],
        secrets: Dict[str, Any],
        os_by_target: Dict[str, TargetOS] | None = None,
    ) -> None:
        """Check remote tools required by the selected job before executing it."""
        rendered_items = []
        resolved = ResolvedJobContext(
            job_path="",
            inventory_path="",
            vars_path=None,
            secrets_path=None,
            documents={},
            job=job,
            inventory=None,  # type: ignore[arg-type]
            variables=variables,
            secrets=secrets,
            plan=plan,
        )
        rendered_items.extend(self.iter_rendered_plan_items(resolved, dry_run=True))
        requirements = collect_requirements(rendered_items, os_by_target or {})
        for target_name, entry in requirements.items():
            tools = entry["tools"]
            if not tools:
                continue
            target = next(item["target"] for item in plan if item["target"].name == target_name)
            command = "missing=0; " + " ".join(
                f"command -v {tool} >/dev/null 2>&1 || {{ echo 'missing tool: {tool}' >&2; missing=1; }};"
                for tool in tools
            ) + " exit $missing"
            with self.ssh_manager.connect(target) as client:
                stdin, stdout, stderr = client.exec_command(command)
                rc = stdout.channel.recv_exit_status()
                out = stdout.read().decode("utf-8", errors="replace")
                err = stderr.read().decode("utf-8", errors="replace")
            if rc != 0:
                detail = self._mask_text((out + "\n" + err).strip(), secrets)
                raise AutomaxError(f"capability preflight failed for {target_name}: {detail}")

    def _execute_plan(
        self,
        *,
        job: Dict[str, Any],
        plan: List[Dict[str, Any]],
        store: StateStore,
        run_id: str,
        dry_run: bool,
        variables: Dict[str, Any],
        secrets: Dict[str, Any],
        from_node: str | None,
        skip_successful: bool = False,
        only_failed: bool = False,
        output_format: str = "text",
        sudo_password: str | None = None,
    ) -> int:
        outputs: Dict[str, Any] = {}
        started = from_node is None
        failed_hosts: set[str] = set()
        stopped_tasks: set[str] = set()
        rc = 0
        previous_statuses = store.node_status_map() if (skip_successful or only_failed) else {}

        stages = self._group_by_stage(plan)
        for stage in stages:
            stage_groups: List[List[Dict[str, Any]]] = []
            for original_group in stage:
                group = self._filter_group_by_resume_status(
                    original_group,
                    previous_statuses=previous_statuses,
                    skip_successful=skip_successful,
                    only_failed=only_failed,
                )
                if not group:
                    continue
                task = group[0]["task"]
                target = group[0]["target"]
                if task["id"] in stopped_tasks:
                    self._mark_group_skipped(store, group, "skipped by failure policy stop_task")
                    continue
                if target.name in failed_hosts:
                    self._mark_group_skipped(store, group, "skipped by failure policy stop_host")
                    continue
                restart_index = self._restart_index(group, from_node) if from_node else 0
                if from_node and restart_index is not None:
                    started = True
                    if restart_index > 0:
                        self._mark_group_skipped(
                            store,
                            group[:restart_index],
                            f"skipped before restart point {from_node}",
                        )
                    stage_groups.append(group[restart_index:])
                    continue
                if not started:
                    self._mark_group_skipped(
                        store,
                        group,
                        f"skipped before restart point {from_node}",
                    )
                    continue
                stage_groups.append(group)

            if not stage_groups:
                continue

            strategy = self._resolve_strategy(job, stage_groups[0][0]["task"], stage_groups[0][0]["step"])
            results = self._execute_stage(
                job=job,
                groups=stage_groups,
                store=store,
                run_id=run_id,
                dry_run=dry_run,
                variables=variables,
                secrets=secrets,
                outputs=outputs,
                strategy=strategy,
                output_format=output_format,
                sudo_password=sudo_password,
            )
            for group, group_rc, failed_by_exception in results:
                if group_rc == 0:
                    continue
                rc = 1
                policy = self._resolve_failure_policy(job, group[0]["task"], group[0]["step"])
                action_key = "onUnreachable" if failed_by_exception else "onFailure"
                action = str(policy.get(action_key, policy.get("onFailure", "stop_job")))
                target_name = group[0]["target"].name
                task_id = group[0]["task"]["id"]
                if action == "continue":
                    continue
                if action == "stop_host":
                    failed_hosts.add(target_name)
                    if self._max_failed_hosts_reached(failed_hosts, policy):
                        return 1
                    continue
                if action == "stop_task":
                    stopped_tasks.add(task_id)
                    continue
                return 1
        return rc

    @staticmethod
    def _filter_group_by_resume_status(
        group: List[Dict[str, Any]],
        *,
        previous_statuses: Dict[tuple[str, str], str],
        skip_successful: bool,
        only_failed: bool,
    ) -> List[Dict[str, Any]]:
        """Filter a step group for resume modes without rewriting existing rows."""
        if not previous_statuses or not (skip_successful or only_failed):
            return group
        filtered: List[Dict[str, Any]] = []
        for item in group:
            key = (item["node_id"], item["target"].name)
            status = previous_statuses.get(key)
            if only_failed:
                if status == NodeStatus.FAILED.value:
                    filtered.append(item)
                continue
            if skip_successful and status in {NodeStatus.SUCCESS.value, NodeStatus.WARNING.value}:
                continue
            filtered.append(item)
        return filtered

    def _execute_stage(
        self,
        *,
        job: Dict[str, Any],
        groups: List[List[Dict[str, Any]]],
        store: StateStore,
        run_id: str,
        dry_run: bool,
        variables: Dict[str, Any],
        secrets: Dict[str, Any],
        outputs: Dict[str, Any],
        strategy: Dict[str, Any],
        output_format: str,
        sudo_password: str | None,
    ) -> List[tuple[List[Dict[str, Any]], int, bool]]:
        mode = strategy["mode"]
        if mode == "serial":
            return [
                self._execute_group_with_connection(
                    job=job,
                    group=group,
                    store=store,
                    run_id=run_id,
                    dry_run=dry_run,
                    variables=variables,
                    secrets=secrets,
                    outputs=outputs,
                    output_format=output_format,
                    sudo_password=sudo_password,
                )
                for group in groups
            ]

        if mode == "parallel":
            max_parallel = int(strategy.get("max_parallel", len(groups)) or len(groups))
            return self._execute_group_chunks(
                job=job,
                groups=self._chunks(groups, max_parallel),
                store=store,
                run_id=run_id,
                dry_run=dry_run,
                variables=variables,
                secrets=secrets,
                outputs=outputs,
                output_format=output_format,
                sudo_password=sudo_password,
            )

        if mode == "rolling":
            batch_size = int(strategy.get("batch_size", 1) or 1)
            pause = float(strategy.get("pause_between_batches", 0) or 0)
            results: List[tuple[List[Dict[str, Any]], int, bool]] = []
            chunks = list(self._chunks(groups, batch_size))
            for index, chunk in enumerate(chunks):
                results.extend(
                    self._execute_group_chunks(
                        job=job,
                        groups=[chunk],
                        store=store,
                        run_id=run_id,
                        dry_run=dry_run,
                        variables=variables,
                        secrets=secrets,
                        outputs=outputs,
                        output_format=output_format,
                        sudo_password=sudo_password,
                    )
                )
                if pause > 0 and index < len(chunks) - 1:
                    time.sleep(pause)
            return results

        raise AutomaxError(f"unsupported strategy mode: {mode}")

    def _execute_group_chunks(
        self,
        *,
        job: Dict[str, Any],
        groups: Iterable[List[List[Dict[str, Any]]]],
        store: StateStore,
        run_id: str,
        dry_run: bool,
        variables: Dict[str, Any],
        secrets: Dict[str, Any],
        outputs: Dict[str, Any],
        output_format: str,
        sudo_password: str | None,
    ) -> List[tuple[List[Dict[str, Any]], int, bool]]:
        results: List[tuple[List[Dict[str, Any]], int, bool]] = []
        for chunk in groups:
            with ThreadPoolExecutor(max_workers=len(chunk)) as executor:
                futures = {
                    executor.submit(
                        self._execute_group_with_connection,
                        job=job,
                        group=group,
                        store=store,
                        run_id=run_id,
                        dry_run=dry_run,
                        variables=variables,
                        secrets=secrets,
                        outputs=outputs,
                        output_format=output_format,
                        sudo_password=sudo_password,
                    ): group
                    for group in chunk
                }
                for future in as_completed(futures):
                    results.append(future.result())
        return results

    def _execute_group_with_connection(
        self,
        *,
        job: Dict[str, Any],
        group: List[Dict[str, Any]],
        store: StateStore,
        run_id: str,
        dry_run: bool,
        variables: Dict[str, Any],
        secrets: Dict[str, Any],
        outputs: Dict[str, Any],
        output_format: str,
        sudo_password: str | None,
    ) -> tuple[List[Dict[str, Any]], int, bool]:
        first = group[0]
        task = first["task"]
        step = first["step"]
        target = self._target_with_step_timeouts(first["target"], job, task, step)
        group = [dict(item, target=target) for item in group]
        needs_ssh = any(self._substep_needs_ssh(item["substep"]) for item in group)
        try:
            if needs_ssh:
                with self.ssh_manager.connect(target) as ssh_client:
                    group_rc = self._execute_step_group(
                        job=job,
                        group=group,
                        store=store,
                        run_id=run_id,
                        dry_run=dry_run,
                        variables=variables,
                        secrets=secrets,
                        outputs=outputs,
                        ssh_client=ssh_client,
                        output_format=output_format,
                        sudo_password=sudo_password,
                    )
            else:
                group_rc = self._execute_step_group(
                    job=job,
                    group=group,
                    store=store,
                    run_id=run_id,
                    dry_run=dry_run,
                    variables=variables,
                    secrets=secrets,
                    outputs=outputs,
                    ssh_client=None,
                    output_format=output_format,
                    sudo_password=sudo_password,
                )
            return group, group_rc, False
        except Exception as exc:
            for item in group:
                store.start_node(
                    node_id=item["node_id"],
                    target=target.name,
                    task_id=task["id"],
                    step_id=step["id"],
                    substep_id=item["substep"]["id"],
                )
                store.finish_node(
                    node_id=item["node_id"],
                    target=target.name,
                    status=NodeStatus.FAILED,
                    rc=1,
                    message=self._mask_text(str(exc), secrets),
                )
            return group, 1, True

    def _execute_step_group(
        self,
        *,
        job: Dict[str, Any],
        group: List[Dict[str, Any]],
        store: StateStore,
        run_id: str,
        dry_run: bool,
        variables: Dict[str, Any],
        secrets: Dict[str, Any],
        outputs: Dict[str, Any],
        ssh_client: Any,
        output_format: str,
        sudo_password: str | None,
    ) -> int:
        step_state: Dict[str, Any] = {}
        for item in group:
            result = self._execute_item(
                job=job,
                item=item,
                store=store,
                run_id=run_id,
                dry_run=dry_run,
                variables=variables,
                secrets=secrets,
                outputs=outputs,
                ssh_client=ssh_client,
                step_state=step_state,
                output_format=output_format,
                sudo_password=sudo_password,
                flow_vars={},
            )
            if not result.ok:
                return 1
        return 0

    def _execute_item(
        self,
        *,
        job: Dict[str, Any],
        item: Dict[str, Any],
        store: StateStore,
        run_id: str,
        dry_run: bool,
        variables: Dict[str, Any],
        secrets: Dict[str, Any],
        outputs: Dict[str, Any],
        ssh_client: Any,
        step_state: Dict[str, Any],
        output_format: str,
        sudo_password: str | None,
        flow_vars: Dict[str, Any],
    ) -> PluginResult:
        substep = item["substep"]
        if self._is_flow_substep(substep):
            return self._execute_flow_item(
                job=job,
                item=item,
                store=store,
                run_id=run_id,
                dry_run=dry_run,
                variables=variables,
                secrets=secrets,
                outputs=outputs,
                ssh_client=ssh_client,
                step_state=step_state,
                output_format=output_format,
                sudo_password=sudo_password,
                flow_vars=flow_vars,
            )
        return self._execute_leaf_item(
            job=job,
            item=item,
            store=store,
            run_id=run_id,
            dry_run=dry_run,
            variables=variables,
            secrets=secrets,
            outputs=outputs,
            ssh_client=ssh_client,
            step_state=step_state,
            output_format=output_format,
            sudo_password=sudo_password,
            flow_vars=flow_vars,
        )

    def _execute_leaf_item(
        self,
        *,
        job: Dict[str, Any],
        item: Dict[str, Any],
        store: StateStore,
        run_id: str,
        dry_run: bool,
        variables: Dict[str, Any],
        secrets: Dict[str, Any],
        outputs: Dict[str, Any],
        ssh_client: Any,
        step_state: Dict[str, Any],
        output_format: str,
        sudo_password: str | None,
        flow_vars: Dict[str, Any],
    ) -> PluginResult:
        task = item["task"]
        step = item["step"]
        substep = item["substep"]
        target = item["target"]
        node_id = item["node_id"]
        store.start_node(
            node_id=node_id,
            target=target.name,
            task_id=task["id"],
            step_id=step["id"],
            substep_id=substep["id"],
        )
        result = self._execute_substep_with_retry(
            job=job,
            task=task,
            step=step,
            substep=substep,
            target=target,
            node_id=node_id,
            store=store,
            run_id=run_id,
            dry_run=dry_run,
            variables=variables,
            secrets=secrets,
            outputs=outputs,
            ssh_client=ssh_client,
            step_state=step_state,
            output_format=output_format,
            sudo_password=sudo_password,
            flow_vars=flow_vars,
        )

        with self._output_lock:
            self._register_outputs(outputs, node_id, target.name, substep, result)
        artifact_error = self._capture_declared_artifacts(
            store=store,
            job=job,
            item=item,
            result=result,
            variables=variables,
            secrets=secrets,
            outputs=outputs,
            flow_vars=flow_vars,
        )
        if artifact_error:
            result = PluginResult.failure(message=artifact_error)
        self._finish_item_node(
            store=store,
            item=item,
            result=result,
            secrets=secrets,
            output_format=output_format,
        )
        return result

    def _execute_flow_item(
        self,
        *,
        job: Dict[str, Any],
        item: Dict[str, Any],
        store: StateStore,
        run_id: str,
        dry_run: bool,
        variables: Dict[str, Any],
        secrets: Dict[str, Any],
        outputs: Dict[str, Any],
        ssh_client: Any,
        step_state: Dict[str, Any],
        output_format: str,
        sudo_password: str | None,
        flow_vars: Dict[str, Any],
    ) -> PluginResult:
        task = item["task"]
        step = item["step"]
        substep = item["substep"]
        target = item["target"]
        node_id = item["node_id"]
        store.start_node(
            node_id=node_id,
            target=target.name,
            task_id=task["id"],
            step_id=step["id"],
            substep_id=substep["id"],
        )
        context = self._template_context(
            job=job,
            task=task,
            step=step,
            substep=substep,
            target=target,
            variables=variables,
            outputs=outputs,
            secrets=secrets,
            step_state=step_state,
            flow_vars=flow_vars,
        )
        if not self._is_condition_true(substep.get("when"), context):
            result = PluginResult.skipped_result("condition evaluated to false")
            self._finish_item_node(store=store, item=item, result=result, secrets=secrets, output_format=output_format)
            return result
        if self._is_if_substep(substep):
            result = self._execute_if_flow(
                job=job,
                item=item,
                store=store,
                run_id=run_id,
                dry_run=dry_run,
                variables=variables,
                secrets=secrets,
                outputs=outputs,
                ssh_client=ssh_client,
                step_state=step_state,
                output_format=output_format,
                sudo_password=sudo_password,
                flow_vars=flow_vars,
                context=context,
            )
        elif self._is_switch_substep(substep):
            result = self._execute_switch_flow(
                job=job,
                item=item,
                store=store,
                run_id=run_id,
                dry_run=dry_run,
                variables=variables,
                secrets=secrets,
                outputs=outputs,
                ssh_client=ssh_client,
                step_state=step_state,
                output_format=output_format,
                sudo_password=sudo_password,
                flow_vars=flow_vars,
                context=context,
            )
        elif self._is_retry_flow_substep(substep):
            result = self._execute_retry_flow(
                job=job,
                item=item,
                store=store,
                run_id=run_id,
                dry_run=dry_run,
                variables=variables,
                secrets=secrets,
                outputs=outputs,
                ssh_client=ssh_client,
                step_state=step_state,
                output_format=output_format,
                sudo_password=sudo_password,
                flow_vars=flow_vars,
            )
        elif self._is_for_substep(substep):
            result = self._execute_for_flow(
                job=job,
                item=item,
                store=store,
                run_id=run_id,
                dry_run=dry_run,
                variables=variables,
                secrets=secrets,
                outputs=outputs,
                ssh_client=ssh_client,
                step_state=step_state,
                output_format=output_format,
                sudo_password=sudo_password,
                flow_vars=flow_vars,
                context=context,
            )
        elif self._is_try_substep(substep):
            result = self._execute_try_flow(
                job=job,
                item=item,
                store=store,
                run_id=run_id,
                dry_run=dry_run,
                variables=variables,
                secrets=secrets,
                outputs=outputs,
                ssh_client=ssh_client,
                step_state=step_state,
                output_format=output_format,
                sudo_password=sudo_password,
                flow_vars=flow_vars,
            )
        elif self._is_block_substep(substep):
            result = self._execute_child_block(
                job=job,
                item=item,
                branch="block",
                children=substep.get("block", []) or [],
                store=store,
                run_id=run_id,
                dry_run=dry_run,
                variables=variables,
                secrets=secrets,
                outputs=outputs,
                ssh_client=ssh_client,
                step_state=step_state,
                output_format=output_format,
                sudo_password=sudo_password,
                flow_vars=flow_vars,
            )
        elif self._is_assignment_substep(substep):
            result = self._execute_assignment_flow(item=item, outputs=outputs, step_state=step_state, flow_vars=flow_vars, context=context)
        elif self._is_noop_substep(substep):
            result = self._execute_noop_flow(substep, context)
        elif self._is_sleep_substep(substep):
            result = self._execute_sleep_flow(substep, context, dry_run=dry_run)
        elif self._is_assert_substep(substep):
            result = self._execute_assert_flow(substep, context)
        elif self._is_echo_substep(substep):
            result = self._execute_echo_flow(substep, context)
        elif self._is_fail_substep(substep):
            result = self._execute_fail_flow(substep, context)
        elif self._is_break_substep(substep):
            result = self._execute_loop_control_flow("break", flow_vars)
        elif self._is_continue_substep(substep):
            result = self._execute_loop_control_flow("continue", flow_vars)
        else:
            result = PluginResult.failure(message="unsupported flow control substep")
        with self._output_lock:
            self._register_outputs(outputs, node_id, target.name, substep, result)
        self._finish_item_node(store=store, item=item, result=result, secrets=secrets, output_format=output_format)
        return result

    def _execute_if_flow(
        self,
        *,
        job: Dict[str, Any],
        item: Dict[str, Any],
        store: StateStore,
        run_id: str,
        dry_run: bool,
        variables: Dict[str, Any],
        secrets: Dict[str, Any],
        outputs: Dict[str, Any],
        ssh_client: Any,
        step_state: Dict[str, Any],
        output_format: str,
        sudo_password: str | None,
        flow_vars: Dict[str, Any],
        context: Dict[str, Any],
    ) -> PluginResult:
        substep = item["substep"]
        selected = self._selected_if_branch(substep, context)
        executed = 0
        for child in selected["then"]:
            child_item = self._child_item(item, child, selected["segment"])
            child_result = self._execute_item(
                job=job,
                item=child_item,
                store=store,
                run_id=run_id,
                dry_run=dry_run,
                variables=variables,
                secrets=secrets,
                outputs=outputs,
                ssh_client=ssh_client,
                step_state=step_state,
                output_format=output_format,
                sudo_password=sudo_password,
                flow_vars=flow_vars,
            )
            executed += 1
            if self._flow_control_signal(child_result):
                return child_result
            if not child_result.ok:
                return PluginResult.failure(message=f"if {selected['segment']} branch failed", data={"flow": "if", "branch": selected["segment"], "executed": executed})
        return PluginResult.success(changed=False, message=f"if {selected['segment']} branch executed", data={"flow": "if", "branch": selected["segment"], "executed": executed})

    def _execute_retry_flow(
        self,
        *,
        job: Dict[str, Any],
        item: Dict[str, Any],
        store: StateStore,
        run_id: str,
        dry_run: bool,
        variables: Dict[str, Any],
        secrets: Dict[str, Any],
        outputs: Dict[str, Any],
        ssh_client: Any,
        step_state: Dict[str, Any],
        output_format: str,
        sudo_password: str | None,
        flow_vars: Dict[str, Any],
    ) -> PluginResult:
        policy = dict(item["substep"].get("retry", {}) or {})
        children = policy.get("do", []) or []
        attempts = int(policy.get("attempts", 1) or 1)
        interval = self._duration_seconds(policy.get("interval", policy.get("delay", 0)), "retry interval")
        backoff = str(policy.get("backoff", "fixed"))
        result = PluginResult.success(changed=False, data={"executed": 0})
        for attempt in range(1, attempts + 1):
            result = self._execute_child_block(
                job=job,
                item=item,
                branch="retry",
                children=children,
                store=store,
                run_id=run_id,
                dry_run=dry_run,
                variables=variables,
                secrets=secrets,
                outputs=outputs,
                ssh_client=ssh_client,
                step_state=step_state,
                output_format=output_format,
                sudo_password=sudo_password,
                flow_vars=flow_vars,
            )
            if self._flow_control_signal(result) or result.ok or attempt >= attempts:
                break
            delay = interval * (2 ** max(0, attempt - 1)) if backoff == "exponential" else interval
            store.record_event(
                "flow_retry",
                node_id=item["node_id"],
                target=item["target"].name,
                payload={"attempt": attempt, "attempts": attempts, "delay": delay},
            )
            if output_format == "text":
                with self._print_lock:
                    print(f"[RETRY] {item['target'].name} {item['node_id']} attempt={attempt}/{attempts}")
            if delay > 0 and not dry_run:
                time.sleep(delay)
        if self._flow_control_signal(result):
            return result
        if result.ok:
            return PluginResult.success(
                changed=False,
                message="retry flow executed",
                data={"flow": "retry", "attempts": attempt, "result": self._result_to_mapping(result)},
            )
        return PluginResult.failure(
            message="retry flow exhausted",
            data={"flow": "retry", "attempts": attempts, "result": self._result_to_mapping(result)},
        )

    def _execute_switch_flow(
        self,
        *,
        job: Dict[str, Any],
        item: Dict[str, Any],
        store: StateStore,
        run_id: str,
        dry_run: bool,
        variables: Dict[str, Any],
        secrets: Dict[str, Any],
        outputs: Dict[str, Any],
        ssh_client: Any,
        step_state: Dict[str, Any],
        output_format: str,
        sudo_password: str | None,
        flow_vars: Dict[str, Any],
        context: Dict[str, Any],
    ) -> PluginResult:
        substep = item["substep"]
        selected = self._selected_switch_branch(substep, context)
        executed = 0
        for child in selected["then"]:
            child_item = self._child_item(item, child, selected["segment"])
            child_result = self._execute_item(
                job=job,
                item=child_item,
                store=store,
                run_id=run_id,
                dry_run=dry_run,
                variables=variables,
                secrets=secrets,
                outputs=outputs,
                ssh_client=ssh_client,
                step_state=step_state,
                output_format=output_format,
                sudo_password=sudo_password,
                flow_vars=flow_vars,
            )
            executed += 1
            if self._flow_control_signal(child_result):
                return child_result
            if not child_result.ok:
                return PluginResult.failure(
                    message=f"switch {selected['segment']} branch failed",
                    data={"flow": "switch", "branch": selected["segment"], "executed": executed},
                )
        return PluginResult.success(
            changed=False,
            message=f"switch {selected['segment']} branch executed",
            data={"flow": "switch", "branch": selected["segment"], "executed": executed},
        )

    def _execute_for_flow(
        self,
        *,
        job: Dict[str, Any],
        item: Dict[str, Any],
        store: StateStore,
        run_id: str,
        dry_run: bool,
        variables: Dict[str, Any],
        secrets: Dict[str, Any],
        outputs: Dict[str, Any],
        ssh_client: Any,
        step_state: Dict[str, Any],
        output_format: str,
        sudo_password: str | None,
        flow_vars: Dict[str, Any],
        context: Dict[str, Any],
    ) -> PluginResult:
        substep = item["substep"]
        loop_var = str(substep["for"])
        values = self._loop_values(evaluate_value(substep.get("in"), context))
        children = substep.get("do", []) or []
        for index, value in enumerate(values):
            loop_vars = dict(flow_vars)
            loop_vars[loop_var] = value
            loop_vars["item"] = value
            loop_vars["loop"] = {
                "index": index + 1,
                "index0": index,
                "first": index == 0,
                "last": index == len(values) - 1,
                "length": len(values),
            }
            for child in children:
                child_item = self._child_item(item, child, f"for.{index}")
                child_result = self._execute_item(
                    job=job,
                    item=child_item,
                    store=store,
                    run_id=run_id,
                    dry_run=dry_run,
                    variables=variables,
                    secrets=secrets,
                    outputs=outputs,
                    ssh_client=ssh_client,
                    step_state=step_state,
                    output_format=output_format,
                    sudo_password=sudo_password,
                    flow_vars=loop_vars,
                )
                signal = self._flow_control_signal(child_result)
                if signal == "continue":
                    break
                if signal == "break":
                    return PluginResult.success(
                        changed=False,
                        message=f"for loop stopped at {loop_var}[{index}]",
                        data={"flow": "for", "variable": loop_var, "index": index, "iterations": len(values), "break": True},
                    )
                if not child_result.ok:
                    return PluginResult.failure(
                        message=f"for loop failed at {loop_var}[{index}]",
                        data={"flow": "for", "variable": loop_var, "index": index, "iterations": len(values)},
                    )
        return PluginResult.success(
            changed=False,
            message=f"for loop executed {len(values)} iteration(s)",
            data={"flow": "for", "variable": loop_var, "iterations": len(values)},
        )

    def _execute_try_flow(
        self,
        *,
        job: Dict[str, Any],
        item: Dict[str, Any],
        store: StateStore,
        run_id: str,
        dry_run: bool,
        variables: Dict[str, Any],
        secrets: Dict[str, Any],
        outputs: Dict[str, Any],
        ssh_client: Any,
        step_state: Dict[str, Any],
        output_format: str,
        sudo_password: str | None,
        flow_vars: Dict[str, Any],
    ) -> PluginResult:
        substep = item["substep"]
        try_result = self._execute_child_block(
            job=job,
            item=item,
            branch="try",
            children=substep.get("try", []) or [],
            store=store,
            run_id=run_id,
            dry_run=dry_run,
            variables=variables,
            secrets=secrets,
            outputs=outputs,
            ssh_client=ssh_client,
            step_state=step_state,
            output_format=output_format,
            sudo_password=sudo_password,
            flow_vars=flow_vars,
        )
        result = try_result
        rescued = False
        signal = self._flow_control_signal(try_result)
        if not signal and not try_result.ok and substep.get("rescue"):
            rescued = True
            result = self._execute_child_block(
                job=job,
                item=item,
                branch="rescue",
                children=substep.get("rescue", []) or [],
                store=store,
                run_id=run_id,
                dry_run=dry_run,
                variables=variables,
                secrets=secrets,
                outputs=outputs,
                ssh_client=ssh_client,
                step_state=step_state,
                output_format=output_format,
                sudo_password=sudo_password,
                flow_vars=flow_vars,
            )
        always_result = PluginResult.success(changed=False, data={"executed": 0})
        if substep.get("always"):
            always_result = self._execute_child_block(
                job=job,
                item=item,
                branch="always",
                children=substep.get("always", []) or [],
                store=store,
                run_id=run_id,
                dry_run=dry_run,
                variables=variables,
                secrets=secrets,
                outputs=outputs,
                ssh_client=ssh_client,
                step_state=step_state,
                output_format=output_format,
                sudo_password=sudo_password,
                flow_vars=flow_vars,
            )
        if not always_result.ok:
            return PluginResult.failure(
                message="try always branch failed",
                data={"flow": "try", "rescued": rescued, "try": self._result_to_mapping(try_result), "always": self._result_to_mapping(always_result)},
            )
        if self._flow_control_signal(result):
            return result
        if not result.ok:
            return PluginResult.failure(
                message="try branch failed",
                data={"flow": "try", "rescued": False, "try": self._result_to_mapping(try_result)},
            )
        return PluginResult.success(
            changed=False,
            message="try flow executed",
            data={
                "flow": "try",
                "rescued": rescued,
                "try": self._result_to_mapping(try_result),
                "always": self._result_to_mapping(always_result),
            },
        )

    def _execute_child_block(
        self,
        *,
        job: Dict[str, Any],
        item: Dict[str, Any],
        branch: str,
        children: list[Dict[str, Any]],
        store: StateStore,
        run_id: str,
        dry_run: bool,
        variables: Dict[str, Any],
        secrets: Dict[str, Any],
        outputs: Dict[str, Any],
        ssh_client: Any,
        step_state: Dict[str, Any],
        output_format: str,
        sudo_password: str | None,
        flow_vars: Dict[str, Any],
    ) -> PluginResult:
        executed = 0
        for child in children:
            child_result = self._execute_item(
                job=job,
                item=self._child_item(item, child, branch),
                store=store,
                run_id=run_id,
                dry_run=dry_run,
                variables=variables,
                secrets=secrets,
                outputs=outputs,
                ssh_client=ssh_client,
                step_state=step_state,
                output_format=output_format,
                sudo_password=sudo_password,
                flow_vars=flow_vars,
            )
            executed += 1
            if self._flow_control_signal(child_result):
                return child_result
            if not child_result.ok:
                return PluginResult.failure(
                    message=f"{branch} branch failed",
                    data={"flow": branch, "executed": executed, "result": self._result_to_mapping(child_result)},
                )
        return PluginResult.success(changed=False, message=f"{branch} branch executed", data={"flow": branch, "executed": executed})

    def _execute_assignment_flow(
        self,
        *,
        item: Dict[str, Any],
        outputs: Dict[str, Any],
        step_state: Dict[str, Any],
        flow_vars: Dict[str, Any],
        context: Dict[str, Any],
    ) -> PluginResult:
        substep = item["substep"]
        assignments = substep.get("set", substep.get("let"))
        values: Dict[str, Any] = {}
        local_context = deepcopy(context)
        local_context.setdefault("vars", {}).update(step_state.get("vars", {}))
        for name, value in assignments.items():
            evaluated = evaluate_value(value, local_context)
            values[name] = evaluated
            local_context[name] = evaluated
            local_context.setdefault("vars", {})[name] = evaluated
            local_context.setdefault("outputs", {})[name] = evaluated
        step_state.setdefault("vars", {}).update(values)
        flow_vars.update(values)
        target_name = item["target"].name
        with self._output_lock:
            for name, value in values.items():
                outputs[name] = value
                outputs.setdefault("targets", {}).setdefault(target_name, {})[name] = value
        return PluginResult.success(changed=False, message="set variables", data={"values": values})

    def _execute_noop_flow(self, substep: Dict[str, Any], context: Dict[str, Any]) -> PluginResult:
        raw = substep.get("noop")
        message = "noop" if raw is True or raw is None else str(evaluate_value(raw, context))
        return PluginResult.success(changed=False, message=message, data={"noop": True})

    def _execute_sleep_flow(self, substep: Dict[str, Any], context: Dict[str, Any], *, dry_run: bool) -> PluginResult:
        seconds = self._duration_seconds(evaluate_value(substep.get("sleep"), context), "sleep")
        if seconds > 0 and not dry_run:
            time.sleep(seconds)
        message = f"sleep {seconds:g}s" + (" skipped in dry-run" if dry_run else "")
        return PluginResult.success(changed=False, message=message, data={"sleep": seconds})

    def _execute_assert_flow(self, substep: Dict[str, Any], context: Dict[str, Any]) -> PluginResult:
        ok = self._is_condition_true(substep.get("assert"), context)
        message = str(evaluate_value(substep.get("message", "assertion failed"), context))
        if ok:
            return PluginResult.success(changed=False, message="assertion passed", data={"assert": True})
        return PluginResult.failure(message=message, data={"assert": False})

    def _execute_echo_flow(self, substep: Dict[str, Any], context: Dict[str, Any]) -> PluginResult:
        value = evaluate_value(substep.get("echo"), context)
        if isinstance(value, (dict, list)):
            text = json.dumps(value, ensure_ascii=False, sort_keys=True)
        else:
            text = str(value)
        return PluginResult.success(stdout=f"{text}\n", message=text, data={"echo": text, "_print_stdout": True})

    def _execute_fail_flow(self, substep: Dict[str, Any], context: Dict[str, Any]) -> PluginResult:
        raw = substep.get("fail")
        if isinstance(raw, dict):
            raw = raw.get("message", "flow failed")
        message = str(evaluate_value(raw if raw is not None else "flow failed", context))
        return PluginResult.failure(message=message, data={"flow": "fail"})

    @staticmethod
    def _execute_loop_control_flow(control: str, flow_vars: Dict[str, Any]) -> PluginResult:
        if "loop" not in flow_vars:
            return PluginResult.failure(message=f"{control} requires an active for loop", data={"flow": control})
        return PluginResult.success(changed=False, message=control, data={"_flow_control": control})

    @staticmethod
    def _flow_control_signal(result: PluginResult) -> str | None:
        signal = result.data.get("_flow_control") if result.data else None
        return str(signal) if signal in {"break", "continue"} else None

    @staticmethod
    def _duration_seconds(value: Any, label: str) -> float:
        if value is None:
            return 0.0
        if isinstance(value, (int, float)):
            seconds = float(value)
        else:
            raw = str(value).strip().lower()
            multiplier = 1.0
            if raw.endswith("ms"):
                raw = raw[:-2]
                multiplier = 0.001
            elif raw.endswith("s"):
                raw = raw[:-1]
            elif raw.endswith("m"):
                raw = raw[:-1]
                multiplier = 60.0
            seconds = float(raw) * multiplier
        if seconds < 0:
            raise AutomaxError(f"{label} must be >= 0")
        return seconds

    @staticmethod
    def _loop_values(value: Any) -> list[Any]:
        if value is None:
            return []
        if isinstance(value, list):
            return value
        if isinstance(value, tuple):
            return list(value)
        if isinstance(value, set):
            return sorted(value)
        if isinstance(value, dict):
            return [{"key": key, "value": item} for key, item in value.items()]
        if isinstance(value, str) and not value.strip():
            return []
        return [value]

    def _selected_switch_branch(self, substep: Dict[str, Any], context: Dict[str, Any]) -> Dict[str, Any]:
        value = evaluate_value(substep.get("switch"), context)
        default_branch: Dict[str, Any] | None = None
        for branch in self._switch_branches(substep):
            if branch.get("default"):
                default_branch = branch
                continue
            if self._switch_case_matches(value, branch["case"]):
                return branch
        if default_branch is not None:
            return default_branch
        return {"segment": "none", "then": []}

    @classmethod
    def _switch_branches(cls, substep: Dict[str, Any], *, label: str = "switch flow") -> list[Dict[str, Any]]:
        cases = substep.get("case")
        branches: list[Dict[str, Any]] = []
        if cases is not None:
            if not isinstance(cases, dict) or not cases:
                raise AutomaxError(f"{label} case must be a non-empty mapping")
            for index, (case_value, children) in enumerate(cases.items()):
                branches.append(
                    {
                        "segment": f"case.{index}",
                        "case": case_value,
                        "then": cls._substep_list(children, f"{label}:case[{case_value}]"),
                    }
                )
        if "default" in substep:
            branches.append(
                {
                    "segment": "default",
                    "default": True,
                    "then": cls._substep_list(substep.get("default"), f"{label}:default"),
                }
            )
        return branches

    @staticmethod
    def _switch_case_matches(value: Any, case_value: Any) -> bool:
        if value == case_value:
            return True
        return str(value) == str(case_value)

    def _selected_if_branch(self, substep: Dict[str, Any], context: Dict[str, Any]) -> Dict[str, Any]:
        for branch in self._if_branches(substep):
            condition = branch.get("condition")
            if condition is None or self._is_condition_true(condition, context):
                return branch
        return {"segment": "none", "then": []}

    @classmethod
    def _if_branches(cls, substep: Dict[str, Any], *, label: str = "if flow") -> list[Dict[str, Any]]:
        raw_if = substep.get("if")
        if isinstance(raw_if, list):
            if "then" in substep or "else" in substep:
                raise AutomaxError(f"{label} list-style if cannot also define top-level 'then' or 'else'")
            branches: list[Dict[str, Any]] = []
            else_seen = False
            for index, raw_branch in enumerate(raw_if):
                if not isinstance(raw_branch, dict):
                    raise AutomaxError(f"{label}:if[{index}] must be a mapping")
                if "else" in raw_branch:
                    if set(raw_branch) != {"else"}:
                        raise AutomaxError(f"{label}:if[{index}] else branch cannot define other keys")
                    if else_seen:
                        raise AutomaxError(f"{label} can define only one else branch")
                    else_seen = True
                    branches.append({"segment": "else", "then": cls._substep_list(raw_branch.get("else"), f"{label}:else")})
                    continue
                if else_seen:
                    raise AutomaxError(f"{label}:if[{index}] cannot appear after else branch")
                if set(raw_branch) != {"when", "then"}:
                    raise AutomaxError(f"{label}:if[{index}] requires exactly 'when' and 'then'")
                branches.append(
                    {
                        "segment": f"if.{index}",
                        "condition": raw_branch.get("when"),
                        "then": cls._substep_list(raw_branch.get("then"), f"{label}:if[{index}]:then"),
                    }
                )
            return branches

        if "then" not in substep and "else" not in substep:
            raise AutomaxError(f"{label} if flow requires 'then' or 'else'")
        return [
            {"segment": "then", "condition": raw_if, "then": cls._substep_list(substep.get("then"), f"{label}:then")},
            {"segment": "else", "then": cls._substep_list(substep.get("else"), f"{label}:else")},
        ]

    @staticmethod
    def _substep_list(value: Any, label: str) -> list[Dict[str, Any]]:
        if value is None:
            return []
        if not isinstance(value, list):
            raise AutomaxError(f"{label} must be a list")
        return value

    @staticmethod
    def _child_item(parent: Dict[str, Any], child: Dict[str, Any], segment: str) -> Dict[str, Any]:
        return {
            **parent,
            "node_id": f"{parent['node_id']}:{segment}.{child['id']}",
            "substep": child,
        }

    def _finish_item_node(
        self,
        *,
        store: StateStore,
        item: Dict[str, Any],
        result: PluginResult,
        secrets: Dict[str, Any],
        output_format: str,
    ) -> None:
        store.finish_node(
            node_id=item["node_id"],
            target=item["target"].name,
            status=self._node_status_for_result(result),
            changed=result.changed,
            rc=result.rc,
            message=self._mask_text(result.message, secrets),
            output=self._result_to_mapping(result, secrets=secrets),
        )
        store.record_event(
            "substep_finished",
            node_id=item["node_id"],
            target=item["target"].name,
            payload={"ok": result.ok, "changed": result.changed, "rc": result.rc},
        )
        if output_format == "text":
            status = "WARN" if result.warning else ("OK" if result.ok else "FAILED")
            with self._print_lock:
                print(
                    f"[{status}] {item['target'].name} {item['node_id']} rc={result.rc} {self._mask_text(result.message, secrets)}".rstrip()
                )
                if result.data.get("_print_stdout") and result.stdout:
                    print(self._mask_text(result.stdout, secrets), end="" if result.stdout.endswith("\n") else "\n")
                if not result.ok:
                    self._print_result_failure_details(result, secrets)

    def _execute_substep_with_retry(
        self,
        *,
        job: Dict[str, Any],
        task: Dict[str, Any],
        step: Dict[str, Any],
        substep: Dict[str, Any],
        target: Target,
        node_id: str,
        store: StateStore,
        run_id: str,
        dry_run: bool,
        variables: Dict[str, Any],
        secrets: Dict[str, Any],
        outputs: Dict[str, Any],
        ssh_client: Any,
        step_state: Dict[str, Any],
        output_format: str,
        sudo_password: str | None,
        flow_vars: Dict[str, Any] | None = None,
    ) -> PluginResult:
        """Execute one substep with inherited retry policy and visible retry events."""
        policy = self._resolve_retry_policy(job, task, step, substep)
        attempts = int(policy["attempts"])
        attempt_records: list[Dict[str, Any]] = []
        result = PluginResult.failure(message="substep did not execute")
        for attempt in range(1, attempts + 1):
            try:
                result = self._execute_substep(
                    job=job,
                    task=task,
                    step=step,
                    substep=substep,
                    target=target,
                    run_id=run_id,
                    dry_run=dry_run,
                    variables=variables,
                    secrets=secrets,
                    outputs=outputs,
                    ssh_client=ssh_client,
                    step_state=step_state,
                    sudo_password=sudo_password,
                    flow_vars=flow_vars or {},
                )
                result = self._apply_error_policy(job, task, step, substep, result, secrets)
            except Exception as exc:
                result = PluginResult.failure(message=str(exc))
            attempt_records.append(
                {
                    "attempt": attempt,
                    "ok": result.ok,
                    "rc": result.rc,
                    "message": self._mask_text(result.message, secrets),
                }
            )
            if result.ok or attempt >= attempts or not self._should_retry_result(result, policy):
                break
            delay = self._retry_delay(policy, attempt)
            retry_payload = {
                "attempt": attempt,
                "next_attempt": attempt + 1,
                "attempts": attempts,
                "rc": result.rc,
                "delay": delay,
                "message": self._mask_text(result.message, secrets),
            }
            store.record_event("substep_retry", node_id=node_id, target=target.name, payload=retry_payload)
            if output_format == "text":
                with self._print_lock:
                    print(
                        f"[RETRY] {target.name} {node_id} attempt={attempt}/{attempts} "
                        f"rc={result.rc} next={attempt + 1} delay={delay:g}s "
                        f"{self._mask_text(result.message, secrets)}".rstrip()
                    )
            if delay > 0:
                time.sleep(delay)
        if attempt_records:
            result.data = dict(result.data)
            result.data["attempts"] = attempt_records
            result.data["attempt"] = attempt_records[-1]["attempt"]
        return result

    def _template_context(
        self,
        *,
        job: Dict[str, Any],
        task: Dict[str, Any],
        step: Dict[str, Any],
        substep: Dict[str, Any],
        target: Target,
        variables: Dict[str, Any],
        outputs: Dict[str, Any],
        secrets: Dict[str, Any],
        step_state: Dict[str, Any],
        flow_vars: Dict[str, Any] | None = None,
    ) -> Dict[str, Any]:
        effective_vars = deepcopy(variables)
        effective_vars.update(target.vars)
        effective_vars.update(step_state.get("vars", {}))
        effective_vars.update(flow_vars or {})
        context = {
            "job": job,
            "task": task,
            "step": step,
            "substep": substep,
            "server": target,
            "target": target,
            "vars": effective_vars,
            "outputs": outputs,
            "secrets": secrets,
            "step_state": step_state,
        }
        context.update(step_state.get("vars", {}))
        context.update(flow_vars or {})
        return context

    def _execute_substep(
        self,
        *,
        job: Dict[str, Any],
        task: Dict[str, Any],
        step: Dict[str, Any],
        substep: Dict[str, Any],
        target: Target,
        run_id: str,
        dry_run: bool,
        variables: Dict[str, Any],
        secrets: Dict[str, Any],
        outputs: Dict[str, Any],
        ssh_client: Any,
        step_state: Dict[str, Any],
        sudo_password: str | None = None,
        flow_vars: Dict[str, Any] | None = None,
    ) -> PluginResult:
        effective_vars = deepcopy(variables)
        effective_vars.update(target.vars)
        effective_vars.update(step_state.get("vars", {}))
        effective_vars.update(flow_vars or {})
        template_context = self._template_context(
            job=job,
            task=task,
            step=step,
            substep=substep,
            target=target,
            variables=variables,
            outputs=outputs,
            secrets=secrets,
            step_state=step_state,
            flow_vars=flow_vars or {},
        )
        if not self._is_condition_true(substep.get("when"), template_context):
            return PluginResult.skipped_result("condition evaluated to false")

        rendered_substep = render_mapping(substep, template_context)
        plugin_name = rendered_substep.get("use") or rendered_substep.get("plugin")
        params = rendered_substep.get("with", rendered_substep.get("params", {})) or {}
        plugin = self.plugin_registry.get(str(plugin_name))
        plugin.validate(params)
        target_os = effective_vars.get("__automax_os_by_target", {}).get(target.name, {})
        os_family = target_os.get("family") if isinstance(target_os, dict) else None
        if mismatch := plugin_os_mismatch(str(plugin_name), os_family, params):
            return PluginResult.warning_result(message=mismatch, data={"os_mismatch": mismatch})

        context = ExecutionContext(
            run_id=run_id,
            dry_run=dry_run,
            job=job,
            task=task,
            step=step,
            substep=rendered_substep,
            target=target,
            vars=effective_vars,
            outputs=outputs,
            secrets=secrets,
            ssh_client=ssh_client,
            logger=self.logger,
            command_timeout=self._resolve_command_timeout(job, task, step, substep),
            sudo_password=sudo_password,
            step_state=step_state,
        )
        if dry_run:
            result = plugin.dry_run(params, context)
        else:
            result = plugin.execute(params, context)
        return self._attach_manual_commands(result, plugin, params, context)

    def _attach_manual_commands(
        self,
        result: PluginResult,
        plugin: Any,
        params: Dict[str, Any],
        context: ExecutionContext,
    ) -> PluginResult:
        """Attach rendered operator commands to the result for state and failure output."""
        data = dict(result.data)
        try:
            commands = plugin.manual_commands(params, context)
        except Exception as exc:  # pragma: no cover - defensive diagnostics only
            data.setdefault("manual_commands_error", str(exc))
        else:
            if commands:
                data.setdefault("commands", list(commands))
        result.data = data
        return result

    def _print_result_failure_details(self, result: PluginResult, secrets: Dict[str, Any]) -> None:
        """Print actionable failed-substep diagnostics without exposing secrets."""
        commands = result.data.get("commands")
        if commands:
            print("  commands:")
            for command in commands:
                print(f"    $ {self._mask_text(str(command), secrets)}")
        elif result.data.get("manual_commands_error"):
            print(f"  commands: <unavailable: {self._mask_text(str(result.data['manual_commands_error']), secrets)}>")
        else:
            print("  commands: <none>")
        self._print_stream_details("stdout", result.stdout, secrets)
        self._print_stream_details("stderr", result.stderr, secrets)

    def _print_stream_details(self, label: str, value: str, secrets: Dict[str, Any]) -> None:
        text = self._mask_text(value or "", secrets)
        if not text:
            print(f"  {label}: <empty>")
            return
        limit = 12000
        truncated = len(text) > limit
        if truncated:
            text = text[:limit] + f"\n... <truncated {len(text) - limit} chars>"
        print(f"  {label}:")
        for line in text.splitlines() or [""]:
            print(f"    {line}")

    def _is_condition_true(self, condition: Any, context: Dict[str, Any]) -> bool:
        if condition is None:
            return True
        if isinstance(condition, bool):
            return condition
        evaluated = evaluate_value(condition, context)
        if isinstance(evaluated, bool):
            return evaluated
        if evaluated is None:
            return False
        if isinstance(evaluated, (list, tuple, dict, set)):
            return bool(evaluated)
        rendered = str(evaluated).strip().lower()
        return rendered not in ("", "0", "false", "no", "none")

    def _capture_declared_artifacts(
        self,
        *,
        store: StateStore,
        job: Dict[str, Any],
        item: Dict[str, Any],
        result: PluginResult,
        variables: Dict[str, Any],
        secrets: Dict[str, Any],
        outputs: Dict[str, Any],
        flow_vars: Dict[str, Any] | None = None,
    ) -> str | None:
        """Persist stdout/stderr/data artifacts declared by a substep."""
        substep = item["substep"]
        declaration = substep.get("artifacts", substep.get("artifact"))
        if not declaration:
            return None
        target = item["target"]
        source_values = {
            "stdout": result.stdout,
            "stderr": result.stderr,
            "data": json.dumps(self._mask_mapping(result.data, secrets), indent=2, sort_keys=True),
        }
        if declaration is True:
            declaration = {"stdout": "stdout.txt", "stderr": "stderr.txt"}
        if not isinstance(declaration, dict):
            return "artifacts declaration must be a mapping or true"
        template_context = self._template_context(
            job=job,
            task=item["task"],
            step=item["step"],
            substep=substep,
            target=target,
            variables=variables,
            outputs=outputs,
            secrets=secrets,
            step_state={},
            flow_vars=flow_vars or {},
        )
        template_context["run"] = {"id": store.run_id}
        template_context["result"] = self._result_to_mapping(result, secrets=secrets)
        try:
            for source, raw_name in declaration.items():
                source_name = str(source)
                if source_name not in source_values:
                    return f"unsupported artifact source: {source_name}"
                if raw_name in (False, None):
                    continue
                name = f"{source_name}.txt" if raw_name is True else str(raw_name)
                rendered_name = render_value(name, template_context)
                store.write_artifact(
                    node_id=item["node_id"],
                    target=target.name,
                    name=rendered_name,
                    kind=source_name,
                    content=self._mask_text(source_values[source_name], secrets),
                )
        except Exception as exc:
            return f"artifact capture failed: {self._mask_text(str(exc), secrets)}"
        return None

    def _register_outputs(
        self,
        outputs: Dict[str, Any],
        node_id: str,
        target_name: str,
        substep: Dict[str, Any],
        result: PluginResult,
    ) -> None:
        result_map = self._result_to_mapping(result)
        outputs.setdefault("nodes", {})[node_id] = result_map
        outputs.setdefault("targets", {}).setdefault(target_name, {}).setdefault("nodes", {})[
            node_id
        ] = result_map
        register = substep.get("register")
        if not register:
            return
        if isinstance(register, str):
            outputs[register] = result_map
            outputs["targets"][target_name][register] = result_map
            return
        if isinstance(register, dict):
            for name, expression in register.items():
                value = self._extract_result_value(result_map, str(expression))
                outputs[name] = value
                outputs["targets"][target_name][name] = value

    @staticmethod
    def _extract_result_value(result: Dict[str, Any], expression: str) -> Any:
        if expression == "stdout.trim":
            return str(result.get("stdout", "")).strip()
        current: Any = result
        for part in expression.split("."):
            if isinstance(current, dict):
                current = current.get(part)
            else:
                return None
        return current

    def _result_to_mapping(
        self, result: PluginResult, *, secrets: Dict[str, Any] | None = None
    ) -> Dict[str, Any]:
        return {
            "ok": result.ok,
            "changed": result.changed,
            "skipped": result.skipped,
            "warning": result.warning,
            "rc": result.rc,
            "stdout": self._mask_text(result.stdout, secrets or {}),
            "stderr": self._mask_text(result.stderr, secrets or {}),
            "message": self._mask_text(result.message, secrets or {}),
            "data": self._mask_mapping(result.data, secrets or {}),
        }

    def _mask_mapping(self, value: Any, secrets: Dict[str, Any]) -> Any:
        return redact_mapping(value, secrets)

    @classmethod
    def _mask_text(cls, value: str, secrets: Dict[str, Any]) -> str:
        """Mask declared secrets and secret-shaped values before persistence."""
        return redact_text(str(value), secrets)

    @classmethod
    def _iter_secret_texts(cls, value: Any) -> Iterable[str]:
        """Yield nested secret strings, ignoring tiny values that would over-mask logs."""
        yield from iter_secret_texts(value)

    @staticmethod
    def _node_status_for_result(result: PluginResult) -> NodeStatus:
        if result.warning:
            return NodeStatus.WARNING
        return NodeStatus.SUCCESS if result.ok else NodeStatus.FAILED

    @staticmethod
    def _final_run_status(store: StateStore, rc: int) -> NodeStatus:
        if rc != 0:
            return NodeStatus.FAILED
        summary = store.summarize()
        if summary["status_counts"].get(NodeStatus.WARNING.value, 0):
            return NodeStatus.WARNING
        return NodeStatus.SUCCESS

    def _resolve_error_policy(
        self, job: Dict[str, Any], task: Dict[str, Any], step: Dict[str, Any], substep: Dict[str, Any]
    ) -> Dict[str, Any]:
        """Resolve inherited error normalization policy for one substep."""
        policy: Dict[str, Any] = {
            "acceptedRc": [],
            "expected": [],
            "fail": [],
            "unmatched": "fail",
            "acceptedStatus": "warning",
        }
        for node in (job, task, step, substep):
            raw = node.get("errorPolicy") or {}
            if raw:
                policy.update(raw)
        self._validate_error_policy(policy, "resolved errorPolicy")
        policy["acceptedRc"] = [int(value) for value in policy.get("acceptedRc", [])]
        policy["expected"] = self._normalize_error_rules(policy.get("expected", []), "expected")
        policy["fail"] = self._normalize_error_rules(policy.get("fail", []), "fail")
        return policy

    def _apply_error_policy(
        self,
        job: Dict[str, Any],
        task: Dict[str, Any],
        step: Dict[str, Any],
        substep: Dict[str, Any],
        result: PluginResult,
        secrets: Dict[str, Any],
    ) -> PluginResult:
        """Normalize accepted non-zero return codes into warning/success when safe."""
        if result.ok:
            return result
        policy = self._resolve_error_policy(job, task, step, substep)
        accepted_rc = set(policy.get("acceptedRc") or [])
        if int(result.rc) not in accepted_rc:
            return result

        fail_matches = self._match_error_rules(result, policy.get("fail", []))
        expected_matches = self._match_error_rules(result, policy.get("expected", []))
        unmatched_lines = self._unmatched_error_lines(result, expected_matches)
        unmatched_mode = str(policy.get("unmatched", "fail"))
        if fail_matches:
            result.data = dict(result.data)
            result.data["errorPolicy"] = self._error_policy_data(
                accepted=False,
                reason="fail pattern matched",
                expected_matches=expected_matches,
                fail_matches=fail_matches,
                unmatched_lines=unmatched_lines,
                policy=policy,
                secrets=secrets,
            )
            return result
        if unmatched_lines and unmatched_mode == "fail":
            result.data = dict(result.data)
            result.data["errorPolicy"] = self._error_policy_data(
                accepted=False,
                reason="unexpected output remained after expected diagnostics were removed",
                expected_matches=expected_matches,
                fail_matches=fail_matches,
                unmatched_lines=unmatched_lines,
                policy=policy,
                secrets=secrets,
            )
            return result

        status = str(policy.get("acceptedStatus", "warning"))
        message = self._accepted_error_policy_message(
            expected_matches=expected_matches,
            unmatched_lines=unmatched_lines,
            unmatched_mode=unmatched_mode,
        )
        data = dict(result.data)
        data["errorPolicy"] = self._error_policy_data(
            accepted=True,
            reason="accepted return code normalized by errorPolicy",
            expected_matches=expected_matches,
            fail_matches=fail_matches,
            unmatched_lines=unmatched_lines,
            policy=policy,
            secrets=secrets,
        )
        if status == "success" and unmatched_mode != "warn":
            return PluginResult.success(
                changed=result.changed,
                rc=result.rc,
                stdout=result.stdout,
                stderr=result.stderr,
                message=message,
                data=data,
            )
        return PluginResult.warning_result(
            changed=result.changed,
            rc=result.rc,
            stdout=result.stdout,
            stderr=result.stderr,
            message=message,
            data=data,
        )

    @staticmethod
    def _accepted_error_policy_message(
        *, expected_matches: list[Dict[str, Any]], unmatched_lines: list[Dict[str, Any]], unmatched_mode: str
    ) -> str:
        suffix = ""
        if unmatched_lines and unmatched_mode == "warn":
            suffix = f", {len(unmatched_lines)} unexpected line(s) downgraded to warning"
        return (
            "accepted failure by errorPolicy: "
            f"{len(expected_matches)} expected diagnostic(s), "
            f"{len(unmatched_lines)} unexpected diagnostic(s){suffix}"
        )

    def _error_policy_data(
        self,
        *,
        accepted: bool,
        reason: str,
        expected_matches: list[Dict[str, Any]],
        fail_matches: list[Dict[str, Any]],
        unmatched_lines: list[Dict[str, Any]],
        policy: Dict[str, Any],
        secrets: Dict[str, Any],
    ) -> Dict[str, Any]:
        return self._mask_mapping(
            {
                "accepted": accepted,
                "reason": reason,
                "acceptedRc": policy.get("acceptedRc", []),
                "acceptedStatus": policy.get("acceptedStatus", "warning"),
                "unmatched": policy.get("unmatched", "fail"),
                "expectedMatches": expected_matches,
                "failMatches": fail_matches,
                "unexpectedLines": unmatched_lines[:50],
                "unexpectedLineCount": len(unmatched_lines),
            },
            secrets,
        )

    def _match_error_rules(
        self, result: PluginResult, rules: list[Dict[str, Any]]
    ) -> list[Dict[str, Any]]:
        matches: list[Dict[str, Any]] = []
        stream_lines = self._error_policy_stream_lines(result)
        for rule in rules:
            pattern = re.compile(str(rule["pattern"]))
            stream = str(rule.get("stream", "combined"))
            for line in stream_lines[stream]:
                if pattern.search(line["text"]):
                    matches.append(
                        {
                            "stream": line["source"],
                            "line": line["text"],
                            "pattern": str(rule["pattern"]),
                            "reason": str(rule.get("reason", "")),
                        }
                    )
        return matches

    def _unmatched_error_lines(
        self, result: PluginResult, expected_matches: list[Dict[str, Any]]
    ) -> list[Dict[str, Any]]:
        matched = {(item["stream"], item["line"]) for item in expected_matches}
        lines = self._error_policy_stream_lines(result)["combined"]
        return [
            {"stream": line["source"], "line": line["text"]}
            for line in lines
            if (line["source"], line["text"]) not in matched
        ]

    @staticmethod
    def _error_policy_stream_lines(result: PluginResult) -> Dict[str, list[Dict[str, str]]]:
        stdout = [
            {"source": "stdout", "text": line}
            for line in str(result.stdout or "").splitlines()
            if line.strip()
        ]
        stderr = [
            {"source": "stderr", "text": line}
            for line in str(result.stderr or "").splitlines()
            if line.strip()
        ]
        message = [
            {"source": "message", "text": line}
            for line in str(result.message or "").splitlines()
            if line.strip()
        ]
        return {
            "stdout": stdout,
            "stderr": stderr,
            "message": message,
            "combined": [*stdout, *stderr],
        }

    @staticmethod
    def _normalize_error_rules(value: Any, label: str) -> list[Dict[str, Any]]:
        if value is None:
            return []
        if isinstance(value, (str, dict)):
            value = [value]
        if not isinstance(value, list):
            raise AutomaxError(f"{label} errorPolicy rules must be a list")
        rules: list[Dict[str, Any]] = []
        for item in value:
            if isinstance(item, str):
                rules.append({"stream": "combined", "pattern": item})
                continue
            if not isinstance(item, dict):
                raise AutomaxError(f"{label} errorPolicy rule must be a mapping or string")
            if not item.get("pattern"):
                raise AutomaxError(f"{label} errorPolicy rule requires pattern")
            stream = str(item.get("stream", "combined"))
            if stream not in {"stdout", "stderr", "combined", "message"}:
                raise AutomaxError(
                    f"{label} errorPolicy rule stream must be stdout, stderr, combined or message"
                )
            re.compile(str(item["pattern"]))
            rules.append(
                {
                    "stream": stream,
                    "pattern": str(item["pattern"]),
                    "reason": str(item.get("reason", "")),
                }
            )
        return rules

    @classmethod
    def _validate_error_policy(cls, policy: Any, label: str) -> None:
        if policy is None:
            return
        if not isinstance(policy, dict):
            raise AutomaxError(f"{label} errorPolicy must be a mapping")
        allowed = {"acceptedRc", "expected", "fail", "unmatched", "acceptedStatus"}
        unknown = sorted(set(policy) - allowed)
        if unknown:
            raise AutomaxError(
                f"{label} errorPolicy unsupported keys: {', '.join(unknown)}. "
                f"Allowed keys: {', '.join(sorted(allowed))}"
            )
        accepted_rc = policy.get("acceptedRc", [])
        if accepted_rc is None:
            accepted_rc = []
        if isinstance(accepted_rc, int):
            raise AutomaxError(f"{label} errorPolicy acceptedRc must be a list of integers")
        if not isinstance(accepted_rc, list):
            raise AutomaxError(f"{label} errorPolicy acceptedRc must be a list of integers")
        for value in accepted_rc:
            int(value)
        unmatched = str(policy.get("unmatched", "fail"))
        if unmatched not in {"fail", "warn", "ignore"}:
            raise AutomaxError(f"{label} errorPolicy unmatched must be fail, warn or ignore")
        accepted_status = str(policy.get("acceptedStatus", "warning"))
        if accepted_status not in {"warning", "success"}:
            raise AutomaxError(f"{label} errorPolicy acceptedStatus must be warning or success")
        cls._normalize_error_rules(policy.get("expected", []), f"{label} expected")
        cls._normalize_error_rules(policy.get("fail", []), f"{label} fail")

    def _resolve_retry_policy(
        self, job: Dict[str, Any], task: Dict[str, Any], step: Dict[str, Any], substep: Dict[str, Any]
    ) -> Dict[str, Any]:
        """Resolve inherited retry policy for one substep."""
        policy: Dict[str, Any] = {"attempts": 1, "delay": 0.0, "backoff": "fixed"}
        for node in (job, task, step, substep):
            raw = node.get("retry") or {}
            if raw:
                policy.update(raw)
        self._validate_retry_policy(policy, "resolved retry")
        policy["attempts"] = int(policy.get("attempts", 1) or 1)
        policy["delay"] = float(policy.get("delay", 0) or 0)
        if "max_delay" in policy:
            policy["max_delay"] = float(policy["max_delay"])
        if "maxDelay" in policy:
            policy["maxDelay"] = float(policy["maxDelay"])
        return policy

    @staticmethod
    def _should_retry_result(result: PluginResult, policy: Dict[str, Any]) -> bool:
        """Return whether a failed result is eligible for another attempt."""
        if result.ok:
            return False
        retry_on_rc = policy.get("retry_on_rc", policy.get("retryOnRc"))
        if retry_on_rc is None:
            return True
        if isinstance(retry_on_rc, int):
            allowed = {retry_on_rc}
        else:
            allowed = {int(value) for value in retry_on_rc}
        return int(result.rc) in allowed

    @staticmethod
    def _retry_delay(policy: Dict[str, Any], attempt: int) -> float:
        """Return delay before the next retry attempt."""
        base = float(policy.get("delay", 0) or 0)
        backoff = str(policy.get("backoff", "fixed"))
        if backoff == "exponential" and base > 0:
            delay = base * (2 ** max(0, attempt - 1))
        else:
            delay = base
        max_delay = policy.get("max_delay", policy.get("maxDelay"))
        if max_delay is not None:
            delay = min(delay, float(max_delay))
        return delay

    @staticmethod
    def _validate_retry_policy(retry: Any, label: str) -> None:
        """Validate inherited retry policy mappings."""
        if retry is None:
            return
        if not isinstance(retry, dict):
            raise AutomaxError(f"{label} retry must be a mapping")
        allowed = {"attempts", "delay", "backoff", "max_delay", "maxDelay", "retry_on_rc", "retryOnRc"}
        unknown = sorted(set(retry) - allowed)
        if unknown:
            raise AutomaxError(
                f"{label} retry unsupported keys: {', '.join(unknown)}. "
                f"Allowed keys: {', '.join(sorted(allowed))}"
            )
        if int(retry.get("attempts", 1) or 1) < 1:
            raise AutomaxError(f"{label} retry attempts must be >= 1")
        if float(retry.get("delay", 0) or 0) < 0:
            raise AutomaxError(f"{label} retry delay must be >= 0")
        backoff = str(retry.get("backoff", "fixed"))
        if backoff not in {"fixed", "exponential"}:
            raise AutomaxError(f"{label} retry backoff must be fixed or exponential")
        max_delay = retry.get("max_delay", retry.get("maxDelay"))
        if max_delay is not None and float(max_delay) < 0:
            raise AutomaxError(f"{label} retry max_delay must be >= 0")
        retry_on_rc = retry.get("retry_on_rc", retry.get("retryOnRc"))
        if retry_on_rc is not None:
            values = [retry_on_rc] if isinstance(retry_on_rc, int) else retry_on_rc
            if not isinstance(values, list) or not values:
                raise AutomaxError(f"{label} retry retry_on_rc must be a non-empty list of integers")
            for value in values:
                int(value)

    def _target_with_step_timeouts(
        self, target: Target, job: Dict[str, Any], task: Dict[str, Any], step: Dict[str, Any]
    ) -> Target:
        """Merge job/task/step SSH timeout controls into the target."""
        timeouts = self._merged_timeouts(job, task, step)
        if not timeouts:
            return target
        ssh = dict(target.ssh)
        mapping = {
            "ssh_connect": "connect_timeout",
            "connect": "connect_timeout",
            "ssh_banner": "banner_timeout",
            "banner": "banner_timeout",
            "ssh_auth": "auth_timeout",
            "auth": "auth_timeout",
        }
        for source, dest in mapping.items():
            if source in timeouts:
                ssh[dest] = int(timeouts[source])
        return replace(target, ssh=ssh)

    def _resolve_command_timeout(
        self, job: Dict[str, Any], task: Dict[str, Any], step: Dict[str, Any], substep: Dict[str, Any]
    ) -> int | None:
        """Resolve the inherited default command timeout for a substep."""
        timeouts = self._merged_timeouts(job, task, step, substep)
        value = timeouts.get("command") or timeouts.get("command_timeout")
        return int(value) if value is not None else None

    @staticmethod
    def _merged_timeouts(*nodes: Dict[str, Any]) -> Dict[str, Any]:
        merged: Dict[str, Any] = {}
        for node in nodes:
            raw = node.get("timeouts") or {}
            if raw:
                merged.update(raw)
        return merged


    @staticmethod
    def _is_if_substep(substep: Dict[str, Any]) -> bool:
        return "if" in substep

    @staticmethod
    def _is_for_substep(substep: Dict[str, Any]) -> bool:
        return "for" in substep or "do" in substep

    @staticmethod
    def _is_retry_flow_substep(substep: Dict[str, Any]) -> bool:
        retry = substep.get("retry")
        return isinstance(retry, dict) and "do" in retry

    @staticmethod
    def _is_switch_substep(substep: Dict[str, Any]) -> bool:
        return "switch" in substep

    @staticmethod
    def _is_try_substep(substep: Dict[str, Any]) -> bool:
        return "try" in substep

    @staticmethod
    def _is_block_substep(substep: Dict[str, Any]) -> bool:
        return "block" in substep

    @staticmethod
    def _is_assignment_substep(substep: Dict[str, Any]) -> bool:
        return "set" in substep or "let" in substep

    @staticmethod
    def _is_echo_substep(substep: Dict[str, Any]) -> bool:
        return "echo" in substep

    @staticmethod
    def _is_assert_substep(substep: Dict[str, Any]) -> bool:
        return "assert" in substep

    @staticmethod
    def _is_sleep_substep(substep: Dict[str, Any]) -> bool:
        return "sleep" in substep

    @staticmethod
    def _is_noop_substep(substep: Dict[str, Any]) -> bool:
        return "noop" in substep

    @staticmethod
    def _is_fail_substep(substep: Dict[str, Any]) -> bool:
        return "fail" in substep

    @staticmethod
    def _is_break_substep(substep: Dict[str, Any]) -> bool:
        return "break" in substep

    @staticmethod
    def _is_continue_substep(substep: Dict[str, Any]) -> bool:
        return "continue" in substep

    @classmethod
    def _is_terminal_flow_substep(cls, substep: Dict[str, Any]) -> bool:
        return (
            cls._is_echo_substep(substep)
            or cls._is_assert_substep(substep)
            or cls._is_sleep_substep(substep)
            or cls._is_noop_substep(substep)
            or cls._is_fail_substep(substep)
            or cls._is_break_substep(substep)
            or cls._is_continue_substep(substep)
        )

    @classmethod
    def _is_flow_substep(cls, substep: Dict[str, Any]) -> bool:
        return (
            cls._is_if_substep(substep)
            or cls._is_switch_substep(substep)
            or cls._is_retry_flow_substep(substep)
            or cls._is_for_substep(substep)
            or cls._is_try_substep(substep)
            or cls._is_block_substep(substep)
            or cls._is_assignment_substep(substep)
            or cls._is_terminal_flow_substep(substep)
        )

    def _substep_needs_ssh(self, substep: Dict[str, Any]) -> bool:
        if self._is_if_substep(substep):
            return any(
                self._substep_needs_ssh(child)
                for branch in self._if_branches(substep)
                for child in branch["then"]
            )
        if self._is_for_substep(substep):
            return any(self._substep_needs_ssh(child) for child in substep.get("do", []) or [])
        if self._is_retry_flow_substep(substep):
            return any(self._substep_needs_ssh(child) for child in substep.get("retry", {}).get("do", []) or [])
        if self._is_switch_substep(substep):
            return any(
                self._substep_needs_ssh(child)
                for branch in self._switch_branches(substep)
                for child in branch["then"]
            )
        if self._is_try_substep(substep):
            return any(
                self._substep_needs_ssh(child)
                for branch in ("try", "rescue", "always")
                for child in substep.get(branch, []) or []
            )
        if self._is_block_substep(substep):
            return any(self._substep_needs_ssh(child) for child in substep.get("block", []) or [])
        if self._is_assignment_substep(substep) or self._is_terminal_flow_substep(substep):
            return False
        plugin_name = substep.get("use") or substep.get("plugin")
        plugin = self.plugin_registry.get(str(plugin_name))
        return bool(plugin.opens_remote_session)

    @staticmethod
    def _group_by_step_target(plan: List[Dict[str, Any]]) -> List[List[Dict[str, Any]]]:
        groups: List[List[Dict[str, Any]]] = []
        current_key = None
        for item in plan:
            key = (item["task"]["id"], item["step"]["id"], item["target"].name)
            if key != current_key:
                groups.append([])
                current_key = key
            groups[-1].append(item)
        return groups

    def _group_by_stage(self, plan: List[Dict[str, Any]]) -> List[List[List[Dict[str, Any]]]]:
        stages: List[List[List[Dict[str, Any]]]] = []
        current_key = None
        for group in self._group_by_step_target(plan):
            key = (group[0]["task"]["id"], group[0]["step"]["id"])
            if key != current_key:
                stages.append([])
                current_key = key
            stages[-1].append(group)
        return stages

    def _mark_group_skipped(
        self, store: StateStore, group: List[Dict[str, Any]], message: str
    ) -> None:
        for item in group:
            store.mark_skipped(
                node_id=item["node_id"],
                target=item["target"].name,
                task_id=item["task"]["id"],
                step_id=item["step"]["id"],
                substep_id=item["substep"]["id"],
                message=message,
            )

    def _restart_index(self, group: List[Dict[str, Any]], from_node: str | None) -> int | None:
        if not from_node:
            return 0
        for index, item in enumerate(group):
            if self._matches_restart(item, from_node):
                if from_node == item["node_id"]:
                    return index
                return 0
        return None

    @staticmethod
    def _matches_restart(item: Dict[str, Any], from_node: str) -> bool:
        task_id = item["task"]["id"]
        step_id = item["step"]["id"]
        task_node = f"task.{task_id}"
        step_node = f"{task_node}:step.{step_id}"
        return from_node in (task_node, step_node, item["node_id"])

    @classmethod
    def _lock_names(cls, job: Dict[str, Any], plan: List[Dict[str, Any]], *, scope: str) -> list[str]:
        """Return lock names for a planned run."""
        if scope not in {"job", "target", "both"}:
            raise AutomaxError("lock scope must be one of: job, target, both")
        job_name = cls._job_name(job)
        names: list[str] = []
        if scope in {"job", "both"}:
            names.append(f"job:{job_name}")
        if scope in {"target", "both"}:
            for target_name in sorted({item["target"].name for item in plan}):
                names.append(f"target:{target_name}")
        return names

    @staticmethod
    def _node_id(task: Dict[str, Any], step: Dict[str, Any], substep: Dict[str, Any]) -> str:
        return f"task.{task['id']}:step.{step['id']}:substep.{substep['id']}"

    @staticmethod
    def _require_id(node: Dict[str, Any], label: str) -> str:
        node_id = node.get("id")
        if not node_id or not isinstance(node_id, str):
            raise AutomaxError(f"{label} requires string id")
        if not re.match(r"^[A-Za-z0-9_.-]+$", node_id):
            raise AutomaxError(f"invalid {label} id: {node_id}")
        return node_id

    @staticmethod
    def _job_name(job: Dict[str, Any]) -> str:
        metadata = job.get("metadata", {}) or {}
        return str(metadata.get("name", "job"))

    def _build_run_id(self, job: Dict[str, Any]) -> str:
        stamp = datetime.now(timezone.utc).strftime("%Y%m%d-%H%M%S")
        name = re.sub(r"[^A-Za-z0-9_.-]+", "-", self._job_name(job)).strip("-") or "job"
        return f"{stamp}-{name}-{uuid.uuid4().hex[:8]}"


    @staticmethod
    def _validate_output_format(output_format: str) -> None:
        if output_format not in {"text", "json"}:
            raise AutomaxError(f"unsupported output format: {output_format}")

    @staticmethod
    def _run_summary_payload(store: StateStore, *, rc: int, state_dir: str) -> Dict[str, Any]:
        summary = store.summarize()
        first_failed = summary["failed_nodes"][0]["node_id"] if summary["failed_nodes"] else None
        resume: Dict[str, str] = {
            "default": f"automax resume {store.run_id} --state-dir {state_dir}",
        }
        if first_failed:
            resume.update(
                {
                    "skip_successful": f"automax resume {store.run_id} --state-dir {state_dir} --skip-successful",
                    "only_failed": f"automax resume {store.run_id} --state-dir {state_dir} --only-failed",
                    "from": f"automax resume {store.run_id} --state-dir {state_dir} --from {first_failed}",
                }
            )
        return {
            "run_id": store.run_id,
            "rc": rc,
            "status": summary["run"]["status"],
            "run": summary["run"],
            "state_dir": str(store.run_dir),
            "summary": {
                "targets": summary["targets_total"],
                "nodes": summary["nodes_total"],
                "success": summary["status_counts"].get(NodeStatus.SUCCESS.value, 0),
                "warning": summary["status_counts"].get(NodeStatus.WARNING.value, 0),
                "failed": summary["status_counts"].get(NodeStatus.FAILED.value, 0),
                "skipped": summary["status_counts"].get(NodeStatus.SKIPPED.value, 0),
                "changed": summary["changed_nodes"],
                "artifacts": summary["artifacts_count"],
            },
            "targets": summary["targets"],
            "failed_nodes": summary["failed_nodes"],
            "warning_nodes": summary.get("warning_nodes", []),
            "first_failed_node": summary["first_failed_node"],
            "resume": resume,
            "artifacts_command": f"automax artifacts list {store.run_id} --state-dir {state_dir}"
            if summary["artifacts_count"]
            else None,
        }

    @classmethod
    def _print_run_summary(
        cls,
        store: StateStore,
        *,
        rc: int,
        state_dir: str,
        output_format: str = "text",
    ) -> None:
        """Print a compact operator summary after each real run/resume."""
        payload = cls._run_summary_payload(store, rc=rc, state_dir=state_dir)
        if output_format == "json":
            print(json.dumps(payload, indent=2, sort_keys=True, default=str))
            return

        run = payload["run"]
        failed_nodes = payload["failed_nodes"]
        warning_nodes = payload.get("warning_nodes", [])
        status_word = "succeeded" if rc == 0 else "failed"
        print("")
        print(f"Automax run {status_word}")
        print(f"Run ID: {store.run_id}")
        print(f"Status: {run['status']}")
        print(f"Job: {run['job_path']}")
        print(f"State: {payload['state_dir']}")
        print("Summary:")
        for key in ("targets", "nodes", "success", "warning", "failed", "skipped", "changed", "artifacts"):
            print(f"  {key}: {payload['summary'][key]}")
        if payload["targets"]:
            print("Targets:")
            for target in payload["targets"]:
                counts = target["status_counts"]
                print(
                    "  "
                    f"{target['target']} {target['status']} "
                    f"changed={target['changed']} "
                    f"success={counts.get(NodeStatus.SUCCESS.value, 0)} "
                    f"warning={counts.get(NodeStatus.WARNING.value, 0)} "
                    f"failed={counts.get(NodeStatus.FAILED.value, 0)} "
                    f"skipped={counts.get(NodeStatus.SKIPPED.value, 0)}"
                )
        if warning_nodes:
            print("Warnings:")
            for node in warning_nodes[:10]:
                detail = f" rc={node['rc']}" if node.get("rc") is not None else ""
                message = f" {node['message']}" if node.get("message") else ""
                print(f"  {node['target']} {node['node_id']}{detail}{message}".rstrip())
            if len(warning_nodes) > 10:
                print(f"  ... {len(warning_nodes) - 10} more warning nodes")
        if failed_nodes:
            print("Failed:")
            for node in failed_nodes[:10]:
                detail = f" rc={node['rc']}" if node.get("rc") is not None else ""
                message = f" {node['message']}" if node.get("message") else ""
                print(f"  {node['target']} {node['node_id']}{detail}{message}".rstrip())
            if len(failed_nodes) > 10:
                print(f"  ... {len(failed_nodes) - 10} more failed nodes")
            print("Resume options:")
            for key in ("skip_successful", "only_failed", "from"):
                if key in payload["resume"]:
                    print(f"  {payload['resume'][key]}")
        if payload["artifacts_command"]:
            print("Artifacts:")
            print(f"  {payload['artifacts_command']}")

    @staticmethod
    def _plan_payload(run_id: str, plan: List[Dict[str, Any]]) -> Dict[str, Any]:
        return {
            "run_id": run_id,
            "nodes": [
                {
                    "target": item["target"].name,
                    "node_id": item["node_id"],
                    "task_id": item["task"]["id"],
                    "step_id": item["step"]["id"],
                    "substep_id": item["substep"]["id"],
                    "plugin": str(item["substep"].get("use") or item["substep"].get("plugin")),
                    "tags": list(item.get("tags") or ()),
                }
                for item in plan
            ],
        }

    @classmethod
    def _print_plan(
        cls, run_id: str, plan: List[Dict[str, Any]], *, output_format: str = "text"
    ) -> None:
        payload = cls._plan_payload(run_id, plan)
        if output_format == "json":
            print(json.dumps(payload, indent=2, sort_keys=True))
            return
        print(f"Run ID: {run_id}")
        for item in plan:
            tags = f" tags={','.join(item['tags'])}" if item.get("tags") else ""
            print(f"{item['target'].name} {item['node_id']}{tags}")

    @staticmethod
    def _effective_tags(
        job: Dict[str, Any], task: Dict[str, Any], step: Dict[str, Any], substep: Dict[str, Any]
    ) -> set[str]:
        tags: set[str] = set()
        for node in (job, task, step, substep):
            raw_tags = node.get("tags", []) or []
            if isinstance(raw_tags, str):
                tags.add(raw_tags)
            else:
                tags.update(str(tag) for tag in raw_tags)
        return tags

    @staticmethod
    def _tag_selected(
        effective_tags: set[str], selected_tags: set[str], skipped_tags: set[str]
    ) -> bool:
        if skipped_tags and effective_tags.intersection(skipped_tags):
            return False
        if selected_tags and not effective_tags.intersection(selected_tags):
            return False
        return True

    @staticmethod
    def _validate_tags(tags: Any, label: str) -> None:
        if tags is None:
            return
        if isinstance(tags, str):
            return
        if not isinstance(tags, list) or not all(isinstance(tag, str) for tag in tags):
            raise AutomaxError(f"{label} tags must be a string or list of strings")

    def _resolve_strategy(
        self, job: Dict[str, Any], task: Dict[str, Any], step: Dict[str, Any]
    ) -> Dict[str, Any]:
        strategy: Dict[str, Any] = {"mode": "serial"}
        for node in (job, task, step):
            raw = node.get("strategy")
            if raw:
                strategy.update(raw)
        self._validate_strategy(strategy, "resolved strategy")
        return strategy

    @staticmethod
    def _validate_strategy(strategy: Any, label: str) -> None:
        if strategy is None:
            return
        if not isinstance(strategy, dict):
            raise AutomaxError(f"{label} strategy must be a mapping")
        mode = str(strategy.get("mode", "serial"))
        if mode not in {"serial", "parallel", "rolling"}:
            raise AutomaxError(f"{label} strategy mode must be serial, parallel or rolling")
        for key in ("max_parallel", "batch_size"):
            if key in strategy and int(strategy[key]) < 1:
                raise AutomaxError(f"{label} strategy {key} must be >= 1")
        if "pause_between_batches" in strategy and float(strategy["pause_between_batches"]) < 0:
            raise AutomaxError(f"{label} strategy pause_between_batches must be >= 0")

    @staticmethod
    def _validate_timeouts(timeouts: Any, label: str) -> None:
        """Validate inherited timeout mappings."""
        if timeouts is None:
            return
        if not isinstance(timeouts, dict):
            raise AutomaxError(f"{label} timeouts must be a mapping")
        allowed = {
            "command",
            "command_timeout",
            "ssh_connect",
            "connect",
            "ssh_banner",
            "banner",
            "ssh_auth",
            "auth",
        }
        for key, value in timeouts.items():
            if key not in allowed:
                raise AutomaxError(
                    f"{label} timeouts unsupported key '{key}'. Allowed: {', '.join(sorted(allowed))}"
                )
            if int(value) <= 0:
                raise AutomaxError(f"{label} timeout {key} must be a positive integer")

    def _resolve_failure_policy(
        self, job: Dict[str, Any], task: Dict[str, Any], step: Dict[str, Any]
    ) -> Dict[str, Any]:
        policy: Dict[str, Any] = {
            "onFailure": "stop_job",
            "onUnreachable": "stop_job",
            "maxFailedHosts": 0,
        }
        for node in (job, task, step):
            raw = node.get("failurePolicy")
            if raw:
                policy.update(raw)
        self._validate_failure_policy(policy, "resolved failurePolicy")
        return policy

    @staticmethod
    def _validate_failure_policy(policy: Any, label: str) -> None:
        if policy is None:
            return
        if not isinstance(policy, dict):
            raise AutomaxError(f"{label} failurePolicy must be a mapping")
        allowed = {"stop_job", "stop_task", "stop_host", "continue"}
        for key in ("onFailure", "onUnreachable"):
            if key in policy and str(policy[key]) not in allowed:
                raise AutomaxError(
                    f"{label} failurePolicy {key} must be one of: {', '.join(sorted(allowed))}"
                )
        if "maxFailedHosts" in policy and int(policy["maxFailedHosts"]) < 0:
            raise AutomaxError(f"{label} failurePolicy maxFailedHosts must be >= 0")

    @staticmethod
    def _max_failed_hosts_reached(failed_hosts: set[str], policy: Dict[str, Any]) -> bool:
        limit = int(policy.get("maxFailedHosts", 0) or 0)
        return bool(limit and len(failed_hosts) > limit)

    @staticmethod
    def _chunks(items: List[Any], size: int) -> Iterable[List[Any]]:
        for offset in range(0, len(items), size):
            yield items[offset : offset + size]

capability_requirements_job(*, job_path, inventory_path, vars_path=None, secrets_path=None, limit=(), exclude=(), tags=(), skip_tags=(), cli_vars=None, check_missing=False)

Return job-scoped remote capability requirements from the selected plan.

Source code in src/automax/core/engine.py
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
def capability_requirements_job(
    self,
    *,
    job_path: str,
    inventory_path: str,
    vars_path: str | None = None,
    secrets_path: str | None = None,
    limit: Iterable[str] = (),
    exclude: Iterable[str] = (),
    tags: Iterable[str] = (),
    skip_tags: Iterable[str] = (),
    cli_vars: Optional[Dict[str, Any]] = None,
    check_missing: bool = False,
) -> Dict[str, Any]:
    """Return job-scoped remote capability requirements from the selected plan."""
    resolved = self.resolve_job_context(
        job_path=job_path,
        inventory_path=inventory_path,
        vars_path=vars_path,
        secrets_path=secrets_path,
        limit=limit,
        exclude=exclude,
        tags=tags,
        skip_tags=skip_tags,
        cli_vars=cli_vars,
    )
    os_by_target = self._detect_os_for_plan(resolved.plan, resolved.secrets)
    requirements = collect_requirements(self.iter_rendered_plan_items(resolved, dry_run=True), os_by_target)
    if check_missing:
        self._annotate_missing_capabilities(requirements, resolved.plan)
    return {
        "job": self._job_name(resolved.job),
        "mode": "capability-requirements",
        "targets": [requirements[name] for name in sorted(requirements)],
        "target_count": len(requirements),
        "tool_count": len({tool for item in requirements.values() for tool in item["tools"]}),
        "package_count": len({package for item in requirements.values() for package in item.get("packages", [])}),
        "missing_tool_count": len({tool for item in requirements.values() for tool in item.get("missing_tools", [])}),
        "missing_package_count": len({package for item in requirements.values() for package in item.get("missing_packages", [])}),
    }

check_job(*, job_path, inventory_path, vars_path=None, secrets_path=None, limit=(), exclude=(), tags=(), skip_tags=(), cli_vars=None)

Render a safe check-mode preview for one resolved job.

Source code in src/automax/core/engine.py
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
def check_job(
    self,
    *,
    job_path: str,
    inventory_path: str,
    vars_path: str | None = None,
    secrets_path: str | None = None,
    limit: Iterable[str] = (),
    exclude: Iterable[str] = (),
    tags: Iterable[str] = (),
    skip_tags: Iterable[str] = (),
    cli_vars: Optional[Dict[str, Any]] = None,
) -> Dict[str, Any]:
    """Render a safe check-mode preview for one resolved job."""
    resolved = self.resolve_job_context(
        job_path=job_path,
        inventory_path=inventory_path,
        vars_path=vars_path,
        secrets_path=secrets_path,
        limit=limit,
        exclude=exclude,
        tags=tags,
        skip_tags=skip_tags,
        cli_vars=cli_vars,
    )
    rows = []
    for item in self.iter_rendered_plan_items(resolved, dry_run=True):
        plugin = item["plugin"]
        params = item["params"]
        try:
            result = plugin.dry_run(params, item["context"])
        except Exception as exc:  # pragma: no cover - defensive plugin boundary
            result = PluginResult.failure(message=str(exc))
        rows.append(
            {
                "target": item["target"].name,
                "node_id": item["node_id"],
                "task_id": str(item["task"]["id"]),
                "step_id": str(item["step"]["id"]),
                "substep_id": str(item["substep"]["id"]),
                "plugin": item["plugin_name"],
                "supports_dry_run": bool(plugin.supports_dry_run),
                "supports_check_mode": bool(plugin.supports_check_mode),
                "ok": result.ok,
                "changed": result.changed,
                "message": self._mask_text(result.message, resolved.secrets),
                "params": self._mask_mapping(params, resolved.secrets),
            }
        )
    return {
        "job": self._job_name(resolved.job),
        "mode": "check",
        "ok": all(row["ok"] for row in rows),
        "nodes": rows,
    }

check_secrets(*, job_path, inventory_path, vars_path=None, secrets_path=None, limit=(), exclude=(), tags=(), skip_tags=(), cli_vars=None, include_all=False)

Check secret definitions referenced by one selected job plan.

Source code in src/automax/core/engine.py
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
def check_secrets(
    self,
    *,
    job_path: str,
    inventory_path: str,
    vars_path: str | None = None,
    secrets_path: str | None = None,
    limit: Iterable[str] = (),
    exclude: Iterable[str] = (),
    tags: Iterable[str] = (),
    skip_tags: Iterable[str] = (),
    cli_vars: Optional[Dict[str, Any]] = None,
    include_all: bool = False,
) -> Dict[str, Any]:
    """Check secret definitions referenced by one selected job plan."""
    documents = self._load_documents(
        job_path=job_path,
        inventory_path=inventory_path,
        vars_path=vars_path,
        secrets_path=secrets_path,
    )
    job = documents["job"]
    self.validate_job(job)
    raw_inventory = load_yaml_file(inventory_path)
    declared = self._declared_secret_names(documents["secrets"])
    known_refs = self._secret_references(job) | self._secret_references(raw_inventory)
    placeholder_secrets = {name: f"__automax_secret_{name}__" for name in declared | known_refs}
    variables = self._merge_variables(documents["vars"], job.get("vars", {}), cli_vars or {})
    context = {"vars": variables, "secrets": placeholder_secrets}
    inventory_document = load_inventory_document(inventory_path, context)
    inventory = Inventory(inventory_document, context)
    plan = self._build_plan(
        job,
        inventory,
        limit=limit,
        exclude=exclude,
        tags=tags,
        skip_tags=skip_tags,
    )
    referenced = set()
    for item in plan:
        referenced.update(
            self._secret_references(
                {key: value for key, value in item["task"].items() if key != "steps"}
            )
        )
        referenced.update(
            self._secret_references(
                {key: value for key, value in item["step"].items() if key != "substeps"}
            )
        )
        referenced.update(self._secret_references(item["substep"]))

    checks = self.secret_manager.check_all(documents["secrets"], base_dir=self._path_parent(secrets_path))
    checks_by_name = {item["name"]: item for item in checks}
    rows = []
    for name in sorted(declared | referenced):
        used = name in referenced
        if not include_all and not used:
            continue
        row = dict(
            checks_by_name.get(
                name,
                {
                    "name": name,
                    "provider": "undeclared",
                    "status": "MISSING",
                    "ok": False,
                    "detail": "referenced by job but not declared in secrets file",
                },
            )
        )
        row["used"] = used
        rows.append(row)

    return {
        "job": self._job_name(job),
        "secrets_path": str(Path(secrets_path).expanduser()) if secrets_path else None,
        "checked": len(rows),
        "ok": all(item["ok"] for item in rows),
        "secrets": rows,
    }

diff_job(*, job_path, inventory_path, vars_path=None, secrets_path=None, limit=(), exclude=(), tags=(), skip_tags=(), cli_vars=None)

Render safe diff previews for one resolved job.

Source code in src/automax/core/engine.py
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
def diff_job(
    self,
    *,
    job_path: str,
    inventory_path: str,
    vars_path: str | None = None,
    secrets_path: str | None = None,
    limit: Iterable[str] = (),
    exclude: Iterable[str] = (),
    tags: Iterable[str] = (),
    skip_tags: Iterable[str] = (),
    cli_vars: Optional[Dict[str, Any]] = None,
) -> Dict[str, Any]:
    """Render safe diff previews for one resolved job."""
    resolved = self.resolve_job_context(
        job_path=job_path,
        inventory_path=inventory_path,
        vars_path=vars_path,
        secrets_path=secrets_path,
        limit=limit,
        exclude=exclude,
        tags=tags,
        skip_tags=skip_tags,
        cli_vars=cli_vars,
    )
    rows = []
    for item in self.iter_rendered_plan_items(resolved, dry_run=True):
        plugin = item["plugin"]
        try:
            previews = plugin.diff_preview(item["params"], item["context"])
        except Exception as exc:  # pragma: no cover - defensive plugin boundary
            previews = []
            reason = str(exc)
        else:
            reason = plugin.diff_preview_reason(item["params"], item["context"])
        if not previews:
            rows.append(
                {
                    "target": item["target"].name,
                    "node_id": item["node_id"],
                    "plugin": item["plugin_name"],
                    "available": False,
                    "reason": self._mask_text(reason, resolved.secrets),
                }
            )
            continue
        for preview in previews:
            row = dict(preview)
            row.update(
                {
                    "target": item["target"].name,
                    "node_id": item["node_id"],
                    "plugin": item["plugin_name"],
                    "available": True,
                }
            )
            if "diff" in row:
                row["diff"] = self._mask_text(str(row["diff"]), resolved.secrets)
            rows.append(row)
    return {
        "job": self._job_name(resolved.job),
        "mode": "diff",
        "diffs": rows,
    }

inspect_inventory(*, job_path, inventory_path, vars_path=None, secrets_path=None, limit=(), exclude=(), tags=(), skip_tags=(), cli_vars=None)

Return inventory targets selected by one resolved job.

Source code in src/automax/core/engine.py
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
def inspect_inventory(
    self,
    *,
    job_path: str,
    inventory_path: str,
    vars_path: str | None = None,
    secrets_path: str | None = None,
    limit: Iterable[str] = (),
    exclude: Iterable[str] = (),
    tags: Iterable[str] = (),
    skip_tags: Iterable[str] = (),
    cli_vars: Optional[Dict[str, Any]] = None,
) -> Dict[str, Any]:
    """Return inventory targets selected by one resolved job."""
    resolved = self.resolve_job_context(
        job_path=job_path,
        inventory_path=inventory_path,
        vars_path=vars_path,
        secrets_path=secrets_path,
        limit=limit,
        exclude=exclude,
        tags=tags,
        skip_tags=skip_tags,
        cli_vars=cli_vars,
    )
    selected: Dict[str, Dict[str, Any]] = {}
    for item in resolved.plan:
        target: Target = item["target"]
        entry = selected.setdefault(
            target.name,
            {
                "name": target.name,
                "host": target.host,
                "port": target.port,
                "user": target.user,
                "groups": list(target.groups),
                "vars": sorted(target.vars),
                "nodes": 0,
            },
        )
        entry["nodes"] += 1

    return {
        "job": self._job_name(resolved.job),
        "inventory_path": resolved.inventory_path,
        "targets": [selected[name] for name in sorted(selected)],
        "target_count": len(selected),
        "node_count": len(resolved.plan),
    }

inspect_job(*, job_path, inventory_path, vars_path=None, secrets_path=None, limit=(), exclude=(), tags=(), skip_tags=(), cli_vars=None)

Return a resolved, serializable view of a job without creating run state.

Source code in src/automax/core/engine.py
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
def inspect_job(
    self,
    *,
    job_path: str,
    inventory_path: str,
    vars_path: str | None = None,
    secrets_path: str | None = None,
    limit: Iterable[str] = (),
    exclude: Iterable[str] = (),
    tags: Iterable[str] = (),
    skip_tags: Iterable[str] = (),
    cli_vars: Optional[Dict[str, Any]] = None,
) -> Dict[str, Any]:
    """Return a resolved, serializable view of a job without creating run state."""
    resolved = self.resolve_job_context(
        job_path=job_path,
        inventory_path=inventory_path,
        vars_path=vars_path,
        secrets_path=secrets_path,
        limit=limit,
        exclude=exclude,
        tags=tags,
        skip_tags=skip_tags,
        cli_vars=cli_vars,
    )
    return build_job_view(resolved.job, resolved.plan)

install_capability_requirements_job(*, job_path, inventory_path, vars_path=None, secrets_path=None, limit=(), exclude=(), tags=(), skip_tags=(), cli_vars=None, sudo_password_env=None, progress_callback=None)

Install missing target packages required by the selected job plan.

Source code in src/automax/core/engine.py
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
def install_capability_requirements_job(
    self,
    *,
    job_path: str,
    inventory_path: str,
    vars_path: str | None = None,
    secrets_path: str | None = None,
    limit: Iterable[str] = (),
    exclude: Iterable[str] = (),
    tags: Iterable[str] = (),
    skip_tags: Iterable[str] = (),
    cli_vars: Optional[Dict[str, Any]] = None,
    sudo_password_env: str | None = None,
    progress_callback: Callable[[Dict[str, Any]], None] | None = None,
) -> Dict[str, Any]:
    """Install missing target packages required by the selected job plan."""
    resolved = self.resolve_job_context(
        job_path=job_path,
        inventory_path=inventory_path,
        vars_path=vars_path,
        secrets_path=secrets_path,
        limit=limit,
        exclude=exclude,
        tags=tags,
        skip_tags=skip_tags,
        cli_vars=cli_vars,
    )
    os_by_target = self._detect_os_for_plan(resolved.plan, resolved.secrets)
    requirements = collect_requirements(self.iter_rendered_plan_items(resolved, dry_run=True), os_by_target)
    sudo_password = self._resolve_sudo_password(sudo_password_env)
    targets = []
    ok = True
    emit = progress_callback or (lambda event: None)
    emit({"event": "job", "job": self._job_name(resolved.job)})
    for target_name in sorted(requirements):
        entry = requirements[target_name]
        target = next(item["target"] for item in resolved.plan if item["target"].name == target_name)
        emit({"event": "target-check", "target": target_name, "host": entry["host"], "os": entry["os"]})
        missing_tools = self._missing_tools(target, entry["tools"])
        packages = self._packages_for_tools(missing_tools, entry["os"]["family"])
        unresolved = self._unresolved_tools(missing_tools, entry["os"]["family"])
        emit({
            "event": "target-missing",
            "target": target_name,
            "host": entry["host"],
            "os": entry["os"],
            "missing_tools": missing_tools,
            "packages": packages,
            "unresolved_tools": unresolved,
        })
        rc = 0
        stdout = ""
        stderr = ""
        changed = False
        if packages:
            emit({"event": "target-install", "target": target_name, "host": entry["host"], "os": entry["os"], "packages": packages})
            rc, stdout, stderr = self._install_packages_for_os(
                target=target,
                os_family=entry["os"]["family"],
                packages=packages,
                sudo_password=sudo_password,
            )
            changed = rc == 0
        target_ok = rc == 0 and not unresolved
        ok = ok and target_ok
        emit({
            "event": "target-done",
            "target": target_name,
            "host": entry["host"],
            "os": entry["os"],
            "rc": rc,
            "ok": target_ok,
            "changed": changed,
            "packages": packages,
            "unresolved_tools": unresolved,
        })
        targets.append(
            {
                "target": target_name,
                "host": entry["host"],
                "os": entry["os"],
                "missing_tools": missing_tools,
                "packages": packages,
                "unresolved_tools": unresolved,
                "changed": changed,
                "ok": target_ok,
                "rc": rc,
                "stdout": self._mask_text(stdout, resolved.secrets),
                "stderr": self._mask_text(stderr, resolved.secrets),
            }
        )
    return {
        "job": self._job_name(resolved.job),
        "mode": "capability-install",
        "ok": ok,
        "targets": targets,
    }

iter_rendered_plan_items(resolved, *, dry_run=True)

Yield rendered plan items for safe operator inspections.

Source code in src/automax/core/engine.py
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
def iter_rendered_plan_items(
    self, resolved: ResolvedJobContext, *, dry_run: bool = True
) -> Iterable[Dict[str, Any]]:
    """Yield rendered plan items for safe operator inspections."""
    outputs: Dict[str, Any] = {}
    step_states: Dict[tuple[str, str], Dict[str, Any]] = {}
    for item in resolved.plan:
        step_key = (str(item["target"].name), str(item["step"]["id"]))
        step_state = step_states.setdefault(step_key, {})
        yield from self._iter_rendered_substep_items(
            resolved=resolved,
            item=item,
            dry_run=dry_run,
            outputs=outputs,
            step_state=step_state,
            flow_vars={},
        )

manual_commands_job(*, job_path, inventory_path, vars_path=None, secrets_path=None, limit=(), exclude=(), tags=(), skip_tags=(), cli_vars=None)

Render manual recovery commands for selected job substeps.

Source code in src/automax/core/engine.py
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
def manual_commands_job(
    self,
    *,
    job_path: str,
    inventory_path: str,
    vars_path: str | None = None,
    secrets_path: str | None = None,
    limit: Iterable[str] = (),
    exclude: Iterable[str] = (),
    tags: Iterable[str] = (),
    skip_tags: Iterable[str] = (),
    cli_vars: Optional[Dict[str, Any]] = None,
) -> Dict[str, Any]:
    """Render manual recovery commands for selected job substeps."""
    resolved = self.resolve_job_context(
        job_path=job_path,
        inventory_path=inventory_path,
        vars_path=vars_path,
        secrets_path=secrets_path,
        limit=limit,
        exclude=exclude,
        tags=tags,
        skip_tags=skip_tags,
        cli_vars=cli_vars,
    )
    rows = []
    uses_sudo = False
    for item in self.iter_rendered_plan_items(resolved, dry_run=True):
        commands = item["plugin"].manual_commands(item["params"], item["context"])
        node_uses_sudo = any("sudo -n" in command for command in commands)
        uses_sudo = uses_sudo or node_uses_sudo
        rows.append(
            {
                "target": item["target"].name,
                "host": item["target"].host,
                "node_id": item["node_id"],
                "plugin": item["plugin_name"],
                "commands": [self._mask_text(command, resolved.secrets) for command in commands],
                "available": bool(commands),
                "uses_sudo": node_uses_sudo,
                "reason": "" if commands else self._mask_text(
                    item["plugin"].manual_commands_reason(item["params"], item["context"]),
                    resolved.secrets,
                ),
            }
        )
    return {
        "job": self._job_name(resolved.job),
        "mode": "manual-commands",
        "uses_sudo": uses_sudo,
        "sudo_note": (
            "Rendered manual commands containing sudo -n require an existing sudo timestamp "
            "when pasted manually; normal automax run/resume can use "
            "--sudo-password-env ENV_NAME instead."
        ) if uses_sudo else "",
        "nodes": rows,
    }

os_info_inventory(*, inventory_path, vars_path=None, secrets_path=None, limit=(), exclude=(), cli_vars=None)

Detect and report operating-system facts for inventory targets.

Source code in src/automax/core/engine.py
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
def os_info_inventory(
    self,
    *,
    inventory_path: str,
    vars_path: str | None = None,
    secrets_path: str | None = None,
    limit: Iterable[str] = (),
    exclude: Iterable[str] = (),
    cli_vars: Optional[Dict[str, Any]] = None,
) -> Dict[str, Any]:
    """Detect and report operating-system facts for inventory targets."""
    vars_document = load_yaml_file(vars_path, required=False) if vars_path else {}
    secrets_document = load_yaml_file(secrets_path, required=False) if secrets_path else {}
    secrets = self.secret_manager.resolve_all(
        secrets_document,
        base_dir=self._path_parent(secrets_path),
    )
    variables = self._merge_variables(vars_document, cli_vars or {})
    context = {"vars": variables, "secrets": secrets}
    inventory_document = load_inventory_document(inventory_path, context)
    inventory = Inventory(inventory_document, context)
    targets = inventory.select("all", limit=list(limit), exclude=list(exclude))
    os_by_target = self._detect_os_for_targets(targets, secrets)
    rows = []
    for target in targets:
        os_info = os_by_target[target.name]
        rows.append(
            {
                "target": target.name,
                "host": target.host,
                "port": target.port,
                "user": target.user,
                "os": self._os_to_mapping(os_info),
            }
        )
    return {
        "mode": "os-info",
        "inventory": str(Path(inventory_path).expanduser()),
        "target_count": len(rows),
        "targets": rows,
    }

render_vars_job(*, job_path, inventory_path, vars_path=None, secrets_path=None, limit=(), exclude=(), tags=(), skip_tags=(), cli_vars=None)

Render the final job-scoped variable context without exposing secrets.

Source code in src/automax/core/engine.py
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
def render_vars_job(
    self,
    *,
    job_path: str,
    inventory_path: str,
    vars_path: str | None = None,
    secrets_path: str | None = None,
    limit: Iterable[str] = (),
    exclude: Iterable[str] = (),
    tags: Iterable[str] = (),
    skip_tags: Iterable[str] = (),
    cli_vars: Optional[Dict[str, Any]] = None,
) -> Dict[str, Any]:
    """Render the final job-scoped variable context without exposing secrets."""
    resolved = self.resolve_job_context(
        job_path=job_path,
        inventory_path=inventory_path,
        vars_path=vars_path,
        secrets_path=secrets_path,
        limit=limit,
        exclude=exclude,
        tags=tags,
        skip_tags=skip_tags,
        cli_vars=cli_vars,
    )
    targets: Dict[str, Dict[str, Any]] = {}
    for item in self.iter_rendered_plan_items(resolved, dry_run=True):
        target: Target = item["target"]
        entry = targets.setdefault(
            target.name,
            {
                "name": target.name,
                "host": target.host,
                "port": target.port,
                "groups": list(target.groups),
                "vars": self._mask_mapping(item["context"].vars, resolved.secrets),
                "secrets": {key: "***" for key in sorted(resolved.secrets)},
                "nodes": [],
            },
        )
        entry["nodes"].append(
            {
                "node_id": item["node_id"],
                "task_id": str(item["task"]["id"]),
                "step_id": str(item["step"]["id"]),
                "substep_id": str(item["substep"]["id"]),
                "plugin": item["plugin_name"],
            }
        )
    return {
        "job": self._job_name(resolved.job),
        "vars_path": resolved.vars_path,
        "secrets_path": resolved.secrets_path,
        "targets": [targets[name] for name in sorted(targets)],
        "target_count": len(targets),
        "node_count": sum(len(target["nodes"]) for target in targets.values()),
    }

resolve_job_context(*, job_path, inventory_path, vars_path=None, secrets_path=None, limit=(), exclude=(), tags=(), skip_tags=(), cli_vars=None)

Resolve job, inventory, vars, secrets and selected plan once.

Source code in src/automax/core/engine.py
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
def resolve_job_context(
    self,
    *,
    job_path: str,
    inventory_path: str,
    vars_path: str | None = None,
    secrets_path: str | None = None,
    limit: Iterable[str] = (),
    exclude: Iterable[str] = (),
    tags: Iterable[str] = (),
    skip_tags: Iterable[str] = (),
    cli_vars: Optional[Dict[str, Any]] = None,
) -> ResolvedJobContext:
    """Resolve job, inventory, vars, secrets and selected plan once."""
    documents = self._load_documents(
        job_path=job_path,
        inventory_path=inventory_path,
        vars_path=vars_path,
        secrets_path=secrets_path,
    )
    secrets = self.secret_manager.resolve_all(
        documents["secrets"],
        base_dir=self._path_parent(secrets_path),
    )
    variables = self._merge_variables(
        documents["vars"], documents["job"].get("vars", {}), cli_vars or {}
    )
    context = {"vars": variables, "secrets": secrets}
    inventory_document = load_inventory_document(inventory_path, context)
    inventory = Inventory(inventory_document, context)
    job = documents["job"]
    self.validate_job(job)
    plan = self._build_plan(
        job,
        inventory,
        limit=limit,
        exclude=exclude,
        tags=tags,
        skip_tags=skip_tags,
    )
    return ResolvedJobContext(
        job_path=str(Path(job_path).expanduser()),
        inventory_path=str(Path(inventory_path).expanduser()),
        vars_path=str(Path(vars_path).expanduser()) if vars_path else None,
        secrets_path=str(Path(secrets_path).expanduser()) if secrets_path else None,
        documents=documents,
        job=job,
        inventory=inventory,
        variables=variables,
        secrets=secrets,
        plan=plan,
    )

resume(*, run_id, state_dir='.automax/runs', from_node=None, dry_run=False, limit=(), exclude=(), tags=(), skip_tags=(), cli_vars=None, skip_successful=False, only_failed=False, output_format='text', lock=False, lock_scope='both', lock_timeout=0, sudo_password_env=None)

Resume a previous run using paths stored in the run state.

Source code in src/automax/core/engine.py
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
def resume(
    self,
    *,
    run_id: str,
    state_dir: str = ".automax/runs",
    from_node: str | None = None,
    dry_run: bool = False,
    limit: Iterable[str] = (),
    exclude: Iterable[str] = (),
    tags: Iterable[str] = (),
    skip_tags: Iterable[str] = (),
    cli_vars: Optional[Dict[str, Any]] = None,
    skip_successful: bool = False,
    only_failed: bool = False,
    output_format: str = "text",
    lock: bool = False,
    lock_scope: str = "both",
    lock_timeout: float = 0,
    sudo_password_env: str | None = None,
) -> int:
    """Resume a previous run using paths stored in the run state."""
    self._validate_output_format(output_format)
    store = StateStore(state_dir, run_id)
    run = store.get_run()
    if not run:
        raise AutomaxError(f"run not found: {run_id}")
    if only_failed:
        failed = store.node_keys_by_status({NodeStatus.FAILED.value})
        if not failed:
            raise AutomaxError(f"run has no failed nodes: {run_id}")
    else:
        from_node = from_node or store.first_failed_node_id()
        if not from_node:
            raise AutomaxError(f"run has no failed checkpoint: {run_id}")
    return self.run(
        job_path=run["job_path"],
        inventory_path=run["inventory_path"],
        vars_path=run.get("vars_path"),
        secrets_path=run.get("secrets_path"),
        state_dir=state_dir,
        run_id=run_id,
        dry_run=dry_run,
        from_node=from_node,
        limit=limit,
        exclude=exclude,
        tags=tags,
        skip_tags=skip_tags,
        cli_vars=cli_vars,
        skip_successful=skip_successful,
        only_failed=only_failed,
        output_format=output_format,
        lock=lock,
        lock_scope=lock_scope,
        lock_timeout=lock_timeout,
        sudo_password_env=sudo_password_env,
    )

run(*, job_path, inventory_path, vars_path=None, secrets_path=None, state_dir='.automax/runs', run_id=None, dry_run=False, plan_only=False, from_node=None, limit=(), exclude=(), tags=(), skip_tags=(), cli_vars=None, extra_plugin_paths=(), skip_successful=False, only_failed=False, output_format='text', lock=False, lock_scope='both', lock_timeout=0, preflight_capabilities=False, sudo_password_env=None)

Execute a new run from external YAML files.

Source code in src/automax/core/engine.py
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
def run(
    self,
    *,
    job_path: str,
    inventory_path: str,
    vars_path: str | None = None,
    secrets_path: str | None = None,
    state_dir: str = ".automax/runs",
    run_id: str | None = None,
    dry_run: bool = False,
    plan_only: bool = False,
    from_node: str | None = None,
    limit: Iterable[str] = (),
    exclude: Iterable[str] = (),
    tags: Iterable[str] = (),
    skip_tags: Iterable[str] = (),
    cli_vars: Optional[Dict[str, Any]] = None,
    extra_plugin_paths: Iterable[str] = (),
    skip_successful: bool = False,
    only_failed: bool = False,
    output_format: str = "text",
    lock: bool = False,
    lock_scope: str = "both",
    lock_timeout: float = 0,
    preflight_capabilities: bool = False,
    sudo_password_env: str | None = None,
) -> int:
    """Execute a new run from external YAML files."""
    self._validate_output_format(output_format)
    registry = self.plugin_registry
    if extra_plugin_paths:
        registry.load_from_paths(extra_plugin_paths)

    documents = self._load_documents(
        job_path=job_path,
        inventory_path=inventory_path,
        vars_path=vars_path,
        secrets_path=secrets_path,
    )
    secrets = self.secret_manager.resolve_all(
        documents["secrets"],
        base_dir=Path(secrets_path).expanduser().resolve().parent if secrets_path else None,
    )
    variables = self._merge_variables(
        documents["vars"], documents["job"].get("vars", {}), cli_vars or {}
    )
    context = {"vars": variables, "secrets": secrets}
    inventory_document = load_inventory_document(inventory_path, context)
    inventory = Inventory(inventory_document, context)
    job = documents["job"]
    self.validate_job(job)
    sudo_password = self._resolve_sudo_password(sudo_password_env)

    run_id = run_id or self._build_run_id(job)
    store = StateStore(state_dir, run_id)
    store.create_run(
        job_path=str(Path(job_path).expanduser()),
        inventory_path=str(Path(inventory_path).expanduser()),
        vars_path=str(Path(vars_path).expanduser()) if vars_path else None,
        secrets_path=str(Path(secrets_path).expanduser()) if secrets_path else None,
        metadata={
            "dry_run": dry_run,
            "from": from_node,
            "limit": list(limit),
            "tags": list(tags),
            "skip_tags": list(skip_tags),
            "skip_successful": skip_successful,
            "only_failed": only_failed,
            "lock": lock,
            "lock_scope": lock_scope,
            "lock_timeout": lock_timeout,
            "preflight_capabilities": preflight_capabilities,
            "sudo_password_env": sudo_password_env,
        },
    )
    store.record_event("job_started", payload={"job": self._job_name(job)})

    try:
        plan = self._build_plan(
            job,
            inventory,
            limit=limit,
            exclude=exclude,
            tags=tags,
            skip_tags=skip_tags,
        )
        if plan_only:
            store.update_run_status(NodeStatus.SUCCESS)
            self._print_plan(run_id, plan, output_format=output_format)
            return 0

        variables = dict(variables)
        os_by_target: Dict[str, TargetOS] = {}
        if not dry_run and self._plan_requires_capability_preflight(job=job, plan=plan, variables=variables, secrets=secrets):
            os_by_target = self._detect_os_for_plan(plan, secrets)
            variables["__automax_os_by_target"] = {name: self._os_to_mapping(info) for name, info in os_by_target.items()}
            self._run_capability_preflight(job=job, plan=plan, variables=variables, secrets=secrets, os_by_target=os_by_target)
            store.record_event("capability_preflight_ok", payload={"targets": len({item["target"].name for item in plan})})

        lock_manager = LockManager.for_state_dir(state_dir) if lock else None
        acquired_locks = []
        try:
            if lock_manager:
                acquired_locks = lock_manager.acquire_many(
                    self._lock_names(job, plan, scope=lock_scope), timeout=lock_timeout
                )
                store.record_event(
                    "locks_acquired",
                    payload={"locks": [item.name for item in acquired_locks]},
                )
            rc = self._execute_plan(
                job=job,
                plan=plan,
                store=store,
                run_id=run_id,
                dry_run=dry_run,
                variables=variables,
                secrets=secrets,
                from_node=from_node,
                skip_successful=skip_successful,
                only_failed=only_failed,
                output_format=output_format,
                sudo_password=sudo_password,
            )
        finally:
            if lock_manager:
                lock_manager.release_many(acquired_locks)
        store.update_run_status(self._final_run_status(store, rc))
        store.record_event("job_finished", payload={"rc": rc})
        self._print_run_summary(store, rc=rc, state_dir=state_dir, output_format=output_format)
        return rc
    except Exception as exc:
        store.update_run_status(NodeStatus.FAILED)
        store.record_event("job_failed", payload={"error": self._mask_text(str(exc), secrets)})
        raise

validate(*, job_path, inventory_path, vars_path=None, secrets_path=None, cli_vars=None, tags=(), skip_tags=(), strict=False)

Validate external YAML files without executing.

Source code in src/automax/core/engine.py
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
def validate(
    self,
    *,
    job_path: str,
    inventory_path: str,
    vars_path: str | None = None,
    secrets_path: str | None = None,
    cli_vars: Optional[Dict[str, Any]] = None,
    tags: Iterable[str] = (),
    skip_tags: Iterable[str] = (),
    strict: bool = False,
) -> None:
    """Validate external YAML files without executing."""
    documents = self._load_documents(
        job_path=job_path,
        inventory_path=inventory_path,
        vars_path=vars_path,
        secrets_path=secrets_path,
    )
    secrets = self.secret_manager.resolve_all(
        documents["secrets"],
        base_dir=Path(secrets_path).expanduser().resolve().parent if secrets_path else None,
    )
    variables = self._merge_variables(
        documents["vars"], documents["job"].get("vars", {}), cli_vars or {}
    )
    context = {"vars": variables, "secrets": secrets}
    inventory_document = load_inventory_document(inventory_path, context)
    inventory = Inventory(inventory_document, context)
    job = documents["job"]
    self.validate_job(job, strict=strict)
    plan = self._build_plan(job, inventory, limit=(), exclude=(), tags=tags, skip_tags=skip_tags)
    if strict:
        self._validate_plan_strict(plan)

validate_job(job, *, strict=False)

Validate the canonical three-level job DSL.

Source code in src/automax/core/engine.py
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
def validate_job(self, job: Dict[str, Any], *, strict: bool = False) -> None:
    """Validate the canonical three-level job DSL."""
    if job.get("apiVersion") != "automax.io/v1":
        raise AutomaxError("job apiVersion must be 'automax.io/v1'")
    if job.get("kind") != "Job":
        raise AutomaxError("job kind must be 'Job'")
    if strict:
        self._validate_known_keys(
            job,
            "job",
            {
                "apiVersion",
                "kind",
                "metadata",
                "vars",
                "targets",
                "strategy",
                "failurePolicy",
                "errorPolicy",
                "timeouts",
                "retry",
                "tags",
                "tasks",
            },
        )
    self._validate_strategy(job.get("strategy"), "job")
    self._validate_failure_policy(job.get("failurePolicy"), "job")
    self._validate_error_policy(job.get("errorPolicy"), "job")
    self._validate_timeouts(job.get("timeouts"), "job")
    self._validate_retry_policy(job.get("retry"), "job")
    tasks = job.get("tasks")
    if not isinstance(tasks, list) or not tasks:
        raise AutomaxError("job requires non-empty tasks list")

    seen_tasks = set()
    for task in tasks:
        task_id = self._require_id(task, "task")
        if strict:
            self._validate_known_keys(
                task,
                f"task '{task_id}'",
                {
                    "id",
                    "name",
                    "description",
                    "vars",
                    "targets",
                    "strategy",
                    "failurePolicy",
                    "errorPolicy",
                    "timeouts",
                    "retry",
                    "tags",
                    "steps",
                },
            )
        self._validate_strategy(task.get("strategy"), f"task '{task_id}'")
        self._validate_failure_policy(task.get("failurePolicy"), f"task '{task_id}'")
        self._validate_error_policy(task.get("errorPolicy"), f"task '{task_id}'")
        self._validate_timeouts(task.get("timeouts"), f"task '{task_id}'")
        self._validate_retry_policy(task.get("retry"), f"task '{task_id}'")
        self._validate_tags(task.get("tags"), f"task '{task_id}'")
        if task_id in seen_tasks:
            raise AutomaxError(f"duplicate task id: {task_id}")
        seen_tasks.add(task_id)
        steps = task.get("steps")
        if not isinstance(steps, list) or not steps:
            raise AutomaxError(f"task '{task_id}' requires non-empty steps")
        seen_steps = set()
        for step in steps:
            step_id = self._require_id(step, "step")
            if strict:
                self._validate_known_keys(
                    step,
                    f"step '{task_id}:{step_id}'",
                    {
                        "id",
                        "name",
                        "description",
                        "vars",
                        "targets",
                        "strategy",
                        "failurePolicy",
                        "errorPolicy",
                        "timeouts",
                        "retry",
                        "tags",
                        "substeps",
                    },
                )
            self._validate_strategy(step.get("strategy"), f"step '{task_id}:{step_id}'")
            self._validate_failure_policy(step.get("failurePolicy"), f"step '{task_id}:{step_id}'")
            self._validate_error_policy(step.get("errorPolicy"), f"step '{task_id}:{step_id}'")
            self._validate_timeouts(step.get("timeouts"), f"step '{task_id}:{step_id}'")
            self._validate_retry_policy(step.get("retry"), f"step '{task_id}:{step_id}'")
            self._validate_tags(step.get("tags"), f"step '{task_id}:{step_id}'")
            if step_id in seen_steps:
                raise AutomaxError(f"duplicate step id in task '{task_id}': {step_id}")
            seen_steps.add(step_id)
            substeps = step.get("substeps")
            if not isinstance(substeps, list) or not substeps:
                raise AutomaxError(
                    f"step '{task_id}:{step_id}' requires non-empty substeps"
                )
            self._validate_substep_list(
                substeps,
                label=f"{task_id}:{step_id}",
                strict=strict,
            )

AutomaxError

Bases: ValueError

Raised for user-facing Automax errors.

Source code in src/automax/core/engine.py
41
42
class AutomaxError(ValueError):
    """Raised for user-facing Automax errors."""

ResolvedJobContext dataclass

Resolved job inputs shared by operator-facing inspection commands.

Source code in src/automax/core/engine.py
45
46
47
48
49
50
51
52
53
54
55
56
57
58
@dataclass(frozen=True)
class ResolvedJobContext:
    """Resolved job inputs shared by operator-facing inspection commands."""

    job_path: str
    inventory_path: str
    vars_path: str | None
    secrets_path: str | None
    documents: Dict[str, Dict[str, Any]]
    job: Dict[str, Any]
    inventory: Inventory
    variables: Dict[str, Any]
    secrets: Dict[str, Any]
    plan: List[Dict[str, Any]]

Plugin base

automax.plugins.base

Plugin base contract for Automax engine.

BasePlugin

Bases: ABC

Stable interface implemented by all action plugins.

Source code in src/automax/plugins/base.py
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
class BasePlugin(ABC):
    """Stable interface implemented by all action plugins."""

    name = "base"
    aliases: tuple[str, ...] = ()
    description = ""
    category = ""
    required_params: tuple[str, ...] = ()
    optional_params: tuple[str, ...] = ()
    parameter_schema: Dict[str, Dict[str, Any]] = {}
    examples: tuple[str, ...] = ()
    result_fields: Dict[str, str] = {}
    opens_remote_session = False
    supports_dry_run = True
    supports_check_mode = False


    def metadata(self) -> Dict[str, Any]:
        """Return structured metadata used by CLI and documentation generators."""
        parameters = []
        for name in (*self.required_params, *self.optional_params):
            details = dict(self.parameter_schema.get(name, {}))
            parameters.append(
                {
                    "name": name,
                    "required": name in self.required_params,
                    "type": details.get("type", "any"),
                    "default": details.get("default"),
                    "description": details.get("description", ""),
                }
            )
        return {
            "name": self.name,
            "category": self.category or self.name.split(".", 1)[0],
            "description": self.description,
            "required_params": list(self.required_params),
            "optional_params": list(self.optional_params),
            "parameters": parameters,
            "examples": list(self.examples),
            "result_fields": dict(self.result_fields),
            "aliases": list(self.aliases),
            "opens_remote_session": self.opens_remote_session,
            "supports_dry_run": self.supports_dry_run,
            "supports_check_mode": self.supports_check_mode,
        }

    def validate(self, params: Dict[str, Any]) -> None:
        """Validate the common plugin parameter contract.

        Builtin plugins expose ``required_params``, ``optional_params`` and a
        runtime ``parameter_schema`` populated by the registry metadata pass.
        Keeping this check in the base class makes typos, wrong YAML scalar
        types and unsupported enum values fail before a plugin builds shell
        commands or touches a target.
        """
        if not isinstance(params, Mapping):
            raise PluginValidationError(f"plugin '{self.name}' params must be mapping")

        missing = [key for key in self.required_params if key not in params]
        if missing:
            raise PluginValidationError(
                f"plugin '{self.name}' missing required params: {', '.join(missing)}"
            )

        allowed = set(self.required_params) | set(self.optional_params)
        unknown = sorted(set(params) - allowed)
        if unknown:
            raise PluginValidationError(
                f"plugin '{self.name}' unknown params: {', '.join(unknown)}"
            )

        for name, value in params.items():
            self._validate_parameter(name, value)

    def _validate_parameter(self, name: str, value: Any) -> None:
        """Validate one parameter using this plugin's runtime schema."""
        schema = dict(self.parameter_schema.get(name, {}) or {})
        expected_types = schema.get("types", schema.get("type", "any"))
        if isinstance(expected_types, str):
            expected_types = (expected_types,)
        if expected_types and "any" not in expected_types:
            self._validate_parameter_type(name, value, tuple(str(item) for item in expected_types))

        enum = schema.get("enum")
        if enum is not None and value not in enum:
            allowed = ", ".join(str(item) for item in enum)
            raise PluginValidationError(
                f"plugin '{self.name}' param '{name}' must be one of: {allowed}"
            )

        if "min" in schema and self._is_number(value) and value < schema["min"]:
            raise PluginValidationError(
                f"plugin '{self.name}' param '{name}' must be >= {schema['min']}"
            )
        if "max" in schema and self._is_number(value) and value > schema["max"]:
            raise PluginValidationError(
                f"plugin '{self.name}' param '{name}' must be <= {schema['max']}"
            )
        if schema.get("non_empty") and self._is_empty(value):
            raise PluginValidationError(
                f"plugin '{self.name}' param '{name}' must not be empty"
            )

    def _validate_parameter_type(
        self, name: str, value: Any, expected_types: tuple[str, ...]
    ) -> None:
        known_types = {"string", "path", "boolean", "integer", "number", "list", "sequence", "mapping"}
        if not any(expected_type in known_types for expected_type in expected_types):
            return

        for expected_type in expected_types:
            if expected_type in {"string", "path"} and isinstance(value, str):
                return
            if expected_type == "boolean" and isinstance(value, bool):
                return
            if (
                expected_type == "integer"
                and isinstance(value, int)
                and not isinstance(value, bool)
            ):
                return
            if expected_type == "number" and self._is_number(value):
                return
            if expected_type in {"list", "sequence"} and isinstance(value, list):
                return
            if expected_type == "mapping" and isinstance(value, dict):
                return

        expected = " or ".join(expected_types)
        raise PluginValidationError(
            f"plugin '{self.name}' param '{name}' must be {expected}"
        )

    @staticmethod
    def _is_number(value: Any) -> bool:
        return isinstance(value, (int, float)) and not isinstance(value, bool)

    @staticmethod
    def _is_empty(value: Any) -> bool:
        return value is None or value == "" or value == [] or value == {}

    def dry_run(self, params: Dict[str, Any], context: ExecutionContext) -> PluginResult:
        """Default dry-run implementation with operator preview data."""
        from automax.plugins.manual_preview import fallback_dry_run_data

        return PluginResult.success(
            changed=False,
            message=f"dry-run: {self.name}",
            data=fallback_dry_run_data(self.name, params, context),
        )

    def diff_preview(
        self, params: Dict[str, Any], context: ExecutionContext
    ) -> list[Dict[str, Any]]:
        """Return safe previews for plugins without a dedicated file diff renderer."""
        from automax.plugins.manual_preview import fallback_diff_preview

        return fallback_diff_preview(self.name, params, context)

    def diff_preview_reason(self, params: Dict[str, Any], context: ExecutionContext) -> str:
        """Explain that the generic preview is an operation plan, not a file diff."""
        return f"{self.name} uses a generic operation-plan preview because it has no deterministic file diff"

    def manual_commands(
        self, params: Dict[str, Any], context: ExecutionContext
    ) -> list[str]:
        """Return copy/pasteable shell commands for manual recovery."""
        from automax.plugins.manual_preview import fallback_manual_commands

        return fallback_manual_commands(self.name, params, context)

    def manual_commands_reason(self, params: Dict[str, Any], context: ExecutionContext) -> str:
        """Explain whether a dedicated or generic manual renderer is used."""
        return f"{self.name} uses the generic manual command renderer"

    @abstractmethod
    def execute(self, params: Dict[str, Any], context: ExecutionContext) -> PluginResult:
        """Execute a plugin action."""

diff_preview(params, context)

Return safe previews for plugins without a dedicated file diff renderer.

Source code in src/automax/plugins/base.py
169
170
171
172
173
174
175
def diff_preview(
    self, params: Dict[str, Any], context: ExecutionContext
) -> list[Dict[str, Any]]:
    """Return safe previews for plugins without a dedicated file diff renderer."""
    from automax.plugins.manual_preview import fallback_diff_preview

    return fallback_diff_preview(self.name, params, context)

diff_preview_reason(params, context)

Explain that the generic preview is an operation plan, not a file diff.

Source code in src/automax/plugins/base.py
177
178
179
def diff_preview_reason(self, params: Dict[str, Any], context: ExecutionContext) -> str:
    """Explain that the generic preview is an operation plan, not a file diff."""
    return f"{self.name} uses a generic operation-plan preview because it has no deterministic file diff"

dry_run(params, context)

Default dry-run implementation with operator preview data.

Source code in src/automax/plugins/base.py
159
160
161
162
163
164
165
166
167
def dry_run(self, params: Dict[str, Any], context: ExecutionContext) -> PluginResult:
    """Default dry-run implementation with operator preview data."""
    from automax.plugins.manual_preview import fallback_dry_run_data

    return PluginResult.success(
        changed=False,
        message=f"dry-run: {self.name}",
        data=fallback_dry_run_data(self.name, params, context),
    )

execute(params, context) abstractmethod

Execute a plugin action.

Source code in src/automax/plugins/base.py
193
194
195
@abstractmethod
def execute(self, params: Dict[str, Any], context: ExecutionContext) -> PluginResult:
    """Execute a plugin action."""

manual_commands(params, context)

Return copy/pasteable shell commands for manual recovery.

Source code in src/automax/plugins/base.py
181
182
183
184
185
186
187
def manual_commands(
    self, params: Dict[str, Any], context: ExecutionContext
) -> list[str]:
    """Return copy/pasteable shell commands for manual recovery."""
    from automax.plugins.manual_preview import fallback_manual_commands

    return fallback_manual_commands(self.name, params, context)

manual_commands_reason(params, context)

Explain whether a dedicated or generic manual renderer is used.

Source code in src/automax/plugins/base.py
189
190
191
def manual_commands_reason(self, params: Dict[str, Any], context: ExecutionContext) -> str:
    """Explain whether a dedicated or generic manual renderer is used."""
    return f"{self.name} uses the generic manual command renderer"

metadata()

Return structured metadata used by CLI and documentation generators.

Source code in src/automax/plugins/base.py
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
def metadata(self) -> Dict[str, Any]:
    """Return structured metadata used by CLI and documentation generators."""
    parameters = []
    for name in (*self.required_params, *self.optional_params):
        details = dict(self.parameter_schema.get(name, {}))
        parameters.append(
            {
                "name": name,
                "required": name in self.required_params,
                "type": details.get("type", "any"),
                "default": details.get("default"),
                "description": details.get("description", ""),
            }
        )
    return {
        "name": self.name,
        "category": self.category or self.name.split(".", 1)[0],
        "description": self.description,
        "required_params": list(self.required_params),
        "optional_params": list(self.optional_params),
        "parameters": parameters,
        "examples": list(self.examples),
        "result_fields": dict(self.result_fields),
        "aliases": list(self.aliases),
        "opens_remote_session": self.opens_remote_session,
        "supports_dry_run": self.supports_dry_run,
        "supports_check_mode": self.supports_check_mode,
    }

validate(params)

Validate the common plugin parameter contract.

Builtin plugins expose required_params, optional_params and a runtime parameter_schema populated by the registry metadata pass. Keeping this check in the base class makes typos, wrong YAML scalar types and unsupported enum values fail before a plugin builds shell commands or touches a target.

Source code in src/automax/plugins/base.py
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
def validate(self, params: Dict[str, Any]) -> None:
    """Validate the common plugin parameter contract.

    Builtin plugins expose ``required_params``, ``optional_params`` and a
    runtime ``parameter_schema`` populated by the registry metadata pass.
    Keeping this check in the base class makes typos, wrong YAML scalar
    types and unsupported enum values fail before a plugin builds shell
    commands or touches a target.
    """
    if not isinstance(params, Mapping):
        raise PluginValidationError(f"plugin '{self.name}' params must be mapping")

    missing = [key for key in self.required_params if key not in params]
    if missing:
        raise PluginValidationError(
            f"plugin '{self.name}' missing required params: {', '.join(missing)}"
        )

    allowed = set(self.required_params) | set(self.optional_params)
    unknown = sorted(set(params) - allowed)
    if unknown:
        raise PluginValidationError(
            f"plugin '{self.name}' unknown params: {', '.join(unknown)}"
        )

    for name, value in params.items():
        self._validate_parameter(name, value)

ReadOnlyCommandPlugin

Bases: BasePlugin

Base class for read-only plugins rendered as shell commands.

Source code in src/automax/plugins/base.py
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
class ReadOnlyCommandPlugin(BasePlugin):
    """Base class for read-only plugins rendered as shell commands."""

    opens_remote_session = True
    supports_check_mode = True

    def diff_preview_reason(self, params: Dict[str, Any], context: ExecutionContext) -> str:
        return f"{self.name} is a read-only assertion or fact query"

    def command_failure_message(self, params: Dict[str, Any]) -> str:
        """Return the failure message used when the read-only command fails."""
        return f"{self.name} failed"

    def command_result_data(self, params: Dict[str, Any], stdout: str, stderr: str, rc: int) -> Dict[str, Any]:
        """Return optional structured data for a successful command result."""
        return {"output": stdout}

    def predicate_data_key(self) -> str:
        """Return the boolean data key used by command-backed check plugins."""
        if self.name.endswith(".check") or self.name.endswith("_check"):
            return "matches"
        return "ok"

    def is_predicate_check(self) -> bool:
        """Return whether this read-only command is a non-failing check predicate."""
        return self.name.endswith(".check") or self.name.endswith("_check")

    def execute(self, params: Dict[str, Any], context: ExecutionContext) -> PluginResult:
        commands = self.manual_commands(params, context)
        rc, out, err = self._execute_read_only_commands(commands, context)
        if self.is_predicate_check() and rc in {0, 1}:
            data = self.command_result_data(params, out, err, rc)
            data[self.predicate_data_key()] = rc == 0
            if rc != 0:
                data["condition_rc"] = rc
            return PluginResult.success(changed=False, rc=0, stdout=out, stderr=err, data=data)
        if rc != 0:
            return PluginResult.failure(
                rc=rc,
                stdout=out,
                stderr=err,
                message=self.command_failure_message(params),
            )
        return PluginResult.success(
            changed=False,
            rc=rc,
            stdout=out,
            stderr=err,
            data=self.command_result_data(params, out, err, rc),
        )

    def _execute_read_only_commands(self, commands: list[str], context: ExecutionContext) -> tuple[int, str, str]:
        """Execute one or more read-only commands and aggregate output."""
        from automax.plugins.remote_utils import exec_remote

        stdout_parts: list[str] = []
        stderr_parts: list[str] = []
        last_rc = 0
        for command in commands:
            last_rc, out, err = exec_remote(context, command)
            if out:
                stdout_parts.append(out)
            if err:
                stderr_parts.append(err)
            if last_rc != 0:
                break
        return last_rc, "\n".join(stdout_parts), "\n".join(stderr_parts)

command_failure_message(params)

Return the failure message used when the read-only command fails.

Source code in src/automax/plugins/base.py
318
319
320
def command_failure_message(self, params: Dict[str, Any]) -> str:
    """Return the failure message used when the read-only command fails."""
    return f"{self.name} failed"

command_result_data(params, stdout, stderr, rc)

Return optional structured data for a successful command result.

Source code in src/automax/plugins/base.py
322
323
324
def command_result_data(self, params: Dict[str, Any], stdout: str, stderr: str, rc: int) -> Dict[str, Any]:
    """Return optional structured data for a successful command result."""
    return {"output": stdout}

is_predicate_check()

Return whether this read-only command is a non-failing check predicate.

Source code in src/automax/plugins/base.py
332
333
334
def is_predicate_check(self) -> bool:
    """Return whether this read-only command is a non-failing check predicate."""
    return self.name.endswith(".check") or self.name.endswith("_check")

predicate_data_key()

Return the boolean data key used by command-backed check plugins.

Source code in src/automax/plugins/base.py
326
327
328
329
330
def predicate_data_key(self) -> str:
    """Return the boolean data key used by command-backed check plugins."""
    if self.name.endswith(".check") or self.name.endswith("_check"):
        return "matches"
    return "ok"

RenderedFileInstallMixin

Shared implementation for plugins that render and install one managed file.

Source code in src/automax/plugins/base.py
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
class RenderedFileInstallMixin:
    """Shared implementation for plugins that render and install one managed file."""

    rendered_file_temp_prefix = "automax-file"
    rendered_file_diff_kind = "managed-file-plan"
    rendered_file_default_mode = "0644"
    rendered_file_default_backup = True
    rendered_file_default_sudo = True

    def rendered_file_path(self, params: Dict[str, Any]) -> str:
        """Return the managed destination path."""
        return str(params["path"])

    def rendered_file_content(self, params: Dict[str, Any]) -> str:
        """Return the desired file content."""
        raise PluginValidationError(f"plugin '{self.name}' must implement rendered_file_content")

    def rendered_file_mode(self, params: Dict[str, Any]) -> str:
        """Return the install mode for the rendered file."""
        return str(params.get("mode", self.rendered_file_default_mode))

    def rendered_file_sudo(self, params: Dict[str, Any]) -> str:
        """Return sudo prefix for managed-file commands."""
        from automax.plugins.remote_utils import sudo_prefix

        return sudo_prefix(params, default=self.rendered_file_default_sudo)

    def rendered_file_backup_enabled(self, params: Dict[str, Any]) -> bool:
        """Return whether the existing destination should be backed up."""
        return bool(params.get("backup", self.rendered_file_default_backup))

    def rendered_file_backup_suffix(self, params: Dict[str, Any]) -> str:
        """Return the suffix used for pre-install backups."""
        return str(params.get("backup_suffix", ".bak"))

    def rendered_file_validate_commands(self, params: Dict[str, Any], context: ExecutionContext, temp_path: str) -> list[str]:
        """Return validation commands to run after rendering and before install."""
        return []

    def rendered_file_post_install_commands(self, params: Dict[str, Any], context: ExecutionContext) -> list[str]:
        """Return commands to run after the managed file is installed."""
        return []

    def rendered_file_result_data(self, params: Dict[str, Any]) -> Dict[str, Any]:
        """Return structured result data for the managed file operation."""
        return {"path": self.rendered_file_path(params)}

    def diff_preview(self, params: Dict[str, Any], context: ExecutionContext) -> list[Dict[str, Any]]:
        self.validate(params)
        from difflib import unified_diff

        path = self.rendered_file_path(params)
        content = self.rendered_file_content(params)
        diff = "".join(
            unified_diff(
                [],
                content.splitlines(keepends=True),
                fromfile=f"{path} (current)",
                tofile=f"{path} (desired)",
            )
        )
        return [{"path": path, "kind": self.rendered_file_diff_kind, "diff": diff}]

    def manual_commands(self, params: Dict[str, Any], context: ExecutionContext) -> list[str]:
        self.validate(params)
        from automax.plugins.remote_utils import (
            cleanup_trap_command,
            heredoc_to_file_expr,
            quote,
            shell_var_ref,
            tempfile_command,
        )

        content = self.rendered_file_content(params)
        path = self.rendered_file_path(params)
        mode = self.rendered_file_mode(params)
        sudo = self.rendered_file_sudo(params)
        temp_var = f"{self.name.replace('.', '_').replace('-', '_')}_tmp"
        temp = shell_var_ref(temp_var)
        commands = [
            tempfile_command(temp_var, self.rendered_file_temp_prefix),
            cleanup_trap_command(temp_var),
            heredoc_to_file_expr(temp, content),
        ]
        commands.extend(self.rendered_file_validate_commands(params, context, temp))
        if self.rendered_file_backup_enabled(params):
            backup = path + self.rendered_file_backup_suffix(params)
            commands.append(f"test ! -e {quote(path)} || {sudo}cp -p {quote(path)} {quote(backup)}")
        commands.append(f"{sudo}install -D -m {quote(mode)} {temp} {quote(path)}")
        if params.get("owner") or params.get("group"):
            owner = str(params.get("owner", ""))
            group = str(params.get("group", ""))
            spec = f"{owner}:{group}" if group else owner
            commands.append(f"{sudo}chown {quote(spec)} {quote(path)}")
        commands.append(f"rm -f {temp}")
        commands.extend(self.rendered_file_post_install_commands(params, context))
        return commands

    def execute(self, params: Dict[str, Any], context: ExecutionContext) -> PluginResult:
        from automax.plugins.remote_utils import CHANGE_MARKER, exec_remote, result_from_remote

        rc, out, err = exec_remote(context, " && ".join(self.manual_commands(params, context)))
        return result_from_remote(
            rc=rc,
            stdout=f"{out}\n{CHANGE_MARKER}\n" if rc == 0 else out,
            stderr=err,
            message=f"{self.name} failed",
            data=self.rendered_file_result_data(params) if rc == 0 else {},
        )

rendered_file_backup_enabled(params)

Return whether the existing destination should be backed up.

Source code in src/automax/plugins/base.py
225
226
227
def rendered_file_backup_enabled(self, params: Dict[str, Any]) -> bool:
    """Return whether the existing destination should be backed up."""
    return bool(params.get("backup", self.rendered_file_default_backup))

rendered_file_backup_suffix(params)

Return the suffix used for pre-install backups.

Source code in src/automax/plugins/base.py
229
230
231
def rendered_file_backup_suffix(self, params: Dict[str, Any]) -> str:
    """Return the suffix used for pre-install backups."""
    return str(params.get("backup_suffix", ".bak"))

rendered_file_content(params)

Return the desired file content.

Source code in src/automax/plugins/base.py
211
212
213
def rendered_file_content(self, params: Dict[str, Any]) -> str:
    """Return the desired file content."""
    raise PluginValidationError(f"plugin '{self.name}' must implement rendered_file_content")

rendered_file_mode(params)

Return the install mode for the rendered file.

Source code in src/automax/plugins/base.py
215
216
217
def rendered_file_mode(self, params: Dict[str, Any]) -> str:
    """Return the install mode for the rendered file."""
    return str(params.get("mode", self.rendered_file_default_mode))

rendered_file_path(params)

Return the managed destination path.

Source code in src/automax/plugins/base.py
207
208
209
def rendered_file_path(self, params: Dict[str, Any]) -> str:
    """Return the managed destination path."""
    return str(params["path"])

rendered_file_post_install_commands(params, context)

Return commands to run after the managed file is installed.

Source code in src/automax/plugins/base.py
237
238
239
def rendered_file_post_install_commands(self, params: Dict[str, Any], context: ExecutionContext) -> list[str]:
    """Return commands to run after the managed file is installed."""
    return []

rendered_file_result_data(params)

Return structured result data for the managed file operation.

Source code in src/automax/plugins/base.py
241
242
243
def rendered_file_result_data(self, params: Dict[str, Any]) -> Dict[str, Any]:
    """Return structured result data for the managed file operation."""
    return {"path": self.rendered_file_path(params)}

rendered_file_sudo(params)

Return sudo prefix for managed-file commands.

Source code in src/automax/plugins/base.py
219
220
221
222
223
def rendered_file_sudo(self, params: Dict[str, Any]) -> str:
    """Return sudo prefix for managed-file commands."""
    from automax.plugins.remote_utils import sudo_prefix

    return sudo_prefix(params, default=self.rendered_file_default_sudo)

rendered_file_validate_commands(params, context, temp_path)

Return validation commands to run after rendering and before install.

Source code in src/automax/plugins/base.py
233
234
235
def rendered_file_validate_commands(self, params: Dict[str, Any], context: ExecutionContext, temp_path: str) -> list[str]:
    """Return validation commands to run after rendering and before install."""
    return []

Plugin registry

automax.plugins.registry

Explicit plugin registry.

Builtins are imported explicitly. Extra plugins can be loaded later from Python entry points or external plugin paths without touching the engine.

PluginRegistry

Runtime plugin registry.

Source code in src/automax/plugins/registry.py
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
class PluginRegistry:
    """Runtime plugin registry."""

    def __init__(self):
        self._plugins: Dict[str, BasePlugin] = {}
        self._canonical_names: set[str] = set()
        self._temporary_plugin_dirs: list[tempfile.TemporaryDirectory[str]] = []

    def register(self, plugin: BasePlugin) -> None:
        """Register one plugin instance under its canonical name and optional aliases."""
        if plugin.name in self._plugins:
            raise PluginRegistryError(f"duplicate plugin name: {plugin.name}")
        self._plugins[plugin.name] = plugin
        self._canonical_names.add(plugin.name)
        for alias in plugin.aliases:
            if alias in self._plugins:
                raise PluginRegistryError(f"duplicate plugin alias: {alias}")
            self._plugins[alias] = plugin

    def get(self, name: str) -> BasePlugin:
        """Return a plugin by name."""
        try:
            return self._plugins[name]
        except KeyError as exc:
            raise PluginRegistryError(f"unknown plugin: {name}") from exc

    def names(self, *, include_aliases: bool = False) -> list[str]:
        """List canonical plugin names, optionally including aliases."""
        if include_aliases:
            return sorted(self._plugins)
        return sorted(self._canonical_names)

    def describe(self, name: str) -> dict[str, object]:
        """Return user-facing metadata for one plugin."""
        return self.get(name).metadata()

    def describe_all(self) -> list[dict[str, object]]:
        """Return metadata for all canonical plugins."""
        return [self.get(name).metadata() for name in self.names()]

    def load_from_paths(self, paths: Iterable[str]) -> None:
        """Load plugin classes from external .py files, directories or ZIP packages."""
        for raw_path in paths:
            path = Path(raw_path).expanduser().resolve()
            if path.is_dir():
                locked_hashes = self._locked_package_hashes(path)
                for plugin_file in sorted(item for item in path.iterdir() if item.is_file()):
                    if plugin_file.suffix.lower() == ".py":
                        self._load_module_file(plugin_file)
                    elif plugin_file.suffix.lower() == ".zip":
                        self._verify_locked_package(path, plugin_file, locked_hashes)
                        self._load_package_file(plugin_file)
                self._verify_locked_packages_present(path, locked_hashes)
            elif path.is_file() and path.suffix.lower() == ".zip":
                self._load_package_file(path)
            elif path.is_file():
                self._load_module_file(path)
            else:
                raise PluginRegistryError(f"plugin path not found: {path}")

    def _locked_package_hashes(self, directory: Path) -> dict[str, str]:
        lock_path = directory / "automax-plugins.lock.json"
        if not lock_path.exists():
            return {}
        try:
            payload = json.loads(lock_path.read_text(encoding="utf-8"))
        except json.JSONDecodeError as exc:
            raise PluginRegistryError(f"plugin lock file is invalid: {lock_path}: {exc}") from exc
        if payload.get("format") != "automax-external-plugin-lock-v1":
            raise PluginRegistryError(f"plugin lock file format is unsupported: {lock_path}")
        packages = payload.get("packages")
        if not isinstance(packages, list):
            raise PluginRegistryError(f"plugin lock file packages must be a list: {lock_path}")
        locked: dict[str, str] = {}
        for entry in packages:
            if not isinstance(entry, dict):
                raise PluginRegistryError(f"plugin lock file package entries must be objects: {lock_path}")
            name = str(entry.get("package") or "")
            digest = str(entry.get("sha256") or "")
            if not name or Path(name).name != name or not name.endswith(".zip"):
                raise PluginRegistryError(f"plugin lock file contains invalid package name: {name or '<empty>'}")
            if not digest:
                raise PluginRegistryError(f"plugin lock file contains empty checksum for: {name}")
            locked[name] = digest
        return locked

    def _verify_locked_package(self, directory: Path, package_file: Path, locked_hashes: dict[str, str]) -> None:
        if not locked_hashes:
            return
        expected_hash = locked_hashes.get(package_file.name)
        if expected_hash is None:
            raise PluginRegistryError(f"plugin package is not recorded in lock: {directory / package_file.name}")
        actual_hash = self._sha256_file(package_file)
        if actual_hash != expected_hash:
            raise PluginRegistryError(f"plugin package lock checksum mismatch: {directory / package_file.name}")

    def _verify_locked_packages_present(self, directory: Path, locked_hashes: dict[str, str]) -> None:
        for name in sorted(locked_hashes):
            if not (directory / name).exists():
                raise PluginRegistryError(f"locked plugin package is missing: {directory / name}")

    @staticmethod
    def _sha256_file(path: Path) -> str:
        digest = hashlib.sha256()
        with path.open("rb") as handle:
            for chunk in iter(lambda: handle.read(1024 * 1024), b""):
                digest.update(chunk)
        return digest.hexdigest()

    def _load_package_file(self, path: Path) -> None:
        package_dir = self._extract_verified_package(path)
        for plugin_file in sorted(Path(package_dir.name).glob("*.py")):
            self._load_module_file(plugin_file)
        self._temporary_plugin_dirs.append(package_dir)

    def _extract_verified_package(self, path: Path) -> tempfile.TemporaryDirectory[str]:
        try:
            archive = zipfile.ZipFile(path)
        except zipfile.BadZipFile as exc:
            raise PluginRegistryError(f"invalid plugin package: {path}: {exc}") from exc

        with archive:
            names = set(archive.namelist())
            if "automax-plugin.json" not in names:
                raise PluginRegistryError(f"plugin package manifest is missing: {path}")
            try:
                manifest = json.loads(archive.read("automax-plugin.json").decode("utf-8"))
            except (UnicodeDecodeError, json.JSONDecodeError) as exc:
                raise PluginRegistryError(f"plugin package manifest is invalid: {path}: {exc}") from exc

            if manifest.get("format") != "automax-external-plugin-package-v1":
                raise PluginRegistryError("plugin package manifest format is unsupported")
            files = manifest.get("files") or []
            if not isinstance(files, list):
                raise PluginRegistryError("plugin package manifest files must be a list")

            sources: list[str] = []
            for entry in files:
                if not isinstance(entry, dict):
                    raise PluginRegistryError("plugin package manifest file entries must be objects")
                rel = str(entry.get("path") or "")
                if not rel or rel.startswith("/") or ".." in Path(rel).parts:
                    raise PluginRegistryError(f"invalid plugin package file path: {rel or '<empty>'}")
                if rel not in names:
                    raise PluginRegistryError(f"packaged file missing from archive: {rel}")
                data = archive.read(rel)
                expected_size = entry.get("size")
                expected_hash = str(entry.get("sha256") or "")
                if not isinstance(expected_size, int) or expected_size != len(data):
                    raise PluginRegistryError(f"plugin package size mismatch: {rel}")
                if expected_hash != hashlib.sha256(data).hexdigest():
                    raise PluginRegistryError(f"plugin package checksum mismatch: {rel}")
                if rel.endswith(".py"):
                    sources.append(rel)

            if not sources:
                raise PluginRegistryError("plugin package does not declare Python plugin sources")

            package_dir = tempfile.TemporaryDirectory(prefix="automax-plugins-")
            root = Path(package_dir.name)
            try:
                for rel in sorted(sources):
                    target = root / rel
                    target.parent.mkdir(parents=True, exist_ok=True)
                    target.write_bytes(archive.read(rel))
            except Exception:
                package_dir.cleanup()
                raise
            return package_dir

    def _load_module_file(self, path: Path) -> None:
        module_name = f"automax_external_plugin_{path.stem}"
        spec = importlib.util.spec_from_file_location(module_name, path)
        if spec is None or spec.loader is None:
            raise PluginRegistryError(f"cannot load plugin module: {path}")
        module = importlib.util.module_from_spec(spec)
        spec.loader.exec_module(module)

        found = False
        for _, obj in inspect.getmembers(module, inspect.isclass):
            if issubclass(obj, BasePlugin) and obj is not BasePlugin:
                self.register(obj())
                found = True
        if not found:
            raise PluginRegistryError(f"no BasePlugin subclasses found in: {path}")

describe(name)

Return user-facing metadata for one plugin.

Source code in src/automax/plugins/registry.py
62
63
64
def describe(self, name: str) -> dict[str, object]:
    """Return user-facing metadata for one plugin."""
    return self.get(name).metadata()

describe_all()

Return metadata for all canonical plugins.

Source code in src/automax/plugins/registry.py
66
67
68
def describe_all(self) -> list[dict[str, object]]:
    """Return metadata for all canonical plugins."""
    return [self.get(name).metadata() for name in self.names()]

get(name)

Return a plugin by name.

Source code in src/automax/plugins/registry.py
49
50
51
52
53
54
def get(self, name: str) -> BasePlugin:
    """Return a plugin by name."""
    try:
        return self._plugins[name]
    except KeyError as exc:
        raise PluginRegistryError(f"unknown plugin: {name}") from exc

load_from_paths(paths)

Load plugin classes from external .py files, directories or ZIP packages.

Source code in src/automax/plugins/registry.py
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
def load_from_paths(self, paths: Iterable[str]) -> None:
    """Load plugin classes from external .py files, directories or ZIP packages."""
    for raw_path in paths:
        path = Path(raw_path).expanduser().resolve()
        if path.is_dir():
            locked_hashes = self._locked_package_hashes(path)
            for plugin_file in sorted(item for item in path.iterdir() if item.is_file()):
                if plugin_file.suffix.lower() == ".py":
                    self._load_module_file(plugin_file)
                elif plugin_file.suffix.lower() == ".zip":
                    self._verify_locked_package(path, plugin_file, locked_hashes)
                    self._load_package_file(plugin_file)
            self._verify_locked_packages_present(path, locked_hashes)
        elif path.is_file() and path.suffix.lower() == ".zip":
            self._load_package_file(path)
        elif path.is_file():
            self._load_module_file(path)
        else:
            raise PluginRegistryError(f"plugin path not found: {path}")

names(*, include_aliases=False)

List canonical plugin names, optionally including aliases.

Source code in src/automax/plugins/registry.py
56
57
58
59
60
def names(self, *, include_aliases: bool = False) -> list[str]:
    """List canonical plugin names, optionally including aliases."""
    if include_aliases:
        return sorted(self._plugins)
    return sorted(self._canonical_names)

register(plugin)

Register one plugin instance under its canonical name and optional aliases.

Source code in src/automax/plugins/registry.py
38
39
40
41
42
43
44
45
46
47
def register(self, plugin: BasePlugin) -> None:
    """Register one plugin instance under its canonical name and optional aliases."""
    if plugin.name in self._plugins:
        raise PluginRegistryError(f"duplicate plugin name: {plugin.name}")
    self._plugins[plugin.name] = plugin
    self._canonical_names.add(plugin.name)
    for alias in plugin.aliases:
        if alias in self._plugins:
            raise PluginRegistryError(f"duplicate plugin alias: {alias}")
        self._plugins[alias] = plugin

PluginRegistryError

Bases: ValueError

Raised when a plugin cannot be registered or found.

Source code in src/automax/plugins/registry.py
26
27
class PluginRegistryError(ValueError):
    """Raised when a plugin cannot be registered or found."""

build_builtin_registry(extra_plugin_paths=())

Create a registry with builtin plugins and optional external plugins.

Source code in src/automax/plugins/registry.py
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
def build_builtin_registry(extra_plugin_paths: Iterable[str] = ()) -> PluginRegistry:
    """Create a registry with builtin plugins and optional external plugins."""
    from automax.plugins.capabilities import CapabilityAssertPlugin, PluginRequirementsPlugin
    from automax.plugins.block import (
        BlockFactsPlugin,
        BlockIdentityPlugin,
        BlockMkfsPlugin,
        BlockPartitionPlugin,
        BlockPartitionRescanPlugin,
        BlockRescanPlugin,
        BlockWipeSignaturesPlugin,
    )
    from automax.plugins.alternatives import AlternativesCheckPlugin, AlternativesGetPlugin, AlternativesListPlugin, AlternativesSetPlugin
    from automax.plugins.cert_ops import (
        CertExpiryReportPlugin,
        CertFingerprintPlugin,
        CertGenerateCsrPlugin,
        CertInstallCaBundlePlugin,
        CertInstallKeypairPlugin,
        CertIssuerAssertPlugin,
        CertMatchesKeyPlugin,
        CertSanAssertPlugin,
        CertSelfSignedPlugin,
        CertSubjectAssertPlugin,
        CertVerifyChainPlugin,
    )
    from automax.plugins.backup import (
        BackupDirectoryPlugin,
        BackupFilePlugin,
        BackupListPlugin,
        BackupManifestPlugin,
        BackupPrunePlugin,
        BackupRestorePlugin,
        BackupRestorePreviewPlugin,
        BackupRestoreVerifyPlugin,
        BackupRotatePlugin,
        BackupVerifyPlugin,
    )
    from automax.plugins.auditd import AuditdReloadPlugin, AuditdRulePlugin, AuditdStatusPlugin
    from automax.plugins.archive import (
        ArchiveTarCheckPlugin,
        ArchiveTarListPlugin,
        ArchiveTarPlugin,
        ArchiveZipCheckPlugin,
        ArchiveZipListPlugin,
        ArchiveZipPlugin,
        CompressionBzip2CheckPlugin,
        CompressionBzip2CompressPlugin,
        CompressionBzip2DecompressPlugin,
        CompressionGzipCheckPlugin,
        CompressionGzipCompressPlugin,
        CompressionGzipDecompressPlugin,
        CompressionXzCheckPlugin,
        CompressionXzCompressPlugin,
        CompressionXzDecompressPlugin,
        CompressionZstdCheckPlugin,
        CompressionZstdCompressPlugin,
        CompressionZstdDecompressPlugin,
        HardenedArchiveUntarPlugin,
        HardenedArchiveUnzipPlugin,
    )
    from automax.plugins.facts import (
        FactsOsPlugin,
        FactsPackagesPlugin,
        FactsServicesPlugin,
        OsArchCheckPlugin,
    )
    from automax.plugins.firewall import (
        FirewalldListPlugin,
        FirewalldReloadPlugin,
        FirewalldPortPlugin,
        FirewalldRichRulePlugin,
        FirewalldServicePlugin,
        FirewalldStatusPlugin,
        FirewalldZonePlugin,
        IptablesChainPlugin,
        IptablesListPlugin,
        IptablesPolicyPlugin,
        IptablesRestorePlugin,
        IptablesRulePlugin,
        IptablesSavePlugin,
        NftablesApplyPlugin,
        NftablesExportPlugin,
        NftablesListPlugin,
        NftablesValidatePlugin,
        UfwDisablePlugin,
        UfwEnablePlugin,
        UfwRulePlugin,
        UfwStatusPlugin,
    )
    from automax.plugins.fs_advanced import FsBindMountPlugin, FsInodeUsageAssertPlugin
    from automax.plugins.fs_chmod import FsChmodPlugin, FsModeCheckPlugin, FsModeGetPlugin
    from automax.plugins.fs_chown import FsChownPlugin, FsOwnerCheckPlugin, FsOwnerGetPlugin
    from automax.plugins.fs_copy import FsCopyPlugin
    from automax.plugins.fs_system import (
        FsAclAssertPlugin,
        FsAclGetPlugin,
        FsAclPlugin,
        FsAclRestorePlugin,
        FsAttrCheckPlugin,
        FsAttrGetPlugin,
        FsAttrPlugin,
        FsQuotaPlugin,
        StorageQuotaCheckPlugin,
        StorageQuotaFactsPlugin,
        StorageQuotaGetPlugin,
    )
    from automax.plugins.fs_extra import (
        FsFindPlugin,
        ExtendedFsLinePlugin,
        FsLineCheckPlugin,
        FsMovePlugin,
        FsReadPlugin,
        ExtendedFsReplacePlugin,
        FsStatPlugin,
        FsSymlinkCreatePlugin,
        FsSymlinkRemovePlugin,
        ExtendedFsTemplatePlugin,
        ExtendedFsWritePlugin,
    )
    from automax.plugins.cron import CronAbsentPlugin, CronEntryPlugin, CronFilePlugin, CronListPlugin, CronValidatePlugin
    from automax.plugins.db import (
        DatabaseMysqlCheckPlugin,
        DatabaseOracleCheckPlugin,
        DatabasePostgresCheckPlugin,
        DatabaseSqliteCheckPlugin,
        DbMysqlQueryPlugin,
        DbOracleQueryPlugin,
        DbPostgresQueryPlugin,
        DbSqliteQueryPlugin,
    )
    from automax.plugins.fs_typed import (
        FsDirCreatePlugin,
        FsDirCheckPlugin,
        FsDirRemovePlugin,
        FsDirWaitPlugin,
        FsFileCreatePlugin,
        FsFileCheckPlugin,
        FsFileRemovePlugin,
        FsFileWaitPlugin,
        FsSymlinkCheckPlugin,
        FsSymlinkGetPlugin,
        FsSymlinkWaitPlugin,
    )
    from automax.plugins.http import HttpAssertPlugin, HttpRequestPlugin, HttpWaitPlugin
    from automax.plugins.wait_assert import AssertDiskPlugin
    from automax.plugins.kernel import (
        KernelModuleLoadPlugin,
        KernelBootParamPlugin,
        KernelModulePersistPlugin,
        KernelModuleUnloadPlugin,
        SysctlGetPlugin,
        SysctlPersistPlugin,
        SysctlReloadPlugin,
        SysctlSetPlugin,
    )
    from automax.plugins.linux_ops import (
        ChronyServersPlugin,
        ChronyServersCheckPlugin,
        ChronyServersGetPlugin,
        ChronySourcesAssertPlugin,
        DownloadFilePlugin,
        EnvCheckPlugin,
        EnvFactsPlugin,
        EnvGetPlugin,
        EnvRemovePlugin,
        EnvSetPlugin,
        HostnameCheckPlugin,
        HostnameGetPlugin,
        HostnameSetPlugin,
        HostsEntryCheckPlugin,
        HostsEntryPlugin,
        HostsEntryRemovePlugin,
        HostsFactsPlugin,
        LimitsDropinPlugin,
        NetworkDnsFactsPlugin,
        PamLimitsPlugin,
        SwapAbsentPlugin,
        SwapPresentPlugin,
        SystemHostCheckPlugin,
        SystemHostPoweroffPlugin,
        SystemHostRebootPlugin,
        SystemHostWaitPlugin,
    )
    from automax.plugins.lvm import (
        LvmLvExtendPlugin,
        LvmLvPresentPlugin,
        LvmLvRemovePlugin,
        LvmLvScanPlugin,
        LvmPvPresentPlugin,
        LvmPvRemovePlugin,
        LvmPvScanPlugin,
        LvmSnapshotPlugin,
        LvmThinPoolPlugin,
        LvmVgPresentPlugin,
        LvmVgRemovePlugin,
        LvmVgScanPlugin,
    )
    from automax.plugins.network import (
        NetworkBondPlugin,
        NetworkBridgePlugin,
        NetworkDnsCheckPlugin,
        NetworkDnsConfigPlugin,
        NetworkInterfacePlugin,
        NetworkLinkCheckPlugin,
        NetworkLinkFactsPlugin,
        NetworkPortCheckPlugin,
        NetworkPortWaitPlugin,
        NetworkRouteAddPlugin,
        NetworkRouteCheckPlugin,
        NetworkRouteFactsPlugin,
        NetworkRouteRemovePlugin,
        NetworkVlanPlugin,
    )
    from automax.plugins.hardening import AuthselectProfilePlugin, ExtendedSshdConfigPlugin, LoginDefsCheckPlugin, LoginDefsGetPlugin, LoginDefsPlugin, PasswordPolicyPlugin
    from automax.plugins.orchestration import (
        ContainerComposeConfigCheckPlugin,
        ContainerComposeDownPlugin,
        ContainerComposeUpPlugin,
        ContainerExecPlugin,
        ContainerImageExistsPlugin,
        ContainerImagePullPlugin,
        ContainerImageRemovePlugin,
        ContainerInspectPlugin,
        ContainerLogsPlugin,
        ContainerRemovePlugin,
        ContainerRunPlugin,
        ContainerStopPlugin,
        HelmDependencyBuildPlugin,
        HelmLintPlugin,
        HelmRepoAddPlugin,
        HelmRepoUpdatePlugin,
        HelmRollbackPlugin,
        HelmStatusPlugin,
        HelmTemplatePlugin,
        HelmUninstallPlugin,
        HelmUpgradePlugin,
        KubernetesApplyPlugin,
        KubernetesContextCheckPlugin,
        KubernetesDeletePlugin,
        KubernetesLogsPlugin,
        KubernetesNamespaceExistsPlugin,
        KubernetesResourceGetPlugin,
        KubernetesRolloutStatusPlugin,
    )
    from automax.plugins.ops_completeness import (
        ApparmorComplainPlugin,
        ApparmorDisablePlugin,
        ApparmorEnforcePlugin,
        ApparmorParserValidatePlugin,
        ApparmorProfileAssertPlugin,
        AuditdBacklogAssertPlugin,
        AuditdRulesFactsPlugin,
        AuditdSearchPlugin,
        AuditdSyscallPlugin,
        AuditdWatchPlugin,
        BlockEmptyAssertPlugin,
        BlockSizeAssertPlugin,
        ChronyTrackingAssertPlugin,
        FirewalldForwardPortPlugin,
        FirewalldIcmpBlockPlugin,
        FirewalldMasqueradePlugin,
        FirewalldSourcePlugin,
        FstabAbsentPlugin,
        FstabAssertPlugin,
        GroupMemberAbsentPlugin,
        GroupMemberAddPlugin,
        GroupMemberCheckPlugin,
        GroupMembersPlugin,
        IptablesCounterCheckPlugin,
        IptablesDeletePlugin,
        IptablesRuleCheckPlugin,
        KernelBootParamAbsentPlugin,
        KernelBootParamCheckPlugin,
        KernelModuleBlacklistPlugin,
        KernelModuleStatusPlugin,
        NftablesRollbackFilePlugin,
        NftablesRulesetCheckPlugin,
        PamBackupPlugin,
        PamIncludeAssertPlugin,
        PamModuleAssertPlugin,
        PamOrderAssertPlugin,
        PamRestorePlugin,
        SudoAssertPlugin,
        SudoListPlugin,
        SysctlAssertPlugin,
        SysctlDropinPlugin,
        SysctlFactsPlugin,
        TimedatectlNtpCheckPlugin,
        TimedatectlNtpGetPlugin,
        TimedatectlNtpPlugin,
        TimedatectlStatusPlugin,
        TimedatectlTimezoneCheckPlugin,
        TimedatectlTimezoneGetPlugin,
        TimedatectlTimezonePlugin,
        UdevFactsPlugin,
        UdevTestPlugin,
        UdevValidatePlugin,
        UfwDeletePlugin,
        UfwResetPlugin,
        UserFactsPlugin,
        UserGroupsAssertPlugin,
        UserHomeAssertPlugin,
        UserShellAssertPlugin,
    )
    from automax.plugins.pam_ops import (
        PamAccessPlugin,
        PamAuthselectPlugin,
        PamFaillockPlugin,
        PamPwhistoryPlugin,
        PamServiceLinePlugin,
        PamStackFactsPlugin,
        PamSucceedIfPlugin,
        PamValidatePlugin,
    )
    from automax.plugins.pki import (
        PkiCaInstallPlugin,
        PkiCertExpiryAssertPlugin,
        PkiKeyPermissionsPlugin,
    )
    from automax.plugins.platform import PlatformFactsPlugin
    from automax.plugins.pkg_pinning import (
        PkgHoldCheckPlugin,
        PkgHoldListPlugin,
        PkgHoldPlugin,
        PkgRepoPriorityCheckPlugin,
        PkgRepoPriorityPlugin,
        PkgUnholdPlugin,
        PkgVersionPinPlugin,
    )
    from automax.plugins.mounts_extra import (
        FindmntAssertPlugin,
        FsResizePlugin,
        MountRemountPlugin,
    )
    from automax.plugins.logs import (
        JournalCollectPlugin,
        JournalGrepPlugin,
        LogExportPlugin,
        LogGrepPlugin,
    )
    from automax.plugins.mail import MailSendPlugin
    from automax.plugins.local_command import LocalCommandPlugin
    from automax.plugins.multipath import (
        MultipathAddPlugin,
        MultipathFlushPlugin,
        MultipathReloadPlugin,
        MultipathStatusPlugin,
    )
    from automax.plugins.udev import (
        UdevReloadPlugin,
        UdevRuleCheckPlugin,
        UdevRulePlugin,
        UdevRuleRemovePlugin,
        UdevSettlePlugin,
        UdevTriggerPlugin,
    )
    from automax.plugins.mounts import (
        FstabEntryPlugin,
        MountAbsentPlugin,
        MountPresentPlugin,
    )
    from automax.plugins.pkg import (
        PackageCheckPlugin,
        PackageCleanPlugin,
        PackageFilesPlugin,
        ExtendedPackageInstallPlugin,
        PackageOwnerPlugin,
        PackageQueryPlugin,
        ExtendedPackageRemovePlugin,
        PackageUpdateCachePlugin,
        ExtendedPackageUpgradePlugin,
        PackageVerifyPlugin,
        PackageVersionAssertPlugin,
    )
    from automax.plugins.pkg_repo import (
        PackageKeyAddPlugin,
        PackageKeyCheckPlugin,
        PackageKeyListPlugin,
        PackageKeyRemovePlugin,
        PackageRepoAddPlugin,
        PackageRepoCheckPlugin,
        PackageRepoListPlugin,
        PackageRepoRemovePlugin,
    )
    from automax.plugins.redaction import SecretRedactAssertPlugin, SecretScanOutputPlugin, SecretScanPreviewPlugin
    from automax.plugins.remote_command import RemoteCommandPlugin
    from automax.plugins.transfer import (
        TransferDownloadPlugin,
        ExtendedTransferRsyncPlugin,
        TransferUploadPlugin,
    )
    from automax.plugins.users_extra import (
        GroupCheckPlugin,
        ExtendedSshAuthorizedKeyPlugin,
        SshAuthorizedKeyCheckPlugin,
        SudoersDropinPlugin,
        UserCheckPlugin,
        UserLockPlugin,
        UserPasswordSetPlugin,
        UserPasswordExpirePlugin,
        UserUnlockPlugin,
    )
    from automax.plugins.user_group_process import (
        GroupCreatePlugin,
        GroupRemovePlugin,
        ProcessCheckPlugin,
        ProcessAssertCountPlugin,
        ProcessKillPlugin,
        ProcessSignalPlugin,
        ProcessWaitPlugin,
        UserCreatePlugin,
        UserModifyPlugin,
        UserRemovePlugin,
    )
    from automax.plugins.security_modules import (
        ApparmorProfilePlugin,
        ApparmorReloadPlugin,
        ApparmorStatusPlugin,
        SelinuxBooleanPlugin,
        SelinuxContextPlugin,
        SelinuxFcontextPlugin,
        SelinuxModePlugin,
        SelinuxPortPlugin,
        SelinuxRestoreconPlugin,
    )
    from automax.plugins.sudo_ops import SudoRulePlugin, SudoValidatePlugin
    from automax.plugins.ssh_ops import (
        SshAuthorizedKeyAbsentPlugin,
        SshConfigPlugin,
        SshFingerprintPlugin,
        SshHostKeygenPlugin,
        ExtendedSshKeygenPlugin,
        SshKnownHostsPlugin,
        SshPublicKeyPlugin,
        SshdValidatePlugin,
    )
    from automax.plugins.systemd_resources import SystemdSysusersPlugin, SystemdTimerPlugin, SystemdTmpfilesPlugin, SystemdUnitPlugin
    from automax.plugins.storage_readback import (
        BlkidAssertPlugin,
        FstabValidatePlugin,
        LvmFactsPlugin,
        LvmLvAssertPlugin,
        MountFactsPlugin,
        StorageFsFactsPlugin,
        StorageSwapCheckPlugin,
        SwapStatusPlugin,
    )
    from automax.plugins.systemctl import (
        SystemctlDaemonReloadPlugin,
        SystemctlDisablePlugin,
        SystemctlEnablePlugin,
        SystemctlIsActivePlugin,
        SystemctlIsEnabledPlugin,
        SystemctlMaskPlugin,
        SystemctlReloadPlugin,
        SystemctlRestartPlugin,
        SystemctlStartPlugin,
        SystemctlStatusPlugin,
        SystemctlStopPlugin,
        SystemctlUnmaskPlugin,
    )

    registry = PluginRegistry()
    for plugin in (
        LocalCommandPlugin(),
        AlternativesGetPlugin(),
        AlternativesListPlugin(),
        AlternativesCheckPlugin(),
        CapabilityAssertPlugin(),
        PluginRequirementsPlugin(),
        AlternativesSetPlugin(),
        BackupFilePlugin(),
        BackupDirectoryPlugin(),
        BackupRestorePlugin(),
        BackupVerifyPlugin(),
        BackupListPlugin(),
        BackupManifestPlugin(),
        BackupPrunePlugin(),
        BackupRotatePlugin(),
        BackupRestorePreviewPlugin(),
        BackupRestoreVerifyPlugin(),
        CertExpiryReportPlugin(),
        CertGenerateCsrPlugin(),
        CertInstallKeypairPlugin(),
        CertSelfSignedPlugin(),
        CertVerifyChainPlugin(),
        CertFingerprintPlugin(),
        CertMatchesKeyPlugin(),
        CertSanAssertPlugin(),
        CertSubjectAssertPlugin(),
        CertIssuerAssertPlugin(),
        CertInstallCaBundlePlugin(),
        HttpRequestPlugin(),
        HttpAssertPlugin(),
        HttpWaitPlugin(),
        DatabaseSqliteCheckPlugin(),
        DatabasePostgresCheckPlugin(),
        DatabaseMysqlCheckPlugin(),
        DatabaseOracleCheckPlugin(),
        DbSqliteQueryPlugin(),
        DbPostgresQueryPlugin(),
        DbMysqlQueryPlugin(),
        DbOracleQueryPlugin(),
        CronEntryPlugin(),
        CronFilePlugin(),
        CronListPlugin(),
        CronAbsentPlugin(),
        CronValidatePlugin(),
        FactsOsPlugin(),
        OsArchCheckPlugin(),
        FactsPackagesPlugin(),
        FactsServicesPlugin(),
        PlatformFactsPlugin(),
        AssertDiskPlugin(),
        FirewalldPortPlugin(),
        FirewalldServicePlugin(),
        FirewalldSourcePlugin(),
        FirewalldIcmpBlockPlugin(),
        FirewalldMasqueradePlugin(),
        FirewalldForwardPortPlugin(),
        FirewalldRichRulePlugin(),
        FirewalldReloadPlugin(),
        FirewalldStatusPlugin(),
        FirewalldListPlugin(),
        FirewalldZonePlugin(),
        IptablesRestorePlugin(),
        IptablesRulePlugin(),
        IptablesSavePlugin(),
        IptablesDeletePlugin(),
        IptablesRuleCheckPlugin(),
        IptablesCounterCheckPlugin(),
        IptablesListPlugin(),
        IptablesPolicyPlugin(),
        IptablesChainPlugin(),
        UfwRulePlugin(),
        UfwStatusPlugin(),
        UfwEnablePlugin(),
        UfwDisablePlugin(),
        UfwDeletePlugin(),
        UfwResetPlugin(),
        NftablesValidatePlugin(),
        NftablesApplyPlugin(),
        NftablesListPlugin(),
        NftablesExportPlugin(),
        NftablesRulesetCheckPlugin(),
        NftablesRollbackFilePlugin(),
        SysctlGetPlugin(),
        SysctlSetPlugin(),
        SysctlPersistPlugin(),
        SysctlReloadPlugin(),
        SysctlAssertPlugin(),
        SysctlFactsPlugin(),
        SysctlDropinPlugin(),
        KernelBootParamPlugin(),
        KernelBootParamAbsentPlugin(),
        KernelBootParamCheckPlugin(),
        KernelModuleLoadPlugin(),
        KernelModuleStatusPlugin(),
        KernelModuleBlacklistPlugin(),
        KernelModuleUnloadPlugin(),
        KernelModulePersistPlugin(),
        MountPresentPlugin(),
        MountAbsentPlugin(),
        FstabEntryPlugin(),
        FstabAbsentPlugin(),
        FstabAssertPlugin(),
        SelinuxModePlugin(),
        SelinuxBooleanPlugin(),
        SelinuxContextPlugin(),
        SelinuxFcontextPlugin(),
        SelinuxPortPlugin(),
        SelinuxRestoreconPlugin(),
        ApparmorStatusPlugin(),
        ApparmorProfilePlugin(),
        ApparmorReloadPlugin(),
        ApparmorEnforcePlugin(),
        ApparmorComplainPlugin(),
        ApparmorDisablePlugin(),
        ApparmorProfileAssertPlugin(),
        ApparmorParserValidatePlugin(),
        AuditdRulePlugin(),
        AuditdStatusPlugin(),
        AuditdReloadPlugin(),
        AuditdRulesFactsPlugin(),
        AuditdWatchPlugin(),
        AuditdSyscallPlugin(),
        AuditdSearchPlugin(),
        AuditdBacklogAssertPlugin(),
        SecretRedactAssertPlugin(),
        SecretScanOutputPlugin(),
        SecretScanPreviewPlugin(),
        RemoteCommandPlugin(),
        ExtendedPackageInstallPlugin(),
        ExtendedPackageRemovePlugin(),
        PackageUpdateCachePlugin(),
        ExtendedPackageUpgradePlugin(),
        PackageQueryPlugin(),
        PackageCheckPlugin(),
        PackageVersionAssertPlugin(),
        PackageOwnerPlugin(),
        PackageFilesPlugin(),
        PackageVerifyPlugin(),
        PackageCleanPlugin(),
        PackageKeyAddPlugin(),
        PackageKeyListPlugin(),
        PackageKeyCheckPlugin(),
        PackageKeyRemovePlugin(),
        PackageRepoAddPlugin(),
        PackageRepoListPlugin(),
        PackageRepoCheckPlugin(),
        PackageRepoRemovePlugin(),
        UserCreatePlugin(),
        UserModifyPlugin(),
        UserFactsPlugin(),
        UserShellAssertPlugin(),
        UserHomeAssertPlugin(),
        UserGroupsAssertPlugin(),
        UserRemovePlugin(),
        UserCheckPlugin(),
        UserLockPlugin(),
        UserUnlockPlugin(),
        UserPasswordSetPlugin(),
        UserPasswordExpirePlugin(),
        GroupCreatePlugin(),
        GroupRemovePlugin(),
        GroupCheckPlugin(),
        GroupMembersPlugin(),
        GroupMemberAddPlugin(),
        GroupMemberCheckPlugin(),
        GroupMemberAbsentPlugin(),
        ExtendedSshAuthorizedKeyPlugin(),
        SshAuthorizedKeyCheckPlugin(),
        ExtendedSshdConfigPlugin(),
        LoginDefsPlugin(),
        LoginDefsGetPlugin(),
        LoginDefsCheckPlugin(),
        PasswordPolicyPlugin(),
        AuthselectProfilePlugin(),
        SshConfigPlugin(),
        ExtendedSshKeygenPlugin(),
        SshKnownHostsPlugin(),
        SshFingerprintPlugin(),
        SshPublicKeyPlugin(),
        SshHostKeygenPlugin(),
        SshAuthorizedKeyAbsentPlugin(),
        SshdValidatePlugin(),
        SudoersDropinPlugin(),
        SudoRulePlugin(),
        SudoValidatePlugin(),
        SudoListPlugin(),
        SudoAssertPlugin(),
        ProcessCheckPlugin(),
        ProcessAssertCountPlugin(),
        ProcessKillPlugin(),
        ProcessSignalPlugin(),
        ProcessWaitPlugin(),
        TransferUploadPlugin(),
        TransferDownloadPlugin(),
        ExtendedTransferRsyncPlugin(),
        FsDirCreatePlugin(),
        FsDirRemovePlugin(),
        FsDirCheckPlugin(),
        FsDirWaitPlugin(),
        FsFileCreatePlugin(),
        FsFileRemovePlugin(),
        FsFileCheckPlugin(),
        FsFileWaitPlugin(),
        FsCopyPlugin(),
        FsStatPlugin(),
        FsReadPlugin(),
        ExtendedFsWritePlugin(),
        ExtendedFsTemplatePlugin(),
        ExtendedFsLinePlugin(),
        FsLineCheckPlugin(),
        ExtendedFsReplacePlugin(),
        FsMovePlugin(),
        FsSymlinkCreatePlugin(),
        FsSymlinkRemovePlugin(),
        FsSymlinkCheckPlugin(),
        FsSymlinkGetPlugin(),
        FsSymlinkWaitPlugin(),
        FsFindPlugin(),
        FsOwnerCheckPlugin(),
        FsOwnerGetPlugin(),
        FsChownPlugin(),
        FsModeCheckPlugin(),
        FsModeGetPlugin(),
        FsChmodPlugin(),
        FsAclPlugin(),
        FsAclGetPlugin(),
        FsAclAssertPlugin(),
        FsAclRestorePlugin(),
        FsBindMountPlugin(),
        FsInodeUsageAssertPlugin(),
        FsAttrPlugin(),
        FsAttrGetPlugin(),
        FsAttrCheckPlugin(),
        FsQuotaPlugin(),
        StorageQuotaGetPlugin(),
        StorageQuotaCheckPlugin(),
        StorageQuotaFactsPlugin(),
        BlockFactsPlugin(),
        BlockIdentityPlugin(),
        BlockRescanPlugin(),
        BlockSizeAssertPlugin(),
        BlockEmptyAssertPlugin(),
        BlockPartitionRescanPlugin(),
        BlockPartitionPlugin(),
        BlockWipeSignaturesPlugin(),
        BlockMkfsPlugin(),
        UdevRulePlugin(),
        UdevRuleRemovePlugin(),
        UdevRuleCheckPlugin(),
        UdevReloadPlugin(),
        UdevTriggerPlugin(),
        UdevSettlePlugin(),
        UdevValidatePlugin(),
        UdevTestPlugin(),
        UdevFactsPlugin(),
        MultipathStatusPlugin(),
        MultipathReloadPlugin(),
        MultipathAddPlugin(),
        MultipathFlushPlugin(),
        SwapPresentPlugin(),
        SwapAbsentPlugin(),
        LimitsDropinPlugin(),
        PamLimitsPlugin(),
        PamAccessPlugin(),
        PamIncludeAssertPlugin(),
        PamModuleAssertPlugin(),
        PamOrderAssertPlugin(),
        PamBackupPlugin(),
        PamRestorePlugin(),
        PamFaillockPlugin(),
        PamPwhistoryPlugin(),
        PamSucceedIfPlugin(),
        PamServiceLinePlugin(),
        PamValidatePlugin(),
        PamStackFactsPlugin(),
        PamAuthselectPlugin(),
        HostsEntryPlugin(),
        HostsEntryRemovePlugin(),
        HostsEntryCheckPlugin(),
        HostsFactsPlugin(),
        HostnameSetPlugin(),
        HostnameGetPlugin(),
        HostnameCheckPlugin(),
        NetworkDnsFactsPlugin(),
        ChronyServersPlugin(),
        ChronyServersGetPlugin(),
        ChronyServersCheckPlugin(),
        ChronySourcesAssertPlugin(),
        ChronyTrackingAssertPlugin(),
        TimedatectlStatusPlugin(),
        TimedatectlTimezonePlugin(),
        TimedatectlTimezoneGetPlugin(),
        TimedatectlTimezoneCheckPlugin(),
        TimedatectlNtpPlugin(),
        TimedatectlNtpGetPlugin(),
        TimedatectlNtpCheckPlugin(),
        EnvSetPlugin(),
        EnvGetPlugin(),
        EnvCheckPlugin(),
        EnvFactsPlugin(),
        EnvRemovePlugin(),
        SystemHostRebootPlugin(),
        SystemHostPoweroffPlugin(),
        SystemHostCheckPlugin(),
        SystemHostWaitPlugin(),
        DownloadFilePlugin(),
        LvmPvPresentPlugin(),
        LvmVgPresentPlugin(),
        LvmLvPresentPlugin(),
        LvmFactsPlugin(),
        LvmLvAssertPlugin(),
        LvmLvExtendPlugin(),
        LvmLvScanPlugin(),
        LvmSnapshotPlugin(),
        LvmThinPoolPlugin(),
        LvmLvRemovePlugin(),
        LvmVgRemovePlugin(),
        LvmVgScanPlugin(),
        LvmPvRemovePlugin(),
        LvmPvScanPlugin(),
        NetworkInterfacePlugin(),
        NetworkRouteAddPlugin(),
        NetworkRouteRemovePlugin(),
        NetworkRouteFactsPlugin(),
        NetworkBondPlugin(),
        NetworkVlanPlugin(),
        NetworkDnsConfigPlugin(),
        NetworkBridgePlugin(),
        NetworkLinkCheckPlugin(),
        NetworkLinkFactsPlugin(),
        NetworkRouteCheckPlugin(),
        NetworkDnsCheckPlugin(),
        NetworkPortCheckPlugin(),
        NetworkPortWaitPlugin(),
        PkiCaInstallPlugin(),
        PkiKeyPermissionsPlugin(),
        PkiCertExpiryAssertPlugin(),
        PkgHoldPlugin(),
        PkgUnholdPlugin(),
        PkgHoldListPlugin(),
        PkgHoldCheckPlugin(),
        PkgVersionPinPlugin(),
        PkgRepoPriorityPlugin(),
        PkgRepoPriorityCheckPlugin(),
        MountRemountPlugin(),
        MountFactsPlugin(),
        FstabValidatePlugin(),
        SwapStatusPlugin(),
        StorageSwapCheckPlugin(),
        BlkidAssertPlugin(),
        StorageFsFactsPlugin(),
        FsResizePlugin(),
        FindmntAssertPlugin(),
        LogGrepPlugin(),
        JournalCollectPlugin(),
        JournalGrepPlugin(),
        LogExportPlugin(),
        MailSendPlugin(),
        ArchiveTarPlugin(),
        HardenedArchiveUntarPlugin(),
        ArchiveTarListPlugin(),
        ArchiveTarCheckPlugin(),
        ArchiveZipPlugin(),
        HardenedArchiveUnzipPlugin(),
        ArchiveZipListPlugin(),
        ArchiveZipCheckPlugin(),
        CompressionGzipCompressPlugin(),
        CompressionGzipDecompressPlugin(),
        CompressionGzipCheckPlugin(),
        CompressionBzip2CompressPlugin(),
        CompressionBzip2DecompressPlugin(),
        CompressionBzip2CheckPlugin(),
        CompressionXzCompressPlugin(),
        CompressionXzDecompressPlugin(),
        CompressionXzCheckPlugin(),
        CompressionZstdCompressPlugin(),
        CompressionZstdDecompressPlugin(),
        CompressionZstdCheckPlugin(),
        ContainerImagePullPlugin(),
        ContainerImageExistsPlugin(),
        ContainerImageRemovePlugin(),
        ContainerRunPlugin(),
        ContainerExecPlugin(),
        ContainerStopPlugin(),
        ContainerRemovePlugin(),
        ContainerInspectPlugin(),
        ContainerLogsPlugin(),
        ContainerComposeUpPlugin(),
        ContainerComposeDownPlugin(),
        ContainerComposeConfigCheckPlugin(),
        KubernetesContextCheckPlugin(),
        KubernetesNamespaceExistsPlugin(),
        KubernetesApplyPlugin(),
        KubernetesDeletePlugin(),
        KubernetesRolloutStatusPlugin(),
        KubernetesResourceGetPlugin(),
        KubernetesLogsPlugin(),
        HelmRepoAddPlugin(),
        HelmRepoUpdatePlugin(),
        HelmDependencyBuildPlugin(),
        HelmTemplatePlugin(),
        HelmLintPlugin(),
        HelmUpgradePlugin(),
        HelmRollbackPlugin(),
        HelmUninstallPlugin(),
        HelmStatusPlugin(),
        SystemctlStartPlugin(),
        SystemctlStopPlugin(),
        SystemctlRestartPlugin(),
        SystemctlReloadPlugin(),
        SystemctlEnablePlugin(),
        SystemctlDisablePlugin(),
        SystemctlStatusPlugin(),
        SystemctlIsActivePlugin(),
        SystemctlIsEnabledPlugin(),
        SystemctlMaskPlugin(),
        SystemctlUnmaskPlugin(),
        SystemctlDaemonReloadPlugin(),
        SystemdUnitPlugin(),
        SystemdTimerPlugin(),
        SystemdTmpfilesPlugin(),
        SystemdSysusersPlugin(),
    ):
        registry.register(apply_builtin_metadata(plugin))
    registry.load_from_paths(extra_plugin_paths)
    return registry