---
name: trace
description: Trace instrumentation and observability for ticket implementations. Use this skill when the user asks to trace a ticket implementation, log implementation events, analyze a completed implementation's decision pathway, or find recurring friction patterns across tickets. Enables post-mortem analysis of the full decision pathway per ticket.
---

# Trace Skill

**For Claude Code AI Assistant**

This skill provides trace instrumentation and observability for the ticket implementation workflow. It logs the full decision pathway per ticket: which files were read, what was generated, what was corrected, token usage per phase, and time per phase.

## Purpose

The trace skill enables post-mortem analysis by:
- Recording every significant event during ticket implementation
- Tracking phase timing and token usage (heuristic + measured)
- Capturing decisions, corrections, and errors
- Providing cross-ticket pattern analysis
- Surfacing per-skill token consumption and estimated cost

## Trace Storage

- Default: `./.artifex/traces/` in the current project directory
- Each trace is a JSON file: `.artifex/traces/<ticket_id>.json`
- Can be overridden with `ARTIFEX_TRACES_DIR` environment variable
- Model rate table for cost computation: `./.artifex/config/model-rates.json` (template at `templates/model-rates.json.template`). Override with `ARTIFEX_MODEL_RATES`.

## Available Commands

### 1. Start Trace (`/afx-trace start <ticket_id>`)

Initialize a trace for a ticket implementation.

```bash
~/.claude/skills/afx-trace/trace-manager.sh start <ticket_id>
```

Creates `.artifex/traces/<ticket_id>.json` with metadata (ticket ID, start time). Auto-initializes the traces directory if needed.

**When to use**: At the beginning of a ticket implementation (Step 1-2 of the workflow).

**Example:**
```bash
~/.claude/skills/afx-trace/trace-manager.sh start 2.3
```

### 2. Log Entry (`/afx-trace log <phase> <step> <event>`)

Append a trace entry recording a significant event.

```bash
~/.claude/skills/afx-trace/trace-manager.sh log <ticket_id> <phase> <step> <event_type> [details_json]
```

**Parameters:**
- **ticket_id**: The ticket being implemented
- **phase**: One of `pre-implementation`, `implementation`, `post-implementation`, `finalization`
- **step**: Step number (1-16, maps to ticket-implementation workflow)
- **event_type**: One of:
  - `file_read` - Reading a file for context or reference
  - `file_write` - Creating a new file
  - `file_edit` - Modifying an existing file
  - `test_run` - Running tests
  - `review_comment` - Self-review finding
  - `decision` - Architectural or implementation decision
  - `correction` - Fixing something that was wrong
  - `error` - An error encountered during implementation
- **details_json**: Optional JSON object with event-specific details

**When to use**: Throughout implementation, at each significant action.

**Examples:**
```bash
# Log reading a file
~/.claude/skills/afx-trace/trace-manager.sh log 2.3 pre-implementation 3 file_read \
  '{"file":"CLAUDE.md","lines_read":120}'

# Log a file edit
~/.claude/skills/afx-trace/trace-manager.sh log 2.3 implementation 8 file_edit \
  '{"file":"src/handler.ts","lines_changed":25,"summary":"Added validation logic"}'

# Log a decision
~/.claude/skills/afx-trace/trace-manager.sh log 2.3 implementation 5 decision \
  '{"rationale":"Using existing repository pattern from auth module"}'

# Log a correction
~/.claude/skills/afx-trace/trace-manager.sh log 2.3 implementation 8 correction \
  '{"reason":"Type mismatch in return value","fix":"Changed Promise<void> to Promise<Result>"}'

# Log a test run
~/.claude/skills/afx-trace/trace-manager.sh log 2.3 post-implementation 10 test_run \
  '{"command":"npm test","passed":true,"duration_seconds":12}'

# Log an error
~/.claude/skills/afx-trace/trace-manager.sh log 2.3 implementation 8 error \
  '{"message":"Cannot find module xyz","resolution":"Added missing import"}'
```

**Token estimation**: The script automatically estimates token usage based on event type and details (e.g., lines read * 4 tokens per line for file reads).

### 3. End Trace (`/afx-trace end <ticket_id>`)

Finalize the trace and compute summary statistics.

```bash
~/.claude/skills/afx-trace/trace-manager.sh end <ticket_id>
```

Calculates:
- Total duration in minutes
- Per-phase duration and entry counts
- Files read, files modified, corrections, errors
- Total estimated token count

**When to use**: After ticket implementation is complete (Step 15-16 of the workflow).

### 4. Analyze (`/afx-trace analyze <ticket_id>`)

Post-mortem analysis of a completed trace. This is a **prompt-driven** command -- Claude reads the trace JSON and provides analysis.

**When the user asks to analyze a trace:**

1. Read the trace file:
   ```bash
   cat .artifex/traces/<ticket_id>.json
   ```

2. Provide analysis covering:
   - **Phase-by-phase breakdown**: Duration, token usage, and entry count per phase
   - **Plan divergence**: Where did the implementation diverge from the initial plan (Step 5)?
   - **Corrections needed**: What was fixed and why? Were corrections in the same files?
   - **Friction points**: Files that caused re-reads, phases that exceeded typical budgets
   - **Decision log**: Key decisions made and their rationale
   - **Recommendations**: What could be improved for similar tickets

