Skip to content

promote

napt.promote

Deployment promotion for NAPT.

Implements ring-based promotion of published apps: napt promote plan computes which releases should enter or advance through the configured deployment rings and writes one reviewable plan file per app; napt promote apply executes each app's plan against Intune independently.

The core invariant: each ring holds at most one release of an app's Update entry: the newest release that has reached it. Promotion advances the published release into the next ring once it has held its current ring for the ring's promote_after_days.

Assignment drift (differences between what deployment state says should be assigned and what Intune actually has) is detected on every apply and on plan --check-drift, and is always reported, never corrected.

Publications whose deployment state writeback was lost (e.g. a failed CI push after a successful upload) are recovered from tenant evidence on every apply and on plan --reconcile.

Modules:

Name Description
planner

Plan computation and plan file writing.

applier

Plan execution against Intune.

preflight

Group resolution validation before assignment.

drift

Assignment drift detection.

reconcile

Lost publication writeback recovery.

napt.promote.planner

Promotion planning for NAPT deployment rings.

Computes promotion actions as a pure function of (deployment state, configuration, clock): no Graph calls, no side effects beyond the plan file. Re-running plan against unchanged inputs produces byte-identical output, so committed plan files diff cleanly and CI can use the plan file's change status to decide whether to open a review.

Two action types are planned per app, one per Intune entry:

  • assign: Point new installs at the published release: assign its install entry to the configured deployment.install groups, displacing the previous release's install assignment.
  • promote: Move the published release one ring forward: assign its update entry to the target ring's groups. from_ring: null marks a first rollout (the release enters the first ring); otherwise the release has held from_ring for at least that ring's promote_after_days.

Every action carries a plain-English summary sentence plus the reviewer context behind it (the entry it touches, the version it displaces, and bake timestamps), so a committed plan file reads on its own in review.

A ring without promote_after_days never advances automatically: releases hold it until the configuration changes (the natural terminal ring, or a deliberate manual gate).

Plans are written per app (default state/plans/<app_id>.json), and an app's plan file exists exactly when that app has eligible actions; a stale plan file is removed when a plan run finds none for its app. Exit codes follow NAPT's uniform contract (0 success, 1 error, 2 usage error); CI detects pending work from the plan files' git status, not from exit codes.

plans_dir_for

plans_dir_for(state_dir: Path) -> Path

Returns the plans directory for a state directory.

Parameters:

Name Type Description Default
state_dir Path

The configured state directory (directories.state).

required

Returns:

Type Description
Path

Path to the plans directory (<state_dir>/plans).

Source code in napt/promote/planner.py
def plans_dir_for(state_dir: Path) -> Path:
    """Returns the plans directory for a state directory.

    Args:
        state_dir: The configured state directory (``directories.state``).

    Returns:
        Path to the plans directory (``<state_dir>/plans``).

    """
    return state_dir / "plans"

plan_path_for

plan_path_for(state_dir: Path, app_id: str) -> Path

Returns an app's plan file path.

Parameters:

Name Type Description Default
state_dir Path

The configured state directory (directories.state).

required
app_id str

Recipe identifier the plan belongs to.

required

Returns:

Type Description
Path

Path to the app's plan file (<state_dir>/plans/<app_id>.json).

Source code in napt/promote/planner.py
def plan_path_for(state_dir: Path, app_id: str) -> Path:
    """Returns an app's plan file path.

    Args:
        state_dir: The configured state directory (``directories.state``).
        app_id: Recipe identifier the plan belongs to.

    Returns:
        Path to the app's plan file (``<state_dir>/plans/<app_id>.json``).

    """
    return plans_dir_for(state_dir) / f"{app_id}.json"

load_recipe_configs

load_recipe_configs(recipes: Path) -> dict[str, dict[str, Any]]

Loads effective configurations for a recipe file or directory.

Parameters:

Name Type Description Default
recipes Path

A recipe YAML file, or a directory scanned recursively.

required

Returns:

Type Description
dict[str, dict[str, Any]]

Effective configurations keyed by recipe id, in path order.

Raises:

Type Description
ConfigError

If the path does not exist, contains no recipes, a recipe is invalid, or two recipe files resolve to the same id.

Source code in napt/promote/planner.py
def load_recipe_configs(recipes: Path) -> dict[str, dict[str, Any]]:
    """Loads effective configurations for a recipe file or directory.

    Args:
        recipes: A recipe YAML file, or a directory scanned recursively.

    Returns:
        Effective configurations keyed by recipe id, in path order.

    Raises:
        ConfigError: If the path does not exist, contains no recipes, a
            recipe is invalid, or two recipe files resolve to the same
            id.

    """
    configs: dict[str, dict[str, Any]] = {}
    sources: dict[str, Path] = {}
    for path in collect_recipe_paths(recipes):
        config = load_effective_config(path)
        app_id: str = config["id"]
        duplicate = register_recipe_id(sources, app_id, path)
        if duplicate is not None:
            raise ConfigError(duplicate)
        configs[app_id] = config
    return configs

plan_promotions

plan_promotions(
    configs: dict[str, dict[str, Any]],
    states: dict[str, dict[str, Any]],
    now: datetime | None = None,
) -> list[dict[str, Any]]

Computes promotion actions for the apps in a run.

Evaluates each app's ring eligibility against its deployment state and the clock. Read-only: neither Intune nor the states are modified.

Parameters:

Name Type Description Default
configs dict[str, dict[str, Any]]

