apm audit
Synopsis
Section titled “Synopsis”apm audit [PACKAGE] [OPTIONS]Description
Section titled “Description”apm audit is the explicit security and integrity tool. It runs in two modes:
- Content scan mode (default). Discovers recognized deployed primitives and checks applicable prompt content for hidden Unicode, including untracked primitives and recorded files outside currently selected target directories. It replays the install pipeline into a scratch tree to detect drift (hand-edits to deployed files, missing integrations, orphaned files vs the lockfile). Can also remediate regular prompt documents with
--stripor scan an arbitrary file with--file. - CI gate mode (
--ci). Runs lockfile consistency checks plus drift in machine-readable form (text, JSON, or SARIF) suitable for branch-protection gates. In a project checkout withapm.ymlandapm.lock.yamlbut noapm_modules/, CI mode prepares a lock-pinned scratch install forskill-subset-consistency,config-consistency, and drift without mutating the checkout. Local dependencies must remain available at their declared paths. Windows long and native 8.3 spellings of the same project use the same project scope. Auto-discovers org policy from your project’s git remote unless--no-policyis set.
Global audit also checks resolved external deployment roots such as
HERMES_HOME, CLAUDE_CONFIG_DIR and COPILOT_HOME. Default audit compares tracked files in
those roots for drift. apm audit --ci also scans target-governed external
subtrees for content integrity. Neither mode modifies those roots.
Auditing the user metadata workspace (~/.apm) still requires its installed
apm_modules/ when apm.lock.yaml records packages or local bundle staging;
if missing, restore it with apm install --global. A user lockfile with only MCP/LSP servers or your
own ~/.apm content needs no apm_modules/, so apm audit --ci passes after
apm update -g as it does after apm install -g. Project scratch replay does
not enable cold replay for global installations.
Scratch replay preserves each scope’s installed-source layout so relative
links, including Kiro prompt links, compare against their deployed equivalents.
Both modes also enforce the lockfile’s canonical deployment ownership; see Deployment-owner integrity.
Drift reports distinguish a differing file that no lockfile entry claims
(unmanaged-conflict: a skipped user-authored file, a refused skill, or a
case-only name variant) from an edited managed file (modified). Ordinary
reinstall skips or refuses the former and never offers apm export-patch for
it: rename the local file or correct the dependency’s existing skill/target
selection first. Audit does not adopt, overwrite, or delete either file.
JSON retains the finding’s path and kind; SARIF uses
apm/drift/unmanaged-conflict with error severity.
When modified findings belong to remote (non-local) dependencies, the text output adds a hint
such as [i] 2 local edit(s) to managed files; run 'apm export-patch' to export them as upstream patches before the next install overwrites them. See
apm export-patch. A modified file whose bytes still
match its locked hash is not a local edit: this APM version renders it
differently. Audit reports it with a hint to run apm install and commit the
result, not with the export-patch hint.
Replay and coverage use the current apm.yml target declaration when present,
otherwise the concrete target identities recorded by install. An unrelated
.github/workflows/ file does not add a Copilot deployment to a recorded
Grok Cloud installation, and .grok/ alone does not relabel it as Grok Build.
Older lockfiles without a recorded deployments section retain directory
discovery; identities inferred from legacy file paths do not narrow it.
The saved target config value (apm config set target) is an
install/update default, not a request to retarget an existing installation
during audit.
Experimental targets remain opt-in. If a selected target’s experiment is
disabled, audit exits with code 3 and an enable instruction on stderr, such
as apm experimental enable grok-cloud, instead of silently skipping verification.
Configuration errors do not produce a JSON audit report.
Changing the manifest can still expose missing requested output; the existing
drift exit rules apply. Audit does not install, repair, or
rewrite that state. Retained paths recorded under a previous target remain
eligible for CI presence and recorded-hash checks,
subject to those checks’ existing exclusions and hash baselines, even when
that target is no longer selected for replay.
For a native Agent Plugin installed with the copilot target, replay uses the
same package interpretation as install. A plugin does not need an accompanying
apm.yml; reinstalling and auditing a clean plugin remains supported. Select
targets in the project’s apm.yml (targets: [copilot]), not an audit
--target option. Invalid native manifests fail replay rather than falling back
to legacy conversion. Audit does not modify plugin sources or live harness state.
Native plugins stay whole, rather than becoming loose managed skills. Audit
checks both the apm_modules/ source and the deployed copy under
.agents/plugins/<plugin>/ against the lockfile’s native_plugin fingerprint.
At project scope that fingerprint covers paths and bytes only, so a checkout
without exec bits (Windows, core.fileMode=false) still passes. Replay
compares admitted local plugins with a scratch copy of their original source.
Modified or missing files fail audit; run apm install to restore them. Remote
native plugins use their recorded package content hash, including in cold-cache
CI; a missing hash requires reinstalling to establish that baseline. Settings
files are not covered by this content comparison. See
Native plugins.
This is the explicit power tool. Built-in protection against critical Unicode findings already runs automatically in apm install, apm compile, and apm unpack; you do not need to call apm audit to be safe by default. See Drift and secure by default for the consumer-side overview and Enforce in CI for the gating workflow. For marketplace plugin transitive-dependency pinning, see apm marketplace audit.
PACKAGE, when supplied, scans one installed dependency, so only files recorded for that package are included. Pass the dependency key from apm.lock.yaml (owner/repo for GitHub, host/owner/repo for other hosts) or any form apm uninstall accepts, such as https://github.com/owner/repo, github.com/owner/repo, owner/repo#ref, plugin@marketplace or the _local/<name> key apm deps list prints; APM selects it offline, exactly as uninstall does, and normalizes it to the lockfile key. A package that matches no installed dependency fails with exit 1, so a typo in a CI gate cannot pass silently:
[x] Package 'test/typo-pkg' is not installed: no matching dependency in apm.lock.yaml. Run 'apm deps list' to see installed packages.Omit PACKAGE to scan deployed files across the whole project. See Baseline CI checks for the exact lockfile, target-directory, symlink, and .apm/ scope boundaries.
Options
Section titled “Options”Content scan
Section titled “Content scan”| Flag | Default | Description |
|---|---|---|
--file PATH | unset | Scan an arbitrary file instead of installed packages. Bypasses drift detection. |
--strip | off | Remove critical and warning severity characters in place. Preserves emoji and ZWJ inside emoji sequences. |
--dry-run | off | Preview what --strip would remove without modifying files. |
--no-drift | off | Skip the install-replay drift check (reduces coverage). Mutually exclusive with --strip and --file. |
--verbose, -v | off | Show info-level findings and per-file detail. No effect in --ci mode. |
External scanners (experimental)
Section titled “External scanners (experimental)”Gated by the external-scanners experimental flag (apm experimental enable external-scanners). Folds findings from any SARIF 2.1.0 scanner into the report. CLI-driven and install-method-neutral — no pip extra; works with the APM binary. See External scanners.
| Flag | Default | Description |
|---|---|---|
--external NAME | unset | Ingest findings from an external SARIF-native scanner (repeatable). Names: skillspector (invokes the CLI on PATH), sarif (ingests a file via --external-sarif). Cannot be combined with --strip, --dry-run, or --ci. |
--external-sarif PATH | unset | SARIF file to ingest for --external sarif. |
--external-llm / --no-external-llm | adapter default | Force a scanner’s LLM-powered analysis on or off for this run (overrides config). SkillSpector default is offline --no-llm. LLM mode makes outbound API calls and needs OPENAI_API_KEY or NVIDIA_INFERENCE_KEY; missing the key fails closed. Requires --external. |
--external-args TEXT | unset | Extra scanner CLI flags as a single shlex-split string (e.g. "--model gpt-4o"). Allowlist-validated per adapter; secret-looking or out-of-cwd tokens are rejected fail-closed. Overrides config args. Requires --external. |
When LLM mode is active APM prints a [!] egress banner before the scan noting that outbound API calls will be made. --external-llm / --external-args used without --external <name> raise a usage error (exit 2).
Output
Section titled “Output”| Flag | Default | Description |
|---|---|---|
--format, -f text|json|sarif|markdown | text | Output format. sarif targets GitHub Code Scanning. markdown is for GitHub step summaries and is not allowed with --ci. |
--output, -o PATH | stdout | Write the report to a file. Format is auto-detected from extension (.sarif, .sarif.json, .json, .md) when --format is omitted. |
-f json in default (non---ci) mode includes a top-level "passed"
boolean (exit_code == 0), alongside the existing summary and finding
list. Deployment-owner integrity findings render in every format —
text, JSON, SARIF, and markdown — as a deployment-owner category entry
naming the locator, its invalid owner(s), and the remediation.
Non-CI JSON also includes coverage.complete and coverage.primitives.
Each entry identifies its file, target, primitive kind, structured pointer,
file-level tracked status and prompt-check status (checked,
not-applicable, or incomplete). Structured findings include their prompt
pointer. JSON uses coordinate_space: decoded-prompt, decoded_line and
decoded_column for structured values instead of physical line/column;
text and Markdown label these offsets as decoded. SARIF omits a physical region.
CI JSON stores inventory in content-integrity.primitive_coverage, separate
from violation details. SARIF retains it in invocation primitiveCoverage
properties, and text shows discovered hooks even when all checks pass.
CI content_findings identifies each critical finding’s actual file and prompt
pointer separately from inventory; SARIF uses that file, not the lockfile.
Automatic --strip also refuses user-scoped prompt files when auditing from
~/.apm, even though the traversal root is the home directory. The explicit
single-file --file operation is unchanged.
CI gate
Section titled “CI gate”| Flag | Default | Description |
|---|---|---|
--ci | off | Run lockfile consistency checks and drift as a CI gate. Run it from the project root: without an apm.yml in the current directory it fails manifest-missing (exit 1) instead of passing an empty audit. Cannot be combined with --strip, --dry-run, --file, or PACKAGE. |
--policy SOURCE | auto | Policy source for --ci. Accepts org (auto-discover from the project’s git remote), owner/repo, an https:// URL, or a local file path. A path, URL, or owner/repo that cannot be loaded (missing, unreachable, malformed) fails the gate with exit 1; org keeps the discovery default (warn unless policy.fetch_failure_default: block). Without --ci it is ignored with a warning. Under enforcement: warn, violating checks pass (exit 0) but show [!] with the dependencies or servers they name. |
--no-policy | off | Skip policy discovery and enforcement. Overridden when --policy is passed explicitly. APM_POLICY_DISABLE=1 also disables enforcement, but it is not overridden by --policy: audit prints a [!] warning that the explicit policy was not enforced and reports policy.enforced: false. |
--no-cache | off | Force a fresh policy fetch (skip the policy cache). Only relevant with policy discovery active. |
--no-fail-fast | off | Run every check even after the first failure, for a full diagnostic report. |
Examples
Section titled “Examples”Default audit (content scan plus drift)
Section titled “Default audit (content scan plus drift)”apm auditScan a specific installed package
Section titled “Scan a specific installed package”apm audit owner/repoScan an arbitrary file outside APM
Section titled “Scan an arbitrary file outside APM”apm audit --file .cursorrulesRemediate findings
Section titled “Remediate findings”# Preview what --strip would removeapm audit --strip --dry-run
# Strip critical and warning severity characters in placeapm audit --strip
# In CI, remediate first and then rerun the gateapm audit --stripapm audit --ci --no-driftReports
Section titled “Reports”# SARIF to stdout (for GitHub Code Scanning upload)apm audit -f sarif
# JSON to a fileapm audit -f json -o results.json
# Markdown for a GitHub Actions step summaryapm audit -f markdown -o "$GITHUB_STEP_SUMMARY"
# Auto-detect format from extensionapm audit -o report.sarifExternal scanners
Section titled “External scanners”# Invoke SkillSpector on PATH (offline by default)apm audit --external skillspector
# Opt into LLM-powered analysis (needs an API key; makes network calls)apm audit --external skillspector --external-llm
# Pass allowlisted scanner flagsapm audit --external skillspector --external-args "--model gpt-4o"
# Ingest a SARIF file from any scannerapm audit --external sarif --external-sarif report.sarifCI gate
Section titled “CI gate”# Default CI gate (auto-discovers org policy)apm audit --ci
# CI gate, baseline checks only (no policy)apm audit --ci --no-policy
# CI gate with an explicit policy sourceapm audit --ci --policy orgapm audit --ci --policy ./apm-policy.yml
# Full diagnostic report (don't stop at first failure)apm audit --ci --no-fail-fast
# CI gate as JSON or SARIFapm audit --ci -f jsonapm audit --ci -f sarif -o audit.sarifFor the full workflow, see Enforce in CI.
Behavior
Section titled “Behavior”Discovery and prompt coverage
Section titled “Discovery and prompt coverage”Whole-project audit discovers recognized primitives even without a lockfile.
Discovery is not a safety verdict: command-only hooks are listed as
discovered/untracked when appropriate, without failing the prompt check.
Each line names its ownership evidence: recorded-file (the lockfile claims
the file), apm-owned-entry (APM merged that entry into a shared hook config
such as .claude/settings.json), or untracked. A JSON field renders as
<file> at <pointer>. Hash and ownership checks remain independent.
User-scope replay preserves the ~/.apm/apm_modules/ layout in relative
asset links, so intact global prompts do not report drift from a scratch-path difference.
The target registry supplies the following project patterns. Patterns are
recursive inside their named directory; skill entry points are SKILL.md,
not every file in a skill bundle.
| Target | Prompt documents/fields | Hook definitions |
|---|---|---|
| Copilot | .github/instructions/*.instructions.md, prompts/*.prompt.md, agents/*.agent.md, .github/copilot-instructions.md; shared skills | .github/hooks/*.json; commands are non-prompt; flat sessionStart prompt handlers’ prompt field (prompt handlers on other events are unsupported) |
| Claude | .claude/rules/*.md, agents/*.md, commands/*.md, skills/**/SKILL.md | .claude/hooks/*.json, .claude/settings.json; nested prompt/agent handlers’ prompt field |
| Cursor | .cursor/rules/*.mdc, agents/*.md, commands/*.md; shared skills | .cursor/hooks/*.json, .cursor/hooks.json; flat command handlers and prompt handlers’ prompt field; nested handlers are unsupported |
| Kiro | .kiro/steering/*.md, agents/*.md, prompts/*.md, skills/**/SKILL.md | .kiro/hooks/*.json; v1 hooks[].action.prompt for agent actions |
| Gemini | .gemini/commands/*.toml: prompt; shared skills | .gemini/hooks/*.json, .gemini/settings.json; nested command handlers |
| Codex | .codex/agents/*.toml: developer_instructions; shared skills | .codex/hooks.json; nested command handlers |
| Antigravity | .agents/rules/*.md, skills | .agents/hooks.json; named containers, nested tool events and flat other events |
| Windsurf | .windsurf/rules/*.md, workflows/*.md; shared skills | .windsurf/hooks.json; flat or APM-preserved nested command handlers |
| OpenCode | .opencode/agents/*.md, commands/*.md; shared skills | None |
| Grok Build / Cloud | .grok/skills/**/SKILL.md; Build also rules/*.md, agents/*.md, commands/*.md | None |
| Agent Skills, OpenClaw, Hermes | .agents/skills/**/SKILL.md | None |
| Copilot Cowork | **/SKILL.md directly under the resolved managed skills root | None |
| Copilot App | Deployed workflow prompts are SQLite rows, not filesystem primitives; this scan does not cover them | None |
Directory shorthand in a row stays under that row’s target root. Shared skills
use .agents/skills/**/SKILL.md. A target’s generated context files and
compile-family root file (AGENTS.md, CLAUDE.md, or GEMINI.md) are also
recognized. Global audit uses scope-resolved profiles instead: for example
Copilot’s root becomes ~/.copilot with per-file modular
instructions/*.instructions.md (mirroring the project-scope layout; the
legacy concatenated copilot-instructions.md is not tracked at user scope),
and Claude/Hermes respect their configured external roots. Primitives
unsupported in user scope are not discovered there.
Only documented prompt fields are decoded and checked in structured formats.
Command strings, referenced scripts, unrelated settings, ownership sidecars,
transcripts, history and caches are excluded from prompt scanning; hooks are
never executed. A recorded script remains non-prompt. A hook bundle’s
package.json holding only {"type": "commonjs"} or {"type": "module"} is
Node module metadata, not a hook definition, while it still matches the hash
apm install recorded for it; an edited or unrecorded package.json, or any
other .json file under a hooks directory, is still read as one. Recognized unreadable,
malformed or unsupported content produces incomplete coverage and exit 1,
not a malicious-content finding or a clean result. This also applies with
--no-drift and --no-policy.
--strip refuses automatic remediation when findings involve structured/shared
configuration or external-root content, or coverage is incomplete; it leaves
all files unchanged. Review those files manually. Explicit --file retains
its user-directed whole-file scan and remediation behavior.
Severity levels (content scan)
Section titled “Severity levels (content scan)”| Severity | Examples | Effect |
|---|---|---|
| Critical | Tag characters (U+E0001-E007F), bidi overrides (U+202A-E, U+2066-9), variation selectors 17-256 (U+E0100-E01EF, the Glassworm vector) | Exit 1. Removed by --strip. Blocks apm install / apm compile / apm unpack by default. |
| Warning | Zero-width spaces and joiners (U+200B-D), variation selectors 1-15 (U+FE00-FE0E), bidi marks (U+200E-F, U+061C), invisible operators (U+2061-4), annotation markers (U+FFF9-B), deprecated formatting (U+206A-F), soft hyphen (U+00AD), mid-file BOM | Exit 2 if no critical findings. Removed by --strip. |
| Info | Non-breaking and unusual whitespace, emoji presentation selector (U+FE0F), ZWJ between emoji characters | Exit 0. Shown only with --verbose. Preserved by --strip. |
Drift detection
Section titled “Drift detection”The default audit replays the install pipeline into a scratch tree and diffs
the result against the working tree. It catches hand-edits, missing
integrations, orphaned files, and unrecorded files. unrecorded applies when
replay produced the same normalized bytes as the project but no exact or
directory deployed_files claim covers the path. For shared merge-hook
targets, audit compares only APM-owned hook entries; user-owned hooks do not
create drift. The APM-owned sidecar is compared as JSON, ignoring object-key
order and formatting while retaining every field and list order. Changed
commands, ownership markers, or execution order still report modified, as
do malformed JSON, duplicate keys, and non-JSON constants (NaN, Infinity,
-Infinity). Install writes APM’s hook entries in one order, sorted by
owning package in the slots they hold, whatever order the packages were
added, so incremental apm install <pkg> runs match a full install; your
own entries and events keep their places. unrecorded findings fail
--ci; run apm install, then commit the regenerated apm.lock.yaml.
Drift is whole-project only; --file and explicit PACKAGE runs skip it.
Use --no-drift to opt out with reduced coverage. In bare apm audit, drift
findings are advisory by default and render as [!] Drift detected. With
security.audit.fail_on_drift: true, a failed drift check (including one that
could not run) promotes the audit to exit 1 and drift renders as [x]. An advisory cache-miss skip remains non-failing
(see Exit codes).
When drift fails and the org policy cannot be resolved, the audit says so:
[x] Org policy could not be resolved; fail_on_drift could not be applied: <cause>
with exit 1 when the project requires the policy (policy.fetch_failure_default: block).
Some outcomes always exit 1, even under warn: a rejected inheritance chain
(cycle, cross-host extends, or too deep), a policy hash mismatch, and an
ambiguous git remote. Any other unresolved policy prints a [!] notice and
drift stays advisory.
Bare apm audit keeps replay cache-only, so a cache miss produces an
informational skip. apm audit --ci instead self-hydrates one lock-pinned
scratch replay through install/audit_replay.py; materialization failures
fail closed without mutating the checkout. Replay fetches each Git dependency
over the transport its declaring apm.yml states, as install does: a
git@host:... or ssh:// dependency replays over SSH, and shorthand follows
the usual transport selection.
Missing apm_modules link targets
Section titled “Missing apm_modules link targets”In text output, a deployed file that links into apm_modules/ at a missing target
(for example after a fresh clone) gets one warning naming the file, the target and
the remedy, apm install. It does not change the exit code.
Deployment-owner integrity
Section titled “Deployment-owner integrity”Before content scanning or drift, both modes validate the lockfile’s
canonical deployments rows: every owners entry and the active_owner
must resolve to a current lock dependency key, the workspace self-owner
(.), or local-bundle. A stale reference — typically left behind when a
dependency was removed without running apm prune — is a hard failure,
not drift: it always exits 1, in bare apm audit and --ci alike, and
is reported under the deployment-ledger-owners check ID in --ci output.
The finding names the owning locator and its invalid owner(s) with one
remediation: Run 'apm prune' to repair the invalid deployment ownership records, then rerun 'apm audit'. --strip refuses to
modify content while any owner reference is invalid. Stale owner rows never
authorize deleting files — only apm prune reconciles them, and only ever
as metadata repair; see apm prune.
CI checks (--ci)
Section titled “CI checks (--ci)”--ci runs the baseline lockfile consistency checks defined in src/apm_cli/policy/ci_checks.py: lockfile presence, canonical deployment-owner integrity (deployment-ledger-owners), ref consistency, deployed-files presence, no orphaned packages, skill-subset consistency, MCP config consistency, content integrity, and an advisory includes consent check. A lockfile is required when apm.yml declares APM or MCP dependencies. For an MCP-only project, normal apm install creates or repairs the resolved MCP lock state; frozen install fails without writing when that state is missing or stale. Content integrity scans hidden Unicode across the whole-project deployed-file scope and checks SHA-256 drift only where the lockfile provides a baseline. Drift replay runs alongside and contributes to the exit code unless --no-drift is set; --no-drift never disables hidden-Unicode scanning. On a cold cache, CI mode self-hydrates a scratch install from the lockfile pins instead of reporting a green skip, so setup-only CI can still catch stale committed deployed files without rewriting the checkout. Audit also reports unrecorded drift when replay produces governed files that no lockfile entry claims. Missing gitignored deployed outputs do not fail deployed-files-present; audit-only CI can pass without them, but lacks deployed-byte integrity and drift coverage when no outputs are committed. Use full-install CI when those outputs need to be materialized. With policy discovery active, declared policy rules are evaluated against the resolved manifest. See Baseline CI checks for the full reference.
Mutual exclusions
Section titled “Mutual exclusions”--no-driftcannot be combined with--stripor--file.--cicannot be combined with--strip,--dry-run,--file, orPACKAGE.--cidoes not support--format markdown.--format json,sariformarkdown(including a format inferred from--output) cannot be combined with--stripor--dry-run.--externalcannot be combined with--strip,--dry-run, or--ci;--external-sarifrequires--external sarif;--external-llm/--no-external-llmand--external-argsrequire--external.
Exit codes
Section titled “Exit codes”Content scan mode
Section titled “Content scan mode”| Code | Meaning |
|---|---|
0 | Clean, info-only findings, advisory drift without security.audit.fail_on_drift, an advisory cache-miss skip, or successful --strip. |
1 | Critical findings, PACKAGE not installed, incomplete primitive coverage (including unreadable parents), refused --strip remediation, invalid canonical deployment-owner references, drift-check failures promoted by security.audit.fail_on_drift or by a required org policy that cannot be resolved, or (except with --file) an apm.lock.yaml written by a newer APM (the message names both versions). |
2 | Warning-only findings, or usage error (mutually exclusive flags). |
3 | Configuration or infrastructure error (feature not enabled, scanner not found, malformed SARIF). |
CI gate mode (--ci)
Section titled “CI gate mode (--ci)”| Code | Meaning |
|---|---|
0 | All checks passed. |
1 | One or more checks failed (including deployment-owner integrity, drift, hash drift, or policy violations), an explicit --policy source could not be loaded, a required org policy (policy.fetch_failure_default: block) could not be resolved, or apm.lock.yaml was written by a newer APM. |
CI JSON includes a top-level policy object (enforced, source, enforcement); SARIF has it under runs[0].invocations[0].properties.policy. enforced: false means no policy checks ran.
A failing CI JSON check can carry remediation: the structured advice that clears it, with id, command (the exact apm command line), fixes (the state it clears) and optional before (a manual step first, such as deleting edited files) and then (a step after it succeeds). remediations lists every applicable remediation; remediation is the first. The text message renders the same advice.
{"name": "lockfile-exists", "passed": false, "remediation": {"id": "lockfile-missing", "command": "apm install", "fixes": "generate apm.lock.yaml"}}Related
Section titled “Related”apm install— the built-in scan that blocks critical findings before deployment.apm export-patch— turn themodifieddrift this reports into upstream patches.apm prune— reconciles the canonical deployment-owner references this check validates.- Drift and secure by default — consumer-side overview of the two-layer security model.
- Enforce in CI — wiring
apm audit --ciinto branch protection.
Copyright (c) Microsoft Corporation. General documentation: CC-BY-4.0. Software, code examples and OpenAPM: Apache-2.0. See scope and exclusions.