Skip to content

Latest commit

 

History

History
629 lines (417 loc) · 20.7 KB

how-to.md

File metadata and controls

629 lines (417 loc) · 20.7 KB

Subspan — How-To Guide

Subspan is a coding-agent observatory. It scans git history to detect sessions authored by AI coding agents (Claude Code, Cursor, Copilot, Codex, etc.), lets Claude Code push live tool-call and cost data via hooks, and presents everything in a real-time dashboard.


Table of Contents

  1. Installation
  2. First Run
  3. Tracking Repositories
  4. Scanning for Sessions
  5. Claude Code Hook Integration
  6. Dashboard Overview
  7. Sessions Page
  8. Session Detail
  9. Cost Budgets
  10. Team Management
  11. Exporting Data
  12. CLI Reference
  13. Troubleshooting

1. Installation

Requirements: Node.js 22 LTS, Git, a GitHub account (for OAuth).

git clone <repo-url>
cd subspan
npm install

Create a GitHub OAuth App

  1. Go to GitHub → Settings → Developer settings → OAuth Apps → New OAuth App
  2. Set:
    • Homepage URL: http://localhost:3000
    • Authorization callback URL: http://localhost:3000/api/auth/callback/github
  3. Copy the Client ID and generate a Client Secret

Configure environment

cp .env.local.example .env.local

Edit .env.local:

GITHUB_CLIENT_ID=your_client_id_here
GITHUB_CLIENT_SECRET=your_client_secret_here
AUTH_SECRET=any-random-32-character-string
NEXTAUTH_URL=http://localhost:3000

2. First Run

Build and start the server:

npm run build
npm start

Open http://localhost:3000 and sign in with GitHub.

Important: Always use npm start (or npm run dev for development). Never run next dev directly — the custom HTTP server (server.ts) is required for WebSocket live-update support.

Node version: Subspan requires Node 22 LTS for the dev server. If you have multiple Node versions installed via Homebrew, use PATH="/opt/homebrew/opt/node@22/bin:$PATH" npm run dev.

(Optional) Load demo data

With the server running on port 3000:

node scripts/seed.mjs

This creates 11 simulated sessions across two demo projects so you can explore the dashboard without needing real agent data.


3. Tracking Repositories

A "tracked repository" is a git repo that Subspan will scan for agent-authored commits.

Via the Settings UI

  1. Go to Settings (gear icon in the sidebar)
  2. Enter the absolute path to your repository
  3. Click Add Repository

Via CLI

./node_modules/.bin/tsx cli/index.ts track /path/to/your-repo
./node_modules/.bin/tsx cli/index.ts track /path/to/your-repo --name "My Project"

List tracked repositories

./node_modules/.bin/tsx cli/index.ts list

Remove a repository

./node_modules/.bin/tsx cli/index.ts untrack my-project

4. Scanning for Sessions

Scanning reads git commit history and groups agent-authored commits into sessions.

How agent detection works

Subspan checks each commit in order:

  1. Co-Authored-By: tags in the commit message (highest confidence)
  2. Commit message patterns (e.g. 🤖 Generated with Claude)
  3. Author email patterns
  4. Custom rules from config

Commits with low confidence are grouped as agent: unknown.

How sessions are clustered

Commits by the same (author, branch) pair are grouped into sessions. A new session starts when the gap between commits exceeds 120 minutes (configurable).

Trigger a scan

Via UI: Go to Settings and click Scan Now.

Via CLI:

# Scan all tracked repositories
./node_modules/.bin/tsx cli/index.ts scan

# Scan a specific project
./node_modules/.bin/tsx cli/index.ts scan my-project

Continuous background scanning

./node_modules/.bin/tsx cli/index.ts watch
./node_modules/.bin/tsx cli/index.ts watch --interval 10m   # every 10 minutes
./node_modules/.bin/tsx cli/index.ts watch --interval 1h    # every hour

Interval format: 30s, 5m, 1h. Default is 5m.


5. Claude Code Hook Integration

Hooks give Subspan real-time visibility into your Claude Code sessions — every tool call, token cost, and context usage is streamed live as it happens.

Install hooks

./node_modules/.bin/tsx cli/index.ts hooks install

This writes four hooks (PreToolUse, PostToolUse, Notification, Stop) into ~/.claude/settings.json. No server restart or npm link required.

Verify installation

./node_modules/.bin/tsx cli/index.ts hooks status

What hooks capture

Hook Data captured
PreToolUse Tool name, input, subagent spawns (Task calls)
PostToolUse Tool output, duration, success/error status
Notification Context window usage (input tokens, cache tokens, model)
Stop Session end; triggers cost + subagent metric aggregation

