agentleFS
Microsoft AzureKnown publisherAzure/sap-automation-qa/.github/copilot-instructions.md

sap-automation-qa

Copilot instructions14 starsChanged 21 months agoMITView on GitHub

Version: 1.0.2 | License: MIT (Microsoft Corporation) Repository: Azure/sap-automation-qa This is the SAP Testing Automation Framework -- an open-source orchestration tool for validating SAP deployments on Microsoft Azure. It provides: - HA functional testing for SAP HANA (Scale-Up, Scale-Out HSR, Scale-Out Standby) and SAP Central Services (ENSA1/ENSA2) in Pacemaker clusters. - Configuration validation for HANA, IBM Db2, SCS, and application instances. - Offline validation of HA configurations without live cluster interaction. - A FastAPI scheduling service with async job execution,…

The file

Show its rules and text

We split this copilot-instructions.md into the rules it gives an agent

17 rules. About 0 are common, 6 are distinctive, and 11 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈6

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 11

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Follow these established patterns when contributing:

    line 158
  2. Very specific:

    Async: Use asyncio_mode = "auto" in pytest.

    line 210
  3. Very specific:

    Task naming: Every task MUST have a descriptive name: field.

    line 216
  4. Very specific:

    Shell tasks: Always use set -o pipefail, executable: /bin/bash, and changed_when: false for read-only commands.

    line 217
  5. Very specific:

    Error handling: Use block/rescue/always patterns.

    line 219
  6. Very specific:

    OS dispatching: Use Jinja2 filters on commands list with ansible_os_family | upper.

    line 220
  7. Very specific:

    API tests: Use httpx.AsyncClient with FastAPI test client pattern.

    line 225
  8. Very specific:

    Core tests: Use tmp_path, mock subprocess.Popen, test state machines.

    line 226
  9. Very specific:

    Safety: Check tool availability (command -v), validate inputs, provide clear error messages.

    line 234
  10. Distinctive:

    All code must meet these non-negotiable standards:

    line 240
  11. Distinctive:

    No plaintext secrets: Azure Key Vault integration for SSH credentials.

    line 267
  12. Very specific:

    Use dependency inversion: define interfaces via Protocol or ABC.

    line 287
  13. Very specific:

    Avoid "stringly typed" protocols -- use enums (TestStatus, HanaTopology, AuthType).

    line 290
  14. Distinctive:

    Prefer composition over inheritance.

    line 292
  15. Distinctive:

    Follow these at all times:

    line 298
  16. Distinctive:

    When modifying HA test scenarios, consider both SUSE and RHEL code paths.

    line 322
  17. Very specific:

    Every STAF skill operates from within a trusted STAF checkout — a working tree the operator has verified out-of-band as either the official …

    line 392

≈ “Common” is an estimate: at least 1 in 5 of the 1,644 Copilot instructions files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
copilot-instructions.md

SAP Testing Automation Framework - Copilot Instructions

Version: 1.0.2 | License: MIT (Microsoft Corporation) Repository: Azure/sap-automation-qa

Project Identity

This is the SAP Testing Automation Framework -- an open-source orchestration tool for validating SAP deployments on Microsoft Azure. It provides:

  • HA functional testing for SAP HANA (Scale-Up, Scale-Out HSR, Scale-Out Standby) and SAP Central Services (ENSA1/ENSA2) in Pacemaker clusters.
  • Configuration validation for HANA, IBM Db2, SCS, and application instances.
  • Offline validation of HA configurations without live cluster interaction.
  • A FastAPI scheduling service with async job execution, cron-based scheduling, workspace management, and event streaming.
  • Multi-destination telemetry to Azure Log Analytics and Azure Data Explorer (Kusto).
  • A CLI entrypoint (sap_automation_qa.sh) for both direct Ansible execution and API-driven workflows.

Technology Stack

LayerTechnologies
LanguagePython 3.10+ (Docker uses 3.12)
APIFastAPI, uvicorn, Pydantic v2
AutomationAnsible-core 2.17, ansible-runner 2.4, Jinja2
Azureazure-identity, azure-keyvault-secrets, azure-kusto-data/ingest, azure-mgmt-compute/network/loganalytics, azure-storage-blob/queue
SchedulingAPScheduler (CronTrigger)
PersistenceSQLite (WAL mode), file-based log/artifact storage
FrontendReact (port 3000, in development)
Testingpytest, pytest-asyncio (auto mode), pytest-cov, pytest-mock, httpx
Code qualityblack (line-length 100), pylint (>=9.0 score, sphinx docstrings), ansible-lint
CI/CDGitHub Actions (code coverage, ansible-lint, Docker build, CodeQL, Trivy, OSSF Scorecard)
ContainerAzure Linux 3.12 base, multi-stage Docker build, non-root user
Target OSSUSE (crm commands) and RHEL (pcs commands) -- OS-family dispatched