Effective configurations keyed by recipe id, from load_recipe_configs.

required
states dict[str, dict[str, Any]]

Each app's deployment state keyed by recipe id, from load_deployment_states.

required
now datetime | None

Evaluation clock. Defaults to the current UTC time; tests pass a fixed value for determinism.

None

Returns:

Type Description
list[dict[str, Any]]

Action dicts sorted by app id and action type.

Raises:

Type Description
StateError

On an invalid ring timestamp.

Source code in napt/promote/planner.py
def plan_promotions(
    configs: dict[str, dict[str, Any]],
    states: dict[str, dict[str, Any]],
    now: datetime | None = None,
) -> list[dict[str, Any]]:
    """Computes promotion actions for the apps in a run.

    Evaluates each app's ring eligibility against its deployment state
    and the clock. Read-only: neither Intune nor the states are modified.

    Args:
        configs: Effective configurations keyed by recipe id, from
            [load_recipe_configs][napt.promote.planner.load_recipe_configs].
        states: Each app's deployment state keyed by recipe id, from
            [load_deployment_states][napt.state.deployment.load_deployment_states].
        now: Evaluation clock. Defaults to the current UTC time; tests
            pass a fixed value for determinism.

    Returns:
        Action dicts sorted by app id and action type.

    Raises:
        StateError: On an invalid ring timestamp.

    """
    logger = get_global_logger()
    if now is None:
        now = datetime.now(UTC)

    actions: list[dict[str, Any]] = []
    for config in configs.values():
        app_actions = _plan_app_actions(config, states[config["id"]], now)
        if app_actions:
            logger.verbose(
                "PROMOTE",
                f"{config['id']}: {len(app_actions)} action(s) planned",
            )
        actions.extend(app_actions)

    actions.sort(key=lambda a: (a["app_id"], _ACTION_ORDER[a["type"]]))
    return actions

write_plan_files

write_plan_files(
    actions: list[dict[str, Any]], state_dir: Path, app_ids: Iterable[str]
) -> list[Path]

Writes one plan file per app, removing stale files for apps without work.

An app's plan file exists exactly when that app has planned actions, so each file's git status is the per-app signal that a promotion review is needed. Only apps covered by this run (app_ids) are written or cleaned up; plan files for apps outside the run are left untouched, so planning a single recipe never clobbers the rest of the fleet's plans.

The app's id and display name are written once at the file's top level rather than repeated per action; promote apply re-injects them when it loads the file. Output is deterministic: a fixed key order (reading order, summary first, not alphabetical), fixed indentation, no clock-derived values.

Parameters:

Name Type Description Default
actions list[dict[str, Any]]

Planned actions from plan_promotions.

required
state_dir Path

The configured state directory; plan files live in its plans/ subdirectory.

required
app_ids Iterable[str]

Recipe ids covered by this plan run.

required

Returns:

Type Description
list[Path]

Paths of the plan files written, sorted by app id.

Source code in napt/promote/planner.py
def write_plan_files(
    actions: list[dict[str, Any]],
    state_dir: Path,
    app_ids: Iterable[str],
) -> list[Path]:
    """Writes one plan file per app, removing stale files for apps without work.

    An app's plan file exists exactly when that app has planned actions,
    so each file's git status is the per-app signal that a promotion
    review is needed. Only apps covered by this run (``app_ids``) are
    written or cleaned up; plan files for apps outside the run are left
    untouched, so planning a single recipe never clobbers the rest of
    the fleet's plans.

    The app's id and display name are written once at the file's top
    level rather than repeated per action; promote apply re-injects them
    when it loads the file. Output is deterministic: a fixed key order
    (reading order, ``summary`` first, not alphabetical), fixed
    indentation, no clock-derived values.

    Args:
        actions: Planned actions from plan_promotions.
        state_dir: The configured state directory; plan files live in
            its ``plans/`` subdirectory.
        app_ids: Recipe ids covered by this plan run.

    Returns:
        Paths of the plan files written, sorted by app id.

    """
    by_app: dict[str, list[dict[str, Any]]] = {}
    for action in actions:
        by_app.setdefault(action["app_id"], []).append(action)

    written: list[Path] = []
    for app_id in sorted(set(app_ids) | set(by_app)):
        plan_path = plan_path_for(state_dir, app_id)
        app_actions = by_app.get(app_id)
        if not app_actions:
            if plan_path.exists():
                plan_path.unlink()
            continue
        plan = {
            "schemaVersion": PLAN_SCHEMA_VERSION,
            "app_id": app_id,
            "name": app_actions[0]["name"],
            "actions": [
                {
                    key: value
                    for key, value in action.items()
                    if key not in ("app_id", "name")
                }
                for action in app_actions
            ],
        }
        # Trailing newline for git.
        write_text_atomic(plan_path, json.dumps(plan, indent=2) + "\n")
        written.append(plan_path)
    return written

napt.promote.applier

Promotion apply for NAPT deployment rings.

Executes promotion plans against Intune: assigns install entries, promotes releases through rings, displaces the older releases they replace, and retires them per the retention policy.

Plans are applied per app: each state/plans/<app_id>.json file is an independent unit of work, preflighted, executed, and consumed on its own. Only the plan files of the recipes given to the run are loaded, so applying one recipe leaves every other app's reviewed plan in place. A failure inside one app's plan (an unresolvable group, a Graph error, a state file that cannot be written) records the failure, keeps that plan file for retry, and moves on to the next; one app's problem never strands the rest of the fleet's promotions.

