diff --git a/.agents/skills/nemoclaw-maintainer-cut-release-tag/SKILL.md b/.agents/skills/nemoclaw-maintainer-cut-release-tag/SKILL.md index c0aa31e9d6e..693070913d4 100644 --- a/.agents/skills/nemoclaw-maintainer-cut-release-tag/SKILL.md +++ b/.agents/skills/nemoclaw-maintainer-cut-release-tag/SKILL.md @@ -15,8 +15,9 @@ push, version-bump, or other release-state GitHub writes. Treat these as separate states: -- **Tag can be cut:** all required documentation and image checks pass. - The release brief records the maintainer's general E2E decision and contains no unresolved prompts. +- **Tag can be cut:** the release entry and required image checks pass. + The maintainer chooses to proceed with the displayed documentation coverage and general E2E state. + The release brief records both decisions and contains no unresolved prompts. - **Tag cut:** the remote signed tag exists and peels to the planned candidate. - **Post-tag follow-through:** after reporting the tag as cut, continue the same task. Monitor `latest`, release labels, public documentation, and release images. Draft the Announcement and @@ -26,8 +27,10 @@ Treat these as separate states: - Use the exact requested version. Generate the plan with `--version vX.Y.Z`; never infer a bump. - Tag only the candidate captured in the plan. -- Require the release entry and exact-candidate approved-empty Pi documentation result. They cannot - be waived. +- Require the release entry. It cannot be waived. +- Treat documentation coverage as maintainer context, not a tag gate. Show the exact coverage point, + later commits and PRs, review and check state, changed paths, and open managed docs PRs. +- Record the maintainer's documentation decision in the signed release brief. - Require applicable GHCR base and managed-image publication evidence. - Treat E2E as maintainer context, not a tag gate. Show the newest full E2E result and let the maintainer run focused tests, run the full suite, or proceed with the displayed status. @@ -81,7 +84,7 @@ After later reads of remote state, keep this candidate when all of these remain - the candidate is still an ancestor of `origin/main`; - the previous release tag still peels to the commit recorded in the plan; -- the candidate's own documentation evidence remains valid; and +- the candidate's release entry remains valid; and - the candidate's own required evidence remains valid. New commits on `main` do not invalidate that plan. A managed documentation PR or branch for a later @@ -116,11 +119,15 @@ the helper after evidence has been added. ### 2. Verify Required Candidate Evidence Read and follow [Candidate Evidence](references/candidate-evidence.md). It owns the executable reads -for the release entry, approved-empty Pi result, candidate-specific managed documentation state, and -applicable base-image verifier. +for the release entry, documentation coverage, and applicable base-image verifier. -Do not offer the general E2E proceed option until every candidate-evidence check passes. Record the -returned paths, URLs, run identities, and image identities in the release brief. +Show the complete documentation coverage evidence. Offer the maintainer the three choices defined +there. If the maintainer requests documentation work or stops, do not continue to E2E or tag +confirmation. If the maintainer proceeds, record the exact decision line in the release brief. + +Do not offer the general E2E proceed option until the release entry and image checks pass and the +maintainer chooses to proceed with the displayed documentation coverage. Record the returned paths, +URLs, PR state, commit ranges, review state, check state, and image identities in the release brief. ### 3. Present General E2E and Ask for a Decision @@ -148,14 +155,16 @@ and no requested run remains unresolved. Otherwise, ask for and record one conci reason. The reason must say what differs or remains unresolved and why the maintainer is proceeding. Selecting “Proceed with the status as shown” is the decision, not the reason. Stop and ask the maintainer why before continuing when a reason is required. -This exception applies only to E2E. It never covers documentation or required image evidence. +This exception applies only to E2E. It never replaces the release entry, documentation coverage +decision, or required image evidence. ### 4. Finish and Review the Release Brief Replace every `TODO_RELEASE_BRIEF` prompt in that Markdown file with: - the complete canonical release entry and its repository path; -- Pi documentation workflow and job URLs, artifact name, and normalized approved-empty review; +- the latest included cumulative docs PR, coverage commit, later commits and PRs, changed-path + result, review and check state, open managed docs PRs, and maintainer decision; - exact-candidate E2E workflow, attempt, and successful `base-image-publication` job URL; - the newest full E2E result and every focused or full rerun result, including SHA, time, age, status, conclusion, and URLs; @@ -177,14 +186,11 @@ Ask the maintainer to paste the plan's exact phrase: CONFIRM RELEASE vX.Y.Z ``` -After receiving that exact phrase, run the self-contained -[Final Documentation Recheck](references/candidate-evidence.md#final-documentation-recheck). It -reads the candidate from the immutable plan again, so it does not depend on the Step 2 shell. Stop on -a failed read or pending state, consume that confirmation, and request a new one after readiness is -restored. Otherwise, run the cutter immediately; do not insert another wait between the reads and -the push. +After receiving that exact phrase, run the cutter immediately. The cutter reads the immutable plan, +validates the signed release brief's documentation decision, and checks remote tag state before the +push. -Then run: +Run: ```bash npm run release:cut -- \ @@ -238,12 +244,11 @@ Keep the semver tag immutable. ## Recovery -- Missing release entry or approved-empty Pi result: finish the candidate's documentation work and - obtain a successful exact-candidate run. Do not bypass it. -- Candidate-specific documentation PR or branch exists: when the patch is required, merge it and generate a - new plan for the resulting commit. When maintainers reject the patch, close the PR, remove its - branch with the required repository authorization, and rerun exact-candidate documentation before - requesting a new confirmation. +- Missing release entry: finish the candidate's documentation work and generate a new plan for the + resulting commit. Do not bypass the release entry. +- Documentation coverage shows a gap, failed checks, unapproved changes, unsupported paths, or an + open managed docs PR: show that state. Let the maintainer proceed, create or update a docs PR, or + stop. If documentation work changes the candidate, generate a new plan. - Required GHCR evidence fails: repair and rerun only the affected image work. Do not replace it with the general E2E proceed decision. - General E2E is old, incomplete, failed, or from another SHA: show it and offer focused, full, or diff --git a/.agents/skills/nemoclaw-maintainer-cut-release-tag/references/candidate-evidence.md b/.agents/skills/nemoclaw-maintainer-cut-release-tag/references/candidate-evidence.md index cdedd1f068e..0b2288443df 100644 --- a/.agents/skills/nemoclaw-maintainer-cut-release-tag/references/candidate-evidence.md +++ b/.agents/skills/nemoclaw-maintainer-cut-release-tag/references/candidate-evidence.md @@ -4,10 +4,8 @@ # Candidate Evidence Candidate evidence is the release-specific evidence required for the planned candidate. Use the -exact version and candidate from `plan.json`. These are read-only checks. Run every section except -[Final Documentation Recheck](#final-documentation-recheck) before the general E2E decision. Keep -the first shell only until its evidence is copied into the release brief. It does not need to remain -open while waiting for tag confirmation. +exact version and candidate from `plan.json`. These are read-only checks. Run every section before +the general E2E decision. Keep the shell only until its evidence is copied into the release brief. ```bash set -euo pipefail @@ -42,16 +40,17 @@ run_or_stop "release plan read" jq -er ' "previousTag", "previousTagCommit", "previousTagObject" ] and (.nextTag | test("^v(0|[1-9][0-9]*)[.](0|[1-9][0-9]*)[.](0|[1-9][0-9]*)$")) and - (.originMainCommit | test("^[0-9a-f]{40}$")) - then [.nextTag, .originMainCommit] | @tsv + (.originMainCommit | test("^[0-9a-f]{40}$")) and + (.previousTagCommit | test("^[0-9a-f]{40}$")) + then [.nextTag, .originMainCommit, .previousTagCommit] | @tsv else error("release plan is invalid") end ' "$PLAN_PATH" >"$PLAN_FIELDS" -IFS=$'\t' read -r VERSION CANDIDATE_SHA <"$PLAN_FIELDS" -DOCS_BRANCH="automation/post-merge-docs-${CANDIDATE_SHA:0:12}" +IFS=$'\t' read -r VERSION CANDIDATE_SHA PREVIOUS_TAG_SHA <"$PLAN_FIELDS" +DOCS_PREFIX='automation/post-merge-docs-' ``` -## Release Entry and Pi Result +## Release Entry and Documentation Coverage Find exactly one target heading at the candidate. Save only that H2 section, ending before the next H2, for the release brief. @@ -82,93 +81,182 @@ run_or_stop "release-entry detail validation" awk ' ' "$ENTRY_FILE" ``` -Read the newest exact-candidate `Docs / Post-Merge Catch-Up` run. Require its one publish job to pass: +Read documentation coverage from Git history and GitHub PR state. Do not require another +`Docs / Post-Merge Catch-Up` run after the cumulative docs PR merges. + +First, list every open managed docs PR. Preserve this JSON for the release brief. ```bash -DOCS_RUNS_FILE="$EVIDENCE_DIR/docs-runs.json" -run_or_stop "documentation run list" gh run list --repo NVIDIA/NemoClaw \ - --workflow post-merge-docs.yaml --event push --branch main --commit "$CANDIDATE_SHA" \ - --limit 100 --json databaseId,headSha,status,conclusion,url,createdAt >"$DOCS_RUNS_FILE" -DOCS_RUN_ID_FILE="$EVIDENCE_DIR/docs-run-id" -run_or_stop "documentation run selection" jq -er --arg sha "$CANDIDATE_SHA" \ - '[.[] | select(.headSha == $sha)] | sort_by(.createdAt) | last | .databaseId' \ - "$DOCS_RUNS_FILE" >"$DOCS_RUN_ID_FILE" -IFS= read -r DOCS_RUN_ID <"$DOCS_RUN_ID_FILE" -DOCS_RUN_FILE="$EVIDENCE_DIR/docs-run.json" -run_or_stop "documentation run read" gh run view "$DOCS_RUN_ID" --repo NVIDIA/NemoClaw \ - --json attempt,headSha,status,conclusion,url,jobs >"$DOCS_RUN_FILE" -run_or_stop "documentation run validation" jq -e --arg sha "$CANDIDATE_SHA" ' - .headSha == $sha and .status == "completed" and .conclusion == "success" and - ([.jobs[] | select(.name == "Publish documentation catch-up")] | length == 1) and - ([.jobs[] | select(.name == "Publish documentation catch-up")][0] | - .status == "completed" and .conclusion == "success") -' "$DOCS_RUN_FILE" >/dev/null -DOCS_RUN_FIELDS_FILE="$EVIDENCE_DIR/docs-run-fields.txt" -run_or_stop "documentation run field read" jq -er ' - [.attempt, .url, ([.jobs[] | select(.name == "Publish documentation catch-up")][0].url)] | - .[] -' "$DOCS_RUN_FILE" >"$DOCS_RUN_FIELDS_FILE" -{ - IFS= read -r DOCS_RUN_ATTEMPT - IFS= read -r DOCS_RUN_URL - IFS= read -r DOCS_PUBLISH_JOB_URL -} <"$DOCS_RUN_FIELDS_FILE" +OPEN_DOCS_PRS="$EVIDENCE_DIR/open-docs-prs.json" +run_or_stop "open documentation PR read" gh pr list --repo NVIDIA/NemoClaw --state open \ + --base main --limit 1000 \ + --json headRefName,headRefOid,headRepository,isDraft,number,title,url >"$OPEN_DOCS_PRS" +run_or_stop "open documentation PR selection" jq -c --arg prefix "$DOCS_PREFIX" ' + [.[] | select( + (.headRefName | startswith($prefix)) and + .headRepository.nameWithOwner == "NVIDIA/NemoClaw" + )] +' "$OPEN_DOCS_PRS" >"$EVIDENCE_DIR/open-managed-docs-prs.json" ``` -Download that run's reviewed patch. A successful publish job is release evidence only when the -review covers this candidate and the approved patch is empty. +Next, list merged PRs and select the newest managed docs PR whose merge commit is an ancestor of +`CANDIDATE_SHA`. Do not select a PR only by merge time. If no such PR exists, report that state and +use `PREVIOUS_TAG_SHA` as the conservative coverage point. ```bash -DOCS_ARTIFACT='post-merge-docs-approved' -DOCS_ARTIFACT_DIR="$EVIDENCE_DIR/docs-approved" -mkdir "$DOCS_ARTIFACT_DIR" -run_or_stop "documentation artifact download" gh run download "$DOCS_RUN_ID" \ - --repo NVIDIA/NemoClaw --name "$DOCS_ARTIFACT" --dir "$DOCS_ARTIFACT_DIR" -DOCS_PATCH="$DOCS_ARTIFACT_DIR/docs.patch" -DOCS_REVIEW="$DOCS_ARTIFACT_DIR/review.json" -[[ -f "$DOCS_PATCH" && -f "$DOCS_REVIEW" ]] || stop "The documentation artifact is incomplete" -[[ ! -s "$DOCS_PATCH" ]] || stop "The approved documentation patch is not empty" -EMPTY_PATCH_SHA256='e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855' -run_or_stop "documentation review validation" jq -e --arg sha "$CANDIDATE_SHA" \ - --arg digest "$EMPTY_PATCH_SHA256" ' - type == "object" and - (keys | sort) == ["mainSha", "outcome", "patchSha256", "repository", "version"] and - .version == 1 and .repository == "NVIDIA/NemoClaw" and .mainSha == $sha and - .patchSha256 == $digest and .outcome == "approved" -' "$DOCS_REVIEW" >/dev/null -DOCS_REVIEW_NORMALIZED="$EVIDENCE_DIR/docs-review-normalized.json" -run_or_stop "documentation review normalization" jq -cS . "$DOCS_REVIEW" >"$DOCS_REVIEW_NORMALIZED" -IFS= read -r DOCS_REVIEW_JSON <"$DOCS_REVIEW_NORMALIZED" +MERGED_DOCS_PRS="$EVIDENCE_DIR/merged-docs-prs.json" +run_or_stop "merged documentation PR read" gh pr list --repo NVIDIA/NemoClaw --state merged \ + --base main --limit 1000 \ + --json headRefName,headRefOid,headRepository,mergeCommit,mergedAt,number,reviewDecision,statusCheckRollup,title,url \ + >"$MERGED_DOCS_PRS" +run_or_stop "merged documentation PR selection" jq -c --arg prefix "$DOCS_PREFIX" ' + [.[] | select( + (.headRefName | startswith($prefix)) and + .headRepository.nameWithOwner == "NVIDIA/NemoClaw" and + (.mergeCommit.oid | test("^[0-9a-f]{40}$")) + )] | sort_by(.mergedAt) | reverse | .[] +' "$MERGED_DOCS_PRS" >"$EVIDENCE_DIR/managed-docs-pr-candidates.jsonl" ``` -Record these values in the release brief: +For each candidate PR in order, test its merge commit against `CANDIDATE_SHA`. Keep the first +ancestor. Stop on an ancestry-check error. Record the selected PR as JSON and assign every field +before a later command reads it. If there is no match, record `null`, assign `None` to the PR +fields, and use `PREVIOUS_TAG_SHA` as the conservative coverage point. -- `DOCS_RUN_ID`; -- `DOCS_RUN_ATTEMPT`; -- `DOCS_RUN_URL`; -- `DOCS_PUBLISH_JOB_URL`; -- the artifact name; and -- `DOCS_REVIEW_JSON`. +```bash +SELECTED_DOCS_PR="$EVIDENCE_DIR/selected-docs-pr.json" +: >"$SELECTED_DOCS_PR" +while IFS= read -r DOCS_PR_CANDIDATE; do + DOCS_PR_MERGE_SHA="$(printf '%s\n' "$DOCS_PR_CANDIDATE" | jq -er '.mergeCommit.oid')" + if git merge-base --is-ancestor "$DOCS_PR_MERGE_SHA" "$CANDIDATE_SHA"; then + printf '%s\n' "$DOCS_PR_CANDIDATE" >"$SELECTED_DOCS_PR" + break + else + ANCESTRY_STATUS=$? + [[ "$ANCESTRY_STATUS" == 1 ]] || stop \ + "documentation PR ancestry check failed with status $ANCESTRY_STATUS" + fi +done <"$EVIDENCE_DIR/managed-docs-pr-candidates.jsonl" + +DOCS_PR_FIELDS="$EVIDENCE_DIR/selected-docs-pr-fields.tsv" +if [[ -s "$SELECTED_DOCS_PR" ]]; then + run_or_stop "selected documentation PR read" jq -er ' + [ + (.number | tostring), + .url, + .mergeCommit.oid, + .headRefOid, + (.reviewDecision // "None") + ] | @tsv + ' "$SELECTED_DOCS_PR" >"$DOCS_PR_FIELDS" + IFS=$'\t' read -r DOCS_PR_NUMBER DOCS_PR_URL DOCS_PR_MERGE_SHA \ + DOCS_PR_HEAD_SHA DOCS_PR_REVIEW_DECISION <"$DOCS_PR_FIELDS" +else + printf 'null\n' >"$SELECTED_DOCS_PR" + DOCS_PR_NUMBER='None' + DOCS_PR_URL='None' + DOCS_PR_MERGE_SHA='None' + DOCS_PR_HEAD_SHA='None' + DOCS_PR_REVIEW_DECISION='None' + DOCS_COVERAGE_SHA="$PREVIOUS_TAG_SHA" + printf 'None\tNone\tNone\tNone\tNone\n' >"$DOCS_PR_FIELDS" +fi +``` -The signed tag annotation then retains the exact candidate and approved-empty patch digest after the -workflow artifact expires. +Only when a PR was selected, read all of its commits and files and derive its coverage point. +Otherwise, preserve empty API evidence and the previous-release coverage point without making a +selected-PR API request. -Require no managed PR or branch for this candidate. A PR or branch for a later candidate does not -invalidate this one. +```bash +DOCS_PR_COMMITS="$EVIDENCE_DIR/docs-pr-commits.json" +DOCS_PR_FILES="$EVIDENCE_DIR/docs-pr-files.json" +if [[ "$DOCS_PR_NUMBER" != 'None' ]]; then + run_or_stop "documentation PR commit read" gh api --paginate --slurp \ + "repos/NVIDIA/NemoClaw/pulls/${DOCS_PR_NUMBER}/commits?per_page=100" >"$DOCS_PR_COMMITS" + run_or_stop "documentation PR file read" gh api --paginate --slurp \ + "repos/NVIDIA/NemoClaw/pulls/${DOCS_PR_NUMBER}/files?per_page=100" >"$DOCS_PR_FILES" + run_or_stop "documentation PR final commit verification" jq -er \ + --arg expected "$DOCS_PR_HEAD_SHA" ' + [.[][]] as $commits | + if + ($commits | length) > 0 and + $commits[-1].sha == $expected + then $commits[-1].sha + else error("documentation PR final commit does not match headRefOid") + end + ' "$DOCS_PR_COMMITS" >"$EVIDENCE_DIR/docs-pr-final-sha" + run_or_stop "documentation PR check rollup read" jq -ce ' + if (.statusCheckRollup | type) == "array" + then .statusCheckRollup + else error("documentation PR check rollup is missing") + end + ' "$SELECTED_DOCS_PR" >"$EVIDENCE_DIR/docs-pr-checks.json" + run_or_stop "documentation coverage commit selection" jq -er \ + --arg message $'docs: catch up after main\n\nSigned-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>' ' + [.[][] | select( + .commit.message == $message and + .commit.author.email == "41898282+github-actions[bot]@users.noreply.github.com" and + .commit.verification.verified == true and + ((.parents | length) == 1 or (.parents | length) == 2) + )] | last | .parents[-1].sha + ' "$DOCS_PR_COMMITS" >"$EVIDENCE_DIR/docs-coverage-sha" + IFS= read -r DOCS_COVERAGE_SHA <"$EVIDENCE_DIR/docs-coverage-sha" + run_or_stop "documentation coverage ancestry" git merge-base --is-ancestor \ + "$DOCS_COVERAGE_SHA" "$CANDIDATE_SHA" + run_or_stop "documentation changed-path read" jq -r '.[].[] | .filename' \ + "$DOCS_PR_FILES" >"$EVIDENCE_DIR/docs-changed-paths.txt" +else + printf '[]\n' >"$DOCS_PR_COMMITS" + printf '[]\n' >"$DOCS_PR_FILES" + printf 'None\n' >"$EVIDENCE_DIR/docs-pr-final-sha" + printf '[]\n' >"$EVIDENCE_DIR/docs-pr-checks.json" + printf '%s\n' "$DOCS_COVERAGE_SHA" >"$EVIDENCE_DIR/docs-coverage-sha" + : >"$EVIDENCE_DIR/docs-changed-paths.txt" +fi +``` + +Confirm that every changed path is under `docs/**`, `fern/docs.yml`, or `fern/assets/**`. Report +the result instead of converting it into an automatic tag gate. The selected PR's final commit must +match its recorded `headRefOid`; show its review decision and every completed, failed, pending, or +skipped check. + +List all first-parent commits after the coverage point through the candidate: ```bash -DOCS_PRS_FILE="$EVIDENCE_DIR/docs-prs.json" -DOCS_BRANCH_FILE="$EVIDENCE_DIR/docs-branch.txt" -run_or_stop "candidate documentation PR read" gh pr list --repo NVIDIA/NemoClaw --state open \ - --head "$DOCS_BRANCH" --limit 100 --json number >"$DOCS_PRS_FILE" -run_or_stop "candidate documentation PR validation" jq -e 'length == 0' "$DOCS_PRS_FILE" >/dev/null -run_or_stop "candidate documentation branch read" git ls-remote --heads origin \ - "refs/heads/$DOCS_BRANCH" >"$DOCS_BRANCH_FILE" -[[ ! -s "$DOCS_BRANCH_FILE" ]] || stop "The candidate documentation branch still exists" +run_or_stop "documentation coverage gap read" git log --first-parent \ + --format='%H%x09%s' "${DOCS_COVERAGE_SHA}..${CANDIDATE_SHA}" \ + >"$EVIDENCE_DIR/docs-coverage-gap.tsv" +``` + +For each commit in that file, read `repos/NVIDIA/NemoClaw/commits//pulls` with the GitHub +`groot-preview` media type. Show the associated merged PR number, title, and URL. The docs PR merge +itself can appear in this range; identify any other merge as work after the final automated refresh. + +Record all of this evidence in the release brief: + +- target tag and candidate commit; +- latest included cumulative docs PR, its final PR commit, and its merge commit, or `None`; +- the final automated refresh coverage commit, or the previous release commit when none exists; +- every commit and merged PR after that coverage point through the candidate; +- whether the docs PR changed only allowed documentation paths; +- the docs PR review decision and complete check state; +- every open managed docs PR; and +- the canonical release entry and path. + +Then offer exactly these choices: + +1. Proceed with the candidate as shown. +2. Create or update a docs PR for the uncovered range. +3. Stop tagging. + +If the maintainer selects option 1, add this exact line to the signed release brief: + +```text +- Maintainer decision: Proceed with the candidate as shown. ``` -This is the initial pending-state check. Do not repeat it before showing the release brief. Run the -self-contained final recheck below only after the maintainer confirms the tag. +If the maintainer selects option 2 or 3, stop before the E2E decision and tag confirmation. +If documentation work changes the intended candidate, generate a new immutable release plan. ## Image Evidence @@ -391,63 +479,3 @@ boundary in `nemoclaw-maintainer-e2e`. This remains operational follow-up, not a If the base-image aggregate is missing or failed, repair or rerun the affected publisher workflow and verifier. The general E2E decision cannot replace required image evidence. - -## Final Documentation Recheck - -Run this block only after the maintainer supplies the exact confirmation phrase. It reads the -candidate from the immutable plan again and does not depend on the earlier evidence shell. If both -checks pass, call the cutter immediately without another wait. - -```bash -set -euo pipefail -PLAN_PATH='../nemoclaw-release-vX.Y.Z/plan.json' -FINAL_DOCS_DIR="$(mktemp -d)" -chmod 700 "$FINAL_DOCS_DIR" -trap 'rm -rf "$FINAL_DOCS_DIR"' EXIT - -run_or_stop() { - local label="$1" - local status - shift - if "$@"; then - return 0 - else - status=$? - printf '%s failed with status %s\n' "$label" "$status" >&2 - exit "$status" - fi -} - -stop() { - printf '%s\n' "$1" >&2 - exit 1 -} - -FINAL_CANDIDATE_FILE="$FINAL_DOCS_DIR/candidate.txt" -run_or_stop "final release plan read" jq -er ' - if - (keys | sort) == [ - "nextTag", "originMainCommit", "originMainHeadline", - "previousTag", "previousTagCommit", "previousTagObject" - ] and - (.originMainCommit | test("^[0-9a-f]{40}$")) - then .originMainCommit - else error("release plan is invalid") - end -' "$PLAN_PATH" >"$FINAL_CANDIDATE_FILE" -IFS= read -r CANDIDATE_SHA <"$FINAL_CANDIDATE_FILE" -DOCS_BRANCH="automation/post-merge-docs-${CANDIDATE_SHA:0:12}" - -FINAL_DOCS_PRS_FILE="$FINAL_DOCS_DIR/docs-prs.json" -FINAL_DOCS_BRANCH_FILE="$FINAL_DOCS_DIR/docs-branch.txt" -run_or_stop "final candidate documentation PR read" gh pr list --repo NVIDIA/NemoClaw --state open \ - --head "$DOCS_BRANCH" --limit 100 --json number >"$FINAL_DOCS_PRS_FILE" -run_or_stop "final candidate documentation PR validation" jq -e 'length == 0' \ - "$FINAL_DOCS_PRS_FILE" >/dev/null -run_or_stop "final candidate documentation branch read" git ls-remote --heads origin \ - "refs/heads/$DOCS_BRANCH" >"$FINAL_DOCS_BRANCH_FILE" -[[ ! -s "$FINAL_DOCS_BRANCH_FILE" ]] || stop "The candidate documentation branch still exists" -``` - -Treat the confirmation as consumed if a read fails or pending state appears. Resolve that state and -request a new confirmation. diff --git a/.agents/skills/nemoclaw-maintainer-day/scripts/handoff-summary.ts b/.agents/skills/nemoclaw-maintainer-day/scripts/handoff-summary.ts index c7dbafa9b86..ca5b465caa3 100644 --- a/.agents/skills/nemoclaw-maintainer-day/scripts/handoff-summary.ts +++ b/.agents/skills/nemoclaw-maintainer-day/scripts/handoff-summary.ts @@ -188,10 +188,16 @@ export function renderHandoffMarkdown(summary: HandoffOutput): string { "", INCOMPLETE, "", - "## Pi documentation evidence", + "## Documentation coverage", "", - `- Pi candidate: ${code(summary.candidateCommit)}`, - `- Evidence: ${INCOMPLETE} (workflow and job URLs, artifact name, normalized approved-empty review, and managed-branch checks)`, + `- Latest included cumulative docs PR: ${INCOMPLETE}`, + `- Final PR commit and merge commit: ${INCOMPLETE}`, + `- Final automated refresh coverage commit: ${INCOMPLETE}`, + `- Later commits and merged PRs: ${INCOMPLETE}`, + `- Changed paths: ${INCOMPLETE}`, + `- Review and checks: ${INCOMPLETE}`, + `- Open managed docs PRs: ${INCOMPLETE}`, + `- Maintainer decision: ${INCOMPLETE}`, "", "## Base and managed image evidence", "", diff --git a/.agents/skills/nemoclaw-maintainer-evening/SKILL.md b/.agents/skills/nemoclaw-maintainer-evening/SKILL.md index 4858dc077d0..a0b33b2583b 100644 --- a/.agents/skills/nemoclaw-maintainer-evening/SKILL.md +++ b/.agents/skills/nemoclaw-maintainer-evening/SKILL.md @@ -43,10 +43,9 @@ the release and one canonical dated entry headed `## vX.Y.Z`. Follow documentation writer review. Do not create a separate release-entry PR when the active cumulative docs PR can carry it. -Merge the documentation PR before selecting the tag candidate. Then wait for the resulting exact -commit's `Docs / Post-Merge Catch-Up` run. The `Publish documentation catch-up` job must succeed, -which records an independently approved empty Pi result for that commit. A release entry without -this result is not complete. +Merge the documentation PR before selecting the tag candidate. A docs-only merge does not start +another `Docs / Post-Merge Catch-Up` run. Preserve the merged PR, its final commit, its merge commit, +and the final automated refresh coverage commit for the tag session. If another product merge lands before candidate selection, decide whether it belongs in this release. When it does, update the cumulative documentation change first. When it does not, the tag @@ -63,7 +62,7 @@ Show: - merged work in `vX.Y.Z`; - open PRs and issues still carrying `vX.Y.Z`; - the canonical release entry; -- the exact Pi documentation run and job URL; +- the cumulative docs PR, coverage commit, later commits and PRs, review state, and check state; - known image-publication state; and - the newest full E2E status, SHA, age, and URLs. @@ -75,7 +74,7 @@ move to the next target, but do not perform label writes here. Load `nemoclaw-maintainer-cut-release-tag` and pass the exact version. That skill owns: - the exact-version plan and candidate; -- nonwaivable documentation and image evidence; +- the required release entry, documentation coverage decision, and image evidence; - the maintainer's focused, full, or proceed E2E choice; - `../nemoclaw-release-vX.Y.Z/release-brief.md`; - the exact confirmation phrase; and @@ -90,7 +89,7 @@ After tag readback, report: - tag and candidate commit; - plan and release-brief paths; -- documentation and image evidence URLs; +- documentation coverage, maintainer decision, and image evidence URLs; and - E2E decision and exception reason, if any. Then let `nemoclaw-maintainer-cut-release-tag` monitor the automatic post-tag workflows, draft the @@ -99,6 +98,6 @@ Announcement, and report `lkg` state. A post-tag failure does not change tag suc ## Hard Rules - Never cut a tag without the maintainer's exact confirmation phrase. -- Never bypass the release entry, approved-empty Pi result, or applicable GHCR evidence. +- Never bypass the release entry, documentation coverage decision, or applicable GHCR evidence. - Never make a different candidate stale merely because `main` advanced or a later documentation PR opened. - Never delay the tag-cut report for post-tag work. Continue the same task after that report. diff --git a/.agents/skills/nemoclaw-maintainer-policies/references/release-train.md b/.agents/skills/nemoclaw-maintainer-policies/references/release-train.md index e02da19c44f..3c9a8e18d68 100644 --- a/.agents/skills/nemoclaw-maintainer-policies/references/release-train.md +++ b/.agents/skills/nemoclaw-maintainer-policies/references/release-train.md @@ -24,9 +24,12 @@ Daily release labels coordinate release work. They do not classify issues and th ## Release-Prep Docs -Use one cumulative documentation PR for all merged changes selected for the release. Continue the -managed Pi PR when one exists. If no managed PR exists and only release documentation remains, use -one direct documentation-only PR. +Use one cumulative documentation PR for all merged changes selected for the release. Each push to +`main` refreshes the same managed PR with an independently reviewed cumulative patch. The PR title +names the next patch tag after the latest release tag. The PR body names both tags and defines the +development and release-cutoff procedure. The publisher creates a merge commit, fast-forwards the +branch, and never force-pushes. Continue that PR when one exists. +If no managed PR exists and only release documentation remains, use one direct documentation-only PR. That PR must include all required user documentation and one canonical `docs/changelog/YYYY-MM-DD.mdx` entry headed `## vX.Y.Z`. In the normal evening flow, merge it before @@ -34,15 +37,23 @@ generating the release plan so the entry is in the planned candidate. If direct skill has already produced a plan whose candidate lacks the entry or another required documentation change, merge the documentation PR and generate a new plan for the resulting candidate. -Require the exact candidate's `Docs / Post-Merge Catch-Up` run to finish with a successful -`Publish documentation catch-up` job. That success records an independently reviewed, approved -empty Pi patch for the candidate. If Pi finds a change, the workflow opens a managed PR and -publication does not succeed. +A push that changes only `docs/**`, `fern/docs.yml`, or `fern/assets/**` does not start +`Docs / Post-Merge Catch-Up`. Merging the cumulative docs PR therefore does not start a final model +run or create an empty-patch receipt. -For the candidate only, require no open managed PR and no remote branch named -`automation/post-merge-docs-`. A managed PR or branch for a later -commit does not invalidate an earlier candidate. The release entry and approved-empty Pi result -cannot be waived. +Before tag confirmation, show the maintainer: + +- the latest included cumulative docs PR, its final PR commit, and its merge commit; +- the final automated refresh coverage commit; +- every commit and merged PR after that coverage point through the candidate; +- whether the docs PR changed only allowed documentation paths; +- the docs PR review decision and complete check state; +- every open managed docs PR; and +- the canonical release entry and path. + +The maintainer must choose to proceed, create or update a docs PR for the uncovered range, or stop. +Record a proceed decision in the signed release brief. The release entry cannot be waived. Do not +create a separate documentation receipt or exception record. ## Cutoff @@ -56,9 +67,9 @@ At cutoff: 4. Complete [Release-Prep Docs](#release-prep-docs) for the intended release range. 5. Generate the immutable release plan with the exact `--version vX.Y.Z` to capture the candidate commit. -6. Verify the candidate's required documentation and image evidence. If - documentation is missing, complete [Release-Prep Docs](#release-prep-docs), merge that PR, - generate a new plan, and repeat the evidence checks for the new candidate. +6. Show the candidate's documentation coverage and required image evidence. If the maintainer + requests documentation work, complete [Release-Prep Docs](#release-prep-docs), merge that PR, + generate a new plan, and show the evidence for the new candidate. 7. Show the newest full E2E context and record the maintainer's focused, full, or proceed decision. 8. Build the Markdown release brief from the exact range and evidence. 9. Cut the release tag only with the plan's explicit maintainer confirmation. @@ -101,8 +112,8 @@ and no requested run remains unresolved. Otherwise, record one plain-language re different, missing, non-successful, or unresolved status and explains why the maintainer is proceeding. -This decision applies only to E2E. It cannot cover missing documentation or required image -evidence. Do not maintain a separate exception schema or ledger. +This decision applies only to E2E. It cannot replace the release entry, documentation coverage +decision, or required image evidence. Do not maintain a separate exception schema or ledger. ## Signed Release Brief @@ -111,7 +122,8 @@ Create `../nemoclaw-release-vX.Y.Z/release-brief.md` from the exact plan range. - exact range, commit and risky-file counts, risky areas, and suggested QA focus from the handoff helper; - the complete canonical release entry and its path; -- Pi documentation workflow and job URLs, artifact name, and normalized approved-empty review; +- the latest included cumulative docs PR, coverage commit, later commits and PRs, changed-path + result, review and check state, open managed docs PRs, and maintainer decision; - the base-image aggregate URL and identity; - the newest full E2E result and every requested run; - the maintainer's E2E decision; and diff --git a/.github/workflows/post-merge-docs.yaml b/.github/workflows/post-merge-docs.yaml index db165a569ca..1d812f8a482 100644 --- a/.github/workflows/post-merge-docs.yaml +++ b/.github/workflows/post-merge-docs.yaml @@ -6,6 +6,10 @@ name: Docs / Post-Merge Catch-Up on: push: branches: [main] + paths-ignore: + - "docs/**" + - "fern/docs.yml" + - "fern/assets/**" permissions: {} concurrency: @@ -13,26 +17,25 @@ concurrency: jobs: gate: - name: Check for an active documentation PR + name: Validate the managed documentation PR count runs-on: ubuntu-24.04 permissions: pull-requests: read - outputs: - pending: ${{ steps.scan.outputs.pending }} steps: - - id: scan - env: + - env: GH_TOKEN: ${{ github.token }} run: | set -euo pipefail - pending="$(gh api --paginate "repos/$GITHUB_REPOSITORY/pulls?state=open&base=main&per_page=100" | jq --slurp 'any(.[][]; (.head.ref | startswith("automation/post-merge-docs-")) and .head.repo.full_name == "NVIDIA/NemoClaw")')" - [[ "$pending" == true || "$pending" == false ]] - echo "pending=$pending" >> "$GITHUB_OUTPUT" + count="$( + gh api --paginate "repos/$GITHUB_REPOSITORY/pulls?state=open&base=main&per_page=100" | + jq --slurp '[.[][] | select((.head.ref | startswith("automation/post-merge-docs-")) and .head.repo.full_name == "NVIDIA/NemoClaw")] | length' + )" + [[ "$count" =~ ^[0-9]+$ && "$count" -le 1 ]] author: name: Author and review documentation catch-up needs: gate - if: ${{ github.repository == 'NVIDIA/NemoClaw' && needs.gate.outputs.pending != 'true' }} + if: ${{ github.repository == 'NVIDIA/NemoClaw' }} runs-on: ubuntu-24.04 timeout-minutes: 70 permissions: diff --git a/docs/CONTRIBUTING.md b/docs/CONTRIBUTING.md index 923f6f15e24..54848f4cb6a 100644 --- a/docs/CONTRIBUTING.md +++ b/docs/CONTRIBUTING.md @@ -7,7 +7,12 @@ This guide owns the public-facing documentation procedure and rules for NemoClaw. Code-changing pull requests (PRs) may defer public `docs/**`, `fern/docs.yml`, and `fern/assets/**` updates to `Docs / Post-Merge Catch-Up`. -Code merges continue while later merged changes remain pending for documentation catch-up. +The workflow maintains one cumulative draft documentation PR for merged changes after the latest release tag. +The PR title names the next patch tag after that release tag. +The PR body names both tags and explains the development and release-cutoff procedures. +Each later push to `main` refreshes the same PR with an independently reviewed cumulative patch. +The publisher fast-forwards the branch and stops if a person changes the branch or PR metadata. +The publisher never force-pushes. ## When to Update Docs @@ -86,7 +91,10 @@ Fern publishes Markdown routes for AI agents from the same source pages. The native Fern changelog under `docs/changelog/` is the release history. One source directory is shared across the OpenClaw, Hermes, and Deep Agents user-guide variants. The end-of-day flow merges the planned release entry. -The tag skill then requires the `Publish documentation catch-up` job to succeed for an independently approved empty patch at the exact `origin/main` commit, with no open managed documentation PR or branch for that candidate. +A docs-only merge does not start another catch-up run. The tag skill shows the latest cumulative +docs PR, its automated coverage point, later commits and PRs, review and check state, changed paths, +and open managed docs PRs. The maintainer then decides whether to proceed, request another docs PR, +or stop tagging. For each release: diff --git a/docs/resources/engineer-agentic-documentation.mdx b/docs/resources/engineer-agentic-documentation.mdx index 16d2efaea0d..ca86a90dfdc 100644 --- a/docs/resources/engineer-agentic-documentation.mdx +++ b/docs/resources/engineer-agentic-documentation.mdx @@ -41,14 +41,23 @@ A polished site with weak retrieval or verification is not agent-ready. ## Move Documentation Into the Engineering Loop -Each push to `main` starts `Docs / Post-Merge Catch-Up` for the merged implementation, tests, and documentation from the latest reachable semver tag through the pushed commit. +A push to `main` that changes a path outside the allowed documentation paths starts `Docs / Post-Merge Catch-Up`. The workflow examines the implementation, tests, and documentation from the latest reachable semver tag through the pushed commit. 1. It authors documentation changes in a credential-free OpenShell sandbox. 2. A separate offline sandbox reviews the exact documentation candidate with a read-only repository checkout. -3. For an approved nonempty patch, a publisher with no model credential creates a GitHub-verified commit and one SHA-specific draft PR. - -Each nonempty documentation PR merge triggers another cumulative exact-SHA run until a later run approves an empty patch, which creates no PR. -Code merges continue while their documentation changes remain pending. +3. For an approved nonempty patch, a publisher with no model credential creates or refreshes one cumulative draft PR with a GitHub-verified commit. + +The first nonempty patch creates the managed PR. +Its title names the next patch tag after the range-start tag. +Its body names both tags and explains how the PR changes during development and closes at release cutoff. +Later pushes to `main` refresh that same PR with a cumulative patch based on the triggering commit. +Each refresh creates a merge commit whose tree exactly matches the reviewed patch applied to `main`, then fast-forwards the branch. The publisher never force-pushes or replaces a branch head that a person changed. +Merge the cumulative PR at the release cutoff. +A push that changes only the allowed documentation paths does not start another catch-up run. +The tag session shows the PR's automated coverage point, later commits and PRs, changed paths, +review and check state, and open managed docs PRs. +The maintainer decides whether to proceed, request another docs PR, or stop tagging. +The signed release brief records a proceed decision. Required PR checks run `npm run docs` after any required approval. ## Use a Layered Architecture diff --git a/scripts/release-cut-tag.sh b/scripts/release-cut-tag.sh index f92b8ce95d3..8aac72f3ab5 100755 --- a/scripts/release-cut-tag.sh +++ b/scripts/release-cut-tag.sh @@ -132,9 +132,9 @@ require_brief_line_once() { [[ "$count" == "1" ]] || fail "Release brief must contain exactly one $label" } -printf -v expected_pi_candidate -- "- Pi candidate: \`%s\`" "$target" +expected_docs_decision="- Maintainer decision: Proceed with the candidate as shown." printf -v expected_base_candidate -- "- Base-image candidate: \`%s\`" "$target" -require_brief_line_once "$expected_pi_candidate" "plan-bound Pi candidate" +require_brief_line_once "$expected_docs_decision" "documentation proceed decision" require_brief_line_once "$expected_base_candidate" "plan-bound base-image candidate" if grep -Eq -- "TODO_RELEASE_BRIEF|Complete before confirmation" "$brief_snapshot"; then fail "Release brief still contains unresolved prompts" diff --git a/test/changelog-docs.test.ts b/test/changelog-docs.test.ts index a83ff4e72c5..0b0a03f198b 100644 --- a/test/changelog-docs.test.ts +++ b/test/changelog-docs.test.ts @@ -165,12 +165,13 @@ describe("Fern changelog documentation", () => { expect(source.match(/^```bash$/gm)?.length ?? 0, "v0.0.34 must retain its examples").toBe(3); }); - it("requires the approved empty-patch publisher result before release", () => { + it("records a maintainer decision from displayed documentation coverage", () => { const guide = fs.readFileSync(path.join(docsDir, "CONTRIBUTING.md"), "utf8"); expect(guide).toContain( - "The tag skill then requires the `Publish documentation catch-up` job to succeed for an independently approved empty patch at the exact `origin/main` commit", + "The maintainer then decides whether to proceed, request another docs PR,", ); + expect(guide).not.toContain("independently approved empty patch"); }); it("sorts complete semantic versions newest first", () => { diff --git a/test/handoff-summary.test.ts b/test/handoff-summary.test.ts index 6953892b39c..52807f36adf 100644 --- a/test/handoff-summary.test.ts +++ b/test/handoff-summary.test.ts @@ -100,6 +100,8 @@ describe("release handoff summary", () => { const markdown = renderHandoffMarkdown(summary); expect(markdown).toContain(`- Candidate: \`${candidate}\``); expect(markdown).toContain("- Risky files detected: 5"); + expect(markdown).toContain("## Documentation coverage"); + expect(markdown).toContain("- Maintainer decision: TODO_RELEASE_BRIEF"); expectMarkdownList(markdown, summary.riskyAreas); expectMarkdownList(markdown, summary.suggestedTestFocus); }); diff --git a/test/post-merge-docs.test.ts b/test/post-merge-docs.test.ts index b17e7871489..75856c0c95f 100644 --- a/test/post-merge-docs.test.ts +++ b/test/post-merge-docs.test.ts @@ -9,7 +9,10 @@ import path from "node:path"; import { afterEach, describe, expect, it, vi } from "vitest"; import YAML from "yaml"; -import { validatePostMergeDocsWorkflowBoundary } from "../tools/post-merge-docs/contract.mts"; +import { + nextPatchReleaseTag, + validatePostMergeDocsWorkflowBoundary, +} from "../tools/post-merge-docs/contract.mts"; import { publishDocumentation, type Request } from "../tools/post-merge-docs/publish.mts"; import { configurePostMergeDocs, executePostMergeDocs } from "../tools/post-merge-docs/run.mts"; import type { OpenShellTools } from "../tools/openshell-agent/runtime.mts"; @@ -18,6 +21,51 @@ const directories: string[] = []; const repository = "NVIDIA/NemoClaw"; const signOff = "Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>"; +const rangeStartTag = "v1.0.0"; +const targetReleaseTag = "v1.0.1"; +const managedTitle = "docs: prepare v1.0.1 documentation"; +const managedBody = `## Release target + +This cumulative draft prepares documentation for \`v1.0.1\`. +It covers merged changes after \`v1.0.0\` through the latest PR commit. +The workflow selects \`v1.0.1\` by incrementing the patch component of \`v1.0.0\`. + +## During development + +- Each push to \`main\` that changes a path outside the allowed documentation paths starts a cumulative authoring and independent review run. +- An approved patch creates a verified merge commit and fast-forwards this branch. +- The workflow never force-pushes. It stops if a person changes the branch or PR metadata. +- Keep this PR open as a draft while code PRs merge for \`v1.0.1\`. + +## Release cutoff + +1. Stop merging code PRs intended for \`v1.0.1\`. +2. Add the dated \`## v1.0.1\` changelog entry and final documentation to this PR. +3. Run \`npm run docs\` and complete the final review. +4. Merge this PR. Its docs-only merge does not start another catch-up run. +5. Ask the tag session to show this PR's coverage point, later commits and PRs, checks, reviews, and any open managed docs PR. +6. Decide whether to proceed, create or update a docs PR for the uncovered range, or stop. +7. Cut \`v1.0.1\` only after you choose to proceed with the displayed documentation coverage. + +## Verification + +- An independent documentation writer approved each exact cumulative patch. +- A maintainer must inspect and approve any approval-required workflow runs. + +${signOff}`; +function legacyManagedBody(mainSha: string): string { + return `## Summary + +Updates documentation for merged changes through \`${mainSha}\`. + +## Verification + +- An independent documentation writer approved the exact patch. +- Required PR checks must run \`npm run docs\` before merge. +- A maintainer must inspect and approve any approval-required workflow runs. + +${signOff}`; +} function temporary(prefix: string): string { const directory = fs.mkdtempSync(path.join(os.tmpdir(), `${prefix}-`)); directories.push(directory); @@ -66,55 +114,87 @@ function artifact(value: Fixture): string { fs.writeFileSync( path.join(directory, "review.json"), JSON.stringify({ - version: 1, - repository, mainSha: value.mainSha, - patchSha256: createHash("sha256").update(value.patch).digest("hex"), outcome: "approved", + patchSha256: createHash("sha256").update(value.patch).digest("hex"), + rangeStartTag, + repository, + targetReleaseTag, + version: 2, }), ); return directory; } class FakeGitHub { - branchRef: { object: { sha: string } } | null = null; - commitBody: Record | null = null; + branchRef: { object: { sha: string }; ref?: string } | null = null; + commitBodies: Record[] = []; liveSha: string; openPulls: Array> = []; readonly branch: string; readonly commitSha = "c".repeat(40); + readonly existingSha = "b".repeat(40); + readonly initialParent = "a".repeat(40); + readonly commits = new Map>(); afterWrite = (): void => undefined; constructor(readonly value: Fixture) { this.branch = `automation/post-merge-docs-${value.mainSha.slice(0, 12)}`; this.liveSha = value.mainSha; } - pull(body = "existing") { + pull( + body = managedBody, + headSha = this.branchRef?.object.sha ?? this.commitSha, + title = managedTitle, + ) { return { body, base: { ref: "main", repo: { full_name: repository } }, draft: true, - head: { ref: this.branch, repo: { full_name: repository }, sha: this.commitSha }, + head: { ref: this.branch, repo: { full_name: repository }, sha: headSha }, html_url: `https://github.com/${repository}/pull/42`, number: 42, state: "open", + title, }; } + installActive( + tree = "e".repeat(40), + authorEmail = "41898282+github-actions[bot]@users.noreply.github.com", + legacy = false, + ) { + this.branchRef = { + object: { sha: this.existingSha }, + ref: `refs/heads/${this.branch}`, + }; + this.commits.set(this.existingSha, { + author: { email: authorEmail }, + message: `docs: catch up after main\n\n${signOff}`, + parents: [{ sha: this.initialParent }], + sha: this.existingSha, + tree: { sha: tree }, + verification: { verified: true }, + }); + this.openPulls = [ + legacy + ? this.pull( + legacyManagedBody(this.initialParent), + this.existingSha, + "docs: catch up after merged changes", + ) + : this.pull(managedBody, this.existingSha, managedTitle), + ]; + } readonly request = vi.fn(async (method, url, body) => { const key = `${method} ${url}`; switch (key) { + case `GET /repos/${repository}/git/commits/${this.existingSha}`: + case `GET /repos/${repository}/git/commits/${this.commitSha}`: + return this.commits.get(url.slice(url.lastIndexOf("/") + 1)); case `GET /repos/${repository}/git/ref/heads/main`: return { object: { sha: this.liveSha } }; case `GET /repos/${repository}/pulls?state=open&base=main&per_page=100&page=1`: return this.openPulls; case `GET /repos/${repository}/git/ref/heads/${this.branch}`: return this.branchRef; - case `GET /repos/${repository}/git/commits/${this.commitSha}`: - return { - message: `docs: catch up after main\n\n${signOff}`, - parents: [{ sha: this.value.mainSha }], - sha: this.commitSha, - tree: { sha: this.value.finalTree }, - verification: { verified: true }, - }; case `POST /repos/${repository}/git/blobs`: { const content = Buffer.from((body as { content: string }).content, "base64"); return { @@ -126,17 +206,49 @@ class FakeGitHub { } case `POST /repos/${repository}/git/trees`: return { sha: this.value.finalTree }; - case `POST /repos/${repository}/git/commits`: - this.commitBody = body as Record; + case `POST /repos/${repository}/git/commits`: { + const commitBody = body as Record; + this.commitBodies.push(commitBody); + this.commits.set(this.commitSha, { + author: { email: "41898282+github-actions[bot]@users.noreply.github.com" }, + message: commitBody.message, + parents: (commitBody.parents as string[]).map((sha) => ({ sha })), + sha: this.commitSha, + tree: { sha: this.value.finalTree }, + verification: { verified: true }, + }); return { sha: this.commitSha, verification: { verified: true } }; + } case `POST /repos/${repository}/git/refs`: { const ref = { object: { sha: this.commitSha }, ref: `refs/heads/${this.branch}` }; this.branchRef = ref; this.afterWrite(); return ref; } + case `PATCH /repos/${repository}/git/refs/heads/${this.branch}`: { + expect(body).toEqual({ force: false, sha: this.commitSha }); + const ref = { object: { sha: this.commitSha }, ref: `refs/heads/${this.branch}` }; + this.branchRef = ref; + this.openPulls = this.openPulls.map((pull) => ({ + ...pull, + head: { ...pull.head, sha: this.commitSha }, + })); + this.afterWrite(); + return ref; + } + case `PATCH /repos/${repository}/pulls/42`: { + const metadata = body as { body: string; title: string }; + this.openPulls = this.openPulls.map((pull) => ({ + ...pull, + body: metadata.body, + title: metadata.title, + })); + this.afterWrite(); + return this.openPulls[0]; + } case `POST /repos/${repository}/pulls`: { - const pull = this.pull((body as { body: string }).body); + const metadata = body as { body: string; title: string }; + const pull = this.pull(metadata.body, undefined, metadata.title); this.openPulls = [pull]; this.afterWrite(); return pull; @@ -155,18 +267,22 @@ function publish(value: Fixture, api: FakeGitHub, approved = artifact(value)) { sourceRepository: value.source, }); } -function postCount(api: FakeGitHub, suffix?: string): number { +function requestCount(api: FakeGitHub, method: string, suffix?: string): number { return api.request.mock.calls.filter( - ([method, url]) => method === "POST" && (!suffix || url.endsWith(suffix)), + ([calledMethod, url]) => calledMethod === method && (!suffix || url.endsWith(suffix)), ).length; } +function writeCount(api: FakeGitHub): number { + return api.request.mock.calls.filter(([method]) => method === "PATCH" || method === "POST") + .length; +} const credentials = "GH_TOKEN GITHUB_TOKEN NVIDIA_API_KEY OPENAI_API_KEY POST_MERGE_DOCS_API_KEY PR_REVIEW_ADVISOR_API_KEY".split( " ", ); type RunnerStage = "create" | "agent" | "export" | "download"; -function runnerFixture(phase: "author" | "review") { +function runnerFixture(phase: "author" | "review", startTag = rangeStartTag) { const { mainSha, source } = sourceFixture(); fs.writeFileSync(path.join(source, "docs/guide.mdx"), "later\n"); git(source, ["commit", "-am", "docs: advance source"]); @@ -190,7 +306,7 @@ function runnerFixture(phase: "author" | "review") { POST_MERGE_DOCS_PHASE: phase, POST_MERGE_DOCS_WORKDIR: path.join(root, "work"), RANGE_START_SHA: mainSha, - RANGE_START_TAG: "v1.0.0", + RANGE_START_TAG: startTag, RUNNER_TEMP: path.join(root, "runner-temp"), SANDBOX_NAME: `docs-${phase}`, TRUSTED_CHECKOUT: source, @@ -265,20 +381,39 @@ afterEach(() => { }); describe("post-merge documentation publisher", () => { - it("creates one immutable branch and draft PR", async () => { + it.each(["v01.2.3", "v1.02.3", "v1.2.003"])("rejects non-canonical release tag %s", (tag) => { + expect(() => nextPatchReleaseTag(tag)).toThrow("cannot produce a release target"); + }); + it("creates one verified branch and cumulative draft PR", async () => { const value = fixture(); const api = new FakeGitHub(value); await expect(publish(value, api)).rejects.toThrow("Documentation remains pending"); - expect(api.commitBody?.message).toEqual(expect.stringContaining(signOff)); - expect(api.commitBody).toMatchObject({ parents: [value.mainSha], tree: value.finalTree }); + expect(api.commitBodies[0]?.message).toEqual(expect.stringContaining(signOff)); + expect(api.commitBodies[0]).toMatchObject({ + parents: [value.mainSha], + tree: value.finalTree, + }); expect(api.branchRef?.object.sha).toBe(api.commitSha); - expect(api.openPulls[0]?.body).toMatch(/`npm run docs`[\s\S]*approval-required/u); + expect(api.openPulls[0]?.title).toBe(managedTitle); + expect(api.openPulls[0]?.body).toContain( + "Its docs-only merge does not start another catch-up run.", + ); + expect(api.openPulls[0]?.body).toMatch( + /`v1[.]0[.]0`[\s\S]*never force-pushes[\s\S]*`npm run docs`[\s\S]*`v1[.]0[.]1`/u, + ); }); - it("creates no writes for an approved empty patch", async () => { + it("creates no writes for an approved empty patch without an active PR", async () => { const value = emptyFixture(); const api = new FakeGitHub(value); await publish(value, api); - expect(postCount(api)).toBe(0); + expect(writeCount(api)).toBe(0); + }); + it("keeps an active PR pending when the approved patch is empty", async () => { + const value = emptyFixture(); + const api = new FakeGitHub(value); + api.installActive(); + await expect(publish(value, api)).rejects.toThrow("Documentation remains pending"); + expect(writeCount(api)).toBe(0); }); it("rejects a patch whose digest was not approved", async () => { const value = emptyFixture(); @@ -288,13 +423,24 @@ describe("post-merge documentation publisher", () => { await expect(publish(value, api, approved)).rejects.toThrow("does not approve the exact patch"); expect(api.request).not.toHaveBeenCalled(); }); + it("rejects a release target that is not the next patch", async () => { + const value = emptyFixture(); + const approved = artifact(value); + const reviewFile = path.join(approved, "review.json"); + const review = JSON.parse(fs.readFileSync(reviewFile, "utf8")); + review.targetReleaseTag = "v1.0.2"; + fs.writeFileSync(reviewFile, JSON.stringify(review)); + const api = new FakeGitHub(value); + await expect(publish(value, api, approved)).rejects.toThrow("release target"); + expect(api.request).not.toHaveBeenCalled(); + }); it.each(["src/bad.ts", "fern/package.json", "fern/.npmrc", "fern/components/CustomFooter.tsx"])( "rejects an approved patch at unsupported path %s", async (file) => { const value = fixture(file); const api = new FakeGitHub(value); await expect(publish(value, api)).rejects.toThrow("patch changes unsupported path"); - expect(postCount(api)).toBe(0); + expect(writeCount(api)).toBe(0); }, ); it("stops when main moved after review", async () => { @@ -303,26 +449,90 @@ describe("post-merge documentation publisher", () => { api.liveSha = "d".repeat(40); await expect(publish(value, api)).rejects.toThrow("main changed after documentation review"); }); - it.each([1, 2])( - "fails when %i managed documentation PRs open during publication", - async (count) => { - const value = fixture(); - const api = new FakeGitHub(value); - api.openPulls = [ - api.pull(), - { ...api.pull(), html_url: `https://github.com/${repository}/pull/43`, number: 43 }, - ].slice(0, count); - await expect(publish(value, api)).rejects.toThrow(/managed documentation PR/u); - expect(postCount(api)).toBe(0); - }, - ); - it("rejects an existing immutable branch with unexpected content", async () => { + it("fails when multiple managed documentation PRs are open", async () => { + const value = fixture(); + const api = new FakeGitHub(value); + api.installActive(); + api.openPulls.push({ + ...api.pull(), + html_url: `https://github.com/${repository}/pull/43`, + number: 43, + }); + await expect(publish(value, api)).rejects.toThrow("multiple managed documentation PRs"); + expect(writeCount(api)).toBe(0); + }); + it("refreshes the active PR with a verified fast-forward merge commit", async () => { + const value = fixture(); + const api = new FakeGitHub(value); + api.installActive(); + await expect(publish(value, api)).rejects.toThrow("Documentation remains pending"); + expect(api.commitBodies[0]).toMatchObject({ + parents: [api.existingSha, value.mainSha], + tree: value.finalTree, + }); + expect(api.branchRef?.object.sha).toBe(api.commitSha); + expect(api.openPulls[0]?.head.sha).toBe(api.commitSha); + expect(api.openPulls[0]?.body).toBe(managedBody); + expect(api.openPulls[0]?.title).toBe(managedTitle); + expect(requestCount(api, "PATCH", `/git/refs/heads/${api.branch}`)).toBe(1); + expect(requestCount(api, "POST", "/pulls")).toBe(0); + }); + it("updates exact legacy metadata for the active managed PR", async () => { const value = fixture(); const api = new FakeGitHub(value); - api.branchRef = { object: { sha: api.commitSha } }; - value.finalTree = "d".repeat(40); - await expect(publish(value, api)).rejects.toThrow("unexpected content"); - expect(postCount(api)).toBe(0); + api.installActive("e".repeat(40), undefined, true); + await expect(publish(value, api)).rejects.toThrow("Documentation remains pending"); + expect(api.openPulls[0]?.title).toBe(managedTitle); + expect(api.openPulls[0]?.body).toBe(managedBody); + expect(requestCount(api, "PATCH", "/pulls/42")).toBe(1); + }); + it("reconciles a lost legacy metadata update without retrying", async () => { + const value = fixture(); + const api = new FakeGitHub(value); + api.installActive("e".repeat(40), undefined, true); + api.afterWrite = () => { + throw new Error("lost response"); + }; + await expect(publish(value, api)).rejects.toThrow("Documentation remains pending"); + expect(api.openPulls[0]?.title).toBe(managedTitle); + expect(requestCount(api, "PATCH", "/pulls/42")).toBe(1); + }); + it("rejects changed metadata on the active managed PR", async () => { + const value = fixture(); + const api = new FakeGitHub(value); + api.installActive(); + api.openPulls[0]!.title = "maintainer title"; + await expect(publish(value, api)).rejects.toThrow("metadata does not match"); + expect(writeCount(api)).toBe(0); + }); + it("does not add a redundant refresh when the active tree already matches", async () => { + const value = fixture(); + const api = new FakeGitHub(value); + api.installActive(value.finalTree); + await expect(publish(value, api)).rejects.toThrow("Documentation remains pending"); + expect(writeCount(api)).toBe(0); + }); + it("rejects a human commit at the active branch head", async () => { + const value = fixture(); + const api = new FakeGitHub(value); + api.installActive("e".repeat(40), "maintainer@example.com"); + await expect(publish(value, api)).rejects.toThrow("not created by the workflow"); + expect(writeCount(api)).toBe(0); + }); + it("rejects an active PR whose branch ref moved", async () => { + const value = fixture(); + const api = new FakeGitHub(value); + api.installActive(); + api.branchRef = { object: { sha: "d".repeat(40) } }; + await expect(publish(value, api)).rejects.toThrow("point to different commits"); + expect(writeCount(api)).toBe(0); + }); + it("rejects an unmanaged branch for the current main commit", async () => { + const value = fixture(); + const api = new FakeGitHub(value); + api.branchRef = { object: { sha: api.existingSha } }; + await expect(publish(value, api)).rejects.toThrow("unmanaged documentation branch"); + expect(writeCount(api)).toBe(0); }); it("reconciles exact lost branch and PR responses without retrying", async () => { const value = fixture(); @@ -331,8 +541,18 @@ describe("post-merge documentation publisher", () => { throw new Error("lost response"); }; await expect(publish(value, api)).rejects.toThrow("Documentation remains pending"); - expect(postCount(api, "/pulls")).toBe(1); - expect(postCount(api, "/git/refs")).toBe(1); + expect(requestCount(api, "POST", "/pulls")).toBe(1); + expect(requestCount(api, "POST", "/git/refs")).toBe(1); + }); + it("reconciles a lost fast-forward response without retrying", async () => { + const value = fixture(); + const api = new FakeGitHub(value); + api.installActive(); + api.afterWrite = () => { + throw new Error("lost response"); + }; + await expect(publish(value, api)).rejects.toThrow("Documentation remains pending"); + expect(requestCount(api, "PATCH", `/git/refs/heads/${api.branch}`)).toBe(1); }); }); @@ -408,10 +628,29 @@ describe("post-merge documentation runner", () => { mainSha: input.env.GITHUB_SHA, outcome: "approved", patchSha256: createHash("sha256").update("").digest("hex"), + rangeStartTag, repository, - version: 1, + targetReleaseTag, + version: 2, }); }); + it("produces and accepts an exact release target above the safe-integer range", async () => { + const input = runnerFixture("review", "v9007199254740992.0.0"); + const { tools } = runnerTools(input); + executePostMergeDocs(input.env, tools); + const approved = path.join(input.root, "artifact"); + const review = JSON.parse(fs.readFileSync(path.join(approved, "review.json"), "utf8")); + expect(review.targetReleaseTag).toBe("v9007199254740992.0.1"); + const value: Fixture = { + finalTree: git(input.env.TRUSTED_CHECKOUT, ["rev-parse", `${input.env.GITHUB_SHA}^{tree}`]), + mainSha: input.env.GITHUB_SHA, + patch: Buffer.alloc(0), + source: input.env.TRUSTED_CHECKOUT, + }; + const api = new FakeGitHub(value); + await publish(value, api, approved); + expect(writeCount(api)).toBe(0); + }); it("rejects an independent review denial and deletes the sandbox", () => { const input = runnerFixture("review"); const { state, tools } = runnerTools(input, undefined, "rejected"); @@ -444,6 +683,9 @@ describe("post-merge documentation workflow boundary", () => { it.each<(candidate: Record) => void>([ (candidate) => (candidate.jobs.author.permissions = { contents: "write" }), + (candidate) => + (candidate.jobs.author.if = + "${{ github.repository == 'NVIDIA/NemoClaw' && needs.gate.outputs.pending != 'true' }}"), (candidate) => (candidate.jobs.publish.permissions.issues = "write"), (candidate) => (candidate.jobs.gate.secrets = "inherit"), (candidate) => @@ -454,6 +696,7 @@ describe("post-merge documentation workflow boundary", () => { (candidate.jobs.publish.env = { OPENAI_API_KEY: "${{ secrets.POST_MERGE_DOCS_API_KEY }}", }), + (candidate) => (candidate.on.push["paths-ignore"] = ["docs/**"]), ])("rejects credential and permission boundary mutation %#", (mutate) => { const candidate = structuredClone(workflow); mutate(candidate); diff --git a/test/release-candidate-evidence.test.ts b/test/release-candidate-evidence.test.ts index 348ea7fb914..73653e27e20 100644 --- a/test/release-candidate-evidence.test.ts +++ b/test/release-candidate-evidence.test.ts @@ -29,7 +29,21 @@ function bashBlockUnder(source: string, heading: string): string { ); } -const releaseEntryBlock = bashBlockUnder(evidence, "## Release Entry and Pi Result"); +function bashBlockContaining(source: string, marker: string): string { + const blocks = [...source.matchAll(/^```bash\n([\s\S]*?)^```\s*$/gmu)].map( + (match) => match[1] ?? "", + ); + return ( + blocks.find((block) => block.includes(marker)) ?? + (() => { + throw new Error(`candidate-evidence.md is missing a bash block containing ${marker}`); + })() + ); +} + +const releaseEntryBlock = bashBlockUnder(evidence, "## Release Entry and Documentation Coverage"); +const docsPrSelectionBlock = bashBlockContaining(evidence, 'SELECTED_DOCS_PR="$EVIDENCE_DIR'); +const docsPrReadBlock = bashBlockContaining(evidence, 'DOCS_PR_COMMITS="$EVIDENCE_DIR'); const temporaryDirectories: string[] = []; const shellHelpers = String.raw` @@ -95,6 +109,111 @@ function runReleaseEntry( }); } +function selectionFixture() { + const input = fixture({ "docs/changelog/2026-08-17.mdx": "# Releases\n" }); + const previousTagSha = input.candidate; + git(input.root, "commit", "--allow-empty", "-m", "docs: merge cumulative documentation"); + const ancestorMergeSha = git(input.root, "rev-parse", "HEAD"); + git(input.root, "commit", "--allow-empty", "-m", "feat: finish release candidate"); + input.candidate = git(input.root, "rev-parse", "HEAD"); + git(input.root, "checkout", "-b", "unrelated", previousTagSha); + git(input.root, "commit", "--allow-empty", "-m", "docs: unrelated documentation"); + const nonAncestorMergeSha = git(input.root, "rev-parse", "HEAD"); + git(input.root, "checkout", "main"); + return { ancestorMergeSha, input, nonAncestorMergeSha, previousTagSha }; +} + +function docsCandidate(number: number, mergeSha: string): Record { + return { + headRefName: `automation/post-merge-docs-${number}`, + headRefOid: String(number).padStart(40, "0"), + headRepository: { nameWithOwner: "NVIDIA/NemoClaw" }, + mergeCommit: { oid: mergeSha }, + mergedAt: "2026-08-20T12:00:00Z", + number, + reviewDecision: "APPROVED", + statusCheckRollup: [ + { + __typename: "CheckRun", + conclusion: "SUCCESS", + name: "docs", + status: "COMPLETED", + }, + ], + title: `docs: prepare v1.2.${number} documentation`, + url: `https://github.com/NVIDIA/NemoClaw/pull/${number}`, + }; +} + +function runDocsPrSelection( + selection: ReturnType, + candidates: readonly Record[], +): ReturnType { + const { input, previousTagSha } = selection; + fs.writeFileSync( + path.join(input.evidenceDir, "managed-docs-pr-candidates.jsonl"), + candidates + .map((candidate) => JSON.stringify(candidate)) + .concat("") + .join("\n"), + ); + const bin = path.join(input.root, "bin"); + fs.mkdirSync(bin); + const callLog = path.join(input.evidenceDir, "gh-calls.txt"); + fs.writeFileSync(callLog, ""); + const fakeGh = path.join(bin, "gh"); + fs.writeFileSync( + fakeGh, + String.raw`#!/usr/bin/env bash +set -euo pipefail +printf '%s\n' "$*" >>"$GH_CALL_LOG" +case "$*" in + *"/commits?"*) printf '%s\n' "$GH_COMMITS_JSON" ;; + *"/files?"*) printf '%s\n' "$GH_FILES_JSON" ;; + *) exit 99 ;; +esac +`, + { mode: 0o755 }, + ); + const commitMessage = + "docs: catch up after main\n\nSigned-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>"; + return spawnSync("bash", ["-c", `${shellHelpers}\n${docsPrSelectionBlock}\n${docsPrReadBlock}`], { + cwd: input.root, + encoding: "utf8", + env: { + ...process.env, + CANDIDATE_SHA: input.candidate, + EVIDENCE_DIR: input.evidenceDir, + GH_CALL_LOG: callLog, + GH_COMMITS_JSON: JSON.stringify([ + [ + { + sha: "1".repeat(40), + commit: { + author: { email: "41898282+github-actions[bot]@users.noreply.github.com" }, + message: "docs: earlier cumulative update", + verification: { verified: true }, + }, + parents: [{ sha: previousTagSha }], + }, + { + sha: String(42).padStart(40, "0"), + commit: { + author: { email: "41898282+github-actions[bot]@users.noreply.github.com" }, + message: commitMessage, + verification: { verified: true }, + }, + parents: [{ sha: previousTagSha }], + }, + ], + ]), + GH_FILES_JSON: JSON.stringify([[{ filename: "docs/guide.mdx" }]]), + PATH: `${bin}:${process.env.PATH ?? ""}`, + PREVIOUS_TAG_SHA: previousTagSha, + }, + }); +} + afterEach(() => { for (const directory of temporaryDirectories.splice(0)) { fs.rmSync(directory, { force: true, recursive: true }); @@ -102,6 +221,14 @@ afterEach(() => { }); describe("release candidate evidence commands", () => { + it("uses maintainer-visible coverage instead of an empty-patch receipt", () => { + expect(evidence).toContain("1. Proceed with the candidate as shown."); + expect(evidence).toContain("2. Create or update a docs PR for the uncovered range."); + expect(evidence).toContain("- Maintainer decision: Proceed with the candidate as shown."); + expect(evidence).not.toContain("approved-empty"); + expect(evidence).not.toContain("Final Documentation Recheck"); + }); + it("extracts only the exact release H2 section from a multi-entry changelog", () => { const input = fixture({ "docs/changelog/2026-08-17.mdx": [ @@ -157,4 +284,80 @@ describe("release candidate evidence commands", () => { expect(result.status).not.toBe(0); expect(result.stderr).toContain("release-entry detail validation failed"); }); + + it("selects the first ancestor documentation PR and reads only that PR", () => { + const selection = selectionFixture(); + const result = runDocsPrSelection(selection, [ + docsCandidate(41, selection.nonAncestorMergeSha), + docsCandidate(42, selection.ancestorMergeSha), + ]); + + expect(result.status, String(result.stderr)).toBe(0); + expect( + fs.readFileSync( + path.join(selection.input.evidenceDir, "selected-docs-pr-fields.tsv"), + "utf8", + ), + ).toContain("42\thttps://github.com/NVIDIA/NemoClaw/pull/42"); + expect( + fs.readFileSync(path.join(selection.input.evidenceDir, "docs-coverage-sha"), "utf8").trim(), + ).toBe(selection.previousTagSha); + const calls = fs.readFileSync(path.join(selection.input.evidenceDir, "gh-calls.txt"), "utf8"); + expect(calls).toContain("/pulls/42/commits"); + expect(calls).toContain("/pulls/42/files"); + expect(calls).not.toContain("/pulls/41/"); + expect( + JSON.parse( + fs.readFileSync(path.join(selection.input.evidenceDir, "docs-pr-checks.json"), "utf8"), + ), + ).toEqual([ + { + __typename: "CheckRun", + conclusion: "SUCCESS", + name: "docs", + status: "COMPLETED", + }, + ]); + expect( + fs.readFileSync(path.join(selection.input.evidenceDir, "docs-pr-final-sha"), "utf8").trim(), + ).toBe(String(42).padStart(40, "0")); + }); + + it("records None and skips selected-PR reads when there are no candidates", () => { + const selection = selectionFixture(); + const result = runDocsPrSelection(selection, []); + + expect(result.status, String(result.stderr)).toBe(0); + expect( + fs + .readFileSync(path.join(selection.input.evidenceDir, "selected-docs-pr-fields.tsv"), "utf8") + .trim(), + ).toBe("None\tNone\tNone\tNone\tNone"); + expect( + fs.readFileSync(path.join(selection.input.evidenceDir, "docs-coverage-sha"), "utf8").trim(), + ).toBe(selection.previousTagSha); + expect(fs.readFileSync(path.join(selection.input.evidenceDir, "gh-calls.txt"), "utf8")).toBe( + "", + ); + }); + + it("rejects a non-ancestor merged documentation PR without reading it", () => { + const selection = selectionFixture(); + const result = runDocsPrSelection(selection, [ + docsCandidate(41, selection.nonAncestorMergeSha), + ]); + + expect(result.status, String(result.stderr)).toBe(0); + expect( + fs + .readFileSync(path.join(selection.input.evidenceDir, "selected-docs-pr-fields.tsv"), "utf8") + .trim(), + ).toBe("None\tNone\tNone\tNone\tNone"); + expect( + fs.readFileSync(path.join(selection.input.evidenceDir, "docs-coverage-sha"), "utf8").trim(), + ).toBe(selection.previousTagSha); + expect(fs.readFileSync(path.join(selection.input.evidenceDir, "gh-calls.txt"), "utf8")).toBe( + "", + ); + }); }); diff --git a/test/release-latest-tag.test.ts b/test/release-latest-tag.test.ts index 66663e9e93c..cb3669565ec 100644 --- a/test/release-latest-tag.test.ts +++ b/test/release-latest-tag.test.ts @@ -262,10 +262,16 @@ function completeBrief(plan: Record): string { "", "- Release detail.", "", - "## Pi documentation evidence", + "## Documentation coverage", "", - `- Pi candidate: \`${plan.originMainCommit}\``, - "- Evidence: approved empty patch.", + "- Latest included cumulative docs PR: #100.", + `- Final PR commit and merge commit: \`${plan.originMainCommit}\``, + `- Final automated refresh coverage commit: \`${plan.originMainCommit}\``, + "- Later commits and merged PRs: Only the docs PR merge.", + "- Changed paths: Allowed documentation paths only.", + "- Review and checks: Approved and successful.", + "- Open managed docs PRs: None.", + "- Maintainer decision: Proceed with the candidate as shown.", "", "## Base and managed image evidence", "", @@ -534,32 +540,32 @@ describe("release-latest-tag.sh", () => { expect(localTagObject(fixture, "v0.0.2")).toBe(""); }); - it.each([ - ["Pi", "Pi candidate", "plan-bound Pi candidate"], - ["base image", "Base-image candidate", "plan-bound base-image candidate"], - ])("does not accept %s evidence copied from an earlier candidate", (_kind, field, error) => { - const fixture = createFixture(); - pushTag(fixture, "v0.0.1", fixture.firstCommit); - const earlierCandidate = commit(fixture, "earlier release candidate"); - const releaseCommit = commit(fixture, "planned release commit"); - const planPath = path.join(fixture.root, "release", "plan.json"); - const { plan } = createPlan(fixture, planPath, releaseCommit); - const staleBrief = completeBrief(plan).replace( - `- ${field}: \`${releaseCommit}\``, - `- ${field}: \`${earlierCandidate}\``, - ); + it.each([["base image", "Base-image candidate", "plan-bound base-image candidate"]])( + "does not accept %s evidence copied from an earlier candidate", + (_kind, field, error) => { + const fixture = createFixture(); + pushTag(fixture, "v0.0.1", fixture.firstCommit); + const earlierCandidate = commit(fixture, "earlier release candidate"); + const releaseCommit = commit(fixture, "planned release commit"); + const planPath = path.join(fixture.root, "release", "plan.json"); + const { plan } = createPlan(fixture, planPath, releaseCommit); + const staleBrief = completeBrief(plan).replace( + `- ${field}: \`${releaseCommit}\``, + `- ${field}: \`${earlierCandidate}\``, + ); - const result = cutFromPlan( - fixture, - planPath, - confirmationFor(plan), - writeBrief(fixture, staleBrief), - ); + const result = cutFromPlan( + fixture, + planPath, + confirmationFor(plan), + writeBrief(fixture, staleBrief), + ); - expect(result.status).not.toBe(0); - expect(result.stderr).toContain(error); - expect(localTagObject(fixture, "v0.0.2")).toBe(""); - }); + expect(result.status).not.toBe(0); + expect(result.stderr).toContain(error); + expect(localTagObject(fixture, "v0.0.2")).toBe(""); + }, + ); it("orders canonical semver components without numeric precision loss", () => { const fixture = createFixture(); @@ -1283,16 +1289,23 @@ describe("release-latest-tag.sh", () => { ], [ "another version", - (brief: string) => - brief.replace(/^# NemoClaw.*$/mu, "# NemoClaw v0.0.3 release brief"), + (brief: string) => brief.replace(/^# NemoClaw.*$/mu, "# NemoClaw v0.0.3 release brief"), "heading does not match planned tag", ], [ "another candidate", - (brief: string) => - brief.replace(/^- Candidate:.*$/mu, `- Candidate: \`${"f".repeat(40)}\``), + (brief: string) => brief.replace(/^- Candidate:.*$/mu, `- Candidate: \`${"f".repeat(40)}\``), "candidate does not match", ], + [ + "no documentation proceed decision", + (brief: string) => + brief.replace( + "- Maintainer decision: Proceed with the candidate as shown.", + "- Maintainer decision: Stop tagging.", + ), + "documentation proceed decision", + ], [ "no exception record", (brief: string) => brief.replace("Exceptions: None", "Exceptions removed"), @@ -1311,8 +1324,7 @@ describe("release-latest-tag.sh", () => { ], [ "content after the exception record", - (brief: string) => - brief.replace("Exceptions: None", "Exceptions: None\n\nTrailing content"), + (brief: string) => brief.replace("Exceptions: None", "Exceptions: None\n\nTrailing content"), "exactly one resolved Exceptions line", ], ])("rejects a release brief with %s", (_case, mutate, expectedError) => { diff --git a/tools/post-merge-docs/contract.mts b/tools/post-merge-docs/contract.mts index f660eb41fa9..7634f117803 100644 --- a/tools/post-merge-docs/contract.mts +++ b/tools/post-merge-docs/contract.mts @@ -18,6 +18,7 @@ function strings(value: unknown): string[] { export function validatePostMergeDocsWorkflowBoundary(value: unknown): string[] { const workflow = object(value) ?? {}; const jobs = object(workflow.jobs) ?? {}; + const push = object(object(workflow.on)?.push) ?? {}; const gate = object(jobs.gate) ?? {}; const author = object(jobs.author) ?? {}; const publish = object(jobs.publish) ?? {}; @@ -29,9 +30,11 @@ export function validatePostMergeDocsWorkflowBoundary(value: unknown): string[] const references = strings(workflow).filter((text) => /\$\{\{[^}]*\bsecrets\b/u.test(text)); const valid = isDeepStrictEqual(workflow.permissions, {}) && + isDeepStrictEqual(push["paths-ignore"], ["docs/**", "fern/docs.yml", "fern/assets/**"]) && Object.keys(jobs).sort().join(",") === "author,gate,publish" && Object.values(jobs).every((job) => !Object.hasOwn(object(job) ?? {}, "secrets")) && isDeepStrictEqual(gate.permissions, { "pull-requests": "read" }) && + author.if === "${{ github.repository == 'NVIDIA/NemoClaw' }}" && isDeepStrictEqual(author.permissions, { contents: "read" }) && isDeepStrictEqual(publish.permissions, { actions: "read", @@ -61,6 +64,15 @@ export function allowedDocumentationPath(file: string): boolean { ); } +export function nextPatchReleaseTag( + rangeStartTag: string, + invalidMessage = "release range start tag cannot produce a release target", +): string { + const match = /^v(0|[1-9]\d*)[.](0|[1-9]\d*)[.](0|[1-9]\d*)$/u.exec(rangeStartTag); + if (!match) throw new Error(invalidMessage); + return `v${BigInt(match[1]!)}.${BigInt(match[2]!)}.${BigInt(match[3]!) + 1n}`; +} + export function readBoundedFile(file: string, maximum: number, allowEmpty = false): Buffer { const descriptor = fs.openSync(file, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW); try { diff --git a/tools/post-merge-docs/publish.mts b/tools/post-merge-docs/publish.mts index faf6acdb56d..86f74d74b13 100755 --- a/tools/post-merge-docs/publish.mts +++ b/tools/post-merge-docs/publish.mts @@ -9,13 +9,13 @@ import { tmpdir } from "node:os"; import path from "node:path"; import { pathToFileURL } from "node:url"; -import { allowedDocumentationPath, readBoundedFile } from "./contract.mts"; +import { allowedDocumentationPath, nextPatchReleaseTag, readBoundedFile } from "./contract.mts"; const PREFIX = "automation/post-merge-docs-"; const SIGN_OFF = "Signed-off-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>"; const SHA = /^[0-9a-f]{40}$/u; -type Method = "GET" | "POST"; +type Method = "GET" | "PATCH" | "POST"; export type Request = (method: Method, apiPath: string, body?: unknown) => Promise; type Repo = { full_name: string }; type Pull = { @@ -26,8 +26,17 @@ type Pull = { html_url: string; number: number; state: string; + title: string; }; type Change = { mode: "100644"; path: string; sha: string | null; type: "blob" }; +type Commit = { + author?: { email?: string }; + message?: string; + parents?: Array<{ sha?: string }>; + sha?: string; + tree?: { sha?: string }; + verification?: { verified?: boolean }; +}; function fail(message: string): never { throw new Error(message); } @@ -37,7 +46,20 @@ function environment(name: string): string { function sha(value: string, name: string): string { return SHA.test(value) ? value : fail(`${name} must be a lowercase 40-character Git SHA`); } -function approvedPatch(directory: string, repository: string, mainSha: string): Buffer { +type Approval = { + patch: Buffer; + rangeStartTag: string; + targetReleaseTag: string; +}; +function targetReleaseTag(rangeStartTag: string): string { + const match = /^v(\d+)[.](\d+)[.](\d+)$/u.exec(rangeStartTag); + if (!match) fail("review range start tag cannot produce a release target"); + return nextPatchReleaseTag( + rangeStartTag, + "review range start tag cannot produce a release target", + ); +} +function approvedPatch(directory: string, repository: string, mainSha: string): Approval { const patch = readBoundedFile(path.join(directory, "docs.patch"), 5_242_880, true); let value: unknown; try { @@ -50,17 +72,24 @@ function approvedPatch(directory: string, repository: string, mainSha: string): if (!value || typeof value !== "object" || Array.isArray(value)) fail("review is invalid"); const review = value as Record; if ( - Object.keys(review).sort().join() !== "mainSha,outcome,patchSha256,repository,version" || - review.version !== 1 || + Object.keys(review).sort().join() !== + "mainSha,outcome,patchSha256,rangeStartTag,repository,targetReleaseTag,version" || + review.version !== 2 || review.repository !== repository || review.mainSha !== mainSha || review.patchSha256 !== createHash("sha256").update(patch).digest("hex") || - review.outcome !== "approved" + review.outcome !== "approved" || + typeof review.rangeStartTag !== "string" || + typeof review.targetReleaseTag !== "string" || + targetReleaseTag(review.rangeStartTag) !== review.targetReleaseTag ) - fail("review does not approve the exact patch for this main commit"); - return patch; + fail("review does not approve the exact patch and release target for this main commit"); + return { + patch, + rangeStartTag: review.rangeStartTag, + targetReleaseTag: review.targetReleaseTag, + }; } - const gitEnv: NodeJS.ProcessEnv = { GIT_CONFIG_GLOBAL: "/dev/null", GIT_CONFIG_NOSYSTEM: "1", @@ -131,10 +160,17 @@ function prepare(source: string, destination: string, mainSha: string, patch: Bu return { changes, finalTree, repository: destination }; } -function checkedPull(pull: Pull, repository: string, branch?: string, body?: string): Pull { +function checkedPull( + pull: Pull, + repository: string, + branch?: string, + body?: string, + title?: string, +): Pull { if ( pull.state !== "open" || typeof pull.draft !== "boolean" || + !pull.draft || !Number.isSafeInteger(pull.number) || pull.number < 1 || pull.base.ref !== "main" || @@ -142,7 +178,9 @@ function checkedPull(pull: Pull, repository: string, branch?: string, body?: str pull.head.repo?.full_name !== repository || !SHA.test(pull.head.sha) || (branch !== undefined && pull.head.ref !== branch) || - (body !== undefined && (pull.body !== body || !pull.draft)) || + (body !== undefined && pull.body !== body) || + (title !== undefined && pull.title !== title) || + typeof pull.title !== "string" || pull.html_url !== `https://github.com/${repository}/pull/${pull.number}` ) fail("GitHub returned an invalid managed documentation PR"); @@ -165,14 +203,211 @@ async function managed(repository: string, request: Request): Promise { } return fail("GitHub pull request pagination exceeded 100 pages"); } -async function checkpoint(repo: string, main: string, request: Request): Promise { +async function checkpoint(repo: string, main: string, request: Request): Promise { const ref = (await request("GET", `/repos/${repo}/git/ref/heads/main`)) as { object?: { sha?: string }; }; if (ref?.object?.sha !== main) fail("main changed after documentation review"); const pulls = await managed(repo, request); if (pulls.length > 1) fail("multiple managed documentation PRs are open"); - if (pulls.length) fail("a managed documentation PR opened during publication"); + return pulls[0]; +} +function samePull(left: Pull | undefined, right: Pull | undefined): boolean { + return left === undefined + ? right === undefined + : right !== undefined && + left.number === right.number && + left.body === right.body && + left.draft === right.draft && + left.head.ref === right.head.ref && + left.head.sha === right.head.sha && + left.title === right.title; +} +function requireSamePull(expected: Pull | undefined, observed: Pull | undefined): void { + if (!samePull(expected, observed)) fail("managed documentation PR changed during publication"); +} +function requireAdvancedPull(previous: Pull, observed: Pull | undefined, commitSha: string): Pull { + if ( + observed === undefined || + observed.number !== previous.number || + observed.body !== previous.body || + observed.draft !== previous.draft || + observed.head.ref !== previous.head.ref || + observed.head.sha !== commitSha || + observed.title !== previous.title + ) + fail("managed documentation PR changed during publication"); + return observed; +} +function pullTitle(target: string): string { + return `docs: prepare ${target} documentation`; +} +function pullBody(rangeStart: string, target: string): string { + return `## Release target + +This cumulative draft prepares documentation for \`${target}\`. +It covers merged changes after \`${rangeStart}\` through the latest PR commit. +The workflow selects \`${target}\` by incrementing the patch component of \`${rangeStart}\`. + +## During development + +- Each push to \`main\` that changes a path outside the allowed documentation paths starts a cumulative authoring and independent review run. +- An approved patch creates a verified merge commit and fast-forwards this branch. +- The workflow never force-pushes. It stops if a person changes the branch or PR metadata. +- Keep this PR open as a draft while code PRs merge for \`${target}\`. + +## Release cutoff + +1. Stop merging code PRs intended for \`${target}\`. +2. Add the dated \`## ${target}\` changelog entry and final documentation to this PR. +3. Run \`npm run docs\` and complete the final review. +4. Merge this PR. Its docs-only merge does not start another catch-up run. +5. Ask the tag session to show this PR's coverage point, later commits and PRs, checks, reviews, and any open managed docs PR. +6. Decide whether to proceed, create or update a docs PR for the uncovered range, or stop. +7. Cut \`${target}\` only after you choose to proceed with the displayed documentation coverage. + +## Verification + +- An independent documentation writer approved each exact cumulative patch. +- A maintainer must inspect and approve any approval-required workflow runs. + +${SIGN_OFF}`; +} +function legacyPullBody(mainSha: string): string { + return `## Summary + +Updates documentation for merged changes through \`${mainSha}\`. + +## Verification + +- An independent documentation writer approved the exact patch. +- Required PR checks must run \`npm run docs\` before merge. +- A maintainer must inspect and approve any approval-required workflow runs. + +${SIGN_OFF}`; +} +function pullMetadataMode( + pull: Pull, + commit: Commit, + rangeStart: string, + target: string, +): "current" | "legacy" { + if (pull.title === pullTitle(target) && pull.body === pullBody(rangeStart, target)) + return "current"; + const firstParent = commit.parents?.[0]?.sha; + if ( + commit.parents?.length === 1 && + firstParent && + pull.title === "docs: catch up after merged changes" && + pull.body === legacyPullBody(firstParent) + ) + return "legacy"; + return fail("managed documentation PR metadata does not match the reviewed release target"); +} +async function managedCommit( + repository: string, + commitSha: string, + request: Request, +): Promise { + const commit = (await request("GET", `/repos/${repository}/git/commits/${commitSha}`)) as Commit; + if ( + commit.sha !== commitSha || + !SHA.test(commit.tree?.sha ?? "") || + !Array.isArray(commit.parents) || + !commit.parents.length || + commit.parents.length > 2 || + commit.parents.some((parent) => !SHA.test(parent.sha ?? "")) || + commit.message !== `docs: catch up after main\n\n${SIGN_OFF}` || + commit.author?.email !== "41898282+github-actions[bot]@users.noreply.github.com" || + !commit.verification?.verified + ) + fail("managed documentation branch contains a commit not created by the workflow"); + return commit; +} +async function createCommit(input: { + changes: Change[]; + finalTree: string; + mainSha: string; + preparedRepository: string; + previousSha?: string; + repository: string; + request: Request; +}): Promise { + for (const entry of input.changes) { + if (!entry.sha) continue; + const content = git(input.preparedRepository, ["cat-file", "blob", entry.sha], true) as Buffer; + const blob = (await input.request("POST", `/repos/${input.repository}/git/blobs`, { + content: content.toString("base64"), + encoding: "base64", + })) as { sha?: string }; + if (blob.sha !== entry.sha) fail(`GitHub returned an unexpected blob for ${entry.path}`); + } + const base = String( + git(input.preparedRepository, ["rev-parse", `${input.mainSha}^{tree}`]), + ).trim(); + const tree = (await input.request("POST", `/repos/${input.repository}/git/trees`, { + base_tree: base, + tree: input.changes, + })) as { sha?: string }; + if (tree.sha !== input.finalTree) fail("GitHub returned a tree different from the reviewed tree"); + const parents = input.previousSha ? [input.previousSha, input.mainSha] : [input.mainSha]; + const commit = (await input.request("POST", `/repos/${input.repository}/git/commits`, { + message: `docs: catch up after main\n\n${SIGN_OFF}`, + parents, + tree: input.finalTree, + })) as { sha?: string; verification?: { reason?: string; verified?: boolean } }; + const commitSha = sha(commit.sha ?? "", "created commit SHA"); + if (!commit.verification?.verified) + fail( + `GitHub did not verify the documentation commit: ${commit.verification?.reason ?? "unknown reason"}`, + ); + return commitSha; +} +async function updateRef( + repository: string, + branch: string, + commitSha: string, + request: Request, +): Promise { + const readPath = `/repos/${repository}/git/ref/heads/${branch}`; + const updatePath = `/repos/${repository}/git/refs/heads/${branch}`; + try { + const updated = (await request("PATCH", updatePath, { + force: false, + sha: commitSha, + })) as { object?: { sha?: string }; ref?: string }; + if (updated.ref !== `refs/heads/${branch}` || updated.object?.sha !== commitSha) + fail("GitHub did not confirm documentation branch update"); + } catch (error) { + const reconciled = (await request("GET", readPath)) as { object?: { sha?: string } } | null; + if (reconciled?.object?.sha !== commitSha) throw error; + } +} + +async function updatePullMetadata( + pull: Pull, + repository: string, + rangeStart: string, + target: string, + request: Request, +): Promise { + const body = pullBody(rangeStart, target); + const title = pullTitle(target); + let updated: Pull; + try { + updated = (await request("PATCH", `/repos/${repository}/pulls/${pull.number}`, { + body, + title, + })) as Pull; + } catch (error) { + const reconciled = await managed(repository, request); + if (reconciled.length !== 1 || reconciled[0]?.number !== pull.number) throw error; + updated = reconciled[0]; + } + checkedPull(updated, repository, pull.head.ref, body, title); + if (updated.head.sha !== pull.head.sha) + fail("managed documentation PR changed during metadata update"); + return updated; } export async function publishDocumentation(input: { @@ -185,79 +420,72 @@ export async function publishDocumentation(input: { const { expectedRepository: repository, request } = input; const mainSha = sha(input.expectedMainSha, "GITHUB_SHA"); if (!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u.test(repository)) fail("GITHUB_REPOSITORY is invalid"); - const patch = approvedPatch(input.artifactDirectory, repository, mainSha); - await checkpoint(repository, mainSha, request); + const approval = approvedPatch(input.artifactDirectory, repository, mainSha); + const { patch, rangeStartTag, targetReleaseTag: target } = approval; + const body = pullBody(rangeStartTag, target); + const title = pullTitle(target); + const active = await checkpoint(repository, mainSha, request); const temporary = fs.mkdtempSync(path.join(tmpdir(), "nemoclaw-docs-publish-")); try { const destination = path.join(temporary, "repository"); const prepared = prepare(input.sourceRepository, destination, mainSha, patch); - await checkpoint(repository, mainSha, request); - if (!prepared.changes.length) return; - const branch = `${PREFIX}${mainSha.slice(0, 12)}`; + requireSamePull(active, await checkpoint(repository, mainSha, request)); + if (!active && !prepared.changes.length) return; + + const branch = active?.head.ref ?? `${PREFIX}${mainSha.slice(0, 12)}`; const refPath = `/repos/${repository}/git/ref/heads/${branch}`; const ref = (await request("GET", refPath)) as { object?: { sha?: string } } | null; - let commitSha = - ref === null ? undefined : sha(ref.object?.sha ?? "", "existing documentation branch SHA"); - const message = `docs: catch up after main\n\n${SIGN_OFF}`; - if (commitSha) { - const commit = (await request("GET", `/repos/${repository}/git/commits/${commitSha}`)) as { - message?: string; - parents?: Array<{ sha?: string }>; - sha?: string; - tree?: { sha?: string }; - verification?: { verified?: boolean }; - }; - if ( - commit.sha !== commitSha || - commit.tree?.sha !== prepared.finalTree || - commit.parents?.length !== 1 || - commit.parents[0]?.sha !== mainSha || - commit.message !== message || - !commit.verification?.verified - ) - fail("existing immutable documentation branch has unexpected content"); - } else { - for (const entry of prepared.changes) { - if (!entry.sha) continue; - const content = git(prepared.repository, ["cat-file", "blob", entry.sha], true) as Buffer; - const blob = (await request("POST", `/repos/${repository}/git/blobs`, { - content: content.toString("base64"), - encoding: "base64", - })) as { sha?: string }; - if (blob.sha !== entry.sha) fail(`GitHub returned an unexpected blob for ${entry.path}`); - } - const base = String(git(prepared.repository, ["rev-parse", `${mainSha}^{tree}`])).trim(); - const tree = (await request("POST", `/repos/${repository}/git/trees`, { - base_tree: base, - tree: prepared.changes, - })) as { sha?: string }; - if (tree.sha !== prepared.finalTree) - fail("GitHub returned a tree different from the reviewed tree"); - const commit = (await request("POST", `/repos/${repository}/git/commits`, { - message, - parents: [mainSha], - tree: prepared.finalTree, - })) as { sha?: string; verification?: { reason?: string; verified?: boolean } }; - commitSha = sha(commit.sha ?? "", "created commit SHA"); - if (!commit.verification?.verified) - fail( - `GitHub did not verify the documentation commit: ${commit.verification?.reason ?? "unknown reason"}`, - ); - await checkpoint(repository, mainSha, request); - try { - const created = (await request("POST", `/repos/${repository}/git/refs`, { - ref: `refs/heads/${branch}`, - sha: commitSha, - })) as { object?: { sha?: string }; ref?: string }; - if (created.ref !== `refs/heads/${branch}` || created.object?.sha !== commitSha) - fail("GitHub did not confirm immutable branch creation"); - } catch (error) { - const reconciled = (await request("GET", refPath)) as { object?: { sha?: string } } | null; - if (reconciled?.object?.sha !== commitSha) throw error; + let metadataMode: "current" | "legacy" | undefined; + if (active) { + if (ref?.object?.sha !== active.head.sha) + fail("managed documentation PR and branch point to different commits"); + const current = await managedCommit(repository, active.head.sha, request); + metadataMode = pullMetadataMode(active, current, rangeStartTag, target); + if (!prepared.changes.length || current.tree?.sha === prepared.finalTree) { + let pending = active; + if (metadataMode === "legacy") { + requireSamePull(active, await checkpoint(repository, mainSha, request)); + pending = await updatePullMetadata(active, repository, rangeStartTag, target, request); + } + fail(`Documentation remains pending in ${pending.html_url}`); } + } else if (ref !== null) { + fail("an unmanaged documentation branch already exists for this main commit"); + } + + const commitSha = await createCommit({ + changes: prepared.changes, + finalTree: prepared.finalTree, + mainSha, + preparedRepository: prepared.repository, + ...(active ? { previousSha: active.head.sha } : {}), + repository, + request, + }); + requireSamePull(active, await checkpoint(repository, mainSha, request)); + + if (active) { + await updateRef(repository, branch, commitSha, request); + let pull = requireAdvancedPull(active, (await managed(repository, request))[0], commitSha); + if (metadataMode === "legacy") + pull = await updatePullMetadata(pull, repository, rangeStartTag, target, request); + else checkedPull(pull, repository, branch, body, title); + fail(`Documentation remains pending in ${pull.html_url}`); } - await checkpoint(repository, mainSha, request); - const body = `## Summary\n\nUpdates documentation for merged changes through \`${mainSha}\`.\n\n## Verification\n\n- An independent documentation writer approved the exact patch.\n- Required PR checks must run \`npm run docs\` before merge.\n- A maintainer must inspect and approve any approval-required workflow runs.\n\n${SIGN_OFF}`; + + try { + const created = (await request("POST", `/repos/${repository}/git/refs`, { + ref: `refs/heads/${branch}`, + sha: commitSha, + })) as { object?: { sha?: string }; ref?: string }; + if (created.ref !== `refs/heads/${branch}` || created.object?.sha !== commitSha) + fail("GitHub did not confirm documentation branch creation"); + } catch (error) { + const reconciled = (await request("GET", refPath)) as { object?: { sha?: string } } | null; + if (reconciled?.object?.sha !== commitSha) throw error; + } + + requireSamePull(undefined, await checkpoint(repository, mainSha, request)); let pull: Pull; try { pull = (await request("POST", `/repos/${repository}/pulls`, { @@ -265,21 +493,20 @@ export async function publishDocumentation(input: { body, draft: true, head: branch, - title: "docs: catch up after merged changes", + title, })) as Pull; } catch (error) { const reconciled = await managed(repository, request); if (reconciled.length !== 1 || reconciled[0]?.head.ref !== branch) throw error; pull = reconciled[0]; } - checkedPull(pull, repository, branch, body); + checkedPull(pull, repository, branch, body, title); if (pull.head.sha !== commitSha) fail("documentation PR does not point to the verified commit"); fail(`Documentation remains pending in ${pull.html_url}`); } finally { fs.rmSync(temporary, { force: true, recursive: true }); } } - function client(token: string): Request { const headers = { Accept: "application/vnd.github+json", diff --git a/tools/post-merge-docs/run.mts b/tools/post-merge-docs/run.mts index c3b129a03b0..b4754d21fd0 100755 --- a/tools/post-merge-docs/run.mts +++ b/tools/post-merge-docs/run.mts @@ -22,7 +22,7 @@ import { RESOLVER_MODEL_ID, resolverModelConfiguration, } from "../pr-merge-conflict-fixer/resolve.mts"; -import { allowedDocumentationPath, readBoundedFile } from "./contract.mts"; +import { allowedDocumentationPath, nextPatchReleaseTag, readBoundedFile } from "./contract.mts"; const PATCH_FILE = "docs.patch"; const MAX_PATCH_BYTES = 5_242_880; @@ -56,6 +56,12 @@ function exactSha(value: string | undefined, name: string): string { return SHA.test(sha) ? sha : fail(`${name} must be a full commit SHA`); } +function targetReleaseTag(rangeStartTag: string): string { + const match = /^v(\d+)[.](\d+)[.](\d+)$/u.exec(rangeStartTag); + if (!match) fail("RANGE_START_TAG cannot produce a release target"); + return nextPatchReleaseTag(rangeStartTag, "RANGE_START_TAG cannot produce a release target"); +} + function git(repository: string, args: readonly string[]): string { return execFileSync("git", ["-C", repository, ...args], { encoding: "utf8", @@ -331,8 +337,10 @@ function exportArtifact(env: NodeJS.ProcessEnv, tools: OpenShellTools): void { mainSha: exactSha(env.GITHUB_SHA, "GITHUB_SHA"), outcome: "approved", patchSha256: createHash("sha256").update(patch).digest("hex"), + rangeStartTag: required(env.RANGE_START_TAG, "RANGE_START_TAG"), repository: required(env.GITHUB_REPOSITORY, "GITHUB_REPOSITORY"), - version: 1, + targetReleaseTag: targetReleaseTag(required(env.RANGE_START_TAG, "RANGE_START_TAG")), + version: 2, })}\n`, ); }