Skip to content

feat(compile): fire a pre-compile lifecycle event before reading sources - #3596

Merged
Daniel Meppiel (danielmeppiel) merged 10 commits into
microsoft:mainfrom
Ryangr0:feat/pre-compile-lifecycle-event
Nov 12, 2026
Merged

Daniel Meppiel (danielmeppiel) merged 10 commits into
microsoft:mainfrom
Ryangr0:feat/pre-compile-lifecycle-event

Conversation

@Ryangr0

Copy link
Copy Markdown
Contributor

Description

Adds a pre-compile lifecycle event that apm compile fires before it reads sources, so a trusted project script can generate instructions under .apm/ first (for example Laravel Boost composing guidelines from installed packages). It follows the existing lifecycle contract: trusted project scripts only, a failing script logs a warning and the compile continues, and APM_NO_SCRIPTS and executables.deny_all switch it off. It runs under the lifecycle lock compile already takes.

It does not fire for --dry-run, --validate, --watch, --global or --root, nor during apm audit.

A lifecycle: block that names pre-compile is fingerprinted under a new hash domain, so a trust record given before this change, when the key had no meaning, needs fresh apm lifecycle trust. Trust for other blocks is unchanged.

Issue and approved scope

Issue: #3459

Human scope-approval comment: #3459 (comment) (scope record by Daniel Meppiel (@danielmeppiel), 2026-11-12)

Does this PR complete the issue, or what remains? It completes the approved scope. Out of scope, as recorded: a post-compile event, any way for a script to fail the compile, and untrusted or dependency-provided scripts.

Fixes #3459

Type of change

  • Bug fix
  • New feature
  • Documentation
  • Maintenance / refactor

Testing

  • Tested locally
  • All existing tests pass
  • Added tests for new functionality (if applicable)

tests/unit/commands/compile/test_pre_compile_scripts.py covers each done-when item: generated sources reach AGENTS.md, the event fires once, a failing script does not stop the compile, untrusted scripts are skipped with a notice, APM_NO_SCRIPTS and executables.deny_all suppress it, the skipped modes and apm audit run no scripts, scripts run under the lifecycle lock, and a pre-upgrade trust record needs fresh trust. The feature's tests and the trust red-team tests pass (90), and the CI lint job passes locally. On macOS, tests/unit/test_unix_installer_checksums.py and tests/unit/test_homebrew_onboarding.py fail the same way on main without this change.

Docs: the lifecycle scripts page, the compile and lifecycle CLI references, the security model, environment variables, and the apm-usage guide in packages/apm-guide.

Spec conformance (OpenAPM v0.1)

  • N/A -- this PR does not change OpenAPM-observable behaviour.

🤖 Generated with Claude Code

A trusted project script on `pre-compile` can generate primitives under
`.apm/` from the project's own toolchain, for example a framework that
composes guidance from installed dependencies, and `apm compile` reads what it
wrote. Like every lifecycle event it is best-effort: a failing script never
stops the compile.

- Fires inside `_run_compilation`, under its existing lifecycle lock, and the
  project check follows it so a first compile finds generated content.
- Not with `--dry-run`, `--validate`, `--watch`, `--root` or `--global`.
- `build_runner_from_context(events=...)` keeps org-policy discovery off
  compiles that have no pre-compile scripts.
- Trust records made before APM knew `pre-compile` do not cover a block that
  names it.
- Docs, the trust prompt, and `apm lifecycle test pre-compile`.

Refs microsoft#3459

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…pile

Act on a maintainer-persona review of the pre-compile change:

- `event_for_dependencies` in core/lifecycle_scripts.py builds the event
  payload; install, update and compile route through it instead of
  rebuilding the package list.
- `apm lifecycle test` takes its event choices from LIFECYCLE_EVENTS.
- Compile decides once whether scripts run, parses apm.yml for the payload
  only when a pre-compile script will run, and catches only the manifest
  read errors, naming them in verbose output.
- `--dry-run` help, the compile reference and the security model say that
  pre-compile content is first scanned at compile; the lifecycle guide
  section is shorter and states the lock timeout behaviour.
- Tests: payload contents, --global, org deny_all, no notice for other
  events' scripts, exit codes on skipped modes, and an end-to-end pre-upgrade
  trust record that needs fresh trust (fails without the domain change).
