Skip to content

SmokeAlot420/piv--loop-sdk

Repository files navigation

PIV Loop SDK

A comprehensive TypeScript SDK for building AI coding agents using the PIV (Plan, Implement, Validate) methodology. Built on top of the Claude Agent SDK, this framework provides a structured approach to autonomous software development with AI.

Overview

The PIV Loop SDK implements a battle-tested agentic coding workflow inspired by the Dynamous Agentic Coding Course. It provides:

  • Structured Planning: Deep codebase analysis before implementation
  • Iterative Development: Plan → Implement → Validate cycles
  • Meta-Learning: System reviews that improve future performance
  • Parallel Development: Git worktree support for concurrent features
┌─────────────────────────────────────────────────────────────────┐
│                     PIV LOOP WORKFLOW                           │
├─────────────────────────────────────────────────────────────────┤
│                                                                 │
│   ┌──────────┐    ┌─────────────┐    ┌────────────┐            │
│   │  PLAN    │───▶│ IMPLEMENT   │───▶│  VALIDATE  │            │
│   └──────────┘    └─────────────┘    └────────────┘            │
│        │                                    │                   │
│        │              ┌────────┐            │                   │
│        │              │  FIX   │◀───────────┤ (if failed)       │
│        │              └────────┘            │                   │
│        │                  │                 │                   │
│        │                  ▼                 ▼                   │
│        │         ┌─────────────────────────────┐               │
│        │         │     ITERATE UNTIL PASS      │               │
│        │         └─────────────────────────────┘               │
│        │                       │                                │
│        │                       ▼                                │
│        │              ┌────────────┐                           │
│        └─────────────▶│   REVIEW   │                           │
│                       └────────────┘                           │
│                              │                                  │
│                              ▼                                  │
│                       ┌────────────┐                           │
│                       │   COMMIT   │                           │
│                       └────────────┘                           │
│                                                                 │
└─────────────────────────────────────────────────────────────────┘

Features

Rich Terminal UI

  • Ink-based React UI: Beautiful terminal interface built with Ink
  • Slash Command Autocomplete: Type / to see dropdown of all commands with filtering
  • Interactive Permission Prompts: Y/A/N approval for dangerous tools (Bash, Write, Edit)
  • ULTRATHINK Gradient: Green phosphor effect when typing ultrathink prefix
  • Permission Mode Cycling: Shift+Tab to cycle default → acceptEdits → bypassPermissions
  • Real-time Status Bar: Context usage, thinking state, and keyboard shortcuts
  • MCP Server Panel: Interactive panel showing server health with connect/disconnect actions
  • Animated Thinking Indicator: Spinner with elapsed time and current tool display
  • Styled Message Stream: Color-coded messages, tool cards, and error handling

Structured Logging

  • OpenTelemetry-compliant: JSON structured output for machine parsing
  • Session Correlation: Track operations across PIV phases with session IDs
  • Duration Tracking: Built-in timing with startTimer() utility
  • Namespace Pattern: {domain}.{component}.{action}_{state}

Core PIV Loop

  • 5-Level Validation Pyramid: Syntax → Types → Unit Tests → Integration → Human Review
  • Subagent Architecture: Orchestrator, Planner, Implementer, Validator, Reviewer
  • Automatic Escalation: Human-in-the-loop when iteration limits reached

19 Built-in Commands

Command Description
/prime Load codebase context and patterns
/prime-tools Load tool-specific patterns
/plan Basic feature planning
/plan-feature Deep planning with codebase analysis
/execute Implement from a plan file
/validate Run validation pyramid
/code-review Technical code review
/code-review-fix Fix review issues
/commit Git commit with conventions
/system-review Meta-level process analysis
/execution-report Document implementation
/create-prd Generate PRD from conversation
/end-to-end-feature Full autonomous workflow
/rca Root Cause Analysis for bugs
/implement-fix Implement fix from RCA
/init-project Project setup and verification
/new-worktree Create parallel dev branches
/merge-worktrees Merge with full validation