Every action is validated against current deployment state before executing (validate-then-act): stale actions, where the published release changed since the plan was written or the action already applied, are skipped with a warning instead of failing, so re-running apply after a partial failure is safe. Deployment state is saved after each applied action, and ring entered_at timestamps are written here and only here.

Displaced releases are found through their provenance stamps (the tenant is listed once per run), not through deployment state, which only records the current release's app IDs. A displaced release that no longer holds any ring moves to the retained list; releases beyond deployment.retain_versions have their Intune apps deleted and leave the run's tenant listing, so the drift check that follows does not report them.

Assignments NAPT does not manage are preserved: assignment sets are read, modified, and written back, so admin-made assignments and non-group targets survive every apply.

ApplyResult dataclass

Result from applying promotion plans against Intune.

Attributes:

Name Type Description
applied list[dict[str, Any]]

The actions that were executed, as planned.

skipped list[dict[str, Any]]

Entries of action and reason for actions that were stale or already applied.

failed list[dict[str, Any]]

Entries of app_id and error for apps whose plan could not be applied; their plan files are kept for retry.

drift list[dict[str, Any]]

Assignment drift findings, reported and never corrected.

recovered list[dict[str, Any]]

Publications whose lost state writeback was recovered before applying.

Source code in napt/promote/applier.py
@dataclass(frozen=True)
class ApplyResult:
    """Result from applying promotion plans against Intune.

    Attributes:
        applied: The actions that were executed, as planned.
        skipped: Entries of ``action`` and ``reason`` for actions that were
            stale or already applied.
        failed: Entries of ``app_id`` and ``error`` for apps whose plan
            could not be applied; their plan files are kept for retry.
        drift: Assignment drift findings, reported and never corrected.
        recovered: Publications whose lost state writeback was recovered
            before applying.
    """

    applied: list[dict[str, Any]] = field(default_factory=list)
    skipped: list[dict[str, Any]] = field(default_factory=list)
    failed: list[dict[str, Any]] = field(default_factory=list)
    drift: list[dict[str, Any]] = field(default_factory=list)
    recovered: list[dict[str, Any]] = field(default_factory=list)

load_plan_file

load_plan_file(plan_path: Path) -> list[dict[str, Any]]

Loads planned actions from a per-app plan file.

The file records its app id and display name once at the top level; both are re-injected into every returned action, so in-memory actions look the same as the planner's output. The filename is the app's identity, as for deployment state: <app_id>.json must declare that same app id.

Parameters:

Name Type Description Default
plan_path Path

Path to the plan file.

required

Returns:

Type Description
list[dict[str, Any]]

The planned action dicts.

Raises:

Type Description
StateError

If the plan file cannot be read, contains invalid JSON, lacks an actions list or app id, declares an app id other than its filename, its schemaVersion is missing or unsupported, an action is not shaped like the planner writes it, or an action references a different app than the one the file declares.

Source code in napt/promote/applier.py
def load_plan_file(plan_path: Path) -> list[dict[str, Any]]:
    """Loads planned actions from a per-app plan file.

    The file records its app id and display name once at the top level;
    both are re-injected into every returned action, so in-memory
    actions look the same as the planner's output. The filename is the
    app's identity, as for deployment state: ``<app_id>.json`` must
    declare that same app id.

    Args:
        plan_path: Path to the plan file.

    Returns:
        The planned action dicts.

    Raises:
        StateError: If the plan file cannot be read, contains invalid
            JSON, lacks an actions list or app id, declares an app id
            other than its filename, its schemaVersion is missing or
            unsupported, an action is not shaped like the planner writes
            it, or an action references a different app than the one
            the file declares.

    """
    try:
        text = plan_path.read_text(encoding="utf-8")
    except OSError as err:
        raise StateError(f"Cannot read plan file {plan_path}: {err}") from err
    try:
        data = json.loads(text)
        actions = data["actions"]
        declared = data["app_id"]
    except (json.JSONDecodeError, KeyError, TypeError) as err:
        raise StateError(
            f"Corrupted plan file: {plan_path}. "
            "Re-run 'napt promote plan' to regenerate it."
        ) from err
    if not isinstance(actions, list):
        raise _corrupted(plan_path, "'actions' is not a list")
    if not isinstance(declared, str):
        raise _corrupted(plan_path, "'app_id' is not a string")
    if declared != plan_path.stem:
        raise StateError(
            f"Plan file {plan_path} declares app_id {declared!r}, but its "
            f"filename says {plan_path.stem!r}. The file was likely copied "
            "or renamed. Fix whichever is wrong before continuing."
        )

    found = data.get("schemaVersion")
    if found != PLAN_SCHEMA_VERSION:
        raise StateError(
            f"Unsupported plan schema version {found!r} in {plan_path} "
            f"(this NAPT release supports version {PLAN_SCHEMA_VERSION}). "
            "Re-run 'napt promote plan' to regenerate it."
        )

    for index, action in enumerate(actions, start=1):
        _check_action(action, index, plan_path)

    # A plan file is one app's unit of work: apply's failure isolation
    # and consume-after-success semantics attribute the whole file to a
    # single app, so a file whose actions reference another app (a hand
    # edit) cannot be applied faithfully.
    foreign = {
        action.get("app_id")
        for action in actions
        if action.get("app_id") not in (None, declared)
    }
    if foreign:
        raise StateError(
            f"Plan file {plan_path} mixes actions for more than one app "
            f"(declared app_id {declared!r}, actions reference "
            f"{sorted(str(a) for a in foreign)}). Plan files are "
            "per-app. Re-run 'napt promote plan' to regenerate them."
        )

    name = data.get("name")
    for action in actions:
        action["app_id"] = declared
        if name is not None:
            action.setdefault("name", name)
    return actions

