-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhalf-clone-conversation.sh
More file actions
executable file
·480 lines (410 loc) · 17.6 KB
/
half-clone-conversation.sh
File metadata and controls
executable file
·480 lines (410 loc) · 17.6 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
#!/usr/bin/env bash
#
# half-clone-conversation.sh - Claude Code 대화의 후반부 복제
#
# 순수 bash 구현 - Python/Node 의존성 없음.
# macOS (bash 3.2+) 및 Linux에서 동작합니다.
#
# 사용법:
# half-clone-conversation.sh <session-id> [project-path]
#
# 인수:
# session-id 복제할 대화의 UUID (필수)
# project-path 프로젝트 경로 (기본값: 현재 디렉토리)
#
# 예시:
# half-clone-conversation.sh d96c899d-7501-4e81-a31b-e0095bb3b501
# half-clone-conversation.sh d96c899d-7501-4e81-a31b-e0095bb3b501 /home/user/myproject
#
# 복제 후 'claude -r'을 사용하면 원본과 반복제된 대화를 모두 볼 수 있습니다.
#
set -euo pipefail
CLAUDE_DIR="${HOME}/.claude"
PROJECTS_DIR="${CLAUDE_DIR}/projects"
HISTORY_FILE="${CLAUDE_DIR}/history.jsonl"
TODOS_DIR="${CLAUDE_DIR}/todos"
# 출력용 색상
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'
log_info() { echo -e "${BLUE}[INFO]${NC} $1"; }
log_success() { echo -e "${GREEN}[SUCCESS]${NC} $1"; }
log_warning() { echo -e "${YELLOW}[WARNING]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1" >&2; }
usage() {
echo "사용법: $0 <session-id> [project-path]"
echo ""
echo "인수:"
echo " session-id 복제할 대화의 UUID (필수)"
echo " project-path 프로젝트 경로 (기본값: 현재 디렉토리)"
exit 1
}
# UUID 생성 - Mac과 Linux 모두에서 동작
generate_uuid() {
if command -v uuidgen &> /dev/null; then
uuidgen | tr '[:upper:]' '[:lower:]'
elif [ -f /proc/sys/kernel/random/uuid ]; then
cat /proc/sys/kernel/random/uuid
else
# $RANDOM을 사용한 대체 방법
printf '%04x%04x-%04x-%04x-%04x-%04x%04x%04x\n' \
$((RANDOM)) $((RANDOM)) $((RANDOM)) \
$((RANDOM & 0x0fff | 0x4000)) \
$((RANDOM & 0x3fff | 0x8000)) \
$((RANDOM)) $((RANDOM)) $((RANDOM))
fi
}
convert_path_to_dirname() {
echo "$1" | sed 's|^/||' | sed 's|/|-|g' | sed 's|^|-|'
}
find_conversation_file() {
local session_id="$1"
local project_path="$2"
local project_dirname
project_dirname=$(convert_path_to_dirname "$project_path")
local project_dir="${PROJECTS_DIR}/${project_dirname}"
local conv_file="${project_dir}/${session_id}.jsonl"
if [ -f "$conv_file" ]; then
echo "$conv_file"
return 0
fi
# 모든 프로젝트 디렉토리에서 찾기 시도
local found_file
found_file=$(find "$PROJECTS_DIR" -name "${session_id}.jsonl" 2>/dev/null | head -1)
if [ -n "$found_file" ]; then
echo "$found_file"
return 0
fi
return 1
}
get_project_from_conv_file() {
local conv_file="$1"
local project_dirname
project_dirname=$(dirname "$conv_file" | xargs basename)
echo "$project_dirname" | sed 's|^-|/|' | sed 's|-|/|g'
}
# awk 스크립트용 UUID 사전 생성
pre_generate_uuids() {
local count="$1"
local output_file="$2"
if command -v hexdump &> /dev/null; then
# 빠른 경로: hexdump
hexdump -vn $((count * 16)) -e '4/1 "%02x" "-" 2/1 "%02x" "-" 2/1 "%02x" "-" 2/1 "%02x" "-" 6/1 "%02x" "\n"' /dev/urandom > "$output_file"
elif [[ -r /proc/sys/kernel/random/uuid ]]; then
# Linux 대체
for ((i=0; i<count; i++)); do
cat /proc/sys/kernel/random/uuid
done > "$output_file"
elif command -v uuidgen &> /dev/null; then
# macOS/BSD 대체
for ((i=0; i<count; i++)); do
uuidgen | tr '[:upper:]' '[:lower:]'
done > "$output_file"
else
log_error "UUID 생성 방법을 찾을 수 없음 (hexdump, /proc/sys/kernel/random/uuid, 또는 uuidgen 필요)"
return 1
fi
}
preview_conversation() {
local source_session="$1"
local project_path="$2"
local source_file
if ! source_file=$(find_conversation_file "$source_session" "$project_path"); then
log_error "세션의 대화 파일을 찾을 수 없음: $source_session"
exit 1
fi
local total_lines
total_lines=$(wc -l < "$source_file" | tr -d ' ')
local first_user_text
first_user_text=$(grep '"type":"user"' "$source_file" | grep -v '"type":"tool_result"' | head -1 | \
grep -oE '"(content|text)":"[^"]*"' | head -1 | \
sed 's/"content":"//;s/"text":"//;s/"$//' | cut -c1-120 || true)
local last_user_text
last_user_text=$(grep '"type":"user"' "$source_file" | grep -v '"type":"tool_result"' | tail -1 | \
grep -oE '"(content|text)":"[^"]*"' | head -1 | \
sed 's/"content":"//;s/"text":"//;s/"$//' | cut -c1-120 || true)
echo "세션: $source_session"
echo "파일: $source_file"
echo "전체 라인 수: $total_lines"
echo "첫 메시지: ${first_user_text:-[추출 불가]}"
echo "마지막 메시지: ${last_user_text:-[추출 불가]}"
}
half_clone_conversation() {
local source_session="$1"
local project_path="$2"
# 복제 태그용 타임스탬프 생성 (예: "Jan 7 14:30")
local clone_timestamp
clone_timestamp=$(date "+%b %-d %H:%M")
local clone_tag="[HALF-CLONE ${clone_timestamp}]"
# 소스 파일 찾기
local source_file
if ! source_file=$(find_conversation_file "$source_session" "$project_path"); then
log_error "세션의 대화 파일을 찾을 수 없음: $source_session"
log_info "검색 위치: ${PROJECTS_DIR}"
log_info "사용 가능한 대화:"
find "$PROJECTS_DIR" -name "*.jsonl" -type f 2>/dev/null | while read -r f; do
local fname
fname=$(basename "$f")
if [[ ${#fname} -eq 42 && "$fname" =~ ^[a-f0-9-]+\.jsonl$ ]]; then
echo " - ${fname%.jsonl}"
fi
done
exit 1
fi
log_info "소스 대화 발견: $source_file"
if [ -z "$project_path" ]; then
project_path=$(get_project_from_conv_file "$source_file")
fi
# "깨끗한" 사용자 메시지 수 세기 (tool_result 제외 - 이들은 선행 tool_use가 필요)
# 깨끗한 사용자 메시지란 대화를 시작할 수 있는 메시지
local total_clean_user_messages
total_clean_user_messages=$(grep '"type":"user"' "$source_file" | grep -cv '"type":"tool_result"' || echo "0")
log_info "대화의 전체 깨끗한 사용자 메시지 수: $total_clean_user_messages"
if [ "$total_clean_user_messages" -lt 2 ]; then
log_error "대화에 깨끗한 사용자 메시지가 2개 미만이라 반복제할 수 없음"
exit 1
fi
# 어떤 깨끗한 사용자 메시지부터 시작할지 계산 (중간 지점)
local skip_clean_count
skip_clean_count=$((total_clean_user_messages / 2))
local keep_clean_count
keep_clean_count=$((total_clean_user_messages - skip_clean_count))
# 최적화: 대상 깨끗한 사용자 메시지가 시작하는 라인 번호 찾기
# grep -n을 사용하여 한 번에 모든 깨끗한 사용자 메시지 라인 번호 가져오기
local clean_user_line_numbers
clean_user_line_numbers=$(grep -n '"type":"user"' "$source_file" | grep -v '"type":"tool_result"' | cut -d: -f1)
# (skip_clean_count + 1)번째 깨끗한 사용자 메시지의 라인 번호 가져오기
local skip_count
skip_count=$(echo "$clean_user_line_numbers" | sed -n "$((skip_clean_count + 1))p")
# 이 라인 이전의 라인을 건너뛰므로 1을 빼기
skip_count=$((skip_count - 1))
log_info "처음 $skip_clean_count개의 깨끗한 사용자 메시지 건너뛰기 ($skip_count 라인), $keep_clean_count개의 깨끗한 사용자 메시지 유지"
# 새 세션 ID 생성
local new_session
new_session=$(generate_uuid)
log_info "새 세션 ID 생성됨: $new_session"
# 대상 파일
local project_dirname
project_dirname=$(convert_path_to_dirname "$project_path")
local project_dir="${PROJECTS_DIR}/${project_dirname}"
local target_file="${project_dir}/${new_session}.jsonl"
mkdir -p "$project_dir"
log_info "대화 반복제 중: $target_file"
# 최적화된 첫 번째 패스: 마지막 깨끗한 사용자 메시지가 clone/half-clone 명령인지 확인
# grep -n을 사용하여 한 번에 모든 사용자 메시지를 찾은 후 필터링
local stop_at_line=0
local last_clone_cmd_line=0
local last_clean_user_line=0
# 라인 번호와 함께 모든 사용자 메시지 라인 가져오기 (라인별 grep보다 훨씬 빠름)
# 깨끗한 사용자 메시지만 필터링 (tool_result 아님, isMeta 아님)
local clean_user_lines
clean_user_lines=$(grep -n '"type":"user"' "$source_file" | grep -v '"type":"tool_result"' | grep -v '"isMeta":true' || true)
if [ -n "$clean_user_lines" ]; then
# 마지막 깨끗한 사용자 메시지 라인 가져오기
local last_line_info
last_line_info=$(echo "$clean_user_lines" | tail -1)
last_clean_user_line=$(echo "$last_line_info" | cut -d: -f1)
# clone 명령인지 확인
if echo "$last_line_info" | grep -qE '<command-message>(dx:)?clone</command-message>|<command-message>(dx:)?half-clone</command-message>' 2>/dev/null; then
last_clone_cmd_line=$last_clean_user_line
fi
fi
# 마지막 깨끗한 사용자 메시지가 clone 명령이면 그 전에서 중지
if [ "$last_clone_cmd_line" -gt 0 ] && [ "$last_clone_cmd_line" -eq "$last_clean_user_line" ]; then
stop_at_line=$last_clone_cmd_line
log_info "/clone 명령 및 이후 메시지 제외 (라인 $stop_at_line부터)"
fi
# awk용 UUID 사전 생성 (추정: uuid, parentUuid, messageId에 라인당 3개)
local lines_to_process=$(($(wc -l < "$source_file") - skip_count))
local uuid_count=$((lines_to_process * 3 + 100)) # 추가 버퍼
local uuid_file
uuid_file=$(mktemp)
trap "rm -f '$uuid_file'" EXIT
log_info "UUID 사전 생성 중..."
pre_generate_uuids "$uuid_count" "$uuid_file"
# awk로 처리 - 단일 패스, 라인당 외부 명령 없음
log_info "awk로 처리 중..."
awk -v skip_count="$skip_count" \
-v stop_at_line="$stop_at_line" \
-v new_session="$new_session" \
-v clone_tag="$clone_tag" \
-v uuid_file="$uuid_file" '
BEGIN {
first_message = 1
first_user = 1
output_count = 0
uuid_idx = 0
# 사전 생성된 UUID 로드
while ((getline uuid < uuid_file) > 0) {
uuids[uuid_idx++] = uuid
}
close(uuid_file)
next_uuid = 0
}
function get_new_uuid(old_uuid) {
if (old_uuid in uuid_map) {
return uuid_map[old_uuid]
}
new_uuid = uuids[next_uuid++]
uuid_map[old_uuid] = new_uuid
return new_uuid
}
function extract_uuid(line, key, pattern, match_str, uuid) {
pattern = "\"" key "\":\"[a-f0-9][a-f0-9-]*[a-f0-9]\""
if (match(line, pattern)) {
match_str = substr(line, RSTART, RLENGTH)
# UUID 값만 추출
uuid = match_str
gsub("\"" key "\":\"", "", uuid)
gsub("\"", "", uuid)
return uuid
}
return ""
}
function halve_number(line, field, pattern, num, halved) {
pattern = "\"" field "\":[0-9]+"
if (match(line, pattern)) {
match_str = substr(line, RSTART, RLENGTH)
gsub("\"" field "\":", "", match_str)
num = int(match_str)
halved = int(num / 2)
gsub("\"" field "\":" num, "\"" field "\":" halved, line)
}
return line
}
NR <= skip_count { next }
stop_at_line > 0 && NR >= stop_at_line { exit }
/^$/ { next }
{
line = $0
# sessionId 교체
old_session = extract_uuid(line, "sessionId")
if (old_session != "") {
gsub("\"sessionId\":\"" old_session "\"", "\"sessionId\":\"" new_session "\"", line)
}
# uuid 교체 (parentUuid, sessionId 제외) - 독립적인 "uuid" 찾기
if (match(line, /"uuid":"[a-f0-9][a-f0-9-]*[a-f0-9]"/)) {
match_str = substr(line, RSTART, RLENGTH)
old_uuid = match_str
gsub("\"uuid\":\"", "", old_uuid)
gsub("\"", "", old_uuid)
new_uuid = get_new_uuid(old_uuid)
gsub("\"uuid\":\"" old_uuid "\"", "\"uuid\":\"" new_uuid "\"", line)
}
# parentUuid 처리
if (first_message) {
# 첫 번째 메시지의 parentUuid를 null로 설정
gsub(/"parentUuid":"[a-f0-9-]*"/, "\"parentUuid\":null", line)
first_message = 0
} else {
old_parent = extract_uuid(line, "parentUuid")
if (old_parent != "") {
new_parent = get_new_uuid(old_parent)
gsub("\"parentUuid\":\"" old_parent "\"", "\"parentUuid\":\"" new_parent "\"", line)
}
}
# messageId 교체
old_msgid = extract_uuid(line, "messageId")
if (old_msgid != "") {
new_msgid = get_new_uuid(old_msgid)
gsub("\"messageId\":\"" old_msgid "\"", "\"messageId\":\"" new_msgid "\"", line)
}
# 첫 번째 사용자 메시지에 태그 추가
if (first_user && index(line, "\"type\":\"user\"") > 0) {
gsub("\"content\":\"", "\"content\":\"" clone_tag " ", line)
gsub("\"text\":\"", "\"text\":\"" clone_tag " ", line)
first_user = 0
}
# 토큰 수 절반으로 줄이기
line = halve_number(line, "input_tokens")
line = halve_number(line, "cache_read_input_tokens")
line = halve_number(line, "cache_creation_input_tokens")
print line
}
' "$source_file" > "$target_file"
# 원본 대화로 연결되는 참조 메시지 추가
# 복제된 파일에서 마지막 uuid 찾기 ("uuid" 또는 "leafUuid"일 수 있음)
local last_uuid
last_uuid=$(tail -5 "$target_file" | grep -oE '"(uuid|leafUuid)":"[a-f0-9-]+"' | tail -1 | sed 's/.*"://;s/"//g' || true)
if [ -z "$last_uuid" ]; then
last_uuid=$(generate_uuid)
fi
local ref_uuid
ref_uuid=$(generate_uuid)
local ref_timestamp
ref_timestamp=$(date -u +"%Y-%m-%dT%H:%M:%S.000Z")
local ref_text="Note: this is a half-clone that only contains the later half of the original conversation. To see the full original conversation, check session \`${source_session}\` at: ${source_file}"
echo "{\"parentUuid\":\"${last_uuid}\",\"isSidechain\":false,\"userType\":\"external\",\"sessionId\":\"${new_session}\",\"type\":\"assistant\",\"message\":{\"role\":\"assistant\",\"content\":[{\"type\":\"text\",\"text\":\"${ref_text}\"}]},\"uuid\":\"${ref_uuid}\",\"timestamp\":\"${ref_timestamp}\",\"isMeta\":true}" >> "$target_file"
local output_line_count
output_line_count=$(wc -l < "$target_file" | tr -d ' ')
log_success "$output_line_count개의 메시지를 $target_file에 기록함"
# claude -r 목록 상단에 나타나도록 파일 수정 시간 갱신
touch "$target_file"
# history.jsonl 업데이트
log_info "히스토리 파일 업데이트 중..."
# 유지된 부분의 첫 번째 사용자 메시지에서 표시 텍스트 가져오기
local display_text
display_text=$(tail -n +"$((skip_count + 1))" "$source_file" | grep '"type":"user"' | head -1 | \
grep -oE '"content":"[^"]*"' | head -1 | \
sed 's/"content":"//;s/"$//' | \
head -c 200 || echo "[반복제된 대화]")
if [ -z "$display_text" ]; then
# 배열 형식 시도
display_text=$(tail -n +"$((skip_count + 1))" "$source_file" | grep '"type":"user"' | head -1 | \
grep -oE '"text":"[^"]*"' | head -1 | \
sed 's/"text":"//;s/"$//' | \
head -c 200 || echo "[반복제된 대화]")
fi
display_text="${clone_tag} ${display_text}"
# 타임스탬프 (밀리초)
local timestamp
if [[ "$OSTYPE" == "darwin"* ]]; then
timestamp=$(( $(date +%s) * 1000 + 1000 ))
else
timestamp=$(( $(date +%s%3N) + 1000 ))
fi
# JSON용 이스케이프
display_text=$(echo "$display_text" | sed 's/\\/\\\\/g' | sed 's/"/\\"/g' | tr '\n' ' ')
# 히스토리 항목 추가
echo "{\"display\":\"${display_text}\",\"pastedContents\":{},\"timestamp\":${timestamp},\"project\":\"${project_path}\",\"sessionId\":\"${new_session}\"}" >> "$HISTORY_FILE"
log_success "히스토리 항목 추가됨"
# 참고: 반복제의 경우 컨텍스트가 잘리므로 할 일 파일을 복사하지 않음
log_success "대화가 성공적으로 반복제되었습니다!"
echo ""
echo "원본 세션: $source_session"
echo "새 세션: $new_session"
echo "프로젝트: $project_path"
echo "깨끗한 사용자 메시지: $keep_clean_count / $total_clean_user_messages (처음 $skip_clean_count개 건너뜀)"
echo ""
echo "반복제된 대화를 이어가려면 다음을 사용하세요:"
echo " claude -r"
echo ""
echo "${clone_tag} 표시가 있는 대화를 선택하세요"
}
# 메인
PREVIEW_MODE=false
if [ "${1:-}" = "--preview" ]; then
PREVIEW_MODE=true
shift
fi
if [ $# -lt 1 ]; then
usage
fi
SESSION_ID="$1"
PROJECT_PATH="${2:-$(pwd)}"
# 세션 ID 유효성 검사
if ! [[ "$SESSION_ID" =~ ^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$ ]]; then
log_error "잘못된 세션 ID 형식. UUID 형식 예시: d96c899d-7501-4e81-a31b-e0095bb3b501"
exit 1
fi
if [ ! -d "$CLAUDE_DIR" ]; then
log_error "Claude 디렉토리를 찾을 수 없음: $CLAUDE_DIR"
exit 1
fi
if [ "$PREVIEW_MODE" = true ]; then
preview_conversation "$SESSION_ID" "$PROJECT_PATH"
else
half_clone_conversation "$SESSION_ID" "$PROJECT_PATH"
fi