package_agent_handoff.ps1 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. <#
  2. .SYNOPSIS
  3. Creates a sanitized, evidence-aware CPLD workspace archive for another agent.
  4. .EXAMPLE
  5. powershell.exe -NoProfile -ExecutionPolicy Bypass -File tools\package_agent_handoff.ps1 -AuditOnly
  6. .EXAMPLE
  7. powershell.exe -NoProfile -ExecutionPolicy Bypass -File tools\package_agent_handoff.ps1 -OutputDir C:\handoff
  8. #>
  9. param(
  10. [string]$SourceRoot = "",
  11. [string]$OutputDir = "",
  12. [string]$PackageName = "",
  13. [switch]$ForceOverwrite,
  14. [switch]$AuditOnly
  15. )
  16. $ErrorActionPreference = "Stop"
  17. if (-not ("AgentHandoff.NativePath" -as [type])) {
  18. Add-Type -TypeDefinition @"
  19. using System;
  20. using System.ComponentModel;
  21. using System.IO;
  22. using System.Runtime.InteropServices;
  23. using System.Text;
  24. using Microsoft.Win32.SafeHandles;
  25. namespace AgentHandoff
  26. {
  27. public static class NativePath
  28. {
  29. private const uint FileShareRead = 0x00000001;
  30. private const uint FileShareWrite = 0x00000002;
  31. private const uint FileShareDelete = 0x00000004;
  32. private const uint OpenExisting = 3;
  33. private const uint FileFlagBackupSemantics = 0x02000000;
  34. [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
  35. private static extern SafeFileHandle CreateFile(
  36. string fileName,
  37. uint desiredAccess,
  38. uint shareMode,
  39. IntPtr securityAttributes,
  40. uint creationDisposition,
  41. uint flagsAndAttributes,
  42. IntPtr templateFile);
  43. [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
  44. private static extern uint GetFinalPathNameByHandle(
  45. SafeFileHandle file,
  46. StringBuilder filePath,
  47. uint filePathLength,
  48. uint flags);
  49. public static string Resolve(string path)
  50. {
  51. string fullPath = Path.GetFullPath(path);
  52. using (SafeFileHandle handle = CreateFile(
  53. fullPath,
  54. 0,
  55. FileShareRead | FileShareWrite | FileShareDelete,
  56. IntPtr.Zero,
  57. OpenExisting,
  58. FileFlagBackupSemantics,
  59. IntPtr.Zero))
  60. {
  61. if (handle.IsInvalid)
  62. {
  63. throw new Win32Exception(Marshal.GetLastWin32Error(), "Unable to open path for final-path resolution");
  64. }
  65. StringBuilder buffer = new StringBuilder(512);
  66. uint length = GetFinalPathNameByHandle(handle, buffer, (uint)buffer.Capacity, 0);
  67. if (length == 0)
  68. {
  69. throw new Win32Exception(Marshal.GetLastWin32Error(), "Unable to resolve final path");
  70. }
  71. if (length >= buffer.Capacity)
  72. {
  73. buffer.Capacity = checked((int)length + 1);
  74. length = GetFinalPathNameByHandle(handle, buffer, (uint)buffer.Capacity, 0);
  75. if (length == 0 || length >= buffer.Capacity)
  76. {
  77. throw new Win32Exception(Marshal.GetLastWin32Error(), "Unable to resolve final path");
  78. }
  79. }
  80. string resolved = buffer.ToString();
  81. if (resolved.StartsWith(@"\\?\UNC\", StringComparison.OrdinalIgnoreCase))
  82. {
  83. return @"\\" + resolved.Substring(8);
  84. }
  85. if (resolved.StartsWith(@"\\?\", StringComparison.OrdinalIgnoreCase))
  86. {
  87. return resolved.Substring(4);
  88. }
  89. return resolved;
  90. }
  91. }
  92. }
  93. }
  94. "@ -ErrorAction Stop
  95. }
  96. function Resolve-FinalPath {
  97. param([string]$Path)
  98. return [AgentHandoff.NativePath]::Resolve($Path)
  99. }
  100. $repo = Resolve-FinalPath (
  101. (Split-Path -Parent (Split-Path -Parent $MyInvocation.MyCommand.Path))
  102. )
  103. $core = Join-Path $repo "tools\package_agent_handoff.py"
  104. $effectiveSourceRoot = if ($SourceRoot) {
  105. Resolve-FinalPath $SourceRoot
  106. }
  107. else {
  108. $repo
  109. }
  110. $pythonIsolationFlags = @("-I", "-S", "-B")
  111. function Test-PathWithinRoot {
  112. param(
  113. [string]$Path,
  114. [string]$Root
  115. )
  116. $fullPath = [System.IO.Path]::GetFullPath($Path)
  117. $fullRoot = [System.IO.Path]::GetFullPath($Root)
  118. if ([string]::Equals($fullPath, $fullRoot, [System.StringComparison]::OrdinalIgnoreCase)) {
  119. return $true
  120. }
  121. if (-not $fullRoot.EndsWith([System.IO.Path]::DirectorySeparatorChar)) {
  122. $fullRoot += [System.IO.Path]::DirectorySeparatorChar
  123. }
  124. return $fullPath.StartsWith($fullRoot, [System.StringComparison]::OrdinalIgnoreCase)
  125. }
  126. function Test-ExternalPythonCandidate {
  127. param([string]$Executable)
  128. if (-not (Test-Path -LiteralPath $Executable -PathType Leaf)) {
  129. return $false
  130. }
  131. try {
  132. $candidatePath = Resolve-FinalPath $Executable
  133. }
  134. catch {
  135. return $false
  136. }
  137. return -not (
  138. (Test-PathWithinRoot -Path $candidatePath -Root $repo) -or
  139. (Test-PathWithinRoot -Path $candidatePath -Root $effectiveSourceRoot)
  140. )
  141. }
  142. function Test-Python311 {
  143. param(
  144. [string]$Executable,
  145. [string[]]$Prefix
  146. )
  147. try {
  148. & $Executable @Prefix @pythonIsolationFlags -c "import sys; raise SystemExit(0 if sys.version_info >= (3, 11) else 1)" *> $null
  149. return $LASTEXITCODE -eq 0
  150. }
  151. catch {
  152. return $false
  153. }
  154. }
  155. function Resolve-Python311 {
  156. $candidates = @()
  157. $python = Get-Command python.exe -ErrorAction SilentlyContinue
  158. if (-not $python) { $python = Get-Command python -ErrorAction SilentlyContinue }
  159. if ($python) { $candidates += ,([ordered]@{ exe = $python.Source; prefix = @() }) }
  160. $py = Get-Command py.exe -ErrorAction SilentlyContinue
  161. if ($py) { $candidates += ,([ordered]@{ exe = $py.Source; prefix = @("-3") }) }
  162. foreach ($candidate in $candidates) {
  163. if (-not (Test-ExternalPythonCandidate -Executable $candidate.exe)) {
  164. continue
  165. }
  166. if (Test-Python311 -Executable $candidate.exe -Prefix $candidate.prefix) {
  167. return $candidate
  168. }
  169. }
  170. throw "Python 3.11 or newer is required to create the agent handoff package"
  171. }
  172. if (-not (Test-Path -LiteralPath $core -PathType Leaf)) {
  173. throw "Agent handoff packager core is missing: $core"
  174. }
  175. $python311 = Resolve-Python311
  176. $arguments = @($python311.prefix) + $pythonIsolationFlags + @($core)
  177. if ($SourceRoot) { $arguments += @("--source-root", $SourceRoot) }
  178. if ($OutputDir) { $arguments += @("--output-dir", $OutputDir) }
  179. if ($PackageName) { $arguments += @("--package-name", $PackageName) }
  180. if ($ForceOverwrite) { $arguments += "--force-overwrite" }
  181. if ($AuditOnly) { $arguments += "--audit-only" }
  182. & $python311.exe @arguments
  183. exit $LASTEXITCODE