apply_plan

apply_plan(
    configs: dict[str, dict[str, Any]],
    state_dir: Path,
    plan_file: Path | None = None,
    now: datetime | None = None,
    report_unknown_apps: bool = True,
) -> ApplyResult

Executes promotion plans against Intune.

Consumes the given recipes' plan files from <state_dir>/plans/, removing each after its app applies fully. A plan file written by napt promote plan is the only thing apply executes: a recipe without one has nothing to apply, and plan files for apps outside the run are left untouched, so applying one recipe never consumes another app's reviewed plan. Each app's plan is an independent unit: its groups are preflighted before any of its actions execute, so an unresolvable group fails that app with zero mutations, and a failure while loading, preflighting, or applying one app records the failure, keeps its plan file for retry, and continues with the remaining apps. A dead group referenced only by stale or already-applied actions never blocks an app. Deployment state is saved after each applied action, so a failed run resumes safely: already-applied actions validate as no-ops.

Assignment drift is checked on every run, including runs with nothing to apply (which therefore still authenticate), and reported in the summary, never corrected. Publications whose state writeback was lost are recovered first (see reconcile_publications); a recovered release is picked up by the next plan run, since the plan files being applied were computed before the recovery.

Parameters:

Name Type Description Default
configs dict[str, dict[str, Any]]

Effective configurations keyed by recipe id, from load_recipe_configs.

required
state_dir Path

State directory holding deployment/ and plans/.

required
plan_file Path | None

Explicit path to a single plan file to apply; its app must be one of the recipes. When omitted, the recipes' plan files in the default plans directory are applied.

None
now datetime | None

Evaluation clock for ring timestamps. Defaults to the current UTC time.

None
report_unknown_apps bool

Whether the drift check reports a stamped app whose recipe id is not in configs. True when the configs cover the whole fleet; a run over one recipe passes False.

True

Returns:

Type Description
ApplyResult

The applied and skipped actions, the per-app failures, the drift findings, and the recovered publications.

Raises:

Type Description
AuthError

If authentication fails, or Graph rejects the token during a run.

ConfigError

On a plan file for an app the run has no recipe for.

NetworkError

On Graph API failures outside a per-app unit (listing the tenant, reconciliation, the drift check).

StateError

On corrupted deployment state, or an explicit plan_file that does not exist. A plan file that cannot be loaded fails its own app instead.

