-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgit-mem
More file actions
712 lines (616 loc) · 22.9 KB
/
git-mem
File metadata and controls
712 lines (616 loc) · 22.9 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
#!/usr/bin/env bash
# git-mem — thin wrapper for git-memory
# Zero-dependency persistent memory using git empty commits.
# https://github.com/chrisribe/git-memory
set -euo pipefail
# --- Configuration ---
GIT_MEM_VERSION="dev" # stamped by install.sh
GIT_MEMORY_DIR="${GIT_MEMORY_DIR:-$HOME/memory-store}"
GIT_MEMORY_DEDUP_THRESHOLD="${GIT_MEMORY_DEDUP_THRESHOLD:-3}" # min matching words to warn
COLOR_YELLOW='\033[1;33m'
COLOR_GREEN='\033[0;32m'
COLOR_RED='\033[0;31m'
COLOR_CYAN='\033[0;36m'
COLOR_DIM='\033[2m'
COLOR_RESET='\033[0m'
# --- Helpers ---
die() { echo -e "${COLOR_RED}error:${COLOR_RESET} $*" >&2; exit 1; }
ensure_repo() {
if [[ ! -d "$GIT_MEMORY_DIR/.git" ]]; then
die "Memory store not found at $GIT_MEMORY_DIR. Run: git-mem init"
fi
}
gc() { git -C "$GIT_MEMORY_DIR" "$@"; }
usage() {
cat <<'EOF'
git-mem — persistent memory using git empty commits
COMMANDS
init Initialize memory store
add "[tags] summary" Store a memory (with dedup check)
add --yes "[tags] msg" Store without dedup prompt (for agents)
edit Store a memory via $EDITOR (multi-line)
search <query> Fuzzy multi-keyword search (OR by default)
search +word1 +word2 AND search (all words must match)
search --json <query> Search with JSON output (for agents)
show <hash> Show full content of a memory
show --json <hash> Show full content as JSON (for agents)
forget <hash> Retract a memory (append-only, no history rewrite)
forget <hash> --reason "…" Retract with reason
resurface [query] Search retracted memories only
resurface --restore <hash> Restore a retracted memory
recent [n] Browse recent memories (default: 20)
tags List all tags with counts
stats Memory statistics
sync Safe pull --rebase, then push
export Dump all memories to stdout
help Show this help
ENVIRONMENT
GIT_MEMORY_DIR Memory store path (default: ~/memory-store)
GIT_MEMORY_DEDUP_THRESHOLD Min word overlap to warn (default: 3)
EXAMPLES
git-mem add "[dri][cosmosdb] RU exhaustion is container ceiling not partition"
git-mem search cosmosdb throttle
git-mem search +cosmosdb +partition # both must match
git-mem edit # opens editor for multi-line
git-mem forget abc1234 # retract a memory
git-mem forget abc1234 --reason "superseded by new finding"
git-mem resurface cosmosdb # search retracted memories
git-mem resurface --restore abc1234 # un-retract a memory
git-mem tags
git-mem sync
EOF
}
# --- Normalize tags to lowercase ---
normalize_tags() {
local msg="$1"
# Extract leading [tag] sequences, lowercase them, reattach the rest
if [[ "$msg" =~ ^((\[[^]]+\])+)(.*) ]]; then
local tags="${BASH_REMATCH[1]}"
local rest="${BASH_REMATCH[3]}"
tags=$(echo "$tags" | tr '[:upper:]' '[:lower:]')
echo "${tags}${rest}"
else
echo "$msg"
fi
}
# --- Validate tag format ---
validate_tags() {
local msg="$1"
# Warn if message starts with text that looks like a tag but isn't bracketed
if [[ "$msg" =~ ^[a-zA-Z]+\] ]] || [[ "$msg" =~ ^\[[^]]*$ ]]; then
echo -e "${COLOR_YELLOW}warning:${COLOR_RESET} Tag format looks off. Expected: [tag] or [tag1][tag2]" >&2
fi
# Suggest tags if none present
if [[ ! "$msg" =~ ^\[ ]]; then
echo -e "${COLOR_YELLOW}hint:${COLOR_RESET} No tags detected. Consider: [dri] [arch] [gotcha] [workflow] [decision] [auto]" >&2
fi
}
# --- Dedup detection ---
# Single-pass: one git-log call, then match all words in awk.
# Why awk? A per-word git-log --grep loop spawned N processes and took ~30s for 8 adds.
# This dumps all subjects once and filters in-memory — same result, ~12x faster.
check_dedup() {
local msg="$1"
local yes_mode="${2:-0}"
# Strip tags, lowercase, extract words (4+ chars to skip noise)
local words
words=$(echo "$msg" | sed 's/\[[^]]*\]//g' | tr '[:upper:]' '[:lower:]' | grep -oE '[a-z]{4,}' | sort -u)
[[ -z "$words" ]] && return 0
local word_count
word_count=$(echo "$words" | wc -l | tr -d ' ')
# For very short messages, require fewer matches
local threshold=$GIT_MEMORY_DEDUP_THRESHOLD
if [[ $word_count -le 3 ]]; then
threshold=2
fi
# Single git call: dump all commits, match words in awk
local words_pipe
words_pipe=$(echo "$words" | paste -sd'|')
local suspicious
suspicious=$(gc log --format="%H %s" --all 2>/dev/null | awk -v thresh="$threshold" -v words="$words_pipe" '
BEGIN {
n = split(words, warr, "|")
}
{
low = tolower($0)
hits = 0
for (i = 1; i <= n; i++) {
if (index(low, warr[i]) > 0) hits++
}
if (hits >= thresh) print $0
}')
if [[ -n "$suspicious" ]]; then
echo -e "${COLOR_YELLOW}Possible duplicates found:${COLOR_RESET}" >&2
while IFS= read -r s; do
local h="${s%% *}"
local subj="${s#* }"
echo -e " ${COLOR_DIM}${h:0:7}${COLOR_RESET} $subj" >&2
done <<< "$suspicious"
echo "" >&2
if [[ "$yes_mode" -eq 1 ]]; then
echo -e "${COLOR_DIM}(--yes mode: storing anyway)${COLOR_RESET}" >&2
else
read -rp "Store anyway? [y/N] " confirm
if [[ "$confirm" != "y" && "$confirm" != "Y" ]]; then
echo "Aborted." >&2
return 1
fi
fi
fi
return 0
}
# --- JSON helper ---
# Escapes a string for safe JSON embedding (handles \ " and newlines)
json_escape_str() {
local s="$1"
s="${s//\\/\\\\}" # \ → \\
s="${s//\"/\\\"}" # " → \" s="${s//$'\r'/}" # strip \r (Windows line endings) s="${s//$'\n'/\\n}" # newline → \n
s="${s//$'\t'/\\t}" # tab → \t
printf '%s' "$s"
}
# --- Retraction helpers ---
# Returns full hashes of memories that are currently retracted (retracted minus restored).
# Single-pass: dump all subjects+bodies, count retractions and restorations per hash.
get_retracted_set() {
gc log --format="%s%n%b" --all 2>/dev/null | awk '
/^\[retracted\]/ { next }
/^\[restored\]/ { next }
/^Retracted: / { retracted[substr($0, 12)]++ ; next }
/^Restored: / { restored[substr($0, 11)]++ ; next }
END {
for (h in retracted) {
if (retracted[h] > (restored[h]+0)) print h
}
}'
}
# Check if a short hash matches any full hash in the retracted set.
# Usage: echo "$retracted_set" | is_retracted "$short_hash"
is_hash_retracted() {
local short="$1"
local retracted_set="$2"
[[ -z "$retracted_set" ]] && return 1
echo "$retracted_set" | grep -q "^${short}\|${short}" 2>/dev/null
}
# --- Fuzzy multi-keyword search ---
# OR mode: single git-log piped to awk (avoids N git calls per search term).
# AND mode: uses git's native --all-match --grep (already single-process).
# \x01 delimiter separates hash/date/subject for JSON output without collisions.
cmd_search() {
ensure_repo
[[ $# -eq 0 ]] && die "Usage: git-mem search [--json] <query words>"
local mode="or"
local json_mode=0
local terms=()
for arg in "$@"; do
case "$arg" in
--json) json_mode=1 ;;
+*) mode="and"; terms+=("${arg#+}") ;;
*) terms+=("$arg") ;;
esac
done
[[ ${#terms[@]} -eq 0 ]] && die "Usage: git-mem search [--json] <query words>"
# Single git call, then format for text or JSON
local terms_pipe
terms_pipe=$(printf '%s|' "${terms[@]}")
terms_pipe="${terms_pipe%|}"
local grep_args=()
if [[ "$mode" == "and" ]]; then
for term in "${terms[@]}"; do
grep_args+=(--grep="$term")
done
fi
# Choose format based on output mode
local fmt="%h %s"
[[ $json_mode -eq 1 ]] && fmt="%h%x01%aI%x01%s"
local raw_results
# Get retracted hashes once
local retracted_set
retracted_set=$(get_retracted_set)
if [[ "$mode" == "or" ]]; then
# Build retracted pattern for awk (pipe-separated full hashes)
local retracted_pipe
retracted_pipe=$(echo "$retracted_set" | paste -sd'|' 2>/dev/null || true)
raw_results=$(gc log --format="$fmt" --all 2>/dev/null | awk -v terms="$terms_pipe" -v retracted="$retracted_pipe" '
BEGIN { n = split(tolower(terms), tarr, "|") }
{
low = tolower($0)
# Skip retraction/restore meta-commits
if (index(low, "[retracted]") > 0) next
if (index(low, "[restored]") > 0) next
# Skip retracted original memories (match short hash at start of line)
if (retracted != "") {
split($0, parts, " ")
hash = parts[1]
# Also handle \x01 delimiter for JSON format
split(hash, hparts, "\x01")
hash = hparts[1]
rn = split(retracted, rarr, "|")
for (r = 1; r <= rn; r++) {
if (index(rarr[r], hash) == 1) next
}
}
for (i = 1; i <= n; i++) {
if (index(low, tarr[i]) > 0) { print; next }
}
}')
else
raw_results=$(gc log --format="$fmt" --all -i --all-match "${grep_args[@]}" 2>/dev/null || true)
# Filter out retraction/restore meta-commits and retracted originals
if [[ -n "$raw_results" ]]; then
raw_results=$(echo "$raw_results" | grep -iv '\[retracted\]' | grep -iv '\[restored\]' || true)
if [[ -n "$retracted_set" ]]; then
local filter_pattern
filter_pattern=$(echo "$retracted_set" | cut -c1-7 | sed 's/^/^/' | paste -sd'|')
raw_results=$(echo "$raw_results" | grep -ivE "$filter_pattern" || true)
fi
fi
fi
if [[ -z "$raw_results" ]]; then
if [[ $json_mode -eq 1 ]]; then
echo "[]"
else
echo "No results."
fi
elif [[ $json_mode -eq 1 ]]; then
local first=1
echo -n "["
while IFS=$'\x01' read -r hash date subj; do
[[ -z "$hash" ]] && continue
subj=$(json_escape_str "$subj")
[[ $first -eq 0 ]] && printf ","
first=0
printf '{"hash":"%s","date":"%s","subject":"%s"}' "$hash" "$date" "$subj"
done <<< "$raw_results"
echo "]"
else
echo -e "${COLOR_GREEN}Found:${COLOR_RESET}"
echo "$raw_results" | while IFS= read -r line; do
local hash="${line%% *}"
local rest="${line#* }"
echo -e " ${COLOR_CYAN}${hash}${COLOR_RESET} ${rest}"
done
fi
}
# --- Commands ---
cmd_init() {
if [[ -d "$GIT_MEMORY_DIR/.git" ]]; then
echo "Memory store already exists at $GIT_MEMORY_DIR"
gc log --oneline -5
return 0
fi
mkdir -p "$GIT_MEMORY_DIR"
git init "$GIT_MEMORY_DIR"
echo -e "${COLOR_GREEN}Memory store initialized at $GIT_MEMORY_DIR${COLOR_RESET}"
}
cmd_add() {
ensure_repo
local yes_mode=0
local args=()
for arg in "$@"; do
case "$arg" in
--yes|-y) yes_mode=1 ;;
*) args+=("$arg") ;;
esac
done
[[ ${#args[@]} -eq 0 ]] && die "Usage: git-mem add [--yes] \"[tags] summary\" [\"body\"]"
local subject="${args[0]}"
# Join all args after subject with newlines (handles Windows .cmd %* newline split)
local body=""
if [[ ${#args[@]} -gt 1 ]]; then
body=$(IFS=$'\n'; echo "${args[*]:1}")
fi
# Normalize and validate
subject=$(normalize_tags "$subject")
validate_tags "$subject"
# Check for duplicates
local full_msg="$subject"
[[ -n "$body" ]] && full_msg="$subject $body"
if ! check_dedup "$full_msg" "$yes_mode"; then
return 1
fi
# Store
if [[ -n "$body" ]]; then
gc commit --allow-empty -m "$subject" -m "$body"
else
gc commit --allow-empty -m "$subject"
fi
echo -e "${COLOR_GREEN}Stored.${COLOR_RESET}"
}
cmd_edit() {
ensure_repo
local tmpfile
tmpfile=$(mktemp "${TMPDIR:-/tmp}/git-mem-XXXXXX.md")
cat > "$tmpfile" <<'TEMPLATE'
# Enter your memory above this line.
# First line = subject (summary). Blank line, then body (details).
# Lines starting with # are ignored.
#
# Format: [tags] Keyword-rich summary
#
# Example:
# [dri][cosmosdb] RU exhaustion is container ceiling not partition
#
# 100% normalized RU can mean container-level ceiling hit.
# Fix: increase autoScaleMaxThroughput in Bicep.
TEMPLATE
"${EDITOR:-vi}" "$tmpfile"
# Parse: strip comments, extract subject and body
local content
content=$(grep -v '^#' "$tmpfile" | sed '/./,$!d') # remove comments, strip leading blanks
rm -f "$tmpfile"
[[ -z "$content" ]] && die "Empty message. Aborted."
local subject
subject=$(echo "$content" | head -1)
local body
body=$(echo "$content" | tail -n +3) # skip subject + blank line
subject=$(normalize_tags "$subject")
validate_tags "$subject"
local full_msg="$subject"
[[ -n "$body" ]] && full_msg="$subject $body"
if ! check_dedup "$full_msg"; then
return 1
fi
if [[ -n "$body" ]]; then
gc commit --allow-empty -m "$subject" -m "$body"
else
gc commit --allow-empty -m "$subject"
fi
echo -e "${COLOR_GREEN}Stored.${COLOR_RESET}"
}
cmd_show() {
ensure_repo
[[ $# -eq 0 ]] && die "Usage: git-mem show [--json] <hash>"
local json_mode=0
local hash=""
for arg in "$@"; do
case "$arg" in
--json) json_mode=1 ;;
*) hash="$arg" ;;
esac
done
[[ -z "$hash" ]] && die "Usage: git-mem show [--json] <hash>"
if [[ $json_mode -eq 1 ]]; then
# Single git call for all fields. \x01 delimiter + awk (not bash read)
# because read truncates multi-line body text.
local raw
raw=$(gc log -1 --format="%h%x01%aI%x01%s%x01%b" "$hash" 2>/dev/null) || die "Not found: $hash"
local short_hash date subj body
short_hash=$(echo "$raw" | awk -F'\x01' 'NR==1{print $1}')
date=$(echo "$raw" | awk -F'\x01' 'NR==1{print $2}')
subj=$(echo "$raw" | awk -F'\x01' 'NR==1{print $3}')
# Body is everything after the 3rd delimiter, may span multiple lines
body=$(echo "$raw" | awk -F'\x01' 'NR==1{sub(/^[^\x01]*\x01[^\x01]*\x01[^\x01]*\x01/,""); print} NR>1{print}')
subj=$(json_escape_str "$subj")
body=$(json_escape_str "$body")
printf '{"hash":"%s","date":"%s","subject":"%s","body":"%s"}\n' \
"$short_hash" "$date" "$subj" "$body"
else
gc log -1 --format="%C(yellow)%h%Creset %C(green)%aI%Creset%n%n%B" "$hash"
fi
}
cmd_recent() {
ensure_repo
local n="${1:-20}"
local retracted_set
retracted_set=$(get_retracted_set)
if [[ -n "$retracted_set" ]]; then
local filter_pattern
# Trim full hashes to 7-char prefix to match --oneline short hashes
filter_pattern=$(echo "$retracted_set" | cut -c1-7 | sed 's/^/^/' | paste -sd'|')
gc log --oneline --all 2>/dev/null \
| grep -Fv '[retracted]' | grep -Fv '[restored]' \
| grep -ivE "$filter_pattern" \
| head -"$n"
else
gc log --oneline --all 2>/dev/null \
| grep -Fv '[retracted]' | grep -Fv '[restored]' \
| head -"$n"
fi
}
cmd_tags() {
ensure_repo
echo -e "${COLOR_GREEN}Tags by frequency:${COLOR_RESET}"
gc log --format="%s" \
| grep -oE '\[[^]]+\]' \
| tr '[:upper:]' '[:lower:]' \
| sort \
| uniq -c \
| sort -rn \
| while read -r count tag; do
printf " %4d %s\n" "$count" "$tag"
done
}
cmd_stats() {
ensure_repo
local total
total=$(gc rev-list --count HEAD 2>/dev/null || echo 0)
local first_date last_date
local root_hash
root_hash=$(gc rev-list --max-parents=0 HEAD 2>/dev/null | head -1 || true)
first_date=$([[ -n "$root_hash" ]] && gc log -1 --format="%aI" "$root_hash" 2>/dev/null || true)
last_date=$(gc log --format="%aI" -1 2>/dev/null)
echo -e "${COLOR_GREEN}Memory store:${COLOR_RESET} $GIT_MEMORY_DIR"
echo -e "${COLOR_GREEN}Total memories:${COLOR_RESET} $total"
if [[ -n "$first_date" ]]; then
echo -e "${COLOR_GREEN}First:${COLOR_RESET} $first_date"
echo -e "${COLOR_GREEN}Latest:${COLOR_RESET} $last_date"
fi
# Tag breakdown
local tag_count
tag_count=$(gc log --format="%s" 2>/dev/null | grep -oE '\[[^]]+\]' | sort -u | grep -c . || echo 0)
echo -e "${COLOR_GREEN}Unique tags:${COLOR_RESET} $tag_count"
# Last 7 days
local recent
recent=$(gc log --oneline --since="7 days ago" 2>/dev/null | wc -l | tr -d ' ')
echo -e "${COLOR_GREEN}Last 7 days:${COLOR_RESET} $recent"
}
cmd_forget() {
ensure_repo
[[ $# -eq 0 ]] && die "Usage: git-mem forget <hash> [--reason \"reason\"]"
local hash=""
local reason=""
while [[ $# -gt 0 ]]; do
case "$1" in
--reason) shift; reason="${1:-}"; [[ -z "$reason" ]] && die "--reason requires a value" ;;
*) hash="$1" ;;
esac
shift
done
[[ -z "$hash" ]] && die "Usage: git-mem forget <hash> [--reason \"reason\"]"
# Verify the commit exists and get its details
local orig_subject orig_date full_hash
orig_subject=$(gc log -1 --format="%s" "$hash" 2>/dev/null) || die "Not found: $hash"
orig_date=$(gc log -1 --format="%aI" "$hash" 2>/dev/null)
full_hash=$(gc log -1 --format="%H" "$hash" 2>/dev/null)
# Check if already retracted
local retracted_set
retracted_set=$(get_retracted_set)
if echo "$retracted_set" | grep -q "$full_hash" 2>/dev/null; then
die "Already retracted. Use: git-mem resurface --restore $hash"
fi
# Build retraction commit
local body="Retracted: ${full_hash}\nOriginal date: ${orig_date}"
[[ -n "$reason" ]] && body="${body}\nReason: ${reason}"
gc commit --allow-empty -m "[retracted] ${orig_subject}" -m "$(echo -e "$body")"
echo -e "${COLOR_GREEN}Retracted:${COLOR_RESET} ${orig_subject}"
echo -e "${COLOR_DIM}(Original still exists. Restore with: git-mem resurface --restore ${hash})${COLOR_RESET}"
}
cmd_resurface() {
ensure_repo
local restore_mode=0
local restore_hash=""
local terms=()
local json_mode=0
for arg in "$@"; do
case "$arg" in
--restore) restore_mode=1 ;;
--json) json_mode=1 ;;
*)
if [[ $restore_mode -eq 1 && -z "$restore_hash" ]]; then
restore_hash="$arg"
else
terms+=("$arg")
fi
;;
esac
done
# --- Restore mode ---
if [[ $restore_mode -eq 1 ]]; then
[[ -z "$restore_hash" ]] && die "Usage: git-mem resurface --restore <hash>"
local orig_subject full_hash
orig_subject=$(gc log -1 --format="%s" "$restore_hash" 2>/dev/null) || die "Not found: $restore_hash"
full_hash=$(gc log -1 --format="%H" "$restore_hash" 2>/dev/null)
# Verify it's actually retracted
local retracted_set
retracted_set=$(get_retracted_set)
if ! echo "$retracted_set" | grep -q "$full_hash" 2>/dev/null; then
die "Not currently retracted: $restore_hash"
fi
gc commit --allow-empty -m "[restored] ${orig_subject}" -m "Restored: ${full_hash}"
echo -e "${COLOR_GREEN}Restored:${COLOR_RESET} ${orig_subject}"
return 0
fi
# --- Search retracted memories ---
local effective_retracted
effective_retracted=$(get_retracted_set)
if [[ -z "$effective_retracted" ]]; then
if [[ $json_mode -eq 1 ]]; then
echo "[]"
else
echo "No retracted memories."
fi
return 0
fi
# Get details for each retracted hash
local fmt="%h %s"
[[ $json_mode -eq 1 ]] && fmt="%h%x01%aI%x01%s"
local results=""
while IFS= read -r full_h; do
[[ -z "$full_h" ]] && continue
local line
line=$(gc log -1 --format="$fmt" "$full_h" 2>/dev/null || true)
[[ -z "$line" ]] && continue
# If search terms provided, filter
if [[ ${#terms[@]} -gt 0 ]]; then
local low
low=$(echo "$line" | tr '[:upper:]' '[:lower:]')
local matched=0
for term in "${terms[@]}"; do
local low_term
low_term=$(echo "$term" | tr '[:upper:]' '[:lower:]')
if [[ "$low" == *"$low_term"* ]]; then
matched=1
break
fi
done
[[ $matched -eq 0 ]] && continue
fi
results+="${line}"$'\n'
done <<< "$effective_retracted"
results=$(echo -n "$results" | sed '/^$/d')
if [[ -z "$results" ]]; then
if [[ $json_mode -eq 1 ]]; then
echo "[]"
else
echo "No results."
fi
elif [[ $json_mode -eq 1 ]]; then
local first=1
echo -n "["
while IFS=$'\x01' read -r hash date subj; do
[[ -z "$hash" ]] && continue
subj=$(json_escape_str "$subj")
[[ $first -eq 0 ]] && printf ","
first=0
printf '{"hash":"%s","date":"%s","subject":"%s","retracted":true}' "$hash" "$date" "$subj"
done <<< "$results"
echo "]"
else
echo -e "${COLOR_YELLOW}Retracted memories:${COLOR_RESET}"
echo "$results" | while IFS= read -r line; do
local hash="${line%% *}"
local rest="${line#* }"
echo -e " ${COLOR_DIM}${hash}${COLOR_RESET} ${rest}"
done
fi
}
cmd_sync() {
ensure_repo
local has_remote
has_remote=$(gc remote 2>/dev/null || true)
if [[ -z "$has_remote" ]]; then
die "No remote configured. Run: git -C $GIT_MEMORY_DIR remote add origin <url>"
fi
echo "Pulling with rebase..."
gc pull --rebase --autostash 2>&1 || die "Pull failed. Resolve manually."
echo "Pushing..."
gc push 2>&1 || die "Push failed."
echo -e "${COLOR_GREEN}Synced.${COLOR_RESET}"
}
cmd_export() {
ensure_repo
gc log --format="%H|%aI|%s%n%b%n---"
}
cmd_version() {
echo "git-mem ${GIT_MEM_VERSION}"
}
# --- Dispatch ---
cmd="${1:-help}"
shift 2>/dev/null || true
case "$cmd" in
init) cmd_init "$@" ;;
add|store|mem) cmd_add "$@" ;;
edit) cmd_edit "$@" ;;
search|recall|find|grep) cmd_search "$@" ;;
show) cmd_show "$@" ;;
forget|retract) cmd_forget "$@" ;;
resurface) cmd_resurface "$@" ;;
recent|ls) cmd_recent "$@" ;;
tags) cmd_tags "$@" ;;
stats) cmd_stats "$@" ;;
sync) cmd_sync "$@" ;;
export) cmd_export "$@" ;;
version|--version|-v) cmd_version ;;
help|--help|-h) usage ;;
*) die "Unknown command: $cmd. Run: git-mem help" ;;
esac