diff --git a/.github/scripts/Apply-PRFinalize.Tests.ps1 b/.github/scripts/Apply-PRFinalize.Tests.ps1 new file mode 100644 index 000000000000..5d3d6faa4717 --- /dev/null +++ b/.github/scripts/Apply-PRFinalize.Tests.ps1 @@ -0,0 +1,319 @@ +#!/usr/bin/env pwsh +#Requires -Modules Pester +<# +.SYNOPSIS + Pester tests for pure-function helpers in apply-pr-finalize.ps1. + +.EXAMPLE + Invoke-Pester ./Apply-PRFinalize.Tests.ps1 +#> + +BeforeAll { + $scriptPath = Join-Path $PSScriptRoot 'apply-pr-finalize.ps1' + $tokens = $null + $parseErrors = $null + $ast = [System.Management.Automation.Language.Parser]::ParseFile($scriptPath, [ref]$tokens, [ref]$parseErrors) + if ($parseErrors -and $parseErrors.Count -gt 0) { + throw ($parseErrors | ForEach-Object { $_.Message }) -join [Environment]::NewLine + } + + # Execute the script's real module-scope config assignments (referenced by the helpers) + # rather than duplicating them here, so the tests can't silently drift from the script. + foreach ($variableName in @('PlatformPrefixes', 'TestingNoteMarker')) { + $assignment = $ast.Find({ + $args[0] -is [System.Management.Automation.Language.AssignmentStatementAst] -and + $args[0].Left.Extent.Text -eq "`$script:$variableName" + }, $true) + + if (-not $assignment) { + throw "Variable '`$script:$variableName' not found" + } + + . ([scriptblock]::Create($assignment.Extent.Text)) + } + + foreach ($functionName in @( + 'ConvertTo-AzdoSafeConsole', + 'Test-FinalizeIsNoOp', + 'Get-FinalizeRecommendation', + 'Merge-PreservedTitlePrefix', + 'Merge-PreservedBodyPreamble' + )) { + $function = $ast.Find({ + $args[0] -is [System.Management.Automation.Language.FunctionDefinitionAst] -and + $args[0].Name -eq $functionName + }, $true) + + if (-not $function) { + throw "Function '$functionName' not found" + } + + . ([scriptblock]::Create($function.Extent.Text)) + } + + # Mirrors the real Phase 4 output shape (see Review-PR.ps1 Phase 4 prompt). + $script:RecommendContent = @' +**Assessment:** ✏️ Recommend updating — the title still has a `[WIP]` prefix. + +**Recommended title** +```text +[iOS] ButtonHandler: Preserve custom UIButton background styling +``` + +**Recommended description** +```text +### Issue details + +Something broke. + +### Description of Change + +Fixed it. +``` +'@ +} + +Describe 'Test-FinalizeIsNoOp' { + It 'is true for the keep-as-is verdict' { + Test-FinalizeIsNoOp -Content '✅ Current title and description accurately reflect the change — recommend keeping as-is.' | + Should -BeTrue + } + + It 'is true for empty content' { + Test-FinalizeIsNoOp -Content '' | Should -BeTrue + } + + It 'is false when an update is recommended' { + Test-FinalizeIsNoOp -Content $script:RecommendContent | Should -BeFalse + } +} + +Describe 'Get-FinalizeRecommendation' { + It 'extracts the title and description' { + $result = Get-FinalizeRecommendation -Content $script:RecommendContent + $result | Should -Not -BeNullOrEmpty + $result.Title | Should -Be '[iOS] ButtonHandler: Preserve custom UIButton background styling' + $result.Body | Should -Match 'Description of Change' + $result.Body | Should -Not -Match '```' + } + + It 'returns null for the keep-as-is verdict' { + Get-FinalizeRecommendation -Content '✅ Current title and description accurately reflect the change — recommend keeping as-is.' | + Should -BeNullOrEmpty + } + + It 'returns null when the fenced blocks are missing' { + Get-FinalizeRecommendation -Content '**Assessment:** ✏️ Recommend updating — but no blocks follow.' | + Should -BeNullOrEmpty + } + + It 'returns null when only a title is present' { + $partial = "**Recommended title**`n``````text`n[iOS] Something`n``````" + Get-FinalizeRecommendation -Content $partial | Should -BeNullOrEmpty + } + + It 'preserves fenced code blocks nested inside the description' { + $nested = @' +**Recommended title** +````text +[Android] Fix it +```` + +**Recommended description** +````text +### Change + +```csharp +var x = 1; +``` +```` +'@ + $result = Get-FinalizeRecommendation -Content $nested + $result | Should -Not -BeNullOrEmpty + $result.Body | Should -Match 'var x = 1;' + } +} + +Describe 'Merge-PreservedTitlePrefix' { + It 'preserves a triage prefix the recommendation dropped' { + Merge-PreservedTitlePrefix ` + -CurrentTitle '[inflight regression][iOS] Fix CarouselView2 dropping scrolls' ` + -RecommendedTitle '[iOS] CarouselView2: Stop internal recenter scrolls' | + Should -Be '[inflight regression][iOS] CarouselView2: Stop internal recenter scrolls' + } + + It 'preserves [WIP] — un-WIP-ing is the author''s call' { + Merge-PreservedTitlePrefix ` + -CurrentTitle '[WIP][Android] Fix for CurrentItem' ` + -RecommendedTitle '[Android] CarouselView: Preserve CurrentItem' | + Should -Be '[WIP][Android] CarouselView: Preserve CurrentItem' + } + + It 'does not duplicate a platform prefix' { + Merge-PreservedTitlePrefix ` + -CurrentTitle '[iOS] Old title' ` + -RecommendedTitle '[iOS] New title' | + Should -Be '[iOS] New title' + } + + It 'does not duplicate a tag the recommendation already kept' { + Merge-PreservedTitlePrefix ` + -CurrentTitle '[WIP][iOS] Old' ` + -RecommendedTitle '[WIP][iOS] New' | + Should -Be '[WIP][iOS] New' + } + + It 'preserves a branch tag such as [net11.0]' { + Merge-PreservedTitlePrefix ` + -CurrentTitle '[net11.0][iOS] Respect InputTransparent' ` + -RecommendedTitle '[iOS] UserInteraction: Respect InputTransparent' | + Should -Be '[net11.0][iOS] UserInteraction: Respect InputTransparent' + } + + It 'returns the recommendation unchanged when there is no prefix' { + Merge-PreservedTitlePrefix ` + -CurrentTitle 'Fix grouped CollectionView section removal' ` + -RecommendedTitle '[iOS] CollectionView: Fix grouped section removal' | + Should -Be '[iOS] CollectionView: Fix grouped section removal' + } + + It 'handles an empty current title' { + Merge-PreservedTitlePrefix -CurrentTitle '' -RecommendedTitle '[iOS] New' | Should -Be '[iOS] New' + } +} + +Describe 'Merge-PreservedBodyPreamble' { + BeforeAll { + $script:NoteBody = @' + +> [!NOTE] +> Are you waiting for the changes in this PR to be merged? +> It would be very helpful if you could test the resulting artifacts. Thank you! + +### Issue Details +Old description. +'@ + } + + It 'preserves the required testing note the recommendation omitted' { + $result = Merge-PreservedBodyPreamble -CurrentBody $script:NoteBody -RecommendedBody "### Issue details`n`nNew description." + $result | Should -Match 'Are you waiting for the changes in this PR to be merged\?' + $result | Should -Match 'New description\.' + $result | Should -Not -Match 'Old description\.' + } + + It 'keeps the note ahead of the new content' { + $result = Merge-PreservedBodyPreamble -CurrentBody $script:NoteBody -RecommendedBody '### New' + $noteIndex = $result.IndexOf('Are you waiting') + $newIndex = $result.IndexOf('### New') + $noteIndex | Should -BeLessThan $newIndex + } + + It 'does not duplicate the note when the recommendation already has it' { + $withNote = "> [!NOTE]`n> Are you waiting for the changes in this PR to be merged?`n`n### New" + $result = Merge-PreservedBodyPreamble -CurrentBody $script:NoteBody -RecommendedBody $withNote + ([regex]::Matches($result, 'Are you waiting')).Count | Should -Be 1 + } + + It 'returns the recommendation unchanged when the current body has no note' { + Merge-PreservedBodyPreamble -CurrentBody '### Just a description' -RecommendedBody '### New' | + Should -Be '### New' + } + + It 'handles an empty current body' { + Merge-PreservedBodyPreamble -CurrentBody '' -RecommendedBody '### New' | Should -Be '### New' + } +} + +Describe 'ConvertTo-AzdoSafeConsole' { + # Behaviour is pinned to the canonical implementation in Review-PR.ps1; these mirror the + # assertions in Review-PR.Tests.ps1 so the duplicated copy can't silently drift. + It 'defangs the task.setvariable logging command' { + ConvertTo-AzdoSafeConsole '##vso[task.setvariable variable=x]y' | + Should -Be '## vso[task.setvariable variable=x]y' + } + + It 'defangs the bare ## command prefix' { + ConvertTo-AzdoSafeConsole '##[command]z' | Should -Be '## [command]z' + } + + It 'collapses a lone CR so it cannot open a column-0 line' { + ConvertTo-AzdoSafeConsole "safe`r##vso[task.complete]" | Should -Be 'safe ## vso[task.complete]' + } + + It 'collapses LF' { + ConvertTo-AzdoSafeConsole "Reviewing`n##vso[task.complete result=Succeeded;]done" | + Should -Be 'Reviewing ## vso[task.complete result=Succeeded;]done' + } + + It 'leaves an innocent ## alone' { + ConvertTo-AzdoSafeConsole 'Reading file src/Foo.cs (## of total)' | + Should -Be 'Reading file src/Foo.cs (## of total)' + } +} + +Describe 'Security regressions — AzDO logging-command injection' { + # Regression coverage for the review finding: the Post phase runs with GH_COMMENT_TOKEN + # and sets GateFailed/CopilotFailed, so PR-controlled text reaching stdout unsanitized + # could set those variables and mask a failing gate. + + It 'does not carry an "##vso[" payload out of an author-controlled title tag' { + $evil = '[##vso[task.setvariable variable=GateFailed] x] fix' + $result = Merge-PreservedTitlePrefix -CurrentTitle $evil -RecommendedTitle '[iOS] Clean title' + $result | Should -Not -Match '##' + $result | Should -Be '[iOS] Clean title' + } + + It 'rejects a recommended title containing a lone CR' { + $CR = [char]13 + $fence = '```' + $content = @( + '**Recommended title**' + "${fence}text" + "harmless${CR}##vso[task.setvariable variable=GateFailed]x" + $fence + '' + '**Recommended description**' + "${fence}text" + 'body' + $fence + ) -join "`n" + + Get-FinalizeRecommendation -Content $content | Should -BeNullOrEmpty + } + + It 'rejects a recommended title containing an LF' { + $fence = '```' + $content = @( + '**Recommended title**' + "${fence}text" + 'line one' + 'line two' + $fence + '' + '**Recommended description**' + "${fence}text" + 'body' + $fence + ) -join "`n" + + Get-FinalizeRecommendation -Content $content | Should -BeNullOrEmpty + } + + It 'still preserves legitimate triage tags after the tag hardening' { + Merge-PreservedTitlePrefix -CurrentTitle '[WIP][iOS] old' -RecommendedTitle '[iOS] new' | + Should -Be '[WIP][iOS] new' + Merge-PreservedTitlePrefix -CurrentTitle '[inflight regression][iOS] old' -RecommendedTitle '[iOS] new' | + Should -Be '[inflight regression][iOS] new' + Merge-PreservedTitlePrefix -CurrentTitle '[net11.0][iOS] old' -RecommendedTitle '[iOS] new' | + Should -Be '[net11.0][iOS] new' + Merge-PreservedTitlePrefix -CurrentTitle '[release/10.0.1xx][iOS] old' -RecommendedTitle '[iOS] new' | + Should -Be '[release/10.0.1xx][iOS] new' + } + + It 'drops a tag carrying a control character' { + $tag = "[wi{0}p][iOS] old" -f [char]13 + Merge-PreservedTitlePrefix -CurrentTitle $tag -RecommendedTitle '[iOS] new' | + Should -Be '[iOS] new' + } +} diff --git a/.github/scripts/Review-PR.ps1 b/.github/scripts/Review-PR.ps1 index 4a22e353c76b..2814a1fc5d46 100644 --- a/.github/scripts/Review-PR.ps1 +++ b/.github/scripts/Review-PR.ps1 @@ -2387,6 +2387,39 @@ if (-not $DryRun) { Write-Host " [DRY RUN] Would set label: $addLabel" -ForegroundColor Magenta } +# ═════════════════════════════════════════════════════════════════════════════ +# STEP 5.5: Apply the Phase 4 (pr-finalize) title/description recommendation +# Deliberately outside the DEFER_COMMENT_TO_STAGE3 block below so the PR gets a +# descriptive title as soon as review finishes, rather than waiting on deep tests. +# Fully non-fatal: on any failure the recommendation still ships in the summary +# comment for a human to apply. +# ═════════════════════════════════════════════════════════════════════════════ + +Write-Host "" +Write-Host "╔═══════════════════════════════════════════════════════════╗" -ForegroundColor Magenta +Write-Host "║ STEP 5.5: APPLY PR TITLE/DESCRIPTION ║" -ForegroundColor Magenta +Write-Host "╚═══════════════════════════════════════════════════════════╝" -ForegroundColor Magenta + +if ($env:SKIP_PR_FINALIZE_APPLY -eq 'true') { + Write-Host " ⏭️ Skipped (SKIP_PR_FINALIZE_APPLY=true)" -ForegroundColor Gray +} else { + $applyFinalizeScript = Join-Path $ScriptsDir "apply-pr-finalize.ps1" + if (Test-Path $applyFinalizeScript) { + try { + # Resolve content.md from $RepoRoot rather than letting the script fall back to + # the current directory — the Post phase's cwd is not guaranteed to be the repo. + $finalizeContent = Join-Path $RepoRoot "CustomAgentLogsTmp/PRState/$PRNumber/PRAgent/pr-finalize/content.md" + $applyArgs = @{ PRNumber = $PRNumber; ContentFile = $finalizeContent } + if ($DryRun) { $applyArgs.DryRun = $true } + & $applyFinalizeScript @applyArgs + } catch { + Write-Host " ⚠️ Failed to apply PR title/description (non-fatal): $_" -ForegroundColor Yellow + } + } else { + Write-Host " ⚠️ apply-pr-finalize.ps1 not found — skipping" -ForegroundColor Yellow + } +} + # ═════════════════════════════════════════════════════════════════════════════ # STEP 6: Post AI Summary Review (direct script invocation) # When DEFER_COMMENT_TO_STAGE3=true, skip posting here — Stage 3 diff --git a/.github/scripts/apply-pr-finalize.ps1 b/.github/scripts/apply-pr-finalize.ps1 new file mode 100644 index 000000000000..b7d317836529 --- /dev/null +++ b/.github/scripts/apply-pr-finalize.ps1 @@ -0,0 +1,365 @@ +#!/usr/bin/env pwsh +<# +.SYNOPSIS + Applies the pr-finalize (Phase 4) recommended title/description to the PR. + +.DESCRIPTION + The /review pipeline's Phase 4 already evaluates the PR's existing title and + description and — when they are stale, vague, or inaccurate — writes a + copy-paste-ready replacement to: + + CustomAgentLogsTmp/PRState/{PRNumber}/PRAgent/pr-finalize/content.md + + Until now that recommendation was only *rendered* in the AI Summary comment, so a + human had to copy it across by hand. This script closes that last mile: it parses + the recommendation and applies it with `gh pr edit`, which makes it the squash-merge + commit message. + + Deliberately conservative — it does nothing unless Phase 4 explicitly recommended an + update, and it never discards author signal: + + * Keep-as-is verdict -> no-op (Phase 4 said the current metadata is already good). + * Unparseable content -> no-op (never guess at a replacement). + * No net change -> no-op (avoids edit churn / notification spam). + * Triage prefixes -> preserved ([WIP], [inflight regression], [net11.0], ...). + Un-WIP-ing a PR is the author's call, not the bot's. + * Testing-note block -> preserved. Phase 4 is told to omit the repo's required + "test the resulting artifacts" note from its recommendation, + so applying the body verbatim would silently delete it. + +.PARAMETER PRNumber + PR number to update (required). + +.PARAMETER ContentFile + Path to pr-finalize/content.md. Auto-discovered from PRNumber when omitted. + +.PARAMETER Repo + Target repo in owner/name form. Defaults to dotnet/maui. + +.PARAMETER DryRun + Print what would be applied without calling `gh pr edit`. + +.EXAMPLE + ./apply-pr-finalize.ps1 -PRNumber 36769 + +.EXAMPLE + ./apply-pr-finalize.ps1 -PRNumber 36769 -DryRun +#> + +param( + [Parameter(Mandatory = $true)] + [int]$PRNumber, + + [Parameter(Mandatory = $false)] + [string]$ContentFile, + + [Parameter(Mandatory = $false)] + [string]$Repo = "dotnet/maui", + + [Parameter(Mandatory = $false)] + [switch]$DryRun +) + +Set-StrictMode -Version Latest +$ErrorActionPreference = 'Stop' + +# Platform tags are owned by the recommendation itself (the pr-finalize title formula is +# "[Platform] Component: What changed"), so they are never re-prepended from the old title. +# Everything else in a leading [bracket] run is author/triage signal and is preserved. +# +# Deliberately excludes "net": a "[net11.0]" tag marks a backport target branch, not a +# platform, and dropping it would erase real triage signal. +$script:PlatformPrefixes = @( + 'android', 'ios', 'maccatalyst', 'macos', 'mac', 'windows', 'winui', 'tizen' +) + +# Sentence that uniquely identifies the repo's required "dogfood this PR" note. +$script:TestingNoteMarker = 'Are you waiting for the changes in this PR to be merged?' + +function ConvertTo-AzdoSafeConsole { + <# + .SYNOPSIS + Defangs AzDO logging commands in PR-controlled text before it is written to stdout. + .DESCRIPTION + Mirrors the canonical implementation in Review-PR.ps1. It is duplicated rather than + imported because this script also runs standalone (and is dot-sourced by Pester), so + it cannot depend on the orchestrator's scope. Apply-PRFinalize.Tests.ps1 pins the same + behaviours that Review-PR.Tests.ps1 asserts for the original. + + Required by rule 6 of ci-copilot-pipeline-security.instructions.md: the Post phase runs + with GH_COMMENT_TOKEN and sets GateFailed/CopilotFailed, so an unsanitized "##vso[...]" + reaching stdout here could mask a gate failure. + #> + param([string]$Text) + + # Collapse CR/LF/FF/VT so PR-influenceable text can't fabricate a fresh column-0 line, + # then defang the AzDO logging-command prefixes. + return ($Text -replace '[\r\n\f\v]+', ' ') -replace '##(?=\[|vso\[)', '## ' +} + +function Test-FinalizeIsNoOp { + <# + .SYNOPSIS + True when Phase 4 concluded the existing title/description are already good. + #> + param( + [Parameter(Mandatory = $true)] + [AllowEmptyString()] + [string]$Content + ) + + if ([string]::IsNullOrWhiteSpace($Content)) { return $true } + + $normalized = ($Content -replace "`r`n", "`n").Trim() + + # Mirrors Test-PhaseContentIsNoOp("pr-finalize") in post-ai-summary-comment.ps1 so the + # comment and the apply step agree on what "no change recommended" looks like. + return [bool]($normalized -match '✅\s*Current title and description accurately reflect the change\s*[—-]\s*recommend keeping as-is') +} + +function Get-FinalizeRecommendation { + <# + .SYNOPSIS + Extracts the recommended title and description from pr-finalize/content.md. + .OUTPUTS + Hashtable with Title and Body keys, or $null when the content is not a + parseable "recommend updating" result. + #> + param( + [Parameter(Mandatory = $true)] + [AllowEmptyString()] + [string]$Content + ) + + if ([string]::IsNullOrWhiteSpace($Content)) { return $null } + if (Test-FinalizeIsNoOp -Content $Content) { return $null } + + $normalized = $Content -replace "`r`n", "`n" + + # Each recommendation is a "**Recommended **" label followed by a fenced block. + # Fence length varies (the Phase 4 prompt nests fences), so match 3+ backticks and + # require the closing fence to be at least as long as the opening one. + $pattern = '(?im)^\s*\*\*Recommended\s+{0}\*\*\s*\n+(?`{{3,}})[^\n]*\n(?.*?)\n?\k\s*(?:\n|$)' + + $titleMatch = [regex]::Match($normalized, ($pattern -f 'title'), [System.Text.RegularExpressions.RegexOptions]::Singleline) + $bodyMatch = [regex]::Match($normalized, ($pattern -f 'description'), [System.Text.RegularExpressions.RegexOptions]::Singleline) + + if (-not $titleMatch.Success -or -not $bodyMatch.Success) { return $null } + + $title = $titleMatch.Groups['value'].Value.Trim() + $body = $bodyMatch.Groups['value'].Value.Trim() + + # A multi-line "title" means the fences were mis-parsed; refuse rather than mangle the PR. + # Matches any line break, not just "`n": $normalized only collapses CRLF pairs, so a lone + # CR would otherwise survive and let the title open a new column-0 console line. + if ([string]::IsNullOrWhiteSpace($title) -or $title -match '[\r\n]') { return $null } + if ([string]::IsNullOrWhiteSpace($body)) { return $null } + + return @{ Title = $title; Body = $body } +} + +function Merge-PreservedTitlePrefix { + <# + .SYNOPSIS + Re-applies leading triage/status tags from the current title. + .DESCRIPTION + Phase 4 writes a clean "[Platform] Component: What changed" title, which can drop + tags that carry real workflow meaning — [WIP], [inflight regression], [net11.0]. + Those are restored in their original order. Platform tags are skipped (the + recommendation supplies its own), as is any tag already present. + #> + param( + [Parameter(Mandatory = $true)] + [AllowEmptyString()] + [string]$CurrentTitle, + + [Parameter(Mandatory = $true)] + [string]$RecommendedTitle + ) + + if ([string]::IsNullOrWhiteSpace($CurrentTitle)) { return $RecommendedTitle } + + $leading = [regex]::Match($CurrentTitle.Trim(), '^(?:\s*\[[^\]]+\])+') + if (-not $leading.Success) { return $RecommendedTitle } + + $preserved = @() + foreach ($tagMatch in [regex]::Matches($leading.Value, '\[([^\]]+)\]')) { + $tag = $tagMatch.Groups[1].Value.Trim() + if ([string]::IsNullOrWhiteSpace($tag)) { continue } + + # Defence in depth: only carry over tags that look like real triage/status markers + # ([WIP], [inflight regression], [net11.0], [release/10.0.1xx]). The title is + # author-controlled, so this stops control characters or an "##vso[" fragment from + # riding a preserved tag into the PR title and the Post phase's console stream. + if ($tag -notmatch '^[A-Za-z0-9][A-Za-z0-9 ._/\-]*$') { continue } + + # Platform tag? The recommendation owns those. Strip any trailing version + # (e.g. "iOS18" -> "ios") so versioned platform tags still match. + $firstWord = ($tag -split '[\s/]')[0].TrimEnd('0123456789.') + if ($script:PlatformPrefixes -contains $firstWord.ToLowerInvariant()) { continue } + + # Already carried over by the recommendation (in any position)? + if ($RecommendedTitle -match ('(?i)\[\s*' + [regex]::Escape($tag) + '\s*\]')) { continue } + + $preserved += "[$tag]" + } + + if ($preserved.Count -eq 0) { return $RecommendedTitle } + + return (($preserved -join '') + $RecommendedTitle) +} + +function Merge-PreservedBodyPreamble { + <# + .SYNOPSIS + Re-attaches the repo's required testing-note preamble to a recommended body. + .DESCRIPTION + Phase 4 is instructed to omit the "test the resulting artifacts" boilerplate, so + applying its body verbatim would delete a note the repo requires on every PR. + The current body's preamble (leading HTML comment + note blockquote) is preserved. + #> + param( + [Parameter(Mandatory = $true)] + [AllowEmptyString()] + [string]$CurrentBody, + + [Parameter(Mandatory = $true)] + [string]$RecommendedBody + ) + + if ([string]::IsNullOrWhiteSpace($CurrentBody)) { return $RecommendedBody } + + $normalizedCurrent = $CurrentBody -replace "`r`n", "`n" + if ($normalizedCurrent -notmatch [regex]::Escape($script:TestingNoteMarker)) { return $RecommendedBody } + + # Already present in the recommendation — don't duplicate it. + if (($RecommendedBody -replace "`r`n", "`n") -match [regex]::Escape($script:TestingNoteMarker)) { return $RecommendedBody } + + # Preamble = everything up to the end of the blockquote containing the marker. + $lines = $normalizedCurrent -split "`n" + $markerIndex = -1 + for ($i = 0; $i -lt $lines.Count; $i++) { + if ($lines[$i] -match [regex]::Escape($script:TestingNoteMarker)) { $markerIndex = $i; break } + } + if ($markerIndex -lt 0) { return $RecommendedBody } + + $endIndex = $markerIndex + for ($i = $markerIndex + 1; $i -lt $lines.Count; $i++) { + if ($lines[$i].TrimStart().StartsWith('>')) { $endIndex = $i } else { break } + } + + $preamble = ($lines[0..$endIndex] -join "`n").TrimEnd() + if ([string]::IsNullOrWhiteSpace($preamble)) { return $RecommendedBody } + + return "$preamble`n`n$RecommendedBody" +} + +# ─── Main ─────────────────────────────────────────────────────────────────────── +# Dot-sourced by the Pester suite to test the helpers above without executing the flow. +if ($MyInvocation.InvocationName -eq '.') { return } + +if ([string]::IsNullOrWhiteSpace($ContentFile)) { + $ContentFile = Join-Path (Get-Location) "CustomAgentLogsTmp/PRState/$PRNumber/PRAgent/pr-finalize/content.md" +} + +Write-Host " 📝 PR finalize — applying recommended title/description..." -ForegroundColor Cyan + +if (-not (Test-Path -LiteralPath $ContentFile)) { + Write-Host " ℹ️ No pr-finalize content at '$(ConvertTo-AzdoSafeConsole $ContentFile)' — nothing to apply." -ForegroundColor Gray + exit 0 +} + +$content = Get-Content -Raw -LiteralPath $ContentFile -Encoding UTF8 + +if (Test-FinalizeIsNoOp -Content $content) { + Write-Host " ✅ Phase 4 recommends keeping the current title/description — no change." -ForegroundColor Green + exit 0 +} + +$recommendation = Get-FinalizeRecommendation -Content $content +if (-not $recommendation) { + Write-Host " ⚠️ Could not parse a recommended title/description — leaving the PR untouched." -ForegroundColor Yellow + exit 0 +} + +# Current metadata, so we can preserve author signal and skip no-op edits. +# A read failure must abort: with an empty $currentBody the preamble merge has nothing to +# re-attach, so we would silently strip the repo's required testing note. +$prJson = $null +try { + $prJson = gh pr view $PRNumber --repo $Repo --json title,body 2>$null | ConvertFrom-Json +} catch { + Write-Host " ⚠️ Could not read the current PR metadata ($(ConvertTo-AzdoSafeConsole "$_")) — skipping to avoid clobbering it." -ForegroundColor Yellow + exit 0 +} + +if (-not $prJson) { + Write-Host " ⚠️ 'gh pr view' returned no metadata for #$PRNumber — skipping to avoid clobbering it." -ForegroundColor Yellow + exit 0 +} + +$currentTitle = if ($prJson.PSObject.Properties['title'] -and $prJson.title) { $prJson.title } else { '' } +$currentBody = if ($prJson.PSObject.Properties['body'] -and $prJson.body) { $prJson.body } else { '' } + +$newTitle = Merge-PreservedTitlePrefix -CurrentTitle $currentTitle -RecommendedTitle $recommendation.Title +$newBody = Merge-PreservedBodyPreamble -CurrentBody $currentBody -RecommendedBody $recommendation.Body + +$titleChanged = $newTitle.Trim() -ne $currentTitle.Trim() +$bodyChanged = ($newBody -replace "`r`n", "`n").Trim() -ne ($currentBody -replace "`r`n", "`n").Trim() + +if (-not $titleChanged -and -not $bodyChanged) { + Write-Host " ✅ Recommendation matches the current title/description — no edit needed." -ForegroundColor Green + exit 0 +} + +# Safety invariant: never let an edit drop the repo's required testing note. If the current +# body carries it, the replacement must too — otherwise abandon the body edit entirely. +if ($bodyChanged -and + $currentBody.Contains($script:TestingNoteMarker) -and + -not $newBody.Contains($script:TestingNoteMarker)) { + Write-Host " ⚠️ Replacement body would drop the required testing note — skipping the body edit." -ForegroundColor Yellow + $bodyChanged = $false + if (-not $titleChanged) { exit 0 } +} + +# Every value below is PR/agent-derived, so it goes through the sanitizer before reaching +# stdout (rule 6). The Post phase sets GateFailed/CopilotFailed, so an unsanitized +# "##vso[task.setvariable ...]" echoed here could mask a gate failure. +Write-Host " Title: $(ConvertTo-AzdoSafeConsole $newTitle)" -ForegroundColor Gray +Write-Host " Changed: title=$titleChanged body=$bodyChanged" -ForegroundColor Gray + +if ($DryRun) { + if ($bodyChanged) { + Write-Host " --- body preview (first 15 lines) ---" -ForegroundColor DarkGray + foreach ($line in (($newBody -split "`r?`n") | Select-Object -First 15)) { + Write-Host " | $(ConvertTo-AzdoSafeConsole $line)" -ForegroundColor DarkGray + } + Write-Host " --- end preview ---" -ForegroundColor DarkGray + } + Write-Host " 🔍 DryRun — would apply the above (no gh pr edit issued)." -ForegroundColor Yellow + exit 0 +} + +$bodyFile = Join-Path ([System.IO.Path]::GetTempPath()) "pr-finalize-body-$PRNumber.md" +try { + $newBody | Set-Content -LiteralPath $bodyFile -Encoding UTF8 + + $ghArgs = @('pr', 'edit', "$PRNumber", '--repo', $Repo) + if ($titleChanged) { $ghArgs += @('--title', $newTitle) } + if ($bodyChanged) { $ghArgs += @('--body-file', $bodyFile) } + + $output = & gh @ghArgs 2>&1 + if ($LASTEXITCODE -eq 0) { + Write-Host " ✅ Applied the recommended PR title/description." -ForegroundColor Green + } else { + # Non-fatal: the review comment still carries the recommendation for a human. + # gh echoes back the title/body it was given, so this is PR-derived too. + Write-Host " ⚠️ gh pr edit failed (non-fatal): $(ConvertTo-AzdoSafeConsole ($output -join ' '))" -ForegroundColor Yellow + } +} catch { + Write-Host " ⚠️ Failed to apply the PR finalize recommendation (non-fatal): $(ConvertTo-AzdoSafeConsole "$_")" -ForegroundColor Yellow +} finally { + Remove-Item -LiteralPath $bodyFile -Force -ErrorAction SilentlyContinue +} + +exit 0