tokensafe 4.16.0 → 4.16.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,565 @@
1
+ """Transcript recall: search prior agent sessions for answers and decisions.
2
+
3
+ The index is built on demand from the host transcript files the engine already
4
+ discovers (``transcript_analyzer.discover_transcript_paths``). Nothing is copied
5
+ into a new database: a query streams the newest in-scope files, normalizes them
6
+ with the same extractors the history compactor uses, ranks turns with a small
7
+ stdlib BM25F, and renders a bounded pointer list.
8
+
9
+ Privacy: transcripts never leave the machine; snippets pass through the same
10
+ secret redactor the project memory uses.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import hashlib
16
+ import json
17
+ import os
18
+ import re
19
+ import time
20
+ from dataclasses import dataclass, field
21
+ from typing import Any, Dict, Iterable, Iterator, List, Optional, Sequence, Tuple
22
+
23
+ from src.paths import resolve_data_dir
24
+
25
+ MAX_FILES = 24
26
+ MAX_FILE_BYTES = 8 * 1024 * 1024
27
+ MAX_TURNS = 6000
28
+ DEFAULT_LIMIT = 10
29
+ DEFAULT_BUDGET = 6000
30
+ SNIPPET_CHARS = 260
31
+ MAX_SESSIONS_STATE = 200
32
+
33
+ _STOPWORDS = {
34
+ "the", "and", "for", "that", "with", "was", "were", "has", "have", "had",
35
+ "this", "from", "but", "not", "you", "your", "are", "what", "when", "where",
36
+ "how", "why", "did", "does", "can", "could", "should", "would", "there",
37
+ "their", "then", "than", "into", "over", "under", "about", "after", "before",
38
+ "use", "using", "used", "file", "files", "code", "line", "lines",
39
+ }
40
+
41
+ _ERROR_RE = re.compile(r"\b(traceback|assertionerror|exception|error|failed|failure|panic|fatal)\b", re.IGNORECASE)
42
+ _DECISION_RE = re.compile(r"\b(decided|decision|chose|chosen|opted|instead of|approach|trade.?off|root cause)\b", re.IGNORECASE)
43
+ _TODO_RE = re.compile(r"\b(todo|next step|pending|remaining|follow.?up|left to do|unresolved)\b", re.IGNORECASE)
44
+ _NOISE_RE = re.compile(r"(system-reminder|task-notification|local-command-caveat|protocolVersion)", re.IGNORECASE)
45
+ _TOKEN_RE = re.compile(r"[a-z0-9][a-z0-9._/+#-]*")
46
+
47
+
48
+ @dataclass
49
+ class Turn:
50
+ key: str
51
+ session: str
52
+ index: int
53
+ role: str
54
+ text: str
55
+ tool_text: str = ""
56
+ ts: str = ""
57
+ agent: str = ""
58
+ path: str = ""
59
+ record_index: int = 0
60
+ is_error: bool = False
61
+ is_decision: bool = False
62
+ is_todo: bool = False
63
+ uuid: str = ""
64
+
65
+ def searchable(self) -> str:
66
+ return f"{self.text}\n{self.tool_text}"
67
+
68
+
69
+ # ---------------------------------------------------------------------------
70
+ # session -> transcript persistence
71
+ # ---------------------------------------------------------------------------
72
+
73
+
74
+ def _state_path() -> str:
75
+ return os.path.join(resolve_data_dir(), "session_paths.json")
76
+
77
+
78
+ def _load_state() -> Dict[str, Dict[str, Any]]:
79
+ path = _state_path()
80
+ try:
81
+ with open(path, "r", encoding="utf-8") as fh:
82
+ data = json.load(fh)
83
+ return data if isinstance(data, dict) else {}
84
+ except Exception:
85
+ return {}
86
+
87
+
88
+ def remember_session(session_id: str, transcript_path: str, agent: str = "", cwd: str = "") -> None:
89
+ """Remember which transcript belongs to a hook session (best-effort)."""
90
+ sid = str(session_id or "").strip()
91
+ path = str(transcript_path or "").strip()
92
+ if not sid or not path:
93
+ return
94
+ try:
95
+ from src.atomic_io import write_text_atomic
96
+
97
+ state = _load_state()
98
+ state[sid] = {
99
+ "path": path,
100
+ "agent": agent,
101
+ "cwd": cwd or os.getcwd(),
102
+ "updated_at": int(time.time()),
103
+ }
104
+ if len(state) > MAX_SESSIONS_STATE:
105
+ newest = sorted(state.items(), key=lambda kv: int(kv[1].get("updated_at") or 0), reverse=True)
106
+ state = dict(newest[:MAX_SESSIONS_STATE])
107
+ write_text_atomic(_state_path(), json.dumps(state, indent=2, ensure_ascii=False) + "\n")
108
+ except Exception:
109
+ pass
110
+
111
+
112
+ def lookup_session(session_id: str) -> Optional[Dict[str, Any]]:
113
+ if not session_id:
114
+ return None
115
+ info = _load_state().get(str(session_id))
116
+ if not isinstance(info, dict):
117
+ return None
118
+ path = str(info.get("path") or "")
119
+ if not path or not os.path.exists(path):
120
+ return None
121
+ return info
122
+
123
+
124
+ # ---------------------------------------------------------------------------
125
+ # record / turn extraction
126
+ # ---------------------------------------------------------------------------
127
+
128
+
129
+ def _read_lines(path: str, max_bytes: int = MAX_FILE_BYTES) -> List[str]:
130
+ try:
131
+ size = os.path.getsize(path)
132
+ except OSError:
133
+ return []
134
+ try:
135
+ with open(path, "rb") as fh:
136
+ if size > max_bytes:
137
+ fh.seek(size - max_bytes)
138
+ fh.readline() # drop the partial first line
139
+ body = fh.read().decode("utf-8", errors="replace")
140
+ except OSError:
141
+ return []
142
+ return body.splitlines()
143
+
144
+
145
+ def read_records(path: str, max_bytes: int = MAX_FILE_BYTES) -> List[Dict[str, Any]]:
146
+ """JSONL records carrying their stable line index (for compaction boundaries)."""
147
+ records: List[Dict[str, Any]] = []
148
+ for idx, raw in enumerate(_read_lines(path, max_bytes)):
149
+ if not raw.strip():
150
+ continue
151
+ try:
152
+ parsed = json.loads(raw)
153
+ except Exception:
154
+ continue
155
+ if isinstance(parsed, dict):
156
+ parsed.setdefault("_record_index", idx)
157
+ records.append(parsed)
158
+ return records
159
+
160
+
161
+ def _block_text_local(content: Any) -> str:
162
+ if isinstance(content, str):
163
+ return content
164
+ if not isinstance(content, list):
165
+ return ""
166
+ parts: List[str] = []
167
+ for block in content:
168
+ if not isinstance(block, dict):
169
+ continue
170
+ btype = str(block.get("type") or "")
171
+ if btype in ("text", "thinking", "reasoning"):
172
+ text = block.get("text") or block.get("thinking")
173
+ if isinstance(text, str) and text:
174
+ parts.append(text)
175
+ elif btype == "tool_result":
176
+ nested = _block_text_local(block.get("content"))
177
+ if nested:
178
+ parts.append(nested)
179
+ return " ".join(parts)
180
+
181
+
182
+ def _tool_summary(calls: Iterable[Tuple[str, Dict[str, Any]]]) -> str:
183
+ out: List[str] = []
184
+ for name, args in calls:
185
+ if not isinstance(args, dict):
186
+ args = {}
187
+ detail = ""
188
+ for key in ("file_path", "path", "command", "pattern", "query", "target", "url"):
189
+ value = args.get(key)
190
+ if isinstance(value, str) and value.strip():
191
+ detail = value.strip().replace("\n", " ")[:120]
192
+ break
193
+ out.append(f"{name}({detail})" if detail else str(name))
194
+ return " ".join(out)[:400]
195
+
196
+
197
+ def _timestamp(rec: Dict[str, Any]) -> str:
198
+ for key in ("timestamp", "created_at", "createdAt", "startedAt", "time"):
199
+ value = rec.get(key)
200
+ if isinstance(value, str) and value.strip():
201
+ return value.strip()
202
+ msg = rec.get("message") if isinstance(rec.get("message"), dict) else {}
203
+ for key in ("timestamp", "created_at"):
204
+ value = msg.get(key)
205
+ if isinstance(value, str) and value.strip():
206
+ return value.strip()
207
+ return ""
208
+
209
+
210
+ def _role(rec: Dict[str, Any]) -> str:
211
+ msg = rec.get("message") if isinstance(rec.get("message"), dict) else rec
212
+ role = str(msg.get("role") or rec.get("role") or rec.get("source") or "").strip().lower()
213
+ if role in ("user", "human"):
214
+ return "user"
215
+ if role in ("assistant", "ai", "model"):
216
+ return "assistant"
217
+ payload = rec.get("payload") if isinstance(rec.get("payload"), dict) else {}
218
+ prole = str(payload.get("role") or payload.get("type") or "").strip().lower()
219
+ if prole in ("user", "human", "user_input"):
220
+ return "user"
221
+ return "assistant"
222
+
223
+
224
+ def _record_text(rec: Dict[str, Any]) -> Tuple[str, List[Tuple[str, Dict[str, Any]]], str]:
225
+ """(text, tool_calls, user_prompt) for every supported transcript schema."""
226
+ from src.history_compactor import _extract_step_text, _extract_step_tool_calls
227
+
228
+ if rec.get("type") == "model_io":
229
+ try:
230
+ from src.history_compactor import _model_io_parts
231
+
232
+ text, calls, prompt = _model_io_parts(rec)
233
+ return text, calls, prompt
234
+ except Exception:
235
+ pass
236
+ text = _extract_step_text(rec)
237
+ try:
238
+ calls = _extract_step_tool_calls(rec)
239
+ except Exception:
240
+ calls = []
241
+ return text, calls, ""
242
+
243
+
244
+ def iter_turns(path: str, agent: str = "", max_turns: int = MAX_TURNS) -> Iterator[Turn]:
245
+ """Yield normalized turns from one transcript file."""
246
+ yield from turns_from_records(read_records(path), path, agent, max_turns)
247
+
248
+
249
+ def turns_from_records(
250
+ records: Sequence[Dict[str, Any]],
251
+ path: str,
252
+ agent: str = "",
253
+ max_turns: int = MAX_TURNS,
254
+ ) -> Iterator[Turn]:
255
+ """Yield normalized turns from already-parsed JSONL records."""
256
+ from src.history_compactor import _is_injected_prompt
257
+
258
+ session = os.path.splitext(os.path.basename(path))[0] or "session"
259
+ produced = 0
260
+ for rec in records:
261
+ text, calls, prompt = _record_text(rec)
262
+ if rec.get("type") == "model_io" and prompt:
263
+ role = "user"
264
+ else:
265
+ role = _role(rec)
266
+ text = (text or "").strip()
267
+ tool_text = _tool_summary(calls)
268
+ if not text and not tool_text:
269
+ continue
270
+ if text and _is_injected_prompt(text):
271
+ continue
272
+ if _NOISE_RE.search(text[:400]):
273
+ continue
274
+ blob = f"{text}\n{tool_text}"
275
+ msg = rec.get("message") if isinstance(rec.get("message"), dict) else {}
276
+ uuid = str(rec.get("uuid") or msg.get("id") or "").strip()
277
+ turn = Turn(
278
+ key=f"{session}:{produced}",
279
+ session=session,
280
+ index=produced,
281
+ role=role,
282
+ text=text,
283
+ tool_text=tool_text,
284
+ ts=_timestamp(rec),
285
+ agent=agent,
286
+ path=path,
287
+ record_index=int(rec.get("_record_index") or 0),
288
+ is_error=bool(_ERROR_RE.search(blob)),
289
+ is_decision=bool(_DECISION_RE.search(blob)),
290
+ is_todo=bool(_TODO_RE.search(blob)),
291
+ uuid=uuid,
292
+ )
293
+ produced += 1
294
+ yield turn
295
+ if produced >= max_turns:
296
+ return
297
+
298
+
299
+ # ---------------------------------------------------------------------------
300
+ # ranking
301
+ # ---------------------------------------------------------------------------
302
+
303
+
304
+ def tokenize(text: str) -> List[str]:
305
+ return [t for t in _TOKEN_RE.findall((text or "").lower()) if len(t) > 1 and t not in _STOPWORDS]
306
+
307
+
308
+ def _bm25_terms(query_tokens: Sequence[str], docs: Sequence[Sequence[str]]) -> Dict[str, float]:
309
+ if not query_tokens:
310
+ return {}
311
+ n = max(1, len(docs))
312
+ avgdl = sum(len(d) for d in docs) / n or 1.0
313
+ df: Dict[str, int] = {}
314
+ for doc in docs:
315
+ for term in set(doc):
316
+ df[term] = df.get(term, 0) + 1
317
+ idf = {term: (n - df[term] + 0.5) / (df[term] + 0.5) for term in df}
318
+ return idf
319
+
320
+
321
+ def rank_turns(query: str, turns: Sequence[Turn], limit: int = DEFAULT_LIMIT) -> List[Tuple[float, Turn]]:
322
+ """BM25F over text+tool fields with category boosts and recency tie-breaks."""
323
+ query_tokens = tokenize(query)
324
+ docs = [tokenize(t.text) + tokenize(t.tool_text) for t in turns]
325
+ idf = _bm25_terms(query_tokens, docs)
326
+ k1, b = 1.2, 0.75
327
+ avgdl = (sum(len(d) for d in docs) / len(docs)) if docs else 1.0
328
+ scored: List[Tuple[float, Turn]] = []
329
+ for turn, doc in zip(turns, docs):
330
+ counts: Dict[str, int] = {}
331
+ for term in doc:
332
+ counts[term] = counts.get(term, 0) + 1
333
+ score = 0.0
334
+ for term in query_tokens:
335
+ tf = counts.get(term, 0)
336
+ if not tf:
337
+ continue
338
+ denom = tf + k1 * (1 - b + b * (len(doc) / (avgdl or 1.0)))
339
+ score += idf.get(term, 0.0) * (tf * (k1 + 1)) / (denom or 1.0)
340
+ if not query_tokens:
341
+ score = 1.0
342
+ if turn.is_error:
343
+ score *= 1.5
344
+ if turn.is_decision:
345
+ score *= 1.3
346
+ if turn.is_todo:
347
+ score *= 1.2
348
+ if score <= 0:
349
+ continue
350
+ scored.append((score, turn))
351
+ if not query_tokens:
352
+ # No query: newest actionable turns first.
353
+ scored.sort(key=lambda pair: (pair[1].is_error, pair[1].is_decision, pair[1].record_index), reverse=True)
354
+ else:
355
+ scored.sort(key=lambda pair: (pair[0], pair[1].record_index), reverse=True)
356
+ return scored[: max(1, limit)]
357
+
358
+
359
+ # ---------------------------------------------------------------------------
360
+ # discovery / scope
361
+ # ---------------------------------------------------------------------------
362
+
363
+
364
+ def _project_slug(cwd: str) -> str:
365
+ return str(cwd or "").rstrip("/").replace("/", "-").replace("\\", "-")
366
+
367
+
368
+ def _transcript_cwd(path: str) -> str:
369
+ for rec in read_records(path, max_bytes=256 * 1024)[:120]:
370
+ value = rec.get("cwd") or rec.get("workspace") or rec.get("project_path")
371
+ if isinstance(value, str) and value.strip():
372
+ return value.strip()
373
+ payload = rec.get("payload") if isinstance(rec.get("payload"), dict) else {}
374
+ value = payload.get("cwd")
375
+ if isinstance(value, str) and value.strip():
376
+ return value.strip()
377
+ return ""
378
+
379
+
380
+ def _matches_project(path: str, cwd: str) -> bool:
381
+ cwd = os.path.realpath(str(cwd or ""))
382
+ if not cwd or cwd == os.path.sep:
383
+ return True
384
+ recorded = _transcript_cwd(path)
385
+ if recorded:
386
+ return os.path.realpath(recorded) == cwd
387
+ slug = _project_slug(cwd)
388
+ return bool(slug) and slug in os.path.realpath(path).replace(os.path.sep, "-")
389
+
390
+
391
+ def discover(scope: str, cwd: str, session_id: str, transcript_path: str) -> List[Tuple[str, str]]:
392
+ """Resolve the (agent, path) list a scope refers to."""
393
+ scope = (scope or "project").lower()
394
+ if transcript_path and os.path.exists(transcript_path):
395
+ from src.transcript_analyzer import _detect_agent_from_path
396
+
397
+ return [(_detect_agent_from_path(transcript_path), transcript_path)]
398
+ if scope == "this":
399
+ info = lookup_session(session_id)
400
+ if info:
401
+ return [(str(info.get("agent") or ""), str(info.get("path") or ""))]
402
+ return []
403
+ from src.transcript_analyzer import discover_transcript_paths
404
+
405
+ entries = discover_transcript_paths(limit=MAX_FILES)
406
+ if scope == "all":
407
+ return [(agent, path) for agent, path, _mtime in entries[:MAX_FILES]]
408
+ matched = [(agent, path) for agent, path, _mtime in entries if _matches_project(path, cwd)]
409
+ if not matched and scope == "project":
410
+ # A project with no recorded cwd still gets the newest transcripts.
411
+ matched = [(agent, path) for agent, path, _mtime in entries[: min(6, len(entries))]]
412
+ return matched[:MAX_FILES]
413
+
414
+
415
+ # ---------------------------------------------------------------------------
416
+ # search / render
417
+ # ---------------------------------------------------------------------------
418
+
419
+
420
+ def _redact(text: str) -> str:
421
+ try:
422
+ from src.project_memory import _redact as redact
423
+
424
+ return redact(text)
425
+ except Exception:
426
+ return text
427
+
428
+
429
+ def _snippet(text: str, limit: int = SNIPPET_CHARS) -> str:
430
+ clean = " ".join((text or "").split())
431
+ clean = _redact(clean)
432
+ return clean[: limit - 1] + "…" if len(clean) > limit else clean
433
+
434
+
435
+ def _since_ok(ts: str, since: str, until: str) -> bool:
436
+ if not since and not until:
437
+ return True
438
+ if not ts:
439
+ return False
440
+ try:
441
+ from datetime import datetime
442
+
443
+ value = datetime.fromisoformat(ts.replace("Z", "+00:00"))
444
+ except Exception:
445
+ return True
446
+ try:
447
+ low = datetime.fromisoformat(since.replace("Z", "+00:00")) if since else None
448
+ high = datetime.fromisoformat(until.replace("Z", "+00:00")) if until else None
449
+ except Exception:
450
+ return True
451
+ try:
452
+ if low and value < low:
453
+ return False
454
+ if high and value > high:
455
+ return False
456
+ except TypeError:
457
+ return True
458
+ return True
459
+
460
+
461
+ def search(
462
+ query: str = "",
463
+ scope: str = "project",
464
+ cwd: str = "",
465
+ session_id: str = "",
466
+ transcript_path: str = "",
467
+ since: str = "",
468
+ until: str = "",
469
+ limit: int = DEFAULT_LIMIT,
470
+ budget_chars: int = DEFAULT_BUDGET,
471
+ ) -> Dict[str, Any]:
472
+ """Rank turns from the selected transcripts and render a bounded result."""
473
+ limit = max(1, min(int(limit or DEFAULT_LIMIT), 50))
474
+ paths = discover(scope, cwd, session_id, transcript_path)
475
+ turns: List[Turn] = []
476
+ seen: set = set()
477
+ for agent, path in paths:
478
+ for turn in iter_turns(path, agent):
479
+ if not _since_ok(turn.ts, since, until):
480
+ continue
481
+ digest = hashlib.sha1(turn.searchable().encode("utf-8", "replace")).hexdigest()
482
+ if digest in seen:
483
+ continue
484
+ seen.add(digest)
485
+ turns.append(turn)
486
+ if not turns:
487
+ return {
488
+ "query": query,
489
+ "scope": scope,
490
+ "files": len(paths),
491
+ "results": [],
492
+ "text": "[TS recall] no transcripts matched the requested scope.",
493
+ }
494
+ ranked = rank_turns(query, turns, limit=limit)
495
+ results: List[Dict[str, Any]] = []
496
+ total = 0
497
+ for score, turn in ranked:
498
+ item = {
499
+ "id": turn.key,
500
+ "session": turn.session,
501
+ "index": turn.index,
502
+ "role": turn.role,
503
+ "ts": turn.ts,
504
+ "score": round(score, 2),
505
+ "snippet": _snippet(turn.text or turn.tool_text),
506
+ "tools": turn.tool_text[:200],
507
+ "agent": turn.agent,
508
+ "path": turn.path,
509
+ }
510
+ size = len(item["snippet"]) + len(item["tools"]) + 80
511
+ if total + size > budget_chars and results:
512
+ break
513
+ total += size
514
+ results.append(item)
515
+ lines = [
516
+ f"[TS recall] {len(results)} result(s) · scope={scope} · files={len(paths)} · query={query!r}",
517
+ ]
518
+ for idx, item in enumerate(results, 1):
519
+ stamp = f" {item['ts']}" if item["ts"] else ""
520
+ tools = f" · tools: {item['tools']}" if item["tools"] else ""
521
+ lines.append(
522
+ f"{idx}. [{item['session']}#{item['index']} {item['role']}{stamp}] (score {item['score']})\n"
523
+ f" {item['snippet']}{tools}\n"
524
+ f" id: {item['id']}"
525
+ )
526
+ return {
527
+ "query": query,
528
+ "scope": scope,
529
+ "files": len(paths),
530
+ "results": results,
531
+ "text": "\n".join(lines)[: max(1000, budget_chars + 800)],
532
+ }
533
+
534
+
535
+ def drill_down(
536
+ turn_id: str,
537
+ scope: str = "all",
538
+ cwd: str = "",
539
+ session_id: str = "",
540
+ transcript_path: str = "",
541
+ ) -> Dict[str, Any]:
542
+ """Return one full turn for a ``session:index`` id from ``search``."""
543
+ raw = str(turn_id or "").strip()
544
+ if ":" not in raw:
545
+ return {"ok": False, "reason": "id must be <session>:<index>"}
546
+ session, _, index_text = raw.rpartition(":")
547
+ try:
548
+ wanted = int(index_text)
549
+ except ValueError:
550
+ return {"ok": False, "reason": "index must be an integer"}
551
+ for agent, path in discover(scope, cwd, session_id, transcript_path):
552
+ if os.path.splitext(os.path.basename(path))[0] != session:
553
+ continue
554
+ for turn in iter_turns(path, agent):
555
+ if turn.index == wanted:
556
+ return {
557
+ "ok": True,
558
+ "id": turn.key,
559
+ "role": turn.role,
560
+ "ts": turn.ts,
561
+ "text": _redact(turn.text),
562
+ "tools": turn.tool_text,
563
+ "path": path,
564
+ }
565
+ return {"ok": False, "reason": f"turn {raw} not found in discovered transcripts"}
@@ -198,6 +198,19 @@ def update_from_transcript(
198
198
  # at a fraction of the previous context and is billed uncached once.
199
199
  if totals["last_context_tokens"] >= 50_000 and context < totals["last_context_tokens"] * 0.5:
200
200
  totals["compactions"] += 1
201
+ # Hosts without PreCompact/PostCompact hooks only reveal the
202
+ # event here. Arm a one-shot recovery digest for the next
203
+ # session-start/prompt injection.
204
+ try:
205
+ from src.compaction_recovery import mark_pending
206
+ mark_pending(
207
+ session_id,
208
+ transcript_path=transcript_path,
209
+ agent=agent,
210
+ reason="context_drop",
211
+ )
212
+ except Exception:
213
+ pass
201
214
  totals["last_context_tokens"] = context
202
215
  totals["peak_context_tokens"] = max(totals["peak_context_tokens"], context)
203
216
  if miss:
@@ -17,7 +17,7 @@ import urllib.request
17
17
  import urllib.error
18
18
  from typing import Dict, Any, Optional, Tuple
19
19
 
20
- CURRENT_VERSION = "4.16.0"
20
+ CURRENT_VERSION = "4.16.2"
21
21
  CACHE_TTL = 86400 # 24 hours
22
22
  # When the cloud is unreachable we must NOT cache the synthesized "up to date"
23
23
  # answer for a full day — otherwise an update released right after an outage