Reference Documentation

  • PRD/PRP templates and guides
  • VSA (Vertical Slice Architecture) patterns
  • API and Frontend component guides
  • Tool design patterns

Agent Definitions

  • Code Reviewer agent with full standards
  • Template for creating custom agents

Full Claude Code Capabilities

The ConversationalAgent wraps the Claude Agent SDK with all capabilities:

  • MCP Servers: stdio, HTTP, SSE server integration
  • Permissions: default, acceptEdits, bypassPermissions modes
  • Hooks: PreToolUse, PostToolUse, Stop, Notification events
  • Sandbox: Secure command execution with network controls
  • Session Management: Resume, fork, and continue sessions
  • Tool Control: Whitelist/blacklist specific tools

Mobile Access (NEW!)

Access the full PIV Loop agent from your phone via:

  • Discord Bot: Chat with Claude via /chat commands
  • Web/PWA: Mobile-optimized terminal UI, installable as app
  • Shared Backend: Express + Socket.io API with streaming

CLI Commands

Basic Usage

Command Description
pivloop Start interactive session
pivloop "request" One-shot mode for single task
pivloop --help Show help and options
pivloop --cwd ./project Work in specific directory
pivloop --max-turns 100 Set max agent turns
pivloop -V Verbose mode (show tool calls)

Advanced Options

Flag Description
--model <name> Override model (default: claude-opus-4-5-20251101)
--max-thinking <n> Max thinking tokens (default: 128000)
--max-budget <usd> Budget limit in USD
--permission <mode> Permission mode: default|acceptEdits|bypassPermissions
--allow-tools <list> Comma-separated tool whitelist
--disallow-tools <list> Comma-separated tool blacklist
--mcp <json> MCP server config as JSON
--resume <id> Resume session by ID
--continue Continue most recent session
--sandbox Enable sandbox mode
--setting-sources <list> Setting sources: user,project,local
--no-piv Disable PIV personality (raw Claude Code)
--env <key>=<value> Set environment variable (repeatable)

Installation

# Clone the repository
git clone https://github.com/SmokeAlot420/piv--loop-sdk.git
cd piv--loop-sdk

# Install dependencies
npm install

# Build and link globally
npm run build
npm link              # Makes 'pivloop' command available globally

# Set up environment
export ANTHROPIC_API_KEY=your-api-key

Quick Start

Interactive Mode (Recommended)

Run pivloop to start an interactive session - like Claude Code, but with PIV methodology built in:

pivloop

# You'll see:
# ╔═══════════════════════════════════════════════════════════════╗
# ║   PIV LOOP AGENT                                               ║
# ║              Plan → Implement → Validate → Iterate             ║
# ╚═══════════════════════════════════════════════════════════════╝
#
# Hey! I'm your PIV Loop agent. I think in Plan → Implement → Validate.
# Tell me what you want to build, and I'll handle it methodically.
#
# piv> _

Then just tell it what to build!

One-Shot Mode

pivloop "Add user authentication feature"

From Source

npm start              # Interactive mode
npm start "Fix bug"    # One-shot mode

Workflow Examples

Simple Bug Fix (Micro PIV):

/prime → implement fix → /validate → /commit

New Feature (Feature PIV):

/prime → /plan-feature → /execute → /validate → /code-review → /commit

Full Project (Full PIV):

/prime → /create-prd → extract features →
for each feature:
  /plan-feature → /execute → /validate → /code-review
/system-review → /commit

GitHub Issue Fix:

/rca [issue-id] → /implement-fix [issue-id] → /validate → /commit

End-to-End Autonomous:

/end-to-end-feature "Add dark mode toggle"

Mobile Access

The PIV Loop SDK includes packages for accessing Claude Code from mobile devices.

Architecture

