Plugin Introspector — White-box Monitoring & Self-Improvement Meta-Plugin
A meta-plugin that monitors Claude Code workflow plugin execution at white-box level,
collects execution data, and generates data-driven improvement proposals.
Role
A monitoring and analysis meta-plugin that provides end-to-end visibility into Claude Code
workflow plugin execution. Collects tool traces, API interactions, token usage, and execution
patterns via hooks. Provides analysis agents that identify bottlenecks, evaluate quality,
detect anomalies, and generate concrete improvement proposals.
Terminology
- Plugin: An installable package (directory with
.claude-plugin/plugin.json and skills/)
- Skill: An invocable unit within a plugin (directory with
SKILL.md)
- Agent: A Task subagent definition (
.md file in agents/)
- Proposal / Improvement: A concrete, ROI-scored change suggestion generated by
improve
Core Principles
- Data-driven improvement: Never guess — always base decisions on collected execution data
- Minimal overhead: Hook scripts must complete in <50ms, use append-only JSONL
- OTel compatibility: Trace data follows OpenTelemetry GenAI Semantic Conventions
- Tiered collection: Tier 0 (pure hooks) → Tier 1 (+ OTel Collector with native telemetry)
- Meta-rules compliance: All generated improvements must pass meta-rules validation
- Zero external dependencies: bash + jq only — no Python, no Node.js (Tier 1 adds optional otelcol-contrib)
Pre-Execution: Session Resolution
Before any command, resolve the session directory:
1. Run: ls -t ~/.claude/plugin-introspector/sessions/ | head -1
→ Gives the most recent session ID
2. If --session {id} was provided: use that ID instead
3. Set: SESSION_DIR = ~/.claude/plugin-introspector/sessions/{resolved-id}
4. Verify: stats.json exists in SESSION_DIR
5. If not found: display "No session data. Run a session with hooks enabled first."
Full details: resources/orchestration-protocol.md
Pre-Execution: Target Plugin Resolution
When --target {plugin-name} is specified:
1. Search for plugin at: {working_dir}/plugins/{plugin-name}/
2. Fallback: check marketplace.json for source path
3. Catalog plugin components → store in SESSION_DIR/target_plugin.json
4. If not found: display "Plugin '{name}' not found" with available list
When --target is omitted:
- Infer plugin from traces: scan
input_summary fields for plugin-specific paths
- If Skill tool invoked: identify from skill name
- If no plugin identified: treat as general session analysis
Data Storage
~/.claude/plugin-introspector/
├── sessions/{session-id}/
│ ├── meta.json # Session metadata (git info, collection_tier)
│ ├── tool_traces.jsonl # Pre/post tool traces with input_summary
│ ├── api_traces.jsonl # API request/response metrics
│ ├── otel_traces.jsonl # OTel spans (hook-generated or merged native)
│ ├── stats.json # Aggregated session statistics
│ ├── evaluation.json # Quality evaluation results (from evaluate)
│ ├── security_events.jsonl # DLP violations, command risk events (from security hooks)
│ └── target_plugin.json # Discovered target plugin info (from --target)
├── session_history.jsonl # Cross-session summary records
├── evaluation_history.jsonl # Cross-session evaluation scores
├── alerts.jsonl # Anomaly detection alerts
├── improvement_log.jsonl # Applied improvement history
├── aggregates.json # Pre-computed cross-session aggregates (from Stop hook)
├── security_baseline.json # Security baseline for anomaly comparison (optional)
├── telemetry.jsonl # Opt-in anonymous telemetry (PI_TELEMETRY=1)
├── plugin-profiles/{plugin}/ # Per-plugin workflow profiles and baselines
├── otel-export/ # Tier 1: OTel Collector File Exporter output
└── otel-collector/ # Tier 1: Collector binary and config
Commands
Quick Reference
| Command |
Agent |
Options |
status |
— |
--session {id} |
dashboard |
— |
--session {id}, --full |
flow |
— |
--session {id} |
profile |
plugin-profiler |
--target {plugin} (required) |
analyze |
workflow-analyzer |
--session {id}, --target {plugin} |
tokens |
token-optimizer |
--session {id} |
api |
api-tracker |
--session {id} |
context |
context-auditor |
--session {id}, --target {plugin} |
evaluate |
quality-evaluator |
--session {id}, --target {plugin} |
alerts |
anomaly-detector |
--session {id} |
optimize * |
auto-optimizer |
--target {plugin}, --component {file} |
improve |
improvement-generator |
--session {id}, --target {plugin} (required) |
report |
5 agents (see below) |
--session {id}, --target {plugin} |
apply |
— |
(reads proposals from last improve/optimize) |
trace |
— |
--tool {name}, --errors, --slow, --last {N} |
web |
— |
--otel, --json, --csv |
quick-scan |
quick-scanner |
--target {plugin} (required) |
security-scan |
— |
--target {plugin} (required) |
security-audit |
security-auditor |
--session {id} |
security-dashboard |
— |
--session {id} |
compliance-report * |
security-reporter |
--period {30d|7d|date~date} |
rotate-data |
— |
--dry-run, env: PI_RETENTION_DAYS, PI_RETENTION_LINES |
otel-setup * |
— |
install, start, stop, status, env |
otel-security-map * |
— |
--watch, --stats |
* available, experimental
Agent Invocation Pattern
Details: resources/orchestration-protocol.md
All analysis agents are invoked via the Task tool using the prompt template defined in orchestration-protocol.md:
1. Read the agent definition: agents/{agent-name}.md
2. Read the relevant JSONL data files from SESSION_DIR (apply truncation per Data Size Management)
3. Construct prompt from Task Prompt Template (see orchestration-protocol.md)
4. Invoke Task with subagent_type: "general-purpose", model per agent's Model Assignment
5. Parse agent's JSON output
6. Display results / write to SESSION_DIR
For multi-agent commands (report, improve, optimize):
1. Read all data files once and reuse across agents
2. For 'report': run independent agents in parallel (workflow-analyzer, token-optimizer, api-tracker, context-auditor), then quality-evaluator
3. For 'improve': run analysis agents + load cross-session data (evaluation_history, improvement_log, plugin profile), aggregate all, pass to improvement-generator with improvement-pipeline.md procedure
4. For 'optimize': read evaluation.json + evaluation_history + improvement_log + target component, pass to auto-optimizer
status — Current Session Overview
- Resolve session directory
- Read
stats.json
- Display: session ID, duration, tool calls, token estimate, error count, top tools
dashboard — htop-style Real-time Dashboard
- Resolve session directory
- Run
Bash: scripts/dashboard.sh {session-id} [--full]
- Renders token progress bar, per-tool breakdown, error rate
flow — Execution Flow Tree (OTel)
- Resolve session directory
- Read
otel_traces.jsonl
- Build parent-child span tree using
parent_span_id
- Display indented tree with timing and token info
profile — Generate Plugin Profile
- Resolve target plugin (required:
--target)
- Read target plugin's main SKILL.md content
- Read target plugin's component catalog (from
target_plugin.json)
- Read agent: agents/plugin-profiler.md
- Invoke Task (haiku): pass SKILL.md content + component catalog
- Output: workflow type, phases, detection patterns, key files
- Write result to
~/.claude/plugin-introspector/plugin-profiles/{plugin}/profile.json
- Create empty
phase-baselines.json and learned-patterns.jsonl if not present
analyze — Deep Workflow Analysis
- Resolve session + target plugin
- Read
tool_traces.jsonl + otel_traces.jsonl
- Read agent: agents/workflow-analyzer.md
- Invoke Task (sonnet): pass agent definition + data
- Output: patterns, bottlenecks, efficiency ratio, recommendations
tokens / api / context — Single-Agent Analysis Commands
All follow the same pattern: resolve session → read data → invoke agent → display output.
| Command |
Agent |
Data Files |
Extra |
tokens |
token-optimizer (sonnet) |
tool_traces.jsonl + api_traces.jsonl + stats.json |
— |
api |
api-tracker (sonnet) |
api_traces.jsonl |
— |
context |
context-auditor (sonnet) |
api_traces.jsonl + tool_traces.jsonl |
--target: read SKILL.md + agents for static cost |
evaluate — Quality Evaluation (LLM-as-Judge)
- Resolve session + target plugin (optional:
--target scopes evaluation)
- Read
tool_traces.jsonl + otel_traces.jsonl + stats.json
- Read agent: agents/quality-evaluator.md
- Invoke Task (sonnet): pass agent definition + data
- Output: 4-dimension scores + quantified improvement signals
- Write result to
SESSION_DIR/evaluation.json
- Append to
~/.claude/plugin-introspector/evaluation_history.jsonl:
- From quality-evaluator output:
weighted_score, scores
- From stats.json:
key_metrics (tool_calls, total_tokens_est, errors, error_rate, duration_ms)
- From orchestrator phase detection (via plugin profile + trace analysis):
phase_breakdown (optional, only for phased workflows)
- From quality-evaluator
improvement_signals: top_waste_sources (top 3 waste entries)
- From improvement_log:
improvements_active (IDs where status == "applied")
- Update phase baselines (if target_plugin has profile with
workflow.type == "phased"):
- Read
plugin-profiles/{plugin}/phase-baselines.json
- Update running mean/stddev for each phase using current phase_breakdown
- Increment
sessions_count, set maturity.baselines_available = true if count ≥ 5
- Closed Loop Check: Read
~/.claude/plugin-introspector/improvement_log.jsonl
- Find entries where
status == "applied" and post_score == null
- If
--target specified: only check entries matching target_plugin
- For each pending entry: compare current
weighted_score with pre_score
- Update
post_score and set status to validated or regressed
- If regressed (score dropped >0.5): suggest rollback via improvement-apply-protocol.md
alerts — Anomaly Detection
- Read
~/.claude/plugin-introspector/alerts.jsonl → display recent alerts
- If deeper analysis requested:
- Resolve session
- Read
tool_traces.jsonl + session_history.jsonl + alerts.jsonl
- Read agent: agents/anomaly-detector.md
- Invoke Task (haiku): pass agent definition + data (including alerts.jsonl for deduplication)
- Output: alert list with severity, suggested actions
optimize — Auto-Optimize (APE Loop) (available, experimental)
- Resolve target plugin (required:
--target)
- Resolve target component (
--component or auto-select lowest-scoring)
- Read
evaluation.json (run evaluate first if missing)
- Read
evaluation_history.jsonl + improvement_log.jsonl (for contrastive analysis + historical learning)
- Read agent: agents/auto-optimizer.md
- Read target component file content
- Invoke Task (opus): pass agent definition + evaluation + history + component content
- Output: optimized version with diff + predicted score improvement
- Display diff for user review — do NOT auto-apply
CAUTION: Review all diffs before applying. See resources/improvement-apply-protocol.md.
improve — Generate Improvement Proposals
- Resolve session + target plugin (required:
--target)
- Run analysis pipeline (or reuse if already run in this session):
- Parallel: workflow-analyzer, token-optimizer, context-auditor
- Parallel: anomaly-detector, quality-evaluator
- Load cross-session data:
evaluation_history.jsonl (last 20 records)
improvement_log.jsonl (all for target plugin)
- Plugin profile:
profile.json, phase-baselines.json, learned-patterns.jsonl
- Read target plugin component files (apply file selection per orchestration-protocol.md)
- Read agent: agents/improvement-generator.md
- Read procedure: resources/improvement-pipeline.md
- Invoke Task (opus): pass agent definition + pipeline procedure + all analysis results + cross-session data + selected plugin files
- Output: ROI-scored proposals with quantified evidence, counterfactuals, diffs, meta-rules validation
- Display proposals for user review — do NOT auto-apply
report — Full Analysis Report
- Resolve session + target plugin
- Read all JSONL data files once
- Run independent agents in parallel (4 concurrent Task calls):
- workflow-analyzer → analysis
- token-optimizer → tokens
- api-tracker → api
- context-auditor → context
- Run quality-evaluator sequentially (can use results from step 3 if needed)
- Aggregate into unified report with sections:
- Executive Summary, Workflow Analysis, Token Efficiency,
API Performance, Context Audit, Quality Score, Recommendations
apply — Apply Improvement Proposals
- Read the most recent
improve or optimize output (proposals)
- For each proposal, follow improvement-apply-protocol.md:
- Display proposal summary + diff for user review
- Wait for explicit user confirmation
- Backup → Edit → Verify → Log to
improvement_log.jsonl
- After all approved proposals applied:
- Display summary of changes
- Suggest: "Run
evaluate --target {plugin} after next session to validate improvements"
CAUTION: Never auto-apply. Each proposal requires explicit user approval.
quick-scan — Quick Plugin Diagnosis (1-minute)
- Resolve target plugin (required:
--target)
- Analyze plugin structure: plugin.json, SKILL.md, agents, scripts, resources
- Run
security-scan.sh for security score
- Read agent: agents/quick-scanner.md
- Invoke Task (haiku): lightweight analysis
- Output: formatted box diagram with structure summary, security score, recommendations
- Suggest follow-up commands for detailed analysis
Use case: First-time plugin evaluation, PR review, quick health check
Details: agents/quick-scanner.md
rotate-data — Data Retention Management
- Run
Bash: scripts/rotate-data.sh
- Deletes session directories older than
PI_RETENTION_DAYS (default: 30)
- Trims JSONL files to
PI_RETENTION_LINES (default: 1000)
- Displays summary of deleted sessions and freed space
Environment variables:
PI_RETENTION_DAYS=30: Days to keep session directories
PI_RETENTION_LINES=1000: Lines to keep in JSONL files
PI_DRY_RUN=1: Preview what would be deleted without actually deleting
PI_AUTO_ROTATE=1: Auto-run at session end (optional)
Example:
# Dry run to see what would be deleted
PI_DRY_RUN=1 /plugin-introspector rotate-data
# Keep only 7 days of data
PI_RETENTION_DAYS=7 /plugin-introspector rotate-data
security-scan — Plugin Static Security Analysis
- Resolve target plugin (required:
--target)
- Run
Bash: scripts/security-scan.sh {plugin-path}
- Scans hook scripts for dangerous patterns (data exfiltration, reverse shells, credential theft)
- Scans SKILL.md + resources for prompt injection patterns
- Scans agent definitions for risky tool permission combinations
- Output: JSON report with findings, severity levels, risk score
- Logs findings to
alerts.jsonl if any found
Environment variables:
PI_ENABLE_SECURITY=1: Enables runtime command risk logging
PI_ENABLE_DLP=1: Enables DLP scanning
PI_SECURITY_BLOCK=1: Enables CRITICAL command blocking (use with caution)
Note: security-check.sh intentionally omits || true in plugin.json so that exit 2 can block CRITICAL commands when PI_SECURITY_BLOCK=1. All other hook scripts use || true per meta-rules.
Details: resources/security-patterns.md
security-audit — Session Security Audit
- Resolve session
- Read
tool_traces.jsonl + otel_traces.jsonl + stats.json + security_events.jsonl + alerts.jsonl
- Read agent: agents/security-auditor.md
- Invoke Task (haiku): pass agent definition + all data (including stats.json)
- Output: risk level, file access audit, command audit, suspicious sequences, DLP summary
- Recommendations for security improvements
security-dashboard — Security Risk Visualization
- Resolve session
- Run
Bash: scripts/security-dashboard.sh {session-id}
- Renders security-focused dashboard with:
- Overall risk score bar
- DLP violations, sensitive reads/writes, risky commands
- Recent security events
- Security configuration status (DLP, security check, blocking)
compliance-report — Compliance Report Generation (available, experimental)
- Read
session_history.jsonl for specified period
- Read
alerts.jsonl + security_events.jsonl + improvement_log.jsonl (aggregated)
- Optionally run
security-scan for each active plugin
- Read agent: agents/security-reporter.md
- Invoke Task (sonnet): pass agent definition + period data
- Output: SOC 2 / ISO 27001 compliance report with executive summary, security events,
plugin audit, recommendations, and compliance mapping
otel-setup — OTel Collector Setup (Tier 1) (available, experimental)
- Run
Bash: scripts/setup-otel-collector.sh {subcommand}
install: Download OTel Collector Contrib binary (~100MB+)
start: Start collector with otel-config.yaml (OTLP receiver → file exporter)
stop: Stop collector
status: Show collector status, export data info, environment variables
env: Print shell environment variables to set
- Display output to user
After setup, the collection tier automatically upgrades from Tier 0 to Tier 1.
Hook scripts detect the running collector and skip redundant OTel span generation.
Native OTel spans (with accurate token counts) are merged at session end.
See: Collection Tiers in orchestration-protocol.md
otel-security-map — OTel Security Event Mapper (available, experimental)
- Run
Bash: scripts/otel-security-mapper.sh [session-id|--watch|--stats]
- Converts native Claude Code OTel events to PI security_events.jsonl format
- Enables deeper security analysis using OTel's tool_parameters (bash_command, full_command)
- Output modes:
<session-id>: Process specific session's OTel data
--watch: Real-time mapping mode
--stats: Show security statistics from OTel data
Use case: Enhanced security analysis with native OTel data (Tier 1+)
trace — Raw Trace Viewer
- Resolve session
- Read
tool_traces.jsonl with filters: --tool {name}, --errors, --slow, --last {N}
- Display formatted records
web — Export for External Tools
- Resolve session
- Export format:
--otel, --json, --csv
- Write export file, display path
Environment Variables
All environment variables are opt-in. Default behavior requires no configuration.
| Variable |
Default |
Description |
PI_ENABLE_SECURITY |
0 |
Enable runtime command risk logging |
PI_ENABLE_DLP |
0 |
Enable DLP (sensitive data detection) |
PI_SECURITY_BLOCK |
0 |
Block CRITICAL commands (use with caution) |
PI_RETENTION_DAYS |
30 |
Days to keep session data |
PI_RETENTION_LINES |
1000 |
Lines to keep in JSONL files |
PI_DRY_RUN |
0 |
Preview data rotation without deleting |
PI_AUTO_ROTATE |
0 |
Auto-rotate data at session end |
PI_SHOW_REMINDER |
1 |
Show PI commands reminder at session start |
PI_TELEMETRY |
0 |
Enable opt-in anonymous telemetry (local only) |
PI_BASELINE_MAX_AGE |
30 |
Days of history for security baseline |
Telemetry Policy (PI_TELEMETRY):
- Data stored locally in
telemetry.jsonl — never transmitted externally
- Collects: command counts only (no content, paths, or personal data)
- Use
scripts/telemetry.sh status to view collected data
Resources (On-demand)
Agents
Skills (Knowledge Base)
Closed Loop: Improve → Apply → Validate
The full improvement cycle connects improve, evaluate, and the apply protocol:
┌─────────┐ ┌───────────┐ ┌─────────┐ ┌──────────┐
│ improve │────▶│ user │────▶│ apply │────▶│ log to │
│ (propose)│ │ review │ │ (backup, │ │ improve- │
│ │ │ (approve?)│ │ edit, │ │ ment_log │
│ │ │ │ │ verify) │ │ .jsonl │
└─────────┘ └───────────┘ └─────────┘ └────┬─────┘
│
▼
┌─────────┐ ┌───────────┐ ┌─────────────────────────┐
│ rollback │◀───│ regressed │◀───│ evaluate (next session) │
│ (if bad) │ │ score? │ │ → checks pending │
│ │ │ │ │ post_scores in log │
└─────────┘ └───────────┘ └─────────────────────────┘
Lifecycle
improve generates proposals with diffs and meta-rules validation
- User reviews each proposal (never auto-apply)
- Apply follows improvement-apply-protocol.md:
- Backup → Edit → Verify → Log to
improvement_log.jsonl with post_score: null
- Next
evaluate run (step 9 — Closed Loop Check) detects pending entries and fills post_score
- If validated (
post_score >= pre_score): mark status: "validated"
- If regressed (
post_score < pre_score - 0.5): suggest rollback, mark status: "regressed"
Rollback Trigger
When evaluate detects regression:
1. Display: "Improvement {proposal_id} caused score regression: {pre_score} → {post_score}"
2. Offer rollback: "Restore from backup? (yes/no)"
3. If yes: follow rollback procedure in improvement-apply-protocol.md
4. Log rollback to improvement_log.jsonl
Self-Referential Loop Prevention
- Hook scripts check
CLAUDE_TOOL_NAME + structured Skill name via jq — skip if Skill invocation targets plugin-introspector
- Analysis agents exclude introspector-related tool calls from analysis
- When running
improve --target plugin-introspector: extra caution, meta-rules strictly enforced
1---2name: plugin-introspector3description: White-box monitoring and self-improvement meta-plugin for Claude Code workflow plugins. Monitors tool usage, token consumption, API calls, and execution patterns. Analyzes collected data to generate data-driven improvement proposals. Activated by keywords: "introspector", "monitor", "analyze plugin", "token usage", "dashboard", "evaluate", "optimize", "improve plugin", "security", "compliance".4---56# Plugin Introspector — White-box Monitoring & Self-Improvement Meta-Plugin78> A meta-plugin that monitors Claude Code workflow plugin execution at white-box level,9> collects execution data, and generates data-driven improvement proposals.1011## Role1213A monitoring and analysis meta-plugin that provides **end-to-end visibility** into Claude Code14workflow plugin execution. Collects tool traces, API interactions, token usage, and execution15patterns via hooks. Provides analysis agents that identify bottlenecks, evaluate quality,16detect anomalies, and generate concrete improvement proposals.1718### Terminology1920- **Plugin**: An installable package (directory with `.claude-plugin/plugin.json` and `skills/`)21- **Skill**: An invocable unit within a plugin (directory with `SKILL.md`)22- **Agent**: A Task subagent definition (`.md` file in `agents/`)23- **Proposal / Improvement**: A concrete, ROI-scored change suggestion generated by `improve`2425### Core Principles26271. **Data-driven improvement**: Never guess — always base decisions on collected execution data282. **Minimal overhead**: Hook scripts must complete in <50ms, use append-only JSONL293. **OTel compatibility**: Trace data follows OpenTelemetry GenAI Semantic Conventions304. **Tiered collection**: Tier 0 (pure hooks) → Tier 1 (+ OTel Collector with native telemetry)315. **Meta-rules compliance**: All generated improvements must pass meta-rules validation326. **Zero external dependencies**: bash + jq only — no Python, no Node.js (Tier 1 adds optional otelcol-contrib)3334---3536## Pre-Execution: Session Resolution3738**Before any command**, resolve the session directory:3940```411. Run: ls -t ~/.claude/plugin-introspector/sessions/ | head -142 → Gives the most recent session ID432. If --session {id} was provided: use that ID instead443. Set: SESSION_DIR = ~/.claude/plugin-introspector/sessions/{resolved-id}454. Verify: stats.json exists in SESSION_DIR465. If not found: display "No session data. Run a session with hooks enabled first."47```4849> Full details: [resources/orchestration-protocol.md](./resources/orchestration-protocol.md)5051## Pre-Execution: Target Plugin Resolution5253When `--target {plugin-name}` is specified:5455```561. Search for plugin at: {working_dir}/plugins/{plugin-name}/572. Fallback: check marketplace.json for source path583. Catalog plugin components → store in SESSION_DIR/target_plugin.json594. If not found: display "Plugin '{name}' not found" with available list60```6162When `--target` is omitted:63- Infer plugin from traces: scan `input_summary` fields for plugin-specific paths64- If Skill tool invoked: identify from skill name65- If no plugin identified: treat as general session analysis6667---6869## Data Storage7071```72~/.claude/plugin-introspector/73├── sessions/{session-id}/74│ ├── meta.json # Session metadata (git info, collection_tier)75│ ├── tool_traces.jsonl # Pre/post tool traces with input_summary76│ ├── api_traces.jsonl # API request/response metrics77│ ├── otel_traces.jsonl # OTel spans (hook-generated or merged native)78│ ├── stats.json # Aggregated session statistics79│ ├── evaluation.json # Quality evaluation results (from evaluate)80│ ├── security_events.jsonl # DLP violations, command risk events (from security hooks)81│ └── target_plugin.json # Discovered target plugin info (from --target)82├── session_history.jsonl # Cross-session summary records83├── evaluation_history.jsonl # Cross-session evaluation scores84├── alerts.jsonl # Anomaly detection alerts85├── improvement_log.jsonl # Applied improvement history86├── aggregates.json # Pre-computed cross-session aggregates (from Stop hook)87├── security_baseline.json # Security baseline for anomaly comparison (optional)88├── telemetry.jsonl # Opt-in anonymous telemetry (PI_TELEMETRY=1)89├── plugin-profiles/{plugin}/ # Per-plugin workflow profiles and baselines90├── otel-export/ # Tier 1: OTel Collector File Exporter output91└── otel-collector/ # Tier 1: Collector binary and config92```9394---9596## Commands9798### Quick Reference99100| Command | Agent | Options |101|---------|-------|---------|102| `status` | — | `--session {id}` |103| `dashboard` | — | `--session {id}`, `--full` |104| `flow` | — | `--session {id}` |105| `profile` | plugin-profiler | `--target {plugin}` (required) |106| `analyze` | workflow-analyzer | `--session {id}`, `--target {plugin}` |107| `tokens` | token-optimizer | `--session {id}` |108| `api` | api-tracker | `--session {id}` |109| `context` | context-auditor | `--session {id}`, `--target {plugin}` |110| `evaluate` | quality-evaluator | `--session {id}`, `--target {plugin}` |111| `alerts` | anomaly-detector | `--session {id}` |112| `optimize` * | auto-optimizer | `--target {plugin}`, `--component {file}` |113| `improve` | improvement-generator | `--session {id}`, `--target {plugin}` (required) |114| `report` | 5 agents (see below) | `--session {id}`, `--target {plugin}` |115| `apply` | — | (reads proposals from last `improve`/`optimize`) |116| `trace` | — | `--tool {name}`, `--errors`, `--slow`, `--last {N}` |117| `web` | — | `--otel`, `--json`, `--csv` |118| `quick-scan` | quick-scanner | `--target {plugin}` (required) |119| `security-scan` | — | `--target {plugin}` (required) |120| `security-audit` | security-auditor | `--session {id}` |121| `security-dashboard` | — | `--session {id}` |122| `compliance-report` * | security-reporter | `--period {30d\|7d\|date~date}` |123| `rotate-data` | — | `--dry-run`, env: `PI_RETENTION_DAYS`, `PI_RETENTION_LINES` |124| `otel-setup` * | — | `install`, `start`, `stop`, `status`, `env` |125| `otel-security-map` * | — | `--watch`, `--stats` |126127\* *available, experimental*128129---130131### Agent Invocation Pattern132133> Details: [resources/orchestration-protocol.md](./resources/orchestration-protocol.md)134135All analysis agents are invoked via the **Task** tool using the prompt template defined in orchestration-protocol.md:136137```1381. Read the agent definition: agents/{agent-name}.md1392. Read the relevant JSONL data files from SESSION_DIR (apply truncation per Data Size Management)1403. Construct prompt from Task Prompt Template (see orchestration-protocol.md)1414. Invoke Task with subagent_type: "general-purpose", model per agent's Model Assignment1425. Parse agent's JSON output1436. Display results / write to SESSION_DIR144```145146For multi-agent commands (`report`, `improve`, `optimize`):147```1481. Read all data files once and reuse across agents1492. For 'report': run independent agents in parallel (workflow-analyzer, token-optimizer, api-tracker, context-auditor), then quality-evaluator1503. For 'improve': run analysis agents + load cross-session data (evaluation_history, improvement_log, plugin profile), aggregate all, pass to improvement-generator with improvement-pipeline.md procedure1514. For 'optimize': read evaluation.json + evaluation_history + improvement_log + target component, pass to auto-optimizer152```153154---155156### `status` — Current Session Overview1571581. Resolve session directory1592. Read `stats.json`1603. Display: session ID, duration, tool calls, token estimate, error count, top tools161162---163164### `dashboard` — htop-style Real-time Dashboard1651661. Resolve session directory1672. Run `Bash: scripts/dashboard.sh {session-id} [--full]`1683. Renders token progress bar, per-tool breakdown, error rate169170---171172### `flow` — Execution Flow Tree (OTel)1731741. Resolve session directory1752. Read `otel_traces.jsonl`1763. Build parent-child span tree using `parent_span_id`1774. Display indented tree with timing and token info178179---180181### `profile` — Generate Plugin Profile1821831. Resolve target plugin (required: `--target`)1842. Read target plugin's main SKILL.md content1853. Read target plugin's component catalog (from `target_plugin.json`)1864. Read agent: [agents/plugin-profiler.md](./agents/plugin-profiler.md)1875. Invoke Task (haiku): pass SKILL.md content + component catalog1886. Output: workflow type, phases, detection patterns, key files1897. **Write** result to `~/.claude/plugin-introspector/plugin-profiles/{plugin}/profile.json`1908. Create empty `phase-baselines.json` and `learned-patterns.jsonl` if not present191192---193194### `analyze` — Deep Workflow Analysis1951961. Resolve session + target plugin1972. Read `tool_traces.jsonl` + `otel_traces.jsonl`1983. Read agent: [agents/workflow-analyzer.md](./agents/workflow-analyzer.md)1994. Invoke Task (sonnet): pass agent definition + data2005. Output: patterns, bottlenecks, efficiency ratio, recommendations201202---203204### `tokens` / `api` / `context` — Single-Agent Analysis Commands205206All follow the same pattern: resolve session → read data → invoke agent → display output.207208| Command | Agent | Data Files | Extra |209|---------|-------|------------|-------|210| `tokens` | [token-optimizer](./agents/token-optimizer.md) (sonnet) | `tool_traces.jsonl` + `api_traces.jsonl` + `stats.json` | — |211| `api` | [api-tracker](./agents/api-tracker.md) (sonnet) | `api_traces.jsonl` | — |212| `context` | [context-auditor](./agents/context-auditor.md) (sonnet) | `api_traces.jsonl` + `tool_traces.jsonl` | `--target`: read SKILL.md + agents for static cost |213214---215216### `evaluate` — Quality Evaluation (LLM-as-Judge)2172181. Resolve session + target plugin (optional: `--target` scopes evaluation)2192. Read `tool_traces.jsonl` + `otel_traces.jsonl` + `stats.json`2203. Read agent: [agents/quality-evaluator.md](./agents/quality-evaluator.md)2214. Invoke Task (sonnet): pass agent definition + data2225. Output: 4-dimension scores + quantified improvement signals2236. **Write** result to `SESSION_DIR/evaluation.json`2247. **Append** to `~/.claude/plugin-introspector/evaluation_history.jsonl`:225 - From quality-evaluator output: `weighted_score`, `scores`226 - From stats.json: `key_metrics` (tool_calls, total_tokens_est, errors, error_rate, duration_ms)227 - From orchestrator phase detection (via plugin profile + trace analysis): `phase_breakdown` (optional, only for phased workflows)228 - From quality-evaluator `improvement_signals`: `top_waste_sources` (top 3 waste entries)229 - From improvement_log: `improvements_active` (IDs where `status == "applied"`)2308. **Update phase baselines** (if target_plugin has profile with `workflow.type == "phased"`):231 - Read `plugin-profiles/{plugin}/phase-baselines.json`232 - Update running mean/stddev for each phase using current phase_breakdown233 - Increment `sessions_count`, set `maturity.baselines_available = true` if count ≥ 52349. **Closed Loop Check**: Read `~/.claude/plugin-introspector/improvement_log.jsonl`235 - Find entries where `status == "applied"` and `post_score == null`236 - If `--target` specified: only check entries matching `target_plugin`237 - For each pending entry: compare current `weighted_score` with `pre_score`238 - Update `post_score` and set `status` to `validated` or `regressed`239 - If regressed (score dropped >0.5): suggest rollback via [improvement-apply-protocol.md](./resources/improvement-apply-protocol.md)240241---242243### `alerts` — Anomaly Detection2442451. Read `~/.claude/plugin-introspector/alerts.jsonl` → display recent alerts2462. If deeper analysis requested:247 - Resolve session248 - Read `tool_traces.jsonl` + `session_history.jsonl` + `alerts.jsonl`249 - Read agent: [agents/anomaly-detector.md](./agents/anomaly-detector.md)250 - Invoke Task (haiku): pass agent definition + data (including alerts.jsonl for deduplication)2513. Output: alert list with severity, suggested actions252253---254255### `optimize` — Auto-Optimize (APE Loop) *(available, experimental)*2562571. Resolve target plugin (required: `--target`)2582. Resolve target component (`--component` or auto-select lowest-scoring)2593. Read `evaluation.json` (run `evaluate` first if missing)2604. Read `evaluation_history.jsonl` + `improvement_log.jsonl` (for contrastive analysis + historical learning)2615. Read agent: [agents/auto-optimizer.md](./agents/auto-optimizer.md)2626. Read target component file content2637. Invoke Task (opus): pass agent definition + evaluation + history + component content2648. Output: optimized version with diff + predicted score improvement2659. **Display diff for user review** — do NOT auto-apply266267**CAUTION**: Review all diffs before applying. See [resources/improvement-apply-protocol.md](./resources/improvement-apply-protocol.md).268269---270271### `improve` — Generate Improvement Proposals2722731. Resolve session + target plugin (required: `--target`)2742. Run analysis pipeline (or reuse if already run in this session):275 - Parallel: workflow-analyzer, token-optimizer, context-auditor276 - Parallel: anomaly-detector, quality-evaluator2773. Load cross-session data:278 - `evaluation_history.jsonl` (last 20 records)279 - `improvement_log.jsonl` (all for target plugin)280 - Plugin profile: `profile.json`, `phase-baselines.json`, `learned-patterns.jsonl`2814. Read target plugin component files (apply file selection per orchestration-protocol.md)2825. Read agent: [agents/improvement-generator.md](./agents/improvement-generator.md)2836. Read procedure: [resources/improvement-pipeline.md](./resources/improvement-pipeline.md)2847. Invoke Task (opus): pass agent definition + pipeline procedure + all analysis results + cross-session data + selected plugin files2858. Output: ROI-scored proposals with quantified evidence, counterfactuals, diffs, meta-rules validation2869. **Display proposals for user review** — do NOT auto-apply287288---289290### `report` — Full Analysis Report2912921. Resolve session + target plugin2932. Read all JSONL data files once2943. Run independent agents in parallel (4 concurrent Task calls):295 - workflow-analyzer → analysis296 - token-optimizer → tokens297 - api-tracker → api298 - context-auditor → context2994. Run quality-evaluator sequentially (can use results from step 3 if needed)3005. Aggregate into unified report with sections:301 - Executive Summary, Workflow Analysis, Token Efficiency,302 API Performance, Context Audit, Quality Score, Recommendations303304---305306### `apply` — Apply Improvement Proposals3073081. Read the most recent `improve` or `optimize` output (proposals)3092. For each proposal, follow [improvement-apply-protocol.md](./resources/improvement-apply-protocol.md):310 - Display proposal summary + diff for user review311 - Wait for explicit user confirmation312 - Backup → Edit → Verify → Log to `improvement_log.jsonl`3133. After all approved proposals applied:314 - Display summary of changes315 - Suggest: "Run `evaluate --target {plugin}` after next session to validate improvements"316317**CAUTION**: Never auto-apply. Each proposal requires explicit user approval.318319---320321### `quick-scan` — Quick Plugin Diagnosis (1-minute)3223231. Resolve target plugin (required: `--target`)3242. Analyze plugin structure: plugin.json, SKILL.md, agents, scripts, resources3253. Run `security-scan.sh` for security score3264. Read agent: [agents/quick-scanner.md](./agents/quick-scanner.md)3275. Invoke Task (haiku): lightweight analysis3286. Output: formatted box diagram with structure summary, security score, recommendations3297. Suggest follow-up commands for detailed analysis330331**Use case:** First-time plugin evaluation, PR review, quick health check332333> Details: [agents/quick-scanner.md](./agents/quick-scanner.md)334335---336337### `rotate-data` — Data Retention Management3383391. Run `Bash: scripts/rotate-data.sh`3402. Deletes session directories older than `PI_RETENTION_DAYS` (default: 30)3413. Trims JSONL files to `PI_RETENTION_LINES` (default: 1000)3424. Displays summary of deleted sessions and freed space343344**Environment variables:**345- `PI_RETENTION_DAYS=30`: Days to keep session directories346- `PI_RETENTION_LINES=1000`: Lines to keep in JSONL files347- `PI_DRY_RUN=1`: Preview what would be deleted without actually deleting348- `PI_AUTO_ROTATE=1`: Auto-run at session end (optional)349350**Example:**351```bash352# Dry run to see what would be deleted353PI_DRY_RUN=1 /plugin-introspector rotate-data354355# Keep only 7 days of data356PI_RETENTION_DAYS=7 /plugin-introspector rotate-data357```358359---360361### `security-scan` — Plugin Static Security Analysis3623631. Resolve target plugin (required: `--target`)3642. Run `Bash: scripts/security-scan.sh {plugin-path}`3653. Scans hook scripts for dangerous patterns (data exfiltration, reverse shells, credential theft)3664. Scans SKILL.md + resources for prompt injection patterns3675. Scans agent definitions for risky tool permission combinations3686. Output: JSON report with findings, severity levels, risk score3697. Logs findings to `alerts.jsonl` if any found370371**Environment variables:**372- `PI_ENABLE_SECURITY=1`: Enables runtime command risk logging373- `PI_ENABLE_DLP=1`: Enables DLP scanning374- `PI_SECURITY_BLOCK=1`: Enables CRITICAL command blocking (use with caution)375376> **Note:** `security-check.sh` intentionally omits `|| true` in plugin.json so that `exit 2` can block CRITICAL commands when `PI_SECURITY_BLOCK=1`. All other hook scripts use `|| true` per meta-rules.377378> Details: [resources/security-patterns.md](./resources/security-patterns.md)379380---381382### `security-audit` — Session Security Audit3833841. Resolve session3852. Read `tool_traces.jsonl` + `otel_traces.jsonl` + `stats.json` + `security_events.jsonl` + `alerts.jsonl`3863. Read agent: [agents/security-auditor.md](./agents/security-auditor.md)3874. Invoke Task (haiku): pass agent definition + all data (including stats.json)3885. Output: risk level, file access audit, command audit, suspicious sequences, DLP summary3896. Recommendations for security improvements390391---392393### `security-dashboard` — Security Risk Visualization3943951. Resolve session3962. Run `Bash: scripts/security-dashboard.sh {session-id}`3973. Renders security-focused dashboard with:398 - Overall risk score bar399 - DLP violations, sensitive reads/writes, risky commands400 - Recent security events401 - Security configuration status (DLP, security check, blocking)402403---404405### `compliance-report` — Compliance Report Generation *(available, experimental)*4064071. Read `session_history.jsonl` for specified period4082. Read `alerts.jsonl` + `security_events.jsonl` + `improvement_log.jsonl` (aggregated)4093. Optionally run `security-scan` for each active plugin4104. Read agent: [agents/security-reporter.md](./agents/security-reporter.md)4115. Invoke Task (sonnet): pass agent definition + period data4126. Output: SOC 2 / ISO 27001 compliance report with executive summary, security events,413 plugin audit, recommendations, and compliance mapping414415---416417### `otel-setup` — OTel Collector Setup (Tier 1) *(available, experimental)*4184191. Run `Bash: scripts/setup-otel-collector.sh {subcommand}`420 - `install`: Download OTel Collector Contrib binary (~100MB+)421 - `start`: Start collector with `otel-config.yaml` (OTLP receiver → file exporter)422 - `stop`: Stop collector423 - `status`: Show collector status, export data info, environment variables424 - `env`: Print shell environment variables to set4252. Display output to user426427After setup, the collection tier automatically upgrades from Tier 0 to Tier 1.428Hook scripts detect the running collector and skip redundant OTel span generation.429Native OTel spans (with accurate token counts) are merged at session end.430431> See: [Collection Tiers in orchestration-protocol.md](./resources/orchestration-protocol.md#collection-tiers)432433---434435### `otel-security-map` — OTel Security Event Mapper *(available, experimental)*4364371. Run `Bash: scripts/otel-security-mapper.sh [session-id|--watch|--stats]`4382. Converts native Claude Code OTel events to PI security_events.jsonl format4393. Enables deeper security analysis using OTel's tool_parameters (bash_command, full_command)4404. Output modes:441 - `<session-id>`: Process specific session's OTel data442 - `--watch`: Real-time mapping mode443 - `--stats`: Show security statistics from OTel data444445**Use case:** Enhanced security analysis with native OTel data (Tier 1+)446447---448449### `trace` — Raw Trace Viewer4504511. Resolve session4522. Read `tool_traces.jsonl` with filters: `--tool {name}`, `--errors`, `--slow`, `--last {N}`4533. Display formatted records454455---456457### `web` — Export for External Tools4584591. Resolve session4602. Export format: `--otel`, `--json`, `--csv`4613. Write export file, display path462463---464465## Environment Variables466467All environment variables are opt-in. Default behavior requires no configuration.468469| Variable | Default | Description |470|----------|---------|-------------|471| `PI_ENABLE_SECURITY` | 0 | Enable runtime command risk logging |472| `PI_ENABLE_DLP` | 0 | Enable DLP (sensitive data detection) |473| `PI_SECURITY_BLOCK` | 0 | Block CRITICAL commands (use with caution) |474| `PI_RETENTION_DAYS` | 30 | Days to keep session data |475| `PI_RETENTION_LINES` | 1000 | Lines to keep in JSONL files |476| `PI_DRY_RUN` | 0 | Preview data rotation without deleting |477| `PI_AUTO_ROTATE` | 0 | Auto-rotate data at session end |478| `PI_SHOW_REMINDER` | 1 | Show PI commands reminder at session start |479| `PI_TELEMETRY` | 0 | Enable opt-in anonymous telemetry (local only) |480| `PI_BASELINE_MAX_AGE` | 30 | Days of history for security baseline |481482**Telemetry Policy (PI_TELEMETRY):**483- Data stored locally in `telemetry.jsonl` — never transmitted externally484- Collects: command counts only (no content, paths, or personal data)485- Use `scripts/telemetry.sh status` to view collected data486487---488489## Resources (On-demand)490491| Document | Purpose |492|----------|---------|493| [orchestration-protocol.md](./resources/orchestration-protocol.md) | Agent invocation, data passing, pipeline composition |494| [improvement-apply-protocol.md](./resources/improvement-apply-protocol.md) | Safe improvement application with rollback |495| [improvement-pipeline.md](./resources/improvement-pipeline.md) | Quantified improvement generation procedure |496| [data-schema.md](./resources/data-schema.md) | JSONL record format specifications |497| [security-patterns.md](./resources/security-patterns.md) | Security threat patterns, DLP signatures, compliance mapping |498| [ci-cd-integration.md](./resources/ci-cd-integration.md) | GitHub Actions, GitLab CI, Jenkins pipeline examples |499| [skill-activation-guide.md](./resources/skill-activation-guide.md) | Optional Forced Eval Hook installation for 84% skill activation |500| [otel-collector-guide.md](./resources/otel-collector-guide.md) | OTel Collector setup with ClickStack/HyperDX |501| [docker-compose.otel.yml](./resources/docker-compose.otel.yml) | Docker Compose for OTel stacks |502| [otel-collector-config.yaml](./resources/otel-collector-config.yaml) | Standalone OTel Collector configuration |503504## Agents505506| Agent | Purpose | Model |507|-------|---------|-------|508| [workflow-analyzer](./agents/workflow-analyzer.md) | Execution pattern analysis, bottleneck detection | sonnet |509| [token-optimizer](./agents/token-optimizer.md) | Token waste identification, optimization suggestions | sonnet |510| [context-auditor](./agents/context-auditor.md) | Context window usage audit | sonnet |511| [api-tracker](./agents/api-tracker.md) | API interaction monitoring and analysis | sonnet |512| [quality-evaluator](./agents/quality-evaluator.md) | LLM-as-Judge multi-dimension evaluation | sonnet |513| [anomaly-detector](./agents/anomaly-detector.md) | Real-time anomaly detection via Z-score/MA | haiku |514| [plugin-profiler](./agents/plugin-profiler.md) | Target plugin workflow profiling | haiku |515| [improvement-generator](./agents/improvement-generator.md) | Concrete improvement proposal generation | opus |516| [auto-optimizer](./agents/auto-optimizer.md) | APE-based automatic prompt optimization | opus |517| [security-auditor](./agents/security-auditor.md) | Session security audit and risk classification | haiku |518| [security-reporter](./agents/security-reporter.md) | Compliance report generation (SOC 2, ISO 27001) | sonnet |519| [quick-scanner](./agents/quick-scanner.md) | Fast plugin structure and security diagnosis | haiku |520521## Skills (Knowledge Base)522523| Skill | Purpose |524|-------|---------|525| [meta-rules](../meta-rules/SKILL.md) | Agent/skill writing rules and anti-bloat constraints |526| [analysis-patterns](../analysis-patterns/SKILL.md) | Reusable analysis patterns and heuristics |527| [cost-tracking](../cost-tracking/SKILL.md) | Model-specific pricing and cost calculation |528529---530531## Closed Loop: Improve → Apply → Validate532533The full improvement cycle connects `improve`, `evaluate`, and the apply protocol:534535```536┌─────────┐ ┌───────────┐ ┌─────────┐ ┌──────────┐537│ improve │────▶│ user │────▶│ apply │────▶│ log to │538│ (propose)│ │ review │ │ (backup, │ │ improve- │539│ │ │ (approve?)│ │ edit, │ │ ment_log │540│ │ │ │ │ verify) │ │ .jsonl │541└─────────┘ └───────────┘ └─────────┘ └────┬─────┘542 │543 ▼544┌─────────┐ ┌───────────┐ ┌─────────────────────────┐545│ rollback │◀───│ regressed │◀───│ evaluate (next session) │546│ (if bad) │ │ score? │ │ → checks pending │547│ │ │ │ │ post_scores in log │548└─────────┘ └───────────┘ └─────────────────────────┘549```550551### Lifecycle5525531. **`improve`** generates proposals with diffs and meta-rules validation5542. **User reviews** each proposal (never auto-apply)5553. **Apply** follows [improvement-apply-protocol.md](./resources/improvement-apply-protocol.md):556 - Backup → Edit → Verify → Log to `improvement_log.jsonl` with `post_score: null`5574. **Next `evaluate` run** (step 9 — Closed Loop Check) detects pending entries and fills `post_score`5585. **If validated** (`post_score >= pre_score`): mark `status: "validated"`5596. **If regressed** (`post_score < pre_score - 0.5`): suggest rollback, mark `status: "regressed"`560561### Rollback Trigger562563When `evaluate` detects regression:564```5651. Display: "Improvement {proposal_id} caused score regression: {pre_score} → {post_score}"5662. Offer rollback: "Restore from backup? (yes/no)"5673. If yes: follow rollback procedure in improvement-apply-protocol.md5684. Log rollback to improvement_log.jsonl569```570571---572573## Self-Referential Loop Prevention5745751. Hook scripts check `CLAUDE_TOOL_NAME` + structured Skill name via jq — skip if Skill invocation targets `plugin-introspector`5762. Analysis agents exclude introspector-related tool calls from analysis5773. When running `improve --target plugin-introspector`: extra caution, meta-rules strictly enforced