Repository navigation
Expand file tree
/
Copy pathprocgrep_view.py
More file actions
148 lines (125 loc) · 5.35 KB
/
Copy pathprocgrep_view.py
File metadata and controls
148 lines (125 loc) · 5.35 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
"""Open the live procedural fingerprint panel on YOUR local Claude Code and Cursor sessions.
Local-first and privacy-first. It reads the transcripts Claude Code already
writes under ``~/.claude/projects`` on this machine, reduces each to the panel's
session shape (atoms + prompt-anchored turns) with ``build_panel_session``,
runs the online intent-cliff detector on each session's action stream, injects
them into a copy of ``docs/live_fingerprint.html``, and opens it. Nothing
leaves the machine.
The conversation (prompt text) is sampled for this local view by default. Pass
``--paraphrase`` -- a local command that rewrites a prompt (stripping writing
style and identifiers) on stdin/stdout -- to normalize prompts before you share
or screenshot. The only sanctioned thing to share is
``to_shareable(record)`` (atoms + hashed id + counts), not this local HTML.
Usage:
python examples/procgrep_view.py
python examples/procgrep_view.py --path ~/.claude/projects --limit 12
python examples/procgrep_view.py --paraphrase "ollama run llama3 'rewrite, strip style and identifiers, one line:'"
"""
from __future__ import annotations
import argparse
import glob
import json
import subprocess
import tempfile
import webbrowser
from collections.abc import Callable
from pathlib import Path
from typing import Any
from procgrep.cliff import enrich_panel_session
from procgrep.ingest.adapters.claude_code import build_panel_session
from procgrep.ingest.adapters.cursor_vscdb import build_panel_sessions as build_cursor_sessions
from procgrep.ingest.clients import find_client
PANEL = Path(__file__).resolve().parent.parent / "docs" / "live_fingerprint.html"
def _make_paraphraser(cmd: str | None) -> Callable[[str], str] | None:
"""A local rewriter: pipe the prompt through ``cmd`` (stdin -> stdout)."""
if not cmd:
return None
def paraphrase(text: str) -> str:
try:
done = subprocess.run(
cmd, shell=True, input=text, capture_output=True, text=True, timeout=60
)
except (OSError, subprocess.SubprocessError):
return ""
out = done.stdout.strip().splitlines()
return out[0].strip() if out else ""
return paraphrase
def _read_lines(path: str) -> list[dict[str, Any]]:
lines: list[dict[str, Any]] = []
for raw in Path(path).read_text(errors="ignore").splitlines():
raw = raw.strip()
if not raw:
continue
try:
parsed = json.loads(raw)
except json.JSONDecodeError:
continue
if isinstance(parsed, dict):
lines.append(parsed)
return lines
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--path", default="~/.claude/projects", help="directory of Claude Code transcripts"
)
parser.add_argument(
"--cursor",
default=None,
help="Cursor state.vscdb to include; found automatically when omitted, skipped if absent",
)
parser.add_argument("--limit", type=int, default=12, help="most recent N Claude Code sessions")
parser.add_argument(
"--paraphrase",
default=None,
help="local command to rewrite prompts (stdin->stdout) for sharing; omit to keep raw local prompts",
)
args = parser.parse_args()
base = Path(args.path).expanduser()
files = sorted(glob.glob(str(base / "*" / "*.jsonl"))) + sorted(
glob.glob(str(base / "*.jsonl"))
)
paraphrase = _make_paraphraser(args.paraphrase)
sessions = []
for file in files[-args.limit :]:
panel = enrich_panel_session(
build_panel_session({"events": _read_lines(file)}, paraphrase=paraphrase)
)
if len(panel["turns"]) >= 3:
sessions.append(panel)
n_cc = len(sessions)
cursor = find_client("cursor", path=args.cursor)
if cursor is not None:
for panel in build_cursor_sessions(cursor.path, paraphrase=paraphrase, limit=args.limit):
panel = enrich_panel_session(panel)
if len(panel["turns"]) >= 3:
sessions.append(panel)
n_cursor = len(sessions) - n_cc
if not sessions:
print(
f"No usable Claude Code transcripts under {base} or Cursor sessions. Opening the demo."
)
webbrowser.open(PANEL.as_uri())
return
sessions.reverse() # newest first in the nav
html = PANEL.read_text()
# Inline the shared theme so the temp file stays self-contained off /tmp,
# where the relative stylesheet link would not resolve.
theme = (PANEL.parent / "assets" / "css" / "theme.css").read_text()
html = html.replace(
'<link rel="stylesheet" href="assets/css/theme.css">', f"<style>{theme}</style>"
)
inject = f"<script>window.PROCGREP_SESSIONS={json.dumps(sessions)};</script>\n"
html = html.replace("<script>", inject + "<script>", 1)
out = Path(tempfile.gettempdir()) / "procgrep_view.html"
out.write_text(html)
webbrowser.open(out.as_uri())
note = (
"paraphrased prompts"
if paraphrase
else "raw local prompts (pass --paraphrase to normalize for sharing)"
)
print(f"opened {len(sessions)} session(s): {n_cc} Claude Code, {n_cursor} Cursor, with {note}")
print(f" {out}")
print(" (local file containing your own data — do not share it; use to_shareable() to export)")
if __name__ == "__main__":
main()