Source code in napt/promote/applier.py
def apply_plan(
    configs: dict[str, dict[str, Any]],
    state_dir: Path,
    plan_file: Path | None = None,
    now: datetime | None = None,
    report_unknown_apps: bool = True,
) -> ApplyResult:
    """Executes promotion plans against Intune.

    Consumes the given recipes' plan files from ``<state_dir>/plans/``,
    removing each after its app applies fully. A plan file written by
    ``napt promote plan`` is the only thing apply executes: a recipe
    without one has nothing to apply, and plan files for apps outside
    the run are left untouched, so applying one recipe never consumes
    another app's reviewed plan. Each app's plan is an independent
    unit: its groups are preflighted before any of its actions execute,
    so an unresolvable group fails that app with zero mutations, and a
    failure while loading, preflighting, or applying one app records
    the failure, keeps its plan file for retry, and continues with the
    remaining apps. A dead group referenced only by stale or
    already-applied actions never blocks an app. Deployment state is
    saved after each applied action, so a failed run resumes safely:
    already-applied actions validate as no-ops.

    Assignment drift is checked on every run, including runs with
    nothing to apply (which therefore still authenticate), and reported
    in the summary, never corrected. Publications whose state writeback
    was lost are recovered first (see
    [reconcile_publications][napt.promote.reconcile.reconcile_publications]);
    a recovered release is picked up by the next plan run, since the
    plan files being applied were computed before the recovery.

    Args:
        configs: Effective configurations keyed by recipe id, from
            [load_recipe_configs][napt.promote.planner.load_recipe_configs].
        state_dir: State directory holding ``deployment/`` and
            ``plans/``.
        plan_file: Explicit path to a single plan file to apply; its app
            must be one of the recipes. When omitted, the recipes' plan
            files in the default plans directory are applied.
        now: Evaluation clock for ring timestamps. Defaults to the
            current UTC time.
        report_unknown_apps: Whether the drift check reports a stamped app
            whose recipe id is not in ``configs``. True when the configs
            cover the whole fleet; a run over one recipe passes False.

    Returns:
        The applied and skipped actions, the per-app failures, the drift
            findings, and the recovered publications.

    Raises:
        AuthError: If authentication fails, or Graph rejects the token
            during a run.
        ConfigError: On a plan file for an app the run has no recipe for.
        NetworkError: On Graph API failures outside a per-app unit
            (listing the tenant, reconciliation, the drift check).
        StateError: On corrupted deployment state, or an explicit
            ``plan_file`` that does not exist. A plan file that cannot
            be loaded fails its own app instead.

    """
    logger = get_global_logger()
    if now is None:
        now = datetime.now(UTC)

    deployment_dir = state_dir / "deployment"
    states = load_deployment_states(deployment_dir, configs)

    # Authenticate even when there is nothing to apply: the steady state
    # (no eligible promotions) is exactly when out-of-band assignment
    # changes accumulate, so drift is checked on every apply run.
    access_token = get_access_token()
    run = _ApplyRun(access_token, configs, states, deployment_dir, now)

    # Recover lost publication writebacks so state is right for the
    # actions below and for the next plan run.
    recovered = reconcile_publications(
        access_token, configs, states, deployment_dir, run.existing_apps
    )

    # Each plan file is one app's unit of work. The filename is the app's
    # identity (load_plan_file rejects a file whose declared app id
    # disagrees), so the stem decides which files belong to this run
    # before any content is read.
    if plan_file is not None:
        if not plan_file.is_file():
            raise StateError(f"Cannot read plan file {plan_file}: no such file")
        if plan_file.stem not in configs:
            raise ConfigError(
                f"Plan file {plan_file} is for app '{plan_file.stem}', which "
                f"is not among the recipes in this run "
                f"({', '.join(sorted(configs))}). Pass that app's recipe, "
                "or the recipes directory."
            )
        units = [plan_file]
        logger.info("PROMOTE", f"Applying plan file: {plan_file}")
    else:
        plan_paths = sorted(plans_dir_for(state_dir).glob("*.json"))
        outside = [path for path in plan_paths if path.stem not in configs]
        if outside:
            logger.info(
                "PROMOTE",
                f"Left {len(outside)} plan file(s) for apps outside this run "
                f"untouched: {', '.join(path.stem for path in outside)}",
            )
        units = [path for path in plan_paths if path.stem in configs]
        if units:
            logger.info(
                "PROMOTE",
                f"Applying {len(units)} plan file(s) from {plans_dir_for(state_dir)}",
            )
        else:
            logger.info(
                "PROMOTE",
                "No plan files to apply; run 'napt promote plan' to compute them",
            )

    failed: list[dict[str, Any]] = []
    for plan_path in units:
        unit_id = plan_path.stem

        # Everything an app's unit does, from reading its plan file to
        # its last action, sits inside one per-app isolation: a plan
        # file that cannot be loaded, an unresolvable group, or a Graph
        # or state failure fails this app only, keeps its file, and the
        # loop moves on. A rejected token (AuthError) still aborts the
        # run, since it would fail every app the same way.
        #
        # Preflight: every group a live action of this app will touch
        # must resolve before any of its actions execute, so an
        # unresolvable group fails this app with zero mutations instead
        # of stranding a half-applied plan. Skipped actions are excluded:
        # a dead group referenced only by a stale or already-applied
        # action never blocks the app. Resolutions are cached for the
        # action loop below.
        try:
            actions = load_plan_file(plan_path)
            if not actions:
                plan_path.unlink()  # An empty plan file holds no decisions.
                continue
            live = [a for a in actions if _action_skip_reason(run, a) is None]
            problems = unresolvable_groups(access_token, live, run.group_id_cache)
            if problems:
                reason = "unresolvable groups: " + "; ".join(problems)
                logger.warning(
                    "PROMOTE",
                    f"{unit_id}: preflight failed, nothing applied for this "
                    f"app; plan kept for retry ({reason})",
                )
                failed.append({"app_id": unit_id, "error": reason})
                continue

            for action in actions:
                reason = _action_skip_reason(run, action)
                if reason is not None:
                    run.skip(action, reason)
                    continue
                if action["type"] == "assign":
                    _apply_assign(run, action)
                else:
                    _apply_promote(run, action)
        except (ConfigError, NetworkError, StateError) as err:
            logger.warning(
                "PROMOTE",
                f"{unit_id}: apply failed, plan kept for retry: {err}",
            )
            failed.append({"app_id": unit_id, "error": str(err)})
            continue

        plan_path.unlink()
        logger.verbose("PROMOTE", f"Consumed plan file: {plan_path}")

    # Drift is checked after the actions so freshly applied assignments
    # are reflected. Findings are warnings only, never corrected.
    drift = detect_drift(
        access_token,
        configs,
        states,
        run.existing_apps,
        group_id_cache=run.group_id_cache,
        report_unknown_apps=report_unknown_apps,
    )

    return ApplyResult(
        applied=run.applied,
        skipped=run.skipped,
        failed=failed,
        drift=drift,
        recovered=recovered,
    )

napt.promote.preflight

Group validation for promotion plans.

A planned action names its assignment groups, so an unresolvable group (a typo in ring configuration, a deleted Entra ID group) is knowable before anything mutates the tenant. Checking up front turns what would be a mid-run abort (leaving a half-applied plan) into either a failed plan that never reaches review, or an apply that refuses to start that app's plan.

Used by the authenticated napt promote plan modes (a plan with an unresolvable group fails instead of becoming a reviewable promotion PR) and by napt promote apply as a per-app preflight before executing any of that app's actions. Offline plans skip validation; the apply preflight is the backstop for anything they produce.

unresolvable_groups

unresolvable_groups(
    access_token: str,
    actions: list[dict[str, Any]],
    group_id_cache: dict[str, str] | None = None,
) -> list[str]

Resolves every group named in the actions, collecting failures.

Each distinct group is resolved once. Successful resolutions land in the shared cache, so a subsequent apply pass re-resolves nothing.

Parameters:

Name Type Description Default
access_token str

Bearer token for Graph API.

required
actions list[dict[str, Any]]

Planned action dicts (each may carry a "groups" list).

