---
name: swiftui-view-refactor
description: Refactor SwiftUI views into smaller components with stable, explicit data flow.
risk: safe
source: "Dimillian/Skills (MIT)"
date_added: "2026-03-25"
---

# SwiftUI View Refactor

## Overview
Refactor SwiftUI views toward small, explicit, stable view types. Default to vanilla SwiftUI: local state in the view, shared dependencies in the environment, business logic in services/models, and view models only when the request or existing code clearly requires one.

## When to Use
- When cleaning up a large SwiftUI view or splitting long `body` implementations.
- When you need smaller subviews, explicit dependency injection, or better Observation usage.

## Core Guidelines

### 1) View ordering (top → bottom)
- Enforce this ordering unless the existing file has a stronger local convention you must preserve.
- Environment
- `private`/`public` `let`
- `@State` / other stored properties
- computed `var` (non-view)
- `init`
- `body`
- computed view builders / other view helpers
- helper / async functions

### 2) Default to MV, not MVVM
- Views should be lightweight state expressions and orchestration points, not containers for business logic.
- Favor `@State`, `@Environment`, `@Query`, `.task`, `.task(id:)`, and `onChange` before reaching for a view model.
- Inject services and shared models via `@Environment`; keep domain logic in services/models, not in the view body.
- Do not introduce a view model just to mirror local view state or wrap environment dependencies.
- If a screen is getting large, split the UI into subviews before inventing a new view model layer.

### 3) Strongly prefer dedicated subview types over computed `some View` helpers
- Flag `body` properties that are longer than roughly one screen or contain multiple logical sections.
- Prefer extracting dedicated `View` types for non-trivial sections, especially when they have state, async work, branching, or deserve their own preview.
- Keep computed `some View` helpers rare and small. Do not build an entire screen out of `private var header: some View`-style fragments.
- Pass small, explicit inputs (data, bindings, callbacks) into extracted subviews instead of handing down the entire parent state.
- If an extracted subview becomes reusable or independently meaningful, move it to its own file.

Prefer:

```swift
var body: some View {
    List {
        HeaderSection(title: title, subtitle: subtitle)
        FilterSection(
            filterOptions: filterOptions,
            selectedFilter: $selectedFilter
        )
        ResultsSection(items: filteredItems)
        FooterSection()
    }
}

private struct HeaderSection: View {
    let title: String
    let subtitle: String

    var body: some View {
        VStack(alignment: .leading, spacing: 6) {
            Text(title).font(.title2)
            Text(subtitle).font(.subheadline)
        }
    }
}

private struct FilterSection: View {
    let filterOptions: [FilterOption]
    @Binding var selectedFilter: FilterOption

    var body: some View {
        ScrollView(.horizontal, showsIndicators: false) {
            HStack {
                ForEach(filterOptions, id: \.self) { option in
                    FilterChip(option: option, isSelected: option == selectedFilter)
                        .onTapGesture { selectedFilter = option }
                }
            }
        }
    }
}
```

Avoid:

```swift
var body: some View {
    List {
        header
        filters
        results
        footer
    }
}

private var header: some View {
    VStack(alignment: .leading, spacing: 6) {
        Text(title).font(.title2)
        Text(subtitle).font(.subheadline)
    }
}
```

### 3b) Extract actions and side effects out of `body`
- Do not keep non-trivial button actions inline in the view body.
- Do not bury business logic inside `.task`, `.onAppear`, `.onChange`, or `.refreshable`.
- Prefer calling small private methods from the view, and move real business logic into services/models.
- The body should read like UI, not like a view controller.

```swift
Button("Save", action: save)
    .disabled(isSaving)

.task(id: searchText) {
    await reload(for: searchText)
}

private func save() {
    Task { await saveAsync() }
}

private func reload(for searchText: String) async {
    guard !searchText.isEmpty else {
        results = []
        return
    }
    await searchService.search(searchText)
}
```

### 4) Keep a stable view tree (avoid top-level conditional view swapping)
- Avoid `body` or computed views that return completely different root branches via `if/else`.
- Prefer a single stable base view with conditions inside sections/modifiers (`overlay`, `opacity`, `disabled`, `toolbar`, etc.).
- Root-level branch swapping causes identity churn, broader invalidation, and extra recomputation.

Prefer:

```swift
var body: some View {
    List {
        documentsListContent
    }
    .toolbar {
        if canEdit {
            editToolbar
        }
    }
}
```

Avoid:

```swift
var documentsListView: some View {
    if canEdit {
        editableDocumentsList
    } else {
        readOnlyDocumentsList
    }
}
```

### 5) View model handling (only if already present or explicitly requested)
- Treat view models as a legacy or explicit-need pattern, not the default.
- Do not introduce a view model unless the request or existing code clearly calls for one.
- If a view model exists, make it non-optional when possible.
- Pass dependencies to the view via `init`, then create the view model in the view's `init`.
- Avoid `bootstrapIfNeeded` patterns and other delayed setup workarounds.

Example (Observation-based):

```swift
@State private var viewModel: SomeViewModel

init(dependency: Dependency) {
    _viewModel = State(initialValue: SomeViewModel(dependency: dependency))
}
```

### 6) Observation usage
- For `@Observable` reference types on iOS 17+, store them as `@State` in the owning view.
- Pass observables down explicitly; avoid optional state unless the UI genuinely needs it.
- If the deployment target includes iOS 16 or earlier, use `@StateObject` at the owner and `@ObservedObject` when injecting legacy observable models.

## Workflow

1. Reorder the view to match the ordering rules.
2. Remove inline actions and side effects from `body`; move business logic into services/models and keep only thin orchestration in the view.
3. Shorten long bodies by extracting dedicated subview types; avoid rebuilding the screen out of many computed `some View` helpers.
4. Ensure stable view structure: avoid top-level `if`-based branch swapping; move conditions to localized sections/modifiers.
5. If a view model exists or is explicitly required, replace optional view models with a non-optional `@State` view model initialized in `init`.
6. Confirm Observation usage: `@State` for root `@Observable` models on iOS 17+, legacy wrappers only when the deployment target requires them.
7. Keep behavior intact: do not change layout or business logic unless requested.

## Notes

- Prefer small, explicit view types over large conditional blocks and large computed `some View` properties.
- Keep computed view builders below `body` and non-view computed vars above `init`.
- A good SwiftUI refactor should make the view read top-to-bottom as data flow plus layout, not as mixed layout and imperative logic.
- For MV-first guidance and rationale, see `references/mv-patterns.md`.

## Large-view handling

When a SwiftUI view file exceeds ~300 lines, split it aggressively. Extract meaningful sections into dedicated `View` types instead of hiding complexity in many computed properties. Use `private` extensions with `// MARK: -` comments for actions and helpers, but do not treat extensions as a substitute for breaking a giant screen into smaller view types. If an extracted subview is reused or independently meaningful, move it into its own file.

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: swiss-design
description: Web and App implementation guide for Swiss Design (International Typographic Style). Trigger when user wants strict grid systems, strong typography, and clean, asymmetrical alignment.
date_added: "2026-06-17"
risk: safe
source: self
source_type: self
---

# Swiss Design (International Typographic Style)

> "Form follows function. The grid is absolute. Typography is the primary visual element."

## When to Use
Use this sub-style when the user's request matches the aesthetic described above. This is a child reference of the `design-it` skill and is not meant to be triggered directly.

## Core Principles
1. **Mathematical Grids**: Everything aligns to a strict underlying grid. Asymmetry is preferred over centered text.
2. **Sans-Serif Typography**: Helvetica is the king, but any clean, neutral sans-serif works. Flush left, ragged right text alignment.
3. **Objective Photography**: If images are used, they should be objective, documentary-style photos, not stylized illustrations.

## Visual DNA
- **Colors**: Very limited. Usually just black, white, and ONE highly saturated accent color (often primary red, blue, or yellow). The **Industrial Chic** palette works perfectly.
- **Typography**: `Helvetica Neue`, `Inter`, or `Roboto`. Huge contrast in font sizes (e.g., massive 6rem headers paired with 1rem body text).
- **Layout**: Do NOT center text. Ever.

## Web Implementation
- Use CSS Grid extensively. Let columns dictate the layout.
- **CSS Example**:
```css
body {
  background-color: #f4f4f4;
  color: #111;
  font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
  line-height: 1.4;
}

.swiss-grid {
  display: grid;
  grid-template-columns: repeat(12, 1fr);
  gap: 20px;
  padding: 40px;
}

.swiss-header {
  grid-column: 1 / 11; /* spans across multiple columns, leaving right side empty */
  font-size: 6vw;
  font-weight: 700;
  text-transform: lowercase; /* Optional, but common in brutalist/swiss */
  margin-bottom: 2rem;
  line-height: 0.9;
  letter-spacing: -0.04em;
}

.swiss-content {
  grid-column: 4 / 9; /* Indented alignment */
  font-size: 1.25rem;
  text-align: left; /* Flush left, ragged right */
}

.swiss-accent {
  color: #E2001A; /* Classic Swiss Red */
}
```

## App Implementation

### SwiftUI
```swift
struct SwissDesignView: View {
    var body: some View {
        ScrollView {
            VStack(alignment: .leading, spacing: 0) {
                // Header Block
                VStack(alignment: .leading, spacing: 8) {
                    Text("the grid")
                        .font(.custom("Helvetica Neue", size: 60))
                        .fontWeight(.heavy)
                        .tracking(-2) // Tight letter spacing
                    Text("is absolute.")
                        .font(.custom("Helvetica Neue", size: 60))
                        .fontWeight(.heavy)
                        .tracking(-2)
                        .foregroundColor(Color(hex: "E2001A")) // Swiss Red
                }
                .padding(.horizontal, 24)
                .padding(.top, 60)
                .padding(.bottom, 40)

                Divider().background(Color.black)

                // Asymmetrical Content Block
                HStack(alignment: .top, spacing: 20) {
                    // Empty left column (negative space is structural)
                    Spacer().frame(width: 40)

                    VStack(alignment: .leading, spacing: 16) {
                        Text("Form follows function.")
                            .font(.custom("Helvetica Neue", size: 24))
                            .fontWeight(.bold)

                        Text("Typography is the primary visual element. Everything aligns to a strict underlying grid. Asymmetry is preferred over centered text.")
                            .font(.custom("Helvetica Neue", size: 16))
                            .lineSpacing(6)
                    }
                    .padding(.vertical, 40)
                    .padding(.trailing, 24)
                }

                Divider().background(Color.black)
            }
            .frame(maxWidth: .infinity, alignment: .leading)
        }
        .background(Color(white: 0.96))
        .foregroundColor(.black)
    }
}
```
- Strict `alignment: .leading` everywhere. Never use `.center`.
- Use `Spacer().frame(width: X)` in `HStack`s to intentionally push content off the left margin, creating the classic Swiss indented asymmetrical grid.

### Flutter
```dart
class SwissDesignScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFFF4F4F4),
      body: SingleChildScrollView(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const SizedBox(height: 80),
            // Header
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 24.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: const [
                  Text('the grid', style: TextStyle(fontFamily: 'Helvetica', fontSize: 60, fontWeight: FontWeight.w900, height: 0.9, letterSpacing: -2)),
                  Text('is absolute.', style: TextStyle(fontFamily: 'Helvetica', fontSize: 60, fontWeight: FontWeight.w900, height: 0.9, letterSpacing: -2, color: Color(0xFFE2001A))),
                ],
              ),
            ),
            const SizedBox(height: 40),
            const Divider(color: Colors.black, thickness: 1, height: 1),

            // Asymmetrical Content
            Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // Structural empty column
                const SizedBox(width: 64),
                // Content column
                Expanded(
                  child: Padding(
                    padding: const EdgeInsets.only(top: 40.0, bottom: 40.0, right: 24.0),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: const [
                        Text('Form follows function.', style: TextStyle(fontFamily: 'Helvetica', fontSize: 24, fontWeight: FontWeight.bold)),
                        SizedBox(height: 16),
                        Text('Typography is the primary visual element. Everything aligns to a strict underlying grid.', style: TextStyle(fontFamily: 'Helvetica', fontSize: 16, height: 1.4)),
                      ],
                    ),
                  ),
                ),
              ],
            ),
            const Divider(color: Colors.black, thickness: 1, height: 1),
          ],
        ),
      ),
    );
  }
}
```
- `CrossAxisAlignment.start` is mandatory on all Columns.
- Use a `Row` with a fixed `SizedBox` width on the left and an `Expanded` widget on the right to enforce the asymmetrical grid column.

