# AGENTS.md

## Project Overview

**pi-tool-stats** is a [pi](https://pi.dev) extension that tracks usage of skills, prompt templates, extensions, and built-in tools. It logs events to a JSONL file and provides a `/tool-stats` command to surface prune candidates.

## Tech Stack

- **Language:** TypeScript (strict, ES modules)
- **Runtime:** Node.js (via pi extension host)
- **Build:** `bun build` for type-checking/verification
- **Package manager:** Bun (`bun.lock`)
- **Pi SDK:** `@earendil-works/pi-coding-agent` (dev dependency)

## Architecture

Single-file extension: `src/index.ts`. No framework, no bundling for production — pi loads the source directly via `"extensions": ["./src/index.ts"]` in package.json.

### Key concepts

- **Event listeners** — `session_start`, `resources_discover`, `tool_call`, `input` hooks on the pi extension API
- **JSONL log** — append-only file at `~/.pi/agent/tool-stats.jsonl`; each line is a `{ts, kind, name, ext?, session?}` record
- **Record kinds** — `tool`, `skill`, `template`, `ext-cmd`
- **Command map** — rebuilt on `session_start` / `resources_discover` from `pi.getCommands()` and `pi.getAllTools()`, classifies slash commands by source (skill/prompt/extension)
- **Skill discovery** — walks conventional skill directories (`~/.pi/agent/skills`, `~/.agents/skills`, `.pi/skills`, `.agents/skills`) and parses SKILL.md frontmatter
- **Reporting** — `/tool-stats [days]` aggregates records, cross-references against live resources, displays via `ctx.ui.select()` (scrollable, no LLM context pollution)

### Important functions

| Function | Purpose |
|---|---|
| `append()` | Writes a record to the JSONL log (never throws) |
| `refreshMaps()` | Rebuilds `cmdMap`, `toolExt`, `skillFileToName` from pi APIs |
| `skillNameFromReadPath()` | Detects skill loads from `read` tool calls |
| `discoverSkillDefs()` | Recursively finds SKILL.md files and parses frontmatter |
| `section()` / `aggregate()` | Report formatting helpers |

## Development Commands

```bash
bun run typecheck   # tsc type-check
bun run build       # bun build to /tmp (verification only)
```

There are no tests yet.

## Conventions

- All I/O in `append()` and metric helpers is wrapped in try/catch — **metrics must never break the agent**
- Paths are normalized and resolved via `fs.realpathSync` for reliable matching across symlinks
- Skill names use aliases (directory name, frontmatter `name`, file basename) for flexible matching
- The report distinguishes **prompt-visible** skills (cost tokens in `<available_skills>`) from explicit-only ones

## File Layout

```
src/
  index.ts       # entire extension (~600 lines)
package.json     # pi extension config in "pi.extensions"
tsconfig.json
README.md
AGENTS.md        # this file
```

## Log File

- **Location:** `~/.pi/agent/tool-stats.jsonl`
- **Reset:** `rm ~/.pi/agent/tool-stats.jsonl`
- **Watch:** `tail -f ~/.pi/agent/tool-stats.jsonl`
