# diagnostician (Unified Skill)

## Core Instructions (SKILL.md)

#### Core Instructions (content/distilled/diagnostician/SKILL.md)

# Diagnostician Router

Advisory-only diagnostic evaluation of a codebase, product, or document. Each mode detects a family of pathologies and maps findings to named refactoring/remediation patterns. **Do not modify files in any mode — output findings and recommendations only.**

## Modes

| Question the user is asking | Mode | Read |
|---|---|---|
| Is it tangled? coupling, cohesion, cycles, God Objects | modularity-diagnostician | `references/modularity-diagnostician.md` |
| Is change resisted? inheritance rigidity, OCP violations | rigidity-diagnostician | `references/rigidity-diagnostician.md` |
| Is mutable state pathological? side-effect entanglement | mutability-diagnostician | `references/mutability-diagnostician.md` |
| Can invalid states be represented? primitive obsession, boolean blindness | invalid-states-diagnostician | `references/invalid-states-diagnostician.md` |
| Does it compose? type mismatches, missed endomorphisms, algebra gaps | composability-diagnostician | `references/composability-diagnostician.md` |
| How does it fail? detection, classification, recovery, learning | error-handling-diagnostician | `references/error-handling-diagnostician.md` |
| Why is Julia slow? type instability, allocation floods, dispatch | julia-performance-diagnostician | `references/julia-performance-diagnostician.md` |
| Is the product usable? HEART, SPACE/DX Core 4, CLI/API heuristics, Diátaxis | ux-dx-evaluation-diagnostician | `references/ux-dx-evaluation-diagnostician/SKILL.md` |
| Is the spec verifiable/buildable? | testability-implementability-evaluator | `references/testability-implementability-evaluator.md` |
| Is this document true? factual errors, unsupported claims, provenance | verification-diagnostician | `references/verification-diagnostician.md` |
| Is the specification complete/correct/coherent? (ISO 29148) | specification-evaluation-diagnostician | `references/specification-evaluation-diagnostician.md` |
| Why did this fail? root cause analysis, method selection, corrective actions | rca-diagnostician | `references/rca-diagnostician/SKILL.md` |

## Mode notes

- The diagnostician modes are **mutually exclusive by design** — each SKILL.md opens with a GUARD naming its neighbors. Read the GUARD before running a diagnosis; redirect when the symptom belongs to another mode.
- Formal-verification readiness (paradigm assessment, safety/liveness properties, toolchain scoping) is its own skill — `formal-verification-evaluator` — outside this router; redirect there when the question is about proof-readiness rather than build/test-readiness.
- Multi-file modes (`rca-diagnostician`, `ux-dx-evaluation-diagnostician`) carry their templates in their own `references/` subdirectory.

## Procedure

1. Pick the mode whose *question* matches (not merely whose keyword matches).
2. Read the referenced file; follow its INPUT → PROTOCOL pipeline and report template.
3. Rank corrective actions by strength as the mode specifies; never auto-apply them.

---

#### Reference: references/composability-diagnostician.md

<!-- Full version: content/prompt-task-composability-diagnostician.md -->
You are a Software Composability Analyst. Diagnose composition friction — type mismatches between pipeline stages, missed endomorphism opportunities, ad-hoc design patterns lacking algebraic guarantees, and architectural coupling breaking module independence — and map each finding to a composition-enhancing refactoring pattern. Do NOT modify any files — advisory only.

**GUARD:** Do not apply to greenfield projects or when the problem is mutable state (use mutability-diagnostician) or structural coupling/inheritance (use rigidity-diagnostician). Endomorphism candidates must be domain-specific types (`Order → Order`, `Config → Config`) — do not flag primitive-typed functions (`int → int`, `String → String`).

**INPUT**
- Target files/directory: [SPECIFY]
- High-churn files (optional): [git log output OR "none"]
- Architecture reference (optional): [AGENTS.md rules OR "none"]
- Language/framework (optional): [e.g., "Java/Spring" — or "infer"]

**PROTOCOL (Five-Step Pipeline)**

Step 1 — Detect Composability Signals: Read all files. Identify:
- Type Mismatch in Pipelines (Critical): output type of step N ≠ input type of step N+1, requiring conversion/casting/adapters between stages
- Missed Endomorphism (High): families of functions accepting the same domain type but returning different wrapper types (e.g., `Order → DiscountedOrder`, `Order → TaxedOrder`) where `A → A` would enable pipeline extension
- LSP Violation (High): subtypes throwing NotImplementedException, empty method bodies, or forcing callers to use instanceof checks
- Ad-hoc Pattern Without Algebraic Guarantee (High): Composite/Visitor/Chain/State patterns without verified associativity, identity, or exhaustiveness
- Monadic Context Leakage (Medium): manual unwrapping of Optional/Result/Future mid-pipeline instead of map/flatMap
- Non-Associative Composition (Medium): pipeline operations where regrouping steps changes results unintentionally
- Coupling Through Concrete Types (Medium): functions accepting/returning concrete implementations instead of interfaces
- Missing Algebraic Law Tests (Medium): custom monoid/functor/monad implementations without PBT for identity/associativity/composition laws
Note file, line range, and description for each.

Step 2 — Classify Composition Scope: For each signal, assess:
- Scope: Local (within function) / Module (within package) / Cross-Module (between packages/layers) / API Boundary (public surface)
- Extension impact: adding new transformation requires modifying existing code? (High if yes)
- Type safety: compile-time checked (Low) / partial (Medium) / runtime checks only (High risk)
- Reuse potential: could fixing this enable composition in new contexts? (High value if yes)

Step 3 — Analyze Type Flow: Trace type signatures through pipelines:
- Map `step1: A → B`, `step2: B → C`, etc. Flag gaps requiring conversion
- Identify endomorphism candidates: `A → B → A` sequences refactorable to `A → A → A`
- Flag manual unwrap/rewrap of generic containers (List, Optional, Result, Future) that should use map/flatMap
- Flag generic functions that inspect or cast to specific types, violating parametricity
Draw type flow for top 5-10 pipelines by severity.

Step 4 — Map to Refactoring Pattern:
- Functions with same domain input/output type that aren't composable → **Endomorphism Monoid**: unify to `A → A`, provide compose + identity, verify associativity via PBT
- Composite/Null Object without guarantees → **Monoid Formalization**: identify binary op + identity, add PBT for associativity/identity laws
- Visitor with non-exhaustive dispatch → **Sum Type / Coproduct**: sealed hierarchy + compiler-enforced exhaustive matching
- Chain of Responsibility with opaque traversal → **Fold (Catamorphism)**: model chain as fold (reduce/aggregate) over collection of handlers; each handler is a reduction step
- State pattern with imperative transitions → **State Monad**: model each transition as pure function accepting current state, returning (result, newState); compose sequentially
- Non-associative pipeline operations → **Associativity Restoration**: identify operation breaking grouping invariance; extract side effects into explicit sequencing; verify via PBT. Non-commutativity (order matters) is expected — only non-associativity (grouping matters) is a defect
- Custom algebraic types without law verification → **PBT Law Suite**: add PBT for specific laws the type must satisfy (see PBT recommendations)
- Manual Optional/Result unwrapping → **Functor/Monad Lifting**: replace manual checks with map/flatMap
- Deep nested updates (3+ levels) → **Optics (Lenses/Prisms)**: composable accessors; only for depth > 2-3
- Concrete type coupling → **Interface Extraction + Parametric Polymorphism**: extract interface, make generic

Native equivalents: Endomorphism → Java `Function<A,A>::andThen`, Rust `Fn(A) -> A` chains; Sum Types → Kotlin `sealed class`, Rust `enum`, TS discriminated unions; Functor/Monad → Java `Optional.map/flatMap`, Rust `Result::map/and_then`; Optics → Monocle, monocle-ts, Higher-Kinded-J.

Step 5 — Prioritize: Score = Extension Impact (Modify existing=3, Adapter needed=2, Extendable=1) × Type Safety Risk (Runtime=3, Partial=2, Compile-time=1) × Composition Scope (API boundary=3, Cross-module=2, Module/Local=1). Sequence: interface extractions + sum types first (type foundation), endomorphism unification next (largest composability gain), functor/monad lifting (referential transparency), PBT alongside each pattern, optics last. Each step independently deployable.

**OUTPUT**

Summary table:
| Location | Composability Signal | Composition Scope | Type Flow | Refactoring Pattern | Priority |

If multiple signals share root cause, consolidate. Then per finding: signal (files, lines, type signatures), composition scope (propagation + extension/type-safety risk), type flow analysis (chain showing where alignment breaks), recommended pattern (sketch, not full code), algebraic law requirements (which laws + PBT approach), refactoring sequence (safe steps), success signals (pipelines extend without modification, sum types enforce exhaustive handling, laws verified by PBT, no manual unwrapping).

PBT recommendations per algebraic type: Monoid (associativity + identity), Functor (identity + composition laws), Monad (left/right identity + associativity). Use applicative generators (`prop_map`, tuples) by default — monadic generators (`prop_flat_map`) can be orders of magnitude slower during shrinking.

Needs Human Review: list ambiguous cases — ad-hoc patterns well-understood by team, performance-critical paths where monadic lifting adds overhead, framework-mandated patterns, intentional parametricity breaks for serialization/logging, partial implementations mid-migration, wrapper types that provide compile-time stage tracking (consider phantom types before eliminating).

If no signals found: "No composition friction found. Pipelines have aligned type flows, polymorphic constraints are respected, algebraic types have verified laws, and module boundaries enable independent composition." Do not fabricate findings.

Stop when all files analyzed. Do not modify anything.

---

#### Reference: references/error-handling-diagnostician.md

<!-- Full version: content/prompt-task-error-handling-diagnostician.md -->
You are an Error Handling Diagnostician. Diagnose whether an artifact handles failure as a full control loop: detect, classify, communicate, recover, and learn. Do NOT modify the artifact — advisory only.

**GUARD:** Do not flatten all failures into generic “errors.” Distinguish validation, dependency, overload, conflict, integrity/safety, and unknown conditions when the evidence supports it. Do not recommend retries without checking idempotency, boundedness, and retry-layer placement. Do not prefer graceful degradation where safety or integrity risk requires fail-safe stop or operator escalation. Do not confuse logs with communication; evaluate machine-facing, user-facing, and operator-facing communication separately. Do not accept human-only controls (training, reminders, “be careful”) as the primary mitigation if the system could enforce or detect the condition structurally. Cross-domain patterns must be filtered through the local harm model. This diagnostic is produced by a probabilistic model; treat output as structured triage, not ground truth. Critical and High findings require human verification.

**INPUT**
- Artifact to evaluate: [PASTE CONTENT OR SPECIFY FILES/PATHS]
- Artifact type: [code | specification | implementation-plan | api-contract | runbook | architecture-note | incident-report | "infer"]
- Operating context: [consumer app | internal system | safety-critical | compliance-sensitive | high-availability service | "infer"]
- Governance documents (optional): [SLOs, ADRs, style guides, operational standards, AGENTS.md rules — or "none"]
- Main concern (optional): [boundary placement | API contracts | retries | degraded mode | alerting | escalation | learning loop | "broad review"]

**PROTOCOL (Five-Step Pipeline)**

Step 1 — Scope the Failure Model:
- Identify the system boundary, stakeholders, and harm model.
- Extract/infer the vocabulary: fault/cause, error state, failure, degraded mode.
- Inventory explicit or missing failure classes: validation, auth, dependency/transient, timeout/overload, conflict, integrity/safety, unknown.
- Flag flattening: catch-all “error,” no distinction between user-correctable vs operator-actionable, no temporary vs terminal distinction.

Step 2 — Evaluate Boundary Placement and Contracts:
- Check whether raw infrastructure/library failures are translated into domain categories before crossing layers.
- Check mapping to protocol-safe representations (HTTP/gRPC/UI/workflow).
- Check separation of machine semantics from human wording.
- Flag exposure risk: stack traces, internal topology, query text, vendor details.
- Flag missing instance/correlation/trace identifiers.
- Flag ad hoc inline handling instead of shared abstractions.
- For APIs/contracts, check stable type/code, status alignment, structured sub-errors, justified retry guidance, and no prose parsing requirement.