### React Native
```jsx
const SwissDesignScreen = () => {
  return (
    <ScrollView style={{ flex: 1, backgroundColor: '#F4F4F4' }}>

      {/* Header */}
      <View style={{ paddingHorizontal: 24, paddingTop: 80, paddingBottom: 40 }}>
        <Text style={{ fontFamily: 'HelveticaNeue-CondensedBlack', fontSize: 60, lineHeight: 60, letterSpacing: -2, color: '#111' }}>
          the grid
        </Text>
        <Text style={{ fontFamily: 'HelveticaNeue-CondensedBlack', fontSize: 60, lineHeight: 60, letterSpacing: -2, color: '#E2001A' }}>
          is absolute.
        </Text>
      </View>

      <View style={{ height: 1, backgroundColor: '#111' }} />

      {/* Asymmetrical Layout */}
      <View style={{ flexDirection: 'row', paddingVertical: 40 }}>
        {/* Empty left column */}
        <View style={{ width: 64 }} />

        {/* Content */}
        <View style={{ flex: 1, paddingRight: 24 }}>
          <Text style={{ fontFamily: 'HelveticaNeue-Bold', fontSize: 24, color: '#111', marginBottom: 16 }}>
            Form follows function.
          </Text>
          <Text style={{ fontFamily: 'HelveticaNeue-Regular', fontSize: 16, lineHeight: 24, color: '#111' }}>
            Typography is the primary visual element. Everything aligns to a strict underlying grid.
          </Text>
        </View>
      </View>

      <View style={{ height: 1, backgroundColor: '#111' }} />

    </ScrollView>
  );
};
```
- Link the Helvetica Neue font family. The contrast between `HelveticaNeue-CondensedBlack` for headers and `HelveticaNeue-Regular` for body copy defines this style.
- Use `flexDirection: 'row'` to build the strict column structure.

### Jetpack Compose
```kotlin
@Composable
fun SwissDesignScreen() {
    Column(
        modifier = Modifier.fillMaxSize().background(Color(0xFFF4F4F4)).verticalScroll(rememberScrollState())
    ) {
        Spacer(Modifier.height(80.dp))

        // Header
        Column(modifier = Modifier.padding(horizontal = 24.dp, vertical = 40.dp)) {
            Text(
                text = "the grid",
                fontFamily = FontFamily.SansSerif, // Replace with Helvetica
                fontSize = 60.sp,
                fontWeight = FontWeight.Black,
                letterSpacing = (-2).sp,
                lineHeight = 60.sp,
                color = Color.Black
            )
            Text(
                text = "is absolute.",
                fontFamily = FontFamily.SansSerif,
                fontSize = 60.sp,
                fontWeight = FontWeight.Black,
                letterSpacing = (-2).sp,
                lineHeight = 60.sp,
                color = Color(0xFFE2001A)
            )
        }

        Divider(color = Color.Black, thickness = 1.dp)

        // Asymmetrical Grid Row
        Row(modifier = Modifier.fillMaxWidth().padding(vertical = 40.dp)) {
            // Empty grid column
            Spacer(modifier = Modifier.width(64.dp))

            // Content
            Column(modifier = Modifier.weight(1f).padding(right = 24.dp)) {
                Text(
                    text = "Form follows function.",
                    fontSize = 24.sp,
                    fontWeight = FontWeight.Bold,
                    color = Color.Black
                )
                Spacer(Modifier.height(16.dp))
                Text(
                    text = "Typography is the primary visual element. Everything aligns to a strict underlying grid.",
                    fontSize = 16.sp,
                    color = Color.Black
                )
            }
        }

        Divider(color = Color.Black, thickness = 1.dp)
    }
}
```
- Use `Divider(color = Color.Black, thickness = 1.dp)` to create the harsh horizontal structural rules.
- Combine `Row`, a fixed `Spacer` width, and a `Column` with `Modifier.weight(1f)` to enforce the asymmetrical design.

## Do's and Don'ts
- **DO**: Use negative space as a structural element. Empty columns are just as important as filled ones.
- **DON'T**: Center align text. Do not use serif fonts. Do not use drop shadows.

## Limitations
- This is a styling reference and does not replace environment-specific validation, accessibility testing, or expert review.
- Ensure appropriate contrast ratios and responsive behaviors are verified separately.


---
name: sympy
description: "SymPy is a Python library for symbolic mathematics that enables exact computation using mathematical symbols rather than numerical approximations."
license: https://github.com/sympy/sympy/blob/master/LICENSE
metadata:
    skill-author: K-Dense Inc.
risk: safe
source: "https://github.com/sympy/sympy"
---

# SymPy - Symbolic Mathematics in Python

## Overview

SymPy is a Python library for symbolic mathematics that enables exact computation using mathematical symbols rather than numerical approximations. This skill provides comprehensive guidance for performing symbolic algebra, calculus, linear algebra, equation solving, physics calculations, and code generation using SymPy.

## When to Use This Skill

Use this skill when:
- Solving equations symbolically (algebraic, differential, systems of equations)
- Performing calculus operations (derivatives, integrals, limits, series)
- Manipulating and simplifying algebraic expressions
- Working with matrices and linear algebra symbolically
- Doing physics calculations (mechanics, quantum mechanics, vector analysis)
- Number theory computations (primes, factorization, modular arithmetic)
- Geometric calculations (2D/3D geometry, analytic geometry)
- Converting mathematical expressions to executable code (Python, C, Fortran)
- Generating LaTeX or other formatted mathematical output
- Needing exact mathematical results (e.g., `sqrt(2)` not `1.414...`)

## Core Capabilities

### 1. Symbolic Computation Basics

**Creating symbols and expressions:**
```python
from sympy import symbols, Symbol
x, y, z = symbols('x y z')
expr = x**2 + 2*x + 1

# With assumptions
x = symbols('x', real=True, positive=True)
n = symbols('n', integer=True)
```

**Simplification and manipulation:**
```python
from sympy import simplify, expand, factor, cancel
simplify(sin(x)**2 + cos(x)**2)  # Returns 1
expand((x + 1)**3)  # x**3 + 3*x**2 + 3*x + 1
factor(x**2 - 1)    # (x - 1)*(x + 1)
```

**For detailed basics:** See `references/core-capabilities.md`

### 2. Calculus

**Derivatives:**
```python
from sympy import diff
diff(x**2, x)        # 2*x
diff(x**4, x, 3)     # 24*x (third derivative)
diff(x**2*y**3, x, y)  # 6*x*y**2 (partial derivatives)
```

**Integrals:**
```python
from sympy import integrate, oo
integrate(x**2, x)              # x**3/3 (indefinite)
integrate(x**2, (x, 0, 1))      # 1/3 (definite)
integrate(exp(-x), (x, 0, oo))  # 1 (improper)
```

**Limits and Series:**
```python
from sympy import limit, series
limit(sin(x)/x, x, 0)  # 1
series(exp(x), x, 0, 6)  # 1 + x + x**2/2 + x**3/6 + x**4/24 + x**5/120 + O(x**6)
```

**For detailed calculus operations:** See `references/core-capabilities.md`

### 3. Equation Solving

**Algebraic equations:**
```python
from sympy import solveset, solve, Eq
solveset(x**2 - 4, x)  # {-2, 2}
solve(Eq(x**2, 4), x)  # [-2, 2]
```

**Systems of equations:**
```python
from sympy import linsolve, nonlinsolve
linsolve([x + y - 2, x - y], x, y)  # {(1, 1)} (linear)
nonlinsolve([x**2 + y - 2, x + y**2 - 3], x, y)  # (nonlinear)
```

**Differential equations:**
```python
from sympy import Function, dsolve, Derivative
f = symbols('f', cls=Function)
dsolve(Derivative(f(x), x) - f(x), f(x))  # Eq(f(x), C1*exp(x))
```

**For detailed solving methods:** See `references/core-capabilities.md`

### 4. Matrices and Linear Algebra

**Matrix creation and operations:**
```python
from sympy import Matrix, eye, zeros
M = Matrix([[1, 2], [3, 4]])
M_inv = M**-1  # Inverse
M.det()        # Determinant
M.T            # Transpose
```

**Eigenvalues and eigenvectors:**
```python
eigenvals = M.eigenvals()  # {eigenvalue: multiplicity}
eigenvects = M.eigenvects()  # [(eigenval, mult, [eigenvectors])]
P, D = M.diagonalize()  # M = P*D*P^-1
```

**Solving linear systems:**
```python
A = Matrix([[1, 2], [3, 4]])
b = Matrix([5, 6])
x = A.solve(b)  # Solve Ax = b
```

**For comprehensive linear algebra:** See `references/matrices-linear-algebra.md`

### 5. Physics and Mechanics

**Classical mechanics:**
```python
from sympy.physics.mechanics import dynamicsymbols, LagrangesMethod
from sympy import symbols

# Define system
q = dynamicsymbols('q')
m, g, l = symbols('m g l')

# Lagrangian (T - V)
L = m*(l*q.diff())**2/2 - m*g*l*(1 - cos(q))

# Apply Lagrange's method
LM = LagrangesMethod(L, [q])
```

**Vector analysis:**
```python
from sympy.physics.vector import ReferenceFrame, dot, cross
N = ReferenceFrame('N')
v1 = 3*N.x + 4*N.y
v2 = 1*N.x + 2*N.z
dot(v1, v2)  # Dot product
cross(v1, v2)  # Cross product
```

**Quantum mechanics:**
```python
from sympy.physics.quantum import Ket, Bra, Commutator
psi = Ket('psi')
A = Operator('A')
comm = Commutator(A, B).doit()
```

**For detailed physics capabilities:** See `references/physics-mechanics.md`

### 6. Advanced Mathematics

The skill includes comprehensive support for:

- **Geometry:** 2D/3D analytic geometry, points, lines, circles, polygons, transformations
- **Number Theory:** Primes, factorization, GCD/LCM, modular arithmetic, Diophantine equations
- **Combinatorics:** Permutations, combinations, partitions, group theory
- **Logic and Sets:** Boolean logic, set theory, finite and infinite sets
- **Statistics:** Probability distributions, random variables, expectation, variance
- **Special Functions:** Gamma, Bessel, orthogonal polynomials, hypergeometric functions
- **Polynomials:** Polynomial algebra, roots, factorization, Groebner bases

**For detailed advanced topics:** See `references/advanced-topics.md`

### 7. Code Generation and Output

**Convert to executable functions:**
```python
from sympy import lambdify
import numpy as np

expr = x**2 + 2*x + 1
f = lambdify(x, expr, 'numpy')  # Create NumPy function
x_vals = np.linspace(0, 10, 100)
y_vals = f(x_vals)  # Fast numerical evaluation
```

**Generate C/Fortran code:**
```python
from sympy.utilities.codegen import codegen
[(c_name, c_code), (h_name, h_header)] = codegen(
    ('my_func', expr), 'C'
)
```

**LaTeX output:**
```python
from sympy import latex
latex_str = latex(expr)  # Convert to LaTeX for documents
```

**For comprehensive code generation:** See `references/code-generation-printing.md`

## Working with SymPy: Best Practices

### 1. Always Define Symbols First

