-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrun.ps1
More file actions
3990 lines (3707 loc) · 176 KB
/
run.ps1
File metadata and controls
3990 lines (3707 loc) · 176 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
<#
Von Launcher / Process Manager
Actions:
start Start server in background (default)
foreground Run server in foreground (like old behavior)
stop Gracefully stop via /admin/shutdown (fallback force)
status Report running/stopped + health
restart Stop then start
logs Show/tail current log (use -Tail/-Follow)
check Quick health check (exit codes: 0/healthy,2/unhealthy,3/not running)
backup Run manual backup
restore-backup Dry-run/apply restore from a backup artefact or receipt
help Show help
Flags:
-Port <int> Server port (default 5001 on macOS, 5000 elsewhere; -AgentTest defaults to 5010)
-AgentTest Isolated coding-agent test instance mode
-IsolatedTestInstance Alias for -AgentTest
-NoBrowser Do not auto-open browser on start
-ForceBrowser Force open browser even if already opened this session
-ChromeBeta Use Chrome Beta only (for MCP DevTools debugging)
-Tail <n> When action=logs, number of lines (default 100)
-Follow When action=logs, stream updates
-LogRetention <n> Keep last n log files (default 20)
-AdminToken <token> Explicit admin token (else auto-generate & persist)
TODO: Full multi-instance worker isolation for modes that require per-instance workers.
TODO: Optional size-based log rollover.
#>
[CmdletBinding()]
param(
[Parameter(Position = 0)] [string]$Action = 'start',
[int]$Port = 5000,
[switch]$AgentTest,
[switch]$IsolatedTestInstance,
[switch]$NoBrowser,
[switch]$ForceBrowser,
[switch]$ChromeBeta,
[int]$Tail = 100,
[switch]$Follow,
[int]$LogRetention = 20,
[string]$AdminToken,
[switch]$SkipHealth,
[int]$HealthTimeoutSec = 60,
[int]$HealthGraceSec = 45,
[string[]]$ReadyLogPatterns = @('Running with Waitress', 'Press CTRL+C to quit', 'Flask app running'),
[switch]$DisableLogReady,
[switch]$HealthDebug,
[switch]$ShowRelationCoverage,
[switch]$StatusRunMaintenance,
# On-demand backups
[switch]$BackupDryRun,
[string]$BackupTag = 'manual',
[string]$BackupOutDir,
# Restore backups
[string]$RestoreBackupPath,
[string]$RestoreTargetDbName,
[switch]$RestoreApply,
[switch]$RestoreDropTarget,
# Auto-update (continuous self-updating runner)
[int]$UpdateIntervalMinutes = 60,
[string]$UpdateBranch = 'main',
[switch]$UpdateNoRestartIfRunning,
# Disable automatic migration of local backups to W: drive
[switch]$NoBackupMigrate,
[Parameter(ValueFromRemainingArguments = $true)] [string[]]$ExtraArgs
)
$Action = $Action.ToLower()
if ($Action -in @('--help', '-h', '/?')) { $Action = 'help' }
$ErrorActionPreference = 'Stop'
$Root = $PSScriptRoot
$RunDir = Join-Path $Root '.run'
$LogsDir = Join-Path $Root 'logs'
New-Item -ItemType Directory -Force -Path $RunDir | Out-Null
New-Item -ItemType Directory -Force -Path $LogsDir | Out-Null
$script:VonStartFailed = $false
# Ensure logging helper is available before any code path that may emit log lines.
if (-not (Get-Command Write-LauncherLog -ErrorAction SilentlyContinue)) {
function Write-LauncherLog {
param([Parameter(Mandatory = $true)][string]$Msg)
$ts = (Get-Date).ToString('HH:mm:ss')
Write-Host ("[{0}] {1}" -f $ts, $Msg)
}
}
function Apply-LauncherSwitchCompatibility {
param(
[string]$RawInvocationLine = $MyInvocation.Line,
[string[]]$RemainingArgs = $ExtraArgs
)
if ((-not $script:ForceBrowser) -and (($RemainingArgs -contains '--ForceBrowser') -or ($RawInvocationLine -match '(^|\s)--ForceBrowser(?:\s|$)'))) {
$script:ForceBrowser = $true
}
if ((-not $script:NoBrowser) -and (($RemainingArgs -contains '--NoBrowser') -or ($RawInvocationLine -match '(^|\s)--NoBrowser(?:\s|$)'))) {
$script:NoBrowser = $true
}
if ((-not $script:ChromeBeta) -and (($RemainingArgs -contains '--ChromeBeta') -or ($RawInvocationLine -match '(^|\s)--ChromeBeta(?:\s|$)'))) {
$script:ChromeBeta = $true
}
if ((-not $script:AgentTest) -and (($RemainingArgs -contains '--AgentTest') -or ($RawInvocationLine -match '(^|\s)--AgentTest(?:\s|$)'))) {
$script:AgentTest = $true
}
if ((-not $script:IsolatedTestInstance) -and (($RemainingArgs -contains '--IsolatedTestInstance') -or ($RawInvocationLine -match '(^|\s)--IsolatedTestInstance(?:\s|$)'))) {
$script:IsolatedTestInstance = $true
}
}
function Test-AgentTestInstance {
return [bool]$script:AgentTestInstance
}
function Test-MacLauncherHost {
return [bool](Get-Variable -Name IsMacOS -ValueOnly -ErrorAction SilentlyContinue)
}
function Get-StandardLauncherDefaultPort {
if (Test-MacLauncherHost) { return 5001 }
return 5000
}
function Apply-AgentTestLauncherDefaults {
param([bool]$PortWasExplicitlyBound = $false)
$script:StandardDefaultPort = Get-StandardLauncherDefaultPort
$script:AgentTestDefaultPort = 5010
$script:AgentTestInstance = [bool]($script:AgentTest -or $script:IsolatedTestInstance)
$script:AgentTestPortDefaulted = $false
if (-not (Test-AgentTestInstance)) {
if (-not $PortWasExplicitlyBound) {
$script:Port = $script:StandardDefaultPort
}
[Environment]::SetEnvironmentVariable('VON_AGENT_TEST_INSTANCE', $null, 'Process')
return
}
if (-not $PortWasExplicitlyBound) {
$script:Port = $script:AgentTestDefaultPort
$script:AgentTestPortDefaulted = $true
}
if (-not $script:ForceBrowser) {
$script:NoBrowser = $true
}
[Environment]::SetEnvironmentVariable('VON_AGENT_TEST_INSTANCE', '1', 'Process')
}
function ConvertTo-PowerShellSingleQuotedLiteral {
param([AllowNull()][string]$Value)
if ($null -eq $Value) { return "''" }
return "'" + ($Value -replace "'", "''") + "'"
}
Apply-LauncherSwitchCompatibility
Apply-AgentTestLauncherDefaults -PortWasExplicitlyBound:$($PSBoundParameters.ContainsKey('Port'))
function Set-EnvFromDotEnv {
param([string]$EnvPath)
if (-not $EnvPath) { return }
if (-not (Test-Path $EnvPath)) { return }
$applied = 0
Get-Content $EnvPath -ErrorAction SilentlyContinue | ForEach-Object {
$line = $_.Trim()
if (-not $line) { return }
if ($line.StartsWith('#')) { return }
if ($line -match '^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$') {
$key = $Matches[1]
$raw = $Matches[2]
if (-not $key) { return }
$value = $raw.Trim()
if ($value.Length -ge 2) {
$first = $value.Substring(0, 1)
$last = $value.Substring($value.Length - 1, 1)
if (($first -eq '"' -and $last -eq '"') -or ($first -eq "'" -and $last -eq "'")) {
$value = $value.Substring(1, $value.Length - 2)
}
}
[Environment]::SetEnvironmentVariable($key, $value, "Process")
$applied++
}
}
if ($applied -gt 0) {
Write-LauncherLog "Loaded $applied .env override(s) from $EnvPath"
}
}
Set-EnvFromDotEnv -EnvPath (Join-Path $Root '.env')
if (Test-AgentTestInstance) {
[Environment]::SetEnvironmentVariable('VON_AGENT_TEST_INSTANCE', '1', 'Process')
}
else {
[Environment]::SetEnvironmentVariable('VON_AGENT_TEST_INSTANCE', $null, 'Process')
}
function Test-TruthySetting {
param([object]$Value)
if ($null -eq $Value) { return $false }
return $Value.ToString().Trim().ToLowerInvariant() -match '^(1|true|yes|y|on)$'
}
function Get-NormalisedAbsolutePath {
param([Parameter(Mandatory = $true)][string]$Path)
$expanded = [Environment]::ExpandEnvironmentVariables($Path)
try {
$full = [System.IO.Path]::GetFullPath($expanded)
}
catch {
$full = $expanded
}
return ($full -replace '/', '\').TrimEnd('\')
}
function Test-IsPathInsideRoot {
param(
[Parameter(Mandatory = $true)][string]$CandidatePath,
[Parameter(Mandatory = $true)][string]$RootPath
)
$candidate = Get-NormalisedAbsolutePath -Path $CandidatePath
$rootPathNormalised = Get-NormalisedAbsolutePath -Path $RootPath
if ($candidate.Equals($rootPathNormalised, [StringComparison]::OrdinalIgnoreCase)) {
return $true
}
return $candidate.StartsWith($rootPathNormalised + '\', [StringComparison]::OrdinalIgnoreCase)
}
$AllowRepoBackupOutput = Test-TruthySetting $env:VON_ALLOW_BACKUP_IN_REPO
function Test-BackupOutputPathAllowed {
param(
[Parameter(Mandatory = $true)][string]$Path,
[Parameter(Mandatory = $true)][string]$Context,
[Parameter(Mandatory = $true)][bool]$ApplyMode
)
if (-not (Test-IsPathInsideRoot -CandidatePath $Path -RootPath $Root)) {
return $true
}
$resolved = Get-NormalisedAbsolutePath -Path $Path
if ($AllowRepoBackupOutput) {
Write-LauncherLog "[$Context] WARN: backup output resolves inside repo root ($resolved), but continuing due to VON_ALLOW_BACKUP_IN_REPO=1."
return $true
}
if ($ApplyMode) {
Write-LauncherLog "[$Context] ERROR: refusing backup apply mode with output under repo root ($resolved). Set VON_BACKUP_ROOT/-BackupOutDir outside repo, or override with VON_ALLOW_BACKUP_IN_REPO=1."
return $false
}
Write-LauncherLog "[$Context] WARN: backup output is under repo root ($resolved). Dry-run allowed, apply mode remains blocked unless VON_ALLOW_BACKUP_IN_REPO=1."
return $true
}
# Backup root resolution:
# - Prefer explicit VON_BACKUP_ROOT if already present in environment.
# - Else prefer W:\von_backups if W: exists and is writable.
# - Else prefer a non-repo local path (%LOCALAPPDATA%\Von\backups).
# - Else fall back to repo-local 'backups' as a last resort.
$BackupRoot = $null
$script:DefaultNonRepoBackupRoot = $null
function Test-WDriveAvailable {
<#
Returns $true only when W: is present and reachable.
This is more defensive than Test-Path alone (network drives can throw).
#>
try {
$drive = Get-PSDrive -Name 'W' -ErrorAction Stop
if (-not $drive) { return $false }
try {
return [bool](Test-Path -LiteralPath 'W:\' -ErrorAction Stop)
}
catch {
return $false
}
}
catch {
return $false
}
}
function Resolve-BackupOutDir {
param(
[Parameter(Mandatory = $true)][string]$OutDir,
[Parameter(Mandatory = $true)][string]$FallbackDir,
[Parameter(Mandatory = $true)][string]$Reason
)
$effective = $OutDir
try {
if ($effective -match '^[Ww]:\\' -and -not (Test-WDriveAvailable)) {
Write-LauncherLog "[backup] WARN: W: drive unavailable ($Reason); falling back to local backups: $FallbackDir"
$effective = $FallbackDir
}
}
catch {
# Defensive: if any drive probing fails, fall back to local.
Write-LauncherLog "[backup] WARN: Backup destination probe failed ($Reason): $($_.Exception.Message); falling back to local backups: $FallbackDir"
$effective = $FallbackDir
}
try { New-Item -ItemType Directory -Force -Path $effective | Out-Null } catch { }
return $effective
}
function Get-BackupFallbackDir {
if ($script:DefaultNonRepoBackupRoot -and $script:DefaultNonRepoBackupRoot.ToString().Trim()) {
return $script:DefaultNonRepoBackupRoot
}
return (Join-Path $Root 'backups')
}
function Get-BackupArtifactSizeBytes {
param([Parameter(Mandatory = $true)][string]$Path)
try {
$item = Get-Item -LiteralPath $Path -ErrorAction Stop
}
catch {
return [int64]0
}
if (-not $item.PSIsContainer) {
return [int64]$item.Length
}
$total = [int64]0
try {
Get-ChildItem -LiteralPath $item.FullName -Recurse -File -ErrorAction Stop | ForEach-Object {
$total += [int64]$_.Length
}
}
catch {
return [int64]0
}
return $total
}
function Test-BackupArtifactPresentAndNonEmpty {
param([Parameter(Mandatory = $true)][string]$Path)
$exists = $false
try { $exists = [bool](Test-Path -LiteralPath $Path) } catch { $exists = $false }
if (-not $exists) {
return [pscustomobject]@{
Present = $false
SizeBytes = [int64]0
Verified = $false
}
}
$sizeBytes = Get-BackupArtifactSizeBytes -Path $Path
return [pscustomobject]@{
Present = $true
SizeBytes = [int64]$sizeBytes
Verified = ($sizeBytes -gt 0)
}
}
$localAppDataRoot = if ($env:LOCALAPPDATA -and $env:LOCALAPPDATA.ToString().Trim()) {
$env:LOCALAPPDATA.ToString().Trim()
}
else {
Join-Path $HOME 'AppData\Local'
}
$defaultCandidate = Join-Path $localAppDataRoot 'Von\backups'
try {
New-Item -ItemType Directory -Force -Path $defaultCandidate | Out-Null
$script:DefaultNonRepoBackupRoot = $defaultCandidate
}
catch {
Write-LauncherLog "[backup] WARN: Cannot create/write default non-repo backup root '$defaultCandidate'."
}
if ($env:VON_BACKUP_ROOT -and $env:VON_BACKUP_ROOT.ToString().Trim()) {
$preferred = $env:VON_BACKUP_ROOT.ToString().Trim().Trim('"')
try {
New-Item -ItemType Directory -Force -Path $preferred | Out-Null
$BackupRoot = $preferred
}
catch {
Write-LauncherLog "[backup] WARN: Cannot create/write VON_BACKUP_ROOT='$preferred'; falling back to automatic selection."
}
}
if (-not $BackupRoot -and (Test-WDriveAvailable)) {
$preferred = 'W:\von_backups'
try {
New-Item -ItemType Directory -Force -Path $preferred | Out-Null
$BackupRoot = $preferred
}
catch {
Write-LauncherLog "[backup] WARN: Cannot create/write $preferred; falling back to repo local backups."
}
}
if (-not $BackupRoot) {
if ($script:DefaultNonRepoBackupRoot) {
$BackupRoot = $script:DefaultNonRepoBackupRoot
}
else {
$BackupRoot = Join-Path $Root 'backups'
try { New-Item -ItemType Directory -Force -Path $BackupRoot | Out-Null } catch { }
Write-LauncherLog "[backup] WARN: Falling back to repo-local backups root '$BackupRoot'. Set VON_BACKUP_ROOT to an external path for safer defaults."
}
}
if (-not $BackupOutDir) {
$BackupOutDir = $BackupRoot
}
function Invoke-MigrateLocalBackupsToWDrive {
<#
If W: exists and local backups dir exists, move all but the most recent
timestamped backup artefact from local 'backups' into W:\von_backups.
Skips if backup root already is W:, or fewer than 2 local backups.
Moves both directories (<name>_YYYYMMDD_HHMMSS*) and zip artefacts
(<name>_YYYYMMDD_HHMMSS*.zip or .zip.enc).
Logs with [backup-migrate]. Failures on individual moves are warned and continue.
#>
$moved = 0
$copied = 0
if (-not (Test-WDriveAvailable)) { Write-LauncherLog "[backup-migrate] summary moved=$moved copied=$copied (no W: drive)"; return }
# Even if current backup root is already on W:, still attempt to migrate any residual local backups directory.
$localBackups = Join-Path $Root 'backups'
if (-not (Test-Path $localBackups)) {
try { New-Item -ItemType Directory -Force -Path $localBackups | Out-Null } catch { Write-LauncherLog "[backup-migrate] summary moved=$moved copied=$copied (cannot create local backups dir)"; return }
}
try {
$items = Get-ChildItem -Path $localBackups -ErrorAction Stop | Where-Object {
$_.PSIsContainer -or $_.Name -match '\.zip(\.enc)?$'
}
}
catch { $items = @() }
$candidates = $items | Where-Object {
$_.Name -match '_[0-9]{8}_[0-9]{6}Z?' -and (
$_.PSIsContainer -or $_.Name -match '\.zip(\.enc)?$'
)
}
$newest = $null; $toMove = @()
if ($candidates -and $candidates.Count -gt 0) {
$sorted = $candidates | Sort-Object LastWriteTime
$newest = $sorted[-1]
if ($sorted.Count -gt 1) { $toMove = $sorted[0..($sorted.Count - 2)] }
}
$destRoot = 'W:\von_backups'
if (-not (Test-Path $destRoot)) {
try { New-Item -ItemType Directory -Force -Path $destRoot | Out-Null } catch { Write-LauncherLog "[backup-migrate] summary moved=$moved copied=$copied (create dest failed)"; return }
}
if ($toMove.Count -gt 0) {
foreach ($item in $toMove) {
$dest = Join-Path $destRoot $item.Name
if (Test-Path $dest) {
Write-Verbose ("[backup-migrate] Skipping existing {0} already on W:" -f $item.Name)
continue
}
try {
Write-LauncherLog "[backup-migrate] Moving $($item.Name) -> $destRoot"
Move-Item -Path $item.FullName -Destination $dest -Force -ErrorAction Stop
$moved++
$verification = Test-BackupArtifactPresentAndNonEmpty -Path $dest
if ($verification.Verified) {
Write-LauncherLog "[backup-migrate] Verified offsite artefact $dest size_bytes=$($verification.SizeBytes)"
}
else {
Write-LauncherLog "[backup-migrate] WARN offsite verification failed after move: $dest"
}
}
catch {
Write-LauncherLog "[backup-migrate] WARN move failed $($item.Name): $($_.Exception.Message)"
}
}
}
if ($newest -and -not (Test-Path (Join-Path $destRoot $newest.Name))) {
try {
Write-LauncherLog "[backup-migrate] Copying newest $($newest.Name) to W: (preserve local copy)"
if ($newest.PSIsContainer) {
Copy-Item -Path $newest.FullName -Destination (Join-Path $destRoot $newest.Name) -Recurse -Force -ErrorAction Stop
}
else {
Copy-Item -Path $newest.FullName -Destination (Join-Path $destRoot $newest.Name) -Force -ErrorAction Stop
}
$copied++
$copiedDest = Join-Path $destRoot $newest.Name
$verification = Test-BackupArtifactPresentAndNonEmpty -Path $copiedDest
if ($verification.Verified) {
Write-LauncherLog "[backup-migrate] Verified offsite artefact $copiedDest size_bytes=$($verification.SizeBytes)"
}
else {
Write-LauncherLog "[backup-migrate] WARN offsite verification failed after copy: $copiedDest"
}
}
catch {
Write-LauncherLog "[backup-migrate] WARN copy newest failed $($newest.Name): $($_.Exception.Message)"
}
}
# Down-sync: if W: holds a newer backup than local newest (or local newest missing), copy newest W: back locally
try {
$wBackups = Get-ChildItem -Path $destRoot -ErrorAction Stop | Where-Object {
$_.Name -match '_[0-9]{8}_[0-9]{6}Z?' -and (
$_.PSIsContainer -or $_.Name -match '\.zip(\.enc)?$'
)
}
if ($wBackups) {
$wSorted = $wBackups | Sort-Object LastWriteTime
$wNewest = $wSorted[-1]
$localNewestPath = if ($newest) { $newest.FullName } else { $null }
$needsDownSync = $false
if (-not $localNewestPath) { $needsDownSync = $true }
else {
try {
$localNewestItem = Get-Item -LiteralPath $localNewestPath -ErrorAction Stop
if ($wNewest.LastWriteTime -gt $localNewestItem.LastWriteTime) { $needsDownSync = $true }
}
catch { $needsDownSync = $true }
}
if ($needsDownSync -and $wNewest) {
$destLocal = Join-Path $localBackups $wNewest.Name
if (-not (Test-Path $destLocal)) {
try {
Write-LauncherLog "[backup-migrate] Down-sync newer $($wNewest.Name) -> local backups"
if ($wNewest.PSIsContainer) {
Copy-Item -Path $wNewest.FullName -Destination $destLocal -Recurse -Force -ErrorAction Stop
}
else {
Copy-Item -Path $wNewest.FullName -Destination $destLocal -Force -ErrorAction Stop
}
}
catch { Write-LauncherLog "[backup-migrate] WARN down-sync failed $($wNewest.Name): $($_.Exception.Message)" }
}
}
}
}
catch { Write-LauncherLog "[backup-migrate] WARN down-sync scan failed: $($_.Exception.Message)" }
Write-LauncherLog "[backup-migrate] summary moved=$moved copied=$copied"
}
if (Test-AgentTestInstance) {
Write-Host "[backup-migrate] disabled via -AgentTest"
}
elseif (-not $NoBackupMigrate) {
Invoke-MigrateLocalBackupsToWDrive
}
else {
Write-Host "[backup-migrate] disabled via -NoBackupMigrate"
}
# Sentinel file to ensure we open the browser only once automatically. Agent
# test instances are normally headless, but keep their forced-browser sentinel
# separate so acceptance runs cannot suppress the user's next normal start.
$BrowserSentinelName = if (Test-AgentTestInstance) { "browser_opened_once_${Port}" } else { 'browser_opened_once' }
$BrowserSentinel = Join-Path $RunDir $BrowserSentinelName
$WorkflowPurityPidFile = Join-Path $RunDir 'workflow_purity_check.pid'
$WorkflowPurityResultFile = Join-Path $RunDir 'workflow_purity_check_last_result.json'
$WorkflowPurityReportedFile = Join-Path $RunDir 'workflow_purity_check_last_reported.txt'
$WorkflowPurityRunnerScript = Join-Path $RunDir 'workflow_purity_runner.ps1'
# PID & log paths (port-scoped for isolated launcher instances)
$PidFile = Join-Path $RunDir "von_${Port}.pid"
$CurrentLog = Join-Path $LogsDir "von_${Port}_current.log"
$Timestamp = Get-Date -Format 'yyyyMMdd_HHmmss'
$NewLog = Join-Path $LogsDir "von_${Port}_${Timestamp}.log"
$RagPidFile = Join-Path $RunDir "rag_worker.pid"
$RagLogFile = Join-Path $LogsDir "rag_worker_${Timestamp}.log"
$ConceptIndexPidFile = Join-Path $RunDir "concept_index_worker.pid"
$ConceptIndexLogFile = Join-Path $LogsDir "concept_index_worker_${Timestamp}.log"
$script:RepairAttempted = $false
function Get-ExistingProcess {
if (-not (Test-Path $PidFile)) { return $null }
$content = Get-Content $PidFile -ErrorAction SilentlyContinue | Where-Object { $_ }
if (-not $content) { return $null }
$pidLine = $content | Select-Object -First 1
if ($pidLine -notmatch 'PID=([0-9]+)') { return $null }
$savedPid = [int]$Matches[1]
try { $p = Get-Process -Id $savedPid -ErrorAction Stop; return $p } catch { return $null }
}
function Get-ListeningProcessByPort {
param([int]$Port)
try {
if (-not $IsWindows) {
$lsof = Get-Command lsof -ErrorAction SilentlyContinue
if ($lsof) {
$lines = & $lsof.Source -nP "-iTCP:$Port" -sTCP:LISTEN -Fp 2>$null
foreach ($line in $lines) {
if ($line -notmatch '^p(\d+)$') { continue }
return (Get-Process -Id ([int]$Matches[1]) -ErrorAction Stop)
}
}
}
# Get-NetTCPConnection can hang on some hosts; parse netstat output instead.
$lines = netstat -ano -p tcp 2>$null
foreach ($line in $lines) {
if ($line -notmatch '^\s*TCP\s+') { continue }
$parts = (($line -replace '\s+', ' ').Trim() -split ' ')
if ($parts.Count -lt 5) { continue }
$localAddress = $parts[1]
$state = $parts[3]
$pidToken = $parts[4]
if ($state -ne 'LISTENING') { continue }
if ($localAddress -notmatch ':(\d+)$') { continue }
if ([int]$Matches[1] -ne $Port) { continue }
if ($pidToken -notmatch '^\d+$') { continue }
return (Get-Process -Id ([int]$pidToken) -ErrorAction Stop)
}
}
catch { }
return $null
}
function Get-ProcessCommandLine {
param([int]$ProcessId)
try {
return (Get-CimInstance Win32_Process -Filter "ProcessId=$ProcessId" | Select-Object -ExpandProperty CommandLine)
}
catch {
return ''
}
}
function Get-ProjectPythonExecutable {
$candidatePaths = @()
$pdmPythonPath = Join-Path $Root '.pdm-python'
if (Test-Path $pdmPythonPath) {
$recordedPython = (Get-Content $pdmPythonPath -Raw -ErrorAction SilentlyContinue).Trim()
if ($recordedPython) {
$candidatePaths += $recordedPython
}
}
$candidatePaths += (Join-Path $Root '.venv\Scripts\python.exe')
foreach ($candidatePath in $candidatePaths) {
if (-not (Test-Path $candidatePath)) {
continue
}
try {
& $candidatePath -c "import sys" 1>$null 2>$null
if ($LASTEXITCODE -eq 0) {
return $candidatePath
}
}
catch { }
}
return 'python'
}
function Stop-ProcessTreeWithEscalation {
param(
[Parameter(Mandatory = $true)][int]$ProcessId,
[int]$WaitMs = 10000
)
if ($ProcessId -le 0) { return $true }
try { & taskkill /PID $ProcessId /T /F 1>$null 2>$null } catch { }
$elapsedMs = 0
while ($elapsedMs -lt $WaitMs) {
Start-Sleep -Milliseconds 500
if (-not (Get-Process -Id $ProcessId -ErrorAction SilentlyContinue)) { return $true }
$elapsedMs += 500
}
try { Stop-Process -Id $ProcessId -Force -ErrorAction SilentlyContinue } catch { }
Start-Sleep -Milliseconds 250
return (-not (Get-Process -Id $ProcessId -ErrorAction SilentlyContinue))
}
function Stop-PythonProcessesByScript {
param(
[Parameter(Mandatory = $true)][string]$ScriptRelativePath,
[Parameter(Mandatory = $true)][string]$Label,
[int]$ExcludePid = 0
)
$pythonExe = Get-ProjectPythonExecutable
$scriptPath = Join-Path $Root $ScriptRelativePath
$helperScript = Join-Path $Root 'scripts/cleanup_stale_python_processes.py'
if (-not (Test-Path $helperScript)) {
Write-LauncherLog ("WARN: Stale-process cleanup helper missing for {0}: {1}" -f $Label, $helperScript)
return
}
$raw = @()
try {
# Use a file-backed helper rather than `python -c` to avoid native-command
# argument parsing regressions in newer PowerShell hosts.
$raw = & $pythonExe $helperScript $scriptPath $ExcludePid 2>$null
}
catch {
Write-LauncherLog ("WARN: Failed stale-process cleanup for {0}: {1}" -f $Label, $_.Exception.Message)
return
}
if (-not $raw) { return }
$lastLine = ($raw | Select-Object -Last 1)
if (-not $lastLine) { return }
try {
$killed = ConvertFrom-Json $lastLine
if ($killed -and $killed.Count -gt 0) {
Write-LauncherLog ("Stopped stale {0} process(es): {1}" -f $Label, ($killed -join ', '))
}
}
catch { }
}
function Test-IsVonMainProcess {
param([int]$ProcessId)
$cmdLine = Get-ProcessCommandLine -ProcessId $ProcessId
if (-not $cmdLine) { return $false }
$normalisedCmd = $cmdLine.ToLowerInvariant().Replace('\', '/')
$normalisedRoot = $Root.ToLowerInvariant().Replace('\', '/')
if (-not $normalisedCmd.Contains('src/workflows/von/main.py')) { return $false }
if (-not $normalisedCmd.Contains($normalisedRoot)) { return $false }
return $true
}
function Stop-ProcessWithEscalation {
param(
[Parameter(Mandatory = $true)][int]$ProcessId,
[int]$WaitMs = 10000
)
try { Stop-Process -Id $ProcessId -ErrorAction SilentlyContinue } catch { }
$elapsedMs = 0
while ($elapsedMs -lt $WaitMs) {
Start-Sleep -Milliseconds 500
if (-not (Get-Process -Id $ProcessId -ErrorAction SilentlyContinue)) { return $true }
$elapsedMs += 500
}
try { Stop-Process -Id $ProcessId -Force -ErrorAction SilentlyContinue } catch { }
Start-Sleep -Milliseconds 250
return (-not (Get-Process -Id $ProcessId -ErrorAction SilentlyContinue))
}
function Invoke-RestartPortTakeover {
param([Parameter(Mandatory = $true)]$Listener)
$listenerPid = [int]$Listener.Id
if (-not (Test-IsVonMainProcess -ProcessId $listenerPid)) {
Write-LauncherLog ("Port {0} is owned by PID={1}, which does not look like this Von server. Aborting restart takeover." -f $Port, $listenerPid)
return $false
}
Write-LauncherLog ("Restart takeover: stopping untracked Von listener PID={0} on port {1}..." -f $listenerPid, $Port)
$stopped = Stop-ProcessWithEscalation -ProcessId $listenerPid
if (-not $stopped) {
Write-LauncherLog ("Failed to stop PID={0}; restart cannot continue safely." -f $listenerPid)
return $false
}
$remaining = Get-ListeningProcessByPort -Port $Port
if ($remaining) {
Write-LauncherLog ("Port {0} is still in use by PID={1} after takeover attempt; aborting start." -f $Port, $remaining.Id)
return $false
}
Write-LauncherLog ("Restart takeover succeeded; port {0} is clear." -f $Port)
return $true
}
function Read-AdminToken {
if ($AdminToken) { return $AdminToken }
$tokenFile = Join-Path $RunDir 'admin_token.txt'
if (Test-Path $tokenFile) { return (Get-Content $tokenFile -Raw).Trim() }
$gen = [guid]::NewGuid().ToString('N')
Set-Content $tokenFile $gen
return $gen
}
function Get-MongoConnectionSummary {
param([int]$Port)
try {
$resp = Invoke-RestMethod -Uri "http://localhost:$Port/api/system/db_status" -TimeoutSec 5
if ($null -eq $resp) { return "Mongo: unknown" }
$usingFallback = $resp.using_fallback
$atlasDetected = $resp.atlas_detected
$effectiveHost = $resp.effective_host
if ($usingFallback -eq $true) {
if ($effectiveHost) { return "Mongo: local fallback ($effectiveHost)" }
return "Mongo: local fallback"
}
if ($atlasDetected -eq $true) {
if ($effectiveHost) { return "Mongo: Atlas ($effectiveHost)" }
return "Mongo: Atlas"
}
if ($effectiveHost) { return "Mongo: $effectiveHost" }
return "Mongo: unknown"
}
catch {
return "Mongo: status unavailable"
}
}
function Invoke-VonLogRotation {
# was Rotate-Logs
# Keep a fixed number of logs per port
$pattern = "von_${Port}_*.log"
$files = Get-ChildItem -Path $LogsDir -Filter $pattern | Sort-Object LastWriteTime -Descending
if ($files.Count -gt $LogRetention) {
$filesToDelete = $files | Select-Object -Skip $LogRetention
foreach ($f in $filesToDelete) { Remove-Item $f.FullName -Force -ErrorAction SilentlyContinue }
}
}
function Write-PidFile {
param($ServerPid)
$startIso = (Get-Date).ToString('o')
Set-Content $PidFile "PID=$ServerPid`nPORT=$Port`nSTART=$startIso"
}
function Remove-PidFile { if (Test-Path $PidFile) { Remove-Item $PidFile -Force -ErrorAction SilentlyContinue } }
# Daily remote backup logic (auto every 24h) ---------------------------------
function Find-NextAllowedValue {
param(
[Parameter(Mandatory = $true)] [int[]]$AllowedValues,
[Parameter(Mandatory = $true)] [int]$Start
)
foreach ($v in $AllowedValues) {
if ($v -ge $Start) { return $v }
}
return $null
}
function Convert-CronTokenToInt {
param(
[Parameter(Mandatory = $true)] [string]$Token,
[Parameter(Mandatory = $true)] [int]$Min,
[Parameter(Mandatory = $true)] [int]$Max,
[Parameter(Mandatory = $false)] [hashtable]$NameMap,
[Parameter(Mandatory = $false)] [switch]$IsDayOfWeek
)
$t = $Token.Trim()
if ($t -match '^\d+$') {
$v = [int]$t
if ($IsDayOfWeek -and $v -eq 7) { $v = 0 }
if ($v -lt $Min -or $v -gt $Max) { throw "Cron value '$t' out of bounds [$Min,$Max]." }
return $v
}
if ($NameMap) {
$k = $t.ToUpperInvariant()
if ($NameMap.ContainsKey($k)) {
$v = [int]$NameMap[$k]
if ($IsDayOfWeek -and $v -eq 7) { $v = 0 }
if ($v -lt $Min -or $v -gt $Max) { throw "Cron value '$t' out of bounds [$Min,$Max]." }
return $v
}
}
throw "Unsupported cron token '$t'."
}
function ConvertFrom-CronField {
param(
[Parameter(Mandatory = $true)] [string]$Field,
[Parameter(Mandatory = $true)] [int]$Min,
[Parameter(Mandatory = $true)] [int]$Max,
[Parameter(Mandatory = $false)] [switch]$IsDayOfWeek,
[Parameter(Mandatory = $false)] [hashtable]$NameMap
)
$fieldTrim = $Field.Trim()
if (-not $fieldTrim) { throw "Invalid cron field (empty)." }
$allowed = New-Object 'System.Boolean[]' ($Max + 1)
$isStar = $false
if ($fieldTrim -eq '*') {
$isStar = $true
for ($i = $Min; $i -le $Max; $i++) { $allowed[$i] = $true }
}
else {
$parts = $fieldTrim -split ','
foreach ($rawPart in $parts) {
$part = $rawPart.Trim()
if (-not $part) { continue }
# Supported forms: *, */n, a, a-b, a/n, a-b/n (lists via commas)
if (-not ($part -match '^(?<base>[^/]+?)(?:\/(?<step>\d+))?$')) {
throw "Unsupported cron token '$part' in field '$Field'."
}
$base = $Matches['base'].Trim()
$step = 1
if ($Matches['step']) {
$step = [int]$Matches['step']
if ($step -lt 1) { throw "Invalid cron step '/$step' in field '$Field'." }
}
$start = $null
$end = $null
if ($base -eq '*') {
$start = $Min
$end = $Max
}
elseif ($base -match '^(?<a>[^-]+)-(?<b>[^-]+)$') {
$start = Convert-CronTokenToInt -Token $Matches['a'] -Min $Min -Max $Max -NameMap $NameMap -IsDayOfWeek:$IsDayOfWeek
$end = Convert-CronTokenToInt -Token $Matches['b'] -Min $Min -Max $Max -NameMap $NameMap -IsDayOfWeek:$IsDayOfWeek
}
else {
$start = Convert-CronTokenToInt -Token $base -Min $Min -Max $Max -NameMap $NameMap -IsDayOfWeek:$IsDayOfWeek
$end = $start
}
if ($start -lt $Min -or $end -gt $Max -or $start -gt $end) {
throw "Cron value range '$base' out of bounds [$Min,$Max] in field '$Field'."
}
for ($v = $start; $v -le $end; $v += $step) {
$vv = $v
if ($IsDayOfWeek -and $vv -eq 7) { $vv = 0 }
$allowed[$vv] = $true
}
}
}
$allowedValues = @()
for ($i = $Min; $i -le $Max; $i++) {
if ($allowed[$i]) { $allowedValues += $i }
}
# NOTE: Do not use `-not $allowedValues` here; a single value of 0 (e.g. minute=0)
# is treated as falsy in PowerShell, which incorrectly rejects valid cron fields.
if ($null -eq $allowedValues -or $allowedValues.Count -eq 0) {
throw "Cron field '$Field' selects no values."
}
return @{
Allowed = $allowed
AllowedValues = [int[]]$allowedValues
IsStar = $isStar
Min = $Min
Max = $Max
}
}
function ConvertFrom-CronSchedule {
param([Parameter(Mandatory = $true)] [string]$Schedule)
$tokens = ($Schedule.Trim() -split '\s+')
if ($tokens.Count -ne 5) {
throw "Cron schedule must have 5 fields: '<minute> <hour> <day-of-month> <month> <day-of-week>'."
}
$monthNames = @{
'JAN' = 1; 'FEB' = 2; 'MAR' = 3; 'APR' = 4; 'MAY' = 5; 'JUN' = 6;
'JUL' = 7; 'AUG' = 8; 'SEP' = 9; 'OCT' = 10; 'NOV' = 11; 'DEC' = 12
}
$dowNames = @{
'SUN' = 0; 'MON' = 1; 'TUE' = 2; 'WED' = 3; 'THU' = 4; 'FRI' = 5; 'SAT' = 6
}
$minute = ConvertFrom-CronField -Field $tokens[0] -Min 0 -Max 59
$hour = ConvertFrom-CronField -Field $tokens[1] -Min 0 -Max 23
$dom = ConvertFrom-CronField -Field $tokens[2] -Min 1 -Max 31
$month = ConvertFrom-CronField -Field $tokens[3] -Min 1 -Max 12 -NameMap $monthNames
$dow = ConvertFrom-CronField -Field $tokens[4] -Min 0 -Max 7 -IsDayOfWeek -NameMap $dowNames
return @{
Minute = $minute
Hour = $hour
DayOfMonth = $dom
Month = $month
DayOfWeek = $dow
Raw = $Schedule
}
}
function ConvertTo-CronSchedule {
param([Parameter(Mandatory = $true)] [string]$Schedule)
$clean = $Schedule.Trim()
if (-not $clean) { return $clean }
# Strip inline comments (e.g. "... # note")
$hashIndex = $clean.IndexOf('#')
if ($hashIndex -ge 0) {
$clean = $clean.Substring(0, $hashIndex).Trim()
}
# Remove stray wrapping quotes
$clean = $clean -replace "^[\""']+", ''
$clean = $clean -replace "[\""']+$", ''
# If extra tokens exist, keep only the first 5 cron fields
$tokens = ($clean -split '\s+')