required
group_id_cache dict[str, str] | None

Shared cache for group name resolution. A new cache is used when omitted.

None

Returns:

Type Description
list[str]

One failure description per unresolvable group, sorted for deterministic output. Empty when every group resolves.

Raises:

Type Description
AuthError

On 401 or 403.

NetworkError

On Graph API failures.

Source code in napt/promote/preflight.py
def unresolvable_groups(
    access_token: str,
    actions: list[dict[str, Any]],
    group_id_cache: dict[str, str] | None = None,
) -> list[str]:
    """Resolves every group named in the actions, collecting failures.

    Each distinct group is resolved once. Successful resolutions land in
    the shared cache, so a subsequent apply pass re-resolves nothing.

    Args:
        access_token: Bearer token for Graph API.
        actions: Planned action dicts (each may carry a "groups" list).
        group_id_cache: Shared cache for group name resolution. A new
            cache is used when omitted.

    Returns:
        One failure description per unresolvable group, sorted for
            deterministic output. Empty when every group resolves.

    Raises:
        AuthError: On 401 or 403.
        NetworkError: On Graph API failures.

    """
    cache = group_id_cache if group_id_cache is not None else {}
    failures: list[str] = []
    seen: set[str] = set()

    for action in actions:
        for group in action.get("groups", []):
            if group in seen:
                continue
            seen.add(group)
            try:
                resolve_assignment_target(access_token, group, cache)
            except ConfigError as err:
                failures.append(str(err))

    failures.sort()
    return failures

napt.promote.drift

Assignment drift detection for NAPT deployment promotion.

Compares what deployment state says should be assigned in Intune against what actually is, and reports every discrepancy as a finding. Strictly observational: drift is warned about and never corrected; manual admin changes are deliberately left alone.

Finding kinds:

  • missing_app: State references a release whose stamped Intune entry no longer exists.
  • missing_assignment: An assignment NAPT applied (ring group or install group) is no longer present.
  • intent_mismatch: An expected assignment exists with a different intent.
  • unrecorded_assignment: A NAPT-stamped app carries an assignment that matches a currently configured target, but NAPT has no record of making it: either an apply writeback was lost (a later apply converges it) or it was made outside NAPT. Left alone.
  • unexpected_assignment: A NAPT-stamped app carries an assignment NAPT has no record of making and that matches no configured target (typically admin-made; left alone).
  • orphaned_release: A stamped app exists for a release that no state file references (e.g., a crashed run replaced by newest-wins).
  • unknown_app: A stamped app references a recipe id with no recipe.

Authorship is always inferred, never known: Graph assignments carry no provenance field, so deployment state records are the only memory of what NAPT assigned, and a lost writeback loses that memory.

target_key

target_key(target: dict[str, Any] | None) -> tuple[str, str]

Returns a comparable identity for an assignment target.

Source code in napt/promote/drift.py
def target_key(target: dict[str, Any] | None) -> tuple[str, str]:
    """Returns a comparable identity for an assignment target."""
    target = target or {}
    return (target.get("@odata.type", ""), target.get("groupId", ""))

detect_drift

detect_drift(
    access_token: str,
    configs: dict[str, dict[str, Any]],
    states: dict[str, dict[str, Any]],
    existing_apps: list[dict[str, Any]],
    group_id_cache: dict[str, str] | None = None,
    report_unknown_apps: bool = True,
) -> list[dict[str, Any]]

Detects assignment drift between deployment state and Intune.

Parameters:

Name Type Description Default
access_token str

Bearer token for Graph API.

required
configs dict[str, dict[str, Any]]

Effective configurations keyed by recipe id.

required
states dict[str, dict[str, Any]]

Each app's deployment state keyed by recipe id, from load_deployment_states.

required
existing_apps list[dict[str, Any]]

Mobile app dicts from list_mobile_apps.

required
group_id_cache dict[str, str] | None

Shared cache for group name resolution, so a caller that already resolved groups (apply, plan validation) re-resolves nothing. A new cache is used when omitted.

None
report_unknown_apps bool

Whether a stamped app whose recipe id is not in configs is reported. True when configs covers the whole fleet; a run over one recipe passes False, since the other apps' entries are not unknown, just outside the run.

True

Returns:

Type Description
list[dict[str, Any]]

Finding dicts, each with "app_id", "kind", and "detail" keys, sorted for deterministic output. Empty when Intune matches state.

Raises:

Type Description
AuthError

On 401 or 403.

ConfigError

If a configured group cannot be resolved.

NetworkError

On Graph API failures.