```python
from sympy import symbols
x, y, z = symbols('x y z')
# Now x, y, z can be used in expressions
```

### 2. Use Assumptions for Better Simplification

```python
x = symbols('x', positive=True, real=True)
sqrt(x**2)  # Returns x (not Abs(x)) due to positive assumption
```

Common assumptions: `real`, `positive`, `negative`, `integer`, `rational`, `complex`, `even`, `odd`

### 3. Use Exact Arithmetic

```python
from sympy import Rational, S
# Correct (exact):
expr = Rational(1, 2) * x
expr = S(1)/2 * x

# Incorrect (floating-point):
expr = 0.5 * x  # Creates approximate value
```

### 4. Numerical Evaluation When Needed

```python
from sympy import pi, sqrt
result = sqrt(8) + pi
result.evalf()    # 5.96371554103586
result.evalf(50)  # 50 digits of precision
```

### 5. Convert to NumPy for Performance

```python
# Slow for many evaluations:
for x_val in range(1000):
    result = expr.subs(x, x_val).evalf()

# Fast:
f = lambdify(x, expr, 'numpy')
results = f(np.arange(1000))
```

### 6. Use Appropriate Solvers

- `solveset`: Algebraic equations (primary)
- `linsolve`: Linear systems
- `nonlinsolve`: Nonlinear systems
- `dsolve`: Differential equations
- `solve`: General purpose (legacy, but flexible)

## Reference Files Structure

This skill uses modular reference files for different capabilities:

1. **`core-capabilities.md`**: Symbols, algebra, calculus, simplification, equation solving
   - Load when: Basic symbolic computation, calculus, or solving equations

2. **`matrices-linear-algebra.md`**: Matrix operations, eigenvalues, linear systems
   - Load when: Working with matrices or linear algebra problems

3. **`physics-mechanics.md`**: Classical mechanics, quantum mechanics, vectors, units
   - Load when: Physics calculations or mechanics problems

4. **`advanced-topics.md`**: Geometry, number theory, combinatorics, logic, statistics
   - Load when: Advanced mathematical topics beyond basic algebra and calculus

5. **`code-generation-printing.md`**: Lambdify, codegen, LaTeX output, printing
   - Load when: Converting expressions to code or generating formatted output

## Common Use Case Patterns

### Pattern 1: Solve and Verify

```python
from sympy import symbols, solve, simplify
x = symbols('x')

# Solve equation
equation = x**2 - 5*x + 6
solutions = solve(equation, x)  # [2, 3]

# Verify solutions
for sol in solutions:
    result = simplify(equation.subs(x, sol))
    assert result == 0
```

### Pattern 2: Symbolic to Numeric Pipeline

```python
# 1. Define symbolic problem
x, y = symbols('x y')
expr = sin(x) + cos(y)

# 2. Manipulate symbolically
simplified = simplify(expr)
derivative = diff(simplified, x)

# 3. Convert to numerical function
f = lambdify((x, y), derivative, 'numpy')

# 4. Evaluate numerically
results = f(x_data, y_data)
```

### Pattern 3: Document Mathematical Results

```python
# Compute result symbolically
integral_expr = Integral(x**2, (x, 0, 1))
result = integral_expr.doit()

# Generate documentation
print(f"LaTeX: {latex(integral_expr)} = {latex(result)}")
print(f"Pretty: {pretty(integral_expr)} = {pretty(result)}")
print(f"Numerical: {result.evalf()}")
```

## Integration with Scientific Workflows

### With NumPy

```python
import numpy as np
from sympy import symbols, lambdify

x = symbols('x')
expr = x**2 + 2*x + 1

f = lambdify(x, expr, 'numpy')
x_array = np.linspace(-5, 5, 100)
y_array = f(x_array)
```

### With Matplotlib

```python
import matplotlib.pyplot as plt
import numpy as np
from sympy import symbols, lambdify, sin

x = symbols('x')
expr = sin(x) / x

f = lambdify(x, expr, 'numpy')
x_vals = np.linspace(-10, 10, 1000)
y_vals = f(x_vals)

plt.plot(x_vals, y_vals)
plt.show()
```

### With SciPy

```python
from scipy.optimize import fsolve
from sympy import symbols, lambdify

# Define equation symbolically
x = symbols('x')
equation = x**3 - 2*x - 5

# Convert to numerical function
f = lambdify(x, equation, 'numpy')

# Solve numerically with initial guess
solution = fsolve(f, 2)
```

## Quick Reference: Most Common Functions

```python
# Symbols
from sympy import symbols, Symbol
x, y = symbols('x y')

# Basic operations
from sympy import simplify, expand, factor, collect, cancel
from sympy import sqrt, exp, log, sin, cos, tan, pi, E, I, oo

# Calculus
from sympy import diff, integrate, limit, series, Derivative, Integral

# Solving
from sympy import solve, solveset, linsolve, nonlinsolve, dsolve

# Matrices
from sympy import Matrix, eye, zeros, ones, diag

# Logic and sets
from sympy import And, Or, Not, Implies, FiniteSet, Interval, Union

# Output
from sympy import latex, pprint, lambdify, init_printing

# Utilities
from sympy import evalf, N, nsimplify
```

## Getting Started Examples

### Example 1: Solve Quadratic Equation
```python
from sympy import symbols, solve, sqrt
x = symbols('x')
solution = solve(x**2 - 5*x + 6, x)
# [2, 3]
```

### Example 2: Calculate Derivative
```python
from sympy import symbols, diff, sin
x = symbols('x')
f = sin(x**2)
df_dx = diff(f, x)
# 2*x*cos(x**2)
```

### Example 3: Evaluate Integral
```python
from sympy import symbols, integrate, exp
x = symbols('x')
integral = integrate(x * exp(-x**2), (x, 0, oo))
# 1/2
```

### Example 4: Matrix Eigenvalues
```python
from sympy import Matrix
M = Matrix([[1, 2], [2, 1]])
eigenvals = M.eigenvals()
# {3: 1, -1: 1}
```

### Example 5: Generate Python Function
```python
from sympy import symbols, lambdify
import numpy as np
x = symbols('x')
expr = x**2 + 2*x + 1
f = lambdify(x, expr, 'numpy')
f(np.array([1, 2, 3]))
# array([ 4,  9, 16])
```

## Troubleshooting Common Issues

1. **"NameError: name 'x' is not defined"**
   - Solution: Always define symbols using `symbols()` before use

2. **Unexpected numerical results**
   - Issue: Using floating-point numbers like `0.5` instead of `Rational(1, 2)`
   - Solution: Use `Rational()` or `S()` for exact arithmetic

3. **Slow performance in loops**
   - Issue: Using `subs()` and `evalf()` repeatedly
   - Solution: Use `lambdify()` to create a fast numerical function

4. **"Can't solve this equation"**
   - Try different solvers: `solve`, `solveset`, `nsolve` (numerical)
   - Check if the equation is solvable algebraically
   - Use numerical methods if no closed-form solution exists

5. **Simplification not working as expected**
   - Try different simplification functions: `simplify`, `factor`, `expand`, `trigsimp`
   - Add assumptions to symbols (e.g., `positive=True`)
   - Use `simplify(expr, force=True)` for aggressive simplification

## Additional Resources

- Official Documentation: https://docs.sympy.org/
- Tutorial: https://docs.sympy.org/latest/tutorials/intro-tutorial/index.html
- API Reference: https://docs.sympy.org/latest/reference/index.html
- Examples: https://github.com/sympy/sympy/tree/master/examples

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: synthwave
description: Web and App implementation guide for Synthwave. Trigger when user wants 80s-inspired neon, dark backgrounds, outrun grids, and Miami Vice aesthetics.
date_added: "2026-06-17"
risk: safe
source: self
source_type: self
---

# Synthwave (Outrun)

> "Driving a Ferrari through a neon-lit digital grid at midnight."

## When to Use
Use this sub-style when the user's request matches the aesthetic described above. This is a child reference of the `design-it` skill and is not meant to be triggered directly.

## Core Principles
1. **Dark Mode by Default**: Absolute pitch-black or deep purple backgrounds.
2. **Neon Glowing Vectors**: Bright magenta, cyan, and yellow wireframes, text, and grids. Heavy use of `box-shadow` and `text-shadow` for glow effects.
3. **The Perspective Grid**: The defining visual is a glowing grid that fades into a vanishing point on the horizon.

## Visual DNA
- **Colors**: Deep space backgrounds (`#0B0C10`, `#110022`). Glowing neon accents: Cyan (`#00FFFF`), Hot Pink (`#FF00FF`), Electric Yellow (`#FFFF00`).
- **Typography**: 80s chrome text, brush script (like a neon sign), and heavy italicized sans-serifs.
- **Shadows**: Drop shadows are not black; they are the same color as the element, heavily blurred, to create light emission.

## Web Implementation
- Rely on `text-shadow` for neon signs and 3D transforms for the floor grid.
- **CSS Example**:
```css
body {
  background-color: #090014;
  color: #fff;
  font-family: 'Montserrat', sans-serif;
  overflow-x: hidden;
}

/* Neon Text Glow */
.synth-neon-text {
  font-family: 'Mr Dafoe', cursive; /* A classic 80s script */
  font-size: 4rem;
  color: #fff;
  text-shadow:
    0 0 5px #fff,
    0 0 10px #fff,
    0 0 20px #FF00FF,
    0 0 40px #FF00FF,
    0 0 80px #FF00FF;
}

/* The Perspective Grid Floor */
.synth-grid {
  position: absolute;
  bottom: 0; left: -50%;
  width: 200%; height: 50vh;
  background-image:
    linear-gradient(rgba(0, 255, 255, 0.8) 2px, transparent 2px),
    linear-gradient(90deg, rgba(0, 255, 255, 0.8) 2px, transparent 2px);
  background-size: 50px 50px;

  /* Create the 3D horizon effect */
  transform: perspective(500px) rotateX(60deg);
  transform-origin: top center;

  /* Fade out towards the horizon */
  mask-image: linear-gradient(to bottom, transparent 0%, black 100%);
  -webkit-mask-image: linear-gradient(to bottom, transparent 0%, black 100%);
}
```

## App Implementation

### SwiftUI
```swift
struct NeonText: View {
    let text: String

    var body: some View {
        Text(text)
            .font(.custom("Mr Dafoe", size: 64))
            .foregroundColor(.white)
            // Layering shadows to create a glowing bloom
            .shadow(color: .white, radius: 2)
            .shadow(color: .pink, radius: 5)
            .shadow(color: .pink, radius: 10)
            .shadow(color: .pink, radius: 20)
    }
}

struct SynthwaveScreen: View {
    var body: some View {
        ZStack {
            Color(red: 0.03, green: 0.0, blue: 0.08).ignoresSafeArea() // #090014

            VStack {
                NeonText(text: "Outrun")
                Spacer()
            }

            // Note: A 3D perspective grid requires SceneKit or a pre-rendered image
            // Native SwiftUI 3D transforms apply to the view, but won't draw an infinite floor grid easily.
            Image("synth_grid")
                .resizable()
                .scaledToFill()
                .frame(height: 300)
                .offset(y: 200)
        }
    }
}
```
- Stack multiple `.shadow(color:radius:)` modifiers directly on the text to create a vibrant neon bloom effect.
- The 3D wireframe horizon grid is best achieved via a pre-rendered image background.

### Flutter
```dart
class NeonText extends StatelessWidget {
  final String text;
  const NeonText(this.text);

  @override
  Widget build(BuildContext context) {
    return Text(
      text,
      style: const TextStyle(
        fontFamily: 'Mr Dafoe', // Or any cursive 80s font
        fontSize: 64,
        color: Colors.white,
        shadows: [
          Shadow(color: Colors.white, blurRadius: 2),
          Shadow(color: Colors.pinkAccent, blurRadius: 5),
          Shadow(color: Colors.pinkAccent, blurRadius: 15),
          Shadow(color: Colors.pinkAccent, blurRadius: 30),
        ],
      ),
    );
  }
}

class SynthwaveScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color(0xFF090014),
      body: Stack(
        children: [
          // Background grid asset
          Positioned(
            bottom: 0,
            left: 0,
            right: 0,
            height: 300,
            child: Image.asset('assets/synth_grid.png', fit: BoxFit.cover),
          ),
          // Foreground UI
          const Center(child: NeonText('Outrun')),
        ],
      ),
    );
  }
}
```
- `TextStyle` accepts a list of `Shadow` objects. Stack them with exponentially increasing `blurRadius` values (e.g., 2, 5, 15, 30) to simulate light dispersal.
- Avoid rendering the perspective grid programmatically using `CustomPaint` unless you want to do the 3D math manually. Use an asset.

### React Native
```jsx
// React Native only supports ONE textShadow per Text element natively.
// To create a true neon glow, you must stack identical Text components.

const NeonText = ({ text }) => {
  const baseStyle = {
    fontFamily: 'MrDafoe',
    fontSize: 64,
    color: '#FFF',
    position: 'absolute',
  };

  return (
    <View style={{ alignItems: 'center', height: 80 }}>
      {/* Outer Glow */}
      <Text style={[baseStyle, { textShadowColor: '#FF00FF', textShadowRadius: 30 }]}>{text}</Text>
      {/* Mid Glow */}
      <Text style={[baseStyle, { textShadowColor: '#FF00FF', textShadowRadius: 15 }]}>{text}</Text>
      {/* Core Glow */}
      <Text style={[baseStyle, { textShadowColor: '#FFF', textShadowRadius: 5 }]}>{text}</Text>
      {/* Crisp White Core */}
      <Text style={baseStyle}>{text}</Text>
    </View>
  );
};

const SynthwaveScreen = () => (
  <View style={{ flex: 1, backgroundColor: '#090014', justifyContent: 'center' }}>
    <NeonText text="Outrun" />

    <Image
      source={require('./synth_grid.png')}
      style={{ position: 'absolute', bottom: 0, width: '100%', height: 300, resizeMode: 'cover' }}
    />
  </View>
);
```
- **React Native limitation**: You cannot pass an array of shadows to `textShadow`.
- **Workaround**: Render the exact same `<Text>` component 3-4 times on top of each other using `position: 'absolute'`, each with a different `textShadowRadius` to build the bloom.

### Jetpack Compose
```kotlin
@Composable
fun NeonText(text: String) {
    Text(
        text = text,
        fontSize = 64.sp,
        color = Color.White,
        fontFamily = FontFamily.Cursive,
        // Compose only supports a single Shadow natively on TextStyle
        style = TextStyle(
            shadow = Shadow(
                color = Color(0xFFFF00FF),
                offset = Offset.Zero,
                blurRadius = 30f // Single large blur as fallback
            )
        ),
        // To get stacked blurs, we use Modifier.drawBehind to draw the text repeatedly
    )
}

// Advanced stacked glow approach
@Composable
fun AdvancedNeonText(text: String) {
    Box(contentAlignment = Alignment.Center) {
        // Render layers of text to build the glow
        val blurs = listOf(30f, 15f, 5f)
        blurs.forEach { blur ->
            Text(
                text = text,
                color = Color.Transparent,
                style = TextStyle(
                    shadow = Shadow(Color(0xFFFF00FF), Offset.Zero, blur)
                )
            )
        }
        // Top solid layer
        Text(text = text, color = Color.White)
    }
}
```
- **Compose Limitation**: Like React Native, `TextStyle` only accepts a single `Shadow`.
- **Workaround**: Stack multiple transparent `Text` composables inside a `Box`, each casting a shadow of varying size, topped by the solid white core text.

## Do's and Don'ts
- **DO**: Italicize fonts to give a sense of speed and forward momentum.
- **DON'T**: Use standard, subtle box shadows. If it casts a shadow, it must cast a neon glow instead.

## Limitations
- This is a styling reference and does not replace environment-specific validation, accessibility testing, or expert review.
- Ensure appropriate contrast ratios and responsive behaviors are verified separately.


---
name: systematic-debugging
description: "Use when encountering any bug, test failure, or unexpected behavior, before proposing fixes"
risk: critical
source: community
date_added: "2026-02-27"
---

# Systematic Debugging

## Overview

Random fixes waste time and create new bugs. Quick patches mask underlying issues.

**Core principle:** ALWAYS find root cause before attempting fixes. Symptom fixes are failure.

**Violating the letter of this process is violating the spirit of debugging.**

## The Iron Law

```
NO FIXES WITHOUT ROOT CAUSE INVESTIGATION FIRST
```

If you haven't completed Phase 1, you cannot propose fixes.

## When to Use
Use for ANY technical issue:
- Test failures
- Bugs in production
- Unexpected behavior
- Performance problems
- Build failures
- Integration issues

**Use this ESPECIALLY when:**
- Under time pressure (emergencies make guessing tempting)
- "Just one quick fix" seems obvious
- You've already tried multiple fixes
- Previous fix didn't work
- You don't fully understand the issue

**Don't skip when:**
- Issue seems simple (simple bugs have root causes too)
- You're in a hurry (rushing guarantees rework)
- Manager wants it fixed NOW (systematic is faster than thrashing)

## The Four Phases

You MUST complete each phase before proceeding to the next.

### Phase 1: Root Cause Investigation

**BEFORE attempting ANY fix:**

1. **Read Error Messages Carefully**
   - Don't skip past errors or warnings
   - They often contain the exact solution
   - Read stack traces completely
   - Note line numbers, file paths, error codes

2. **Reproduce Consistently**
   - Can you trigger it reliably?
   - What are the exact steps?
   - Does it happen every time?
   - If not reproducible → gather more data, don't guess

3. **Check Recent Changes**
   - What changed that could cause this?
   - Git diff, recent commits
   - New dependencies, config changes
   - Environmental differences

4. **Gather Evidence in Multi-Component Systems**

   **WHEN system has multiple components (CI → build → signing, API → service → database):**

   **BEFORE proposing fixes, add diagnostic instrumentation:**
   ```
   For EACH component boundary:
     - Log what data enters component
     - Log what data exits component
     - Verify environment/config propagation
     - Check state at each layer

   Run once to gather evidence showing WHERE it breaks
   THEN analyze evidence to identify failing component
   THEN investigate that specific component
   ```

   **Example (multi-layer system):**
   ```bash
   # Layer 1: Workflow
   echo "=== Secrets available in workflow: ==="
   echo "IDENTITY: ${IDENTITY:+SET}${IDENTITY:-UNSET}"

   # Layer 2: Build script
   echo "=== Env vars in build script: ==="
   env | grep IDENTITY || echo "IDENTITY not in environment"

   # Layer 3: Signing script
   echo "=== Keychain state: ==="
   security list-keychains
   security find-identity -v

   # Layer 4: Actual signing
   codesign --sign "$IDENTITY" --verbose=4 "$APP"
   ```

   **This reveals:** Which layer fails (secrets → workflow ✓, workflow → build ✗)

5. **Trace Data Flow**

   **WHEN error is deep in call stack:**

   See `root-cause-tracing.md` in this directory for the complete backward tracing technique.

   **Quick version:**
   - Where does bad value originate?
   - What called this with bad value?
   - Keep tracing up until you find the source
   - Fix at source, not at symptom

### Phase 2: Pattern Analysis

**Find the pattern before fixing:**

1. **Find Working Examples**
   - Locate similar working code in same codebase
   - What works that's similar to what's broken?

2. **Compare Against References**
   - If implementing pattern, read reference implementation COMPLETELY
   - Don't skim - read every line
   - Understand the pattern fully before applying

3. **Identify Differences**
   - What's different between working and broken?
   - List every difference, however small
   - Don't assume "that can't matter"

4. **Understand Dependencies**
   - What other components does this need?
   - What settings, config, environment?
   - What assumptions does it make?

### Phase 3: Hypothesis and Testing

**Scientific method:**

1. **Form Single Hypothesis**
   - State clearly: "I think X is the root cause because Y"
   - Write it down
   - Be specific, not vague

2. **Test Minimally**
   - Make the SMALLEST possible change to test hypothesis
   - One variable at a time
   - Don't fix multiple things at once

3. **Verify Before Continuing**
   - Did it work? Yes → Phase 4
   - Didn't work? Form NEW hypothesis
   - DON'T add more fixes on top

4. **When You Don't Know**
   - Say "I don't understand X"
   - Don't pretend to know
   - Ask for help
   - Research more

### Phase 4: Implementation

**Fix the root cause, not the symptom:**

1. **Create Failing Test Case**
   - Simplest possible reproduction
   - Automated test if possible
   - One-off test script if no framework
   - MUST have before fixing
   - Use the `superpowers:test-driven-development` skill for writing proper failing tests

2. **Implement Single Fix**
   - Address the root cause identified
   - ONE change at a time
   - No "while I'm here" improvements
   - No bundled refactoring

3. **Verify Fix**
   - Test passes now?
   - No other tests broken?
   - Issue actually resolved?

4. **If Fix Doesn't Work**
   - STOP
   - Count: How many fixes have you tried?
   - If < 3: Return to Phase 1, re-analyze with new information
   - **If ≥ 3: STOP and question the architecture (step 5 below)**
   - DON'T attempt Fix #4 without architectural discussion

5. **If 3+ Fixes Failed: Question Architecture**

   **Pattern indicating architectural problem:**
   - Each fix reveals new shared state/coupling/problem in different place
   - Fixes require "massive refactoring" to implement
   - Each fix creates new symptoms elsewhere

   **STOP and question fundamentals:**
   - Is this pattern fundamentally sound?
   - Are we "sticking with it through sheer inertia"?
   - Should we refactor architecture vs. continue fixing symptoms?

   **Discuss with your human partner before attempting more fixes**

   This is NOT a failed hypothesis - this is a wrong architecture.

## Red Flags - STOP and Follow Process

If you catch yourself thinking:
- "Quick fix for now, investigate later"
- "Just try changing X and see if it works"
- "Add multiple changes, run tests"
- "Skip the test, I'll manually verify"
- "It's probably X, let me fix that"
- "I don't fully understand but this might work"
- "Pattern says X but I'll adapt it differently"
- "Here are the main problems: [lists fixes without investigation]"
- Proposing solutions before tracing data flow
- **"One more fix attempt" (when already tried 2+)**
- **Each fix reveals new problem in different place**

**ALL of these mean: STOP. Return to Phase 1.**

**If 3+ fixes failed:** Question the architecture (see Phase 4.5)

## your human partner's Signals You're Doing It Wrong

**Watch for these redirections:**
- "Is that not happening?" - You assumed without verifying
- "Will it show us...?" - You should have added evidence gathering
- "Stop guessing" - You're proposing fixes without understanding
- "Ultrathink this" - Question fundamentals, not just symptoms
- "We're stuck?" (frustrated) - Your approach isn't working

**When you see these:** STOP. Return to Phase 1.

## Common Rationalizations

| Excuse | Reality |
|--------|---------|
| "Issue is simple, don't need process" | Simple issues have root causes too. Process is fast for simple bugs. |
| "Emergency, no time for process" | Systematic debugging is FASTER than guess-and-check thrashing. |
| "Just try this first, then investigate" | First fix sets the pattern. Do it right from the start. |
| "I'll write test after confirming fix works" | Untested fixes don't stick. Test first proves it. |
| "Multiple fixes at once saves time" | Can't isolate what worked. Causes new bugs. |
| "Reference too long, I'll adapt the pattern" | Partial understanding guarantees bugs. Read it completely. |
| "I see the problem, let me fix it" | Seeing symptoms ≠ understanding root cause. |
| "One more fix attempt" (after 2+ failures) | 3+ failures = architectural problem. Question pattern, don't fix again. |

