-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrun.sh
More file actions
executable file
·3761 lines (3525 loc) · 127 KB
/
Copy pathrun.sh
File metadata and controls
executable file
·3761 lines (3525 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
#!/usr/bin/env bash
set -euo pipefail
SCRIPT_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ROOT="${VON_LAUNCHER_ROOT:-$SCRIPT_ROOT}"
if [ ! -d "$ROOT" ]; then
echo "ERROR: VON_LAUNCHER_ROOT is not a directory: $ROOT" >&2
exit 2
fi
ROOT="$(cd "$ROOT" && pwd -P)"
log() {
# Match run.ps1: lightweight timestamped console logs.
local ts
ts="$(date +%H:%M:%S 2>/dev/null || true)"
echo "[${ts}] $*"
}
RUN_DIR="${ROOT}/.run"
LOGS_DIR="${ROOT}/logs"
mkdir -p "${RUN_DIR}" "${LOGS_DIR}" 2>/dev/null || true
ACTION="${1:-start}"
ACTION="$(printf '%s' "$ACTION" | tr '[:upper:]' '[:lower:]')"
if [[ "$ACTION" == "--help" || "$ACTION" == "-h" || "$ACTION" == "/?" ]]; then
ACTION="help"
fi
shift 1 || true
# Defaults (match run.ps1): macOS avoids AirPlay Receiver's common port 5000.
DEFAULT_PORT=5000
if [[ "$(uname -s 2>/dev/null || true)" == "Darwin" ]]; then
DEFAULT_PORT=5001
fi
PORT="$DEFAULT_PORT"
PORT_EXPLICIT=0
AGENT_TEST=0
ISOLATED_TEST_INSTANCE=0
AGENT_TEST_INSTANCE=0
NO_BROWSER=0
FORCE_BROWSER=0
CHROME_BETA=0
TAIL=100
FOLLOW=0
LOG_RETENTION=20
ADMIN_TOKEN=""
SKIP_HEALTH=0
HEALTH_TIMEOUT_SEC=960
HEALTH_GRACE_SEC=45
BACKUP_DRY_RUN=0
BACKUP_TAG="manual"
BACKUP_OUT_DIR=""
RESTORE_BACKUP_PATH=""
RESTORE_TARGET_DB_NAME=""
RESTORE_APPLY=0
RESTORE_DROP_TARGET=0
UPDATE_INTERVAL_MINUTES=60
UPDATE_BRANCH="main"
UPDATE_NO_RESTART_IF_RUNNING=0
NO_BACKUP_MIGRATE=0
DISABLE_LOG_READY=0
HEALTH_DEBUG=0
SHOW_RELATION_COVERAGE=0
STATUS_RUN_MAINTENANCE=0
RUNTIME_WORKTREE_PATH=""
BACKUP_FLAGS_SET=0
READY_LOG_PATTERNS=("Running with Waitress" "Press CTRL+C to quit" "Flask app running")
EXTRA_ARGS=()
while [ $# -gt 0 ]; do
case "$1" in
-Port) PORT="$2"; PORT_EXPLICIT=1; shift 2 ;;
--port|--Port) PORT="$2"; PORT_EXPLICIT=1; shift 2 ;;
-AgentTest|--AgentTest) AGENT_TEST=1; shift ;;
-IsolatedTestInstance|--IsolatedTestInstance) ISOLATED_TEST_INSTANCE=1; shift ;;
-NoBrowser|--NoBrowser) NO_BROWSER=1; shift ;;
--no-browser|-n) NO_BROWSER=1; shift ;;
-ForceBrowser|--ForceBrowser) FORCE_BROWSER=1; shift ;;
--force-browser|-f) FORCE_BROWSER=1; shift ;;
-ChromeBeta|--ChromeBeta) CHROME_BETA=1; shift ;;
-Tail) TAIL="$2"; shift 2 ;;
--tail|--Tail) TAIL="$2"; shift 2 ;;
-Follow) FOLLOW=1; shift ;;
--follow) FOLLOW=1; shift ;;
-LogRetention) LOG_RETENTION="$2"; shift 2 ;;
-AdminToken) ADMIN_TOKEN="$2"; shift 2 ;;
-SkipHealth|--SkipHealth) SKIP_HEALTH=1; shift ;;
--skip-health) SKIP_HEALTH=1; shift ;;
-HealthTimeoutSec) HEALTH_TIMEOUT_SEC="$2"; shift 2 ;;
-HealthGraceSec) HEALTH_GRACE_SEC="$2"; shift 2 ;;
-ReadyLogPatterns)
if [ $# -ge 2 ]; then
IFS=',' read -r -a READY_LOG_PATTERNS <<<"$2"
# Trim whitespace on each pattern.
for i in "${!READY_LOG_PATTERNS[@]}"; do
local_pattern="${READY_LOG_PATTERNS[$i]}"
local_pattern="${local_pattern#"${local_pattern%%[![:space:]]*}"}"
local_pattern="${local_pattern%"${local_pattern##*[![:space:]]}"}"
READY_LOG_PATTERNS[$i]="$local_pattern"
done
fi
shift 2
;;
-DisableLogReady) DISABLE_LOG_READY=1; shift ;;
-HealthDebug) HEALTH_DEBUG=1; shift ;;
-ShowRelationCoverage) SHOW_RELATION_COVERAGE=1; shift ;;
-StatusRunMaintenance) STATUS_RUN_MAINTENANCE=1; shift ;;
-RuntimeWorktree|--RuntimeWorktree|--runtime-worktree) RUNTIME_WORKTREE_PATH="$2"; shift 2 ;;
-BackupDryRun) BACKUP_DRY_RUN=1; BACKUP_FLAGS_SET=1; shift ;;
-BackupTag) BACKUP_TAG="$2"; BACKUP_FLAGS_SET=1; shift 2 ;;
-BackupOutDir) BACKUP_OUT_DIR="$2"; BACKUP_FLAGS_SET=1; shift 2 ;;
-RestoreBackupPath) RESTORE_BACKUP_PATH="$2"; shift 2 ;;
-RestoreTargetDbName) RESTORE_TARGET_DB_NAME="$2"; shift 2 ;;
-RestoreApply) RESTORE_APPLY=1; shift ;;
-RestoreDropTarget) RESTORE_DROP_TARGET=1; shift ;;
-UpdateIntervalMinutes) UPDATE_INTERVAL_MINUTES="$2"; shift 2 ;;
-UpdateBranch) UPDATE_BRANCH="$2"; shift 2 ;;
-UpdateNoRestartIfRunning) UPDATE_NO_RESTART_IF_RUNNING=1; shift ;;
-NoBackupMigrate) NO_BACKUP_MIGRATE=1; shift ;;
*)
# Keep parity with run.ps1's 'ExtraArgs' behaviour: stash unrecognised args.
EXTRA_ARGS+=("$1")
shift
;;
esac
done
if [ "$AGENT_TEST" -eq 1 ] || [ "$ISOLATED_TEST_INSTANCE" -eq 1 ]; then
AGENT_TEST_INSTANCE=1
fi
if [ "$AGENT_TEST_INSTANCE" -eq 1 ]; then
if [ "$PORT_EXPLICIT" -eq 0 ]; then
PORT=5010
fi
if [ "$FORCE_BROWSER" -eq 0 ]; then
NO_BROWSER=1
fi
fi
load_env_from_dotenv() {
local env_path="$1"
if [ -z "$env_path" ] || [ ! -f "$env_path" ]; then
return 0
fi
local applied=0
local line=""
local trimmed=""
local key=""
local value=""
local first_char=""
local last_char=""
while IFS= read -r line || [ -n "$line" ]; do
# Handle CRLF files safely.
line="${line%$'\r'}"
trimmed="$line"
trimmed="${trimmed#"${trimmed%%[![:space:]]*}"}"
trimmed="${trimmed%"${trimmed##*[![:space:]]}"}"
if [ -z "$trimmed" ]; then
continue
fi
if [[ "$trimmed" == \#* ]]; then
continue
fi
if [[ "$trimmed" =~ ^([A-Za-z_][A-Za-z0-9_]*)[[:space:]]*=[[:space:]]*(.*)$ ]]; then
key="${BASH_REMATCH[1]}"
value="${BASH_REMATCH[2]}"
value="${value#"${value%%[![:space:]]*}"}"
value="${value%"${value##*[![:space:]]}"}"
if [ "${#value}" -ge 2 ]; then
first_char="${value:0:1}"
last_char="${value:${#value}-1:1}"
if [[ "$first_char" == '"' && "$last_char" == '"' ]] || [[ "$first_char" == "'" && "$last_char" == "'" ]]; then
value="${value:1:${#value}-2}"
fi
fi
printf -v "$key" '%s' "$value"
export "$key"
applied=$((applied + 1))
fi
done < "$env_path"
if [ "$applied" -gt 0 ]; then
log "Loaded $applied .env override(s) from $env_path"
fi
}
# Backup path and policy globals below must see the same .env values as the
# eventual backup process. Load them before resolving roots or migrating data.
load_env_from_dotenv "${ROOT}/.env"
PID_FILE="${RUN_DIR}/von_${PORT}.pid"
CURRENT_LOG="${LOGS_DIR}/von_${PORT}_current.log"
TS="$(date +%Y%m%d_%H%M%S 2>/dev/null || date +%Y%m%d_%H%M%S)"
NEW_LOG="${LOGS_DIR}/von_${PORT}_${TS}.log"
SERVER_ERR_LOG="${NEW_LOG}.err"
RAG_PID_FILE="${RUN_DIR}/rag_worker.pid"
RAG_LOG_FILE="${LOGS_DIR}/rag_worker_${TS}.log"
RAG_ERR_LOG_FILE="${RAG_LOG_FILE}.err"
CONCEPT_INDEX_PID_FILE="${RUN_DIR}/concept_index_worker.pid"
CONCEPT_INDEX_LOG_FILE="${LOGS_DIR}/concept_index_worker_${TS}.log"
CONCEPT_INDEX_ERR_LOG_FILE="${CONCEPT_INDEX_LOG_FILE}.err"
TOKEN_FILE="${RUN_DIR}/admin_token.txt"
WORKFLOW_PURITY_SUCCESS_FILE="${RUN_DIR}/workflow_purity_check_last_success.env"
WORKFLOW_PURITY_TTL_SECONDS="${VON_WORKFLOW_PURITY_TTL_SECONDS:-86400}"
BROWSER_SENTINEL_NAME="browser_opened_once"
if [ "$AGENT_TEST_INSTANCE" -eq 1 ]; then
BROWSER_SENTINEL_NAME="browser_opened_once_${PORT}"
fi
SENTINEL_BROWSER="${RUN_DIR}/${BROWSER_SENTINEL_NAME}"
LOCAL_BACKUPS="${ROOT}/backups"
BACKUP_ROOT=""
REMOTE_BACKUP_ROOT=""
REPAIR_ATTEMPTED=0
ALLOW_REPO_BACKUP_OUTPUT=0
case "${VON_ALLOW_BACKUP_IN_REPO:-}" in
1|true|TRUE|yes|YES|y|Y|on|ON) ALLOW_REPO_BACKUP_OUTPUT=1 ;;
esac
same_path() {
local a="$1"
local b="$2"
if [ -z "$a" ] || [ -z "$b" ]; then
return 1
fi
local ra=""
local rb=""
ra="$(cd "$a" 2>/dev/null && pwd -P)" || return 1
rb="$(cd "$b" 2>/dev/null && pwd -P)" || return 1
[ "$ra" = "$rb" ]
}
normalise_path() {
local input_path="$1"
if [ -z "$input_path" ]; then
return 1
fi
local expanded="$input_path"
if [ "${expanded#\~}" != "$expanded" ]; then
expanded="${HOME}${expanded#\~}"
fi
local dir_part
local base_part
dir_part="$(dirname "$expanded")"
base_part="$(basename "$expanded")"
if [ "$dir_part" = "." ]; then
dir_part="$PWD"
fi
local abs_dir
abs_dir="$(cd "$dir_part" 2>/dev/null && pwd -P)" || return 1
printf '%s/%s' "$abs_dir" "$base_part"
}
is_path_inside_root() {
local candidate="$1"
local root_path="$2"
local candidate_abs=""
local root_abs=""
candidate_abs="$(normalise_path "$candidate")" || return 1
root_abs="$(normalise_path "$root_path")" || return 1
if [ "$candidate_abs" = "$root_abs" ]; then
return 0
fi
case "$candidate_abs" in
"$root_abs"/*) return 0 ;;
esac
return 1
}
backup_output_path_allowed() {
local path="$1"
local context="$2"
local apply_mode="$3"
if ! is_path_inside_root "$path" "$ROOT"; then
return 0
fi
local resolved
resolved="$(normalise_path "$path" 2>/dev/null || printf '%s' "$path")"
if [ "$ALLOW_REPO_BACKUP_OUTPUT" -eq 1 ]; then
log "[$context] WARN: backup output resolves inside repo root ($resolved), but continuing due to VON_ALLOW_BACKUP_IN_REPO=1."
return 0
fi
if [ "$apply_mode" = "1" ]; then
log "[$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 1
fi
log "[$context] WARN: backup output is under repo root ($resolved). Dry-run allowed, apply mode remains blocked unless VON_ALLOW_BACKUP_IN_REPO=1."
return 0
}
resolve_backup_root() {
local preferred=""
if [ -n "${VON_BACKUP_ROOT:-}" ]; then
preferred="${VON_BACKUP_ROOT}"
preferred="${preferred#\"}"
preferred="${preferred%\"}"
if mkdir -p "$preferred" 2>/dev/null; then
BACKUP_ROOT="$preferred"
else
log "[backup] WARN: Cannot create/write VON_BACKUP_ROOT='${preferred}'; falling back to automatic selection."
fi
fi
REMOTE_BACKUP_ROOT=""
if [ -d "/Volumes/von_backups" ] && [ -w "/Volumes/von_backups" ]; then
REMOTE_BACKUP_ROOT="/Volumes/von_backups"
elif [ -d "/mnt/von_backups" ] && [ -w "/mnt/von_backups" ]; then
REMOTE_BACKUP_ROOT="/mnt/von_backups"
fi
if [ -z "$BACKUP_ROOT" ]; then
if [ -n "$REMOTE_BACKUP_ROOT" ]; then
BACKUP_ROOT="$REMOTE_BACKUP_ROOT"
else
BACKUP_ROOT="$LOCAL_BACKUPS"
fi
fi
mkdir -p "$BACKUP_ROOT" 2>/dev/null || true
}
resolve_backup_out_dir() {
local requested="$1"
local fallback="$2"
local reason="$3"
local effective="$requested"
if [ -z "$effective" ]; then
effective="$fallback"
fi
if ! mkdir -p "$effective" 2>/dev/null; then
log "[backup] WARN: Cannot create/write ${effective} (${reason}); falling back to local backups: ${fallback}"
effective="$fallback"
mkdir -p "$effective" 2>/dev/null || true
fi
printf '%s' "$effective"
}
mtime_epoch() {
local path="$1"
if command -v stat >/dev/null 2>&1; then
if stat -c %Y "$path" >/dev/null 2>&1; then
stat -c %Y "$path" 2>/dev/null || true
return 0
fi
if stat -f %m "$path" >/dev/null 2>&1; then
stat -f %m "$path" 2>/dev/null || true
return 0
fi
fi
return 1
}
migrate_local_backups() {
local moved=0
local copied=0
local remote_root="$REMOTE_BACKUP_ROOT"
if [ -z "$remote_root" ]; then
log "[backup-migrate] summary moved=$moved copied=$copied (no remote backup root)"
return 0
fi
if [ ! -d "$LOCAL_BACKUPS" ]; then
mkdir -p "$LOCAL_BACKUPS" 2>/dev/null || {
log "[backup-migrate] summary moved=$moved copied=$copied (cannot create local backups dir)"
return 0
}
fi
if same_path "$LOCAL_BACKUPS" "$remote_root"; then
log "[backup-migrate] summary moved=$moved copied=$copied (remote backup root is local)"
return 0
fi
if ! mkdir -p "$remote_root" 2>/dev/null; then
log "[backup-migrate] summary moved=$moved copied=$copied (create dest failed)"
return 0
fi
local candidates=()
while IFS= read -r entry; do
if [ -z "$entry" ]; then
continue
fi
if printf '%s' "$entry" | grep -qE '_[0-9]{8}_[0-9]{6}Z?'; then
if [ -d "${LOCAL_BACKUPS}/${entry}" ] || printf '%s' "$entry" | grep -qE '\.zip(\.enc)?$'; then
candidates+=("$entry")
fi
fi
done < <(ls -1t "$LOCAL_BACKUPS" 2>/dev/null || true)
local newest=""
if [ "${#candidates[@]}" -gt 0 ]; then
newest="${candidates[0]}"
fi
if [ "${#candidates[@]}" -gt 1 ]; then
local i
for ((i=1; i<${#candidates[@]}; i++)); do
local item="${candidates[$i]}"
if [ -e "${remote_root}/${item}" ]; then
continue
fi
log "[backup-migrate] Moving ${item} -> ${remote_root}"
if mv "${LOCAL_BACKUPS}/${item}" "${remote_root}/" 2>/dev/null; then
moved=$((moved+1))
else
log "[backup-migrate] WARN move failed ${item}"
fi
done
fi
if [ -n "$newest" ] && [ ! -e "${remote_root}/${newest}" ]; then
log "[backup-migrate] Copying newest ${newest} to backup root (preserve local copy)"
if [ -d "${LOCAL_BACKUPS}/${newest}" ]; then
if cp -a "${LOCAL_BACKUPS}/${newest}" "${remote_root}/" 2>/dev/null; then
copied=$((copied+1))
fi
else
if cp -a "${LOCAL_BACKUPS}/${newest}" "${remote_root}/" 2>/dev/null; then
copied=$((copied+1))
fi
fi
fi
local remote_candidates=()
while IFS= read -r entry; do
if [ -z "$entry" ]; then
continue
fi
if printf '%s' "$entry" | grep -qE '_[0-9]{8}_[0-9]{6}Z?'; then
if [ -d "${remote_root}/${entry}" ] || printf '%s' "$entry" | grep -qE '\.zip(\.enc)?$'; then
remote_candidates+=("$entry")
fi
fi
done < <(ls -1t "$remote_root" 2>/dev/null || true)
local remote_newest=""
if [ "${#remote_candidates[@]}" -gt 0 ]; then
remote_newest="${remote_candidates[0]}"
fi
if [ -n "$remote_newest" ]; then
local local_path="${LOCAL_BACKUPS}/${remote_newest}"
local remote_path="${remote_root}/${remote_newest}"
local needs_downsync=0
if [ ! -e "$local_path" ]; then
needs_downsync=1
else
local remote_mtime
local local_mtime
remote_mtime="$(mtime_epoch "$remote_path" || true)"
local_mtime="$(mtime_epoch "$local_path" || true)"
if [ -n "$remote_mtime" ] && [ -n "$local_mtime" ] && [ "$remote_mtime" -gt "$local_mtime" ]; then
needs_downsync=1
fi
fi
if [ "$needs_downsync" -eq 1 ]; then
log "[backup-migrate] Down-sync newer ${remote_newest} -> local backups"
if [ -d "$remote_path" ]; then
cp -a "$remote_path" "$LOCAL_BACKUPS/" 2>/dev/null || log "[backup-migrate] WARN down-sync failed ${remote_newest}"
else
cp -a "$remote_path" "$LOCAL_BACKUPS/" 2>/dev/null || log "[backup-migrate] WARN down-sync failed ${remote_newest}"
fi
fi
fi
log "[backup-migrate] summary moved=$moved copied=$copied"
}
rotate_logs() {
# Keep last N logs per port; ignore failures.
local n="$1"
if ! printf '%s' "$n" | grep -qE '^[0-9]+$'; then
return 0
fi
if [ "$n" -lt 1 ]; then
return 0
fi
# shellcheck disable=SC2012
local files
files=( $(ls -1t "${LOGS_DIR}/von_${PORT}_"*.log 2>/dev/null || true) )
local count=${#files[@]}
if [ "$count" -le "$n" ]; then
return 0
fi
local i
for ((i=n; i<count; i++)); do
rm -f "${files[$i]}" 2>/dev/null || true
done
}
# Resolve backup root and migrate local backups if configured.
resolve_backup_root
if [ "$AGENT_TEST_INSTANCE" -eq 1 ]; then
log "[backup-migrate] disabled via -AgentTest"
elif [ "$NO_BACKUP_MIGRATE" -eq 0 ]; then
migrate_local_backups
else
log "[backup-migrate] disabled via -NoBackupMigrate"
fi
# Backward-compatible convenience: if start action is combined with backup flags,
# run the backup action instead of starting the server.
if [ "$ACTION" = "start" ] && [ "$BACKUP_FLAGS_SET" -eq 1 ]; then
log "Start requested with backup flags; running backup action only."
ACTION="backup"
fi
if [ "$AGENT_TEST_INSTANCE" -eq 1 ]; then
export VON_AGENT_TEST_INSTANCE=1
else
unset VON_AGENT_TEST_INSTANCE || true
fi
export PYTHONPATH="${ROOT}"
if [ -x "${HOME}/.local/bin/tesseract" ]; then
# setup_all.sh may install the distro Tesseract packages in the ordinary
# user's local prefix when sudo is unavailable. Keep that PATH correction
# scoped to Von's launcher process rather than changing global shell files.
export PATH="${HOME}/.local/bin:${PATH}"
fi
export PYTHONUNBUFFERED=1
export PYTHONFAULTHANDLER="${PYTHONFAULTHANDLER:-1}"
export PYTHONUTF8=1
export PYTHONIOENCODING=utf-8
export VON_SKIP_BROWSER_LAUNCH=1
get_pid() {
if [ ! -f "$PID_FILE" ]; then
return 0
fi
# PID file format matches run.ps1: first line contains PID=nnn.
local pid_line
pid_line="$(head -n 1 "$PID_FILE" 2>/dev/null || true)"
if [[ "$pid_line" =~ ^PID=([0-9]+)$ ]]; then
echo "${BASH_REMATCH[1]}"
fi
}
write_pidfile() {
local pid="$1"
local start
start="$(date -Iseconds 2>/dev/null || date)"
printf 'PID=%s\nPORT=%s\nSTART=%s\n' "$pid" "$PORT" "$start" > "$PID_FILE"
}
remove_pidfile() {
[ -f "$PID_FILE" ] && rm -f "$PID_FILE" || true
}
read_admin_token() {
if [ -f "$TOKEN_FILE" ]; then
tr -d '\r\n' < "$TOKEN_FILE" 2>/dev/null || true
return 0
fi
local tok=""
if command -v uuidgen >/dev/null 2>&1; then
tok="$(uuidgen | tr -d '-')"
elif command -v python3 >/dev/null 2>&1; then
tok="$(python3 - <<'PY'
import uuid
print(uuid.uuid4().hex)
PY
)"
else
tok="$(dd if=/dev/urandom bs=16 count=1 2>/dev/null | od -An -tx1 | tr -d ' \n')"
fi
printf '%s\n' "$tok" > "$TOKEN_FILE" 2>/dev/null || true
chmod 600 "$TOKEN_FILE" 2>/dev/null || true
echo "$tok"
}
set_admin_token_env() {
# Mirrors run.ps1: allow supplying a stable admin token via -AdminToken.
local tok=""
if [ -n "$ADMIN_TOKEN" ]; then
tok="$ADMIN_TOKEN"
printf '%s\n' "$tok" > "$TOKEN_FILE" 2>/dev/null || true
chmod 600 "$TOKEN_FILE" 2>/dev/null || true
else
tok="$(read_admin_token)"
fi
export VON_ADMIN_TOKEN="$tok"
}
pdm_cmd() {
if [ -x "${ROOT}/.venv/bin/pdm" ]; then
echo "${ROOT}/.venv/bin/pdm"
elif [ -x "${ROOT}/.venv/Scripts/pdm.exe" ]; then
echo "${ROOT}/.venv/Scripts/pdm.exe"
else
echo "pdm"
fi
}
python_cmd() {
if [ -x "${ROOT}/.venv/bin/python" ]; then
echo "${ROOT}/.venv/bin/python"
elif [ -x "${ROOT}/.venv/Scripts/python.exe" ]; then
echo "${ROOT}/.venv/Scripts/python.exe"
elif command -v python3 >/dev/null 2>&1; then
echo "python3"
elif command -v python >/dev/null 2>&1; then
echo "python"
else
echo ""
fi
}
now_iso() {
date -Iseconds 2>/dev/null || date
}
is_truthy() {
case "${1:-}" in
1|true|TRUE|yes|YES|y|Y) return 0 ;;
*) return 1 ;;
esac
}
read_failure_count() {
local meta="$1"
if [ ! -f "$meta" ]; then
echo 0
return 0
fi
local count
count="$(grep -Eo '"failure_count"[[:space:]]*:[[:space:]]*[0-9]+' "$meta" 2>/dev/null | head -n 1 | grep -Eo '[0-9]+' || true)"
if [ -z "$count" ]; then
count=0
fi
echo "$count"
}
write_failure_count() {
local meta="$1"
local count="$2"
printf '{"failure_count": %s}\n' "$count" > "$meta" 2>/dev/null || true
}
parse_iso_epoch() {
local iso="$1"
local epoch=""
epoch="$(date -d "$iso" +%s 2>/dev/null || true)"
if [ -z "$epoch" ]; then
epoch="$(date -j -f "%Y-%m-%dT%H:%M:%S%z" "$iso" +%s 2>/dev/null || true)"
fi
echo "$epoch"
}
pidfile_uptime_minutes() {
if [ ! -f "$PID_FILE" ]; then
return 1
fi
local start_line=""
start_line="$(grep -E '^START=' "$PID_FILE" 2>/dev/null | head -n 1 || true)"
if [ -z "$start_line" ]; then
return 1
fi
local start_value="${start_line#START=}"
if [ -z "$start_value" ]; then
return 1
fi
local start_epoch=""
start_epoch="$(parse_iso_epoch "$start_value")"
if [ -z "$start_epoch" ]; then
return 1
fi
local now_epoch=""
now_epoch="$(date +%s 2>/dev/null || true)"
if [ -z "$now_epoch" ]; then
return 1
fi
local diff=$(( (now_epoch - start_epoch) / 60 ))
if [ "$diff" -lt 0 ]; then
diff=0
fi
printf '%s' "$diff"
}
should_run_interval() {
local sentinel="$1"
local interval_hours="$2"
local force="$3"
if [ "$force" -eq 1 ]; then
return 0
fi
if [ ! -f "$sentinel" ]; then
return 0
fi
local last
last="$(cat "$sentinel" 2>/dev/null || true)"
if [ -z "$last" ]; then
return 0
fi
local last_epoch
last_epoch="$(parse_iso_epoch "$last")"
if [ -z "$last_epoch" ]; then
return 0
fi
local now_epoch
now_epoch="$(date +%s)"
local elapsed_hours=$(( (now_epoch - last_epoch) / 3600 ))
if [ "$elapsed_hours" -lt "$interval_hours" ]; then
return 1
fi
return 0
}
get_health_payload() {
local timeout=2
if printf '%s' "${VON_HEALTH_HTTP_TIMEOUT:-}" | grep -qE '^[0-9]+$'; then
if [ "$VON_HEALTH_HTTP_TIMEOUT" -gt 0 ] && [ "$VON_HEALTH_HTTP_TIMEOUT" -lt 61 ]; then
timeout="$VON_HEALTH_HTTP_TIMEOUT"
fi
fi
local hosts=("127.0.0.1")
if [ -n "${VON_HEALTH_HOSTS:-}" ]; then
IFS=',' read -r -a hosts <<<"${VON_HEALTH_HOSTS}"
local i
for i in "${!hosts[@]}"; do
hosts[$i]="${hosts[$i]#"${hosts[$i]%%[![:space:]]*}"}"
hosts[$i]="${hosts[$i]%"${hosts[$i]##*[![:space:]]}"}"
done
elif is_truthy "${VON_HEALTH_INCLUDE_LOCALHOST:-}"; then
hosts+=("localhost")
fi
local host
for host in "${hosts[@]}"; do
if [ -z "$host" ]; then
continue
fi
local url="http://${host}:${PORT}/health"
if command -v curl >/dev/null 2>&1; then
local body
body="$(curl -fsS --max-time "$timeout" "$url" 2>/dev/null || true)"
if [ -n "$body" ]; then
printf '%s' "$body"
return 0
fi
if [ "$HEALTH_DEBUG" -eq 1 ]; then
log "Health attempt failed $url"
fi
continue
fi
if command -v wget >/dev/null 2>&1; then
local body
body="$(wget -q -T "$timeout" -O - "$url" 2>/dev/null || true)"
if [ -n "$body" ]; then
printf '%s' "$body"
return 0
fi
if [ "$HEALTH_DEBUG" -eq 1 ]; then
log "Health attempt failed $url"
fi
continue
fi
done
return 1
}
health_ok() {
get_health_payload >/dev/null
}
health_payload_field() {
local payload="$1"
local field="$2"
local py
py="$(python_cmd)"
if [ -z "$py" ]; then
return 1
fi
HEALTH_PAYLOAD="$payload" "$py" - "$field" <<'PY' 2>/dev/null
import json
import os
import sys
field = sys.argv[1]
try:
payload = json.loads(os.environ.get("HEALTH_PAYLOAD", ""))
except Exception:
raise SystemExit(1)
value = payload.get(field)
if isinstance(value, bool):
print("true" if value else "false")
elif value is not None:
print(value)
else:
raise SystemExit(1)
PY
}
log_von_version() {
local target_port="${1:-$PORT}"
local payload=""
local version=""
local saved_port="$PORT"
PORT="$target_port"
payload="$(get_health_payload || true)"
PORT="$saved_port"
version="$(health_payload_field "$payload" "version" || true)"
if [ -n "$version" ]; then
log "Von version: $version"
else
log "Von version: unavailable (/health did not report version)."
fi
}
agent_test_health_payload_valid() {
local payload="$1"
local log_failure="${2:-0}"
if [ -z "$payload" ]; then
if [ "$log_failure" = "1" ]; then
log "Agent test health read-back rejected: /health returned no JSON payload."
fi
return 1
fi
local marker
marker="$(health_payload_field "$payload" "agent_test_instance" || true)"
if [ "$marker" != "true" ]; then
if [ "$log_failure" = "1" ]; then
log "Agent test health read-back rejected: agent_test_instance marker was not true."
fi
return 1
fi
local listener
listener="$(get_listening_pid_by_port "$PORT" || true)"
if [ -z "$listener" ]; then
if [ "$log_failure" = "1" ]; then
log "Agent test health read-back rejected: no listener remained on port $PORT."
fi
return 1
fi
local payload_pid
payload_pid="$(health_payload_field "$payload" "pid" || true)"
if ! printf '%s' "$payload_pid" | grep -qE '^[0-9]+$'; then
if [ "$log_failure" = "1" ]; then
log "Agent test health read-back rejected: /health payload did not include a valid pid."
fi
return 1
fi
if [ "$payload_pid" != "$listener" ]; then
if [ "$log_failure" = "1" ]; then
log "Agent test health read-back rejected: /health pid $payload_pid did not match listener PID $listener."
fi
return 1
fi
return 0
}
launcher_health_ready() {
local log_failure="${1:-0}"
local payload
payload="$(get_health_payload || true)"
if [ -z "$payload" ]; then
if [ "$log_failure" = "1" ] && [ "$AGENT_TEST_INSTANCE" -eq 1 ]; then
log "Agent test health read-back not ready: /health did not return a payload."
fi
return 1
fi
if [ "$AGENT_TEST_INSTANCE" -eq 1 ]; then
agent_test_health_payload_valid "$payload" "$log_failure"
return $?
fi
return 0
}
confirm_health_stable() {
local attempts=4
local i=0
while [ "$i" -lt "$attempts" ]; do
sleep 0.5
if ! launcher_health_ready "$([ "$i" -eq $((attempts - 1)) ] && echo 1 || echo 0)"; then
return 1
fi
i=$((i + 1))
done
return 0
}
report_server_readiness_observation() {
local pid="$1"
local detail="$2"
if ! process_exists "$pid"; then
remove_pidfile
log "ERROR: $detail The server process PID=$pid has exited."
show_server_start_failure_tail
return 1
fi
log "WARNING: $detail"
log "Readiness observation window elapsed; server process PID=$pid remains active. Returning with readiness pending so /health can continue initialising and be reconciled by ./run.sh status or the caller."
return 0
}
show_server_start_failure_tail() {
log "Showing last 40 log lines for startup diagnostics:"
if [ -f "$CURRENT_LOG" ]; then
local log_tail
log_tail="$(tail -n 40 "$CURRENT_LOG" 2>/dev/null || true)"
if [ -n "$log_tail" ]; then
printf '%s\n' "$log_tail"
fi
fi
if [ -f "$SERVER_ERR_LOG" ]; then
log "Last 40 stderr log lines:"
local err_tail
err_tail="$(tail -n 40 "$SERVER_ERR_LOG" 2>/dev/null || true)"
if [ -n "$err_tail" ]; then
printf '%s\n' "$err_tail"
fi
fi
}
launch_detached_process() {
local launcher_py="$1"
local stdout_log="$2"
local stderr_log="$3"
local working_dir="$4"
local executable="$5"
shift 5
"$launcher_py" - "$stdout_log" "$stderr_log" "$working_dir" "$executable" "$@" <<'PY'
import subprocess
import sys
stdout_path = sys.argv[1]
stderr_path = sys.argv[2]
working_dir = sys.argv[3]
executable = sys.argv[4]
args = sys.argv[5:]
stdout = open(stdout_path, "ab", buffering=0)
stderr = open(stderr_path, "ab", buffering=0)
process = subprocess.Popen(
[executable, *args],
cwd=working_dir,
stdin=subprocess.DEVNULL,
stdout=stdout,
stderr=stderr,
close_fds=True,
start_new_session=True,
)
print(process.pid)
PY
}
open_browser() {
local url="http://localhost:${PORT}/"
# Match run.ps1 behaviour: prefer Chrome Beta, with optional Beta-only mode.
if command -v google-chrome-beta >/dev/null 2>&1; then
google-chrome-beta "$url" >/dev/null 2>&1 || true
return 0
fi
if command -v chromium-beta >/dev/null 2>&1; then
chromium-beta "$url" >/dev/null 2>&1 || true
return 0
fi
if [ "$CHROME_BETA" -eq 1 ] && command -v open >/dev/null 2>&1; then
open -a "Google Chrome Beta" "$url" >/dev/null 2>&1 || true
return 0
fi
if [ "$CHROME_BETA" -eq 1 ]; then
log "Browser open skipped (-ChromeBeta requested, but Chrome Beta was not found). URL: $url"
return 0
fi
# Stable/browser fallbacks.
if command -v google-chrome >/dev/null 2>&1; then
google-chrome "$url" >/dev/null 2>&1 || true
return 0
fi
if command -v chromium >/dev/null 2>&1; then
chromium "$url" >/dev/null 2>&1 || true
return 0
fi
if command -v chromium-browser >/dev/null 2>&1; then
chromium-browser "$url" >/dev/null 2>&1 || true
return 0
fi
if command -v xdg-open >/dev/null 2>&1; then
xdg-open "$url" >/dev/null 2>&1 || true