┌─────────────────────────────────────────────────────────────────┐
│                     YOUR SERVER (Backend)                       │
├─────────────────────────────────────────────────────────────────┤
│  ┌──────────────────┐    ┌────────────────────────────────┐    │
│  │  PIV Loop API    │◄───│  ConversationalAgent           │    │
│  │  (Express + WS)  │    │  (Full Claude Code)            │    │
│  └────────┬─────────┘    └────────────────────────────────┘    │
└───────────┼─────────────────────────────────────────────────────┘
            │
    ┌───────┴───────┐
    ▼               ▼
┌───────────┐  ┌───────────┐
│  Discord  │  │  Web/PWA  │
│  Bot      │  │  (Mobile) │
└───────────┘  └───────────┘

Quick Setup

# On your server (SSH in first)
curl -fsSL https://raw.githubusercontent.com/SmokeAlot420/piv--loop-sdk/main/deploy/setup.sh | bash

# Edit configuration
nano /opt/pivloop/packages/api/.env        # API key, Claude key
nano /opt/pivloop/packages/discord/.env    # Discord bot token

# Restart services
pm2 restart all

Discord Bot Commands

Command Description
/chat <message> Send a message to Claude
/session new Start fresh session
/session status Check current status
/session clear Clear conversation history
/session stop Interrupt current operation
/project clone <url> Clone a GitHub repo
/project list List available projects
/project pull <name> Pull latest changes

Web/PWA Features

  • Mobile-optimized terminal interface
  • Syntax highlighting for code blocks
  • Installable as PWA on iPhone/Android
  • Real-time streaming via WebSocket
  • Touch-friendly design

Packages

Package Description
@piv-loop/api Backend server with REST + WebSocket
@piv-loop/discord Discord bot with slash commands
@piv-loop/web React PWA for mobile browsers

Project Structure

piv-loop-sdk/
├── src/
│   ├── index.ts          # Core PIV loop implementation
│   ├── cli.ts            # CLI entry point with all flags
│   ├── orchestrator.ts   # Main PIV loop coordinator
│   ├── conversation/     # ConversationalAgent modules
│   │   ├── index.ts      # Main agent class
│   │   ├── options.ts    # AgentOptions builder
│   │   ├── agents.ts     # Custom agent configuration
│   │   ├── mcp.ts        # MCP server configuration
│   │   ├── hooks.ts      # Hook system for events
│   │   └── tools.ts      # Tool management
│   ├── agents/           # PIV subagent implementations
│   │   ├── planner.ts    # PRD creation, feature planning
│   │   ├── implementer.ts# Task execution
│   │   ├── validator.ts  # 5-level validation pyramid
│   │   └── reviewer.ts   # Code review, system learning
│   ├── features/         # Feature modules
│   │   ├── commands.ts   # Slash command system
│   │   ├── mcp.ts        # MCP server health/config
│   │   └── plugins.ts    # Plugin management
│   ├── ui/               # Ink-based terminal UI
│   │   ├── App.tsx       # Main Ink application
│   │   ├── components/   # Header, StatusBar, InputPrompt, CommandAutocomplete
│   │   │   └── panels/   # McpPanel, ServerCard, ServerActions
│   │   └── hooks/        # useAgent, useThinking, useMcpHealth, useCommandAutocomplete
│   ├── utils/            # Utilities
│   │   ├── logger.ts     # Structured logging
│   │   └── errors.ts     # Error handling
│   └── types/            # TypeScript type definitions
├── docs/
│   └── API.md            # Comprehensive API reference
├── .agents/
│   ├── commands/         # 19 command definitions
│   ├── reference/        # 12 reference documents (PRD, VSA patterns, etc.)
│   ├── agents/           # Agent definitions (code-reviewer, template)
│   ├── plans/            # Generated PRPs
│   ├── execution-reports/# Implementation reports
│   └── system-reviews/   # Meta-level reviews
├── tests/                # Unit and integration tests (627 tests)
│   ├── conversation.test.ts  # Agent options, MCP, custom agents
│   ├── cli.test.ts           # CLI flags and help output
│   ├── orchestrator.test.ts  # PIV loop coordinator
│   ├── agents/               # Subagent tests
│   ├── features/             # Feature module tests
│   ├── utils/                # Utility tests
│   └── ui/                   # UI component and hook tests
├── packages/             # Mobile access packages
│   ├── api/              # Backend server (Express + Socket.io)
│   ├── discord/          # Discord bot
│   └── web/              # React PWA
├── CLAUDE.md             # Project-specific AI rules
├── package.json
└── tsconfig.json

