add-session-card
Skill15 starsChanged 3 months agoMITView on GitHub
Add a new analytics card to the session summary panel. Covers backend analyzer, database migration, API response, and frontend component with Storybook stories.
- Deletes or force-pushes
In this repository8 other files it gives its agents.
- backend/CLAUDE.mdCLAUDE.md
- CLAUDE.mdCLAUDE.md
- docs/CLAUDE.mdCLAUDE.md
- frontend/CLAUDE.mdCLAUDE.md
- backend-maintenanceSkill
- bugfixSkill
- cut-releaseSkill
- frontend-maintenanceSkill
The file
We split this skill into the rules it gives an agent
11 rules. About 0 are common, 7 are distinctive, and 4 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈7
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
- Distinctive: line 8
Add a new analytics card to the session summary panel following the card-per-table architecture.
- Distinctive: line 20
Use TodoWrite to track all phases.
- Distinctive: line 24
Before writing any code:
- Very specific: line 33
Create migration files in backend/internal/db/migrations/:
- Very specific: line 175
Update GetCards() to include new card
- Distinctive: line 209
Add card data schema:
- Distinctive: line 265
Import the card component
- Very specific: line 266
Add to cardRegistry array with appropriate order
- Distinctive: line 272
Add new card to expected cards list
- Very specific: line 322
Update backend/API.md with the new card schema in the analytics response.
- Distinctive: line 342
Component returns null: when data is empty:
≈ “Common” is an estimate: at least 1 in 5 of the 408,460 skill 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
Add Session Analytics Card
Add a new analytics card to the session summary panel following the card-per-table architecture.
Overview
The analytics system uses a card-per-table architecture where each card type has:
- Its own database table (
session_card_<name>) - Independent version constant for cache invalidation
- An analyzer that extracts metrics from a
FileCollection - Frontend component registered in the card registry
Instructions for Claude
Use TodoWrite to track all phases. This is a multi-step task requiring both backend and frontend changes.
Phase 1: Plan the Card
Before writing any code:
- Understand what metrics the card will display
- Identify which transcript line types contain the data
- Plan the database schema (what columns are needed)
- Plan the API response format
Phase 2: Backend - Database Migration
Create migration files in backend/internal/db/migrations/:
Up migration (000XXX_session_card_<name>.up.sql):
CREATE TABLE session_card_<name> (
session_id UUID PRIMARY KEY REFERENCES sessions(id) ON DELETE CASCADE,
version INT NOT NULL DEFAULT 1,
computed_at TIMESTAMPTZ NOT NULL,
up_to_line BIGINT NOT NULL,
-- card-specific columns (use snake_case)
my_metric BIGINT NOT NULL DEFAULT 0
);
CREATE INDEX idx_session_card_<name>_version ON session_card_<name>(version);Down migration (000XXX_session_card_<name>.down.sql):
DROP TABLE IF EXISTS session_card_<name>;Get the next migration number:
ls backend/internal/db/migrations/*.up.sql | sort | tail -1Phase 3: Backend - Card Types
In backend/internal/analytics/cards.go, add:
- Version constant (bump to invalidate all cached cards):
const <Name>CardVersion = 1- Record type (matches database schema):
type <Name>CardRecord struct {
SessionID string `json:"session_id"`
Version int `json:"version"`
ComputedAt time.Time `json:"computed_at"`
UpToLine int64 `json:"up_to_line"`
MyMetric int64 `json:"my_metric"`
}
func (c *<Name>CardRecord) IsValid(currentLineCount int64) bool {
return c != nil &&
c.Version == <Name>CardVersion &&
c.UpToLine == currentLineCount
}- API data type (JSON response):
type <Name>CardData struct {
MyMetric int64 `json:"my_metric"`
}- Add to Cards struct and AllValid()
Phase 4: Backend - Analyzer
Create backend/internal/analytics/analyzer_<name>.go:
package analytics
// <Name>Result contains <name> metrics.
type <Name>Result struct {
MyMetric int64
}
// <Name>Analyzer extracts <name> metrics from transcripts.
type <Name>Analyzer struct{}
// Analyze processes the file collection and returns <name> metrics.
func (a *<Name>Analyzer) Analyze(fc *FileCollection) (*<Name>Result, error) {
result := &<Name>Result{}
// Process files - typically main transcript, sometimes agents too
for _, line := range fc.Main.Lines {
// Use line helpers to extract data
if line.IsAssistantMessage() {
// Process assistant messages
}
if line.IsUserMessage() {
// Process user messages
}
}
return result, nil
}FileCollection methods:
fc.Main- main transcript filefc.Agents- slice of agent transcript filesfc.AllFiles()- iterate over main + all agents
TranscriptLine helpers:
IsUserMessage()- true for user messagesIsAssistantMessage()- true for assistant messages with usageIsHumanMessage()- true for human prompts (not tool results)IsToolResultMessage()- true for tool result messagesIsCompactBoundary()- true for compaction markersGetTimestamp()- parse timestampGetToolUses()- extract tool_use blocksGetContentBlocks()- get all content blocksGetAgentResults()- get subagent/Task resultsGetModel()- get model IDGetStopReason()- get stop reasonHasTextContent()- true if message has textHasThinking()- true if message has thinking block
Phase 5: Backend - Wire Up
- Add to ComputeResult in
compute_result.go:
// In ComputeResult struct
MyMetric int64- Run analyzer in
ComputeFromFileCollection():
<name>, err := (&<Name>Analyzer{}).Analyze(fc)
if err != nil {
return nil, err
}- Populate result in
ComputeFromFileCollection():
return &ComputeResult{
// ... existing fields ...
MyMetric: <name>.MyMetric,
}, nil- Store operations in
store.go:- Add
get<Name>Card()method - Add
upsert<Name>Card()method - Update
GetCards()to include new card - Update
UpsertCards()to include new card
- Add
- Card creation in
store.goToCards():
<Name>: &<Name>CardRecord{
SessionID: sessionID,
Version: <Name>CardVersion,
ComputedAt: now,
UpToLine: lineCount,
MyMetric: r.MyMetric,
},- API response in
store.goToResponse():
if c.<Name> != nil {
response.Cards["<name>"] = <Name>CardData{
MyMetric: c.<Name>.MyMetric,
}
}Phase 6: Backend - Tests
Run backend tests:
cd backend && DOCKER_HOST=unix:///Users/jackie/.orbstack/run/docker.sock go test ./...Phase 7: Frontend - Zod Schema
In frontend/src/schemas/api.ts:
- Add card data schema:
export const <Name>CardDataSchema = z.object({
my_metric: z.number(),
});- Add to
AnalyticsCardsSchema:
<name>: <Name>CardDataSchema.optional(),- Export type:
export type <Name>CardData = z.infer<typeof <Name>CardDataSchema>;Phase 8: Frontend - Card Component
Create frontend/src/components/session/cards/<Name>Card.tsx:
import { CardWrapper, StatRow, CardLoading } from './Card';
import type { <Name>CardData } from '@/schemas/api';
import type { CardProps } from './types';
const TOOLTIPS = {
myMetric: 'Description of what this metric means',
};
export function <Name>Card({ data, loading }: CardProps<<Name>CardData>) {
if (loading && !data) {
return (
<CardWrapper title="<Display Name>">
<CardLoading />
</CardWrapper>
);
}
if (!data) return null;
return (
<CardWrapper title="<Display Name>">
<StatRow
label="My Metric"
value={data.my_metric}
tooltip={TOOLTIPS.myMetric}
/>
</CardWrapper>
);
}Phase 9: Frontend - Register Card
- In
registry.ts:- Import the card component
- Add to
cardRegistryarray with appropriate order
- In
index.ts:- Export the card component
- Update
registry.test.ts:- Add new card to expected cards list
Phase 10: Frontend - Storybook
Create frontend/src/components/session/cards/<Name>Card.stories.tsx:
import type { Meta, StoryObj } from '@storybook/react-vite';
import { <Name>Card } from './<Name>Card';
const meta: Meta<typeof <Name>Card> = {
title: 'Session/Cards/<Name>Card',
component: <Name>Card,
parameters: { layout: 'centered' },
decorators: [
(Story) => (
<div style={{ width: '280px' }}>
<Story />
</div>
),
],
};
export default meta;
type Story = StoryObj<typeof <Name>Card>;
export const Default: Story = {
args: {
data: { my_metric: 42 },
loading: false,
},
};
export const Loading: Story = {
args: {
data: undefined,
loading: true,
},
};Phase 11: Frontend - Tests & Build
cd frontend && npm run build && npm run lint && npm test
cd frontend && npm run build-storybookPhase 12: Documentation
Update backend/API.md with the new card schema in the analytics response.
Common Patterns
Time-based invalidation
For cards that should refresh periodically:
func (c *<Name>CardRecord) IsValid(currentLineCount int64) bool {
if c == nil || c.Version != <Name>CardVersion {
return false
}
return time.Since(c.ComputedAt) < time.Hour
}Conditional rendering and grid layout
Cards that shouldn't show when empty need two things:
- Component returns null when data is empty:
if (data.total_count === 0) return null;- Registry has
shouldRenderto prevent empty grid cells:
{
key: 'my_card',
title: 'My Card',
component: MyCard,
order: 5,
span: 2, // Important: cards with span > 1 MUST have shouldRender
shouldRender: (data: MyCardData | null) => !!data && data.total_count > 0,
}Why both? The card component is wrapped in a <div> with grid span/size classes. If the component returns null but the wrapper is still rendered, CSS Grid reserves the columns for the empty div, creating gaps in the layout. The shouldRender function prevents the wrapper from rendering at all.
Rule of thumb: Any card that can return null based on data content (not just !data) should have a matching shouldRender function in the registry. This is especially critical for cards with span: 2 or span: 3.
Processing agent files
For metrics that include subagent data:
// Process all files - main and agents
for _, file := range fc.AllFiles() {
for _, line := range file.Lines {
// Process each line
}
}Building tool ID maps
For correlating tool_use with tool_result:
toolIDToName := file.BuildToolUseIDToNameMap()Checklist Before Commit
- Migration creates and drops table correctly
- Version constant is defined
- Analyzer extracts correct metrics
- Store operations handle get/upsert
- API response includes new card
- Zod schema validates card data
- Frontend component renders correctly
- Card is registered in registry
- If card can return null when empty,
shouldRenderis defined in registry - Storybook stories cover key states
- All backend tests pass
- All frontend tests pass
- API.md is updated
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.