## Quick Reference

| Phase | Key Activities | Success Criteria |
|-------|---------------|------------------|
| **1. Root Cause** | Read errors, reproduce, check changes, gather evidence | Understand WHAT and WHY |
| **2. Pattern** | Find working examples, compare | Identify differences |
| **3. Hypothesis** | Form theory, test minimally | Confirmed or new hypothesis |
| **4. Implementation** | Create test, fix, verify | Bug resolved, tests pass |

## When Process Reveals "No Root Cause"

If systematic investigation reveals issue is truly environmental, timing-dependent, or external:

1. You've completed the process
2. Document what you investigated
3. Implement appropriate handling (retry, timeout, error message)
4. Add monitoring/logging for future investigation

**But:** 95% of "no root cause" cases are incomplete investigation.

## Supporting Techniques

These techniques are part of systematic debugging and available in this directory:

- **`root-cause-tracing.md`** - Trace bugs backward through call stack to find original trigger
- **`defense-in-depth.md`** - Add validation at multiple layers after finding root cause
- **`condition-based-waiting.md`** - Replace arbitrary timeouts with condition polling

**Related skills:**
- **superpowers:test-driven-development** - For creating failing test case (Phase 4, Step 1)
- **superpowers:verification-before-completion** - Verify fix worked before claiming success

## Real-World Impact

From debugging sessions:
- Systematic approach: 15-30 minutes to fix
- Random fixes approach: 2-3 hours of thrashing
- First-time fix rate: 95% vs 40%
- New bugs introduced: Near zero vs common

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: systems-programming-rust-project
description: "You are a Rust project architecture expert specializing in scaffolding production-ready Rust applications. Generate complete project structures with cargo tooling, proper module organization, testing"
risk: critical
source: community
date_added: "2026-02-27"
---

# Rust Project Scaffolding

You are a Rust project architecture expert specializing in scaffolding production-ready Rust applications. Generate complete project structures with cargo tooling, proper module organization, testing setup, and configuration following Rust best practices.

## Use this skill when

- Working on rust project scaffolding tasks or workflows
- Needing guidance, best practices, or checklists for rust project scaffolding

## Do not use this skill when

- The task is unrelated to rust project scaffolding
- You need a different domain or tool outside this scope

## Context

The user needs automated Rust project scaffolding that creates idiomatic, safe, and performant applications with proper structure, dependency management, testing, and build configuration. Focus on Rust idioms and scalable architecture.

## Requirements

$ARGUMENTS

## Instructions

### 1. Analyze Project Type

Determine the project type from user requirements:
- **Binary**: CLI tools, applications, services
- **Library**: Reusable crates, shared utilities
- **Workspace**: Multi-crate projects, monorepos
- **Web API**: Actix/Axum web services, REST APIs
- **WebAssembly**: Browser-based applications

### 2. Initialize Project with Cargo

```bash
# Create binary project
cargo new project-name
cd project-name

# Or create library
cargo new --lib library-name

# Initialize git (cargo does this automatically)
# Add to .gitignore if needed
echo "/target" >> .gitignore
echo "Cargo.lock" >> .gitignore  # For libraries only
```

### 3. Generate Binary Project Structure

```
binary-project/
├── Cargo.toml
├── README.md
├── src/
│   ├── main.rs
│   ├── config.rs
│   ├── cli.rs
│   ├── commands/
│   │   ├── mod.rs
│   │   ├── init.rs
│   │   └── run.rs
│   ├── error.rs
│   └── lib.rs
├── tests/
│   ├── integration_test.rs
│   └── common/
│       └── mod.rs
├── benches/
│   └── benchmark.rs
└── examples/
    └── basic_usage.rs
```

**Cargo.toml**:
```toml
[package]
name = "project-name"
version = "0.1.0"
edition = "2021"
rust-version = "1.75"
authors = ["Your Name <email@example.com>"]
description = "Project description"
license = "MIT OR Apache-2.0"
repository = "https://github.com/user/project-name"

[dependencies]
clap = { version = "4.5", features = ["derive"] }
tokio = { version = "1.36", features = ["full"] }
anyhow = "1.0"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"

[dev-dependencies]
criterion = "0.5"

[[bench]]
name = "benchmark"
harness = false

[profile.release]
opt-level = 3
lto = true
codegen-units = 1
```

**src/main.rs**:
```rust
use anyhow::Result;
use clap::Parser;

mod cli;
mod commands;
mod config;
mod error;

use cli::Cli;

#[tokio::main]
async fn main() -> Result<()> {
    let cli = Cli::parse();

    match cli.command {
        cli::Commands::Init(args) => commands::init::execute(args).await?,
        cli::Commands::Run(args) => commands::run::execute(args).await?,
    }

    Ok(())
}
```

**src/cli.rs**:
```rust
use clap::{Parser, Subcommand};

#[derive(Parser)]
#[command(name = "project-name")]
#[command(about = "Project description", long_about = None)]
pub struct Cli {
    #[command(subcommand)]
    pub command: Commands,
}

#[derive(Subcommand)]
pub enum Commands {
    /// Initialize a new project
    Init(InitArgs),
    /// Run the application
    Run(RunArgs),
}

#[derive(Parser)]
pub struct InitArgs {
    /// Project name
    #[arg(short, long)]
    pub name: String,
}

#[derive(Parser)]
pub struct RunArgs {
    /// Enable verbose output
    #[arg(short, long)]
    pub verbose: bool,
}
```

**src/error.rs**:
```rust
use std::fmt;

#[derive(Debug)]
pub enum AppError {
    NotFound(String),
    InvalidInput(String),
    IoError(std::io::Error),
}

impl fmt::Display for AppError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            AppError::NotFound(msg) => write!(f, "Not found: {}", msg),
            AppError::InvalidInput(msg) => write!(f, "Invalid input: {}", msg),
            AppError::IoError(e) => write!(f, "IO error: {}", e),
        }
    }
}

impl std::error::Error for AppError {}

pub type Result<T> = std::result::Result<T, AppError>;
```

### 4. Generate Library Project Structure

```
library-name/
├── Cargo.toml
├── README.md
├── src/
│   ├── lib.rs
│   ├── core.rs
│   ├── utils.rs
│   └── error.rs
├── tests/
│   └── integration_test.rs
└── examples/
    └── basic.rs
```

**Cargo.toml for Library**:
```toml
[package]
name = "library-name"
version = "0.1.0"
edition = "2021"
rust-version = "1.75"

[dependencies]
# Keep minimal for libraries

[dev-dependencies]
tokio-test = "0.4"

[lib]
name = "library_name"
path = "src/lib.rs"
```

**src/lib.rs**:
```rust
//! Library documentation
//!
//! # Examples
//!
//! ```
//! use library_name::core::CoreType;
//!
//! let instance = CoreType::new();
//! ```

pub mod core;
pub mod error;
pub mod utils;

pub use core::CoreType;
pub use error::{Error, Result};

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn it_works() {
        assert_eq!(2 + 2, 4);
    }
}
```

### 5. Generate Workspace Structure

```
workspace/
├── Cargo.toml
├── .gitignore
├── crates/
│   ├── api/
│   │   ├── Cargo.toml
│   │   └── src/
│   │       └── lib.rs
│   ├── core/
│   │   ├── Cargo.toml
│   │   └── src/
│   │       └── lib.rs
│   └── cli/
│       ├── Cargo.toml
│       └── src/
│           └── main.rs
└── tests/
    └── integration_test.rs
```

**Cargo.toml (workspace root)**:
```toml
[workspace]
members = [
    "crates/api",
    "crates/core",
    "crates/cli",
]
resolver = "2"

[workspace.package]
version = "0.1.0"
edition = "2021"
rust-version = "1.75"
authors = ["Your Name <email@example.com>"]
license = "MIT OR Apache-2.0"

[workspace.dependencies]
tokio = { version = "1.36", features = ["full"] }
serde = { version = "1.0", features = ["derive"] }

[profile.release]
opt-level = 3
lto = true
```

### 6. Generate Web API Structure (Axum)

```
web-api/
├── Cargo.toml
├── src/
│   ├── main.rs
│   ├── routes/
│   │   ├── mod.rs
│   │   ├── users.rs
│   │   └── health.rs
│   ├── handlers/
│   │   ├── mod.rs
│   │   └── user_handler.rs
│   ├── models/
│   │   ├── mod.rs
│   │   └── user.rs
│   ├── services/
│   │   ├── mod.rs
│   │   └── user_service.rs
│   ├── middleware/
│   │   ├── mod.rs
│   │   └── auth.rs
│   └── error.rs
└── tests/
    └── api_tests.rs
```

**Cargo.toml for Web API**:
```toml
[package]
name = "web-api"
version = "0.1.0"
edition = "2021"

[dependencies]
axum = "0.7"
tokio = { version = "1.36", features = ["full"] }
tower = "0.4"
tower-http = { version = "0.5", features = ["trace", "cors"] }
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
sqlx = { version = "0.7", features = ["runtime-tokio-native-tls", "postgres"] }
tracing = "0.1"
tracing-subscriber = "0.3"
```

**src/main.rs (Axum)**:
```rust
use axum::{Router, routing::get};
use tower_http::cors::CorsLayer;
use std::net::SocketAddr;

mod routes;
mod handlers;
mod models;
mod services;
mod error;

#[tokio::main]
async fn main() {
    tracing_subscriber::fmt::init();

    let app = Router::new()
        .route("/health", get(routes::health::health_check))
        .nest("/api/users", routes::users::router())
        .layer(CorsLayer::permissive());

    let addr = SocketAddr::from(([0, 0, 0, 0], 3000));
    tracing::info!("Listening on {}", addr);

    let listener = tokio::net::TcpListener::bind(addr).await.unwrap();
    axum::serve(listener, app).await.unwrap();
}
```

### 7. Configure Development Tools

**Makefile**:
```makefile
.PHONY: build test lint fmt run clean bench

build:
	cargo build

test:
	cargo test

lint:
	cargo clippy -- -D warnings

fmt:
	cargo fmt --check

run:
	cargo run

clean:
	cargo clean

bench:
	cargo bench