Source code in napt/promote/drift.py
def detect_drift(
    access_token: str,
    configs: dict[str, dict[str, Any]],
    states: dict[str, dict[str, Any]],
    existing_apps: list[dict[str, Any]],
    group_id_cache: dict[str, str] | None = None,
    report_unknown_apps: bool = True,
) -> list[dict[str, Any]]:
    """Detects assignment drift between deployment state and Intune.

    Args:
        access_token: Bearer token for Graph API.
        configs: Effective configurations keyed by recipe id.
        states: Each app's deployment state keyed by recipe id, from
            [load_deployment_states][napt.state.deployment.load_deployment_states].
        existing_apps: Mobile app dicts from list_mobile_apps.
        group_id_cache: Shared cache for group name resolution, so a
            caller that already resolved groups (apply, plan validation)
            re-resolves nothing. A new cache is used when omitted.
        report_unknown_apps: Whether a stamped app whose recipe id is not
            in ``configs`` is reported. True when ``configs`` covers the
            whole fleet; a run over one recipe passes False, since the
            other apps' entries are not unknown, just outside the run.

    Returns:
        Finding dicts, each with "app_id", "kind", and "detail" keys,
            sorted for deterministic output. Empty when Intune matches
            state.

    Raises:
        AuthError: On 401 or 403.
        ConfigError: If a configured group cannot be resolved.
        NetworkError: On Graph API failures.

    """
    findings: list[dict[str, Any]] = []
    if group_id_cache is None:
        group_id_cache = {}
    names: dict = {}

    stamped_by_recipe: dict[str, list[tuple[dict, dict]]] = {}
    for app in existing_apps:
        stamp = parse_stamp(app.get("notes"))
        if stamp is None:
            continue
        if stamp["id"] not in configs:
            if report_unknown_apps:
                findings.append(
                    {
                        "app_id": stamp["id"],
                        "kind": "unknown_app",
                        "detail": (
                            f"stamped app '{app.get('displayName', app['id'])}' "
                            f"references recipe id '{stamp['id']}', which has "
                            "no recipe"
                        ),
                    }
                )
            continue
        stamped_by_recipe.setdefault(stamp["id"], []).append((stamp, app))

    for app_id, config in configs.items():
        state = states[app_id]
        expected = _expected_assignments(
            access_token, config, state, group_id_cache, names
        )
        # Built lazily: only an unaccounted-for assignment needs it.
        configured: dict[str, dict[tuple[str, str], str]] | None = None
        referenced = _referenced_shas(state)
        stamped = stamped_by_recipe.get(app_id, [])
        stamped_keys = {(s["entry"], s["sha256"]) for s, _ in stamped}

        for entry, sha in expected:
            if (entry, sha) not in stamped_keys:
                findings.append(
                    {
                        "app_id": app_id,
                        "kind": "missing_app",
                        "detail": (
                            f"state expects a stamped {entry} entry for "
                            f"release {sha[:12]}, but none exists in the "
                            "tenant"
                        ),
                    }
                )

        for stamp, app in stamped:
            entry = stamp["entry"]
            sha = stamp["sha256"]
            if sha not in referenced:
                findings.append(
                    {
                        "app_id": app_id,
                        "kind": "orphaned_release",
                        "detail": (
                            f"stamped {entry} entry "
                            f"'{app.get('displayName', app['id'])}' for "
                            f"release {sha[:12]} is not referenced by "
                            "deployment state"
                        ),
                    }
                )
                continue

            expected_targets = expected.get((entry, sha), {})
            actual = {
                target_key(a.get("target")): a
                for a in get_app_assignments(access_token, app["id"])
            }

            for key, intent in expected_targets.items():
                if key not in actual:
                    findings.append(
                        {
                            "app_id": app_id,
                            "kind": "missing_assignment",
                            "detail": (
                                f"{entry} entry for {sha[:12]}: expected "
                                f"assignment '{names.get(key, key)}' "
                                f"({intent}) is not present in Intune"
                            ),
                        }
                    )
                elif actual[key].get("intent") != intent:
                    findings.append(
                        {
                            "app_id": app_id,
                            "kind": "intent_mismatch",
                            "detail": (
                                f"{entry} entry for {sha[:12]}: "
                                f"'{names.get(key, key)}' has intent "
                                f"'{actual[key].get('intent')}' "
                                f"(expected '{intent}')"
                            ),
                        }
                    )

            for key, assignment in actual.items():
                if key in expected_targets:
                    continue
                if configured is None:
                    configured = _configured_targets(
                        access_token, config, group_id_cache, names
                    )
                target_name = _describe_target(assignment.get("target"), names)
                intent = assignment.get("intent")
                if configured[entry].get(key) == intent:
                    findings.append(
                        {
                            "app_id": app_id,
                            "kind": "unrecorded_assignment",
                            "detail": (
                                f"{entry} entry for {sha[:12]}: assignment "
                                f"'{target_name}' ({intent}) matches the "
                                "configured target but NAPT has no record "
                                "of making it - either an apply writeback "
                                "was lost (a later apply converges it) or "
                                "it was made outside NAPT - leaving it "
                                "alone"
                            ),
                        }
                    )
                else:
                    findings.append(
                        {
                            "app_id": app_id,
                            "kind": "unexpected_assignment",
                            "detail": (
                                f"{entry} entry for {sha[:12]}: NAPT has no "
                                f"record of making assignment "
                                f"'{target_name}' ({intent}) and it matches "
                                "no configured target - leaving it alone"
                            ),
                        }
                    )

    findings.sort(key=lambda f: (f["app_id"], f["kind"], f["detail"]))
    return findings

napt.promote.reconcile

Publication recovery for lost deployment state writebacks.

A publish run records the pending-to-published transition in deployment state after uploading, but that record can be lost, most commonly when a CI runner uploads successfully and then fails to push the state commit (branch protection, network). The tenant then holds a fully published release that state still lists as pending, which blocks promotion planning and, if a newer discovery replaces the pending slot, orphans the published release permanently.

Reconciliation closes that gap by re-deriving the record from tenant evidence: when every entry the app's build_types requires exists in Intune, stamped for the pending release's installer hash and with committed content, the publication demonstrably succeeded and published is recorded exactly as the publish run would have. This trusts provenance stamps and committed content the same way idempotent upload adoption already does, so no new trust is introduced.