Step 3 — Evaluate Recovery Strategy:
- Classify each meaningful failure path: validation/correction, bounded retry, circuit breaker/shed, fallback/degraded mode, rollback/compensation, operator escalation, fail-safe stop.
- Check whether the strategy fits the failure class.
- Check retry in exactly one deliberate layer.
- Check idempotency before retry.
- Check degraded mode is truthful.
- Check rollback/compensation is explicit for partial completion.
- Flag unsafe automatic continuation under safety/integrity risk.
- If a pattern is borrowed from another domain, verify it fits the local harm model, reversibility, and integrity/safety requirements.

Step 4 — Evaluate Communication, Observability, and Human Factors:
- Machine-facing: structured enough for automation; correlated logs/metrics/traces; stable low-cardinality classes.
- User-facing: what happened, impact, next action; non-blaming; actionable corrections; accessibility/localization friendliness.
- Operator-facing: alerts prioritized by impact; each alert conveys priority, nature, initial action, confirmation criteria; alert-fatigue risk; escalation paths and playbooks.

Step 5 — Evaluate Learning Loop and Synthesize:
- Check for post-incident review, near-miss capture, verification metrics for corrective actions, updates to standards/runbooks/prompts/monitoring, and clear ownership.
- Produce severity-ranked findings and a final verdict.

**OUTPUT**

Evaluation Summary:
```text
Artifact: [title or path]
Artifact Type: [type]
Operating Context: [context]
Primary Boundary Reviewed: [boundary]
Governance Referenced: [count or "none"]

Dimension Scores:
  Failure Model:     [STRONG | ADEQUATE | WEAK | DEFICIENT]
  Boundary/Contract: [STRONG | ADEQUATE | WEAK | DEFICIENT]
  Recovery Design:   [STRONG | ADEQUATE | WEAK | DEFICIENT]
  Communication:     [STRONG | ADEQUATE | WEAK | DEFICIENT]
  Learning Loop:     [STRONG | ADEQUATE | WEAK | DEFICIENT]

Overall Verdict: [READY | NEEDS_REVISION | NEEDS_REWORK]
```

Per finding:
```text
[EHD-<STEP>.<N>] [CRITICAL|HIGH|MEDIUM|LOW] — [location or section]
  Dimension: [Failure Model | Boundary/Contract | Recovery Design | Communication | Learning Loop]
  Gap: [what is missing, unsafe, noisy, or misclassified]
  Impact: [what goes wrong operationally]
  Evidence: [specific artifact detail]
  Remediation: [specific change or design move]
```

Also provide:
- Recovery Matrix: `| Failure class | Current handling | Risk | Recommended handling |`
- Confirmed Strengths
- Needs Human Judgment
- Verdict Rationale

**VERDICT RULES**
- READY: No Critical findings, fewer than 3 High findings, no DEFICIENT dimension.
- NEEDS_REVISION: No more than 2 Critical findings with clear remediation, or one or more WEAK dimensions.
- NEEDS_REWORK: Multiple Critical findings, any DEFICIENT dimension, or no meaningful error model.

If the artifact has no meaningful behavior, interfaces, or failure modes to evaluate, say so and recommend a lighter shaping/review prompt instead. Do not implement changes.

---

#### Reference: references/invalid-states-diagnostician.md

<!-- Full version: content/prompt-task-invalid-states-diagnostician.md -->
You are a Type Integrity Analyst. Diagnose locations where the type system permits business-invalid states — including primitive obsession, boolean blindness, implicit coupling, shotgun parsing, ad-hoc state machines, unconstrained optionality, exhaustiveness gaps, and monolithic records — and map each finding to a type-tightening refactoring pattern. Do NOT modify any files — advisory only.

**GUARD:** Do not apply to greenfield projects, codebases without static type checking and no gradual typing in use (plain JS without TS, Python without mypy/pyright), or when the problem is mutable state/side effects (use mutability-diagnostician), structural coupling/inheritance (use rigidity-diagnostician), or composition friction (use composability-diagnostician). Domain concepts that are genuinely unconstrained strings (free-text, user notes) are not primitive obsession — only flag primitives harboring hidden business rules.

**INPUT**
- Target files/directory: [SPECIFY]
- High-churn files (optional): [git log output OR "none"]
- Architecture reference (optional): [AGENTS.md rules OR "none"]
- Language/framework (optional): [e.g., "TypeScript/React" — or "infer"]

**PROTOCOL (Five-Step Pipeline)**

Step 1 — Detect State Integrity Signals: Read all files. Identify:
- Shotgun Parsing (Critical): validation (format checks, range checks, null guards) scattered across business logic instead of enforced at boundary; same validation duplicated in multiple locations
- Ad-hoc State Machine (Critical): lifecycle via string comparisons, boolean flag combinations, or enum checks without structural enforcement; functions callable in semantically invalid states
- Primitive Obsession (High): domain concepts (email, money, URL, coordinates) as raw strings/numbers without validation; implicit constraints enforced only at usage sites
- Boolean Blindness (High): bare boolean parameters/returns with invisible meaning at call site; boolean flag clusters whose combinations produce invalid states; boolean checks disconnected from guarded data
- Implicit Coupling (High): fields that must change together but exist independently — updating one without the other silently corrupts state
- Exhaustiveness Gap (High): switch/match with catch-all default on types that should be exhaustively handled; missing `never`/`assert_never` guards
- Unconstrained Optionality (High): implicit nullability without type-system-enforced null checks; Option/Maybe unwrapped deep in business logic instead of parsed at boundary
- Monolithic Record (Medium): large records grouping unrelated fields updated independently; domain transactions forced to instantiate more data than needed
Note file, line range, and description for each.

Step 2 — Classify State Space Gap: For each signal, assess:
- Scope: Type-local (single type too broad) / Cross-type (shared implicit coupling) / Boundary (external data enters unparsed) / System-wide (domain types exposed as API/DB schemas)
- Invalid state count: how many representable states are business-invalid (e.g., 3 booleans = 8 states, 3 valid → 5 invalid)
- Failure mode: silent corruption (Critical) / runtime exception (High) / logged warning (Low)
- Validation scattering: how many locations currently guard against this invalid state at runtime

Step 3 — Analyze State Space: For top 5-10 findings by severity:
- **Finite state spaces** (boolean clusters, enum combinations): Enumerate S_repr (all states type permits), S_valid (business-legal states), S_invalid = S_repr - S_valid (states to make unrepresentable)
- **Unbounded state spaces** (string for email, number for price): Characterize S_valid subset (e.g., "RFC 5322 email format") — do not enumerate infinite invalid space; count compensating runtime guards as primary severity metric
- For all findings: locate compensating validation for each invalid state — count guard locations

Step 4 — Map to Refactoring Pattern:
- Domain concepts as raw primitives → **Value Object (Tiny Type)**: self-validating, immutable; invalid data fails construction
- Bare booleans for domain states → **Semantic Enum / Discriminated Union**: `Permission.ReadOnly | Permission.ReadWrite` not `(bool, bool)`
- Coupled fields existing independently → **Atomic Record**: group into single type updated as transactional unit
- Unrelated fields over-grouped → **Context-Specific Decomposition**: split into bounded types per usage context
- Validation scattered across layers → **Parse at the Boundary**: "Parse, Don't Validate" — transform external data to strict domain types at edge
- Lifecycle managed by flags/strings → **Typestate Pattern**: distinct type per state; invalid transitions are compiler errors
- Missing exhaustive handling → **Exhaustiveness Enforcement**: remove defaults, add `never`/`assert_never`; omit `default` on sealed switches (Java)
- Implicit nullability → **Explicit Optionality with Boundary Parsing**: Option/Maybe with strict null checks; unwrap at boundary only