Configuration

CLAUDE.md

The CLAUDE.md file contains project-specific rules that guide the AI agent:

# Project Rules

## Architecture
- Use TypeScript with strict mode
- Follow VSA patterns
- Structured logging required

## Conventions
- camelCase for functions
- PascalCase for types
- Descriptive variable names

Validation Pyramid Levels

Level Check Command
1 Syntax & Style npm run lint
2 Type Safety npm run typecheck
3 Unit Tests npm test
4 Integration npm run test:integration
5 Human Review Manual approval

API Reference

For comprehensive API documentation, see docs/API.md.

Documentation

Document Description
Architecture System diagrams, PIV loop flow, and component relationships
API Reference Complete API documentation with examples
Troubleshooting Common issues, error codes, and debugging tips
Contributing How to contribute, code style, and PR process
Changelog Version history and release notes

Quick Reference

import { PIVOrchestrator, createPlannerAgent, createValidatorAgent } from 'loop-agent';

// Run a complete PIV loop
const orchestrator = new PIVOrchestrator(config, runCommand, fileOps);
const finalState = await orchestrator.run('Add user authentication');

// Use individual agents
const plannerConfig = createPlannerAgent();
const prd = await createPRD(plannerConfig, 'Build a REST API');

const validatorConfig = createValidatorAgent();
const result = await runValidationPyramid(validatorConfig, commands, runCommand);

Core Types

interface PIVLoopState {
  sessionId: string;
  userRequest: string;
  phase: PIVPhase;
  status: 'idle' | 'running' | 'paused' | 'completed' | 'failed';
  prd?: PRD;
  features: Feature[];
  validationResults: ValidationResult[];
  totalIterations: number;
}

type PIVPhase = 'idle' | 'discovery' | 'creating_prd' | 'planning_feature'
  | 'implementing' | 'validating' | 'reviewing' | 'completed' | 'failed';

Extending the SDK

Adding Custom Commands

Create a new file in .agents/commands/:

---
description: Your command description
argument-hint: [optional-args]
---

# Command Name

## Purpose
What this command does

## Process
1. Step one
2. Step two

## Output
What the command produces

Creating Custom Agents

Use the template in .agents/agents/agent-template.md:

---
name: my-agent
description: When to use this agent
model: sonnet
---

# My Agent

## Mission
What this agent accomplishes

## Process
How it works

## Output Format
What it returns

Contributing

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Run the PIV loop on your changes
  4. Commit using conventional commits
  5. Push and create a Pull Request

Acknowledgments & Credits

The PIV Loop Methodology

This SDK implements the PIV (Plan, Implement, Validate) methodology created by the Dynamous Community.

"Only about 5% of developers have mastered a systematic approach that produces consistent, reliable results. The PIV Loop bridges that gap."

Special Thanks

Cole Medin - Software engineer, entrepreneur, and AI agent expert who's been using AI coding assistants daily to ship production software, automations, and AI agents.

Rasmus Widing - Project manager and expert at building AI coding systems, creator of the PRP framework, focused on building systems that fully delegate coding to AI.

Course Materials

The framework, commands, and workflows in this SDK are derived from the Dynamous Agentic Coding Course, specifically:

  • Modules 3-12: Commands, planning systems, validation pyramids
  • The PRP Framework: Per-task Requirement Plans by Rasmus Widing
  • VSA Patterns: Vertical Slice Architecture for AI-assisted development
  • The 5-Level Validation Pyramid: Systematic code quality verification

Built With

License

MIT License - see LICENSE for details.


Built with the PIV Loop methodology for reliable AI-assisted software development.

Learn more at community.dynamous.ai

About

No description, website, or topics provided.

Resources

License

Contributing

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors