-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathBuild.ps1
More file actions
3380 lines (2902 loc) · 127 KB
/
Build.ps1
File metadata and controls
3380 lines (2902 loc) · 127 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#Requires -Version 7.0
<#
.SYNOPSIS
Unified build orchestrator for PC_AI native components.
.DESCRIPTION
Consolidates all build processes into a single entry point with well-defined
output folders, clear progress messaging, and artifact manifests.
Output Structure:
.pcai/
└── build/
├── artifacts/ # Final distributable binaries
│ ├── pcai-llamacpp/ # llamacpp backend binaries
│ ├── pcai-mistralrs/ # mistralrs backend binaries
│ └── manifest.json # Build manifest with hashes
├── logs/ # Build logs (timestamped)
└── packages/ # Release packages (ZIPs)
.PARAMETER Component
Which component(s) to build:
- inference: pcai-inference (llamacpp + mistralrs backends)
- llamacpp: pcai-inference llamacpp backend only
- mistralrs: pcai-inference mistralrs backend only
- functiongemma: FunctionGemma runtime + train crates
- functiongemma-router-data: Generate FunctionGemma router training dataset
- functiongemma-token-cache: Build FunctionGemma token cache artifacts
- functiongemma-train: Run FunctionGemma training via rust-functiongemma-train
- functiongemma-eval: Run FunctionGemma evaluation harness via Rust CLI
- media: pcai-media Janus-Pro media agent (FFI DLL + HTTP server)
- tui: PcaiChatTui .NET chat terminal UI
- pcainative: PcaiNative .NET interop wrapper
- servicehost: PcaiServiceHost .NET host binary
- nukenul: Hybrid Rust/C# NukeNul utility (external repo preferred)
- lint: Run repository lint checks only
- format: Run formatting checks only
- fix: Apply automated formatting/fixes where supported
- deps: Refresh and validate Rust dependency graph/cache state
- media-convert: Run GGUF model conversion via AI-Media Python toolchain
- test: Run Rust + PowerShell test suites (unit, functional, GPU unit tests)
- benchmark: Run media pipeline benchmarks via Tests/Benchmarks/Benchmarks.Media.ps1
- native: .NET native toolchain (pcainative + servicehost + tui)
- all: All components (default)
.PARAMETER Configuration
Build configuration: Debug or Release (default: Release)
.PARAMETER EnableCuda
Enable CUDA GPU acceleration for supported backends.
.PARAMETER Clean
Clean all build artifacts before building.
.PARAMETER Package
Create distributable ZIP packages after building.
.PARAMETER RunTests
Run component-aligned post-build tests.
.PARAMETER SkipTests
Skip running tests after build even if -RunTests is provided.
.PARAMETER Deploy
Create a deployable aggregate bundle in addition to per-component packages.
.PARAMETER CargoTools
CargoTools integration mode:
- auto: use CargoTools when available (default)
- enabled: require CargoTools and fail if unavailable
- disabled: do not import/use CargoTools defaults
.PARAMETER CargoPreflight
Enable CargoTools preflight checks for Rust builds.
.PARAMETER CargoPreflightMode
CargoTools preflight mode: check, clippy, fmt, all.
.PARAMETER SyncCargoDefaults
Persist CargoTools default Cargo/rustfmt/clippy settings to user config files.
Disabled by default to avoid mutating developer workstation state implicitly.
.PARAMETER FunctionGemmaArgs
Optional passthrough arguments for FunctionGemma operation components:
functiongemma-router-data, functiongemma-token-cache, functiongemma-train, functiongemma-eval.
.PARAMETER LintProfile
Lint/format profile selector used by lint/format/fix components:
all, rust-check, rust-clippy, rust-fmt, rust-inference-check,
rust-inference-clippy, rust-inference-fmt, dotnet-format, powershell, docs, astgrep, toml.
.PARAMETER DependencyStrategy
Rust dependency lock behavior:
- locked: pass --locked to cargo commands (default, cache-friendly)
- frozen: pass --frozen to cargo commands
- update: allow dependency updates (no lock flag)
.PARAMETER AutoFix
Apply auto-fixes where supported (ast-grep update, formatters, dotnet format write mode).
.PARAMETER SkipQualityGate
Skip pre-build ast-grep quality gate for non-lint components.
.PARAMETER Verbose
Show detailed build output.
.EXAMPLE
.\Build.ps1 -Component inference -EnableCuda
Build pcai-inference with CUDA support.
.EXAMPLE
.\Build.ps1 -Clean -Package
Clean build all components and create release packages.
.EXAMPLE
.\Build.ps1 -Component llamacpp -Configuration Debug
Debug build of llamacpp backend only.
.EXAMPLE
.\Build.ps1 -Component functiongemma-router-data
Generate FunctionGemma router dataset using unified orchestration defaults.
.EXAMPLE
.\Build.ps1 -Component functiongemma-train
Run FunctionGemma training using default config and dataset paths.
.EXAMPLE
.\Build.ps1 -Component nukenul
Build the NukeNul hybrid Rust + C# utility from `NUKENUL_ROOT` or `C:\codedev\nukenul`.
.EXAMPLE
.\Build.ps1 -Component lint -LintProfile all
Run repository lint checks only.
.EXAMPLE
.\Build.ps1 -Component format -LintProfile rust-fmt
Run Rust formatting checks only.
.EXAMPLE
.\Build.ps1 -Component fix -LintProfile all -AutoFix
Apply automated code/document fixes where toolchains support write mode.
.EXAMPLE
.\Build.ps1 -Component media -EnableCuda
Build pcai-media DLL + pcai-media-server with full CUDA/cuDNN/flash-attn/nvml features.
Detects GPU compute capabilities automatically and sets CUDA_COMPUTE_CAPS.
Deploys to bin/ and creates symlinks in ~/bin/.
.EXAMPLE
.\Build.ps1 -Component media-convert
Run Janus-Pro GGUF model conversion via AI-Media/.venv Python toolchain.
.EXAMPLE
.\Build.ps1 -Component test
Run Rust unit tests (pcai-media, pcai-media-model, pcai-inference) and
PowerShell Pester suites (PC-AI.Gpu.Tests, PC-AI.Media.Tests).
.EXAMPLE
.\Build.ps1 -Component benchmark
Run media pipeline performance benchmarks via Tests/Benchmarks/Benchmarks.Media.ps1.
.EXAMPLE
.\Build.ps1 -Component all -EnableCuda -Configuration Release -Package
Full release build with CUDA, RUSTFLAGS="-D warnings", auto-detected compute caps,
all features enabled, and packaged ZIP artifacts.
#>
[CmdletBinding()]
param(
[ValidateSet('inference', 'llamacpp', 'mistralrs', 'functiongemma', 'functiongemma-router-data', 'functiongemma-token-cache', 'functiongemma-train', 'functiongemma-eval', 'media', 'media-convert', 'tui', 'pcainative', 'servicehost', 'nukenul', 'lint', 'format', 'fix', 'deps', 'native', 'test', 'benchmark', 'all')]
[string]$Component = 'all',
[ValidateSet('Debug', 'Release')]
[string]$Configuration = 'Release',
[switch]$EnableCuda,
[switch]$Clean,
[switch]$Package,
[switch]$RunTests,
[switch]$SkipTests,
[switch]$Deploy,
[ValidateSet('auto', 'enabled', 'disabled')]
[string]$CargoTools = 'auto',
[switch]$CargoPreflight,
[ValidateSet('check', 'clippy', 'fmt', 'all')]
[string]$CargoPreflightMode = 'check',
[switch]$SyncCargoDefaults,
[string[]]$FunctionGemmaArgs = @(),
[ValidateSet('all', 'rust-check', 'rust-clippy', 'rust-fmt', 'rust-inference-check', 'rust-inference-clippy', 'rust-inference-fmt', 'dotnet-format', 'powershell', 'docs', 'astgrep', 'toml', 'rag-quality')]
[string]$LintProfile = 'all',
[ValidateSet('locked', 'frozen', 'update')]
[string]$DependencyStrategy = 'locked',
[switch]$AutoFix,
[switch]$SkipQualityGate,
[switch]$Quiet
)
$ErrorActionPreference = 'Stop'
$script:StartTime = Get-Date
$script:ProjectRoot = $PSScriptRoot
$script:ArtifactsRoot = if ($env:PCAI_ARTIFACTS_ROOT) {
$env:PCAI_ARTIFACTS_ROOT
} else {
Join-Path $script:ProjectRoot '.pcai'
}
$script:BuildRoot = Join-Path $script:ArtifactsRoot 'build'
$script:BuildArtifactsDir = Join-Path $script:BuildRoot 'artifacts'
$script:BuildLogsDir = Join-Path $script:BuildRoot 'logs'
$script:BuildPackagesDir = Join-Path $script:BuildRoot 'packages'
$script:BuildDeployDir = Join-Path $script:BuildRoot 'deploy'
$script:QuietMode = $Quiet.IsPresent
$script:CargoToolsEnabled = $false
$script:RustBuildWrapper = Join-Path $script:ProjectRoot 'Tools\Invoke-RustBuild.ps1'
$script:DependencyStrategy = $DependencyStrategy
$script:PcaiModuleBootstrap = Join-Path $script:ProjectRoot 'Tools\PcaiModuleBootstrap.ps1'
$script:NukeNulRootCandidates = @(
$env:NUKENUL_ROOT,
'C:\codedev\nukenul',
(Join-Path $script:ProjectRoot 'Native\NukeNul')
) | Where-Object { $_ }
if (Test-Path -LiteralPath $script:PcaiModuleBootstrap) {
. $script:PcaiModuleBootstrap
}
function Resolve-NukeNulProjectRoot {
foreach ($candidate in $script:NukeNulRootCandidates) {
if (-not $candidate) { continue }
$resolved = try {
if (Test-Path -LiteralPath $candidate) {
(Resolve-Path -LiteralPath $candidate -ErrorAction Stop).Path
} else {
[System.IO.Path]::GetFullPath($candidate)
}
} catch {
continue
}
if (Test-Path -LiteralPath (Join-Path $resolved 'NukeNul.csproj')) {
return $resolved
}
}
return $null
}
function Initialize-NvidiaBuildEnvironment {
[CmdletBinding()]
param()
$result = [ordered]@{
UsedGpuModule = $false
CudaInitialized = $false
PreferredGpu = $null
Inventory = @()
Source = $null
}
$gpuModule = $null
if (Get-Command -Name Import-PcaiResolvedModule -ErrorAction SilentlyContinue) {
try {
$gpuModule = Import-PcaiResolvedModule -ModuleName 'PC-AI.Gpu' -RepoRoot $script:ProjectRoot -Force
}
catch {
Write-BuildStep "PC-AI.Gpu import failed: $($_.Exception.Message)" 'warning'
}
}
if ($gpuModule) {
$result.UsedGpuModule = $true
try {
$envResult = Initialize-NvidiaEnvironment -Scope Process -Quiet
if ($envResult.CudaPath) {
$result.CudaInitialized = $true
$result.Source = 'PC-AI.Gpu'
Write-BuildStep "NVIDIA environment initialized via PC-AI.Gpu: $($envResult.CudaVersion) ($($envResult.CudaPath))" 'success'
}
}
catch {
Write-BuildStep "PC-AI.Gpu environment init failed: $($_.Exception.Message)" 'warning'
}
try {
$inventory = @(Get-NvidiaGpuInventory)
if ($inventory.Count -gt 0) {
$preferredGpu = $inventory |
Sort-Object @{ Expression = { $_.MemoryTotalMB }; Descending = $true }, @{ Expression = { $_.Index } } |
Select-Object -First 1
$result.Inventory = $inventory
$result.PreferredGpu = $preferredGpu
Write-BuildStep "Preferred NVIDIA GPU: [$($preferredGpu.Index)] $($preferredGpu.Name) ($($preferredGpu.MemoryTotalMB) MiB, CC $($preferredGpu.ComputeCapability))" 'success'
}
}
catch {
Write-BuildStep "GPU inventory query failed: $($_.Exception.Message)" 'warning'
}
}
if (-not $result.CudaInitialized) {
$cudaInitScript = Join-Path $script:ProjectRoot 'Tools\\Initialize-CudaEnvironment.ps1'
if (Test-Path $cudaInitScript) {
$cudaResult = & $cudaInitScript
if ($cudaResult.Found) {
$result.CudaInitialized = $true
$result.Source = 'Initialize-CudaEnvironment.ps1'
Write-BuildStep "CUDA environment initialized: $($cudaResult.SelectedVersion) (NVCC_CCBIN=$($cudaResult.NvccCcbin))" 'success'
} else {
Write-BuildStep 'CUDA not found - GPU build may fail' 'warning'
}
}
}
return [PSCustomObject]$result
}
function Get-CudaComputeCaps {
[CmdletBinding()]
param(
[object[]]$GpuInventory
)
# Build a comma-separated CUDA_COMPUTE_CAPS string from GPU inventory.
# Prefers CC reported by the GPU module; falls back to nvidia-smi -q.
$caps = [System.Collections.Generic.List[string]]::new()
if ($GpuInventory -and $GpuInventory.Count -gt 0) {
foreach ($gpu in $GpuInventory) {
$cc = $gpu.ComputeCapability
if ($cc -and $cc -match '^\d+\.\d+$') {
$normalized = $cc -replace '\.', ''
if (-not $caps.Contains($normalized)) {
$caps.Add($normalized)
}
}
}
}
# Fallback: parse nvidia-smi directly
if ($caps.Count -eq 0 -and (Get-Command nvidia-smi -ErrorAction SilentlyContinue)) {
$smiOut = & nvidia-smi --query-gpu=compute_cap --format=csv,noheader 2>$null
foreach ($line in $smiOut) {
$trimmed = $line.Trim()
if ($trimmed -match '^\d+\.\d+$') {
$normalized = $trimmed -replace '\.', ''
if (-not $caps.Contains($normalized)) {
$caps.Add($normalized)
}
}
}
}
if ($caps.Count -eq 0) { return $null }
return ($caps | Sort-Object) -join ','
}
function Set-ReleaseBuildFlags {
[CmdletBinding()]
param(
[string]$Configuration,
[string]$CudaComputeCaps
)
if ($Configuration -eq 'Release') {
# Treat warnings as errors for release builds.
# Preserve any existing RUSTFLAGS the caller may have set.
$existingFlags = $env:RUSTFLAGS
if ($existingFlags -and $existingFlags -notmatch '-D\s+warnings') {
$env:RUSTFLAGS = "$existingFlags -D warnings"
} elseif (-not $existingFlags) {
$env:RUSTFLAGS = '-D warnings'
}
Write-BuildStep "RUSTFLAGS (release): $($env:RUSTFLAGS)" 'success'
}
if ($CudaComputeCaps) {
$env:CUDA_COMPUTE_CAPS = $CudaComputeCaps
Write-BuildStep "CUDA_COMPUTE_CAPS: $CudaComputeCaps" 'success'
}
}
function Set-BuildAccelerationEnvironment {
[CmdletBinding()]
param()
# Ninja: use as CMake generator if available (faster than MSBuild for C/C++)
if (-not $env:CMAKE_GENERATOR) {
if (Get-Command ninja -ErrorAction SilentlyContinue) {
$env:CMAKE_GENERATOR = 'Ninja'
Write-BuildStep 'Build acceleration: Ninja generator detected, CMAKE_GENERATOR=Ninja' 'success'
} elseif (Get-Command 'ninja.exe' -ErrorAction SilentlyContinue) {
$env:CMAKE_GENERATOR = 'Ninja'
Write-BuildStep 'Build acceleration: Ninja generator detected, CMAKE_GENERATOR=Ninja' 'success'
} else {
Write-BuildStep 'Ninja not found; using default CMake generator (install via winget install Ninja-build.Ninja)' 'warning'
}
} else {
Write-BuildStep "CMAKE_GENERATOR already set: $($env:CMAKE_GENERATOR)" 'skip'
}
# ccache: C/C++ compiler launcher for clang/gcc builds (e.g. candle native code)
if (-not $env:CMAKE_C_COMPILER_LAUNCHER) {
if (Get-Command ccache -ErrorAction SilentlyContinue) {
$env:CMAKE_C_COMPILER_LAUNCHER = 'ccache'
$env:CMAKE_CXX_COMPILER_LAUNCHER = 'ccache'
Write-BuildStep 'Build acceleration: ccache found, CMAKE_C/CXX_COMPILER_LAUNCHER=ccache' 'success'
} else {
Write-BuildStep 'ccache not found; C/C++ incremental compilation not accelerated' 'warning'
}
} else {
Write-BuildStep "CMAKE_C_COMPILER_LAUNCHER already set: $($env:CMAKE_C_COMPILER_LAUNCHER)" 'skip'
}
# sccache verification (for Rust)
if ($env:RUSTC_WRAPPER) {
$sccacheRunning = $false
if ($env:RUSTC_WRAPPER -match '(^|[\\/])sccache(?:\.exe)?$|^sccache$') {
$sccacheRunning = (Get-Command sccache -ErrorAction SilentlyContinue) -ne $null
}
if ($sccacheRunning) {
Write-BuildStep "sccache: active (RUSTC_WRAPPER=$($env:RUSTC_WRAPPER))" 'success'
} else {
Write-BuildStep "RUSTC_WRAPPER set but sccache not found on PATH: $($env:RUSTC_WRAPPER)" 'warning'
}
} else {
# Try to locate sccache even if not configured
if (Get-Command sccache -ErrorAction SilentlyContinue) {
$env:RUSTC_WRAPPER = 'sccache'
Write-BuildStep 'Build acceleration: sccache found on PATH, RUSTC_WRAPPER=sccache' 'success'
} else {
Write-BuildStep 'sccache not configured; Rust incremental builds rely on cargo cache only' 'warning'
}
}
# lld-link: verify the fast linker is available (configured via .cargo/config.toml)
if (Get-Command lld-link -ErrorAction SilentlyContinue) {
Write-BuildStep 'Build acceleration: lld-link available (fast linker)' 'success'
} elseif (Get-Command 'lld-link.exe' -ErrorAction SilentlyContinue) {
Write-BuildStep 'Build acceleration: lld-link.exe available (fast linker)' 'success'
} else {
Write-BuildStep 'lld-link not found; using default MSVC linker (install LLVM for faster linking)' 'warning'
}
}
function New-HomeBinSymlink {
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[string]$TargetPath,
[Parameter(Mandatory)]
[string]$LinkName
)
$homeBinDir = Join-Path $HOME 'bin'
if (-not (Test-Path -LiteralPath $homeBinDir)) {
New-Item -ItemType Directory -Path $homeBinDir -Force | Out-Null
Write-BuildStep "Created ~/bin directory: $homeBinDir" 'success'
}
$linkPath = Join-Path $homeBinDir $LinkName
if (-not (Test-Path -LiteralPath $TargetPath -PathType Leaf)) {
Write-BuildStep "Symlink target not found, skipping ~/bin/$LinkName -> $TargetPath" 'warning'
return
}
try {
if (Test-Path -LiteralPath $linkPath) {
Remove-Item -LiteralPath $linkPath -Force -ErrorAction SilentlyContinue
}
New-Item -ItemType SymbolicLink -Path $linkPath -Target $TargetPath -Force | Out-Null
Write-BuildStep "Symlink: ~/bin/$LinkName -> $TargetPath" 'success'
} catch {
# Symlink creation can fail if not running as admin; fall back to file copy
Write-BuildStep "Symlink creation failed (need admin?), copying instead: $($_.Exception.Message)" 'warning'
try {
Copy-Item -LiteralPath $TargetPath -Destination $linkPath -Force
Write-BuildStep "Fallback copy: ~/bin/$LinkName <- $TargetPath" 'success'
} catch {
Write-BuildStep "Fallback copy also failed: $($_.Exception.Message)" 'error'
}
}
}
#region Output Formatting
function Write-BuildHeader {
param([string]$Message)
if ($script:QuietMode) { return }
$line = '=' * 70
Write-Host "`n$line" -ForegroundColor Cyan
Write-Host " $Message" -ForegroundColor Cyan
Write-Host "$line" -ForegroundColor Cyan
}
function Write-BuildPhase {
param([string]$Phase, [string]$Description)
if ($script:QuietMode) { return }
$elapsed = (Get-Date) - $script:StartTime
Write-Host "`n[$($elapsed.ToString('mm\:ss'))] " -ForegroundColor DarkGray -NoNewline
Write-Host "PHASE: $Phase" -ForegroundColor Yellow
if ($Description) {
Write-Host " $Description" -ForegroundColor DarkGray
}
}
function Write-BuildStep {
param([string]$Step, [string]$Status = 'running')
if ($script:QuietMode -and $Status -notin @('warning', 'error')) { return }
$symbol = switch ($Status) {
'running' { '[..]' }
'success' { '[OK]' }
'warning' { '[!!]' }
'error' { '[XX]' }
'skip' { '[--]' }
default { '[..]' }
}
$color = switch ($Status) {
'running' { 'White' }
'success' { 'Green' }
'warning' { 'Yellow' }
'error' { 'Red' }
'skip' { 'DarkGray' }
default { 'White' }
}
Write-Host " $symbol " -ForegroundColor $color -NoNewline
Write-Host $Step
}
function Format-InvariantString {
param(
[Parameter(Mandatory)]
[string]$Template,
[Parameter(Mandatory)]
[object[]]$Args
)
return [string]::Format([System.Globalization.CultureInfo]::InvariantCulture, $Template, $Args)
}
function Get-DotnetPublishDefaults {
param(
[Parameter(Mandatory)]
[string]$Configuration
)
$args = @(
'--nologo',
'-maxcpucount',
'-p:BuildInParallel=true',
'-p:UseSharedCompilation=true'
)
if ($Configuration -eq 'Release') {
$args += @(
'-p:TieredCompilation=true',
'-p:TieredPGO=true',
'-p:PublishReadyToRun=true',
'-p:ReadyToRunUseCrossgen2=true'
)
}
return $args
}
function Write-BuildResult {
param(
[string]$Component,
[bool]$Success,
[TimeSpan]$Duration,
[string[]]$Artifacts
)
$status = if ($Success) { 'SUCCESS' } else { 'FAILED' }
$color = if ($Success) { 'Green' } else { 'Red' }
if ($script:QuietMode) { return }
Write-Host "`n $Component build: " -NoNewline
Write-Host $status -ForegroundColor $color -NoNewline
Write-Host " ($($Duration.ToString('mm\:ss')))"
if ($Artifacts -and @($Artifacts).Count -gt 0) {
Write-Host ' Artifacts:' -ForegroundColor DarkGray
foreach ($artifact in $Artifacts) {
Write-Host " - $artifact" -ForegroundColor DarkGray
}
}
}
function Write-BuildSummary {
param(
[hashtable]$Results,
[string]$ManifestPath
)
$elapsed = (Get-Date) - $script:StartTime
$successCount = @($Results.Values | Where-Object { $_.Success }).Count
$totalCount = $Results.Count
Write-BuildHeader 'BUILD SUMMARY'
Write-Host "`n Total Time: $($elapsed.ToString('hh\:mm\:ss'))" -ForegroundColor Cyan
Write-Host " Components: $successCount / $totalCount succeeded" -ForegroundColor $(if ($successCount -eq $totalCount) { 'Green' } else { 'Yellow' })
Write-Host "`n Results:" -ForegroundColor White
foreach ($name in $Results.Keys | Sort-Object) {
$result = $Results[$name]
$status = if ($result.Success) { 'OK' } else { 'FAILED' }
$color = if ($result.Success) { 'Green' } else { 'Red' }
Write-Host " [$status] " -ForegroundColor $color -NoNewline
Write-Host "$name ($($result.Duration.ToString('mm\:ss')))"
}
if ($ManifestPath -and (Test-Path $ManifestPath)) {
Write-Host "`n Manifest: $ManifestPath" -ForegroundColor DarkGray
}
if (Test-Path $script:BuildArtifactsDir) {
Write-Host " Artifacts: $script:BuildArtifactsDir" -ForegroundColor DarkGray
}
if (Test-Path $script:BuildLogsDir) {
Write-Host " Logs: $script:BuildLogsDir" -ForegroundColor DarkGray
}
if (Test-Path $script:BuildPackagesDir) {
Write-Host " Packages: $script:BuildPackagesDir" -ForegroundColor DarkGray
}
if (Test-Path $script:BuildDeployDir) {
Write-Host " Deploy: $script:BuildDeployDir" -ForegroundColor DarkGray
}
Write-BuildAccelerationSummary
Write-Host ''
}
function Write-BuildAccelerationSummary {
if ($script:QuietMode) { return }
Write-Host "`n Acceleration:" -ForegroundColor White
if ($script:CargoToolsEnabled) {
Write-Host ' CargoTools: enabled' -ForegroundColor DarkGray
} else {
Write-Host ' CargoTools: disabled/unavailable' -ForegroundColor DarkGray
}
if ($env:RUSTC_WRAPPER) {
Write-Host " RUSTC_WRAPPER: $($env:RUSTC_WRAPPER)" -ForegroundColor DarkGray
}
if ($env:CMAKE_GENERATOR) {
Write-Host " CMAKE_GENERATOR: $($env:CMAKE_GENERATOR)" -ForegroundColor DarkGray
}
if ($env:CMAKE_C_COMPILER_LAUNCHER) {
Write-Host " C launcher: $($env:CMAKE_C_COMPILER_LAUNCHER)" -ForegroundColor DarkGray
}
if ($env:CMAKE_CXX_COMPILER_LAUNCHER) {
Write-Host " CXX launcher: $($env:CMAKE_CXX_COMPILER_LAUNCHER)" -ForegroundColor DarkGray
}
if ($env:CMAKE_CUDA_COMPILER_LAUNCHER) {
Write-Host " CUDA launcher: $($env:CMAKE_CUDA_COMPILER_LAUNCHER)" -ForegroundColor DarkGray
}
$usingSccache = $env:RUSTC_WRAPPER -and ($env:RUSTC_WRAPPER -match '(^|[\\/])sccache(?:\.exe)?$|^sccache$')
if ($usingSccache -and (Get-Command sccache -ErrorAction SilentlyContinue)) {
$stats = & sccache --show-stats 2>$null
if ($LASTEXITCODE -eq 0 -and $stats) {
foreach ($line in ($stats | Where-Object {
$_ -match '^(Compile requests|Compile requests executed|Cache hits|Cache misses|Cache hits rate|Compilations|Cache location|Use direct/preprocessor mode\?)'
})) {
Write-Host " $line" -ForegroundColor DarkGray
}
}
}
}
#endregion
#region Version Information
function Initialize-BuildVersion {
Write-BuildPhase 'Version' 'Extracting git metadata'
$versionScript = Join-Path $script:ProjectRoot 'Tools\Get-BuildVersion.ps1'
if (Test-Path $versionScript) {
$script:VersionInfo = & $versionScript -SetEnv -Quiet
Write-BuildStep "Version: $($script:VersionInfo.Version)" 'success'
Write-BuildStep "Git: $($script:VersionInfo.GitHashShort) ($($script:VersionInfo.GitBranch))" 'success'
Write-BuildStep "Type: $($script:VersionInfo.BuildType)" 'success'
return $script:VersionInfo
} else {
Write-BuildStep 'Version script not found, using defaults' 'warning'
$env:PCAI_VERSION = '0.1.0+unknown'
$env:PCAI_BUILD_VERSION = '0.1.0+unknown'
return $null
}
}
#endregion
#region Toolchain Setup
function Resolve-PowerShellExecutable {
$pwshCmd = Get-Command pwsh -ErrorAction SilentlyContinue
if ($pwshCmd) { return $pwshCmd.Source }
$powershellCmd = Get-Command powershell -ErrorAction SilentlyContinue
if ($powershellCmd) { return $powershellCmd.Source }
throw 'Neither pwsh nor powershell is available on PATH.'
}
function Initialize-CargoToolsDefaults {
Write-BuildPhase 'Toolchain' 'Initializing CargoTools defaults and build environment'
if ($CargoTools -eq 'disabled') {
Write-BuildStep 'CargoTools integration disabled by request' 'skip'
return $false
}
$cargoToolsManifest = if (Get-Command Resolve-PcaiModuleManifestPath -ErrorAction SilentlyContinue) {
Resolve-PcaiModuleManifestPath -ModuleName 'CargoTools' -RepoRoot $script:ProjectRoot
} else {
$null
}
if (-not $cargoToolsManifest) {
if ($CargoTools -eq 'enabled') {
Write-BuildStep 'CargoTools module required but not installed' 'error'
throw 'CargoTools integration was explicitly enabled but the module was not found.'
}
Write-BuildStep 'CargoTools module not found; using direct tooling defaults' 'warning'
return $false
}
if (-not (Get-Module CargoTools)) {
Import-Module -Name $cargoToolsManifest -ErrorAction Stop | Out-Null
}
$cacheRoot = if ($env:PCAI_CACHE_ROOT) {
$env:PCAI_CACHE_ROOT
} elseif (Get-Command Resolve-CacheRoot -Module CargoTools -ErrorAction SilentlyContinue) {
Resolve-CacheRoot
} elseif (Test-Path 'T:\RustCache') {
'T:\RustCache'
} else {
Join-Path $script:ArtifactsRoot 'cache'
}
try {
$callerTargetDir = $env:CARGO_TARGET_DIR
if ($SyncCargoDefaults) {
Initialize-RustDefaults -Scope Cargo | Out-Null
Write-BuildStep 'CargoTools defaults synchronized to user Cargo config' 'success'
} else {
Write-BuildStep 'CargoTools defaults not persisted (use -SyncCargoDefaults to write config files)' 'skip'
}
Initialize-CargoEnv -CacheRoot $cacheRoot
if ($callerTargetDir) {
$env:CARGO_TARGET_DIR = $callerTargetDir
Write-BuildStep "Preserved caller CARGO_TARGET_DIR: $callerTargetDir" 'success'
}
if ($CargoPreflight) {
$env:CARGO_PREFLIGHT = '1'
$env:CARGO_PREFLIGHT_MODE = $CargoPreflightMode
Write-BuildStep "Cargo preflight enabled ($CargoPreflightMode)" 'success'
}
$script:CargoToolsEnabled = $true
Write-BuildStep "CargoTools manifest: $cargoToolsManifest" 'success'
Write-BuildStep "CargoTools initialized (cache root: $cacheRoot)" 'success'
if ($env:RUSTC_WRAPPER) {
Write-BuildStep "Rust compiler wrapper: $($env:RUSTC_WRAPPER)" 'success'
}
if (Get-Command Start-SccacheServer -Module CargoTools -ErrorAction SilentlyContinue) {
Start-SccacheServer | Out-Null
Write-BuildStep 'sccache server initialized via CargoTools' 'success'
}
} catch {
if ($CargoTools -eq 'enabled') {
Write-BuildStep "CargoTools initialization failed: $($_.Exception.Message)" 'error'
throw
}
Write-BuildStep "CargoTools initialization failed; continuing without module defaults: $($_.Exception.Message)" 'warning'
$script:CargoToolsEnabled = $false
}
return $script:CargoToolsEnabled
}
function Add-CargoDependencyFlags {
param(
[Parameter(Mandatory)]
[string[]]$CargoArgs
)
if (-not $CargoArgs -or $CargoArgs.Count -eq 0) {
return $CargoArgs
}
if ($CargoArgs -contains '--locked' -or $CargoArgs -contains '--frozen') {
return $CargoArgs
}
if ($script:DependencyStrategy -eq 'locked') {
return $CargoArgs + @('--locked')
}
if ($script:DependencyStrategy -eq 'frozen') {
return $CargoArgs + @('--frozen')
}
return $CargoArgs
}
function Invoke-RustBuildCommand {
param(
[Parameter(Mandatory)]
[string]$Path,
[Parameter(Mandatory)]
[string[]]$CargoArgs,
[Parameter(Mandatory)]
[string]$LogFile
)
if (-not (Test-Path $Path)) {
throw "Rust project path not found: $Path"
}
$effectiveCargoArgs = Add-CargoDependencyFlags -CargoArgs $CargoArgs
if (Test-Path $script:RustBuildWrapper) {
$shellExe = Resolve-PowerShellExecutable
$wrapperArgs = @('-NoProfile', '-File', $script:RustBuildWrapper, '-Path', $Path, '-CargoArgs') + $effectiveCargoArgs
if ($env:CARGO_USE_LLD -eq '1') {
$wrapperArgs += '-UseLld'
}
if ($env:PCAI_DISABLE_CACHE -eq '1') {
$wrapperArgs += '-DisableCache'
}
if ($CargoPreflight) {
$wrapperArgs += @('-Preflight', '-PreflightMode', $CargoPreflightMode, '-PreflightBlocking')
}
& $shellExe @wrapperArgs 2>&1 | Tee-Object -FilePath $LogFile | Out-Null
return ($LASTEXITCODE -eq 0)
}
Push-Location $Path
try {
if ($CargoPreflight) {
$preflightSets = switch ($CargoPreflightMode) {
'check' { @(@('check')) }
'clippy' { @(@('clippy', '--all-targets', '--', '-D', 'warnings')) }
'fmt' { @(@('fmt', '--', '--check')) }
'all' {
@(
@('check'),
@('clippy', '--all-targets', '--', '-D', 'warnings'),
@('fmt', '--', '--check')
)
}
}
foreach ($preflightArgs in $preflightSets) {
$effectivePreflightArgs = Add-CargoDependencyFlags -CargoArgs $preflightArgs
& cargo @effectivePreflightArgs 2>&1 | Tee-Object -FilePath $LogFile | Out-Null
if ($LASTEXITCODE -ne 0) {
return $false
}
}
}
& cargo @effectiveCargoArgs 2>&1 | Tee-Object -FilePath $LogFile | Out-Null
return ($LASTEXITCODE -eq 0)
} finally {
Pop-Location
}
}
function Resolve-CargoOutputDirectory {
param(
[Parameter(Mandatory)]
[string]$ProjectDir,
[Parameter(Mandatory)]
[string]$Configuration
)
if (Get-Command Resolve-CargoTargetDirectory -ErrorAction SilentlyContinue) {
$manifestPath = Join-Path $ProjectDir 'Cargo.toml'
return Resolve-CargoTargetDirectory -ProjectDir $ProjectDir -ManifestPath $manifestPath -Configuration $Configuration
}
$configDir = $Configuration.ToLower()
if ($env:CARGO_TARGET_DIR) {
$sharedTargetDir = Join-Path $env:CARGO_TARGET_DIR $configDir
if (Test-Path $sharedTargetDir) {
return $sharedTargetDir
}
}
return Join-Path $ProjectDir "target\$configDir"
}
function Publish-StagedArtifact {
param(
[Parameter(Mandatory)]
[string]$SourcePath,
[Parameter(Mandatory)]
[string]$DestinationDirectory,
[string]$DestinationFileName,
[string]$ArtifactKind = 'binary'
)
if (-not (Test-Path -LiteralPath $SourcePath -PathType Leaf)) {
return $null
}
if (Get-Command Publish-BuildArtifact -ErrorAction SilentlyContinue) {
return Publish-BuildArtifact -SourcePath $SourcePath -DestinationDirectory $DestinationDirectory -DestinationFileName $DestinationFileName -VersionInfo $script:VersionInfo -ArtifactKind $ArtifactKind
}
if (-not (Test-Path -LiteralPath $DestinationDirectory)) {
New-Item -ItemType Directory -Path $DestinationDirectory -Force | Out-Null
}
if (-not $DestinationFileName) {
$DestinationFileName = [System.IO.Path]::GetFileName($SourcePath)
}
$destinationPath = Join-Path $DestinationDirectory $DestinationFileName
Copy-Item -LiteralPath $SourcePath -Destination $destinationPath -Force
return [pscustomobject]@{
DestinationPath = $destinationPath
ManifestPath = $null
FileName = [System.IO.Path]::GetFileName($destinationPath)
}
}
function ConvertTo-SafePathLabel {
param(
[Parameter(Mandatory)]
[string]$Value
)
$safe = $Value -replace '[^A-Za-z0-9._-]', '_'
$safe = $safe.Trim('_')
if ([string]::IsNullOrWhiteSpace($safe)) {
return 'unknown'
}
return $safe
}
function Publish-PcaiNativeBundle {
param(
[Parameter(Mandatory)]
[string]$PublishRoot,
[Parameter(Mandatory)]
[string]$Configuration
)
$repoBinRoot = Join-Path $script:ProjectRoot 'bin'
$bundleParent = Join-Path $repoBinRoot 'native-bundles'
if (-not (Test-Path -LiteralPath $bundleParent)) {
New-Item -ItemType Directory -Path $bundleParent -Force | Out-Null
}
$versionLabel = if ($script:VersionInfo) {
if ($script:VersionInfo.ReleaseTag) {
$script:VersionInfo.ReleaseTag
} elseif ($script:VersionInfo.InformationalVersion) {
$script:VersionInfo.InformationalVersion
} elseif ($script:VersionInfo.SemVer) {
$script:VersionInfo.SemVer
} else {
$script:VersionInfo.FileVersion
}
} else {
'unknown'
}
$bundleName = '{0}-{1}' -f (ConvertTo-SafePathLabel -Value $versionLabel), (Get-Date -Format 'yyyyMMdd-HHmmss')
$bundleRoot = Join-Path $bundleParent $bundleName
if (-not (Test-Path -LiteralPath $bundleRoot)) {
New-Item -ItemType Directory -Path $bundleRoot -Force | Out-Null
}
$coreProjectDir = Join-Path $script:ProjectRoot 'Native\\pcai_core'
$coreTargetDir = Resolve-CargoOutputDirectory -ProjectDir $coreProjectDir -Configuration $Configuration
$publishedEntries = [System.Collections.Generic.List[object]]::new()
$bundleSpecs = @(
@{ Name = 'PcaiNative.dll'; Source = (Join-Path $PublishRoot 'PcaiNative.dll'); Kind = 'managed-dotnet'; Required = $true },
@{ Name = 'PcaiNative.deps.json'; Source = (Join-Path $PublishRoot 'PcaiNative.deps.json'); Kind = 'managed-dotnet'; Required = $true },
@{ Name = 'PcaiNative.pdb'; Source = (Join-Path $PublishRoot 'PcaiNative.pdb'); Kind = 'managed-dotnet'; Required = $false },
@{ Name = 'PcaiNative.xml'; Source = (Join-Path $PublishRoot 'PcaiNative.xml'); Kind = 'managed-dotnet'; Required = $false },
@{ Name = 'pcai_core_lib.dll'; Source = (Join-Path $coreTargetDir 'pcai_core_lib.dll'); Fallback = (Join-Path $PublishRoot 'pcai_core_lib.dll'); Kind = 'native-rust'; Required = $true },
@{ Name = 'pcai_core_lib.pdb'; Source = (Join-Path $coreTargetDir 'pcai_core_lib.pdb'); Fallback = (Join-Path $PublishRoot 'pcai_core_lib.pdb'); Kind = 'native-rust'; Required = $false },
@{ Name = 'pcai_inference.dll'; Source = (Join-Path $coreTargetDir 'pcai_inference.dll'); Fallback = (Join-Path $PublishRoot 'pcai_inference.dll'); Kind = 'native-rust'; Required = $false }
)