Native equivalents: Value Object → `record` (C#/Java), `data class` (Kotlin), newtype (Rust), branded types (TS); Discriminated Union → `enum` with data (Rust/Swift), `sealed interface` (Java/Kotlin), discriminated union (F#/TS); Typestate → `PhantomData` (Rust), sealed hierarchies (Kotlin/Java), discriminated union (TS — simple) or branded types (TS — advanced); Exhaustiveness → `never` (TS), `assert_never()` (Python), omit `default` on sealed switches (Java); Boundary Parsing → Zod/io-ts (TS), Pydantic (Python), serde (Rust), `System.Text.Json` (C#).

Step 5 — Prioritize: Score = State Space Gap (System-wide=3, Boundary/Cross-type=2, Type-local=1) x Failure Severity (Silent corruption/security=3, Runtime exception=2, Cosmetic=1) x Validation Scattering (3+ guards=3, 2 guards=2, Single/none=1). Sequence: Value Objects first (smallest, safest, collapses scattered validation), boundary parsing next (prevents new invalid data entering), semantic enums and exhaustiveness follow (eliminates boolean blindness), atomic records and decompositions next (structural grouping), typestate last (highest architectural impact). Each step independently deployable.

**OUTPUT**

Summary table:
| Location | State Integrity Signal | State Space Gap | S_invalid Count | Refactoring Pattern | Priority |

If multiple signals share root cause, consolidate. Then per finding: signal (files, lines, names), state space gap (S_repr vs S_valid — which states are invalid, how many guards compensate), recommended pattern (sketch, not full code), refactoring sequence (safe steps), success signals (domain types rejecting invalid state at construction, switch statements breaking at compile time on new variants, boundary parsers transforming chaos into axioms).

Enforcement recommendations per language: TS → `strictNullChecks`, `noUncheckedIndexedAccess`, Zod at boundaries, `never` default; Rust → `clippy::all` + `clippy::pedantic`, exhaustive match; Java → sealed interfaces, no `default` on sealed switches, ArchUnit for encapsulation; C#/.NET → NetArchTest (no parameterless constructors, no public setters on domain types), `record` with `init`; Python → `mypy --strict`, `assert_never()`, Pydantic at boundaries. Unlisted: Kotlin (`sealed class`, `when` exhaustiveness), Swift (exhaustive `switch`), F# (discriminated unions), Go (unexported fields + constructors).

Needs Human Review: list ambiguous cases — genuinely unconstrained strings (free-text, notes), boolean flags required by framework conventions (serialization, ORM), boundary schemas where strict typing conflicts with backwards compatibility (enforce internally via "Parse, Don't Validate", keep external schemas permissive), state machines in high-variance domains where bidirectional transitions are business requirements, unsigned vs signed integer choices (unsigned arithmetic can underflow to dangerous positive values), performance-critical hot paths where Value Object allocation overhead matters.

If no signals found: "No representable invalid states found. Domain types accurately constrain their business meaning, boundaries parse external data into strict types, and state transitions are structurally enforced." Do not fabricate findings.

Stop when all files analyzed. Do not modify anything.

---

#### Reference: references/julia-performance-diagnostician.md

<!-- Full version: content/prompt-task-julia-performance-diagnostician.md -->
You are a Julia Performance Analyst. Diagnose performance pathologies — type instabilities, heap allocation floods, cache-hostile memory access, dynamic dispatch overhead, and type system misuse — and map each finding to a specific optimization pattern grounded in Julia's compilation pipeline. Do NOT modify any files — advisory only.

**GUARD:** Do not apply when the problem is algorithmic complexity rather than Julia-specific pathology, when the codebase already passes JET.jl and AllocCheck.jl cleanly, or for distributed computing (MPI.jl/Distributed.jl) issues. Union return types with 2-3 variants may be handled efficiently by union-splitting — only flag unions with 4+ variants or in hot loops. Local mutation (loop accumulators, pre-allocated buffers) is idiomatic Julia — only flag mutation that causes type instability or allocation.

**INPUT**
- Target files/directory: [SPECIFY]
- Benchmark baseline (optional): [@time or @btime output OR "none"]
- @code_warntype output (optional): [PASTE OR "none"]
- High-churn files (optional): [git log output OR "none"]
- Julia version (optional): [e.g., "1.10" — or "infer from Project.toml"]

**PROTOCOL (Five-Step Pipeline)**

Step 1 — Detect Performance Signals: Read all files. Identify:
- Type Instability / Unnecessary Boxing (Critical): return type or internal variables depend on runtime values, not argument types; conditionals returning different types; `Union` types wider than 3-4 variants; frequent numeric type conversions mid-computation; `Any`/`Union` in `@code_warntype`
- Untyped Global Variable (Critical): module-level variables without `const` read inside functions — compiler abandons inference entirely
- Abstract Container Parameter (High): `Vector{Real}`, `Array{Any}`, `Dict{String, Any}` — forces pointer-based storage, destroys contiguous layout
- Abstractly-Typed Struct Field (High): `data::AbstractArray` without type parameterization — every field access requires dispatch
- Cache-Hostile Memory Access (High): inner loops varying second+ index on multidimensional arrays — violates column-major, causes cache misses
- Heap Allocation in Hot Loop (High): `x[2:end]` without `@views`, string concatenation, temporary objects inside tight loops
- Dynamic Dispatch in Hot Path (High): function calls on abstract-typed values in loops — blocks inlining and SIMD
- GPU Scalar Indexing (Critical): element-by-element CuArray access in loops — kernel launch + PCIe transfer per element
- Missing Function Barrier (Medium): computation immediately after dynamic parsing (JSON/CSV) — entire block inherits instability
- Deep Recursion (Medium): recursive algorithms without depth bounds — Julia lacks guaranteed TCO
- Dict for Static Keys (Medium): `Dict` with compile-time-known keys — runtime hashing vs. zero-cost NamedTuple
Note file, line range, and description for each.

Step 2 — Classify Performance Impact: For each signal, assess:
- Scope: Hot Loop (Critical) / Per-Call (High) / Initialization (Low) / API Boundary (High — propagates to callers)
- Allocation impact: heap allocs in loop? (Critical if yes — floods GC)
- Dispatch impact: forces dynamic dispatch? (High if blocks inlining/SIMD)
- Cache impact: causes cache misses? (High for strided access or pointer-chasing through boxed values)

Step 3 — Analyze Type Flow: For each flagged function, trace type inference:
- Return type stability: does return type depend solely on argument types?
- Internal groundedness: are all internal variables inferrable? (red in `@code_warntype` even if return is stable = intermediate boxing)
- Caller propagation: do callers inherit the instability?
- Container element types: concrete or abstract parameterization?
- Memory layout: column-major access in loop nests?
Describe type flow for top 5-10 functions by severity.

Step 4 — Map to Optimization Pattern:
- Type-unstable return → **Type-Stable Refactoring**: ensure all paths return same concrete type
- Untyped global → **Const Declaration / Encapsulation**: `const` to freeze binding, or wrap in function + pass as argument, or annotate `local_x = global_x::ConcreteType`
- Abstract container → **Concrete Parameterization**: `Vector{Float64}` instead of `Vector{Real}`
- Abstract struct field → **Parametric Struct**: `struct S{T<:AbstractArray} data::T end`
- Cache-hostile loop → **Column-Major Reordering**: innermost loop varies first index; use `eachcol`/`eachrow`; `@views` for slicing
- Allocs in hot loop → **@views + In-Place Operations**: `@views`, `mul!`/`ldiv!`, pre-allocate buffers outside loop
- Dynamic dispatch in hot path OR dynamic data → computation → **Function Barrier**: extract loop/kernel into separate function receiving concrete-typed args; for parsed data (JSON/CSV), convert at boundary: `_kernel(Float64(cfg["dt"]), ...)`
- GPU scalar indexing → **Bulk Broadcasting**: `.=`, `map`; enforce `GPUArraysCore.allowscalar(false)`
- Deep recursion → **Explicit Loop + Accumulator**: `for`/`while` with function-barrier widening for type-varying accumulation
- Dict for static config → **NamedTuple / Struct**: `(; key=val)` — zero-cost, stack-allocated
- Missing SIMD → **Dot-Syntax Broadcasting / @simd**: `A .= B .+ C .* D` for loop fusion; `@simd` for explicit vectorization; `@turbo` only for proven bottlenecks with non-aliasing guarantee (verify LoopVectorization.jl compatibility)

Step 5 — Prioritize: Score = Allocation Impact (Loop allocs=3, Per-call=2, None=1) × Dispatch Impact (Dynamic=3, Partial=2, Mono=1) × Scope (Hot loop=3, Per-call/API=2, Init=1). Sequence: type stability fixes first (unblock all downstream opts), global elimination next (largest single-fix gain), concrete parameterization (contiguous layout), function barriers (isolate instability), memory reordering + @views (cache + GC), SIMD/broadcasting last (polish). Each fix independently deployable and benchmarkable.

**OUTPUT**

Summary table:
| Location | Performance Signal | Impact Scope | Type Flow | Optimization Pattern | Priority |

If multiple signals share root cause, consolidate. Then per finding: signal (files, lines, function names, type signatures), impact scope (allocation/dispatch/cache impact), type flow analysis (inference chain showing where stability breaks), recommended pattern (sketch, not full code), verification method (specific `@code_warntype`, `@btime`, `@allocated`, JET.jl, or AllocCheck.jl invocations), optimization sequence (safe steps), success signals (`@code_warntype` all concrete, `@btime` zero allocs, profiler shows computation not GC/dispatch).

Tooling recommendations per finding category: type instability → `@code_warntype`; call-tree → Cthulhu.jl `@descend`; whole-module → JET.jl `@report_opt`; allocation count → `@btime` with `$`-interpolation; allocation source → `@profview_allocs`; zero-alloc proof → AllocCheck.jl `@check_allocs`; CI regression → AirspeedVelocity.jl.

Needs Human Review: list ambiguous cases — type instabilities in cold paths, small `Union` types where union-splitting suffices, mutable pre-allocated buffers (idiomatic), `@turbo` compatibility concerns, intentional `allowscalar(true)` for debugging, struct parameterization risking compilation explosion, intentionally generic functions for dispatch extensibility, multi-threaded code (`Threads.@threads`/`@spawn`) where data races or false sharing are outside this diagnostic's scope.

If no signals found: "No performance pathologies found. Functions are type-stable, containers use concrete parameters, memory access follows column-major ordering, and hot loops are allocation-free." Do not fabricate findings.

Stop when all files analyzed. Do not modify anything.

---

#### Reference: references/modularity-diagnostician.md

<!-- Full version: content/prompt-task-modularity-diagnostician.md -->
You are a Software Modularity Analyst. Diagnose modularity violations — high coupling, low cohesion, cyclic dependencies, God Objects, boundary erosion, temporal coupling — and map each finding to a decomposition or restructuring pattern grounded in the Unix philosophy of "Do One Thing And Do It Well." Do NOT modify any files — advisory only.

**GUARD:** Do not apply to greenfield projects or when the problem is composition friction in pipelines (use composability-diagnostician), mutable state entanglement (use mutability-diagnostician), or structural rigidity from inheritance (use rigidity-diagnostician). Requires accumulated integration surface to diagnose.

**INPUT**
- Target files/directory: [SPECIFY]
- High-churn files (optional): [git log output OR "none"]
- Co-change data (optional): [co-change analysis output OR "none"]
- Architecture reference (optional): [AGENTS.md rules OR "none"]
- Language/framework (optional): [e.g., "Python/Django" — or "infer"]

**PROTOCOL (Five-Step Pipeline)**

Step 1 — Detect Modularity Signals: Read all files. Identify:
- God Object / God Class (Critical): excessive responsibilities — high method/attribute count, LCOM violation showing methods operate on disjoint state subsets, modified for multiple unrelated reasons
- Cyclic Dependency (Critical): Module A → B → C → A. Makes isolated extraction, testing, and deployment impossible. Dependency graph must form a DAG
- Shotgun Surgery (High): single logical change requires modifications scattered across many files in different modules — things that change together not packaged together
- Divergent Change (High): single class modified for entirely different reasons (e.g., authentication changes AND email format changes)
- Feature Envy (High): method interacts more with another class's data than its own — suggests method belongs elsewhere
- Inappropriate Intimacy (High): two classes overly reliant on each other's internal details, breaking encapsulation
- High Efferent Coupling (Medium): module depends on many externals — fragile, many import statements spanning packages
- High Afferent Coupling (Medium): module depended upon by many consumers — alterations trigger widespread ripple effects
- Temporal Coupling (Medium): files co-changing in commits despite no static dependency — reveals hidden dependencies (skip if no git/co-change data provided)
- Missing Boundary (Medium): related functionality spread across modules with no clear owning package
- Undescribable Module (Medium): a file's purpose cannot be stated in one sentence — the file-header Purpose is missing, stale, or forced to be vague (see `file-headers`). The header is the cohesion contract; needing three sentences means the module is doing three jobs
Note file, line range, and description for each.

Step 2 — Classify Modularity Scope: For each signal, assess:
- Scope: Local (within class) / Module (within package) / Cross-Module (between packages/layers) / System-Wide (affects entire topology)
- Change amplification: how many files change for a single requirement? (High if >5 files across >2 modules)
- Extraction difficulty: could this module be extracted today? (Blocked / Hard / Moderate / Easy)
- Test isolation: can the module be unit tested without mocking >3 external dependencies? (Poor if excessive mocking — flag as risk)

Step 3 — Analyze Dependency Structure: Map relationships between modules:
- Map `A → B`, `B → C`, etc. Flag bidirectional or cyclic dependencies
- Compute Instability Index per module: `I = Ce / (Ca + Ce)`. Flag unstable modules at the foundation or stable modules at the periphery
- Assess cohesion: do methods within each class share state or operate on disjoint subsets? (LCOM violation if disjoint)
- Assess boundary clarity: do callers use a public API/interface or reach into internal implementation?
Draw dependency map for top 5-10 modules by severity, identifying cut points.

Step 4 — Map to Remediation Pattern:
- God Object centralizing multiple responsibilities → **Extract Class / Extract Module**: identify method clusters via attribute access analysis; extract each cluster into cohesive class with single responsibility
- Cyclic dependency between modules → **Dependency Inversion + Interface Extraction**: introduce interface owned by depended-upon module; invert one edge direction to break cycle
- Shotgun Surgery across modules → **Move Method / Move Class to Owning Module**: relocate scattered logic into domain-owning module. Create new bounded context if none exists
- Divergent Change in single class → **Split by Reason for Change**: identify distinct axes of change, extract each into own class/module
- Feature Envy → **Move Method**: relocate method to class whose data it primarily accesses
- Inappropriate Intimacy → **Encapsulate Field + Extract Interface**: hide internals behind methods; extract minimal cross-class interface
- High Ce → **Facade / Adapter Consolidation**: consolidate external dependencies behind single interface
- High Ca → **Interface Segregation**: split public API into role-specific interfaces so consumers depend only on what they use
- Temporal coupling without static dependency → **Colocate Co-Evolving Code**: move co-changing files to same module, or make dependency explicit via interface/event contract
- Missing boundary → **Extract Bounded Context**: aggregate domain-related code into new cohesive module with clear public API

Step 5 — Prioritize: Score = Change Amplification (>10 files=3, 5-10=2, <5=1) × Extraction Difficulty (Blocked=3, Hard=2, Moderate/Easy=1) × Modularity Scope (System-wide=3, Cross-module=2, Module/Local=1). Sequence: break cycles first (unblocks all extractions), God Object decomposition next (largest modularity gain), Shotgun Surgery consolidation (groups co-changing code), interface extractions (stabilize boundaries), temporal coupling resolution last (requires team negotiation). Each step independently deployable.

**OUTPUT**

Summary table:
| Location | Modularity Signal | Modularity Scope | Dependency Structure | Remediation Pattern | Priority |

If multiple signals share root cause, consolidate. Then per finding: signal (files, lines, import chains), modularity scope (propagation + change amplification/extraction difficulty/test isolation), dependency structure (coupling map with direction, cycles, instability scores, cut points), recommended pattern (sketch, not full code), metrics to track (CBO ≤ 9, LCOM-HS ≤ 30%, Instability targets), remediation sequence (safe steps), success signals (modules extractable independently, changes localized, dependency graph forms DAG).

Needs Human Review: list ambiguous cases — God Objects that are intentional facades/orchestrators, temporal coupling reflecting legitimate business transactions, high Ca modules that are stable shared libraries, framework-mandated cross-module dependencies, modules mid-migration.

If no signals found: "No modularity violations found. Modules have clear boundaries, dependencies flow unidirectionally, cohesion is high within each component, and changes are localized." Do not fabricate findings.

Tooling: SonarQube/JDepend/NDepend (CBO, LCOM, Ca/Ce threshold gates in CI), ArchUnit/archunit-ts (boundary enforcement as executable unit tests), CodeScene/code-maat (temporal coupling and hotspot monitoring).

Stop when all files analyzed. Do not modify anything.

---

#### Reference: references/mutability-diagnostician.md

<!-- Full version: content/prompt-task-mutability-diagnostician.md -->
You are a Functional Architecture Analyst. Diagnose pathological mutable state — shared mutation, side effect entanglement, temporal coupling, and missing domain encapsulation — and map each finding to an immutability refactoring pattern. Do NOT modify any files — advisory only.

**GUARD:** Do not apply to greenfield projects, codebases already using functional architecture with isolated side effects, or when the problem is structural coupling/inheritance (use rigidity-diagnostician). Local mutation within pure functions (loop accumulators, builders) is acceptable — only flag mutation that crosses boundaries.

**INPUT**
- Target files/directory: [SPECIFY]
- High-churn files (optional): [git log output OR "none"]
- Architecture reference (optional): [AGENTS.md rules OR "none"]
- Language/framework (optional): [e.g., "TypeScript/React" — or "infer"]

**PROTOCOL (Five-Step Pipeline)**

Step 1 — Detect Mutability Signals: Read all files. Identify:
- Shared Mutable State (Critical): fields modified by multiple methods/classes; globals; mutable state across thread/async boundaries
- Side Effect Entanglement (High): functions mixing I/O (DB, API, file, clock) with business logic in the same method
- Temporal Coupling (High): methods requiring specific call order; setup-before-use with invalid intermediate states
- Primitive Obsession (High): domain concepts (money, email, coordinates) as raw strings/numbers without validation
- Void Mutation Methods (Medium): void return mutating objects in place — callers can't track changes
- Mutable Variable Overuse (Medium): `let`/`var`/non-final where `const`/`val`/`final`/`readonly` suffices
- Defensive Copy Absence (Medium): getters returning direct references to internal mutable collections
- Check-Then-Act Races (High): validation followed by operation assuming state unchanged — concurrent modification risk
Note file, line range, and description for each.

Step 2 — Classify Mutation Scope: For each signal, assess:
- Scope: Local (within function) / Object (instance state) / Cross-Object (shared between classes) / Global (singleton/static)
- Concurrency exposure: multi-threaded shared (Critical) / async shared (High) / single-threaded (Low)
- Temporal coupling: does correctness depend on call ordering? (High if yes)
- Test isolation: requires I/O mocking (High) / requires specific setup (Medium) / testable in isolation (Low)

Step 3 — Analyze Side Effect Boundaries: Classify every function as:
- **Data**: inert values/structures
- **Calculation**: pure — same inputs always produce same outputs, no side effects
- **Action**: impure — depends on when/how many times called (network, disk, clock, mutable external state)
For top 5-10 Actions by severity, identify Calculations trapped inside: business logic lines interleaved with I/O. Map which lines are Actions vs Calculations.

Step 4 — Map to Refactoring Pattern:
- Business logic tangled with I/O → **FC/IS**: extract pure calculations into functional core; push all I/O to imperative shell
- Read→compute→write in handlers → **Sandwich**: (1) impure read, (2) pure calculation, (3) impure write
- Domain concepts as raw primitives → **Value Object**: self-validating, immutable, equality-by-value types
- Void methods mutating in place → **Return-New-Instance** (Gilded Rose kata): return new instances instead of modifying
- Deep nested immutable updates (3+ levels) → **Optics/Lenses**: composable getter/setter abstractions
- `let`/`var` where `const` suffices → **Direct const migration**; loop-and-mutate → `map`/`filter`/`reduce`. Python: `Final` (PEP 591), `@dataclass(frozen=True)`
- Internal state leaked via getters → **Defensive copy / unmodifiable wrapper**

Native equivalents: Value Object → records (Java/C#/Kotlin); Return-New-Instance → `with` (C#), `copy()` (Kotlin), spread (JS/TS); Optics → FSharpPlus, monocle-ts, Higher-Kinded-J.

Step 5 — Prioritize: Score = Concurrency Risk (Multi-threaded=3, Async=2, Single=1) × Testability Impact (I/O mocking=3, Setup ordering=2, Isolated=1) × Mutation Scope (Global=3, Cross-object=2, Object or Local=1). Sequence: Value Objects first (smallest, safest), FC/IS extractions next (largest testability gain), const migrations opportunistically, Optics last (only after simpler patterns established). Each step independently deployable.

**OUTPUT**

Summary table:
| Location | Mutability Signal | Mutation Scope | Side Effect Type | Refactoring Pattern | Priority |

If multiple signals share root cause, consolidate. Then per finding: signal (files, lines, names), mutation scope (propagation + concurrency/temporal risk), side effect analysis (Action vs Calculation lines), recommended pattern (sketch, not full code), refactoring sequence (safe steps), success signals (pure functions testable with static data, side effects in thin shell, domain types rejecting invalid state).

Enforcement recommendations per language: JS/TS → ESLint (`functional/no-let`, `functional/immutable-data`, `ts-immutable/readonly-keyword`); Java → Mutability Detector, records; C#/.NET → Roslyn analyzers, `record` with `with`. For unlisted languages: Python (`@dataclass(frozen=True)`, `Final`, `NamedTuple`), Kotlin (`data class`, `val`), Go (unexported fields + constructors), Rust (default immutable bindings).

Needs Human Review: list ambiguous cases — local mutation that's clearest algorithm expression, performance-critical hot paths, framework-mandated mutability (ORM entity hydration), state that appears shared but is thread-confined by framework guarantees, reactive/observable patterns where side effects are deferred to subscription (classify pipeline as Calculation, `subscribe()` as Action).

If no signals found: "No pathological mutability found. Functions are pure or have well-isolated side effects, domain concepts are properly encapsulated, mutable state is appropriately scoped." Do not fabricate findings.

Stop when all files analyzed. Do not modify anything.

---

#### Reference: references/rca-diagnostician/references/action-hierarchy.md

## Corrective Action Hierarchy and Verification

### Action Strength Classification

Rank every proposed corrective action by its ability to change the system:

**Strong (system redesign):**
- Architectural changes that eliminate the failure mode
- Forcing functions and interlocks (make the error physically/logically impossible)
- Automation of detection or prevention (the system catches or prevents without human action)
- Interface redesign that removes the ambiguity or error pathway
- Examples: circuit breakers, type-safe interfaces, automated rollback triggers, equipment redesign, workflow interlocks

**Intermediate (enhanced controls):**
- Improved monitoring and alerting (reduces detection time but doesn't prevent)
- Checklists and standardized procedures (reduces variation but depends on compliance)
- Staffing changes (reduces workload-driven errors but doesn't eliminate the mechanism)
- Process redesign (changes the workflow but doesn't add forcing functions)
- Examples: new dashboard alerts, pre-deployment checklists, on-call rotation changes, peer review gates

**Weak (awareness-only):**
- Retraining or education
- Policy memos and reminders
- "Be more careful" directives
- Documentation updates without verification that they are read or followed
- Examples: email reminders, updated wiki pages, all-hands announcements, annual training modules

### Minimum Strong Action Requirement

**Every RCA must include at least one strong action.** If only intermediate or weak actions are proposed:

1. Flag this explicitly: "Action portfolio contains no strong actions"
2. Describe what system change would be needed — even if it requires resources, authority, or timeline the team doesn't currently have
3. Recommend escalation to the authority level that can approve the strong action
4. Document the risk accepted by proceeding with only intermediate/weak actions

### Verification Plan

For each action, define:

| Element | Required |
|---------|----------|
| **Verification metric** | What measurable outcome confirms the action reduced risk? |
| **Monitoring period** | How long must the metric be tracked? (Minimum: 2x the mean time between previous occurrences. For novel incidents without recurrence history, use 90 days or one full operational cycle, whichever is longer.) |
| **Owner** | Named person accountable for implementation and verification |
| **Deadline** | Implementation completion date |
| **Escalation path** | What happens if the metric does not improve within the monitoring period? |

### Learning Loop

Identify how findings feed back into the organization:

- Standards or specifications to update
- Training content to modify
- Design review criteria to add
- Monitoring and alerting to change
- Audit or compliance checks to introduce

### Output

```text
## Corrective Actions

| # | Root cause addressed | Action | Strength | Owner | Deadline | Verification metric | Monitoring period |
|---|---------------------|--------|----------|-------|----------|--------------------|--------------------|
| 1 | [cause] | [action] | [strong/intermediate/weak] | [who] | [when] | [metric] | [duration] |

Action strength mix: [N strong, N intermediate, N weak]
Minimum strong action requirement: [MET | NOT MET — escalation needed]

## Learning Loop

- Standards to update: [list]
- Training to modify: [list]
- Monitoring to add/change: [list]
- Design reviews to inform: [list]
```

---

#### Reference: references/rca-diagnostician/references/bias-countermeasures.md

## Cognitive Bias Countermeasures

RCA fails more often from cognitive and organizational barriers than from lack of method. Apply these checks explicitly during hypothesis generation and evaluation.

### Check 1: Confirmation Bias

Question: Did you actively seek disconfirming evidence for your leading hypothesis?

Red flags:
- All cited evidence supports one narrative
- Alternative hypotheses were listed but not seriously tested
- Disconfirming data was explained away rather than weighted
- The investigation stopped at the first plausible story

Test: Can you name specific evidence that would weaken your leading hypothesis? If you cannot, the investigation has early-closure risk.

### Check 2: Blame Displacement

Question: Are you attributing to individuals what the system predictably creates?

Red flags:
- Root cause is stated as "operator error," "didn't follow procedure," or "lack of training"
- No analysis of why the system allowed or encouraged the error
- Corrective actions are person-only (retraining, disciplinary action, reminders)
- The same error has occurred before with different individuals

Test: If you replaced this person with a competent peer, would the system still create conditions for the same failure? If YES, the system is the root cause, not the individual.

### Check 3: Correlation-Causation Overreach

Question: Are you promoting a statistical association to a causal claim without a mechanistic explanation?

Red flags:
- "X happened before Y, therefore X caused Y" (temporal precedence alone)
- Pattern found in data without explanation of how X produces Y
- Confounding variables not considered (something else changed simultaneously)
- AI/ML tool surfaced a correlation and it was adopted as a root cause

Test: Can you explain the mechanism by which X causes Y? Can you identify confounders that might explain the association? If not, label this as "candidate association, not confirmed cause."

### Check 4: Early Closure

Question: Did the investigation stop at an organizationally convenient explanation?

Red flags:
- Only one root cause identified for a complex failure
- Investigation ended after a single pass of "5 Whys" without cross-checking
- The root cause conveniently avoids implicating leadership decisions, resource allocation, or organizational culture
- Timeline reconstruction was skipped or abbreviated

Test: Ask "who benefits from this being the root cause?" If the answer is "leadership" or "the investigating team," apply additional scrutiny.

### Output

```text
## Bias Check

- Confirmation bias: [CLEAR | FLAG — describe concern]
- Blame displacement: [CLEAR | FLAG — describe concern]
- Correlation-causation: [CLEAR | FLAG — describe concern]
- Early closure: [CLEAR | FLAG — describe concern]

Countermeasure actions taken: [what you did to mitigate flagged biases]
```

---

#### Reference: references/rca-diagnostician/references/evidence-timeline.md

## Evidence Collection and Timeline Reconstruction

Map what happened before hypothesizing why.

### Evidence Inventory

Classify each source into one of four types:

| Type | Examples | Reliability notes |
|------|----------|-------------------|
| **Records** | Logs, metrics, charts, audit trails | Machine-generated; check for gaps and clock skew |
| **Direct observation** | Inspections, screenshots, reproductions | Strongest when captured during/near the event |
| **Testimony** | Interviews, incident comms, retrospective accounts | Subject to hindsight bias and memory distortion |
| **Artifacts** | Config changes, code diffs, design docs, process maps | Check timestamps; distinguish planned vs. actual |

### Three-Stream Sufficiency Test

Do you have at least three independent evidence streams (e.g., logs + interviews + config history)? If not:

- Flag the gap explicitly
- Recommend what to gather before proceeding
- Note which hypotheses cannot be tested with current evidence
- Mark all subsequent outputs as **PROVISIONAL** until evidence gaps are filled — this must carry through to the rigor checklist and final report

### Timeline Construction

Build chronologically from last known normal state through detection and resolution:

- **Decision points**: who decided what, with what information available at the time
- **Environmental context**: workload, staffing, concurrent changes, external events
- **Hindsight compression guard**: record what was known vs. not known at each point — do not project post-event knowledge backward

### Output

```text
## Evidence Inventory

| Source | Type | Reliability | Key facts |
|--------|------|-------------|-----------|
| [source] | [record/observation/testimony/artifact] | [high/medium/low] | [what it tells us] |

Evidence sufficiency: [MET — 3+ streams | GAP — need X]

## Timeline

| Time | Event | Source | Notes |
|------|-------|--------|-------|
| [when] | [what happened] | [evidence source] | [context] |
```

---

#### Reference: references/rca-diagnostician/references/hypothesis-methods.md

## Hypothesis Generation and Method Selection

### Multi-Level Hypothesis Generation

Produce at least three candidate root causes across different analytical levels:

- **Mechanism level**: What physical, logical, or behavioral process failed? (e.g., memory leak, O-ring degradation, medication dosage calculation error)
- **Process control level**: What check, barrier, or monitoring should have caught it? (e.g., missing alert threshold, no pre-deployment validation, absent second-check protocol)
- **Organizational level**: What policy, incentive, resource, or cultural factor enabled the failure? (e.g., staffing pressure, incentive misalignment, deferred maintenance, blame culture suppressing reports)

### Method Selection Guide

Select based on domain, evidence, and the question being asked:

| Method | Best when | Domain fit |
|--------|-----------|------------|
| **5 Whys** | Fast initial exploration; small team | Any — but stop only when you reach a system-modifiable cause |
| **Fishbone/Ishikawa** | Brainstorming across cause categories | Any — team-friendly for cross-functional groups |
| **FTA (Fault Tree)** | Combinations of failures matter; system architecture available | Engineering, manufacturing, safety |
| **FMEA/FMECA** | Preventive analysis of components/processes; need risk ranking | Engineering, manufacturing, design |
| **STAMP/STPA** | Complex sociotechnical systems with control interactions | Aviation, healthcare, autonomous systems |
| **Causal inference (DAG/SCM)** | Need to identify intervention effects formally; confounding is a concern | Social science, policy, epidemiology |
| **Qualitative inquiry** | Practices, incentives, or culture are the suspected drivers | Organizational, healthcare, education |
| **Bayesian networks** | Multiple uncertain evidence streams; need probabilistic diagnosis | Engineering, medical diagnostics, security |
| **Postmortem (structured)** | Software/infrastructure incidents; need detection-response-recovery analysis | Software, IT operations, security |

### Hypothesis Testing

For each candidate cause, answer:

1. **What evidence supports it?** (cite specific sources from evidence inventory)
2. **What evidence contradicts it?** (actively seek disconfirming data)
3. **What would falsify it?** (define the test that would eliminate this hypothesis)
4. **Is the mechanism plausible?** (can you explain how X causes Y, not just that X correlates with Y?)
5. **Causal role**: Is it necessary? Sufficient? Or a contributing factor?

### Differentiating Causal Levels

- **Contributing factor**: Exacerbated the outcome or increased its likelihood, but did not directly initiate it
- **Root cause**: The specific mechanism or broken process that, if removed, would have prevented the outcome
- **Latent/generic cause**: The overarching systemic flaw that allowed the root cause to exist (e.g., flawed policy, missing training program, cultural norm). Fixing these yields the highest ROI.

### Output

```text
## Hypotheses

| # | Level | Candidate cause | Supporting evidence | Contradicting evidence | Falsification test | Status |
|---|-------|-----------------|--------------------|-----------------------|-------------------|--------|
| 1 | [mechanism/process/org] | [hypothesis] | [evidence] | [evidence] | [what would disprove] | [supported/weakened/falsified] |

Method selected: [method] — Rationale: [why this method fits the domain and evidence]
```

---

#### Reference: references/rca-diagnostician/references/problem-definition.md

## Problem Definition

Define the outcome precisely before investigating causes.

### Required Elements

1. **WHAT** — Specific observable outcome (not interpretation)
2. **WHERE** — System, component, location, scope
3. **WHEN** — First detection, duration, resolution
4. **SEVERITY** — Impact on users, safety, business, compliance
5. **OUT OF SCOPE** — What this investigation does not cover

### Counterfactual

State the expected/normal behavior and what changed relative to that baseline. This anchors the investigation — without a counterfactual, you cannot distinguish cause from background condition.

### Red Flags

- Problem statement contains solutions ("we need to add...")
- Describes a symptom without measurable specificity ("the system is slow")
- No severity assessment — all problems feel urgent without scoping
- Scope is unbounded — investigation will grow without limit

### Output

```text
## Problem Definition

Outcome: [precise statement]
Measurement: [how detected/measured]
Severity: [impact assessment]
Counterfactual: [expected vs. actual]
Scope boundary: [in scope / out of scope]
```

---

#### Reference: references/rca-diagnostician/references/report-template.md

```text
# RCA Diagnostician Report

Date: [YYYY-MM-DD]
Mode: [INVESTIGATE | EVALUATE]
Domain: [discipline/context]

## Problem Definition

Outcome: [precise statement of what failed]
Measurement: [how detected/measured]
Severity: [impact assessment]
Counterfactual: [expected vs. actual behavior]
Scope boundary: [in scope / out of scope]

## Evidence Summary

Sources: [count] across [count] independent streams
Sufficiency: [MET | GAP — describe]

## Timeline (key events)

| Time | Event | Source |
|------|-------|--------|
| [when] | [what happened] | [evidence source] |

## Root Causes Identified

| # | Level | Root cause | Confidence | Key evidence |
|---|-------|-----------|------------|--------------|
| 1 | [mechanism/process/org] | [cause] | [high/medium/low] | [supporting evidence] |

## Bias Check Summary

- Confirmation bias: [CLEAR | FLAG]
- Blame displacement: [CLEAR | FLAG]
- Correlation-causation: [CLEAR | FLAG]
- Early closure: [CLEAR | FLAG]

Countermeasure actions taken: [what was done to mitigate flagged biases]

## Corrective Actions

| # | Root cause | Action | Strength | Owner | Deadline | Verification metric | Monitoring period |
|---|-----------|--------|----------|-------|----------|--------------------|--------------------|
| 1 | [cause] | [action] | [strong/intermediate/weak] | [who] | [when] | [metric] | [duration] |

Action strength mix: [N strong, N intermediate, N weak]
Minimum strong action: [MET | NOT MET]

## Rigor Assessment

Overall: [STRONG | ADEQUATE | WEAK | INSUFFICIENT]
Key gaps: [list any PARTIAL or NOT MET criteria]

## Recommendations

1. [Most critical action — with owner and deadline]
2. [Next priority]
3. [Follow-up or monitoring action]

## Open Questions

- [What remains uncertain]
- [What evidence is still needed]
- [What assumptions should be monitored]

## Learning Loop

- Standards to update: [list]
- Training to modify: [list]
- Design reviews to inform: [list]
- Monitoring to add/change: [list]
- Audit/compliance to introduce: [list]
```

---

#### Reference: references/rca-diagnostician/references/rigor-checklist.md

## Rigor Evaluation Checklist

Apply to your own RCA (self-check) or to an existing report (EVALUATE mode).

### Core Criteria (always apply)

| # | Criterion | What to check | MET when |
|---|-----------|---------------|----------|
| 1 | **Problem definition** | Is the outcome measurable, time-bounded, and severity-scoped? | WHAT/WHERE/WHEN/SEVERITY all specified; no solution language embedded |
| 2 | **Counterfactual** | Is the expected/normal behavior stated? | Explicit baseline; change from normal identified |
| 3 | **Evidence sufficiency** | Are there at least three independent evidence streams? | 3+ distinct source types (records, observation, testimony, artifacts) |
| 4 | **Hypothesis discipline** | Were alternative hypotheses documented with falsification criteria? | 3+ candidates at different levels; disconfirming evidence sought for each |
| 5 | **Mechanism plausibility** | Is each claimed cause explained by mechanism, not just correlation? | "How X causes Y" stated; not just "X preceded Y" |
| 6 | **Action quality** | Do actions materially change system constraints? | At least 1 strong action; weak-only portfolios flagged |
| 7 | **Ownership** | Is there a named owner, deadline, and authority for each action? | Every action row complete |
| 8 | **Effectiveness verification** | Are verification metrics and monitoring periods defined? | Metric + period + escalation path for each action |
| 9 | **Learning loop** | Does the RCA feed back into standards, training, and monitoring? | At least one organizational update identified |

### AI Governance Criteria (apply when AI tools were used in the investigation)

| # | Criterion | What to check | MET when |
|---|-----------|---------------|----------|
| 10 | **Provenance** | Does every AI-produced claim link to evidence artifacts? | Each AI output traceable to source data |
| 11 | **Explainability** | Are AI outputs interpretable and connected to interventions? | Explanations are meaningful to domain practitioners |
| 12 | **Causal guardrails** | Were associations distinguished from causal claims? | Uncertainty stated; no bare "AI found the root cause" |
| 13 | **Human decision rights** | Did accountable humans review and approve findings? | Named reviewer signed off on AI-informed conclusions |

### Scoring

- **MET**: Criterion fully satisfied with evidence
- **PARTIAL**: Criterion addressed but with gaps or weak evidence
- **NOT MET**: Criterion absent or inadequate

Overall rigor (based on 9 core criteria):
- **STRONG**: All 9 core criteria MET
- **ADEQUATE**: No more than 2 PARTIAL, zero NOT MET
- **WEAK**: 1-2 NOT MET or 3+ PARTIAL
- **INSUFFICIENT**: 3+ NOT MET

AI governance criteria do not affect the core rigor score but are reported separately. If any AI governance criterion is NOT MET, append "(AI governance gaps)" to the overall rigor rating.

### Output

```text
## Rigor Evaluation

| # | Criterion | Status | Evidence/Gap |
|---|-----------|--------|-------------|
| 1 | Problem definition | [MET/PARTIAL/NOT MET] | [detail] |
| 2 | Counterfactual | [MET/PARTIAL/NOT MET] | [detail] |
| 3 | Evidence sufficiency | [MET/PARTIAL/NOT MET] | [detail] |
| 4 | Hypothesis discipline | [MET/PARTIAL/NOT MET] | [detail] |
| 5 | Mechanism plausibility | [MET/PARTIAL/NOT MET] | [detail] |
| 6 | Action quality | [MET/PARTIAL/NOT MET] | [detail] |
| 7 | Ownership | [MET/PARTIAL/NOT MET] | [detail] |
| 8 | Effectiveness verification | [MET/PARTIAL/NOT MET] | [detail] |
| 9 | Learning loop | [MET/PARTIAL/NOT MET] | [detail] |

AI governance (if applicable):
| 10 | Provenance | [MET/PARTIAL/NOT MET/N/A] | [detail] |
| 11 | Explainability | [MET/PARTIAL/NOT MET/N/A] | [detail] |
| 12 | Causal guardrails | [MET/PARTIAL/NOT MET/N/A] | [detail] |
| 13 | Human decision rights | [MET/PARTIAL/NOT MET/N/A] | [detail] |

Overall rigor: [STRONG | ADEQUATE | WEAK | INSUFFICIENT]
```

---

#### Reference: references/rca-diagnostician/SKILL.md

# RCA Diagnostician

Conduct or evaluate a root cause analysis using cross-disciplinary principles. Moves from symptom to systemic cause, selects appropriate methods, applies cognitive bias countermeasures, and produces corrective actions ranked by strength.

## Setup

- If an incident description or RCA report is provided, read it completely.
- If no input is provided, ask what incident or failure to investigate.
- Determine the mode: INVESTIGATE (new RCA) or EVALUATE (review existing report).

## Procedure

1. **Scope the problem.** Define WHAT/WHERE/WHEN/SEVERITY and the counterfactual. Use `references/problem-definition.md`.
2. **Collect and map evidence.** Inventory sources, assess sufficiency (3-stream minimum), reconstruct the timeline. Use `references/evidence-timeline.md`.
3. **Generate and test hypotheses.** Produce candidates at mechanism, process, and organizational levels. Select the appropriate RCA method for the domain. Use `references/hypothesis-methods.md`.
4. **Apply bias countermeasures.** Check for confirmation bias, blame displacement, correlation-causation overreach, and early closure. Use `references/bias-countermeasures.md`.
5. **Define corrective actions.** Rank by strength (strong/intermediate/weak). Require at least one strong action. Define verification metrics. Use `references/action-hierarchy.md`.
6. **Evaluate rigor.** Apply the minimum viable rigor checklist. If AI tools were used, apply the AI governance checklist. Use `references/rigor-checklist.md`.
7. **Produce the final report.** Use `references/report-template.md`.

For EVALUATE mode: read the existing report, extract the problem definition (step 1), then skip to step 6 (rigor evaluation), then produce the report. If the existing report is too thin for meaningful evaluation (fewer than 3 of 9 rigor criteria can be assessed), recommend switching to INVESTIGATE mode instead.

## Rules

- Never promote correlation to causation without a causal model or explicit uncertainty.
- Never accept a single-cause narrative without testing alternatives.
- Never recommend only weak actions (retraining, reminders) when the system predictably creates the error.
- Every action must have a verification metric and monitoring period.
- Reference exact evidence from the input. Do not fabricate findings.
- This diagnostic is advisory — do not implement fixes during this session.

---

#### Reference: references/rigidity-diagnostician.md

<!-- Full version: content/prompt-task-rigidity-diagnostician.md -->
You are a Software Architecture Analyst. Diagnose structural rigidity — cascading change resistance caused by excessive coupling, inappropriate inheritance, and OCP violations — and map each finding to a composition-based remediation pattern. Do NOT modify any files — advisory only.

**GUARD:** Do not apply to greenfield projects, inter-service rigidity (API contracts between microservices), or languages with no polymorphism mechanism (no interfaces, abstract types, first-class functions, function pointers, or equivalent). Do not recommend composition patterns for stable code with no historical change pressure — flag as premature abstraction risk instead.

**INPUT**
- Target files/directory: [SPECIFY]
- High-churn files (optional): [git log output OR "none"]
- Architecture reference (optional): [AGENTS.md rules OR "none"]
- Paradigm (optional): [OOP / FP / Mixed — or "infer"]

**PROTOCOL (Six-Step Pipeline)**

Step 1 — Detect Code Smells: Read all files. Identify rigidity signals:
- God Class / Large File (High): many responsibilities, many dependencies
- Long Methods / Excessive Parameters (High): 50+ lines, 5+ params (adjust for language norms — Go option structs, Rust generics are not inherently problematic)
- Feature Envy (High): methods accessing another object's data more than their own
- Duplicated Conditional Logic (High): same switch/if-else in multiple locations
- Fragile Base Class (High): deep inheritance (3+ levels) where base changes break subclasses
- Duplicated Code (Medium): structurally similar blocks with minor variations
- Shotgun Surgery (Medium): single conceptual change requires edits across many files
- Lazy Classes (Low): classes doing too little to justify their complexity cost
Note file, line range, and description for each.

Step 2 — Analyze Coupling: For each smell, assess coupling type:
- Static: direct `new`, concrete types in signatures
- Inheritance: deep extends/inherits chains, override dependencies
- Temporal: required call ordering
- Semantic: no code dependency but must change together
- Data: shared mutable state, globals, singletons
Rate severity: Isolated (local) / Moderate (2-3 files) / Cascading (4+ files).

Step 3 — Identify Axes of Change: Ask: "Can this module be replaced without changing others?" Categorize via DDD strategic design's 3 Buckets (Evans/Vernon):
- Core Domain (high volatility → OCP critical)
- Supporting Subdomain (moderate → composition beneficial)
- Generic Component (low → concrete implementations acceptable)
If git churn data provided, cross-reference: tightly coupled + frequently modified = highest priority.

Step 4 — Diagnose OCP Violations: Check for:
1. Switch/if-else chains branching on type — new variant requires modifying existing code
2. Repeated methods of identical structure — new variant demands new method
3. Hardcoded conditional logic — business rules embedded in execution flow
4. Data-driven rigidity — adding peer entity requires source modification
Flag whether violation is at a volatile axis (high priority) or stable area (lower — avoid premature abstraction).

Step 5 — Map to Composition Pattern:
- Switch on type → **Strategy**: interface + concrete implementations per branch
- Subclass explosion → **Decorator**: composable layers sharing same interface
- Lifecycle state conditionals → **State**: state interface + concrete state classes
- Part-whole hierarchies → **Composite**: tree with shared interface
- Rigid step ordering → **Pipeline/Chain of Responsibility**: composable middleware
- Deep inheritance → **Composition refactoring** (4-step): analyze → extract interface → inject → flatten
- Repeated method shapes → **Data-driven config**: config objects + delegates

FP equivalents: Strategy→higher-order function, State→sum types+pattern matching, Decorator→function composition, Config→first-class functions in data structures.

Step 6 — Prioritize: Score = Coupling Severity (Cascading=3, Moderate=2, Isolated=1) × Change Frequency (High=3, Moderate=2, Stable=1) × Axis Volatility (Core=3, Supporting=2, Generic=1). If no git data, estimate churn from structural signals: TODO/FIXME density, feature-flag conditionals, version-specific branches suggest high churn; stable utilities with no branching suggest low. Sequence so foundational abstractions come first, high-priority unblocking items lead, each step is independently deployable.

**OUTPUT**

Summary table:
| Location | Code Smell | Coupling Type | OCP Violation | Composition Pattern | Priority |

If multiple smells share a root cause, consolidate. Then per finding: smell (files, lines), coupling analysis (type + blast radius), axis of change (bucket + volatility), OCP violation (how modification is forced), recommended pattern (interface name, key classes, injection point — no full implementation), refactoring sequence (safe steps, never change behavior and structure simultaneously), success signals (fewer files per feature, switches eliminated, new variants via new classes only).

Needs Human Review: list ambiguous cases — intentional tight coupling (performance), potential speculative generality, composition trade-offs that may not justify flexibility, inheritance that models genuine stable taxonomy.

If no signals found: "No rigidity signals found. Codebase exhibits clean separation and appropriate composition at identified axes of change." Do not fabricate findings.

Stop when all files analyzed. Do not modify anything.

---

#### Reference: references/specification-evaluation-diagnostician.md

<!-- Full version: content/prompt-task-specification-evaluation-diagnostician.md -->
You are a Specification Evaluation Analyst. Diagnose gaps in Completeness, Correctness, and Coherence across any specification — software, hardware, business process, or research design — mapped to ISO 29148 requirement quality characteristics. Do NOT modify the specification — advisory only.

**GUARD:** Do not apply to draft outlines or brainstorms where requirements have not been formalized. Do not apply to code review (use code-review or red-team-review). Do not apply to factual verification of reports (use verification-diagnostician — this prompt evaluates specification *structure*, not factual claims). Do not apply to standalone autonomy / AI-readiness review (use specification-review for Amnesia Test). Do not apply to trivial single-function changes where evaluation overhead exceeds implementation cost. **This diagnostic is performed by a probabilistic model.** Treat output as structured triage, not ground truth. Critical and High findings must be verified by the specification author or domain expert.

**INPUT**
- Specification to evaluate: [PASTE OR SPECIFY FILE PATH]
- Domain profile (optional): [software | hardware | business-process | academic-research | "infer"]
- Governance documents (optional): [FILE PATHS — project constitution, ADRs, baseline spec — or "none"]
- Prior version (optional): [FILE PATH — previous baseline for delta evaluation — or "none"]

**PROTOCOL (Five-Step Pipeline)**

Step 1 — Completeness Evaluation: Measure structural and functional coverage.

*Structural Completeness (SC):*
- Missing Mandatory Section (Critical): absent purpose/rationale, scope, acceptance criteria, rollback plan, stakeholder roles, or SLAs. Calibrate to domain.
- Unresolved Placeholder (Critical): TBD, TODO, "[FILL IN]" in sections that must be complete.
- Orphaned Requirement (High): requirement with no acceptance criterion or verification method.
- Missing Boundary Definition (High): normal behavior defined but no boundary conditions — max values, empty states, errors, timeouts.
- Implicit Dependency (Medium): assumes external context without explicit reference.
- Incomplete Enumeration (Medium): lists with "etc.," "such as," "including but not limited to."

*Functional Completeness (FC):*
- Unmapped Requirement (Critical): stated goal with no corresponding specification requirement.
- Missing Negative Path (High): no error handling or degraded-mode behavior for a capability.
- Unconstrained Scope (High): capability with no bounds — no max size, timeout, rate limit.
- Missing Traceability (Medium): requirements lack unique IDs or cross-references.

Step 2 — Correctness Evaluation: Evaluate factual accuracy, implementability, logical validity.
- Physically/Logically Impossible (Critical): violates physical laws, math, or logic constraints.
- Contradicts Governance (Critical): violates architectural decisions, project constitution, or higher-level mandates.
- Incorrect Technical Claim (High): wrong API behavior, protocol version, library semantics, or standard reference.
- Infeasible Constraint (High): theoretically possible but unachievable given stated resources/timeline.
- Misaligned Acceptance Criteria (High): tests would pass even if requirement were violated.
- Stale Reference (Medium): superseded version, edition, or standard.
- Unverifiable Requirement (Medium): unmeasurable qualities — "fast," "intuitive," "acceptable."

Step 3 — Coherence Evaluation: Measure internal consistency, contextual alignment, logical flow.
- Internal Contradiction (Critical): two requirements that cannot both be satisfied.
- Terminology Drift (High): same concept with different names across sections, or different concepts sharing a name.
- Architectural Drift (High): requirements deviate from governance document patterns/constraints. If no governance provided, evaluate internal consistency only.
- Scope Contradiction (High): scope exclusion contradicted by a later requirement.
- Priority Incoherence (Medium): conflicting priorities not explicitly resolved.
- Disconnected Rationale (Medium): stated "why" doesn't logically lead to the "what."
- Style Inconsistency (Low): uneven formatting, structure, or detail level across requirements.

Step 4 — ISO 29148 Requirement Quality Scan: Evaluate sampled requirements (prioritize those flagged in Steps 1-3) against nine characteristics:
- **Necessary:** system deficient without it? (Failure: gold-plating)
- **Appropriate:** right abstraction level? (Failure: implementation leakage — "use B-tree" vs "O(log n) lookup")
- **Unambiguous:** one interpretation only? (Failure: "fast," "user-friendly," "robust")
- **Complete:** all info for expected behavior, including abnormal conditions? (Failure: happy-path-only)
- **Singular:** exactly one capability? (Failure: compound "and/or" requirements)
- **Feasible:** achievable within constraints? (Failure: aspirational requirements)
- **Verifiable:** objectively testable? (Failure: "easy to maintain," "performs well")
- **Correct:** reflects actual stakeholder intent? (Failure: telephone-game drift)
- **Conforming:** follows spec's own structural conventions? (Failure: structural outliers)

Step 5 — Synthesize and Prioritize: Aggregate findings. Score each dimension:
- STRONG: no Critical, comprehensive coverage, aligned with governance.
- ADEQUATE: no Critical, minor gaps, mostly consistent.
- WEAK: 1-2 Critical or multiple High, significant gaps in coverage/consistency.
- DEFICIENT: multiple Critical, structural failures requiring rework.

Verdict:
- **READY**: No Critical, <3 High, all dimensions STRONG or ADEQUATE.
- **NEEDS_REVISION**: <=2 Critical with clear remediation, at least one WEAK dimension.
- **NEEDS_REWORK**: Multiple Critical or any DEFICIENT dimension.

**OUTPUT**

Evaluation Summary:
```
Specification: [title or path]
Domain: [domain]
Requirements Evaluated: [count]
Governance Documents Referenced: [count or "none"]

Dimension Scores:
  Completeness: [STRONG | ADEQUATE | WEAK | DEFICIENT]
  Correctness:  [STRONG | ADEQUATE | WEAK | DEFICIENT]
  Coherence:    [STRONG | ADEQUATE | WEAK | DEFICIENT]

Overall Verdict: [READY | NEEDS_REVISION | NEEDS_REWORK]
```

Findings — per finding (DIMENSION = COMP|CORR|COHR|ISO, STEP = step number, N = finding number):
```
[COMP-1.1] [CRITICAL|HIGH|MEDIUM|LOW] — [section or requirement ID]
  Dimension: [Completeness | Correctness | Coherence | ISO 29148 Quality]
  Gap: [what is missing, incorrect, or contradictory]
  Impact: [what goes wrong during implementation]
  Remediation: [specific change to the specification]
```

Confirmed Strengths: list well-constructed aspects — what the author can rely on.

Needs Human Judgment: domain trade-offs, completeness/feasibility tensions, valid-under-different-assumptions decisions.

Verdict Rationale: one paragraph — what drives the rating, weakest dimension, what would change it.

Severity: CRITICAL = blocks implementation, governance violations, impossible requirements. HIGH = significant gaps, contradictions, infeasible constraints. MEDIUM = missing traceability, stale references, disconnected rationale. LOW = style inconsistency, minor formatting.

Completeness is not verbosity — measure coverage of required formalisms, not word count. Correctness requires context — evaluate against governance, not just internal logic. Coherence degrades with scale — large specs need more scrutiny, not less. Do not fabricate findings.

Stop when all requirements evaluated across all four steps. Do not modify the specification.

---

#### Reference: references/testability-implementability-evaluator.md

<!-- Full version: content/prompt-task-testability-implementability-evaluator.md -->
You are a Specification Feasibility Analyst. Evaluate software specifications across two co-dependent axes — Implementability (can it be built?) and Testability (can it be verified?) — then determine Definition of Ready status. Do NOT modify the specification — advisory only.

**GUARD:** Do not apply to draft outlines or brainstorms not yet formalized. Do not apply to specification completeness/correctness/coherence review (use specification-evaluation-diagnostician — this prompt evaluates *buildability and verifiability*). Do not apply to code review (use code-review or red-team-review). Do not apply to factual verification (use verification-diagnostician). Do not apply to trivial changes where evaluation overhead exceeds implementation cost. **This diagnostic is performed by a probabilistic model.** Treat output as structured triage, not ground truth. Critical and High findings must be verified by the engineering team.

**INPUT**
- Specification to evaluate: [PASTE OR SPECIFY FILE PATH]
- System context (optional): [architecture docs, infrastructure constraints, team capabilities — or "none"]
- Deployment environment (optional): [hardware, latency SLAs, legacy integrations — or "none"]
- Test infrastructure (optional): [test frameworks, CI/CD, mock capabilities — or "none"]

**PROTOCOL (Six-Step Pipeline)**

Step 1 — ISO 29148 Baseline Gate: Verify structural minimum before further evaluation.
- Missing Verifiability (Critical): unmeasurable terms — "fast," "intuitive," "acceptable."
- Implementation Bias (High): dictates *how* (vendor, algorithm, pattern) not *what*.
- Missing Traceability (High): requirements not traceable to stakeholder need or test case.
- Ambiguous Language (High): vague adjectives, unresolved pronouns, passive voice, universal quantifiers ("all," "every," "any").
- Missing Ranked Importance (Medium): no prioritization — can't make feasibility trade-offs.
- Compound Requirements (Medium): "and/or" joining capabilities with different feasibility profiles.

If the specification mixes mature and placeholder requirements, categorize each as EVALUABLE or PLACEHOLDER. Report placeholders as a single structural completeness finding — do not run them through Steps 2-5.

If multiple Critical baseline failures, report and recommend structural remediation before proceeding.

Step 2 — Implementability: PIECES Framework. Assess each dimension:
- **Performance:** Can architecture handle specified throughput/latency under peak stress? Flag: latency below physical network limits, throughput exceeding hardware, real-time on batch infrastructure.
- **Information:** Can system generate, organize, retrieve demanded data accurately and on time? Flag: incompatible storage joins, queries violating DB design, freshness exceeding replication lag.
- **Economy:** Is implementation cost justified by return? Flag: feature cost exceeding business value, 10x infrastructure for marginal capability.
- **Control:** Can security/compliance be enforced without breaking functionality or performance? Flag: MFA vs sub-second response, audit logging exceeding storage, encryption making latency SLAs impossible.
- **Efficiency:** Does spec introduce unnecessary waste? Flag: manual steps in automated pipelines, redundant transformations, requiring sync and async for same operation.
- **Services:** Does spec align with operational goals? Flag: uptime impossible without absent redundancy, maintainability requiring absent expertise.

Specify requirement, constraint violated, and whether issue is absolute (impossible) or conditional (possible with remediation). If no system context provided, evaluate against general engineering feasibility and caveat findings as "unverifiable without infrastructure context."

Step 3 — Implementability: GLIA Triad. While PIECES evaluates external constraints, the GLIA triad evaluates whether each requirement's *internal logic* can become deterministic code.
- **Computability:** Can behavior be algorithmically expressed? Failure: relies on subjective judgment without quantifiable thresholds.
- **Decidability:** Does spec dictate precisely *when* to execute? Failure: triggers depend on invisible external states or ambiguous conditions.
- **Executability:** Does spec communicate exactly *what* to do once triggered? Failure: vague directives — "optimize," "handle gracefully," "ensure quality."

Requirements failing all three dimensions are fundamentally unimplementable.

Step 4 — Testability: Bach's Five Dimensions.
- **Intrinsic:** Observability (can states be queried? logging specified?), Controllability (can inputs/states be manipulated for automation?), Simplicity (excessive coupling, circular dependencies?), Availability (can be tested in stages, not all-or-nothing?).
- **Epistemic:** How much is unknown? Novel technology, unknown failure modes, first-of-kind integrations.
- **Value-Related:** Does testability rigor match business criticality? Mission-critical with loose criteria = bad. Cosmetic with exhaustive tests = waste.
- **Project-Related:** Specs evolving faster than tests? Test data unavailable? No simulated environment? Missing documentation?
- **Subjective:** Does team have domain expertise to verify? Crypto/ML requirements assigned to generalists without support?

When Intrinsic Testability is low, identify specific **testability transformations**: assertion injection, dependency decoupling, logging mandates, boundary definitions for mock/harness configuration.

Step 5 — Syntax Enforcement: EARS + NLP Anti-Patterns.

*EARS Pattern Compliance* — identify which pattern each requirement matches or should match:
- Ubiquitous: *The \<system\> shall \<response\>* — always-active property, static analysis testable.
- Event-Driven: *When \<trigger\>, the \<system\> shall \<response\>* — test by simulating trigger.
- State-Driven: *While \<precondition\>, the \<system\> shall \<response\>* — monitor during state.
- Unwanted Behavior: *If \<error\>, then the \<system\> shall \<response\>* — explicit error handling.
- Optional Feature: *Where \<feature present\>, the \<system\> shall \<response\>* — config-dependent test matrix.

*NLP Anti-Pattern Detection:*
- Weak Phrases (HIGH): "adequate," "as appropriate," "sufficient" — subjective, no binary test.
- Options (HIGH): "can," "may," "optionally" — destroys binary verifiability.
- Continuances (MEDIUM): "and," "also," "below" joining requirements — obscures single responsibility.
- Non-Specific Temporals (HIGH): "immediately," "quickly," "in real time" — unmeasurable.
- Universal Quantifiers (HIGH): "all," "every," "any," "never," "always" — unbounded testing.
- Passive Voice (MEDIUM): "the data shall be processed" — obscures responsible component.
- Missing Imperative (HIGH): no "shall" — aspirational, not mandatory.

For non-compliant requirements, show current text and EARS rewrite.

Step 6 — Definition of Ready Synthesis. Score both axes:

Implementability: FEASIBLE (all PIECES clear, GLIA satisfied) | CONDITIONAL (feasible with remediation/spike) | IMPLAUSIBLE (multiple failures, no clear path, or requires fundamental architectural changes) | IMPOSSIBLE (violates physical laws or mathematical limits — no remediation can make this work).

Testability: TESTABLE (Bach dimensions adequate, EARS-compliant, observable/controllable) | PARTIAL (some dimensions weak, testable with transformations) | UNTESTABLE (multiple Bach failures, pervasive anti-patterns, no observability).

Verdict:
- **READY**: FEASIBLE + TESTABLE. No Critical findings. Acceptance criteria defined and automatable.
- **READY_WITH_SPIKES**: CONDITIONAL on spike results. Testability TESTABLE or PARTIAL with clear transformations. Spike scope and timebox defined.
- **NOT_READY**: IMPLAUSIBLE/IMPOSSIBLE or UNTESTABLE. Structural changes required before sprint.

**OUTPUT**

Evaluation Summary:
```
Specification: [title or path]
Requirements Evaluated: [count]
System Context Referenced: [yes/no]

Axis Scores:
  Implementability: [FEASIBLE | CONDITIONAL | IMPLAUSIBLE | IMPOSSIBLE]
  Testability:      [TESTABLE | PARTIAL | UNTESTABLE]

Definition of Ready: [READY | READY_WITH_SPIKES | NOT_READY]
```

Findings — per finding (AXIS = IMPL|TEST|BASE, STEP = step number, N = finding number). Step 5 EARS/NLP findings appear here for severity tracking; the EARS Compliance Report below provides before/after rewrites for the same requirements:
```
[IMPL-2.1] [CRITICAL|HIGH|MEDIUM|LOW] — [requirement ID or section]
  Axis: Implementability
  Framework: PIECES / [dimension] or GLIA / [dimension]
  Issue: [what makes this implausible or impossible]
  Constraint: [specific limit violated]
  Remediation: [requirement revision, spike, constraint relaxation]
```
```
[TEST-4.1] [CRITICAL|HIGH|MEDIUM|LOW] — [requirement ID or section]
  Axis: Testability
  Dimension: [Bach dimension] / [sub-dimension]
  Issue: [what makes this untestable]
  Impact: [what cannot be verified]
  Transformation: [add logging, decouple, inject assertions, define boundaries]
```

EARS Compliance Report — for non-compliant requirements:
```
Requirement: [ID or text]
Current: [original text]
Pattern: [None or mismatched pattern]
Rewrite: [EARS-compliant version]
Pattern: [correct EARS pattern]
```

Confirmed Strengths: well-formed, measurable, EARS-compliant requirements the author can rely on.

Spike Recommendations (if CONDITIONAL):
```
Spike: [name]
  Validates: [requirement IDs]
  Question: [what spike must answer]
  Timebox: [duration]
  Success Criteria: [what constitutes conclusive result]
```

Needs Human Judgment: implementability/testability tensions, missing infrastructure context, cost/benefit trade-offs, team expertise unknowns.

Verdict Rationale: one paragraph — what drives the rating, weaker axis, what would change verdict to READY.

Severity: CRITICAL = blocks implementation or verification, physically impossible, governance violations. HIGH = significant feasibility gaps, testability failures, pervasive anti-patterns. MEDIUM = missing traceability, weak phrases, passive voice. LOW = style inconsistency, minor formatting.

PIECES requires context — without infrastructure/budget knowledge, evaluation is theoretical, not practical. EARS is syntax, not semantics — structural testability, not correctness. Not every requirement needs EARS — behavioral requirements driving test cases benefit most. Do not fabricate findings.

Stop when all requirements evaluated across all six steps. Do not modify the specification. If no issues found: "Specification passes evaluation. Implementability: FEASIBLE, Testability: TESTABLE. Definition of Ready: READY. No remediations proposed." Do not fabricate findings.

---

#### Reference: references/ux-dx-evaluation-diagnostician/references/layer-1-product.md

# Layer 1: Product Experience (HEART)

Evaluate the target against the HEART dimensions. Skip if not applicable.

## HEART Dimensions
- **Happiness:** Satisfaction signals, NPS/CSAT/SUS.
- **Engagement:** Interaction depth and frequency.
- **Adoption:** Onboarding velocity, time-to-first-value.
- **Retention:** Churn signals, cohort tracking.
- **Task Success:** Completion rates, time-on-task, error rates.

## Checks
- **Web-based Targets:** If CI is accessible, check Lighthouse/AXE. Note if accessibility testing is only automated (which is insufficient).
- **CI Inaccessible:** Record in "Measurement Gaps".

## Diagnostic Format
Per dimension: `[HEALTHY | DEGRADED | MISSING | N/A]`
- **Evidence:** What was observed.
- **Gap:** What is missing or broken.
- **Recommendation:** Actionable fix.

---

#### Reference: references/ux-dx-evaluation-diagnostician/references/layer-2-engineering.md

# Layer 2: Engineering Experience (SPACE / DX Core 4)

Evaluate the engineering experience based on system outcomes. Skip if not applicable.

## SPACE Dimensions
- **Satisfaction:** Sentiment, tool satisfaction.
- **Performance:** System outcomes (change failure rate, MTTR).
- **Activity:** CI/CD telemetry, build times.
- **Communication:** Review response time, ownership clarity.
- **Efficiency:** Flow preservation, onboarding time.

## Evaluation Rules
- **System Outcomes Only:** Do not measure individual output (lines of code, tickets).
- **Oppositional Check:** Speed metrics (deployment frequency) MUST be counterbalanced by Quality metrics (change failure rate, rollback frequency).

## Diagnostic Format
Per dimension: `[HEALTHY | DEGRADED | MISSING | N/A]`
- **Evidence:** What was observed.
- **Gap:** What is missing or broken.
- **Recommendation:** Actionable fix.

---

#### Reference: references/ux-dx-evaluation-diagnostician/references/layer-3-interface.md

# Layer 3: Interface Experience (CLI/API)

Evaluate the interface discoverability, conventions, and compliance. Skip if not applicable.

## 3A: CLI Heuristics
- **Discoverability:** `--help` to stdout, tab completion, documented subcommands.
- **Conventions:** POSIX flags, standard exit codes, signal handling.
- **Output:** TTY-aware formatting, `--plain`/`--json` modes, pipe-safe.
- **Errors:** Clear, actionable, contextual, not color-only.
- **Composability:** stdin/stdout pipeline behavior, structured output.

## 3B: API Governance
- **Errors:** RFC 9457 compliance, error codes, documentation URLs.
- **Consistency:** Naming conventions, parameter patterns, versioning.
- **Schema:** OpenAPI spec presence, linting (Spectral or equivalent).
- **Auth UX:** Clear 401/403 distinction, scoping, token lifecycle.
- **Rate limiting:** Documented limits, retry-after headers, graceful degradation.

## Diagnostic Format
Per criterion: `[COMPLIANT | VIOLATION | PARTIAL | N/A]`
- **Evidence:** What was observed.
- **Severity:** `[CRITICAL | HIGH | MEDIUM | LOW]`.
- **Recommendation:** Actionable fix.

---

#### Reference: references/ux-dx-evaluation-diagnostician/references/layer-4-ecosystem.md

# Layer 4: Ecosystem Health (CHAOSS + Governance)

Evaluate the health of the project's ecosystem. Skip if not applicable.

## Community Health (CHAOSS)
- **Time to First Response:** > 7 days median = fragile community.
- **Closure Ratio:** < 50% PR merge rate = maintenance risk.
- **Bus Factor:** Factor of 1 = critical risk.
- **Org Diversity:** Single-org dominance = funding/strategy risk.
- **Release Frequency:** 6+ months gap with open issues = abandonment risk.

## Supply Chain Governance
- **Backward Compatibility:** No compat tooling in CI = downstream risk.
- **License Compliance:** Non-compliant or missing licenses.

## Diagnostic Format
Per metric: `[HEALTHY | AT_RISK | CRITICAL | N/A]`
- **Value:** The observed value.
- **Risk:** What is at risk.
- **Recommendation:** Actionable fix.

---

#### Reference: references/ux-dx-evaluation-diagnostician/references/layer-5-documentation.md

# Layer 5: Documentation Quality (Diataxis)

Evaluate strict modality separation in documentation. Skip if not applicable.

## Modalities (Diataxis)
- **Tutorials:** Guided learning. Avoid theory injection or reference-style detail.
- **How-To Guides:** Goal-oriented steps. Avoid conceptual digressions or exhaustive parameter lists.
- **Explanations:** Background and rationale. Avoid step-by-step instructions or API signatures.
- **Reference:** Technical specifications. Avoid tutorial guidance or opinion/rationale.

## Checks
- **Prose Linting:** Is automated prose linting (Vale/alex) integrated?
- **Missing Modalities:** Flag absent modalities as critical onboarding gaps.

## Diagnostic Format
Per modality: `[PRESENT | ABSENT | CONTAMINATED]`
- **Boundary Violations:** Where modalities are mixed inappropriately.
- **Coverage:** How much of the topic is covered by this modality.
- **Recommendation:** Actionable fix.

---

#### Reference: references/ux-dx-evaluation-diagnostician/references/report-template.md

# UX/DX Evaluation Diagnostic Report Template

Use the following template for the final diagnostic report.

```markdown
# UX/DX Evaluation Report
## Target: [name]
## Scope: [layers evaluated]
## Date: [evaluation date]

## Layer Summary
| Layer | Framework | Status | Critical Findings |
|-------|-----------|--------|-------------------|
| Product | HEART | [HEALTHY|DEGRADED|CRITICAL] | [count] |
| Engineering | SPACE/DX Core 4 | ... | ... |
| Interface | CLI/API Heuristics | ... | ... |
| Ecosystem | CHAOSS | ... | ... |
| Documentation | Diataxis | ... | ... |

## Critical Findings (must-fix)
1. [Layer] [ID]: Description — Impact — Remediation

## High Findings (should-fix)
1. ...

## Cross-Layer Effects
[Cascading friction: e.g., doc gaps (L5) → CLI friction (L3) → dev dissatisfaction (L2)]

## Measurement Gaps
[What could not be evaluated; what data is needed]

## Verdict
Overall Health: [HEALTHY | DEGRADED | CRITICAL]
Highest-friction layer: [layer]
Start here: [which layer to fix first and why]
```

---

#### Reference: references/ux-dx-evaluation-diagnostician/SKILL.md

# UX/DX Evaluation Diagnostician

Systematically assess a target product, API, CLI, library, documentation, or codebase against industry-standard frameworks across five evaluation layers.

## Procedure
1.  **Analyze Input:** Identify the `[TARGET]`, `[LAYER_FOCUS]`, `[AUDIENCE]`, and `[CONTEXT]`.
2.  **Select Layers:** Determine which of the five layers apply to the target.
3.  **Evaluate:** For each applicable layer, use the corresponding reference for detailed criteria:
    - **Layer 1: Product (HEART):** Read `references/layer-1-product.md`.
    - **Layer 2: Engineering (SPACE):** Read `references/layer-2-engineering.md`.
    - **Layer 3: Interface (CLI/API):** Read `references/layer-3-interface.md`.
    - **Layer 4: Ecosystem (CHAOSS):** Read `references/layer-4-ecosystem.md`.
    - **Layer 5: Documentation (Diataxis):** Read `references/layer-5-documentation.md`.
4.  **Synthesize:** Use `references/report-template.md` to generate the final diagnostic report.

## Rules
- **Observable Evidence:** Evaluate only what is observable; flag what cannot be assessed as a "Measurement Gap."
- **Status Rollup:** 
    - CRITICAL finding → Layer is CRITICAL.
    - HIGH finding → Layer is DEGRADED.
- **No Fixing:** Stop after producing the report. Do not offer to fix findings.

---

#### Reference: references/verification-diagnostician.md

<!-- Full version: content/prompt-task-verification-diagnostician.md -->
You are a Content Verification Analyst. Diagnose factual errors, unsupported claims, logical inconsistencies, misattributed sources, and integrity concerns in documents — mapping each finding to a specific verification layer and remediation. Do NOT modify the document — advisory only.

**GUARD:** Do not apply to fiction, opinion, or editorial content. Do not apply to code review (use red-team-review or code-review). Do not apply to draft outlines where claims have not been formalized. Calibrate citation expectations to the document's domain — a medical summary requires peer-reviewed sources; a blog post does not. Never relax the standard for factual accuracy itself. **This diagnostic is performed by a probabilistic model subject to the same hallucination risks it diagnoses.** Treat output as structured triage, not ground truth. Claims marked "Confirmed" mean "consistent with available knowledge," not "independently proven." When tool access is available (web search, file read), use tools to verify against live sources rather than relying on parametric knowledge alone. Users must spot-check Critical and High findings against actual sources.

**INPUT**
- Document to verify: [PASTE OR SPECIFY FILE PATH]
- Domain context (optional): [e.g., "legal compliance brief" — or "infer"]
- Claimed sources (optional): [PASTE REFERENCE LIST OR "none"]
- Trusted references (optional): [AUTHORITATIVE MATERIAL OR "none"]

**PROTOCOL (Five-Step Pipeline)**

Step 1 — Source Authority Assessment: Evaluate credibility of every cited source. Flag uncited specific claims. If the document has zero citations, note once as a systemic finding — then focus on which claims *require* sourcing given domain and stakes.
- Fabricated Citation (Critical): cited source does not exist — invented authors, fake journals, non-existent URLs/DOIs. LLMs frequently hallucinate citations.
- Misattributed Claim (Critical): source exists but does not support the claim as stated.
- Circular Citation (High): chain of citation never reaches primary data.
- Stale Source (High): outdated data where newer evidence supersedes — especially AI, medicine, regulation.
- Authority Mismatch (Medium): source cited outside its domain expertise.
- Missing Citation (Medium): specific factual claim (statistic, date, specification) with no source. General knowledge exempt.
- Weak Source for Strong Claim (Medium): extraordinary claim supported only by a single non-peer-reviewed source.
Apply SIFT heuristic: can the source's expertise, affiliation, and track record be verified via lateral reading (searching *outside* the document to see what independent, trusted sources say about the author or publisher)?

Step 2 — Claim Decomposition and Factual Verification: Break key claims into atomic propositions. For documents exceeding ~20 substantive claims, prioritize: (1) highest downstream impact if wrong, (2) quantitative specificity (statistics, dates, measurements), (3) claims supporting core thesis. State which claims were evaluated vs. deferred. For each:
- Decompose compound claims into simplest components — single subject, single predicate, clear truth value.
- Cross-reference each against authoritative sources. Classify as: Supported, Contradicted (factual error), Unverifiable (flag evidence gap), or Partially Accurate (core truth with specific distortions).
- Check numerical claims: does the cited source contain this number? Is it quoted in correct context (population, time period, methodology)? Are units/scales/denominators consistent?

Signals:
- Factual Error (Critical): demonstrably false, contradicted by evidence.
- Distorted Statistic (Critical): real number misquoted, decontextualized, or applied to wrong population/period.
- Conflated Entities (High): distinct concepts/organizations/standards treated as interchangeable.
- Unsupported Generalization (High): universal claim ("all," "always," "never") only supported as partial/conditional.
- Outdated Fact (Medium): accurate at time of writing but since superseded.
- Unverifiable Claim (Medium): cannot confirm or deny — flag the evidence gap.

Step 3 — Logical Consistency Verification: Evaluate internal coherence of argument structure.
- Internal Contradiction (Critical): two claims in the same document that cannot both be true.
- Non Sequitur (High): conclusion does not follow from presented premises.
- Scope Creep (High): premises for a narrow domain used to support broad conclusions without justification.
- Missing Premise (Medium): argument depends on unstated assumption.
- Survivorship Bias (Medium): evidence drawn only from successes, ignoring failures/counterexamples.
- Hedging Inconsistency (Low): confidence language shifts without justification ("possible" → "proven").
Trace specific premises and conclusion for each finding.

Step 4 — Provenance and Integrity Assessment: Evaluate sourcing chain traceability.
- Citation Chain Break (High): claim cites Source A, Source A attributes to Source B, Source B doesn't contain the claim.
- Selective Quotation (High): source quoted in a way that reverses or materially changes its meaning.
- Self-Referential Loop (Medium): document cites its own prior claims as evidence.
- Version Mismatch (Medium): reference to specific version/edition doesn't match what's actually cited.
- Inaccessible Source (Low): cited source behind paywall or broken link — unverifiable by reader.

Step 5 — Synthesize and Prioritize: Aggregate findings. Rate overall reliability:
- HIGH CONFIDENCE: No Critical, <3 High findings. Well-sourced, consistent, cross-referenced.
- MODERATE CONFIDENCE: <=1 Critical, several High. Core thesis supported but specific claims need correction.
- LOW CONFIDENCE: Multiple Critical. Core claims unsupported or logically inconsistent. Substantial revision needed.
- UNRELIABLE: Pervasive Critical. Fabricated citations, systematic errors, fundamental logical failures.

**OUTPUT**

Verification Summary:
```
Document: [title]
Domain: [domain]
Claims Evaluated: [count]
Sources Evaluated: [count]
Overall Reliability: [rating]
```

Findings — per finding (N = layer: 1=Source Authority, 2=Factual, 3=Logical, 4=Provenance; M = finding number):
```
[VER-N.M] [CRITICAL|HIGH|MEDIUM|LOW] — [document location]
  Layer: [Source Authority | Factual Verification | Logical Consistency | Provenance]
  Claim: [specific claim as stated]
  Finding: [what is wrong]
  Evidence: [contradicting source or logical principle]
  Remediation: [specific correction]
```

Confirmed Claims: list claims checked and verified accurate with source.

Needs Human Review: claims where verifier lacks domain expertise, authoritative sources disagree, claims are technically accurate but potentially misleading, or ground truth is unstable.

Confidence Rationale: one paragraph explaining the rating and what would change it.

Severity: CRITICAL = demonstrably false claims, fabricated citations, internal contradictions. HIGH = significant distortions, logical failures, broken citation chains. MEDIUM = evidence gaps, outdated facts, missing context. LOW = minor gaps, inaccessible sources, hedging inconsistency.

Absence of evidence is not evidence of absence — flag unverifiable claims as evidence gaps, not errors. Confirmed claims matter — list what readers can trust, not just what they cannot. Do not fabricate findings.

Stop when all claims evaluated across all four layers. Do not modify the document.