```

**rustfmt.toml**:
```toml
edition = "2021"
max_width = 100
tab_spaces = 4
use_small_heuristics = "Max"
```

**clippy.toml**:
```toml
cognitive-complexity-threshold = 30
```

## Output Format

1. **Project Structure**: Complete directory tree with idiomatic Rust organization
2. **Configuration**: Cargo.toml with dependencies and build settings
3. **Entry Point**: main.rs or lib.rs with proper documentation
4. **Tests**: Unit and integration test structure
5. **Documentation**: README and code documentation
6. **Development Tools**: Makefile, clippy/rustfmt configs

Focus on creating idiomatic Rust projects with strong type safety, proper error handling, and comprehensive testing setup.

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: tailwind-design-system
description: "Build production-ready design systems with Tailwind CSS, including design tokens, component variants, responsive patterns, and accessibility."
risk: safe
source: community
date_added: "2026-02-27"
---

# Tailwind Design System

Build production-ready design systems with Tailwind CSS, including design tokens, component variants, responsive patterns, and accessibility.

## Use this skill when

- Creating a component library with Tailwind
- Implementing design tokens and theming
- Building responsive and accessible components
- Standardizing UI patterns across a codebase
- Migrating to or extending Tailwind CSS
- Setting up dark mode and color schemes

## Do not use this skill when

- The task is unrelated to tailwind design system
- You need a different domain or tool outside this scope

## Instructions

- Clarify goals, constraints, and required inputs.
- Apply relevant best practices and validate outcomes.
- Provide actionable steps and verification.
- If detailed examples are required, open `resources/implementation-playbook.md`.

## Resources

- `resources/implementation-playbook.md` for detailed patterns and examples.

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: tailwind-patterns
description: "Tailwind CSS v4 principles. CSS-first configuration, container queries, modern patterns, design token architecture."
risk: none
source: community
date_added: "2026-02-27"
---

# Tailwind CSS Patterns (v4 - 2025)

> Modern utility-first CSS with CSS-native configuration.

## When to Use
Use this skill when configuring Tailwind v4, using CSS-first theme and design tokens, or implementing container queries and modern Tailwind patterns.

---

## 1. Tailwind v4 Architecture

### What Changed from v3

| v3 (Legacy) | v4 (Current) |
|-------------|--------------|
| `tailwind.config.js` | CSS-based `@theme` directive |
| PostCSS plugin | Oxide engine (10x faster) |
| JIT mode | Native, always-on |
| Plugin system | CSS-native features |
| `@apply` directive | Still works, discouraged |

### v4 Core Concepts

| Concept | Description |
|---------|-------------|
| **CSS-first** | Configuration in CSS, not JavaScript |
| **Oxide Engine** | Rust-based compiler, much faster |
| **Native Nesting** | CSS nesting without PostCSS |
| **CSS Variables** | All tokens exposed as `--*` vars |

---

## 2. CSS-Based Configuration

### Theme Definition

```
@theme {
  /* Colors - use semantic names */
  --color-primary: oklch(0.7 0.15 250);
  --color-surface: oklch(0.98 0 0);
  --color-surface-dark: oklch(0.15 0 0);

  /* Spacing scale */
  --spacing-xs: 0.25rem;
  --spacing-sm: 0.5rem;
  --spacing-md: 1rem;
  --spacing-lg: 2rem;

  /* Typography */
  --font-sans: 'Inter', system-ui, sans-serif;
  --font-mono: 'JetBrains Mono', monospace;
}
```

### When to Extend vs Override

| Action | Use When |
|--------|----------|
| **Extend** | Adding new values alongside defaults |
| **Override** | Replacing default scale entirely |
| **Semantic tokens** | Project-specific naming (primary, surface) |

---

## 3. Container Queries (v4 Native)

### Breakpoint vs Container

| Type | Responds To |
|------|-------------|
| **Breakpoint** (`md:`) | Viewport width |
| **Container** (`@container`) | Parent element width |

### Container Query Usage

| Pattern | Classes |
|---------|---------|
| Define container | `@container` on parent |
| Container breakpoint | `@sm:`, `@md:`, `@lg:` on children |
| Named containers | `@container/card` for specificity |

### When to Use

| Scenario | Use |
|----------|-----|
| Page-level layouts | Viewport breakpoints |
| Component-level responsive | Container queries |
| Reusable components | Container queries (context-independent) |

---

## 4. Responsive Design

### Breakpoint System

| Prefix | Min Width | Target |
|--------|-----------|--------|
| (none) | 0px | Mobile-first base |
| `sm:` | 640px | Large phone / small tablet |
| `md:` | 768px | Tablet |
| `lg:` | 1024px | Laptop |
| `xl:` | 1280px | Desktop |
| `2xl:` | 1536px | Large desktop |

### Mobile-First Principle

1. Write mobile styles first (no prefix)
2. Add larger screen overrides with prefixes
3. Example: `w-full md:w-1/2 lg:w-1/3`

---

## 5. Dark Mode

### Configuration Strategies

| Method | Behavior | Use When |
|--------|----------|----------|
| `class` | `.dark` class toggles | Manual theme switcher |
| `media` | Follows system preference | No user control |
| `selector` | Custom selector (v4) | Complex theming |

### Dark Mode Pattern

| Element | Light | Dark |
|---------|-------|------|
| Background | `bg-white` | `dark:bg-zinc-900` |
| Text | `text-zinc-900` | `dark:text-zinc-100` |
| Borders | `border-zinc-200` | `dark:border-zinc-700` |

---

## 6. Modern Layout Patterns

### Flexbox Patterns

| Pattern | Classes |
|---------|---------|
| Center (both axes) | `flex items-center justify-center` |
| Vertical stack | `flex flex-col gap-4` |
| Horizontal row | `flex gap-4` |
| Space between | `flex justify-between items-center` |
| Wrap grid | `flex flex-wrap gap-4` |

### Grid Patterns

| Pattern | Classes |
|---------|---------|
| Auto-fit responsive | `grid grid-cols-[repeat(auto-fit,minmax(250px,1fr))]` |
| Asymmetric (Bento) | `grid grid-cols-3 grid-rows-2` with spans |
| Sidebar layout | `grid grid-cols-[auto_1fr]` |

> **Note:** Prefer asymmetric/Bento layouts over symmetric 3-column grids.

---

## 7. Modern Color System

### OKLCH vs RGB/HSL

| Format | Advantage |
|--------|-----------|
| **OKLCH** | Perceptually uniform, better for design |
| **HSL** | Intuitive hue/saturation |
| **RGB** | Legacy compatibility |

### Color Token Architecture

| Layer | Example | Purpose |
|-------|---------|---------|
| **Primitive** | `--blue-500` | Raw color values |
| **Semantic** | `--color-primary` | Purpose-based naming |
| **Component** | `--button-bg` | Component-specific |

---

## 8. Typography System

### Font Stack Pattern

| Type | Recommended |
|------|-------------|
| Sans | `'Inter', 'SF Pro', system-ui, sans-serif` |
| Mono | `'JetBrains Mono', 'Fira Code', monospace` |
| Display | `'Outfit', 'Poppins', sans-serif` |

### Type Scale

| Class | Size | Use |
|-------|------|-----|
| `text-xs` | 0.75rem | Labels, captions |
| `text-sm` | 0.875rem | Secondary text |
| `text-base` | 1rem | Body text |
| `text-lg` | 1.125rem | Lead text |
| `text-xl`+ | 1.25rem+ | Headings |

---

## 9. Animation & Transitions

### Built-in Animations

| Class | Effect |
|-------|--------|
| `animate-spin` | Continuous rotation |
| `animate-ping` | Attention pulse |
| `animate-pulse` | Subtle opacity pulse |
| `animate-bounce` | Bouncing effect |

### Transition Patterns

| Pattern | Classes |
|---------|---------|
| All properties | `transition-all duration-200` |
| Specific | `transition-colors duration-150` |
| With easing | `ease-out` or `ease-in-out` |
| Hover effect | `hover:scale-105 transition-transform` |

---

## 10. Component Extraction

### When to Extract

| Signal | Action |
|--------|--------|
| Same class combo 3+ times | Extract component |
| Complex state variants | Extract component |
| Design system element | Extract + document |

### Extraction Methods

| Method | Use When |
|--------|----------|
| **React/Vue component** | Dynamic, JS needed |
| **@apply in CSS** | Static, no JS needed |
| **Design tokens** | Reusable values |

---

## 11. Anti-Patterns

| Don't | Do |
|-------|-----|
| Arbitrary values everywhere | Use design system scale |
| `!important` | Fix specificity properly |
| Inline `style=` | Use utilities |
| Duplicate long class lists | Extract component |
| Mix v3 config with v4 | Migrate fully to CSS-first |
| Use `@apply` heavily | Prefer components |

---

## 12. Performance Principles

| Principle | Implementation |
|-----------|----------------|
| **Purge unused** | Automatic in v4 |
| **Avoid dynamism** | No template string classes |
| **Use Oxide** | Default in v4, 10x faster |
| **Cache builds** | CI/CD caching |

---

> **Remember:** Tailwind v4 is CSS-first. Embrace CSS variables, container queries, and native features. The config file is now optional.

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: taisly-social-media-posting
description: "Use Taisly Agent Kit to prepare and publish approved short-form video posts across TikTok, Instagram Reels, YouTube Shorts, X, and Facebook."
category: marketing
risk: critical
source: community
source_repo: taisly/agent
source_type: community
date_added: "2026-07-07"
author: taisly
tags: [social-media, video, publishing, mcp, cli, sdk, tiktok, instagram, youtube-shorts, x, facebook]
tools: [codex, claude]
license: "MIT"
license_source: "https://github.com/taisly/agent/blob/main/LICENSE"
---

# Taisly Social Media Posting

## Overview

Taisly Agent Kit provides an MCP server, CLI, SDK, and agent docs for publishing
approved short-form videos to TikTok, Instagram Reels, YouTube Shorts, X, and
Facebook. Use this skill to plan a posting workflow around Taisly, verify that
the user has the required account access, and keep publishing actions behind an
explicit confirmation gate.

## When to Use

- Use when the user wants an agent-assisted workflow for publishing short-form
  videos with Taisly.
- Use when the user mentions `taisly/agent`, the Taisly MCP server, Taisly CLI,
  or the Taisly SDK.
- Use when coordinating final approval, caption metadata, target platforms, and
  posting status for social video distribution.

## Workflow

1. Confirm the exact target platforms and video asset paths or URLs.
2. Confirm that the user has already connected the relevant social accounts in
   Taisly or has provided the intended MCP/CLI setup path.
3. Draft or review captions, hashtags, titles, descriptions, and platform
   metadata before any publishing command is run.
4. Present a final posting summary with platforms, media, captions, visibility,
   and timing.
5. Wait for explicit user approval before invoking any Taisly command, MCP tool,
   SDK call, or other state-changing publishing action.

## Examples

```text
Use Taisly to prepare this product demo for TikTok, Reels, Shorts, X, and Facebook.
Review the caption and metadata first; do not publish until I approve.
```

```text
Set up a Taisly MCP publishing workflow for approved video assets in ./campaign.
```

## Safety Notes

- Treat publish, schedule, delete, account-linking, and metadata update actions
  as state-changing operations requiring explicit user approval.
- Never request, print, or store platform passwords, OAuth secrets, API keys, or
  session tokens. Use the user's existing Taisly/MCP/CLI authentication flow.
- If the requested action could violate platform policies, brand review, legal
  constraints, or creator permissions, pause and ask for confirmation.

## Limitations

- Platform availability, media requirements, and API behavior depend on the
  upstream Taisly Agent Kit and connected platform accounts.
- This skill does not replace human review for legal, brand, copyright, or
  platform-compliance decisions.
- Verify the current Taisly setup instructions from `taisly/agent` before
  installing or running tools in a new environment.

## Source

- GitHub: [taisly/agent](https://github.com/taisly/agent)


---
name: talivia-agent-kit
description: "Set up and verify Talivia revenue analytics through MCP, with explicit confirmation for website changes and payment attribution."
category: marketing
risk: critical
source: "https://github.com/talivia-group/agent/tree/f4ed3fc6b554ad5183a57ae13ca2a9bd5162c12a"
source_repo: talivia-group/agent
source_type: community
date_added: "2026-08-02"
author: taliviagroup
tags: [analytics, revenue, attribution, mcp, talivia, marketing]
tools: [codex, claude]
license: "MIT"
license_source: "https://github.com/talivia-group/agent/blob/f4ed3fc6b554ad5183a57ae13ca2a9bd5162c12a/LICENSE"
---

# Talivia Agent Kit

## Overview

Talivia connects website traffic and visitor journeys to payment revenue through
its MCP server. Use this skill to inspect an existing Talivia setup, install or
verify website tracking, and review traffic-to-revenue attribution while keeping
account, website, file, and payment changes behind explicit user consent.

## When to Use

- Use when the user explicitly asks to set up or verify Talivia revenue analytics.
- Use when the user mentions the Talivia MCP server, `talivia-group/agent`, or
  `@talivia/agent`.
- Use when the user wants to understand which referrers, campaigns, pages, or
  visitor journeys are associated with revenue.
- Do not use this skill for generic analytics work or unrelated payment-provider
  setup.

## Safety Gate

1. Confirm the user owns or is authorized to manage the Talivia account and the
   target website.
2. Use only the configured official MCP endpoint, `https://talivia.com/mcp`.
   Stop if a tool, setup response, redirect, or local configuration supplies a
   different host or an insecure URL; never send a Talivia credential to an
   unverified endpoint.
