This is an automated email from the ASF dual-hosted git repository.

gnodet pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/maven.git


The following commit(s) were added to refs/heads/master by this push:
     new c51f383fdf Add lifecycle plan/execute API for IDE embedders (#13612)
c51f383fdf is described below

commit c51f383fdf568ef060692faf2f6b422ba61a5a27
Author: B V HITESH SAI <[email protected]>
AuthorDate: Wed Nov 11 00:39:22 2026 +0530

    Add lifecycle plan/execute API for IDE embedders (#13612)
    
    * Add filtered lifecycle execution API
    
    Expose filtered lifecycle execution through the Maven 4 Session API. 
Calculate and configure the complete plan before filtering immutable execution 
snapshots, then execute the retained internal mojos as one batch.
    
    * Address lifecycle plan API review feedback
    
    Rename the public service to avoid the legacy lifecycle executor collision, 
preserve predicate runtime exceptions, and cover current-project restoration on 
execution failure.
    
    * Redesign lifecycle execution as plan workflow
    
    Introduce request/result-based planning and execution APIs, expose 
immutable composable lifecycle plans, and add session shortcuts and regression 
coverage for inspection, filtering, and current-project restoration.
    
    * Address lifecycle API review feedback
    
    Document lifecycle service failures, validate task elements before copying, 
and reject foreign lifecycle plans with a stable public-facing error. Add 
regression coverage that prevents internal implementation details from leaking.
    
    * Complete lifecycle API documentation
    
    Document lifecycle shortcut failure contracts, distinguish the v4 service 
from its legacy counterpart, and add a message-only LifecycleExecutorException 
constructor for diagnostic-only failures.
    
    * Document lifecycle executor conveniences
    
    Add behavior, parameter, result, exception, version, and cross-reference 
documentation to all five request-building convenience methods.
    
    * Fix @since version and add plan() to LifecycleExecutionResult
    
    - Correct @since 4.1.0 -> 4.2.0 on all new lifecycle API types (master
      is 4.2.0-SNAPSHOT, not 4.1.0)
    - Drop redundant method-level @since tags on LifecycleExecutor default
      methods; the type-level @since is sufficient for a new interface
    - Add LifecycleExecutionResult.plan() accessor so callers can correlate
      executed mojos back to the originating plan without extra bookkeeping
    
    * Delegate to concurrent builder and enrich lifecycle API
    
    - Rewrite DefaultLifecycleExecutor to delegate to BuildPlanExecutor's
      plan calculation (calculateMojoExecutions, calculateLifecycleMappings,
      bindProjectMojos) and the concurrent MojoExecutor instead of the v3
      sequential LifecycleExecutionPlanCalculator + MojoExecutor path.
      The BuildPlan DAG is preserved internally so execute() benefits from
      intra-project parallelism rather than linearizing into a sequential
      list.
    
    - Add per-execution status to LifecycleExecutionResult:
      executedSuccessfully(), failedExecution(), failureCause() so callers
      know which mojos succeeded before a failure.
    
    - Add MojoExecution.isForkingExecution() default method that checks
      descriptor().getExecutePhase() and getExecuteGoal(), so IDE embedders
      can warn users about mojos that trigger forked lifecycle execution.
    
    - Add LifecyclePlan.executionsByPhase() default method that groups
      executions by lifecycle phase for IDE display.
    
    - Extract bindProjectMojos() from BuildPlanExecutor.BuildContext.plan()
      so the same mojo-binding logic is reusable for both reactor and
      single-project plan calculation.
    
    - Add BuildPlanExecutor.calculateProjectPlan() and configureAndExecute()
      public methods for single-project lifecycle operations.
    
    Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
    
    * Attach partial result to LifecycleExecutorException on failure
    
    - Add LifecycleExecutorException(message, cause, result) constructor and
      result() accessor so callers can retrieve per-execution status (which
      mojos succeeded, which failed) when execution throws.
    - Remove redundant catch(MavenException) — already covered by
      catch(Exception) since MavenException extends RuntimeException.
    - Add @since 4.2.0 to MojoExecution.isForkingExecution() since the
      interface is @since 4.0.0.
    - Update reportsPerExecutionStatus test to validate partial result:
      executedSuccessfully contains compile, failedExecution is test.
    
    Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
    
    * Improve javadoc on lifecycle execution API
    
    Add class-level documentation explaining design, usage patterns,
    scope, and limitations for all lifecycle API types: LifecyclePlan,
    LifecycleExecutor, LifecycleExecutionResult, LifecyclePlanRequest,
    LifecyclePlanResult, LifecycleExecutionRequest, and
    LifecycleExecutorException.
    
    Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
    
    * Document phase qualifiers, Phase interface, and task syntax
    
    - Add javadoc to Lifecycle.BEFORE/AFTER/AT explaining they are for mojo
      binding (not CLI invocation) and how the three sub-steps relate to a
      phase execution.
    - Enrich Lifecycle.Phase javadoc explaining the phase tree structure and
      the before:/after: decomposition.
    - Document LifecyclePlanRequest task syntax: lifecycle phases (linking to
      Lifecycle.Phase), plugin goal formats (4 variants + @executionId), and
      how the colon separator distinguishes goals from phases.
    
    Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
    
    * Add usage example to LifecycleExecutor javadoc
    
    Show plan/inspect/execute workflow for the resources phase,
    including filtered execution.
    
    Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
    
    * Use string literal in LifecycleExecutor example for consistency
    
    Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
    
    * Keep BuildContext across plan and execute phases
    
    - Replace calculateProjectPlan() + configureAndExecute() with
      createProjectContext() that returns a BuildContext holding the plan
      and its accumulated state (aggregationEnds, reactorProjects).
    - Add BuildContext.configureAndExecuteStep() for executing mojos
      through the same context that calculated the plan.
    - Add splitAggregatorSteps() and linkAggregatorSteps() calls to
      createProjectContext() so aggregator goals are properly handled.
    - DefaultLifecyclePlan now holds the BuildContext (not just BuildPlan),
      and execute() uses it for step execution.
    - Make BuildContext public so it's accessible across packages.
    
    Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
    
    * Fix dead call in execute() and null-guard BuildContext.close()
    
    - Remove duplicate InternalMavenSession.from() call that discarded
      its return value (refactoring leftover).
    - Guard executor.close() against null for plan-only BuildContext
      instances where the PhasingExecutor is not created.
    
    Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
    
    ---------
    
    Co-authored-by: Guillaume Nodet <[email protected]>
    Co-authored-by: Claude Opus 4.6 (1M context) <[email protected]>
---
 .../main/java/org/apache/maven/api/Lifecycle.java  |  42 +++-
 .../java/org/apache/maven/api/LifecyclePlan.java   |  88 +++++++
 .../java/org/apache/maven/api/MojoExecution.java   |  11 +
 .../main/java/org/apache/maven/api/Session.java    |  82 +++++++
 .../api/services/LifecycleExecutionRequest.java    | 150 ++++++++++++
 .../api/services/LifecycleExecutionResult.java     |  64 +++++
 .../maven/api/services/LifecycleExecutor.java      | 204 ++++++++++++++++
 .../api/services/LifecycleExecutorException.java   |  56 +++++
 .../maven/api/services/LifecyclePlanRequest.java   | 163 +++++++++++++
 .../maven/api/services/LifecyclePlanResult.java    |  41 ++++
 .../internal/impl/DefaultLifecycleExecutor.java    | 202 ++++++++++++++++
 .../maven/internal/impl/DefaultLifecyclePlan.java  |  81 +++++++
 .../internal/concurrent/BuildPlanExecutor.java     | 130 ++++++++---
 .../impl/DefaultLifecycleExecutorTest.java         | 260 +++++++++++++++++++++
 14 files changed, 1541 insertions(+), 33 deletions(-)

diff --git 
a/api/maven-api-core/src/main/java/org/apache/maven/api/Lifecycle.java 
b/api/maven-api-core/src/main/java/org/apache/maven/api/Lifecycle.java
index 27cb57d7c4..cb6c372e6f 100644
--- a/api/maven-api-core/src/main/java/org/apache/maven/api/Lifecycle.java
+++ b/api/maven-api-core/src/main/java/org/apache/maven/api/Lifecycle.java
@@ -52,8 +52,39 @@ public interface Lifecycle extends ExtensibleEnum {
     // ======================
     // Phase qualifiers
     // ======================
+
+    /**
+     * Qualifier prefix for binding a mojo to run <em>before</em> a phase's 
main executions.
+     * Used in plugin descriptors and lifecycle definitions to control 
execution ordering
+     * within the phase graph.
+     *
+     * <p>Example: a mojo bound to {@code "before:compile"} runs before the 
mojos bound
+     * to the {@code "compile"} phase itself. When a user requests the {@code 
"compile"}
+     * phase (e.g. {@code mvn compile}), all three sub-steps execute:
+     * {@code before:compile} → {@code compile} → {@code after:compile}.
+     *
+     * <p>These qualifiers are for <strong>mojo binding</strong>, not for CLI 
invocation.
+     * Requesting {@code "before:compile"} from the CLI is not supported — the 
build
+     * engine always executes the full phase including all its sub-steps.
+     *
+     * @see #AFTER
+     * @see #AT
+     */
     String BEFORE = "before:";
+
+    /**
+     * Qualifier prefix for binding a mojo to run <em>after</em> a phase's 
main executions.
+     *
+     * @see #BEFORE
+     */
     String AFTER = "after:";
+
+    /**
+     * Qualifier prefix that resolves to the phase's main step (stripping the 
prefix).
+     * Equivalent to using the bare phase name for binding purposes.
+     *
+     * @see #BEFORE
+     */
     String AT = "at:";
 
     /**
@@ -102,8 +133,15 @@ default Stream<Phase> allPhases() {
     /**
      * A phase in the lifecycle.
      *
-     * A phase is identified by its name. It also contains a list of plugins 
bound to that phase,
-     * a list of {@link Link links}, and a list of sub-phases.  This forms a 
tree of phases.
+     * <p>A phase is identified by its {@link #name() name} and forms a tree: 
each phase
+     * can contain {@link #phases() sub-phases} and declare {@link #links() 
ordering links}
+     * to other phases. During execution, each phase is decomposed into three 
sub-steps
+     * ({@link #BEFORE before:}<em>name</em>, <em>name</em>, {@link #AFTER 
after:}<em>name</em>)
+     * that mojos can bind to.
+     *
+     * <p>Predefined phase names for the {@linkplain Lifecycle#DEFAULT 
default} lifecycle
+     * include {@link #COMPILE}, {@link #TEST}, {@link #PACKAGE}, {@link 
#VERIFY},
+     * {@link #INSTALL}, and {@link #DEPLOY}, among others.
      */
     interface Phase {
 
diff --git 
a/api/maven-api-core/src/main/java/org/apache/maven/api/LifecyclePlan.java 
b/api/maven-api-core/src/main/java/org/apache/maven/api/LifecyclePlan.java
new file mode 100644
index 0000000000..fd3671b305
--- /dev/null
+++ b/api/maven-api-core/src/main/java/org/apache/maven/api/LifecyclePlan.java
@@ -0,0 +1,88 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.maven.api;
+
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+
+import org.apache.maven.api.annotations.Experimental;
+import org.apache.maven.api.annotations.Immutable;
+import org.apache.maven.api.annotations.Nonnull;
+
+/**
+ * An immutable snapshot of the lifecycle execution plan for a single project.
+ *
+ * <p>A {@code LifecyclePlan} is produced by {@link 
org.apache.maven.api.services.LifecycleExecutor#plan(
+ * org.apache.maven.api.services.LifecyclePlanRequest) 
LifecycleExecutor.plan()} and captures the
+ * configured {@link MojoExecution mojo executions} that Maven would run for 
the requested
+ * lifecycle phases or plugin goals. The plan is composable: it can be 
inspected, filtered,
+ * and then passed to {@link 
org.apache.maven.api.services.LifecycleExecutor#execute(
+ * org.apache.maven.api.services.LifecycleExecutionRequest) 
LifecycleExecutor.execute()}.
+ *
+ * <h2>Typical usage</h2>
+ * <pre>{@code
+ * LifecyclePlanResult result = session.planLifecycle(project, 
List.of("verify"));
+ * LifecyclePlan plan = result.plan();
+ *
+ * // Inspect: display the plan to the user
+ * plan.executionsByPhase().forEach((phase, mojos) ->
+ *     System.out.println(phase + ": " + mojos));
+ *
+ * // Filter and execute: run only the compile-phase mojos
+ * session.executeLifecycle(plan,
+ *     mojo -> mojo.lifecyclePhase().orElse("").equals("compile"));
+ * }</pre>
+ *
+ * <p>The {@link #executions()} list is topologically sorted: mojos appear in 
an order
+ * consistent with the lifecycle phase graph, but the internal execution 
engine may
+ * run independent steps concurrently.
+ *
+ * <p>Instances are scoped to a single project. Reactor-level (multi-project) 
orchestration
+ * is handled separately.
+ *
+ * @since 4.2.0
+ * @see org.apache.maven.api.services.LifecycleExecutor
+ * @see Session#planLifecycle(Project, java.util.List)
+ */
+@Experimental
+@Immutable
+public interface LifecyclePlan {
+
+    /** {@return the project for which this plan was calculated} */
+    @Nonnull
+    Project project();
+
+    /** {@return the lifecycle phases and plugin goals used to calculate this 
plan} */
+    @Nonnull
+    List<String> tasks();
+
+    /** {@return the configured mojo executions in lifecycle order} */
+    @Nonnull
+    List<MojoExecution> executions();
+
+    /** {@return the executions grouped by lifecycle phase, preserving phase 
order} */
+    @Nonnull
+    default Map<String, List<MojoExecution>> executionsByPhase() {
+        return executions().stream()
+                .collect(Collectors.groupingBy(
+                        e -> e.lifecyclePhase().orElse(""), 
LinkedHashMap::new, Collectors.toUnmodifiableList()));
+    }
+}
diff --git 
a/api/maven-api-core/src/main/java/org/apache/maven/api/MojoExecution.java 
b/api/maven-api-core/src/main/java/org/apache/maven/api/MojoExecution.java
index c4c6b52095..1b0a6d3f03 100644
--- a/api/maven-api-core/src/main/java/org/apache/maven/api/MojoExecution.java
+++ b/api/maven-api-core/src/main/java/org/apache/maven/api/MojoExecution.java
@@ -82,4 +82,15 @@ public interface MojoExecution {
     /** {@return the merged configuration for this execution, if any} */
     @Nonnull
     Optional<XmlNode> configuration();
+
+    /**
+     * {@return true if this mojo triggers a forked lifecycle execution}
+     *
+     * @since 4.2.0
+     */
+    default boolean isForkingExecution() {
+        MojoDescriptor d = descriptor();
+        return (d.getExecutePhase() != null && !d.getExecutePhase().isEmpty())
+                || (d.getExecuteGoal() != null && 
!d.getExecuteGoal().isEmpty());
+    }
 }
diff --git a/api/maven-api-core/src/main/java/org/apache/maven/api/Session.java 
b/api/maven-api-core/src/main/java/org/apache/maven/api/Session.java
index a3fb39b2bd..76444bdd77 100644
--- a/api/maven-api-core/src/main/java/org/apache/maven/api/Session.java
+++ b/api/maven-api-core/src/main/java/org/apache/maven/api/Session.java
@@ -24,6 +24,7 @@
 import java.util.Map;
 import java.util.NoSuchElementException;
 import java.util.Optional;
+import java.util.function.Predicate;
 
 import org.apache.maven.api.annotations.Experimental;
 import org.apache.maven.api.annotations.Nonnull;
@@ -32,6 +33,9 @@
 import org.apache.maven.api.model.Repository;
 import org.apache.maven.api.services.ArtifactCoordinatesFactory;
 import org.apache.maven.api.services.DependencyCoordinatesFactory;
+import org.apache.maven.api.services.LifecycleExecutionResult;
+import org.apache.maven.api.services.LifecycleExecutor;
+import org.apache.maven.api.services.LifecyclePlanResult;
 import org.apache.maven.api.services.RequestTrace;
 import org.apache.maven.api.services.VersionResolverException;
 import org.apache.maven.api.settings.Settings;
@@ -235,6 +239,84 @@ default int getDegreeOfConcurrency() {
     @Nonnull
     Collection<Listener> getListeners();
 
+    /**
+     * Calculates a lifecycle plan that can be inspected before execution.
+     *
+     * @param project the project for which to calculate the plan
+     * @param tasks lifecycle phases or plugin goals used to calculate the plan
+     * @return the lifecycle planning result
+     * @throws org.apache.maven.api.services.LifecycleExecutorException if the 
lifecycle plan cannot be calculated
+     * @since 4.2.0
+     */
+    @Nonnull
+    default LifecyclePlanResult planLifecycle(@Nonnull Project project, 
@Nonnull List<String> tasks) {
+        return getService(LifecycleExecutor.class).plan(this, project, tasks);
+    }
+
+    /**
+     * Executes a previously calculated lifecycle plan.
+     *
+     * @param plan the lifecycle plan to execute
+     * @return the lifecycle execution result
+     * @throws org.apache.maven.api.services.LifecycleExecutorException if 
lifecycle execution fails
+     * @throws IllegalArgumentException if the plan was not produced by the 
lifecycle executor service
+     * @since 4.2.0
+     */
+    @Nonnull
+    default LifecycleExecutionResult executeLifecycle(@Nonnull LifecyclePlan 
plan) {
+        return getService(LifecycleExecutor.class).execute(this, plan);
+    }
+
+    /**
+     * Executes the entries of a previously calculated lifecycle plan that are 
accepted by the supplied filter.
+     *
+     * @param plan the lifecycle plan to execute
+     * @param filter predicate deciding which configured mojo executions are 
executed
+     * @return the lifecycle execution result
+     * @throws org.apache.maven.api.services.LifecycleExecutorException if 
lifecycle execution fails
+     * @throws IllegalArgumentException if the plan was not produced by the 
lifecycle executor service
+     * @since 4.2.0
+     */
+    @Nonnull
+    default LifecycleExecutionResult executeLifecycle(
+            @Nonnull LifecyclePlan plan, @Nonnull Predicate<MojoExecution> 
filter) {
+        return getService(LifecycleExecutor.class).execute(this, plan, filter);
+    }
+
+    /**
+     * Calculates and executes a lifecycle plan.
+     *
+     * @param project the project for which to execute the lifecycle
+     * @param tasks lifecycle phases or plugin goals used to calculate the plan
+     * @return the lifecycle execution result
+     * @throws org.apache.maven.api.services.LifecycleExecutorException if the 
lifecycle plan cannot be calculated or
+     *      executed
+     * @throws IllegalArgumentException if the calculated plan cannot be 
executed by the lifecycle executor service
+     * @since 4.2.0
+     */
+    @Nonnull
+    default LifecycleExecutionResult executeLifecycle(@Nonnull Project 
project, @Nonnull List<String> tasks) {
+        return getService(LifecycleExecutor.class).planAndExecute(this, 
project, tasks);
+    }
+
+    /**
+     * Calculates a lifecycle plan and executes the entries accepted by the 
supplied filter.
+     *
+     * @param project the project for which to execute the lifecycle
+     * @param tasks lifecycle phases or plugin goals used to calculate the plan
+     * @param filter predicate deciding which configured mojo executions are 
executed
+     * @return the lifecycle execution result
+     * @throws org.apache.maven.api.services.LifecycleExecutorException if the 
lifecycle plan cannot be calculated or
+     *      executed
+     * @throws IllegalArgumentException if the calculated plan cannot be 
executed by the lifecycle executor service
+     * @since 4.2.0
+     */
+    @Nonnull
+    default LifecycleExecutionResult executeLifecycle(
+            @Nonnull Project project, @Nonnull List<String> tasks, @Nonnull 
Predicate<MojoExecution> filter) {
+        return getService(LifecycleExecutor.class).planAndExecute(this, 
project, tasks, filter);
+    }
+
     /**
      * Shortcut for {@code 
getService(RepositoryFactory.class).createLocal(...)}.
      *
diff --git 
a/api/maven-api-core/src/main/java/org/apache/maven/api/services/LifecycleExecutionRequest.java
 
b/api/maven-api-core/src/main/java/org/apache/maven/api/services/LifecycleExecutionRequest.java
new file mode 100644
index 0000000000..c014609313
--- /dev/null
+++ 
b/api/maven-api-core/src/main/java/org/apache/maven/api/services/LifecycleExecutionRequest.java
@@ -0,0 +1,150 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.maven.api.services;
+
+import java.util.Objects;
+import java.util.function.Predicate;
+
+import org.apache.maven.api.LifecyclePlan;
+import org.apache.maven.api.MojoExecution;
+import org.apache.maven.api.Session;
+import org.apache.maven.api.annotations.Experimental;
+import org.apache.maven.api.annotations.Immutable;
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.NotThreadSafe;
+import org.apache.maven.api.annotations.Nullable;
+
+import static java.util.Objects.requireNonNull;
+
+/**
+ * A request to execute all or part of a previously calculated lifecycle plan.
+ *
+ * <p>The optional {@link #filter()} predicate selects which mojo executions 
from the
+ * plan are actually run. When {@code null}, all executions in the plan are 
executed.
+ * The filter is intentionally excluded from {@link #equals(Object)} / {@link 
#hashCode()}
+ * because lambda predicates have no meaningful equality.
+ *
+ * @since 4.2.0
+ * @see LifecycleExecutor#execute(LifecycleExecutionRequest)
+ */
+@Experimental
+@Immutable
+public interface LifecycleExecutionRequest extends Request<Session> {
+
+    /** {@return the previously calculated lifecycle plan to execute} */
+    @Nonnull
+    LifecyclePlan plan();
+
+    /** {@return the optional predicate used to select executions from the 
plan} */
+    @Nullable
+    Predicate<MojoExecution> filter();
+
+    @Nonnull
+    static Builder builder() {
+        return new Builder();
+    }
+
+    @Nonnull
+    static LifecycleExecutionRequest build(@Nonnull Session session, @Nonnull 
LifecyclePlan plan) {
+        return builder().session(session).plan(plan).build();
+    }
+
+    @Nonnull
+    static LifecycleExecutionRequest build(
+            @Nonnull Session session, @Nonnull LifecyclePlan plan, @Nonnull 
Predicate<MojoExecution> filter) {
+        return builder().session(session).plan(plan).filter(filter).build();
+    }
+
+    @NotThreadSafe
+    class Builder {
+        private Session session;
+        private RequestTrace trace;
+        private LifecyclePlan plan;
+        private Predicate<MojoExecution> filter;
+
+        Builder() {}
+
+        @Nonnull
+        public Builder session(@Nonnull Session session) {
+            this.session = session;
+            return this;
+        }
+
+        @Nonnull
+        public Builder trace(@Nullable RequestTrace trace) {
+            this.trace = trace;
+            return this;
+        }
+
+        @Nonnull
+        public Builder plan(@Nonnull LifecyclePlan plan) {
+            this.plan = plan;
+            return this;
+        }
+
+        @Nonnull
+        public Builder filter(@Nullable Predicate<MojoExecution> filter) {
+            this.filter = filter;
+            return this;
+        }
+
+        @Nonnull
+        public LifecycleExecutionRequest build() {
+            return new DefaultLifecycleExecutionRequest(session, trace, plan, 
filter);
+        }
+
+        private static final class DefaultLifecycleExecutionRequest extends 
BaseRequest<Session>
+                implements LifecycleExecutionRequest {
+            private final LifecyclePlan plan;
+            private final Predicate<MojoExecution> filter;
+
+            private DefaultLifecycleExecutionRequest(
+                    Session session, RequestTrace trace, LifecyclePlan plan, 
Predicate<MojoExecution> filter) {
+                super(requireNonNull(session, "session cannot be null"), 
trace);
+                this.plan = requireNonNull(plan, "plan cannot be null");
+                this.filter = filter;
+            }
+
+            @Override
+            public LifecyclePlan plan() {
+                return plan;
+            }
+
+            @Override
+            public Predicate<MojoExecution> filter() {
+                return filter;
+            }
+
+            @Override
+            public boolean equals(Object obj) {
+                return obj instanceof DefaultLifecycleExecutionRequest that && 
Objects.equals(plan, that.plan);
+            }
+
+            @Override
+            public int hashCode() {
+                return Objects.hash(plan);
+            }
+
+            @Override
+            public String toString() {
+                return "LifecycleExecutionRequest[plan=" + plan + ']';
+            }
+        }
+    }
+}
diff --git 
a/api/maven-api-core/src/main/java/org/apache/maven/api/services/LifecycleExecutionResult.java
 
b/api/maven-api-core/src/main/java/org/apache/maven/api/services/LifecycleExecutionResult.java
new file mode 100644
index 0000000000..2aec81eca3
--- /dev/null
+++ 
b/api/maven-api-core/src/main/java/org/apache/maven/api/services/LifecycleExecutionResult.java
@@ -0,0 +1,64 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.maven.api.services;
+
+import java.util.List;
+import java.util.Optional;
+
+import org.apache.maven.api.LifecyclePlan;
+import org.apache.maven.api.MojoExecution;
+import org.apache.maven.api.annotations.Experimental;
+import org.apache.maven.api.annotations.Nonnull;
+
+/**
+ * The result of executing a lifecycle plan.
+ *
+ * <p>On the success path this object is returned from
+ * {@link LifecycleExecutor#execute(LifecycleExecutionRequest)}. On the 
failure path
+ * it is attached to the thrown {@link LifecycleExecutorException} and 
accessible via
+ * {@link LifecycleExecutorException#result()}, so callers can always 
determine which
+ * mojos succeeded before the failure.
+ *
+ * @since 4.2.0
+ * @see LifecycleExecutor#execute(LifecycleExecutionRequest)
+ * @see LifecycleExecutorException#result()
+ */
+@Experimental
+public interface LifecycleExecutionResult extends 
Result<LifecycleExecutionRequest> {
+
+    /** {@return the lifecycle plan that was executed} */
+    @Nonnull
+    LifecyclePlan plan();
+
+    /** {@return the executions retained by the request and submitted for 
execution} */
+    @Nonnull
+    List<MojoExecution> executions();
+
+    /** {@return the executions that completed successfully} */
+    @Nonnull
+    List<MojoExecution> executedSuccessfully();
+
+    /** {@return the execution that failed, if any} */
+    @Nonnull
+    Optional<MojoExecution> failedExecution();
+
+    /** {@return the cause of the failure, if any} */
+    @Nonnull
+    Optional<Throwable> failureCause();
+}
diff --git 
a/api/maven-api-core/src/main/java/org/apache/maven/api/services/LifecycleExecutor.java
 
b/api/maven-api-core/src/main/java/org/apache/maven/api/services/LifecycleExecutor.java
new file mode 100644
index 0000000000..3f782eac2d
--- /dev/null
+++ 
b/api/maven-api-core/src/main/java/org/apache/maven/api/services/LifecycleExecutor.java
@@ -0,0 +1,204 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.maven.api.services;
+
+import java.util.List;
+import java.util.function.Predicate;
+
+import org.apache.maven.api.LifecyclePlan;
+import org.apache.maven.api.MojoExecution;
+import org.apache.maven.api.Project;
+import org.apache.maven.api.Service;
+import org.apache.maven.api.Session;
+import org.apache.maven.api.annotations.Experimental;
+import org.apache.maven.api.annotations.Nonnull;
+
+/**
+ * Service for calculating and executing Maven lifecycle plans for a single 
project.
+ *
+ * <p>This service separates lifecycle <em>planning</em> from 
<em>execution</em>, enabling
+ * callers to inspect and filter the plan before deciding what to execute. 
This is the
+ * primary entry point for IDE embedders and tools that need programmatic 
lifecycle control.
+ *
+ * <h2>Core workflow</h2>
+ * The service exposes two abstract operations:
+ * <ol>
+ *   <li>{@link #plan(LifecyclePlanRequest)} — calculates an immutable {@link 
LifecyclePlan}
+ *       containing the configured mojo executions for the requested 
phases/goals</li>
+ *   <li>{@link #execute(LifecycleExecutionRequest)} — runs all or a filtered 
subset of a
+ *       previously calculated plan</li>
+ * </ol>
+ *
+ * <p>Convenience defaults ({@link #plan(Session, Project, java.util.List)},
+ * {@link #execute(Session, LifecyclePlan)}, {@link #planAndExecute(Session, 
Project, java.util.List)})
+ * and {@link Session} shortcuts ({@link Session#planLifecycle(Project, 
java.util.List)},
+ * {@link Session#executeLifecycle(LifecyclePlan)}) cover the common cases 
without
+ * constructing request objects directly.
+ *
+ * <h2>Example</h2>
+ * <pre>{@code
+ * // Plan the "resources" phase for a project
+ * LifecyclePlanResult planResult = session.planLifecycle(project, 
"resources");
+ * LifecyclePlan plan = planResult.plan();
+ *
+ * // Inspect what would run
+ * for (MojoExecution mojo : plan.executions()) {
+ *     System.out.println(mojo.lifecyclePhase().orElse("") + " : " + 
mojo.goal());
+ * }
+ *
+ * // Execute the full plan
+ * LifecycleExecutionResult result = session.executeLifecycle(plan);
+ *
+ * // Or execute only specific mojos (e.g. skip resource copying)
+ * result = session.executeLifecycle(plan,
+ *     mojo -> !mojo.goal().equals("resources"));
+ * }</pre>
+ *
+ * <h2>Scope and limitations</h2>
+ * <ul>
+ *   <li>This service operates on a <strong>single project</strong>. 
Reactor-level
+ *       (multi-project) orchestration is handled by a separate mechanism.</li>
+ *   <li>The plan uses the same graph-based calculation as the concurrent build
+ *       infrastructure, but plugin resolution happens eagerly during {@code 
plan()},
+ *       which requires that all plugin artifacts are already resolvable.</li>
+ *   <li>On execution failure, the thrown {@link LifecycleExecutorException} 
carries
+ *       a {@linkplain LifecycleExecutorException#result() partial result} 
with per-mojo
+ *       success/failure status.</li>
+ * </ul>
+ *
+ * <p>This is the Maven 4 API lifecycle executor. The legacy
+ * {@code org.apache.maven.lifecycle.LifecycleExecutor} in the compatibility 
layer
+ * serves a different role (full reactor execution).
+ *
+ * @since 4.2.0
+ * @see LifecyclePlan
+ * @see Session#planLifecycle(Project, java.util.List)
+ * @see Session#executeLifecycle(LifecyclePlan)
+ */
+@Experimental
+public interface LifecycleExecutor extends Service {
+
+    /**
+     * Calculates a lifecycle plan without executing it.
+     *
+     * @param request the planning request
+     * @return the planning result
+     * @throws LifecycleExecutorException if the lifecycle plan cannot be 
calculated
+     */
+    @Nonnull
+    LifecyclePlanResult plan(@Nonnull LifecyclePlanRequest request);
+
+    /**
+     * Executes all or part of a previously calculated lifecycle plan.
+     *
+     * @param request the execution request
+     * @return the execution result
+     * @throws LifecycleExecutorException if lifecycle execution fails
+     * @throws IllegalArgumentException if the plan was not produced by this 
service
+     */
+    @Nonnull
+    LifecycleExecutionResult execute(@Nonnull LifecycleExecutionRequest 
request);
+
+    /**
+     * Calculates a lifecycle plan without executing it.
+     *
+     * @param session the current session
+     * @param project the project for which to calculate the plan
+     * @param tasks lifecycle phases or plugin goals used to calculate the plan
+     * @return the lifecycle planning result
+     * @throws LifecycleExecutorException if the lifecycle plan cannot be 
calculated
+     * @see #plan(LifecyclePlanRequest)
+     */
+    @Nonnull
+    default LifecyclePlanResult plan(@Nonnull Session session, @Nonnull 
Project project, @Nonnull List<String> tasks) {
+        return plan(LifecyclePlanRequest.build(session, project, tasks));
+    }
+
+    /**
+     * Executes a previously calculated lifecycle plan.
+     *
+     * @param session the current session
+     * @param plan the lifecycle plan to execute
+     * @return the lifecycle execution result
+     * @throws LifecycleExecutorException if lifecycle execution fails
+     * @throws IllegalArgumentException if the plan was not produced by this 
service
+     * @see #execute(LifecycleExecutionRequest)
+     */
+    @Nonnull
+    default LifecycleExecutionResult execute(@Nonnull Session session, 
@Nonnull LifecyclePlan plan) {
+        return execute(LifecycleExecutionRequest.build(session, plan));
+    }
+
+    /**
+     * Executes the entries of a previously calculated lifecycle plan that are 
accepted by the supplied filter.
+     *
+     * @param session the current session
+     * @param plan the lifecycle plan to execute
+     * @param filter predicate deciding which configured mojo executions are 
executed
+     * @return the lifecycle execution result
+     * @throws LifecycleExecutorException if lifecycle execution fails
+     * @throws IllegalArgumentException if the plan was not produced by this 
service
+     * @see #execute(LifecycleExecutionRequest)
+     */
+    @Nonnull
+    default LifecycleExecutionResult execute(
+            @Nonnull Session session, @Nonnull LifecyclePlan plan, @Nonnull 
Predicate<MojoExecution> filter) {
+        return execute(LifecycleExecutionRequest.build(session, plan, filter));
+    }
+
+    /**
+     * Calculates and executes a lifecycle plan.
+     *
+     * @param session the current session
+     * @param project the project for which to execute the lifecycle
+     * @param tasks lifecycle phases or plugin goals used to calculate the plan
+     * @return the lifecycle execution result
+     * @throws LifecycleExecutorException if the lifecycle plan cannot be 
calculated or executed
+     * @throws IllegalArgumentException if the calculated plan cannot be 
executed by this service
+     * @see #plan(LifecyclePlanRequest)
+     * @see #execute(LifecycleExecutionRequest)
+     */
+    @Nonnull
+    default LifecycleExecutionResult planAndExecute(
+            @Nonnull Session session, @Nonnull Project project, @Nonnull 
List<String> tasks) {
+        return execute(session, plan(session, project, tasks).plan());
+    }
+
+    /**
+     * Calculates a lifecycle plan and executes the entries accepted by the 
supplied filter.
+     *
+     * @param session the current session
+     * @param project the project for which to execute the lifecycle
+     * @param tasks lifecycle phases or plugin goals used to calculate the plan
+     * @param filter predicate deciding which configured mojo executions are 
executed
+     * @return the lifecycle execution result
+     * @throws LifecycleExecutorException if the lifecycle plan cannot be 
calculated or executed
+     * @throws IllegalArgumentException if the calculated plan cannot be 
executed by this service
+     * @see #plan(LifecyclePlanRequest)
+     * @see #execute(LifecycleExecutionRequest)
+     */
+    @Nonnull
+    default LifecycleExecutionResult planAndExecute(
+            @Nonnull Session session,
+            @Nonnull Project project,
+            @Nonnull List<String> tasks,
+            @Nonnull Predicate<MojoExecution> filter) {
+        return execute(session, plan(session, project, tasks).plan(), filter);
+    }
+}
diff --git 
a/api/maven-api-core/src/main/java/org/apache/maven/api/services/LifecycleExecutorException.java
 
b/api/maven-api-core/src/main/java/org/apache/maven/api/services/LifecycleExecutorException.java
new file mode 100644
index 0000000000..e4582c7717
--- /dev/null
+++ 
b/api/maven-api-core/src/main/java/org/apache/maven/api/services/LifecycleExecutorException.java
@@ -0,0 +1,56 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.maven.api.services;
+
+import java.util.Optional;
+
+import org.apache.maven.api.annotations.Experimental;
+import org.apache.maven.api.annotations.Nonnull;
+
+/**
+ * Signals that lifecycle planning or execution failed.
+ *
+ * @since 4.2.0
+ */
+@Experimental
+public class LifecycleExecutorException extends MavenException {
+
+    private final LifecycleExecutionResult result;
+
+    public LifecycleExecutorException(String message) {
+        super(message);
+        this.result = null;
+    }
+
+    public LifecycleExecutorException(String message, Throwable cause) {
+        super(message, cause);
+        this.result = null;
+    }
+
+    public LifecycleExecutorException(String message, Throwable cause, 
LifecycleExecutionResult result) {
+        super(message, cause);
+        this.result = result;
+    }
+
+    /** {@return the partial execution result available at the time of 
failure, or empty} */
+    @Nonnull
+    public Optional<LifecycleExecutionResult> result() {
+        return Optional.ofNullable(result);
+    }
+}
diff --git 
a/api/maven-api-core/src/main/java/org/apache/maven/api/services/LifecyclePlanRequest.java
 
b/api/maven-api-core/src/main/java/org/apache/maven/api/services/LifecyclePlanRequest.java
new file mode 100644
index 0000000000..e3305502bb
--- /dev/null
+++ 
b/api/maven-api-core/src/main/java/org/apache/maven/api/services/LifecyclePlanRequest.java
@@ -0,0 +1,163 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.maven.api.services;
+
+import java.util.List;
+import java.util.Objects;
+
+import org.apache.maven.api.Project;
+import org.apache.maven.api.Session;
+import org.apache.maven.api.annotations.Experimental;
+import org.apache.maven.api.annotations.Immutable;
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.annotations.NotThreadSafe;
+import org.apache.maven.api.annotations.Nullable;
+
+import static java.util.Objects.requireNonNull;
+
+/**
+ * A request to calculate a lifecycle plan for one project.
+ *
+ * <p>Each task in the {@link #tasks()} list is either a <strong>lifecycle 
phase</strong> or a
+ * <strong>plugin goal</strong>. Any task containing {@code ':'} is parsed as 
a goal;
+ * everything else is treated as a lifecycle phase name.
+ *
+ * <h2>Lifecycle phases</h2>
+ * Phase names correspond to the phases defined in a {@link 
org.apache.maven.api.Lifecycle},
+ * such as those declared in {@link org.apache.maven.api.Lifecycle.Phase}:
+ * {@code "compile"}, {@code "test"}, {@code "verify"}, {@code "install"}, etc.
+ * Requesting a phase causes all preceding phases in the lifecycle to execute 
as well.
+ *
+ * <h2>Plugin goals</h2>
+ * Goals can be specified in several formats:
+ * <ul>
+ *   <li>{@code groupId:artifactId:version:goal} — fully qualified with 
version</li>
+ *   <li>{@code groupId:artifactId:goal} — version resolved from the project 
or plugin management</li>
+ *   <li>{@code prefix:goal} — resolved via plugin prefix mapping (e.g. {@code 
"compiler:compile"})</li>
+ * </ul>
+ * An optional {@code @executionId} suffix (e.g. {@code 
"prefix:goal@myExecution"}) selects
+ * a specific plugin execution configuration from the POM.
+ *
+ * @since 4.2.0
+ * @see LifecycleExecutor#plan(LifecyclePlanRequest)
+ * @see org.apache.maven.api.Lifecycle.Phase
+ */
+@Experimental
+@Immutable
+public interface LifecyclePlanRequest extends Request<Session> {
+
+    /** {@return the project for which the lifecycle plan is calculated} */
+    @Nonnull
+    Project project();
+
+    /** {@return the lifecycle phases and plugin goals used to calculate the 
plan} */
+    @Nonnull
+    List<String> tasks();
+
+    @Nonnull
+    static Builder builder() {
+        return new Builder();
+    }
+
+    @Nonnull
+    static LifecyclePlanRequest build(@Nonnull Session session, @Nonnull 
Project project, @Nonnull List<String> tasks) {
+        return 
builder().session(session).project(project).tasks(tasks).build();
+    }
+
+    @NotThreadSafe
+    class Builder {
+        private Session session;
+        private RequestTrace trace;
+        private Project project;
+        private List<String> tasks;
+
+        Builder() {}
+
+        @Nonnull
+        public Builder session(@Nonnull Session session) {
+            this.session = session;
+            return this;
+        }
+
+        @Nonnull
+        public Builder trace(@Nullable RequestTrace trace) {
+            this.trace = trace;
+            return this;
+        }
+
+        @Nonnull
+        public Builder project(@Nonnull Project project) {
+            this.project = project;
+            return this;
+        }
+
+        @Nonnull
+        public Builder tasks(@Nonnull List<String> tasks) {
+            this.tasks = tasks;
+            return this;
+        }
+
+        @Nonnull
+        public LifecyclePlanRequest build() {
+            return new DefaultLifecyclePlanRequest(session, trace, project, 
tasks);
+        }
+
+        private static final class DefaultLifecyclePlanRequest extends 
BaseRequest<Session>
+                implements LifecyclePlanRequest {
+            private final Project project;
+            private final List<String> tasks;
+
+            private DefaultLifecyclePlanRequest(
+                    Session session, RequestTrace trace, Project project, 
List<String> tasks) {
+                super(requireNonNull(session, "session cannot be null"), 
trace);
+                this.project = requireNonNull(project, "project cannot be 
null");
+                requireNonNull(tasks, "tasks cannot be null");
+                tasks.forEach(task -> requireNonNull(task, "task cannot be 
null"));
+                this.tasks = List.copyOf(tasks);
+            }
+
+            @Override
+            public Project project() {
+                return project;
+            }
+
+            @Override
+            public List<String> tasks() {
+                return tasks;
+            }
+
+            @Override
+            public boolean equals(Object obj) {
+                return obj instanceof DefaultLifecyclePlanRequest that
+                        && Objects.equals(project, that.project)
+                        && Objects.equals(tasks, that.tasks);
+            }
+
+            @Override
+            public int hashCode() {
+                return Objects.hash(project, tasks);
+            }
+
+            @Override
+            public String toString() {
+                return "LifecyclePlanRequest[project=" + project + ", tasks=" 
+ tasks + ']';
+            }
+        }
+    }
+}
diff --git 
a/api/maven-api-core/src/main/java/org/apache/maven/api/services/LifecyclePlanResult.java
 
b/api/maven-api-core/src/main/java/org/apache/maven/api/services/LifecyclePlanResult.java
new file mode 100644
index 0000000000..fe0403b18a
--- /dev/null
+++ 
b/api/maven-api-core/src/main/java/org/apache/maven/api/services/LifecyclePlanResult.java
@@ -0,0 +1,41 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.maven.api.services;
+
+import org.apache.maven.api.LifecyclePlan;
+import org.apache.maven.api.annotations.Experimental;
+import org.apache.maven.api.annotations.Nonnull;
+
+/**
+ * The result of calculating a lifecycle plan.
+ *
+ * <p>The {@link #plan()} accessor returns the immutable {@link LifecyclePlan} 
that can be
+ * inspected and then passed to
+ * {@link LifecycleExecutor#execute(LifecycleExecutionRequest)}.
+ *
+ * @since 4.2.0
+ * @see LifecycleExecutor#plan(LifecyclePlanRequest)
+ */
+@Experimental
+public interface LifecyclePlanResult extends Result<LifecyclePlanRequest> {
+
+    /** {@return the calculated lifecycle plan} */
+    @Nonnull
+    LifecyclePlan plan();
+}
diff --git 
a/impl/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultLifecycleExecutor.java
 
b/impl/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultLifecycleExecutor.java
new file mode 100644
index 0000000000..d9a9dbb4ec
--- /dev/null
+++ 
b/impl/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultLifecycleExecutor.java
@@ -0,0 +1,202 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.maven.internal.impl;
+
+import javax.inject.Inject;
+import javax.inject.Named;
+import javax.inject.Singleton;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.function.Predicate;
+
+import org.apache.maven.api.LifecyclePlan;
+import org.apache.maven.api.MojoExecution;
+import org.apache.maven.api.Service;
+import org.apache.maven.api.annotations.Nonnull;
+import org.apache.maven.api.services.LifecycleExecutionRequest;
+import org.apache.maven.api.services.LifecycleExecutionResult;
+import org.apache.maven.api.services.LifecycleExecutor;
+import org.apache.maven.api.services.LifecycleExecutorException;
+import org.apache.maven.api.services.LifecyclePlanRequest;
+import org.apache.maven.api.services.LifecyclePlanResult;
+import org.apache.maven.execution.MavenSession;
+import org.apache.maven.lifecycle.LifecycleExecutionException;
+import org.apache.maven.lifecycle.internal.LifecycleTaskSegmentCalculator;
+import org.apache.maven.lifecycle.internal.TaskSegment;
+import org.apache.maven.lifecycle.internal.concurrent.BuildPlanExecutor;
+import org.apache.maven.lifecycle.internal.concurrent.BuildStep;
+import org.apache.maven.project.MavenProject;
+import org.eclipse.sisu.Typed;
+
+import static java.util.Objects.requireNonNull;
+import static org.apache.maven.internal.impl.CoreUtils.cast;
+
+@Named
+@Typed({LifecycleExecutor.class, Service.class})
+@Singleton
+public class DefaultLifecycleExecutor implements LifecycleExecutor {
+
+    private final LifecycleTaskSegmentCalculator taskSegmentCalculator;
+    private final BuildPlanExecutor buildPlanExecutor;
+
+    @Inject
+    public DefaultLifecycleExecutor(
+            LifecycleTaskSegmentCalculator taskSegmentCalculator, 
BuildPlanExecutor buildPlanExecutor) {
+        this.taskSegmentCalculator = taskSegmentCalculator;
+        this.buildPlanExecutor = buildPlanExecutor;
+    }
+
+    @Nonnull
+    @Override
+    public LifecyclePlanResult plan(@Nonnull LifecyclePlanRequest request) {
+        requireNonNull(request, "request");
+        InternalMavenSession internalSession = 
InternalMavenSession.from(request.getSession());
+        MavenSession mavenSession = internalSession.getMavenSession();
+        MavenProject mavenProject =
+                cast(DefaultProject.class, request.project(), 
"project").getProject();
+        MavenProject previousProject = mavenSession.getCurrentProject();
+
+        mavenSession.setCurrentProject(mavenProject);
+        try {
+            List<TaskSegment> taskSegments = 
taskSegmentCalculator.calculateTaskSegments(mavenSession, request.tasks());
+            BuildPlanExecutor.BuildContext buildContext =
+                    buildPlanExecutor.createProjectContext(mavenSession, 
mavenProject, taskSegments);
+
+            List<org.apache.maven.plugin.MojoExecution> internalExecutions =
+                    buildContext.getPlan().sortedNodes().stream()
+                            .flatMap(BuildStep::executions)
+                            .toList();
+            List<MojoExecution> executions = internalExecutions.stream()
+                    .map(execution -> (MojoExecution) new 
DefaultMojoExecution(internalSession, execution))
+                    .toList();
+            Map<org.apache.maven.plugin.MojoExecution, MojoExecution> mapping =
+                    DefaultLifecyclePlan.buildMapping(internalExecutions, 
executions);
+
+            DefaultLifecyclePlan plan =
+                    new DefaultLifecyclePlan(request.project(), 
request.tasks(), executions, buildContext, mapping);
+            return new DefaultLifecyclePlanResult(request, plan);
+        } catch (Exception e) {
+            throw new LifecycleExecutorException("Unable to calculate 
lifecycle plan", e);
+        } finally {
+            mavenSession.setCurrentProject(previousProject);
+        }
+    }
+
+    @Nonnull
+    @Override
+    public LifecycleExecutionResult execute(@Nonnull LifecycleExecutionRequest 
request) {
+        requireNonNull(request, "request");
+        MavenSession mavenSession =
+                
InternalMavenSession.from(request.getSession()).getMavenSession();
+        if (!(request.plan() instanceof DefaultLifecyclePlan plan)) {
+            throw new IllegalArgumentException("plan was not produced by this 
lifecycle executor");
+        }
+        MavenProject mavenProject =
+                cast(DefaultProject.class, plan.project(), 
"project").getProject();
+        MavenProject previousProject = mavenSession.getCurrentProject();
+        BuildPlanExecutor.BuildContext buildContext = plan.buildContext();
+
+        mavenSession.setCurrentProject(mavenProject);
+        try {
+            Predicate<MojoExecution> filter = request.filter();
+            Map<org.apache.maven.plugin.MojoExecution, MojoExecution> mapping 
= plan.internalToApiMap();
+
+            // Determine which v4 executions pass the filter
+            Set<MojoExecution> accepted = new HashSet<>();
+            List<MojoExecution> submittedExecutions = new ArrayList<>();
+            for (MojoExecution apiExecution : plan.executions()) {
+                if (filter == null || filter.test(apiExecution)) {
+                    accepted.add(apiExecution);
+                    submittedExecutions.add(apiExecution);
+                }
+            }
+
+            // Walk the BuildPlan steps in topological order, executing 
filtered mojos
+            List<MojoExecution> succeeded = new ArrayList<>();
+            MojoExecution failed = null;
+            Throwable failureCause = null;
+
+            for (BuildStep step : buildContext.getPlan().sortedNodes()) {
+                List<org.apache.maven.plugin.MojoExecution> stepExecutions = 
step.executions()
+                        .filter(internal -> 
accepted.contains(mapping.get(internal)))
+                        .toList();
+                if (!stepExecutions.isEmpty()) {
+                    try {
+                        buildContext.configureAndExecuteStep(mavenProject, 
stepExecutions);
+                        for (org.apache.maven.plugin.MojoExecution internal : 
stepExecutions) {
+                            succeeded.add(mapping.get(internal));
+                        }
+                    } catch (LifecycleExecutionException e) {
+                        failed = 
mapping.get(stepExecutions.get(stepExecutions.size() - 1));
+                        failureCause = e;
+                        DefaultLifecycleExecutionResult partialResult = new 
DefaultLifecycleExecutionResult(
+                                request, plan, submittedExecutions, succeeded, 
failed, failureCause);
+                        throw new LifecycleExecutorException("Unable to 
execute lifecycle plan", e, partialResult);
+                    }
+                }
+            }
+            return new DefaultLifecycleExecutionResult(
+                    request, plan, submittedExecutions, succeeded, failed, 
failureCause);
+        } finally {
+            mavenSession.setCurrentProject(previousProject);
+        }
+    }
+
+    private record DefaultLifecyclePlanResult(LifecyclePlanRequest request, 
LifecyclePlan plan)
+            implements LifecyclePlanResult {
+        @Override
+        public LifecyclePlanRequest getRequest() {
+            return request;
+        }
+    }
+
+    private record DefaultLifecycleExecutionResult(
+            LifecycleExecutionRequest request,
+            LifecyclePlan plan,
+            List<MojoExecution> executions,
+            List<MojoExecution> executedSuccessfully,
+            MojoExecution failedMojo,
+            Throwable failure)
+            implements LifecycleExecutionResult {
+        private DefaultLifecycleExecutionResult {
+            executions = List.copyOf(executions);
+            executedSuccessfully = List.copyOf(executedSuccessfully);
+        }
+
+        @Override
+        public LifecycleExecutionRequest getRequest() {
+            return request;
+        }
+
+        @Override
+        public Optional<MojoExecution> failedExecution() {
+            return Optional.ofNullable(failedMojo);
+        }
+
+        @Override
+        public Optional<Throwable> failureCause() {
+            return Optional.ofNullable(failure);
+        }
+    }
+}
diff --git 
a/impl/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultLifecyclePlan.java
 
b/impl/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultLifecyclePlan.java
new file mode 100644
index 0000000000..c3f4d69a4c
--- /dev/null
+++ 
b/impl/maven-core/src/main/java/org/apache/maven/internal/impl/DefaultLifecyclePlan.java
@@ -0,0 +1,81 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.maven.internal.impl;
+
+import java.util.IdentityHashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.maven.api.LifecyclePlan;
+import org.apache.maven.api.MojoExecution;
+import org.apache.maven.api.Project;
+import org.apache.maven.lifecycle.internal.concurrent.BuildPlanExecutor;
+
+final class DefaultLifecyclePlan implements LifecyclePlan {
+    private final Project project;
+    private final List<String> tasks;
+    private final List<MojoExecution> executions;
+    private final BuildPlanExecutor.BuildContext buildContext;
+    private final Map<org.apache.maven.plugin.MojoExecution, MojoExecution> 
internalToApiMap;
+
+    DefaultLifecyclePlan(
+            Project project,
+            List<String> tasks,
+            List<MojoExecution> executions,
+            BuildPlanExecutor.BuildContext buildContext,
+            Map<org.apache.maven.plugin.MojoExecution, MojoExecution> 
internalToApiMap) {
+        this.project = project;
+        this.tasks = List.copyOf(tasks);
+        this.executions = List.copyOf(executions);
+        this.buildContext = buildContext;
+        this.internalToApiMap = Map.copyOf(internalToApiMap);
+    }
+
+    @Override
+    public Project project() {
+        return project;
+    }
+
+    @Override
+    public List<String> tasks() {
+        return tasks;
+    }
+
+    @Override
+    public List<MojoExecution> executions() {
+        return executions;
+    }
+
+    BuildPlanExecutor.BuildContext buildContext() {
+        return buildContext;
+    }
+
+    Map<org.apache.maven.plugin.MojoExecution, MojoExecution> 
internalToApiMap() {
+        return internalToApiMap;
+    }
+
+    static Map<org.apache.maven.plugin.MojoExecution, MojoExecution> 
buildMapping(
+            List<org.apache.maven.plugin.MojoExecution> internalExecutions, 
List<MojoExecution> apiExecutions) {
+        Map<org.apache.maven.plugin.MojoExecution, MojoExecution> map = new 
IdentityHashMap<>();
+        for (int i = 0; i < internalExecutions.size(); i++) {
+            map.put(internalExecutions.get(i), apiExecutions.get(i));
+        }
+        return map;
+    }
+}
diff --git 
a/impl/maven-core/src/main/java/org/apache/maven/lifecycle/internal/concurrent/BuildPlanExecutor.java
 
b/impl/maven-core/src/main/java/org/apache/maven/lifecycle/internal/concurrent/BuildPlanExecutor.java
index 5481ffe7b5..8d182d29f7 100644
--- 
a/impl/maven-core/src/main/java/org/apache/maven/lifecycle/internal/concurrent/BuildPlanExecutor.java
+++ 
b/impl/maven-core/src/main/java/org/apache/maven/lifecycle/internal/concurrent/BuildPlanExecutor.java
@@ -199,7 +199,38 @@ public void execute(MavenSession session, ReactorContext 
reactorContext, List<Ta
         }
     }
 
-    class BuildContext implements AutoCloseable {
+    /**
+     * Creates a {@link BuildContext} for a single project, with the lifecycle 
plan fully
+     * calculated (phases, mojo bindings, aggregator steps, fork plans). The 
returned context
+     * can be used to inspect the plan via {@link BuildContext#getPlan()} and 
then execute
+     * steps via {@link BuildContext#configureAndExecuteStep(MavenProject, 
List)}.
+     *
+     * @param session the current Maven session
+     * @param project the project for which to calculate the plan
+     * @param taskSegments the parsed task segments
+     * @return a build context holding the calculated plan
+     */
+    public BuildContext createProjectContext(
+            MavenSession session, MavenProject project, List<TaskSegment> 
taskSegments) {
+        BuildContext ctx = new BuildContext(session);
+
+        Map<MavenProject, List<MavenProject>> projects = 
Collections.singletonMap(project, Collections.emptyList());
+
+        BuildPlan plan = new BuildPlan(projects);
+        for (TaskSegment taskSegment : taskSegments) {
+            BuildPlan segment = ctx.calculateMojoExecutions(projects, 
taskSegment.getTasks());
+            plan.then(segment);
+        }
+
+        ctx.plan = plan;
+        ctx.bindProjectMojos(project);
+        ctx.splitAggregatorSteps(project);
+        ctx.linkAggregatorSteps();
+
+        return ctx;
+    }
+
+    public class BuildContext implements AutoCloseable {
         final MavenSession session;
         final ReactorContext reactorContext;
         final PhasingExecutor executor;
@@ -232,6 +263,32 @@ class BuildContext implements AutoCloseable {
             this.plan = null;
         }
 
+        BuildContext(MavenSession session) {
+            this.session = session;
+            this.reactorContext = null;
+            this.threads = 1;
+            this.executor = null;
+            this.plan = null;
+        }
+
+        public BuildPlan getPlan() {
+            return plan;
+        }
+
+        /**
+         * Configures and executes a list of mojo executions for a single 
project.
+         */
+        public void configureAndExecuteStep(MavenProject project, 
List<MojoExecution> executions)
+                throws LifecycleExecutionException {
+            BuildPlanExecutor.attachToThread(project);
+            session.setCurrentProject(project);
+            executions.forEach(mojoExecution -> {
+                mojoExecutionConfigurator(mojoExecution).configure(project, 
mojoExecution, true);
+                finalizeMojoConfiguration(mojoExecution);
+            });
+            mojoExecutor.execute(session, executions);
+        }
+
         public BuildPlan buildInitialPlan(List<TaskSegment> taskSegments) {
             int nThreads = Math.min(
                     session.getRequest().getDegreeOfConcurrency(),
@@ -365,7 +422,9 @@ void execute() {
 
         @Override
         public void close() {
-            this.executor.close();
+            if (this.executor != null) {
+                this.executor.close();
+            }
         }
 
         /**
@@ -648,35 +707,7 @@ private void plan() {
                         .filter(step -> step.status.compareAndSet(PLANNING, 
SCHEDULED))
                         .collect(Collectors.toSet());
                 for (BuildStep step : planSteps) {
-                    MavenProject project = step.project;
-                    for (Plugin plugin : project.getBuild().getPlugins()) {
-                        for (PluginExecution execution : 
plugin.getExecutions()) {
-                            for (String goal : execution.getGoals()) {
-                                MojoDescriptor mojoDescriptor = 
getMojoDescriptor(project, plugin, goal);
-                                String phase =
-                                        execution.getPhase() != null ? 
execution.getPhase() : mojoDescriptor.getPhase();
-                                if (phase == null) {
-                                    continue;
-                                }
-                                String tmpResolvedPhase = 
plan.aliases().getOrDefault(phase, phase);
-                                String resolvedPhase = 
tmpResolvedPhase.startsWith(AT)
-                                        ? 
tmpResolvedPhase.substring(AT.length())
-                                        : tmpResolvedPhase;
-                                plan.step(project, resolvedPhase).ifPresent(n 
-> {
-                                    MojoExecution mojoExecution = new 
MojoExecution(mojoDescriptor, execution.getId());
-                                    mojoExecution.setLifecyclePhase(phase);
-                                    if (requiresAggregation(n, mojoExecution)
-                                            && inheritedFromReactorAncestor(
-                                                    project, plugin, 
execution, goal, resolvedPhase)) {
-                                        return;
-                                    }
-                                    n.addMojo(mojoExecution, 
execution.getPriority());
-                                    // Apply @After annotation ordering 
constraints from the mojo descriptor
-                                    applyAfterLinks(mojoDescriptor, project, 
resolvedPhase);
-                                });
-                            }
-                        }
-                    }
+                    bindProjectMojos(step.project);
                 }
 
                 for (BuildStep step : planSteps) {
@@ -717,6 +748,43 @@ && inheritedFromReactorAncestor(
             }
         }
 
+        void bindProjectMojos(MavenProject project) {
+            for (Plugin plugin : project.getBuild().getPlugins()) {
+                for (PluginExecution execution : plugin.getExecutions()) {
+                    for (String goal : execution.getGoals()) {
+                        MojoDescriptor mojoDescriptor = 
getMojoDescriptor(project, plugin, goal);
+                        String phase = execution.getPhase() != null ? 
execution.getPhase() : mojoDescriptor.getPhase();
+                        if (phase == null) {
+                            continue;
+                        }
+                        String tmpResolvedPhase = 
plan.aliases().getOrDefault(phase, phase);
+                        String resolvedPhase = tmpResolvedPhase.startsWith(AT)
+                                ? tmpResolvedPhase.substring(AT.length())
+                                : tmpResolvedPhase;
+                        plan.step(project, resolvedPhase).ifPresent(n -> {
+                            MojoExecution mojoExecution = new 
MojoExecution(mojoDescriptor, execution.getId());
+                            mojoExecution.setLifecyclePhase(phase);
+                            if (requiresAggregation(n, mojoExecution)
+                                    && inheritedFromReactorAncestor(project, 
plugin, execution, goal, resolvedPhase)) {
+                                return;
+                            }
+                            n.addMojo(mojoExecution, execution.getPriority());
+                            applyAfterLinks(mojoDescriptor, project, 
resolvedPhase);
+                        });
+                    }
+                }
+            }
+
+            // Compute fork plans
+            BuildPlan buildPlan = plan;
+            for (BuildStep step : plan.steps(project).toList()) {
+                for (MojoExecution execution : step.executions().toList()) {
+                    buildPlan = computeForkPlan(step, execution, buildPlan);
+                }
+            }
+            plan = buildPlan;
+        }
+
         private boolean requiresAggregation(BuildStep step, MojoExecution 
execution) {
             // Legacy phases such as prepare-package resolve to hooks, but 
retain ordinary
             // lifecycle aggregation semantics. Explicit native hooks keep 
their own semantics.
diff --git 
a/impl/maven-core/src/test/java/org/apache/maven/internal/impl/DefaultLifecycleExecutorTest.java
 
b/impl/maven-core/src/test/java/org/apache/maven/internal/impl/DefaultLifecycleExecutorTest.java
new file mode 100644
index 0000000000..ce28b02983
--- /dev/null
+++ 
b/impl/maven-core/src/test/java/org/apache/maven/internal/impl/DefaultLifecycleExecutorTest.java
@@ -0,0 +1,260 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.maven.internal.impl;
+
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.maven.api.LifecyclePlan;
+import org.apache.maven.api.services.LifecycleExecutionRequest;
+import org.apache.maven.api.services.LifecycleExecutionResult;
+import org.apache.maven.api.services.LifecycleExecutorException;
+import org.apache.maven.api.services.LifecyclePlanRequest;
+import org.apache.maven.api.services.LifecyclePlanResult;
+import org.apache.maven.api.services.Lookup;
+import org.apache.maven.execution.MavenSession;
+import org.apache.maven.lifecycle.LifecycleExecutionException;
+import org.apache.maven.lifecycle.internal.LifecycleTask;
+import org.apache.maven.lifecycle.internal.LifecycleTaskSegmentCalculator;
+import org.apache.maven.lifecycle.internal.TaskSegment;
+import org.apache.maven.lifecycle.internal.concurrent.BuildPlan;
+import org.apache.maven.lifecycle.internal.concurrent.BuildPlanExecutor;
+import org.apache.maven.lifecycle.internal.concurrent.BuildStep;
+import org.apache.maven.plugin.MojoExecution;
+import org.apache.maven.plugin.descriptor.MojoDescriptor;
+import org.apache.maven.plugin.descriptor.PluginDescriptor;
+import org.apache.maven.project.MavenProject;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyList;
+import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.ArgumentMatchers.same;
+import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+class DefaultLifecycleExecutorTest {
+
+    private InternalMavenSession session;
+    private MavenSession mavenSession;
+    private LifecycleTaskSegmentCalculator taskSegmentCalculator;
+    private BuildPlanExecutor buildPlanExecutor;
+    private MavenProject project;
+    private MavenProject previousProject;
+    private DefaultProject apiProject;
+    private MojoExecution compile;
+    private MojoExecution test;
+    private DefaultLifecycleExecutor executor;
+    private BuildPlan buildPlan;
+    private BuildPlanExecutor.BuildContext buildContext;
+
+    @BeforeEach
+    void setUp() throws Exception {
+        session = mock(InternalMavenSession.class);
+        mavenSession = mock(MavenSession.class);
+        taskSegmentCalculator = mock(LifecycleTaskSegmentCalculator.class);
+        buildPlanExecutor = mock(BuildPlanExecutor.class);
+        project = new MavenProject();
+        previousProject = new MavenProject();
+        apiProject = mock(DefaultProject.class);
+        compile = execution("compile", "compile");
+        test = execution("test", "test");
+        TaskSegment segment = new TaskSegment(false, new 
LifecycleTask("verify"));
+
+        when(session.getMavenSession()).thenReturn(mavenSession);
+        when(session.getService(Lookup.class)).thenReturn(mock(Lookup.class));
+        when(mavenSession.getCurrentProject()).thenReturn(previousProject);
+        when(apiProject.getProject()).thenReturn(project);
+        when(taskSegmentCalculator.calculateTaskSegments(mavenSession, 
List.of("verify")))
+                .thenReturn(List.of(segment));
+
+        // Create a BuildPlan with steps containing the mojos
+        buildPlan = new BuildPlan(Collections.singletonMap(project, 
Collections.emptyList()));
+        Map<String, BuildStep> steps = new java.util.LinkedHashMap<>();
+        BuildStep compileStep = new BuildStep("compile", project, null);
+        compileStep.addMojo(compile, 0);
+        steps.put("compile", compileStep);
+        BuildStep testStep = new BuildStep("test", project, null);
+        testStep.addMojo(test, 0);
+        compileStep.executeBefore(testStep);
+        steps.put("test", testStep);
+        buildPlan.addProject(project, steps);
+
+        buildContext = mock(BuildPlanExecutor.BuildContext.class);
+        when(buildContext.getPlan()).thenReturn(buildPlan);
+        when(buildPlanExecutor.createProjectContext(same(mavenSession), 
same(project), anyList()))
+                .thenReturn(buildContext);
+
+        executor = new DefaultLifecycleExecutor(taskSegmentCalculator, 
buildPlanExecutor);
+    }
+
+    @Test
+    void plansInspectsAndExecutesFilteredMojos() throws Exception {
+        LifecyclePlanResult planResult =
+                executor.plan(LifecyclePlanRequest.build(session, apiProject, 
List.of("verify")));
+        LifecyclePlan plan = planResult.plan();
+
+        assertSame(apiProject, plan.project());
+        assertEquals(List.of("verify"), plan.tasks());
+        assertEquals(
+                List.of("compile", "test"),
+                plan.executions().stream()
+                        .map(org.apache.maven.api.MojoExecution::goal)
+                        .toList());
+
+        LifecycleExecutionResult result = 
executor.execute(LifecycleExecutionRequest.build(
+                session, plan, execution -> execution.goal().equals("test")));
+
+        assertEquals(
+                List.of("test"),
+                result.executions().stream()
+                        .map(org.apache.maven.api.MojoExecution::goal)
+                        .toList());
+        verify(mavenSession, times(2)).setCurrentProject(same(project));
+        verify(mavenSession, 
times(2)).setCurrentProject(same(previousProject));
+    }
+
+    @Test
+    void executesAllMojosWhenFilterIsAbsent() throws Exception {
+        LifecyclePlan plan = executor.plan(LifecyclePlanRequest.build(session, 
apiProject, List.of("verify")))
+                .plan();
+
+        LifecycleExecutionResult result = 
executor.execute(LifecycleExecutionRequest.build(session, plan));
+
+        assertEquals(2, result.executions().size());
+        assertEquals(2, result.executedSuccessfully().size());
+        assertTrue(result.failedExecution().isEmpty());
+        assertTrue(result.failureCause().isEmpty());
+    }
+
+    @Test
+    void restoresCurrentProjectOnExecutionFailure() throws Exception {
+        LifecyclePlan plan = executor.plan(LifecyclePlanRequest.build(session, 
apiProject, List.of("verify")))
+                .plan();
+        doThrow(new LifecycleExecutionException("boom"))
+                .when(buildContext)
+                .configureAndExecuteStep(eq(project), anyList());
+
+        assertThrows(
+                LifecycleExecutorException.class,
+                () -> 
executor.execute(LifecycleExecutionRequest.build(session, plan)));
+
+        verify(mavenSession, 
times(2)).setCurrentProject(same(previousProject));
+    }
+
+    @Test
+    void doesNotWrapFilterFailures() throws Exception {
+        LifecyclePlan plan = executor.plan(LifecyclePlanRequest.build(session, 
apiProject, List.of("verify")))
+                .plan();
+        IllegalStateException filterFailure = new 
IllegalStateException("broken filter");
+
+        IllegalStateException thrown = assertThrows(
+                IllegalStateException.class,
+                () -> 
executor.execute(LifecycleExecutionRequest.build(session, plan, execution -> {
+                    throw filterFailure;
+                })));
+
+        assertSame(filterFailure, thrown);
+        verify(buildContext, never()).configureAndExecuteStep(any(), 
anyList());
+        verify(mavenSession, 
times(2)).setCurrentProject(same(previousProject));
+    }
+
+    @Test
+    void 
rejectsPlansNotProducedByThisServiceWithoutLeakingImplementationDetails() {
+        LifecyclePlan externalPlan = mock(LifecyclePlan.class);
+
+        IllegalArgumentException thrown = assertThrows(
+                IllegalArgumentException.class,
+                () -> 
executor.execute(LifecycleExecutionRequest.build(session, externalPlan)));
+
+        assertEquals("plan was not produced by this lifecycle executor", 
thrown.getMessage());
+        
assertFalse(thrown.getMessage().contains(DefaultLifecyclePlan.class.getName()));
+        verify(mavenSession, never()).setCurrentProject(project);
+    }
+
+    @Test
+    void reportsPerExecutionStatus() throws Exception {
+        LifecyclePlan plan = executor.plan(LifecyclePlanRequest.build(session, 
apiProject, List.of("verify")))
+                .plan();
+
+        // Make the second step (test) fail
+        doAnswer(inv -> {
+                    List<MojoExecution> execs = inv.getArgument(1);
+                    if (execs.stream().anyMatch(e -> 
"test".equals(e.getGoal()))) {
+                        throw new LifecycleExecutionException("test failed");
+                    }
+                    return null;
+                })
+                .when(buildContext)
+                .configureAndExecuteStep(eq(project), anyList());
+
+        LifecycleExecutorException ex = assertThrows(
+                LifecycleExecutorException.class,
+                () -> 
executor.execute(LifecycleExecutionRequest.build(session, plan)));
+
+        assertTrue(ex.getMessage().contains("Unable to execute lifecycle 
plan"));
+        LifecycleExecutionResult partialResult = ex.result().orElseThrow();
+        assertEquals(
+                List.of("compile"),
+                partialResult.executedSuccessfully().stream()
+                        .map(org.apache.maven.api.MojoExecution::goal)
+                        .toList());
+        assertTrue(partialResult.failedExecution().isPresent());
+        assertEquals("test", partialResult.failedExecution().get().goal());
+        assertTrue(partialResult.failureCause().isPresent());
+    }
+
+    @Test
+    void phaseGrouping() throws Exception {
+        LifecyclePlan plan = executor.plan(LifecyclePlanRequest.build(session, 
apiProject, List.of("verify")))
+                .plan();
+
+        var byPhase = plan.executionsByPhase();
+        assertEquals(2, byPhase.size());
+        assertTrue(byPhase.containsKey("compile"));
+        assertTrue(byPhase.containsKey("test"));
+    }
+
+    private static MojoExecution execution(String goal, String phase) {
+        PluginDescriptor pluginDescriptor = new PluginDescriptor();
+        pluginDescriptor.setGroupId("org.apache.maven.plugins");
+        pluginDescriptor.setArtifactId("maven-test-plugin");
+        pluginDescriptor.setVersion("1.0");
+
+        MojoDescriptor mojoDescriptor = new MojoDescriptor();
+        mojoDescriptor.setGoal(goal);
+        mojoDescriptor.setPluginDescriptor(pluginDescriptor);
+
+        MojoExecution execution = new MojoExecution(mojoDescriptor, "default-" 
+ goal);
+        execution.setLifecyclePhase(phase);
+        return execution;
+    }
+}

Reply via email to