-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathopencode-relocate
More file actions
executable file
·2288 lines (2008 loc) · 78.8 KB
/
Copy pathopencode-relocate
File metadata and controls
executable file
·2288 lines (2008 loc) · 78.8 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
# opencode-relocate — CLI tool for managing OpenCode session locations
#
# Provides three subcommands:
# relocate Move a project directory and update all OpenCode references
# move-sessions Reassign sessions from one project to another
# split-project Create a new project entry and move sessions into it
#
# Requirements: sqlite3, git, optionally jq
# No LLM required — operates directly on the OpenCode SQLite database.
set -euo pipefail
# ── Constants ────────────────────────────────────────────────────────────────
OPENCODE_DATA="${HOME}/.local/share/opencode"
OPENCODE_DB="${OPENCODE_DATA}/opencode.db"
OPENCODE_PROJECTS_DIR="${OPENCODE_DATA}/storage/project"
OPENCODE_SESSIONS_DIR="${OPENCODE_DATA}/storage/session"
VERSION="1.0.0"
# ── Terminal state (global for EXIT trap visibility) ─────────────────────────
_CURSOR_HIDDEN=false
# ── Colors ───────────────────────────────────────────────────────────────────
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
BOLD='\033[1m'
DIM='\033[2m'
NC='\033[0m'
info() { echo -e "${CYAN}[INFO]${NC} $*"; }
warn() { echo -e "${YELLOW}[WARN]${NC} $*"; }
ok() { echo -e "${GREEN}[ OK ]${NC} $*"; }
err() { echo -e "${RED}[ERR]${NC} $*" >&2; }
# ── SQL helpers ──────────────────────────────────────────────────────────────
sql_esc() {
# Escape single quotes for SQL string literals
printf '%s' "${1//\'/\'\'}"
}
sql_query() {
# Execute a SQL query and return the trimmed result
local result
result="$(sqlite3 "$OPENCODE_DB" "$1" 2>/dev/null)" || true
printf '%s' "$(echo "$result" | sed '/^$/d')"
}
sql_query_strict() {
# Execute a SQL query, fail on error
sqlite3 "$OPENCODE_DB" "$1"
}
# ── Backup ───────────────────────────────────────────────────────────────────
backup_suffix() {
date +%Y%m%d_%H%M%S
}
backup_database() {
local suffix
suffix="$(backup_suffix).bak"
local db_backup="${OPENCODE_DB}.${suffix}"
cp "$OPENCODE_DB" "$db_backup"
if [[ -f "${OPENCODE_DB}-wal" ]]; then
cp "${OPENCODE_DB}-wal" "${OPENCODE_DB}-wal.${suffix}"
fi
if [[ -f "${OPENCODE_DB}-shm" ]]; then
cp "${OPENCODE_DB}-shm" "${OPENCODE_DB}-shm.${suffix}"
fi
# Return values via global variables
BACKUP_SUFFIX="$suffix"
BACKUP_DB_PATH="$db_backup"
}
# ── Path helpers ─────────────────────────────────────────────────────────────
resolve_path() {
local p="$1"
# Expand tilde
if [[ "$p" == "~"* ]]; then
p="${HOME}${p:1}"
fi
# Resolve to absolute path
# If the path exists, use realpath; otherwise resolve the parent
if [[ -e "$p" ]]; then
realpath "$p"
else
local parent
parent="$(dirname "$p")"
if [[ -d "$parent" ]]; then
echo "$(cd "$parent" && pwd)/$(basename "$p")"
else
echo "$p"
fi
fi
}
# ── Pre-flight checks ───────────────────────────────────────────────────────
check_sqlite3() {
if ! command -v sqlite3 &>/dev/null; then
err "sqlite3 is required but not found in PATH."
exit 1
fi
}
check_git() {
if ! command -v git &>/dev/null; then
err "git is required but not found in PATH."
exit 1
fi
}
check_opencode_db() {
if [[ ! -d "$OPENCODE_DATA" ]]; then
err "OpenCode data directory not found: ${OPENCODE_DATA}"
exit 1
fi
if [[ ! -f "$OPENCODE_DB" ]]; then
err "OpenCode database not found: ${OPENCODE_DB}"
exit 1
fi
}
# ── Project helpers ──────────────────────────────────────────────────────────
get_project_id_by_path() {
# Look up project ID from the database by worktree path
local path="$1"
local escaped
escaped="$(sql_esc "$path")"
sql_query "SELECT id FROM project WHERE worktree = '${escaped}';"
}
resolve_project_id_from_git() {
# Derive project ID from the first root commit hash
local dir_path="$1"
local result
result="$(git -C "$dir_path" rev-list --max-parents=0 HEAD 2>/dev/null | sort | head -1)" || true
if [[ -z "$result" ]]; then
echo "global"
else
echo "$result"
fi
}
ensure_project_exists() {
# Create a project entry if it doesn't exist. Returns "created" or "exists".
local project_id="$1"
local worktree="$2"
local existing
existing="$(sql_query "SELECT worktree FROM project WHERE id = '$(sql_esc "$project_id")';")"
if [[ -n "$existing" ]]; then
echo "exists"
return 0
fi
# Determine VCS type
local vcs="none"
if git -C "$worktree" rev-parse --is-inside-work-tree &>/dev/null; then
vcs="git"
fi
local now
now="$(date -u +%Y-%m-%dT%H:%M:%S.000Z)"
sql_query_strict \
"INSERT INTO project (id, worktree, vcs, time_created, time_updated, sandboxes, commands) \
VALUES ('$(sql_esc "$project_id")', '$(sql_esc "$worktree")', '${vcs}', '${now}', '${now}', '[]', '[]');"
# Create project JSON
if [[ ! -d "$OPENCODE_PROJECTS_DIR" ]]; then
mkdir -p "$OPENCODE_PROJECTS_DIR"
fi
local project_json="${OPENCODE_PROJECTS_DIR}/${project_id}.json"
if command -v jq &>/dev/null; then
jq -n \
--arg id "$project_id" \
--arg wt "$worktree" \
--arg vcs "$vcs" \
--arg now "$now" \
'{id: $id, worktree: $wt, vcs: $vcs, sandboxes: [], time: {created: $now, updated: $now}}' \
> "$project_json"
else
cat > "$project_json" <<ENDJSON
{
"id": "${project_id}",
"worktree": "${worktree}",
"vcs": "${vcs}",
"sandboxes": [],
"time": {
"created": "${now}",
"updated": "${now}"
}
}
ENDJSON
fi
# Write project ID to .git/opencode
if [[ "$vcs" == "git" ]]; then
local git_opencode="${worktree}/.git/opencode"
printf '%s' "$project_id" > "$git_opencode" 2>/dev/null || true
fi
echo "created"
}
# ── Relink helpers ───────────────────────────────────────────────────────────
# Populated by migrate_project_id: "created" (new project row inserted) or
# "merged" (sessions folded into an existing project row).
MIGRATE_MODE=""
migrate_project_id() {
# Re-point all references from an old project ID to a new one.
# Arguments: old_id new_id
# If the new project row does not exist, it is created as a copy of the old
# row. If it already exists, sessions are merged into it. The old project row
# is removed at the end. Runs inside a single transaction.
#
# The project INSERT is built dynamically from the live schema so it keeps
# working if OpenCode adds or removes project columns.
local old_id="$1"
local new_id="$2"
local e_old e_new
e_old="$(sql_esc "$old_id")"
e_new="$(sql_esc "$new_id")"
local now_ms
now_ms="$(($(date +%s) * 1000))"
local new_exists
new_exists="$(sql_query "SELECT id FROM project WHERE id = '${e_new}';")"
local insert_sql=""
if [[ -z "$new_exists" ]]; then
# Build column + value lists dynamically from the project schema.
local insert_cols="" insert_vals=""
local cid cname rest
while IFS='|' read -r cid cname rest; do
[[ -z "$cname" ]] && continue
insert_cols+="${insert_cols:+, }\"${cname}\""
case "$cname" in
id) insert_vals+="${insert_vals:+, }'${e_new}'" ;;
time_updated) insert_vals+="${insert_vals:+, }${now_ms}" ;;
*) insert_vals+="${insert_vals:+, }\"${cname}\"" ;;
esac
done < <(sqlite3 "$OPENCODE_DB" "PRAGMA table_info('project');")
insert_sql="INSERT INTO project (${insert_cols}) SELECT ${insert_vals} FROM project WHERE id = '${e_old}';"
MIGRATE_MODE="created"
else
MIGRATE_MODE="merged"
fi
sql_query_strict "BEGIN TRANSACTION;
${insert_sql}
UPDATE session SET project_id = '${e_new}' WHERE project_id = '${e_old}';
UPDATE workspace SET project_id = '${e_new}' WHERE project_id = '${e_old}';
UPDATE OR IGNORE permission SET project_id = '${e_new}' WHERE project_id = '${e_old}';
DELETE FROM permission WHERE project_id = '${e_old}';
DELETE FROM project WHERE id = '${e_old}';
COMMIT;"
}
migrate_project_json_artifacts() {
# Move on-disk JSON artifacts from old project ID to new project ID.
# Arguments: old_id new_id worktree
local old_id="$1"
local new_id="$2"
local worktree="$3"
# ── Project JSON ────────────────────────────────────────────────
local old_json="${OPENCODE_PROJECTS_DIR}/${old_id}.json"
local new_json="${OPENCODE_PROJECTS_DIR}/${new_id}.json"
if [[ -f "$old_json" ]]; then
if [[ ! -d "$OPENCODE_PROJECTS_DIR" ]]; then
mkdir -p "$OPENCODE_PROJECTS_DIR"
fi
if command -v jq &>/dev/null; then
jq --arg id "$new_id" --arg wt "$worktree" \
'if .id then .id = $id else . end |
if .worktree then .worktree = $wt else . end' \
"$old_json" > "$new_json" 2>/dev/null \
&& rm -f "$old_json" \
&& ok "Migrated project JSON: ${old_id}.json -> ${new_id}.json" \
|| warn "Failed to migrate project JSON via jq"
else
local old_sed new_sed
old_sed="$(printf '%s' "$old_id" | sed 's/[&/\]/\\&/g')"
new_sed="$(printf '%s' "$new_id" | sed 's/[&/\]/\\&/g')"
sed "s/${old_sed}/${new_sed}/g" "$old_json" > "$new_json" \
&& rm -f "$old_json" \
&& ok "Migrated project JSON: ${old_id}.json -> ${new_id}.json" \
|| warn "Failed to migrate project JSON via sed"
fi
fi
# ── Session directory ───────────────────────────────────────────
local old_dir="${OPENCODE_SESSIONS_DIR}/${old_id}"
local new_dir="${OPENCODE_SESSIONS_DIR}/${new_id}"
if [[ -d "$old_dir" ]]; then
if [[ -d "$new_dir" ]]; then
# Merge contents into the existing directory
local moved=0
shopt -s nullglob
for f in "$old_dir"/*; do
mv "$f" "$new_dir/" 2>/dev/null && moved=$((moved + 1))
done
shopt -u nullglob
rmdir "$old_dir" 2>/dev/null || true
if [[ $moved -gt 0 ]]; then
ok "Merged ${moved} session file(s) into storage/session/${new_id}/"
else
info "Removed empty session directory storage/session/${old_id}/"
fi
else
mv "$old_dir" "$new_dir" \
&& ok "Migrated session directory: ${old_id}/ -> ${new_id}/" \
|| warn "Failed to migrate session directory"
fi
fi
}
# ── Session helpers ──────────────────────────────────────────────────────────
list_project_sessions() {
# List root sessions for a project. Output: pipe-delimited rows
# id|title|directory|time_created
local project_id="$1"
sql_query \
"SELECT id, title, directory, time_created \
FROM session \
WHERE project_id = '$(sql_esc "$project_id")' \
AND parent_id IS NULL \
ORDER BY time_created DESC;"
}
list_global_sessions_by_directory() {
# List root sessions from the 'global' project filtered by directory prefix.
# Used when the source is a non-git directory whose sessions live under
# the catch-all global project (worktree: /).
# Output: pipe-delimited rows — id|title|directory|time_created
local dir_path="$1"
# Ensure no trailing slash for consistent LIKE matching (unless root /)
dir_path="${dir_path%/}"
sql_query \
"SELECT id, title, directory, time_created \
FROM session \
WHERE project_id = 'global' \
AND (directory = '$(sql_esc "$dir_path")' \
OR directory LIKE '$(sql_esc "$dir_path")/%') \
AND parent_id IS NULL \
ORDER BY time_created DESC;"
}
get_descendant_session_ids() {
# BFS to find all child/subagent sessions of a given session
local session_id="$1"
local -a queue=("$session_id")
local -a descendants=()
while [[ ${#queue[@]} -gt 0 ]]; do
local current="${queue[0]}"
queue=("${queue[@]:1}")
local children
children="$(sql_query "SELECT id FROM session WHERE parent_id = '$(sql_esc "$current")';")"
if [[ -n "$children" ]]; then
while IFS= read -r child_id; do
if [[ -n "$child_id" ]]; then
descendants+=("$child_id")
queue+=("$child_id")
fi
done <<< "$children"
fi
done
# Print one per line
for d in "${descendants[@]+"${descendants[@]}"}"; do
echo "$d"
done
}
format_date() {
# Format a timestamp for display
local time_created="$1"
if command -v date &>/dev/null && [[ -n "$time_created" ]]; then
date -j -f "%Y-%m-%dT%H:%M:%S" "${time_created%%.*}" "+%b %d, %Y %H:%M" 2>/dev/null \
|| date -d "$time_created" "+%b %d, %Y %H:%M" 2>/dev/null \
|| echo "$time_created"
else
echo "$time_created"
fi
}
# Global arrays populated by parse_sessions_raw
PARSED_IDS=()
PARSED_TITLES=()
PARSED_DATES=()
PARSED_COUNT=0
parse_sessions_raw() {
# Parse pipe-delimited session rows into global arrays.
# Argument: raw session data string (pipe-delimited rows).
# Populates PARSED_IDS, PARSED_TITLES, PARSED_DATES, PARSED_COUNT.
local raw_data="$1"
PARSED_IDS=()
PARSED_TITLES=()
PARSED_DATES=()
PARSED_COUNT=0
while IFS='|' read -r id title directory time_created; do
[[ -z "$id" ]] && continue
PARSED_IDS+=("$id")
# Truncate title
if [[ ${#title} -gt 60 ]]; then
title="${title:0:57}..."
fi
[[ -z "$title" ]] && title="(untitled)"
PARSED_TITLES+=("$title")
PARSED_DATES+=("$(format_date "$time_created")")
PARSED_COUNT=$((PARSED_COUNT + 1))
done <<< "$raw_data"
}
format_session_table() {
# Print a formatted table from pipe-delimited session row data.
# Argument: raw session data string.
# Uses parse_sessions_raw internally.
local raw_data="$1"
parse_sessions_raw "$raw_data"
if [[ $PARSED_COUNT -eq 0 ]]; then
echo "(no sessions found)"
return
fi
# Print header
printf " ${BOLD}%-4s %-14s %-62s %s${NC}\n" "#" "ID" "Title" "Created"
printf " %-4s %-14s %-62s %s\n" "----" "--------------" "--------------------------------------------------------------" "--------------------"
for ((i=0; i<PARSED_COUNT; i++)); do
local short_id="${PARSED_IDS[$i]:0:12}..."
printf " %-4s %-14s %-62s %s\n" "$((i+1))" "$short_id" "${PARSED_TITLES[$i]}" "${PARSED_DATES[$i]}"
done
echo ""
echo " Total: ${PARSED_COUNT} root session(s)"
}
parse_selection() {
# Parse a selection string like "1,3,5-7,all" against a max count.
# Prints selected 0-based indices, one per line.
local selection="$1"
local max_count="$2"
local -a selected=()
# Normalize: lowercase, strip spaces
selection="$(echo "$selection" | tr '[:upper:]' '[:lower:]' | tr -d ' ')"
if [[ "$selection" == "all" ]]; then
for ((i=0; i<max_count; i++)); do
echo "$i"
done
return 0
fi
# Split by comma
IFS=',' read -ra parts <<< "$selection"
for part in "${parts[@]}"; do
if [[ "$part" == *-* ]]; then
# Range: e.g. "3-7"
local start="${part%-*}"
local end="${part#*-}"
if ! [[ "$start" =~ ^[0-9]+$ ]] || ! [[ "$end" =~ ^[0-9]+$ ]]; then
err "Invalid range: ${part}"
return 1
fi
if [[ $start -lt 1 || $end -gt $max_count || $start -gt $end ]]; then
err "Range out of bounds: ${part} (valid: 1-${max_count})"
return 1
fi
for ((i=start; i<=end; i++)); do
echo "$((i-1))"
done
elif [[ "$part" =~ ^[0-9]+$ ]]; then
if [[ $part -lt 1 || $part -gt $max_count ]]; then
err "Selection out of bounds: ${part} (valid: 1-${max_count})"
return 1
fi
echo "$((part-1))"
else
err "Invalid selection: ${part}"
return 1
fi
done
}
# ── Interactive checkbox selector ────────────────────────────────────────────
# Requires: PARSED_IDS, PARSED_TITLES, PARSED_DATES, PARSED_COUNT to be set
# (call parse_sessions_raw before this function).
#
# Populates the global SELECTED_SESSION_IDS array with chosen session IDs.
# Returns 0 on confirm, 1 on abort.
SELECTED_SESSION_IDS=()
interactive_select() {
SELECTED_SESSION_IDS=()
if [[ $PARSED_COUNT -eq 0 ]]; then
err "No sessions to select from."
return 1
fi
# Check for TTY
if [[ ! -t 0 ]]; then
err "Interactive mode requires a terminal (stdin is not a TTY)."
err "Use --session-ids to provide session IDs non-interactively."
return 1
fi
local cursor=0
local -a toggled=()
for ((i=0; i<PARSED_COUNT; i++)); do
toggled+=("0")
done
# Terminal dimensions
local term_rows term_cols
term_rows="$(tput lines 2>/dev/null || echo 24)"
term_cols="$(tput cols 2>/dev/null || echo 80)"
# Reserve lines for: header(2) + footer(3) + hints(1) + padding(2) = 8
local max_visible=$((term_rows - 8))
[[ $max_visible -lt 5 ]] && max_visible=5
if [[ $PARSED_COUNT -lt $max_visible ]]; then
max_visible=$PARSED_COUNT
fi
local scroll_offset=0
# Count selected
_count_selected() {
local n=0
for ((i=0; i<PARSED_COUNT; i++)); do
[[ "${toggled[$i]}" == "1" ]] && n=$((n + 1))
done
echo "$n"
}
# Restore terminal on exit
_cleanup_select() {
if [[ "$_CURSOR_HIDDEN" == "true" ]]; then
tput cnorm 2>/dev/null || true
fi
# Restore stty if we changed it
stty echo 2>/dev/null || true
}
trap _cleanup_select EXIT
# Hide cursor
tput civis 2>/dev/null && _CURSOR_HIDDEN=true
# Number of terminal lines drawn by the last _render call
local rendered_lines=0
# Helper: output a single line, truncated to terminal width, and bump the counter
_out() {
local text="$1"
# Strip ANSI codes to measure visible length
local stripped
stripped="$(printf '%b' "$text" | sed $'s/\033\\[[0-9;]*m//g')"
if [[ ${#stripped} -ge $term_cols ]]; then
# Too wide — output truncated plain text (drops formatting)
printf '%s\n' "${stripped:0:$((term_cols - 1))}"
else
printf '%b\n' "$text"
fi
rendered_lines=$((rendered_lines + 1))
}
_render() {
# Erase previous render by moving up and clearing each line
if [[ $rendered_lines -gt 0 ]]; then
printf '\033[%dA' "$rendered_lines" # move up N lines
for ((i=0; i<rendered_lines; i++)); do
printf '\033[2K\n' # clear entire line, move down
done
printf '\033[%dA' "$rendered_lines" # move back up to start
fi
rendered_lines=0
# Header hints (plain text, no multi-byte unicode issues)
_out " Use UP/DOWN to navigate, SPACE to toggle, a to toggle all, ENTER to confirm, q to cancel"
_out ""
# Adjust scroll_offset so cursor is visible
if [[ $cursor -lt $scroll_offset ]]; then
scroll_offset=$cursor
elif [[ $cursor -ge $((scroll_offset + max_visible)) ]]; then
scroll_offset=$((cursor - max_visible + 1))
fi
# Show scroll indicator at top
if [[ $scroll_offset -gt 0 ]]; then
_out " ${DIM} ... $scroll_offset more above ...${NC}"
fi
# Calculate available width for title
# Fixed prefix: " > [x] 999 ses_123456789... " = ~40 chars
local title_max=$((term_cols - 40))
[[ $title_max -lt 10 ]] && title_max=10
# Render visible rows
local end=$((scroll_offset + max_visible))
[[ $end -gt $PARSED_COUNT ]] && end=$PARSED_COUNT
for ((i=scroll_offset; i<end; i++)); do
local marker=" "
[[ $i -eq $cursor ]] && marker="> "
local checkbox="[ ]"
[[ "${toggled[$i]}" == "1" ]] && checkbox="[x]"
local short_id="${PARSED_IDS[$i]:0:12}..."
local num_display=$((i + 1))
local title="${PARSED_TITLES[$i]}"
# Truncate title to fit terminal width
if [[ ${#title} -gt $title_max ]]; then
title="${title:0:$((title_max - 3))}..."
fi
local line
line="$(printf '%s%s %-3s %-14s %s' "$marker" "$checkbox" "$num_display" "$short_id" "$title")"
if [[ $i -eq $cursor ]]; then
_out " ${BOLD}${line}${NC}"
elif [[ "${toggled[$i]}" == "1" ]]; then
_out " ${GREEN}${line}${NC}"
else
_out " ${line}"
fi
done
# Show scroll indicator at bottom
local remaining=$((PARSED_COUNT - end))
if [[ $remaining -gt 0 ]]; then
_out " ${DIM} ... $remaining more below ...${NC}"
fi
# Footer
_out ""
local sel_count
sel_count="$(_count_selected)"
_out " ${CYAN}Selected: ${sel_count} of ${PARSED_COUNT}${NC}"
}
_render
# Input loop
while true; do
local key=""
IFS= read -rsn1 key
case "$key" in
$'\x1b')
# Escape sequence — read next 2 chars for arrow keys
local seq1="" seq2=""
IFS= read -rsn1 -t 0.1 seq1 || true
IFS= read -rsn1 -t 0.1 seq2 || true
if [[ "$seq1" == "[" ]]; then
case "$seq2" in
A) # Up arrow
if [[ $cursor -gt 0 ]]; then
cursor=$((cursor - 1))
fi
;;
B) # Down arrow
if [[ $cursor -lt $((PARSED_COUNT - 1)) ]]; then
cursor=$((cursor + 1))
fi
;;
esac
else
# Plain Escape — abort
echo ""
tput cnorm 2>/dev/null && _CURSOR_HIDDEN=false
info "Aborted."
return 1
fi
;;
" ")
# Space — toggle current item
if [[ "${toggled[$cursor]}" == "0" ]]; then
toggled[$cursor]="1"
else
toggled[$cursor]="0"
fi
;;
"a"|"A")
# Toggle all
local any_off=false
for ((i=0; i<PARSED_COUNT; i++)); do
if [[ "${toggled[$i]}" == "0" ]]; then
any_off=true
break
fi
done
if [[ "$any_off" == "true" ]]; then
for ((i=0; i<PARSED_COUNT; i++)); do
toggled[$i]="1"
done
else
for ((i=0; i<PARSED_COUNT; i++)); do
toggled[$i]="0"
done
fi
;;
""|$'\n')
# Enter — confirm
local sel_count
sel_count="$(_count_selected)"
if [[ $sel_count -eq 0 ]]; then
# Don't confirm with nothing selected — just re-render
_render
continue
fi
# Collect selected IDs
for ((i=0; i<PARSED_COUNT; i++)); do
if [[ "${toggled[$i]}" == "1" ]]; then
SELECTED_SESSION_IDS+=("${PARSED_IDS[$i]}")
fi
done
echo ""
tput cnorm 2>/dev/null && _CURSOR_HIDDEN=false
return 0
;;
"q"|"Q")
echo ""
tput cnorm 2>/dev/null && _CURSOR_HIDDEN=false
info "Aborted."
return 1
;;
"k"|"K")
# vim-style up
if [[ $cursor -gt 0 ]]; then
cursor=$((cursor - 1))
fi
;;
"j"|"J")
# vim-style down
if [[ $cursor -lt $((PARSED_COUNT - 1)) ]]; then
cursor=$((cursor + 1))
fi
;;
*)
# Ignore other keys
continue
;;
esac
_render
done
}
move_sessions_to_project() {
# Move sessions from source to target project.
# Arguments: source_project_id target_project_id target_worktree session_ids...
local source_project_id="$1"
local target_project_id="$2"
local target_worktree="$3"
shift 3
local -a root_session_ids=("$@")
# Collect all session IDs (roots + descendants)
local -a all_session_ids=()
for root_id in "${root_session_ids[@]}"; do
all_session_ids+=("$root_id")
local descendants
descendants="$(get_descendant_session_ids "$root_id")"
if [[ -n "$descendants" ]]; then
local desc_count=0
while IFS= read -r desc_id; do
if [[ -n "$desc_id" ]]; then
all_session_ids+=("$desc_id")
desc_count=$((desc_count + 1))
fi
done <<< "$descendants"
if [[ $desc_count -gt 0 ]]; then
info "Session ${root_id:0:12}...: found ${desc_count} child session(s)"
fi
fi
done
# Deduplicate
local -a unique_ids=()
local -A seen=()
for sid in "${all_session_ids[@]}"; do
if [[ -z "${seen[$sid]+x}" ]]; then
unique_ids+=("$sid")
seen[$sid]=1
fi
done
info "Total sessions to move: ${#unique_ids[@]}"
# Update database
local escaped_target
escaped_target="$(sql_esc "$target_worktree")"
local updated_count=0
for session_id in "${unique_ids[@]}"; do
sql_query_strict \
"UPDATE session SET project_id = '$(sql_esc "$target_project_id")', \
directory = '${escaped_target}' \
WHERE id = '$(sql_esc "$session_id")';"
updated_count=$((updated_count + 1))
done
ok "Updated project_id and directory for ${updated_count} session(s) in database"
# Move session JSON files
local source_session_dir="${OPENCODE_SESSIONS_DIR}/${source_project_id}"
local target_session_dir="${OPENCODE_SESSIONS_DIR}/${target_project_id}"
if [[ ! -d "$target_session_dir" ]]; then
mkdir -p "$target_session_dir"
info "Created session directory: storage/session/${target_project_id}/"
fi
local moved_files=0
if [[ -d "$source_session_dir" ]]; then
for session_id in "${unique_ids[@]}"; do
local source_file="${source_session_dir}/${session_id}.json"
local target_file="${target_session_dir}/${session_id}.json"
if [[ -f "$source_file" ]]; then
if command -v jq &>/dev/null; then
# Update project_id/projectID fields in the JSON
jq --arg tid "$target_project_id" \
'if .project_id then .project_id = $tid else . end |
if .projectID then .projectID = $tid else . end' \
"$source_file" > "$target_file" 2>/dev/null
if [[ $? -eq 0 ]]; then
rm "$source_file"
moved_files=$((moved_files + 1))
else
# Fallback: just move the file
mv "$source_file" "$target_file" 2>/dev/null && moved_files=$((moved_files + 1)) || \
warn "Failed to move session file: ${session_id}.json"
fi
else
# No jq — use sed to update project_id fields, then move
local old_escaped new_escaped
old_escaped="$(printf '%s' "$source_project_id" | sed 's/[&/\]/\\&/g')"
new_escaped="$(printf '%s' "$target_project_id" | sed 's/[&/\]/\\&/g')"
sed "s/${old_escaped}/${new_escaped}/g" "$source_file" > "$target_file"
rm "$source_file"
moved_files=$((moved_files + 1))
fi
fi
done
fi
ok "Moved ${moved_files} session JSON file(s) to storage/session/${target_project_id}/"
}
verify_moved_sessions() {
# Verify that moved sessions now belong to the target project
local source_project_id="$1"
local target_project_id="$2"
shift 2
local -a root_session_ids=("$@")
echo ""
info "Verifying..."
local remaining_count
remaining_count="$(sql_query "SELECT COUNT(*) FROM session WHERE project_id = '$(sql_esc "$source_project_id")';")"
local target_count
target_count="$(sql_query "SELECT COUNT(*) FROM session WHERE project_id = '$(sql_esc "$target_project_id")';")"
echo " Source project now has ${remaining_count} session(s)"
echo " Target project now has ${target_count} session(s)"
local all_good=true
for sid in "${root_session_ids[@]}"; do
local new_owner
new_owner="$(sql_query "SELECT project_id FROM session WHERE id = '$(sql_esc "$sid")';")"
if [[ "$new_owner" != "$target_project_id" ]]; then
warn "Session ${sid} still belongs to ${new_owner}"
all_good=false
fi
done
if [[ "$all_good" == "true" ]]; then
ok "All moved sessions verified in target project"
fi
}
# ── Subcommand: relocate ─────────────────────────────────────────────────────
usage_relocate() {
cat <<'EOF'
Usage: opencode-relocate relocate <old-path> <new-path>
Move an entire OpenCode project directory to a new filesystem path and
update all internal references (SQLite database and project JSON).
Arguments:
old-path Current (absolute) path of the project
new-path Desired (absolute) path after relocation
The parent directory of <new-path> must exist, and <new-path> itself
must not already exist.
Example:
opencode-relocate relocate ~/Projects/my-app ~/Projects/my-app-v2
After relocation, restart OpenCode from the new path:
cd ~/Projects/my-app-v2 && opencode
EOF
}
cmd_relocate() {
if [[ "${1:-}" == "--help" || "${1:-}" == "-h" ]]; then
usage_relocate
exit 0
fi
if [[ $# -ne 2 ]]; then
err "Expected 2 arguments: <old-path> <new-path>"
echo ""
usage_relocate
exit 1
fi
check_sqlite3
check_opencode_db
local old_path new_path
old_path="$(resolve_path "$1")"
new_path="$(resolve_path "$2")"
echo ""
echo -e " ${BOLD}OpenCode Project Relocator${NC}"
echo " ─────────────────────────"
echo ""
# ── Validate ──────────────────────────────────────────────────────
if [[ ! -d "$old_path" ]]; then
err "Old project path does not exist: ${old_path}"
exit 1
fi
if [[ "$old_path" == "$new_path" ]]; then
err "Old and new paths are identical."
exit 1
fi
local new_parent
new_parent="$(dirname "$new_path")"
if [[ ! -d "$new_parent" ]]; then
err "Parent directory of new path does not exist: ${new_parent}"
exit 1
fi
if [[ -e "$new_path" ]]; then
err "New path already exists: ${new_path}"
exit 1
fi
# ── Find project ─────────────────────────────────────────────────
local project_id
project_id="$(get_project_id_by_path "$old_path")"
if [[ -z "$project_id" ]]; then
err "No OpenCode project found with worktree: ${old_path}"
echo ""
info "Known projects:"
sqlite3 -column -header "$OPENCODE_DB" "SELECT id, worktree FROM project;" 2>/dev/null || true
exit 1
fi
local project_json="${OPENCODE_PROJECTS_DIR}/${project_id}.json"
local has_project_json="false"
[[ -f "$project_json" ]] && has_project_json="true"
local session_count
session_count="$(sql_query "SELECT COUNT(*) FROM session WHERE project_id = '${project_id}';")"
info "Found project:"