- CHANGELOG: a Security entry for the fresh-trust prompt.

apm-spec-waiver: install/service.py only delegates its existing payload construction to core/lifecycle_scripts.py; no OpenAPM-observable change.

Refs microsoft#3459

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Covers the two remaining done-when items of the approved scope.

Refs microsoft#3459

Co-Authored-By: Claude Opus 5.5 <[email protected]>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Active findings identify a critical policy-discovery failure that bypasses executable restrictions, non-project scripts running outside the intended trust scope, and missing warnings for failed generators.

3 open issues
What changed in this PR

Adds a pre-compile lifecycle event for #3459, allowing project generators to create instruction sources before APM compiles them into agent guidance.

Changes:

  • Fires the event under the existing lifecycle lock, excluding inspection, watch, global, and redirected-output modes.
  • Shares event-payload construction across commands and requires fresh trust for lifecycle blocks containing pre-compile.
  • Adds regression coverage and updates CLI help, documentation, and the changelog.
File Description
tests/​unit/​core/​test_lifecycle_scripts.py Tests event filtering and registration.
tests/​unit/​commands/​test_lifecycle.py Tests synthetic event preview.
tests/​unit/​commands/​compile/​test_pre_compile_scripts.py Covers generation, trust, suppression, skipped modes, and locking.
tests/​red_team/​trust/​test_hash_domain_completeness.py Checks trust migration and fingerprint compatibility.
tests/​red_team/​install/​test_failure_isolation.py Tests failure isolation for the new event.
src/​apm_cli/​install/​service.py Uses shared dependency-payload construction.
src/​apm_cli/​core/​script_trust.py Adds event-specific fingerprint versioning.
src/​apm_cli/​core/​lifecycle_scripts.py Registers the event, filters runners, and shares payload construction.
src/​apm_cli/​commands/​update.py Reuses the shared payload helper.
src/​apm_cli/​commands/​lifecycle.py Updates event choices and trust messaging.
src/​apm_cli/​commands/​compile/​cli.py Runs scripts before source validation and compilation.
packages/​apm-guide/​.apm/​skills/​apm-usage/​commands.md Documents the event and excluded modes.
docs/​src/​content/​docs/​reference/​environment-variables.md Clarifies that script suppression includes compile.
docs/​src/​content/​docs/​reference/​cli/​lifecycle.md Updates supported events and trust documentation.
docs/​src/​content/​docs/​reference/​cli/​compile.md Describes pre-compile execution and mode exclusions.
docs/​src/​content/​docs/​producer/​compile.md Links source generation into the authoring workflow.
docs/​src/​content/​docs/​enterprise/​security.md Updates compile-time execution and scanning explanations.
docs/​src/​content/​docs/​enterprise/​lifecycle-scripts.md Adds generator guidance, locking behavior, and trust migration.
docs/​src/​content/​docs/​enterprise/​index.md Includes compile in the lifecycle guide summary.
CHANGELOG.md Records the feature and trust migration.

Review effort: Balanced

Comment thread src/apm_cli/commands/compile/cli.py Resolved
Comment thread src/apm_cli/commands/compile/cli.py Resolved
Comment thread src/apm_cli/core/lifecycle_scripts.py Resolved
The approved microsoft#3459 scope requires that executables.deny_all suppress
pre-compile scripts and that a failing script log a warning while the
compile continues. Neither held: the shared runner passed a str
project_root to discover_policy_with_chain, whose hash-pin read joins
"apm.yml" onto it, so a TypeError was swallowed and deny_all never
applied (for every lifecycle event); and a command that exited non-zero
only reached scripts.log. The runner now hands discovery a Path, and
the shared command executor warns with the event, exit code and log
path (not the command, which may carry secrets). Regression tests use
real chain discovery (compile path and red-team runner path) and assert
the warning; both were mutation-break checked.

