-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfindsession
More file actions
executable file
·283 lines (241 loc) · 7.38 KB
/
findsession
File metadata and controls
executable file
·283 lines (241 loc) · 7.38 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
#!/usr/bin/env bash
set -euo pipefail
if [[ $# -lt 1 ]]; then
cat >&2 <<'EOF'
Usage: findsession <keyword> [context_chars]
Examples:
findsession ibm
findsession geofence 90
EOF
exit 1
fi
keyword="$1"
context_chars="${2:-80}"
RS=$'\036' # record separator for snippet lists
FS=$'\037' # field separator for sortable records
PY_SCRIPT=$(cat <<'PY'
import json
import os
import re
import sys
import time
from pathlib import Path
KEYWORD = os.environ['KEYWORD']
ASSISTANT = os.environ['ASSISTANT']
RADIUS = int(os.environ.get('CONTEXT_CHARS', '80'))
FS = os.environ['FS']
RS = os.environ['RS']
kw_lower = KEYWORD.lower()
kw_re = re.compile(re.escape(KEYWORD), re.IGNORECASE)
uuid_re = re.compile(r'[0-9a-fA-F]{8}-(?:[0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}')
ws_re = re.compile(r'\s+')
INJECT_TAGS = [
'system-reminder',
'command-name',
'command-message',
'command-args',
'local-command-stdout',
'local-command-stderr',
'user-prompt-submit-hook',
]
inject_res = [re.compile(rf'<{t}>.*?</{t}>', re.DOTALL) for t in INJECT_TAGS]
TRIVIAL = {
'resume', 'continue', 'go', 'ok', 'okay', 'y', 'yes', 'n', 'no',
'next', 'more', 'thanks', 'thank you',
}
def clean(s):
return ws_re.sub(' ', s).strip()
def strip_injections(s):
for pat in inject_res:
s = pat.sub('', s)
return s
def highlight(s):
return kw_re.sub(lambda m: f'[[{m.group(0).upper()}]]', s)
def make_snippet(text):
lc = text.lower()
pos = lc.find(kw_lower)
if pos < 0:
return None
start = max(0, pos - RADIUS)
length = len(KEYWORD) + 2 * RADIUS
segment = clean(text[start:start + length])
if not segment:
return None
return highlight('...' + segment + '...')
def iter_text_claude(rec):
t = rec.get('type')
if t not in ('user', 'assistant'):
return
msg = rec.get('message')
if not isinstance(msg, dict):
return
role = msg.get('role') or t
content = msg.get('content')
if isinstance(content, str):
yield role, content
elif isinstance(content, list):
for item in content:
if not isinstance(item, dict):
continue
itype = item.get('type')
if itype == 'text' and isinstance(item.get('text'), str):
yield role, item['text']
elif itype == 'thinking' and isinstance(item.get('thinking'), str):
yield role, item['thinking']
# tool_use and tool_result are skipped: metadata/noise
def iter_text_codex(rec):
# Codex duplicates each user/assistant turn in response_item messages and
# event_msg user_message/agent_message. Read only event_msg to avoid
# double-counting and to skip the huge developer-role base_instructions.
if rec.get('type') != 'event_msg':
return
payload = rec.get('payload')
if not isinstance(payload, dict):
return
pt = payload.get('type')
msg = payload.get('message')
if not isinstance(msg, str):
return
if pt == 'user_message':
yield 'user', msg
elif pt == 'agent_message':
yield 'assistant', msg
def session_id_claude(rec, current):
if current:
return current
return rec.get('sessionId')
def session_id_codex(rec, current):
if current:
return current
if rec.get('type') == 'session_meta':
payload = rec.get('payload')
if isinstance(payload, dict):
return payload.get('id')
return None
def sid_from_path(path):
stem = Path(path).stem
m = uuid_re.search(stem)
return m.group(0) if m else None
if ASSISTANT == 'Codex':
iter_text = iter_text_codex
get_sid = session_id_codex
resume_fmt = 'codex resume {}'
else:
iter_text = iter_text_claude
get_sid = session_id_claude
resume_fmt = 'claude --resume {}'
def process_file(path):
hits = 0
session_id = None
first_prompt = None
snippets = []
seen_snips = set()
try:
fh = open(path, encoding='utf-8', errors='replace')
except OSError:
return None
with fh:
for line in fh:
if not line.strip():
continue
# cheap pre-filter: if neither keyword nor session-id markers
# appear on the raw line, nothing interesting is here.
if kw_lower not in line.lower() and session_id is not None:
continue
try:
rec = json.loads(line)
except json.JSONDecodeError:
continue
session_id = get_sid(rec, session_id)
for role, text in iter_text(rec):
if not text:
continue
if first_prompt is None and role == 'user':
stripped = clean(strip_injections(text))
if len(stripped) >= 4 and stripped.lower() not in TRIVIAL:
first_prompt = stripped[:240]
lc = text.lower()
if kw_lower not in lc:
continue
hits += lc.count(kw_lower)
if len(snippets) < 3:
snip = make_snippet(text)
if snip and snip not in seen_snips:
snippets.append(snip)
seen_snips.add(snip)
if hits == 0:
return None
if session_id is None:
session_id = sid_from_path(path)
if not session_id:
return None
try:
epoch = int(os.stat(path).st_mtime)
except OSError:
return None
return {
'epoch': epoch,
'human': time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(epoch)),
'resume': resume_fmt.format(session_id),
'hits': hits,
'first': first_prompt or '',
'snippets': snippets,
}
def sanitize(s):
return s.replace(FS, ' ').replace(RS, ' ').replace('\n', ' ').replace('\r', ' ')
for raw in sys.stdin:
path = raw.rstrip('\n')
if not path:
continue
result = process_file(path)
if not result:
continue
snippets_joined = RS.join(sanitize(s) for s in result['snippets'])
fields = [
str(result['epoch']),
result['human'],
ASSISTANT,
result['resume'],
str(result['hits']),
sanitize(result['first']),
snippets_joined,
]
print(FS.join(fields))
PY
)
tmp="$(mktemp)"
trap 'rm -f "$tmp"' EXIT
process_matches() {
local assistant="$1"
local root="$2"
[[ -d "$root" ]] || return 0
# rg exits 1 when there are no matches; tolerate that so pipefail doesn't
# kill the whole script when a corpus has nothing to offer.
{ rg -l -F -i --glob '*.json' --glob '*.jsonl' -- "$keyword" "$root" 2>/dev/null || true; } |
KEYWORD="$keyword" \
CONTEXT_CHARS="$context_chars" \
ASSISTANT="$assistant" \
FS="$FS" \
RS="$RS" \
python3 -c "$PY_SCRIPT" >> "$tmp"
}
process_matches "Codex" "${CODEX_HOME:-$HOME/.codex}/sessions"
process_matches "Claude" "${CLAUDE_HOME:-$HOME/.claude}/projects"
if [[ ! -s "$tmp" ]]; then
echo "No matching resumable sessions found for: $keyword"
exit 0
fi
# Rank by content-hit count (desc), then recency (desc) as tiebreak.
sort -t "$FS" -k5,5nr -k1,1nr "$tmp" |
awk -v FS="$FS" -v RSN="$RS" '
!seen[$3 FS $4]++ {
printf "%-7s %s (%s hits)\n", $3, $2, $5
print "resume: " $4
if ($6 != "") print "Q: " $6
n = split($7, parts, RSN)
for (i = 1; i <= n; i++) {
if (parts[i] != "") print parts[i]
}
print ""
}
'