Project Structure

src/
├── api/                    # FastAPI application (routes, middleware, lifespan)
│   ├── app.py              # Entry point: lifespan wires stores, worker, scheduler
│   └── routes/             # health, jobs, schedules, workspaces
├── core/                   # Framework core (no Ansible dependency)
│   ├── execution/          # AnsibleExecutor, JobWorker, SshCredentialProvider
│   ├── models/             # Job, Schedule, SshCredential, TelemetryConfig, Workspace
│   ├── observability/      # StructuredLogger, ObservabilityMiddleware, telemetry handlers
│   ├── services/           # SchedulerService (async background cron loop)
│   └── storage/            # JobStore, ScheduleStore (SQLite WAL)
├── agents/                 # Agent architecture scaffold (not yet implemented)
├── module_utils/           # Shared Python utilities for Ansible modules
│   ├── sap_automation_qa.py  # ABC base for all modules
│   ├── collector.py          # CommandCollector, AzureDataParser (with command sanitization)
│   ├── filesystem_collector.py  # FileSystemCollector (findmnt, df, LVM, ANF, AFS, IMDS)
│   ├── commands.py           # OS-family command constants, DANGEROUS_COMMANDS blocklist
│   ├── enums.py              # TestStatus, TestSeverity, HanaTopology, HanaSRProvider
│   ├── get_cluster_status.py # BaseClusterStatusChecker (template method pattern)
│   ├── get_pcmk_properties.py  # BaseHAClusterValidator (CIB XML validation)
│   └── filter_tests.py      # TestFilter (test group/case selection, extra-vars generation)
├── modules/                # Custom Ansible modules (AnsibleModule pattern)
│   ├── configuration_check_module.py  # Parallel config checks via ThreadPoolExecutor
│   ├── get_cluster_status_db.py       # HANA cluster status (scale-up + scale-out HSR)
│   ├── get_cluster_status_scs.py      # SCS cluster status
│   ├── get_pcmk_properties_db.py      # DB pacemaker CIB validation
│   ├── get_pcmk_properties_scs.py     # SCS pacemaker CIB validation
│   ├── get_azure_lb.py               # Azure Load Balancer validation (MSI auth)
│   ├── send_telemetry_data.py         # ADX/Log Analytics telemetry sender (batch)
│   ├── log_parser.py                  # /var/log/messages parser with time-range filtering
│   ├── render_html_report.py          # Jinja2 HTML report generation
│   ├── check_indexserver.py           # HANA indexserver config check
│   ├── get_package_list.py            # SAP cluster package facts
│   ├── filesystem_freeze.py           # ANF filesystem freeze/unfreeze
│   └── location_constraints.py        # Pacemaker constraint removal
├── roles/                  # Ansible roles (task YAML files)
│   ├── ha_db_hana/tasks/   # 15 HANA HA scenarios
│   ├── ha_scs/tasks/       # 14 SCS HA scenarios
│   ├── configuration_checks/  # Config validation tasks + vars
│   └── misc/tasks/         # 13 shared tasks (pre/post validation, telemetry, cluster report)
├── playbook_00_*.yml       # Top-level playbooks (config checks, DB HA, SCS HA)
├── playbook_01_*.yml       # Offline HA tests
├── templates/              # Jinja2 templates, Azure pipeline template
└── vars/                   # Framework configuration (input-api.yaml)

tests/                      # pytest test suite (85% coverage enforced)
├── api/                    # FastAPI endpoint tests (httpx AsyncClient)
├── core/                   # Execution, models, storage, observability tests
├── modules/                # All 13 Ansible module tests
├── module_utils/           # Utility class tests
└── roles/                  # Role integration tests (RolesTestingBase + ansible_runner)

scripts/                    # Shell CLI and setup scripts
├── sap_automation_qa.sh    # Main CLI: API subcommands + direct Ansible execution
├── api_utils.sh            # REST API CLI wrapper (CRUD, formatting)
├── setup.sh                # Python venv, pip, Azure CLI installation
├── container_setup.sh      # Docker/compose management
├── utils.sh                # Colored logging, distro detection, package install
└── version_check.sh        # GitHub version check with semver comparison

deploy/                     # Docker deployment
├── Dockerfile              # Multi-stage (Azure Linux 3.12, non-root, healthcheck)
└── docker-compose.yml      # Single service, SQLite volume, WORKSPACES bind mount