**Analysis output format:**
```
Trace Analysis: Ticket <ID>

Phase Breakdown:
  pre-implementation:  Xm, Y entries, ~Z tokens
  implementation:      Xm, Y entries, ~Z tokens
  post-implementation: Xm, Y entries, ~Z tokens
  finalization:        Xm, Y entries, ~Z tokens

Plan Divergence:
  - [What changed from the plan and why]

Corrections:
  - [What was corrected, root cause]

Friction Points:
  - [Files re-read multiple times]
  - [Phases that took longer than expected]

Recommendations:
  - [Actionable improvements]
```

### 5. Patterns (`/afx-trace patterns`)

Cross-ticket analysis across all traces. This is a **prompt-driven** command.

**When the user asks for trace patterns:**

1. Get aggregate stats:
   ```bash
   ~/.claude/skills/afx-trace/trace-manager.sh stats
   ```

2. Read individual trace files for deeper analysis:
   ```bash
   ls .artifex/traces/*.json
   ```

3. Provide pattern analysis covering:
   - **Recurring friction points**: Files or patterns that cause issues across tickets
   - **Average phase durations**: How long each phase typically takes
   - **Token usage trends**: Are implementations getting more or less efficient?
   - **Common failure categories**: What types of errors recur?
   - **Correction hotspots**: Which phases generate the most corrections?
   - **Recommendations**: Process improvements based on observed patterns

## Trace JSON Format

```json
{
  "ticket_id": "2.3",
  "started_at": "2026-04-11T21:30:00Z",
  "ended_at": "2026-04-11T22:15:00Z",
  "status": "complete",
  "entries": [
    {
      "timestamp": "2026-04-11T21:30:05Z",
      "phase": "pre-implementation",
      "step": 3,
      "step_name": "Research Architecture",
      "event_type": "file_read",
      "details": {"file": "CLAUDE.md", "lines_read": 120},
      "token_estimate": 500
    }
  ],
  "summary": {
    "total_duration_minutes": 45,
    "phases": {
      "pre-implementation": {"duration_minutes": 10, "entries": 8},
      "implementation": {"duration_minutes": 25, "entries": 15},
      "post-implementation": {"duration_minutes": 8, "entries": 6},
      "finalization": {"duration_minutes": 2, "entries": 3}
    },
    "files_read": 12,
    "files_modified": 5,
    "corrections": 2,
    "errors": 0,
    "total_token_estimate": 32000
  }
}
```

## Integration with ticket-implementation Agent

The trace skill is designed to be used alongside the ticket-implementation agent workflow:

- **Step 1-2** (Pre-Implementation): `trace start <ID>`, log initial events
- **Step 3** (Research): Log each `file_read` with file path and lines
- **Step 4-5** (Planning): Log `decision` events for architectural choices
- **Step 8** (Implementation): Log `file_write`, `file_edit`, `correction` events
- **Step 9-10** (Testing): Log `test_run` events with pass/fail
- **Step 11-12** (Post-Implementation): Log `review_comment` events
- **Step 14** (Commit): Log final `decision` event
- **Step 15-16** (Finalization): `trace end <ID>`

## Typical Workflow

1. **Start tracing at implementation start:**
   ```bash
   ~/.claude/skills/afx-trace/trace-manager.sh start 2.3
   ```

2. **Log events throughout implementation:**
   ```bash
   ~/.claude/skills/afx-trace/trace-manager.sh log 2.3 pre-implementation 3 file_read '{"file":"CLAUDE.md","lines_read":120}'
   ~/.claude/skills/afx-trace/trace-manager.sh log 2.3 implementation 8 file_edit '{"file":"src/api.ts","lines_changed":40}'
   ~/.claude/skills/afx-trace/trace-manager.sh log 2.3 implementation 8 correction '{"reason":"Missing null check"}'
   ```

3. **Finalize trace:**
   ```bash
   ~/.claude/skills/afx-trace/trace-manager.sh end 2.3
   ```

4. **Review what happened:**
   ```bash
   ~/.claude/skills/afx-trace/trace-manager.sh show 2.3
   ```

5. **Analyze for improvements:**
   > "Analyze trace for ticket 2.3"

6. **Find patterns across tickets:**
   > "Show trace patterns across all tickets"

## Error Handling

The skill exits with non-zero status on errors:
- Traces directory not initialized (auto-init on `start`)
- Trace not found for ticket
- Invalid phase or event type
- Missing required dependencies (jq)

## Dependencies

- **Required**: jq, bash 4.0+

## Best Practices

1. **Start early**: Begin tracing at Step 1 of the workflow
2. **Log decisions**: Capture the "why" behind choices, not just the "what"
3. **Log corrections**: Every correction is a learning opportunity
4. **End traces**: Always finalize traces to get summary statistics
5. **Review regularly**: Use `/afx-trace patterns` to find process improvements
6. **Include details**: The more context in log entries, the better the post-mortem

## Version

1.0.0