How hooks identify your session

Hooks use Claude Code's session_id and the current working directory to associate tool calls with the right project. Make sure to run Claude Code from inside a tracked repository directory.

Remove hooks

./node_modules/.bin/tsx cli/index.ts hooks uninstall

6. Dashboard Overview

The dashboard (/dashboard) gives a live overview of all agent activity.

KPI Cards (top row)

Card What it shows
Total Sessions All-time session count; live count in sublabel
Total Cost Cumulative USD cost across all sessions
Tool Calls Total tool invocations tracked via hooks
Success Rate Completed sessions as a percentage of all finished sessions
Cache Hit Rate Prompt cache efficiency: read tokens / (read + write tokens)
Budget Usage Current month spend vs your org-wide budget; links to Budgets page

The cache hit rate card colors green (≥70%), amber (40–69%), or red (<40%) to signal whether sessions are reaping cache savings.

Budget Banner

If any budget is at 80%+ of its limit, a banner appears above the KPIs. It turns red at 100%.

Live Now Strip

Sessions currently running appear as cards with a pulsing live indicator. Click any card to open the live session detail.

Agent Usage (pie chart)

Donut chart showing the share of sessions per agent type (claude-code, cursor, copilot, etc.). Hover for exact counts and costs.

Cost Over Time (line chart)

30-day rolling cost history. Useful for spotting spending spikes.

Top Subagents

The most-spawned subagent types (e.g. Explore, Plan, code-reviewer). Populated from Task tool calls in hook data.

Top Tools

Horizontal bar chart of the most-used tools, with failure rate pills:

  • Green — <5% failure rate
  • Amber — 5–20%
  • Red — >20%

Activity Heatmap

7-day × 24-hour grid showing session density. Darker/brighter cells = more sessions at that day+hour combination.


7. Sessions Page

The sessions page (/sessions) lists all sessions with filtering and search.

Filters

  • Project — filter by tracked repository
  • Agent — filter by agent type
  • Status — running / completed / failed / unknown
  • Author — filter by commit author email

Date Quick-Filters

Use the chip buttons to jump to common time windows:

  • Last 24h — sessions from the past 24 hours
  • Last 7d — past week
  • Last 30d — past month
  • Click the active chip again to clear it back to "All time"

Search

The search box filters sessions by summary, branch name, author, or project name. Matching text is highlighted in amber in the results.

Exporting Sessions

Click the Download button next to the search box to export the current filtered view:

  • CSV — opens in Excel/Numbers, 14 columns (id, agent, author, project, branch, status, model, start/end times, duration, cost, tokens, tool calls)
  • JSON — full structured data, useful for scripting

The export respects all active filters and caps at 1000 rows.


8. Session Detail

Click any session row to open the detail view.

Metrics Sidebar

Shows token and cost metrics for the session:

  • Input/output/cache tokens
  • Total cost in USD
  • Tool call count and failure count
  • Subagent count

Context Bar

A horizontal bar showing peak context window usage for the session. Colors:

  • Blue — under 60% of the model's context window
  • Amber — 60–85%
  • Orange/Red — above 85%

Timeline

All events in chronological order:

  • Commits — git commits included in the session
  • Tool Calls — individual tool invocations from hooks (collapsible; shows input/output)
  • Subagent Cards — Task tool calls that spawned subagents; expand to see the prompt, result, and nested tool calls
  • Notes — any manual notes attached to the session

Related Sessions

The sidebar shows other sessions on the same project and branch that overlap in time — useful for spotting parallel or follow-up work.


9. Cost Budgets

Budgets let you set monthly USD spending caps at four levels of granularity.

Budget Scopes

Scope What it covers
Org All sessions across all projects and users
Project All sessions in a specific tracked repository
User All sessions authored by a specific user (matched by email)
Agent All sessions by a specific agent type (e.g. claude-code)

Via the Budgets UI

Go to Budgets in the sidebar. Use the Add Budget form to choose a scope and set an amount. Budgets reset at the start of each calendar month.

Via CLI

# Set an org-wide monthly budget of $100
./node_modules/.bin/tsx cli/index.ts budget set org 100

# Set a per-project budget
./node_modules/.bin/tsx cli/index.ts budget set project my-project 50

# Set a per-user budget
./node_modules/.bin/tsx cli/index.ts budget set user alice@example.com 25

# Set a per-agent budget
./node_modules/.bin/tsx cli/index.ts budget set agent claude-code 200

# List all budgets with current month spend
./node_modules/.bin/tsx cli/index.ts budget list

