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..8834586ae28 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. 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. -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..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 @@ -8,24 +8,27 @@ 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; +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 = { measuredAt: string; + lifetime?: LifetimeArtifacts; repository: string; number: number; url: string; @@ -163,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; @@ -181,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); }), @@ -192,8 +195,13 @@ async function handleCancellation(signal: (typeof cancellationSignals)[number]): process.kill(process.pid, signal); } -function trackArtifactDirectory(directory: string): void { - artifactDirectories.add(directory); +function releaseTrackedPath(path: string): void { + artifactDirectories.delete(path); + if (artifactDirectories.size === 0 && cancellationHandlersInstalled) removeCancellationHandlers(); +} + +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; @@ -283,11 +291,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, }; } @@ -332,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); @@ -1392,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, @@ -1459,17 +1470,7 @@ export async function analyzePrValueStream(input: Input): Promise(); for (let index = 0; index < argv.length; index += 2) { const key = argv[index]; @@ -1489,16 +1490,24 @@ 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"), }; } 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 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, + }); 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..474ecd6b843 --- /dev/null +++ b/.agents/skills/nemoclaw-maintainer-analyze-pr-value-stream/scripts/export-pr-lifetime-trace.mts @@ -0,0 +1,1067 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { randomUUID } from "node:crypto"; +import { + mkdir, + mkdtemp, + readFile, + readdir, + rename, + rm, + stat, + utimes, + writeFile, +} from "node:fs/promises"; +import path from "node:path"; + +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; +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; +const PUBLICATION_LOCK_STALE_MS = 5 * 60 * 1_000; + +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; + subject: string; +}; + +type Run = { + id: number; + event: string; + head_sha: string; + created_at: string; + 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; + pullSnapshot: unknown; + githubRead: GithubRead; + trackTemporaryPath?: (path: string, cleanup?: () => Promise) => void; + releaseTemporaryPath?: (path: string) => void; +}; + +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; +} + +type MetadataIndex = { processes: Set; threads: Set }; + +function addMetadata( + events: TraceEvent[], + index: MetadataIndex, + pid: number, + tid: number, + processName: string, + threadName: string, +): void { + if (!index.processes.has(pid)) { + index.processes.add(pid); + events.push({ name: "process_name", ph: "M", pid, tid: 0, args: { name: processName } }); + } + 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( + 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 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: validateObjectId(commit?.oid), + authoredAt: parseTime(commit?.authoredDate ?? commit?.committedDate, "commit authoredDate"), + 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,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, + 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,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), + ); + }); + 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: false }; +} + +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?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,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?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", + }); + 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[] = []; + 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; + 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 }, + }); + } + feedback.sort((left, right) => left.at - right.at); + 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, metadata, 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 }, + }); + } + } + } + const commitsByAuthoredAt = input.commits + .slice() + .sort((left, right) => left.authoredAt - right.authoredAt); + for (const [index, entry] of feedback.entries()) { + const nextCommit = commitsByAuthoredAt.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, + metadata, + 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, + metadata, + 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, + metadata, + 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, + metadata, + 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 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(), +): 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; + let owner: { pid?: unknown; startIdentity?: unknown } | null = null; + try { + owner = JSON.parse(await readFile(path.join(lock, "owner.json"), "utf8")); + } catch { + // An old lock can be left before owner metadata is written. + } + 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; + // 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 { + 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 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 requirePublicationLockOwnership(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, + 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, 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( + path.join(candidate, "owner.json"), + JSON.stringify({ + token, + pid: process.pid, + startIdentity, + createdAt: new Date().toISOString(), + }) + "\n", + { mode: 0o600 }, + ); + await rename(candidate, lock); + 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 }); + 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)); + } + } + throw new Error("timed out waiting for active lifetime artifact publication lock: " + lock); +} + +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)) + .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 requirePublicationLockOwnership(lock, token); + 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; 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 }))); +} + +export async function publishStagedDirectory(input: { + staging: string; + destination: string; + lock: string; + validate?: () => Promise; + track?: (path: string, cleanup?: () => Promise) => void; + release?: (path: string) => void; +}): Promise { + const token = await acquirePublicationLock(input.lock, input.track, input.release); + const heartbeat = setInterval(() => { + 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; + try { + await recoverInterruptedPublication(input.destination, input.lock, token); + await input.validate?.(); + await requirePublicationLockOwnership(input.lock, token); + try { + await rename(input.destination, backup); + movedPrevious = true; + } catch (error) { + 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 requirePublicationLockOwnership(input.lock, token); + await rm(backup, { recursive: true, force: true }); + } + } finally { + clearInterval(heartbeat); + if (await lockOwnershipMatches(input.lock, token)) + await rm(input.lock, { recursive: true, force: true }); + input.release?.(input.lock); + } +} + +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 = 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"); + const commits = normalizeCommits(pull); + const runsCollection = await readRuns(input, commits); + 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 parentDirectory = path.dirname(directory); + 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, + }; + const summary = + JSON.stringify({ ...(input.report as object), lifetime: artifacts }, 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"; + await mkdir(parentDirectory, { recursive: true, mode: 0o700 }); + const staging = await mkdtemp(path.join(parentDirectory, ".pr-" + input.number + "-staging-")); + input.trackTemporaryPath?.(staging); + const tracePath = path.join(staging, "trace.json"); + const summaryPath = path.join(staging, "summary.json"); + const manifestPath = path.join(staging, "manifest.json"); + try { + await Promise.all([ + writeFile(tracePath, trace, { mode: 0o600 }), + writeFile(summaryPath, summary, { mode: 0o600 }), + ]); + await validateChromeTrace(tracePath); + await writeFile(manifestPath, manifest, { mode: 0o600 }); + await publishStagedDirectory({ + staging, + destination: directory, + lock: directory + ".lock", + track: input.trackTemporaryPath, + release: input.releaseTemporaryPath, + validate: async () => { + const currentPull = await readPull(input); + if (currentPull.headRefOid !== pull.headRefOid) + throw new Error("pull request head changed during lifetime analysis"); + }, + }); + } catch (error) { + await cleanupLifetimeStaging(staging, error); + input.releaseTemporaryPath?.(staging); + throw error; + } + input.releaseTemporaryPath?.(staging); + return artifacts; +} 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..539f3959d6a 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,17 @@ // 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, + utimes, + writeFile, +} from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; @@ -9,6 +19,12 @@ 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 { + cleanupLifetimeStaging, + publishStagedDirectory, + reclaimStalePublicationLock, + validateChromeTrace, +} 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( @@ -74,11 +90,16 @@ 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 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")) value = 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:""}]; +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:[]}; @@ -86,7 +107,7 @@ else if (args.includes("/actions/runs/") && !args.includes("/jobs") && !args.inc else if (args.includes("/artifacts?") && scenario === "artifact-failure") { console.error("Authorization: secret-token"); process.exit(1); } else if (args.includes("/artifacts?")) value = {total_count:1,artifacts:[{id:31,name:"cli-blob-report-1",size_in_bytes:Number(process.env.VALUE_STREAM_ARTIFACT_SIZE),expired:false,workflow_run:{id:11,head_sha:sha},workflow_run_id:11,workflow_run_head_sha:sha}]}; else if (args.includes("/actions/artifacts/31/zip")) { if (scenario === "artifact-cancel") setInterval(() => {}, 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")); @@ -113,7 +134,7 @@ async function run(scenario: string, extra: string[] = []) { "--no-warnings", analyzer, "--workdir", - root, + fake.directory, "--number", "42", ...extra, @@ -131,7 +152,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 () => { @@ -163,7 +187,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"); @@ -171,11 +195,62 @@ 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(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("removes lifetime artifacts when the pull request head changes (#10542)", async () => { + const result = await run("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("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", ["--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", @@ -183,8 +258,25 @@ 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", ["--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({ @@ -200,8 +292,23 @@ 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", ["--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.", @@ -209,55 +316,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(); }); @@ -341,14 +440,250 @@ 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)), + ), + ), + ); + 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("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, "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(); + }); + + 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}`, ); - expect(report.waterfall).toMatchObject({ - runsAvailable: 2, - runsIncluded: 1, - runsTruncated: true, + 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); + const destination = path.join(publicationRoot, "pr-42"); + const staging = path.join(publicationRoot, "staging"); + const lock = destination + ".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"), + ]); + const publication = publishStagedDirectory({ + staging, + destination, + lock, + validate: async () => { + throw new Error("pull request head changed during lifetime analysis"); + }, + }); + 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("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"); + 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; + let firstOwnsLock!: () => void; + const firstEnteredValidation = new Promise((resolve) => { + firstOwnsLock = resolve; + }); + const firstBlocked = new Promise((resolve) => { + resumeFirst = resolve; + }); + vi.useFakeTimers(); + const firstPublication = publishStagedDirectory({ + staging: first, + destination, + lock, + validate: () => { + firstOwnsLock(); + return firstBlocked; + }, + }); + 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 }); + 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); + const lock = path.join(publicationRoot, "pr-42.lock"); + await mkdir(lock); + 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: 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(); + }); + + 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-")), + "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); + expect(result.stderr).toContain("unknown argument: --max-automation-runs"); + expect(result.ghCalls).toBe(""); }); });