crune
CLAUDE.md23 starsChanged 9 months agoApache-2.0View on GitHub
crune is a static web dashboard that visualizes Claude Code session logs. It consists of two parts: analyze-sessions.ts reads from ~/.claude/projects/ by default. Override with --sessions-dir and --output-dir flags. Before analysis, /insights is automatically executed via claude -p to refresh facets data in ~/.claude/usage-data/facets/. Use --skip-facets to skip this step. Output structure: The knowledge graph builder (knowledge-graph-builder.ts) uses a multi-signal embedding approach: - Text TF-IDF (weight 0.50) + Tool-IDF (weight 0.25) + structural features (weight 0.25), concatenated with sqrt-weighting -…
- Installs packages
The file
We split this CLAUDE.md into the rules it gives an agent
4 rules. About 0 are common, 0 are distinctive, and 4 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈0
Distinctive · estimate
This author's own choices. Worth a look.
4
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 40
Before analysis, /insights is automatically executed via claude -p to refresh facets data in ~/.claude/usage-data/facets/.
- Very specific: line 110
After a candidate is synthesized, analyze-sessions evaluates the generated SKILL.md via scripts/skill-evaluator.ts and persists the result …
- Very specific: line 124
UI badge: When candidate.evaluation exists, KnowledgeNodeDetail and TacitKnowledgeView render a compact評価バッジ --- 構造 OK/NG, スコア NN/100, …
- Very specific: line 182
All domain types are in src/types/session.ts.
≈ “Common” is an estimate: at least 1 in 5 of the 29,248 CLAUDE.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
CLAUDE.md
Project Overview
crune is a static web dashboard that visualizes Claude Code session logs. It consists of two parts:
- Data pipeline (
scripts/analyze-sessions.ts+scripts/knowledge-graph-builder.ts): Reads JSONL session files, extracts structured data, builds a semantic knowledge graph, and outputs JSON files topublic/data/sessions/. - Frontend (
src/): React SPA that loads the generated JSON and renders three views --- Overview, Session Playback, and Knowledge Graph.
Build & Run
npm install
npm run analyze-sessions # Generate data from ~/.claude/projects/
npm run dev # Vite dev server at localhost:5173
npm run build # tsc -b && vite build -> dist/
npm run lint # ESLint
npm run skill-server # Local synthesis server at localhost:3456
npm run dev:full # skill-server + Vite dev server togetherArchitecture
- No routing library ---
App.tsxmanages view state viauseState<ViewMode>(overview | playback | knowledge) - No state management library --- Data flows through props from
App.tsxdown. Each view fetches its own data via custom hooks (useSessionIndex,useSessionDetail,useSessionOverview) - Plain CSS --- Each component has a co-located
.cssfile. Global CSS variables are insrc/index.css(colors, fonts, shadows) - Session playback opens as a right-side drawer overlay, not a separate route
Key Conventions
- UI text is in Japanese (commit
abc92e1) - Color variables have semantic roles:
--accent(amber, interactive),--brand(amber, logo only — unified with accent),--success/warning/danger(status),--chart-1..6(data visualization) - Tool call display logic is centralized in
ToolCallBlock.tsxwith per-tool rendering (Bash, Edit, Write, Read, Grep, Glob, Agent) - Expand/collapse pattern:
useState(false)+ conditional render (no animation), seeSubagentBranch.tsx
Data Pipeline Details
analyze-sessions.ts reads from ~/.claude/projects/ by default. Override with --sessions-dir and --output-dir flags.
Before analysis, /insights is automatically executed via claude -p to refresh facets data in ~/.claude/usage-data/facets/. Use --skip-facets to skip this step.
Output structure:
public/data/sessions/
index.json # All sessions (sorted by createdAt desc)
overview.json # Cross-session stats + knowledge graph + tacit knowledge
detail/{sessionId}.json # Individual session turns, subagents, linked planThe knowledge graph builder (knowledge-graph-builder.ts) uses a multi-signal embedding approach:
- Text TF-IDF (weight 0.50) + Tool-IDF (weight 0.25) + structural features (weight 0.25), concatenated with sqrt-weighting
- Truncated SVD via Gram matrix power iteration (k = min(80, max(20, m/4)))
- Agglomerative clustering (average linkage) with elbow-detected threshold + oversized cluster splitting + facets-based narrow cluster merging
- Louvain community detection -> Brandes betweenness centrality
- See docs/knowledge-graph-algorithm.md for full details
/insights Integration
The pipeline reads /insights facets data (~/.claude/usage-data/facets/) to improve accuracy:
- Topic labels: Uses
underlying_goalfrom facets instead of TF-IDF keywords when available - Narrow cluster merging: Merges small clusters (≤2 sessions) that share normalized goal categories
- Reusability scoring: Adds
successRateandhelpfulnesssignals (weight 0.10 each) derived fromoutcomeandclaude_helpfulness - Synthesis prompt enrichment: Includes goals, friction details, and success rate in the LLM synthesis prompt
- Session list: Shows
brief_summaryfrom facets instead of raw first user prompt
Facets reader (scripts/knowledge-graph/facets-reader.ts) normalizes 50+ raw goal categories into ~10 canonical categories (feature, bugfix, refactoring, documentation, review, testing, ci, git_ops, setup, other).
Skill Synthesis
The pipeline detects recurring workflow patterns and generates reusable Claude Code skill definitions using LLM synthesis via claude -p.
Pre-synthesis (build time)
analyze-sessions automatically synthesizes the top skill candidates during data generation:
npm run analyze-sessions # Top 5 candidates, default model
npm run analyze-sessions -- --synthesize-model haiku # Use Haiku for speed
npm run analyze-sessions -- --synthesize-count 3 # Distill only top 3
npm run analyze-sessions -- --skip-synthesize # Skip synthesis entirelyFlags:
--synthesize-model <model>--- Use a specific Claude model (e.g.haiku,sonnet,opus)--synthesize-count <n>--- Number of top candidates to synthesize (default: 5)--skip-synthesize--- Skip LLM synthesis for faster builds--facets-dir <path>--- Custom facets directory (default:~/.claude/usage-data/facets)--skip-facets--- Skip/insightsrefresh and facets integration--use-human-feedback--- Fold playback feedback (issue #24) into synthesis + reusability scoring (default OFF for A/B)--feedback-file <path>--- Custom feedback file (defaultpublic/data/feedback.json)
Pre-synthesized results are stored in overview.json as synthesizedMarkdown on each SkillCandidate and displayed immediately in the Knowledge Graph UI. Synthesis output is post-processed by stripSynthesisPreamble() to remove any LLM preamble before the YAML frontmatter.
Synthesis calls use --no-session-persistence to prevent creating spurious JSONL session files.
On-demand re-synthesis
The UI provides a "再合成" button for on-demand re-synthesis with full graph context (connected topics, community, centrality). This requires the local skill server:
npm run dev:full # Runs skill-server + Vite dev serverThe skill server (scripts/skill-server.ts) accepts POST requests at /api/synthesize and calls claude -p with the enriched prompt including graph context.
Synthesis jobs are global (SkillSynthesisProvider, src/hooks/): each useSkillSynthesis(key) reads/triggers a job keyed by a stable id (topic id, or an adhoc:<sorted topic ids> slice id). The fetch lives in the provider, so a synthesis keeps running in the background and its result persists when you change filters, switch tabs, or deselect a node — coming back to the same key shows the running/finished job. (Earlier the state was component-local and was lost on unmount.)
Skill Evaluation (issue #20)
After a candidate is synthesized, analyze-sessions evaluates the generated SKILL.md via scripts/skill-evaluator.ts and persists the result onto SkillCandidate.evaluation (serialized into overview.json). Evaluation is gated behind synthesis success so heuristic skillMarkdown is never scored.
Three layers (evaluateSkill):
- Structural validation --- deterministic zod-backed YAML frontmatter checks (name kebab-case, description length, body present). Always runs locally.
- LLM rubric ---
claude -pscores the skill 0-100 across nameQuality / descriptionTriggering / instructionsConcrete / noPreambleNoise (25 each). Runs unless--skip-eval. - Smoke firing --- stubbed (deferred to a follow-up issue); always reports
skipped: true.
overallScore = 50 for structural pass + scaled rubric (0-50). toSkillEvaluation() strips the raw LLM response and intermediate parse before persistence.
Flags (next to the --synthesize-* flags, eval defaults ON):
--skip-eval--- Skip the LLM rubric (structural-only).--eval-model <model>--- Claude model for rubric scoring (e.g.haiku).--eval-threshold <n>--- Soft threshold (default 60). WhenoverallScore < n, the pipeline runs exactly one bounded re-synthesis retry and keeps the higher-scoring attempt. The candidate is never dropped; low scores are flagged in the UI.--eval-threshold 0disables retries. The retry decision is the pure functionshouldRetrySynthesis(score, threshold).
UI badge: When candidate.evaluation exists, KnowledgeNodeDetail and TacitKnowledgeView render a compact評価バッジ --- 構造 OK/NG, スコア NN/100, optional rubric内訳, and 改善ヒント list. Pass/borderline/fail tone uses --success/--warning/--danger (pass ≥70, borderline ≥50, fail otherwise or structural NG).
RAG Embedding Pipeline (issue #32, opt-in)
A chunk-level dense vector index for retrieval, alongside (not replacing) the whole-session embedding path in scripts/knowledge-graph/. PoC findings + Go/Hold/Pivot recommendation are in docs/rag-poc.md (issue #35).
Modules (scripts/knowledge-graph/):
embedder.ts---EmbeddingBackendinterface (injectable; tests use a deterministic fake, no network), turn-level chunk extraction (extractChunks:userPrompt + assistantTexts + tool namesper turn), int8quantize/dequantize(L2-normalized components →[-127,127], scale1/127, bounded round-trip error), andembedSessionsorchestration.embedding-io.ts---writeEmbeddingIndex/readEmbeddingIndex(public/data/embeddings/index.binrow-major int8 +meta.json) andcreateTransformersBackend(lazy-loaded Transformers.js,Xenova/paraphrase-multilingual-MiniLM-L12-v2, 384-dim, mean pooling + normalize). Kept separate so tests never import@huggingface/transformers.retriever.ts--- hybridcreateRetriever/createRetrieverFromIndex: dense cosine (dequantized) + sparse BM25 (reusesbuildBm25), per-query min-max normalized, blendedalpha*dense + (1-alpha)*bm25(defaultalpha=0.6), with a per-session diversification cap (default 2).retrieve(query, k, opts)returnsRetrievedChunk[].
Flags on analyze-sessions (default OFF, promotion gated on the PoC):
--embed--- run the embedder over analyzed sessions and writepublic/data/embeddings/.--embed-model <id>--- override the default model.
PoC harness: npx tsx scripts/rag-poc.ts (measures footprint / throughput / latency + A/B; --fake forces the no-network backend).
Retrieval-enriched synthesis (issue #33, opt-in)
--retrieval-context (on both analyze-sessions and the crune CLI, default OFF for clean A/B) swaps the loosely-related cluster-blob "examples" slot (Representative User Prompts + Enriched Tool Patterns) for a Retrieved Relevant Moments section built from the hybrid retriever's top-k turn snippets (k=8). The rest of the synthesis prompt (frontmatter ask, topic info, graph position, human-flagged moments, heuristic reference) is unchanged.
- Query per candidate:
buildRetrievalQuery(candidate, topic)= topic label + top keywords + truncated heuristicskillMarkdown(600 chars). Pure/testable. - Section:
buildRetrievedMomentsSection(chunks)renders[sessionId#turnIndex] (score: N.NNN) snippet;SynthesisRequest.retrievedContext?: RetrievedChunk[]threads it intobuildSynthesisPrompt. When present and non-empty, the blob slots are suppressed and a numbered task rule grounds the skill in the retrieved moments. - Retriever wiring (
buildSynthesisRetriever, shared viascripts/knowledge-graph/synthesis-retriever.ts): reuse the EmbedResult from--embedif it ran this run → else read an on-disk index atpublic/data/embeddings/→ else embed fresh in-memory viacreateTransformersBackend+embedSessions. Index reuse is gated on per-chunksessionId/turnIndexidentity (chunksAlign), not just count, so a stale index can't ground synthesis on unrelated sessions. BM25 text is re-derived withextractChunks(same chunk order as the index). On any failure (no index, no backend) it logs a warning and returnsnullso synthesis FALLS BACK to the cluster blob (never crashes). - Preview A/B (
crune --preview --retrieval-context): the synthesis loop printsContext strategy: retrieval (N moments)vscluster blobper candidate so a human can compare side by side. - Measurement: the #20 evaluator path (
overallScore) is unchanged — run--retrieval-contextvs without and compareSkillCandidate.evaluation.overallScoreto A/B synthesis quality. Tests inject a fakeEmbeddingBackend/in-memory retriever; theclaude -pcall stays behind thesynthesizeWithClaudeseam (never invoked in tests).
Semantic Search UI (issue #34)
The chunk index powers a UI semantic search and a "似た瞬間" bookmark affordance, served by the skill-server.
- Endpoint:
POST /api/retrieve(scripts/skill-server.ts, proxied byvite.config.ts). Body{ query, k? }→{ results: RetrievedChunk[] }. The on-disk index is resolved lazily bycreateLazyRetrieverProvider(scripts/retrieve-service.ts); a successful retriever is memoized ONCE and reused (the model is never reloaded per request), while negative resolutions are NOT cached so a server started before--embedran recovers once the index appears — no restart. The provider builds the embedding backend from the loaded index's ownmeta.model/meta.dim(via an injectedBackendFactory) so query vectors always match the chunk vectors even when the index was embedded with--embed-model. Resolution distinguishes an ABSENT index (400{error:'no embedding index; run analyze-sessions --embed'}) from a CORRUPT/unreadable one (503, logged viaconsole.error), so the UI degrades gracefully without telling the user to re-run a command that won't help. The purehandleRetrieveRequestis unit-tested with an injectedRetrieverResolution. - BM25 fallback:
meta.jsonpersists only the short snippet, so BM25 runs over snippets as a documented degraded fallback; dense cosine (alpha=0.6) remains the primary signal. - Hook:
src/hooks/useSemanticSearch.ts— debounced (SEARCH_DEBOUNCE_MS) best-effort POST; puremapRetrieveResponse(ok, body, status)maps the HTTP status (503 → "モデル準備中", 404 → "検索未対応", else generic) and purerunSearchRequestencapsulates the stale-response guard — both tested without a DOM. - UI:
SemanticSearchbar on the Overview dashboard (src/components/search/); clicking a result opens the playback drawer at the matched turn via an optionalturnIndexononSessionSelect(App →SessionPlayback initialTurnIndex). On a bookmarked turn,FeedbackClustershows a 🔍 "このブックマークに似た瞬間" popover (SimilarMoments) that searches with the turn's text and deep-links similar moments. - Static-deploy note: in-browser retrieval (loading the ~93KB quantized index + a WASM embedder) is a viable follow-up; the current PoC routes through the local server.
Session Summarization
セッション一覧の firstUserPrompt フィールドは、facetsデータが利用可能な場合は /insights の brief_summary(LLM生成の要約)で置き換えられる。facetsがないセッションは従来通り最初のユーザープロンプトを表示する。
scripts/session-summarizer.ts generates per-session summaries locally without LLM, using plan mode prompts as the primary source.
Algorithm:
- Collect all user prompts from plan mode turns (fallback: all user prompts)
- Select representative prompt via Jaccard centrality with position weighting (
1/(1+index)) - Extract top-5 keywords via tokenizer + stopword filtering
- Classify
workTypefrom tool histogram:investigation--- Read/Grep/Glob dominant (70%+)implementation--- Edit/Write dominant (40%+)debugging--- Bash dominant (40%+) with some writesplanning--- plan mode with few turns and no writes
- Compute
scopefrom longest common directory prefix of edited files
Output fields on SessionSummary: summaryText, keywords, scope, workType
Type Definitions
All domain types are in src/types/session.ts. Key types:
SessionIndex,SessionSummary--- session list (includessummaryText,keywords,scope,workType)SessionDetail,ConversationTurn,AssistantBlock--- playback dataKnowledgeGraph,TopicNode,TopicEdge--- graph dataReusabilityScore--- includessuccessRate?andhelpfulness?(facets-derived, optional)SkillCandidate--- includesskillMarkdown(heuristic),synthesizedMarkdown(LLM-synthesized), andevaluation(SkillEvaluation, issue #20)SkillEvaluation--- persisted evaluation:structural, optionalrubric, optionalsmokeFiring(stub),overallScoreGraphContext,ConnectedTopicInfo--- graph context for synthesisTacitKnowledge,WorkflowPattern--- extracted insights
Pipeline-internal types in scripts/knowledge-graph/types.ts:
FacetsData--- parsed/insightsfacets data per sessionFacetsInsightsSummary--- aggregated facets for a topic (goals, categories, success rate, frictions)
Human Feedback (issue #24)
Playback feedback (bookmark / tag / note, issue #23) is fed into skill synthesis as a human signal.
Persistence bridge: localStorage (crune.feedback.v1) stays the offline source of truth. The UI best-effort POSTs each session's entries to the skill-server (POST /api/feedback, fire-and-forget via src/components/playback/feedback/feedbackSync.ts), which merges them into public/data/feedback.json (GET /api/feedback reads it back). The offline pipeline reads that file via scripts/feedback-reader.ts.
Meaningful tags (free-text otherwise; constants in src/components/playback/feedback/tagSemantics.ts and mirrored in scripts/feedback-reader.ts):
reusable--- this turn is VALUABLE evidence to replicate in a skill.anti-pattern--- this turn is a counter-example; skills should avoid it.
Both are surfaced first in the TagInput datalist.
Synthesis (gated behind --use-human-feedback, default OFF for A/B): buildSynthesisPrompt adds a "Human-Flagged Moments" section listing bookmarked turns, reusable turns marked as evidence to replicate, and anti-pattern turns marked as counter-examples to avoid. --feedback-file <path> overrides the default public/data/feedback.json.
Reusability score: an optional humanSignal term (ReusabilityScore.humanSignal, weight 0.10) boosts clusters with bookmarks/reusable tags and dampens for anti-pattern, folded in alongside successRate/helpfulness.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

