Metadata-Version: 2.4
Name: wrought
Version: 1.0.0
Summary: Spec-driven engineering for Claude Code — enforced, and audited
Project-URL: Homepage, https://fluxforge.ai
Project-URL: Repository, https://github.com/fluxforgeai/wrought-plugin
Project-URL: Issues, https://github.com/fluxforgeai/wrought-plugin/issues
Author-email: FluxForge AI <hello@fluxforge.ai>
License-Expression: MIT
License-File: LICENSE
License-File: NOTICE
Keywords: ai-agents,claude-code,cli,code-review,engineering-methodology,findings-tracker,spec-driven-development,workflow
Classifier: Development Status :: 5 - Production/Stable
Classifier: Environment :: Console
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Quality Assurance
Requires-Python: >=3.10
Description-Content-Type: text/markdown

# Wrought

**AI Engineering Skills Toolkit by FluxForge AI**

Wrought gives your AI coding assistant a structured engineering process. Instead of ad-hoc debugging and scattered notes, every incident, investigation, finding, and design decision follows a repeatable workflow — and produces documentation that builds your project's institutional memory over time.

Think of it as an engineering runbook that your AI assistant actually follows.

---

## Table of Contents

- [Quick Start](#quick-start)
- [How Wrought Thinks](#how-wrought-thinks)
- [Complete Skills Reference](#complete-skills-reference)
  - [Reactive Skills](#reactive-skills)
  - [Proactive Skills](#proactive-skills)
  - [Strategic Skills](#strategic-skills)
  - [Onboarding Skills](#onboarding-skills)
  - [Code Quality Skills](#code-quality-skills)
  - [Greenfield Onboarding](#greenfield-onboarding)
- [Real-World Scenarios](#real-world-scenarios)
- [The Findings Tracker](#the-findings-tracker)
- [Environment Profiling](#environment-profiling)
- [Session Management](#session-management)
- [Autonomous Implementation Loop](#autonomous-implementation-loop)
- [Workflow Enforcement](#workflow-enforcement)
- [Artifact Index](#artifact-index)
- [CLI Reference](#cli-reference)
- [Under the Hood](#under-the-hood)
- [Project Conventions](#project-conventions)
- [License](#license)

---

## Quick Start

> **Spec-driven / agentic engineering for Claude Code — with enforcement + audit.** Most frameworks *tell* your agent the process; **WROUGHT™** *makes* it follow the pipeline (PreToolUse / Stop hooks) and *proves* it followed (cross-session Findings Trackers).

### Install — Claude Code plugin (recommended, no Python)

In Claude Code:

```
/plugin marketplace add fluxforgeai/wrought-plugin
/plugin install wrought@wrought-plugin
```

That installs the full WROUGHT™ pipeline — skills, commands, hooks, agents — into your project.

### Prerequisites

- Python 3.10 or later
- [uv](https://docs.astral.sh/uv/) package manager
- An AI coding assistant that supports skills/commands (Claude Code, Cursor, Cline)

### Installation

```bash
# Install the CLI from PyPI
uv tool install wrought      # or: pipx install wrought
```

### Initialize in Any Project

```bash
cd ~/your-project
wrought init
```

This runs a 5-step setup:

```
Wrought v1.0.0 — Initializing...

[1/5] Copying skills and commands
  Copied .claude/skills/
  Copied .claude/commands/

[2/5] Scaffolding docs structure
  Created docs/ (14 directories)

[3/5] Project context
  Created CLAUDE.md (auto-detected: project=my-app, user=Johan, tz=SAST)

[4/5] Version control
  Detected: Git repository with GitHub remote (myorg/my-app)
  Created .gitignore with Wrought entries

[5/5] Wrought marker
  Written .wrought (17 fields)

Wrought initialized in /Users/you/my-app

Next: Open Claude Code and run /session-start
```

Use `-n` for non-interactive mode (skips VCS prompts, ideal for scripting):

```bash
wrought init -n
```

### Verify It Works

```bash
wrought status
```

You should see your version, install path, installation status, and safeguard profile. Then try one of these in your AI assistant:

```
/analyze health                  # Get a health assessment of your codebase
/incident API returning 500s     # Document an incident when something breaks
/safeguard detect                # Profile your deployment environment
```

### Installing in Multiple Projects

Wrought copies skills into each project, so one installation serves every project:

```bash
cd ~/Projects/project-a && wrought init -n
cd ~/Projects/project-b && wrought init -n
cd ~/Projects/project-c && wrought init -n
```

All three projects share the same skills. Update once, apply everywhere.

---

## How Wrought Thinks

> *"Good intentions don't work. Mechanisms do."* — long an Amazon operating doctrine, and the cleanest one-line summary of why Wrought exists. Most frameworks *suggest* a process; Wrought builds the *mechanism* that makes it followed.

Wrought organizes engineering work into three pipelines. Each one starts with a trigger ("something happened" or "I want to build something") and ends with a documented plan ready for implementation.

You don't need to memorize the pipelines. Each skill tells you what to run next. But understanding the flow helps you get the most out of the toolkit.

Alongside the Findings Tracker, Wrought keeps a small **Active Constraints** surface in `CLAUDE.md` — a required-read list of in-force cross-session decisions ("don't re-propose X", "freeze module Y until Z"), each carrying a clearing predicate (`EXPIRES`/`CLEARS-WHEN`/`SUPERSEDED-ONLY`) so it decays by default instead of evaporating post-compaction or lingering as a stale rule. Inspect it with `wrought constraints list`. See [CONVENTIONS.md](CONVENTIONS.md#active-constraints-decisions-artifact-class).

### The Reactive Pipeline — "Something broke"

When production goes sideways, the reactive pipeline walks you through a structured response:

```
/watchdog  -->  /incident  -->  /investigate  -->  /rca-bugfix  -->  /wrought-rca-fix  -->  /forge-review
  (detect)      (document)       (dig in)         (fix + learn)     (implement loop)      (code review)
```

Each step reads the output of the previous step and builds on it. By the end, you have a documented incident, a root cause analysis, and a fix prompt ready for implementation. Three months from now, when someone asks "what happened to the API that night?", the answer is in `docs/incidents/`.

### The Proactive Pipeline — "Building something new"

When you're adding a feature, migrating a system, or making an architectural change:

```
/research  -->  /design  -->  [/ux-design]  -->  /blueprint  -->  /wrought-implement  -->  /forge-review
  (learn)       (decide)     (design UI)        (spec it)       (implement loop)        (code review)
                              (optional)
```

Research gathers context. Design evaluates trade-offs (should you use WebSockets or SSE? Redis or Memcached?). For frontend work, `/ux-design` generates a Design Brief with application-type-aware design tokens, typography, color, and anti-patterns — eliminating the generic "AI slop" aesthetic. Blueprint turns the chosen design (and Design Brief, if present) into an implementation spec. Plan mode turns it into code.

### The Audit Pipeline — "Found something that needs attention"

Sometimes you discover issues proactively — through code review, analysis, or just reading logs carefully. The audit pipeline handles these:

```
/analyze  -->  /finding  -->  (routes to Fix or Design branch)
```

The `/finding` skill classifies what you found and tells you where to go next:

- **Defect or Vulnerability?** Route to Fix: `/investigate` then `/rca-bugfix`
- **Technical debt, gap, or drift?** Route to Design: `/design` then `/blueprint`

Each downstream skill automatically updates the [Findings Tracker](#the-findings-tracker) with its stage transition:

```
Fix route:    /finding → /investigate → /rca-bugfix → /wrought-rca-fix → /forge-review
               Open    Investigating  RCA Complete    Implementing       Verified

Design route: /finding → /design   → [/ux-design] → /blueprint     → /wrought-implement → /forge-review
               Open     Designing    (optional)    Blueprint Ready     Implementing        Verified
```

### Onboarding — "How mature is this project's deployment?"

Before any of the pipelines above, Wrought can assess your project's deployment maturity:

```
/safeguard detect  -->  (profile artifact)
                          ↓ read by all pipelines
```

The safeguard skill scans your codebase for 12 deployment indicators — Docker, CI/CD, SIGTERM handling, environment count, process managers, health endpoints, and more — then classifies your project on a four-tier maturity scale. Every downstream skill can optionally read this profile to tailor its recommendations.

---

## Complete Skills Reference

Wrought ships with 12 skills, 3 implementation loop commands, and 3 session management commands organized across four categories. Every skill is invoked as a slash command and produces timestamped documentation in your project's `docs/` directory.

### Reactive Skills

These skills handle the "something broke" pipeline — from detection through root cause analysis.

#### `/watchdog` — Autonomous Log Monitoring

```
/watchdog {what to monitor}
```

A fully autonomous bash script that monitors logs after a fix is implemented. Once started, it runs independently — no AI session required, no user presence needed. When it spots trouble, it creates a structured JSON incident and fans out alerts via your configured backends (default: local-file + ntfy push to your phone; optional: Telegram, Slack, webhook, email).

**Examples**:
```
/watchdog Monitor extraction after retry logic fix - watch for timeout errors
/watchdog Watch backend after GCS upload fix - look for upload failures
/watchdog Monitor batch job API after endpoint fix
```

**What it does**:
- Polls any log source every 60 seconds (Docker, Kubernetes, file tail, CI output — configurable via `WATCHDOG_MONITOR_CMD`)
- Creates incident JSON files in `/tmp/watchdog_{id}_incidents/`
- Fans out distinct alerts via every configured backend for system errors vs fix-related errors
- De-duplicates similar errors (won't alert you 50 times for the same issue)
- Writes status every 60 seconds to a status file
- Runs until you stop it — survives Claude session endings

**Typical workflow**:
```
1. You deploy a fix at 11pm and start watchdog
2. You go to sleep
3. Watchdog detects an error at 3am
4. You get a push alert on your phone (via the first push-capable backend)
5. You wake up, start Claude, run: /incident {error summary}
6. The reactive pipeline picks up from there
```

**Writes to**: `/tmp/watchdog_{id}_incidents/*.json`

**Backends & setup**: see [`docs/setup/watchdog.md`](docs/setup/watchdog.md) for per-backend configuration (ntfy, Telegram, Slack, webhook, email) and [`.env.watchdog.example`](.env.watchdog.example) for a sample config.

---

#### `/incident` — Incident Documentation

```
/incident {brief description of what happened}
```

Creates a factual, timestamped record of what happened. Not why — that's for `/investigate` and `/rca-bugfix`. Think of it as the police report: just the facts, in chronological order.

**Examples**:
```
/incident Payment API returning 500 errors since 02:15 UTC, affecting checkout flow
/incident Database connection pool exhausted, all API requests timing out
/incident Background worker crashed with OOM, 15,000 jobs in dead letter queue
/incident Health check returning red for Backend since 09:15 UTC but API responding normally
```

**What it produces**: A structured incident report with:
- Timeline of events (exact times in UTC)
- Observed symptoms
- Affected systems and impact scope
- Current status

**Rules it follows**:
- Factual only — describes what was observed, not what is assumed
- Neutral language — no blame, no speculation
- Chronological — events in the order they occurred
- Specific — exact times, exact error messages, exact numbers

**Writes to**: `docs/incidents/{YYYY-MM-DD_HHMM}_{name}.md`
**Suggests next**: `/investigate`

---

#### `/investigate` — Deep Investigation

```
/investigate {incident report, finding report, or description}
```

Thorough investigation into an incident or finding. Reads past incidents, RCAs, and findings to identify patterns. Researches external documentation for known issues. Produces hypotheses backed by evidence.

**Examples**:
```
# Investigate from an incident report
/investigate docs/incidents/2026-02-10_0230_payment_api_500_errors.md

# Investigate from a finding report
/investigate docs/findings/2026-02-10_0800_state_desynchronization.md

# Investigate by finding number (tracker-aware)
/investigate F1

# Investigate from a description
/investigate Rate limiting errors despite batch processing - 429 responses every 2 seconds
```

**Two investigation modes**:

| Mode | Triggered By | Depth |
|------|-------------|-------|
| **Full Investigation** | Incident report or description | Deep dive — external research, hypothesis testing, evidence gathering |
| **Confirmation Mode** | Finding report (cause often already known) | Abbreviated — confirm scope, validate evidence, assess blast radius |

**What it does**:
1. Researches external documentation for relevant known issues
2. Reviews past RCAs and investigations in your project to recognize patterns
3. Deeply investigates the issue with hypothesis testing
4. Writes a detailed investigation report with evidence and recommended next steps

**Writes to**: `docs/investigations/{YYYY-MM-DD_HHMM}_{name}.md`
**Updates tracker**: Stage -> `Investigating`
**Suggests next**: `/rca-bugfix`

---

#### `/rca-bugfix` — Root Cause Analysis + Fix

```
/rca-bugfix {issue description, investigation report, or finding reference}
```

The culmination of the reactive pipeline. Identifies the root cause chain, produces a formal RCA document, and generates a ready-to-use implementation prompt for `/plan` mode.

**Examples**:
```
# From a description
/rca-bugfix Connection pool exhaustion causing payment API timeouts

# From an investigation report
/rca-bugfix docs/investigations/2026-02-10_0300_payment_api_timeout.md

# By finding number (resolves the full chain: tracker -> finding -> investigation)
/rca-bugfix F1

# From a finding when cause is already known (abbreviated RCA)
/rca-bugfix docs/findings/2026-02-10_0800_state_desynchronization.md
```

**What it reads** (in priority order):
1. Investigation reports in `docs/investigations/` — if one exists for this issue, it's the primary input
2. Finding reports in `docs/findings/` — if investigation was skipped, uses the finding directly
3. User-provided description — if no upstream artifacts exist

**What it produces**:
- **RCA document** in `docs/RCAs/` — root cause chain, contributing factors, timeline, evidence
- **Fix prompt** in `docs/prompts/` — ready for `/plan` mode implementation

**Writes to**: `docs/RCAs/{YYYY-MM-DD_HHMM}_{name}.md` and `docs/prompts/{YYYY-MM-DD_HHMM}_{name}.md`
**Updates tracker**: Stage -> `RCA Complete`
**Suggests next**: `/plan` mode with the generated prompt

---

### Proactive Skills

These skills handle the "building something new" pipeline — from research through implementation spec.

#### `/research` — Topic Research

```
/research {question or topic}
```

Researches a technical topic thoroughly, combining official documentation, community knowledge, and codebase analysis. Produces a documented record that prevents the same research from being repeated in future sessions.

**Examples**:
```
/research What are httpx timeout best practices for long-running downloads?
/research How does GCS resumable upload handle network interruptions?
/research WebSocket vs SSE vs long-polling for real-time order status updates
/research Why does Iterable batch export return 400 after job expires?
/research Best practices for database connection pooling in Python async applications
/research [paste an error message or documentation excerpt]
```

**What it does**:
1. Identifies the technologies and APIs involved
2. Searches official documentation (using current-year sources)
3. Searches Stack Overflow, GitHub issues, and community resources
4. Checks existing research in `docs/research/` and `docs/RCAs/` to avoid duplicating work
5. Writes a structured research report with findings, comparisons, and recommendations

**Writes to**: `docs/research/{YYYY-MM-DD_HHMM}_{topic}.md`
**Suggests next**: `/design` (if an architectural decision is needed) or `/blueprint` (if the path forward is clear)

---

#### `/design` — Architectural Design

```
/design {mode} {topic}
```

Research-driven, interactive design analysis for architectural decisions. Combines codebase analysis, documentation review, external research (current-year sources), and impact assessment to provide evidence-based recommendations.

**Five modes**:

| Mode | Command | When to Use |
|------|---------|-------------|
| **tradeoff** | `/design tradeoff {topic}` | Comparing approaches — the most common mode |
| **validate** | `/design validate {proposal}` | Reviewing a proposed design for completeness and risk |
| **migrate** | `/design migrate {from} {to}` | Planning a migration between approaches |
| **impact** | `/design impact {change}` | Assessing the blast radius of a specific change |
| **pattern** | `/design pattern {name}` | Explaining a pattern and assessing its applicability |

**Examples**:
```
# Compare approaches
/design tradeoff real-time communication for order status (WebSocket vs SSE vs polling)
/design tradeoff database migration strategy (Alembic vs raw SQL vs Django migrations)
/design tradeoff caching layer (Redis vs Memcached vs in-memory)

# Review a design
/design validate proposed microservices migration for the authentication layer
/design validate docs/design/2026-02-17_1825_review_deployment_safety_blueprint.md

# Plan a migration
/design migrate session-based auth to JWT
/design migrate monolith to event-driven architecture

# Assess impact
/design impact replacing PostgreSQL with CockroachDB for the billing service
/design impact adding rate limiting to all public API endpoints

# Evaluate a pattern
/design pattern circuit breaker for external API calls
/design pattern saga pattern for distributed transactions
```

**What it does**:
1. Analyzes the current codebase state (dependencies, interfaces, patterns in use)
2. Researches external best practices and current-year documentation
3. Evaluates each option with weighted scoring against your project's constraints
4. Presents findings at interactive checkpoints for your validation
5. Produces a recommendation with clear rationale

**Writes to**: `docs/design/{YYYY-MM-DD_HHMM}_{topic}.md`
**Updates tracker**: Stage -> `Designing`
**Suggests next**: `/blueprint`

---

#### `/blueprint` — Implementation Specification

```
/blueprint {feature description}
```

Transforms design and research output into a concrete implementation specification — which files to create, which APIs to define, which tests to write — plus a ready-to-use prompt for `/plan` mode.

**Examples**:
```
/blueprint CSV migration with schema drift detection
/blueprint add real-time WebSocket notifications to the monitoring dashboard
/blueprint migrate authentication from session-based to JWT
/blueprint implement circuit breaker for external API calls
/blueprint add graceful shutdown to the background worker
```

**What it reads**: Design documents in `docs/design/` and research documents in `docs/research/` that are relevant to the feature.

**What it produces**:
- **Blueprint** in `docs/blueprints/` — file specs, API definitions, test specs, acceptance criteria
- **Implementation prompt** in `docs/prompts/` — ready for `/plan` mode

**Writes to**: `docs/blueprints/{YYYY-MM-DD_HHMM}_{name}.md` and `docs/prompts/{YYYY-MM-DD_HHMM}_{name}.md`
**Updates tracker**: Stage -> `Blueprint Ready`
**Suggests next**: `/plan` mode with the generated prompt

---

#### `/ux-design` — Frontend Design Quality

```
/ux-design [app-type|auto] [--refresh]
```

Generates an application-type-aware **Design Brief** with design tokens, typography, color, motion, layout, anti-patterns, accessibility requirements, and performance budgets. Eliminates "AI slop" — the generic Inter-font-purple-gradient aesthetic that LLMs default to — by providing concrete, opinionated design direction before implementation.

**Application Types** (auto-detected or specified):

| Type | Character | Key Signal |
|------|-----------|-----------|
| `saas-dashboard` | Data-dense, professional, dark mode | React + charting library |
| `landing-page` | Hero-driven, bold, conversion-focused | Next.js/Astro, < 10 routes |
| `ecommerce` | Product-focused, trust signals, fast | Stripe/Shopify in dependencies |
| `mobile-app` | Touch-first, native-feel, spring physics | React Native/Flutter/Expo |
| `admin-panel` | Dense, functional, keyboard-navigable | react-admin, /admin routes |
| `blog-content` | Readable, editorial, serif-forward | MDX/contentlayer, /blog routes |
| `developer-tool` | Monospace-heavy, dark-first, terminal | CLI frameworks, /bin directory |

**How it works**:
1. Detects application type from `package.json`, route patterns, and component structure (or accepts explicit type)
2. Loads the matching design profile with typography, color, motion, and layout conventions
3. Scans for existing design system (CSS variables, Tailwind config, design tokens) — augments rather than replaces
4. Generates a Design Brief with concrete CSS custom properties, font choices, spacing scales, and anti-patterns
5. If `--refresh`: re-evaluates an existing brief against current recommendations

**What the Design Brief contains**:
- **Aesthetic Direction** — the visual personality (not generic, not safe)
- **Design Tokens** — CSS custom properties for colors, typography, spacing, borders
- **Typography Rules** — Google Font pairings, scale, weights (never Inter, never Roboto)
- **Color System** — palette with contrast ratios, semantic colors, dark/light variants
- **Motion Guidelines** — transitions, easing, reduced-motion support
- **Layout Conventions** — grid, spacing, breakpoints, key patterns
- **Anti-Patterns** — what NOT to do (purple gradients, emoji icons, missing focus states, etc.)
- **Accessibility** — WCAG 2.1 AA, contrast, focus, semantic HTML
- **Performance Budgets** — font count, CSS size, LCP/CLS targets

**Works with existing design systems**: If your project already has Tailwind, CSS variables, or design tokens, `/ux-design` reads them and aligns the brief with your existing choices. It flags conflicts ("Your Tailwind config uses Inter — consider alternatives") without overwriting anything.

**Examples**:
```
/ux-design auto                    # Auto-detect app type, generate brief
/ux-design saas-dashboard          # Use SaaS Dashboard profile directly
/ux-design landing-page            # Use Landing Page profile
/ux-design --refresh               # Re-evaluate existing brief
```

**Writes to**: `docs/design-briefs/{YYYY-MM-DD_HHMM}_{project}.md`
**Suggests next**: `/wrought-implement` (design context loaded automatically in a future phase)

---

### Strategic Skills

These skills handle system-level analysis and proactive discovery. They feed findings into both the reactive and proactive pipelines.

#### `/analyze` — Systems Analysis

```
/analyze {mode} [scope]
```

Strategic-level system analysis that goes beyond reactive incident response. Discovers what exists in your codebase, assesses it against engineering standards, and surfaces issues proactively.

**Six modes**:

| Mode | Command | What It Produces |
|------|---------|-----------------|
| **health** | `/analyze health` | Full system health assessment — reliability, performance, maintainability, observability scores |
| **risk** | `/analyze risk [scope]` | Risk assessment with scoring matrix and prioritized mitigations |
| **patterns** | `/analyze patterns [time-period]` | Pattern recognition across incidents, code, and logs (default: last 7 days) |
| **component** | `/analyze component [scope]` | Deep dive into a specific component's health and architecture |
| **architecture** | `/analyze architecture` | Full architectural review with documentation sync |
| **discover** | `/analyze discover` | Build or refresh the System Map only (no assessment) |

**Examples**:
```
# Assess overall health
/analyze health

# Evaluate risk in a specific area
/analyze risk payment processing
/analyze risk authentication layer

# Find recurring patterns
/analyze patterns last-30-days
/analyze patterns

# Deep dive into one component
/analyze component extraction pipeline
/analyze component API gateway

# Full architectural review
/analyze architecture

# Just build the system map
/analyze discover
```

**The System Map**: Before any analysis, `/analyze` checks for (or creates) a System Map at `docs/analysis/system-map.md`. This persistent artifact maps your codebase — components, dependencies, entry points, error handling patterns — and is refreshed when stale (>24 hours old). The map is reused across analysis runs, so subsequent analyses are faster and more consistent.

**When it finds something**: The analysis modes surface issues and offer to route them:
- Defect or vulnerability found? Suggests `/finding` to log it, then `/investigate` + `/rca-bugfix`
- Gap or debt discovered? Suggests `/finding` to log it, then `/design` + `/blueprint`

**Writes to**: `docs/analysis/{YYYY-MM-DD_HHMM}_{name}.md` and `docs/analysis/system-map.md`
**Suggests next**: `/finding` (for issues), `/design` (for design escalation), or nothing (if healthy)

---

#### `/finding` — Proactive Discovery Logging

```
/finding {description of what was found}
```

Logs a proactive discovery — something found through analysis, review, or inspection that needs attention. Creates a factual record of WHAT was found and routes it to the appropriate pipeline. Does NOT fix anything — that's for downstream skills.

**Examples**:
```
# From your own observation
/finding Missing companyId filter in invoice WHERE clauses -- authorization gap
/finding Deprecated bcrypt v2.1 in auth service -- known CVE
/finding Config drift: staging has debug logging enabled in production

# From an analysis report (batch processing)
/finding docs/analysis/2026-02-02_1530_extraction_systems_analysis.md
```

**Classification taxonomy**:

| Type | Description | Routes To |
|------|-------------|-----------|
| **Defect** | Known bug found proactively (not via incident) | `/investigate` then `/rca-bugfix` |
| **Vulnerability** | Security issue with known exposure | `/investigate` then `/rca-bugfix` |
| **Debt** | Technical debt requiring remediation | `/design` then `/blueprint` |
| **Gap** | Missing expected capability or coverage | `/design` then `/blueprint` |
| **Drift** | Configuration or code divergence from intent | Either branch, depending on scope |

**Severity levels**: **Critical** > **High** > **Medium** > **Low**

**What it produces**:
- Individual finding reports in `docs/findings/`
- A [Findings Tracker](#the-findings-tracker) (auto-created or auto-updated)
- Auto-generated resolution tasks based on finding type

**Writes to**: `docs/findings/{YYYY-MM-DD_HHMM}_{name}.md` and `docs/findings/{datetime}_{scope}_FINDINGS_TRACKER.md`
**Suggests next**: `/investigate` (for defects/vulnerabilities) or `/design` (for debt/gaps/drift)

---

### Onboarding Skills

These skills run at project setup time to establish baseline context for all other pipelines.

#### `/safeguard` — Environment Profile Classification

```
/safeguard {mode}
```

Classifies a project's deployment environment maturity and paradigm. Scans the codebase for 12 deployment indicators — Docker, CI/CD, SIGTERM handling, environment count, process managers, health endpoints, rollback mechanisms, and approval workflows — then produces a profile document consumed by all downstream skills.

**Three modes**:

| Mode | Command | What It Does | Requires Existing Profile |
|------|---------|-------------|:---:|
| **detect** | `/safeguard detect` | Full environment profiling from scratch | No |
| **check** | `/safeguard check` | Re-validate existing profile against current state | Yes |
| **recommend** | `/safeguard recommend` | Generate prioritized improvement guidance | Yes |

**Profile levels** (cumulative — each includes all requirements of the level below):

| Profile | Name | What It Means |
|---------|------|---------------|
| **Zero** | DEV-Only | Single environment, no deployment pipeline, development-stage project |
| **A** | Minimal SDLC | DEV + PROD, Docker or process manager for deployment, limited CI/CD |
| **B** | Typical SDLC | DEV + TEST + PROD, CI/CD pipeline, deployment scripts with safety gates |
| **C** | Strong SDLC | Full CI/CD with required checks, branch protection, audit trails, automated rollback |

**Deployment paradigms**:

| Paradigm | What It Means |
|----------|---------------|
| **Docker** | Application itself runs in containers (not just dependencies) |
| **Non-Docker** | Application runs via process manager, systemd, or direct execution |
| **Hybrid** | Some components containerized, some run directly |

**What detect mode does**:
1. Scans 12 indicators (Docker presence, environment count, CI/CD, pre-commit hooks, SIGTERM handling, grace periods, process managers, deployment scripts, long-lived work, health endpoints, rollback mechanisms, approval workflows)
2. Presents scan results and asks you to clarify ambiguities (e.g., "Is Docker for the app or just dependencies?")
3. Classifies profile and paradigm with justification
4. Asks you to confirm the classification
5. Writes a profile document with classification summary, gap analysis, and recommendations
6. Updates `.wrought` marker with safeguard fields
7. Optionally routes gaps to `/finding` for formal tracking

**What check mode does**: Re-scans the same 12 indicators and compares against the recorded profile. Reports drift — new indicators detected, indicators removed, or changes that may warrant reclassification.

**What recommend mode does**: Generates prioritized improvement recommendations based on the current profile and its gap analysis.

**Writes to**: `docs/analysis/{YYYY-MM-DD_HHMM}_environment_profile.md` and `docs/analysis/{YYYY-MM-DD_HHMM}_safeguard_recommendations.md`

See [Environment Profiling](#environment-profiling) for a detailed walkthrough.

---

### Code Quality Skills

#### `/forge-review`

**Trigger**: `/forge-review [--scope=diff|full] [file or directory]`

Deep multi-agent code review that orchestrates 4 specialized subagents in parallel. Each subagent analyzes a different dimension of code quality:

1. **Complexity Analyst** — Algorithmic time/space complexity (Big O), hot paths, cross-function complexity chains
2. **DS&A Reviewer** — Data structure selection vs access patterns, algorithm choice for the problem domain
3. **Paradigm Enforcer** — FP/OOP paradigm consistency within files and modules
4. **Efficiency Sentinel** — Performance anti-patterns: unnecessary iterations, missed concurrency, memory waste, N+1 queries

Results are aggregated into a tiered report (Critical/Warning/Suggestion) with deduplication across agents.

**Flags**:
- `--scope=diff` (default) — Review only changed files
- `--scope=full` — Review all project source files

**Examples**:
```
/forge-review                              # Review changed files
/forge-review --scope=full                 # Review entire codebase
/forge-review --scope=full src/wrought/    # Review all files in src/wrought/
/forge-review src/wrought/cli/main.py      # Review specific changed file
```

**Writes to**: `docs/reviews/{YYYY-MM-DD_HHMM}_{scope}.md`

**Lifecycle integration**: When invoked after `/wrought-implement` or `/wrought-rca-fix`, automatically updates the Findings Tracker (stage → Reviewed → Resolved) and clears the `review_pending` flag.

**Suggests**: `/finding` (for critical/warning findings), `/simplify` (for auto-fixable suggestions)

---

### Greenfield Onboarding

#### `/genesis`

**Trigger**: `/genesis [--brownfield] <project description>`

Structured 3-phase project bootstrapping wizard that takes you from "I have an idea" to complete project documentation. Supports two modes:

- **Greenfield** (default): Interactive 5-question discovery interview
- **Brownfield** (`--brownfield`): Analyzes your existing codebase instead of interviewing

**Phases**:

| Phase | What It Does | Artifact Produced |
|-------|-------------|-------------------|
| **1. Discovery** | Captures problem domain, users, scope, tech preferences, deployment, timeline (greenfield) or analyzes existing codebase (brownfield) | `docs/genesis/{project}_discovery.md` |
| **2. Business Analysis** | Synthesizes discovery into personas, user stories with ACs, MoSCoW prioritization, NFRs | `PRD.md` |
| **3. Systems Analysis** | Designs tech stack, component architecture, data model, deployment, security | `ARCHITECTURE.md` |

**Cross-session resumption**: A state file (`docs/genesis/{project}_progress.json`) tracks phase completion. If you stop mid-way, running `/genesis` again resumes from where you left off.

**Examples**:
```
/genesis Acme Banking API — REST API for banking data aggregation
/genesis --brownfield existing-saas-app
```

**Writes to**: `docs/genesis/{project}_discovery.md`, `PRD.md`, `ARCHITECTURE.md`

**Suggests**: `/safeguard detect` (profile your deployment environment, then start building with the Wrought pipeline)

---

## Real-World Scenarios

### Scenario 1: Your API starts throwing errors at 2am

You wake up to alerts. Something's wrong with the payment service.

**Step 1** — Document what you see:
```
/incident Payment API returning 500 errors since 02:15 UTC, affecting checkout flow
```
Wrought creates `docs/incidents/2026-02-10_0230_payment_api_500_errors.md` with a structured incident report. No guessing the format — it's standardized.

**Step 2** — Dig into the cause:
```
/investigate docs/incidents/2026-02-10_0230_payment_api_500_errors.md
```
The investigation skill reads your incident report, examines the codebase, checks related past incidents, and produces a detailed investigation with hypotheses and evidence.

**Step 3** — Fix it:
```
/rca-bugfix Connection pool exhaustion causing payment API timeouts
```
Root cause analysis plus a fix prompt. The RCA goes into `docs/RCAs/` (your project's permanent knowledge base), and a ready-to-implement prompt goes into `docs/prompts/`.

**Step 4** — Implement:
Enter `/plan` mode with the generated prompt. Code the fix with full context.

**What you end up with**: An incident record, investigation, RCA, and fix — all linked, all searchable, all available for the next engineer (or AI session) that encounters a similar problem.

---

### Scenario 2: Adding WebSocket support to your application

You need real-time updates. Time to evaluate your options.

**Step 1** — Research the landscape:
```
/research WebSocket vs SSE vs long-polling for real-time order status updates
```
Wrought produces a research document covering each approach, with trade-offs specific to your codebase.

**Step 2** — Make the architectural decision:
```
/design tradeoff real-time communication for order status
```
The design skill reads your research, evaluates each option against your project's constraints, and produces a recommendation with clear rationale.

**Step 3** — Spec the implementation:
```
/blueprint WebSocket integration for order status updates
```
Turns the chosen design into a concrete implementation spec: which files to create, which APIs to define, which tests to write. Also generates a prompt for plan mode.

**Step 4** — Build it:
Enter `/plan` mode. The blueprint gives your AI assistant everything it needs to implement the feature correctly.

---

### Scenario 3: Your analysis reveals a hidden problem

You run a system health check and something looks off.

**Step 1** — Analyze the system:
```
/analyze health
```
The analysis runs across your codebase and operational history, scoring reliability, performance, maintainability, and observability.

**Step 2** — The analysis flags a concern. Log it as a finding:
```
/finding Stale detection reads DB but extraction writes to filesystem — state desynchronization
```
Wrought classifies it (Defect, High severity), writes a finding report, and **automatically creates a Findings Tracker** to track resolution across sessions.

**Step 3** — The finding skill tells you what to do next:
```
This is a corrective fix candidate. Recommended next steps:
1. /investigate stale detection state desynchronization
2. /rca-bugfix stale detection state desynchronization
```

**Step 4** — Investigate. You can invoke the next skill two ways:

```
# Option A: Pass the artifact path (explicit — the skill reads it directly)
/investigate docs/findings/2026-02-10_0800_state_desynchronization.md

# Option B: Reference the finding number (tracker-aware — the skill looks up F1 in the tracker)
/investigate F1
```

Both work. Option A is explicit: the skill reads the file you point it to. Option B uses the lifecycle tracking protocol: the skill searches `docs/findings/*_FINDINGS_TRACKER.md` for F1, finds the linked finding report and any prior artifacts, and uses all of them as context.

The investigation produces a report in `docs/investigations/`. The tracker is automatically updated: F1 Stage -> `Investigating`.

**Step 5** — Fix it. Same pattern — pass the investigation report or reference the finding:

```
# Option A: Pass the investigation report
/rca-bugfix docs/investigations/2026-02-10_0830_state_desynchronization.md

# Option B: Reference the finding (skill finds the tracker, finding report, AND investigation)
/rca-bugfix F1
```

The RCA skill reads upstream artifacts in order: investigations first, then findings. When you pass `F1`, it resolves the full chain — tracker -> finding report -> investigation — and uses all of them as context for the root cause analysis.

**Step 6** — Plan and implement:
Enter `/plan` mode with the generated prompt. The tracker is updated at each step: `RCA Complete` -> `Planned` -> `Resolved` -> `Verified`.

---

### Scenario 4: Multiple findings from a single analysis

Your `/analyze` run on the extraction pipeline reveals four related issues — a critical defect, two high-severity gaps, and a medium-severity architectural concern.

```
/finding docs/analysis/2026-02-02_1530_extraction_systems_analysis.md
```

Wrought processes the analysis and produces:
- 4 individual finding reports in `docs/findings/`
- 1 named Findings Tracker: `docs/findings/2026-02-02_1600_extraction_pipeline_FINDINGS_TRACKER.md`

The tracker lists all four findings sorted by severity, with auto-generated resolution tasks for each one:

```
| # | Finding                    | Type   | Severity     | Status | Stage |
|---|----------------------------|--------|--------------|--------|-------|
| F1 | State desynchronization   | Defect | **Critical** | Open   | Open  |
| F3 | Download stall blind spot | Gap    | **High**     | Open   | Open  |
| F2 | No external termination   | Gap    | **High**     | Open   | Open  |
| F4 | Serial queue blocking     | Gap    | **Medium**   | Open   | Open  |
```

Over the next few sessions, you work through the findings. Every downstream skill automatically updates the tracker as it processes a finding. You invoke each skill with the F-number — the skill resolves the full artifact chain (tracker -> finding report -> investigation -> RCA) from that single identifier:

```
Session 1: /finding discovers F1, F2, F3, F4 → tracker created (all Stage: Open)

Session 2: /investigate F1
             → tracker: F1 Stage → Investigating, lifecycle row added
           /rca-bugfix F1
             → tracker: F1 Stage → RCA Complete, lifecycle row added

Session 3: /plan (with F1 prompt)
             → tracker: F1 Stage → Planned, lifecycle row added
           Implement fix
             → tracker: F1 Stage → Resolved

Session 4: Verify fix in production
             → tracker: F1 Stage → Verified
```

Each `/session-end` reconciles the tracker with reality — if an artifact exists but the tracker wasn't updated (e.g., the skill ran before lifecycle tracking was added), session-end backfills the missing stages.

---

### Scenario 5: Onboarding a new project with environment profiling

You just initialized Wrought in a new project and want to understand its deployment maturity before doing any engineering work.

**Step 1** — Profile the environment:
```
/safeguard detect
```

Wrought scans the codebase for Docker files, CI/CD configs, SIGTERM handlers, environment-specific configs, deployment scripts, process managers, health endpoints, and more. It presents its findings and asks you to clarify anything ambiguous:

```
"Based on the codebase scan, here's what I found:

Docker: docker-compose.yml with app + postgres + redis containers
Environments: .env.dev, .env.prod, .env.staging (3 environments)
CI/CD: GitHub Actions with lint, test, and deploy-to-staging steps

Before classifying, I need to clarify:
Is Docker used for the application itself, or just for dependencies?"
```

After your answers, it proposes a classification:

```
Profile: B (Typical SDLC)
Paradigm: Docker
Justification: 3 environments, Docker for the application, CI/CD with deployment steps
```

**Step 2** — The profile document is written with a full gap analysis:

```
| Requirement              | Required By | Current State          | Gap? |
|--------------------------|-------------|------------------------|------|
| SIGTERM handling         | All         | Not present            | YES  |
| Grace period config      | Profile A+  | stop_grace_period: 10s | No   |
| Health endpoints         | Profile A+  | /health exists         | No   |
| Rollback mechanisms      | Profile B+  | Not detected           | YES  |
```

**Step 3** — Wrought asks if you want to route the gaps:
```
"I found 2 gaps against Profile B requirements. The most significant:
No SIGTERM handling — application will terminate immediately on shutdown.

Should I route these to /finding to formally log them?"
```

If you say yes, the gaps become tracked findings with auto-generated resolution tasks, and the full audit pipeline takes over.

---

### Scenario 6: Deploying a fix overnight with watchdog monitoring

You've fixed a critical bug and want to monitor it overnight without staying awake.

**Step 1** — Deploy the fix and start watchdog:
```
/watchdog Monitor extraction after retry logic fix - watch for timeout errors and connection resets
```

Wrought generates a bash script that:
- Tails your application logs every 60 seconds
- Matches against patterns relevant to your fix
- Creates JSON incident files when errors are detected
- Sends Telegram alerts to your phone

**Step 2** — Go to sleep. The watchdog runs autonomously.

**Step 3** — Morning. Two scenarios:

*If all clear*:
```
Watchdog has been running for 8 hours. No errors detected.
Status: MONITORING | Last check: 07:02 UTC | Errors: 0
```

*If something went wrong*:
```
You have 2 Telegram alerts from 03:14 UTC.
Incident files created in /tmp/watchdog_abc123_incidents/
```

**Step 4** — Review and document:
```
/incident Extraction timeout errors at 03:14 UTC after retry logic deploy
```

The reactive pipeline picks up from there.

---

### Scenario 7: Migrating from monolith to microservices

A large architectural change that needs careful planning.

**Step 1** — Research the landscape:
```
/research microservices migration patterns for Python monoliths 2026
```

**Step 2** — Evaluate the migration approach:
```
/design migrate monolith to microservices for the billing domain
```

The design skill analyzes your current monolith structure, identifies service boundaries, evaluates migration strategies (strangler fig, branch by abstraction, parallel run), and recommends an approach with risk assessment.

**Step 3** — Spec the first phase:
```
/blueprint extract billing service from monolith — phase 1 API gateway
```

**Step 4** — Assess the impact:
```
/design impact extracting billing service from the shared database
```

What's the blast radius? Which other services depend on the billing tables? What queries need to be updated? The impact analysis answers these before you write a single line of code.

**Step 5** — Implement phase 1:
Enter `/plan` mode with the blueprint prompt. Each subsequent phase repeats steps 3-5.

---

## The Findings Tracker

When you log findings with `/finding`, Wrought automatically creates a **Findings Tracker** — a living document that tracks resolution progress across sessions.

### How It Works

1. You run `/finding` (directly, or as part of `/analyze`)
2. Wrought writes individual finding reports to `docs/findings/`
3. Wrought creates (or updates) a named tracker: `docs/findings/{datetime}_{name}_FINDINGS_TRACKER.md`

Each tracker is scoped to a **group of related findings**. If you analyze your authentication system and find three issues, those go into one tracker. If you later analyze your payment system and find two more, those get their own separate tracker. Multiple trackers coexist — one per problem domain.

### What's Inside a Tracker

- **Overview table** — All findings sorted by severity (Critical first), with status
- **Dependency map** — How findings relate to each other
- **Per-finding sections** — Summary, root cause, resolution tasks (auto-generated), status tracking
- **Changelog** — Every update logged with session number and date

### Resolution Tasks

Wrought auto-generates resolution tasks based on the finding type:

**For defects and vulnerabilities** (something's broken):
```
- [ ] F1.1: Confirm root cause and scope
- [ ] F1.2: Implement corrective fix
- [ ] F1.3: Verify fix
```

**For debt, gaps, and drift** (something needs designing):
```
- [ ] F1.1: Design approach (evaluate options)
- [ ] F1.2: Implement chosen approach
- [ ] F1.3: Verify implementation
```

When your finding reports contain specific code locations and root causes, the tasks are customized with those details.

### Lifecycle Tracking

Every finding is tracked from discovery through resolution. The tracker maintains two levels of granularity:

- **Status** (coarse, 4 values): `Open` -> `In Progress` -> `Resolved` -> `Verified`
- **Stage** (fine-grained, 7 values): tracks exactly where in the pipeline a finding sits

There are two stage progressions depending on the finding type:

**Corrective Route** (Defect / Vulnerability — something's broken):
```
Open → Investigating → RCA Complete → Planned → Implementing → Resolved → Verified
         /investigate    /rca-bugfix    /plan      (code work)   session-end  session-end
```

**Design Route** (Debt / Gap / Drift — something needs designing):
```
Open → Designing → Blueprint Ready → Planned → Implementing → Resolved → Verified
        /design      /blueprint       /plan      (code work)   session-end  session-end
```

Every downstream skill that processes a finding **automatically updates the tracker** — setting the Stage, appending a lifecycle row, checking the resolution task, and adding a changelog entry. You don't need to update the tracker manually.

Each finding's detail section includes a **Lifecycle table** that grows as the finding progresses:

```
| Stage          | Timestamp             | Session | Artifact                              |
|----------------|-----------------------|---------|---------------------------------------|
| Open           | 2026-02-02 16:00 UTC  | 119     | [Finding Report](docs/findings/...)   |
| Investigating  | 2026-02-03 09:00 UTC  | 120     | [Investigation](docs/investigations/) |
| RCA Complete   | 2026-02-03 11:00 UTC  | 120     | [RCA](docs/RCAs/) + [Prompt](docs/prompts/) |
| Planned        | 2026-02-03 14:00 UTC  | 120     | [Plan](docs/plans/...)                |
| Resolved       | 2026-02-04 10:00 UTC  | 121     | Commit abc123                         |
| Verified       | 2026-02-04 15:00 UTC  | 121     | Production validation                 |
```

### Cross-Session Persistence

The tracker integrates with Wrought's session management:

- **`/session-end`** checks all active trackers and updates any that had work done during the session — checking off completed tasks, updating statuses and stages, backfilling any missed lifecycle rows, and adding changelog entries.


### Naming Convention

Trackers are named by their scope:
```
docs/findings/2026-02-02_1639_iterable_extraction_pipeline_FINDINGS_TRACKER.md
docs/findings/2026-03-15_0900_auth_authorization_gaps_FINDINGS_TRACKER.md
docs/findings/2026-04-01_1400_api_rate_limiting_FINDINGS_TRACKER.md
```

---

## Environment Profiling

The `/safeguard` skill provides deployment environment classification — a one-time onboarding assessment that establishes baseline context for all Wrought skills.

### Why It Matters

Different projects need different recommendations. A development-stage CLI toolkit doesn't need rollback mechanisms. A production API serving millions of requests needs SIGTERM handling, health endpoints, and graceful shutdown. Wrought's environment profile captures these differences so downstream skills can tailor their output.

### The Detection Matrix

Wrought scans 12 indicators to classify your project:

| # | Indicator | What It Tells Wrought |
|---|-----------|----------------------|
| 1 | Docker presence | Docker vs Non-Docker paradigm |
| 2 | Environment count | How many environments exist (DEV, TEST, STAGING, PROD) |
| 3 | CI/CD presence | Continuous integration and deployment maturity |
| 4 | Pre-commit hooks | Local quality gates before code reaches CI |
| 5 | SIGTERM handling | Whether the application shuts down gracefully |
| 6 | Grace period config | Time allowed for graceful shutdown |
| 7 | Process manager | How the application is supervised in production |
| 8 | Deployment scripts | Existing deployment automation |
| 9 | Long-lived work | Background tasks that need graceful shutdown (Celery, APScheduler, etc.) |
| 10 | Health endpoints | Application health monitoring infrastructure |
| 11 | Rollback mechanisms | Ability to revert a bad deployment |
| 12 | Approval workflows | Code review and deployment gate processes |

### Profile Levels

Profiles are cumulative — each level includes all requirements of the level below:

**Profile Zero (DEV-Only)**: Single environment, no deployment pipeline. A project in development. Quality gates (pre-commit, CI) may exist but no deployment infrastructure.

**Profile A (Minimal SDLC)**: DEV + PROD. Docker or a process manager handles deployment. Limited or no CI/CD. The minimum for a project serving real users.

**Profile B (Typical SDLC)**: DEV + TEST + PROD. CI/CD pipeline exists. Deployment scripts include some safety gates. A test environment validates changes before production.

**Profile C (Strong SDLC)**: Full CI/CD with required checks. Branch protection and approval workflows. Multiple environments with promotion gates. Audit trails, signed releases, or automated rollback.

### How Downstream Skills Use It

When an environment profile exists, skills across all three pipelines can optionally read it:

- `/analyze` tailors its health scoring to your profile level — a Profile Zero project won't be penalized for missing rollback mechanisms
- `/design` factors your deployment paradigm into architectural recommendations
- `/rca-bugfix` includes profile-aware fix recommendations (e.g., "Add SIGTERM handler" for non-Docker deployments vs "Increase `stop_grace_period`" for Docker)
- `/finding` adjusts gap severity based on what your profile requires

Profile awareness is always **additive and optional** — every skill works identically without a profile.

### Staleness Detection

The `wrought status` command shows your profile age:

```
Safeguard:        Profile ZERO (non-docker) -- 0 days old
```

After 90 days, it suggests re-validation:

```
Safeguard:        Profile B (docker) -- 95 days old (consider re-running /safeguard check)
```

Run `/safeguard check` to re-scan and confirm your profile is still accurate, or `/safeguard detect` to reclassify from scratch.

---

## Session Management

Wrought includes three session commands that maintain continuity between AI coding sessions. No more "where were we?" — each session starts with full context and ends with a complete handoff.

### `/session-start`

Reads your project's `CLAUDE.md` and the latest session handoff document. Orients the AI assistant with:

- Full project context (architecture, conventions, active work)
- What happened in the last session
- Current priorities and next steps
- Active findings trackers and their status

Run this at the beginning of every AI session.

### `/session-end`

Creates all handoff documentation for the next session:

1. Saves any active plan files
2. Creates a new `NEXT_SESSION_PROMPT_{datetime}.md` with current status and priorities
3. Creates a `SESSION_SUMMARY_{datetime}.md` documenting what was accomplished
4. Updates `CLAUDE.md` to point to the new handoff
5. Archives old handoff documents to `docs/archive/sessions/`
6. Updates any Findings Trackers that had work done during the session

Run this at the end of every AI session to preserve context.

### Session Workflow

A typical working day with Wrought:

```
1. Start a new AI session
2. /session-start                  # Load context, see priorities
3. (do your engineering work)      # Use any Wrought skills as needed
4. /session-end                    # Create handoff docs
5. Close the session               # Context preserved for next time
```

---

## Autonomous Implementation Loop

Wrought includes an autonomous implementation system (internally called "Ralph Wiggum") that iterates on code changes until tests pass. Instead of manually running tests after each change, the loop runs a verifier command automatically when Claude attempts to stop — and blocks the exit if tests fail, forcing another iteration.

### How It Works

1. You finish the pipeline (`/finding` → `/design` → `/blueprint` → plan) and have an implementation plan or RCA report ready
2. You invoke `/wrought-implement` (for new features) or `/wrought-rca-fix` (for bug fixes)
3. The command initializes loop state at `.claude/wrought-loop-state.json` and begins implementation
4. When Claude attempts to stop, the **Stop hook** (`stop-hook.sh`) automatically runs the configured verifier command (e.g., `uv run pytest tests/ -q`)
5. If tests fail: Claude is blocked from exiting and receives the error output — it must fix and try again
6. If tests pass: the loop completes and Claude exits normally
7. Each iteration's verifier output is saved as a **capsule artifact** at `docs/capsules/{finding_id}/iter_N/run.log`

### Three Commands

#### `/wrought-implement` — Autonomous Implementation Loop

Start a loop for implementing a plan. Reads the most recent plan from `docs/plans/` (or a path you provide), initializes loop state, and begins step-by-step implementation with automatic test verification.

```
/wrought-implement                              # Uses most recent plan
/wrought-implement docs/plans/2026-03-01_my_plan.md   # Specific plan
```

#### `/wrought-rca-fix` — Autonomous Bugfix Loop

Start a loop for applying an RCA fix. Reads the most recent RCA from `docs/RCAs/` (or a path you provide), applies the fix, and verifies with automatic test verification.

```
/wrought-rca-fix                                # Uses most recent RCA
/wrought-rca-fix docs/RCAs/2026-03-01_my_rca.md       # Specific RCA
```

#### `/cancel-wrought-loop` — Cancel Active Loop

Stop the current implementation or RCA loop. Deactivates the loop state and reports iteration history.

```
/cancel-wrought-loop
```

### Configuration

The loop reads verifier settings from the `.wrought` marker file:

| Field | Default | Description |
|-------|---------|-------------|
| `verifier_type` | `none` | Verifier preset (`none` prompts for manual config) |
| `verifier_test_path` | `tests/` | Default test path |
| `verifier_max_loops` | `5` | Maximum iterations before budget exhaustion |
| `verifier_timeout` | `300` | Per-run timeout in seconds |

If `verifier_type` is `none`, the command will ask you to provide a verifier command (e.g., `uv run pytest tests/ -q`).

### Pipeline Enforcement Guard (PreToolUse Hook)

Wrought includes a **runtime enforcement mechanism** that mechanically prevents source file edits outside of an active implementation loop. This complements the CLAUDE.md enforcement rules with a hook that runs in the shell — the model cannot bypass it.

**How it works**: A `PreToolUse` hook fires before every `Edit` or `Write` tool call. It checks:

1. Is the target file a **pipeline artifact** (docs/, .claude/, root-level *.md, .gitignore)? If so, **allow** — these are created by pipeline skills and don't need loop protection.
2. Is there an **active loop** (`.claude/wrought-loop-state.json` with `active: true`)? If so, **allow** — the implementation loop is running as expected.
3. Otherwise, **deny** with: "No active implementation loop. Run `/wrought-implement` or `/wrought-rca-fix` first."

This means if your AI assistant tries to edit source code directly — skipping the pipeline — the edit is blocked at the tool level. It must invoke `/wrought-implement` or `/wrought-rca-fix` to start a loop first.

**Two-layer enforcement**:
- **Layer 1 (prompt)**: CLAUDE.md rules guide the model's behavior — "follow the pipeline, don't skip steps"
- **Layer 2 (runtime)**: PreToolUse hook mechanically blocks violations — model-agnostic, compaction-resistant, deterministic

The hook is installed automatically via the Wrought plugin or `wrought init`.

### Safety

- **`stop_hook_active`**: The Stop hook checks this flag to prevent infinite re-blocking — if Claude is already continuing from a previous block, the hook allows exit
- **`max_iterations`**: Hard budget limit prevents runaway loops; when reached, the loop deactivates and Claude exits
- **Context alert priority**: The context-alert hook runs before the Stop hook. If context usage exceeds 80%, context-alert blocks first — preserving context is more important than test verification
- **Pipeline guard allowlist**: Pipeline artifacts (docs/, .claude/, CLAUDE.md, root *.md, .gitignore) are always editable without a loop — skills that produce documentation are not blocked

### Example Walkthrough

```
# 1. Pipeline is complete — you have a plan
/wrought-implement

# 2. Command finds the plan, initializes loop state, starts implementing
# ... Claude implements changes ...

# 3. Claude tries to stop → Stop hook runs pytest
#    Tests fail → Claude is blocked with error output
#    "Verifier failed (iteration 1/5). Fix the failing tests..."

# 4. Claude fixes the failing tests, tries to stop again
#    Tests pass → Loop completes
#    "Implementation complete after 2 iterations.
#     Capsule artifacts at docs/capsules/my_finding/iter_0/ and iter_1/"
```

---

## Workflow Enforcement

Wrought enforces pipeline discipline through a workflow orchestration system. Skills have **prerequisite checks** that validate upstream artifacts exist before execution — preventing you from skipping pipeline steps.

### Commands

#### `wrought workflow status`

Show all active findings across all Findings Trackers, with their current stage and status.

```bash
wrought workflow status
```

Output:
```
Active findings (3):

  F1: State desynchronization
    Stage: RCA Complete | Status: In Progress | Severity: Critical
    Tracker: docs/findings/2026-02-02_extraction_pipeline_FINDINGS_TRACKER.md

  F2: No external termination signal
    Stage: Designing | Status: In Progress | Severity: High
    Tracker: docs/findings/2026-02-02_extraction_pipeline_FINDINGS_TRACKER.md

  F3: Download stall blind spot
    Stage: Open | Status: Open | Severity: High
    Tracker: docs/findings/2026-02-02_extraction_pipeline_FINDINGS_TRACKER.md
```

#### `wrought workflow check <skill>`

Validate prerequisites before invoking a skill. Exits 0 if prerequisites are met, exits 1 if blocked.

```bash
wrought workflow check blueprint
# OK: Prerequisites met: found files matching docs/design/*.md.

wrought workflow check rca-bugfix
# BLOCKED: Run /investigate first to create an investigation report.
```

### Prerequisite Map

| Skill | Requires | Mode |
|-------|----------|------|
| `/investigate` | Findings Tracker OR incident report | any |
| `/rca-bugfix` | Investigation report | all |
| `/design` | Findings Tracker | all |
| `/ux-design` | Findings Tracker | all |
| `/blueprint` | Design document | all |
| `/plan` | Blueprint AND implementation prompt | all |

Skills not listed here (e.g., `/incident`, `/finding`, `/analyze`, `/research`, `/safeguard`, `/watchdog`, `/forge-review`) are standalone and have no prerequisites.

---

## Artifact Index

Wrought maintains a searchable index of all artifacts in your `docs/` directory. The index enables quick lookup across incidents, findings, investigations, RCAs, designs, blueprints, research, and analysis reports.

### Commands

#### `wrought index build`

Rebuild the artifact index from all files in `docs/`. The index is stored at `docs/.artifact-index.json`.

```bash
wrought index build
# Index built: 235 artifacts indexed.
```

#### `wrought index search <query>`

Search across all indexed artifacts by keyword.

```bash
wrought index search "connection pool"
```

Output:
```
Results for "connection pool" (3 matches):

  investigation  2026-02-10  Payment API timeout investigation
               docs/investigations/2026-02-10_0300_payment_api_timeout.md

  rca            2026-02-10  Connection pool exhaustion RCA
               docs/RCAs/2026-02-10_0400_connection_pool_exhaustion.md

  finding        2026-02-10  Connection pool sizing gap
               docs/findings/2026-02-10_0800_connection_pool_sizing.md
```

---

## CLI Reference

The `wrought` CLI manages installation, updates, and development workflow. Zero external dependencies — stdlib only.

### Commands

#### `wrought init`

Initialize Wrought in the current project. Creates `.claude/` directory, copies skills and commands, writes `.wrought` marker with safeguard fields, and creates a `.wrought-manifest` to track installed files.

```bash
cd ~/Projects/my-app
wrought init
```

Output:
```
[1/5] Copying skills and commands
  Copied .claude/skills/
  Copied .claude/commands/

Wrought initialized in /Users/you/Projects/my-app

Next: Open Claude Code and run /session-start
```

#### `wrought update`

Pull the latest skills from GitHub.

```bash
wrought update
```

#### `wrought upgrade`

Pull the latest and check for new capabilities. If the `/safeguard` skill hasn't been run yet, it will suggest running it. If a profile exists, it shows the current classification.

```bash
wrought upgrade
```

Output (no profile):
```
Already up to date.

NEW: /safeguard skill available
Optional: Run /safeguard detect to classify your deployment environment
```

Output (with profile):
```
Already up to date.

Safeguard profile: Profile B (docker)
Consider running /safeguard check to re-validate your profile
```

##### `--refresh-stale`

Overwrite divergent `agents/`, `commands/`, and `hooks/` files with current source. User-asserted authority for legacy installs predating manifest-pin tracking (Wrought ≤ 0.1.x). Does **not** affect skills, `statusline.py`, or hook scripts.

```bash
# Preview candidates first
wrought doctor

# Then heal
wrought upgrade --refresh-stale
```

Scope is locked to `agents/`, `commands/`, `hooks/` because these content types accept byte-identity adoption (F2). Skills carry a deploy-time transformation (`disable-model-invocation: true → false`) that makes byte-identity to source impossible; the statusline and hook scripts are handled by independent migration paths.

Once an install has pins recorded (i.e. ran any `wrought upgrade` from Wrought 0.2+ once), drift detection runs automatically on every subsequent upgrade — the flag is only needed once per legacy install. See finding F4 in `docs/findings/2026-04-16_0719_upgrade_missing_agent_deployment_FINDINGS_TRACKER.md` for the design rationale.

#### `wrought status`

Show version, repository status, installation health, and safeguard profile.

```bash
wrought status
```

Output:
```
Wrought v1.0.0
Install: ~/.local/share/uv/tools/wrought
Clean (no uncommitted changes)

Current project: /Users/you/Projects/my-app
  Skills:   YES
  Commands: YES
  Safeguard:        Profile B (docker) -- 12 days old
```

#### `wrought diff`

Show uncommitted changes in the Wrought repo. Useful when you've improved a skill while working in a project.

```bash
wrought diff
```

#### `wrought commit -m "message"`

Stage and commit all changes in the Wrought repo.

```bash
wrought commit -m "Improve /finding skill with batch support"
```

#### `wrought push`

Push Wrought changes to GitHub. Every project using Wrought immediately picks up the change.

```bash
wrought push
```

#### `wrought uninstall`

Remove Wrought files and marker from the current project. Uses the `.wrought-manifest` to identify wrought-owned files. Does not affect the Wrought repo, other projects, or user-created files.

```bash
wrought uninstall
```

#### `wrought workflow status`

Show all active findings with their current stage and status. See [Workflow Enforcement](#workflow-enforcement) for details.

```bash
wrought workflow status
```

#### `wrought workflow check <skill>`

Validate prerequisites before invoking a skill. Exits 0 if OK, 1 if blocked.

```bash
wrought workflow check design
```

#### `wrought index build`

Rebuild the artifact index from `docs/`. See [Artifact Index](#artifact-index) for details.

```bash
wrought index build
```

#### `wrought index search <query>`

Search across all indexed artifacts by keyword.

```bash
wrought index search "timeout"
```

#### `wrought doctor`

Inspect Wrought install health. Per-repo (default) or cross-repo (`--all-repos`). Surfaces incomplete installs (BROKEN), content drift (WARNING), and opt-in opportunities (INFO).

```bash
# Per-repo (current directory)
wrought doctor

# Cross-repo (scan ~/Projects/ by default)
wrought doctor --all-repos

# Cross-repo with explicit base paths
wrought doctor --all-repos ~/Work ~/SideProjects

# JSON output for CI integration
wrought doctor --format=json

# Auto-fix BROKEN repos (re-runs `wrought upgrade` per repo)
wrought doctor --all-repos --fix-incomplete
```

Exit codes: `0` if all OK/INFO, `1` if any WARNING (content drift), `2` if any BROKEN (incomplete install).

### Contributing Changes Back

To contribute skill improvements back to the Wrought repo, edit the skills in the Wrought source directory and then push:

```bash
wrought diff               # See what changed in the wrought repo
wrought commit -m "Improve /finding skill with batch support"
wrought push               # Share with the team
```

Then run `wrought upgrade` in each project to refresh the copies.

---

## Under the Hood

### How Installation Works

Wrought installs via file copies. When you run `wrought init`, it creates:

```
your-project/.claude/
├── settings.json          <- Your project's config (untouched)
├── .wrought-manifest      <- Tracks wrought-owned files
├── skills/                <- Copied from wrought/skills/
│   ├── analyze/
│   ├── blueprint/
│   ├── design/
│   ├── finding/
│   ├── incident/
│   ├── investigate/
│   ├── rca-bugfix/
│   ├── research/
│   ├── safeguard/
│   └── watchdog/
└── commands/              <- Copied from wrought/commands/
    ├── session-start.md
    ├── session-end.md
    ├── finding.md
    ├── analyze.md
    ├── wrought-implement.md
    ├── wrought-rca-fix.md
    ├── cancel-wrought-loop.md
    └── ... (10 skill stubs)
```

Files are independent copies — edits in a project stay local and don't affect the Wrought source. Use `wrought upgrade` to refresh copies from the latest source.

### The `.wrought` Marker

Each initialized project gets a `.wrought` marker file:

```
format_version=1
version=1.0.0
install_path=~/.local/share/uv/tools/wrought
safeguard_version=1
safeguard_profile=B
safeguard_paradigm=docker
safeguard_last_run=2026-02-19T18:38:41Z
safeguard_created=2026-02-19T18:38:41Z
safeguard_override=none
github_owner=myorg
github_repo=my-app
github_project_number=none
github_project_id=none
verifier_type=none
verifier_test_path=tests/
verifier_max_loops=5
verifier_timeout=300
```

The CLI reads this marker for `wrought status`, `wrought upgrade`, and profile display. The `safeguard_*` fields track deployment environment classification. The `github_*` fields are auto-detected from Git remotes during `wrought init`. The `verifier_*` fields configure the [autonomous implementation loop](#autonomous-implementation-loop) — test command, iteration budget, and timeout. The `safeguard_override` field allows manual classification overrides when the automated detection doesn't match reality.

### Institutional Memory

Every skill writes to `docs/`. Over time, your project accumulates:

```
docs/
├── incidents/        # What broke and when
├── findings/         # What was discovered proactively (+ Findings Trackers)
├── investigations/   # Deep dives into problems
├── RCAs/             # Root cause analyses
├── research/         # Technology evaluations
├── design/           # Architectural decisions
├── blueprints/       # Implementation specs
├── analysis/         # System health assessments + environment profiles
├── prompts/          # Ready-to-use implementation prompts
├── plans/            # Implementation plans
├── reviews/          # Code review reports from /forge-review
├── capsules/         # Ralph Wiggum loop iteration artifacts
└── archive/
    └── sessions/     # Past session handoffs
```

This is your project's engineering logbook. Each document is written by one skill and read by downstream skills, creating a feedback loop. The more you use Wrought, the better it understands your project's history and patterns.

### Pipeline Data Flow

Skills communicate through shared documents, not APIs. Here's what each skill reads and writes:

| Artifact | Written By | Read By |
|----------|-----------|---------|
| `docs/incidents/*.md` | `/incident` | `/investigate`, `/analyze` |
| `docs/findings/*.md` | `/finding` | `/investigate`, `/analyze`, `/rca-bugfix`, `/research` |
| `docs/findings/*_FINDINGS_TRACKER.md` | `/finding` | `/investigate`, `/rca-bugfix`, `/design`, `/blueprint`, `/session-end` |
| `docs/investigations/*.md` | `/investigate` | `/rca-bugfix`, `/analyze` |
| `docs/RCAs/*.md` | `/rca-bugfix` | `/investigate`, `/analyze` |
| `docs/research/*.md` | `/research` | `/investigate`, `/design`, `/blueprint` |
| `docs/analysis/*.md` | `/analyze` | `/design`, `/investigate`, `/finding` |
| `docs/design/*.md` | `/design` | `/blueprint` |
| `docs/blueprints/*.md` | `/blueprint` | `/plan` mode |
| `docs/prompts/*.md` | `/rca-bugfix`, `/blueprint` | `/plan` mode |
| `docs/analysis/system-map.md` | `/analyze` | `/analyze` (refreshed each run) |
| `docs/analysis/*_environment_profile.md` | `/safeguard` | All pipeline skills (optional enrichment) |
| `docs/analysis/*_safeguard_recommendations.md` | `/safeguard` | (human consumption) |
| `docs/reviews/*.md` | `/forge-review` | `/finding`, `/simplify` |
| `docs/capsules/{finding_id}/iter_N/run.log` | `stop-hook.sh` | `/wrought-implement`, `/wrought-rca-fix` |
| `docs/capsules/{finding_id}/loop_summary.json` | `stop-hook.sh` | `/session-end`, (human consumption) |
| `.claude/wrought-loop-state.json` | `/wrought-implement`, `/wrought-rca-fix` | `stop-hook.sh`, `/cancel-wrought-loop` |

### Hooks

Wrought uses Claude Code hooks to enforce safety and enable autonomous loops:

| Hook | Event | What It Does |
|------|-------|-------------|
| `context-alert.py` | `stop` | Monitors context window usage. Warns at 70% (stderr), blocks at 80% (prevents context exhaustion) |
| `stop-hook.sh` | `stop` | Runs the verifier command when an [autonomous implementation loop](#autonomous-implementation-loop) is active. Blocks exit on test failure |

**Ordering**: Both hooks are registered on the `stop` event. `context-alert.py` runs first — if context usage exceeds 80%, it blocks before the Stop hook runs. This ensures context preservation takes priority over test verification.

---

## Finding Classification

The `/finding` skill classifies discoveries to determine the resolution path:

| Type | What It Means | Where It Goes |
|------|--------------|---------------|
| **Defect** | Code that doesn't work as intended | Fix Branch: `/investigate` then `/rca-bugfix` |
| **Vulnerability** | Security weakness with known exposure | Fix Branch: `/investigate` then `/rca-bugfix` |
| **Debt** | Technical debt that hurts maintainability | Design Branch: `/design` then `/blueprint` |
| **Gap** | A capability that should exist but doesn't | Design Branch: `/design` then `/blueprint` |
| **Drift** | Something diverged from its intended state | Either branch, depending on scope |

Severity levels: **Critical** > **High** > **Medium** > **Low**

---

## Project Conventions

See [CONVENTIONS.md](CONVENTIONS.md) for the full directory structure and file naming conventions that Wrought skills expect.

All Wrought artifacts use this naming format:
```
{YYYY-MM-DD_HHMM}_{description}.md
```

Examples:
```
2026-01-22_1700_stream_download_timeout.md
2026-02-19_1838_environment_profile.md
2026-02-02_1639_iterable_extraction_pipeline_FINDINGS_TRACKER.md
```

---

## Development

After adding new skills or commands to the source tree, reinstall the editable package so the CLI picks them up:

```bash
uv tool install --force -e .
```

Quick test in a scratch directory:

```bash
mkdir /tmp/test-project && cd /tmp/test-project
wrought init -n
```

Run the test suite:

```bash
uv run pytest tests/ -q
```

---

## Versioning & stability

Wrought's package version is **independent SemVer** — it tracks the CLI/package on its own clock, not the product-roadmap tier labels ("v1.0" the launch, "V1.x" the roadmap). Three version clocks run in parallel and do **not** need to match:

| Clock | Current | What it is |
|-------|---------|------------|
| Package SemVer (PyPI `wrought`) | `1.0.0` | The installed CLI + skills — this section's subject |
| Plugin channel (`wrought-plugin`) | `1.1.x` | The Claude Code plugin marketplace build, on its **own** clock |
| Marketing tier | "v1.0" | The free single-developer product line |

So `1.0.0 < 1.1.6` is **not** "the CLI is behind the plugin" — they are separate distribution channels with independent version histories.

**Major-on-break.** `1.0.0` is a standing SemVer commitment. The **next backward-incompatible change to a documented surface ships as a major bump (`2.0.0`)** — never smuggled inside a `1.x` minor or patch. Additive, backward-compatible changes stay in `1.x` indefinitely.

**What the stability promise covers** (SemVer applies to these):
- documented CLI subcommands, flags, and exit codes;
- the `.wrought` marker file format.

**What is explicitly *not* covered** (may change in a minor/patch without a major bump):
- experimental or unreleased skills;
- internal hook interfaces and private module layout;
- anything marked unstable in its own docs.

**On the number itself** — `1.0.0` is the first **stable** public release: the API is stable enough to depend on, justified by heavy dogfooding (Wrought builds Wrought). It is **not** a claim of completeness or adoption — the only real user so far is the author. If it breaks for you, that is the most useful thing you can report.

---

## License

MIT — see [LICENSE](LICENSE). **WROUGHT™** is a trademark of FluxForge AI (filed/pending — CIPC Class 9 + 42); the MIT licence covers the code, not the name. See [NOTICE](NOTICE).

### V1.0 vs WROUGHT Platform boundary

V1.0 (this repo — the single-developer Claude Code pipeline: skills, CLI, hooks, Findings Trackers) is **free and MIT, forever**. The planned **WROUGHT Platform** is a **separate paid hosted/team/multi-model product** — V1.0 is never feature-gated to sell it. Multi-platform support (Codex, etc.) is a deliberate WROUGHT Platform concern; V1.0 is Claude-Code-native by design.
