Skip to content

Integration Testing

This document describes APM’s integration testing strategy to ensure runtime setup scripts work correctly and the golden scenario from the README functions as expected.

APM uses a tiered approach to integration testing:

1. Smoke Tests (merge queue, runtime changes, and releases)

Section titled “1. Smoke Tests (merge queue, runtime changes, and releases)”
  • Location: tests/integration/test_runtime_smoke.py
  • Purpose: Fast verification that runtime setup scripts work
  • Scope:
    • Runtime installation (codex, llm)
    • Binary functionality (--version, --help)
    • APM runtime detection
    • Workflow compilation without execution
  • Duration: ~2-3 minutes per platform
  • Trigger: merge queue integration workflow, runtime-code pushes, scheduled/manual runs, and release validation

2. End-to-End Golden Scenario Tests (merge queue and promotion runs)

Section titled “2. End-to-End Golden Scenario Tests (merge queue and promotion runs)”
  • Location: tests/integration/test_golden_scenario_e2e.py
  • Purpose: Complete verification of the README golden scenario
  • Scope:
    • Full runtime setup and configuration
    • Project initialization (apm init)
    • Dependency installation (apm install)
    • Real API calls to GitHub Models
    • Copilot, Codex, LLM, and Gemini runtime execution
  • Duration: ~10-15 minutes per platform (with 20-minute timeout)
  • Trigger: merge queue integration workflow, plus tag, schedule, and manual promotion runs

3. Lifecycle Smoke (PR-time required check)