# Delete a budget (get the ID from budget list)
./node_modules/.bin/tsx cli/index.ts budget delete <id>

Budget alerts

When a budget reaches 80%, the dashboard banner turns amber and the Budget KPI card shows "approaching limit". At 100%, both turn red.

The Budget KPI card also shows a projected month-end spend based on a linear extrapolation of your current burn rate.


10. Team Management

Subspan supports multi-user teams via shareable magic invite links — no email/SMTP required. The first person to sign in claims ownership of the default organization; after that, owners and admins can mint invite links for anyone else.

Roles

Role Can do
owner Everything. Promote/invite admins. Remove any member.
admin Create/revoke invites (member role only), remove members (except owners), edit budgets, delete projects, change scan config.
member Read-only across dashboard, sessions, projects, budgets, profile, export. Cannot create or delete budgets, cannot delete projects, cannot see the invite form.

Server-side enforcement is centralized in requireRole(['owner','admin']) — even if a member scripts a mutation directly, the API returns 403 Forbidden.

Create an invite link

  1. Sign in as owner or admin.
  2. Settings → Team → scroll to Create invite link.
  3. Pick a role (member always available; admin only visible to owners).
  4. Pick an expiry: 1 day, 7 days (default), 30 days, or never.
  5. Set max uses (default 1, up to 100). Keep at 1 for single-person invites; raise it for team-onboarding links.
  6. Click Create invite. A modal appears with the one-time URL — copy it immediately. The raw token is never stored on disk (only its SHA-256 hash), so there's no way to retrieve it after you close the modal.

Accept an invite

The invitee opens the link in any browser:

  1. If signed out → redirected to /login?callbackUrl=/invite/<token> → GitHub OAuth → automatically returned to the accept page.
  2. If signed in → instantly enrolled into the organization with the role embedded in the invite → redirected to /dashboard?joined=1.
  3. If the link is dead (revoked, expired, or exhausted) → a friendly "Invite [state]" card renders with guidance to ask for a new link.

The accept is transactional — two browser tabs racing the last seat of a maxUses=1 invite will have exactly one succeed and one receive a 410.

Revoke an invite

In Settings → Team, click Revoke next to any pending invite. Revocation is immediate; existing members keep their access (it only blocks future accepts). If you need to evict an already-joined member, use Remove on the Members table instead.

Member management

  • Remove is visible to owners and admins, hidden for the current user's own row.
  • Admins cannot remove owners; only owners can.
  • The system refuses to remove the last owner (409) to prevent locking out of your own org.

Multi-organization ownership

Short answer: one user, one org, for now. The orgMembers composite primary key (userId, orgId) allows one user to belong to many orgs at the DB level, and an invite accept will happily insert a new membership for each org. However, several layers of the app assume single-tenant:

  • The nav sidebar has no org switcher — the team page / dashboard / budgets always render the first membership returned by SQLite.
  • requireRole() authorizes against "any org the user is in" rather than an active org.
  • Sessions, projects, and budgets are not org-scoped in the query layer.

Practical effect: if a user accepts invites to two different orgs, everything keeps working but both orgs' data effectively merges in the UI. This is acceptable for the current local-first deployment where a Subspan instance serves one team. Proper multi-org support (org switcher in sidebar, active-org JWT claim, org-scoped queries, requireRole(orgId, ...)) is tracked as part of the cloud-deployment roadmap.

If you need to split workspaces today, run a second Subspan instance with a different DATABASE_URL.


11. Exporting Data

There are two ways to export session data.

Web export (filtered)

On the Sessions page, apply any filters/search you want, then click Download → CSV or Download → JSON. The export matches exactly what's visible in the table, capped at 1000 rows.

CLI export (offline, no server needed)

# Export all sessions as JSON to stdout
./node_modules/.bin/tsx cli/index.ts export sessions

# Export with date range
./node_modules/.bin/tsx cli/index.ts export sessions --from 2026-04-01 --to 2026-04-30

# Export as CSV
./node_modules/.bin/tsx cli/index.ts export sessions --format csv

# Write directly to a file
./node_modules/.bin/tsx cli/index.ts export sessions --format csv --output sessions.csv

# Pipe into other tools
./node_modules/.bin/tsx cli/index.ts export sessions | jq '.[].cost | tonumber' | awk '{sum+=$1} END {print sum}'

CSV columns: id, agent, author, project, branch, status, model, startedAt, endedAt, durationMinutes, cost, inputTokens, outputTokens, toolCalls.


12. CLI Reference

All CLI commands talk directly to the local SQLite database. No running server is required.

