This repository was archived by the owner on Feb 27, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathagent-install.sh
More file actions
executable file
·1553 lines (1347 loc) · 55.1 KB
/
agent-install.sh
File metadata and controls
executable file
·1553 lines (1347 loc) · 55.1 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
#!/bin/bash
# nova-memory comprehensive installer
# Idempotent - safe to run multiple times
set -e
VERSION="2.2"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# Load centralized PG config (ENV → postgres.json → defaults)
PG_CONFIG="${HOME}/.openclaw/postgres.json"
if [ -f "$PG_CONFIG" ] && [ -r "$PG_CONFIG" ]; then
# Source the shared loader if available, otherwise inline
if [ -f "$SCRIPT_DIR/lib/pg-env.sh" ]; then
source "$SCRIPT_DIR/lib/pg-env.sh"
load_pg_env
else
# Inline fallback: read config file for any unset PG* vars
_pg_val() { jq -r ".$1 // empty" "$PG_CONFIG" 2>/dev/null; }
val=$(_pg_val host); [ -z "${PGHOST:-}" ] && [ -n "$val" ] && export PGHOST="$val"
val=$(_pg_val port); [ -z "${PGPORT:-}" ] && [ -n "$val" ] && export PGPORT="$val"
val=$(_pg_val database); [ -z "${PGDATABASE:-}" ] && [ -n "$val" ] && export PGDATABASE="$val"
val=$(_pg_val user); [ -z "${PGUSER:-}" ] && [ -n "$val" ] && export PGUSER="$val"
val=$(_pg_val password); [ -z "${PGPASSWORD:-}" ] && [ -n "$val" ] && export PGPASSWORD="$val"
export PGHOST="${PGHOST:-localhost}"
export PGPORT="${PGPORT:-5432}"
export PGUSER="${PGUSER:-$(whoami)}"
fi
else
echo "ERROR: Config file not found: $PG_CONFIG" >&2
echo "Run shell-install.sh first or create ~/.openclaw/postgres.json" >&2
echo "" >&2
echo "Example ~/.openclaw/postgres.json:" >&2
echo ' { "host": "localhost", "port": 5432, "database": "mydb", "user": "myuser", "password": "" }' >&2
exit 1
fi
# Use loaded env vars
DB_USER="${PGUSER:-$(whoami)}"
DB_NAME="${PGDATABASE:-${DB_USER//-/_}_memory}" # Replace hyphens with underscores (nova-staging → nova_staging_memory)
WORKSPACE="${OPENCLAW_WORKSPACE:-$HOME/.openclaw/workspace-claude-code}"
# Parse arguments
VERIFY_ONLY=0
FORCE_INSTALL=0
DB_NAME_OVERRIDE=""
while [[ $# -gt 0 ]]; do
case $1 in
--verify-only)
VERIFY_ONLY=1
shift
;;
--force)
FORCE_INSTALL=1
shift
;;
--database|-d)
DB_NAME_OVERRIDE="$2"
shift 2
;;
--help)
echo "Usage: $0 [OPTIONS]"
echo ""
echo "Options:"
echo " --verify-only Check installation without modifying anything"
echo " --force Force overwrite existing files (skip file verification)"
echo " --database, -d NAME Override database name (default: \${USER}_memory)"
echo " --help Show this help message"
echo ""
echo "Examples:"
echo " $0 # Use default database name"
echo " $0 --database nova_memory # Use specific database"
echo " $0 -d nova_memory # Short form"
exit 0
;;
*)
echo "Unknown option: $1"
echo "Run '$0 --help' for usage information"
exit 1
;;
esac
done
# Apply database name override if provided
if [ -n "$DB_NAME_OVERRIDE" ]; then
DB_NAME="$DB_NAME_OVERRIDE"
fi
# Temp file cleanup
TMPFILES=()
cleanup_tmp() { rm -f "${TMPFILES[@]}"; }
trap cleanup_tmp EXIT
# Color codes for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
# Status indicators
CHECK_MARK="${GREEN}✅${NC}"
CROSS_MARK="${RED}❌${NC}"
WARNING="${YELLOW}⚠️${NC}"
INFO="${BLUE}ℹ️${NC}"
# Verification results
VERIFICATION_PASSED=0
VERIFICATION_WARNINGS=0
VERIFICATION_ERRORS=0
# Track if gateway restart is needed
GATEWAY_RESTART_NEEDED=0
# Install shared PG loader files to ~/.openclaw/lib/
# Uses SHA-256 hash comparison: install if missing, update if changed, skip if identical
install_lib_files() {
local lib_src="$SCRIPT_DIR/lib"
local lib_dst="$HOME/.openclaw/lib"
local files=("pg-env.sh" "pg_env.py" "pg-env.ts" "env-loader.sh" "env_loader.py")
mkdir -p "$lib_dst"
chmod 755 "$lib_dst"
for f in "${files[@]}"; do
local src="$lib_src/$f"
local dst="$lib_dst/$f"
if [ ! -f "$src" ]; then
echo -e " ${WARNING} [lib] $f: source not found in repo, skipping"
continue
fi
if [ ! -f "$dst" ]; then
cp "$src" "$dst"
chmod 644 "$dst"
echo -e " ${CHECK_MARK} [lib] $f: installed"
else
local src_hash dst_hash
src_hash=$(sha256sum "$src" | awk '{print $1}')
dst_hash=$(sha256sum "$dst" | awk '{print $1}')
if [ "$src_hash" != "$dst_hash" ]; then
cp "$src" "$dst"
chmod 644 "$dst"
echo -e " ${CHECK_MARK} [lib] $f: updated (hash changed)"
else
echo -e " ${INFO} [lib] $f: up to date"
fi
fi
done
}
# Copy a directory tree excluding node_modules and dist directories
# Usage: copy_excluding <source_dir> <target_dir>
copy_excluding() {
local source="$1"
local target="$2"
mkdir -p "$target"
(cd "$source" && find . -type f \
-not -path '*/node_modules/*' \
-not -path '*/dist/*' \
-print0 | while IFS= read -r -d '' f; do
mkdir -p "$target/$(dirname "$f")"
cp "$f" "$target/$f"
done)
}
echo ""
echo "═══════════════════════════════════════════"
if [ $VERIFY_ONLY -eq 1 ]; then
echo " nova-memory verification v${VERSION}"
else
echo " nova-memory installer v${VERSION}"
fi
echo "═══════════════════════════════════════════"
echo ""
# ============================================
# Verification Functions
# ============================================
verify_schema() {
echo "Schema verification..."
# Check if database exists
if ! psql -U "$DB_USER" -lqt | cut -d \| -f 1 | grep -qw "$DB_NAME"; then
echo -e " ${CROSS_MARK} Database '$DB_NAME' does not exist"
VERIFICATION_ERRORS=$((VERIFICATION_ERRORS + 1))
return 1
fi
# Extract expected table names from schema/schema.sql
TABLE_NAMES=$(grep "^CREATE TABLE" "$SCRIPT_DIR/schema/schema.sql" | sed -E 's/CREATE TABLE IF NOT EXISTS ([^ ]+).*/\1/' | sort)
local tables_missing=()
local tables_present=0
for table in $TABLE_NAMES; do
# Check if table exists
TABLE_EXISTS=$(psql -U "$DB_USER" -d "$DB_NAME" -tAc "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = 'public' AND table_name = '$table'" | tr -d '[:space:]')
if [ "$TABLE_EXISTS" -eq 0 ]; then
tables_missing+=("$table")
else
tables_present=$((tables_present + 1))
fi
done
if [ ${#tables_missing[@]} -gt 0 ]; then
echo -e " ${WARNING} Missing tables:"
for table in "${tables_missing[@]}"; do
echo " • $table"
done
VERIFICATION_WARNINGS=$((VERIFICATION_WARNINGS + ${#tables_missing[@]}))
fi
# Reverse check: warn about extra tables not defined in schema.sql
local db_tables
db_tables=$(psql -U "$DB_USER" -d "$DB_NAME" -tAc "SELECT table_name FROM information_schema.tables WHERE table_schema = 'public' AND table_type = 'BASE TABLE' ORDER BY table_name")
local tables_extra=()
for db_table in $db_tables; do
if ! echo "$TABLE_NAMES" | grep -qxF "$db_table"; then
tables_extra+=("$db_table")
fi
done
if [ ${#tables_extra[@]} -gt 0 ]; then
echo -e " ${WARNING} Extra tables not in schema/schema.sql (not managed by installer):"
for table in "${tables_extra[@]}"; do
echo " • $table"
done
VERIFICATION_WARNINGS=$((VERIFICATION_WARNINGS + ${#tables_extra[@]}))
else
echo -e " ${CHECK_MARK} No extra tables found outside schema/schema.sql"
fi
# Sample column count check for a few key tables
local sample_tables=("entities" "entity_facts" "events" "lessons" "agents")
local column_issues=0
for table in "${sample_tables[@]}"; do
# Get column count from database
COL_COUNT=$(psql -U "$DB_USER" -d "$DB_NAME" -tAc "SELECT COUNT(*) FROM information_schema.columns WHERE table_schema = 'public' AND table_name = '$table'" 2>/dev/null | tr -d '[:space:]')
if [ -n "$COL_COUNT" ] && [ "$COL_COUNT" -gt 0 ]; then
echo -e " ${CHECK_MARK} Table '$table' schema present ($COL_COUNT columns)"
elif psql -U "$DB_USER" -d "$DB_NAME" -tAc "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = 'public' AND table_name = '$table'" | grep -q 1; then
echo -e " ${WARNING} Table '$table' exists but column check failed"
column_issues=$((column_issues + 1))
fi
done
if [ $column_issues -gt 0 ]; then
VERIFICATION_WARNINGS=$((VERIFICATION_WARNINGS + column_issues))
fi
return 0
}
verify_files() {
echo ""
echo "File verification..."
local files_checked=0
local files_matching=0
local files_different=0
local files_missing=0
# Check hooks
for hook_dir in "$SCRIPT_DIR/hooks"/*; do
if [ ! -d "$hook_dir" ]; then
continue
fi
hook_name=$(basename "$hook_dir")
target_dir="$HOME/.openclaw/hooks/$hook_name"
if [ ! -d "$target_dir" ]; then
echo -e " ${WARNING} Hook '$hook_name' not installed"
files_missing=$((files_missing + 1))
continue
fi
# Check each file in the hook
for source_file in "$hook_dir"/*.ts "$hook_dir"/*.js "$hook_dir"/*.sh; do
if [ ! -f "$source_file" ]; then
continue
fi
filename=$(basename "$source_file")
target_file="$target_dir/$filename"
if [ ! -f "$target_file" ]; then
echo -e " ${WARNING} $hook_name/$filename missing"
files_missing=$((files_missing + 1))
continue
fi
# Compare checksums
source_hash=$(sha256sum "$source_file" | awk '{print $1}')
target_hash=$(sha256sum "$target_file" | awk '{print $1}')
files_checked=$((files_checked + 1))
if [ "$source_hash" = "$target_hash" ]; then
echo -e " ${CHECK_MARK} $hook_name/$filename matches source"
files_matching=$((files_matching + 1))
else
echo -e " ${WARNING} $hook_name/$filename differs (local modifications?)"
files_different=$((files_different + 1))
fi
done
done
# Check scripts
if [ -d "$SCRIPT_DIR/scripts" ]; then
for source_file in "$SCRIPT_DIR/scripts"/*.sh "$SCRIPT_DIR/scripts"/*.py; do
if [ ! -f "$source_file" ]; then
continue
fi
filename=$(basename "$source_file")
target_file="$WORKSPACE/scripts/$filename"
if [ ! -f "$target_file" ]; then
echo -e " ${WARNING} scripts/$filename missing"
files_missing=$((files_missing + 1))
continue
fi
# Compare checksums
source_hash=$(sha256sum "$source_file" | awk '{print $1}')
target_hash=$(sha256sum "$target_file" | awk '{print $1}')
files_checked=$((files_checked + 1))
if [ "$source_hash" = "$target_hash" ]; then
echo -e " ${CHECK_MARK} scripts/$filename matches source"
files_matching=$((files_matching + 1))
else
echo -e " ${WARNING} scripts/$filename differs (local modifications?)"
files_different=$((files_different + 1))
fi
done
fi
# Check skills
if [ -d "$SCRIPT_DIR/skills" ]; then
local skills_target="$HOME/.openclaw/skills"
for skill_dir in "$SCRIPT_DIR/skills"/*/; do
if [ ! -d "$skill_dir" ]; then
continue
fi
skill_name=$(basename "$skill_dir")
target_skill="$skills_target/$skill_name"
if [ ! -d "$target_skill" ]; then
echo -e " ${WARNING} skill '$skill_name' not installed"
files_missing=$((files_missing + 1))
continue
fi
# Check for SKILL.md file (required for OpenClaw skills)
if [ -f "$skill_dir/SKILL.md" ]; then
if [ -f "$target_skill/SKILL.md" ]; then
source_hash=$(sha256sum "$skill_dir/SKILL.md" | awk '{print $1}')
target_hash=$(sha256sum "$target_skill/SKILL.md" | awk '{print $1}')
files_checked=$((files_checked + 1))
if [ "$source_hash" = "$target_hash" ]; then
echo -e " ${CHECK_MARK} skill '$skill_name' SKILL.md matches"
files_matching=$((files_matching + 1))
else
echo -e " ${WARNING} skill '$skill_name' SKILL.md differs"
files_different=$((files_different + 1))
fi
else
echo -e " ${WARNING} skill '$skill_name' missing SKILL.md"
files_missing=$((files_missing + 1))
fi
fi
done
fi
if [ $files_different -gt 0 ]; then
echo -e " ${INFO} Run with --force to overwrite modified files"
VERIFICATION_WARNINGS=$((VERIFICATION_WARNINGS + files_different))
fi
if [ $files_missing -gt 0 ]; then
VERIFICATION_WARNINGS=$((VERIFICATION_WARNINGS + files_missing))
fi
return 0
}
verify_config() {
echo ""
echo "Config verification..."
# Check environment variables
# Note: Hooks run as child processes of OpenClaw and inherit its environment
# API keys should be configured in OpenClaw, not separately for nova-memory
if [ -z "$PGUSER" ]; then
echo -e " ${WARNING} PGUSER not set (using current user: $(whoami))"
VERIFICATION_WARNINGS=$((VERIFICATION_WARNINGS + 1))
else
echo -e " ${CHECK_MARK} PGUSER set: $PGUSER"
fi
if [ -z "$ANTHROPIC_API_KEY" ]; then
echo -e " ${WARNING} ANTHROPIC_API_KEY not set in environment"
echo -e " Hooks will inherit from OpenClaw's environment"
VERIFICATION_WARNINGS=$((VERIFICATION_WARNINGS + 1))
else
echo -e " ${CHECK_MARK} ANTHROPIC_API_KEY set: ${ANTHROPIC_API_KEY:0:8}..."
fi
if [ -z "$OPENAI_API_KEY" ]; then
echo -e " ${WARNING} OPENAI_API_KEY not set in environment"
echo -e " Hooks will inherit from OpenClaw's environment"
VERIFICATION_WARNINGS=$((VERIFICATION_WARNINGS + 1))
else
echo -e " ${CHECK_MARK} OPENAI_API_KEY set: ${OPENAI_API_KEY:0:8}..."
fi
if [ -z "$OPENCLAW_WORKSPACE" ]; then
echo -e " ${INFO} OPENCLAW_WORKSPACE not set (using default: $WORKSPACE)"
else
echo -e " ${CHECK_MARK} OPENCLAW_WORKSPACE set: $OPENCLAW_WORKSPACE"
fi
# Check database connection
if psql -U "$DB_USER" -d "$DB_NAME" -c '\q' 2>/dev/null; then
echo -e " ${CHECK_MARK} Database connection works"
else
echo -e " ${CROSS_MARK} Database connection failed"
VERIFICATION_ERRORS=$((VERIFICATION_ERRORS + 1))
return 1
fi
# Check OpenClaw hook config
HOOK_CONFIG="$HOME/.openclaw/hooks.json"
if [ -f "$HOOK_CONFIG" ]; then
echo -e " ${CHECK_MARK} OpenClaw hook config exists"
# Check if our hooks are registered
for hook in "memory-extract" "semantic-recall" "session-init" "agent-turn-context"; do
if grep -q "\"$hook\"" "$HOOK_CONFIG" 2>/dev/null; then
ENABLED=$(grep -A5 "\"$hook\"" "$HOOK_CONFIG" | grep -c "\"enabled\": true" || echo "0")
if [ "$ENABLED" -gt 0 ]; then
echo -e " ${CHECK_MARK} Hook '$hook' enabled in OpenClaw"
else
echo -e " ${WARNING} Hook '$hook' exists but not enabled"
VERIFICATION_WARNINGS=$((VERIFICATION_WARNINGS + 1))
fi
else
echo -e " ${WARNING} Hook '$hook' not found in OpenClaw config"
VERIFICATION_WARNINGS=$((VERIFICATION_WARNINGS + 1))
fi
done
else
echo -e " ${WARNING} OpenClaw hook config not found at $HOOK_CONFIG"
VERIFICATION_WARNINGS=$((VERIFICATION_WARNINGS + 1))
fi
# Check cron job installation
CRON_FILE="/etc/cron.d/nova-memory-maintenance"
if [ -f "$CRON_FILE" ]; then
echo -e " ${CHECK_MARK} Cron job installed at $CRON_FILE"
# Verify it has correct content
if grep -q "memory-maintenance.py" "$CRON_FILE"; then
echo -e " ${CHECK_MARK} Cron job configured correctly"
else
echo -e " ${WARNING} Cron job exists but may need updating"
VERIFICATION_WARNINGS=$((VERIFICATION_WARNINGS + 1))
fi
else
echo -e " ${WARNING} Cron job not installed (requires manual setup)"
VERIFICATION_WARNINGS=$((VERIFICATION_WARNINGS + 1))
fi
return 0
}
# ============================================
# Part 1: Prerequisites Check
# ============================================
echo "Checking prerequisites..."
# Check PostgreSQL installed
if command -v psql &> /dev/null; then
PG_VERSION=$(psql --version | awk '{print $3}')
echo -e " ${CHECK_MARK} PostgreSQL installed ($PG_VERSION)"
else
echo -e " ${CROSS_MARK} PostgreSQL not found"
echo ""
echo "Please install PostgreSQL first:"
echo " Ubuntu/Debian: sudo apt install postgresql postgresql-contrib"
echo " macOS: brew install postgresql"
exit 1
fi
# Check psql command available
if command -v psql &> /dev/null; then
echo -e " ${CHECK_MARK} psql command available"
else
echo -e " ${CROSS_MARK} psql command not found"
exit 1
fi
# Check PostgreSQL service running
if pg_isready -q 2>/dev/null; then
echo -e " ${CHECK_MARK} PostgreSQL service running"
else
echo -e " ${CROSS_MARK} PostgreSQL service not running"
echo ""
echo "Please start PostgreSQL:"
echo " Ubuntu/Debian: sudo systemctl start postgresql"
echo " macOS: brew services start postgresql"
exit 1
fi
# Check for pgvector extension
if psql -U "$DB_USER" -d postgres -tAc "SELECT 1 FROM pg_available_extensions WHERE name='vector'" | grep -q 1; then
echo -e " ${CHECK_MARK} pgvector extension available"
else
echo -e " ${WARNING} pgvector extension not found (required for semantic search)"
echo " Install: sudo apt install postgresql-16-pgvector"
fi
# Check for pgschema (required for declarative schema management)
if command -v pgschema &> /dev/null; then
PGSCHEMA_BIN="pgschema"
echo -e " ${CHECK_MARK} pgschema available ($(pgschema --help 2>&1 | head -1 || true))"
elif [ -x "$HOME/go/bin/pgschema" ]; then
PGSCHEMA_BIN="$HOME/go/bin/pgschema"
echo -e " ${CHECK_MARK} pgschema available at $PGSCHEMA_BIN"
else
echo -e " ${CROSS_MARK} pgschema not found (required for schema management)"
echo ""
echo " Install pgschema:"
echo " go install github.com/pgplex/pgschema@latest"
echo ""
echo " Then ensure ~/go/bin is in your PATH:"
echo " export PATH=\"\$PATH:\$HOME/go/bin\""
exit 1
fi
# Check for jq (required for plan hazard detection)
if command -v jq &> /dev/null; then
echo -e " ${CHECK_MARK} jq available"
else
echo -e " ${CROSS_MARK} jq not found (required for plan hazard detection)"
echo " Install: sudo apt install jq"
exit 1
fi
# ============================================
# Part 1.5: Install Shared PG Loader Libraries
# ============================================
echo ""
echo "Installing shared PG loader libraries..."
install_lib_files
# ============================================
# Part 1.6: API Key Check and Configuration
# ============================================
echo ""
echo "API key configuration..."
# Check if OPENAI_API_KEY is set in environment
if [ -z "${OPENAI_API_KEY:-}" ]; then
echo -e " ${WARNING} OPENAI_API_KEY not set"
echo " Required for semantic recall (embeddings)."
echo " Set it in openclaw.json env.vars or export it before running."
echo " Get a key from: https://platform.openai.com/api-keys"
else
echo -e " ${CHECK_MARK} OPENAI_API_KEY set: ${OPENAI_API_KEY:0:8}..."
fi
# ============================================
# Run Verification if --verify-only
# ============================================
if [ $VERIFY_ONLY -eq 1 ]; then
echo ""
verify_schema
verify_files
verify_config
echo ""
echo "═══════════════════════════════════════════"
echo " Verification Summary"
echo "═══════════════════════════════════════════"
if [ $VERIFICATION_ERRORS -gt 0 ]; then
echo -e " ${CROSS_MARK} $VERIFICATION_ERRORS errors found"
exit 1
elif [ $VERIFICATION_WARNINGS -gt 0 ]; then
echo -e " ${WARNING} $VERIFICATION_WARNINGS warnings found"
exit 0
else
echo -e " ${CHECK_MARK} All checks passed"
exit 0
fi
fi
# ============================================
# Part 2: Database Setup (Idempotent)
# ============================================
echo ""
echo "Database setup..."
# Check if database exists
if psql -U "$DB_USER" -lqt | cut -d \| -f 1 | grep -qw "$DB_NAME"; then
echo -e " ${CHECK_MARK} Database '$DB_NAME' exists"
# Verify connection
if psql -U "$DB_USER" -d "$DB_NAME" -c '\q' 2>/dev/null; then
echo -e " ${CHECK_MARK} Database connection verified"
else
echo -e " ${CROSS_MARK} Cannot connect to database '$DB_NAME'"
exit 1
fi
else
echo " Creating database '$DB_NAME'..."
createdb -U "$DB_USER" "$DB_NAME" 2>/dev/null || {
echo -e " ${CROSS_MARK} Failed to create database"
echo " Try: createdb -U $DB_USER $DB_NAME"
exit 1
}
echo -e " ${CHECK_MARK} Database '$DB_NAME' created"
fi
# ============================================
# Schema Management via pgschema
# ============================================
SCHEMA_DIR="$SCRIPT_DIR/schema"
SCHEMA_FILE="$SCHEMA_DIR/schema.sql"
if [ ! -f "$SCHEMA_FILE" ]; then
echo -e " ${CROSS_MARK} schema/schema.sql not found at $SCHEMA_FILE"
echo " Generate it with: pgschema dump --host <host> --db <db> --user <user> --schema public > schema/schema.sql"
exit 1
fi
# Track whether schema apply was skipped
SCHEMA_DIFF_SKIPPED=0
echo ""
echo "Schema management (pgschema)..."
# ----------------------------------------------------------
# Step 1: Ensure extensions
# ----------------------------------------------------------
echo " Ensuring extensions..."
# Parse extension requirements from schema.sql (handles both active and commented-out forms)
EXTENSIONS=$(grep -E "(^|INSTALLER HANDLES: )CREATE EXTENSION IF NOT EXISTS" "$SCHEMA_FILE" | sed "s/.*CREATE EXTENSION IF NOT EXISTS //;s/ .*//;s/;//" || true)
if [ -n "$EXTENSIONS" ]; then
for ext in $EXTENSIONS; do
# Only a superuser can install extensions; if already installed, no-op
if psql -U "$DB_USER" -d "$DB_NAME" -tAc "SELECT 1 FROM pg_extension WHERE extname = '$ext'" | grep -q 1; then
echo -e " ${CHECK_MARK} Extension '$ext' already installed"
else
# Try to install — will succeed if user is superuser, fail gracefully if not
if psql -U "$DB_USER" -d "$DB_NAME" -c "CREATE EXTENSION IF NOT EXISTS \"$ext\";" > /dev/null 2>&1; then
echo -e " ${CHECK_MARK} Extension '$ext' installed"
else
echo -e " ${WARNING} Extension '$ext' not installed — requires superuser"
echo " Ask a superuser to run: CREATE EXTENSION IF NOT EXISTS \"$ext\";"
echo " Then re-run the installer."
SCHEMA_DIFF_SKIPPED=1
fi
fi
done
else
echo -e " ${INFO} No extensions defined in schema.sql"
fi
# ----------------------------------------------------------
# Step 2: Run pre-migrations
# ----------------------------------------------------------
PRE_MIGRATIONS_DIR="$SCRIPT_DIR/pre-migrations"
if [ -d "$PRE_MIGRATIONS_DIR" ]; then
PRE_MIGRATION_FILES=()
while IFS= read -r -d '' f; do
PRE_MIGRATION_FILES+=("$f")
done < <(find "$PRE_MIGRATIONS_DIR" -maxdepth 1 -name "*.sql" -print0 | sort -z)
if [ ${#PRE_MIGRATION_FILES[@]} -gt 0 ]; then
echo " Running pre-migrations (${#PRE_MIGRATION_FILES[@]} files)..."
for sql_file in "${PRE_MIGRATION_FILES[@]}"; do
filename=$(basename "$sql_file")
if psql -U "$DB_USER" -d "$DB_NAME" -f "$sql_file" > /dev/null 2>&1; then
echo -e " ${CHECK_MARK} Pre-migration: $filename"
else
echo -e " ${WARNING} Pre-migration failed: $filename (continuing)"
fi
done
else
echo -e " ${INFO} No pre-migration scripts found"
fi
fi
if [ "$SCHEMA_DIFF_SKIPPED" -eq 1 ]; then
echo -e " ${WARNING} Skipping pgschema plan/apply (extension install failed above)"
else
# ----------------------------------------------------------
# Step 3: Plan
# ----------------------------------------------------------
PLAN_FILE=$(mktemp /tmp/pgschema-plan-XXXXXX.json)
TMPFILES+=("$PLAN_FILE")
echo " Running pgschema plan..."
# Build connection args — omit --password if PGPASSWORD is empty (peer auth)
PGSCHEMA_CONN_ARGS=(
"--host" "${PGHOST:-/var/run/postgresql}"
"--port" "${PGPORT:-5432}"
"--db" "$DB_NAME"
"--user" "$DB_USER"
)
PGSCHEMA_PLAN_ARGS=(
"--plan-host" "${PGHOST:-/var/run/postgresql}"
"--plan-port" "${PGPORT:-5432}"
"--plan-db" "$DB_NAME"
"--plan-user" "$DB_USER"
)
if [ -n "${PGPASSWORD:-}" ]; then
PGSCHEMA_CONN_ARGS+=("--password" "$PGPASSWORD")
PGSCHEMA_PLAN_ARGS+=("--plan-password" "$PGPASSWORD")
fi
PLAN_EXIT=0
"$PGSCHEMA_BIN" plan \
"${PGSCHEMA_CONN_ARGS[@]}" \
--schema public \
--file "$SCHEMA_FILE" \
"${PGSCHEMA_PLAN_ARGS[@]}" \
--output-json "$PLAN_FILE" \
--no-color 2>&1 || PLAN_EXIT=$?
if [ $PLAN_EXIT -ne 0 ]; then
echo -e " ${WARNING} pgschema plan failed (exit $PLAN_EXIT) — schema apply skipped"
SCHEMA_DIFF_SKIPPED=1
else
# ----------------------------------------------------------
# Step 4: Hazard check — look for destructive table/column drops
# ----------------------------------------------------------
# Check for DROP TABLE, DROP COLUMN (not privilege revokes — those are ignored)
# Note: .groups may be null when there are no changes
HAZARD_COUNT=$(jq '[(.groups // [])[] | .steps[] | select(.type != "privilege") | select(.operation == "drop") | select(.type | test("^table"))] | length' "$PLAN_FILE" 2>/dev/null || echo "0")
TOTAL_STEPS=$(jq '[(.groups // [])[] | .steps[] | select(.type != "privilege")] | length' "$PLAN_FILE" 2>/dev/null || echo "0")
if [ "$HAZARD_COUNT" -gt 0 ] 2>/dev/null; then
echo -e " ${WARNING} Destructive changes detected in plan — schema apply SKIPPED"
echo " $HAZARD_COUNT destructive operation(s) found (DROP on table/column):"
jq -r '(.groups // [])[] | .steps[] | select(.type != "privilege") | select(.operation == "drop") | select(.type | test("^table")) | " • " + .path' "$PLAN_FILE" 2>/dev/null || true
echo ""
echo " Review the plan file to understand the changes:"
echo " jq . $PLAN_FILE"
echo ""
echo " If these drops are intentional, apply manually with:"
echo " $PGSCHEMA_BIN apply ${PGSCHEMA_CONN_ARGS[*]} --schema public --plan $PLAN_FILE --auto-approve"
SCHEMA_DIFF_SKIPPED=1
elif [ "$TOTAL_STEPS" -eq 0 ] 2>/dev/null; then
echo -e " ${CHECK_MARK} Schema is up to date — no changes needed"
else
# ----------------------------------------------------------
# Step 5: Apply
# ----------------------------------------------------------
echo " Applying $TOTAL_STEPS schema change(s)..."
APPLY_EXIT=0
"$PGSCHEMA_BIN" apply \
"${PGSCHEMA_CONN_ARGS[@]}" \
--schema public \
--plan "$PLAN_FILE" \
--auto-approve \
--no-color 2>&1 || APPLY_EXIT=$?
if [ $APPLY_EXIT -eq 0 ]; then
echo -e " ${CHECK_MARK} Schema applied successfully"
TABLE_COUNT=$(psql -U "$DB_USER" -d "$DB_NAME" -tAc "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = 'public' AND table_type = 'BASE TABLE'" | tr -d '[:space:]')
echo " Total tables in database: $TABLE_COUNT"
else
echo -e " ${WARNING} Schema apply failed (exit $APPLY_EXIT) — continuing installer"
SCHEMA_DIFF_SKIPPED=1
fi
fi
fi
# ----------------------------------------------------------
# Step 6: Cleanup plan file
# ----------------------------------------------------------
rm -f "$PLAN_FILE"
fi
# ============================================
# Part 3: Hooks Installation
# ============================================
echo ""
echo "Hooks installation..."
HOOKS_SOURCE="$SCRIPT_DIR/hooks"
HOOKS_TARGET="$HOME/.openclaw/hooks"
# Create hooks directory if needed
if [ ! -d "$HOOKS_TARGET" ]; then
mkdir -p "$HOOKS_TARGET"
echo -e " ${CHECK_MARK} Created hooks directory: $HOOKS_TARGET"
else
echo " Hooks directory exists: $HOOKS_TARGET"
fi
# Function to install a hook (copy, not symlink)
install_hook() {
local hook_name="$1"
local source="$HOOKS_SOURCE/$hook_name"
local target="$HOOKS_TARGET/$hook_name"
if [ ! -d "$source" ]; then
echo -e " ${WARNING} Hook not found: $hook_name (skipping)"
return 1
fi
# If not forcing, check if files are already up to date
if [ $FORCE_INSTALL -eq 0 ] && [ -d "$target" ]; then
local all_match=1
for source_file in "$source"/*.ts "$source"/*.js "$source"/*.sh; do
if [ ! -f "$source_file" ]; then
continue
fi
filename=$(basename "$source_file")
target_file="$target/$filename"
if [ -f "$target_file" ]; then
source_hash=$(sha256sum "$source_file" | awk '{print $1}')
target_hash=$(sha256sum "$target_file" | awk '{print $1}')
if [ "$source_hash" != "$target_hash" ]; then
all_match=0
break
fi
else
# Target file missing, need to reinstall
all_match=0
break
fi
done
if [ $all_match -eq 1 ]; then
echo -e " ${INFO} $hook_name up to date"
return 2
fi
fi
# Remove existing target if it exists
local was_existing=0
if [ -e "$target" ]; then
was_existing=1
rm -rf "$target"
fi
# Copy hook directory (excluding node_modules and dist)
copy_excluding "$source" "$target"
if [ $was_existing -eq 1 ]; then
echo -e " ${CHECK_MARK} $hook_name updated"
else
echo -e " ${CHECK_MARK} $hook_name installed"
fi
return 0
}
# Install each hook
INSTALLED_HOOKS=()
SKIPPED_HOOKS=()
for hook in "memory-extract" "semantic-recall" "session-init" "agent-turn-context"; do
install_hook "$hook" && result=$? || result=$?
if [ $result -eq 0 ]; then
INSTALLED_HOOKS+=("$hook")
elif [ $result -eq 2 ]; then
SKIPPED_HOOKS+=("$hook")
fi
done
if [ ${#INSTALLED_HOOKS[@]} -eq 0 ] && [ ${#SKIPPED_HOOKS[@]} -eq 0 ]; then
echo -e " ${CROSS_MARK} No hooks installed"
exit 1
fi
# ============================================
# Part 4: Scripts Setup
# ============================================
echo ""
echo "Scripts setup..."
SCRIPTS_SOURCE="$SCRIPT_DIR/scripts"
SCRIPTS_TARGET_WORKSPACE="$WORKSPACE/scripts"
SCRIPTS_TARGET_OPENCLAW="$HOME/.openclaw/scripts"
OPENCLAW_LOGS_DIR="$HOME/.openclaw/logs"
# Ensure logs directory exists
if [ ! -d "$OPENCLAW_LOGS_DIR" ]; then
mkdir -p "$HOME/.openclaw/logs"
echo -e " ${CHECK_MARK} Created logs directory: $OPENCLAW_LOGS_DIR"
else
echo -e " ${INFO} Logs directory exists: $OPENCLAW_LOGS_DIR"
fi
# Copy scripts directory to both locations:
# 1. Workspace scripts (for hooks using relative paths)
# 2. OpenClaw scripts (where semantic-recall handler expects them)
if [ -d "$SCRIPTS_SOURCE" ]; then
# Create both target directories
mkdir -p "$SCRIPTS_TARGET_WORKSPACE"
mkdir -p "$SCRIPTS_TARGET_OPENCLAW"
# Copy scripts, respecting force flag
scripts_copied=0
scripts_updated=0
scripts_skipped=0
for source_file in "$SCRIPTS_SOURCE"/*.sh "$SCRIPTS_SOURCE"/*.py; do
if [ ! -f "$source_file" ]; then
continue
fi
filename=$(basename "$source_file")
target_file_workspace="$SCRIPTS_TARGET_WORKSPACE/$filename"
target_file_openclaw="$SCRIPTS_TARGET_OPENCLAW/$filename"
# Check if we should skip (both files match source)
if [ $FORCE_INSTALL -eq 0 ]; then
source_hash=$(sha256sum "$source_file" | awk '{print $1}')
workspace_matches=0
openclaw_matches=0
if [ -f "$target_file_workspace" ]; then
workspace_hash=$(sha256sum "$target_file_workspace" | awk '{print $1}')
[ "$source_hash" = "$workspace_hash" ] && workspace_matches=1
fi
if [ -f "$target_file_openclaw" ]; then
openclaw_hash=$(sha256sum "$target_file_openclaw" | awk '{print $1}')
[ "$source_hash" = "$openclaw_hash" ] && openclaw_matches=1
fi
# If both locations match source, skip
if [ $workspace_matches -eq 1 ] && [ $openclaw_matches -eq 1 ]; then
continue
fi
fi
# Copy to both locations
cp "$source_file" "$target_file_workspace"
cp "$source_file" "$target_file_openclaw"
if [ -f "$target_file_workspace" ] && [ -f "$target_file_openclaw" ]; then
scripts_copied=$((scripts_copied + 1))
fi
done
echo -e " ${CHECK_MARK} $scripts_copied scripts installed to:"
echo " • $SCRIPTS_TARGET_WORKSPACE"
echo " • $SCRIPTS_TARGET_OPENCLAW"
else
echo -e " ${CROSS_MARK} Scripts directory not found at $SCRIPTS_SOURCE"
exit 1
fi
# Ensure all scripts are executable in both locations
SCRIPT_COUNT=0
for location in "$SCRIPTS_TARGET_WORKSPACE" "$SCRIPTS_TARGET_OPENCLAW"; do
for script in "$location"/*.sh "$location"/*.py; do
if [ -f "$script" ]; then
chmod +x "$script"
SCRIPT_COUNT=$((SCRIPT_COUNT + 1))
fi
done
done
echo -e " ${CHECK_MARK} Made $SCRIPT_COUNT scripts executable"
# Check Python dependencies (if Python scripts exist)
if ls "$SCRIPTS_TARGET_WORKSPACE"/*.py &> /dev/null; then
if command -v python3 &> /dev/null; then
echo -e " ${CHECK_MARK} Python3 available"
# Check for common dependencies
MISSING_DEPS=()
for dep in "psycopg2" "anthropic" "openai"; do
if ! python3 -c "import $dep" 2>/dev/null; then
MISSING_DEPS+=("$dep")
fi