client/                     # React frontend (in development, port 3000)
WORKSPACES/                 # System-specific configuration and credentials
docs/                       # Architecture, HA guides, setup, telemetry, changelog

HA Test Scenarios

HANA Database HA (ha_db_hana)

ScenarioTask File
HA configuration validation (online/offline)ha-config.yml, ha-config-offline.yml
Azure Load Balancer validationazure-lb.yml
Resource migrationresource-migration.yml
Primary node crash / killprimary-node-crash.yml, primary-node-kill.yml
Primary indexserver crash / echo-bprimary-crash-index.yml, primary-echo-b.yml
Secondary node kill / indexserver crash / echo-bsecondary-node-kill.yml, secondary-crash-index.yml, secondary-echo-b.yml
Network / HANA-shared isolationblock-network.yml, block-hana-shared.yml
Filesystem freeze (ANF)fs-freeze.yml
SBD fencingsbd-fencing.yml

SAP Central Services HA (ha_scs)

ScenarioTask File
HA configuration validation (online/offline)ha-config.yml, ha-config-offline.yml
Azure Load Balancer / SAP control validationazure-lb.yml, sapcontrol-config.yml
ASCS migration / node crashascs-migration.yml, ascs-node-crash.yml
Kill message/enqueue/replication serverkill-message-server.yml, kill-enqueue-server.yml, kill-enqueue-replication.yml
Kill SAPStartSrv processkill-sapstartsrv-process.yml
Manual restart / failover to nodemanual-restart.yml, ha-failover-to-node.yml
Network isolationblock-network.yml

HANA Topologies Supported

  • Scale-Up -- classic two-node HSR (default)
  • Scale-Out HSR -- multi-node with system replication
  • Scale-Out Standby -- multi-node with standby nodes

HANA SR Providers

  • SAPHanaSR -- classic provider
  • SAPHanaSR-angi -- next-generation provider (different resource ID discovery)

Key Design Patterns

Follow these established patterns when contributing:

PatternImplementationLocation
Protocol (structural typing)ExecutorProtocol for dependency inversioncore/execution/executor.py
ABC + Template MethodSapAutomationQA, BaseClusterStatusChecker.run() with abstract hooksmodule_utils/
State MachineJob model with explicit transitions (start(), complete(), fail(), cancel())core/models/job.py
RepositoryJobStore, ScheduleStore -- SQLite-backed, clean interfacecore/storage/
Factory + SingletonLoggerFactory.get_logger(), ObservabilityContextManagercore/observability/
Context Manager (scoped)ObservabilityScope, ExecutionScope -- auto context push/popcore/observability/context.py
ContextVar (async-safe)ContextVarProvider for thread-safe context propagation + correlation IDscore/observability/context.py
StrategyCollector hierarchy -- CommandCollector, AzureDataParser, FileSystemCollectormodule_utils/collector.py
Module-level DIAPI routes wired via set_job_store() etc. during FastAPI lifespanapi/routes/
Async worker + event queueJobWorker with asyncio.create_task() and SSE event streamingcore/execution/worker.py
Background batchingTelemetry handlers use threaded queues for async batch deliverycore/observability/telemetry_handlers.py
Workspace lockingOne active job per workspace enforced in JobWorker.submit_job()core/execution/worker.py
Immutable value objectsContextData, TelemetryConfig -- frozen dataclassescore/models/, core/observability/
LifespanFastAPI asynccontextmanager for service initialization/teardownapi/app.py
OS-family dispatchingCommands differ for SUSE (crm) vs RHEL (pcs) via filtered command mapsmodule_utils/commands.py
Command sanitizationDANGEROUS_COMMANDS blocklist in CommandCollectormodule_utils/collector.py

API Reference (Quick)

MethodEndpointPurpose
GET/healthzHealth check
GET/api/v1/jobsList jobs (filter: workspace, status, active)
POST/api/v1/jobsCreate and submit a job
GET/api/v1/jobs/{id}Get job details
POST/api/v1/jobs/{id}/cancelCancel a running job
GET/api/v1/jobs/{id}/eventsSSE event stream
GET/api/v1/jobs/{id}/logPlain-text Ansible log (?tail=N)
POST/api/v1/schedulesCreate cron schedule
GET/api/v1/schedulesList schedules
PATCH/api/v1/schedules/{id}Update schedule
DELETE/api/v1/schedules/{id}Delete schedule
POST/api/v1/schedules/{id}/triggerTrigger schedule immediately
GET/api/v1/workspacesList available workspaces

Coding Standards