Prefix: ./node_modules/.bin/tsx cli/index.ts <command>

For convenience, add an alias: alias subspan='./node_modules/.bin/tsx /path/to/subspan/cli/index.ts'

Setup

subspan init                        # Initialize .subspan/ in current directory

Repository management

subspan track <path>                # Track a git repository
subspan track <path> --name "Name"  # Track with a custom display name
subspan untrack <name-or-id>        # Stop tracking
subspan list                        # List all tracked repositories

Scanning

subspan scan                        # Scan all tracked repositories once
subspan scan <project-name>         # Scan a specific project
subspan watch                       # Continuous scan (default: every 5 minutes)
subspan watch --interval 30s        # Scan every 30 seconds
subspan watch --interval 1h         # Scan every hour

Activity

subspan stats                       # Colored summary: today / this week / all-time
subspan stats --json                # Same data as JSON (pipe-friendly)
subspan top                         # Live view of running sessions (Ctrl+C to exit)

subspan stats output:

Subspan Stats

Today
  Sessions  8
  Cost      $0.26
  Top agent claude-code

This Week
  Sessions  8
  Cost      $0.26

All Time
  Sessions  98
  Cost      $13.94

  Top Agents
    claude-code             57 sessions  $12.63
    cursor                  19 sessions  $0.61

  Top Subagent Types
    Explore                 13 spawns
    Plan                     4 spawns

Budgets

subspan budget list                              # Table: scope, limit, spent, % used, status
subspan budget set org 100                       # Set org-wide limit to $100/month
subspan budget set project <name> 50             # Set project limit
subspan budget set user <email> 25               # Set per-user limit
subspan budget set agent claude-code 200         # Set per-agent limit
subspan budget delete <id>                       # Delete a budget

subspan budget list output:

Scope    Label        Limit     Spent   % Used  Status
-------  --------  --------  --------  -------  ------
org      org-wide      $100       $14      14%  OK
project  subspan        $50       $12      25%  OK

Export

subspan export sessions                          # All sessions as JSON to stdout
subspan export sessions --from 2026-04-01        # From a date
subspan export sessions --to 2026-04-30          # To a date
subspan export sessions --format csv             # As CSV
subspan export sessions --output out.csv         # Write to file (stderr shows count)

Hooks

subspan hooks install    # Wire Claude Code hooks into ~/.claude/settings.json
subspan hooks uninstall  # Remove hooks
subspan hooks status     # Show which hook types are installed

Manual session logging

subspan log --agent claude-code --project my-project --summary "Refactored auth module"
subspan log --agent cursor --project my-api --summary "Fixed rate limit bug" --duration 45

Web UI

subspan dashboard            # Start the dashboard server and open it in your browser
subspan dashboard --port 8080

13. Troubleshooting

"Subspan not initialized" when running CLI commands

Run subspan init in your project directory, or ensure you're running the CLI from the directory that contains .subspan/.

Sessions not appearing after scan

  1. Check that the repository is tracked: subspan list
  2. Confirm the repo has git history: git log --oneline | head -5
  3. Make sure commits have agent signatures (Co-Authored-By, message patterns, or author email patterns)
  4. Lower confidence threshold or add custom rules in Settings

Hook data not appearing in session detail

  1. Verify hooks are installed: subspan hooks status
  2. Confirm the server is running on port 3000 before starting Claude Code
  3. Check that you're working inside a tracked repository directory
  4. View server logs — the POST /api/ingest/hook endpoint logs every hook payload

better-sqlite3 module error on Node 25

Error: The module ... was compiled against a different Node.js version

Rebuild the native module for your Node version:

# If you have Homebrew Node 22:
PATH="/opt/homebrew/opt/node@22/bin:$PATH" npm rebuild better-sqlite3

# Or switch your default Node to 22 via your version manager

The web server always runs correctly under Node 22. The CLI and web server share the same native module, so both need the same Node version.

Dashboard shows "Failed to load dashboard"

The stats endpoint failed. Check:

  1. Is the server running? (curl http://localhost:3000/api/dashboard/stats)
  2. Are you signed in? The endpoint requires an active session.
  3. Check the terminal where npm start is running for error output.

Export downloads as a UUID filename with no extension

This is a known browser quirk when the Content-Disposition header is not picked up. Use the CLI export instead:

./node_modules/.bin/tsx cli/index.ts export sessions --format csv --output sessions.csv

WebSocket not connecting (live updates not working)

The WebSocket server runs on the same port as the HTTP server via the custom server.ts. If you ran next dev directly instead of npm run dev, WebSockets won't be available. Stop the server and restart with npm run dev or npm start.