agentleFS
gustavo-meilusgustavo-meilus/superpipelines/llms-full.txt

superpipelines

llms.txt4 starsChanged 6 months agoMITView on GitHub

Multi-agent AI pipelines with guaranteed spec compliance, write/review isolation, and full crash recovery. Superpipelines enables complex task decomposition into coordinated subagents with automated verification and state persistence. Users achieve the following outcomes when utilizing Superpipelines: Superpipelines executes tasks through a structured lifecycle: The framework selects the optimal pattern based on task complexity: Install the Superpipelines plugin via Claude Code:

  • Reads credentials
  • Deletes or force-pushes
  • Commits and pushes

The file

Show its rules and text

We split this llms-full.txt into the rules it gives an agent

64 rules. About 0 are common, 34 are distinctive, and 30 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈34

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 30

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    Permission Granularity: Every agent declares a permissionMode (e.g., acceptEdits, plan).

    line 89
  2. Distinctive:

    Skill Descriptions: Use triggering conditions only.

    line 149
  3. Very specific:

    Scribius v1 Standardization: All 20+ core skills migrated to semantically anchored XML envelopes (<overview>, <protocol>, <invariants>, …

    line 217
  4. Very specific:

    Agent permissionMode now required: All agents declare permissionMode in frontmatter (acceptEdits for executors, plan for …

    line 235
  5. Very specific:

    Read and display the current topology.json as a numbered list of steps and dependency edges.

    line 394
  6. Very specific:

    Verify the staged topology.json for:

    line 406
  7. Very specific:

    Update the registry.json lists to include new components.

    line 419
  8. Distinctive:

    NEVER skip the delta audit.

    line 423
  9. Very specific:

    ALWAYS use a staging directory (edit-{ts}/) for artifact generation to prevent partial, unverified updates.

    line 424
  10. Distinctive:

    Large-Scale Requests: If the request describes multiple subsystems, decompose them into independent sub-projects before refining details.

    line 476
  11. Distinctive:

    Ask clarifying questions focused on purpose, constraints, and success criteria.

    line 479
  12. Very specific:

    Prefer multiple-choice options (A/B/C) for faster decision-making.

    line 481
  13. Distinctive:

    NEVER combine the "Visual Companion" offer with other questions.

    line 498
  14. Distinctive:

    NEVER skip the design gate for "simple" projects.

    line 499
  15. Distinctive:

    ALWAYS design for isolation, breaking systems into smaller units with well-defined interfaces.

    line 500
  16. Distinctive:

    Offering: If upcoming questions are visual (layouts, diagrams), offer the companion once in a standalone message.

    line 506
  17. Distinctive:

    Browser: Use for mockups, wireframes, and architecture diagrams.

    line 508
  18. Distinctive:

    Terminal: Use for requirements, conceptual choices, and tradeoff lists.

    line 509
  19. Distinctive:

    Goal: Ensure the environment supports the isolation requirements of the selected pattern.

    line 560
  20. Distinctive:

    Restriction: If git is absent, limit selection to Pattern 1 or 4.

    line 572
  21. Distinctive:

    Approval Required: Do NOT generate the entry skill until the user explicitly approves the design.

    line 583
  22. Very specific:

    All step agents and skills under <scope-root>/agents/superpipelines/{P}/ and <scope-root>/skills/superpipelines/{P}/

    line 593
  23. Very specific:

    NEVER hardcode paths; always resolve via sk-pipeline-paths.

    line 600
  24. Very specific:

    NEVER generate the entry skill before human approval of the tasks.md and topology.json.

    line 601
  25. Very specific:

    All internal step skills MUST be marked user-invocable: false.

    line 602
  26. Very specific:

    Update the registry.json to reflect the removal.

    line 678
  27. Very specific:

    NEVER assume a step is "unused" without verifying all depends_on entries in the topology graph.

    line 682
  28. Distinctive:

    ALWAYS perform atomic promotion from a staging area to ensure rollback capability.

    line 683
  29. Distinctive:

    NEVER delete a step that creates an unresolvable blocking-gap in the orchestration.

    line 684
  30. Very specific:

    Run the project's primary test suite (e.g., npm test, pytest).

    line 734
  31. Distinctive:

    NEVER proceed with integration if the verification gate fails.

    line 758
  32. Distinctive:

    NEVER cleanup the worktree for Option 3 (Keep as-is).

    line 759
  33. Distinctive:

    ALWAYS re-verify tests on the base branch after a local merge (Option 1).

    line 760
  34. Distinctive:

    ALWAYS obtain "discard" confirmation before executing Option 4.

    line 761
  35. Distinctive:

    Every agent body must declare its contract near the top:

    line 881
  36. Very specific:

    Fix: Every agent emits exactly one of DONE / DONE_WITH_CONCERNS / NEEDS_CONTEXT / BLOCKED with the agent's output schema.

    line 957
  37. Distinctive:

    Symptoms: Read-only reviewer agent has Write/Edit tools.

    line 979
  38. Very specific:

    Symptoms: Every agent has hooks: PreToolUse: matcher: Bash with allow-stamp.

    line 997
  39. Very specific:

    Fix: All pipeline state lives in <scope-root>/superpipelines/temp/{P}/{runId}/pipeline-state.json per STATE_MANAGEMENT: STRUCTURED_JSON.

    line 1005
  40. Very specific:

    Fix: All paths relative and start with ./.

    line 1029
  41. Very specific:

    Fix: Always fully qualified: ServerName:tool_name (e.g., BigQuery:bigquery_schema).

    line 1035
  42. Distinctive:

    Every spec AC maps to at least one task.

    line 1160
  43. Distinctive:

    Use exactly this phrasing for the Phase 4b gate (don't paraphrase — the wording is calibrated to elicit a clean APPROVE/REVISE response):

    line 1164
  44. Distinctive:

    Wait for APPROVE. If REVISE arrives, route back per the 4D feedback table:

    line 1173
  45. Distinctive:

    Always emit the executive summary even when no findings — record the audit happened.

    line 1332
  46. Very specific:

    Read each target file with Read.

    line 1407
  47. Very specific:

    Action: Add permissionMode based on the agent's role.

    line 1464
  48. Very specific:

    Wait: If the agent needs to persist pipeline-specific state, use sk-pipeline-state to write to pipeline-state.json instead of relying on …

    line 1489
  49. Distinctive:

    Action: Add near top of agent body:

    line 1548
  50. Very specific:

    Action: Remove the hooks block from agent frontmatter when plugin settings.json already has Bash(*) in permissions.allow.

    line 1558
  51. Distinctive:

    No output contract declared.

    line 1592
  52. Distinctive:

    No automated success criteria for agent self-verification.

    line 1602
  53. Very specific:

    Every entry in S.depends_on must reference a valid id in the same steps array.

    line 1700
  54. Very specific:

    Every step must be reachable via depends_on chains from at least one entry point (no orphan steps).

    line 1701
  55. Distinctive:

    When input/output schemas are declared as structured objects (not bare strings), the producer's declared output type must match the …

    line 1702
  56. Distinctive:

    Check via topological sort.

    line 1711
  57. Very specific:

    NEVER ignore a non-DONE status.

    line 1897
  58. Very specific:

    When and how running-a-pipeline escalates to a human.

    line 1904
  59. Very specific:

    When a worker reports BLOCKED, the orchestrator follows a 4-step ladder:

    line 1971
  60. Distinctive:

    After step 4 escalation, surface to user with the full attempt history.

    line 1991
  61. Distinctive:

    If Pattern 3 escalates and the user wants to continue manually but with safety:

    line 2009
  62. Distinctive:

    EVERY state update follows the write-temp-then-rename pattern:

    line 2096
  63. Distinctive:

    When user accepts "resume" prompt for crashed state:

    line 2123
  64. Very specific:

    If phases[i] had partial outputs that survived, prefer to keep them.

    line 2128

≈ “Common” is an estimate: at least 1 in 5 of the 3,727 llms.txt files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
llms-full.txt
# Superpipelines — Full Documentation Suite

# File: README.md
----------------------------------------
# Superpipelines — Multi-Agent Orchestration Framework

> Multi-agent AI pipelines with guaranteed spec compliance, write/review isolation, and full crash recovery. Superpipelines enables complex task decomposition into coordinated subagents with automated verification and state persistence.

<overview>
Superpipelines provides a framework for decomposing complex tasks into coordinated subagents. It enforces engineering best practices through separate author and reviewer roles, explicit handoffs, and mandatory human gates for high-stakes transitions. The system ensures that every output matches its specification before merging, reducing model hallucinations and providing a robust path for crash recovery.
</overview>

<glossary>
  <term name="pipeline">A coordinated sequence of agent-driven tasks that transform a high-level goal into a verified implementation.</term>
  <term name="write/review isolation">The structural separation of implementation and verification, where the reviewer agent lacks modification permissions.</term>
  <term name="hard gate">A mandatory pause in execution requiring explicit human approval to proceed.</term>
</glossary>

## Capabilities

Users achieve the following outcomes when utilizing Superpipelines:

- **Deconstruction**: Tasks are decomposed into a precise specification, implementation plan, and itemized task list before execution.
- **Structural Review**: Dedicated reviewer agents validate every task against the specification before commitment.
- **State Persistence**: Pipeline state persists to scope-aware temporary directories, allowing for crash recovery and session resumption.
- **Escalation Guards**: Hard-coded iteration caps and human gates prevent model rationalization and infinite loops.

## Execution Workflow

Superpipelines executes tasks through a structured lifecycle:

<workflow>
1. **DECONSTRUCT**: The system identifies gaps, ambiguities, and constraints through targeted intake.
2. **DIAGNOSE**: Environmental and architectural constraints are surfaced before code generation.
3. **DEVELOP**: The `pipeline-architect` generates the `spec.md`, `plan.md`, and `tasks.md`.
4. **HARD GATE**: Execution pauses for human review and approval of the specification.
5. **IMPLEMENT**: Worker agents execute tasks in isolated git worktrees.
6. **STAGE 1**: `pipeline-spec-reviewer` validates output against the specification.
7. **STAGE 2**: `pipeline-quality-reviewer` performs a code quality audit (only after Stage 1 passes).
8. **COMMIT**: Passing tasks merge to the integration branch.
9. **DONE**: Temporary state is cleaned and a completion summary is surfaced.
</workflow>

<invariant>
Reviewer agents operate with `disallowedTools: Write, Edit, Bash`, ensuring they cannot modify the code they are tasked with validating.
</invariant>

## Execution Patterns

The framework selects the optimal pattern based on task complexity:

<pattern_matrix>
| Pattern | Shape | Use Case |
| :--- | :--- | :--- |
| **1 — Sequential** | A → B → C | Ordered phases with hard data dependencies. |
| **2 — Parallel Fan-Out** | A → [B, C, D] → Merger | Independent branches that merge upon completion. |
| **3 — Iterative Loop** | Implement → Test → Fix | Test-driven repair with a hard escalation cap of 3 iterations. |
| **4 — Human-Gated** | Agent → Gate → Agent | High-stakes stages requiring manual approval. |
| **5 — Spec-Driven Dev** | Spec → Tasks → 2-Stage Review | Full SDD with worktrees per task. |
| **6 — 4D Wrapper** | 4D Intake → Pattern | Wraps any pattern with structured deconstruction. |
</pattern_matrix>

## Installation

Install the Superpipelines plugin via Claude Code:

<installation>
```bash
// Installation command
claude plugin install github:gustavo-meilus/superpipelines
```
</installation>

## Slash Commands

| Command | Function |
| :--- | :--- |
| `/superpipelines:new-pipeline` | Initiates 4D intake and generates pipeline artifacts. |
| `/superpipelines:run-pipeline` | Orchestrates an existing pipeline end-to-end. |
| `/superpipelines:new-step` | Adds a new step to an existing named pipeline. |
| `/superpipelines:update-step` | Modifies an existing step within a named pipeline. |
| `/superpipelines:delete-step` | Removes a step from a named pipeline with gap analysis. |
| `/superpipelines:audit-pipeline` | Audits agents and skills against the v2 compliance matrix. |

## Design Principles

- **Structural Isolation**: Permission boundaries are enforced at the agent definition level. Reviewers cannot rationalize their way into "fixing" code; they can only fail it.
- **Scope-Aware State**: Pipeline state persists to `<scope-root>/superpipelines/temp/{P}/{runId}/pipeline-state.json`. Resumption resets in-progress phases while preserving completed work.
- **Permission Granularity**: Every agent declares a `permissionMode` (e.g., `acceptEdits`, `plan`). Bypassing permissions requires explicit, documented justification.
- **Progressive Disclosure**: High-density reference documentation resides in companion `*-references/` directories and is loaded on demand to minimize context bloat.

## Repository Layout

<file_structure>
```
superpipelines/
├── .claude-plugin/           # Plugin manifest and marketplace data
├── agents/                   # Core agent definitions (Architect, Auditor, Executor, Reviewers)
├── skills/                   # Shared skills (State, Paths, Patterns, Worktree Safety)
│   ├── *-references/         # Deep reference libraries (On-demand loading)
├── commands/                 # Slash command wrappers
├── hooks/                    # SessionStart hooks for bootstrap injection
└── settings.json             # Global plugin configuration
```
</file_structure>

## Contributing

Contributions are managed via issues and PRs at [gustavo-meilus/superpipelines](https://github.com/gustavo-meilus/superpipelines). Use `/superpipelines:audit-pipeline` to validate additions against the compliance matrix before submission.

## License

MIT — See [LICENSE](./LICENSE).


# File: CLAUDE.md
----------------------------------------
# Superpipelines — Architecture and Authoring Reference

> Canonical project reference for the Superpipelines Claude Code plugin. This document defines the architectural invariants, file layout rules, and authoring constraints required to maintain system integrity and LLM readability.

<overview>
Superpipelines implements a multi-agent orchestration framework where architecture is enforced through structural isolation and strict authoring rules. This reference serves as the ground truth for developers and agents operating within the repository.
</overview>

## Architecture Invariants

<architecture_invariants>
- `SUB_AGENT_SPAWNING: FALSE` — Subagents never spawn children; orchestration resides in top-level skills or the parent session.
- `WRITE_REVIEW_ISOLATION: TRUE` — The agent generating code is structurally barred from reviewing it.
- `MODEL_SELECTION: DYNAMIC_DEFAULT_SONNET` — Pipeline execution agents default to `claude-sonnet-4-6`. Planning and utility agents may utilize category-based dynamic routing (e.g., `deep-plan`, `quick-audit`).
- `PERMISSION_MODE: PER_AGENT` — Agents declare explicit permission boundaries (e.g., `acceptEdits`, `plan`) in frontmatter.
- `STATE_MANAGEMENT: STRUCTURED_JSON` — State persists to `<scope-root>/superpipelines/temp/{P}/{runId}/pipeline-state.json`.
- `MULTI_PIPELINE: TRUE` — Multiple named pipelines coexist in isolation per workspace.
</architecture_invariants>

## File-Layout Rules

<file_rules>
- **Manifests**: `.claude-plugin/plugin.json` and `.claude-plugin/marketplace.json` are the only permitted files in the plugin directory.
- **Source Roots**: `agents/`, `skills/`, `commands/`, and `hooks/` reside at the repository root.
- **Generated Artifacts**: Artifacts live under scope-dependent roots (`project`, `local`, or `user`) as resolved by `sk-pipeline-paths`.
- **Reference Skills**: Companion reference skills (`*-references/`) omit `SKILL.md` to prevent preloading into system context.
</file_rules>

## Authoring Rules

<authoring_rules>
- **Skill Descriptions**: Use triggering conditions only; avoid workflow summaries.
- **Voice**: Enforce third-person impersonal voice throughout all documentation and skills.
- **Constraints**: Skill bodies ≤500 lines; agent bodies ≤150 lines; every skill description ≤1024 characters.
- **Reference Topology**: References >100 lines must include a Table of Contents.
- **Status Reporting**: Agents must emit exactly one terminal status: `DONE`, `DONE_WITH_CONCERNS`, `NEEDS_CONTEXT`, or `BLOCKED`.
</authoring_rules>

<glossary>
  <term name="Sonnet 4.6">The canonical model ID: `claude-sonnet-4-6`.</term>
  <term name="Scope Root">The base directory for generated artifacts, variable by project configuration.</term>
</glossary>

## Metadata

- **Current Model IDs**: `claude-sonnet-4-6`, `claude-opus-4-7`, `claude-haiku-4-5-20251001`.
- **Project Version**: v1.0.4


# File: RELEASE-NOTES.md
----------------------------------------
# Superpipelines — Release Notes

> Canonical record of versioned changes, feature additions, and removals for the Superpipelines framework. This document serves as the primary reference for tracking migration paths and architectural evolution.

<overview>
Superpipelines release notes document the transition from legacy Superpowers-era infrastructure to the standalone v1.0.x architecture. Key milestones include the implementation of scope-aware deployment, multi-pipeline isolation, and the 20-criterion compliance matrix.
</overview>

## v1.0.4 — OMOA Integration & Hierarchical Context (2026-05-05)

This release integrates three major architectural enhancements inspired by the Oh My OpenAgent ecosystem, dramatically improving edit stability, context efficiency, and cost-to-performance ratios for specific agents.

<release_entry version="1.0.4" status="STABLE">

### Added
- **Hashline Protocol**: Added `sk-hashline-protocol` skill and updated the `pipeline-task-executor` to enforce hash-anchored code modifications, preventing source code corruption from stale line edits.
- **Hierarchical Context Command**: Added the `/superpipelines:init-deep` command and `sk-hierarchical-context` skill to map repository architecture into distributed `PIPELINE-CONTEXT.md` files, ensuring agents access lean, localized context without bloating global prompts.
- **Scribius Formatting Enforcement**: Enforced strict Scribius v1 standards (H1-first, XML-anchored structured envelopes, third-person voice) on all generated `PIPELINE-CONTEXT.md` files.
- **Dynamic Intent Routing**: Added `sk-dynamic-routing` to permit intent-based LLM selection. `pipeline-architect` now defaults to `claude-opus-4-7` (`deep-plan` category) and `pipeline-quality-reviewer` routes to `claude-haiku-4-5-20251001` (`quick-audit` category), while standard implementation workers remain bound to `claude-sonnet-4-6`.

### Changed
- **Architecture Invariant Updated**: `MODEL_SELECTION: SONNET_ONLY` updated to `MODEL_SELECTION: DYNAMIC_DEFAULT_SONNET` to support category-based routing.
- **New Pipeline Preflight**: The `/superpipelines:new-pipeline` command now explicitly checks for a root context map and suggests `/superpipelines:init-deep` during the preflight phase.

</release_entry>

## v1.0.3 — Adherence Cleanup (2026-05-04)

This release ensures 100% adherence to the framework's core architectural standards. It resolves cosmetic and structural issues identified during a comprehensive audit, including stale marketplace metadata, corrupted agent definitions, and structural inconsistencies in the release history.

<release_entry version="1.0.3" status="STABLE">

### Added
- **Adherence Audit Verified**: Confirmed 100% compliance with all 16 core architectural requirements (Git preflight, multi-pipeline isolation, scope-aware pathing, temp lifecycle).

### Improved
- **Marketplace Metadata**: Synchronized marketplace description with canonical plugin capabilities, removing stale documentation references.
- **Structural Integrity**: Resolved file corruption in `skill-architect.md` and consolidated duplicate history headers in `RELEASE-NOTES.md`.

</release_entry>

## v1.0.2 — Scribius v1 & Standardized Architecture (2026-05-04)

This release implements a repository-wide refactoring to the Scribius v1 documentation standard and finalizes the v2 scope-aware architecture. It introduces semantically anchored XML envelopes for machine-readability and master manifests for high-performance context retrieval.

<release_entry version="1.0.2" status="STABLE">

### Added
- **Scribius v1 Standardization**: All 20+ core skills migrated to semantically anchored XML envelopes (`<overview>`, `<protocol>`, `<invariants>`, `<rationalization_table>`).
- **AI-Ready Indexing**: Added `llms.txt` and `llms-full.txt` master manifests for optimized LLM context injection.
- **Integrity Verification**: Verified 100% semantic alignment between pre-refactor baselines and standardized documentation via a multi-agent audit protocol.
- **Automated Registry**: Added `generate_llms_full.py` script for periodic manifest updates.
- **Scope-aware deployment**: Pipelines support `project`, `local`, and `user` scopes with path resolution via `sk-pipeline-paths`.
- **Multi-pipeline support**: Multiple named pipelines coexist per workspace in isolated directories.
- **Step management commands**: `/superpipelines:new-step`, `/superpipelines:update-step`, and `/superpipelines:delete-step` enable granular pipeline mutations.
- **Compliance Matrix**: A 20-criterion audit system for layout, frontmatter, topology, and runtime safety.
- **Local Memory**: Agents may utilize `memory: local` for persisting cross-run heuristics.

### Improved
- **Protocol Clarity**: Refined operational gates in `systematic-debugging`, `tdd`, and `verification-before-completion` for sharper agent adherence.
- **Structural Voice**: Standardized all documentation to third-person impersonal voice to reinforce protocol objectivity.

### Breaking changes
- **State file path moved**: Pipeline state now lives at `<scope-root>/superpipelines/temp/{P}/{runId}/pipeline-state.json` instead of `tmp/pipeline-state.json`. There is no migration path — any in-progress pipelines from v1.0.0 must be restarted.
- **State schema extended**: `pipeline-state.json` now requires `pipeline_name`, `scope_root`, and `run_id` fields.
- **`.claudeignore` updated**: The ignore pattern changed from `tmp/pipeline-*` to `.claude/superpipelines/temp/`.
- **Agent `permissionMode` now required**: All agents declare `permissionMode` in frontmatter (`acceptEdits` for executors, `plan` for reviewers/architects).

### Removed
- `docs/AI_PIPELINES_LLM.md` — Replaced by `ai-pipelines-trimmed.md` and agent-frontmatter-schema.
- `docs/ai-pipelines-improvement-plan.md` — Legacy gap analysis.
- `docs/superpowers-vs-ai-pipelines.md`, `docs/claude-plugins-complete-guide.md`, `docs/testing.md`.
- `docs/windows/`, `docs/plans/`, `docs/superpowers/`, `docs/examples/` — Legacy directories.
- `tests/` — Legacy Superpowers-era test suites.
- Visual companion server scripts from `skills/brainstorming/`.

</release_entry>

## v1.0.0 — Initial Release (2026-05-03)

<release_entry version="1.0.0" status="INITIAL">
First standalone release of Superpipelines. Established the core framework with 7 agents, 6 execution patterns, and the spec-driven development (SDD) workflow.
</release_entry>


# File: CHANGELOG.md
----------------------------------------
# Changelog

## Distribution

Superpipelines is distributed via the GitHub-hosted marketplace at `gustavo-meilus/superpipelines`. Each entry below corresponds to a git tag of the same name on `main`.

**Install (Claude Code):**

```text
/plugin marketplace add gustavo-meilus/superpipelines
/plugin install superpipelines@superpipelines-marketplace
```

**Pin to a specific version:**

```text
/plugin install superpipelines@superpipelines-marketplace --version v1.0.2
```

## 1.0.4 — OMOA Integration & Hierarchical Context (2026-05-05)

### Architecture & Agent Optimizations

- **Hashline Editing Protocol** — Implemented `sk-hashline-protocol` to enforce content-hash validation prior to any atomic file mutation by `pipeline-task-executor`, eliminating stale-line corruption.
- **Hierarchical Context Maps** — Introduced `/superpipelines:init-deep` and `sk-hierarchical-context` to generate token-efficient, distributed `PIPELINE-CONTEXT.md` files conforming strictly to Scribius v1 XML-anchored standards.
- **Dynamic Model Routing** — Relaxed the strict `SONNET_ONLY` invariant to `DYNAMIC_DEFAULT_SONNET`, permitting specific agents (like `pipeline-architect` and `pipeline-quality-reviewer`) to dynamically route to Opus or Haiku based on their intent category (`deep-plan` vs `quick-audit`), optimizing reasoning and cost.

## 1.0.3 — Adherence Cleanup (2026-05-04)

### Documentation & Maintenance

- **Adherence Audit** — Verified 100% compliance with the v1.0.2 specification.
- **Marketplace Sync** — Updated marketplace description to remove stale references and align with plugin capabilities.
- **Structural Integrity** — Removed corrupted lines in `skill-architect.md` and consolidated duplicate headers in `RELEASE-NOTES.md`.

## 1.0.2 — Scribius v1 AI-Readiness (2026-05-04)

### Documentation & AI-Readiness

- **Scribius v1 Refactor** — Migrated all core workflow, foundation, and engineering skills to semantically anchored XML envelopes (`<protocol>`, `<invariants>`, `<rationalization_table>`).
- **Master Manifests** — Added `llms.txt` (discovery index) and `llms-full.txt` (complete documentation suite) to the repository root.
- **Automation** — Added `scripts/generate_llms_full.py` for periodic doc-suite synchronization.
- **Integrity Verified** — Performed a multi-agent semantic audit confirming 100% information persistence between pre-refactor baselines and Scribius v1 versions.

### Engineering Protocols

- **Gate Enforcement** — Formalized operational gates in `systematic-debugging` (Root Cause), `tdd` (Red-Green), and `verification-before-completion` (Evidence-Before-Claim).
- **Structural Voice** — Enforced third-person impersonal voice throughout all documentation to maintain architectural objectivity.

## 1.0.2 — v2 Redesign

### Architecture

- **Scope-aware registry** — pipelines deploy to one of three scope roots (`project` → `<workspace>/.claude/`, `local` → `<workspace>/.claude/`, `user` → `~/.claude/`). Paths resolved by `sk-pipeline-paths`.
- **Multi-pipeline isolation** — multiple named pipelines coexist per workspace, each in its own `{P}/` directory tree.
- **State path migrated** — `<scope-root>/superpipelines/temp/{P}/{runId}/pipeline-state.json` replaces the legacy flat `tmp/pipeline-state.json`. State schema now includes `pipeline_name`, `scope_root`, and `run_id`.
- **Temp dir lifecycle** — run directories are deleted on `DONE`; preserved on `ESCALATED / FAILED / BLOCKED` for inspection.

### Commands

- **New:** `/superpipelines:new-step` — add a step to an existing named pipeline.
- **New:** `/superpipelines:update-step` — modify an existing step within a named pipeline.
- **New:** `/superpipelines:delete-step` — remove a step with gap analysis and topology rewiring.
- **Updated:** `/superpipelines:audit-pipeline` — rewritten with a 20-criterion compliance matrix across 4 bands (layout, frontmatter, topology, runtime safety).

### Agent frontmatter

- **`permissionMode`** now declared per-agent: `acceptEdits` for executors, `plan` for reviewers/architects/auditors. All 7 agents updated.
- **`memory: local`** is now allowed for agents that persist learned heuristics. `memory: project` remains forbidden.
- **`skills:` frontmatter** stripped from non-agent SKILL.md files (5 workflow skills cleaned).

### Skills

- **`sk-pipeline-paths`** — added `disable-model-invocation: true` and `user-invocable: false` for proper suppression.
- **`sk-pipeline-state`** — complete rewrite for scope-aware multi-pipeline state management.
- **`severity-classification.md`** — `permissionMode` removed from SEV-0 list; `memory: local` on executors now valid; `bypassPermissions` without justification added as SEV-0.
- **`ai-pipelines-trimmed.md`** — `PERMISSION_MODE: PER_AGENT` replaces `NULL`; state management references v2 paths.
- **`anti-patterns.md`** — concurrent state race fix updated for multi-pipeline isolation.
- **`brainstorming`** — stripped ghost `writing-plans` references; terminal state is now user spec approval. Visual companion server and scripts removed.
- **`systematic-debugging`** — stripped `superpowers:` namespace prefix from skill cross-references.
- **`finishing-a-development-branch`** — caller references updated to point to `running-a-pipeline`.

### Documentation cleanup

- **Removed:** `docs/AI_PIPELINES_LLM.md`, `docs/ai-pipelines-improvement-plan.md`, `docs/superpowers-vs-ai-pipelines.md`, `docs/claude-plugins-complete-guide.md`, `docs/testing.md`, `docs/windows/`, `docs/plans/`, `docs/superpowers/`, `docs/examples/`.
- **Removed:** `RELEASE-NOTES.md` (58KB of Superpowers-era history), `CHAT_LOG_04-05-2026.md`.
- **Removed:** `tests/` directory (5 Superpowers-era test suites).
- **Updated:** `README.md` — full rewrite for v2 architecture.
- **Updated:** `.claudeignore` — `tmp/pipeline-*` replaced with `.claude/superpipelines/temp/`.
- **Synced:** `package.json` version to `1.0.2`.

## 1.0.0 — Initial release

Superpipelines is a fresh plugin built from the ground up to design and run multi-agent AI pipelines.

### Added

- Plugin manifest (`superpipelines` namespace) and marketplace entry.
- Bootstrap skill `using-superpipelines` loaded via SessionStart hook on Claude Code.
- Shared method skills (preloaded by orchestrator agents): `sk-4d-method`, `sk-spec-driven-development`, `sk-claude-code-conventions`, `sk-pipeline-patterns`, `sk-pipeline-state`, `sk-worktree-safety`, `sk-write-review-isolation`, `sk-rationalization-resistance`.
- User-invocable workflow skills: `creating-a-pipeline`, `running-a-pipeline`.
- Subagents: `pipeline-architect`, `pipeline-auditor`, `skill-architect`, `pipeline-task-executor`, `pipeline-spec-reviewer`, `pipeline-quality-reviewer`, `pipeline-failure-analyzer`.
- Companion reference libraries (no `SKILL.md`, read on demand): `pipeline-architect-references/`, `pipeline-auditor-references/`, `skill-architect-references/`, `pipeline-runner-references/`.
- Slash commands: `/superpipelines:new-pipeline`, `/superpipelines:run-pipeline`, `/superpipelines:audit-pipeline`.
- Settings: `autoMemoryEnabled: false`, `Bash(*)` permission, `CLAUDE_CODE_DISABLE_AUTO_MEMORY=1` env.
- Curated retained skills: `brainstorming`, `finishing-a-development-branch`, `test-driven-development`, `systematic-debugging`, `verification-before-completion`.

### Removed

Legacy Superpowers skills and components superseded by pipeline-specific equivalents.


# File: skills\adding-a-pipeline-step\SKILL.md
----------------------------------------
---
name: adding-a-pipeline-step
description: Use when the user wants to add a new step, capability, or agent to an existing named pipeline, or invokes /superpipelines:new-step. Selects insertion point, designs the new component, mutates topology.json, audits the delta, and gates on human approval before writing to disk.
---

# Adding a Pipeline Step — Mutation Workflow

> Orchestrates the insertion of a new step, capability, or agent into an existing named pipeline. Trigger when the user requests to expand a workflow or invokes `/superpipelines:new-step`.

<overview>
The Adding a Pipeline Step workflow ensures that any mutation to an existing topology is seamless, audited, and atomic. It manages the full lifecycle from insertion point selection and architected design to rigorous topology validation and staging-to-production promotion, preventing broken edges or invalid dependency graphs.
</overview>

<glossary>
  <term name="Insertion Point">The specific location in the topology (Before, After, Parallel, or Append) where the new step is added.</term>
  <term name="Topology Mutation">The process of updating `topology.json` and the entry skill to reflect new dependency edges.</term>
  <term name="Atomic Promotion">Moving all verified artifacts from a temporary staging directory to final production paths in a single operation.</term>
</glossary>

## Workflow Phases

<protocol>
### PHASE 0: PIPELINE SELECTION & INSPECTION
- Resolve scope registries and select the target pipeline via `AskUserQuestion`.
- Read and display the current `topology.json` as a numbered list of steps and dependency edges.

### PHASE 1: INSERTION DESIGN
- Identify the insertion point (Before/After/Parallel/Append) and affected neighbors.
- Apply the 4D Method to define the new step's intent, inputs, and outputs.
- Determine the component type: Skill-only, Skill + Agent, or Reuse Existing.

### PHASE 2: ARCHITECTED STAGING
- Dispatch `pipeline-architect` in `STEP-ADD` mode to generate new artifacts.
- <invariant>All new artifacts MUST be written to `{ROOT}/superpipelines/temp/{P}/edit-{ts}/` for staging. NEVER write directly to production paths during design.</invariant>

### PHASE 3: TOPOLOGY VALIDATION
- Verify the staged `topology.json` for:
  - Unique Step ID.
  - Valid `depends_on` references.
  - Schema compatibility between predecessor outputs and new step inputs.
- **Failures**: Return to the Architect with specific error logs.

### PHASE 4: DELTA AUDIT
- Dispatch `pipeline-auditor` in `DELTA` mode on all staged files (components, topology, and entry skill).
- <HARD-GATE>If the audit returns SEV-0 or SEV-1 findings, remediate and re-audit. Do NOT proceed to promotion until the delta is clear.</HARD-GATE>

### PHASE 5: PROMOTION & REGISTRATION
- Present the updated topology and audit results for human approval (`AskUserQuestion`).
- Upon `APPROVE`, move staged files to their final absolute paths in agents, skills, and pipeline directories.
- Update the `registry.json` lists to include new components.
</protocol>

<invariants>
- NEVER skip the delta audit; topology mutations are the primary source of runtime orchestration failures.
- ALWAYS use a staging directory (`edit-{ts}/`) for artifact generation to prevent partial, unverified updates.
- Promote changes ONLY after explicit human approval of the updated `tasks.md` and topology snippet.
</invariants>

## Red Flags — STOP
- "The audit found minor issues, let's promote anyway." → **STOP**. SEV-0/1 findings are hard blockers for promotion.
- "I'll write directly to production paths to save time." → **STOP**. Direct writes bypass the mutation safety protocol.
- "The insertion point looks obvious, skip validation." → **STOP**. Topology validation catches silent edge mismatches.

## Rationalization Table

<rationalization_table>
| Excuse | Reality |
| :--- | :--- |
| "Staging is extra overhead." | Staging allows for a rollback if the audit or human review fails. Direct writes are permanent and destructive. |
| "Topology validation is redundant." | Manual inspection often misses transitive dependency breaks caused by insertion. |
| "Minor audit findings won't break it." | Even SEV-1 findings can cause context leakage or state corruption during execution. |
</rationalization_table>

## Reference Files
- `sk-pipeline-paths/SKILL.md` — Path resolution.
- `sk-4d-method/SKILL.md` — Brief refinement.
- `creating-a-pipeline/SKILL.md` — Core scaffolding rules.
- `deleting-a-pipeline-step/SKILL.md` — Removal workflow.


# File: skills\brainstorming\SKILL.md
----------------------------------------
---
name: brainstorming
description: Use before creative or design work — features, components, new behaviors, or pipeline briefs that need refinement before a spec exists. Loaded by creating-a-pipeline Phase 0 when the user's request is exploratory or under-specified.
---

# Brainstorming — Idea Refinement Workflow

> Orchestrates the transition from vague ideas to fully formed designs and specifications through collaborative dialogue. Trigger when the user's request is exploratory, under-specified, or involves new feature design before a pipeline exists.

<overview>
Brainstorming acts as the mandatory pre-flight phase for creative and design work. It enforces a strict "no-code-before-design" policy, guiding the orchestrator through context exploration, clarifying questions, and trade-off analysis to produce a validated design document (spec) that serves as the foundation for subsequent pipeline execution.
</overview>

<glossary>
  <term name="Design Doc (Spec)">A persistent markdown file (e.g., `docs/specs/YYYY-MM-DD-topic-design.md`) capturing validated requirements.</term>
  <term name="Visual Companion">A browser-based tool for presenting mockups and diagrams during the design phase.</term>
  <term name="The Design Gate">The non-negotiable requirement for user approval of a design before any implementation begins.</term>
</glossary>

## The Brainstorming Process

<protocol>
### 1. CONTEXT & DECOMPOSITION
- Explore existing project structure, documentation, and recent commits.
- **Large-Scale Requests**: If the request describes multiple subsystems, decompose them into independent sub-projects before refining details.

### 2. CLARIFYING DIALOGUE
- Ask clarifying questions focused on purpose, constraints, and success criteria.
- <invariant>Ask exactly one question per message to avoid overwhelming the user.</invariant>
- Prefer multiple-choice options (A/B/C) for faster decision-making.

### 3. APPROACH & RECOMMENDATION
- Propose 2-3 different architectural approaches with clear trade-offs.
- Lead with a specific recommendation and provide reasoning grounded in project context.

### 4. DESIGN PRESENTATION (THE GATE)
- Present the refined design in logical sections (Architecture, Data Flow, Error Handling, Testing).
- <HARD-GATE>Do NOT write code or scaffold projects until the user has explicitly approved the presented design sections.</HARD-GATE>

### 5. SPECIFICATION & REVIEW
- Author the design document to `docs/specs/`.
- Perform a **Spec Self-Review**: scan for placeholders, internal contradictions, or ambiguity.
- <HARD-GATE>Ask the user to review the final written spec file. Brainstorming is complete only upon user approval of the spec.</HARD-GATE>
</protocol>

<invariants>
- NEVER combine the "Visual Companion" offer with other questions; it must be a standalone message.
- NEVER skip the design gate for "simple" projects; simplicity is often a mask for unexamined assumptions.
- ALWAYS design for isolation, breaking systems into smaller units with well-defined interfaces.
</invariants>

## The Visual Companion Protocol

<visual_companion_rules>
- **Offering**: If upcoming questions are visual (layouts, diagrams), offer the companion once in a standalone message.
- **Decision**: For every subsequent question, determine if visual treatment (browser) or text treatment (terminal) is superior.
- **Browser**: Use for mockups, wireframes, and architecture diagrams.
- **Terminal**: Use for requirements, conceptual choices, and tradeoff lists.
</visual_companion_rules>

## Red Flags — STOP
- "This is too simple to need a design." → **STOP**. Every project requires a validated design gate.
- "I'll ask 5 questions at once to save time." → **STOP**. One-question-per-message is mandatory for cognitive clarity.
- "I'll start scaffolding while we brainstorm." → **STOP**. Design must be approved before implementation begins.

## Rationalization Table

<rationalization_table>
| Excuse | Reality |
| :--- | :--- |
| "I'll fix the spec later." | A vague spec leads to divergent parallel workers. Fix all ambiguity during the design phase. |
| "Visuals take too many tokens." | Visuals prevent multi-turn misunderstandings that cost far more tokens in rework. |
| "The user already knows what they want." | Brainstorming surfaces implicit assumptions the user hasn't documented. |
</rationalization_table>

## Reference Files
- `creating-a-pipeline/SKILL.md` — Implementation workflow.
- `sk-4d-method/SKILL.md` — Brief deconstruction.
- `sk-claude-code-conventions/SKILL.md` — Design patterns.
- `visual-companion.md` — Detailed browser usage guide.


# File: skills\creating-a-pipeline\SKILL.md
----------------------------------------
---
name: creating-a-pipeline
description: Use when the user asks to design a pipeline, build a workflow for X, plan multi-step feature work, or invokes /superpipelines:new-pipeline. Walks git preflight, scope selection, pattern selection, architect dispatch, pre-gate audit, and human approval to produce a runnable named pipeline bundle.
---

# Creating a Pipeline — Scaffolding Workflow

> Orchestrates the end-to-end design and scaffolding of a new multi-agent pipeline. Trigger when the user requests to design a workflow, plan multi-step feature work, or invokes `/superpipelines:new-pipeline`.

<overview>
The Pipeline Creation workflow guides an orchestrator from a raw user brief to an approved, runnable pipeline bundle. It enforces rigorous pre-flight checks (Git status), scope resolution, architectural patterns, and a mandatory audit-architect loop before presenting a final design for human approval.
</overview>

<glossary>
  <term name="Pipeline Scope">The deployment context (Local, Project, or User) determining where artifacts are persisted.</term>
  <term name="Architect Dispatch">Engaging the `pipeline-architect` agent to generate the formal specification, plan, and topology.</term>
  <term name="Pre-gate Audit">A mandatory review by the `pipeline-auditor` to clear critical (SEV-0/1) issues before human review.</term>
</glossary>

## Workflow Phases

<protocol>
### PHASE 0: GIT PREFLIGHT
- <HARD-GATE>Run git preflight FIRST — before any other action. STOP if the workspace is not a valid git repository and present the user with three options: (a) proceed without git (Pattern 1 or 4 only), (b) initialize git, (c) cancel. Do NOT advance to Phase 1 until this gate is resolved.</HARD-GATE>
- **Goal**: Ensure the environment supports the isolation requirements of the selected pattern.

### PHASE 1: SCOPE & IDENTITY
- <HARD-GATE>Ask the user to choose a deployment scope (`local`, `project`, or `user`) and a pipeline name BEFORE proceeding to Phase 2. Resolve all paths via `sk-pipeline-paths`. Validate the name: lowercase/hyphens only, ≤48 chars, unique in the scope's `registry.json`. Do NOT advance to Phase 2 without a confirmed scope and a valid, unique pipeline name.</HARD-GATE>

### PHASE 2: BRIEF REFINEMENT (4D)
- Apply the 4D Method to deconstruct core intent and constraints.
- Acknowledge if the user requested a specific output format. If not specified, deduce an appropriate format based on the pipeline's goal (e.g., markdown files, code snippets, code files).
- <HARD-GATE>If ≥3 critical slots are missing (goal, success criteria, scope, data), STOP and ask targeted questions.</HARD-GATE>

### PHASE 3: PATTERN SELECTION
- Select a topology pattern (Sequential, Parallel, Iterative, Gated, or Spec-Driven) using the `sk-pipeline-patterns` decision tree.
- **Restriction**: If git is absent, limit selection to Pattern 1 or 4.

### PHASE 4: DESIGN & AUDIT LOOP
- **Dispatch Architect**: Generate `spec.md`, `plan.md`, `tasks.md`, `topology.json`, and all step-specific agents/skills.
- **Output Formatter Rule**: The Architect MUST append a specific `output-formatter` step as the final node in the topology, designed to transform the output into the deduced format and save it to the `<workspace-root>/output/` folder.
- **Dispatch Auditor**: Review all generated files in DELTA mode.
- <HARD-GATE>The `pipeline-auditor` MUST be dispatched after the architect. Do NOT present the human gate without audit results. If any SEV-0 or SEV-1 findings are returned, re-dispatch the Architect to remediate before proceeding.</HARD-GATE>


### PHASE 5: HUMAN APPROVAL
- Present the topology diagram, spec summary, full task list, and audit results to the user.
- **Approval Required**: Do NOT generate the entry skill until the user explicitly approves the design.
- <HARD-GATE>When the user approves, proceed DIRECTLY to Phase 6 (scaffold generation). Do NOT ask for runtime inputs (e.g., "what's the topic?"). The pipeline does not run here — it is scaffolded. Running is a separate command (`/superpipelines:run-pipeline`).</HARD-GATE>

### PHASE 6: FINALIZATION
- <HARD-GATE>Write ALL of the following to disk before ending the session. Do NOT tell the user the pipeline is ready until every file is confirmed written:
  1. `<scope-root>/superpipelines/pipelines/{P}/spec.md`
  2. `<scope-root>/superpipelines/pipelines/{P}/plan.md`
  3. `<scope-root>/superpipelines/pipelines/{P}/tasks.md`
  4. `<scope-root>/superpipelines/pipelines/{P}/topology.json`
  5. `<scope-root>/skills/superpipelines/{P}/run-{P}/SKILL.md` (entry skill, `user-invocable: true`)
  6. All step agents and skills under `<scope-root>/agents/superpipelines/{P}/` and `<scope-root>/skills/superpipelines/{P}/`
  7. Updated `<scope-root>/superpipelines/registry.json`
</HARD-GATE>
- Confirm to the user: "Pipeline `{P}` scaffolded. Use `/superpipelines:run-pipeline` to execute it."
</protocol>

<invariants>
- NEVER hardcode paths; always resolve via `sk-pipeline-paths`.
- NEVER generate the entry skill before human approval of the `tasks.md` and `topology.json`.
- All internal step skills MUST be marked `user-invocable: false`.
- Any modification to the design MUST trigger a re-audit for SEV-0/1 issues.
</invariants>

## Red Flags — STOP
- "The brief is detailed enough, I'll skip git preflight and scope selection." → **STOP**. Phases 0 and 1 are mandatory regardless of brief quality. A detailed brief does not substitute for git verification or scope confirmation.
- "The user approved, what's the topic for the first run?" → **STOP**. Approval triggers Phase 6 (scaffold generation), not a run. Writing files to disk comes first. Running is `/superpipelines:run-pipeline`.
- "The audit only found SEV-2 issues, let's proceed." → **STOP**. SEV-0/1 must be zero before the human gate.
- "The user said skip the spec." → **STOP**. The spec is the non-negotiable contract for parallel execution.
- "I'll skip the human gate to save time." → **STOP**. One misunderstanding at this stage wastes all downstream implementation.
- "I'll write state to `tmp/pipeline-state.json`." → **STOP**. The canonical state path is `<scope-root>/superpipelines/temp/{P}/{runId}/pipeline-state.json`. The legacy `tmp/` path is retired.

## Rationalization Table

<rationalization_table>
| Excuse | Reality |
| :--- | :--- |
| "The audit is extra overhead." | SEV-0 topology errors only surface at runtime. Pre-flight auditing is 10x cheaper than runtime recovery. |
| "Git preflight is unnecessary." | Worktree patterns silently fail in non-git workspaces. Preflight prevents mid-run deadlocks. |
| "I'll generate the entry skill now." | Entry skills are expensive to refactor if the user revises the underlying topology. Wait for approval. |
</rationalization_table>

## Reference Files
- `sk-pipeline-paths/SKILL.md` — Scope and path resolution.
- `sk-pipeline-patterns/SKILL.md` — Topology selection tree.
- `sk-4d-method/SKILL.md` — Brief deconstruction framework.
- `sk-pipeline-state/SKILL.md` — State initialization schema.


# File: skills\deleting-a-pipeline-step\SKILL.md
----------------------------------------
---
name: deleting-a-pipeline-step
description: Use when the user wants to remove or delete a step from an existing named pipeline, or invokes /superpipelines:delete-step. Performs gap analysis, optionally rewires edges, audits the delta, and gates on human approval before any deletion occurs.
---

# Deleting a Pipeline Step — Removal Workflow

> Orchestrates the removal of a step from an existing named pipeline while ensuring topology continuity. Trigger when the user requests to delete a capability or invokes `/superpipelines:delete-step`.

<overview>
The Deleting a Pipeline Step workflow guarantees that the removal of a component does not result in a fragmented dependency graph. It utilizes a rigorous gap analysis to identify necessary rewiring, stages all deletions and mutations for audit, and enforces a mandatory human gate before executing irreversible file removals.
</overview>

<glossary>
  <term name="Gap Analysis">The process of identifying predecessor/successor disconnections caused by a step removal.</term>
  <term name="Through-gap">A condition where a deleted step sat between two active steps, requiring direct reconnection.</term>
  <term name="Blocking-gap">A condition where a deleted step was the sole source of required inputs for a successor.</term>
</glossary>

## Workflow Phases

<protocol>
### PHASE 0: PIPELINE & STEP SELECTION
- Resolve scope registries and identify the target pipeline and step.
- Display the current `topology.json` as a graph showing all dependency chains.

### PHASE 1: GAP ANALYSIS
- Analyze the impact of removal on predecessors and successors.
- <HARD-GATE>If a **Blocking-gap** is found (no alternative input source), STOP. The user must provide an alternative source or cancel the deletion.</HARD-GATE>

### PHASE 2: MUTATION DESIGN (REWIRE)
- For through-gaps or entry-gaps, present a rewire plan to the user (e.g., "Wire A directly to C").
- Dispatch `pipeline-architect` in `STEP-DELETE` mode to stage all changes.
- <invariant>All mutations (file removals and topology updates) MUST be staged in `edit-{ts}/`. NEVER delete directly from production paths during design.</invariant>

### PHASE 3: DELTA AUDIT
- Dispatch `pipeline-auditor` in `DELTA` mode on the staged topology, entry skill, and neighbor steps.
- <HARD-GATE>SEV-0 or SEV-1 findings block deletion. A fragmented pipeline is a critical failure. Re-audit until the delta is clear.</HARD-GATE>

### PHASE 4: HUMAN APPROVAL
- Present a "Deletion Manifest" showing exactly which files will be removed and which edges will be rewired.
- <HARD-GATE>Wait for explicit `APPROVE`. On `CANCEL`, discard all staged changes and do NOT delete artifacts.</HARD-GATE>

### PHASE 5: ATOMIC PROMOTION
- Execute file removals (agents/skills) and write updated `topology.json` and `tasks.md`.
- Update the `registry.json` to reflect the removal.
</protocol>

<invariants>
- NEVER assume a step is "unused" without verifying all `depends_on` entries in the topology graph.
- ALWAYS perform atomic promotion from a staging area to ensure rollback capability.
- NEVER delete a step that creates an unresolvable blocking-gap in the orchestration.
</invariants>

## Red Flags — STOP
- "The pipeline will work without rewiring — it's obvious." → **STOP**. Obvious assumptions are the leading source of silent runtime failures.
- "I'll skip the human gate; deletion is a simple task." → **STOP**. Deletion is irreversible; the human gate is the final recovery point.
- "I'll delete the files first, then update the topology." → **STOP**. This results in a broken pipeline if the topology update fails.

## Rationalization Table

<rationalization_table>
| Excuse | Reality |
| :--- | :--- |
| "The step is terminal, why audit?" | Removing a terminal step can still break final status reporting or cleanup logic. |
| "Rewiring is over-engineering." | A broken dependency chain blocks every subsequent pipeline run. Rewiring is essential maintenance. |
| "I can recover from git if I'm wrong." | Relying on git recovery for basic workflow errors indicates a failure of the safety protocol. |
</rationalization_table>

## Reference Files
- `sk-pipeline-paths/SKILL.md` — Path resolution.
- `sk-pipeline-state/SKILL.md` — Run state tracking.
- `adding-a-pipeline-step/SKILL.md` — Insertion workflow.
- `updating-a-pipeline-step/SKILL.md` — Modification workflow.


# File: skills\finishing-a-development-branch\SKILL.md
----------------------------------------
---
name: finishing-a-development-branch
description: Use when implementation is complete, tests pass, and integration decisions are pending — presents structured options for merge, PR, or cleanup of the development branch
---

# Finishing a Development Branch — Integration Protocol

> Facilitates the structured conclusion of development work by verifying readiness and presenting integration options. Trigger when implementation is complete, tests pass, and integration decisions (merge, PR, or cleanup) are pending.

<overview>
Finishing a Development Branch ensures that work is integrated or preserved according to the user's explicit choice. It enforces a mandatory test verification gate before any options are presented, preventing the promotion of broken or unverified code to the base branch.
</overview>

<glossary>
  <term name="Base Branch">The target for integration, typically `main` or `master`.</term>
  <term name="Worktree">An isolated directory for development; must be cleaned after integration.</term>
  <term name="PR Gate">Option 2, which involves pushing the branch and creating a Pull Request via `gh pr create`.</term>
</glossary>

## The Completion Protocol

<protocol>
### 1. VERIFY TESTS (THE GATE)
- Run the project's primary test suite (e.g., `npm test`, `pytest`).
- <HARD-GATE>If tests fail, STOP. You cannot proceed to integration options until all tests are green.</HARD-GATE>

### 2. DETERMINE BASE BRANCH
- Identify the split point (e.g., `git merge-base HEAD main`).
- Confirm the base branch with the user if ambiguity exists.

### 3. PRESENT STRUCTURED OPTIONS
- Present exactly these four options without modification:
  1. **Merge back to [base] locally**
  2. **Push and create a Pull Request**
  3. **Keep the branch as-is (Handle later)**
  4. **Discard this work**

### 4. EXECUTE CHOICE
- **Option 1**: Checkout base, pull latest, merge, re-verify tests, and delete feature branch.
- **Option 2**: Push to origin and create PR using the `gh` CLI.
- **Option 4**: Request explicit typed confirmation ("discard") before destructive deletion.

### 5. CLEANUP
- For Options 1, 2, and 4: Remove the associated git worktree to maintain repository hygiene.
</protocol>

<invariants>
- NEVER proceed with integration if the verification gate fails.
- NEVER cleanup the worktree for Option 3 (Keep as-is).
- ALWAYS re-verify tests on the base branch after a local merge (Option 1).
- ALWAYS obtain "discard" confirmation before executing Option 4.
</invariants>

## Completion Patterns

<patterns>
| Option | Merge | Push | Cleanup Branch | Cleanup Worktree |
| :--- | :--- | :--- | :--- | :--- |
| **1. Merge Locally** | ✓ | - | ✓ | ✓ |
| **2. Create PR** | - | ✓ | - | ✓ |
| **3. Keep As-Is** | - | - | - | - |
| **4. Discard** | - | - | ✓ (force) | ✓ |
</patterns>

## Red Flags — STOP
- "I'll merge now and fix the tests later." → **STOP**. Integration of failing code is a SEV-0 failure.
- "What should I do next?" → **STOP**. Present the four structured options defined in the protocol.
- "Deleting worktree automatically." → **STOP**. Option 3 requires worktree preservation.

## Rationalization Table

<rationalization_table>
| Excuse | Reality |
| :--- | :--- |
| "PR handles testing anyway." | Local verification prevents broken builds and reduces CI overhead. |
| "It's just a one-line change." | One-line changes are the leading cause of "it worked in my head" regressions. |
| "Discarding is faster than cleanup." | Unconfirmed discards cause irreversible data loss. |
</rationalization_table>

## Reference Files
- `sk-worktree-safety/SKILL.md` — Worktree management.
- `verification-before-completion/SKILL.md` — Final evidence gate.
- `running-a-pipeline/SKILL.md` — Integration point for pipeline completion.


# File: skills\pipeline-architect-references\references\agent-frontmatter-schema.md
----------------------------------------
# Agent Frontmatter Schema — Architect Reference

Canonical YAML frontmatter for pipeline subagents. Use this when generating new agent files via `pipeline-architect`.

## Schema

```yaml
---
name: lowercase-hyphens          # ≤64 chars, matches filename
description: triggering conditions only — third person, ≤1024 chars
tools: Read, Write, Edit, Bash, Glob, Grep   # explicit allowlist
disallowedTools: Write, Edit                 # explicit denylist (read-only agents)
model: sonnet                                 # SONNET_ONLY default; non-sonnet requires user opt-in
effort: low | medium | high | xhigh | max
maxTurns: 25                                  # bounds execution
version: "1.0"                                # bump on breaking change
permissionMode: default | acceptEdits | plan | bypassPermissions   # optional; omit = default
memory: none | local                          # optional; omit = none. NEVER "project"
skills:                                       # ONLY sk-* preloaded method skills
  - sk-4d-method
  - sk-pipeline-paths
mcpServers:
  - server-name
background: false
isolation: worktree                           # Patterns 2/2b/3/5
---
```

## Field rules

| Field | Required | Notes |
|-------|----------|-------|
| `name` | yes | Lowercase + hyphens only. Matches filename (without `.md`). |
| `description` | yes | Routing contract. Triggering conditions only. NEVER summarize workflow. Third person. |
| `tools` | recommended | Minimal allowlist. Read-only agents: omit Write/Edit/Bash. |
| `disallowedTools` | optional | Use to deny tools the agent must never call. Reviewers must deny Write/Edit/Bash. |
| `model` | yes | `sonnet` by default. Non-sonnet: document user opt-in in Architect's Brief and agent body. |
| `effort` | yes | Architect/auditor: `high`. Workers: `medium`. Triage: `low`. |
| `maxTurns` | yes | Read-only: 15–25. Generation: 30–40. Validation: 10–15. |
| `version` | yes | Bump major on breaking change to output schema or required inputs. |
| `permissionMode` | optional | `acceptEdits` for implementation agents; `plan` for analysis-only; omit or `default` for standard. `bypassPermissions` requires inline justification in agent body. |
| `memory` | optional | `local` for agents persisting learned heuristics. Omit (= `none`) for stateless agents. NEVER `project`. |
| `skills` | recommended | ONLY shared `sk-*` skills. Never large workflow skills. Never companion-reference skills. |
| `isolation` | conditional | `worktree` for parallel/iterative patterns. Omit for read-only analysis. |
| `background` | optional | `true` only for fire-and-forget observers. Default `false`. |

## NEVER use

- `memory: project` — state goes to `pipeline-state.json` in the temp directory.
- Companion `<agent>-references` in `skills:` frontmatter — read reference files on demand via `Read`.
- Large workflow skills (`brainstorming`, `creating-a-pipeline`, etc.) in `skills:` frontmatter.
- Hooks specifying per-agent Bash auto-allow when `Bash(*)` is already in plugin `settings.json` permissions.

## permissionMode selection guide

| Agent role | Recommended permissionMode |
|------------|---------------------------|
| Implementation / task-executor | `acceptEdits` |
| Architect (design only) | `plan` |
| Auditor / reviewer | `plan` (reviewers also use `disallowedTools`) |
| Orchestrator skill | omit (controlled by plugin `settings.json`) |
| Agent requiring unrestricted access | `bypassPermissions` — ONLY with documented user justification in agent body |

## memory selection guide

| Agent role | Recommended memory |
|------------|-------------------|
| Stateless worker (most agents) | omit or `none` |
| Agent learning command patterns across runs | `local` |
| Any agent | NEVER `project` |

## Effort selection

| Task type | Effort |
|-----------|--------|
| Triage / routing / extraction | `low` |
| Most worker agents | `medium` |
| Architect / auditor / multi-file analysis | `high` |
| Cross-system integration with competing constraints | `xhigh` |
| Truly ambiguous, last-resort problems | `max` |

## Capability contract (agent body)

Every agent body must declare its contract near the top:

```markdown
# Inputs required: {task_file_path}, {project_context}, {scope_root}
# Output schema: { "status": "DONE|BLOCKED|...", "outputs": [...] }
# Breaking change log: v1.0 — initial release
```

## Versioning rules

Breaking (bump major):
- Output schema changes (field names, types, required fields).
- Required input changes.
- Tool removal that orchestrator depends on.
- Status protocol changes.

Non-breaking (no bump):
- Internal reasoning improvements.
- Optional output fields added.
- Effort level changes.
- `permissionMode` or `memory` changes.
- Tools added that don't change output schema.


# File: skills\pipeline-architect-references\references\anti-patterns.md
----------------------------------------
# Pipeline Architecture Anti-Patterns

Catalog of common failure modes when designing pipelines and agents. Each entry: name, symptoms, fix.

## Table of contents

1. The Diver
2. The Mega-Prompt
3. Context Dumping
4. Silent Failures
5. Tool Sprawl
6. Vague Description
7. Leaky Context
8. Over-Tooled
9. Workflow-Skill Preload
10. Companion-Reference Preload
11. Per-Agent Bash Hook with Global Allow
12. Memory Leak (memory: project)
13. Synchronous Iterative Loop
14. Single-Stage Review
15. Worktree Reuse Without Re-Baseline
16. Path-Traversal Handoff
17. Unqualified MCP Tool Names
18. Concurrent State Race
19. Hardcoded Plugin Paths

---

## 1. The Diver

**Symptoms:** One agent does everything (research + plan + implement + test + review). Context fills past 60%; reasoning quality collapses.

**Fix:** Decompose into RPI loop with separate agents per phase. `ANT_SWARM_PRINCIPLE: TRUE`. Pattern 5 is the canonical decomposition.

## 2. The Mega-Prompt

**Symptoms:** Agent body >150 lines; one giant numbered list; no structural sections.

**Fix:** Body ≤150 lines. Move depth to companion `<agent>-references/references/*.md`. Use clearly-named sections.

## 3. Context Dumping

**Symptoms:** Orchestrator pastes entire file contents into spawn prompts. Subagent context bloated with material it doesn't need.

**Fix:** `PASS_PATHS_NOT_CONTENT: TRUE`. Pass file path; let the worker read it. Exception: task text is content (extract from `tasks.md` once at orchestrator, pass extracted text per worker).

## 4. Silent Failures

**Symptoms:** Agent reports success; downstream phase fails; orchestrator can't tell what went wrong because no terminal status was emitted.

**Fix:** Every agent emits exactly one of `DONE / DONE_WITH_CONCERNS / NEEDS_CONTEXT / BLOCKED` with the agent's output schema. Orchestrator NEVER ignores a non-`DONE` status.

## 5. Tool Sprawl

**Symptoms:** Agent has 15+ tools in `tools:` field. Most never invoked. Tool definitions consume context budget.

**Fix:** Minimal allowlist. Audit utilization: if a tool is invoked 0 times across 3 iterations, prune it.

## 6. Vague Description

**Symptoms:** "Helps with code review" — orchestrator can't decide when to dispatch. Agent never gets routed to the right tasks.

**Fix:** Triggering conditions only. Specific, action-oriented, includes WHEN and WHAT. Third person.

## 7. Leaky Context

**Symptoms:** Agent body references `CLAUDE.md`, parent system prompt, "as discussed earlier."

**Fix:** Body is self-contained. Receives all context via inputs. Never references parent state.

## 8. Over-Tooled

**Symptoms:** Read-only reviewer agent has Write/Edit tools. Reviewer accidentally edits the file it's reviewing.

**Fix:** Enforce `disallowedTools: Write, Edit` on reviewer agents. Reviewers READ ONLY.

## 9. Workflow-Skill Preload

**Symptoms:** Agent frontmatter `skills: [brainstorming, creating-a-pipeline, running-a-pipeline]`. Every agent startup injects ~3000 tokens of workflow content.

**Fix:** `skills:` preloads ONLY shared `sk-*` method skills (≤100 lines each). Workflow skills are session-level lazy invocation, not pre-injection.

## 10. Companion-Reference Preload

**Symptoms:** Agent frontmatter `skills: [pipeline-architect-references]`. Bloats startup context with files agent might never read.

**Fix:** Companion reference skills have NO `SKILL.md`. Agent reads `references/*.md` on demand via `Read` tool. Never preload.

## 11. Per-Agent Bash Hook with Global Allow

**Symptoms:** Every agent has `hooks: PreToolUse: matcher: Bash` with allow-stamp; plugin `settings.json` ALSO has `Bash(*)` in permissions.

**Fix:** Pick one. Prefer global `Bash(*)` in `settings.json`; remove per-agent hooks. Less noise, same outcome.

## 12. Memory Leak

**Symptoms:** Agent uses `memory: project` to persist state across runs. State scattered across `.claude/memory/*` files.

**Fix:** All pipeline state lives in `<scope-root>/superpipelines/temp/{P}/{runId}/pipeline-state.json` per `STATE_MANAGEMENT: STRUCTURED_JSON`. `memory: local` is allowed for learned heuristics. Memory tool must never be used for deterministic pipeline state.

## 13. Synchronous Iterative Loop

**Symptoms:** Pattern 3 with no max-iterations cap; agents loop until context exhausted.

**Fix:** `<HARD-GATE>` after 3 failed iterations without measurable progress. Escalate per Pattern 3 escalation protocol.

## 14. Single-Stage Review

**Symptoms:** One reviewer checks both spec compliance and code quality. Stage 2 issues mask Stage 1 failures (or vice versa).

**Fix:** TWO stages, separate agents. Stage 1 (spec compliance) gates Stage 2 (code quality). Re-Stage-1 after every Stage 2 fix.

## 15. Worktree Reuse Without Re-Baseline

**Symptoms:** Pipeline reuses an existing worktree without running test baseline. Pre-existing failures get blamed on the new pipeline.

**Fix:** `sk-worktree-safety` Step 3: VERIFY_BASELINE every time, even on reused worktrees.

## 16. Path-Traversal Handoff

**Symptoms:** Agent uses `../../` paths to reference files outside its plugin/worktree.

**Fix:** All paths relative and start with `./`. Use symlinks if cross-tree references are required. `${CLAUDE_PLUGIN_ROOT}` for plugin-relative paths.

## 17. Unqualified MCP Tool Names

**Symptoms:** Agent calls `bigquery_schema` without server qualifier. Fails when multiple MCP servers expose tools with similar names.

**Fix:** Always fully qualified: `ServerName:tool_name` (e.g., `BigQuery:bigquery_schema`).

## 18. Concurrent State Race

**Symptoms:** Two pipelines run concurrently in same workspace; each overwrites the other's state.

**Fix:** Each named pipeline `{P}` gets its own directory under `superpipelines/temp/{P}/`. Within the same `{P}`, only one active run is allowed. Orchestrator refuses to start if active state exists.

## 19. Hardcoded Plugin Paths

**Symptoms:** Agent body references `~/.claude/agents/...` or absolute paths.

**Fix:** `${CLAUDE_PLUGIN_ROOT}` for plugin-relative; `${CLAUDE_PLUGIN_DATA}` for persistent state; never `~/.claude/...`.


# File: skills\pipeline-architect-references\references\sdd-artifacts.md
----------------------------------------
# SDD Artifacts — Architect Templates

Templates for `spec.md`, `plan.md`, `tasks.md`, and the human gate prompt. Used by `pipeline-architect` when working in Pattern 5 (Spec-Driven Development).

## Table of contents

1. `spec.md` — what + why
2. `plan.md` — how
3. `tasks.md` — atomic, sequenced
4. Task atomicity rules
5. Human approval gate prompt
6. `pipeline-state.json` initial entry

---

## `spec.md` — what + why

```markdown
# Feature: {name}

## Context & motivation
{Why now? What prompted this? What's the business or technical problem?}

## User journeys
{Scenario → outcome. One bullet per journey. Concrete actors and inputs.}

- As a {role}, I {action}, so that {outcome}.

## Success criteria (acceptance criteria)
- [ ] AC-1: {verifiable outcome — written so a reader can answer "is this true yet?"}
- [ ] AC-2: …

## Non-goals
- {Out-of-scope item 1}
- {Out-of-scope item 2}

## Constraints
- Regulatory: {GDPR, SOC2, etc.}
- Performance: {latency, throughput targets}
- Compatibility: {browsers, SDKs, runtime versions}
- Timeline: {deadline, milestones}

## Open questions (defer to /clarify)
- {Question 1}
- {Question 2}
```

**Gate:** A reader who has never seen the code can answer "what does done look like?" If not, the spec is incomplete.

## `plan.md` — how

```markdown
# Plan: {feature name}

## Tech stack
- Language: {…}
- Frameworks: {…}
- Libraries (with versions): {…}
- Runtime: {…}

## Architecture
{Layer diagram OR sequence diagram OR data flow diagram}

## API contracts
{Schemas, function signatures, request/response shapes. Use code blocks.}

## Dependency matrix
| Component | Depends on | Owned by |
|-----------|-----------|----------|
| {…} | {…} | {…} |

## Risks & mitigations
| Risk | Likelihood | Mitigation |
|------|-----------|-----------|
| {…} | {high/med/low} | {…} |

## Rollout plan
- Phase 1: {staged or canary or feature-flagged}
- Phase 2: {…}
- Rollback procedure: {…}

## Explicit design decisions
- {Decision 1}: {chose A over B because …}
- {Decision 2}: {…}
```

## `tasks.md` — atomic, sequenced

```markdown
# Tasks

## T-1: {short name}
- **Description:** {one sentence}
- **Files:** {list of files this task touches}
- **Acceptance:** {a command or check that returns pass/fail}
- **Depends on:** {T-0 or none}
- **Estimated turns:** {5-30 min of agent work}

## T-2: {short name}
…
```

### Task atomicity rules

- One task = one agent session = 5–30 min of work.
- Acceptance criterion is automatable (typecheck, lint, test, grep, file existence).
- Files list is exhaustive (the worker won't touch files outside the list).
- Dependencies form a DAG (no cycles).
- Every spec AC maps to at least one task. No orphan tasks.

## Human approval gate prompt

Use exactly this phrasing for the Phase 4b gate (don't paraphrase — the wording is calibrated to elicit a clean APPROVE/REVISE response):

```
Spec and tasks written. Please review spec.md and tasks.md before I begin parallel implementation.

[APPROVE] — proceed to /implement (parallel dispatch).
[REVISE]  — return to spec or plan with feedback.
```

Wait for APPROVE. If REVISE arrives, route back per the 4D feedback table:

| Feedback signal | Re-entry |
|-----------------|----------|
| Wrong goal / missed problem | re-spec (Phase 1) |
| Right goal, wrong architecture | re-plan (Phase 2) |
| Right plan, task breakdown wrong | re-tasks (Phase 3) |

## `pipeline-state.json` initial entry

```json
{
  "pipeline_id": "<uuid>",
  "started_at": "<iso8601>",
  "pattern": "5",
  "status": "running",
  "current_phase": 0,
  "phases": [
    { "index": 0, "name": "specify",   "status": "pending", "agent": "pipeline-architect", "outputs": [], "error": null },
    { "index": 1, "name": "plan",      "status": "pending", "agent": "pipeline-architect", "outputs": [], "error": null },
    { "index": 2, "name": "tasks",     "status": "pending", "agent": "pipeline-architect", "outputs": [], "error": null },
    { "index": 3, "name": "human-gate","status": "pending", "agent": "user",               "outputs": [], "error": null },
    { "index": 4, "name": "implement", "status": "pending", "agent": "pipeline-task-executor", "outputs": [], "error": null }
  ],
  "metadata": {}
}
```


# File: skills\pipeline-architect-references\references\topology-selection.md
----------------------------------------
# Topology Selection — Architect Decision Guide

Used by `pipeline-architect` when choosing a pipeline pattern for a brief. Reads on demand; not preloaded.

## Decision tree

```
Is the task multi-step with dependencies between phases?
├── No → no pipeline; just apply the 4D Method and execute.
└── Yes
    ├── Sub-tasks independent and mergeable? → Pattern 2 / 2b (Parallel Fan-Out)
    ├── Fix/heal cycle (test → analyze → fix)? → Pattern 3 (Iterative Loop)
    ├── Destructive or irreversible action involved? → Pattern 4 (Human-Gated)
    ├── Feature requiring spec/plan/tasks? → Pattern 5 (SDD)
    └── Strictly linear, each phase depends on prior? → Pattern 1 (Sequential)
```

Pattern 6 (4D wrapper) always runs on top of any other pattern.

## Topology trade-offs

| Pattern | Latency | Token cost | Failure isolation | Human attention |
|---------|---------|------------|-------------------|-----------------|
| 1 | High (serial) | Low–medium | Per-phase rollback | Low |
| 2 / 2b | Low (parallel) | High (N concurrent) | Per-branch isolation | Medium |
| 3 | Variable | Medium per iteration | Loop bounded | Low until escalation |
| 4 | High (gated) | Low | Manual rollback | High at gates |
| 5 | Low (parallel implement) | High | Per-task isolation | Medium (1 gate) |

## Choosing handoff format

| Data shape | Handoff | Why |
|-----------|---------|-----|
| < 1 KB structured (status, JSON) | Pass content directly | Cheap; no file I/O cost |
| > 1 KB or any code | Pass file path | Avoids bloating spawn prompts |
| Per-task text from tasks.md | Extract once, pass extracted text to worker | Worker shouldn't have to find its own task |
| Logs / large datasets | Pass path + line range | Bound stdout + scope reads |

## Mermaid diagram template (deliverable)

```mermaid
flowchart TD
  A[Architect] --> B[Spec.md]
  B --> C[Plan.md]
  C --> D[Tasks.md]
  D --> E{Human Gate}
  E -- APPROVE --> F[Implementer T-1]
  E -- APPROVE --> G[Implementer T-2]
  F --> H[Spec Reviewer T-1]
  G --> I[Spec Reviewer T-2]
  H --> J[Quality Reviewer T-1]
  I --> K[Quality Reviewer T-2]
  J --> L[Reconcile state]
  K --> L
```

## Context budget per pattern

Estimate before authoring. Budget = sum of agent body + preloaded skills + tool definitions + initial prompt.

| Pattern | Typical agents | Budget per agent | Total per pipeline |
|---------|----------------|------------------|--------------------|
| 1 | 3 sequential | 3–5k tokens | 9–15k |
| 2 | 3 parallel + 1 merge | 3–5k each | 12–20k |
| 3 | Tester + Analyzer + Fixer × N iterations | 4–6k each | 12–18k × N |
| 5 | Architect + N implementers + 2N reviewers | 4–6k each | 4–6k × (1 + 3N) |

Reasoning quality degrades around 40–60% context fill. Add up to 100k cap and prefer many small contexts over one large one (`ANT_SWARM_PRINCIPLE`).


# File: skills\pipeline-auditor-references\references\audit-report-template.md
----------------------------------------
# Audit Report Template

Standard structure for audit reports emitted by `pipeline-auditor`.

```markdown
# Audit Report — {target file or pipeline name}

**Auditor:** pipeline-auditor v1.0
**Target:** {file path(s)}
**Date:** {ISO 8601}
**Compliance score:** {X / 20 criteria PASS}

## Executive summary

{2–4 sentences: overall verdict, count by severity, recommended action.}

## Findings by severity

### SEV-0 — Hard blockers

| # | File:line | Criterion | Evidence | Fix |
|---|-----------|-----------|----------|-----|
| 1 | {path}:{line} | C{n} | "{quote}" | {one-line fix} |

### SEV-1 — Quality

| # | File:line | Criterion | Evidence | Fix |

### SEV-2 — Drift risk

| # | File:line | Criterion | Evidence | Fix |

### SEV-3 — Style

| # | File:line | Criterion | Evidence | Fix |

## Compliance matrix results

| # | Criterion | Verdict | Evidence |
|---|-----------|---------|----------|
| 1 | name valid | PASS | line 2 |
| 2 | description triggering-only | FAIL | "Processes X by reading…" — workflow summary |
| ... | ... | ... | ... |

## Recommendations

1. {Highest-priority remediation.}
2. ...

## Status

DONE
```

## Authoring rules

- Always emit the executive summary even when no findings — record the audit happened.
- Quote evidence verbatim. Never paraphrase.
- File:line citations are mandatory for every finding.
- Sort within each severity by file path, then line number.
- "Recommended action" in summary maps to a single next step (e.g., "Fix SEV-0s, then re-audit; SEV-1s tracked in followup ticket").

## When to fix vs report

`pipeline-auditor` is read-only by default. Apply fixes ONLY when the user explicitly requests it. Even then:

- SEV-0: prefer Edit (targeted) over Write.
- SEV-1: Edit when ≤3 changes per file; Write only if >50% of body changes.
- SEV-2 / SEV-3: report only; let the user decide.


# File: skills\pipeline-auditor-references\references\compliance-matrix.md
----------------------------------------
# Compliance Matrix — Auditor Reference

20-criterion checklist for `pipeline-auditor`. Applied to every file in a pipeline bundle.
Each criterion: PASS / FAIL / PARTIAL / N/A with cited file:line evidence.

## Table of contents

1. Layout & registry (criteria 1–5)
2. Frontmatter (criteria 6–11)
3. Topology (criteria 12–16)
4. Runtime safety (criteria 17–20)

---

## 1. Layout & registry

| # | Criterion | PASS condition |
|---|-----------|----------------|
| 1 | Files under correct scope root | Agents at `agents/superpipelines/{P}/`; skills at `skills/superpipelines/{P}/`; support files at `superpipelines/pipelines/{P}/` — all under the correct scope root resolved by `sk-pipeline-paths` |
| 2 | Registry entry present | `registry.json` in the scope root has an entry for this pipeline with all required fields (`name`, `scope`, `created_at`, `pattern`, `entry_skill`, `agents`, `skills`, `topology_path`, `last_audit`) |
| 3 | Registry consistent with disk | `registry.json[].agents` and `[].skills` match files on disk exactly; `topology_path` resolves to a readable file |
| 4 | Entry skill correctly flagged | `run-{P}/SKILL.md` has `disable-model-invocation: true` AND `user-invocable: true` in frontmatter |
| 5 | Internal skills suppressed | Every skill under `skills/superpipelines/{P}/` other than `run-{P}` has `user-invocable: false` in frontmatter |

## 2. Frontmatter

| # | Criterion | PASS condition |
|---|-----------|----------------|
| 6 | `name` valid | Lowercase + hyphens only, ≤64 chars, matches filename (without `.md`) |
| 7 | `description` triggering-only | Third person, ≤1024 chars, no workflow summary, no first/second person ("I", "you") |
| 8 | `model` appropriate | `sonnet` by default; any non-sonnet model must have a justification comment in the agent body or Architect's Brief |
| 9 | Core agent fields set | `effort` (one of `low/medium/high/xhigh/max`), `maxTurns` (integer), `version` (semver string) all present |
| 10 | `permissionMode` valid | If present: one of `default \| acceptEdits \| plan \| bypassPermissions`; `bypassPermissions` requires an inline justification comment in the agent body |
| 11 | `memory` valid | If present: `none` or `local` only. `memory: project` is a hard SEV-0 violation |

## 3. Topology

| # | Criterion | PASS condition |
|---|-----------|----------------|
| 12 | `topology.json` schema valid | Valid JSON; required top-level keys present; every step has `id`, `depends_on`, `inputs`, `outputs` (see `topology-rules.md` §1) |
| 13 | Agent coverage | Every non-null `step.agent` has a corresponding file; agent `name` frontmatter matches the `agent` field value |
| 14 | Dependency graph integrity | No dangling `depends_on` ids; no orphan steps; topological sort succeeds for non-pattern-3 graphs |
| 15 | Edge consistency | Step inputs reference valid producers; output-input type compatibility preserved where schemas are declared |
| 16 | Spec ↔ tasks coverage | Every acceptance criterion in `spec.md` maps to ≥1 task in `tasks.md`; no orphan tasks (tasks without a corresponding AC) |

## 4. Runtime safety

| # | Criterion | PASS condition |
|---|-----------|----------------|
| 17 | Temp path convention | State and outputs stored at `{ROOT}/superpipelines/temp/{P}/{runId}/` — no `tmp/` or hardcoded absolute paths |
| 18 | No hardcoded absolute paths in agent bodies | Agent bodies reference paths via a scope-root variable (`${SCOPE_ROOT}` or equivalent), never literal `/home/...` or `~/.claude/...` |
| 19 | Write/review isolation honored | Review-role agents (`*-spec-reviewer`, `*-quality-reviewer`) have `disallowedTools: Write, Edit, Bash` (or equivalent) in frontmatter |
| 20 | Cleanup contract present in entry skill | Entry skill body explicitly: (a) writes `status: completed` to `pipeline-state.json` on success, (b) deletes `temp/{P}/{runId}/` on DONE, (c) preserves temp on ESCALATED/FAILED/BLOCKED |

---

## How to use

1. Read each target file with `Read`.
2. Walk criteria 1–20 in order. Mark each PASS / FAIL / PARTIAL / N/A.
3. For every FAIL or PARTIAL: cite the file path, line number, and quoted evidence.
4. Assign severity per `severity-classification.md`.
5. Emit the audit report per `audit-report-template.md`.

Mark PARTIAL when a criterion is half-met (e.g., description has triggering conditions but also contains a workflow summary sentence). Do NOT guess on ambiguous cases — mark PARTIAL and explain.


# File: skills\pipeline-auditor-references\references\fix-templates.md
----------------------------------------
# Fix Templates — Auditor Reference

Canonical fixes for common findings. Use as Edit templates when the user requests remediation.

## Table of contents

1. Description summarizes workflow
2. Agent body >150 lines
3. `permissionMode` in frontmatter
4. `memory: project` / `memory: local`
5. Skill preload includes workflow skill
6. Reviewer agent has Write/Edit
7. Pattern 3 missing iteration cap
8. Hardcoded plugin path
9. Missing capability contract
10. Per-agent Bash hook with global allow

---

## Fix 1 — Description summarizes workflow

**Symptom:** Description includes verbs describing what the skill does ("processes", "reads", "writes").

**Before:**
```yaml
description: Processes Excel files by reading sheets, cleaning data, and generating charts. Use when working with spreadsheets.
```

**After:**
```yaml
description: Use when working with Excel files, spreadsheets, or .xlsx data extraction.
```

## Fix 2 — Agent body >150 lines

**Action:** Split into body + companion `<agent>-references/references/*.md`.

1. Identify the deepest sections (frontmatter schemas, anti-pattern catalogs, decision trees).
2. Move them to `skills/<agent>-references/references/<topic>.md`.
3. In the body, replace the section with a 1–3 line summary + "Read `references/<topic>.md` for detail."
4. Verify body ≤150 lines.

## Fix 3 — `permissionMode` in frontmatter

**Symptom:** Missing `permissionMode` in agent frontmatter.

**Action:** Add `permissionMode` based on the agent's role.

- **Executors:** `permissionMode: acceptEdits`
- **Reviewers/Architects/Auditors:** `permissionMode: plan`

**Example (Executor):**
```yaml
permissionMode: acceptEdits
```

**Example (Reviewer):**
```yaml
permissionMode: plan
```

## Fix 4 — `memory: project` / `memory: local`

**Symptom:** Agent uses `memory: project` (forbidden).

**Action:** Replace `memory: project` with `memory: local` (if persisting cross-run heuristics) or remove it.

**Correct Usage:**
- **Allowed:** `memory: local` (for workers/executors).
- **Forbidden:** `memory: project`.

**Wait:** If the agent needs to persist pipeline-specific state, use `sk-pipeline-state` to write to `pipeline-state.json` instead of relying on model memory.

## Fix 5 — Skill preload includes workflow skill

**Before:**
```yaml
skills:
  - sk-4d-method
  - brainstorming
  - running-a-pipeline
```

**After:**
```yaml
skills:
  - sk-4d-method
```

Workflow skills (`brainstorming`, `running-a-pipeline`, `creating-a-pipeline`) are session-level lazy invocation, not pre-injection. Reference them in body text instead.

## Fix 6 — Reviewer agent has Write/Edit

**Before:**
```yaml
tools: Read, Write, Edit, Glob, Grep
```

**After:**
```yaml
tools: Read, Glob, Grep
disallowedTools: Write, Edit
```

## Fix 7 — Pattern 3 missing iteration cap

**Before (in body):**
```markdown
Loop until tests pass.
```

**After:**
```markdown
Loop bounded by `MAX_ITERATIONS: 3`. After 3 failures without measurable progress (failure count not decreasing), STOP and escalate per `sk-pipeline-patterns` Pattern 3 escalation protocol.
```

## Fix 8 — Hardcoded plugin path

**Before:**
```markdown
Read ~/.claude/agents/code-reviewer.md
```

**After:**
```markdown
Resolve path via `sk-pipeline-paths` using the appropriate scope (local/project/user). Avoid hardcoded absolute paths.
```

## Fix 9 — Missing capability contract

**Action:** Add near top of agent body:

```markdown
# Inputs required: {list of required context fields}
# Output schema: { "status": "DONE|BLOCKED|...", "outputs": [...] }
# Breaking change log: v1.0 — initial release
```

## Fix 10 — Per-agent Bash hook with global allow

**Action:** Remove the hooks block from agent frontmatter when plugin `settings.json` already has `Bash(*)` in `permissions.allow`. Verify before removing — without the global allow, removing the hook breaks the agent.


# File: skills\pipeline-auditor-references\references\severity-classification.md
----------------------------------------
# Severity Classification — Auditor Reference

Findings classified into four severity tiers.

| Severity | Definition | Block ship? |
|----------|-----------|-------------|
| **SEV-0** | Hard blocker — pipeline will fail or produce silent data loss | YES |
| **SEV-1** | Quality issue — degraded behavior, wasted tokens, drift risk | Should fix before merge |
| **SEV-2** | Drift risk — works today, fragile under common changes | Track for next iteration |
| **SEV-3** | Style — token over-budget, suboptimal section ordering, missing examples | Optional |

---

## SEV-0 examples

- Subagent attempts to spawn children (`SUB_AGENT_SPAWNING: FALSE` violated).
- `memory: project` in agent frontmatter.
- `permissionMode: bypassPermissions` without inline justification in agent body.
- `memory: local` on a reviewer agent (reviewers must not persist heuristics).
- Tool churn mid-session (skills list mutated, tools added/removed).
- Missing required-field in plugin manifest.
- Reviewer agent has `Write` or `Edit` enabled (write/review isolation broken).
- Stage 2 dispatch without Stage 1 PASS gate.
- Worktree destroy without commit-before-destroy step.

## SEV-1 examples

- Agent body >150 lines.
- Skill body >500 lines.
- No output contract declared.
- Vague identity / no single goal.
- Over-tooled subagent (≥10 tools, most unused).
- Description not third-person.
- Missing `skills:` preload when 4D / SDD warranted.
- Pattern 3 used without max-iterations cap.
- `tasks.md` missing acceptance criteria for some tasks.

## SEV-2 examples

- No automated success criteria for agent self-verification.
- Generic chain-of-thought without role-specific framing.
- Token waste (boilerplate prose, redundant examples).
- Missing uncertainty permission ("if you don't know, ask").
- References nested >1 level deep from SKILL.md.
- Reference file >100 lines without ToC.
- Description >1024 chars (truncation).

## SEV-3 examples

- Suboptimal section ordering (Quick Reference before Overview).
- Slight token over-budget vs. peer agents.
- Missing concrete code example.
- Unix path inconsistency (Windows backslashes used in body).
- Inconsistent pronouns across sections.
- Stale model IDs cited in examples (e.g., `claude-3-5-sonnet`).

---

## Severity assignment rules

- A SEV-0 in any file blocks the pipeline. Surface immediately.
- SEV-1s aggregate per agent — three SEV-1s in one agent escalates to SEV-0 review (architectural rewrite warranted).
- A SEV-2 that compounds across multiple agents (e.g., all agents missing self-verification) is a SEV-1 architectural concern.
- SEV-3 issues are reported but never block.

## Reporting format

In the audit report, group findings by severity with most-severe first. Each finding includes:

- File path + line range.
- Compliance matrix criterion # (if applicable).
- Quoted evidence.
- Suggested fix (use `references/fix-templates.md`).


# File: skills\pipeline-auditor-references\references\topology-rules.md
----------------------------------------
# Topology Rules — Auditor Reference

Graph-level checks applied by `pipeline-auditor` on `topology.json` and the surrounding file bundle.
These are distinct from the 20-criterion compliance matrix and are run in addition to it.

## Table of contents

1. Schema check
2. Agent coverage
3. Edge consistency
4. Cycle rules
5. Entry-skill contract
6. Registry consistency

---

## 1. Schema check

`topology.json` must be valid, parseable JSON containing all required fields:

```json
{
  "pipeline": "<name>",
  "version": "1.0",
  "pattern": "<1|2|2b|3|4|5>",
  "steps": [
    {
      "id": "<step-id>",
      "name": "<human-readable name>",
      "agent": "<agent-name or null>",
      "skill": "<skill-relative-path or null>",
      "inputs": ["<step-id-ref or literal-description>"],
      "outputs": ["<step-id-ref or literal-description>"],
      "parallel_group": "<group-id or null>",
      "depends_on": ["<step-id>"]
    }
  ],
  "entry_skill": "run-{P}"
}
```

**FAIL criteria:** JSON parse error; missing required top-level key (`pipeline`, `version`, `pattern`, `steps`, `entry_skill`); invalid `pattern` value; any step missing `id`, `depends_on`, `inputs`, or `outputs`.

---

## 2. Agent coverage

For every step where `step.agent` is non-null:

- A file must exist at `agents/superpipelines/{P}/{step.agent}.md`.
- The agent file's `name` frontmatter field must match `step.agent` exactly.

**FAIL:** Agent file missing, or `name` frontmatter does not match the `agent` field value.

---

## 3. Edge consistency

For every step S:

- Every entry in `S.depends_on` must reference a valid `id` in the same `steps` array.
- Every step must be reachable via `depends_on` chains from at least one entry point (no orphan steps).
- When input/output schemas are declared as structured objects (not bare strings), the producer's declared output type must match the consumer's declared input type.

**FAIL:** Dangling `depends_on` reference; orphan step (no path from any predecessor leads to it); input-output type mismatch on typed edges.

---

## 4. Cycle rules

- **Non-iterative patterns (1, 2, 2b, 4, 5):** The dependency graph must be acyclic (valid DAG). Any cycle is SEV-0.
  - Check via topological sort. If topo-sort fails → SEV-0.
- **Iterative pattern (3):** Exactly ONE back-edge is expected (the loop-back from the fixer to the tester/entry). More than one back-edge is SEV-1 (unintended additional cycle).

---

## 5. Entry-skill contract

- `topology.json["entry_skill"]` must equal `run-{P}` (where `{P}` is the pipeline name).
- The corresponding SKILL.md must exist at `skills/superpipelines/{P}/run-{P}/SKILL.md`.
- That SKILL.md frontmatter must contain:
  - `disable-model-invocation: true`
  - `user-invocable: true`
- **All other** skills under `skills/superpipelines/{P}/` must have `user-invocable: false`.

**FAIL:** Entry skill path mismatch; missing `disable-model-invocation` or `user-invocable` on entry skill; internal step skill missing `user-invocable: false`.

---

## 6. Registry consistency

- `registry.json` (in the appropriate scope root) must contain an entry for this pipeline.
- `registry.json[].agents` must list exactly the agent files present on disk under `agents/superpipelines/{P}/`.
- `registry.json[].skills` must list exactly the skill directories present on disk under `skills/superpipelines/{P}/`.
- `registry.json[].topology_path` must resolve to a readable `topology.json`.

**FAIL:** Registry missing entry; agent or skill list out of sync with disk; `topology_path` not resolvable.

---

## Severity mapping

| Rule violated | Severity |
|---------------|----------|
| Invalid or unparseable `topology.json` schema | SEV-0 |
| Agent file missing for a step | SEV-0 |
| Orphan step (unreachable) | SEV-0 |
| Cycle in non-iterative pattern | SEV-0 |
| Dangling `depends_on` id | SEV-0 |
| Entry skill file missing | SEV-0 |
| Entry skill missing `disable-model-invocation: true` | SEV-0 |
| Input-output type mismatch on typed edge | SEV-1 |
| Extra back-edge in pattern-3 topology | SEV-1 |
| Registry agent/skill list stale (out of sync with disk) | SEV-1 |
| Internal step skill missing `user-invocable: false` | SEV-2 |
| Entry skill missing `user-invocable: true` | SEV-2 |
| Registry `last_audit` null or >7 days old | SEV-3 |


# File: skills\pipeline-runner-references\references\dispatch-protocols.md
----------------------------------------
# Dispatch Protocols — Pipeline-Runner Reference

How `running-a-pipeline` dispatches workers and reviewers per pattern. Maps the canonical patterns from `sk-pipeline-patterns` to concrete `Task` calls.

## Table of contents

1. Common dispatch shape (Claude Code)
2. Pattern 1 — Sequential
3. Pattern 2 / 2b — Parallel Fan-Out
4. Pattern 3 — Iterative Loop
5. Pattern 4 — Human-Gated
6. Pattern 5 — Spec-Driven Development
7. Status protocol handling

---

## Common dispatch shape (Claude Code)

```
Task(
  subagent_type="pipeline-task-executor",
  description="Implement T-1: {short_name}",
  prompt="""
    Inputs:
      - task_text: <extracted from tasks.md>
      - spec_path: {ROOT}/superpipelines/pipelines/{P}/spec.md
      - plan_path: {ROOT}/superpipelines/pipelines/{P}/plan.md
      - project_context: <relevant files / commands>

    Output: emit one of DONE / DONE_WITH_CONCERNS / NEEDS_CONTEXT / BLOCKED with the agent's output schema.
  """
)
```

## Pattern 1 — Sequential

```
state.current_phase = 0
for phase in [Agent_A, Agent_B, Agent_C]:
  result = Task(phase, prompt with prior phase's output paths)
  if result.status != "DONE": handle per status protocol
  state.update(phase done, outputs=result.outputs)
```

## Pattern 2 / 2b — Parallel Fan-Out

Dispatch all branch workers in a SINGLE message block (true parallelism).

```
# Single message:
Task(Agent_A, ...)
Task(Agent_B, ...)
Task(Agent_C, ...)
# Wait for all results.
results = await all
if any(r.status != "DONE"): handle per status protocol per branch
Task(Merger, prompt with [out_a_path, out_b_path, out_c_path])
```

## Pattern 3 — Iterative Loop

```
for iteration in 1..MAX_ITERATIONS (3):
  test_result = Task(Tester, ...)
  if test_result.status == "DONE" and tests passed: break
  diagnosis = Task(Analyzer, prompt with test_result.outputs)
  if diagnosis says architectural: HARD-GATE escalate
  fix = Task(Fixer, prompt with diagnosis.outputs)
  if fix.status != "DONE": handle per status protocol
  if iteration >= 2 and failure_count_not_decreasing: HARD-GATE escalate
else:
  state.status = "escalated"
  surface to user
```

## Pattern 4 — Human-Gated

```
result = Task(Agent_A, ...)
write outputs
gate_response = AskUserQuestion("Phase 1 complete. APPROVE / REJECT / REVISE?")
match gate_response:
  APPROVE → continue
  REJECT  → state.status = "failed", surface to user
  REVISE  → Task(Agent_A, prompt = "REVISION: {feedback} + read {original_files}")
```

## Pattern 5 — Spec-Driven Development

```
# Phase 1-3
Task(pipeline-architect, ...) → spec.md, plan.md, tasks.md

# Phase 4 — preflight validation
analyze tasks.md: every AC covered? no orphans? no cycles?
if validation fails: BLOCK; ask architect to revise

# Phase 4b — HARD-GATE human approval
gate = AskUserQuestion("Spec and tasks written. Review before parallel implement. APPROVE / REVISE?")
if REVISE: route per 4D feedback table → re-spec or re-plan

# Phase 5 — parallel implement (per task)
for each task in tasks.md (respecting dependencies):
  worktree = create worktree per sk-worktree-safety
  exec_result = Task(pipeline-task-executor, prompt with extracted task text + worktree path)
  if exec_result.status != "DONE": handle per status protocol
  
  # Stage 1
  spec_result = Task(pipeline-spec-reviewer, prompt with spec.md path + exec_result.outputs)
  if spec_result.verdict == "FAIL":
    Task(pipeline-task-executor, prompt = "FIX: {spec_result.under_build + over_build}")
    re-Stage-1
  
  # Stage 2 (only if Stage 1 PASSed)
  qual_result = Task(pipeline-quality-reviewer, prompt with spec_result.verdict + exec_result.outputs)
  if qual_result.verdict == "FAIL" with critical/major:
    Task(pipeline-task-executor, prompt = "FIX: {qual_result.issues}")
    re-Stage-1 (full re-review, not just Stage 2)
  
  # Commit
  commit changes; merge to integration branch

# Phase 6 — reconcile
update pipeline state (via sk-pipeline-state) with all task outcomes
# Temp dirs are deleted on DONE; preserved on escalation/failure
```

## Status protocol handling

| Worker status | Orchestrator action |
|---------------|---------------------|
| `DONE` | Proceed to next phase. |
| `DONE_WITH_CONCERNS` | Read concerns. If correctness/scope: address before review. If observational: proceed. |
| `NEEDS_CONTEXT` | Identify missing context; re-dispatch with same model + added context. |
| `BLOCKED` | (1) provide more context; (2) higher effort/model; (3) decompose; (4) escalate. NEVER retry same approach. |

NEVER ignore a non-`DONE` status. NEVER force a re-dispatch without addressing the root cause.


# File: skills\pipeline-runner-references\references\escalation.md
----------------------------------------
# Escalation Protocol — Pipeline-Runner Reference

When and how `running-a-pipeline` escalates to a human. Two main triggers: Pattern 3 iteration cap and `BLOCKED` status that can't be resolved.

## Table of contents

1. Pattern 3 escalation triggers
2. What escalation looks like
3. `BLOCKED` status escalation
4. Worktree handling on escalation
5. Pattern 4 fallback
6. Reporting to user
7. Red Flags — STOP

---

## Pattern 3 escalation triggers

The orchestrator MUST escalate when ANY of these conditions hold:

1. **Iteration cap reached:** 3 iterations completed; tests still failing.
2. **Architectural signal:** Each fix reveals a failure in a NEW location (not the same failure improving).
3. **No measurable progress:** Failure count not decreasing for 2 consecutive iterations.

```
escalate when:
  iteration_count >= 3
  OR (iteration_count >= 2 AND new_failure_locations != prior_failure_locations)
  OR (iteration_count >= 2 AND failure_count[-1] >= failure_count[-2])
```

## What escalation looks like

```bash
# 1. Update state
TEMP_DIR="${SCOPE_ROOT}/superpipelines/temp/${PIPELINE_NAME}/${RUN_ID}"
STATE_FILE="${TEMP_DIR}/pipeline-state.json"
STATE=$(cat "$STATE_FILE" | jq \
  --arg reason "Pattern 3 iteration cap" \
  --arg last_failure "$LAST_FAILURE_SUMMARY" \
  '.status = "escalated"
   | .metadata.escalation_reason = $reason
   | .metadata.last_failure = $last_failure
   | .metadata.iterations = '"$ITERATION_COUNT"'
   | .metadata.attempted_fixes = '"$ATTEMPTED_FIXES_JSON")
echo "$STATE" > "${STATE_FILE}.tmp"
mv "${STATE_FILE}.tmp" "$STATE_FILE"

# 2. Surface to user (no auto-resume)
cat <<EOF
Pipeline ESCALATED.

Reason: ${ESCALATION_REASON}
Iterations: ${ITERATION_COUNT}
Last failure: ${LAST_FAILURE_SUMMARY}
Attempted fixes: ${ATTEMPTED_FIXES}

State preserved at ${TEMP_DIR}/pipeline-state.json.

Suggested next steps:
  - Review the diagnosis history in metadata.attempted_fixes
  - Re-architect the failing component
  - Run /superpipelines:audit-pipeline on the spec/tasks if specs were drifting
  - When ready, restart with: rm -rf ${TEMP_DIR} && /superpipelines:run-pipeline
EOF
```

## `BLOCKED` status escalation

When a worker reports `BLOCKED`, the orchestrator follows a 4-step ladder:

```
1. CONTEXT problem? → provide more context, re-dispatch with same model.
2. REASONING problem? → re-dispatch with higher effort or more capable model.
3. TASK TOO LARGE? → decompose into smaller tasks via pipeline-architect, re-dispatch each.
4. ARCHITECTURAL problem? → escalate to human. DO NOT retry same approach.
```

Track which step has been tried in `metadata.blocked_resolution_attempts`:

```json
{
  "blocked_resolution_attempts": [
    { "step": 1, "outcome": "still_blocked", "added_context": "spec.md, plan.md" },
    { "step": 2, "outcome": "still_blocked", "effort_raised_to": "high" }
  ]
}
```

After step 4 escalation, surface to user with the full attempt history.

## Worktree handling on escalation

`sk-worktree-safety` Step 4 still applies. Before any cleanup:

```bash
cd "$WORKTREE_PATH"
if ! git diff --quiet || ! git diff --cached --quiet; then
  git add -A
  git commit -m "wip: pipeline escalation checkpoint at iteration ${ITERATION_COUNT}"
fi
# Do NOT remove worktree on escalation — user may want to inspect or continue manually.
echo "Worktree preserved at $WORKTREE_PATH for human inspection."
```

## Pattern 4 fallback

If Pattern 3 escalates and the user wants to continue manually but with safety:

```
state.pattern = "4"  # switch to human-gated
state.status = "running"
re-dispatch the failing phase as Pattern 4 (gate before each modification)
```

## Reporting to user

Escalation messages must include:

- Reason (one sentence).
- Concrete evidence (test failures, error messages).
- Attempted fixes summary.
- Absolute path to preserved state and worktree.
- 2–3 concrete next-step options.

## Red Flags — STOP

- "One more iteration should do it" → STOP. The escalation triggers exist precisely to prevent this. Trust the protocol.
- "Let me silently re-dispatch with a different prompt" → NO. Re-dispatch counts as a new iteration; honor the cap.
- "I'll skip the worktree commit, the failure is the user's problem" → STOP. `WORKTREE_MERGE_REQUIRED: TRUE` applies even on escalation. Commit, then preserve.


# File: skills\pipeline-runner-references\references\state-management.md
----------------------------------------
# State Management — Pipeline-Runner Reference

How `running-a-pipeline` writes and reads pipeline state. Companion to `sk-pipeline-state` (which defines the schema).

## Table of contents

1. Read-on-startup flow
2. Initialize new state
3. Atomic write pattern
4. Phase transitions
5. Resume protocol
6. Concurrent pipeline detection
7. Metadata fields used by runner
8. Cleanup on success
9. Cleanup on failure / escalation

---

## Read-on-startup flow

```
1. Resolve scope root via sk-pipeline-paths
2. Check for existing state in <scope-root>/superpipelines/temp/{P}/
   ├── No run dirs → fresh start; proceed to "initialize new state"
   ├── Found run dir with status: "running" AND started_at < 1h ago → live; refuse to start new
   ├── Found run dir with status: "running" AND started_at > 1h ago → crashed; prompt user (resume/restart/abort)
   ├── status: "completed" → "already done"; exit
   ├── status: "escalated" or "failed" → surface to human; do NOT auto-resume
   └── parse error → escalate to human; do NOT auto-resume
```

## Initialize new state

```bash
PIPELINE_NAME="my-pipeline"
SCOPE_ROOT=$(# resolved by sk-pipeline-paths)
RUN_ID=$(uuidgen)
PIPELINE_ID=$(uuidgen)
NOW=$(date -u +%Y-%m-%dT%H:%M:%SZ)
TEMP_DIR="${SCOPE_ROOT}/superpipelines/temp/${PIPELINE_NAME}/${RUN_ID}"
mkdir -p "$TEMP_DIR"
cat > "${TEMP_DIR}/pipeline-state.json.tmp" <<EOF
{
  "pipeline_id": "${PIPELINE_ID}",
  "pipeline_name": "${PIPELINE_NAME}",
  "scope_root": "${SCOPE_ROOT}",
  "run_id": "${RUN_ID}",
  "started_at": "${NOW}",
  "pattern": "${PATTERN}",
  "status": "running",
  "current_phase": 0,
  "phases": [...],
  "metadata": {}
}
EOF
mv "${TEMP_DIR}/pipeline-state.json.tmp" "${TEMP_DIR}/pipeline-state.json"
```

## Atomic write pattern

EVERY state update follows the write-temp-then-rename pattern:

```bash
TEMP_DIR="${SCOPE_ROOT}/superpipelines/temp/${PIPELINE_NAME}/${RUN_ID}"
STATE_FILE="${TEMP_DIR}/pipeline-state.json"
# 1. Read current state
STATE=$(cat "$STATE_FILE")
# 2. Modify (use jq for safety)
NEW_STATE=$(echo "$STATE" | jq --arg phase "$PHASE" '.current_phase = ($phase | tonumber)')
# 3. Write atomically
echo "$NEW_STATE" > "${STATE_FILE}.tmp"
mv "${STATE_FILE}.tmp" "$STATE_FILE"
```

## Phase transitions

| Transition | State change |
|------------|--------------|
| Phase starts | `phases[i].status = "running"` |
| Phase completes successfully | `phases[i].status = "done"`, `phases[i].outputs = [...]`, `current_phase = i+1` |
| Phase fails (recoverable) | `phases[i].status = "failed"`, `phases[i].error = "..."`, retry per status protocol |
| Phase fails (non-recoverable) | `status = "failed"` (top-level), surface to user |
| Pattern 3 hits max iterations | `status = "escalated"`, write last failure summary to metadata |
| Pipeline completes | `status = "completed"` |

## Resume protocol

When user accepts "resume" prompt for crashed state:

1. Validate `pipeline_id` matches what user expected.
2. Find `phases[i]` with `status: "running"`.
3. Reset `phases[i].status = "pending"` (assume in-progress work was lost).
4. If `phases[i]` had partial outputs that survived, prefer to keep them; otherwise re-dispatch from clean.
5. Continue from `current_phase = i`.

## Concurrent pipeline detection

Each pipeline name `{P}` has its own directory under `superpipelines/temp/`. Multiple named pipelines can run concurrently. Within the same `{P}`, only one active run is allowed:

```
echo "Active pipeline detected: $EXISTING_ID started $STARTED_AT"
echo "Cannot start new run of '${PIPELINE_NAME}'. Options:"
echo "  - Wait for active pipeline to finish"
echo "  - Resume the active run (claude /superpipelines:run-pipeline --resume)"
echo "  - Abort the active run (rm -rf ${TEMP_DIR})"
exit 1
```

## Metadata fields used by runner

| Field | Type | Used for |
|-------|------|----------|
| `worktree_root` | string | Path to created worktree (for cleanup) |
| `task_count_target` | integer | Total tasks in pipeline (for progress display) |
| `task_progress` | object | `{ "T-1": "done", "T-2": "running", ... }` |
| `last_failure` | object | Pattern 3 escalation summary |
| `attempted_fixes` | array | Pattern 3 audit trail |

## Cleanup on success

```bash
TEMP_DIR="${SCOPE_ROOT}/superpipelines/temp/${PIPELINE_NAME}/${RUN_ID}"
STATE_FILE="${TEMP_DIR}/pipeline-state.json"
# Pipeline completed — mark status and delete temp dir
NEW_STATE=$(cat "$STATE_FILE" | jq '.status = "completed" | .completed_at = now | todate')
echo "$NEW_STATE" > "${STATE_FILE}.tmp"
mv "${STATE_FILE}.tmp" "$STATE_FILE"
# Temp dirs are deleted on DONE
rm -rf "$TEMP_DIR"
```

## Cleanup on failure / escalation

Do NOT delete the temp directory. Surface to user with the absolute path so they can inspect:

```
echo "Pipeline ESCALATED. State preserved at: ${TEMP_DIR}/pipeline-state.json"
echo "Next steps documented in metadata.last_failure."
```


# File: skills\running-a-pipeline\SKILL.md
----------------------------------------
---
name: running-a-pipeline
description: Use when the user asks to run a pipeline, execute a workflow, list available pipelines, or invokes /superpipelines:run-pipeline. Reads all scope registries, lets the user pick a pipeline, then invokes its entry skill.
---

# Running a Pipeline — Execution Workflow

> Registry-driven launcher for named Superpipelines. Trigger when the user asks to execute a workflow, list available pipelines, or invokes `/superpipelines:run-pipeline`.

<overview>
The Running a Pipeline workflow acts as the central orchestrator for pipeline execution. It manages the full lifecycle from discovery across multiple scopes (Local, Project, User) to state-aware resumption and terminal completion. It ensures that execution is always grounded in the current `pipeline-state.json` and that escalation states are preserved for human review.
</overview>

<glossary>
  <term name="Pipeline Registry">A central `registry.json` tracking all pipelines within a scope.</term>
  <term name="Resume Protocol">The logic used to recover a crashed or interrupted run using its persisted state.</term>
  <term name="Escalated State">A non-terminal status indicating that a pipeline reached a boundary requiring human intervention.</term>
</glossary>

## Workflow Phases

<protocol>
### PHASE 0: DISCOVERY & SELECTION
- Resolve all scope roots via `sk-pipeline-paths`.
- Read and merge `registry.json` files from `local`, `project`, and `user` scopes.
- Present available pipelines to the user and capture the selection (`{ROOT}`, `{P}`, `pattern`).

### PHASE 1: RESUME CHECK
- Check for existing run directories in `{ROOT}/superpipelines/temp/{P}/`.
- **Logic**: If runs exist, prompt the user to start new or resume.
- <HARD-GATE>NEVER auto-resume an `escalated` or `failed` run. Surface the state path and require explicit user review first.</HARD-GATE>

### PHASE 2: STATE INITIALIZATION
- Generate a new `runId` (format: `{P}-{YYYYMMDD-HHMMSS}`).
- Initialize `pipeline-state.json` using the atomic write protocol (write to `.tmp` then rename).
- **Invariants**: Must include `pipeline_id`, `started_at`, and the selected execution `pattern`.

### PHASE 3: ENTRY SKILL DISPATCH
- Invoke the pipeline's entry skill (`run-{P}`).
- **Context Handoff**: Pass absolute paths to the scope root, state file, and topology.
- **Responsibility**: The entry skill owns step dispatch, two-stage review (Stage 1 gates Stage 2), and cleanup.

### PHASE 4: COMPLETION & CLEANUP
- Read final state from `pipeline-state.json`.
- **Status: `completed`**: Delete the temporary run directory and summarize outputs.
- **Status: `escalated/failed`**: **PRESERVE** the temporary directory and state path for debugging and recovery.
</protocol>

<invariants>
- ALWAYS read from the registry before execution to ensure pipeline validity.
- ALWAYS preserve the temp directory on any status other than `completed`.
- NEVER pass full file content to the entry skill; use absolute paths.
- All state updates must utilize the atomic write pattern.
</invariants>

## Red Flags — STOP
- "The previous run was escalated, but I'll restart it anyway." → **STOP**. Read the state first to avoid repeating the failure.
- "There is no registry, I'll search for artifacts manually." → **STOP**. Direct the user to create a managed pipeline.
- "I'll delete the temp directory to keep the workspace clean." → **STOP**. Deletion on non-completion destroys all recovery findings.

## Rationalization Table

<rationalization_table>
| Excuse | Reality |
| :--- | :--- |
| "I'll resume the escalated run." | Escalation signals a boundary the model cannot cross. Resuming without review wastes tokens. |
| "Registry-only lookup is slow." | Searching without a registry is non-deterministic and risks path leakage. |
| "The entry skill is just a wrapper." | The entry skill is the source of truth for step ordering and review gating. |
</rationalization_table>

## Reference Files
- `sk-pipeline-paths/SKILL.md` — Scope root resolution.
- `sk-pipeline-state/SKILL.md` — State schema and recovery rules.
- `sk-write-review-isolation/SKILL.md` — Two-stage review protocol.
- `creating-a-pipeline/SKILL.md` — Pipeline scaffolding.


# File: skills\sk-4d-method\SKILL.md
----------------------------------------
---
name: sk-4d-method
description: Use when an AI pipeline orchestrator or worker faces an ambiguous request, missing slots, or feedback that requires re-entry — the per-invocation Deconstruct/Diagnose/Develop/Deliver wrapper. Reference-only; preload via agent skills frontmatter.
disable-model-invocation: true
user-invocable: false
---

# 4D Method — Per-Invocation Processing Wrapper

> A systematic four-phase framework for processing ambiguous requests, resolving missing context, and handling iterative feedback. Trigger when an agent receives a vague brief or requires precise task deconstruction.

<overview>
The 4D Method (Deconstruct, Diagnose, Develop, Deliver) ensures that every agent invocation begins with a rigorous analysis of intent and constraints. It prevents hallucinations and misaligned outputs by enforcing a "hard gate" on missing information and providing a structured path for re-entry based on feedback.
</overview>

<glossary>
  <term name="4D">Deconstruct → Diagnose → Develop → Deliver.</term>
  <term name="Hard-Gate">A mandatory stop point if critical information (audience, format, goal, constraints, scope) is missing.</term>
  <term name="Re-entry">Returning to a specific 4D phase based on the type of user feedback received.</term>
</glossary>

<protocol>
### 1. DECONSTRUCT (Intent & Entities)
- **Goal**: Strip the request to its core intent.
- Identify noun-level entities, explicit constraints, and target audience.
- Surface implicit assumptions and missing context.
- **HARD-GATE**: If ≥3 critical slots are missing, STOP and ask the user targeted questions.

### 2. DIAGNOSE (Specs & Guardrails)
- **Goal**: Transform vague terms into concrete specifications.
- Replace subjective language ("clean," "professional") with measurable metrics.
- Separate overloaded asks into a numbered sub-task list.
- Anticipate the top 2–3 failure modes and design build-time guardrails.

### 3. DEVELOP (Tactics & Strategy)
- **Goal**: Match the task type to the optimal execution strategy.
- Select the appropriate model (Sonnet/Opus) and effort level.
- Define output format precisely (schemas, bullet counts, code languages).
- Layer constraints using primacy and recency (critical rules first and last).

### 4. DELIVER (Formatting & Scannability)
- **Goal**: Ensure the response is optimized for the user's environment.
- Use an inverted pyramid structure (conclusion first).
- Match the medium (Slack-tight vs. report-structured).
- Provide an actionable next step for the user.
</protocol>

## 4D Feedback Routing

<routing_table>
| Feedback Signal | Re-entry Phase | Rationale |
| :--- | :--- | :--- |
| "Not what I asked" | **Deconstruct** | Misaligned intent or goal. |
| "This is incorrect" | **Diagnose** | Technical failure or missed edge case. |
| "Use a different approach" | **Develop** | Correct intent, wrong implementation strategy. |
| "Format/style change" | **Deliver** | Cosmetic or presentation refinement. |
</routing_table>

## Quick Reference

<quick_reference>
| Phase | Core Question | Key Action |
| :--- | :--- | :--- |
| **Deconstruct** | "What is actually being asked?" | Separate intent from output; surface gaps. |
| **Diagnose** | "Where will this break?" | Replace vague terms; resolve conflicts. |
| **Develop** | "What's the best approach?" | Match strategy to task; define format. |
| **Deliver** | "Is this ready for the user?" | Organize for scannability; match context. |
</quick_reference>

<invariants>
- Run all four phases internally; show them only on explicit request ("show 4D").
- The HARD-GATE in Phase 1 is non-negotiable for high-stakes tasks.
- Match model selection and effort level to the phase requirements per project standards.
</invariants>

## Reference Files

- `sk-pipeline-patterns/SKILL.md` — Pattern 6 definition.
- `sk-spec-driven-development/SKILL.md` — SDD handoff rules.
- `sk-claude-code-conventions/SKILL.md` — Scaling and model selection.


# File: skills\sk-claude-code-conventions\SKILL.md
----------------------------------------
---
name: sk-claude-code-conventions
description: Use when authoring or modifying agents, skills, hooks, or pipeline orchestration — covers Claude 4.6 model selection, adaptive thinking, prompt-cache discipline, frontmatter schemas, and progressive disclosure rules. Reference-only; preload via agent skills frontmatter.
disable-model-invocation: true
user-invocable: false
---

# Claude Code Conventions — 2026 Reference

> Canonical engineering standards for authoring agents, skills, hooks, and pipeline orchestration. Optimizes for Claude 4.6+ model selection, adaptive thinking, prompt-cache discipline, and progressive disclosure.

<overview>
The Claude Code Conventions define the structural and behavioral invariants required for high-performance agentic systems. They prioritize cache stability, context efficiency, and deterministic routing to ensure that complex multi-agent pipelines remain reliable and scalable.
</overview>

<glossary>
  <term name="Adaptive Thinking">Model-driven reasoning scaled by the `effort` parameter.</term>
  <term name="Prompt Caching">A mechanism to persist static context (system prompts, skills) to reduce latency and cost.</term>
  <term name="Progressive Disclosure">Structuring content into layers (Body → References) to minimize context bloat.</term>
</glossary>

## Model & Reasoning Selection

<model_tier_table>
| Tier | Model ID | Application |
| :--- | :--- | :--- |
| **Workhorse** | `claude-sonnet-4-6` | Default for pipelines, agents, and skills. |
| **Deep Reasoning** | `claude-opus-4-7` | High-complexity architecture or auditing tasks. |
| **Triage/Batch** | `claude-haiku-4-5` | High-volume, low-latency classification. |
</model_tier_table>

<invariant>
Pipelines must enforce `MODEL_SELECTION: SONNET_ONLY`. Scale reasoning depth via the `effort` parameter rather than model switching.
</invariant>

## Caching & Context Discipline

<protocol>
### 1. CACHE STABILITY
- **Static First**: Order context as System Prompt → Skills → Tools → Conversation History.
- **Invariant Toolsets**: Never mutate the tool or skill list mid-session; doing so invalidates the entire prefix.
- **Static Headers**: Avoid dynamic timestamps or mutable data in the static system prefix.

### 2. CACHE BREAKPOINTS
- Utilize up to 4 `cache_control` breakpoints.
- Place the final breakpoint on the last block that remains identical across requests.
- Use 1-hour TTL for agentic loops to prevent cache expiration between turns.
</protocol>

## Artifact Schemas

### Skill Frontmatter
<invariant>
`SKILL.md` bodies must not exceed 500 lines. Descriptions must use third-person voice and focus strictly on triggering conditions.
</invariant>

```yaml
name: {lowercase-hyphens}
description: {triggering-only, third person}
effort: {low | medium | high | xhigh | max}
disable-model-invocation: {boolean}
user-invocable: {boolean}
```

### Agent Frontmatter
<invariant>
Agent bodies must not exceed 150 lines. Depth must be moved to companion `<agent>-references/references/*.md` files.
</invariant>

```yaml
name: {identifier}
description: {action-oriented trigger}
effort: {high for architects, medium for workers}
isolation: worktree
skills: [sk-4d-method, sk-spec-driven-development]
```

## Progressive Disclosure Checklist

<checklist>
- [ ] `SKILL.md` body ≤500 lines.
- [ ] References are exactly one level deep from `SKILL.md`.
- [ ] References >100 lines include a Table of Contents.
- [ ] Descriptions are third-person and triggering-only.
- [ ] Examples are concrete and specific to the domain.
</checklist>

<invariants>
- NEVER use `memory: project` in agent frontmatter.
- Resolve all relative paths via `${CLAUDE_PLUGIN_ROOT}` or `${CLAUDE_PLUGIN_DATA}`.
- All pipeline state must be persisted to the canonical `pipeline-state.json` location.
</invariants>

## Reference Files

- `sk-pipeline-state/SKILL.md` — State management rules.
- `sk-pipeline-paths/SKILL.md` — Scope-aware path resolution.
- `sk-4d-method/SKILL.md` — Per-invocation wrapper.
- `sk-spec-driven-development/SKILL.md` — SDD protocol.


# File: skills\sk-dynamic-routing\SKILL.md
----------------------------------------
---
name: sk-dynamic-routing
description: Use when determining the appropriate LLM for a specific pipeline stage. Defines category constraints for dynamic model routing, allowing specific utility and planning agents to diverge from the Sonnet default.
disable-model-invocation: true
user-invocable: false
---

# Dynamic Model Routing — Intent-Based Capability Mapping

> Provides the ruleset for dynamically assigning Large Language Models based on the task intent category. Trigger when architecting new pipelines or configuring subagents to ensure cost-efficiency and optimal reasoning paths.

<overview>
While Superpipelines maintains `claude-sonnet-4-6` as the baseline default for all implementation workers, certain specialized roles (e.g., fast audits, deep architectural planning, vision analysis) benefit from dynamic routing. This skill defines the permitted categories and fallback chains for those overrides.
</overview>

<glossary>
  <term name="Category">An intent-based tag that dictates the model requirement (e.g., `quick-audit`, `deep-plan`).</term>
  <term name="Fallback Chain">The sequence of alternative models if the primary is unavailable or rate-limited.</term>
</glossary>

## Category Mappings

<categories_table>
| Category | Primary Model | Fallback Chain | Use Case |
| :--- | :--- | :--- | :--- |
| **`default`** | `claude-sonnet-4-6` | *None* | Implementation, general tasks, and task-execution. |
| **`deep-plan`** | `claude-opus-4-7` | `gpt-5.4` -> `sonnet-4-6` | High-stakes architectural planning (e.g., `pipeline-architect`). |
| **`quick-audit`** | `claude-haiku-4-5-20251001` | *None* | Fast, broad pattern matching and codebase grepping. |
| **`visual`** | `gemini-3.1-pro` | `gpt-5.4` | Tasks requiring image processing, UI screenshots, or diagram analysis. |
</categories_table>

## Routing Protocol

<protocol>
### 1. EVALUATE INTENT
- Determine the nature of the specific task or agent role.
- If it is standard code implementation or a functional review, the category MUST be `default`.

### 2. ASSIGN CATEGORY
- If the role is exclusively planning, architecture, or deep conceptual alignment, assign `deep-plan`.
- If the role is pure read-only utility (fast file searching, lint aggregation), assign `quick-audit`.
- If the role requires interpreting screenshots, assign `visual`.

### 3. CONFIGURATION OVERRIDE
- When generating an agent or scaffold, set the `model:` field in the frontmatter according to the primary model of the selected category.
- Add a comment or meta-tag noting the category intent for future auditing.
</protocol>

<invariants>
- NEVER override `pipeline-task-executor` or `pipeline-spec-reviewer`; they MUST remain on `claude-sonnet-4-6` (`default`).
- NEVER route to a model not explicitly defined in the category mapping table.
- Maintain `MODEL_SELECTION: DYNAMIC_DEFAULT_SONNET` adherence.
</invariants>


# File: skills\sk-hashline-protocol\SKILL.md
----------------------------------------
---
name: sk-hashline-protocol
description: Use whenever performing file mutations to prevent stale-line edits. Mandates appending content hashes to read lines and verifying those hashes before committing an edit operation to a worktree.
disable-model-invocation: true
user-invocable: false
---

# Hashline Protocol — Anchored Edit Verification

> Enforces a hash-anchored modification protocol to prevent source code corruption. Invoked during the `DEVELOP` and `IMPLEMENT` phases to ensure code edits target verifiable content hashes rather than fragile, static line numbers.

<overview>
The Hashline Protocol ensures atomic mutation safety. By tagging every line read with a 16-character content identifier hash, the system guarantees that edits only occur if the underlying file state matches the expected state, eliminating stale-line and whitespace-drift errors.
</overview>

<glossary>
  <term name="Content Identifier Hash">A 16-character string appended to a line representing its exact content state.</term>
  <term name="Hashline Edit">A mutation operation referencing the hash rather than line number.</term>
</glossary>

## Protocol Execution

<protocol>
### 1. READ WITH HASHES
- When reading target files, request the content to be annotated with line hashes.
- Format expectation: `<line_number>#<HASH>| <content>`

### 2. PREPARE THE EDIT
- Identify the exact block of code to be modified.
- Include the explicit `<HASH>` identifiers in your edit payload alongside the target content.

### 3. VERIFICATION (PRE-WRITE)
- The harness calculates the current hash of the target lines before writing.
- If the current hash does NOT match the requested hash, the write operation is **REJECTED**.
- In case of rejection, the agent must re-read the file to acquire fresh hashes and re-attempt the edit.

### 4. COMMIT
- If the hashes match, the mutation is committed to the isolated worktree for subsequent Stage 1 functional review.
</protocol>

<invariants>
- NEVER target a file edit using static line numbers; always anchor to the Content Identifier Hash.
- ALWAYS re-read the file upon a hash mismatch; never guess or synthesize the current state.
- Ensure the edit is fully localized to the targeted hashes to prevent over-build or collateral mutations.
</invariants>

## Reference Files

- `${CLAUDE_PLUGIN_ROOT}/skills/sk-worktree-safety/SKILL.md` — Isolated worktree principles.


# File: skills\sk-hierarchical-context\SKILL.md
----------------------------------------
---
name: sk-hierarchical-context
description: Use when initiating or updating localized PIPELINE-CONTEXT.md files across a repository. Crawls the project to generate token-efficient context maps summarizing directory contents and architectural boundaries.
disable-model-invocation: true
user-invocable: false
---

# Hierarchical Context Maps — Distributed Architecture Context

> Generates and maintains localized `PIPELINE-CONTEXT.md` files throughout the project tree. Trigger during the `/superpipelines:init-deep` command or during the PREFLIGHT phase of new pipeline creation to ensure agents have lean, relevant context without bloated global prompts.

<overview>
The Hierarchical Context system distributes architectural knowledge across the repository instead of centralizing it in a single massive file. By placing a `PIPELINE-CONTEXT.md` in relevant subdirectories, agents operating within that directory automatically acquire the necessary context for their specific scope, conserving tokens and improving reasoning focus.
</overview>

<glossary>
  <term name="Context Map">A localized markdown file (`PIPELINE-CONTEXT.md`) describing the purpose and boundaries of its resident directory.</term>
  <term name="Deep Initialization">The recursive process of generating context maps for all significant project directories.</term>
</glossary>

## Protocol Execution

<protocol>
### 1. DIRECTORY TRAVERSAL
- Identify all significant architectural boundaries (e.g., `src/`, `components/`, `api/`, `utils/`).
- Skip ignored directories (e.g., `node_modules/`, `.git/`, `dist/`).

### 2. CONTEXT GENERATION
For each significant directory, create a `PIPELINE-CONTEXT.md` adhering to strict LLM-readability standards (Scribius format):
- **H1-First & Summary:** Begin with an H1 header (`# Directory Name`) followed immediately by a blockquote summary (`> `).
- **Cache-Stable Ordering:** Place static context (purpose, constraints) before any volatile elements.
- **XML-Anchored Content:** Wrap structured information in semantic XML envelopes:
  - `<directory_purpose>`: A concise summary of what the directory does.
  - `<architectural_constraints>`: Specific rules (e.g., "no database access in components").
  - `<key_exports>`: Bulleted list of primary modules and their responsibilities.
  - `<pipeline_relationship>`: How this directory interacts with the broader system.
- **Voice & Tone:** Enforce third-person impersonal voice, positive scoping, and unambiguous noun anchors (never use "this" or "it" without a noun). Omit all preambles.

### 3. ROOT CONTEXT INJECTION
- Generate a root-level `PIPELINE-CONTEXT.md` that serves as the entry point, detailing the overall system architecture and linking to subdirectory context maps.

### 4. MAINTENANCE
- When files are significantly refactored during pipeline execution, flag the relevant `PIPELINE-CONTEXT.md` for a required update.
</protocol>

<invariants>
- NEVER generate a single monolithic context file; always distribute context hierarchically.
- ALWAYS respect `.gitignore` when traversing the repository.
- Ensure context maps are concise and free of redundant code snippets (use summaries).
- ALWAYS format `PIPELINE-CONTEXT.md` files according to Scribius standards (XML envelopes, H1-first, impersonal voice).
</invariants>

## Reference Files

- `${CLAUDE_PLUGIN_ROOT}/skills/sk-pipeline-paths/SKILL.md` — Path resolution guidelines.


# File: skills\sk-pipeline-paths\SKILL.md
----------------------------------------
---
name: sk-pipeline-paths
description: Use when resolving scope-aware file paths for superpipelines artifacts — agents, skills, support files, temp directories, or the pipeline registry. Reference whenever scope (local, project, user) and a pipeline name are known and an absolute path is needed.
disable-model-invocation: true
user-invocable: false
---

# Pipeline Path Resolver — Scope-Aware Layout

> Resolves absolute file paths for Superpipelines artifacts across local, project, and user scopes. Trigger when creating or accessing agents, skills, temporary directories, or the pipeline registry.

<overview>
The Path Resolver enforces a canonical layout for the Superpipelines v2 architecture. It eliminates hardcoded paths by providing scope-dependent roots and templates for every artifact type, ensuring consistency across diverse workspace environments.
</overview>

<glossary>
  <term name="Scope Root">The base directory (`.claude/` or `~/.claude/`) where artifacts are persisted.</term>
  <term name="Pipeline Registry">A central `registry.json` file tracking all pipelines within a specific scope.</term>
  <term name="Staging Directory">A temporary `temp/{P}/edit-{ts}/` directory used for atomic mutations.</term>
</glossary>

## Scope Roots & Git Integration

<scope_roots_table>
| Scope | Physical Root | Git Status | Persistence |
| :--- | :--- | :--- | :--- |
| **Project** | `<workspace>/.claude/` | Committed | Shared with the team. |
| **Local** | `<workspace>/.claude/` | Ignored | Machine-specific/temporary. |
| **User** | `~/.claude/` | External | Global across all workspaces. |
</scope_roots_table>

<invariant>
`project` and `local` scopes share the same physical directory; the distinction is managed via `.gitignore` entries for `.claude/`.
</invariant>

## Path Templates

<path_templates>
| Artifact Type | Path Template (relative to ROOT) |
| :--- | :--- |
| **Registry** | `superpipelines/registry.json` |
| **Spec/Plan/Tasks** | `superpipelines/pipelines/{P}/` |
| **Topology Graph** | `superpipelines/pipelines/{P}/topology.json` |
| **Audit Report** | `superpipelines/pipelines/{P}/audit/latest.md` |
| **Entry Skill** | `skills/superpipelines/{P}/run-{P}/SKILL.md` |
| **Step Skill** | `skills/superpipelines/{P}/{step}/SKILL.md` |
| **Step Agent** | `agents/superpipelines/{P}/{agent-name}.md` |
| **Pipeline State** | `superpipelines/temp/{P}/{runId}/pipeline-state.json` |
| **Staged Edits** | `superpipelines/temp/{P}/edit-{ts}/` |
</path_templates>

## Pipeline Name Constraints

<constraints>
- **Format**: Lowercase alphanumeric and hyphens only (`[a-z0-9-]+`).
- **Length**: Maximum 48 characters to accommodate the `run-` prefix within the 64-character skill limit.
- **Uniqueness**: Must be unique within the chosen scope's `registry.json`.
</constraints>

<invariants>
- NEVER hardcode absolute paths; always resolve via the current `{ROOT}` and `{P}` context.
- ALWAYS expand `~` to the absolute home directory path before passing it to agent spawn prompts.
- Atomic mutations MUST use the staged edits path before promotion to final locations.
</invariants>

## Reference Files

- `sk-pipeline-state/SKILL.md` — State persistence schema.
- `sk-claude-code-conventions/SKILL.md` — Frontmatter and directory rules.


# File: skills\sk-pipeline-patterns\SKILL.md
----------------------------------------
---
name: sk-pipeline-patterns
description: Use when selecting an execution pattern for a pipeline (Sequential, Parallel Fan-Out, Iterative Loop, Human-Gated, Spec-Driven) or matching a task's information flow to a topology — distillation of Patterns 1–6. Reference-only; preload via agent skills frontmatter.
disable-model-invocation: true
user-invocable: false
---

# Pipeline Patterns — Selection Reference

> Distills Patterns 1–6 for pipeline topology selection. Trigger when designing the execution flow of a multi-agent system or matching a task's information flow to a canonical architecture.

<overview>
Pipeline Patterns provide standardized architectures for diverse agentic workloads. By selecting the appropriate pattern (Sequential, Parallel, Iterative, Gated, or Spec-Driven), orchestrators ensure deterministic handoffs, manageable context windows, and robust failure recovery.
</overview>

<glossary>
  <term name="Pattern 3 (Iterative Loop)">A fix/heal cycle bounded by max iterations and an escalation protocol.</term>
  <term name="Pattern 5 (Spec-Driven Development)">A multi-phase workflow where a specification acts as a formal contract for parallel implementation.</term>
  <term name="Pattern 6 (4D Wrapper)">A per-invocation processing framework that runs inside all other patterns.</term>
</glossary>

## Pattern Selection Matrix

<pattern_matrix>
| Pattern | Information Flow | Worktree | Best Applied To |
| :--- | :--- | :--- | :--- |
| **1. Sequential** | Linear (A → B → C) | Optional | Strictly dependent sequential phases. |
| **2. Parallel** | Fan-Out / Merge | **Required** | Independent analyses or reviews. |
| **3. Iterative** | Loop (Test → Fix) | **Required** | Fix/heal cycles with defined exit criteria. |
| **4. Gated** | Phase → GATE → User | Selective | Destructive or irreversible operations. |
| **5. Spec-Driven** | Spec → Plan → Implement | **Required** | Large feature work or complex migrations. |
| **6. 4D Method** | Wrapper (Internal) | N/A | Every agent turn within any other pattern. |
</pattern_matrix>

## Pattern 3 — Iterative Loop Protocol

<protocol>
### 1. LOOP EXECUTION
- **Cycle**: Tester (identifies failures) → Analyzer (diagnoses RCA) → Fixer (applies fix) → Restart.
- **Iteration Cap**: Maximum 3 iterations by default.

### 2. ESCALATION (HARD-GATE)
<HARD-GATE>
**STOP** immediately and escalate to the user if:
- Iteration count ≥ 3.
- Failure count does not decrease for 2 consecutive cycles.
- A fix reveals a new failure in a different architectural location (regression).
</HARD-GATE>

### 3. EARLY TERMINATION SIGNALS
- "One more fix should do it" (after 2+ failures).
- "The fix is almost working" (indicates lack of convergence).
</protocol>

## Pattern 5 — Spec-Driven Development (SDD)

<sdd_workflow>
1. **Specify**: Generate `spec.md` (WHAT + WHY).
2. **Plan**: Generate `plan.md` (HOW).
3. **Tasks**: Decompose into `tasks.md`.
4. **Gate**: Mandatory human review of spec and tasks.
5. **Implement**: Parallel execution of tasks with two-stage review.
</sdd_workflow>

## Decision Tree

<decision_tree>
Is the task multi-step with dependencies?
- **NO**: Apply 4D Method and execute directly.
- **YES**:
  - Independent/Mergeable tasks? → **Pattern 2**.
  - Fix/Heal cycle? → **Pattern 3**.
  - Irreversible action? → **Pattern 4** (Human Gate).
  - Feature work? → **Pattern 5** (SDD).
  - Linear dependency? → **Pattern 1**.
</decision_tree>

<invariants>
- Disk-based handoffs (file paths) must be used instead of pasting content between agents.
- Pattern 6 (4D) must execute within every agent turn across all patterns.
- Escalation state must be explicitly written to `pipeline-state.json` on failure.
</invariants>

## Reference Files

- `sk-4d-method/SKILL.md` — Per-invocation wrapper.
- `sk-spec-driven-development/SKILL.md` — SDD implementation details.
- `sk-write-review-isolation/SKILL.md` — Review loop protocol.
- `sk-worktree-safety/SKILL.md` — Parallel isolation rules.
- `references/ai-pipelines-trimmed.md` — Full conventions trimmed for runtime.


# File: skills\sk-pipeline-patterns\references\ai-pipelines-trimmed.md
----------------------------------------
# AI Pipelines — Trimmed Runtime Reference

> Canonical runtime reference for pipeline conventions. Cross-refs to `sk-claude-code-conventions` and `sk-*` skills carry the depth that this file omits.

## Table of contents

1. Core architecture invariants
2. Execution patterns 1–6 (gated)
3. Subagent status protocol
4. Write/review isolation
5. Worktree safety
6. Pipeline state schema + recovery
7. Rationalization resistance
8. Strict conventions essentials
9. Cross-references

---

## 1. Core architecture invariants

- `SUB_AGENT_SPAWNING: FALSE` — Subagents never spawn children. Orchestration lives in top-level skills (`creating-a-pipeline`, `running-a-pipeline`) or the parent session.
- `ANT_SWARM_PRINCIPLE: TRUE` — Prefer many small-context agents over single large-context agents. Reasoning quality degrades around 40–60% context fill.
- `PIPELINE_PHASE_ISOLATION: TRUE` — Tester, Analyzer, Healer (and Executor / Stage-1 Reviewer / Stage-2 Reviewer) are separate instances.
- `WORKTREE_MERGE_REQUIRED: TRUE` — If `isolation: worktree` is used, the orchestrator MUST commit and merge successful changes before worktree destruction. See `sk-worktree-safety`.

Agent definition cap: body ≤150 lines STRICT. Depth lives in companion `<agent>-references/references/*.md` (read on demand).

---

## 2. Execution patterns

Distilled selection table. Full per-pattern details in `sk-pipeline-patterns` SKILL.md.

| # | Name | Information flow | Worktree | Use when |
|---|------|------------------|----------|----------|
| 1 | Sequential | A → file → B → file → C | OPT-IN | Linear, dependent phases |
| 2 | Parallel Fan-Out / Merge | [A, B, C] → D | REQUIRED per branch | Independent analyses converge |
| 2b | Parallel with QA | [QA, Worker_A, Worker_B] | REQUIRED per branch | Concurrent QA validation |
| 3 | Iterative Loop | Tester → Analyzer → Fixer → restart | REQUIRED for loop scope | Fix/heal cycles |
| 4 | Human-Gated | Phase → GATE → APPROVE/REVISE | NEVER for read-only; REQUIRED for modification | Destructive or irreversible |
| 5 | Spec-Driven (SDD) | spec → plan → tasks → GATE → parallel implement | REQUIRED per task | Multi-step features |
| 6 | 4D Wrapper | Per-invocation: Deconstruct→Diagnose→Develop→Deliver | n/a | Inside Patterns 1–5, every turn |

### Pattern 3 escalation protocol (HARD-GATE)

After 3 failed iterations without measurable progress: STOP. Do NOT attempt iteration 4.

Early-stop signal: each fix reveals a new failure in a different location (architectural problem, not a fixable bug).

Action on early stop: escalate to human or invoke Pattern 4. Write current state to `pipeline-state.json` with `status: "escalated"`.

### Pattern 5 human approval gate (HARD-GATE)

Phase 4b — before parallel implementation:

> "Spec and tasks written. Review `spec.md` and `tasks.md` before I begin parallel implementation. [APPROVE | REVISE]"

Wait for APPROVE. If REVISE, return to Phase 1 or 2 based on the feedback type (see `sk-4d-method` feedback routing).

Rationale: Phase 5 dispatches N parallel agents. Misunderstood spec means N agents produce wrong output simultaneously. Gate cost: ~1 minute. Ungated mistake cost: discard all parallel work and restart.

---

## 3. Subagent status protocol

Every agent emits exactly one terminal status before exiting.

| Status | Condition | Orchestrator action |
|--------|-----------|---------------------|
| `DONE` | Task completed; outputs written | Proceed to next phase |
| `DONE_WITH_CONCERNS` | Task done; agent flagged doubts about correctness or scope | Read concerns; address before review if they touch correctness/scope, else proceed |
| `NEEDS_CONTEXT` | Cannot begin — critical info missing | Identify missing context; re-dispatch with same model + added context |
| `BLOCKED` | Cannot complete even with context | (1) provide more context; (2) higher effort/model; (3) decompose; (4) escalate to human. NEVER retry same approach |

Output schemas:

```json
{ "status": "DONE", "outputs": ["{path1}", "{path2}"] }
{ "status": "DONE_WITH_CONCERNS", "concerns": "<text>", "outputs": [...] }
{ "status": "NEEDS_CONTEXT", "missing": "<what is needed>" }
{ "status": "BLOCKED", "reason": "<description>", "attempted": "<what was tried>" }
```

Never ignore a non-`DONE` status. Never re-dispatch without addressing the root cause.

---

## 4. Write/review isolation

`WRITE_REVIEW_ISOLATION: TRUE`. Writer ≠ Reviewer (separate instances). Two stages:

- **Stage 1 (Spec Compliance):** Does output match spec exactly? Under-build AND over-build both fail.
- **Stage 2 (Code Quality):** Idiomatic? Maintainable? Edge cases per spec handled?

<EXTREMELY-IMPORTANT>
Stage 1 MUST pass before Stage 2 begins. Running Stage 2 on spec-noncompliant output is wasted work.
</EXTREMELY-IMPORTANT>

`OVER_BUILD_IS_SPEC_FAILURE` — adding unrequested features fails Stage 1. The reviewer does NOT excuse "useful extras."

`REVIEW_LOOP` — reviewer finds issues → implementer fixes → reviewer re-reviews. Terminate only when reviewer approves.

After any Stage 2 fix, re-run Stage 1 (the fix can break ACs or introduce over-build).

See `sk-write-review-isolation` for full output schemas and review loop.

---

## 5. Worktree safety

4-step protocol when `isolation: worktree` is used:

1. **VERIFY_IGNORED** — `.worktrees/` (or `worktrees/`) is git-ignored. If not, add and commit before creating any worktree.
2. **SETUP_AFTER_CREATE** — auto-detect manifest (`package.json`, `Cargo.toml`, `requirements.txt`, `go.mod`, etc.) and run setup.
3. **VERIFY_BASELINE** — run the full test suite before any implementation. If failing, do not proceed without human approval.
4. **COMMIT_BEFORE_DESTROY** — never `git worktree remove` with uncommitted changes; commit (or stash + commit) first.

See `sk-worktree-safety` for detection signals, per-pattern requirements, and Red Flags.

---

## 6. Pipeline state schema

Path: `<scope-root>/superpipelines/temp/{P}/{runId}/pipeline-state.json` (scope-resolved by `sk-pipeline-paths`, NOT plugin-relative — plugin dirs wipe on update).

```json
{
  "pipeline_id": "<uuid>",
  "pipeline_name": "<P>",
  "scope_root": "<resolved scope root>",
  "run_id": "<uuid>",
  "started_at": "<iso8601>",
  "pattern": "1 | 2 | 2b | 3 | 4 | 5",
  "status": "running | completed | escalated | failed",
  "current_phase": 0,
  "phases": [
    { "index": 0, "name": "<phase>", "status": "pending|running|done|failed", "agent": "<name>", "outputs": ["<path>"], "error": null }
  ],
  "metadata": {}
}
```

Atomic writes: write to `pipeline-state.json.tmp`, then `mv` to final path.

Recovery rules:

- `status: running` AND `started_at < 1h ago` → live; refuse to start new.
- `status: running` AND `started_at > 1h ago` → treat as crashed; prompt user.
- `status: completed` → skip; "already done."
- `status: escalated | failed` → surface to human; do NOT auto-resume.
- Parse error → do NOT auto-resume; escalate.

See `sk-pipeline-state` for full rules and worked examples.

---

## 7. Rationalization resistance

Three mechanisms required in discipline-enforcing content:

1. `<HARD-GATE>` — wraps non-negotiable checkpoints (e.g., max iterations, human approval).
2. `<EXTREMELY-IMPORTANT>` — wraps rules frequently rationalized away. Use sparingly to preserve signal.
3. **Red Flags + Rationalization Table** — bullet list of exact rationalization phrases → corrective action; table of `| Excuse | Reality |`.

See `sk-rationalization-resistance` for tag conventions and authoring rules.

---

## 8. Strict conventions essentials

- `MODEL_SELECTION: SONNET_ONLY` — every pipeline agent is `model: sonnet`. Scale via `effort: low | medium | high | xhigh | max`.
- `PERMISSION_MODE: PER_AGENT` — each pipeline agent may declare `permissionMode: default | acceptEdits | plan | bypassPermissions`. Never use `bypassPermissions` without explicit user justification documented in the agent body.
- `STATE_MANAGEMENT: STRUCTURED_JSON` — `<scope-root>/superpipelines/temp/{P}/{runId}/pipeline-state.json` only. No `memory: project`. `memory: local` is allowed for agents that persist learned heuristics.
- `AUTO_MEMORY: DISABLED` — `autoMemoryEnabled: false` in settings; `CLAUDE_CODE_DISABLE_AUTO_MEMORY=1` env var. Reclaims 658+ tokens.
- `BOUND_STDOUT: TRUE` — pipe long outputs through `tail -80` etc. before passing back.
- `SCOPE_FILE_READS: TRUE` — Read specific line ranges over full files when possible.
- `PASS_PATHS_NOT_CONTENT: TRUE` for large files. Exception: task text is content (extract once at orchestrator, pass extracted text to each worker — never tell the worker "find your task in tasks.md").
- `MCP tool naming: ServerName:tool_name` — always fully qualified.
- Path variables: `${CLAUDE_PLUGIN_ROOT}` (plugin dir, wipes on update), `${CLAUDE_PLUGIN_DATA}` (persists across updates), `${user_config.KEY}` (user config).
- Description discipline: triggering conditions only, NEVER workflow summary. See `sk-claude-code-conventions`.

---

## 9. Cross-references

- `sk-pipeline-patterns` — pattern selection skill that loads this file.
- `sk-4d-method` — Pattern 6 wrapper details.
- `sk-spec-driven-development` — Pattern 5 details + artifact templates.
- `sk-pipeline-state` — schema + recovery rules.
- `sk-worktree-safety` — 4-step protocol.
- `sk-write-review-isolation` — Stage 1/2 output schemas.
- `sk-rationalization-resistance` — tag conventions.
- `sk-claude-code-conventions` — frontmatter schemas, model selection, prompt-cache discipline.


# File: skills\sk-pipeline-state\SKILL.md
----------------------------------------
---
name: sk-pipeline-state
description: Use when reading or writing pipeline-state.json, resuming an interrupted pipeline, or detecting a crashed run — defines the schema, recovery rules, and atomic-write pattern. Reference-only; preload via agent skills frontmatter.
disable-model-invocation: true
user-invocable: false
---

# Pipeline State — Persistence & Recovery

> Defines the schema, storage layout, and recovery protocols for pipeline execution state. Trigger when reading or writing `pipeline-state.json`, resuming an interrupted run, or diagnosing a crashed orchestrator.

<overview>
Superpipelines utilize a structured JSON state to manage the lifecycle of multi-agent workflows. This state is isolated from model behavior, ensuring that runs are inspectable, resumable, and resilient to environment restarts. All state transitions must follow an atomic write pattern to prevent corruption.
</overview>

<glossary>
  <term name="Pipeline State">A structured JSON file (`pipeline-state.json`) representing the source of truth for a specific run.</term>
  <term name="Atomic Write">The process of writing to a temporary file and renaming it to ensure file integrity.</term>
  <term name="Run ID">A UUID v4 uniquely identifying a single execution instance of a pipeline.</term>
</glossary>

## State Location

<invariant>
State must be persisted to `<scope-root>/superpipelines/temp/{P}/{runId}/pipeline-state.json`. Never store state within `${CLAUDE_PLUGIN_ROOT}`, as it is not persistent across updates.
</invariant>

## Schema Definition

<schema>
```json
{
  "pipeline_id": "<uuid>",
  "pipeline_name": "<P>",
  "scope_root": "<absolute path>",
  "run_id": "<uuid>",
  "started_at": "<iso8601>",
  "pattern": "1 | 2 | 2b | 3 | 4 | 5",
  "status": "running | completed | escalated | failed",
  "current_phase": <index>,
  "phases": [
    {
      "index": 0,
      "name": "<phase name>",
      "status": "pending | running | done | failed",
      "agent": "<agent name>",
      "outputs": ["<path>"],
      "error": null
    }
  ],
  "metadata": {}
}
```
</schema>

## Atomic Write Protocol

<protocol>
To prevent JSON corruption during concurrent operations or crashes, always use the following atomic write pattern:
1. Write the new state content to `pipeline-state.json.tmp`.
2. Move (rename) the temporary file to `pipeline-state.json`.

**Bash Implementation:**
```bash
TEMP_DIR="${SCOPE_ROOT}/superpipelines/temp/${PIPELINE_NAME}/${RUN_ID}"
mkdir -p "$TEMP_DIR"
echo "$NEW_STATE_JSON" > "${TEMP_DIR}/pipeline-state.json.tmp"
mv "${TEMP_DIR}/pipeline-state.json.tmp" "${TEMP_DIR}/pipeline-state.json"
```
</protocol>

## Recovery & Resumption Rules

<recovery_rules>
| State Found | Required Action |
| :--- | :--- |
| **`status: running`** (<1h old) | Active run detected; refuse to start a new instance. |
| **`status: running`** (>1h old) | Treat as crashed. Prompt user to resume, restart, or abort. |
| **`status: completed`** | Terminal state reached. Skip or archive. |
| **`status: escalated/failed`** | Stop execution. Surface to human for manual intervention. |
| **Parse Error** | Corruption detected. Escalate to human; do NOT auto-resume. |
</recovery_rules>

<invariants>
- **No Model Coupling**: Never use the model's native memory tool for pipeline state management; use structured JSON.
- **Atomic Renaming**: Direct writes to `pipeline-state.json` are forbidden.
- **Explicit Resumption**: NEVER auto-resume from an `escalated` or `failed` state without explicit user confirmation.
</invariants>

## Reference Files

- `sk-pipeline-paths/SKILL.md` — Scope root resolution.
- `sk-pipeline-patterns/SKILL.md` — Execution pattern definitions.
- `running-a-pipeline/SKILL.md` — Primary orchestrator workflow.


# File: skills\sk-rationalization-resistance\SKILL.md
----------------------------------------
---
name: sk-rationalization-resistance
description: Use when authoring a discipline-enforcing skill or agent body that must hold up under time pressure, sunk cost, or "obvious answer" rationalization — defines HARD-GATE / EXTREMELY-IMPORTANT tag conventions, Red Flags lists, and Rationalization Tables. Reference-only; preload via agent skills frontmatter.
disable-model-invocation: true
user-invocable: false
---

# Rationalization Resistance — Discipline-Enforcement Conventions

> Establishes mechanisms (HARD-GATE, EXTREMELY-IMPORTANT, Red Flags) to prevent agents from taking shortcuts under time pressure, sunk cost, or cognitive bias. Trigger when authoring discipline-enforcing skills or agent bodies that require strict adherence to protocols.

<overview>
Rationalization Resistance ensures that critical safety and quality rules hold the line even when an agent is tempted to shortcut them. It utilizes specific semantic tags and tables to force the model to confront its own internal monologue and adhere to non-negotiable architectural gates.
</overview>

<glossary>
  <term name="HARD-GATE">A semantic tag wrapping non-negotiable checkpoints that requires a STOP condition before proceeding.</term>
  <term name="Red Flag">An exact thought or behavior that signals an agent is attempting to rationalize a shortcut.</term>
  <term name="Rationalization Table">A tabular comparison of common model excuses against project reality.</term>
</glossary>

## Resistance Mechanisms

<protocol>
### 1. THE `<HARD-GATE>` TAG
- **Usage**: Wrap non-negotiable checkpoints at decision points.
- **Convention**: Use one sentence stating the STOP condition and the required action (e.g., "STOP. Do NOT attempt iteration 4.").
- **Goal**: Force a terminal break in execution if safety or quality thresholds are breached.

### 2. THE `<EXTREMELY-IMPORTANT>` TAG
- **Usage**: Wrap rules that are frequently rationalized away or ignored.
- **Convention**: State the rule positively, then append the "non-optional" clause.
- **Invariant**: Use sparingly to maintain high semantic weight.

### 3. RED FLAGS & RATIONALIZATION TABLES
- **Red Flags**: Bulleted list of specific internal monologues that trigger a STOP.
- **Rationalization Table**: Mapping of `| Excuse | Reality |` to debunk common model justifications with concrete corrective actions.
</protocol>

## Applicability Matrix

<applicability_table>
| Skill Type | HARD-GATE | EXTREMELY-IMPORTANT | Red Flags / Tables |
| :--- | :---: | :---: | :---: |
| **Reference-only** (`sk-*`) | Optional | Optional | Not required |
| **Discipline-enforcing** | Required | Required | Required |
| **Workflow** | Required | Required | Required |
| **Agent Bodies** | Required | Required | Optional |
</applicability_table>

## Anti-Patterns

<anti_patterns>
- **Soft-pedaling**: Using phrases like "you might want to consider" instead of "STOP" or "DO NOT."
- **User-perspective Red Flags**: Writing flags from the user's view instead of the agent's internal monologue.
- **Abstract Realities**: Using vague reasons like "correctness matters" instead of concrete technical consequences.
- **Tag Bloat**: Wrapping excessive amounts of text, which dilutes the semantic signal.
</anti_patterns>

<invariants>
- Every discipline-enforcing skill MUST include both a Red Flags list and a Rationalization Table at the bottom.
- Corrective actions in Red Flags MUST be concrete and immediate.
- Place mechanisms at the exact decision points the agent will reach naturally.
</invariants>

## Reference Files

- `sk-pipeline-patterns/SKILL.md` — Example Pattern 3 escalation gate.
- `sk-write-review-isolation/SKILL.md` — Example EXTREMELY-IMPORTANT usage.
- `references/ai-pipelines-trimmed.md` — Full conventions reference.


# File: skills\sk-spec-driven-development\SKILL.md
----------------------------------------
---
name: sk-spec-driven-development
description: Use when authoring multi-step pipelines or features that need a spec contract before execution — the spec→plan→tasks→implement workflow aligned with GitHub Spec Kit. Reference-only; preload via agent skills frontmatter.
disable-model-invocation: true
user-invocable: false
---

# Spec-Driven Development (SDD) — Workflow Reference

> Establishes a formal spec→plan→tasks→implement contract for multi-step feature work and pipeline authoring. Trigger when building new features, refactoring systems, or whenever a request is too ambiguous for direct execution.

<overview>
Spec-Driven Development (SDD) minimizes hallucinations and misaligned outputs by front-loading requirements analysis. It ensures that every task is rooted in a verified specification and that parallel execution is protected by a mandatory human gate and precise acceptance criteria.
</overview>

<glossary>
  <term name="spec.md">The canonical contract defining WHAT and WHY, focusing on user journeys and success criteria.</term>
  <term name="plan.md">The technical architecture document defining HOW, including stack, API contracts, and risk mitigations.</term>
  <term name="tasks.md">A decomposition of the plan into small, independent, and verifiable units of work (T-1, T-2, etc.).</term>
</glossary>

## The Four Phases

<protocol>
### 1. SPECIFY (`/specify`)
- **Goal**: Define the outcome without implementation details.
- Capture user journeys, success criteria (AC), non-goals, and constraints.
- **Invariant**: The spec must be readable without code; it must answer "What does done look like?"

### 2. PLAN (`/plan`)
- **Goal**: Design the technical implementation.
- Define the tech stack, architecture (contracts/schemas), dependency matrix, and risks.
- Resolve ambiguities surfaced in the spec via `/clarify`.

### 3. TASKS (`/tasks`)
- **Goal**: Decompose the plan into chunks (5–30 min per agent session).
- Each task requires a stable ID, description, file list, and verifiable AC.
- **Validation**: BLOCK implementation if any spec AC lacks a corresponding task.

### 4. IMPLEMENT (`/implement`)
- **Goal**: Execute tasks in parallel where dependencies allow.
- Each task runs through an isolated RPI loop (Research, Plan, Implement).
- Reconcile `pipeline-state.json` upon completion or failure of each task.
</protocol>

<HARD-GATE>
**MANDATORY HUMAN APPROVAL**: Before dispatching parallel implementation, present `spec.md` and `tasks.md` to the user. Wait for explicit `APPROVE`. A misunderstood spec at this stage will cause all parallel workers to fail simultaneously.
</HARD-GATE>

## Artifact Skeletons

<artifacts>
### `spec.md`
- **Context**: Motivation for the change.
- **User Journeys**: Scenarios and expected outcomes.
- **Success Criteria**: Numbered list of verifiable ACs.
- **Non-Goals**: Explicit out-of-scope items.

### `plan.md`
- **Architecture**: Layer diagrams and data flow.
- **API Contracts**: Schemas and signatures.
- **Dependency Matrix**: Upstream/downstream component mapping.

### `tasks.md`
- **ID**: `T-1`, `T-2`, etc.
- **Acceptance**: A concrete command or check that returns pass/fail.
- **Depends On**: Upstream task IDs.
</artifacts>

## Pattern Mapping

<mapping_table>
| SDD Command | Pattern 5 Phase | Outcome |
| :--- | :--- | :--- |
| `/specify` | Phase 1 | `spec.md` |
| `/plan` | Phase 2 | `plan.md` |
| `/tasks` | Phase 3 | `tasks.md` |
| `/analyze` | Phase 4 | Pre-gate validation |
| **Approval** | Phase 4b | Human authorization |
| `/implement` | Phase 5 | Parallel execution |
</mapping_table>

<invariants>
- Every acceptance criterion in `spec.md` MUST be mapped to at least one task in `tasks.md`.
- Tasks must be small enough for a single agent session (avoiding context bloat).
- Maintain strict write/review isolation during the implementation phase.
</invariants>

## Reference Files

- `sk-4d-method/SKILL.md` — Per-invocation wrapper.
- `sk-pipeline-patterns/SKILL.md` — Pattern 5 definition.
- `sk-write-review-isolation/SKILL.md` — Implementation review loop.
- `sk-pipeline-state/SKILL.md` — State reconciliation rules.


# File: skills\sk-worktree-safety\SKILL.md
----------------------------------------
---
name: sk-worktree-safety
description: Use when creating, populating, verifying, or destroying a git worktree as part of a pipeline — the 4-step safety protocol (verify-ignored, setup-after-create, verify-baseline, commit-before-destroy). Reference-only; preload via agent skills frontmatter.
disable-model-invocation: true
user-invocable: false
---

# Worktree Safety Protocol — Isolated Execution

> Defines the mandatory 4-step protocol (Ignore, Setup, Baseline, Commit) for creating, managing, and destroying git worktrees. Trigger when utilizing `isolation: worktree` or preparing parallel branches for pipeline tasks.

<overview>
Worktrees provide critical isolation for parallel pipeline tasks, but improper handling risks data loss or workspace pollution. This protocol ensures that every worktree is properly ignored, initialized with a verified baseline, and committed before destruction to preserve all generated artifacts and findings.
</overview>

<glossary>
  <term name="Worktree">An isolated git workspace sharing the same repository object but operating on a different branch and path.</term>
  <term name="Baseline Verification">Running the project's test suite before modification to identify pre-existing failures.</term>
  <term name="Atomic Teardown">Committing all uncommitted work before removing the worktree directory.</term>
</glossary>

## The 4-Step Safety Protocol

<protocol>
### 1. VERIFY_IGNORED
Ensure the `.worktrees/` directory is git-ignored to prevent accidental pollution of the main workspace or commits.
```bash
git check-ignore -q .worktrees || { echo ".worktrees/" >> .gitignore && git add .gitignore && git commit -m "chore: ignore worktrees"; }
```

### 2. SETUP_AFTER_CREATE
Auto-detect manifests (`package.json`, `Cargo.toml`, etc.) and run the corresponding installation commands (`npm install`, `cargo build`) to prepare the isolated environment.

### 3. VERIFY_BASELINE
Run the project's full test suite.
- **Failures Found**: Report results to the user. **DO NOT PROCEED** with implementation without explicit human authorization.
- **Goal**: Distinguish between pre-existing issues and pipeline-introduced regressions.

### 4. COMMIT_BEFORE_DESTROY
Before removing any worktree, add and commit all changes to preserve the work-in-progress state.
```bash
cd "$WORKTREE_PATH" && git add -A && git commit -m "wip: pipeline checkpoint"
git worktree remove "$WORKTREE_PATH"
```
</protocol>

## Pattern Integration

<integration_table>
| Pattern | Worktree Requirement | Rationale |
| :--- | :--- | :--- |
| **1. Sequential** | Optional | Linear flow may not require isolation. |
| **2. Parallel** | **Mandatory** | Required for fanned-out task isolation. |
| **3. Iterative** | **Mandatory** | Enables atomic rollback on escalation. |
| **4. Gated** | Conditional | Required only during the modification phase. |
| **5. Spec-Driven** | **Mandatory** | Enforced per-task during Phase 5 (Implement). |
</integration_table>

## Detection Signals

<signals>
Before execution, verify the environment state:
- **`GIT_DIR != GIT_COMMON`**: Already in a linked worktree; skip Step 1.
- **Branch empty**: Detached HEAD detected; cannot branch/push. Escalate to user.
</signals>

<invariants>
- NEVER skip the baseline test; it is the leading cause of false escalations in iterative loops.
- NEVER use `git worktree remove --force` without an preceding commit to preserve findings.
- ALWAYS verify that `.worktrees/` is ignored before creation.
</invariants>

## Red Flags — STOP
- "I'll skip the baseline test, it'll be fine." → **STOP**. Pre-existing failures will corrupt the pipeline metrics.
- "Just force-remove the worktree, the pipeline failed." → **STOP**. Commit partial findings first to aid debugging.

## Reference Files
- `sk-pipeline-patterns/SKILL.md` — Topology selection.
- `sk-pipeline-state/SKILL.md` — `metadata.worktree_root` tracking.
- `finishing-a-development-branch/SKILL.md` — Final merge protocol.


# File: skills\sk-write-review-isolation\SKILL.md
----------------------------------------
---
name: sk-write-review-isolation
description: Use when dispatching a reviewer after a pipeline worker has produced output, or when authoring a pipeline that requires two-stage review — enforces separate writer/reviewer instances and Stage 1 (spec compliance) gating Stage 2 (code quality). Reference-only; preload via agent skills frontmatter.
disable-model-invocation: true
user-invocable: false
---

# Write/Review Isolation — Two-Stage Review Protocol

> Enforces a non-negotiable separation between the agent authoring code and the agent reviewing it. Trigger when dispatching reviewers, authoring multi-stage pipelines, or implementing any task requiring formal verification against a specification.

<overview>
`WRITE_REVIEW_ISOLATION: TRUE` is a fundamental invariant of the Superpipelines architecture. By separating the writer from the reviewer and splitting the review process into Stage 1 (Spec Compliance) and Stage 2 (Code Quality), we prevent context bleed, detect over-build early, and ensure that only verified code is promoted.
</overview>

<glossary>
  <term name="Stage 1 (Spec Compliance)">A binary check answering: "Does the output match the spec exactly?"</term>
  <term name="Stage 2 (Code Quality)">A qualitative check answering: "Is the code maintainable, idiomatic, and robust?"</term>
  <term name="Over-build">Adding features or logic not explicitly requested by the specification; results in a Stage 1 FAIL.</term>
</glossary>

## The Two-Stage Protocol

<protocol>
### STAGE 1 — SPEC COMPLIANCE REVIEW
- **Agent**: `pipeline-spec-reviewer`.
- **Inputs**: `spec.md`, output files, and the executor's status report.
- **Goal**: Verify every acceptance criterion is present and verifiable. Flag any unrequested output as **Over-build**.
- **HARD-GATE**: Stage 2 cannot begin until Stage 1 returns a `PASS`.

### STAGE 2 — CODE QUALITY REVIEW
- **Agent**: `pipeline-quality-reviewer`.
- **Inputs**: Same as Stage 1, plus the Stage 1 `PASS` verdict.
- **Goal**: Evaluate maintainability, naming, separation of concerns, and edge-case handling.
- **Exit Condition**: Terminal `PASS` only when all critical and major issues are resolved.
</protocol>

<EXTREMELY-IMPORTANT>
Stage 1 spec compliance review MUST pass before Stage 2 code quality review begins. This order is not optional. Running Stage 2 on spec-noncompliant output is wasted work and risks propagating incorrect logic.
</EXTREMELY-IMPORTANT>

## The Review Loop

<loop_diagram>
1. **Executor**: Writes output for a given task.
2. **SpecReviewer**: Reviews for compliance (Stage 1).
   - **FAIL**: Executor fixes issues → Re-run Stage 1.
   - **PASS**: Proceed to Stage 2.
3. **QualityReviewer**: Reviews for quality (Stage 2).
   - **FAIL (Critical/Major)**: Executor fixes issues → **Re-run Stage 1** (to ensure the fix didn't break compliance).
   - **PASS**: Task complete; update `pipeline-state.json`.
</loop_diagram>

<invariants>
- **Instance Isolation**: The writing agent and reviewing agent must be separate model instances with fresh context.
- **Full Re-review**: Any code change triggered by Stage 2 MUST trigger a fresh Stage 1 review.
- **No Scope Creep**: Reviewers must stay within their defined stage scope (e.g., Stage 1 does not flag formatting; Stage 2 does not flag missing ACs).
</invariants>

## Red Flags — STOP
- "The output looks fine, I'll skip Stage 1." → **STOP**. Spec compliance is the primary defense against production regressions.
- "I'll mention this AC issue in the Stage 2 report." → **STOP**. Re-dispatch Stage 1 immediately.
- "I added a helper that wasn't in the spec, but it's clearly needed." → **STOP**. This is over-build. Re-architect the spec or remove the helper.

## Rationalization Table

<rationalization_table>
| Excuse | Reality |
| :--- | :--- |
| "Separate instances are pointless." | Fresh context forces new reasoning paths and prevents "assumption blindness." |
| "Stage 1 is just a sanity check." | Stage 1 catches the most expensive bugs (wrong logic/output). It is the primary gate. |
| "Re-Stage 1 is over-engineering." | Code quality fixes often break specification compliance. Re-verification is mandatory. |
| "Over-build is a bonus for the user." | Over-build invalidates the contract that parallel workers and dependent steps rely on. |
</rationalization_table>

## Reference Files
- `sk-pipeline-patterns/SKILL.md` — Pattern 5 integration.
- `pipeline-spec-reviewer.md` — Spec reviewer blueprint.
- `pipeline-quality-reviewer.md` — Quality reviewer blueprint.
- `sk-rationalization-resistance/SKILL.md` — Resistance mechanism standards.


# File: skills\skill-architect-references\references\anti-patterns.md
----------------------------------------
# Skill-Authoring Anti-Patterns

Common authoring mistakes when designing SKILL.md files. Each entry: symptoms, fix.

## 1. Workflow-summary description

**Symptoms:** Description includes verbs describing what the skill does ("processes", "reads", "writes").

**Fix:** Triggering conditions only — see `description-engineering.md`.

## 2. Body restates the description

**Symptoms:** First paragraph of body repeats the description's content.

**Fix:** Body's Overview section states the core principle. Description states triggers.

## 3. Inconsistent person

**Symptoms:** Skill switches between "I", "you", and third person across sections.

**Fix:** Third person throughout. Imperative voice for actions ("Read the file" not "You should read the file").

## 4. Force-load via `@path`

**Symptoms:** Cross-reference uses `@references/foo.md` syntax.

**Fix:** Use prose markers instead: "Read `references/foo.md` for detail." `@path` force-loads the file at activation, defeating progressive disclosure.

## 5. Multi-language code examples

**Symptoms:** Same concept shown in Python, JS, Rust, Go.

**Fix:** ONE excellent example in the most relevant language. Multiple languages bloat context without adding signal.

## 6. Flowchart for linear steps

**Symptoms:** Mermaid/ASCII flowchart for a process that's just numbered steps.

**Fix:** Numbered list. Flowcharts are for non-obvious decisions, loops, or A-vs-B choices.

## 7. Nested references

**Symptoms:** `references/foo/bar/baz.md` — references nested 2+ levels.

**Fix:** One level deep from SKILL.md. Nested references cause partial reads.

## 8. Vague qualifiers

**Symptoms:** "as needed", "if appropriate", "consider", "you might want to".

**Fix:** Use deterministic instructions. "Read the file. If it exists, parse it. Otherwise, create it."

## 9. No "When NOT to use"

**Symptoms:** Skill triggers on cases it shouldn't.

**Fix:** Add a "When NOT to use" subsection enumerating false-positive scenarios.

## 10. Discipline skill missing Red Flags

**Symptoms:** Skill enforces a rule but doesn't say what rationalization to watch for.

**Fix:** Add Red Flags + Rationalization Table per `sk-rationalization-resistance`.

## 11. Reference file missing ToC

**Symptoms:** Reference file >100 lines without a Table of Contents.

**Fix:** Add `## Table of contents` at the top before any other section.

## 12. Body >500 lines

**Symptoms:** SKILL.md exceeds the 500-line limit.

**Fix:** Split into SKILL.md (navigation index) + `references/*.md` for depth.

## 13. Skill that's actually documentation

**Symptoms:** Body is mostly explanation of a concept, no actionable instructions.

**Fix:** Skills are instructions, not docs. Move to `docs/` or merge into a host skill's reference.

## 14. Trigger overlap with sibling skills

**Symptoms:** Two skills have overlapping descriptions; orchestrator can't tell them apart.

**Fix:** Make descriptions non-overlapping. Add explicit "When NOT to use" pointing to the sibling skill.

## 15. Hardcoded plugin paths

**Symptoms:** Skill body references `~/.claude/...` or `/usr/local/...`.

**Fix:** Use `${CLAUDE_PLUGIN_ROOT}` for plugin-relative paths. Workspace-relative paths use `./` prefix.


# File: skills\skill-architect-references\references\claude-code-skill-spec.md
----------------------------------------
# Claude Code Skill Spec — Frontmatter Reference

Full frontmatter field reference for SKILL.md files. Subset of `sk-claude-code-conventions` Section 5, expanded with usage notes.

## Table of contents

1. All supported fields
2. Field reference
3. Common patterns
---

## All supported fields

```yaml
---
name: skill-name-with-hyphens
description: Use when [triggering conditions only — NO workflow summary]
when_to_use: |
  Optional extended trigger description.
  Counts toward the 1536-char metadata cap.
argument-hint: "[issue-number]"
disable-model-invocation: true
user-invocable: false
allowed-tools: Read, Write, Edit, Bash
model: sonnet
effort: medium
context: fork
agent: Explore
hooks:
  PreToolUse:
    - matcher: Bash
      hooks:
        - type: command
          command: '...'
paths:
  - "src/**/*.ts"
shell: bash
---
```

## Field reference

| Field | Type | Notes |
|-------|------|-------|
| `name` | string | Lowercase + hyphens. ≤64 chars. Matches dir name. Required. |
| `description` | string | ≤1024 chars. Triggering conditions only. Third person. Required. |
| `when_to_use` | string | Optional extended description. Total `description + when_to_use` ≤1536. |
| `argument-hint` | string | Hint shown in slash-command UI (e.g., `"[issue-number]"`). |
| `disable-model-invocation` | boolean | If `true`, only user can trigger. Reference-only skills always set `true`. |
| `user-invocable` | boolean | If `false`, skill is invoked only by other skills/agents. Default `true`. |
| `allowed-tools` | list | Tools allowed without permission prompt when this skill is active. |
| `model` | string | Override model for this skill's body invocation. Rarely used in pipelines. |
| `effort` | string | `low / medium / high / xhigh / max`. |
| `context` | string | `fork` runs the body as a forked subagent prompt. |
| `agent` | string | Subagent type when `context: fork` (e.g., `Explore`). |
| `hooks` | object | Lifecycle hooks. Generally avoided in skills. |
| `paths` | list | Glob patterns. Skill activates only when matching files in context. |
| `shell` | string | `bash` or `powershell` for skills that emit shell snippets. |

## Common patterns

### Reference-only skill

```yaml
---
name: sk-example
description: Use when [triggers]
disable-model-invocation: true
user-invocable: false
---
```

### User-only skill (logger, deploy, destructive ops)

```yaml
---
name: deploy
description: Use when deploying to production
disable-model-invocation: true
user-invocable: true
---
```

### Auto-invoked workflow skill

```yaml
---
name: creating-a-pipeline
description: Use when [triggers]
---
```

(Default behavior: auto-invocation enabled, user-invocation enabled.)

### Path-scoped skill

```yaml
---
name: typescript-helpers
description: Use when editing TypeScript files
paths:
  - "src/**/*.ts"
  - "src/**/*.tsx"
---
```

Skill activates only when context includes a file matching the glob.

When in doubt, ship the minimal set — `name`, `description`, optional `disable-model-invocation` and `user-invocable`.


# File: skills\skill-architect-references\references\description-engineering.md
----------------------------------------
# Description Engineering — Skill-Architect Reference

The description field is the most important text in any skill — it determines whether the skill is ever invoked. Get it wrong and the skill becomes documentation that's never read (silent failure, no error).

## The rule

**Description = ONLY triggering conditions. NEVER summarize the skill's process or workflow.**

Pattern: `Use when [specific triggering conditions and symptoms]`

## Why this matters

Claude reads the description to decide whether to load the skill body. If the description summarizes the workflow, Claude treats the description as a shortcut and skips the body. The skill becomes documentation Claude never reads.

A real failure: a description saying "dispatches subagent per task with code review between tasks" caused Claude to perform ONE review instead of the two-stage review specified in the skill body. Changing the description to triggering conditions only fixed the behavior without changing any skill content.

## Patterns

### ❌ WRONG — Summarizes workflow

```yaml
description: Processes Excel files by reading sheets, cleaning data, and generating charts. Use when working with spreadsheets.
```

### ❌ WRONG — Process detail in description

```yaml
description: Use for commit messages — analyze diff, extract intent, write conventional commit.
```

### ✅ CORRECT — Triggering conditions only

```yaml
description: Use when working with Excel files, spreadsheets, or .xlsx data extraction.
```

### ✅ CORRECT — Problem-symptom triggers

```yaml
description: Use when tests have race conditions, timing dependencies, or fail inconsistently.
```

## Authoring checklist

- [ ] Starts with "Use when" or equivalent triggering verb.
- [ ] Third person only ("Generates...", NOT "I generate" / "You can use").
- [ ] No verbs describing the skill's internal process ("by reading", "after analyzing").
- [ ] Includes the symptoms / contexts the user would describe.
- [ ] Front-loads the most discriminating trigger.
- [ ] ≤1024 chars (truncation at 1536 if `when_to_use` extends).
- [ ] Trigger keywords match what users naturally say.

## Counter under-triggering

The most common failure is descriptions that are too narrow. Enumerate non-obvious triggers:

```yaml
# Narrow — only triggers on the obvious case
description: Use when reviewing a PR.

# Wider — covers obvious + non-obvious cases
description: Use when reviewing a PR, auditing changed files, checking diffs against acceptance criteria, or before merging a feature branch.
```

## Test the description

Before shipping, simulate routing:

1. Take 3 task descriptions a user might give.
2. For each, ask: would this description trigger on that task?
3. Take 3 unrelated tasks. Ask: would this description NOT trigger? (False positives are as bad as false negatives.)

## Red Flags — STOP

- "I'll add the workflow steps so the user knows what the skill does" → STOP. The description is for routing, not user docs. Workflow goes in body.
- "The description sounds vague, let me add detail" → distinguish detail-as-triggers (good) from detail-as-process (bad).
- "I'll write it in second person so it feels more direct" → STOP. Third person only. Inconsistent POV breaks discovery.


# File: skills\skill-architect-references\references\skill-architecture.md
----------------------------------------
# Universal Skill Architecture — Skill-Architect Reference

Every well-designed SKILL.md follows the same five-layer architecture. Use this when designing or auditing a skill.

## Table of contents

1. The five layers
2. Standard SKILL.md template
3. Layer-by-layer rules
4. Compression vs. progressive disclosure
5. Cross-references

---

## The five layers

1. **Metadata** — `name` + `description` (the routing contract).
2. **Overview** — 1–2 sentences stating the core principle.
3. **When to use** — concrete triggers and contexts; when NOT to use.
4. **Core pattern or process** — the step-by-step / cycle / decision tree.
5. **Quick reference + Common mistakes + (for discipline skills) Red Flags + Rationalization Table**.

Skills under 100 lines may compress layers 3–5; skills over 300 lines should split into SKILL.md + `references/*.md`.

---

## Standard SKILL.md template

```markdown
---
name: skill-name-with-hyphens
description: Use when [triggering conditions only — NO workflow summary]
---

# Skill Name

## Overview
Core principle in 1–2 sentences. What problem this solves.

## When to Use
Bullet list: symptoms and contexts where this applies.
When NOT to use.

## Core Pattern or Process
[Step-by-step OR cycle OR decision tree]
[Before/after comparison if a "bad vs good" pattern exists]

## Quick Reference
Table or short bullet list — optimized for scanning.

## Common Mistakes
What goes wrong + specific fix for each.

## Red Flags — STOP   (discipline skills only)
List of exact thoughts/behaviors → single corrective action.

## Rationalization Table   (discipline skills only)
| Excuse | Reality |

## Cross-references
Other skills, references, canonical sources.
```

---

## Layer-by-layer rules

### Layer 1 — Metadata

- `name`: lowercase + hyphens. ≤64 chars. Matches directory name.
- `description`: triggering conditions only. Third person. ≤1024 chars.
- Optional: `disable-model-invocation: true` for reference-only skills; `user-invocable: false` for skills only invoked by other skills.

### Layer 2 — Overview

- 1–2 sentences. State the problem the skill solves.
- No preamble ("This skill helps you...").
- No version / changelog / metadata in body.

### Layer 3 — When to use

- Symptoms-based triggers, not feature-based ("when tests fail intermittently" beats "for testing").
- Counter under-triggering: enumerate non-obvious cases.
- "When NOT to use" prevents over-application.

### Layer 4 — Core pattern

- Numbered list for linear processes.
- Decision tree (mermaid or ASCII) for non-obvious choices.
- Before/after code blocks for "bad vs good" patterns.
- ONE excellent example, not multi-language.

### Layer 5 — Quick reference + mistakes + Red Flags

- Quick reference: optimized for scanning, not reading.
- Common mistakes: paired with specific fix per mistake.
- Red Flags + Rationalization Table: required for discipline-enforcing skills.

---

## Compression vs. progressive disclosure

| Skill body length | Strategy |
|-------------------|----------|
| < 100 lines | Single SKILL.md, all layers compressed |
| 100–500 lines | Single SKILL.md, full layers |
| > 500 lines | SKILL.md as navigation index + `references/*.md` for depth |

Reference files >100 lines must include a Table of Contents at the top.

---

## Cross-references

- `description-engineering.md` — how to write a description that triggers correctly.
- `claude-code-skill-spec.md` — full frontmatter field reference.
- `anti-patterns.md` — common authoring mistakes and fixes.


# File: skills\systematic-debugging\condition-based-waiting.md
----------------------------------------
# Condition-Based Waiting

## Overview

Flaky tests often guess at timing with arbitrary delays. This creates race conditions where tests pass on fast machines but fail under load or in CI.

**Core principle:** Wait for the actual condition you care about, not a guess about how long it takes.

## When to Use

```dot
digraph when_to_use {
    "Test uses setTimeout/sleep?" [shape=diamond];
    "Testing timing behavior?" [shape=diamond];
    "Document WHY timeout needed" [shape=box];
    "Use condition-based waiting" [shape=box];

    "Test uses setTimeout/sleep?" -> "Testing timing behavior?" [label="yes"];
    "Testing timing behavior?" -> "Document WHY timeout needed" [label="yes"];
    "Testing timing behavior?" -> "Use condition-based waiting" [label="no"];
}
```

**Use when:**
- Tests have arbitrary delays (`setTimeout`, `sleep`, `time.sleep()`)
- Tests are flaky (pass sometimes, fail under load)
- Tests timeout when run in parallel
- Waiting for async operations to complete

**Don't use when:**
- Testing actual timing behavior (debounce, throttle intervals)
- Always document WHY if using arbitrary timeout

## Core Pattern

```typescript
// ❌ BEFORE: Guessing at timing
await new Promise(r => setTimeout(r, 50));
const result = getResult();
expect(result).toBeDefined();

// ✅ AFTER: Waiting for condition
await waitFor(() => getResult() !== undefined);
const result = getResult();
expect(result).toBeDefined();
```

## Quick Patterns

| Scenario | Pattern |
|----------|---------|
| Wait for event | `waitFor(() => events.find(e => e.type === 'DONE'))` |
| Wait for state | `waitFor(() => machine.state === 'ready')` |
| Wait for count | `waitFor(() => items.length >= 5)` |
| Wait for file | `waitFor(() => fs.existsSync(path))` |
| Complex condition | `waitFor(() => obj.ready && obj.value > 10)` |

## Implementation

Generic polling function:
```typescript
async function waitFor<T>(
  condition: () => T | undefined | null | false,
  description: string,
  timeoutMs = 5000
): Promise<T> {
  const startTime = Date.now();

  while (true) {
    const result = condition();
    if (result) return result;

    if (Date.now() - startTime > timeoutMs) {
      throw new Error(`Timeout waiting for ${description} after ${timeoutMs}ms`);
    }

    await new Promise(r => setTimeout(r, 10)); // Poll every 10ms
  }
}
```

See `condition-based-waiting-example.ts` in this directory for complete implementation with domain-specific helpers (`waitForEvent`, `waitForEventCount`, `waitForEventMatch`) from actual debugging session.

## Common Mistakes

**❌ Polling too fast:** `setTimeout(check, 1)` - wastes CPU
**✅ Fix:** Poll every 10ms

**❌ No timeout:** Loop forever if condition never met
**✅ Fix:** Always include timeout with clear error

**❌ Stale data:** Cache state before loop
**✅ Fix:** Call getter inside loop for fresh data

## When Arbitrary Timeout IS Correct

```typescript
// Tool ticks every 100ms - need 2 ticks to verify partial output
await waitForEvent(manager, 'TOOL_STARTED'); // First: wait for condition
await new Promise(r => setTimeout(r, 200));   // Then: wait for timed behavior
// 200ms = 2 ticks at 100ms intervals - documented and justified
```

**Requirements:**
1. First wait for triggering condition
2. Based on known timing (not guessing)
3. Comment explaining WHY

## Real-World Impact

From debugging session (2025-10-03):
- Fixed 15 flaky tests across 3 files
- Pass rate: 60% → 100%
- Execution time: 40% faster
- No more race conditions


# File: skills\systematic-debugging\defense-in-depth.md
----------------------------------------
# Defense-in-Depth Validation

## Overview

When you fix a bug caused by invalid data, adding validation at one place feels sufficient. But that single check can be bypassed by different code paths, refactoring, or mocks.

**Core principle:** Validate at EVERY layer data passes through. Make the bug structurally impossible.

## Why Multiple Layers

Single validation: "We fixed the bug"
Multiple layers: "We made the bug impossible"

Different layers catch different cases:
- Entry validation catches most bugs
- Business logic catches edge cases
- Environment guards prevent context-specific dangers
- Debug logging helps when other layers fail

## The Four Layers

### Layer 1: Entry Point Validation
**Purpose:** Reject obviously invalid input at API boundary

```typescript
function createProject(name: string, workingDirectory: string) {
  if (!workingDirectory || workingDirectory.trim() === '') {
    throw new Error('workingDirectory cannot be empty');
  }
  if (!existsSync(workingDirectory)) {
    throw new Error(`workingDirectory does not exist: ${workingDirectory}`);
  }
  if (!statSync(workingDirectory).isDirectory()) {
    throw new Error(`workingDirectory is not a directory: ${workingDirectory}`);
  }
  // ... proceed
}
```

### Layer 2: Business Logic Validation
**Purpose:** Ensure data makes sense for this operation

```typescript
function initializeWorkspace(projectDir: string, sessionId: string) {
  if (!projectDir) {
    throw new Error('projectDir required for workspace initialization');
  }
  // ... proceed
}
```

### Layer 3: Environment Guards
**Purpose:** Prevent dangerous operations in specific contexts

```typescript
async function gitInit(directory: string) {
  // In tests, refuse git init outside temp directories
  if (process.env.NODE_ENV === 'test') {
    const normalized = normalize(resolve(directory));
    const tmpDir = normalize(resolve(tmpdir()));

    if (!normalized.startsWith(tmpDir)) {
      throw new Error(
        `Refusing git init outside temp dir during tests: ${directory}`
      );
    }
  }
  // ... proceed
}
```

### Layer 4: Debug Instrumentation
**Purpose:** Capture context for forensics

```typescript
async function gitInit(directory: string) {
  const stack = new Error().stack;
  logger.debug('About to git init', {
    directory,
    cwd: process.cwd(),
    stack,
  });
  // ... proceed
}
```

## Applying the Pattern

When you find a bug:

1. **Trace the data flow** - Where does bad value originate? Where used?
2. **Map all checkpoints** - List every point data passes through
3. **Add validation at each layer** - Entry, business, environment, debug
4. **Test each layer** - Try to bypass layer 1, verify layer 2 catches it

## Example from Session

Bug: Empty `projectDir` caused `git init` in source code

**Data flow:**
1. Test setup → empty string
2. `Project.create(name, '')`
3. `WorkspaceManager.createWorkspace('')`
4. `git init` runs in `process.cwd()`

**Four layers added:**
- Layer 1: `Project.create()` validates not empty/exists/writable
- Layer 2: `WorkspaceManager` validates projectDir not empty
- Layer 3: `WorktreeManager` refuses git init outside tmpdir in tests
- Layer 4: Stack trace logging before git init

**Result:** All 1847 tests passed, bug impossible to reproduce

## Key Insight

All four layers were necessary. During testing, each layer caught bugs the others missed:
- Different code paths bypassed entry validation
- Mocks bypassed business logic checks
- Edge cases on different platforms needed environment guards
- Debug logging identified structural misuse

**Don't stop at one validation point.** Add checks at every layer.


# File: skills\systematic-debugging\root-cause-tracing.md
----------------------------------------
# Root Cause Tracing

## Overview

Bugs often manifest deep in the call stack (git init in wrong directory, file created in wrong location, database opened with wrong path). Your instinct is to fix where the error appears, but that's treating a symptom.

**Core principle:** Trace backward through the call chain until you find the original trigger, then fix at the source.

## When to Use

```dot
digraph when_to_use {
    "Bug appears deep in stack?" [shape=diamond];
    "Can trace backwards?" [shape=diamond];
    "Fix at symptom point" [shape=box];
    "Trace to original trigger" [shape=box];
    "BETTER: Also add defense-in-depth" [shape=box];

    "Bug appears deep in stack?" -> "Can trace backwards?" [label="yes"];
    "Can trace backwards?" -> "Trace to original trigger" [label="yes"];
    "Can trace backwards?" -> "Fix at symptom point" [label="no - dead end"];
    "Trace to original trigger" -> "BETTER: Also add defense-in-depth";
}
```

**Use when:**
- Error happens deep in execution (not at entry point)
- Stack trace shows long call chain
- Unclear where invalid data originated
- Need to find which test/code triggers the problem

## The Tracing Process

### 1. Observe the Symptom
```
Error: git init failed in /home/user/project/packages/core
```

### 2. Find Immediate Cause
**What code directly causes this?**
```typescript
await execFileAsync('git', ['init'], { cwd: projectDir });
```

### 3. Ask: What Called This?
```typescript
WorktreeManager.createSessionWorktree(projectDir, sessionId)
  → called by Session.initializeWorkspace()
  → called by Session.create()
  → called by test at Project.create()
```

### 4. Keep Tracing Up
**What value was passed?**
- `projectDir = ''` (empty string!)
- Empty string as `cwd` resolves to `process.cwd()`
- That's the source code directory!

### 5. Find Original Trigger
**Where did empty string come from?**
```typescript
const context = setupCoreTest(); // Returns { tempDir: '' }
Project.create('name', context.tempDir); // Accessed before beforeEach!
```

## Adding Stack Traces

When you can't trace manually, add instrumentation:

```typescript
// Before the problematic operation
async function gitInit(directory: string) {
  const stack = new Error().stack;
  console.error('DEBUG git init:', {
    directory,
    cwd: process.cwd(),
    nodeEnv: process.env.NODE_ENV,
    stack,
  });

  await execFileAsync('git', ['init'], { cwd: directory });
}
```

**Critical:** Use `console.error()` in tests (not logger - may not show)

**Run and capture:**
```bash
npm test 2>&1 | grep 'DEBUG git init'
```

**Analyze stack traces:**
- Look for test file names
- Find the line number triggering the call
- Identify the pattern (same test? same parameter?)

## Finding Which Test Causes Pollution

If something appears during tests but you don't know which test:

Use the bisection script `find-polluter.sh` in this directory:

```bash
./find-polluter.sh '.git' 'src/**/*.test.ts'
```

Runs tests one-by-one, stops at first polluter. See script for usage.

## Real Example: Empty projectDir

**Symptom:** `.git` created in source code directory (e.g., `packages/core/`)

**Trace chain:**
1. `git init` runs in `process.cwd()` ← empty cwd parameter
2. WorktreeManager called with empty projectDir
3. Session.create() passed empty string
4. Test accessed `context.tempDir` before beforeEach
5. setupCoreTest() returns `{ tempDir: '' }` initially

**Root cause:** Top-level variable initialization accessing empty value

**Fix:** Made tempDir a getter that throws if accessed before beforeEach

**Also added defense-in-depth:**
- Layer 1: Project.create() validates directory
- Layer 2: WorkspaceManager validates not empty
- Layer 3: NODE_ENV guard refuses git init outside tmpdir
- Layer 4: Stack trace logging before git init

## Key Principle

```dot
digraph principle {
    "Found immediate cause" [shape=ellipse];
    "Can trace one level up?" [shape=diamond];
    "Trace backwards" [shape=box];
    "Is this the source?" [shape=diamond];
    "Fix at source" [shape=box];
    "Add validation at each layer" [shape=box];
    "Bug impossible" [shape=doublecircle];
    "NEVER fix just the symptom" [shape=octagon, style=filled, fillcolor=red, fontcolor=white];

    "Found immediate cause" -> "Can trace one level up?";
    "Can trace one level up?" -> "Trace backwards" [label="yes"];
    "Can trace one level up?" -> "NEVER fix just the symptom" [label="no"];
    "Trace backwards" -> "Is this the source?";
    "Is this the source?" -> "Trace backwards" [label="no - keeps going"];
    "Is this the source?" -> "Fix at source" [label="yes"];
    "Fix at source" -> "Add validation at each layer";
    "Add validation at each layer" -> "Bug impossible";
}
```

**NEVER fix just where the error appears.** Trace back to find the original trigger.

## Stack Trace Tips

**In tests:** Use `console.error()` not logger - logger may be suppressed
**Before operation:** Log before the dangerous operation, not after it fails
**Include context:** Directory, cwd, environment variables, timestamps
**Capture stack:** `new Error().stack` shows complete call chain

## Real-World Impact

From debugging session (2025-10-03):
- Found root cause through 5-level trace
- Fixed at source (getter validation)
- Added 4 layers of defense
- 1847 tests passed, zero pollution


# File: skills\systematic-debugging\SKILL.md
----------------------------------------
---
name: systematic-debugging
description: Use when encountering any bug, test failure, or unexpected behavior, before proposing fixes
---

# Systematic Debugging — Root Cause Protocol

> Establishes a rigorous methodology for identifying, isolating, and resolving technical issues. Trigger when encountering any bug, test failure, or unexpected behavior before proposing or implementing a fix.

<overview>
Systematic Debugging is based on the Iron Law: **NO FIXES WITHOUT ROOT CAUSE INVESTIGATION FIRST**. It replaces guess-and-check thrashing with a scientific method—Read, Reproduce, Hypothesize, and Test—ensuring that fixes address the underlying problem rather than masking symptoms.
</overview>

<glossary>
  <term name="Root Cause">The original source of a failure; fixing it prevents the symptom from recurring.</term>
  <term name="Symptom Fix">A patch that hides a failure without addressing the cause; leads to technical debt and regression.</term>
  <term name="Iron Law">The non-negotiable rule prohibiting any fix proposal until Phase 1 is complete.</term>
</glossary>

## The Debugging Protocol

<protocol>
### PHASE 1: ROOT CAUSE INVESTIGATION
- **Read**: Complete error messages, stack traces, and logs. Do not skim.
- **Reproduce**: Establish a consistent, reliable trigger for the failure.
- **Gather Evidence**: Instrument component boundaries to log data ingress/egress.
- **Trace**: Map data flow backward from the failure point to the origin of the bad state.
- <HARD-GATE>Phase 1 is complete only when you can explain exactly WHAT failed and WHY.</HARD-GATE>

### PHASE 2: PATTERN ANALYSIS
- Find working examples of similar logic in the codebase.
- Compare the broken implementation against reference standards or successful instances.
- Identify all differences, however minor; do not assume any detail "doesn't matter."

### PHASE 3: HYPOTHESIS & MINIMAL TESTING
- Form a single, specific hypothesis: "I think X is the root cause because Y."
- Make the **smallest possible change** to test the hypothesis.
- Verify the result before adding more logic. If it fails, revert the change and form a new hypothesis.

### PHASE 4: IMPLEMENTATION & VERIFICATION
- Create a minimal failing test case (using the `test-driven-development` skill).
- Implement the single fix addressing the root cause.
- Verify the fix against the test case and ensure no regressions exist.
</protocol>

<invariants>
- **No Fix Bundling**: Address only the root cause; do not include "while I'm here" refactors.
- **The 3-Fix Limit**: If three separate fix attempts have failed, **STOP**. This indicates an architectural flaw, not a simple bug. Question the fundamental pattern with the human partner.
- **Data Flow Truth**: Base fixes on observed data state at component boundaries, not on intuition.
</invariants>

## Red Flags — STOP
- "Quick fix for now, investigate later." → **STOP**. Symptom fixes are failure.
- "Just try changing X and see if it works." → **STOP**. This is guessing, not debugging.
- "I'll skip the test; I manually verified it." → **STOP**. Untested fixes are guaranteed regressions.
- "Each fix reveals a new problem in a different place." → **STOP**. This is a signal of an architectural failure (The 3-Fix Limit).

## Rationalization Table

<rationalization_table>
| Excuse | Reality |
| :--- | :--- |
| "The issue is too simple for process." | Simple issues have root causes. Process is faster than guessing even for minor bugs. |
| "Emergency, no time for investigation." | Systematic debugging is 5x faster than guess-and-check thrashing during crises. |
| "I see the problem, let me fix it." | Seeing a symptom is not the same as understanding the trigger. |
| "Multiple fixes at once save time." | Bundled fixes make it impossible to isolate the true resolution. |
</rationalization_table>

## Reference Files
- `test-driven-development/SKILL.md` — Creating failing tests.
- `verification-before-completion/SKILL.md` — Final verification protocol.
- `sk-pipeline-state/SKILL.md` — Debugging state corruption.
- `root-cause-tracing.md` — Backward tracing techniques.


# File: skills\test-driven-development\SKILL.md
----------------------------------------
---
name: test-driven-development
description: Use when implementing any feature or bugfix, before writing implementation code
---

# Test-Driven Development (TDD) — Quality Protocol

> Enforces a "test-first" implementation cycle to ensure code correctness, maintainability, and regression safety. Trigger when implementing any feature, bugfix, or architectural refactor before writing production code.

<overview>
TDD is governed by the Iron Law: **NO PRODUCTION CODE WITHOUT A FAILING TEST FIRST**. By watching a test fail before implementing a solution, we prove that the test is valid and that the resulting code satisfies a specific, verified requirement rather than an assumed implementation.
</overview>

<glossary>
  <term name="Red Phase">The stage where a minimal, failing test is authored and verified to fail for the expected reason.</term>
  <term name="Green Phase">The stage where the minimal amount of code is written to satisfy the failing test.</term>
  <term name="Refactor Phase">The stage where code is cleaned and optimized while ensuring all tests remain green.</term>
</glossary>

## The TDD Cycle

<protocol>
### 1. RED — WRITE FAILING TEST
- Write a single, minimal test describing the desired behavior or bug reproduction.
- <invariant>Use real code and avoid mocks unless interacting with external, non-deterministic systems.</invariant>
- **Verify RED**: Run the test and confirm it fails. If it passes, the test is invalid or testing existing behavior.

### 2. GREEN — MINIMAL IMPLEMENTATION
- Write the **simplest possible code** to make the test pass.
- <invariant>Avoid adding unrequested features (YAGNI) or "while-I'm-here" refactors.</invariant>
- **Verify GREEN**: Run the test and confirm it passes alongside all existing tests.

### 3. REFACTOR — CLEAN UP
- Improve names, remove duplication, and extract helpers.
- Ensure the tests stay green throughout the refactoring process.
</protocol>

<EXTREMELY-IMPORTANT>
If you wrote production code before the test: **DELETE IT**. Start over from Step 1. Do not "adapt" existing code; the ritual of failure is what guarantees the validity of the test suite.
</EXTREMELY-IMPORTANT>

## Verification Checklist

<verification_checklist>
- [ ] Every new function/method has a corresponding test.
- [ ] Each test was observed failing before implementation began.
- [ ] Failure was due to missing logic, not typos or configuration errors.
- [ ] Minimal code was written to achieve a green state.
- [ ] No unrequested logic (over-build) was introduced.
- [ ] Output is pristine with no warnings or silent errors.
</verification_checklist>

## Red Flags — STOP
- "I'll write the tests after to verify it works." → **STOP**. Tests-after prove nothing; they only verify what was built, not what was required.
- "The test passed immediately." → **STOP**. Your test is invalid or you are testing logic that already exists.
- "Deleting this code is wasteful." → **STOP**. Sunk cost fallacy. Keeping unverified code is technical debt.
- "I manually tested it, so it's fine." → **STOP**. Manual testing is non-deterministic and non-reproducible.

## Rationalization Table

<rationalization_table>
| Excuse | Reality |
| :--- | :--- |
| "Too simple to test." | Simple code is the most frequent source of silent failures. Tests take seconds. |
| "Already manually tested." | Ad-hoc testing provides no record and cannot prevent future regressions. |
| "Keep as reference." | Keeping "reference" code leads to adapting it, which is just testing-after. Delete it. |
| "TDD slows me down." | TDD is faster than the inevitable debugging cycle caused by untested code. |
</rationalization_table>

## Reference Files
- `systematic-debugging/SKILL.md` — Root cause protocol.
- `verification-before-completion/SKILL.md` — Final verification gate.
- `sk-write-review-isolation/SKILL.md` — Review isolation rules.
- `testing-anti-patterns.md` — Common TDD pitfalls.


# File: skills\test-driven-development\testing-anti-patterns.md
----------------------------------------
# Testing Anti-Patterns

**Load this reference when:** writing or changing tests, adding mocks, or tempted to add test-only methods to production code.

## Overview

Tests must verify real behavior, not mock behavior. Mocks are a means to isolate, not the thing being tested.

**Core principle:** Test what the code does, not what the mocks do.

**Following strict TDD prevents these anti-patterns.**

## The Iron Laws

```
1. NEVER test mock behavior
2. NEVER add test-only methods to production classes
3. NEVER mock without understanding dependencies
```

## Anti-Pattern 1: Testing Mock Behavior

**The violation:**
```typescript
// ❌ BAD: Testing that the mock exists
test('renders sidebar', () => {
  render(<Page />);
  expect(screen.getByTestId('sidebar-mock')).toBeInTheDocument();
});
```

**Why this is wrong:**
- You're verifying the mock works, not that the component works
- Test passes when mock is present, fails when it's not
- Tells you nothing about real behavior

**your human partner's correction:** "Are we testing the behavior of a mock?"

**The fix:**
```typescript
// ✅ GOOD: Test real component or don't mock it
test('renders sidebar', () => {
  render(<Page />);  // Don't mock sidebar
  expect(screen.getByRole('navigation')).toBeInTheDocument();
});

// OR if sidebar must be mocked for isolation:
// Don't assert on the mock - test Page's behavior with sidebar present
```

### Gate Function

```
BEFORE asserting on any mock element:
  Ask: "Am I testing real component behavior or just mock existence?"

  IF testing mock existence:
    STOP - Delete the assertion or unmock the component

  Test real behavior instead
```

## Anti-Pattern 2: Test-Only Methods in Production

**The violation:**
```typescript
// ❌ BAD: destroy() only used in tests
class Session {
  async destroy() {  // Looks like production API!
    await this._workspaceManager?.destroyWorkspace(this.id);
    // ... cleanup
  }
}

// In tests
afterEach(() => session.destroy());
```

**Why this is wrong:**
- Production class polluted with test-only code
- Dangerous if accidentally called in production
- Violates YAGNI and separation of concerns
- Confuses object lifecycle with entity lifecycle

**The fix:**
```typescript
// ✅ GOOD: Test utilities handle test cleanup
// Session has no destroy() - it's stateless in production

// In test-utils/
export async function cleanupSession(session: Session) {
  const workspace = session.getWorkspaceInfo();
  if (workspace) {
    await workspaceManager.destroyWorkspace(workspace.id);
  }
}

// In tests
afterEach(() => cleanupSession(session));
```

### Gate Function

```
BEFORE adding any method to production class:
  Ask: "Is this only used by tests?"

  IF yes:
    STOP - Don't add it
    Put it in test utilities instead

  Ask: "Does this class own this resource's lifecycle?"

  IF no:
    STOP - Wrong class for this method
```

## Anti-Pattern 3: Mocking Without Understanding

**The violation:**
```typescript
// ❌ BAD: Mock breaks test logic
test('detects duplicate server', () => {
  // Mock prevents config write that test depends on!
  vi.mock('ToolCatalog', () => ({
    discoverAndCacheTools: vi.fn().mockResolvedValue(undefined)
  }));

  await addServer(config);
  await addServer(config);  // Should throw - but won't!
});
```

**Why this is wrong:**
- Mocked method had side effect test depended on (writing config)
- Over-mocking to "be safe" breaks actual behavior
- Test passes for wrong reason or fails mysteriously

**The fix:**
```typescript
// ✅ GOOD: Mock at correct level
test('detects duplicate server', () => {
  // Mock the slow part, preserve behavior test needs
  vi.mock('MCPServerManager'); // Just mock slow server startup

  await addServer(config);  // Config written
  await addServer(config);  // Duplicate detected ✓
});
```

### Gate Function

```
BEFORE mocking any method:
  STOP - Don't mock yet

  1. Ask: "What side effects does the real method have?"
  2. Ask: "Does this test depend on any of those side effects?"
  3. Ask: "Do I fully understand what this test needs?"

  IF depends on side effects:
    Mock at lower level (the actual slow/external operation)
    OR use test doubles that preserve necessary behavior
    NOT the high-level method the test depends on

  IF unsure what test depends on:
    Run test with real implementation FIRST
    Observe what actually needs to happen
    THEN add minimal mocking at the right level

  Red flags:
    - "I'll mock this to be safe"
    - "This might be slow, better mock it"
    - Mocking without understanding the dependency chain
```

## Anti-Pattern 4: Incomplete Mocks

**The violation:**
```typescript
// ❌ BAD: Partial mock - only fields you think you need
const mockResponse = {
  status: 'success',
  data: { userId: '123', name: 'Alice' }
  // Missing: metadata that downstream code uses
};

// Later: breaks when code accesses response.metadata.requestId
```

**Why this is wrong:**
- **Partial mocks hide structural assumptions** - You only mocked fields you know about
- **Downstream code may depend on fields you didn't include** - Silent failures
- **Tests pass but integration fails** - Mock incomplete, real API complete
- **False confidence** - Test proves nothing about real behavior

**The Iron Rule:** Mock the COMPLETE data structure as it exists in reality, not just fields your immediate test uses.

**The fix:**
```typescript
// ✅ GOOD: Mirror real API completeness
const mockResponse = {
  status: 'success',
  data: { userId: '123', name: 'Alice' },
  metadata: { requestId: 'req-789', timestamp: 1234567890 }
  // All fields real API returns
};
```

### Gate Function

```
BEFORE creating mock responses:
  Check: "What fields does the real API response contain?"

  Actions:
    1. Examine actual API response from docs/examples
    2. Include ALL fields system might consume downstream
    3. Verify mock matches real response schema completely

  Critical:
    If you're creating a mock, you must understand the ENTIRE structure
    Partial mocks fail silently when code depends on omitted fields

  If uncertain: Include all documented fields
```

## Anti-Pattern 5: Integration Tests as Afterthought

**The violation:**
```
✅ Implementation complete
❌ No tests written
"Ready for testing"
```

**Why this is wrong:**
- Testing is part of implementation, not optional follow-up
- TDD would have caught this
- Can't claim complete without tests

**The fix:**
```
TDD cycle:
1. Write failing test
2. Implement to pass
3. Refactor
4. THEN claim complete
```

## When Mocks Become Too Complex

**Warning signs:**
- Mock setup longer than test logic
- Mocking everything to make test pass
- Mocks missing methods real components have
- Test breaks when mock changes

**your human partner's question:** "Do we need to be using a mock here?"

**Consider:** Integration tests with real components often simpler than complex mocks

## TDD Prevents These Anti-Patterns

**Why TDD helps:**
1. **Write test first** → Forces you to think about what you're actually testing
2. **Watch it fail** → Confirms test tests real behavior, not mocks
3. **Minimal implementation** → No test-only methods creep in
4. **Real dependencies** → You see what the test actually needs before mocking

**If you're testing mock behavior, you violated TDD** - you added mocks without watching test fail against real code first.

## Quick Reference

| Anti-Pattern | Fix |
|--------------|-----|
| Assert on mock elements | Test real component or unmock it |
| Test-only methods in production | Move to test utilities |
| Mock without understanding | Understand dependencies first, mock minimally |
| Incomplete mocks | Mirror real API completely |
| Tests as afterthought | TDD - tests first |
| Over-complex mocks | Consider integration tests |

## Red Flags

- Assertion checks for `*-mock` test IDs
- Methods only called in test files
- Mock setup is >50% of test
- Test fails when you remove mock
- Can't explain why mock is needed
- Mocking "just to be safe"

## The Bottom Line

**Mocks are tools to isolate, not things to test.**

If TDD reveals you're testing mock behavior, you've gone wrong.

Fix: Test real behavior or question why you're mocking at all.


# File: skills\updating-a-pipeline-step\SKILL.md
----------------------------------------
---
name: updating-a-pipeline-step
description: Use when the user wants to modify, change, or update an existing step within a named pipeline, or invokes /superpipelines:update-step. Reads current step, applies changes, re-validates edges with neighbors, audits the delta, and gates on human approval before writing to disk.
---

# Updating a Pipeline Step — Modification Workflow

> Orchestrates the modification of an existing step within a named pipeline. Trigger when the user requests to change logic, tools, or I/O contracts for a step or invokes `/superpipelines:update-step`.

<overview>
The Updating a Pipeline Step workflow ensures that modifications to individual components do not break the larger orchestration contract. It focuses on impact analysis—identifying how I/O schema changes propagate to predecessors and successors—and enforces a rigorous audit-and-stage protocol before promoting changes to production paths.
</overview>

<glossary>
  <term name="Edge Re-validation">The process of verifying that neighbor steps still satisfy (or consume) modified input/output contracts.</term>
  <term name="Internal Behavior Change">A modification affecting only a step's logic or tools, with no impact on the topology edges.</term>
  <term name="Contract Propagation">The automatic update of neighboring steps to accommodate a changed I/O schema.</term>
</glossary>

## Workflow Phases

<protocol>
### PHASE 0: PIPELINE & STEP SELECTION
- Resolve registries and identify the target pipeline and step via `AskUserQuestion`.
- Display step metadata: agent/skill paths, current frontmatter, and declared I/O schemas.

### PHASE 1: IMPACT ANALYSIS (4D)
- Apply the 4D Method to deconstruct the brief.
- Classify the change category: Input Change, Output Change, Internal Change, or Full Contract Change.
- **Goal**: Identify exactly which predecessors or successors are affected by the mutation.

### PHASE 2: EDGE RE-VALIDATION
- If I/O schemas change, verify that all neighbor steps remain compatible.
- Present the impact analysis to the user (e.g., "Updating A's output affects B and C").
- <invariant>Obtain explicit user confirmation before propagating contract changes to neighboring steps.</invariant>

### PHASE 3: ARCHITECTED STAGING
- Dispatch `pipeline-architect` in `STEP-UPDATE` mode to generate modified artifacts.
- <invariant>All changes MUST be written to `{ROOT}/superpipelines/temp/{P}/edit-{ts}/` for staging. NEVER overwrite production files during design.</invariant>

### PHASE 4: DELTA AUDIT
- Dispatch `pipeline-auditor` in `DELTA` mode on the staged artifacts and neighbor components.
- <HARD-GATE>SEV-0 or SEV-1 findings block promotion. Dispatch the Architect to remediate and re-audit until the delta is clear.</HARD-GATE>

### PHASE 5: HUMAN APPROVAL & PROMOTION
- Present a diff summary, updated topology edges, and audit results for human review (`AskUserQuestion`).
- Upon `APPROVE`, atomically move staged files to their final absolute paths and update `registry.json`.
</protocol>

<invariants>
- NEVER assume an I/O change is "minor"; always run the Phase 2 impact analysis.
- ALWAYS use a staging directory (`edit-{ts}/`) for all modifications to allow for safe rollback.
- Propagate contract changes to neighbors ONLY after explicit user authorization.
</invariants>

## Red Flags — STOP
- "The output schema change is minor — no need to check successors." → **STOP**. Contract changes propagate; skipping re-validation causes runtime cascading failures.
- "I'll skip the human gate; it's just a small logic tweak." → **STOP**. Small logic changes can have non-obvious impacts on state management or neighbor agents.
- "The audit found only SEV-2 issues; good enough." → **STOP**. SEV-0/1 findings are hard blockers for promotion.

## Rationalization Table

<rationalization_table>
| Excuse | Reality |
| :--- | :--- |
| "The neighbors clearly accept the new format." | Contracts are explicit in `topology.json`. Verify against the schema, not from intuition. |
| "Skip Phase 2 to save time." | A 30-second impact check prevents a multi-hour pipeline redesign. |
| "I'll update the neighbors in a separate task." | Neighbor updates must be atomic with the step update to prevent an inconsistent topology state. |
</rationalization_table>

## Reference Files
- `sk-pipeline-paths/SKILL.md` — Path resolution.
- `sk-write-review-isolation/SKILL.md` — Review loop rules.
- `adding-a-pipeline-step/SKILL.md` — Insertion workflow.
- `deleting-a-pipeline-step/SKILL.md` — Removal workflow.


# File: skills\using-superpipelines\SKILL.md
----------------------------------------
---
name: using-superpipelines
description: Use when starting any conversation in a project that has the superpipelines plugin installed — establishes how to design, run, and manage AI pipelines, when to invoke pipeline-specific skills, and which subagents handle which roles
---

# Using Superpipelines — Core Orchestration Reference

> Establishes the foundational rules for designing, executing, and managing multi-agent AI pipelines. Trigger when starting any conversation in a project where Superpipelines is installed.

<SUBAGENT-STOP>
If dispatched as a subagent to execute a specific task, skip this skill. Subagents do not orchestrate; they perform a single role and exit with a terminal status (DONE, NEEDS_CONTEXT, BLOCKED).
</SUBAGENT-STOP>

<overview>
Superpipelines is a framework for designing and running multi-agent workflows across three deployment scopes (Local, Project, User). It enforces rigorous architectural standards, including non-negotiable write/review isolation, model selection constraints, and audit-driven mutations to ensure stability in production AI environments.
</overview>

<EXTREMELY-IMPORTANT>
If a pipeline skill applies to the user's request, invoke it. Do not rationalize past it. Pipelines fail silently when specialized skills are skipped—the orchestrator must trust the defined routing protocols.
</EXTREMELY-IMPORTANT>

## Skill Routing Protocols

<routing_table>
| User Request / Situation | Skill to Invoke | Rationale |
| :--- | :--- | :--- |
| `/new-pipeline` or "Design a workflow" | `creating-a-pipeline` | End-to-end scaffolding. |
| `/run-pipeline` or "Execute [P]" | `running-a-pipeline` | Registry-driven launcher. |
| `/new-step` or "Add capability" | `adding-a-pipeline-step` | Topology mutation. |
| `/update-step` or "Modify agent" | `updating-a-pipeline-step` | Contract-aware update. |
| `/delete-step` or "Remove step" | `deleting-a-pipeline-step` | Gap-analysis removal. |
| `/audit-pipeline` | `pipeline-auditor` | Security/topology review. |
| Ambiguous / Discovery phase | `sk-4d-method` | Intent deconstruction. |
| Implementation / Task execution | `sk-spec-driven-development` | Contracted development. |
| Authoring Agents or Skills | `sk-claude-code-conventions` | Format enforcement. |
</routing_table>

## Core Pipeline Invariants

<invariants>
- **`SUB_AGENT_SPAWNING: FALSE`**: Subagents must not spawn children; orchestration is restricted to the top-level parent.
- **`WRITE_REVIEW_ISOLATION: TRUE`**: The agent that writes code never reviews it. Stage 1 (Compliance) gates Stage 2 (Quality).
- **`MODEL_SELECTION: SONNET_ONLY`**: All agents default to `model: sonnet` unless the user explicitly opts into another model.
- **`STATE_PERSISTENCE`**: All state must reside in `<scope-root>/superpipelines/temp/{P}/{runId}/pipeline-state.json`.
- **`ATOMIC_MUTATION`**: Topology changes must be staged in `edit-{ts}/` before promotion.
</invariants>

## Red Flags — STOP
- "I already know what to do, skip the spec." → **STOP**. The spec is the contract for parallel worker synchronization.
- "One more iteration should fix it." → **STOP**. Hard cap at 3 iterations without measurable progress; escalate per Pattern 3.
- "The reviewer and executor can be the same." → **STOP**. Write/review isolation is a non-negotiable security boundary.
- "Skip the worktree for a small change." → **STOP**. If the pattern requires isolation, the safety protocol is mandatory.
- "The brief is detailed, I'll skip git preflight and scope selection." → **STOP**. `creating-a-pipeline` Phases 0 and 1 are mandatory. Run them before the 4D analysis.

## Rationalization Table

<rationalization_table>
| Excuse | Reality |
| :--- | :--- |
| "I'll read the skill file directly." | Using `Read` instead of `Skill` tool breaks discovery, caching, and body-loading logic. |
| "The user said it's urgent, skip audit." | A 30-second audit prevents silent topology gaps that lead to catastrophic runtime failure. |
| "The state file is too complex." | Standardized state is the only path to reliable resumption and multi-step recovery. |
| "The brief is complete, skip preflight." | Git preflight and scope selection are non-negotiable. A rich brief does not substitute for environment validation or deployment scope confirmation. |
| "I'll write state to `tmp/`." | The canonical state path is `<scope-root>/superpipelines/temp/{P}/{runId}/pipeline-state.json`. The `tmp/` path is a retired pattern. |
</rationalization_table>

## Reference Files
- `sk-pipeline-paths/SKILL.md` — Scope and path resolution.
- `sk-pipeline-patterns/SKILL.md` — Topology selection.
- `sk-write-review-isolation/SKILL.md` — Two-stage review protocol.
- `sk-rationalization-resistance/SKILL.md` — Resistance mechanism standards.


# File: skills\using-superpipelines\references\skill-routing.md
----------------------------------------
# Skill Routing — Decision Table

When to invoke which superpipelines skill or agent. Source of truth for the routing rules in `using-superpipelines` SKILL.md.

## User-facing workflow skills

| Trigger phrase / context | Invoke |
|--------------------------|--------|
| "Design a pipeline that…" | `creating-a-pipeline` |
| "Build me a workflow for…" | `creating-a-pipeline` |
| "Plan multi-step feature work" | `creating-a-pipeline` |
| `/superpipelines:new-pipeline` invoked | `creating-a-pipeline` |
| "Run the pipeline" / "Execute [name]" | `running-a-pipeline` |
| "Which pipelines are available?" | `running-a-pipeline` |
| "Resume the pipeline" / `/run-pipeline --resume` | `running-a-pipeline` |
| `/superpipelines:run-pipeline` invoked | `running-a-pipeline` |
| "Add a step to [pipeline]" / "Insert [X] into [pipeline]" | `adding-a-pipeline-step` |
| `/superpipelines:new-step` invoked | `adding-a-pipeline-step` |
| "Update [step] in [pipeline]" / "Change how [step] works" | `updating-a-pipeline-step` |
| `/superpipelines:update-step` invoked | `updating-a-pipeline-step` |
| "Remove / delete [step] from [pipeline]" | `deleting-a-pipeline-step` |
| `/superpipelines:delete-step` invoked | `deleting-a-pipeline-step` |
| "Audit [pipeline]" / "Review my pipeline" | dispatch `pipeline-auditor` (FULL mode) |
| "Audit all pipelines" / `/audit-pipeline --all` | dispatch `pipeline-auditor` (SCOPE-WIDE mode) |
| `/superpipelines:audit-pipeline` invoked | dispatch `pipeline-auditor` |

## Subagent dispatch (direct)

| Trigger | Subagent | Mode |
|---------|----------|------|
| Design a full pipeline | `pipeline-architect` | PIPELINE |
| Add a step to an existing pipeline | `pipeline-architect` | STEP-ADD |
| Update an existing pipeline step | `pipeline-architect` | STEP-UPDATE |
| Delete a step from an existing pipeline | `pipeline-architect` | STEP-DELETE |
| Audit pipeline files | `pipeline-auditor` | FULL / DELTA / SCOPE-WIDE |
| Implement a task | `pipeline-task-executor` | — |
| Stage 1: spec compliance review | `pipeline-spec-reviewer` | — |
| Stage 2: code quality review (after Stage 1 passes) | `pipeline-quality-reviewer` | — |
| Iterative loop failure diagnosis | `pipeline-failure-analyzer` | — |

## Shared method skills (preloaded by agents — only invoke explicitly when authoring)

| Use case | Skill |
|----------|-------|
| Ambiguous request needs structured processing | `sk-4d-method` |
| Multi-step feature needs spec/plan/tasks | `sk-spec-driven-development` |
| Authoring or modifying an agent or skill | `sk-claude-code-conventions` |
| Choosing an execution pattern (Sequential, Fan-Out, Iterative, Human-Gated, SDD) | `sk-pipeline-patterns` |
| Resolving scope-aware artifact paths | `sk-pipeline-paths` |
| Tracking pipeline state across iterations | `sk-pipeline-state` |
| About to use a git worktree | `sk-worktree-safety` |
| Setting up two-stage review | `sk-write-review-isolation` |
| Authoring a discipline-enforcing skill | `sk-rationalization-resistance` |

## Supporting skills (loaded by workflow skills as needed)

| Use case | Skill |
|----------|-------|
| Refining a vague request via Socratic questions | `brainstorming` (loaded by `creating-a-pipeline` Phase 3) |
| Closing out the pipeline (merge / PR / cleanup) | `finishing-a-development-branch` (loaded by entry skill end phase) |
| Project signals TDD requirement | `test-driven-development` (loaded by `pipeline-task-executor`) |
| Iterative-loop failure diagnosis | `systematic-debugging` (loaded by `pipeline-failure-analyzer`) |
| Self-verify before reporting DONE | `verification-before-completion` (every executor) |

## When NOT to invoke a skill

- Trivial single-step tasks (rename, typo fix, config flip) — execute directly.
- Read-only Q&A about the codebase — use Read/Glob/Grep directly.
- User has explicitly said "skip the spec phase" or similar — user instruction wins.
- Subagent dispatched to perform a single role — skip orchestration skills, run the task, emit status.


# File: skills\verification-before-completion\SKILL.md
----------------------------------------
---
name: verification-before-completion
description: Use when about to claim work is complete, fixed, or passing, before committing or creating PRs - requires running verification commands and confirming output before making any success claims; evidence before assertions always
---

# Verification Before Completion — Success Protocol

> Requires absolute evidence before any claim of task completion, bug resolution, or system readiness. Trigger when about to conclude a task, fixed a bug, or claim a system state is passing before committing changes or creating PRs.

<overview>
Verification Before Completion is governed by the Iron Law: **NO COMPLETION CLAIMS WITHOUT FRESH VERIFICATION EVIDENCE**. It prohibits the use of "should," "probably," or "seems to" in favor of documented command output and logs, ensuring that success is a verifiable fact rather than an assumption.
</overview>

<glossary>
  <term name="Gate Function">A mandatory five-step sequence (Identify, Run, Read, Verify, Claim) that must be completed before communicating success.</term>
  <term name="Evidence before Claim">The requirement to execute a verification command and analyze its output before stating a status.</term>
  <term name="Regression Verification">A Red-Green cycle proving that a test not only passes now but would have failed without the fix.</term>
</glossary>

## The Success Protocol

<protocol>
### THE GATE FUNCTION
1. **IDENTIFY**: Determine exactly which command or action proves the claim.
2. **RUN**: Execute the full, fresh verification command.
3. **READ**: Analyze the complete output, check exit codes, and count failures.
4. **VERIFY**: Confirm the output matches the success criteria of the original requirement.
5. **CLAIM**: State the completion status alongside the supporting evidence.

<invariant>Skip any step = failure of the verification protocol.</invariant>
</protocol>

<invariants>
- NEVER express satisfaction ("Great!", "Perfect!") before running verification.
- NEVER trust a subagent's "DONE" report without inspecting the VCS diff and running local tests.
- ALWAYS perform a Red-Green cycle for regression tests to prove the test's validity.
- Linter clean state is NOT a proxy for build success or logic correctness.
</invariants>

## Verification Patterns

<patterns>
| Quality | Goal | Required Evidence |
| :--- | :--- | :--- |
| **Tests** | All green | Command output showing `0 failures` across the entire suite. |
| **Linter** | Clean state | Command output showing `0 errors` and `0 warnings`. |
| **Build** | Successful binary | Execution log showing `exit 0` and artifact generation. |
| **Bug Fix** | Resolved symptom | Reproduction script passing + Red-Green verification. |
| **Requirements** | Spec compliance | Line-by-line checklist verification against `spec.md`. |
</patterns>

## Red Flags — STOP
- "It should work now." → **STOP**. Run the verification command.
- "I'm confident it's fixed." → **STOP**. Confidence is not evidence.
- "The agent said it was done." → **STOP**. Subagents are non-deterministic; verify independently.
- "I'll do a partial check to save time." → **STOP**. Partial verification proves nothing about system integration.

## Rationalization Table

<rationalization_table>
| Excuse | Reality |
| :--- | :--- |
| "I manually verified it." | Manual verification is non-reproducible and prone to observation bias. |
| "It's just a small fix." | Small fixes cause the majority of production regressions. |
| "I'm tired/in a hurry." | Exhaustion increases the probability of overlooking silent failures. |
| "Spirit over ritual." | The ritual of evidence is what protects the system's integrity. |
</rationalization_table>

## Reference Files
- `systematic-debugging/SKILL.md` — Root cause investigation.
- `test-driven-development/SKILL.md` — Red-Green cycle rules.
- `sk-write-review-isolation/SKILL.md` — Two-stage review protocol.
- `sk-worktree-safety/SKILL.md` — Integration verification.


Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.