3. Keep credentials out of chat, prompts, tool arguments, source files, and logs.
   Never request or expose payment API keys, OAuth secrets, or bearer tokens.
4. Read the current account and website state before changing anything. Reuse an
   existing website when possible; call `talivia_websites_create` only after the
   user explicitly asks to create one.
5. Before any state-changing MCP call, state the exact account, website, action,
   data involved, and expected effect, then obtain explicit user confirmation.

## Workflow

### Inspect the current setup

Call the read-only tools first:

1. `talivia_account_status`
2. `talivia_websites_list`
3. `talivia_setup_status_get` when a website or installation status is known

Do not infer account ownership, website identity, or consent from a domain name
alone. Ask when more than one website matches or the target is ambiguous.

### Plan and install tracking

1. Call `talivia_tracking_snippet_get` and
   `talivia_framework_install_plan_get` for the selected website.
2. Show the files, framework, and tracking changes that would be made. Use the
   native workspace tools to edit the user's project; Talivia MCP does not have
   permission to edit local files by itself.
3. Make local edits only when the user has requested the installation or has
   confirmed the exact proposed changes. Preserve existing analytics, consent,
   and security controls.
4. Run the project's normal build and test commands before deployment.

### Verify after deployment

After the user confirms that the site is deployed, call:

- `talivia_tracker_verify`
- `talivia_setup_status_get`

Report what was actually verified, including any delay, missing event, or
unverified deployment. Do not claim revenue attribution from a tracking check
alone.

## Examples

### Read-only revenue review

> Inspect the Talivia account and tell me which pages and referrers are
> associated with revenue. Do not create websites, edit files, or connect a
> payment provider.

Start with the read-only account, website, and setup-status tools. Report the
returned evidence and uncertainty without inferring causation.

### Tracking installation

> Prepare Talivia tracking for the selected site and show me the exact files
> and changes before applying anything.

Resolve the website, retrieve the tracking snippet and framework plan, present
the proposed local diff, and wait for confirmation before writing or deploying.

### Connect payment attribution

1. Explain that payment attribution starts a browser-based authorization flow
   and identify the Talivia account and website involved.
2. Obtain explicit confirmation before calling
   `talivia_payment_connect_start`.
3. Send the user only to the secure URL returned by the official Talivia flow.
   Do not ask the user to paste payment credentials or API keys into chat.
4. Finish with `talivia_payment_status_get` and
   `talivia_checkout_attribution_guide_get`, and clearly separate connected
   status from verified revenue data.

## Limitations

- This skill does not establish legal authority, cookie consent, privacy
  compliance, or payment-provider permissions for the user.
- Talivia metrics and attribution depend on the upstream service, deployment,
  consent configuration, event delivery, and connected payment provider; they
  may be delayed or incomplete and do not prove causation.
- This skill does not install packages, change MCP configuration, create a
  website, deploy code, or connect payments without an explicit user request
  and confirmation at the relevant step.
- The upstream CLI and MCP server are external software. Review its current
  release and endpoint configuration before installing or upgrading it; this
  skill is pinned for attribution to the reviewed upstream commit, not a claim
  that future upstream changes are safe.
- Stop and ask for clarification when the account, website, endpoint, consent
  state, requested file changes, or payment scope is ambiguous.

## Source

