gnodet-bot commented on code in PR #14077:
URL: https://github.com/apache/maven/pull/14077#discussion_r4750864966


##########
api/maven-api-core/src/main/java/org/apache/maven/api/build/report/MojoReport.java:
##########
@@ -0,0 +1,184 @@
+/*
+ * 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.build.report;
+
+import java.time.Duration;
+import java.time.Instant;
+import java.util.List;
+
+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.Nullable;
+import org.apache.maven.api.logging.LogEvent;
+
+/**
+ * Report for a single mojo (plugin goal) execution within a subproject.
+ *
+ * @since 4.2.0
+ * @see SubprojectReport#mojos()
+ */
+@Experimental
+@Immutable
+public interface MojoReport {
+
+    /**
+     * The plugin's group ID.
+     *
+     * @return the group ID, never {@code null}
+     */
+    @Nonnull
+    String groupId();
+
+    /**
+     * The plugin's artifact ID.
+     *
+     * @return the artifact ID, never {@code null}
+     */
+    @Nonnull
+    String artifactId();
+
+    /**
+     * The plugin version.
+     *
+     * @return the version string, never {@code null}
+     */
+    @Nonnull
+    String version();
+
+    /**
+     * The goal that was executed (e.g. {@code "compile"}, {@code "test"}).
+     *
+     * @return the goal name, never {@code null}
+     */
+    @Nonnull
+    String goal();
+
+    /**
+     * The execution ID (e.g. {@code "default-compile"}).
+     *
+     * @return the execution ID, or {@code null} if not set
+     */
+    @Nullable
+    String executionId();
+
+    /**
+     * The lifecycle phase this mojo was bound to (e.g. {@code "compile"}, 
{@code "test"}).
+     *
+     * @return the phase name, or {@code null} if invoked directly
+     */
+    @Nullable
+    String phase();
+
+    /**
+     * The outcome of this mojo execution.
+     *
+     * @return the status, never {@code null}
+     */
+    @Nonnull
+    BuildStatus status();
+
+    /**
+     * When this mojo execution started (wall-clock time).
+     *
+     * @return the start instant, never {@code null}
+     */
+    @Nonnull
+    Instant startTime();
+
+    /**
+     * How long this mojo execution took.
+     *
+     * @return the duration, never {@code null}
+     */
+    @Nonnull
+    Duration duration();
+
+    /**
+     * The trace identifier associated with this mojo execution.
+     * <p>
+     * Tracing extensions can provide this value by setting the
+     * {@code otel.trace_id} key in the SLF4J MDC before the mojo starts.
+     *
+     * @return the trace identifier, or {@code null} if no tracing context was 
provided
+     * @since 4.2.0
+     */
+    @Nullable
+    String traceId();
+
+    /**
+     * The span identifier associated with this mojo execution.
+     * <p>
+     * Tracing extensions can provide this value by setting the
+     * {@code otel.span_id} key in the SLF4J MDC before the mojo starts.
+     *
+     * @return the span identifier, or {@code null} if no tracing context was 
provided
+     * @since 4.2.0
+     */
+    @Nullable
+    String spanId();
+
+    /**
+     * The name of the thread that executed this mojo.
+     * <p>
+     * With concurrent builds ({@code -T}, {@code -bconcurrent}), different
+     * mojos — even within the same module — may run on different threads.
+     * This field enables timeline visualizations that assign each mojo to a
+     * lane, and critical-path analysis that uses actual execution times.
+     *
+     * @return the thread name (e.g. {@code "BuilderThread 0"}), or
+     *         {@code null} if not captured
+     * @since 4.1.0

Review Comment:
   🔴 **`@since` version error (raised twice previously):** `@since 4.1.0` 
should be `@since 4.2.0`. The adjacent `traceId()` and `spanId()` methods — 
added in the same PR — both correctly use `@since 4.2.0`.



##########
api/maven-api-core/src/main/java/org/apache/maven/api/build/report/StepReport.java:
##########
@@ -0,0 +1,122 @@
+/*
+ * 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.build.report;
+
+import java.time.Duration;
+import java.time.Instant;
+import java.util.List;
+
+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.Nullable;
+
+/**
+ * Report for a single build step in the concurrent builder's execution plan.
+ * <p>
+ * Steps are the atomic scheduling units of the concurrent builder. Each step
+ * belongs to a module and a lifecycle phase (e.g. {@code "before:compile"},
+ * {@code "compile"}, {@code "$setup$"}). Steps form a directed acyclic graph
+ * via their {@link #predecessors()}, which determines the execution order.
+ * <p>
+ * This data is only collected when verbose step reporting is enabled
+ * (e.g. via {@code -Dmaven.build.report.steps=true} or {@code -X}).
+ * It enables timeline reconstruction, critical-path analysis, and
+ * scheduling diagnostics.
+ *
+ * @since 4.1.0

Review Comment:
   🔴 **`@since` version error:** `@since 4.1.0` should be `@since 4.2.0`. 
`StepReport` is a new type introduced in this PR; every other new type in the 
`build.report` package (`BuildReport`, `MojoReport`, `SubprojectReport`, 
`FailureReport`) uses `@since 4.2.0`.



##########
impl/maven-core/src/main/java/org/apache/maven/lifecycle/internal/concurrent/BuildPlanExecutor.java:
##########
@@ -576,8 +606,11 @@ private void processStep(BuildStep step) {
 
             // 2. Either schedule the step or mark it as skipped based on the 
decision
             if (shouldExecute && step.status.compareAndSet(CREATED, 
SCHEDULED)) {
+                step.startTime = MonotonicClock.now();

Review Comment:
   🟡 **`startTime` captures scheduling time, not execution start.** This 
assignment runs on the scheduler thread before `executor.execute()` submits the 
lambda. Under thread pool contention the step may wait in the queue — 
`startTime` will precede actual execution by the queueing delay.
   
   The `StepReport.startTime()` Javadoc says _"When this step started executing 
(wall-clock time)"_, so this is a contract violation. Move the assignment 
inside the lambda (before `executeStep(step)`).



##########
impl/maven-impl/src/main/java/org/apache/maven/impl/build/BuildReportCollector.java:
##########
@@ -0,0 +1,820 @@
+/*
+ * 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.impl.build;
+
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.AtomicMoveNotSupportedException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.StandardCopyOption;
+import java.time.Duration;
+import java.time.Instant;
+import java.time.ZoneOffset;
+import java.time.format.DateTimeFormatter;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Queue;
+import java.util.concurrent.ArrayBlockingQueue;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentLinkedQueue;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import org.apache.maven.api.BuildInvocation;
+import org.apache.maven.api.Constants;
+import org.apache.maven.api.ExecutionEvent;
+import org.apache.maven.api.ExecutionListener;
+import org.apache.maven.api.MojoExecution;
+import org.apache.maven.api.MonotonicClock;
+import org.apache.maven.api.Project;
+import org.apache.maven.api.Session;
+import org.apache.maven.api.build.report.BuildReport;
+import org.apache.maven.api.build.report.BuildStatus;
+import org.apache.maven.api.build.report.FailureReport;
+import org.apache.maven.api.build.report.MojoReport;
+import org.apache.maven.api.build.report.SubprojectReport;
+import org.apache.maven.api.di.Named;
+import org.apache.maven.api.di.Singleton;
+import org.apache.maven.api.logging.LogEvent;
+import org.apache.maven.api.logging.LogSink;
+import org.apache.maven.api.spi.SpiService;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.slf4j.MDC;
+
+/**
+ * Collects build lifecycle events and produces a structured {@code 
BuildReport}
+ * at the end of the session.
+ * <p>
+ * Implements {@link ExecutionListener} for typed lifecycle callbacks,
+ * {@link LogSink} for receiving log events from {@code 
ProjectBuildLogAppender},
+ * and {@link SpiService} for auto-discovery via the DI container.
+ * <p>
+ * Thread-safe: concurrent subproject builds (with {@code -T}) each write to 
their
+ * own entry in a {@link ConcurrentHashMap}.
+ * <p>
+ * Log capture: receives already-enriched {@link LogEvent} objects from
+ * {@code ProjectBuildLogAppender} via the {@link LogSink#accept(LogEvent)} 
method.
+ * Uses thread-based tracking to associate events with the currently-executing
+ * mojo or subproject.
+ *
+ * @since 4.2.0
+ */
+@Named
+@Singleton
+public final class BuildReportCollector implements ExecutionListener, LogSink, 
SpiService {
+
+    private static final Logger LOGGER = 
LoggerFactory.getLogger(BuildReportCollector.class);
+
+    @org.apache.maven.api.di.Inject
+    private StepReportData stepReportData;
+
+    static final String REPORT_DIR = "build-reports";
+    static final String REPORT_LATEST = "build-report-latest.json";
+    static final String TRACE_ID_MDC_KEY = "otel.trace_id";
+    static final String SPAN_ID_MDC_KEY = "otel.span_id";
+
+    private static final int DEFAULT_MAX_STACKTRACE_LINES = 30;
+
+    // ---- Per-session config (read from system properties at SessionStarted) 
----
+
+    /** Whether report generation is enabled; set at session start from {@link 
Constants#MAVEN_BUILD_REPORT_ENABLED}. */
+    private volatile boolean reportEnabled = true;
+
+    /** Whether PII properties are included; set at session start from {@link 
Constants#MAVEN_BUILD_REPORT_INCLUDE_PII}. */
+    private volatile boolean includePii = false;
+
+    /** Cap on log events per scope; set at session start from {@link 
Constants#MAVEN_BUILD_REPORT_MAX_LOG_EVENTS}. */
+    private volatile int maxLogEventsPerScope = 500;
+
+    /** Cap on stack-trace lines per failure; set at session start from {@link 
Constants#MAVEN_BUILD_REPORT_MAX_STACKTRACE_LINES}. */
+    private volatile int maxStacktraceLines = DEFAULT_MAX_STACKTRACE_LINES;
+
+    /** Cap on throwable lines per log event; set at session start from {@link 
Constants#MAVEN_BUILD_REPORT_MAX_THROWABLE_LINES}. */
+    private volatile int maxThrowableLines = 
BuildReportJsonWriter.DEFAULT_MAX_THROWABLE_LINES;
+
+    // ---- Mutable state, populated during the build ----
+
+    /** Per-project mojo tracking: project key -> queue of in-flight/completed 
mojos. */
+    private final Map<String, Queue<MojoTiming>> mojoTimings = new 
ConcurrentHashMap<>();
+
+    /** Per-project start instants for duration computation. */
+    private final Map<String, Instant> projectStartTimes = new 
ConcurrentHashMap<>();
+
+    /** Per-project trace context captured when the project starts. */
+    private final Map<String, TraceContext> projectTraceContexts = new 
ConcurrentHashMap<>();
+
+    /** Per-mojo start instants for duration computation. */
+    private final Map<String, Instant> mojoStartTimes = new 
ConcurrentHashMap<>();
+
+    /** Per-mojo trace context captured when the mojo starts. */
+    private final Map<String, TraceContext> mojoTraceContexts = new 
ConcurrentHashMap<>();
+
+    /** Per-project build status tracked from project events. */
+    private final Map<String, BuildStatus> projectStatuses = new 
ConcurrentHashMap<>();
+
+    /** Per-project build duration tracked from start/finish events. */
+    private final Map<String, Duration> projectDurations = new 
ConcurrentHashMap<>();
+
+    /** Per-project failure causes. */
+    private final Map<String, Throwable> projectFailures = new 
ConcurrentHashMap<>();
+
+    /** Session-level state - set once on SessionStarted. */
+    // visible for testing
+    volatile Session session;
+
+    /** Build invocation - captured once at SessionStarted, immutable 
thereafter. */
+    private volatile BuildInvocation buildInvocation;
+
+    /** Session start time. */
+    private volatile Instant sessionStartTime;
+
+    /** JVM shutdown hook used to persist a partial build report on unexpected 
termination. */
+    // visible for testing
+    volatile Thread shutdownHook;
+
+    /** Ensures that normal completion and shutdown hook do not write 
competing reports. */
+    // visible for testing
+    final AtomicBoolean reportWritten = new AtomicBoolean();
+
+    // ---- Log capture state ----
+
+    /**
+     * Maps thread ID -> mojo key for the currently-executing mojo on that 
thread.
+     * Lifecycle events and mojo execution run on the same thread, so this is 
safe
+     * for parallel builds with {@code -T}.
+     */
+    private final Map<Long, String> currentMojoByThread = new 
ConcurrentHashMap<>();
+
+    /** Per-mojo log buffers: mojo key -> captured log events. */
+    private final Map<String, BlockingQueue<LogEvent>> mojoLogBuffers = new 
ConcurrentHashMap<>();
+
+    /**
+     * Maps thread ID -> project key for the currently-building project on 
that thread.
+     * Used to route log events that occur between mojo executions to the 
subproject-level buffer.
+     */
+    private final Map<Long, String> currentProjectByThread = new 
ConcurrentHashMap<>();
+
+    /** Per-subproject log buffers: project key -> events captured outside any 
mojo. */
+    private final Map<String, BlockingQueue<LogEvent>> subprojectLogBuffers = 
new ConcurrentHashMap<>();
+
+    /** Build-level log buffer: events captured outside any subproject 
lifecycle. Created at session start. */
+    private volatile BlockingQueue<LogEvent> buildLogBuffer = new 
ArrayBlockingQueue<>(500);
+
+    // ---- LogSink implementation ----
+
+    /**
+     * Receives pre-formed {@link LogEvent} objects from {@code 
ProjectBuildLogAppender}.
+     * Routes to the appropriate buffer (mojo, subproject, or build-level) 
based on
+     * the current thread's lifecycle context.
+     * <p>
+     * No-op when no session is active.
+     */
+    @Override
+    public void accept(LogEvent event) {
+        // No-op when no session is active
+        if (session == null) {
+            return;
+        }
+        long threadId = Thread.currentThread().getId();
+        // 1. Mojo-level
+        String mKey = currentMojoByThread.get(threadId);
+        if (mKey != null) {
+            BlockingQueue<LogEvent> buffer = mojoLogBuffers.get(mKey);
+            if (buffer != null) {
+                buffer.offer(event);
+            }
+            return;
+        }
+        // 2. Module-level
+        String pKey = currentProjectByThread.get(threadId);
+        if (pKey != null) {
+            BlockingQueue<LogEvent> buffer = subprojectLogBuffers.get(pKey);
+            if (buffer != null) {
+                buffer.offer(event);
+            }
+            return;
+        }
+        // 3. Build-level
+        buildLogBuffer.offer(event);
+    }
+
+    // ---- ExecutionListener typed callbacks ----
+
+    @Override
+    public void sessionStarted(ExecutionEvent event) {
+        this.session = event.session();
+        this.sessionStartTime = MonotonicClock.now();
+        // Read configurable caps from session properties (or fall back to 
defaults)
+        this.reportEnabled = readBooleanProperty(session, 
Constants.MAVEN_BUILD_REPORT_ENABLED, true);
+        this.includePii = readBooleanProperty(session, 
Constants.MAVEN_BUILD_REPORT_INCLUDE_PII, false);
+        this.maxLogEventsPerScope = readIntProperty(session, 
Constants.MAVEN_BUILD_REPORT_MAX_LOG_EVENTS, 500);
+        this.maxStacktraceLines = readIntProperty(
+                session, Constants.MAVEN_BUILD_REPORT_MAX_STACKTRACE_LINES, 
DEFAULT_MAX_STACKTRACE_LINES);
+        this.maxThrowableLines = readIntProperty(
+                session,
+                Constants.MAVEN_BUILD_REPORT_MAX_THROWABLE_LINES,
+                BuildReportJsonWriter.DEFAULT_MAX_THROWABLE_LINES);
+        this.buildLogBuffer = new 
ArrayBlockingQueue<>(this.maxLogEventsPerScope);
+        this.buildInvocation = session.buildInvocation();
+        if (this.buildInvocation == null) {
+            this.buildInvocation = DefaultBuildInvocation.from(session);
+        }
+        if (!includePii && this.buildInvocation instanceof 
DefaultBuildInvocation inv) {
+            // Strip potentially sensitive system properties from the report 
unless opted in.
+            // Note: this guard only applies when session.buildInvocation() 
returns a
+            // DefaultBuildInvocation (the standard runtime). Embedders that 
supply a custom
+            // BuildInvocation implementation are responsible for filtering 
PII themselves.
+            Map<String, String> filtered = new 
java.util.TreeMap<>(inv.systemInfo());
+            filtered.remove("user.home");
+            filtered.remove("user.name");
+            this.buildInvocation = new DefaultBuildInvocation(
+                    inv.goals(),
+                    inv.userProperties(),
+                    java.util.Collections.unmodifiableMap(filtered),
+                    inv.activeProfiles(),
+                    inv.selectedProjects(),
+                    inv.excludedProjects(),
+                    inv.makeBehavior(),
+                    inv.resumeFrom(),
+                    inv.reactorFailureBehavior(),
+                    inv.offline(),
+                    inv.updateSnapshots(),
+                    inv.batchMode(),
+                    inv.recursive(),
+                    inv.resume(),
+                    inv.threads());
+        }
+        // Remove any leftover hook from a previous build (mvnd / embedded 
Maven reuse).
+        // Must be done before resetting reportWritten to prevent the old hook 
from firing
+        // against the new session's state.
+        removeShutdownHook();
+        this.reportWritten.set(false);
+
+        if (!reportEnabled) {
+            return;
+        }
+
+        Thread hook = new Thread(
+                () -> {
+                    Session activeSession = this.session;
+                    if (activeSession == null || 
!reportWritten.compareAndSet(false, true)) {
+                        return;
+                    }
+                    try {
+                        LOGGER.debug("JVM shutting down: writing partial build 
report");
+                        // hasFailure=true: an interrupted build is always a 
failure.
+                        BuildReport report = buildReport(activeSession, true);
+                        writeReport(report, activeSession);
+                    } catch (Exception e) {
+                        LOGGER.warn("Failed to write partial build report 
during shutdown", e);
+                    }
+                },
+                "maven-build-report-shutdown-hook");
+
+        try {
+            Runtime.getRuntime().addShutdownHook(hook);
+            this.shutdownHook = hook;
+        } catch (IllegalStateException e) {
+            LOGGER.debug("JVM shutdown already in progress", e);
+        }
+    }
+
+    @Override
+    public void sessionEnded(ExecutionEvent event) {
+        removeShutdownHook();
+
+        Session endSession = event.session();
+        if (!reportEnabled || endSession == null || 
!reportWritten.compareAndSet(false, true)) {
+            clearSessionState();
+            return;
+        }
+
+        try {
+            boolean hasFailure = event.exception().isPresent();
+            BuildReport report = buildReport(endSession, hasFailure);
+            writeReport(report, endSession);
+        } catch (Exception e) {
+            // Never let the report collector crash the build
+            LOGGER.debug("Failed to produce build report: {}", e.getMessage(), 
e);
+        } finally {
+            clearSessionState();
+        }
+    }
+
+    @Override
+    public void projectStarted(ExecutionEvent event) {
+        event.project().ifPresent(project -> {
+            String key = projectKey(project);
+            projectStartTimes.put(key, MonotonicClock.now());
+            projectTraceContexts.put(key, currentTraceContext());
+            mojoTimings.putIfAbsent(key, new ConcurrentLinkedQueue<>());
+            subprojectLogBuffers.put(key, new 
ArrayBlockingQueue<>(maxLogEventsPerScope));
+            currentProjectByThread.put(Thread.currentThread().getId(), key);
+        });
+    }
+
+    @Override
+    public void projectSucceeded(ExecutionEvent event) {
+        event.project().ifPresent(project -> {
+            String key = projectKey(project);
+            Instant start = projectStartTimes.get(key);
+            Instant now = MonotonicClock.now();
+            projectStatuses.put(key, BuildStatus.SUCCESS);
+            if (start != null) {
+                projectDurations.put(key, Duration.between(start, now));
+            }
+        });
+        currentProjectByThread.remove(Thread.currentThread().getId());
+    }
+
+    @Override
+    public void projectFailed(ExecutionEvent event) {
+        event.project().ifPresent(project -> {
+            String key = projectKey(project);
+            Instant start = projectStartTimes.get(key);
+            Instant now = MonotonicClock.now();
+            projectStatuses.put(key, BuildStatus.FAILURE);
+            if (start != null) {
+                projectDurations.put(key, Duration.between(start, now));
+            }
+            event.exception().ifPresent(ex -> projectFailures.put(key, ex));
+        });
+        currentProjectByThread.remove(Thread.currentThread().getId());
+    }
+
+    @Override
+    public void projectSkipped(ExecutionEvent event) {
+        event.project().ifPresent(project -> {
+            String key = projectKey(project);
+            projectStatuses.put(key, BuildStatus.SKIPPED);
+        });
+        currentProjectByThread.remove(Thread.currentThread().getId());
+    }
+
+    @Override
+    public void mojoStarted(ExecutionEvent event) {
+        event.project()
+                .ifPresent(project -> event.mojoExecution().ifPresent(mojo -> {
+                    String mKey = mojoKey(project, mojo);
+                    mojoStartTimes.put(mKey, MonotonicClock.now());
+                    mojoTraceContexts.put(mKey, currentTraceContext());
+
+                    currentMojoByThread.put(Thread.currentThread().getId(), 
mKey);
+                    mojoLogBuffers.put(mKey, new 
ArrayBlockingQueue<>(maxLogEventsPerScope));
+                }));
+    }
+
+    @Override
+    public void mojoSucceeded(ExecutionEvent event) {
+        onMojoFinished(event, BuildStatus.SUCCESS);
+    }
+
+    @Override
+    public void mojoFailed(ExecutionEvent event) {
+        onMojoFinished(event, BuildStatus.FAILURE);
+    }
+
+    @Override
+    public void mojoSkipped(ExecutionEvent event) {
+        event.project()
+                .ifPresent(project -> event.mojoExecution().ifPresent(mojo -> {
+                    String pKey = projectKey(project);
+                    Instant now = MonotonicClock.now();
+                    TraceContext traceContext = TraceContext.EMPTY;
+
+                    MojoTiming timing = new MojoTiming(
+                            mojo.plugin().getModel().groupId(),
+                            mojo.plugin().getModel().artifactId(),
+                            mojo.plugin().getModel().version(),
+                            mojo.goal(),
+                            mojo.executionId().orElse(null),
+                            mojo.lifecyclePhase().orElse(null),
+                            BuildStatus.SKIPPED,
+                            now,
+                            Duration.ZERO,
+                            traceContext.traceId,
+                            traceContext.spanId,
+                            Thread.currentThread().getName(),

Review Comment:
   🟡 **`Thread.currentThread().getName()` for a skipped mojo has no semantic 
value.** No thread executed this mojo — the thread name captured here is the 
event-dispatch scheduler thread, which is unrelated to mojo execution. The 
value will appear in reports/timelines without meaning.
   
   Consider passing `null` instead, consistent with how 
`StepReport.threadName()` returns `null` for skipped steps (per the Javadoc: 
_"or `null` if the step was skipped"_).



##########
impl/maven-impl/src/test/java/org/apache/maven/impl/build/BuildReportJsonWriterTest.java:
##########
@@ -0,0 +1,622 @@
+/*
+ * 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.impl.build;
+
+import java.time.Duration;
+import java.time.Instant;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.maven.api.BuildInvocation;
+import org.apache.maven.api.ReactorFailureBehavior;
+import org.apache.maven.api.build.report.BuildReport;
+import org.apache.maven.api.build.report.BuildStatus;
+import org.apache.maven.api.build.report.FailureReport;
+import org.apache.maven.api.build.report.MojoReport;
+import org.apache.maven.api.build.report.SubprojectReport;
+import org.apache.maven.api.logging.LogEvent;
+import org.apache.maven.api.logging.LogLevel;
+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.assertTrue;
+
+class BuildReportJsonWriterTest {
+
+    private static LogEvent logEvent(Instant ts, LogLevel level, String msg, 
String logger) {
+        return new LogEvent() {
+            @Override
+            public Instant timestamp() {
+                return ts;
+            }
+
+            @Override
+            public LogLevel level() {
+                return level;
+            }
+
+            @Override
+            public String message() {
+                return msg;
+            }
+
+            @Override
+            public String loggerName() {
+                return logger;
+            }
+
+            @Override
+            public Throwable throwable() {
+                return null;
+            }
+        };
+    }
+
+    @SuppressWarnings("checkstyle:ParameterNumber")
+    private static LogEvent logEventWithMeta(
+            Instant ts,
+            LogLevel level,
+            String msg,
+            String logger,
+            String srcClass,
+            String srcMethod,
+            long threadId,
+            long seqNum) {
+        return new LogEvent() {
+            @Override
+            public Instant timestamp() {
+                return ts;
+            }
+
+            @Override
+            public LogLevel level() {
+                return level;
+            }
+
+            @Override
+            public String message() {
+                return msg;
+            }
+
+            @Override
+            public String loggerName() {
+                return logger;
+            }
+
+            @Override
+            public Throwable throwable() {
+                return null;
+            }
+
+            @Override
+            public String sourceClassName() {
+                return srcClass;
+            }
+
+            @Override
+            public String sourceMethodName() {
+                return srcMethod;
+            }
+
+            @Override
+            public long threadId() {
+                return threadId;
+            }
+
+            @Override
+            public long sequenceNumber() {
+                return seqNum;
+            }
+        };
+    }
+
+    private static final BuildInvocation EMPTY_INVOCATION = new 
DefaultBuildInvocation(
+            List.of(),
+            Map.of(),
+            Map.of(),
+            List.of(),
+            List.of(),
+            List.of(),
+            null,
+            null,
+            ReactorFailureBehavior.FAIL_FAST,
+            false,
+            false,
+            false,
+            true,
+            false,
+            1);
+    private static final Instant BASE_TIME = 
Instant.parse("2025-01-15T10:30:00Z");
+
+    @Test
+    void testSuccessfulBuildReport() {
+        List<LogEvent> mojoOutput = List.of(
+                logEvent(BASE_TIME.plusSeconds(6), LogLevel.INFO, "Compiling 
42 source files", "o.a.m.compiler"),
+                logEvent(BASE_TIME.plusSeconds(7), LogLevel.INFO, "BUILD 
SUCCESS", "o.a.m.compiler"));
+
+        MojoReport mojo = new DefaultMojoReport(
+                "org.apache.maven.plugins",
+                "maven-compiler-plugin",
+                "3.15.0",
+                "compile",
+                "default-compile",
+                "compile",
+                BuildStatus.SUCCESS,
+                BASE_TIME.plusSeconds(5),
+                Duration.ofMillis(2100),
+                "0123456789abcdef0123456789abcdef",
+                "0123456789abcdef",
+                "BuilderThread 0",
+                mojoOutput);
+
+        List<LogEvent> subprojectOutput = List.of(logEvent(
+                BASE_TIME.plusSeconds(2), LogLevel.INFO, "Resolving 
dependencies for maven-core", "o.a.m.resolver"));
+
+        SubprojectReport subproject = new DefaultSubprojectReport(
+                "org.apache.maven",
+                "maven-core",
+                "4.1.0-SNAPSHOT",
+                BuildStatus.SUCCESS,
+                BASE_TIME.plusSeconds(1),
+                Duration.ofMillis(12345),
+                "fedcba9876543210fedcba9876543210",
+                "fedcba9876543210",
+                List.of(mojo),
+                subprojectOutput);
+
+        List<LogEvent> buildOutput = List.of(
+                logEvent(BASE_TIME, LogLevel.INFO, "Reactor Build Order:", 
"o.a.m.reactor"),
+                logEvent(BASE_TIME, LogLevel.INFO, "Maven Core", 
"o.a.m.reactor"));
+
+        BuildReport report = new DefaultBuildReport(
+                EMPTY_INVOCATION,
+                BuildStatus.SUCCESS,
+                Duration.ofMillis(30000),
+                BASE_TIME,
+                "4.1.0-SNAPSHOT",
+                "21.0.1",
+                List.of("clean", "install"),
+                "org.apache.maven:maven:4.1.0-SNAPSHOT",
+                true,
+                4,
+                List.of(subproject),
+                List.of(),
+                List.of(),
+                buildOutput,
+                List.of());

Review Comment:
   🟡 **`writeStep()` has zero test coverage.** Every `DefaultBuildReport` 
constructor in this file passes `List.of()` for `steps`. The `"steps"` array 
emission path and `writeStep()` method (including the `predecessors` array) are 
entirely untested. Add a test case with a non-empty `List<StepReport>` — even a 
minimal `DefaultStepReport` with one predecessor is enough to verify the JSON 
structure.



##########
impl/maven-impl/src/main/java/org/apache/maven/impl/build/BuildReportCollector.java:
##########
@@ -0,0 +1,820 @@
+/*
+ * 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.impl.build;
+
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.AtomicMoveNotSupportedException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.StandardCopyOption;
+import java.time.Duration;
+import java.time.Instant;
+import java.time.ZoneOffset;
+import java.time.format.DateTimeFormatter;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Queue;
+import java.util.concurrent.ArrayBlockingQueue;
+import java.util.concurrent.BlockingQueue;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentLinkedQueue;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import org.apache.maven.api.BuildInvocation;
+import org.apache.maven.api.Constants;
+import org.apache.maven.api.ExecutionEvent;
+import org.apache.maven.api.ExecutionListener;
+import org.apache.maven.api.MojoExecution;
+import org.apache.maven.api.MonotonicClock;
+import org.apache.maven.api.Project;
+import org.apache.maven.api.Session;
+import org.apache.maven.api.build.report.BuildReport;
+import org.apache.maven.api.build.report.BuildStatus;
+import org.apache.maven.api.build.report.FailureReport;
+import org.apache.maven.api.build.report.MojoReport;
+import org.apache.maven.api.build.report.SubprojectReport;
+import org.apache.maven.api.di.Named;
+import org.apache.maven.api.di.Singleton;
+import org.apache.maven.api.logging.LogEvent;
+import org.apache.maven.api.logging.LogSink;
+import org.apache.maven.api.spi.SpiService;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.slf4j.MDC;
+
+/**
+ * Collects build lifecycle events and produces a structured {@code 
BuildReport}
+ * at the end of the session.
+ * <p>
+ * Implements {@link ExecutionListener} for typed lifecycle callbacks,
+ * {@link LogSink} for receiving log events from {@code 
ProjectBuildLogAppender},
+ * and {@link SpiService} for auto-discovery via the DI container.
+ * <p>
+ * Thread-safe: concurrent subproject builds (with {@code -T}) each write to 
their
+ * own entry in a {@link ConcurrentHashMap}.
+ * <p>
+ * Log capture: receives already-enriched {@link LogEvent} objects from
+ * {@code ProjectBuildLogAppender} via the {@link LogSink#accept(LogEvent)} 
method.
+ * Uses thread-based tracking to associate events with the currently-executing
+ * mojo or subproject.
+ *
+ * @since 4.2.0
+ */
+@Named
+@Singleton
+public final class BuildReportCollector implements ExecutionListener, LogSink, 
SpiService {
+
+    private static final Logger LOGGER = 
LoggerFactory.getLogger(BuildReportCollector.class);
+
+    @org.apache.maven.api.di.Inject
+    private StepReportData stepReportData;
+
+    static final String REPORT_DIR = "build-reports";
+    static final String REPORT_LATEST = "build-report-latest.json";
+    static final String TRACE_ID_MDC_KEY = "otel.trace_id";
+    static final String SPAN_ID_MDC_KEY = "otel.span_id";
+
+    private static final int DEFAULT_MAX_STACKTRACE_LINES = 30;
+
+    // ---- Per-session config (read from system properties at SessionStarted) 
----
+
+    /** Whether report generation is enabled; set at session start from {@link 
Constants#MAVEN_BUILD_REPORT_ENABLED}. */
+    private volatile boolean reportEnabled = true;
+
+    /** Whether PII properties are included; set at session start from {@link 
Constants#MAVEN_BUILD_REPORT_INCLUDE_PII}. */
+    private volatile boolean includePii = false;
+
+    /** Cap on log events per scope; set at session start from {@link 
Constants#MAVEN_BUILD_REPORT_MAX_LOG_EVENTS}. */
+    private volatile int maxLogEventsPerScope = 500;
+
+    /** Cap on stack-trace lines per failure; set at session start from {@link 
Constants#MAVEN_BUILD_REPORT_MAX_STACKTRACE_LINES}. */
+    private volatile int maxStacktraceLines = DEFAULT_MAX_STACKTRACE_LINES;
+
+    /** Cap on throwable lines per log event; set at session start from {@link 
Constants#MAVEN_BUILD_REPORT_MAX_THROWABLE_LINES}. */
+    private volatile int maxThrowableLines = 
BuildReportJsonWriter.DEFAULT_MAX_THROWABLE_LINES;
+
+    // ---- Mutable state, populated during the build ----
+
+    /** Per-project mojo tracking: project key -> queue of in-flight/completed 
mojos. */
+    private final Map<String, Queue<MojoTiming>> mojoTimings = new 
ConcurrentHashMap<>();
+
+    /** Per-project start instants for duration computation. */
+    private final Map<String, Instant> projectStartTimes = new 
ConcurrentHashMap<>();
+
+    /** Per-project trace context captured when the project starts. */
+    private final Map<String, TraceContext> projectTraceContexts = new 
ConcurrentHashMap<>();
+
+    /** Per-mojo start instants for duration computation. */
+    private final Map<String, Instant> mojoStartTimes = new 
ConcurrentHashMap<>();
+
+    /** Per-mojo trace context captured when the mojo starts. */
+    private final Map<String, TraceContext> mojoTraceContexts = new 
ConcurrentHashMap<>();
+
+    /** Per-project build status tracked from project events. */
+    private final Map<String, BuildStatus> projectStatuses = new 
ConcurrentHashMap<>();
+
+    /** Per-project build duration tracked from start/finish events. */
+    private final Map<String, Duration> projectDurations = new 
ConcurrentHashMap<>();
+
+    /** Per-project failure causes. */
+    private final Map<String, Throwable> projectFailures = new 
ConcurrentHashMap<>();
+
+    /** Session-level state - set once on SessionStarted. */
+    // visible for testing
+    volatile Session session;
+
+    /** Build invocation - captured once at SessionStarted, immutable 
thereafter. */
+    private volatile BuildInvocation buildInvocation;
+
+    /** Session start time. */
+    private volatile Instant sessionStartTime;
+
+    /** JVM shutdown hook used to persist a partial build report on unexpected 
termination. */
+    // visible for testing
+    volatile Thread shutdownHook;
+
+    /** Ensures that normal completion and shutdown hook do not write 
competing reports. */
+    // visible for testing
+    final AtomicBoolean reportWritten = new AtomicBoolean();
+
+    // ---- Log capture state ----
+
+    /**
+     * Maps thread ID -> mojo key for the currently-executing mojo on that 
thread.
+     * Lifecycle events and mojo execution run on the same thread, so this is 
safe
+     * for parallel builds with {@code -T}.
+     */
+    private final Map<Long, String> currentMojoByThread = new 
ConcurrentHashMap<>();
+
+    /** Per-mojo log buffers: mojo key -> captured log events. */
+    private final Map<String, BlockingQueue<LogEvent>> mojoLogBuffers = new 
ConcurrentHashMap<>();
+
+    /**
+     * Maps thread ID -> project key for the currently-building project on 
that thread.
+     * Used to route log events that occur between mojo executions to the 
subproject-level buffer.
+     */
+    private final Map<Long, String> currentProjectByThread = new 
ConcurrentHashMap<>();
+
+    /** Per-subproject log buffers: project key -> events captured outside any 
mojo. */
+    private final Map<String, BlockingQueue<LogEvent>> subprojectLogBuffers = 
new ConcurrentHashMap<>();
+
+    /** Build-level log buffer: events captured outside any subproject 
lifecycle. Created at session start. */
+    private volatile BlockingQueue<LogEvent> buildLogBuffer = new 
ArrayBlockingQueue<>(500);
+
+    // ---- LogSink implementation ----
+
+    /**
+     * Receives pre-formed {@link LogEvent} objects from {@code 
ProjectBuildLogAppender}.
+     * Routes to the appropriate buffer (mojo, subproject, or build-level) 
based on
+     * the current thread's lifecycle context.
+     * <p>
+     * No-op when no session is active.
+     */
+    @Override
+    public void accept(LogEvent event) {
+        // No-op when no session is active
+        if (session == null) {
+            return;
+        }
+        long threadId = Thread.currentThread().getId();
+        // 1. Mojo-level
+        String mKey = currentMojoByThread.get(threadId);
+        if (mKey != null) {
+            BlockingQueue<LogEvent> buffer = mojoLogBuffers.get(mKey);
+            if (buffer != null) {
+                buffer.offer(event);
+            }
+            return;
+        }
+        // 2. Module-level
+        String pKey = currentProjectByThread.get(threadId);
+        if (pKey != null) {
+            BlockingQueue<LogEvent> buffer = subprojectLogBuffers.get(pKey);
+            if (buffer != null) {
+                buffer.offer(event);
+            }
+            return;
+        }
+        // 3. Build-level
+        buildLogBuffer.offer(event);
+    }
+
+    // ---- ExecutionListener typed callbacks ----
+
+    @Override
+    public void sessionStarted(ExecutionEvent event) {
+        this.session = event.session();
+        this.sessionStartTime = MonotonicClock.now();
+        // Read configurable caps from session properties (or fall back to 
defaults)
+        this.reportEnabled = readBooleanProperty(session, 
Constants.MAVEN_BUILD_REPORT_ENABLED, true);
+        this.includePii = readBooleanProperty(session, 
Constants.MAVEN_BUILD_REPORT_INCLUDE_PII, false);
+        this.maxLogEventsPerScope = readIntProperty(session, 
Constants.MAVEN_BUILD_REPORT_MAX_LOG_EVENTS, 500);
+        this.maxStacktraceLines = readIntProperty(
+                session, Constants.MAVEN_BUILD_REPORT_MAX_STACKTRACE_LINES, 
DEFAULT_MAX_STACKTRACE_LINES);
+        this.maxThrowableLines = readIntProperty(
+                session,
+                Constants.MAVEN_BUILD_REPORT_MAX_THROWABLE_LINES,
+                BuildReportJsonWriter.DEFAULT_MAX_THROWABLE_LINES);
+        this.buildLogBuffer = new 
ArrayBlockingQueue<>(this.maxLogEventsPerScope);
+        this.buildInvocation = session.buildInvocation();
+        if (this.buildInvocation == null) {
+            this.buildInvocation = DefaultBuildInvocation.from(session);
+        }
+        if (!includePii && this.buildInvocation instanceof 
DefaultBuildInvocation inv) {
+            // Strip potentially sensitive system properties from the report 
unless opted in.
+            // Note: this guard only applies when session.buildInvocation() 
returns a
+            // DefaultBuildInvocation (the standard runtime). Embedders that 
supply a custom
+            // BuildInvocation implementation are responsible for filtering 
PII themselves.
+            Map<String, String> filtered = new 
java.util.TreeMap<>(inv.systemInfo());
+            filtered.remove("user.home");
+            filtered.remove("user.name");
+            this.buildInvocation = new DefaultBuildInvocation(
+                    inv.goals(),
+                    inv.userProperties(),
+                    java.util.Collections.unmodifiableMap(filtered),
+                    inv.activeProfiles(),
+                    inv.selectedProjects(),
+                    inv.excludedProjects(),
+                    inv.makeBehavior(),
+                    inv.resumeFrom(),
+                    inv.reactorFailureBehavior(),
+                    inv.offline(),
+                    inv.updateSnapshots(),
+                    inv.batchMode(),
+                    inv.recursive(),
+                    inv.resume(),
+                    inv.threads());
+        }
+        // Remove any leftover hook from a previous build (mvnd / embedded 
Maven reuse).
+        // Must be done before resetting reportWritten to prevent the old hook 
from firing
+        // against the new session's state.
+        removeShutdownHook();
+        this.reportWritten.set(false);
+
+        if (!reportEnabled) {
+            return;
+        }
+
+        Thread hook = new Thread(
+                () -> {
+                    Session activeSession = this.session;
+                    if (activeSession == null || 
!reportWritten.compareAndSet(false, true)) {
+                        return;
+                    }
+                    try {
+                        LOGGER.debug("JVM shutting down: writing partial build 
report");
+                        // hasFailure=true: an interrupted build is always a 
failure.
+                        BuildReport report = buildReport(activeSession, true);
+                        writeReport(report, activeSession);
+                    } catch (Exception e) {
+                        LOGGER.warn("Failed to write partial build report 
during shutdown", e);
+                    }
+                },
+                "maven-build-report-shutdown-hook");
+
+        try {
+            Runtime.getRuntime().addShutdownHook(hook);
+            this.shutdownHook = hook;
+        } catch (IllegalStateException e) {
+            LOGGER.debug("JVM shutdown already in progress", e);
+        }
+    }
+
+    @Override
+    public void sessionEnded(ExecutionEvent event) {
+        removeShutdownHook();
+
+        Session endSession = event.session();
+        if (!reportEnabled || endSession == null || 
!reportWritten.compareAndSet(false, true)) {
+            clearSessionState();
+            return;
+        }
+
+        try {
+            boolean hasFailure = event.exception().isPresent();
+            BuildReport report = buildReport(endSession, hasFailure);
+            writeReport(report, endSession);
+        } catch (Exception e) {
+            // Never let the report collector crash the build
+            LOGGER.debug("Failed to produce build report: {}", e.getMessage(), 
e);
+        } finally {
+            clearSessionState();
+        }
+    }
+
+    @Override
+    public void projectStarted(ExecutionEvent event) {
+        event.project().ifPresent(project -> {
+            String key = projectKey(project);
+            projectStartTimes.put(key, MonotonicClock.now());
+            projectTraceContexts.put(key, currentTraceContext());
+            mojoTimings.putIfAbsent(key, new ConcurrentLinkedQueue<>());
+            subprojectLogBuffers.put(key, new 
ArrayBlockingQueue<>(maxLogEventsPerScope));
+            currentProjectByThread.put(Thread.currentThread().getId(), key);
+        });
+    }
+
+    @Override
+    public void projectSucceeded(ExecutionEvent event) {
+        event.project().ifPresent(project -> {
+            String key = projectKey(project);
+            Instant start = projectStartTimes.get(key);
+            Instant now = MonotonicClock.now();
+            projectStatuses.put(key, BuildStatus.SUCCESS);
+            if (start != null) {
+                projectDurations.put(key, Duration.between(start, now));
+            }
+        });
+        currentProjectByThread.remove(Thread.currentThread().getId());
+    }
+
+    @Override
+    public void projectFailed(ExecutionEvent event) {
+        event.project().ifPresent(project -> {
+            String key = projectKey(project);
+            Instant start = projectStartTimes.get(key);
+            Instant now = MonotonicClock.now();
+            projectStatuses.put(key, BuildStatus.FAILURE);
+            if (start != null) {
+                projectDurations.put(key, Duration.between(start, now));
+            }
+            event.exception().ifPresent(ex -> projectFailures.put(key, ex));
+        });
+        currentProjectByThread.remove(Thread.currentThread().getId());
+    }
+
+    @Override
+    public void projectSkipped(ExecutionEvent event) {
+        event.project().ifPresent(project -> {
+            String key = projectKey(project);
+            projectStatuses.put(key, BuildStatus.SKIPPED);
+        });
+        currentProjectByThread.remove(Thread.currentThread().getId());
+    }
+
+    @Override
+    public void mojoStarted(ExecutionEvent event) {
+        event.project()
+                .ifPresent(project -> event.mojoExecution().ifPresent(mojo -> {
+                    String mKey = mojoKey(project, mojo);
+                    mojoStartTimes.put(mKey, MonotonicClock.now());
+                    mojoTraceContexts.put(mKey, currentTraceContext());
+
+                    currentMojoByThread.put(Thread.currentThread().getId(), 
mKey);
+                    mojoLogBuffers.put(mKey, new 
ArrayBlockingQueue<>(maxLogEventsPerScope));
+                }));
+    }
+
+    @Override
+    public void mojoSucceeded(ExecutionEvent event) {
+        onMojoFinished(event, BuildStatus.SUCCESS);
+    }
+
+    @Override
+    public void mojoFailed(ExecutionEvent event) {
+        onMojoFinished(event, BuildStatus.FAILURE);
+    }
+
+    @Override
+    public void mojoSkipped(ExecutionEvent event) {
+        event.project()
+                .ifPresent(project -> event.mojoExecution().ifPresent(mojo -> {
+                    String pKey = projectKey(project);
+                    Instant now = MonotonicClock.now();
+                    TraceContext traceContext = TraceContext.EMPTY;
+
+                    MojoTiming timing = new MojoTiming(
+                            mojo.plugin().getModel().groupId(),
+                            mojo.plugin().getModel().artifactId(),
+                            mojo.plugin().getModel().version(),
+                            mojo.goal(),
+                            mojo.executionId().orElse(null),
+                            mojo.lifecyclePhase().orElse(null),
+                            BuildStatus.SKIPPED,
+                            now,
+                            Duration.ZERO,
+                            traceContext.traceId,
+                            traceContext.spanId,
+                            Thread.currentThread().getName(),
+                            List.of());
+
+                    mojoTimings
+                            .computeIfAbsent(pKey, k -> new 
ConcurrentLinkedQueue<>())
+                            .add(timing);
+                }));
+    }
+
+    private void onMojoFinished(ExecutionEvent event, BuildStatus status) {
+        event.project()
+                .ifPresent(project -> event.mojoExecution().ifPresent(mojo -> {
+                    String mKey = mojoKey(project, mojo);
+                    String pKey = projectKey(project);
+
+                    // Unregister the mojo from this thread
+                    currentMojoByThread.remove(Thread.currentThread().getId());
+
+                    Instant now = MonotonicClock.now();
+                    Instant startInstant = mojoStartTimes.remove(mKey);
+                    TraceContext traceContext = mojoTraceContexts.remove(mKey);
+                    if (traceContext == null) {
+                        traceContext = TraceContext.EMPTY;
+                    }
+                    if (startInstant == null) {
+                        startInstant = now;
+                    }
+                    Duration duration = Duration.between(startInstant, now);
+
+                    // Drain the log buffer for this mojo
+                    BlockingQueue<LogEvent> logBuffer = 
mojoLogBuffers.remove(mKey);
+                    List<LogEvent> output = logBuffer != null ? new 
ArrayList<>(logBuffer) : List.of();
+
+                    MojoTiming timing = new MojoTiming(
+                            mojo.plugin().getModel().groupId(),
+                            mojo.plugin().getModel().artifactId(),
+                            mojo.plugin().getModel().version(),
+                            mojo.goal(),
+                            mojo.executionId().orElse(null),
+                            mojo.lifecyclePhase().orElse(null),
+                            status,
+                            startInstant,
+                            duration,
+                            traceContext.traceId,
+                            traceContext.spanId,
+                            Thread.currentThread().getName(),
+                            output);
+
+                    mojoTimings
+                            .computeIfAbsent(pKey, k -> new 
ConcurrentLinkedQueue<>())
+                            .add(timing);
+                }));
+    }
+
+    // ---- State management ----
+
+    /**
+     * Removes the currently-registered JVM shutdown hook, if any.
+     * Safe to call when no hook is registered, or when shutdown is already in 
progress.
+     * Called from {@link #sessionStarted} (to clean up a leftover hook from a 
previous build)
+     * and from {@link #sessionEnded} (normal lifecycle cleanup).
+     */
+    private void removeShutdownHook() {
+        Thread hook = shutdownHook;
+        if (hook != null) {
+            try {
+                Runtime.getRuntime().removeShutdownHook(hook);
+            } catch (IllegalStateException e) {
+                LOGGER.debug("JVM shutdown already in progress", e);
+            } catch (SecurityException e) {
+                LOGGER.debug("Unable to remove build report shutdown hook", e);
+            } finally {
+                shutdownHook = null;
+            }
+        }
+    }
+
+    /**
+     * Resets all mutable per-session fields. Called at the end of each 
session so that
+     * when the DI container (e.g. mvnd) reuses this singleton across builds 
the maps do
+     * not accumulate stale data from prior builds.
+     */
+    private void clearSessionState() {
+        mojoTimings.clear();
+        projectStartTimes.clear();
+        projectTraceContexts.clear();
+        mojoStartTimes.clear();
+        mojoTraceContexts.clear();
+        projectStatuses.clear();
+        projectDurations.clear();
+        projectFailures.clear();
+        currentMojoByThread.clear();
+        mojoLogBuffers.clear();
+        currentProjectByThread.clear();
+        subprojectLogBuffers.clear();
+        buildLogBuffer.clear();

Review Comment:
   🟡 **`stepReportData` is not cleared here.** `clearSessionState()` resets 
every per-session map but omits `stepReportData`. In Maven daemon (mvnd) or 
embedded Maven reuse scenarios, step data from a previous build will appear in 
the next build's report.
   
   Add: `if (stepReportData != null) { stepReportData.clear(); }`



##########
impl/maven-impl/src/main/java/org/apache/maven/impl/build/DefaultBuildInvocation.java:
##########
@@ -86,22 +86,16 @@ public record DefaultBuildInvocation(
     /**
      * Creates a {@link BuildInvocation} snapshot from the current session 
state.

Review Comment:
   🟡 **Javadoc overstates method scope (raised 3× previously).** `"Creates a 
{@link BuildInvocation} snapshot from the current session state"` implies full 
state capture, but `goals`, `activeProfiles`, `selectedProjects`, 
`excludedProjects`, `makeBehavior`, and `resumeFrom` all default to 
`List.of()`. Only `userProperties`, `systemInfo`, and `threads` come from the 
session.
   
   Suggest: `"Creates a minimal {@link BuildInvocation} with user properties, 
system info, and concurrency settings from the given session."`



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to