Section titled “3. Lifecycle Smoke (PR-time required check)”
  • Location: selected declaratively via lifecycle_smoke and not lifecycle_merge_group. Tests marked lifecycle_merge_group remain outside the bounded required set.
  • Purpose: Promote a stable, hermetic slice of Consume/Produce/Govern lifecycle contracts onto the PR-time critical path, so regressions in install, lock, deployment ownership, compile, pack, prune, uninstall, audit, and repair fail the PR.
  • Scope: the family contains a static authority guard plus content-hash, policy, hook, virtual-package, audit, auth, and installed-console rows. Real subprocess cases use the uv-installed apm command and local Git. This is not frozen PyInstaller coverage.
  • Prerequisites: the pytest step sets APM_E2E_TESTS=1 so subprocess rows execute. APM_RUN_INTEGRATION_TESTS remains unset, the socket guard denies network sockets, and the job binds no credentials.
  • Duration: five shards each have a hard 20-minute timeout, including setup and cleanup; a balanced shard is expected to use under 60 percent of it, with four loadgroup workers. Hosted job results are authoritative; a printed pytest summary does not override a job timeout.
  • Trigger: every pull request and merge queue run. The required Lifecycle Smoke (Linux) aggregate checks every shard result independently and fails if any is missing, skipped, cancelled, or failed.
  • Selection mechanism: pytest --strict-markers -m 'lifecycle_smoke and not lifecycle_merge_group' tests/integration — declarative, not a file/node-id list. No central count or membership list is maintained.
  • Sharding: scripts.ci_sharding balances the shards by the measured lifecycle smoke durations in .github/ci-durations/lifecycle-smoke.json while keeping each module and composite xdist_group intact. The shards are disjoint and their union is the unchanged required selection.
  • Full-coverage path: merge-group workflow ci-integration.yml, job integration-tests-shard, step Run integration tests (sharded + parallelized), calls uv run ./scripts/test-integration.sh over tests/integration/. The hermetic shards and the network lane together run every non-live test, so the complete lifecycle family remains exercised.
  • Drift guard: tests/quality/test_ci_topology.py independently collects the full, merge-group-only, required, and every sharded selection. It verifies their set relationships, each shard’s timeout and worker bounds, the aggregate’s failure behavior, the full-integration execution path, step-level APM_E2E_TESTS: "1" binding, network/credential prohibitions, and required-check membership.
  • Fixture controls: lifecycle helpers set APM_TEST_LOOPBACK_PORTS for a port-scoped local registry and APM_TEST_FAIL_LOCK_REPLACE=1 for atomic-write fault injection, and APM_TEST_LOCK_COMMIT (hold:<marker> or kill) to stop a command at its lockfile commit point. These are internal test controls, not user-facing APM settings.
  • Source and ownership fixtures: downloader stubs must return real PackageInfo and ResolvedReference values and materialize each package at the requested path, including staging directories. Native MCP cleanup tests must generate managed baselines through the real writer, then prove both authorized removal and unchanged bytes on unverifiable or foreign entries. Keep successful transitive-service, frozen replay, and exact-byte assertions; a mock-error exit is not success.
  • Learning ledger: tests/fixtures/lifecycle_bug_ledger/ (one JSON file per row, such as bugs/<issue>.json, so concurrent PRs do not conflict) maps representative escaped defects to generalized laws, oracle tiers, phases, and executable regression node IDs, including coverage of already-correct behavior. Use same-workspace transitions to prove survivor ownership and scoped cleanup. It is not a bug-count census; tests/quality/test_lifecycle_bug_ledger.py validates its taxonomy and links.
  • Spine state machine: tests/lifecycle/machines/test_m_spine.py uses Hypothesis to generate guarded install, dry-run, audit, tamper, repair, declaration, prune, update, lock, compile and frozen sequences through the lifecycle driver (python -m apm_cli.cli on PR, the packaged binary on the nightly). The model tracks declaration, materialization, integrity, and lock state independently of the product lockfile. Its mandatory and generated project, global-canonical, and global-aliased replays verify that ordinary reinstall preserves edited skill bytes and their original deployment hashes. After prune removes ownership, ordinary install must refuse the retained user file without changing its bytes or durable state. Deliberate repair uses existing install --force consent, then checks exact source bytes, installed lock state, and a clean audit. Every command, including those the shared helpers run, is followed by check_cross_cutting, so each step keeps I1-I9 and earns receipts; per-rule write-set snapshots stay as before. The mandatory spine replays once per world; later examples restore that post-spine world in place. PR shards run 4 derandomized examples per variant; the nightly explores 25 (APM_SPINE_MAX_EXAMPLES=25).
  • GATE state machine: tests/lifecycle/machines/test_m_gate.py drives the lifecycle driver (python -m apm_cli.cli on PR, the packaged binary on the nightly) through declare, approve, deny, revoke, org-policy tightening, install, install --frozen, update, uninstall, prune and audit --ci for hook, LSP and native-plugin content, at project scope and at user scope with APM_HOME outside HOME. After every step check_cross_cutting (tests/lifecycle/oracles.py) checks lock/deployed agreement, idempotence, frozen/audit agreement, gate monotonicity (relative to the model: after each successful mutating step nothing is deployed that current approvals and policy do not allow), write sets, ASCII output, failure atomicity, exit codes and duplicated output. A cell that fails on main is a strict expected failure naming its tracking issue. Every step emits a cell: event; the mandatory spine must cover tests/quality/gate_cell_obligations.json, and a recorded mutant that skips the approval check must fail the machine. PR shards run 4 derandomized examples per scope; .github/workflows/gate-machine-nightly.yml builds the binary and explores 25 fresh examples per scope (APM_LIFECYCLE_DRIVER=binary, APM_GATE_MAX_EXAMPLES=25).
  • Lifecycle family core: tests/lifecycle/ holds the shared pieces: a pure reference model (model/state.py, model/expected.py), a driver (driver.py, APM_LIFECYCLE_DRIVER=engine|binary), the cross-cutting oracle (oracles.py) and receipts (receipts.py). Each oracle law that applies to a step and passes writes one receipt; only the oracle module may write receipts. tests/quality/promise_obligations.json lists every obligation as required, with the witness test that must earn its receipt (checked inside the lifecycle shards), or in the baseline with the lane that will cover it. A new obligation must be in one of the two lists, and the 0.37 release needs an empty baseline.
  • Docs journeys: tests/lifecycle/journeys/test_journeys.py replays the 25 journeys of index.yaml (one YAML file per journey; the schema is the module docstring) through the driver and applies output oracles O1-O13 plus check_cross_cutting. Golden journeys carry lifecycle_smoke; .github/workflows/lifecycle-journeys.yml runs all of them nightly on Linux, Windows and macOS, plus the full tests/lifecycle suite on Linux (PR and push CI run only the smoke subset), and on dispatch for a release-candidate ref, which must be a commit on main or a release/* branch (a first resolve-ref job refuses anything else before any checkout). Regenerate goldens with python tests/lifecycle/journeys/regen_goldens.py.
  • Frozen under-recording: the required smoke scenario and the generated model’s mandatory project replay add a local skill without refreshing the lockfile, require frozen refusal with unchanged lockfile bytes, repair with ordinary install, and verify two byte-stable frozen replays. The scenario uses ApmLifecycleRunner in an isolated environment. It does not promise filesystem rollback: the new skill is deployed before refusal.
  • Frozen local dependencies: test_frozen_local_path_lifecycle.py uses the selected installed CLI to check direct and transitive source changes before deployment, including portable identities for packages inside the consumer project. It covers a fresh consumer with a separate empty cache, unchanged lock and managed bytes on refusal, preserved unrelated cache content, and recovery by restoring the source or explicitly accepting it with a normal install. This is separate from the root project’s under-recording scenario above.
  • Known gap: a late lockfile replacement failure can leave target files on the newly declared target while retaining the prior lockfile. The required lifecycle suite bounds that blast radius and proves the next install converges; expanding the install transaction is a separate design decision recorded in the ledger.
  • Run it locally (repeat with shards 2 and 3 to cover the full required selection):
    Terminal window
    APM_E2E_TESTS=1 uv run --extra dev python -m pytest -p no:cacheprovider -q --strict-markers \
    -p scripts.ci_sharding --shard-count 3 --shard-index 1 \
    --shard-durations .github/ci-durations/linux-x86_64.json \
    -n 4 --dist loadgroup --durations=20 \
    -m 'lifecycle_smoke and not lifecycle_merge_group' tests/integration

3b. Owner Surface Check (required on every PR)

Section titled “3b. Owner Surface Check (required on every PR)”
  • Location: .github/workflows/owner-surface.yml, selection in scripts/owner_surface.py.
  • Purpose: run, on every pull request, the slice of the merge-time integration suite that an owner or install-path change can break. Owner-guard and install regressions then show on the PR, not on main.
  • Trigger: a change to src/apm_cli/install/*, src/apm_cli/deps/lockfile*, .apm/architecture/*, scripts/architecture_linter/*, tests/integration/test_architecture_*.py, tests/integration/test_install_*.py, or any file an owner registry selector names.
  • Slice: owner-rule mutation cases and test_architecture_*.py files that name a changed file or an affected owner, guard or rule; plus every test_install_*.py file for install-path changes. It runs hermetic tests in 3 duration-balanced shards (target under 10 min).
  • Result: Owner Surface Check always reports and is required by gate in every context. It passes when no owner surface changed (the slice steps are skipped) and on merge_group and merge trains (as the owner tier), where the full suite runs.
  • Run it locally:
    Terminal window
    python3 -m scripts.owner_surface plan --base origin/main --out /tmp/changed.txt
    APM_E2E_TESTS=1 uv run --extra dev python -m scripts.owner_surface run \
    --base origin/main --changed /tmp/changed.txt -- -n 4 --dist loadgroup

4. Live Guardrailing Hero (scheduled/manual)

Section titled “4. Live Guardrailing Hero (scheduled/manual)”
  • Location: tests/integration/test_guardrailing_hero_e2e.py
  • Purpose: Preserve the real remote, token-gated packaged CLI hero without multiplying it across the default packaged platform matrix
  • Scope: project initialization, two GitHub-backed installs, compile/deploy, and prompt startup through the built Linux x64 binary
  • Trigger: one ci-runtime.yml invocation on schedule or manual dispatch that fails the workflow on error (continue-on-error is not set); never pull requests or the generic integration script
  • Selection mechanism: the explicit test node with -m live; collection gates remain owned by tests/integration/conftest.py

5. Real Harness (nightly, manual, native-plugin PRs; not required)

Section titled “5. Real Harness (nightly, manual, native-plugin PRs; not required)”
  • Location: scripts/real_harness/probe.py, .github/workflows/real-harness.yml; harness pins are npm lockfiles under scripts/real_harness/npm/
  • Purpose: Prove that pinned Claude Code and Copilot CLI releases actually load a plugin APM installs natively, not only that the files exist
  • Cells: harness x environment (TUI in tmux, git worktree, -p) x scope (user, project), plus Claude diagnostic cells (second session, absolute path, no folder trust, native claude plugin install, worktree branches), and two #1120 cells: two packages whose native plugins ship the same skill name, and the same plugin name from two packages (refused)
  • Evidence: the plugin’s SessionStart hook marker, its stdio MCP server’s JSON-RPC log, the skill in the claude -p init event or copilot skill list. Claude never reaches a model; Copilot sessions need the real-harness environment token, available only to schedule and dispatch runs on main, so those cells report BLOCKED elsewhere
  • Verdicts: scripts/real_harness/expected.json records each cell’s expected verdict, known bugs included. probe.py check fails on any divergence except BLOCKED; a fix flips its cells

Exact-head HOME-alias lifecycle qualification

Section titled “Exact-head HOME-alias lifecycle qualification”

The #2867 contract uses real CLI subprocesses in isolated project, canonical-home and aliased-home fixtures. Its eight required/generated/replay witnesses retain the mandatory lifecycle inside Hypothesis execution; an additional project scenario checks semver transport refusal and recovery. Ownership snapshot tests also enforce one lockfile read per used root and integration phase, zero unused reads, and at most 15x record visits when fixture size grows from N to 10N. These counts do not claim a wall-clock speedup.

For fully native Claude fixtures, global compile verifies the installed revision in rules/revision.md, absence of redundant CLAUDE.md, and unchanged complete snapshots. Separate lifecycle cases retain unmatched fallback, policy refusal, and protected explicit-cleanup coverage. Mixed Claude/Hermes fixtures additionally check the Hermes revision and permit only its AGENTS.md compilation write.

Use a clean committed checkout. Set BASE_SHA to the full 40-hex commit SHA of a locally available, distinct ancestor of the checked-out HEAD. Set REPORT_PATH and COMPLETION_PATH to distinct, new paths outside the checkout:

Terminal window
uv run --frozen --extra dev python scripts/check_lifecycle_evidence.py \
--base "$BASE_SHA" --head "$(git rev-parse HEAD)" --lane full \
--report "$REPORT_PATH" --completion-output "$COMPLETION_PATH"

The command emits the schema-validated native completion sidecar only after fresh success. It verifies source/interpreter identity and freshly executes the authored contract; a skipped witness or disconnected sequence is not acceptance. It is source-Python coverage, not packaged-binary parity. Ordinary hosted platform checks remain separate.

For independent acceptance, use another clean checkout with the same base/head, its own interpreter and disposable environment. Replace --completion-output with --completion "$DRIVER_COMPLETION_PATH", pointing to the driver’s native sidecar, and use a new external --report path. Keep the driver’s report available at the path recorded in that sidecar. Completion mode verifies its digest and reruns the contract; it does not reuse the report as execution. Keep this native sidecar separate from the unchanged merge-worker completion JSON.

Integration tests live under tests/integration/ and run via pytest directly. Each test module declares the preconditions it needs as standard pytest markers; the registry in tests/integration/conftest.py (_MARKER_CHECKS) automatically skips tests whose precondition is not met, so you only have to install/set what the test family you want actually requires.

MarkerPreconditionHow to satisfy it
requires_e2e_modeOpt-in for the heavyweight golden-scenario suiteexport APM_E2E_TESTS=1
requires_network_integrationOpt-in for tests that hit live registriesexport APM_RUN_INTEGRATION_TESTS=1
requires_windowsA Windows-only process or filesystem boundaryRun on Windows
requires_windows_native_standard_userVerified standard-user token without symlink privilegeThe disposable Windows native-symlink CI job; do not enable manually
requires_inferenceOpt-in for tests that call inference APIsexport APM_RUN_INFERENCE_TESTS=1
requires_github_tokenA token usable against github.com / GitHub Modelsexport GITHUB_APM_PAT=... (or GITHUB_TOKEN)
requires_ado_patAzure DevOps PAT for ADO host testsexport ADO_APM_PAT=...
requires_ado_bearerAzure CLI signed in + opt-in flagaz login and export APM_TEST_ADO_BEARER=1
requires_apm_binaryA built apm binary on disk or PATHscripts/build-binary.sh (or set APM_BINARY_PATH)
requires_runtime_codexThe codex runtime on PATH or under ~/.apm/runtimes/; optional min_version="0.163.0" requires a stable release at or above that version on PATHapm runtime setup codex
requires_runtime_copilotThe GitHub Copilot CLI runtime installed under ~/.apm/runtimes/apm runtime setup copilot
requires_runtime_llmThe llm runtime installed under ~/.apm/runtimes/apm runtime setup llm
liveTests that hit real third-party repositories; deselected by defaultOverride the deselect: pytest -m live tests/integration -v

Without any of those env vars or runtimes a pytest tests/integration invocation is silent rather than red: every test is collected and reported as SKIPPED with a one-line reason, so you can see exactly what is missing and why.

Pytest markers compose across independent axes:

AxisQuestionMarkers
BehavioralWhat boundary does the test cross?unit, component, e2e
SchedulingWhen is the test selected?integration, slow, benchmark, live
PrerequisiteWhat environment must exist?requires_*
CI-selectionIs this test part of a named required CI gate?lifecycle_smoke

live is both an opt-in scheduling marker and an external-service prerequisite. Behavioral markers do not replace prerequisite markers. lifecycle_smoke is orthogonal to all three: it does not describe a test’s boundary, scheduling, or precondition, only that ci.yml selects it for lifecycle coverage. The required smoke shards use -m 'lifecycle_smoke and not lifecycle_merge_group'; the full integration path also retains the merge-group-only cases (see Tier 3 above).

The behavioral definitions are:

MarkerDefinition
unitPure logic with no filesystem and no CLI
componentIn-process behavior that touches a filesystem or one command boundary
e2eA real installed CLI crossing at least one command boundary

pyproject.toml owns these definitions. Module-level pytestmark is the sole behavioral classification authority. This is a marker-only behavioral taxonomy. Every classified module declares exactly one behavioral marker, and every collected node in that module must inherit the same classification. Function- or class-level behavioral markers are rejected because they would split the module’s authority.

There is no central module whitelist or exact classified-module count. New modules opt in by adding one module-level marker. The trade-off is deliberate: APM gives up the old closed-set/count ratchet in exchange for distributed ownership and removal of a central merge hotspot. Repository-wide collection still rejects empty, mixed, and multiple classifications deterministically.

Directory names and _e2e.py suffixes are not proof of behavior. test_policy_pinned_constraint_e2e.py is component because it uses Click in-process; test_core_smoke.py is e2e because it invokes an installed binary through subprocess boundaries.

To classify a module:

  1. Confirm the whole module has one behavioral boundary.
  2. Add exactly one module-level behavioral pytestmark, preserving scheduling and prerequisite markers.
  3. Document why behavior wins if the filename suggests another boundary.
  4. Run the contracts:
Terminal window
uv run --extra dev pytest -p no:cacheprovider -q tests/quality
uv run --frozen python scripts/check_test_assertions.py
uv run --frozen python scripts/check_exact_test_duplicates.py

The assertion and exact-duplicate baseline updaters only accept reductions.

Terminal window
uv run --frozen python scripts/check_test_assertions.py --update-baseline
uv run --frozen python scripts/check_exact_test_duplicates.py --update-baseline

Provisional mode is CI-only and allowed only on draft pull requests. Contributor commands, ready pull requests, merge queue runs, and final validation are strict. Do not pass the internal provisional flag manually; remove provisional metadata after remeasurement and review.

Three no-growth ratchets keep the test corpus from getting worse. Each records today’s debt in a baseline and fails only on new debt. A baseline entry whose test or module is gone or fixed is reported as stale ([i]) and never fails, so parallel cleanups do not conflict. Baselines are sorted JSON with one entry per line; entries may only be removed.

  1. Duplicate tests (scripts/check_exact_test_duplicates.py, baseline tests/quality/exact_test_duplicates.json). Each test body is hashed as a normalized AST (ast-body-v1: docstrings, comments and formatting ignored, literals kept). A test whose body equals another test’s body, or whose Class::name also exists in another file, fails unless the baseline lists it. Fix: delete the copy, parametrize it, or rename it after the distinct contract it checks.
  2. Classification and placement (tests/quality/test_test_taxonomy.py, baseline tests/quality/test_taxonomy_baseline.json). A module with no behavioral marker, a unit module under tests/integration, or a tests/unit module that spawns processes fails unless listed. Fix: add the marker, or move the module.
  3. Promise links (same contract and baseline). Every new test module names the promises it protects in its module-level pytestmark, using ids from tests/quality/promise-catalog.json: OpenAPM req-* ids, P-OWN-<owner id> architecture owners, P-INV-I1..P-INV-I9 lifecycle invariants, P-LAW-<id> lifecycle laws and P-DOC-<id> documented-surface promises. Add a missing promise to the catalog in the same pull request. A new id family (P-<FAMILY>-<id>) must first be declared in the catalog’s families; undeclared families fail.
pytestmark = [pytest.mark.unit, pytest.mark.promise("P-OWN-accepted-target-vocabulary")]

scripts/check_test_assertions.py (baseline tests/quality/assertion_quality_baseline.json) ratchets per-file counts the same way: AQ001 constant assertions, AQ002 pytest.raises(Exception), AQ003 component or e2e tests that assert no user-visible output, exit code or durable state, AQ004 tests that patch a symbol defined in an owner module they import, and AQ006 e2e modules that do not drive the real CLI (they use CliRunner, patch an owner module, or never run apm through ApmLifecycleRunner, the apm_binary_path or apm_engine_command fixtures, or the lifecycle driver).

For consolidation, uv run --frozen python scripts/check_exact_test_duplicates.py --report-equal-copies lists equal copies that are safe to delete. A copy qualifies only if body, decorators, fixtures, class context, module bindings and CI lane all match its kept twin. The report never fails and never edits files.

Moving a listed test or module to another directory under the same name keeps its allowance and is reported as moved. Prune stale or moved duplicate entries with --update-baseline; edit stale or moved taxonomy entries by hand.

Keep transport selection and authentication owners real in download tests; mock the Git/HTTP I/O instead. To exercise GitLab REST fallback, first simulate a typed Git transport failure on the same-origin HTTPS route. An empty mock transport plan does not authorize REST.

Home-directory fixtures must align HOME and USERPROFILE so Path.home() and Path("~").expanduser() refer to the same directory on Windows. Assert serialized dependency paths with Path.as_posix(). For deployed_file_hashes, use compute_file_hash, which canonicalizes text CRLF; package-tree integrity continues to hash raw bytes.

Concurrent fixtures must await every worker before inspecting shared results or cleaning up resources. Submit both consumers before collecting their futures; Thread.join(timeout=...) can return while a worker is still running. Keep real parallel materialization and content assertions in cache regression tests.

Installation snapshots must allow only the three local identity paths (.apm-local, .apm-local/.gitignore, .apm-local/installation) at the appropriate project or user root, not the whole subtree. Changing ownership metadata in a fixture invalidates its bound local receipt. For project installs, derive the exact user-state receipt path through DeploymentMaterializationSession under the fixture home; do not allow arbitrary sibling receipts. Pair conservative preservation checks with an unchanged, trusted-receipt recovery control.

When adding a registered architecture-owner guard, add its surgical mutation to test_architecture_owner_rule_mutations.py in the same change. The matrix requires exactly one mutation for every registered guard.

Terminal window
# Run everything you currently have the prerequisites for
uv run pytest tests/integration -v
# Run a single suite (the marker registry still applies)
uv run pytest tests/integration/test_golden_scenario_e2e.py -v
# Run only a marker family
uv run pytest tests/integration -m requires_github_token -v
# Run the spine state machine (python -m apm_cli.cli; no binary needed)
uv run --extra dev pytest -q tests/lifecycle/machines/test_m_spine.py
# Run the GATE state machine (python -m apm_cli.cli; no binary needed)
uv run --extra dev pytest -q tests/lifecycle/machines/test_m_gate.py
# Run the lifecycle family core and its obligation ratchet
uv run --extra dev pytest -q tests/lifecycle tests/quality/test_promise_obligations.py

tests/integration/test_hermetic_lifecycle_foundation.py is the cross-module contract. Complete the development setup first.

UtilityOwnsContract test
isolated_apm_environment.pyChild roots, environment, Python socket tripwiretest_isolated_apm_environment_contract.py
local_git_repository.pyDeterministic local Git originstest_local_git_repository_factory_contract.py
local_package.pySource-only package inputstest_local_package_factory_contract.py
apm_lifecycle_runner.pyBounded process execution and evidencetest_apm_lifecycle_runner_contract.py
lifecycle_state.pyExact bytes and semantic durable-state receiptstest_lifecycle_state_snapshot_contract.py
artifact_snapshot.pyRead-only filesystem observationstest_artifact_snapshot_contract.py
scenario_rows.pyImmutable scenario datatest_scenario_rows_contract.py

Source fixtures author only source inputs; the real APM CLI creates lockfiles, deployed trees, compiled output, bundles, hashes, cache state, and audit reports.

Use ArtifactSnapshot for one complete filesystem root and ArtifactSnapshotSet when an operation can affect multiple isolated roots. These open-world captures complement LifecycleStateSnapshot: the latter explains semantic lock and deployment state, while the former catches stray files even when the lockfile fails to record them.

Hypothesis failures print a minimized transition program that can be replayed by running the failing test with the reported example. Keep the generated model bounded and deterministic in CI (database=None, derandomize=True), and turn every confirmed product defect into a named regression before extending the ledger. The static scenario rows remain valuable for exact reproductions; the generated model searches valid orderings that authored rows may miss.

IsolatedApmEnvironment builds deterministic child environments for APM/Git/GitHub/ADO/GitLab/SSH flows with a best-effort Python socket guard. The guard preserves native optional socket API availability: it defines sendmsg only when the native socket supports it, keeping feature detection platform-correct. It isolates APM, Git, GH, Azure, home, cache, and temporary roots, not arbitrary variables; it is not a general credential scrubber.

For deeply nested fixtures that populate real sparse Git caches, use short pytest-owned roots such as tmp_path_factory.mktemp("r") instead of test-named tmp_path roots to avoid Git for Windows metadata path limits. Retain worker-equivalent directory depth in focused gates so they still exercise the paths used by the sharded suite.

It is also not an OS/native-code sandbox: executables found through PATH remain trusted, reflective access to CPython internals or native extensions can bypass Python monkey-patches, file:// access is not confined by the OS, and hostile post-creation filesystem races are outside the contract. GIT_ALLOW_PROTOCOL=file and local url.*.insteadOf rewriting separately restrict Git transport in reviewed scenarios.

Keep modules flat. Inside a pytest test with tmp_path and apm_binary_path, compose them directly:

import os
from tests.utils.apm_lifecycle_runner import ApmLifecycleRunner
from tests.utils.artifact_snapshot import ArtifactSnapshot
from tests.utils.isolated_apm_environment import IsolatedApmEnvironment
from tests.utils.local_package import LocalPackageFactory
isolated = IsolatedApmEnvironment.create(tmp_path / "scenario", base_env=os.environ)
environment = isolated.subprocess_env()
sources = LocalPackageFactory(isolated.package_root)
project = sources.create("consumer", targets=("copilot",))
sources.add_skill(
project,
"example",
"---\nname: example\ndescription: Fixture\n---\n# Example\n",
)
result = ApmLifecycleRunner((str(apm_binary_path),)).run(
("install", "--target", "copilot"),
cwd=project.root,
env=environment,
)
snapshot = ArtifactSnapshot.capture(project.root)
assert result.returncode == 0
assert "apm.lock.yaml" in snapshot.paths

For auth-bearing remote-package scenarios, create a local origin with LocalGitRepositoryFactory and pass the complete environment returned by url_rewrite_subprocess_env() to ApmLifecycleRunner. That process-scoped Git rewrite survives the production auth environment builder; do not hand-merge GIT_CONFIG_* slots or rely on the older global-config-only rewrite. ApmLifecycleRunner((str(apm_binary_path),)) invokes the fixture-selected console script. Packaged-binary tests belong to the separate platform lane.

test_packaged_virtual_file_lifecycle_e2e.py, test_deployed_files_e2e.py, and test_silent_adopt_existing_files_e2e.py are narrow hermetic packaged counterparts to the live hero. They run the real binary against a local bare Git origin through process-scoped URL rewriting, then check package installation, deployment lifecycle, and exact lock provenance without credentials or live HTTP.

Terminal window
# The three hermetic packaged counterparts (real binary, local file:// origin, no creds):
uv run pytest tests/integration/test_packaged_virtual_file_lifecycle_e2e.py -v
uv run pytest tests/integration/test_deployed_files_e2e.py -v
uv run pytest tests/integration/test_silent_adopt_existing_files_e2e.py -v
# Supporting hermetic foundation + contract suites:
uv run pytest tests/integration/test_local_package_factory_contract.py -v
uv run pytest tests/integration/test_hermetic_lifecycle_foundation.py -v
uv run pytest -n auto tests/integration/test_hermetic_lifecycle_foundation.py -v

These suites need no PAT and make no live HTTP calls: the packaged binary reaches the dependency through a process-scoped file:// URL rewrite. If one fails with a network or authentication error, the rewrite did not apply — confirm the test uses the hermetic_packaged_sample fixture (which sets GIT_CONFIG_COUNT and GIT_ALLOW_PROTOCOL=file) rather than invoking apm against the raw GitHub URL.

Tests that need to shell out to a real apm binary use the apm_binary_path fixture and the requires_apm_binary marker. The binary is resolved in this order, so a local build is preferred over a system install:

  1. APM_BINARY_PATH env var
  2. ./dist/apm-<os>-<arch>/apm (the layout produced by scripts/build-binary.sh)
  3. shutil.which("apm")

apm_engine_command is the canonical fixture for narrowly scoped Python filesystem-boundary fault injection: it returns (sys.executable, "-m", "apm_cli.cli") so ApmLifecycleRunner executes the installed Python engine. This is an explicit engine contract, not packaged-binary coverage, and it is independent of APM_BINARY_PATH so frozen CI cannot bypass the instrumentation. Packaged executable tests must continue to use apm_binary_path.

Adding an integration test that needs a precondition

Section titled “Adding an integration test that needs a precondition”
  1. Apply the marker at module or test level:
    import pytest
    pytestmark = pytest.mark.requires_github_token
  2. If you need a brand-new precondition, add an entry to _MARKER_CHECKS in tests/integration/conftest.py (predicate + skip reason) and declare the marker in pyproject.toml. That is the only place the precondition needs to live.

CI orchestrator: scripts/test-integration.sh

Section titled “CI orchestrator: scripts/test-integration.sh”

scripts/test-integration.sh is the thin orchestrator the CI integration job invokes. Its sole responsibilities are: resolve GitHub / ADO tokens, detect platform, locate or build the apm PyInstaller binary, install runtimes (codex / copilot / llm), install python test dependencies, and run pytest tests/integration/ once. All per-test gating lives in the marker registry described above. New integration tests dropped into tests/integration/ are picked up automatically; add the right requires_* marker and the registry will skip the test when its precondition is missing.

Release promotion sets PYTEST_MARK_EXPR="not live", so an expiring third-party credential cannot block publication. Live ADO PAT coverage is owned by the Auth Acceptance Tests workflow: dispatch it with ado_pat_e2e: true and an ado_repo acceptance fixture. That workflow selects live and requires_ado_pat, requires AUTH_TEST_ADO_APM_PAT, and fails with the normal actionable auth diagnostic when the PAT is rejected.

Run the same focused acceptance locally with:

Terminal window
APM_TEST_ADO_REPO=dev.azure.com/org/project/_git/repo \
ADO_APM_PAT=... \
uv run pytest tests/integration/ -m "live and requires_ado_pat" -v

The orchestrator is mainly intended for reproducing the full CI environment end-to-end; for local iteration prefer the direct pytest invocations earlier on this page.

On PR and merge queue:

  1. PR-time unit checks and the hermetic Lifecycle Smoke gate run first; merge queue adds the global coverage floor (Coverage Combine (Linux)) and Linux smoke, integration, and release-validation gates. Integration runs in up to 16 shards planned like the release pipeline’s, in about 16-18 minutes.

Architecture ratchet contracts and the real architecture-scaling test run in separate Linux jobs, each with the same five-minute setup-to-cleanup limit. Their test selections, scaling threshold and environment opt-ins are unchanged. The required Test Architecture Ratchets aggregate gates only the contracts job; failure, cancellation, skipping or a missing result fails it. merge-gate.yml requires it at PR time and on merge_group, because it runs the tests/quality guards, including the merge-time topology checks. The wall-clock scaling ratio stays a separate, non-required Architecture Scaling (Linux) check, since timing asserts flake. A passing test summary does not override a cancelled job.

gate also requires Spec conformance gate and its three Spec tests (N/3) shards on every pull request and merge group. spec-conformance.yml has no paths: filter, so these checks always run.

The required Windows compatibility gate runs the full Windows unit suite through scripts/ci_selections.py, the same selection main push runs, then the windows_compat tests in tests/integration with APM_E2E_TESTS=1 for marked real-CLI contracts. It runs only that integration marker subset, not the full integration suite. Its collection guard requires a non-empty subset, not a fixed test count. Every module under those roots must import on Windows before marker deselection. Import Unix-only modules such as pwd or fcntl inside the helpers that need them, not at module scope. The collection guard checks this with Unix-only standard modules unavailable, even on Linux and macOS. The nested collection subprocess has a 300-second hard timeout: pytest must import and collect the whole root before applying the marker, including on release runners sharing CPU with other test workers. Plugin autoload remains disabled, and a collection timeout fails the check rather than skipping it. Collection proves a test is selected; a successful Windows job provides Windows execution evidence. The existing job timeout bounds runtime.

The trusted_executable scheduling marker selects Git/GitHub CLI discovery contracts and real install/reinstall/update scenarios for an additional Windows Python 3.11 job. That version needs explicit PATHEXT candidates for directory-qualified executable lookup. The same tests also carry windows_compat, so the existing Python 3.12 gate checks compatibility. Run the focused contracts locally with uv run --frozen --extra dev pytest -m trusted_executable tests/unit/cache/test_git_env.py tests/integration/test_trusted_executable_discovery.py. The legacy job collects only these files so unrelated tests requiring newer interpreters cannot prevent collection. They select the same discovery cases as the marker across both test roots. Production imports on this path remain compatible with Python 3.11, the minimum supported version. Python 3.12 and later use the standard-library lookup without the legacy fallback; a candidate-count regression checks linear extension scanning. Only a native Windows run demonstrates Windows behavior; passing mocks or collection alone do not.

The Windows Native Symlink Acceptance job checks out the exact PR head and uses a temporary standard account on a disposable hosted runner. It requires successful ordinary file I/O, no administrator or symlink privilege, and actual Windows error 1314 before running the Git/APM link regression. APM must install a package with links as their target content, with the POSIX content_hash, and apm install --frozen must replay that lock.

The job requires a passing native case, failure after disabling the Git-object link writer in memory, and a restored pass. Empty or skipped runs fail. Account, profile, scratch and any changed Developer Mode value are cleaned up independently, with an always() cleanup fallback. A restoration failure fails the job. This is link-materialization evidence, not archive-symlink support, and the job does not change repository protection or replace required SDL scanning.

Plugin sequential-install coverage checks deployed-file removal and lockfile ownership after uninstall, plus unchanged files and ownership for the retained skill. The local fixture covers both an independent skill and a separately installed skill from the plugin; the network-backed case uses the same assertions. Cleanup wording is not the lifecycle contract.

Linux Lifecycle Smoke runs the required marker subset with four bounded workers (-n 4 --dist loadgroup) on the public Ubuntu runner. Grouped tests stay on one worker. The 20-minute whole-job limit includes setup and cleanup; --durations=20 reports slow cases without changing selection or assertions. Its lifecycle_smoke and not lifecycle_merge_group selection is not all lifecycle coverage: also run affected generated state machines, deployment ledger, and failure/retry contracts when changing those behaviors.

Releasing: push a v* tag, as before. scripts/release_plan.py picks how much the run validates:

  • push (push to main): unit tests and Linux/Windows binaries. The Windows installer runs alongside two duration-balanced unit shards. All three must succeed before the Windows binary is built or uploaded.
  • full (nightly schedule or repository_dispatch): every lane. A green full run is promotion evidence for its SHA.
  • promoted (tag whose SHA already has a green full run on main): builds, binary smoke tests and release validation only, then publishes (about 5 min).
  • tag without evidence: full validation in the tag run, then publishes.

For the fast path, dispatch manual-build-release on the main commit, wait for it to finish green, then tag that commit. Nothing publishes without a green full validation of the exact SHA.

The tag must point at a commit on main or a release/* branch. Any other tag fails the plan before anything builds or publishes; if the plan cannot reach the GitHub compare API, it fails too, and you re-run the job.

If a published stable release never reached PyPI, re-publish it from its tag without re-running validation:

Terminal window
gh api repos/microsoft/apm/dispatches -f event_type=publish-existing-tag \
-F 'client_payload[tag]=vX.Y.Z'

The run refuses a tag that is not a published stable GitHub release, or whose version is already on PyPI.

On qualifying PRs and merge groups, Spec conformance gate requires three serial pytest shards on isolated runners plus the statement check. Only the statement job’s full collection is used to regenerate CONFORMANCE.{json,md}. On every PR, Windows Compatibility Gate requires three shards on parallel Windows runners (units with four xdist workers, then serial windows_compat integration); Lifecycle Smoke (Linux) and the two Build & Test shards are split the same way. The seeds in .github/ci-durations/ (windows-unit, windows-compat, linux-unit, spec-conformance, and linux-x86_64 for lifecycle smoke) weight the current pytest collection; they are not lists of tests to run.

Full-run lanes:

  • Linux x86_64 and arm64: hermetic integration (not live and not requires_github_token and not requires_network_integration) split across runners by scripts/ci_sharding.py. Shards are balanced by measured durations and keep xdist groups and heavy modules whole. The nightly run publishes durations; .github/ci-durations/ holds the fallback seeds. Architecture-linter contracts (architecture_contract) run on x86_64 only.
  • Network lane (Linux x86_64): requires_github_token or requires_network_integration, re-running only failed tests up to twice.
  • Windows: scripts/windows/test-integration.ps1.
  • macOS: Intel is one job running windows_compat or platform_sensitive. Apple Silicon runs the unit suite in its own job, in parallel with the build job that runs lifecycle_smoke or windows_compat or platform_sensitive. Mark OS-, filesystem- or shell-sensitive integration tests platform_sensitive.

create-release requires a pushed tag and every release-bound lane. Only a promoted tag may skip integration and the Apple Silicon unit job.

The existing unprivileged PR Binary Smoke (Linux) job also runs tests/integration/test_audit_workspace_identity_lifecycle.py against its built binary with a five-minute limit. The fixture isolates HOME, credentials, cache, and local Git repositories; captured audit output and full failure tracebacks remain visible in the job log. This focused witness does not replace the full release qualification or change required checks.

Daily scheduled release smoke:

  • Runs the same promotion validation path once per day.
  • Failing scheduled runs update one ci/daily-smoke tracking issue; a later recovered run closes it.
  • This signal is advisory and is not a required PR check.

Manual workflow dispatch:

  • Test builds (uploads as workflow artifacts)
  • Allows testing the full build pipeline without creating a release, even when dispatched from a tag ref
  • Useful for validating changes before tagging

main-push-gate.yml runs the whole PR gate suite (ci.yml, including every Lifecycle Smoke shard), the full integration suite (ci-integration.yml, every shard) and the lifecycle security cells (lifecycle-security.yml) on each push to main. Its main-push-gate job fails the run when any tier job fails, so a red main shows on the commit. It is not a required check and never saves caches to the main scope.

lifecycle-security.yml runs tests/lifecycle/security on Linux and then requires a receipt from every security witness. Pull requests run it when they touch src/apm_cli/, tests/lifecycle/, the receipt ratchet, pyproject.toml or uv.lock; it is not a required check. The security cells run on Linux only; Windows and macOS run only the nightly journeys.

merge-train.yml proves one exact merge result before it lands. Push the merged tree (main plus the queued PRs) to a queue/* branch and read the single train-gate check at that SHA:

RefRunsTime
queue/t<id>/p<k>-guardscope, guard, train-gateabout 5-10 min
queue/t<id>/p<k>-fullthe guard plus tier1 (ci.yml), tier2 (ci-integration.yml), spec (spec-conformance.yml) and owner (owner-surface.yml)about 30-35 min
queue/b<sha12>/p0-fulla full proof of a main SHAabout 30-35 min

guard runs the Lint chain (.github/actions/lint-chain, shared with the Lint job), the architecture ratchet contracts, every other tests/quality module and the NOTICE check. The ratchets compare against the merge base with main; a Queue-Base: <sha> trailer must name exactly that commit. A full train runs every check the merge_group gate requires. train-gate passes only when every job is green, or when every failure is inherited: gate.py collects the failing pytest node ids from the failed jobs’ logs and subtracts the train-failures.json of the newest base probe (queue/b<sha12>/p0-full). It then publishes the run’s own train-failures.json. A cancelled job, or a failure without node ids, is never excused.

Strict known cells must cite open issues. Pull requests check the committed snapshot (tests/quality/known_cell_issue_states.json) only. A train’s guard checks the live GitHub state, fail-closed. Every main push and a daily run check it in .github/workflows/known-cells-live.yml, outside the main push gate: a failure there is a ledger-state red (an issue changed state), not a code red, and opens one tracking issue. An API outage or a closed issue never reds open pull requests.

Queue refs are real branches: only write-access users can push them, and every job tests the triggering commit. Train jobs restore caches (including main’s) read-only and never save one. After train-gate reports, the cleanup job deletes the train branch, so push it again to re-run (a manual dispatch with --ref <queue branch> works only while the branch exists).

A green train-gate found by SHA alone is not a full proof: the same SHA can also carry a guard-only run. A full proof is a successful merge-train run on the -full branch (queue/t<id>/p<k>-full or queue/b<sha12>/p0-full) at that exact SHA:

Terminal window
git push origin HEAD:refs/heads/queue/t0001/p1-full
gh run list --workflow merge-train.yml --branch queue/t0001/p1-full \
--commit "$(git rev-parse HEAD)" --json conclusion,url

The run must show "conclusion": "success"; cite its url as the proof.

scripts/merge_queue/ composes these trains automatically (shadow mode: it builds and proves trains but never merges). It reads PRs labeled queue:ready with an apm-queue-ticket marker comment, builds queue-build/t<id> through the merges API, publishes the prefix refs, and logs would-land events:

Terminal window
python -m scripts.merge_queue.runner tick # one pass; state in ~/.apm-queue
python -m scripts.merge_queue.runner metrics # shadow summary from events.jsonl

A red train is classified by scripts/merge_queue/classify.py:

  • the earliest red guard prefix ejects its PR;
  • an infra failure is rerun once, and a second infra failure halts launches;
  • a failure attributable to one member’s files ejects that member;
  • any other failure is rerun once (a flake lands), then bisected by halves.

An ejected PR re-enters only with a new head.

Landing is off by default. --land (scripts/merge_queue/landing.py) also admin-merges proven trains in launch order with gh pr merge --merge --admin --match-head-commit. It does so only when main’s tree is the tree the member was proven on, and the merge commit must carry the proven tree. Any drift, or a merge to main that the runner did not make, HALTs landing and records the reason in landing.json; trains keep testing. Two failed admin probes in a row pause landing until elevation returns. Before merging, closure.py requires the issues GitHub will close (closingIssuesReferences plus closing keywords in commit messages) to equal the ticket’s fixes; a mismatch ejects the train unmerged. After the merge it closes any fix GitHub left open and retargets stacked PRs.

The Windows unit steps in .github/workflows/build-release.yml and the PR Windows Compatibility Gate run the selection owned by scripts/ci_selections.py:

Terminal window
uv run --frozen python -m scripts.ci_selections windows-unit [--shard-count N --shard-index I]

which runs pytest tests/unit tests/test_console.py -n 4 --dist worksteal -vv --tb=short --show-capture=no --no-showlocals.

PYTHONUNBUFFERED=1 keeps named test starts and outcomes visible while the suite runs. Captured test output and local-variable dumps remain disabled. These diagnostics identify candidate unfinished tests, not stack frames or the exact blocked phase; an outcome can appear before fixture teardown completes.

The 60-minute step limit fails closed on a hang; it is not proof that tests pass or a root-cause fix. The PR-time gate exercises live name visibility during setup, call, and teardown after a failed call.

E2E tests require proper GitHub Models API access:

Required Permissions:

  • contents: read - for repository access
  • models: read - Required for GitHub Models API access

Environment Variables:

  • GITHUB_TOKEN - user-scoped token for GitHub Models runtime calls
  • GITHUB_APM_PAT - package access token; used as fallback by runtime setup

Runtime setup prefers GITHUB_TOKEN for GitHub Models and falls back to GITHUB_APM_PAT when no user-scoped token is present.

The workflow ensures quality gates at each step:

  1. release-plan job - Chooses push, full or promoted mode
  2. build-linux-x86, build-linux-arm, build-windows jobs - Unit tests plus binary builds
  3. integration-tests job (Integration Tests Summary) - Requires every sharded integration lane
  4. release-validation jobs - Final shipped-binary validation
  5. create-release job - GitHub release creation
  6. publish-pypi job - PyPI package publication

Each publication stage must succeed before proceeding to the next. Live third-party credential acceptance remains a failing gate in the opt-in Auth Acceptance workflow rather than a dependency of release publication.

The microsoft/homebrew-apm tap updates independently: it polls the latest APM release and commits formula updates with its own repository-scoped GITHUB_TOKEN. The release pipeline does not hold a cross-repository Homebrew credential.

Promotion integration tests run on:

  • Linux: ubuntu-24.04 (x86_64), ubuntu-24.04-arm (arm64)
  • Windows: windows-latest (x86_64)
  • macOS Intel: macos-15-intel (x86_64), with the windows_compat or platform_sensitive subset, native binary startup, and isolated release validation
  • macOS Apple Silicon: macos-latest (arm64), with unit tests and the lifecycle_smoke or windows_compat or platform_sensitive subset

Python Version: 3.12 (standardized across all environments) Package Manager: uv (for fast dependency management and virtual environments)

  • [+] Runtime setup scripts execute successfully
  • [+] Binaries are downloaded and installed correctly
  • [+] Binaries respond to basic commands
  • [+] APM can detect installed runtimes
  • [+] Configuration files are created properly
  • [+] Workflow compilation works (without execution)
  • [+] Complete golden scenario from README works
  • [+] apm runtime setup copilot installs and configures GitHub Copilot CLI
  • [+] apm runtime setup codex installs and configures Codex
  • [+] apm runtime setup llm installs and configures LLM
  • [+] apm init my-hello-world creates project correctly
  • [+] apm install handles dependencies
  • [+] apm run start --param name="Tester" executes successfully
  • [+] Real API calls to GitHub Models work
  • [+] Parameter substitution works correctly
  • [+] MCP integration functions (GitHub tools)
  • [+] Binary artifacts work across platforms
  • [+] Release pipeline integrity (GitHub Release -> PyPI)
  • Install content-hash roundtrip (Consume contract)
  • Virtual-skill lock convergence (Produce contract, adjacent to the #2226 ADO lock-coordinate fix)
  • Policy pinned-constraint enforcement (Govern contract)
  • The virtual/manifestless lifecycle matrix: install, lock, frozen-install, update, and audit stay consistent (the direct #2240 regression)
  • The ADO lock-coordinate single-owner guard (the direct #2226 regression)
  • Prune’s merged-hook and ownership-sidecar reconciliation for the claude target (the direct #2249 regression — an orphaned package’s merged hook entries and sidecar markers must be cleaned up, not left pointing at deleted scripts)
  • No network, no credentials, no built binary required for any of the above
  • Smoke tests: Fast feedback (2-3 min) in the merge queue and on runtime changes
  • E2E tests: High confidence (15 min) in the merge queue and promotion runs
  • Smoke tests use no API credits
  • E2E tests run in the merge queue and promotion runs, not on every PR push (minimizing API usage)
  • Manual workflow dispatch for test builds without publishing
  • Tests run on all supported platforms
  • Catches platform-specific runtime issues
  • E2E tests must pass before any publishing steps
  • Multi-stage release pipeline ensures quality gates
  • Guarantees shipped releases work end-to-end
  • Users can trust the README golden scenario
  • Cross-platform binary verification
  • Check runtime setup script output
  • Verify platform compatibility
  • Check network connectivity for downloads
  • Use the unified integration script first: Run ./scripts/test-integration.sh to reproduce the exact CI environment locally
  • Verify GITHUB_TOKEN has required permissions (models:read)
  • Ensure both GITHUB_TOKEN and GITHUB_MODELS_KEY environment variables are set
  • Check GitHub Models API availability
  • Review actual vs expected output
  • Test locally with same environment
  • These tests are hermetic — no credentials, no built binary, no network (a real socket attempt raises OSError, it does not hang or retry). A failure is a genuine regression, not an environment issue.
  • Run the exact CI command from the “Run it locally” block under Tier 3 above to reproduce.
  • If the failure is about the CI job’s shape (marker not registered, wrong -m/--strict-markers invocation, unbounded root, timeout, empty marker family, or required-check wiring) rather than test logic, check tests/quality/test_ci_topology.py — that guard pins the job’s contract and its own failure message will point at what drifted.
  • For hanging issues: Check command transformation in script runner (codex expects prompt content, not file paths)
  1. Add a smoke test for runtime setup, marked @pytest.mark.requires_runtime_<name> (and add the marker entry to _MARKER_CHECKS in tests/integration/conftest.py if the runtime is brand new).
  2. Add an E2E test for the golden scenario with the new runtime, marked @pytest.mark.requires_e2e_mode and any token markers it needs.
  3. Update the CI matrix if the runtime introduces new platform support.

Lifecycle family: add a row or a machine rule

Section titled “Lifecycle family: add a row or a machine rule”
  1. Name the promise ids, for example P-INV-I4 or P-LAW-<property>. Every id must resolve in tests/quality/promise-catalog.json; the row loader rejects any other id.
  2. For a fixed command sequence, add a row to tests/lifecycle/replay/rows/ (copy core_gate_row.yaml) with promises, world, given, when and then (exit, deployed: expected, announce). RowReplay (tests/lifecycle/rows.py) runs every step through the driver and check_cross_cutting, and compares the final world with expected_deployed.
  3. For a transition that must hold from many states, add a rule to the matching state machine. Each rule builds an Operation (oracles.operation_for(args)) and calls check_cross_cutting; never write receipts yourself.
  4. If a step fails on main, open a neutral tracking issue and add a known_cells entry (law, tracking issue, step, match). It is a strict expected failure; never skip the step.
  5. Run the row red first: use a recorded mutant (entry_point=), or remove the oracle call and check that its obligations show up uncovered. Then move the obligations it covers from baseline to required in tests/quality/promise_obligations.json, with the row’s test as witness.
  1. Add a smoke test for compilation/validation.
  2. Add an E2E test if the feature requires API calls — pick the smallest set of markers that captures its real preconditions (requires_github_token, requires_network_integration, etc.) so contributors without those credentials still get a clean SKIPPED rather than a hard failure.
  3. Keep tests focused and fast.

Copyright (c) Microsoft Corporation. General documentation: CC-BY-4.0. Software, code examples and OpenAPM: Apache-2.0. See scope and exclusions.