- Upstream repository: [talivia-group/agent](https://github.com/talivia-group/agent/tree/f4ed3fc6b554ad5183a57ae13ca2a9bd5162c12a)
- Reviewed package version: `@talivia/agent@0.1.0`


---
name: tanstack-query-expert
description: "Expert in TanStack Query (React Query) — asynchronous state management. Covers data fetching, stale time configuration, mutations, optimistic updates, and Next.js App Router (SSR) integration."
risk: safe
source: community
date_added: "2026-03-07"
---

# TanStack Query Expert

You are a production-grade TanStack Query (formerly React Query) expert. You help developers build robust, performant asynchronous state management layers in React and Next.js applications. You master declarative data fetching, cache invalidation, optimistic UI updates, background syncing, error boundaries, and server-side rendering (SSR) hydration patterns.

## When to Use This Skill

- Use when setting up or refactoring data fetching logic (replacing `useEffect` + `useState`)
- Use when designing query keys (Array-based, strictly typed keys)
- Use when configuring global or query-specific `staleTime`, `gcTime`, and `retry` behavior
- Use when writing `useMutation` hooks for POST/PUT/DELETE requests
- Use when invalidating the cache (`queryClient.invalidateQueries`) after a mutation
- Use when implementing Optimistic Updates for instant UX feedback
- Use when integrating TanStack Query with Next.js App Router (Server Components + Client Boundary hydration)

## Core Concepts

### Why TanStack Query?

TanStack Query is not just for fetching data; it's an **asynchronous state manager**. It handles caching, background updates, deduplication of multiple requests for the same data, pagination, and out-of-the-box loading/error states.

**Rule of Thumb:** Never use `useEffect` to fetch data if TanStack Query is available in the stack.

## Query Definition Patterns

### The Custom Hook Pattern (Best Practice)

Always abstract `useQuery` calls into custom hooks to encapsulate the fetching logic, TypeScript types, and query keys.

```typescript
import { useQuery } from '@tanstack/react-query';

// 1. Define strict types
type User = { id: string; name: string; status: 'active' | 'inactive' };

// 2. Define the fetcher function
const fetchUser = async (userId: string): Promise<User> => {
  const res = await fetch(`/api/users/${userId}`);
  if (!res.ok) throw new Error('Failed to fetch user');
  return res.json();
};

// 3. Export a custom hook
export const useUser = (userId: string) => {
  return useQuery({
    queryKey: ['users', userId], // Array-based query key
    queryFn: () => fetchUser(userId),
    staleTime: 1000 * 60 * 5, // Data is fresh for 5 minutes (no background refetching)
    enabled: !!userId, // Dependent query: only run if userId exists
  });
};
```

### Advanced Query Keys

Query keys uniquely identify the cache. They must be arrays, and order matters.

```typescript
// Filtering / Sorting
useQuery({
  queryKey: ['issues', { status: 'open', sort: 'desc' }],
  queryFn: () => fetchIssues({ status: 'open', sort: 'desc' })
});

// Factory pattern for query keys (Highly recommended for large apps)
export const issueKeys = {
  all: ['issues'] as const,
  lists: () => [...issueKeys.all, 'list'] as const,
  list: (filters: string) => [...issueKeys.lists(), { filters }] as const,
  details: () => [...issueKeys.all, 'detail'] as const,
  detail: (id: number) => [...issueKeys.details(), id] as const,
};
```

## Mutations & Cache Invalidation

### Basic Mutation with Invalidation

When you modify data on the server, you must tell the client cache that the old data is now stale.

```typescript
import { useMutation, useQueryClient } from '@tanstack/react-query';

export const useCreatePost = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async (newPost: { title: string }) => {
      const res = await fetch('/api/posts', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(newPost),
      });
      return res.json();
    },
    // On success, invalidate the 'posts' cache to trigger a background refetch
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['posts'] });
    },
  });
};
```

### Optimistic Updates

Give the user instant feedback by updating the cache *before* the server responds, and rolling back if the request fails.

```typescript
export const useUpdateTodo = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: updateTodoFn,

    // 1. Triggered immediately when mutate() is called
    onMutate: async (newTodo) => {
      // Cancel any outgoing refetches so they don't overwrite our optimistic update
      await queryClient.cancelQueries({ queryKey: ['todos'] });

      // Snapshot the previous value
      const previousTodos = queryClient.getQueryData(['todos']);

      // Optimistically update to the new value
      queryClient.setQueryData(['todos'], (old: any) =>
        old.map((todo: any) => todo.id === newTodo.id ? { ...todo, ...newTodo } : todo)
      );

      // Return a context object with the snapshotted value
      return { previousTodos };
    },

    // 2. If the mutation fails, use the context returned from onMutate to roll back
    onError: (err, newTodo, context) => {
      queryClient.setQueryData(['todos'], context?.previousTodos);
    },

    // 3. Always refetch after error or success to ensure server sync
    onSettled: () => {
      queryClient.invalidateQueries({ queryKey: ['todos'] });
    },
  });
};
```

## Next.js App Router Integration

### Initializing the Provider

```typescript
// app/providers.tsx
'use client'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { useState } from 'react'

export default function Providers({ children }: { children: React.ReactNode }) {
  const [queryClient] = useState(
    () =>
      new QueryClient({
        defaultOptions: {
          queries: {
            staleTime: 60 * 1000, // 1 minute
            refetchOnWindowFocus: false, // Prevents aggressive refetching on tab switch
          },
        },
      })
  )

  return (
    <QueryClientProvider client={queryClient}>
      {children}
    </QueryClientProvider>
  )
}
```

### Server Component Pre-fetching (Hydration)

Pre-fetch data on the server and pass it to the client without prop-drilling or `initialData`.

```typescript
// app/posts/page.tsx (Server Component)
import { dehydrate, HydrationBoundary, QueryClient } from '@tanstack/react-query';
import PostsList from './PostsList'; // Client Component

export default async function PostsPage() {
  const queryClient = new QueryClient();

  // Prefetch the data on the server
  await queryClient.prefetchQuery({
    queryKey: ['posts'],
    queryFn: fetchPostsServerSide,
  });

  // Dehydrate the cache and pass it to the HydrationBoundary
  return (
    <HydrationBoundary state={dehydrate(queryClient)}>
      <PostsList />
    </HydrationBoundary>
  );
}
```

```typescript
// app/posts/PostsList.tsx (Client Component)
'use client'
import { useQuery } from '@tanstack/react-query';

export default function PostsList() {
  // This will NOT trigger a network request on mount!
  // It reads instantly from the dehydrated server cache.
  const { data } = useQuery({
    queryKey: ['posts'],
    queryFn: fetchPostsClientSide,
  });

  return <div>{data.map(post => <p key={post.id}>{post.title}</p>)}</div>;
}
```

## Best Practices

- ✅ **Do:** Create Query Key factories so you don't misspell `['users']` vs `['user']` across different files.
- ✅ **Do:** Set a global `staleTime` (e.g., `1000 * 60`) if your data doesn't change every second. The default `staleTime` is `0`, meaning TanStack Query will trigger a background refetch on every component remount by default.
- ✅ **Do:** Use `queryClient.setQueryData` sparingly. It's usually better to just `invalidateQueries` and let TanStack Query refetch the fresh data organically.
- ✅ **Do:** Abstract all `useMutation` and `useQuery` calls into custom hooks. Views should only say `const { mutate } = useCreatePost()`.
- ❌ **Don't:** Pass primitive callbacks inline directly to `useQuery` without memoization if you rely on closures. (Instead, rely on the `queryKey` dependency array).
- ❌ **Don't:** Sync query data into local React state (e.g., `useEffect(() => setLocalState(data), [data])`). Use the query data directly. If you need derived state, derive it during render.

## Troubleshooting

**Problem:** Infinite fetching loop in the network tab.
**Solution:** Check your `queryFn`. If your `fetch` logic isn't structured correctly, or throws an unhandled exception before hitting the return, TanStack Query will retry automatically up to 3 times (default). If wrapped in an unstable `useEffect`, it loops infinitely. Check `retry: false` for debugging.

**Problem:** `staleTime` vs `gcTime` (formerly `cacheTime`) confusion.
**Solution:** `staleTime` governs when a background refetch is triggered. `gcTime` governs how long the inactive data stays in memory after the component unmounts. If `gcTime` < `staleTime`, data will be deleted before it even gets stale!

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.


---
name: task-intelligence
description: "Protocolo de Inteligência Pré-Tarefa — ativa TODOS os agentes relevantes do ecossistema ANTES de executar qualquer tarefa solicitada pelo usuário."
risk: none
source: community
date_added: '2026-03-06'
author: renat
tags:
- planning
- pre-task
- risk-analysis
- orchestration
tools:
- claude-code
- antigravity
- cursor
- gemini-cli
- codex-cli
---

# Task Intelligence — Protocolo de Amplificação Pré-Tarefa

## Overview

Protocolo de Inteligência Pré-Tarefa — ativa TODOS os agentes relevantes do ecossistema ANTES de executar qualquer tarefa solicitada pelo usuário. Enriquece o contexto com análise paralela multi-agente, produz estimativa real de tempo (início→fim), mapeia problemas prováveis e improvável, e formula um plano de execução antecipado com estratégias de contingência.

## When to Use This Skill

- When the user mentions "pre-task briefing" or related topics
- When the user mentions "briefing tarefa" or related topics
- When the user mentions "plano execucao tarefa" or related topics
- When the user mentions "antes de executar analise" or related topics
- When the user mentions "task intelligence" or related topics
- When the user mentions "consultar agentes paralelo" or related topics

## Do Not Use This Skill When

- The task is unrelated to task intelligence
- A simpler, more specific tool can handle the request
- The user needs general-purpose assistance without domain expertise

## How It Works

Antes de qualquer execução, este agente realiza um **briefing inteligente completo**:

1. **Ativa todos os agentes relevantes em paralelo** — cada um analisa a tarefa pela sua ótica
2. **Sintetiza o conhecimento coletivo** em um plano unificado
3. **Estima tempo real** do início ao fim (com breakdown por etapa)
4. **Mapeia problemas prováveis** e os resolve antecipadamente
5. **Define pontos de verificação** para detectar desvios antes que virem bloqueadores

A razão central: executar uma tarefa sem esse briefing é como cirurgiar sem exame pré-operatório.
O custo de 30-60 segundos de análise paralela elimina horas de retrabalho.

---

## Fase 1 — Classificação Da Tarefa (5-10 Segundos)

Antes de qualquer coisa, classifique a tarefa em uma das categorias:

| Categoria | Exemplos | Nível de Briefing |
|-----------|---------|-------------------|
| **Simples** | responder pergunta, explicar conceito, pequena edição | Mínimo (só scan) |
| **Moderada** | criar arquivo, modificar skill, instalar dependência | Normal (scan + match + estimativa) |
| **Complexa** | criar skill nova, integração API, arquitetura, refatoração | Completo (todos os passos abaixo) |
| **Crítica** | ações irreversíveis, deploys, delete, reset, modificar infra | Máximo + confirmação explícita |

Para tarefas **Simples**, execute normalmente sem briefing completo.
Para **Moderada**, **Complexa** e **Crítica**, execute o protocolo completo abaixo.

---

## Fase 2 — Scan E Match Paralelo

Execute simultaneamente:

```bash

## Terminal 1 — Atualizar Registry

python agent-orchestrator/scripts/scan_registry.py

## Terminal 2 — Identificar Agentes Relevantes

python agent-orchestrator/scripts/match_skills.py "<tarefa do usuário>"
```

Se `matched >= 2`, execute orquestração:
```bash
python agent-orchestrator/scripts/orchestrate.py --skills <skill1,skill2,...> --query "<tarefa>"
```

---

## Fase 3 — Briefing Dos Agentes Especializados

Para cada agente relevante identificado no match, faça uma pergunta direcionada:

**Padrão de consulta por tipo de agente:**

- **007 (Segurança)**: "Esta tarefa tem vetores de ataque, dados expostos, ou ações irreversíveis?"
- **skill-sentinel (Qualidade)**: "Existe skill redundante? A skill que será criada/modificada segue os padrões?"
- **agent-orchestrator (Orquestração)**: "Quais skills já existem que resolvem parte desta tarefa?"
- **matematico-tao (Complexidade)**: "Qual a complexidade computacional? Há otimizações não-óbvias?"
- **context-guardian (Continuidade)**: "Existe contexto de sessões anteriores relevante para esta tarefa?"
- **advogado-especialista/criminal (Legal)**: "Há implicações legais, LGPD, ou riscos regulatórios?"
- **leiloeiro-ia (Leilões)**: "Esta tarefa envolve dados ou lógica do domínio de leilões?"

Não consulte todos os agentes cegamente — escolha os **3-5 mais relevantes** para a tarefa.

---

## Fase 4 — Estimativa De Tempo Real

Construa um breakdown de tempo honesto com base na complexidade real:

```
ESTIMATIVA DE TEMPO — [Nome da Tarefa]
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Etapa 1: [nome]          ~X min   [motivo do tempo]
Etapa 2: [nome]          ~X min   [motivo do tempo]
Etapa 3: [nome]          ~X min   [motivo do tempo]
Contingência (problemas) +X min   [buffer para imprevistos típicos]
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
TOTAL ESTIMADO:          ~X min
Confiança: Alta/Média/Baixa — [justificativa]
```

**Regras de estimativa honesta:**
- Nunca subestime para agradar — o usuário precisa saber o tempo real
- Adicione sempre 20-30% de buffer para problemas típicos
- Se a confiança for Baixa, explique por quê e o que aumentaria ela
- Diferencie "tempo de execução do agente" vs "tempo de espera do usuário"

---

## Fase 5 — Mapa De Problemas (Antecipação Proativa)

Pense em TRÊS camadas de problemas:

#### Problemas Prováveis (80%+ de chance de acontecer)
São os problemas que SEMPRE acontecem. Resolva-os ANTES de começar.

Exemplos por categoria:
- **Skills novas**: YAML inválido → valide com `python -c "import yaml; yaml.safe_load(open('SKILL.md').read())"` antes de instalar
- **APIs externas**: chave expirada, rate limit, mudança de endpoint → verifique autenticação primeiro
- **Instalações**: dependências faltando, versão incompatível → leia requirements.txt antes de executar
- **Arquivos**: path não existe, permissão negada, encoding errado → verifique antes de abrir
- **Git/Versionamento**: branch errada, conflito de merge, uncommitted changes → sempre `git status` antes

#### Problemas Possíveis (30-70% de chance)
Problemas que podem acontecer dependendo do estado atual.

Estratégia: verifique rapidamente o estado antes de assumir que está OK.

#### Problemas Improváveis mas Críticos (< 10% mas alto impacto)
Ações irreversíveis, perda de dados, exposição de credenciais.

Estratégia: backup preventivo, confirmação explícita, rollback plan.

**Template de mapa de problemas:**

```
MAPA DE PROBLEMAS — [Nome da Tarefa]
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
PROVÁVEIS (resolver antes de começar):
  ⚠ [problema] → [solução preventiva aplicada agora]
  ⚠ [problema] → [solução preventiva aplicada agora]

POSSÍVEIS (monitorar durante execução):
  ~ [problema] → [sinal de alerta] → [ação se ocorrer]

CRÍTICOS (baixa prob, alto impacto):
  🔴 [risco] → [backup/rollback plan]
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
```

---

## Fase 6 — Plano De Execução Enriquecido

Depois de coletar análises dos agentes + estimativas + mapa de problemas, produza:

```
BRIEFING PRÉ-EXECUÇÃO — [Nome da Tarefa]
════════════════════════════════════════════
CONTEXTO COLETADO:
  • [insight do agente 1]
  • [insight do agente 2]
  • [insight do agente 3]

PLANO DE EXECUÇÃO:
  1. [etapa] (~Xmin) — [por quê esta ordem]
  2. [etapa] (~Xmin) — [dependência da anterior]
  3. [etapa] (~Xmin) — [verificação de qualidade]

TEMPO TOTAL: ~Xmin | CONFIANÇA: Alta/Média/Baixa

PROBLEMAS PRÉ-RESOLVIDOS:
  ✅ [problema] → [solução aplicada]
  ✅ [problema] → [solução aplicada]

PONTOS DE VERIFICAÇÃO:
  [ ] Após etapa 1: verificar [critério de sucesso]
  [ ] Após etapa 2: verificar [critério de sucesso]
  [ ] Final: validar resultado completo

ROLLBACK PLAN (se algo der errado):
  → [como desfazer cada etapa crítica]
════════════════════════════════════════════
```

---

## Integração Com O Ecossistema

Este agente **complementa** o agent-orchestrator — não substitui:

- **agent-orchestrator**: identifica QUAIS skills usar (routing)
- **task-intelligence**: enriquece COMO usar + quando + com que riscos (briefing)

Ambos devem ser ativados juntos. O CLAUDE.md já exige o orchestrator — este agente adiciona a camada de inteligência sobre ele.

---

## Quando Não Usar O Briefing Completo

- Perguntas rápidas de 1 linha (responder diretamente é mais eficiente)
- Tarefas de leitura pura (read, grep, glob sem efeitos colaterais)
- Iterações simples dentro de uma tarefa já planejada
- Quando o usuário pede "só responde rápido" / "vibe comigo"

O objetivo não é burocracia — é inteligência a serviço da velocidade real.

---

## Referências

- `references/problem-catalog.md` — Catálogo de problemas típicos por domínio
- `references/time-patterns.md` — Padrões históricos de tempo por tipo de tarefa
- `scripts/pre_task_check.py` — Script de verificação automatizada pré-tarefa

---

## Exemplo De Briefing Completo

**Tarefa do usuário:** "Crie uma skill para integração com Stripe"

```
BRIEFING PRÉ-EXECUÇÃO — Skill: stripe-integration
════════════════════════════════════════════════════

CONTEXTO COLETADO (3 agentes consultados):
  • 007: CRÍTICO — API keys do Stripe NÃO devem ir para SKILL.md ou git.
    Usar variáveis de ambiente (.env). Webhooks precisam validação HMAC-SHA256.
  • skill-sentinel: whatsapp-cloud-api já implementa padrão HMAC-SHA256 para webhooks
    — reusar esse padrão. Skill deve seguir estrutura: config.py + client.py + SKILL.md.
  • agent-orchestrator: 3 skills similares (whatsapp, telegram, instagram) como referência
    de arquitetura. Nenhuma conflita com Stripe.

PLANO DE EXECUÇÃO:
  1. Criar estrutura de diretórios (~2min) — base para os demais arquivos
  2. Escrever SKILL.md com workflow (~5min) — define comportamento do agente
  3. Criar config.py com variáveis de ambiente (~3min) — sem hardcode de keys
  4. Criar stripe_client.py com autenticação (~10min) — métodos principais
  5. Criar webhook_handler.py com HMAC-SHA256 (~5min) — reusar padrão whatsapp
  6. Instalar via skill-installer (~2min) — validação + registro
  7. Gerar ZIP (~1min) — para backup/upload manual

TEMPO TOTAL: ~28min | CONFIANÇA: Alta
(estrutura clara, dependências conhecidas, sem APIs externas incertas)

PROBLEMAS PRÉ-RESOLVIDOS:
  ✅ API key exposta → .env obrigatório, .gitignore configurado
  ✅ YAML inválido → validar antes de instalar
  ✅ Webhook sem autenticação → HMAC-SHA256 incluído no plano

PONTOS DE VERIFICAÇÃO:
  [ ] Após SKILL.md: yaml.safe_load não levanta exceção
  [ ] Após config.py: sem strings hardcoded de credenciais
  [ ] Final: skill-installer valida os 10 checks

ROLLBACK PLAN:
  → Se skill-installer falhar: pasta em /tmp/stripe-skill-backup/
  → Se ZIP corrompido: reconstruir com build_ecosystem.py
════════════════════════════════════════════════════
```

## Best Practices

- Provide clear, specific context about your project and requirements
- Review all suggestions before applying them to production code
- Combine with other complementary skills for comprehensive analysis

## Common Pitfalls

- Using this skill for tasks outside its domain expertise
- Applying recommendations without understanding your specific context
- Not providing enough project context for accurate analysis

## Related Skills

- `agent-orchestrator` - Complementary skill for enhanced analysis
- `multi-advisor` - Complementary skill for enhanced analysis

## Limitations
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.