From db21cbb8abe11c200e109c5f01598a3c30a8babb Mon Sep 17 00:00:00 2001 From: Carlos Villela Date: Fri, 28 Aug 2026 18:35:19 -0700 Subject: [PATCH 01/22] feat(maintainer): export PR lifetime traces Signed-off-by: Carlos Villela --- .../SKILL.md | 44 +- .../scripts/analyze-pr-value-stream.mts | 15 +- .../scripts/export-pr-lifetime-trace.mts | 747 ++++++++++++++++++ .../scripts/validate-chrome-trace.mts | 67 ++ .../analyze-pr-value-stream.test.ts | 48 +- 5 files changed, 896 insertions(+), 25 deletions(-) create mode 100644 .agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts create mode 100644 .agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/validate-chrome-trace.mts diff --git a/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/SKILL.md b/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/SKILL.md index dea5f6645f2..f60cb7cf03a 100644 --- a/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/SKILL.md +++ b/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/SKILL.md @@ -1,6 +1,6 @@ --- name: nemoclaw-maintainer-analyze-pr-value-stream -description: Analyze one NemoClaw pull request from its earliest observable branch push through merge. Separates approval delay from automation time and compares the latest revision with a target. Use for PR latency, value-stream, bottleneck, or ten-minute-target analysis. +description: Analyze one NemoClaw pull request across its complete observable lifetime. Produces a bounded Perfetto trace and summary, separates contributor, review, and automation time, and compares the latest revision with a target. Use for PR latency, value-stream, bottleneck, timeline, or ten-minute-target analysis. user_invocable: true --- @@ -9,18 +9,18 @@ user_invocable: true # Analyze a Pull Request Value Stream -Run the deterministic read-only analyzer for one pull request. The analyzer uses authenticated GitHub reads and emits bounded JSON. +Run the deterministic read-only analyzer once for one pull request. Every invocation collects the complete observable retained lifetime. It writes a Perfetto-compatible trace, summary, and manifest under `.nemoclaw-maintainer/pr-value-stream/pr-/` and emits the summary as bounded JSON on stdout. + +Do not run a reduced or latest-revision-only analysis. The latest-revision waterfall remains one derived part of the complete lifetime result. ## Prerequisites - Run from a NemoClaw checkout with authenticated `gh` access. - Use Node.js 22.19 or later with type stripping enabled. -- Retained Vitest artifact timing is conditional: install this checkout’s dependencies so `node_modules/vitest/vitest.mjs` is available, and install `zipinfo` and `unzip`. The analyzer still returns the bounded report when these optional tools or an artifact are unavailable, with the failure recorded in `caveats`. +- Retained Vitest artifact timing is conditional: install this checkout's dependencies so `node_modules/vitest/vitest.mjs` is available, and install `zipinfo` and `unzip`. Optional artifact failures appear in `caveats` and do not become test-timing evidence. ## Run the analysis -Use the default ten-minute target: - ```bash node --experimental-strip-types --no-warnings \ .agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/analyze-pr-value-stream.mts \ @@ -28,20 +28,21 @@ node --experimental-strip-types --no-warnings \ --number ``` -The default repository is `NVIDIA/NemoClaw`. Use `--repository OWNER/REPO` only when the user requests another repository. +The default repository is `NVIDIA/NemoClaw`. Use `--repository OWNER/REPO` only when the user requests another repository. The ten-minute target defaults to 10; use `--target-minutes` only when the user requests another target. + +The analyzer owns completeness and safety bounds. Do not use legacy pagination or truncation options to reduce the standard analysis. If required retained history exceeds a bound, the command fails rather than calling a partial trace complete. -Use these comparison-friendly options. Keep every option equal when comparing pull requests: +## Outputs -| Option | Default | Accepted value | -|---|---:|---:| -| `--target-minutes` | `10` | Greater than 0, at most 1440 | -| `--max-run-pages` | `3` | Integer from 1 through 10 | -| `--max-check-pages` | `3` | Integer from 1 through 10 | -| `--max-automation-runs` | `50` | Integer from 1 through 100 | -| `--max-test-artifacts` | `12` | Integer from 0 through 24 | -| `--top-tests-per-shard` | `10` | Integer from 1 through 25 | +A successful invocation writes: -Use `--max-test-artifacts 0` to skip artifact downloads. +- `summary.json`: the complete bounded value-stream report printed on stdout. +- `trace.json`: Chrome Trace Event JSON for Perfetto or `chrome://tracing`. +- `manifest.json`: exact pull request identity, head commit, output sizes, and completeness declarations. This file is written last. + +The trace contains lifecycle events, all retained PR revisions, workflows, job queues, job executions, steps, external checks, reviews, comments, inline feedback, commit publication spans, and temporal feedback-to-next-change spans. + +Open `trace.json` in Perfetto to zoom, filter categories, inspect event arguments, and measure arbitrary intervals. ## Interpret the result @@ -50,12 +51,15 @@ Report these fields first: 1. `target.status` and `target.theoreticalFastestSeconds`. 2. The largest entries in `bottlenecks`. 3. `elapsed.approvalDelaySeconds` and `elapsed.mergeLagAfterReadySeconds`. -4. `waterfall.runsTruncated` and all applicable `caveats`. +4. The `lifetime` artifact paths and counts. +5. All applicable `caveats`. -Do not describe a fallback branch timestamp as exact. Do not claim causal attribution from the counterfactual approval calculation. A truncated run set is incomplete evidence. Treat null timing fields as queued or otherwise not yet observed. Treat artifact failure caveats as status evidence, not test timing evidence. +Do not describe a fallback branch timestamp as exact. Do not claim causal attribution from temporal feedback-to-change spans or counterfactual approval calculations. Treat null timing fields as queued or otherwise unobserved. Treat artifact failure caveats as status evidence, not test timing evidence. ## Trust boundaries -The script performs no GitHub writes. It invokes executables with argument arrays and rejects unknown or duplicate options. It bounds GitHub output, pagination, job counts, artifact sizes, extracted data, and final JSON. +The script performs no GitHub writes. It invokes executables with argument arrays, bounds GitHub output, pagination, revisions, workflow runs, jobs, trace events, artifact sizes, and file sizes, and rejects malformed or incomplete required history. + +GitHub does not expose canonical branch-creation timestamps or pull request description edit history. The trace uses the first retained exact-commit workflow as an observable push signal and records that limitation. Draft transitions appear only when GitHub's timeline returns them. -When retained CLI shard artifacts are enabled, the script accepts only an exact run and commit match, one regular `blob-*.json` ZIP entry, and bounded compressed and expanded sizes. It uses a private temporary directory and removes that directory after the attempt. +When retained CLI shard artifacts are available, the script accepts only an exact run and commit match, one regular `blob-*.json` ZIP entry, and bounded compressed and expanded sizes. It uses a private temporary directory and removes it after the attempt. diff --git a/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/analyze-pr-value-stream.mts b/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/analyze-pr-value-stream.mts index e23dedbd01c..b537ede7449 100644 --- a/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/analyze-pr-value-stream.mts +++ b/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/analyze-pr-value-stream.mts @@ -8,6 +8,8 @@ import path from "node:path"; import { promisify } from "node:util"; import { fileURLToPath, pathToFileURL } from "node:url"; +import { exportLifetimeTrace, type LifetimeArtifacts } from "./export-pr-lifetime-trace.mts"; + const execFileAsync = promisify(execFile); const MAX_GH_OUTPUT = 10_000_000; const MAX_JSON_OUTPUT = 4_000_000; @@ -26,6 +28,7 @@ type Input = { export type ValueStreamReport = { measuredAt: string; + lifetime?: LifetimeArtifacts; repository: string; number: number; url: string; @@ -1498,7 +1501,17 @@ function parseArguments(argv: string[]): Input { } async function main(): Promise { - const report = await analyzePrValueStream(parseArguments(process.argv.slice(2))); + const input = parseArguments(process.argv.slice(2)); + const normalized = normalizeAnalysisInput(input); + const report = await collectValueStreamReport(normalized); + const lifetime = await exportLifetimeTrace({ + workdir: normalized.workdir, + repository: normalized.repository, + number: normalized.number, + report, + githubRead: async (args) => runGithubCli({ workdir: normalized.workdir, args }), + }); + void lifetime; const output = `${JSON.stringify(report, null, 2)}\n`; if (Buffer.byteLength(output) > MAX_JSON_OUTPUT) throw new Error("value-stream JSON exceeded the 4 MB output bound"); diff --git a/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts b/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts new file mode 100644 index 00000000000..2b0745b6e3f --- /dev/null +++ b/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts @@ -0,0 +1,747 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { mkdir, rename, rm, writeFile } from "node:fs/promises"; +import path from "node:path"; + +import { validateChromeTrace } from "./validate-chrome-trace.mts"; + +const MAX_PAGES = 10; +const MAX_REVISIONS = 250; +const MAX_WORKFLOW_RUNS = 2_000; +const MAX_JOBS = 10_000; +const MAX_TRACE_EVENTS = 250_000; +const MAX_TRACE_BYTES = 100_000_000; +const PAGE_SIZE = 100; +const READ_CONCURRENCY = 8; + +type GithubRead = (args: string[]) => Promise<{ stdout: string }>; + +type TraceEvent = { + name: string; + cat?: string; + ph: "M" | "i" | "X"; + ts?: number; + dur?: number; + pid: number; + tid: number; + s?: "t"; + args: Record; +}; + +type Commit = { + oid: string; + authoredAt: number; + committedAt: number; + subject: string; +}; + +type Run = { + id: number; + event: string; + head_sha: string; + created_at: string; + run_started_at: string | null; + updated_at: string; + status: string; + conclusion: string | null; + name: string; + html_url: string; +}; + +export type LifetimeArtifacts = { + directory: string; + summary: string; + trace: string; + traceEvents: number; + lifecycleEvents: number; + revisions: number; + workflowRuns: number; + jobs: number; + externalChecks: number; + manifest: string; + truncated: false; + caveats: string[]; +}; + +type ExportInput = { + workdir: string; + repository: string; + number: number; + report: unknown; + githubRead: GithubRead; +}; + +function parseTime(value: unknown, label: string): number { + if (typeof value !== "string" || !Number.isFinite(Date.parse(value))) + throw new Error(label + " was not a valid timestamp"); + return Date.parse(value); +} + +function optionalTime(value: unknown): number | null { + return typeof value === "string" && Number.isFinite(Date.parse(value)) ? Date.parse(value) : null; +} + +function micros(milliseconds: number): number { + return Math.round(milliseconds * 1_000); +} + +function boundedText(value: unknown, maximum = 300): string { + return typeof value === "string" ? value.slice(0, maximum) : ""; +} + +function validateArray(value: unknown, label: string): any[] { + if (!Array.isArray(value)) throw new Error(label + " response was not an array"); + return value; +} + +async function readPages(input: { + githubRead: GithubRead; + endpoint: string; + projection: string; + label: string; +}): Promise<{ rows: any[]; truncated: boolean }> { + const rows: any[] = []; + for (let page = 1; page <= MAX_PAGES; page += 1) { + const separator = input.endpoint.includes("?") ? "&" : "?"; + const result = await input.githubRead([ + "api", + input.endpoint + separator + "per_page=" + PAGE_SIZE + "&page=" + page, + "--jq", + input.projection, + ]); + const pageRows = validateArray(JSON.parse(result.stdout), input.label); + rows.push(...pageRows); + if (pageRows.length < PAGE_SIZE) return { rows, truncated: false }; + } + return { rows, truncated: true }; +} + +async function mapBounded(values: T[], operation: (value: T) => Promise): Promise { + const result: R[] = []; + for (let index = 0; index < values.length; index += READ_CONCURRENCY) { + result.push( + ...(await Promise.all(values.slice(index, index + READ_CONCURRENCY).map(operation))), + ); + } + return result; +} + +function addMetadata( + events: TraceEvent[], + pid: number, + tid: number, + processName: string, + threadName: string, +): void { + if ( + !events.some((event) => event.ph === "M" && event.name === "process_name" && event.pid === pid) + ) + events.push({ name: "process_name", ph: "M", pid, tid: 0, args: { name: processName } }); + if ( + !events.some( + (event) => + event.ph === "M" && event.name === "thread_name" && event.pid === pid && event.tid === tid, + ) + ) + events.push({ name: "thread_name", ph: "M", pid, tid, args: { name: threadName } }); +} + +function addInstant( + events: TraceEvent[], + input: { + name: string; + category: string; + at: number; + pid: number; + tid: number; + args?: TraceEvent["args"]; + }, +): void { + events.push({ + name: input.name, + cat: input.category, + ph: "i", + s: "t", + ts: micros(input.at), + pid: input.pid, + tid: input.tid, + args: input.args ?? {}, + }); +} + +function addSpan( + events: TraceEvent[], + input: { + name: string; + category: string; + start: number | null; + end: number | null; + pid: number; + tid: number; + args?: TraceEvent["args"]; + }, +): void { + if (input.start === null) return; + if (input.end === null || input.end < input.start) { + addInstant(events, { + name: input.name + " — timing incomplete", + category: input.category, + at: input.start, + pid: input.pid, + tid: input.tid, + args: { ...(input.args ?? {}), timingIncomplete: true }, + }); + return; + } + events.push({ + name: input.name, + cat: input.category, + ph: "X", + ts: micros(input.start), + dur: micros(input.end - input.start), + pid: input.pid, + tid: input.tid, + args: input.args ?? {}, + }); +} + +function normalizeCommits(pull: any): Commit[] { + const rows = validateArray(pull?.commits, "pull request commits"); + if (rows.length < 1 || rows.length > MAX_REVISIONS) + throw new Error("lifetime trace requires between 1 and " + MAX_REVISIONS + " revisions"); + return rows.map((commit: any) => ({ + oid: String(commit?.oid ?? ""), + authoredAt: parseTime(commit?.authoredDate ?? commit?.committedDate, "commit authoredDate"), + committedAt: parseTime(commit?.committedDate, "commit committedDate"), + subject: + boundedText(commit?.messageHeadline, 200) || + "Commit " + String(commit?.oid ?? "").slice(0, 8), + })); +} + +async function readPull(input: ExportInput): Promise { + const result = await input.githubRead([ + "pr", + "view", + String(input.number), + "--repo", + input.repository, + "--json", + "number,url,state,isDraft,createdAt,mergedAt,updatedAt,author,assignees,baseRefName,headRefName,headRefOid,commits,reviews", + ]); + const pull = JSON.parse(result.stdout); + if (pull?.number !== input.number || typeof pull?.url !== "string") + throw new Error("GitHub pull request response did not match the lifetime trace contract"); + return pull; +} + +async function readRuns( + input: ExportInput, + branch: string, + commitIds: Set, +): Promise<{ rows: Run[]; truncated: boolean }> { + const collection = await readPages({ + githubRead: input.githubRead, + endpoint: "repos/" + input.repository + "/actions/runs?branch=" + encodeURIComponent(branch), + projection: + "[.workflow_runs[] | {id,event,head_sha,created_at,run_started_at,updated_at,status,conclusion,name,html_url}]", + label: "workflow runs", + }); + if (collection.truncated) throw new Error("workflow history exceeded the bounded lifetime pages"); + const rows = collection.rows.filter( + (run) => commitIds.has(run?.head_sha) && Number.isSafeInteger(run?.id), + ); + if (rows.length > MAX_WORKFLOW_RUNS) + throw new Error("lifetime workflow history exceeded " + MAX_WORKFLOW_RUNS + " runs"); + return { rows: rows as Run[], truncated: collection.truncated }; +} + +async function readJobs(input: ExportInput, runs: Run[]): Promise { + const groups = await mapBounded(runs, async (run) => { + const result = await input.githubRead([ + "api", + "repos/" + input.repository + "/actions/runs/" + run.id + "/jobs?per_page=100", + "--jq", + "{total_count,jobs:[.jobs[] | {id,name,status,conclusion,created_at,started_at,completed_at,runner_name,runner_group_name,labels,html_url,steps}]}", + ]); + const payload = JSON.parse(result.stdout); + const jobs = validateArray(payload?.jobs, "workflow jobs"); + if (Number(payload?.total_count) > jobs.length) + throw new Error("workflow " + run.id + " exceeded the 100-job lifetime trace bound"); + return jobs.map((job) => ({ ...job, run })); + }); + const jobs = groups.flat(); + if (jobs.length > MAX_JOBS) + throw new Error("lifetime workflow history exceeded " + MAX_JOBS + " jobs"); + return jobs; +} + +async function readExternalChecks(input: ExportInput, commits: Commit[]): Promise { + const groups = await mapBounded(commits, async (commit) => { + const collection = await readPages({ + githubRead: input.githubRead, + endpoint: "repos/" + input.repository + "/commits/" + commit.oid + "/check-runs", + projection: + "[.check_runs[] | {id,name,status,conclusion,created_at,started_at,completed_at,html_url,app:{id:.app.id,slug:.app.slug}}]", + label: "check runs", + }); + if (collection.truncated) + throw new Error("check runs exceeded the bounded lifetime pages for " + commit.oid); + return collection.rows + .filter((check) => check?.app?.slug !== "github-actions") + .map((check) => ({ ...check, commit })); + }); + return groups.flat(); +} + +async function readLifecycle( + input: ExportInput, +): Promise<{ timeline: any[]; comments: any[]; inline: any[]; truncated: boolean }> { + const [timeline, comments, inline] = await Promise.all([ + readPages({ + githubRead: input.githubRead, + endpoint: "repos/" + input.repository + "/issues/" + input.number + "/timeline", + projection: + "[.[] | {id,event,created_at,actor:(.actor.login // null),commit_id,label:(.label.name // null),requested_reviewer:(.requested_reviewer.login // null),rename}]", + label: "pull request timeline", + }), + readPages({ + githubRead: input.githubRead, + endpoint: "repos/" + input.repository + "/issues/" + input.number + "/comments", + projection: "[.[] | {id,created_at,updated_at,user:(.user.login // null),html_url}]", + label: "pull request comments", + }), + readPages({ + githubRead: input.githubRead, + endpoint: "repos/" + input.repository + "/pulls/" + input.number + "/comments", + projection: + "[.[] | {id,created_at,updated_at,user:(.user.login // null),path,line,commit_id,html_url,in_reply_to_id}]", + label: "pull request review comments", + }), + ]); + return { + timeline: timeline.rows, + comments: comments.rows, + inline: inline.rows, + truncated: timeline.truncated || comments.truncated || inline.truncated, + }; +} + +function renderTrace(input: { + pull: any; + commits: Commit[]; + runs: Run[]; + jobs: any[]; + externalChecks: any[]; + lifecycle: Awaited>; +}): { events: TraceEvent[]; lifecycleEvents: number } { + const events: TraceEvent[] = []; + addMetadata(events, 1, 1, "PR #" + input.pull.number, "Lifecycle"); + addMetadata(events, 2, 1, "Author activity", input.pull.author?.login ?? "author"); + addMetadata(events, 3, 1, "Feedback and reviews", "Comments and reviews"); + let lifecycleEvents = 0; + const instant = (entry: Parameters[1]): void => { + lifecycleEvents += 1; + addInstant(events, entry); + }; + const opened = parseTime(input.pull.createdAt, "pull request createdAt"); + const merged = optionalTime(input.pull.mergedAt); + const observedEnd = merged ?? optionalTime(input.pull.updatedAt); + addSpan(events, { + name: "Pull request lifetime", + category: "pr.lifecycle", + start: opened, + end: observedEnd, + pid: 1, + tid: 1, + args: { state: input.pull.state, url: input.pull.url }, + }); + instant({ + name: "Pull request opened" + (input.pull.isDraft ? " as draft" : " for review"), + category: "pr.lifecycle", + at: opened, + pid: 1, + tid: 1, + args: { actor: input.pull.author?.login ?? null, url: input.pull.url, state: input.pull.state }, + }); + for (const row of input.lifecycle.timeline) { + const at = optionalTime(row?.created_at); + if (at === null || ["commented", "reviewed", "committed"].includes(String(row?.event))) + continue; + instant({ + name: String(row.event).replaceAll("_", " "), + category: "pr.timeline", + at, + pid: 1, + tid: 1, + args: { + actor: row.actor ?? null, + label: row.label ?? null, + requestedReviewer: row.requested_reviewer ?? null, + renameFrom: row.rename?.from ?? null, + renameTo: row.rename?.to ?? null, + }, + }); + } + for (const review of validateArray(input.pull.reviews ?? [], "pull request reviews")) { + const submitted = optionalTime(review?.submittedAt); + if (submitted === null) continue; + instant({ + name: "Review " + String(review.state ?? "submitted").toLowerCase(), + category: "review.submission", + at: submitted, + pid: 3, + tid: 1, + args: { actor: review.author?.login ?? null, commit: review.commit?.oid ?? null }, + }); + } + for (const row of input.lifecycle.comments) { + const created = optionalTime(row.created_at); + if (created !== null) + instant({ + name: "Comment added", + category: "review.comment", + at: created, + pid: 3, + tid: 1, + args: { id: row.id, actor: row.user, url: row.html_url ?? null }, + }); + const updated = optionalTime(row.updated_at); + if (created !== null && updated !== null && updated !== created) + instant({ + name: "Comment updated", + category: "review.comment", + at: updated, + pid: 3, + tid: 1, + args: { id: row.id, actor: row.user, url: row.html_url ?? null }, + }); + } + const feedback: { at: number; row: any }[] = []; + for (const row of input.lifecycle.inline) { + const created = optionalTime(row.created_at); + if (created !== null) { + feedback.push({ at: created, row }); + instant({ + name: "Inline feedback added", + category: "review.feedback", + at: created, + pid: 3, + tid: 1, + args: { + id: row.id, + actor: row.user, + path: boundedText(row.path, 500), + line: row.line ?? null, + commit: row.commit_id ?? null, + url: row.html_url ?? null, + }, + }); + } + const updated = optionalTime(row.updated_at); + if (created !== null && updated !== null && updated !== created) + instant({ + name: "Inline feedback updated", + category: "review.feedback", + at: updated, + pid: 3, + tid: 1, + args: { id: row.id, actor: row.user, url: row.html_url ?? null }, + }); + } + const firstRuns = new Map(); + for (const run of input.runs + .slice() + .sort((a, b) => Date.parse(a.created_at) - Date.parse(b.created_at))) { + if (!firstRuns.has(run.head_sha)) firstRuns.set(run.head_sha, run); + } + for (const [index, commit] of input.commits.entries()) { + const pid = 1_000 + index; + addMetadata(events, pid, 1, "Revision " + commit.oid.slice(0, 8), "Workflows"); + instant({ + name: commit.subject, + category: "author.commit", + at: commit.authoredAt, + pid: 2, + tid: 1, + args: { commit: commit.oid }, + }); + const firstRun = firstRuns.get(commit.oid); + if (firstRun) { + const pushed = parseTime(firstRun.created_at, "workflow createdAt"); + instant({ + name: "Commit push observed", + category: "author.push", + at: pushed, + pid: 2, + tid: 1, + args: { commit: commit.oid, source: "first exact-commit workflow" }, + }); + addSpan(events, { + name: "Commit publication", + category: "author.publish", + start: commit.authoredAt, + end: pushed, + pid: 2, + tid: 1_000 + index, + args: { commit: commit.oid, causality: "not-established" }, + }); + const firstFeedback = feedback.find( + (entry) => entry.at >= pushed && entry.row.commit_id === commit.oid, + ); + if (firstFeedback) { + addSpan(events, { + name: "Waiting for actionable feedback", + category: "author.waiting-for-feedback", + start: pushed, + end: firstFeedback.at, + pid: 2, + tid: 2_000 + index, + args: { commit: commit.oid, feedbackId: firstFeedback.row.id }, + }); + } + } + } + for (const [index, entry] of feedback.entries()) { + const nextCommit = input.commits.find((commit) => commit.authoredAt > entry.at); + if (!nextCommit) continue; + addSpan(events, { + name: "Feedback to next author change", + category: "author.response", + start: entry.at, + end: nextCommit.authoredAt, + pid: 2, + tid: 3_000 + index, + args: { + feedbackId: entry.row.id, + nextCommit: nextCommit.oid, + relationship: "next-author-change", + causality: "not-established", + }, + }); + } + for (const [index, run] of input.runs.entries()) { + const commitIndex = input.commits.findIndex((commit) => commit.oid === run.head_sha); + const pid = 1_000 + Math.max(0, commitIndex); + const tid = 10 + index; + addMetadata(events, pid, tid, "Revision " + run.head_sha.slice(0, 8), run.name + " #" + run.id); + addSpan(events, { + name: run.name, + category: "ci.workflow", + start: optionalTime(run.created_at), + end: optionalTime(run.updated_at), + pid, + tid, + args: { + runId: run.id, + event: run.event, + status: run.status, + conclusion: run.conclusion, + url: run.html_url, + }, + }); + } + for (const [jobIndex, job] of input.jobs.entries()) { + const commitIndex = input.commits.findIndex((commit) => commit.oid === job.run.head_sha); + const pid = 1_000 + Math.max(0, commitIndex); + const tid = 10_000 + jobIndex; + addMetadata( + events, + pid, + tid, + "Revision " + job.run.head_sha.slice(0, 8), + job.run.name + " / " + job.name, + ); + const created = optionalTime(job.created_at); + const started = optionalTime(job.started_at); + const completed = optionalTime(job.completed_at); + addSpan(events, { + name: job.name, + category: "ci.queue", + start: created, + end: started, + pid, + tid, + args: { + jobId: job.id, + runner: job.runner_name ?? null, + runnerGroup: job.runner_group_name ?? null, + }, + }); + addSpan(events, { + name: job.name, + category: "ci.execution", + start: started, + end: completed, + pid, + tid, + args: { + jobId: job.id, + status: job.status, + conclusion: job.conclusion, + url: job.html_url ?? null, + }, + }); + for (const [stepIndex, step] of validateArray(job.steps ?? [], "workflow steps").entries()) { + const stepTid = 1_000_000 + jobIndex * 1_000 + stepIndex; + addMetadata( + events, + pid, + stepTid, + "Revision " + job.run.head_sha.slice(0, 8), + job.name + " / " + step.name, + ); + addSpan(events, { + name: step.name, + category: "ci.step", + start: optionalTime(step.started_at), + end: optionalTime(step.completed_at), + pid, + tid: stepTid, + args: { + jobId: job.id, + number: step.number, + status: step.status, + conclusion: step.conclusion, + }, + }); + } + } + for (const [index, check] of input.externalChecks.entries()) { + const commitIndex = input.commits.findIndex((commit) => commit.oid === check.commit.oid); + const pid = 1_000 + Math.max(0, commitIndex); + const tid = 50_000 + index; + addMetadata(events, pid, tid, "Revision " + check.commit.oid.slice(0, 8), "External checks"); + addSpan(events, { + name: check.name, + category: "ci.external-check", + start: optionalTime(check.started_at ?? check.created_at), + end: optionalTime(check.completed_at), + pid, + tid, + args: { + checkId: check.id, + app: check.app?.slug ?? null, + status: check.status, + conclusion: check.conclusion, + url: check.html_url ?? null, + }, + }); + } + events.sort( + (a, b) => + (a.ts ?? -1) - (b.ts ?? -1) || a.pid - b.pid || a.tid - b.tid || a.name.localeCompare(b.name), + ); + if (events.length > MAX_TRACE_EVENTS) + throw new Error("lifetime trace exceeded " + MAX_TRACE_EVENTS + " events"); + return { events, lifecycleEvents }; +} + +async function writeAtomic(file: string, content: string): Promise { + const temporary = file + ".tmp-" + process.pid; + await writeFile(temporary, content, { mode: 0o600 }); + await rename(temporary, file); +} + +export async function exportLifetimeTrace(input: ExportInput): Promise { + const pull = await readPull(input); + const expectedHead = (input.report as { headSha?: unknown }).headSha; + if (typeof expectedHead !== "string" || pull.headRefOid !== expectedHead) + throw new Error("pull request head changed during lifetime analysis"); + const commits = normalizeCommits(pull); + const runsCollection = await readRuns( + input, + pull.headRefName, + new Set(commits.map((commit) => commit.oid)), + ); + const [jobs, externalChecks, lifecycle] = await Promise.all([ + readJobs(input, runsCollection.rows), + readExternalChecks(input, commits), + readLifecycle(input), + ]); + const rendered = renderTrace({ + pull, + commits, + runs: runsCollection.rows, + jobs, + externalChecks, + lifecycle, + }); + const caveats = [ + "GitHub does not expose a canonical branch-created timestamp. The first exact-commit workflow is the observable push signal.", + "GitHub does not expose pull request description edit history. The trace cannot reconstruct description edits.", + "Feedback-to-change spans identify the next author change. They do not establish causality.", + ]; + if (lifecycle.truncated) + throw new Error("pull request lifecycle exceeded the bounded lifetime pages"); + const relativeDirectory = path.join( + ".nemoclaw-maintainer", + "pr-value-stream", + "pr-" + input.number, + ); + const directory = path.resolve(input.workdir, relativeDirectory); + const tracePath = path.join(directory, "trace.json"); + const summaryPath = path.join(directory, "summary.json"); + const manifestPath = path.join(directory, "manifest.json"); + await mkdir(directory, { recursive: true, mode: 0o700 }); + const generatedAt = new Date().toISOString(); + const trace = + JSON.stringify( + { + traceEvents: rendered.events, + displayTimeUnit: "ms", + metadata: { repository: input.repository, pullRequest: input.number, generatedAt, caveats }, + }, + null, + 2, + ) + "\n"; + if (Buffer.byteLength(trace) > MAX_TRACE_BYTES) + throw new Error("lifetime trace exceeded the 100 MB output bound"); + const artifacts: LifetimeArtifacts = { + directory: relativeDirectory, + summary: path.join(relativeDirectory, "summary.json"), + trace: path.join(relativeDirectory, "trace.json"), + manifest: path.join(relativeDirectory, "manifest.json"), + traceEvents: rendered.events.length, + lifecycleEvents: rendered.lifecycleEvents, + revisions: commits.length, + workflowRuns: runsCollection.rows.length, + jobs: jobs.length, + externalChecks: externalChecks.length, + truncated: false, + caveats, + }; + Object.assign(input.report as object, { lifetime: artifacts }); + const summary = JSON.stringify(input.report, null, 2) + "\n"; + const manifest = + JSON.stringify( + { + schemaVersion: 1, + repository: input.repository, + pullRequest: input.number, + headSha: pull.headRefOid, + generatedAt, + files: { summary: "summary.json", trace: "trace.json" }, + bytes: { summary: Buffer.byteLength(summary), trace: Buffer.byteLength(trace) }, + completeness: { + revisions: "complete", + workflowRuns: "complete", + jobs: "complete", + checks: "complete", + lifecycle: "complete", + }, + }, + null, + 2, + ) + "\n"; + try { + await Promise.all([writeAtomic(tracePath, trace), writeAtomic(summaryPath, summary)]); + await validateChromeTrace(tracePath); + await writeAtomic(manifestPath, manifest); + } catch (error) { + await rm(directory, { recursive: true, force: true }); + throw error; + } + return artifacts; +} diff --git a/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/validate-chrome-trace.mts b/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/validate-chrome-trace.mts new file mode 100644 index 00000000000..db82af9ac8d --- /dev/null +++ b/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/validate-chrome-trace.mts @@ -0,0 +1,67 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { readFile } from "node:fs/promises"; +import path from "node:path"; +import { pathToFileURL } from "node:url"; + +type Event = { + name?: unknown; + ph?: unknown; + ts?: unknown; + dur?: unknown; + pid?: unknown; + tid?: unknown; +}; + +export async function validateChromeTrace(file: string): Promise<{ + events: number; + tracks: number; +}> { + const payload = JSON.parse(await readFile(file, "utf8")) as { traceEvents?: unknown }; + if (!Array.isArray(payload.traceEvents)) throw new Error("traceEvents must be an array"); + const tracks = new Map(); + const metadata = new Set(); + for (const raw of payload.traceEvents as Event[]) { + if (typeof raw.name !== "string" || !["M", "i", "X"].includes(String(raw.ph))) + throw new Error("trace event used an unsupported Chrome trace phase"); + if (!Number.isSafeInteger(raw.pid) || !Number.isSafeInteger(raw.tid)) + throw new Error("trace event pid and tid must be safe integers"); + if (raw.ph === "M") { + const key = raw.name + ":" + raw.pid + ":" + raw.tid; + if (metadata.has(key)) throw new Error("duplicate trace metadata event " + key); + metadata.add(key); + continue; + } + if (!Number.isSafeInteger(raw.ts)) + throw new Error("timed trace event must have a safe timestamp"); + if (raw.ph !== "X") continue; + if (!Number.isSafeInteger(raw.dur) || Number(raw.dur) < 0) + throw new Error("complete trace event must have a nonnegative safe duration"); + const key = raw.pid + ":" + raw.tid; + const track = tracks.get(key) ?? []; + track.push({ ts: Number(raw.ts), dur: Number(raw.dur), name: raw.name }); + tracks.set(key, track); + } + for (const [key, events] of tracks) { + events.sort((left, right) => left.ts - right.ts || right.dur - left.dur); + const stack: typeof events = []; + for (const event of events) { + while (stack.length > 0 && event.ts >= stack.at(-1)!.ts + stack.at(-1)!.dur) stack.pop(); + if (stack.length > 0 && event.ts + event.dur > stack.at(-1)!.ts + stack.at(-1)!.dur) + throw new Error("crossing complete events on trace track " + key); + stack.push(event); + } + } + return { events: payload.traceEvents.length, tracks: tracks.size }; +} + +const invokedPath = process.argv[1]; +if ( + invokedPath && + process.argv[2] && + import.meta.url === pathToFileURL(path.resolve(invokedPath)).href +) + validateChromeTrace(process.argv[2]).then((result) => + process.stdout.write(JSON.stringify(result) + "\n"), + ); diff --git a/test/automation/pull-requests/analyze-pr-value-stream.test.ts b/test/automation/pull-requests/analyze-pr-value-stream.test.ts index aa040480afb..fd9b39b69d1 100644 --- a/test/automation/pull-requests/analyze-pr-value-stream.test.ts +++ b/test/automation/pull-requests/analyze-pr-value-stream.test.ts @@ -74,11 +74,14 @@ const scenario = process.env.VALUE_STREAM_SCENARIO; const sha = "a".repeat(40); const review = (state,time) => ({state,submittedAt:time,author:{login:"reviewer"},commit:{oid:sha}}); const reviews = scenario === "approval-restored" ? [review("APPROVED","2026-01-01T00:02:45Z"),review("CHANGES_REQUESTED","2026-01-01T00:03:00Z"),review("APPROVED","2026-01-01T00:03:15Z")] : scenario === "approval-revoked" ? [review("APPROVED","2026-01-01T00:02:45Z"),review("CHANGES_REQUESTED","2026-01-01T00:03:00Z")] : []; -const pull = {number:42,url:"https://example.test/pr/42",state:scenario.startsWith("approval-") ? "MERGED" : "OPEN",isDraft:false,createdAt:"2026-01-01T00:01:00Z",mergedAt:scenario.startsWith("approval-") ? "2026-01-01T00:04:00Z" : null,baseRefName:"main",headRefName:"topic",headRefOid:sha,commits:[{oid:sha,committedDate:"2026-01-01T00:00:00Z"}],reviews}; +const pull = {number:42,url:"https://example.test/pr/42",state:scenario.startsWith("approval-") ? "MERGED" : "OPEN",isDraft:false,createdAt:"2026-01-01T00:01:00Z",updatedAt:"2026-01-01T00:04:00Z",mergedAt:scenario.startsWith("approval-") ? "2026-01-01T00:04:00Z" : null,author:{login:"author"},assignees:[],baseRefName:"main",headRefName:"topic",headRefOid:sha,commits:[{oid:sha,authoredDate:"2026-01-01T00:00:00Z",committedDate:"2026-01-01T00:00:00Z",messageHeadline:"change"}],reviews}; const run = (id) => ({id,event:"push",head_sha:sha,created_at:"2026-01-01T00:00:30Z",run_started_at:scenario === "queued" ? null : "2026-01-01T00:00:31Z",updated_at:"2026-01-01T00:03:00Z",status:scenario === "queued" ? "queued" : "completed",conclusion:scenario === "queued" ? null : "success",name:"CI PR #42"}); let value; if (args.startsWith("pr view")) value = pull; else if (args.includes("required_status_checks")) value = scenario === "wrong-app" || scenario === "app-status-denied" ? {contexts:[],checks:[{context:"required-a",app_id:7}]} : scenario === "any-app" || scenario === "early-check" ? {contexts:[],checks:[{context:"required-a",app_id:-1}]} : scenario.startsWith("legacy-") ? {contexts:["legacy-required"],checks:[]} : {contexts:["required-a", "required-b"],checks:[]}; +else if (args.includes("issues/42/timeline")) value = [{id:41,event:"assigned",created_at:"2026-01-01T00:01:05Z",actor:"author",commit_id:null,label:null,requested_reviewer:null,rename:null}]; +else if (args.includes("issues/42/comments")) value = [{id:42,created_at:"2026-01-01T00:01:10Z",updated_at:"2026-01-01T00:01:10Z",user:"reviewer",html_url:""}]; +else if (args.includes("pulls/42/comments")) value = [{id:43,created_at:"2026-01-01T00:01:20Z",updated_at:"2026-01-01T00:01:20Z",user:"reviewer",path:"src/example.ts",line:1,commit_id:sha,html_url:"",in_reply_to_id:null}]; else if (args.includes("actions/runs?")) value = scenario === "fallback" ? [] : scenario === "truncated" ? [run(11),run(12)] : [run(11)]; else if (args.includes("/actions/runs/11/jobs")) value = {total_count:1,jobs:[{id:21,name:scenario.startsWith("artifact") ? "cli-test-shards (1)" : "job",status:scenario === "queued" ? "queued" : "completed",conclusion:scenario === "queued" ? null : "success",created_at:"2026-01-01T00:00:31Z",started_at:scenario === "queued" ? null : "2026-01-01T00:00:32Z",completed_at:scenario === "queued" ? null : "2026-01-01T00:02:00Z",runner_name:null,runner_group_name:null,labels:[],html_url:"",steps:[{number:1,name:"step",status:scenario === "queued" ? "queued" : "completed",conclusion:scenario === "queued" ? null : "success",started_at:scenario === "queued" ? null : "2026-01-01T00:00:33Z",completed_at:scenario === "queued" ? null : "2026-01-01T00:01:00Z"}]}]}; else if (args.includes("/actions/runs/12/jobs")) value = {total_count:0,jobs:[]}; @@ -113,7 +116,7 @@ async function run(scenario: string, extra: string[] = []) { "--no-warnings", analyzer, "--workdir", - root, + fake.directory, "--number", "42", ...extra, @@ -131,7 +134,10 @@ async function run(scenario: string, extra: string[] = []) { reject: false, }, ); - return Object.assign(result, { ghCalls: await readFile(fake.logPath, "utf8") }); + return Object.assign(result, { + directory: fake.directory, + ghCalls: await readFile(fake.logPath, "utf8"), + }); } afterEach(async () => { @@ -171,7 +177,41 @@ describe("pull request value-stream analysis", () => { expect(report.automation.checksConsidered).toBe(2); expect(report.automation.firstCheckCreatedAt).toBe("2026-01-01T00:00:35.000Z"); expect(report.automation.triggerDelaySeconds).toBe(5); - expect(result.ghCalls.match(/^pr view /gmu)).toHaveLength(1); + expect(result.ghCalls.match(/^pr view /gmu)).toHaveLength(2); + expect(report.lifetime).toMatchObject({ + revisions: 1, + workflowRuns: 1, + jobs: 1, + truncated: false, + }); + const summaryPath = path.resolve(result.directory, report.lifetime.summary); + const tracePath = path.resolve(result.directory, report.lifetime.trace); + const manifestPath = path.resolve(result.directory, report.lifetime.manifest); + expect(JSON.parse(await readFile(summaryPath, "utf8"))).toEqual(report); + const trace = JSON.parse(await readFile(tracePath, "utf8")); + expect(trace.traceEvents).toEqual( + expect.arrayContaining([ + expect.objectContaining({ name: "Pull request opened for review", ph: "i" }), + expect.objectContaining({ name: "job", cat: "ci.queue", ph: "X" }), + expect.objectContaining({ name: "job", cat: "ci.execution", ph: "X" }), + expect.objectContaining({ name: "step", cat: "ci.step", ph: "X" }), + expect.objectContaining({ name: "Inline feedback added", cat: "review.feedback" }), + ]), + ); + expect( + trace.traceEvents.every( + (event: { ts?: number; dur?: number }) => + (event.ts === undefined || Number.isSafeInteger(event.ts)) && + (event.dur === undefined || (Number.isSafeInteger(event.dur) && event.dur >= 0)), + ), + ).toBe(true); + expect(JSON.parse(await readFile(manifestPath, "utf8"))).toMatchObject({ + schemaVersion: 1, + repository: "NVIDIA/NemoClaw", + pullRequest: 42, + headSha: "a".repeat(40), + completeness: { workflowRuns: "complete", jobs: "complete", lifecycle: "complete" }, + }); }); test("uses commit timestamps when retained workflow runs are absent (#10542)", async () => { From e1651238545194bf94916b9d03db282961aed863 Mon Sep 17 00:00:00 2001 From: Carlos Villela Date: Fri, 28 Aug 2026 18:56:38 -0700 Subject: [PATCH 02/22] fix(maintainer): address lifetime trace review Signed-off-by: Carlos Villela --- .../scripts/analyze-pr-value-stream.mts | 3 +- .../scripts/export-pr-lifetime-trace.mts | 66 +++++++++++++------ .../analyze-pr-value-stream.test.ts | 12 +++- 3 files changed, 58 insertions(+), 23 deletions(-) diff --git a/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/analyze-pr-value-stream.mts b/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/analyze-pr-value-stream.mts index b537ede7449..6b624b6c026 100644 --- a/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/analyze-pr-value-stream.mts +++ b/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/analyze-pr-value-stream.mts @@ -1504,14 +1504,13 @@ async function main(): Promise { const input = parseArguments(process.argv.slice(2)); const normalized = normalizeAnalysisInput(input); const report = await collectValueStreamReport(normalized); - const lifetime = await exportLifetimeTrace({ + report.lifetime = await exportLifetimeTrace({ workdir: normalized.workdir, repository: normalized.repository, number: normalized.number, report, githubRead: async (args) => runGithubCli({ workdir: normalized.workdir, args }), }); - void lifetime; const output = `${JSON.stringify(report, null, 2)}\n`; if (Buffer.byteLength(output) > MAX_JSON_OUTPUT) throw new Error("value-stream JSON exceeded the 4 MB output bound"); diff --git a/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts b/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts index 2b0745b6e3f..224a27c04f8 100644 --- a/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts +++ b/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts @@ -127,24 +127,25 @@ async function mapBounded(values: T[], operation: (value: T) => Promise return result; } +type MetadataIndex = { processes: Set; threads: Set }; + function addMetadata( events: TraceEvent[], + index: MetadataIndex, pid: number, tid: number, processName: string, threadName: string, ): void { - if ( - !events.some((event) => event.ph === "M" && event.name === "process_name" && event.pid === pid) - ) + if (!index.processes.has(pid)) { + index.processes.add(pid); events.push({ name: "process_name", ph: "M", pid, tid: 0, args: { name: processName } }); - if ( - !events.some( - (event) => - event.ph === "M" && event.name === "thread_name" && event.pid === pid && event.tid === tid, - ) - ) + } + const threadKey = pid + ":" + tid; + if (!index.threads.has(threadKey)) { + index.threads.add(threadKey); events.push({ name: "thread_name", ph: "M", pid, tid, args: { name: threadName } }); + } } function addInstant( @@ -206,12 +207,18 @@ function addSpan( }); } +function validateObjectId(value: unknown): string { + if (typeof value !== "string" || !/^[0-9a-f]{40,64}$/u.test(value)) + throw new Error("pull request commit had an invalid object ID"); + return value; +} + function normalizeCommits(pull: any): Commit[] { const rows = validateArray(pull?.commits, "pull request commits"); if (rows.length < 1 || rows.length > MAX_REVISIONS) throw new Error("lifetime trace requires between 1 and " + MAX_REVISIONS + " revisions"); return rows.map((commit: any) => ({ - oid: String(commit?.oid ?? ""), + oid: validateObjectId(commit?.oid), authoredAt: parseTime(commit?.authoredDate ?? commit?.committedDate, "commit authoredDate"), committedAt: parseTime(commit?.committedDate, "commit committedDate"), subject: @@ -337,9 +344,10 @@ function renderTrace(input: { lifecycle: Awaited>; }): { events: TraceEvent[]; lifecycleEvents: number } { const events: TraceEvent[] = []; - addMetadata(events, 1, 1, "PR #" + input.pull.number, "Lifecycle"); - addMetadata(events, 2, 1, "Author activity", input.pull.author?.login ?? "author"); - addMetadata(events, 3, 1, "Feedback and reviews", "Comments and reviews"); + const metadata: MetadataIndex = { processes: new Set(), threads: new Set() }; + addMetadata(events, metadata, 1, 1, "PR #" + input.pull.number, "Lifecycle"); + addMetadata(events, metadata, 2, 1, "Author activity", input.pull.author?.login ?? "author"); + addMetadata(events, metadata, 3, 1, "Feedback and reviews", "Comments and reviews"); let lifecycleEvents = 0; const instant = (entry: Parameters[1]): void => { lifecycleEvents += 1; @@ -450,6 +458,7 @@ function renderTrace(input: { args: { id: row.id, actor: row.user, url: row.html_url ?? null }, }); } + feedback.sort((left, right) => left.at - right.at); const firstRuns = new Map(); for (const run of input.runs .slice() @@ -458,7 +467,7 @@ function renderTrace(input: { } for (const [index, commit] of input.commits.entries()) { const pid = 1_000 + index; - addMetadata(events, pid, 1, "Revision " + commit.oid.slice(0, 8), "Workflows"); + addMetadata(events, metadata, pid, 1, "Revision " + commit.oid.slice(0, 8), "Workflows"); instant({ name: commit.subject, category: "author.commit", @@ -503,8 +512,11 @@ function renderTrace(input: { } } } + const commitsByAuthoredAt = input.commits + .slice() + .sort((left, right) => left.authoredAt - right.authoredAt); for (const [index, entry] of feedback.entries()) { - const nextCommit = input.commits.find((commit) => commit.authoredAt > entry.at); + const nextCommit = commitsByAuthoredAt.find((commit) => commit.authoredAt > entry.at); if (!nextCommit) continue; addSpan(events, { name: "Feedback to next author change", @@ -525,7 +537,14 @@ function renderTrace(input: { const commitIndex = input.commits.findIndex((commit) => commit.oid === run.head_sha); const pid = 1_000 + Math.max(0, commitIndex); const tid = 10 + index; - addMetadata(events, pid, tid, "Revision " + run.head_sha.slice(0, 8), run.name + " #" + run.id); + addMetadata( + events, + metadata, + pid, + tid, + "Revision " + run.head_sha.slice(0, 8), + run.name + " #" + run.id, + ); addSpan(events, { name: run.name, category: "ci.workflow", @@ -548,6 +567,7 @@ function renderTrace(input: { const tid = 10_000 + jobIndex; addMetadata( events, + metadata, pid, tid, "Revision " + job.run.head_sha.slice(0, 8), @@ -587,6 +607,7 @@ function renderTrace(input: { const stepTid = 1_000_000 + jobIndex * 1_000 + stepIndex; addMetadata( events, + metadata, pid, stepTid, "Revision " + job.run.head_sha.slice(0, 8), @@ -612,7 +633,14 @@ function renderTrace(input: { const commitIndex = input.commits.findIndex((commit) => commit.oid === check.commit.oid); const pid = 1_000 + Math.max(0, commitIndex); const tid = 50_000 + index; - addMetadata(events, pid, tid, "Revision " + check.commit.oid.slice(0, 8), "External checks"); + addMetadata( + events, + metadata, + pid, + tid, + "Revision " + check.commit.oid.slice(0, 8), + "External checks", + ); addSpan(events, { name: check.name, category: "ci.external-check", @@ -712,8 +740,8 @@ export async function exportLifetimeTrace(input: ExportInput): Promise ({id,event:"push",head_sha:sha,created_at:"2026-01-01T00:00:30Z",run_started_at:scenario === "queued" ? null : "2026-01-01T00:00:31Z",updated_at:"2026-01-01T00:03:00Z",status:scenario === "queued" ? "queued" : "completed",conclusion:scenario === "queued" ? null : "success",name:"CI PR #42"}); let value; -if (args.startsWith("pr view")) value = pull; +if (args.startsWith("pr view")) value = scenario === "head-race" && fs.readFileSync(process.env.VALUE_STREAM_LOG,"utf8").match(/^pr view /gmu).length > 1 ? {...pull,headRefOid:"b".repeat(40)} : pull; else if (args.includes("required_status_checks")) value = scenario === "wrong-app" || scenario === "app-status-denied" ? {contexts:[],checks:[{context:"required-a",app_id:7}]} : scenario === "any-app" || scenario === "early-check" ? {contexts:[],checks:[{context:"required-a",app_id:-1}]} : scenario.startsWith("legacy-") ? {contexts:["legacy-required"],checks:[]} : {contexts:["required-a", "required-b"],checks:[]}; else if (args.includes("issues/42/timeline")) value = [{id:41,event:"assigned",created_at:"2026-01-01T00:01:05Z",actor:"author",commit_id:null,label:null,requested_reviewer:null,rename:null}]; else if (args.includes("issues/42/comments")) value = [{id:42,created_at:"2026-01-01T00:01:10Z",updated_at:"2026-01-01T00:01:10Z",user:"reviewer",html_url:""}]; @@ -177,7 +177,6 @@ describe("pull request value-stream analysis", () => { expect(report.automation.checksConsidered).toBe(2); expect(report.automation.firstCheckCreatedAt).toBe("2026-01-01T00:00:35.000Z"); expect(report.automation.triggerDelaySeconds).toBe(5); - expect(result.ghCalls.match(/^pr view /gmu)).toHaveLength(2); expect(report.lifetime).toMatchObject({ revisions: 1, workflowRuns: 1, @@ -214,6 +213,15 @@ describe("pull request value-stream analysis", () => { }); }); + test("removes lifetime artifacts when the pull request head changes (#10542)", async () => { + const result = await run("head-race", ["--max-test-artifacts", "0"]); + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain("pull request head changed during lifetime analysis"); + await expect( + stat(path.join(result.directory, ".nemoclaw-maintainer/pr-value-stream/pr-42")), + ).rejects.toThrow(); + }); + test("uses commit timestamps when retained workflow runs are absent (#10542)", async () => { const report = JSON.parse((await run("fallback", ["--max-test-artifacts", "0"])).stdout); expect(report.events.firstBranchPush).toMatchObject({ From 80eb9fad49dad9192ab17f36bf849563630da6de Mon Sep 17 00:00:00 2001 From: Carlos Villela Date: Fri, 28 Aug 2026 19:44:39 -0700 Subject: [PATCH 03/22] fix(maintainer): harden lifetime trace publication Signed-off-by: Carlos Villela --- .../scripts/analyze-pr-value-stream.mts | 37 +++---- .../scripts/export-pr-lifetime-trace.mts | 68 ++++++++++--- .../scripts/validate-chrome-trace.mts | 12 --- .../analyze-pr-value-stream.test.ts | 98 +++++++++++++------ 4 files changed, 135 insertions(+), 80 deletions(-) diff --git a/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/analyze-pr-value-stream.mts b/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/analyze-pr-value-stream.mts index 6b624b6c026..1ce30142061 100644 --- a/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/analyze-pr-value-stream.mts +++ b/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/analyze-pr-value-stream.mts @@ -13,17 +13,17 @@ import { exportLifetimeTrace, type LifetimeArtifacts } from "./export-pr-lifetim const execFileAsync = promisify(execFile); const MAX_GH_OUTPUT = 10_000_000; const MAX_JSON_OUTPUT = 4_000_000; +const MAX_RUN_PAGES = 3; +const MAX_CHECK_PAGES = 3; +const MAX_AUTOMATION_RUNS = 50; +const MAX_TEST_ARTIFACTS = 12; +const TOP_TESTS_PER_SHARD = 10; type Input = { workdir: string; number: number; repository?: string; targetMinutes?: number; - maxRunPages?: number; - maxCheckPages?: number; - maxAutomationRuns?: number; - maxTestArtifacts?: number; - topTestsPerShard?: number; }; export type ValueStreamReport = { @@ -286,11 +286,11 @@ function normalizeAnalysisInput(input: Input): AnalysisOptions { number: input.number, repository, targetMinutes, - maxRunPages: boundedInteger(input.maxRunPages ?? 3, "maxRunPages", 1, 10), - maxCheckPages: boundedInteger(input.maxCheckPages ?? 3, "maxCheckPages", 1, 10), - maxAutomationRuns: boundedInteger(input.maxAutomationRuns ?? 50, "maxAutomationRuns", 1, 100), - maxTestArtifacts: boundedInteger(input.maxTestArtifacts ?? 12, "maxTestArtifacts", 0, 24), - topTestsPerShard: boundedInteger(input.topTestsPerShard ?? 10, "topTestsPerShard", 1, 25), + maxRunPages: MAX_RUN_PAGES, + maxCheckPages: MAX_CHECK_PAGES, + maxAutomationRuns: MAX_AUTOMATION_RUNS, + maxTestArtifacts: MAX_TEST_ARTIFACTS, + topTestsPerShard: TOP_TESTS_PER_SHARD, }; } @@ -1462,17 +1462,7 @@ export async function analyzePrValueStream(input: Input): Promise(); for (let index = 0; index < argv.length; index += 2) { const key = argv[index]; @@ -1492,11 +1482,6 @@ function parseArguments(argv: string[]): Input { number, repository: values.get("repository"), targetMinutes: numeric("target-minutes"), - maxRunPages: numeric("max-run-pages"), - maxCheckPages: numeric("max-check-pages"), - maxAutomationRuns: numeric("max-automation-runs"), - maxTestArtifacts: numeric("max-test-artifacts"), - topTestsPerShard: numeric("top-tests-per-shard"), }; } diff --git a/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts b/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts index 224a27c04f8..4dcb2f0a2d9 100644 --- a/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts +++ b/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts @@ -1,7 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { mkdir, rename, rm, writeFile } from "node:fs/promises"; +import { mkdir, mkdtemp, rename, rm, writeFile } from "node:fs/promises"; import path from "node:path"; import { validateChromeTrace } from "./validate-chrome-trace.mts"; @@ -666,10 +666,44 @@ function renderTrace(input: { return { events, lifecycleEvents }; } -async function writeAtomic(file: string, content: string): Promise { - const temporary = file + ".tmp-" + process.pid; - await writeFile(temporary, content, { mode: 0o600 }); - await rename(temporary, file); +async function acquirePublicationLock(lock: string): Promise { + for (let attempt = 0; attempt < 300; attempt += 1) { + try { + await mkdir(lock); + return; + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error; + await new Promise((resolve) => setTimeout(resolve, 100)); + } + } + throw new Error("timed out waiting for lifetime artifact publication lock"); +} + +export async function publishStagedDirectory(input: { + staging: string; + destination: string; + lock: string; +}): Promise { + await acquirePublicationLock(input.lock); + const backup = input.staging + "-previous"; + let movedPrevious = false; + try { + try { + await rename(input.destination, backup); + movedPrevious = true; + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; + } + try { + await rename(input.staging, input.destination); + } catch (error) { + if (movedPrevious) await rename(backup, input.destination); + throw error; + } + if (movedPrevious) await rm(backup, { recursive: true, force: true }); + } finally { + await rm(input.lock, { recursive: true, force: true }); + } } export async function exportLifetimeTrace(input: ExportInput): Promise { @@ -709,10 +743,7 @@ export async function exportLifetimeTrace(input: ExportInput): Promise - process.stdout.write(JSON.stringify(result) + "\n"), - ); diff --git a/test/automation/pull-requests/analyze-pr-value-stream.test.ts b/test/automation/pull-requests/analyze-pr-value-stream.test.ts index 3a6f834575c..7e48a7bf385 100644 --- a/test/automation/pull-requests/analyze-pr-value-stream.test.ts +++ b/test/automation/pull-requests/analyze-pr-value-stream.test.ts @@ -1,7 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { chmod, mkdtemp, readFile, readdir, rm, stat, writeFile } from "node:fs/promises"; +import { chmod, mkdir, mkdtemp, readFile, readdir, rm, stat, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; @@ -9,6 +9,7 @@ import { execa } from "execa"; import { afterEach, describe, expect, test, vi } from "vitest"; import { cleanupArtifactDirectory } from "../../../.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/analyze-pr-value-stream.mts"; +import { publishStagedDirectory } from "../../../.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts"; const root = path.resolve(import.meta.dirname, "../../.."); const analyzer = path.join( @@ -169,7 +170,7 @@ describe("pull request value-stream analysis", () => { }); test("returns a complete bounded report through mocked process boundaries (#10542)", async () => { - const result = await run("complete", ["--max-test-artifacts", "0"]); + const result = await run("complete"); expect(result.exitCode, result.stderr).toBe(0); const report = JSON.parse(result.stdout); expect(report.events.automationSettled).toBe("2026-01-01T00:02:40.000Z"); @@ -214,7 +215,7 @@ describe("pull request value-stream analysis", () => { }); test("removes lifetime artifacts when the pull request head changes (#10542)", async () => { - const result = await run("head-race", ["--max-test-artifacts", "0"]); + const result = await run("head-race"); expect(result.exitCode).toBe(1); expect(result.stderr).toContain("pull request head changed during lifetime analysis"); await expect( @@ -223,7 +224,7 @@ describe("pull request value-stream analysis", () => { }); test("uses commit timestamps when retained workflow runs are absent (#10542)", async () => { - const report = JSON.parse((await run("fallback", ["--max-test-artifacts", "0"])).stdout); + const report = JSON.parse((await run("fallback")).stdout); expect(report.events.firstBranchPush).toMatchObject({ source: "first commit committedDate fallback", confidence: "low", @@ -232,7 +233,7 @@ describe("pull request value-stream analysis", () => { }); test("keeps queued runs jobs and steps with nullable timing fields (#10542)", async () => { - const report = JSON.parse((await run("queued", ["--max-test-artifacts", "0"])).stdout); + const report = JSON.parse((await run("queued")).stdout); const queuedRun = report.waterfall.runs[0]; expect(queuedRun).toMatchObject({ startedAt: null, queueSeconds: null, durationSeconds: null }); expect(queuedRun.jobs[0]).toMatchObject({ @@ -249,7 +250,7 @@ describe("pull request value-stream analysis", () => { }); test("does not settle automation when a required exact-head check is absent (#10542)", async () => { - const report = JSON.parse((await run("incomplete", ["--max-test-artifacts", "0"])).stdout); + const report = JSON.parse((await run("incomplete")).stdout); expect(report.events.automationSettled).toBeNull(); expect(report.caveats).toContain( "Automation is not settled because at least one configured required check is absent, pending, or unsuccessful on the exact head.", @@ -257,55 +258,47 @@ describe("pull request value-stream analysis", () => { }); test("does not satisfy an app-bound required check with another GitHub App (#10542)", async () => { - const report = JSON.parse((await run("wrong-app", ["--max-test-artifacts", "0"])).stdout); + const report = JSON.parse((await run("wrong-app")).stdout); expect(report.events.automationSettled).toBeNull(); expect(report.automation.checksConsidered).toBe(0); }); test("accepts any provider for an unrestricted required check (#10542)", async () => { - const report = JSON.parse((await run("any-app", ["--max-test-artifacts", "0"])).stdout); + const report = JSON.parse((await run("any-app")).stdout); expect(report.events.automationSettled).toBe("2026-01-01T00:02:30.000Z"); expect(report.automation.checksConsidered).toBe(1); }); test("settles automation from an earlier exact-commit check run (#10542)", async () => { - const report = JSON.parse((await run("early-check", ["--max-test-artifacts", "0"])).stdout); + const report = JSON.parse((await run("early-check")).stdout); expect(report.events.automationSettled).toBe("2026-01-01T00:00:20.000Z"); }); test("settles automation from an earlier exact-commit legacy status (#10542)", async () => { - const report = JSON.parse((await run("legacy-status", ["--max-test-artifacts", "0"])).stdout); + const report = JSON.parse((await run("legacy-status")).stdout); expect(report.events.automationSettled).toBe("2026-01-01T00:00:20.000Z"); expect(report.automation.firstCheckCreatedAt).toBe("2026-01-01T00:00:04.000Z"); }); test("skips legacy status permission when app-bound checks are sufficient (#10542)", async () => { - const report = JSON.parse( - (await run("app-status-denied", ["--max-test-artifacts", "0"])).stdout, - ); + const report = JSON.parse((await run("app-status-denied")).stdout); expect(report.events.automationSettled).toBe("2026-01-01T00:02:30.000Z"); }); test("finds a required legacy status on the second bounded page (#10542)", async () => { - const report = JSON.parse( - (await run("legacy-paginated", ["--max-test-artifacts", "0"])).stdout, - ); + const report = JSON.parse((await run("legacy-paginated")).stdout); expect(report.events.automationSettled).toBe("2026-01-01T00:00:20.000Z"); }); test("uses the restored final-head approval after a later change request (#10542)", async () => { - const report = JSON.parse( - (await run("approval-restored", ["--max-test-artifacts", "0"])).stdout, - ); + const report = JSON.parse((await run("approval-restored")).stdout); expect(report.events.firstFinalHeadApproval).toBe("2026-01-01T00:03:15.000Z"); expect(report.elapsed.approvalDelaySeconds).toBe(35); expect(report.elapsed.mergeLagAfterReadySeconds).toBe(45); }); test("omits a final-head approval superseded by a change request (#10542)", async () => { - const report = JSON.parse( - (await run("approval-revoked", ["--max-test-artifacts", "0"])).stdout, - ); + const report = JSON.parse((await run("approval-revoked")).stdout); expect(report.events.firstFinalHeadApproval).toBeNull(); expect(report.elapsed.approvalDelaySeconds).toBeNull(); }); @@ -389,14 +382,59 @@ describe("pull request value-stream analysis", () => { expect(JSON.stringify(report)).not.toContain("secret-token"); }); - test("marks the waterfall truncated at the configured run bound (#10542)", async () => { - const report = JSON.parse( - (await run("truncated", ["--max-automation-runs", "1", "--max-test-artifacts", "0"])).stdout, + test("publishes each concurrent lifetime artifact set without mixing files (#10542)", async () => { + const publicationRoot = await mkdtemp(path.join(tmpdir(), "value-stream-publish-")); + temporaryDirectories.push(publicationRoot); + const destination = path.join(publicationRoot, "pr-42"); + const first = path.join(publicationRoot, "first"); + const second = path.join(publicationRoot, "second"); + await Promise.all([mkdir(first), mkdir(second)]); + await Promise.all( + [first, second].flatMap((directory, index) => + ["summary.json", "trace.json", "manifest.json"].map((file) => + writeFile(path.join(directory, file), String(index)), + ), + ), ); - expect(report.waterfall).toMatchObject({ - runsAvailable: 2, - runsIncluded: 1, - runsTruncated: true, - }); + await Promise.all([ + publishStagedDirectory({ staging: first, destination, lock: destination + ".lock" }), + publishStagedDirectory({ staging: second, destination, lock: destination + ".lock" }), + ]); + const manifest = await readFile(path.join(destination, "manifest.json"), "utf8"); + await expect(readFile(path.join(destination, "summary.json"), "utf8")).resolves.toBe(manifest); + await expect(readFile(path.join(destination, "trace.json"), "utf8")).resolves.toBe(manifest); + }); + + test("restores a completed lifetime artifact set when staged publication fails (#10542)", async () => { + const publicationRoot = await mkdtemp(path.join(tmpdir(), "value-stream-restore-")); + temporaryDirectories.push(publicationRoot); + const destination = path.join(publicationRoot, "pr-42"); + await mkdir(destination); + await Promise.all( + ["summary.json", "trace.json", "manifest.json"].map((file) => + writeFile(path.join(destination, file), "complete"), + ), + ); + await expect( + publishStagedDirectory({ + staging: path.join(publicationRoot, "missing-staging"), + destination, + lock: destination + ".lock", + }), + ).rejects.toThrow(); + await expect(readFile(path.join(destination, "summary.json"), "utf8")).resolves.toBe( + "complete", + ); + await expect(readFile(path.join(destination, "trace.json"), "utf8")).resolves.toBe("complete"); + await expect(readFile(path.join(destination, "manifest.json"), "utf8")).resolves.toBe( + "complete", + ); + }); + + test("rejects removed user-controlled truncation options before GitHub access (#10542)", async () => { + const result = await run("complete", ["--max-automation-runs", "1"]); + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain("unknown argument: --max-automation-runs"); + expect(result.ghCalls).toBe(""); }); }); From b2c409e16e9dbac5aa913b3d3727d43fda8e973b Mon Sep 17 00:00:00 2001 From: Carlos Villela Date: Sat, 29 Aug 2026 00:43:22 -0700 Subject: [PATCH 04/22] fix(maintainer): close lifetime publication races Signed-off-by: Carlos Villela --- .../SKILL.md | 2 +- .../scripts/export-pr-lifetime-trace.mts | 37 +++++++- .../analyze-pr-value-stream.test.ts | 89 ++++++++++++++++++- 3 files changed, 122 insertions(+), 6 deletions(-) diff --git a/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/SKILL.md b/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/SKILL.md index f60cb7cf03a..20ae3b3214d 100644 --- a/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/SKILL.md +++ b/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/SKILL.md @@ -58,7 +58,7 @@ Do not describe a fallback branch timestamp as exact. Do not claim causal attrib ## Trust boundaries -The script performs no GitHub writes. It invokes executables with argument arrays, bounds GitHub output, pagination, revisions, workflow runs, jobs, trace events, artifact sizes, and file sizes, and rejects malformed or incomplete required history. +The script performs no GitHub writes. It invokes executables with argument arrays, bounds GitHub output, pagination, revisions, workflow runs, jobs, trace events, artifact sizes, and file sizes, and rejects malformed or incomplete required history. Lifetime artifact publication uses a per-PR lock. An active publication waits for up to 30 seconds; a lock left untouched for more than five minutes is treated as orphaned and reclaimed automatically. A timeout reports the exact active lock path for diagnosis. GitHub does not expose canonical branch-creation timestamps or pull request description edit history. The trace uses the first retained exact-commit workflow as an observable push signal and records that limitation. Draft transitions appear only when GitHub's timeline returns them. diff --git a/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts b/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts index 4dcb2f0a2d9..2578cf49adf 100644 --- a/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts +++ b/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts @@ -1,7 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { mkdir, mkdtemp, rename, rm, writeFile } from "node:fs/promises"; +import { mkdir, mkdtemp, rename, rm, stat, writeFile } from "node:fs/promises"; import path from "node:path"; import { validateChromeTrace } from "./validate-chrome-trace.mts"; @@ -14,6 +14,7 @@ const MAX_TRACE_EVENTS = 250_000; const MAX_TRACE_BYTES = 100_000_000; const PAGE_SIZE = 100; const READ_CONCURRENCY = 8; +const PUBLICATION_LOCK_STALE_MS = 5 * 60 * 1_000; type GithubRead = (args: string[]) => Promise<{ stdout: string }>; @@ -666,17 +667,46 @@ function renderTrace(input: { return { events, lifecycleEvents }; } +export async function reclaimStalePublicationLock( + lock: string, + now = Date.now(), +): Promise { + let lockStat; + try { + lockStat = await stat(lock); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return false; + throw error; + } + if (now - lockStat.mtimeMs <= PUBLICATION_LOCK_STALE_MS) return false; + const stale = lock + ".stale-" + process.pid + "-" + now; + try { + await rename(lock, stale); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") return false; + throw error; + } + await rm(stale, { recursive: true, force: true }); + return true; +} + async function acquirePublicationLock(lock: string): Promise { for (let attempt = 0; attempt < 300; attempt += 1) { try { await mkdir(lock); + await writeFile( + path.join(lock, "owner.json"), + JSON.stringify({ pid: process.pid, createdAt: new Date().toISOString() }) + "\n", + { mode: 0o600 }, + ); return; } catch (error) { if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error; + if (await reclaimStalePublicationLock(lock)) continue; await new Promise((resolve) => setTimeout(resolve, 100)); } } - throw new Error("timed out waiting for lifetime artifact publication lock"); + throw new Error("timed out waiting for active lifetime artifact publication lock: " + lock); } export async function publishStagedDirectory(input: { @@ -806,6 +836,9 @@ export async function exportLifetimeTrace(input: ExportInput): Promise ({id,event:"push",head_sha:sha,created_at:"2026-01-01T00:00:30Z",run_started_at:scenario === "queued" ? null : "2026-01-01T00:00:31Z",updated_at:"2026-01-01T00:03:00Z",status:scenario === "queued" ? "queued" : "completed",conclusion:scenario === "queued" ? null : "success",name:"CI PR #42"}); let value; -if (args.startsWith("pr view")) value = scenario === "head-race" && fs.readFileSync(process.env.VALUE_STREAM_LOG,"utf8").match(/^pr view /gmu).length > 1 ? {...pull,headRefOid:"b".repeat(40)} : pull; +if (args.startsWith("pr view")) { const calls=fs.readFileSync(process.env.VALUE_STREAM_LOG,"utf8").match(/^pr view /gmu).length; value = (scenario === "head-race" && calls > 1) || (scenario === "final-head-race" && calls > 2) ? {...pull,headRefOid:"b".repeat(40)} : pull; } else if (args.includes("required_status_checks")) value = scenario === "wrong-app" || scenario === "app-status-denied" ? {contexts:[],checks:[{context:"required-a",app_id:7}]} : scenario === "any-app" || scenario === "early-check" ? {contexts:[],checks:[{context:"required-a",app_id:-1}]} : scenario.startsWith("legacy-") ? {contexts:["legacy-required"],checks:[]} : {contexts:["required-a", "required-b"],checks:[]}; else if (args.includes("issues/42/timeline")) value = [{id:41,event:"assigned",created_at:"2026-01-01T00:01:05Z",actor:"author",commit_id:null,label:null,requested_reviewer:null,rename:null}]; else if (args.includes("issues/42/comments")) value = [{id:42,created_at:"2026-01-01T00:01:10Z",updated_at:"2026-01-01T00:01:10Z",user:"reviewer",html_url:""}]; @@ -223,6 +237,15 @@ describe("pull request value-stream analysis", () => { ).rejects.toThrow(); }); + test("does not replace artifacts when the head changes before publication (#10542)", async () => { + const result = await run("final-head-race"); + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain("pull request head changed during lifetime analysis"); + await expect( + stat(path.join(result.directory, ".nemoclaw-maintainer/pr-value-stream/pr-42")), + ).rejects.toThrow(); + }); + test("uses commit timestamps when retained workflow runs are absent (#10542)", async () => { const report = JSON.parse((await run("fallback")).stdout); expect(report.events.firstBranchPush).toMatchObject({ @@ -431,6 +454,66 @@ describe("pull request value-stream analysis", () => { ); }); + test("reclaims stale publication locks but preserves active locks (#10542)", async () => { + const publicationRoot = await mkdtemp(path.join(tmpdir(), "value-stream-lock-")); + temporaryDirectories.push(publicationRoot); + const lock = path.join(publicationRoot, "pr-42.lock"); + await mkdir(lock); + expect(await reclaimStalePublicationLock(lock)).toBe(false); + const stale = new Date(Date.now() - 6 * 60 * 1_000); + await utimes(lock, stale, stale); + expect(await reclaimStalePublicationLock(lock)).toBe(true); + await expect(stat(lock)).rejects.toThrow(); + }); + + test("accepts a valid synthetic Chrome trace (#10542)", async () => { + const trace = path.join( + await mkdtemp(path.join(tmpdir(), "value-stream-trace-")), + "trace.json", + ); + temporaryDirectories.push(path.dirname(trace)); + await writeFile( + trace, + JSON.stringify({ + traceEvents: [{ name: "valid", ph: "X", ts: 1, dur: 2, pid: 1, tid: 1, args: {} }], + }), + ); + await expect(validateChromeTrace(trace)).resolves.toEqual({ events: 1, tracks: 1 }); + }); + + test("rejects an unsupported Chrome trace phase (#10542)", async () => { + const trace = path.join( + await mkdtemp(path.join(tmpdir(), "value-stream-trace-")), + "trace.json", + ); + temporaryDirectories.push(path.dirname(trace)); + await writeFile( + trace, + JSON.stringify({ + traceEvents: [{ name: "invalid", ph: "s", ts: 1, pid: 1, tid: 1, args: {} }], + }), + ); + await expect(validateChromeTrace(trace)).rejects.toThrow("unsupported Chrome trace phase"); + }); + + test("rejects crossing complete Chrome trace events (#10542)", async () => { + const trace = path.join( + await mkdtemp(path.join(tmpdir(), "value-stream-trace-")), + "trace.json", + ); + temporaryDirectories.push(path.dirname(trace)); + await writeFile( + trace, + JSON.stringify({ + traceEvents: [ + { name: "outer", ph: "X", ts: 1, dur: 5, pid: 1, tid: 1, args: {} }, + { name: "crossing", ph: "X", ts: 3, dur: 5, pid: 1, tid: 1, args: {} }, + ], + }), + ); + await expect(validateChromeTrace(trace)).rejects.toThrow("crossing complete events"); + }); + test("rejects removed user-controlled truncation options before GitHub access (#10542)", async () => { const result = await run("complete", ["--max-automation-runs", "1"]); expect(result.exitCode).toBe(1); From d38ce9cd5d27ae419033e28ad915426269d73c2c Mon Sep 17 00:00:00 2001 From: Carlos Villela Date: Sat, 29 Aug 2026 00:52:07 -0700 Subject: [PATCH 05/22] fix(maintainer): validate head under publication lock Signed-off-by: Carlos Villela --- .../scripts/export-pr-lifetime-trace.mts | 10 ++++--- .../analyze-pr-value-stream.test.ts | 27 +++++++++++++++++++ 2 files changed, 34 insertions(+), 3 deletions(-) diff --git a/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts b/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts index 2578cf49adf..75e13df0e02 100644 --- a/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts +++ b/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts @@ -713,11 +713,13 @@ export async function publishStagedDirectory(input: { staging: string; destination: string; lock: string; + validate?: () => Promise; }): Promise { await acquirePublicationLock(input.lock); const backup = input.staging + "-previous"; let movedPrevious = false; try { + await input.validate?.(); try { await rename(input.destination, backup); movedPrevious = true; @@ -836,13 +838,15 @@ export async function exportLifetimeTrace(input: ExportInput): Promise { + const currentPull = await readPull(input); + if (currentPull.headRefOid !== pull.headRefOid) + throw new Error("pull request head changed during lifetime analysis"); + }, }); } catch (error) { await rm(staging, { recursive: true, force: true }); diff --git a/test/automation/pull-requests/analyze-pr-value-stream.test.ts b/test/automation/pull-requests/analyze-pr-value-stream.test.ts index 9bf2651a2eb..4f1c411f476 100644 --- a/test/automation/pull-requests/analyze-pr-value-stream.test.ts +++ b/test/automation/pull-requests/analyze-pr-value-stream.test.ts @@ -454,6 +454,33 @@ describe("pull request value-stream analysis", () => { ); }); + test("validates freshness after publication lock contention (#10542)", async () => { + const publicationRoot = await mkdtemp(path.join(tmpdir(), "value-stream-contention-")); + temporaryDirectories.push(publicationRoot); + const destination = path.join(publicationRoot, "pr-42"); + const staging = path.join(publicationRoot, "staging"); + const lock = destination + ".lock"; + await Promise.all([mkdir(destination), mkdir(staging), mkdir(lock)]); + await Promise.all([ + writeFile(path.join(destination, "manifest.json"), "current"), + writeFile(path.join(staging, "manifest.json"), "stale"), + ]); + const publication = publishStagedDirectory({ + staging, + destination, + lock, + validate: async () => { + throw new Error("pull request head changed during lifetime analysis"); + }, + }); + await new Promise((resolve) => setTimeout(resolve, 150)); + await rm(lock, { recursive: true }); + await expect(publication).rejects.toThrow("pull request head changed during lifetime analysis"); + await expect(readFile(path.join(destination, "manifest.json"), "utf8")).resolves.toBe( + "current", + ); + }); + test("reclaims stale publication locks but preserves active locks (#10542)", async () => { const publicationRoot = await mkdtemp(path.join(tmpdir(), "value-stream-lock-")); temporaryDirectories.push(publicationRoot); From 2bb77c24ea56fed1af92342e4b8f1293192ef357 Mon Sep 17 00:00:00 2001 From: Carlos Villela Date: Sat, 29 Aug 2026 01:05:22 -0700 Subject: [PATCH 06/22] fix(maintainer): preserve complete lifetime publication Signed-off-by: Carlos Villela --- .../scripts/analyze-pr-value-stream.mts | 7 ++++ .../scripts/export-pr-lifetime-trace.mts | 41 +++++++++++++++---- .../analyze-pr-value-stream.test.ts | 17 +++++++- 3 files changed, 57 insertions(+), 8 deletions(-) diff --git a/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/analyze-pr-value-stream.mts b/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/analyze-pr-value-stream.mts index 1ce30142061..09f07cd6329 100644 --- a/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/analyze-pr-value-stream.mts +++ b/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/analyze-pr-value-stream.mts @@ -195,6 +195,11 @@ async function handleCancellation(signal: (typeof cancellationSignals)[number]): process.kill(process.pid, signal); } +function releaseTrackedPath(path: string): void { + artifactDirectories.delete(path); + if (artifactDirectories.size === 0 && cancellationHandlersInstalled) removeCancellationHandlers(); +} + function trackArtifactDirectory(directory: string): void { artifactDirectories.add(directory); if (cancellationHandlersInstalled) return; @@ -1495,6 +1500,8 @@ async function main(): Promise { number: normalized.number, report, githubRead: async (args) => runGithubCli({ workdir: normalized.workdir, args }), + trackTemporaryPath: trackArtifactDirectory, + releaseTemporaryPath: releaseTrackedPath, }); const output = `${JSON.stringify(report, null, 2)}\n`; if (Buffer.byteLength(output) > MAX_JSON_OUTPUT) diff --git a/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts b/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts index 75e13df0e02..6fe63795985 100644 --- a/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts +++ b/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts @@ -1,7 +1,8 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { mkdir, mkdtemp, rename, rm, stat, writeFile } from "node:fs/promises"; +import { randomUUID } from "node:crypto"; +import { mkdir, mkdtemp, readFile, rename, rm, stat, utimes, writeFile } from "node:fs/promises"; import path from "node:path"; import { validateChromeTrace } from "./validate-chrome-trace.mts"; @@ -71,6 +72,8 @@ type ExportInput = { number: number; report: unknown; githubRead: GithubRead; + trackTemporaryPath?: (path: string) => void; + releaseTemporaryPath?: (path: string) => void; }; function parseTime(value: unknown, label: string): number { @@ -289,7 +292,7 @@ async function readExternalChecks(input: ExportInput, commits: Commit[]): Promis const groups = await mapBounded(commits, async (commit) => { const collection = await readPages({ githubRead: input.githubRead, - endpoint: "repos/" + input.repository + "/commits/" + commit.oid + "/check-runs", + endpoint: "repos/" + input.repository + "/commits/" + commit.oid + "/check-runs?filter=all", projection: "[.check_runs[] | {id,name,status,conclusion,created_at,started_at,completed_at,html_url,app:{id:.app.id,slug:.app.slug}}]", label: "check runs", @@ -690,16 +693,26 @@ export async function reclaimStalePublicationLock( return true; } -async function acquirePublicationLock(lock: string): Promise { +async function lockOwnershipMatches(lock: string, token: string): Promise { + try { + const owner = JSON.parse(await readFile(path.join(lock, "owner.json"), "utf8")); + return owner?.token === token; + } catch { + return false; + } +} + +async function acquirePublicationLock(lock: string): Promise { for (let attempt = 0; attempt < 300; attempt += 1) { try { await mkdir(lock); + const token = randomUUID(); await writeFile( path.join(lock, "owner.json"), - JSON.stringify({ pid: process.pid, createdAt: new Date().toISOString() }) + "\n", + JSON.stringify({ token, pid: process.pid, createdAt: new Date().toISOString() }) + "\n", { mode: 0o600 }, ); - return; + return token; } catch (error) { if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error; if (await reclaimStalePublicationLock(lock)) continue; @@ -714,8 +727,14 @@ export async function publishStagedDirectory(input: { destination: string; lock: string; validate?: () => Promise; + track?: (path: string) => void; + release?: (path: string) => void; }): Promise { - await acquirePublicationLock(input.lock); + const token = await acquirePublicationLock(input.lock); + input.track?.(input.lock); + const heartbeat = setInterval(() => { + void utimes(input.lock, new Date(), new Date()).catch(() => undefined); + }, PUBLICATION_LOCK_STALE_MS / 3); const backup = input.staging + "-previous"; let movedPrevious = false; try { @@ -734,7 +753,10 @@ export async function publishStagedDirectory(input: { } if (movedPrevious) await rm(backup, { recursive: true, force: true }); } finally { - await rm(input.lock, { recursive: true, force: true }); + clearInterval(heartbeat); + if (await lockOwnershipMatches(input.lock, token)) + await rm(input.lock, { recursive: true, force: true }); + input.release?.(input.lock); } } @@ -828,6 +850,7 @@ export async function exportLifetimeTrace(input: ExportInput): Promise { const currentPull = await readPull(input); if (currentPull.headRefOid !== pull.headRefOid) @@ -850,7 +875,9 @@ export async function exportLifetimeTrace(input: ExportInput): Promise {}, 1000); else { process.stdout.write(fs.readFileSync(process.env.VALUE_STREAM_ARTIFACT)); process.exit(0); } } -else if (args.includes("/check-runs?")) { const checks=scenario.startsWith("legacy-") ? [] : [{id:1,name:"required-a",status:"completed",conclusion:"success",created_at:"2026-01-01T00:00:35Z",started_at:"2026-01-01T00:00:45Z",completed_at:scenario === "early-check" ? "2026-01-01T00:00:20Z" : "2026-01-01T00:02:30Z",html_url:"",app:{id:scenario === "wrong-app" ? 8 : 7,slug:"actions"}}]; if (scenario !== "incomplete" && scenario !== "wrong-app" && scenario !== "any-app" && scenario !== "app-status-denied" && scenario !== "early-check" && !scenario.startsWith("legacy-")) checks.push({...checks[0],id:2,name:"required-b",created_at:"2026-01-01T00:00:40Z",completed_at:"2026-01-01T00:02:40Z"}); value=checks; } +else if (args.includes("/check-runs?")) { const checks=scenario.startsWith("legacy-") ? [] : [{id:1,name:"required-a",status:"completed",conclusion:"success",created_at:"2026-01-01T00:00:35Z",started_at:"2026-01-01T00:00:45Z",completed_at:scenario === "early-check" ? "2026-01-01T00:00:20Z" : "2026-01-01T00:02:30Z",html_url:"",app:{id:scenario === "wrong-app" ? 8 : 7,slug:"actions"}}]; if (scenario === "duplicate-checks" && args.includes("filter=all")) checks.push({...checks[0],id:3,created_at:"2026-01-01T00:00:30Z"}); if (scenario !== "incomplete" && scenario !== "wrong-app" && scenario !== "any-app" && scenario !== "app-status-denied" && scenario !== "early-check" && !scenario.startsWith("legacy-")) checks.push({...checks[0],id:2,name:"required-b",created_at:"2026-01-01T00:00:40Z",completed_at:"2026-01-01T00:02:40Z"}); value=checks; } else if (args.includes("/status?")) { if (scenario === "app-status-denied") { console.error("Commit statuses forbidden"); process.exit(1); } const page = Number(new URL("https://example.test/?" + args.split("?")[1].split(" ")[0]).searchParams.get("page")); @@ -272,6 +272,21 @@ describe("pull request value-stream analysis", () => { }); }); + test("retains every external check attempt with the same name (#10542)", async () => { + const result = await run("duplicate-checks"); + const report = JSON.parse(result.stdout); + expect(report.lifetime.externalChecks).toBe(3); + const trace = JSON.parse( + await readFile(path.join(result.directory, report.lifetime.trace), "utf8"), + ); + expect( + trace.traceEvents.filter( + (event: { cat?: string; name?: string }) => + event.cat === "ci.external-check" && event.name === "required-a", + ), + ).toHaveLength(2); + }); + test("does not settle automation when a required exact-head check is absent (#10542)", async () => { const report = JSON.parse((await run("incomplete")).stdout); expect(report.events.automationSettled).toBeNull(); From c5e5fc57cf8bdfe3efc74bf41174d413ea4b0fd2 Mon Sep 17 00:00:00 2001 From: Carlos Villela Date: Sat, 29 Aug 2026 01:15:05 -0700 Subject: [PATCH 07/22] fix(maintainer): recover interrupted trace publication Signed-off-by: Carlos Villela --- .../scripts/export-pr-lifetime-trace.mts | 134 +++++++++++++++--- .../scripts/validate-chrome-trace.mts | 55 ------- .../analyze-pr-value-stream.test.ts | 20 ++- 3 files changed, 132 insertions(+), 77 deletions(-) delete mode 100644 .agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/validate-chrome-trace.mts diff --git a/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts b/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts index 6fe63795985..5767f80088b 100644 --- a/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts +++ b/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts @@ -2,10 +2,68 @@ // SPDX-License-Identifier: Apache-2.0 import { randomUUID } from "node:crypto"; -import { mkdir, mkdtemp, readFile, rename, rm, stat, utimes, writeFile } from "node:fs/promises"; +import { + mkdir, + mkdtemp, + readFile, + readdir, + rename, + rm, + stat, + utimes, + writeFile, +} from "node:fs/promises"; import path from "node:path"; -import { validateChromeTrace } from "./validate-chrome-trace.mts"; +type ValidatedEvent = { + name?: unknown; + ph?: unknown; + ts?: unknown; + dur?: unknown; + pid?: unknown; + tid?: unknown; +}; + +export async function validateChromeTrace( + file: string, +): Promise<{ events: number; tracks: number }> { + const payload = JSON.parse(await readFile(file, "utf8")) as { traceEvents?: unknown }; + if (!Array.isArray(payload.traceEvents)) throw new Error("traceEvents must be an array"); + const tracks = new Map(); + const metadata = new Set(); + for (const raw of payload.traceEvents as ValidatedEvent[]) { + if (typeof raw.name !== "string" || !["M", "i", "X"].includes(String(raw.ph))) + throw new Error("trace event used an unsupported Chrome trace phase"); + if (!Number.isSafeInteger(raw.pid) || !Number.isSafeInteger(raw.tid)) + throw new Error("trace event pid and tid must be safe integers"); + if (raw.ph === "M") { + const key = raw.name + ":" + raw.pid + ":" + raw.tid; + if (metadata.has(key)) throw new Error("duplicate trace metadata event " + key); + metadata.add(key); + continue; + } + if (!Number.isSafeInteger(raw.ts)) + throw new Error("timed trace event must have a safe timestamp"); + if (raw.ph !== "X") continue; + if (!Number.isSafeInteger(raw.dur) || Number(raw.dur) < 0) + throw new Error("complete trace event must have a nonnegative safe duration"); + const key = raw.pid + ":" + raw.tid; + const track = tracks.get(key) ?? []; + track.push({ ts: Number(raw.ts), dur: Number(raw.dur), name: raw.name }); + tracks.set(key, track); + } + for (const [key, events] of tracks) { + events.sort((left, right) => left.ts - right.ts || right.dur - left.dur); + const stack: typeof events = []; + for (const event of events) { + while (stack.length > 0 && event.ts >= stack.at(-1)!.ts + stack.at(-1)!.dur) stack.pop(); + if (stack.length > 0 && event.ts + event.dur > stack.at(-1)!.ts + stack.at(-1)!.dur) + throw new Error("crossing complete events on trace track " + key); + stack.push(event); + } + } + return { events: payload.traceEvents.length, tracks: tracks.size }; +} const MAX_PAGES = 10; const MAX_REVISIONS = 250; @@ -249,23 +307,27 @@ async function readPull(input: ExportInput): Promise { async function readRuns( input: ExportInput, - branch: string, - commitIds: Set, -): Promise<{ rows: Run[]; truncated: boolean }> { - const collection = await readPages({ - githubRead: input.githubRead, - endpoint: "repos/" + input.repository + "/actions/runs?branch=" + encodeURIComponent(branch), - projection: - "[.workflow_runs[] | {id,event,head_sha,created_at,run_started_at,updated_at,status,conclusion,name,html_url}]", - label: "workflow runs", + commits: Commit[], +): Promise<{ rows: Run[]; truncated: false }> { + const groups = await mapBounded(commits, async (commit) => { + const collection = await readPages({ + githubRead: input.githubRead, + endpoint: + "repos/" + input.repository + "/actions/runs?head_sha=" + encodeURIComponent(commit.oid), + projection: + "[.workflow_runs[] | {id,event,head_sha,created_at,run_started_at,updated_at,status,conclusion,name,html_url}]", + label: "workflow runs", + }); + if (collection.truncated) + throw new Error("workflow history exceeded the bounded lifetime pages for " + commit.oid); + return collection.rows.filter( + (run) => run?.head_sha === commit.oid && Number.isSafeInteger(run?.id), + ); }); - if (collection.truncated) throw new Error("workflow history exceeded the bounded lifetime pages"); - const rows = collection.rows.filter( - (run) => commitIds.has(run?.head_sha) && Number.isSafeInteger(run?.id), - ); + const rows = [...new Map(groups.flat().map((run) => [run.id, run])).values()]; if (rows.length > MAX_WORKFLOW_RUNS) throw new Error("lifetime workflow history exceeded " + MAX_WORKFLOW_RUNS + " runs"); - return { rows: rows as Run[], truncated: collection.truncated }; + return { rows: rows as Run[], truncated: false }; } async function readJobs(input: ExportInput, runs: Run[]): Promise { @@ -722,6 +784,39 @@ async function acquirePublicationLock(lock: string): Promise { throw new Error("timed out waiting for active lifetime artifact publication lock: " + lock); } +async function recoverInterruptedPublication(destination: string): Promise { + const parent = path.dirname(destination); + const prefix = "." + path.basename(destination) + "-staging-"; + const backups = (await readdir(parent)) + .filter((entry) => entry.startsWith(prefix) && entry.endsWith("-previous")) + .map((entry) => path.join(parent, entry)); + let destinationExists = true; + try { + await stat(destination); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; + destinationExists = false; + } + if (!destinationExists && backups.length === 1) { + try { + await rename(backups[0], destination); + return; + } catch (error) { + throw new Error( + "failed to restore interrupted lifetime artifact publication from " + + backups[0] + + ": " + + String(error), + ); + } + } + if (!destinationExists && backups.length > 1) + throw new Error( + "multiple interrupted lifetime artifact backups require recovery: " + backups.join(", "), + ); + await Promise.all(backups.map((backup) => rm(backup, { recursive: true, force: true }))); +} + export async function publishStagedDirectory(input: { staging: string; destination: string; @@ -738,6 +833,7 @@ export async function publishStagedDirectory(input: { const backup = input.staging + "-previous"; let movedPrevious = false; try { + await recoverInterruptedPublication(input.destination); await input.validate?.(); try { await rename(input.destination, backup); @@ -766,11 +862,7 @@ export async function exportLifetimeTrace(input: ExportInput): Promise commit.oid)), - ); + const runsCollection = await readRuns(input, commits); const [jobs, externalChecks, lifecycle] = await Promise.all([ readJobs(input, runsCollection.rows), readExternalChecks(input, commits), diff --git a/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/validate-chrome-trace.mts b/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/validate-chrome-trace.mts deleted file mode 100644 index 83164e9a6be..00000000000 --- a/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/validate-chrome-trace.mts +++ /dev/null @@ -1,55 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -import { readFile } from "node:fs/promises"; - -type Event = { - name?: unknown; - ph?: unknown; - ts?: unknown; - dur?: unknown; - pid?: unknown; - tid?: unknown; -}; - -export async function validateChromeTrace(file: string): Promise<{ - events: number; - tracks: number; -}> { - const payload = JSON.parse(await readFile(file, "utf8")) as { traceEvents?: unknown }; - if (!Array.isArray(payload.traceEvents)) throw new Error("traceEvents must be an array"); - const tracks = new Map(); - const metadata = new Set(); - for (const raw of payload.traceEvents as Event[]) { - if (typeof raw.name !== "string" || !["M", "i", "X"].includes(String(raw.ph))) - throw new Error("trace event used an unsupported Chrome trace phase"); - if (!Number.isSafeInteger(raw.pid) || !Number.isSafeInteger(raw.tid)) - throw new Error("trace event pid and tid must be safe integers"); - if (raw.ph === "M") { - const key = raw.name + ":" + raw.pid + ":" + raw.tid; - if (metadata.has(key)) throw new Error("duplicate trace metadata event " + key); - metadata.add(key); - continue; - } - if (!Number.isSafeInteger(raw.ts)) - throw new Error("timed trace event must have a safe timestamp"); - if (raw.ph !== "X") continue; - if (!Number.isSafeInteger(raw.dur) || Number(raw.dur) < 0) - throw new Error("complete trace event must have a nonnegative safe duration"); - const key = raw.pid + ":" + raw.tid; - const track = tracks.get(key) ?? []; - track.push({ ts: Number(raw.ts), dur: Number(raw.dur), name: raw.name }); - tracks.set(key, track); - } - for (const [key, events] of tracks) { - events.sort((left, right) => left.ts - right.ts || right.dur - left.dur); - const stack: typeof events = []; - for (const event of events) { - while (stack.length > 0 && event.ts >= stack.at(-1)!.ts + stack.at(-1)!.dur) stack.pop(); - if (stack.length > 0 && event.ts + event.dur > stack.at(-1)!.ts + stack.at(-1)!.dur) - throw new Error("crossing complete events on trace track " + key); - stack.push(event); - } - } - return { events: payload.traceEvents.length, tracks: tracks.size }; -} diff --git a/test/automation/pull-requests/analyze-pr-value-stream.test.ts b/test/automation/pull-requests/analyze-pr-value-stream.test.ts index bd5e6fba8e9..fac2f8c999f 100644 --- a/test/automation/pull-requests/analyze-pr-value-stream.test.ts +++ b/test/automation/pull-requests/analyze-pr-value-stream.test.ts @@ -22,8 +22,8 @@ import { cleanupArtifactDirectory } from "../../../.agents/skills/nemoclaw-maint import { publishStagedDirectory, reclaimStalePublicationLock, + validateChromeTrace, } from "../../../.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts"; -import { validateChromeTrace } from "../../../.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/validate-chrome-trace.mts"; const root = path.resolve(import.meta.dirname, "../../.."); const analyzer = path.join( @@ -469,6 +469,24 @@ describe("pull request value-stream analysis", () => { ); }); + test("recovers a complete artifact set stranded by interrupted publication (#10542)", async () => { + const publicationRoot = await mkdtemp(path.join(tmpdir(), "value-stream-recover-")); + temporaryDirectories.push(publicationRoot); + const destination = path.join(publicationRoot, "pr-42"); + const backup = path.join(publicationRoot, ".pr-42-staging-interrupted-previous"); + const staging = path.join(publicationRoot, "replacement"); + await Promise.all([mkdir(backup), mkdir(staging)]); + await Promise.all([ + writeFile(path.join(backup, "manifest.json"), "prior"), + writeFile(path.join(staging, "manifest.json"), "replacement"), + ]); + await publishStagedDirectory({ staging, destination, lock: destination + ".lock" }); + await expect(readFile(path.join(destination, "manifest.json"), "utf8")).resolves.toBe( + "replacement", + ); + await expect(stat(backup)).rejects.toThrow(); + }); + test("validates freshness after publication lock contention (#10542)", async () => { const publicationRoot = await mkdtemp(path.join(tmpdir(), "value-stream-contention-")); temporaryDirectories.push(publicationRoot); From 07f8c493d4698fdec0826d997a033ce058faf1a3 Mon Sep 17 00:00:00 2001 From: Carlos Villela Date: Sat, 29 Aug 2026 01:24:21 -0700 Subject: [PATCH 08/22] fix(maintainer): fence displaced trace publishers Signed-off-by: Carlos Villela --- .../scripts/export-pr-lifetime-trace.mts | 12 +++++++- .../analyze-pr-value-stream.test.ts | 30 +++++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) diff --git a/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts b/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts index 5767f80088b..44d85bc2c4e 100644 --- a/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts +++ b/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts @@ -764,6 +764,11 @@ async function lockOwnershipMatches(lock: string, token: string): Promise { + if (!(await lockOwnershipMatches(lock, token))) + throw new Error("lifetime artifact publication lock ownership changed: " + lock); +} + async function acquirePublicationLock(lock: string): Promise { for (let attempt = 0; attempt < 300; attempt += 1) { try { @@ -835,6 +840,7 @@ export async function publishStagedDirectory(input: { try { await recoverInterruptedPublication(input.destination); await input.validate?.(); + await requirePublicationLockOwnership(input.lock, token); try { await rename(input.destination, backup); movedPrevious = true; @@ -842,12 +848,16 @@ export async function publishStagedDirectory(input: { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; } try { + await requirePublicationLockOwnership(input.lock, token); await rename(input.staging, input.destination); } catch (error) { if (movedPrevious) await rename(backup, input.destination); throw error; } - if (movedPrevious) await rm(backup, { recursive: true, force: true }); + if (movedPrevious) { + await requirePublicationLockOwnership(input.lock, token); + await rm(backup, { recursive: true, force: true }); + } } finally { clearInterval(heartbeat); if (await lockOwnershipMatches(input.lock, token)) diff --git a/test/automation/pull-requests/analyze-pr-value-stream.test.ts b/test/automation/pull-requests/analyze-pr-value-stream.test.ts index fac2f8c999f..c65951818a0 100644 --- a/test/automation/pull-requests/analyze-pr-value-stream.test.ts +++ b/test/automation/pull-requests/analyze-pr-value-stream.test.ts @@ -514,6 +514,36 @@ describe("pull request value-stream analysis", () => { ); }); + test("prevents a displaced publisher from replacing newer artifacts (#10542)", async () => { + const publicationRoot = await mkdtemp(path.join(tmpdir(), "value-stream-fence-")); + temporaryDirectories.push(publicationRoot); + const destination = path.join(publicationRoot, "pr-42"); + const first = path.join(publicationRoot, "first"); + const second = path.join(publicationRoot, "second"); + const lock = destination + ".lock"; + await Promise.all([mkdir(first), mkdir(second)]); + await Promise.all([ + writeFile(path.join(first, "manifest.json"), "first"), + writeFile(path.join(second, "manifest.json"), "second"), + ]); + let resumeFirst!: () => void; + const firstBlocked = new Promise((resolve) => { + resumeFirst = resolve; + }); + const firstPublication = publishStagedDirectory({ + staging: first, + destination, + lock, + validate: () => firstBlocked, + }); + await new Promise((resolve) => setTimeout(resolve, 150)); + expect(await reclaimStalePublicationLock(lock, Date.now() + 6 * 60 * 1_000)).toBe(true); + await publishStagedDirectory({ staging: second, destination, lock }); + resumeFirst(); + await expect(firstPublication).rejects.toThrow("lock ownership changed"); + await expect(readFile(path.join(destination, "manifest.json"), "utf8")).resolves.toBe("second"); + }); + test("reclaims stale publication locks but preserves active locks (#10542)", async () => { const publicationRoot = await mkdtemp(path.join(tmpdir(), "value-stream-lock-")); temporaryDirectories.push(publicationRoot); From 41a9c439f7e01d85a277a40251bb35b6fbc27472 Mon Sep 17 00:00:00 2001 From: Carlos Villela Date: Sat, 29 Aug 2026 01:32:51 -0700 Subject: [PATCH 09/22] fix(maintainer): reclaim only stopped trace owners Signed-off-by: Carlos Villela --- .../SKILL.md | 2 +- .../scripts/export-pr-lifetime-trace.mts | 13 ++++++++++ .../analyze-pr-value-stream.test.ts | 26 ++++++++++++------- 3 files changed, 31 insertions(+), 10 deletions(-) diff --git a/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/SKILL.md b/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/SKILL.md index 20ae3b3214d..be917fc13c6 100644 --- a/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/SKILL.md +++ b/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/SKILL.md @@ -58,7 +58,7 @@ Do not describe a fallback branch timestamp as exact. Do not claim causal attrib ## Trust boundaries -The script performs no GitHub writes. It invokes executables with argument arrays, bounds GitHub output, pagination, revisions, workflow runs, jobs, trace events, artifact sizes, and file sizes, and rejects malformed or incomplete required history. Lifetime artifact publication uses a per-PR lock. An active publication waits for up to 30 seconds; a lock left untouched for more than five minutes is treated as orphaned and reclaimed automatically. A timeout reports the exact active lock path for diagnosis. +The script performs no GitHub writes. It invokes executables with argument arrays, bounds GitHub output, pagination, revisions, workflow runs, jobs, trace events, artifact sizes, and file sizes, and rejects malformed or incomplete required history. Lifetime artifact publication uses a per-PR lock. An active publication waits for up to 30 seconds; a lock left untouched for more than five minutes is reclaimed automatically only when its recorded owner process has stopped. A timeout reports the exact active lock path for diagnosis. GitHub does not expose canonical branch-creation timestamps or pull request description edit history. The trace uses the first retained exact-commit workflow as an observable push signal and records that limitation. Draft transitions appear only when GitHub's timeline returns them. diff --git a/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts b/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts index 44d85bc2c4e..056a3414b4f 100644 --- a/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts +++ b/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts @@ -744,6 +744,19 @@ export async function reclaimStalePublicationLock( throw error; } if (now - lockStat.mtimeMs <= PUBLICATION_LOCK_STALE_MS) return false; + let owner: { pid?: unknown }; + try { + owner = JSON.parse(await readFile(path.join(lock, "owner.json"), "utf8")); + } catch { + return false; + } + if (!Number.isSafeInteger(owner.pid) || Number(owner.pid) <= 0) return false; + try { + process.kill(Number(owner.pid), 0); + return false; + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "ESRCH") return false; + } const stale = lock + ".stale-" + process.pid + "-" + now; try { await rename(lock, stale); diff --git a/test/automation/pull-requests/analyze-pr-value-stream.test.ts b/test/automation/pull-requests/analyze-pr-value-stream.test.ts index c65951818a0..fb536a97afd 100644 --- a/test/automation/pull-requests/analyze-pr-value-stream.test.ts +++ b/test/automation/pull-requests/analyze-pr-value-stream.test.ts @@ -493,7 +493,7 @@ describe("pull request value-stream analysis", () => { const destination = path.join(publicationRoot, "pr-42"); const staging = path.join(publicationRoot, "staging"); const lock = destination + ".lock"; - await Promise.all([mkdir(destination), mkdir(staging), mkdir(lock)]); + await Promise.all([mkdir(destination), mkdir(staging)]); await Promise.all([ writeFile(path.join(destination, "manifest.json"), "current"), writeFile(path.join(staging, "manifest.json"), "stale"), @@ -506,15 +506,13 @@ describe("pull request value-stream analysis", () => { throw new Error("pull request head changed during lifetime analysis"); }, }); - await new Promise((resolve) => setTimeout(resolve, 150)); - await rm(lock, { recursive: true }); await expect(publication).rejects.toThrow("pull request head changed during lifetime analysis"); await expect(readFile(path.join(destination, "manifest.json"), "utf8")).resolves.toBe( "current", ); }); - test("prevents a displaced publisher from replacing newer artifacts (#10542)", async () => { + test("does not reclaim a lock while its publisher is alive (#10542)", async () => { const publicationRoot = await mkdtemp(path.join(tmpdir(), "value-stream-fence-")); temporaryDirectories.push(publicationRoot); const destination = path.join(publicationRoot, "pr-42"); @@ -527,6 +525,10 @@ describe("pull request value-stream analysis", () => { writeFile(path.join(second, "manifest.json"), "second"), ]); let resumeFirst!: () => void; + let firstOwnsLock!: () => void; + const firstEnteredValidation = new Promise((resolve) => { + firstOwnsLock = resolve; + }); const firstBlocked = new Promise((resolve) => { resumeFirst = resolve; }); @@ -534,13 +536,16 @@ describe("pull request value-stream analysis", () => { staging: first, destination, lock, - validate: () => firstBlocked, + validate: () => { + firstOwnsLock(); + return firstBlocked; + }, }); - await new Promise((resolve) => setTimeout(resolve, 150)); - expect(await reclaimStalePublicationLock(lock, Date.now() + 6 * 60 * 1_000)).toBe(true); - await publishStagedDirectory({ staging: second, destination, lock }); + await firstEnteredValidation; + expect(await reclaimStalePublicationLock(lock, Date.now() + 6 * 60 * 1_000)).toBe(false); resumeFirst(); - await expect(firstPublication).rejects.toThrow("lock ownership changed"); + await firstPublication; + await publishStagedDirectory({ staging: second, destination, lock }); await expect(readFile(path.join(destination, "manifest.json"), "utf8")).resolves.toBe("second"); }); @@ -549,9 +554,12 @@ describe("pull request value-stream analysis", () => { temporaryDirectories.push(publicationRoot); const lock = path.join(publicationRoot, "pr-42.lock"); await mkdir(lock); + await writeFile(path.join(lock, "owner.json"), JSON.stringify({ pid: process.pid })); expect(await reclaimStalePublicationLock(lock)).toBe(false); const stale = new Date(Date.now() - 6 * 60 * 1_000); await utimes(lock, stale, stale); + expect(await reclaimStalePublicationLock(lock)).toBe(false); + await writeFile(path.join(lock, "owner.json"), JSON.stringify({ pid: 2_147_483_647 })); expect(await reclaimStalePublicationLock(lock)).toBe(true); await expect(stat(lock)).rejects.toThrow(); }); From 5eeacf6e09c3ab0a02815ed510276b0c329dc120 Mon Sep 17 00:00:00 2001 From: Carlos Villela Date: Sat, 29 Aug 2026 01:41:17 -0700 Subject: [PATCH 10/22] fix(maintainer): identify stale trace lock owners Signed-off-by: Carlos Villela --- .../scripts/export-pr-lifetime-trace.mts | 42 +++++++++++++++---- .../analyze-pr-value-stream.test.ts | 22 ++++++++-- 2 files changed, 51 insertions(+), 13 deletions(-) diff --git a/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts b/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts index 056a3414b4f..209053ad7cc 100644 --- a/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts +++ b/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts @@ -732,6 +732,19 @@ function renderTrace(input: { return { events, lifecycleEvents }; } +async function processStartIdentity(pid: number): Promise { + try { + const value = await readFile("/proc/" + pid + "/stat", "utf8"); + const fields = value + .slice(value.lastIndexOf(")") + 2) + .trim() + .split(/\s+/u); + return fields[19] ?? null; + } catch { + return null; + } +} + export async function reclaimStalePublicationLock( lock: string, now = Date.now(), @@ -744,18 +757,23 @@ export async function reclaimStalePublicationLock( throw error; } if (now - lockStat.mtimeMs <= PUBLICATION_LOCK_STALE_MS) return false; - let owner: { pid?: unknown }; + let owner: { pid?: unknown; startIdentity?: unknown } | null = null; try { owner = JSON.parse(await readFile(path.join(lock, "owner.json"), "utf8")); } catch { - return false; + // An old lock can be left before owner metadata is written. } - if (!Number.isSafeInteger(owner.pid) || Number(owner.pid) <= 0) return false; - try { - process.kill(Number(owner.pid), 0); - return false; - } catch (error) { - if ((error as NodeJS.ErrnoException).code !== "ESRCH") return false; + if (owner && Number.isSafeInteger(owner.pid) && Number(owner.pid) > 0) { + const observedIdentity = await processStartIdentity(Number(owner.pid)); + if (observedIdentity !== null && observedIdentity === owner.startIdentity) return false; + if (observedIdentity === null) { + try { + process.kill(Number(owner.pid), 0); + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ESRCH") owner = null; + } + if (owner !== null) return false; + } } const stale = lock + ".stale-" + process.pid + "-" + now; try { @@ -787,9 +805,15 @@ async function acquirePublicationLock(lock: string): Promise { try { await mkdir(lock); const token = randomUUID(); + const startIdentity = await processStartIdentity(process.pid); await writeFile( path.join(lock, "owner.json"), - JSON.stringify({ token, pid: process.pid, createdAt: new Date().toISOString() }) + "\n", + JSON.stringify({ + token, + pid: process.pid, + startIdentity, + createdAt: new Date().toISOString(), + }) + "\n", { mode: 0o600 }, ); return token; diff --git a/test/automation/pull-requests/analyze-pr-value-stream.test.ts b/test/automation/pull-requests/analyze-pr-value-stream.test.ts index fb536a97afd..c0ff74e7bcb 100644 --- a/test/automation/pull-requests/analyze-pr-value-stream.test.ts +++ b/test/automation/pull-requests/analyze-pr-value-stream.test.ts @@ -469,7 +469,7 @@ describe("pull request value-stream analysis", () => { ); }); - test("recovers a complete artifact set stranded by interrupted publication (#10542)", async () => { + test("removes an interrupted backup before publishing replacement artifacts (#10542)", async () => { const publicationRoot = await mkdtemp(path.join(tmpdir(), "value-stream-recover-")); temporaryDirectories.push(publicationRoot); const destination = path.join(publicationRoot, "pr-42"); @@ -487,7 +487,7 @@ describe("pull request value-stream analysis", () => { await expect(stat(backup)).rejects.toThrow(); }); - test("validates freshness after publication lock contention (#10542)", async () => { + test("preserves published artifacts when freshness validation fails (#10542)", async () => { const publicationRoot = await mkdtemp(path.join(tmpdir(), "value-stream-contention-")); temporaryDirectories.push(publicationRoot); const destination = path.join(publicationRoot, "pr-42"); @@ -554,12 +554,26 @@ describe("pull request value-stream analysis", () => { temporaryDirectories.push(publicationRoot); const lock = path.join(publicationRoot, "pr-42.lock"); await mkdir(lock); - await writeFile(path.join(lock, "owner.json"), JSON.stringify({ pid: process.pid })); + const liveStart = await readFile("/proc/" + process.pid + "/stat", "utf8"); + const liveIdentity = liveStart + .slice(liveStart.lastIndexOf(")") + 2) + .trim() + .split(/\s+/u)[19]; + await writeFile( + path.join(lock, "owner.json"), + JSON.stringify({ pid: process.pid, startIdentity: liveIdentity }), + ); expect(await reclaimStalePublicationLock(lock)).toBe(false); const stale = new Date(Date.now() - 6 * 60 * 1_000); await utimes(lock, stale, stale); expect(await reclaimStalePublicationLock(lock)).toBe(false); - await writeFile(path.join(lock, "owner.json"), JSON.stringify({ pid: 2_147_483_647 })); + await writeFile( + path.join(lock, "owner.json"), + JSON.stringify({ pid: process.pid, startIdentity: "reused-owner" }), + ); + expect(await reclaimStalePublicationLock(lock)).toBe(true); + await mkdir(lock); + await utimes(lock, stale, stale); expect(await reclaimStalePublicationLock(lock)).toBe(true); await expect(stat(lock)).rejects.toThrow(); }); From 5f4805677ae12c520aba5d8fdc760a21de1e42af Mon Sep 17 00:00:00 2001 From: Carlos Villela Date: Sat, 29 Aug 2026 01:49:54 -0700 Subject: [PATCH 11/22] fix(maintainer): complete retained workflow attempts Signed-off-by: Carlos Villela --- .../scripts/export-pr-lifetime-trace.mts | 32 ++++++++++++++++--- .../analyze-pr-value-stream.test.ts | 13 ++++++++ 2 files changed, 41 insertions(+), 4 deletions(-) diff --git a/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts b/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts index 209053ad7cc..2b55601ebd3 100644 --- a/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts +++ b/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts @@ -334,7 +334,7 @@ async function readJobs(input: ExportInput, runs: Run[]): Promise { const groups = await mapBounded(runs, async (run) => { const result = await input.githubRead([ "api", - "repos/" + input.repository + "/actions/runs/" + run.id + "/jobs?per_page=100", + "repos/" + input.repository + "/actions/runs/" + run.id + "/jobs?filter=all&per_page=100", "--jq", "{total_count,jobs:[.jobs[] | {id,name,status,conclusion,created_at,started_at,completed_at,runner_name,runner_group_name,labels,html_url,steps}]}", ]); @@ -826,7 +826,11 @@ async function acquirePublicationLock(lock: string): Promise { throw new Error("timed out waiting for active lifetime artifact publication lock: " + lock); } -async function recoverInterruptedPublication(destination: string): Promise { +async function recoverInterruptedPublication( + destination: string, + lock: string, + token: string, +): Promise { const parent = path.dirname(destination); const prefix = "." + path.basename(destination) + "-staging-"; const backups = (await readdir(parent)) @@ -841,6 +845,7 @@ async function recoverInterruptedPublication(destination: string): Promise } if (!destinationExists && backups.length === 1) { try { + await requirePublicationLockOwnership(lock, token); await rename(backups[0], destination); return; } catch (error) { @@ -856,6 +861,7 @@ async function recoverInterruptedPublication(destination: string): Promise throw new Error( "multiple interrupted lifetime artifact backups require recovery: " + backups.join(", "), ); + await requirePublicationLockOwnership(lock, token); await Promise.all(backups.map((backup) => rm(backup, { recursive: true, force: true }))); } @@ -875,7 +881,7 @@ export async function publishStagedDirectory(input: { const backup = input.staging + "-previous"; let movedPrevious = false; try { - await recoverInterruptedPublication(input.destination); + await recoverInterruptedPublication(input.destination, input.lock, token); await input.validate?.(); await requirePublicationLockOwnership(input.lock, token); try { @@ -903,6 +909,24 @@ export async function publishStagedDirectory(input: { } } +export async function cleanupLifetimeStaging( + staging: string, + original: unknown, + remove: typeof rm = rm, +): Promise { + try { + await remove(staging, { recursive: true, force: true }); + } catch (cleanupError) { + throw new Error( + String(original) + + "; failed to remove retained lifetime staging directory " + + staging + + "; remove it manually: " + + String(cleanupError), + ); + } +} + export async function exportLifetimeTrace(input: ExportInput): Promise { const pull = await readPull(input); const expectedHead = (input.report as { headSha?: unknown }).headSha; @@ -1013,7 +1037,7 @@ export async function exportLifetimeTrace(input: ExportInput): Promise { await expect(stat(lock)).rejects.toThrow(); }); + test("reports retained staging path without hiding publication failure (#10542)", async () => { + const staging = "/tmp/value-stream-retained-staging"; + const remove = vi.fn(async () => { + throw new Error("permission denied"); + }); + await expect( + cleanupLifetimeStaging(staging, new Error("publication failed"), remove), + ).rejects.toThrow( + "publication failed; failed to remove retained lifetime staging directory " + staging, + ); + }); + test("accepts a valid synthetic Chrome trace (#10542)", async () => { const trace = path.join( await mkdtemp(path.join(tmpdir(), "value-stream-trace-")), From b84fbcdd8302be6bd924806cc9f9814b0e6c69db Mon Sep 17 00:00:00 2001 From: Carlos Villela Date: Sat, 29 Aug 2026 01:58:35 -0700 Subject: [PATCH 12/22] fix(maintainer): recover portable trace locks Signed-off-by: Carlos Villela --- .../SKILL.md | 2 +- .../scripts/export-pr-lifetime-trace.mts | 10 ++------- .../analyze-pr-value-stream.test.ts | 21 ++++++++++++++++++- 3 files changed, 23 insertions(+), 10 deletions(-) diff --git a/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/SKILL.md b/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/SKILL.md index be917fc13c6..8834586ae28 100644 --- a/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/SKILL.md +++ b/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/SKILL.md @@ -58,7 +58,7 @@ Do not describe a fallback branch timestamp as exact. Do not claim causal attrib ## Trust boundaries -The script performs no GitHub writes. It invokes executables with argument arrays, bounds GitHub output, pagination, revisions, workflow runs, jobs, trace events, artifact sizes, and file sizes, and rejects malformed or incomplete required history. Lifetime artifact publication uses a per-PR lock. An active publication waits for up to 30 seconds; a lock left untouched for more than five minutes is reclaimed automatically only when its recorded owner process has stopped. A timeout reports the exact active lock path for diagnosis. +The script performs no GitHub writes. It invokes executables with argument arrays, bounds GitHub output, pagination, revisions, workflow runs, jobs, trace events, artifact sizes, and file sizes, and rejects malformed or incomplete required history. Lifetime artifact publication uses a per-PR lock. An active publication waits for up to 30 seconds; a lock left untouched for more than five minutes is reclaimed when its recorded owner identity no longer matches, when owner metadata is unreadable, or when the host cannot provide a process-start identity. A timeout reports the exact active lock path for diagnosis. GitHub does not expose canonical branch-creation timestamps or pull request description edit history. The trace uses the first retained exact-commit workflow as an observable push signal and records that limitation. Draft transitions appear only when GitHub's timeline returns them. diff --git a/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts b/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts index 2b55601ebd3..4411898adbe 100644 --- a/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts +++ b/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts @@ -766,14 +766,8 @@ export async function reclaimStalePublicationLock( if (owner && Number.isSafeInteger(owner.pid) && Number(owner.pid) > 0) { const observedIdentity = await processStartIdentity(Number(owner.pid)); if (observedIdentity !== null && observedIdentity === owner.startIdentity) return false; - if (observedIdentity === null) { - try { - process.kill(Number(owner.pid), 0); - } catch (error) { - if ((error as NodeJS.ErrnoException).code === "ESRCH") owner = null; - } - if (owner !== null) return false; - } + // On hosts without process start identities, the stale heartbeat is the fence. + if (observedIdentity === null) owner = null; } const stale = lock + ".stale-" + process.pid + "-" + now; try { diff --git a/test/automation/pull-requests/analyze-pr-value-stream.test.ts b/test/automation/pull-requests/analyze-pr-value-stream.test.ts index 36db2319e52..d2645b1a2cf 100644 --- a/test/automation/pull-requests/analyze-pr-value-stream.test.ts +++ b/test/automation/pull-requests/analyze-pr-value-stream.test.ts @@ -90,7 +90,9 @@ const scenario = process.env.VALUE_STREAM_SCENARIO; const sha = "a".repeat(40); const review = (state,time) => ({state,submittedAt:time,author:{login:"reviewer"},commit:{oid:sha}}); const reviews = scenario === "approval-restored" ? [review("APPROVED","2026-01-01T00:02:45Z"),review("CHANGES_REQUESTED","2026-01-01T00:03:00Z"),review("APPROVED","2026-01-01T00:03:15Z")] : scenario === "approval-revoked" ? [review("APPROVED","2026-01-01T00:02:45Z"),review("CHANGES_REQUESTED","2026-01-01T00:03:00Z")] : []; -const pull = {number:42,url:"https://example.test/pr/42",state:scenario.startsWith("approval-") ? "MERGED" : "OPEN",isDraft:false,createdAt:"2026-01-01T00:01:00Z",updatedAt:"2026-01-01T00:04:00Z",mergedAt:scenario.startsWith("approval-") ? "2026-01-01T00:04:00Z" : null,author:{login:"author"},assignees:[],baseRefName:"main",headRefName:"topic",headRefOid:sha,commits:[{oid:sha,authoredDate:"2026-01-01T00:00:00Z",committedDate:"2026-01-01T00:00:00Z",messageHeadline:"change"}],reviews}; +const laterSha = "b".repeat(40); +const responseCommits = [{oid:sha,authoredDate:"2026-01-01T00:00:00Z",committedDate:"2026-01-01T00:00:00Z",messageHeadline:"change"},{oid:laterSha,authoredDate:"2026-01-01T00:01:30Z",committedDate:"2026-01-01T00:01:30Z",messageHeadline:"response"}]; +const pull = {number:42,url:"https://example.test/pr/42",state:scenario.startsWith("approval-") ? "MERGED" : "OPEN",isDraft:false,createdAt:"2026-01-01T00:01:00Z",updatedAt:"2026-01-01T00:04:00Z",mergedAt:scenario.startsWith("approval-") ? "2026-01-01T00:04:00Z" : null,author:{login:"author"},assignees:[],baseRefName:"main",headRefName:"topic",headRefOid:scenario === "feedback-response" ? laterSha : sha,commits:scenario === "feedback-response" ? responseCommits : [responseCommits[0]],reviews}; const run = (id) => ({id,event:"push",head_sha:sha,created_at:"2026-01-01T00:00:30Z",run_started_at:scenario === "queued" ? null : "2026-01-01T00:00:31Z",updated_at:"2026-01-01T00:03:00Z",status:scenario === "queued" ? "queued" : "completed",conclusion:scenario === "queued" ? null : "success",name:"CI PR #42"}); let value; if (args.startsWith("pr view")) { const calls=fs.readFileSync(process.env.VALUE_STREAM_LOG,"utf8").match(/^pr view /gmu).length; value = (scenario === "head-race" && calls > 1) || (scenario === "final-head-race" && calls > 2) ? {...pull,headRefOid:"b".repeat(40)} : pull; } @@ -256,6 +258,23 @@ describe("pull request value-stream analysis", () => { expect(report.events.latestRevisionObserved.source).toBe("head commit committedDate fallback"); }); + test("links feedback to the next author change (#10542)", async () => { + const result = await run("feedback-response"); + const report = JSON.parse(result.stdout); + const trace = JSON.parse( + await readFile(path.resolve(result.directory, report.lifetime.trace), "utf8"), + ); + expect(trace.traceEvents).toContainEqual( + expect.objectContaining({ + name: "Feedback to next author change", + cat: "author.response", + ts: Date.parse("2026-01-01T00:01:20Z") * 1_000, + dur: 10_000_000, + args: expect.objectContaining({ feedbackId: 43, nextCommit: "b".repeat(40) }), + }), + ); + }); + test("keeps queued runs jobs and steps with nullable timing fields (#10542)", async () => { const report = JSON.parse((await run("queued")).stdout); const queuedRun = report.waterfall.runs[0]; From 9caaaa97d14af97f515628d79ef0d96ab6daa25c Mon Sep 17 00:00:00 2001 From: Carlos Villela Date: Sat, 29 Aug 2026 02:07:23 -0700 Subject: [PATCH 13/22] fix(maintainer): bind trace lock cancellation cleanup Signed-off-by: Carlos Villela --- .../scripts/analyze-pr-value-stream.mts | 10 +++++----- .../scripts/export-pr-lifetime-trace.mts | 9 ++++++--- .../analyze-pr-value-stream.test.ts | 19 ++++++++----------- 3 files changed, 19 insertions(+), 19 deletions(-) diff --git a/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/analyze-pr-value-stream.mts b/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/analyze-pr-value-stream.mts index 09f07cd6329..53f49d867ac 100644 --- a/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/analyze-pr-value-stream.mts +++ b/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/analyze-pr-value-stream.mts @@ -166,7 +166,7 @@ async function runGithubCli(input: GithubCliInput): Promise<{ stdout: string }> type RequiredCheck = { name: string; appId: number | null; legacy: boolean }; -const artifactDirectories = new Set(); +const artifactDirectories = new Map Promise) | undefined>(); const artifactAbortController = new AbortController(); const cancellationSignals = ["SIGINT", "SIGTERM"] as const; let cancellationHandlersInstalled = false; @@ -184,8 +184,8 @@ async function handleCancellation(signal: (typeof cancellationSignals)[number]): artifactAbortController.abort(); const retained: string[] = []; await Promise.all( - [...artifactDirectories].map(async (directory) => { - const caveat = await cleanupArtifactDirectory(directory); + [...artifactDirectories].map(async ([directory, cleanup]) => { + const caveat = await cleanupArtifactDirectory(directory, cleanup); if (caveat !== null) retained.push(caveat); else artifactDirectories.delete(directory); }), @@ -200,8 +200,8 @@ function releaseTrackedPath(path: string): void { if (artifactDirectories.size === 0 && cancellationHandlersInstalled) removeCancellationHandlers(); } -function trackArtifactDirectory(directory: string): void { - artifactDirectories.add(directory); +function trackArtifactDirectory(directory: string, cleanup?: () => Promise): void { + artifactDirectories.set(directory, cleanup); if (cancellationHandlersInstalled) return; for (const signal of cancellationSignals) process.on(signal, handleCancellation); cancellationHandlersInstalled = true; diff --git a/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts b/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts index 4411898adbe..0b3efa7c9f7 100644 --- a/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts +++ b/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts @@ -130,7 +130,7 @@ type ExportInput = { number: number; report: unknown; githubRead: GithubRead; - trackTemporaryPath?: (path: string) => void; + trackTemporaryPath?: (path: string, cleanup?: () => Promise) => void; releaseTemporaryPath?: (path: string) => void; }; @@ -864,11 +864,14 @@ export async function publishStagedDirectory(input: { destination: string; lock: string; validate?: () => Promise; - track?: (path: string) => void; + track?: (path: string, cleanup?: () => Promise) => void; release?: (path: string) => void; }): Promise { const token = await acquirePublicationLock(input.lock); - input.track?.(input.lock); + input.track?.(input.lock, async () => { + if (await lockOwnershipMatches(input.lock, token)) + await rm(input.lock, { recursive: true, force: true }); + }); const heartbeat = setInterval(() => { void utimes(input.lock, new Date(), new Date()).catch(() => undefined); }, PUBLICATION_LOCK_STALE_MS / 3); diff --git a/test/automation/pull-requests/analyze-pr-value-stream.test.ts b/test/automation/pull-requests/analyze-pr-value-stream.test.ts index d2645b1a2cf..6873ac0a496 100644 --- a/test/automation/pull-requests/analyze-pr-value-stream.test.ts +++ b/test/automation/pull-requests/analyze-pr-value-stream.test.ts @@ -489,21 +489,18 @@ describe("pull request value-stream analysis", () => { ); }); - test("removes an interrupted backup before publishing replacement artifacts (#10542)", async () => { + test("restores an interrupted backup when replacement publication fails (#10542)", async () => { const publicationRoot = await mkdtemp(path.join(tmpdir(), "value-stream-recover-")); temporaryDirectories.push(publicationRoot); const destination = path.join(publicationRoot, "pr-42"); const backup = path.join(publicationRoot, ".pr-42-staging-interrupted-previous"); - const staging = path.join(publicationRoot, "replacement"); - await Promise.all([mkdir(backup), mkdir(staging)]); - await Promise.all([ - writeFile(path.join(backup, "manifest.json"), "prior"), - writeFile(path.join(staging, "manifest.json"), "replacement"), - ]); - await publishStagedDirectory({ staging, destination, lock: destination + ".lock" }); - await expect(readFile(path.join(destination, "manifest.json"), "utf8")).resolves.toBe( - "replacement", - ); + const staging = path.join(publicationRoot, "missing-replacement"); + await mkdir(backup); + await writeFile(path.join(backup, "manifest.json"), "prior"); + await expect( + publishStagedDirectory({ staging, destination, lock: destination + ".lock" }), + ).rejects.toThrow(); + await expect(readFile(path.join(destination, "manifest.json"), "utf8")).resolves.toBe("prior"); await expect(stat(backup)).rejects.toThrow(); }); From 62ca52007104e04cc634b347497f92b473391cce Mon Sep 17 00:00:00 2001 From: Carlos Villela Date: Sat, 29 Aug 2026 02:15:40 -0700 Subject: [PATCH 14/22] fix(maintainer): track trace lock creation Signed-off-by: Carlos Villela --- .../scripts/export-pr-lifetime-trace.mts | 23 +++++++++++++------ 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts b/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts index 0b3efa7c9f7..67cdbd0fa6d 100644 --- a/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts +++ b/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts @@ -794,11 +794,24 @@ async function requirePublicationLockOwnership(lock: string, token: string): Pro throw new Error("lifetime artifact publication lock ownership changed: " + lock); } -async function acquirePublicationLock(lock: string): Promise { +async function acquirePublicationLock( + lock: string, + track?: (path: string, cleanup?: () => Promise) => void, +): Promise { for (let attempt = 0; attempt < 300; attempt += 1) { try { - await mkdir(lock); const token = randomUUID(); + await mkdir(lock); + track?.(lock, async () => { + let ownerMissing = false; + try { + await stat(path.join(lock, "owner.json")); + } catch (error) { + ownerMissing = (error as NodeJS.ErrnoException).code === "ENOENT"; + } + if (ownerMissing || (await lockOwnershipMatches(lock, token))) + await rm(lock, { recursive: true, force: true }); + }); const startIdentity = await processStartIdentity(process.pid); await writeFile( path.join(lock, "owner.json"), @@ -867,11 +880,7 @@ export async function publishStagedDirectory(input: { track?: (path: string, cleanup?: () => Promise) => void; release?: (path: string) => void; }): Promise { - const token = await acquirePublicationLock(input.lock); - input.track?.(input.lock, async () => { - if (await lockOwnershipMatches(input.lock, token)) - await rm(input.lock, { recursive: true, force: true }); - }); + const token = await acquirePublicationLock(input.lock, input.track); const heartbeat = setInterval(() => { void utimes(input.lock, new Date(), new Date()).catch(() => undefined); }, PUBLICATION_LOCK_STALE_MS / 3); From cd70802bd9c24438af8938b1174d4a3546439d18 Mon Sep 17 00:00:00 2001 From: Carlos Villela Date: Sat, 29 Aug 2026 02:22:17 -0700 Subject: [PATCH 15/22] fix(maintainer): remove only owned trace locks Signed-off-by: Carlos Villela --- .../scripts/export-pr-lifetime-trace.mts | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts b/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts index 67cdbd0fa6d..7b44576e9a9 100644 --- a/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts +++ b/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts @@ -803,13 +803,7 @@ async function acquirePublicationLock( const token = randomUUID(); await mkdir(lock); track?.(lock, async () => { - let ownerMissing = false; - try { - await stat(path.join(lock, "owner.json")); - } catch (error) { - ownerMissing = (error as NodeJS.ErrnoException).code === "ENOENT"; - } - if (ownerMissing || (await lockOwnershipMatches(lock, token))) + if (await lockOwnershipMatches(lock, token)) await rm(lock, { recursive: true, force: true }); }); const startIdentity = await processStartIdentity(process.pid); From 61427ac429429c45576af1e70eafd7ed66d4f4f7 Mon Sep 17 00:00:00 2001 From: Carlos Villela Date: Sat, 29 Aug 2026 02:29:42 -0700 Subject: [PATCH 16/22] fix(maintainer): initialize trace locks atomically Signed-off-by: Carlos Villela --- .../scripts/export-pr-lifetime-trace.mts | 26 ++++++++++++------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts b/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts index 7b44576e9a9..1f2676c0456 100644 --- a/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts +++ b/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts @@ -797,18 +797,17 @@ async function requirePublicationLockOwnership(lock: string, token: string): Pro async function acquirePublicationLock( lock: string, track?: (path: string, cleanup?: () => Promise) => void, + release?: (path: string) => void, ): Promise { for (let attempt = 0; attempt < 300; attempt += 1) { + const token = randomUUID(); + const candidate = lock + ".candidate-" + token; + await mkdir(candidate); + track?.(candidate); try { - const token = randomUUID(); - await mkdir(lock); - track?.(lock, async () => { - if (await lockOwnershipMatches(lock, token)) - await rm(lock, { recursive: true, force: true }); - }); const startIdentity = await processStartIdentity(process.pid); await writeFile( - path.join(lock, "owner.json"), + path.join(candidate, "owner.json"), JSON.stringify({ token, pid: process.pid, @@ -817,9 +816,18 @@ async function acquirePublicationLock( }) + "\n", { mode: 0o600 }, ); + await rename(candidate, lock); + release?.(candidate); + track?.(lock, async () => { + if (await lockOwnershipMatches(lock, token)) + await rm(lock, { recursive: true, force: true }); + }); return token; } catch (error) { - if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error; + await rm(candidate, { recursive: true, force: true }); + release?.(candidate); + if (!["EEXIST", "ENOTEMPTY"].includes((error as NodeJS.ErrnoException).code ?? "")) + throw error; if (await reclaimStalePublicationLock(lock)) continue; await new Promise((resolve) => setTimeout(resolve, 100)); } @@ -874,7 +882,7 @@ export async function publishStagedDirectory(input: { track?: (path: string, cleanup?: () => Promise) => void; release?: (path: string) => void; }): Promise { - const token = await acquirePublicationLock(input.lock, input.track); + const token = await acquirePublicationLock(input.lock, input.track, input.release); const heartbeat = setInterval(() => { void utimes(input.lock, new Date(), new Date()).catch(() => undefined); }, PUBLICATION_LOCK_STALE_MS / 3); From 7a42c14148f4c79a5c2f3f8bbed96ca146ff6f64 Mon Sep 17 00:00:00 2001 From: Carlos Villela Date: Sat, 29 Aug 2026 02:36:53 -0700 Subject: [PATCH 17/22] fix(maintainer): guide trace backup recovery Signed-off-by: Carlos Villela --- .../scripts/export-pr-lifetime-trace.mts | 5 ++++- .../analyze-pr-value-stream.test.ts | 19 +++++++++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts b/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts index 1f2676c0456..aed9c760af0 100644 --- a/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts +++ b/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts @@ -868,7 +868,10 @@ async function recoverInterruptedPublication( } if (!destinationExists && backups.length > 1) throw new Error( - "multiple interrupted lifetime artifact backups require recovery: " + backups.join(", "), + "multiple interrupted lifetime artifact backups require recovery; destination " + + destination + + "; inspect each manifest.json, then rename exactly one complete candidate to the destination without deleting the others: " + + backups.join(", "), ); await requirePublicationLockOwnership(lock, token); await Promise.all(backups.map((backup) => rm(backup, { recursive: true, force: true }))); diff --git a/test/automation/pull-requests/analyze-pr-value-stream.test.ts b/test/automation/pull-requests/analyze-pr-value-stream.test.ts index 6873ac0a496..e80909c41ae 100644 --- a/test/automation/pull-requests/analyze-pr-value-stream.test.ts +++ b/test/automation/pull-requests/analyze-pr-value-stream.test.ts @@ -504,6 +504,25 @@ describe("pull request value-stream analysis", () => { await expect(stat(backup)).rejects.toThrow(); }); + test("reports non-destructive recovery for multiple interrupted backups (#10542)", async () => { + const publicationRoot = await mkdtemp(path.join(tmpdir(), "value-stream-multiple-backups-")); + temporaryDirectories.push(publicationRoot); + const destination = path.join(publicationRoot, "pr-42"); + const first = path.join(publicationRoot, ".pr-42-staging-first-previous"); + const second = path.join(publicationRoot, ".pr-42-staging-second-previous"); + await Promise.all([mkdir(first), mkdir(second)]); + await expect( + publishStagedDirectory({ + staging: path.join(publicationRoot, "missing"), + destination, + lock: destination + ".lock", + }), + ).rejects.toThrow( + `inspect each manifest.json, then rename exactly one complete candidate to the destination without deleting the others: ${first}, ${second}`, + ); + await expect(Promise.all([stat(first), stat(second)])).resolves.toHaveLength(2); + }); + test("preserves published artifacts when freshness validation fails (#10542)", async () => { const publicationRoot = await mkdtemp(path.join(tmpdir(), "value-stream-contention-")); temporaryDirectories.push(publicationRoot); From 383a5e2fe50a03ad2873cd5f2f0072b01b676a28 Mon Sep 17 00:00:00 2001 From: Carlos Villela Date: Sat, 29 Aug 2026 02:45:00 -0700 Subject: [PATCH 18/22] refactor(maintainer): narrow trace history reads Signed-off-by: Carlos Villela --- .../scripts/export-pr-lifetime-trace.mts | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts b/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts index aed9c760af0..65520b1466a 100644 --- a/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts +++ b/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts @@ -92,7 +92,6 @@ type TraceEvent = { type Commit = { oid: string; authoredAt: number; - committedAt: number; subject: string; }; @@ -101,7 +100,6 @@ type Run = { event: string; head_sha: string; created_at: string; - run_started_at: string | null; updated_at: string; status: string; conclusion: string | null; @@ -282,7 +280,6 @@ function normalizeCommits(pull: any): Commit[] { return rows.map((commit: any) => ({ oid: validateObjectId(commit?.oid), authoredAt: parseTime(commit?.authoredDate ?? commit?.committedDate, "commit authoredDate"), - committedAt: parseTime(commit?.committedDate, "commit committedDate"), subject: boundedText(commit?.messageHeadline, 200) || "Commit " + String(commit?.oid ?? "").slice(0, 8), @@ -297,7 +294,7 @@ async function readPull(input: ExportInput): Promise { "--repo", input.repository, "--json", - "number,url,state,isDraft,createdAt,mergedAt,updatedAt,author,assignees,baseRefName,headRefName,headRefOid,commits,reviews", + "number,url,state,isDraft,createdAt,mergedAt,updatedAt,author,headRefOid,commits,reviews", ]); const pull = JSON.parse(result.stdout); if (pull?.number !== input.number || typeof pull?.url !== "string") @@ -315,7 +312,7 @@ async function readRuns( endpoint: "repos/" + input.repository + "/actions/runs?head_sha=" + encodeURIComponent(commit.oid), projection: - "[.workflow_runs[] | {id,event,head_sha,created_at,run_started_at,updated_at,status,conclusion,name,html_url}]", + "[.workflow_runs[] | {id,event,head_sha,created_at,updated_at,status,conclusion,name,html_url}]", label: "workflow runs", }); if (collection.truncated) @@ -336,7 +333,7 @@ async function readJobs(input: ExportInput, runs: Run[]): Promise { "api", "repos/" + input.repository + "/actions/runs/" + run.id + "/jobs?filter=all&per_page=100", "--jq", - "{total_count,jobs:[.jobs[] | {id,name,status,conclusion,created_at,started_at,completed_at,runner_name,runner_group_name,labels,html_url,steps}]}", + "{total_count,jobs:[.jobs[] | {id,name,status,conclusion,created_at,started_at,completed_at,runner_name,runner_group_name,html_url,steps}]}", ]); const payload = JSON.parse(result.stdout); const jobs = validateArray(payload?.jobs, "workflow jobs"); From af9a07d7145774fdff6a970d850d61fda809efed Mon Sep 17 00:00:00 2001 From: Carlos Villela Date: Sat, 29 Aug 2026 02:51:26 -0700 Subject: [PATCH 19/22] fix(maintainer): fence trace lock handoff Signed-off-by: Carlos Villela --- .../scripts/export-pr-lifetime-trace.mts | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts b/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts index 65520b1466a..95d0de2ce5e 100644 --- a/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts +++ b/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts @@ -800,7 +800,12 @@ async function acquirePublicationLock( const token = randomUUID(); const candidate = lock + ".candidate-" + token; await mkdir(candidate); - track?.(candidate); + track?.(candidate, async () => { + if (await lockOwnershipMatches(candidate, token)) + await rm(candidate, { recursive: true, force: true }); + else if (await lockOwnershipMatches(lock, token)) + await rm(lock, { recursive: true, force: true }); + }); try { const startIdentity = await processStartIdentity(process.pid); await writeFile( @@ -814,11 +819,11 @@ async function acquirePublicationLock( { mode: 0o600 }, ); await rename(candidate, lock); - release?.(candidate); track?.(lock, async () => { if (await lockOwnershipMatches(lock, token)) await rm(lock, { recursive: true, force: true }); }); + release?.(candidate); return token; } catch (error) { await rm(candidate, { recursive: true, force: true }); From 5d25c4b7094bdae50ec58e2ae27553c674ebbad0 Mon Sep 17 00:00:00 2001 From: Carlos Villela Date: Sat, 29 Aug 2026 02:58:13 -0700 Subject: [PATCH 20/22] fix(maintainer): fence trace lock heartbeat Signed-off-by: Carlos Villela --- .../scripts/export-pr-lifetime-trace.mts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts b/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts index 95d0de2ce5e..a28bba0eb5f 100644 --- a/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts +++ b/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts @@ -889,7 +889,12 @@ export async function publishStagedDirectory(input: { }): Promise { const token = await acquirePublicationLock(input.lock, input.track, input.release); const heartbeat = setInterval(() => { - void utimes(input.lock, new Date(), new Date()).catch(() => undefined); + void lockOwnershipMatches(input.lock, token) + .then((owned) => { + if (owned) return utimes(input.lock, new Date(), new Date()); + clearInterval(heartbeat); + }) + .catch(() => undefined); }, PUBLICATION_LOCK_STALE_MS / 3); const backup = input.staging + "-previous"; let movedPrevious = false; From 57bcfe4a71ff49b4a6007241c3ed1f0e07f882a5 Mon Sep 17 00:00:00 2001 From: Carlos Villela Date: Sat, 29 Aug 2026 03:06:12 -0700 Subject: [PATCH 21/22] test(maintainer): prove trace lock heartbeat Signed-off-by: Carlos Villela --- .../pull-requests/analyze-pr-value-stream.test.ts | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/test/automation/pull-requests/analyze-pr-value-stream.test.ts b/test/automation/pull-requests/analyze-pr-value-stream.test.ts index e80909c41ae..623c090cac0 100644 --- a/test/automation/pull-requests/analyze-pr-value-stream.test.ts +++ b/test/automation/pull-requests/analyze-pr-value-stream.test.ts @@ -568,6 +568,7 @@ describe("pull request value-stream analysis", () => { const firstBlocked = new Promise((resolve) => { resumeFirst = resolve; }); + vi.useFakeTimers(); const firstPublication = publishStagedDirectory({ staging: first, destination, @@ -579,6 +580,11 @@ describe("pull request value-stream analysis", () => { }); await firstEnteredValidation; expect(await reclaimStalePublicationLock(lock, Date.now() + 6 * 60 * 1_000)).toBe(false); + const heartbeatBefore = (await stat(lock)).mtimeMs; + await vi.advanceTimersByTimeAsync(2 * 60 * 1_000); + vi.useRealTimers(); + await vi.waitUntil(async () => (await stat(lock)).mtimeMs > heartbeatBefore); + expect((await stat(lock)).mtimeMs).toBeGreaterThan(heartbeatBefore); resumeFirst(); await firstPublication; await publishStagedDirectory({ staging: second, destination, lock }); From e53b069de5e56c81bf2afc146be075c3c76f3eb3 Mon Sep 17 00:00:00 2001 From: Carlos Villela Date: Sat, 29 Aug 2026 03:15:31 -0700 Subject: [PATCH 22/22] fix(maintainer): share trace pull snapshot Signed-off-by: Carlos Villela --- .../scripts/analyze-pr-value-stream.mts | 13 +++++++++---- .../scripts/export-pr-lifetime-trace.mts | 5 ++++- .../pull-requests/analyze-pr-value-stream.test.ts | 2 +- 3 files changed, 14 insertions(+), 6 deletions(-) diff --git a/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/analyze-pr-value-stream.mts b/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/analyze-pr-value-stream.mts index 53f49d867ac..17a1177ff1b 100644 --- a/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/analyze-pr-value-stream.mts +++ b/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/analyze-pr-value-stream.mts @@ -340,7 +340,7 @@ async function readPullContext(input: AnalysisOptions): Promise { "--repo", input.repository, "--json", - "number,url,state,isDraft,createdAt,mergedAt,baseRefName,headRefName,headRefOid,commits,reviews", + "number,url,state,isDraft,createdAt,mergedAt,updatedAt,author,baseRefName,headRefName,headRefOid,commits,reviews", ], }); const pull = JSON.parse(result.stdout); @@ -1400,8 +1400,11 @@ function assembleValueStreamReport(context: ReportAssemblyContext): ValueStreamR }; } -async function collectValueStreamReport(input: AnalysisOptions): Promise { - const pullContext = await readPullContext(input); +async function collectValueStreamReport( + input: AnalysisOptions, + snapshot?: PullContext, +): Promise { + const pullContext = snapshot ?? (await readPullContext(input)); const runs = await readWorkflowRuns(input, pullContext.pull.headRefName); const timeline = selectRevisionTimeline({ pull: pullContext.pull, @@ -1493,12 +1496,14 @@ function parseArguments(argv: string[]): Input { async function main(): Promise { const input = parseArguments(process.argv.slice(2)); const normalized = normalizeAnalysisInput(input); - const report = await collectValueStreamReport(normalized); + const pullContext = await readPullContext(normalized); + const report = await collectValueStreamReport(normalized, pullContext); report.lifetime = await exportLifetimeTrace({ workdir: normalized.workdir, repository: normalized.repository, number: normalized.number, report, + pullSnapshot: pullContext.pull, githubRead: async (args) => runGithubCli({ workdir: normalized.workdir, args }), trackTemporaryPath: trackArtifactDirectory, releaseTemporaryPath: releaseTrackedPath, diff --git a/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts b/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts index a28bba0eb5f..474ecd6b843 100644 --- a/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts +++ b/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts @@ -127,6 +127,7 @@ type ExportInput = { repository: string; number: number; report: unknown; + pullSnapshot: unknown; githubRead: GithubRead; trackTemporaryPath?: (path: string, cleanup?: () => Promise) => void; releaseTemporaryPath?: (path: string) => void; @@ -946,7 +947,9 @@ export async function cleanupLifetimeStaging( } export async function exportLifetimeTrace(input: ExportInput): Promise { - const pull = await readPull(input); + const pull = input.pullSnapshot as any; + if (pull?.number !== input.number || typeof pull?.url !== "string") + throw new Error("shared pull request snapshot did not match the lifetime trace contract"); const expectedHead = (input.report as { headSha?: unknown }).headSha; if (typeof expectedHead !== "string" || pull.headRefOid !== expectedHead) throw new Error("pull request head changed during lifetime analysis"); diff --git a/test/automation/pull-requests/analyze-pr-value-stream.test.ts b/test/automation/pull-requests/analyze-pr-value-stream.test.ts index 623c090cac0..539f3959d6a 100644 --- a/test/automation/pull-requests/analyze-pr-value-stream.test.ts +++ b/test/automation/pull-requests/analyze-pr-value-stream.test.ts @@ -95,7 +95,7 @@ const responseCommits = [{oid:sha,authoredDate:"2026-01-01T00:00:00Z",committedD const pull = {number:42,url:"https://example.test/pr/42",state:scenario.startsWith("approval-") ? "MERGED" : "OPEN",isDraft:false,createdAt:"2026-01-01T00:01:00Z",updatedAt:"2026-01-01T00:04:00Z",mergedAt:scenario.startsWith("approval-") ? "2026-01-01T00:04:00Z" : null,author:{login:"author"},assignees:[],baseRefName:"main",headRefName:"topic",headRefOid:scenario === "feedback-response" ? laterSha : sha,commits:scenario === "feedback-response" ? responseCommits : [responseCommits[0]],reviews}; const run = (id) => ({id,event:"push",head_sha:sha,created_at:"2026-01-01T00:00:30Z",run_started_at:scenario === "queued" ? null : "2026-01-01T00:00:31Z",updated_at:"2026-01-01T00:03:00Z",status:scenario === "queued" ? "queued" : "completed",conclusion:scenario === "queued" ? null : "success",name:"CI PR #42"}); let value; -if (args.startsWith("pr view")) { const calls=fs.readFileSync(process.env.VALUE_STREAM_LOG,"utf8").match(/^pr view /gmu).length; value = (scenario === "head-race" && calls > 1) || (scenario === "final-head-race" && calls > 2) ? {...pull,headRefOid:"b".repeat(40)} : pull; } +if (args.startsWith("pr view")) { const calls=fs.readFileSync(process.env.VALUE_STREAM_LOG,"utf8").match(/^pr view /gmu).length; value = (scenario === "head-race" && calls > 1) || (scenario === "final-head-race" && calls > 1) ? {...pull,headRefOid:"b".repeat(40)} : pull; } else if (args.includes("required_status_checks")) value = scenario === "wrong-app" || scenario === "app-status-denied" ? {contexts:[],checks:[{context:"required-a",app_id:7}]} : scenario === "any-app" || scenario === "early-check" ? {contexts:[],checks:[{context:"required-a",app_id:-1}]} : scenario.startsWith("legacy-") ? {contexts:["legacy-required"],checks:[]} : {contexts:["required-a", "required-b"],checks:[]}; else if (args.includes("issues/42/timeline")) value = [{id:41,event:"assigned",created_at:"2026-01-01T00:01:05Z",actor:"author",commit_id:null,label:null,requested_reviewer:null,rename:null}]; else if (args.includes("issues/42/comments")) value = [{id:42,created_at:"2026-01-01T00:01:10Z",updated_at:"2026-01-01T00:01:10Z",user:"reviewer",html_url:""}];