-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathopencode-memory
More file actions
executable file
·1436 lines (1176 loc) · 38.7 KB
/
Copy pathopencode-memory
File metadata and controls
executable file
·1436 lines (1176 loc) · 38.7 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-memory — Wrapper for OpenCode with post-session memory maintenance.
#
# Installs a shell hook (function) that intercepts the `opencode` command,
# then wraps the real binary with post-session extraction and auto-dream.
#
# Subcommands:
# opencode-memory install — Install shell hook to ~/.zshrc or ~/.bashrc
# opencode-memory uninstall — Remove shell hook
# opencode-memory self -v — Print the wrapper package version
# opencode-memory [args...] — Run opencode with post-session memory maintenance
#
# How it works:
# 1. Shell hook defines `opencode()` function that delegates to `opencode-memory`
# 2. `opencode-memory` finds the real `opencode` binary in PATH
# 3. Runs it normally with all your arguments
# 4. After you exit, finds the most recent session
# 5. Optionally runs memory extraction (conversation -> memories)
# 6. Optionally runs auto-dream consolidation (memory pruning/merge)
#
# Requirements:
# - Real `opencode` CLI reachable in PATH
# - `jq` for auto-dream gate/session counting
# - The opencode-memory plugin installed (provides memory_* tools)
#
# Environment variables:
# OPENCODE_MEMORY_EXTRACT=0 — Disable post-session extraction
# OPENCODE_MEMORY_FOREGROUND=1 — Run maintenance in foreground (debug)
# OPENCODE_MEMORY_TERMINAL_LOG=1|0 — Force-enable/disable terminal logs (default: foreground only)
# OPENCODE_MEMORY_MODEL=... — Extraction model override
# OPENCODE_MEMORY_AGENT=... — Extraction agent override
# OPENCODE_MEMORY_AUTODREAM=0 — Disable auto-dream consolidation
# OPENCODE_MEMORY_AUTODREAM_MIN_HOURS=24 — Min hours between auto-dream runs
# OPENCODE_MEMORY_AUTODREAM_MIN_SESSIONS=5 — Min touched sessions since last consolidation
# OPENCODE_MEMORY_AUTODREAM_MODEL=... — Auto-dream model override
# OPENCODE_MEMORY_AUTODREAM_AGENT=... — Auto-dream agent override
# OPENCODE_MEMORY_DIR=... — Override working directory for opencode
#
set -euo pipefail
resolve_script_path() {
if command -v python3 >/dev/null 2>&1; then
python3 - "${BASH_SOURCE[0]}" <<'PY'
import os
import sys
print(os.path.realpath(sys.argv[1]))
PY
return 0
fi
printf '%s\n' "${BASH_SOURCE[0]}"
}
SCRIPT_PATH="$(resolve_script_path)"
SCRIPT_DIR="$(CDPATH= cd -- "$(dirname -- "$SCRIPT_PATH")" && pwd)"
PACKAGE_JSON="$SCRIPT_DIR/../package.json"
resolve_package_json() {
if [ -f "$PACKAGE_JSON" ]; then
printf '%s\n' "$PACKAGE_JSON"
return 0
fi
if command -v npm >/dev/null 2>&1; then
local npm_root
npm_root=$(npm root -g 2>/dev/null || true)
if [ -n "$npm_root" ] && [ -f "$npm_root/opencode-claude-memory/package.json" ]; then
printf '%s\n' "$npm_root/opencode-claude-memory/package.json"
return 0
fi
fi
printf '%s\n' "$PACKAGE_JSON"
}
print_wrapper_version() {
local version
local package_json
package_json="$(resolve_package_json)"
version=$(awk -F'"' '/^[[:space:]]*"version"[[:space:]]*:/ { print $4; exit }' "$package_json")
if [ -z "$version" ]; then
echo "[opencode-memory] ERROR: Cannot read package version from $package_json" >&2
exit 1
fi
printf '%s\n' "$version"
}
# ============================================================================
# Shell Hook Management
# ============================================================================
HOOK_START_MARKER='# >>> opencode-memory auto-initialization >>>'
HOOK_END_MARKER='# <<< opencode-memory auto-initialization <<<'
detect_shell_rc() {
local shell_name
shell_name="$(basename "${SHELL:-}")"
case "$shell_name" in
zsh)
echo "$HOME/.zshrc"
;;
bash)
echo "$HOME/.bashrc"
;;
*)
if [ -f "$HOME/.zshrc" ]; then
echo "$HOME/.zshrc"
elif [ -f "$HOME/.bashrc" ]; then
echo "$HOME/.bashrc"
else
echo "$HOME/.zshrc"
fi
;;
esac
}
install_hook() {
local rc_file
rc_file=$(detect_shell_rc)
if grep -qF "$HOOK_START_MARKER" "$rc_file" 2>/dev/null; then
echo "[opencode-memory] Hook already installed in $rc_file"
return 0
fi
cat >> "$rc_file" << 'HOOK'
# >>> opencode-memory auto-initialization >>>
opencode() {
command opencode-memory "$@"
}
# <<< opencode-memory auto-initialization <<<
HOOK
echo "[opencode-memory] Shell hook installed in $rc_file"
echo "[opencode-memory] Restart your shell or run: source $rc_file"
}
remove_hook_from_rc() {
local rc_file="$1"
local tmp_file
tmp_file=$(mktemp)
awk -v start="$HOOK_START_MARKER" -v end="$HOOK_END_MARKER" '
$0 == start { skip=1; next }
$0 == end { skip=0; next }
!skip
' "$rc_file" > "$tmp_file"
mv "$tmp_file" "$rc_file"
}
uninstall_hook() {
local removed=0
local rc_file
for rc_file in "$HOME/.zshrc" "$HOME/.bashrc"; do
[ -f "$rc_file" ] || continue
if grep -qF "$HOOK_START_MARKER" "$rc_file" 2>/dev/null; then
remove_hook_from_rc "$rc_file"
echo "[opencode-memory] Shell hook removed from $rc_file"
removed=1
fi
done
if [ "$removed" -eq 0 ]; then
rc_file=$(detect_shell_rc)
echo "[opencode-memory] Hook not found in $rc_file"
return 0
fi
echo "[opencode-memory] Restart your shell or run: source <your rc file>"
}
# Handle subcommands before any opencode resolution
case "${1:-}" in
install)
install_hook
exit 0
;;
uninstall)
uninstall_hook
exit 0
;;
self)
case "${2:-}" in
-v|--version|version)
print_wrapper_version
exit 0
;;
esac
;;
esac
# ============================================================================
# Resolve the real opencode binary
# ============================================================================
find_real_opencode() {
# Since this script is named `opencode-memory` (not `opencode`),
# `command -v opencode` finds the real binary without ambiguity.
local real
real=$(command -v opencode 2>/dev/null) || true
if [ -z "$real" ] || [ ! -x "$real" ]; then
echo "[opencode-memory] ERROR: Cannot find opencode binary in PATH" >&2
echo "[opencode-memory] Make sure opencode is installed: https://opencode.ai" >&2
exit 1
fi
echo "$real"
}
REAL_OPENCODE="$(find_real_opencode)"
is_opencode_subcommand() {
case "$1" in
completion|acp|mcp|attach|run|debug|providers|auth|agent|upgrade|uninstall|serve|web|models|stats|export|import|github|pr|session|plugin|plug|db)
return 0
;;
*)
return 1
;;
esac
}
extract_working_dir_from_args() {
local previous=""
for arg in "$@"; do
if [ "$previous" = "--dir" ]; then
printf '%s\n' "$arg"
return 0
fi
previous="$arg"
done
if [ "$#" -gt 0 ] && [ -n "${1:-}" ] && [[ "${1:-}" != -* ]] && ! is_opencode_subcommand "$1" && [ -d "$1" ]; then
printf '%s\n' "$1"
return 0
fi
return 1
}
# ============================================================================
# Configuration
# ============================================================================
EXTRACT_ENABLED="${OPENCODE_MEMORY_EXTRACT:-1}"
FOREGROUND="${OPENCODE_MEMORY_FOREGROUND:-0}"
LOG_ENABLED="${OPENCODE_MEMORY_TERMINAL_LOG:-}"
EXTRACT_MODEL="${OPENCODE_MEMORY_MODEL:-}"
EXTRACT_AGENT="${OPENCODE_MEMORY_AGENT:-}"
AUTODREAM_ENABLED="${OPENCODE_MEMORY_AUTODREAM:-1}"
AUTODREAM_MIN_HOURS="${OPENCODE_MEMORY_AUTODREAM_MIN_HOURS:-24}"
AUTODREAM_MIN_SESSIONS="${OPENCODE_MEMORY_AUTODREAM_MIN_SESSIONS:-5}"
AUTODREAM_SCAN_LIMIT="${OPENCODE_MEMORY_AUTODREAM_SCAN_LIMIT:-200}"
AUTODREAM_MODEL="${OPENCODE_MEMORY_AUTODREAM_MODEL:-$EXTRACT_MODEL}"
AUTODREAM_AGENT="${OPENCODE_MEMORY_AUTODREAM_AGENT:-$EXTRACT_AGENT}"
AUTODREAM_STALE_LOCK_SECS=$((60 * 60))
SESSION_WAIT_SECONDS="${OPENCODE_MEMORY_SESSION_WAIT_SECONDS:-5}"
WORKING_DIR="${OPENCODE_MEMORY_DIR:-$(extract_working_dir_from_args "$@" || pwd)}"
TMP_BASE_DIR="${TMPDIR:-/tmp}"
while [ "$TMP_BASE_DIR" != "/" ] && [ "${TMP_BASE_DIR%/}" != "$TMP_BASE_DIR" ]; do
TMP_BASE_DIR="${TMP_BASE_DIR%/}"
done
if [ -z "$TMP_BASE_DIR" ]; then
TMP_BASE_DIR="/"
fi
# Scope lock files at project root granularity (not per-subdirectory).
PROJECT_SCOPE_DIR="$WORKING_DIR"
if git -C "$WORKING_DIR" rev-parse --show-toplevel >/dev/null 2>&1; then
PROJECT_SCOPE_DIR="$(git -C "$WORKING_DIR" rev-parse --show-toplevel 2>/dev/null || echo "$WORKING_DIR")"
fi
PROJECT_KEY="$(printf '%s' "$PROJECT_SCOPE_DIR" | cksum | awk '{print $1}')"
# Lock files (prevent concurrent work on the same project)
LOCK_DIR="$TMP_BASE_DIR/opencode-memory-locks"
mkdir -p "$LOCK_DIR"
EXTRACT_LOCK_FILE="$LOCK_DIR/${PROJECT_KEY}.extract.lock"
STATE_DIR="${CLAUDE_CONFIG_DIR:-$HOME/.claude}/opencode-memory"
mkdir -p "$STATE_DIR"
CONSOLIDATION_LOCK_FILE="$STATE_DIR/${PROJECT_KEY}.consolidate-lock"
# Logs
LOG_DIR="$TMP_BASE_DIR/opencode-memory-logs"
mkdir -p "$LOG_DIR"
TASK_LOG_PREFIX="$(date +%Y%m%d-%H%M%S)-${PROJECT_KEY}"
EXTRACT_LOG_FILE="$LOG_DIR/extract-${TASK_LOG_PREFIX}.log"
AUTODREAM_LOG_FILE="$LOG_DIR/dream-${TASK_LOG_PREFIX}.log"
# ============================================================================
# Prompts
# ============================================================================
# Adapted from Claude Code's extraction prompt, simplified for OpenCode's
# headless run mode. The model sees the full conversation context via --fork.
EXTRACT_PROMPT='You are now acting as the memory extraction subagent. Review the entire conversation above and extract any information worth remembering for future sessions.
## What to save
Use the `memory_save` tool to persist memories. There are four types:
1. **user** — Who the user is: role, expertise, preferences, communication style. Helps tailor future interactions.
2. **feedback** — Guidance on how to work: corrections ("don'\''t do X"), confirmations ("yes, keep doing that"), approach preferences. Include *why* so edge cases can be judged.
3. **project** — Ongoing work context: goals, deadlines, initiatives, decisions, bugs. NOT derivable from code/git. Convert relative dates to absolute.
4. **reference** — Pointers to external resources: URLs, tool names, where to find information outside the codebase.
## What NOT to save
- Code patterns, architecture, file structure — derivable from the codebase
- Git history, recent changes — use `git log`/`git blame`
- Debugging solutions — the fix is in the code
- Anything already in AGENTS.md / project config files
- Ephemeral task details or current conversation context
- Information that was already saved in a previous extraction
## How to save
For each memory worth saving, call `memory_save` with:
- `file_name`: descriptive slug (e.g., `user_role`, `feedback_testing_approach`)
- `name`: short title
- `description`: one-line description (used for relevance matching in future sessions)
- `type`: one of user, feedback, project, reference
- `content`: the memory content. For feedback/project types, structure as: rule/fact, then **Why:** and **How to apply:** lines.
## Instructions
1. Analyze the conversation for memorable information
2. Check existing memories first (use `memory_list`) to avoid duplicates — update existing ones if needed
3. Save each distinct memory as a separate entry
4. If the conversation was trivial (e.g., just "hello" or a quick lookup), save nothing — that'\''s fine
5. Be selective: 0-3 memories per session is typical. Quality over quantity.
6. Do NOT save a memory about the extraction process itself.'
# Periodic memory consolidation inspired by Claude Code auto-dream.
AUTODREAM_PROMPT="$(cat <<'EOF'
You are performing an auto-dream memory consolidation pass.
Goal: tighten and de-duplicate memory files so future sessions can orient faster.
## Available tools
- memory_list
- memory_search
- memory_read
- memory_save
- memory_delete
## Phase 1 — Orient
1. Use memory_list to inspect current memory inventory.
2. Identify overlapping or stale entries that can be merged/updated/deleted.
## Phase 2 — Consolidate
1. Merge duplicates into a single stronger memory using memory_save.
2. Rewrite vague descriptions so retrieval is easier and more precise.
3. For feedback/project entries, ensure content is structured as:
- main rule/fact
- **Why:**
- **How to apply:**
## Phase 3 — Prune
1. Delete memories that are clearly obsolete, contradictory, or low-value.
2. Keep total memory set concise and high signal.
## Guardrails
- Do NOT invent facts.
- If confidence is low, keep existing memory instead of guessing.
- If memory quality is already strong, make no changes and explicitly say so.
Return a short summary of what you updated, merged, or removed.
EOF
)"
# ============================================================================
# Helper Functions
# ============================================================================
should_log() {
if [ -n "$LOG_ENABLED" ]; then
[ "$LOG_ENABLED" = "1" ]
return $?
fi
[ "$FOREGROUND" = "1" ]
}
log() {
should_log || return 0
echo "[opencode-memory] $*" >&2
}
is_positive_int() {
[[ "$1" =~ ^[0-9]+$ ]] && [ "$1" -gt 0 ]
}
is_bool_flag() {
[ "$1" = "0" ] || [ "$1" = "1" ]
}
if [ -n "$LOG_ENABLED" ] && ! is_bool_flag "$LOG_ENABLED"; then
echo "[opencode-memory] Invalid OPENCODE_MEMORY_TERMINAL_LOG=$LOG_ENABLED, expected 0 or 1; defaulting to foreground-only logging" >&2
LOG_ENABLED=""
fi
if ! is_positive_int "$AUTODREAM_MIN_HOURS"; then
log "Invalid OPENCODE_MEMORY_AUTODREAM_MIN_HOURS=$AUTODREAM_MIN_HOURS, using default 24"
AUTODREAM_MIN_HOURS=24
fi
if ! is_positive_int "$AUTODREAM_MIN_SESSIONS"; then
log "Invalid OPENCODE_MEMORY_AUTODREAM_MIN_SESSIONS=$AUTODREAM_MIN_SESSIONS, using default 5"
AUTODREAM_MIN_SESSIONS=5
fi
if ! is_positive_int "$AUTODREAM_SCAN_LIMIT"; then
log "Invalid OPENCODE_MEMORY_AUTODREAM_SCAN_LIMIT=$AUTODREAM_SCAN_LIMIT, using default 200"
AUTODREAM_SCAN_LIMIT=200
fi
has_new_memories() {
# Check if any memory file was modified during the session.
local mem_base="${CLAUDE_CONFIG_DIR:-$HOME/.claude}/projects"
if [ ! -d "$mem_base" ]; then
return 1
fi
local newer_files
newer_files=$(find "$mem_base" -path "*/memory/*.md" -newer "$TIMESTAMP_FILE" 2>/dev/null | head -1)
[ -n "$newer_files" ]
}
cleanup_timestamp() {
rm -f "$TIMESTAMP_FILE" "${TRANSCRIPT_CHECKPOINT_FILE:-}"
}
get_session_list_json() {
local limit="$1"
local output
if output=$("$REAL_OPENCODE" session list --format json -n "$limit" 2>/dev/null); then
echo "$output"
return 0
fi
if output=$("$REAL_OPENCODE" session list --format json 2>/dev/null); then
echo "$output"
return 0
fi
return 1
}
get_latest_session_id() {
local session_json
session_json=$(get_session_list_json 1) || return 1
# Parse with jq if available, fallback to grep.
if command -v jq &>/dev/null; then
echo "$session_json" | jq -r '.[0].id // empty'
else
echo "$session_json" | grep -o '"id"[[:space:]]*:[[:space:]]*"[^"]*"' | head -1 | sed 's/.*"id"[[:space:]]*:[[:space:]]*"\([^"]*\)"/\1/'
fi
}
get_opencode_db_path() {
printf '%s\n' "$HOME/.local/share/opencode/opencode.db"
}
get_session_title_from_db() {
local session_id="$1"
local db_path
db_path=$(get_opencode_db_path)
if [ -z "$session_id" ] || [ ! -f "$db_path" ] || ! command -v python3 >/dev/null 2>&1; then
return 1
fi
python3 - "$db_path" "$session_id" <<'PY'
import sqlite3
import sys
db_path, session_id = sys.argv[1:3]
try:
conn = sqlite3.connect(f"file:{db_path}?mode=ro", uri=True)
row = conn.execute("SELECT title FROM session WHERE id = ? LIMIT 1", (session_id,)).fetchone()
except Exception:
raise SystemExit(1)
finally:
try:
conn.close()
except Exception:
pass
if row and row[0]:
print(row[0])
PY
}
get_session_target_id() {
local before_json="$1"
local started_at_ms="$2"
local workdir="$3"
local project_dir="$4"
local allow_existing_fallback="${5:-1}"
local after_json
after_json=$(get_session_list_json "$AUTODREAM_SCAN_LIMIT") || return 1
if command -v python3 >/dev/null 2>&1; then
python3 - "$before_json" "$after_json" "$started_at_ms" "$workdir" "$project_dir" "$allow_existing_fallback" <<'PY'
import json
import os
import sys
before_raw, after_raw, started_at_ms_raw, workdir, project_dir, allow_existing_fallback_raw = sys.argv[1:7]
def parse(raw):
try:
data = json.loads(raw)
return data if isinstance(data, list) else []
except Exception:
return []
def timestamp(item):
time_obj = item.get("time") if isinstance(item.get("time"), dict) else {}
for key in ("updated", "created"):
value = item.get(key)
if value is not None:
try:
return int(value)
except Exception:
pass
value = time_obj.get(key)
if value is not None:
try:
return int(value)
except Exception:
pass
return 0
def normalize(path):
if not path:
return ""
return os.path.realpath(path)
before = parse(before_raw)
after = parse(after_raw)
started_at_ms = int(started_at_ms_raw or "0")
allow_existing_fallback = allow_existing_fallback_raw == "1"
before_ids = {item.get("id") for item in before if item.get("id")}
workdir = normalize(workdir)
project_dir = normalize(project_dir)
def in_scope(item):
directory = normalize(item.get("directory", ""))
return directory != "" and directory in {workdir, project_dir}
def choose(candidates):
ranked = sorted(
[item for item in candidates if item.get("id")],
key=lambda item: timestamp(item),
reverse=True,
)
if ranked:
print(ranked[0]["id"])
return True
return False
new_sessions = [item for item in after if item.get("id") not in before_ids]
updated_sessions = [item for item in after if timestamp(item) > started_at_ms]
candidate_pools = [
[item for item in new_sessions if in_scope(item)],
[item for item in updated_sessions if in_scope(item)],
]
if allow_existing_fallback:
candidate_pools.append([item for item in after if in_scope(item)])
for pool in candidate_pools:
if choose(pool):
break
PY
return 0
fi
get_latest_session_id
}
get_transcripts_dir() {
printf '%s\n' "${CLAUDE_CONFIG_DIR:-$HOME/.claude}/transcripts"
}
get_storage_session_diff_dir() {
printf '%s\n' "$HOME/.local/share/opencode/storage/session_diff"
}
resolve_session_directory() {
local session_id="$1"
local output_file
output_file=$(mktemp)
if ! "$REAL_OPENCODE" export "$session_id" >"$output_file" 2>/dev/null; then
rm -f "$output_file"
return 1
fi
if [ ! -s "$output_file" ]; then
rm -f "$output_file"
return 1
fi
if command -v python3 >/dev/null 2>&1; then
python3 - "$output_file" <<'PY'
import json
from pathlib import Path
import sys
raw = Path(sys.argv[1]).read_text()
start = raw.find('{')
if start == -1:
raise SystemExit(1)
try:
data = json.loads(raw[start:])
except Exception:
raise SystemExit(1)
directory = ((data.get("info") or {}).get("directory") or "")
if directory:
print(directory)
PY
local status=$?
rm -f "$output_file"
return $status
fi
rm -f "$output_file"
return 1
}
get_scoped_artifact_session_id_since() {
local timestamp_file="$1"
local workdir="$2"
local project_dir="$3"
if ! command -v python3 >/dev/null 2>&1; then
return 1
fi
local candidates
candidates=$(python3 - "$timestamp_file" "$HOME" "${CLAUDE_CONFIG_DIR:-$HOME/.claude}" <<'PY'
import os
import sys
timestamp_file, home_dir, claude_dir = sys.argv[1:4]
try:
threshold = os.path.getmtime(timestamp_file)
except OSError:
raise SystemExit(1)
sources = [
(os.path.join(home_dir, '.local', 'share', 'opencode', 'storage', 'session_diff'), '.json'),
(os.path.join(claude_dir, 'transcripts'), '.jsonl'),
]
latest = {}
for directory, suffix in sources:
if not os.path.isdir(directory):
continue
for entry in os.scandir(directory):
if not entry.is_file() or not entry.name.endswith(suffix):
continue
try:
mtime = entry.stat().st_mtime
except OSError:
continue
if mtime <= threshold:
continue
session_id = entry.name[:-len(suffix)]
latest[session_id] = max(latest.get(session_id, -1), mtime)
for session_id, mtime in sorted(latest.items(), key=lambda item: item[1], reverse=True):
print(session_id)
PY
) || return 1
local session_id=""
local session_dir=""
local normalized_session_dir=""
local normalized_workdir=""
local normalized_project_dir=""
normalized_workdir=$(python3 - "$workdir" <<'PY'
import os, sys
print(os.path.realpath(sys.argv[1]))
PY
)
normalized_project_dir=$(python3 - "$project_dir" <<'PY'
import os, sys
print(os.path.realpath(sys.argv[1]))
PY
)
while IFS= read -r session_id; do
[ -n "$session_id" ] || continue
session_dir=$(resolve_session_directory "$session_id" || true)
[ -n "$session_dir" ] || continue
normalized_session_dir=$(python3 - "$session_dir" <<'PY'
import os, sys
print(os.path.realpath(sys.argv[1]))
PY
)
if [ "$normalized_session_dir" = "$normalized_workdir" ] || [ "$normalized_session_dir" = "$normalized_project_dir" ]; then
printf '%s\n' "$session_id"
return 0
fi
done <<EOF
$candidates
EOF
return 1
}
get_latest_storage_session_id_since() {
local timestamp_file="$1"
local storage_dir
storage_dir=$(get_storage_session_diff_dir)
if [ ! -d "$storage_dir" ]; then
return 1
fi
if command -v python3 >/dev/null 2>&1; then
python3 - "$storage_dir" "$timestamp_file" <<'PY'
import os
import sys
storage_dir, timestamp_file = sys.argv[1:3]
try:
threshold = os.path.getmtime(timestamp_file)
except OSError:
raise SystemExit(1)
latest = None
latest_mtime = -1.0
for entry in os.scandir(storage_dir):
if not entry.is_file() or not entry.name.endswith('.json'):
continue
try:
mtime = entry.stat().st_mtime
except OSError:
continue
if mtime <= threshold:
continue
if mtime > latest_mtime:
latest_mtime = mtime
latest = entry.name[:-5]
if latest:
print(latest)
PY
return 0
fi
return 1
}
get_latest_transcript_session_id_since() {
local timestamp_file="$1"
local transcripts_dir
transcripts_dir=$(get_transcripts_dir)
if [ ! -d "$transcripts_dir" ]; then
return 1
fi
if command -v python3 >/dev/null 2>&1; then
python3 - "$transcripts_dir" "$timestamp_file" <<'PY'
import os
import sys
transcripts_dir, timestamp_file = sys.argv[1:3]
try:
threshold = os.path.getmtime(timestamp_file)
except OSError:
raise SystemExit(1)
latest = None
latest_mtime = -1.0
for entry in os.scandir(transcripts_dir):
if not entry.is_file() or not entry.name.endswith('.jsonl'):
continue
try:
mtime = entry.stat().st_mtime
except OSError:
continue
if mtime <= threshold:
continue
if mtime > latest_mtime:
latest_mtime = mtime
latest = entry.name[:-6]
if latest:
print(latest)
PY
return 0
fi
return 1
}
main_prompt_requests_ignore_memory() {
if [ "${1:-}" != "run" ]; then
return 1
fi
local joined
joined=$(printf '%s\n' "$*" | tr '[:upper:]' '[:lower:]')
printf '%s\n' "$joined" | grep -Eq "(ignore|don't use|do not use|without|skip)[[:space:]]+(the[[:space:]]+)?memory|memory[[:space:]]+((should|must)[[:space:]]+be[[:space:]]+)?ignored"
}
wait_for_scoped_session_id_since() {
local before_json="$1"
local started_at_ms="$2"
local timestamp_file="$3"
local wait_seconds="${4:-5}"
local allow_existing_fallback="${5:-1}"
local attempt=0
local session_id=""
while [ "$attempt" -lt "$wait_seconds" ]; do
session_id=$(get_session_target_id "$before_json" "$started_at_ms" "$WORKING_DIR" "$PROJECT_SCOPE_DIR" "$allow_existing_fallback" || true)
if [ -z "$session_id" ]; then
session_id=$(get_scoped_artifact_session_id_since "$timestamp_file" "$WORKING_DIR" "$PROJECT_SCOPE_DIR" || true)
fi
if [ -n "$session_id" ]; then
printf '%s\n' "$session_id"
return 0
fi
sleep 1
attempt=$((attempt + 1))
done
return 1
}
wait_for_session_target_id() {
local before_json="$1"
local started_at_ms="$2"
local wait_seconds="${3:-5}"
wait_for_scoped_session_id_since "$before_json" "$started_at_ms" "$TIMESTAMP_FILE" "$wait_seconds"
}
get_fork_cleanup_candidate_id() {
local started_at_ms="$1"
local parent_title="$2"
local workdir="$3"
local project_dir="$4"
local db_path
db_path=$(get_opencode_db_path)
if [ -z "$started_at_ms" ] || [ -z "$parent_title" ] || [ ! -f "$db_path" ] || ! command -v python3 >/dev/null 2>&1; then
return 1
fi
python3 - "$db_path" "$started_at_ms" "$parent_title" "$workdir" "$project_dir" <<'PY'
import os
import re
import sqlite3
import sys
db_path, started_at_ms_raw, parent_title, workdir, project_dir = sys.argv[1:6]
started_at_ms = int(started_at_ms_raw or "0")
scope = {os.path.realpath(path) for path in (workdir, project_dir) if path}
title_pattern = re.compile(rf"^{re.escape(parent_title)} \(fork #\d+\)$")
try:
conn = sqlite3.connect(f"file:{db_path}?mode=ro", uri=True)
rows = conn.execute(
"SELECT id, title, directory, time_created FROM session WHERE time_created >= ? ORDER BY time_created DESC",
(started_at_ms,),
).fetchall()
except Exception:
raise SystemExit(1)
finally:
try:
conn.close()
except Exception:
pass
matches = []
for session_id, title, directory, time_created in rows:
if not session_id or not title or not directory or not time_created:
continue
if os.path.realpath(directory) not in scope:
continue
if not title_pattern.match(title):
continue
matches.append(session_id)
if len(matches) == 1:
print(matches[0])
PY
}
wait_for_fork_cleanup_candidate_id() {
local started_at_ms="$1"
local parent_title="$2"
local wait_seconds="${3:-5}"
local attempt=0
local session_id=""
while [ "$attempt" -lt "$wait_seconds" ]; do
session_id=$(get_fork_cleanup_candidate_id "$started_at_ms" "$parent_title" "$WORKING_DIR" "$PROJECT_SCOPE_DIR" || true)
if [ -n "$session_id" ]; then
printf '%s\n' "$session_id"
return 0
fi
sleep 1
attempt=$((attempt + 1))
done
return 1
}
file_mtime_secs() {
local file="$1"
if [ ! -f "$file" ]; then
echo 0
return 0
fi
if stat -c %Y "$file" >/dev/null 2>&1; then
stat -c %Y "$file"
return 0
fi
stat -f %m "$file"
}
# Claude-style lock/mtime semantics:
# - lock file CONTENT (PID) = current holder
# - lock file MTIME = last successful consolidation timestamp
read_last_consolidated_at_secs() {
file_mtime_secs "$CONSOLIDATION_LOCK_FILE"
}
set_file_mtime_secs() {
local file="$1"
local secs="$2"
if command -v python3 >/dev/null 2>&1; then
python3 - "$file" "$secs" <<'PY'
import os
import sys
path = sys.argv[1]
secs = int(sys.argv[2])
os.utime(path, (secs, secs))
PY
return 0
fi
# Best effort fallback; may not be portable across all environments.
touch -d "@$secs" "$file" >/dev/null 2>&1 || true
}
acquire_simple_lock() {
local lock_file="$1"
local lock_name="$2"
if [ -f "$lock_file" ]; then
local lock_pid
lock_pid=$(cat "$lock_file" 2>/dev/null || true)
if [ -n "$lock_pid" ] && kill -0 "$lock_pid" 2>/dev/null; then
log "Another $lock_name is already running (PID $lock_pid), skipping"
return 1
fi
rm -f "$lock_file"
fi
echo $$ > "$lock_file"