Private/Set-KadenAgentFrontmatterModel.ps1
|
function Set-KadenAgentFrontmatterModel { <# .SYNOPSIS Write one model line into an existing agent frontmatter block. .DESCRIPTION Leaves the file untouched when the model line is already that value, or when the file has no frontmatter block. Does not create files. #> [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '', Justification = 'Private writer. The public apply command owns ShouldProcess.')] [CmdletBinding()] param( [Parameter(Mandatory = $true)] [string]$LiteralPath, [Parameter(Mandatory = $true)] [string]$Model ) if (-not (Test-Path -LiteralPath $LiteralPath -PathType Leaf)) { return [pscustomobject]@{ Changed = $false; Applied = $false; Reason = 'managed agent is not on disk' } } $original = [System.IO.File]::ReadAllText($LiteralPath) $newline = if ($original.Contains("`r`n")) { "`r`n" } else { "`n" } $normalized = $original -replace "`r`n", "`n" -replace "`r", "`n" $match = [regex]::Match($normalized, '(?s)\A---\n(?<fm>.*?)\n---(?<rest>.*)\z') if (-not $match.Success) { return [pscustomobject]@{ Changed = $false; Applied = $false; Reason = 'agent has no frontmatter' } } $frontmatterText = $match.Groups['fm'].Value $lines = @($frontmatterText.Split([string[]]@("`n"), [System.StringSplitOptions]::None)) $replaced = $false for ($i = 0; $i -lt $lines.Count; $i++) { if (-not $replaced -and $lines[$i] -match '^model:') { $lines[$i] = 'model: ' + $Model $replaced = $true } } if (-not $replaced) { $lines += ('model: ' + $Model) } $frontmatter = ($lines -join "`n") $rebuilt = "---`n$frontmatter`n---$($match.Groups['rest'].Value)" $rebuilt = $rebuilt -replace "`n", $newline if ($rebuilt -eq $original) { return [pscustomobject]@{ Changed = $false; Applied = $true; Reason = '' } } Write-KadenTextAtomic -LiteralPath $LiteralPath -Text $rebuilt return [pscustomobject]@{ Changed = $true; Applied = $true; Reason = '' } } |