Unlike drift detection, which never corrects, reconciliation writes deployment state: it completes NAPT's own half-persisted transaction rather than overriding an admin's tenant change.

Finding kinds:

  • recovered: The publication was fully committed in the tenant and has been recorded as published.
  • incomplete: Some required entries are missing or their content was never committed; nothing is recorded; re-run publish to finish.

reconcile_publications

reconcile_publications(
    access_token: str,
    configs: dict[str, dict[str, Any]],
    states: dict[str, dict[str, Any]],
    deployment_dir: Path,
    existing_apps: list[dict[str, Any]],
) -> list[dict[str, Any]]

Records publications whose deployment state writeback was lost.

For each app with a pending release, checks the tenant for stamped entries matching the pending installer hash. When every entry required by the app's build_types exists with committed content, records the release as published (clearing the pending slot) exactly as the original publish run would have. Partial evidence (some entries missing or uncommitted) is warned about but never recorded, because only a publish re-run can finish the upload.

Apps whose pending release has no stamped entries at all are the normal awaiting-publication case and produce no finding.

Parameters:

Name Type Description Default
access_token str

Bearer token for Graph API.

required
configs dict[str, dict[str, Any]]

Effective configurations keyed by recipe id.

required
states dict[str, dict[str, Any]]

Each app's deployment state keyed by recipe id, from load_deployment_states. A recovered publication is recorded into the dict as well as the file, so the steps that follow see it.

required
deployment_dir Path

Directory holding per-app deployment state files.

required
existing_apps list[dict[str, Any]]

Mobile app dicts from list_mobile_apps.

required

Returns:

Type Description
list[dict[str, Any]]

Finding dicts, each with "app_id", "kind" ("recovered" or "incomplete"), and "detail" keys, sorted for deterministic output. Empty when no pending release has tenant evidence.

Raises:

Type Description
AuthError

On 401 or 403.

NetworkError

On Graph API failures.

Source code in napt/promote/reconcile.py
def reconcile_publications(
    access_token: str,
    configs: dict[str, dict[str, Any]],
    states: dict[str, dict[str, Any]],
    deployment_dir: Path,
    existing_apps: list[dict[str, Any]],
) -> list[dict[str, Any]]:
    """Records publications whose deployment state writeback was lost.

    For each app with a pending release, checks the tenant for stamped
    entries matching the pending installer hash. When every entry
    required by the app's ``build_types`` exists with committed content,
    records the release as published (clearing the pending slot) exactly
    as the original publish run would have. Partial evidence (some
    entries missing or uncommitted) is warned about but never recorded,
    because only a publish re-run can finish the upload.

    Apps whose pending release has no stamped entries at all are the
    normal awaiting-publication case and produce no finding.

    Args:
        access_token: Bearer token for Graph API.
        configs: Effective configurations keyed by recipe id.
        states: Each app's deployment state keyed by recipe id, from
            [load_deployment_states][napt.state.deployment.load_deployment_states].
            A recovered publication is recorded into the dict as well as
            the file, so the steps that follow see it.
        deployment_dir: Directory holding per-app deployment state files.
        existing_apps: Mobile app dicts from list_mobile_apps.

    Returns:
        Finding dicts, each with "app_id", "kind" ("recovered" or
            "incomplete"), and "detail" keys, sorted for deterministic
            output. Empty when no pending release has tenant evidence.

    Raises:
        AuthError: On 401 or 403.
        NetworkError: On Graph API failures.

    """
    logger = get_global_logger()
    findings: list[dict[str, Any]] = []

    for app_id, config in configs.items():
        state_path = deployment_state_path(deployment_dir, app_id)
        state = states[app_id]
        pending = state.get("pending")
        if not pending:
            continue

        sha256 = pending["sha256"]
        required = _REQUIRED_ENTRIES[config["intune"]["build_types"]]
        matches = {
            entry: find_stamped_app(existing_apps, app_id, entry, sha256)
            for entry in required
        }
        if not any(matches.values()):
            continue  # Never published; a normal pending release.

        problems: list[str] = []
        for entry, match in matches.items():
            if match is None:
                problems.append(f"no stamped {entry} entry exists")
                continue
            full_app = get_mobile_app(access_token, match["id"])
            if not full_app.get("committedContentVersion"):
                problems.append(f"the {entry} entry's content was never committed")

        version = pending["version"]
        if problems:
            detail = (
                f"pending release {version} ({sha256[:12]}) was partially "
                f"published: {'; '.join(problems)} - re-run publish to finish"
            )
            logger.warning("PROMOTE", f"{app_id}: {detail}")
            findings.append({"app_id": app_id, "kind": "incomplete", "detail": detail})
            continue

        install_match = matches.get(ENTRY_INSTALL)
        update_match = matches.get(ENTRY_UPDATE)
        record_published(
            state,
            version=version,
            sha256=sha256,
            intune_app_id=install_match["id"] if install_match else None,
            intune_update_app_id=update_match["id"] if update_match else None,
        )
        state["name"] = config["name"]
        save_deployment_state(state, state_path)
        detail = (
            f"recorded publication of {version} ({sha256[:12]}): all entries "
            "are committed in the tenant but the published record was missing"
        )
        logger.info("PROMOTE", f"{app_id}: {detail}")
        findings.append({"app_id": app_id, "kind": "recovered", "detail": detail})

    findings.sort(key=lambda f: (f["app_id"], f["kind"], f["detail"]))
    return findings