Panel folds in the same surface: drop the embedded [!] that rendered
twice through CommandLogger.warning; the timeout warning no longer
echoes the raw command; CHANGELOG entries cite the PR (microsoft#3596); docs
describe the warning, the pre-compile payload, and that --root runs no
pre-compile scripts; event_for_dependencies is typed and unit tested.

Addresses Copilot inline r4550077388 and r4550077469 on
src/apm_cli/commands/compile/cli.py and panel follow-ups from
python-architect, supply-chain-security-expert, test-coverage-expert,
cli-logging-expert, doc-writer and devx-ux-expert.

Co-authored-by: Copilot App <[email protected]>
The compile subsection said every failure prints a warning, but only a command script that exits non-zero or times out warns; HTTP and pre-exit failures stay verbose-only. Point at Security considerations instead of restating the rule. Addresses doc-writer delta finding on lifecycle-scripts.md:148.

Co-authored-by: Copilot App <[email protected]>
@danielmeppiel

Copy link
Copy Markdown
Collaborator

APM Review Panel: ship_with_followups

Community PR adds a pre-compile lifecycle event for Laravel Boost-style generators. The full panel converged after one fold cycle, and the deny_all fix now suppresses every lifecycle event as documented.

panel-mode=delta; personas=python-architect,test-coverage-expert,supply-chain-security-expert,devx-ux-expert,doc-writer,cli-logging-expert,apm-ceo (iteration 1 ran full; cli-logging-expert ad-hoc: the merge worker added a user-facing warning for failed lifecycle command scripts)

cc Ryan Grippeling (@Ryangr0) Daniel Meppiel (@danielmeppiel) Sergio Sisternes (@sergio-sisternes-epam) -- a fresh advisory pass is ready for your review.

This PR delivers the pre-compile hook scoped in #3459, so a generator such as Laravel Boost can run as a trusted project script before compile reads sources. It is one event under the existing lifecycle contract. Failures do not stop the compile, and a failing command script prints a warning naming the event, the exit code and the log path. APM_NO_SCRIPTS and executables.deny_all suppress it, and it does not run with --dry-run, --validate, --watch, --global or --root, or during audit. The full six-persona pass raised nine findings, none blocking. All but one were folded in 0aae996 and 493e86a, and the delta pass found nothing new.

The most significant fold is the str/Path fix at policy discovery. The shared runner passed a str project_root, so a TypeError was silently swallowed and executables.deny_all never applied: not for pre-compile, and not for install, update or uninstall either. deny_all now suppresses lifecycle scripts on every event, as documented. Anyone with deny_all set whose scripts still ran will see them suppressed. The CHANGELOG Security entry names all four commands.

Copilot's suggestion to exclude policy- and user-tier pre-compile scripts (r4550077531) was declined, and the supply-chain reviewer agreed. The three-tier trust contract applies to every lifecycle event. "Trusted project scripts only" in the scope record means project scripts need apm lifecycle trust.

Aligned with: Secure by default: deny_all now honored on every lifecycle event, closing a silent bypass that predated this PR. Governed by policy: APM_NO_SCRIPTS and deny_all suppress the new event like every other. OSS community driven: a well-scoped community contribution with authorship preserved through the fold cycle. Pragmatic as npm: mirrors npm's prebuild hook without new abstractions.

Panel summary

Persona B R N Takeaway
Python Architect 0 2 1 Clean single-owner payload helper and fingerprint-domain design; the str/Path boundary is fixed.
Test Coverage Expert 0 2 1 Done-when list covered; deny_all and the failure warning now have real-path regressions.
Supply Chain Security Expert 0 1 2 Trust-domain migration sound; the deny_all bypass was the real gap and is closed.
Doc Writer 0 2 1 Docs cover pre-compile on every surface; CHANGELOG and failure wording corrected.
DevX UX Expert 0 0 2 CLI surface consistent; --root now says it skips pre-compile scripts.
CLI Logging Expert 0 2 1 New warning added without a command echo; double [!] prefix removed.

B = blocking-severity findings, R = recommended, N = nits. Counts are from the iteration-1 full pass. All are folded except the devx re-trust notice below. The delta pass found nothing new.

Top 1 follow-up

  1. [DevX UX Expert] After upgrading APM, the skip notice for a block that needs fresh trust because it names pre-compile reads the same as for a block that was never trusted. A specific message ("needs fresh trust after this APM upgrade") would need a new trust-store query in script_trust. Question for Daniel Meppiel (@danielmeppiel) and Ryan Grippeling (@Ryangr0): fold it here, or track it as a follow-up issue? The CHANGELOG and the lifecycle docs already describe the re-trust step.

Recommendation

All in-scope findings are folded, CI is green, and the delta pass is clean. Ship, and decide whether the re-trust-specific notice belongs here or in a follow-up issue. It does not need to hold the merge.

Folded in this run

  • (copilot) deny_all never applied: str project_root broke policy discovery; the runner now passes a Path, with real-discovery regressions on the compile and red-team runner paths -- resolved in 0aae996.
  • (copilot) No warning on a failed generator; the shared executor now warns with the event, exit code and log path, and the failing-generator test asserts it -- resolved in 0aae996.
  • (panel: cli-logging-expert) Double [!] [!] prefix on lifecycle warnings; the timeout warning no longer echoes the raw command -- resolved in 0aae996.
  • (panel: doc-writer) CHANGELOG entries cite feat(compile): fire a pre-compile lifecycle event before reading sources #3596; failure-visibility wording, pre-compile payload note, security.md em dash -- resolved in 0aae996 and 493e86a.
  • (panel: devx-ux-expert) --root help and reference row say pre-compile scripts do not run -- resolved in 0aae996.
  • (panel: python-architect, test-coverage-expert) event_for_dependencies typed Iterable[DependencyReference], with a direct unit test -- resolved in 0aae996.
  • (merge) Current main merged three times, all clean auto-merges; the latest is 2878381.

Copilot signals reviewed

  • src/apm_cli/commands/compile/cli.py:594 -- LEGIT: str root raised a swallowed TypeError in policy discovery, so deny_all was skipped (resolved in 0aae996).
  • src/apm_cli/commands/compile/cli.py:604 -- LEGIT: a nonzero exit reached only scripts.log, but the scope requires a warning (resolved in 0aae996).
  • src/apm_cli/core/lifecycle_scripts.py:663 -- NOT-LEGIT: policy and user tiers are admin- and developer-controlled and run ungated for every event under the existing contract the scope record cites. They are not untrusted or dependency-provided.

Deferred (out-of-scope follow-ups)

  • (panel: devx-ux-expert) Re-trust-specific skip notice after upgrade -- scope boundary: needs a new trust-store query API in script_trust, a design question for the review contact; suggested follow-up: a separate issue if Daniel Meppiel (@danielmeppiel) prefers not to fold it here.

Regression-trap evidence (mutation-break gate)

  • test_org_deny_all_suppresses_scripts_through_real_policy_discovery and test_org_deny_all_reaches_runner_through_real_chain_discovery -- deleted the Path(project_root) normalization; tests FAILED as expected; guard restored.
  • test_failing_script_does_not_stop_compile and test_warns_on_nonzero_exit -- deleted the nonzero-exit warning; tests FAILED as expected; guard restored.

Lint contract

The full CI lint mirror is silent on 2878381: ruff check and format (src/, tests/, scripts/), pylint R0801, lint-auth-signals.sh and lint-architecture-boundaries.sh.

CI

All 26 checks pass on 2878381 (CI, Merge Gate, Spec conformance, CodeQL, NOTICE Drift, Windows Compatibility Gate, Lint, Lifecycle Smoke, license/cla): https://github.com/microsoft/apm/actions/runs/43236821872 and https://github.com/microsoft/apm/actions/runs/43236821734. This took 1 CI fix iteration: on 490f6e9 the lifecycle and architecture shards were abandoned by the runner, and a rerun of the failed jobs passed.

Mergeability status

PR head SHA CEO stance iters folds defers Copilot rounds CI mergeable mergeStateStatus notes
#3596 2878381 ship_with_followups 2 7 1 2 green MERGEABLE BLOCKED pending required review

Convergence

2 outer iterations; 2 Copilot rounds (the second returned nothing new). Final stance: ship_with_followups. All review threads are replied to and resolved. Ready for maintainer review.

This panel is advisory. It does not block merge. Re-apply the panel-review label after addressing feedback to re-run.


Generated by autopilot-pr-merge-worker. This comment is AI-generated and may contain errors.

@danielmeppiel
Daniel Meppiel (danielmeppiel) merged commit 9beb436 into microsoft:main Nov 12, 2026
26 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[FEATURE] Let a project generate instruction sources before compile

3 participants