Python

  • Formatter: black with line_length = 100.
  • Linter: pylint with minimum score 9.0; sphinx docstring convention.
  • Typing: Strict type hints on all public signatures. Use Protocol for interfaces.
  • Docstrings: Required on every public class, method, and function (params, returns, raises).
  • Max constraints: max-args=5, max-line-length=100, max-module-lines=1000, max-nested-blocks=3.
  • Async: Use asyncio_mode = "auto" in pytest; prefer native async/await over threads.
  • Imports: Ansible modules use dual-import fallback (from ansible.module_utils... with from src.module_utils... in except).

Ansible

  • Lint: ansible-lint enforced in CI.
  • Task naming: Every task MUST have a descriptive name: field.
  • Shell tasks: Always use set -o pipefail, executable: /bin/bash, and changed_when: false for read-only commands.
  • Become: Explicit become: true / become_user: root where required.
  • Error handling: Use block/rescue/always patterns; set failed_when explicitly.
  • OS dispatching: Use Jinja2 filters on commands list with ansible_os_family | upper.

Testing

  • Coverage: 85% minimum enforced (--cov-fail-under=85).
  • API tests: Use httpx.AsyncClient with FastAPI test client pattern.
  • Core tests: Use tmp_path, mock subprocess.Popen, test state machines.
  • Module tests: Mock AnsibleModule; test command execution, XML parsing, edge cases.
  • Role tests: Extend RolesTestingBase; use ansible_runner with file-based mock data.
  • Fixtures: Shared via conftest.py; avoid test-to-test coupling.

Shell Scripts

  • Style: Consistent function naming (_prefixed for internal), colored logging helpers.
  • Safety: Check tool availability (command -v), validate inputs, provide clear error messages.

Enterprise-Grade Defaults (mandatory)

All code must meet these non-negotiable standards:

Production Readiness

  • Safe defaults, clear failure modes, strict typing, deterministic behavior.
  • Typed exception hierarchy (ExecutionError, WorkspaceLockError, JobNotFoundError, etc.).
  • Pydantic models for API boundaries; frozen dataclasses for internal value objects.

Observability

  • Structured logging via StructuredLogger -- JSON for production, color-coded console for dev.
  • Correlation IDs (X-Correlation-ID) propagated through all layers via ContextVar.
  • Event-based logging: ServiceEvent and ExecutionEvent with automatic context population.
  • RotatingFileHandler (10 MB, 5 backups) for persistent log storage.
  • Multi-destination telemetry: Azure Log Analytics (shared key or MSI) + Azure Data Explorer (Kusto).

Resilience

  • Timeouts on subprocess calls (execute_command_subprocess with configurable timeout).
  • Workspace locking (one active job per workspace; prevents concurrent execution).
  • Crash recovery on worker startup (detects and marks orphaned running jobs).
  • Graceful job cancellation via subprocess signal handling.
  • SSH credential provisioning with auto-detect (Key Vault MSI or local workspace files).

Security

  • Least privilege: non-root Docker user (appuser:1000).
  • No plaintext secrets: Azure Key Vault integration for SSH credentials.
  • Input validation: Pydantic models, command sanitization (DANGEROUS_COMMANDS blocklist).
  • CORS configuration via environment variable (CORS_ORIGINS).
  • Hardened CI: step-security/harden-runner, pinned action SHAs, Trivy scanning, OSSF Scorecard.

Performance

  • SQLite WAL mode for concurrent read/write.
  • Indexed queries on workspace_id, status, schedule_id, created_at.
  • Threaded background batching for telemetry delivery.
  • ThreadPoolExecutor for parallel configuration checks.
  • Async job execution with asyncio.create_task().

Object-Oriented Design Principles

Apply these consistently in all contributions:

  • Favor well-named classes with Single Responsibility; keep modules under 1000 lines.
  • Use dependency inversion: define interfaces via Protocol or ABC; inject collaborators.
  • Encapsulate external systems (Azure, OS, Ansible runner) behind ports/adapters.
  • Model states and workflows as explicit types (JobStatus enum, Job state machine).
  • Avoid "stringly typed" protocols -- use enums (TestStatus, HanaTopology, AuthType).
  • Provide seams for testing via interfaces and small, mockable collaborators.
  • Prefer composition over inheritance; use ABCs only for true "is-a" hierarchies.

Coding Partnership Rules

Follow these at all times:

  1. Be critical, not agreeable
    • Flag missing context, risky designs, and incorrect SAP/Azure assumptions.
    • Provide counterpoints and alternatives -- especially for cluster behavior edge cases.
  2. Apply best design principles
    • SOLID, DRY, KISS, clear separation of concerns.
    • Maintainability > cleverness. Small units > god-objects.
    • Production SAP constraints: reliability, observability, rollback capability, operability.
  3. Cover edge cases thoroughly
    • Empty/invalid inputs, boundary conditions, transient Azure failures.
    • Cluster-specific: partial outages, quorum loss, fencing misconfiguration, split-brain, storage throttling, DNS/MI/IMDS hiccups, SAPHanaSR vs SAPHanaSR-angi differences.
  4. Output style
    • Concise, minimal yet complete. Black-formatted, pylint-clean, <=100-char lines.
    • Include types, docstrings, explicit exceptions. Show tests when relevant.
    • Ansible tasks: proper name, become, changed_when, failed_when, block/rescue.
  5. Collaboration stance
    • Act as a Principal software reviewer. Push back on weak requests or ambiguous scope.
    • Offer 2-3 viable designs when trade-offs exist, with crisp pros/cons.
    • When modifying HA test scenarios, consider both SUSE and RHEL code paths.

File-Specific Guidance

When editing...Remember to...
src/api/routes/*.pyUse dependency injection via module-level setters; return Pydantic models; document endpoints
src/core/models/*.pyValidate state transitions; use frozen dataclasses for value objects; include is_terminal helpers
src/core/execution/worker.pyRespect workspace locking; handle crash recovery; propagate events via AsyncGenerator
src/core/observability/*.pyMaintain correlation ID propagation; use StructuredLogger not print/raw logging
src/module_utils/*.pyExtend ABCs properly; keep command constants OS-family-aware; sanitize inputs
src/modules/*.pyFollow AnsibleModule + DOCUMENTATION string pattern; return standardized result dicts
src/roles/*/tasks/*.ymlUse block/rescue/always; include test-case-setup.yml; post telemetry; handle both OS families
tests/Maintain 85% coverage; use conftest.py fixtures; mock external deps; test failure paths
scripts/*.shUse _prefixed internal functions; validate tool availability; provide colored output
deploy/Keep non-root; pin base images; test healthcheck; preserve volume mounts

CI/CD Pipeline

WorkflowTriggerChecks
Code Coveragepush, PRpytest --cov-fail-under=85, pylint --fail-under=9, black --check
Ansible Lintpush, PRansible-lint src/
Docker Buildpush (main/dev), PRMulti-stage build; optional ACR push via OIDC
CodeQLpush, PR, weeklyJavaScript + Python security analysis
TrivyPR, merge_groupFilesystem vulnerability scanning
Dependency ReviewPRDependency vulnerability review
OSSF Scorecardpush, PR, weeklySupply-chain security scoring

Common Workflows

Running tests locally

source .venv/bin/activate
pytest tests/ --cov=src --cov-fail-under=85 -v

Starting the full stack (API + React)

# Backend: uvicorn on port 8000
PYTHONPATH=src uvicorn api.app:app --reload --host 0.0.0.0 --port 8000

# Frontend: React on port 3000
cd client && npm start

Running a direct Ansible test

./scripts/sap_automation_qa.sh --test_groups DatabaseHighAvailability --test_cases ha-config

Docker deployment

cd deploy && docker compose up -d

Locate Framework

Every STAF skill operates from within a trusted STAF checkout — a working tree the operator has verified out-of-band as either the official upstream (https://github.com/Azure/sap-automation-qa.git) or a fork of it, at a specific revision, with the framework marker ./scripts/sap_automation_qa.sh present. The operator must have verified both the source (upstream URL or fork URL) and the revision through a trusted out-of-band channel, and must have cd-ed into that directory.

Skills never auto-adopt, auto-clone, or auto-execute against any tree. Trust cannot be inferred from remote URL, git status, or filesystem structure; a pre-existing tree can carry attacker-controlled config (for example, core.fsmonitor pointing at a hook binary) that would execute the moment any git command touched it. Only the operator can confirm the tree is trusted.

The setup-guide skill is the single owner of the setup workflow — how the operator verifies an existing checkout or manually creates a new one. Every other skill (test-runner, test-result-analyzer, workspace-creator, workspace-validator) hands off to setup-guide when the trusted-checkout state is not confirmed and does not carry its own setup logic.

Copilot CLI Skills

This repo includes skills in skills/ that provide guided workflows. Skills activate automatically based on prompt context, or can be invoked directly with the / prefix (e.g., /test-runner).

SkillWhen to Use
/setup-guideSetup, installation, Docker deployment, vars.yaml configuration
/workspace-validatorValidate workspace config, troubleshoot workspace issues
/workspace-creatorCreate new workspace, onboard SAP system
/test-runnerRun tests, execute configuration checks, start HA tests
/test-result-analyzerAnalyze test failures, interpret results, find root causes

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.