Claude on Rails Tooling System - Persistent memory for Claude Code

version
2.4.1
GitHub stars
107

Install

/plugin install matrix@matrix-marketplace

Run it inside Claude Code after adding the marketplace with /plugin marketplace add ojowwalker77/Claude-Matrix.

Contents

Discovered from source

Skills 9

Matrix Deep Research

Perform comprehensive research on a topic using multiple sources: web search, Context7 documentation, Matrix memory, GitHub repositories, and more.

Usage

Parse user arguments from the skill invocation (text after the trigger phrase).

Format: <query> [depth]

  • query: The research topic or question
  • depth (optional): quick | standard | exhaustive (default: standard)

Depth Levels

  • quick: Fast research using 2-3 sources, ~500 words output
  • standard: Balanced research using 4-5 sources, ~1500 words output
  • exhaustive: Deep research using 6+ sources, ~3000+ words output

Research Pipeline

Follow the 5-phase research pipeline detailed in references/research-pipeline.md:

  1. Phase 1: Query Expansion - Analyze query, generate sub-queries, identify domains
  2. Phase 2: Multi-Source Gathering - Collect from Web, Context7, Matrix, GitHub
  3. Phase 3: Content Fetching - Retrieve full content from promising URLs
  4. Phase 4: Synthesis - Deduplicate, organize, identify patterns
  5. Phase 5: Output - Generate polished markdown report

Output

Save to session directory: $CLAUDE_SESSION_DIR/matrix-research-[slug]-[timestamp].md

If $CLAUDE_SESSION_DIR is not available, fall back to current working directory.

After completing research:

  1. Display a summary of findings in the chat
  2. Report the full markdown file location
  3. Offer to elaborate on any section

Examples

/matrix:deep-research React Server Components best practices standard
/matrix:deep-research "how to implement OAuth 2.0 with PKCE" exhaustive
/matrix:deep-research TypeScript generics quick

Additional Resources

Reference Files

For detailed pipeline procedures, consult:

  • references/research-pipeline.md - Complete 5-phase research process with output format

Matrix Doctor

Run comprehensive diagnostics on the Matrix plugin and automatically fix issues when possible.

What It Does

  1. Checks Matrix Directory: Verifies ~/.claude/matrix/ exists and is writable
  2. Checks Database: Tests connection, validates schema version
  3. Checks Configuration: Validates config file, checks for missing sections
  4. Checks Hooks: Verifies hooks are installed correctly
  5. Checks Code Index: Confirms repository is indexed
  6. Checks Repo Detection: Tests fingerprinting works

Auto-Fix Capabilities

The doctor will automatically attempt to fix:

  • Missing Matrix directory (creates it)
  • Database connection issues (reinitializes)
  • Invalid/missing configuration (resets to defaults)
  • Missing code index (triggers reindex)

Usage

Call the matrix_doctor tool with:

  • autoFix: true (default) - Attempt to fix issues automatically
  • autoFix: false - Only run diagnostics without fixing

If Issues Cannot Be Fixed

If the doctor finds issues that cannot be automatically fixed:

  1. A GitHub issue template will be generated
  2. The user should be directed to open an issue at: https://github.com/ojowwalker77/Claude-Matrix/issues/new?template=bug_report.md
  3. Include the full diagnostic output in the issue

Expected Output

The tool returns a DoctorResult object containing:

  • healthy: boolean indicating overall health
  • checks: array of diagnostic results
  • environment: OS, Bun version, paths
  • suggestions: array of recommended actions
  • issueTemplate: pre-filled GitHub issue template (if issues found)

Effect-TS Expert

Expert-level guidance for Effect-TS functional programming with typed errors, dependency injection, concurrency, and production-ready patterns.

Core Concepts

The Effect Type

Effect<Success, Error, Requirements>
//     ^        ^       ^
//     |        |       └── Services/dependencies needed (Context)
//     |        └────────── Typed error channel
//     └─────────────────── Success value type

Key insight: Effects are lazy descriptions of computations. They don't execute until run.

Creating Effects

import { Effect } from "effect"

// From pure values
const success = Effect.succeed(42)
const failure = Effect.fail(new Error("oops"))

// From sync code (may throw)
const sync = Effect.sync(() => JSON.parse(data))
const trySync = Effect.try({
  try: () => JSON.parse(data),
  catch: (e) => new ParseError(e)
})

// From async code
const promise = Effect.promise(() => fetch(url))
const tryPromise = Effect.tryPromise({
  try: () => fetch(url).then(r => r.json()),
  catch: (e) => new FetchError(e)
})

// From callbacks
const callback = Effect.async<string, Error>((resume) => {
  someCallbackApi((err, result) => {
    if (err) resume(Effect.fail(err))
    else resume(Effect.succeed(result))
  })
})

Running Effects

// Development/testing
Effect.runSync(effect)           // Sync, throws on async/error
Effect.runPromise(effect)        // Returns Promise<A>
Effect.runPromiseExit(effect)    // Returns Promise<Exit<A, E>>

// Production (with runtime)
const runtime = ManagedRuntime.make(AppLayer)
await runtime.runPromise(effect)

Building Pipelines

pipe and Effect.gen

import { Effect, pipe } from "effect"

// Using pipe (point-free style)
const program = pipe(
  Effect.succeed(5),
  Effect.map(n => n * 2),
  Effect.flatMap(n => n > 5
    ? Effect.succeed(n)
    : Effect.fail(new Error("too small"))
  ),
  Effect.tap(n => Effect.log(`Result: ${n}`))
)

// Using Effect.gen (generator style - RECOMMENDED)
const program = Effect.gen(function* () {
  const n = yield* Effect.succeed(5)
  const doubled = n * 2
  if (doubled <= 5) {
    return yield* Effect.fail(new Error("too small"))
  }
  yield* Effect.log(`Result: ${doubled}`)
  return doubled
})

Recommendation: Prefer Effect.gen for readability. Use pipe for simple transformations.

Error Handling

Typed Errors vs Defects

TypeUse CaseRecovery
Typed ErrorDomain failures (validation, not found, permissions)Yes - caller can handle
DefectBugs, invariant violations, unrecoverableNo - terminates fiber
// Typed errors - tracked in type system
class NotFoundError extends Data.TaggedError("NotFoundError")<{
  readonly id: string
}> {}

class ValidationError extends Data.TaggedError("ValidationError")<{
  readonly message: string
}> {}

const findUser = (id: string): Effect.Effect<User, NotFoundError> =>
  pipe(
    db.query(id),
    Effect.flatMap(user =>
      user ? Effect.succeed(user) : Effect.fail(new NotFoundError({ id }))
    )
  )

// Defects - for bugs, not domain errors
const divide = (a: number, b: number): Effect.Effect<number> =>
  b === 0
    ? Effect.die(new Error("Division by zero - this is a bug!"))
    : Effect.succeed(a / b)

Error Recovery

// Catch all errors
Effect.catchAll(effect, (error) => Effect.succeed(fallback))

// Catch specific tagged errors
Effect.catchTag(effect, "NotFoundError", (e) =>
  Effect.succeed(defaultUser)
)

// Catch multiple tags
Effect.catchTags(effect, {
  NotFoundError: (e) => Effect.succeed(defaultUser),
  ValidationError: (e) => Effect.fail(new HttpError(400, e.message))
})

// Convert to Either (errors become Left)
Effect.either(effect)  // Effect<Either<E, A>, never, R>

// Retry on failure
Effect.retry(effect, Schedule.recurs(3))

Best Practice: Error Design

// DO: Use tagged errors with Schema
import { Schema } from "effect"

class ApiError extends Schema.TaggedError<ApiError>()("ApiError", {
  status: Schema.Number,
  message: Schema.String,
}) {}

// DON'T: Use plain Error or strings
Effect.fail(new Error("something went wrong"))  // Loses type info
Effect.fail("error")  // Not an Error type

Dependency Injection

Services with Context.Tag

import { Context, Effect, Layer } from "effect"

// 1. Define service interface
class UserRepository extends Context.Tag("UserRepository")<
  UserRepository,
  {
    readonly findById: (id: string) => Effect.Effect<User, NotFoundError>
    readonly save: (user: User) => Effect.Effect<void>
  }
>() {}

// 2. Use in effects
const getUser = (id: string) => Effect.gen(function* () {
  const repo = yield* UserRepository
  return yield* repo.findById(id)
})
// Type: Effect<User, NotFoundError, UserRepository>

// 3. Create layer implementation
const UserRepositoryLive = Layer.succeed(UserRepository, {
  findById: (id) => Effect.tryPromise(() => db.users.find(id)),
  save: (user) => Effect.tryPromise(() => db.users.save(user))
})

// 4. Provide to run
const program = getUser("123")
const runnable = Effect.provide(program, UserRepositoryLive)

Effect.Service (Simplified Pattern)

// Combines Tag + Layer in one declaration
class Logger extends Effect.Service<Logger>()("Logger", {
  // Option 1: Sync implementation
  sync: () => ({
    log: (msg: string) => console.log(msg)
  }),

  // Option 2: Effect-based with dependencies
  effect: Effect.gen(function* () {
    const config = yield* Config
    return {
      log: (msg: string) => Effect.sync(() =>
        console.log(`[${config.level}] ${msg}`)
      )
    }
  }),
  dependencies: [ConfigLive]
}) {}

// Use directly
const program = Logger.log("Hello")

// Access via Layer
Effect.provide(program, Logger.Default)

Layer Composition

// Merge independent layers
const BaseLayer = Layer.merge(ConfigLive, LoggerLive)

// Provide dependencies
const DbLayer = Layer.provide(DatabaseLive, ConfigLive)

// Full composition
const AppLayer = pipe(
  Layer.merge(ConfigLive, LoggerLive),
  Layer.provideMerge(DatabaseLive),
  Layer.provideMerge(UserRepositoryLive)
)

See references/layers.md for advanced patterns.

Concurrency

Fibers

// Fork to run concurrently
const fiber = yield* Effect.fork(longRunningTask)

// Wait for result
const result = yield* Fiber.join(fiber)

// Interrupt
yield* Fiber.interrupt(fiber)

// Race - first to complete wins
const fastest = yield* Effect.race(task1, task2)

// All - run all, collect results
const results = yield* Effect.all([task1, task2, task3])

// All with concurrency limit
const results = yield* Effect.all(tasks, { concurrency: 5 })

Synchronization Primitives

// Ref - mutable reference
const counter = yield* Ref.make(0)
yield* Ref.update(counter, n => n + 1)
const value = yield* Ref.get(counter)

// Queue - bounded producer/consumer
const queue = yield* Queue.bounded<number>(100)
yield* Queue.offer(queue, 42)
const item = yield* Queue.take(queue)

// Semaphore - limit concurrent access
const sem = yield* Effect.makeSemaphore(3)
yield* sem.withPermits(1)(expensiveOperation)

// Deferred - one-shot signal
const deferred = yield* Deferred.make<string, Error>()
yield* Deferred.succeed(deferred, "done")
const value = yield* Deferred.await(deferred)

Resource Management

Scoped Resources

// Acquire/release pattern
const file = Effect.acquireRelease(
  Effect.sync(() => fs.openSync(path, "r")),  // acquire
  (fd) => Effect.sync(() => fs.closeSync(fd))  // release
)

// Use with scoped
const program = Effect.scoped(
  Effect.gen(function* () {
    const fd = yield* file
    return yield* readFile(fd)
  })
)
// File automatically closed after scope

Finalizers

const program = Effect.gen(function* () {
  yield* Effect.addFinalizer((exit) =>
    Effect.log(`Cleanup: ${exit._tag}`)
  )
  // ... do work
})

const runnable = Effect.scoped(program)

Quick Reference

Common Operators

OperatorPurpose
Effect.mapTransform success value
Effect.flatMapChain effects (monadic bind)
Effect.tapSide effect, keep original value
Effect.andThenSequence, can be value or effect
Effect.catchAllHandle all errors
Effect.catchTagHandle specific tagged error
Effect.provideInject dependencies
Effect.retryRetry with schedule
Effect.timeoutAdd timeout
Effect.forkRun concurrently
Effect.allParallel execution

When to Use What

ScenarioUse
Transform valueEffect.map
Chain effectsEffect.flatMap or Effect.gen
Error recoveryEffect.catchTag / Effect.catchAll
Add loggingEffect.tap + Effect.log
Run in parallelEffect.all with concurrency
Limit concurrencySemaphore
Share mutable stateRef
Producer/consumerQueue
One-time signalDeferred
Cleanup resourcesEffect.acquireRelease

Reference Documents

  • references/error-handling.md - Typed errors, defects, recovery patterns
  • references/layers.md - Dependency injection, service composition
  • references/concurrency.md - Fibers, synchronization, parallelism
  • references/streams.md - Stream, Sink, Channel patterns
  • references/schema.md - Validation, encoding/decoding
  • references/testing.md - Test layers, mocking, vitest integration
  • references/config.md - Configuration management
  • references/anti-patterns.md - Common mistakes and fixes
  • references/fp-ts-migration.md - Migration from fp-ts

Usage

This skill activates automatically when working with Effect-TS files or when the user mentions Effect, functional TypeScript, or typed errors.

Explicit invocation:

/effect-ts help me refactor this to use Effect
/effect-ts create a service with dependency injection
/effect-ts fix error handling in this code

Matrix List & Export

Display or export Matrix memory contents and statistics.

List (default)

Use matrix_status to retrieve information and present it to the user.

  • No arguments: Show statistics, scope breakdown, recent solutions, top performers
  • "stats": Focus on statistics only
  • "failures": Focus on recorded failures
  • "warnings": Use matrix_warn with action "list" to show warnings
  • "solutions": Show detailed solutions list

Export

When the user says "export" or "backup":

  1. Use matrix_status to get all data
  2. Format as JSON
  3. Use Write to save to the specified path (or default to matrix-export.json)

Matrix Nuke

Comprehensive codebase hygiene analysis. Detects dead code, unused imports, orphaned files, circular dependencies, stale TODOs, unnecessary comments, overengineered dependencies, and more across 11 categories.

Tip: This skill runs in a forked context for unbiased analysis - clean slate, no conversation history bias.

Architecture

ORCHESTRATOR (parse mode, dispatch agents, aggregate report)
     |
     +-- STRUCTURAL AGENT --> dead exports, orphaned files, unused imports
     +-- CIRCULAR DEP AGENT --> import cycle detection
     +-- DEPENDENCY AGENT --> unused npm packages, overengineered deps
     +-- GENERATIVE AGENT --> comments, console.log, copy-paste, TODOs
     +-- TRIAGE AGENT --> confidence scoring, safety filtering, tiering

Usage

Parse user arguments from the skill invocation (text after the trigger phrase).

Expected format: /nuke [mode] [path]

Modes

ModeCommandBehavior
Scan/nuke or /nuke scanReport only - touch nothing (default)
This/nuke this <file>Single file analysis
Safe/nuke safeReport HIGH confidence only (>90%)
Aggressive/nuke aggressiveReport MEDIUM+ confidence (>70%)

Path Filtering

Append a path to any mode to limit scope:

  • /nuke scan src/api/ - only scan src/api/
  • /nuke this src/utils/auth.ts - single file

Examples

/nuke                        # Full scan, report only
/nuke scan                   # Same as above
/nuke this src/utils/auth.ts # Single file analysis
/nuke scan src/api/          # Scan specific directory
/nuke safe                   # High-confidence findings only
/nuke aggressive             # Medium+ confidence findings

Pipeline

Follow the orchestration detailed in references/nuke-pipeline.md:

  1. Pre-flight - Check index availability (matrix_index_status), detect entry points from package.json, parse mode
  2. Structural Analysis - Use matrix_find_dead_code for dead exports + orphaned files
  3. Circular Dep Detection - Use matrix_find_circular_deps for import cycles
  4. Dependency Analysis - Read package.json, cross-reference with actual imports via Grep
  5. Generative Analysis - AI inspection of files for comments, console.log, duplication, TODOs
  6. Triage - Apply safety rules, assign confidence scores, classify into tiers
  7. Report - Generate formatted output per references/output-format.md

Early exit for /nuke this: Only run Structural + Generative agents on that single file. Skip dependency and circular dep analysis.

Graceful degradation: If index is unavailable, fall back to Grep-based analysis. Report reduced accuracy.

What Gets Detected (11 Categories)

Structural (deterministic, via MCP tools)

  1. Dead exports - exported symbols with zero callers across the codebase
  2. Orphaned files - files that nothing imports (excluding entry points)
  3. Circular dependencies - import cycles in the dependency graph
  4. Unused npm packages - in package.json but never imported
  5. Unused imports - imports brought in but never referenced in the file

Generative (AI judgment required)

  1. Unnecessary comments - obvious/redundant comments (// increment i, // constructor)
  2. Commented-out code - dead code hiding in comments (contains {, =, function, return)
  3. Console.log leftovers - console.log and console.debug left from debugging (NOT console.error)
  4. Overengineered deps - libraries replaceable with native APIs (lodash.get -> ?., moment -> Intl)
  5. Copy-paste duplication - near-identical code blocks (5+ similar consecutive lines)
  6. Stale TODO/FIXME - ancient TODOs with no linked issues and old git blame dates

Safety Rules

See references/safety-rules.md for full details. Key rules:

  • Never flag entry points - index.ts, main.ts, bin/*, package.json main/module/exports
  • Never flag framework conventions - pages/, routes/, app/, .config., migrations/
  • Never flag dynamically imported modules - import(), require() references
  • Never flag public API surface - root barrel exports, @public JSDoc
  • Respect .nukeignore - if present, honor it like .gitignore

Additional Resources

  • references/nuke-pipeline.md - Full orchestrator pipeline
  • references/agents/structural-agent.md - Dead code detection via MCP tools
  • references/agents/generative-agent.md - AI-judged detection patterns
  • references/agents/dependency-agent.md - Package analysis and native alternatives
  • references/agents/triage-agent.md - Confidence scoring and safety filtering
  • references/safety-rules.md - Entry point detection, what NOT to flag
  • references/output-format.md - Report template

Matrix Reindex

Trigger a manual reindex of the TypeScript/JavaScript codebase.

Use the matrix_reindex MCP tool to refresh the code index.

Arguments

  • full (optional): If true, force a complete reindex ignoring incremental mode

When to Use

  • After making significant file changes outside of Claude
  • When the index seems stale or incomplete
  • After renaming or moving many files

Output

  • Files scanned, indexed, and skipped
  • Symbols and imports found
  • Duration of the indexing process

Matrix Code Review

Perform comprehensive, context-aware code review using 5-agent architecture with 95% false positive reduction.

Tip: This skill runs in a forked context for an unbiased perspective - similar to how a human reviewer would approach the code for the first time.

Architecture

ORCHESTRATOR (parses target, routes, aggregates)
     │
     ├── DETECTION AGENT → security, runtime, breaking, logic flaws, hygiene (nuke)
     ├── IMPACT AGENT → blast radius, transitive graph, test coverage
     ├── TRIAGE AGENT → tier assignment, confidence calibration, noise filter
     ├── REMEDIATION AGENT → context-aware fixes, regression checks
     └── VERIFICATION AGENT → build, test, lint validation

Usage

Parse user arguments from the skill invocation (text after the trigger phrase).

Expected format: <target> [mode]

  • target: File path, PR number, or "staged" for staged changes
  • mode (optional): default | lazy (default: from config or default)

Modes

Default Mode (Comprehensive)

Full 5-agent review pipeline with maximum index utilization:

  • Detection: Security vulns, runtime issues, breaking changes, hygiene (nuke scan)
  • Impact: Transitive blast radius (2-3 levels), service boundaries, test coverage
  • Triage: Tier classification, >80% signal ratio target
  • Remediation: Context-aware fixes matching codebase patterns
  • Verification: Run build, test, lint commands automatically

Lazy Mode (Quick)

Detection agent only:

  • Direct code inspection
  • Critical issues only (Tier 1)
  • ~2-3 comments, no blast radius

Review Pipeline

Follow the 5-agent orchestration detailed in references/review-phases.md:

  1. Orchestrator - Parse target, dispatch agents, aggregate results
  2. Detection Agent - Find security, runtime, breaking, logic issues
  3. Impact Agent - Calculate transitive blast radius, test coverage
  4. Triage Agent - Classify tiers, calibrate confidence, filter noise
  5. Remediation Agent - Generate fixes, check regression risk
  6. Verification Agent - Run build, test, lint; report results

Early exit: If Detection finds nothing critical, skip Impact/Triage depth.

Examples

/matrix:review src/utils/auth.ts          # Default mode (comprehensive)
/matrix:review staged                     # Review staged changes
/matrix:review staged lazy                # Quick review of staged changes
/matrix:review 123                        # Review PR #123
/matrix:review 123 lazy                   # Quick review of PR #123

Additional Resources

Reference Files

  • references/review-phases.md - Orchestrator + 5-agent pipeline
  • references/agents/detection.md - Detection patterns and output format
  • references/agents/impact.md - Blast radius algorithm
  • references/agents/triage.md - Tier classification and signal ratio
  • references/agents/remediation.md - Fix generation and regression checks
  • references/agents/verification.md - Build/test/lint command detection and execution

Swift & SwiftUI Expert

Expert-level guidance for Swift and SwiftUI development with modern patterns, iOS 17+/macOS 14+ best practices, and production-ready code generation.

Core Principles

When writing Swift/SwiftUI code, ALWAYS follow these principles:

1. Modern State Management (iOS 17+)

Use @Observable macro instead of ObservableObject:

// MODERN (iOS 17+)
@Observable
class UserViewModel {
    var name: String = ""
    var isLoggedIn: Bool = false
}

// View owns the model
struct ContentView: View {
    @State private var viewModel = UserViewModel()
    var body: some View {
        Text(viewModel.name)
    }
}

// Child view (read-only) - NO wrapper needed
struct ProfileView: View {
    var viewModel: UserViewModel  // Just pass it
    var body: some View {
        Text(viewModel.name)
    }
}

// Child view (needs binding)
struct EditView: View {
    @Bindable var viewModel: UserViewModel
    var body: some View {
        TextField("Name", text: $viewModel.name)
    }
}

2. Property Wrapper Decision Tree

Use CaseProperty Wrapper
Local view state (value types)@State
Two-way binding to parent state@Binding
Observable model (view owns)@State + @Observable class
Observable model (read-only child)No wrapper (just pass object)
Observable model (needs binding)@Bindable
Shared app-wide state@Environment
User defaults@AppStorage
Scene storage@SceneStorage
Focus state@FocusState

3. Architecture Patterns

For most apps: Modern MVVM with @Observable For large apps with teams: TCA (Composable Architecture) For simple views: No ViewModel needed

See references/architecture.md for detailed patterns.

Anti-Patterns to AVOID

State Management

// WRONG: @ObservedObject with initialization
@ObservedObject var viewModel = ViewModel()  // Will crash!

// RIGHT: Use @StateObject or @State
@StateObject private var viewModel = ViewModel()  // Legacy
@State private var viewModel = ViewModel()  // Modern (iOS 17+)
// WRONG: @State with reference types
@State var user: User  // Where User is a class

// RIGHT: @State only for value types
@State var userName: String
@State private var viewModel = ViewModel()  // Only with @Observable
// WRONG: Clearing data on error
func refresh() async {
    self.items = []  // Data disappears if error occurs!
    do {
        self.items = try await fetchItems()
    } catch {
        // Items now empty forever
    }
}

// RIGHT: Preserve existing data
func refresh() async {
    do {
        self.items = try await fetchItems()
    } catch {
        // Keep existing items, show error toast
    }
}

Performance

// WRONG: Heavy computation in body
var body: some View {
    let sorted = items.sorted { ... }.filter { ... }  // Runs every render!
    List(sorted) { ... }
}

// RIGHT: Memoize or compute elsewhere
var sortedItems: [Item] {
    items.sorted { ... }.filter { ... }
}  // Or use @State for expensive computations
// WRONG: Using id modifier on lazy content
LazyVStack {
    ForEach(items) { item in
        ItemView(item: item)
            .id(item.id)  // Breaks lazy loading!
    }
}

// RIGHT: Let ForEach handle identity
LazyVStack {
    ForEach(items) { item in
        ItemView(item: item)  // ForEach uses Identifiable
    }
}

Navigation

// WRONG: Using deprecated NavigationView
NavigationView {
    List { ... }
}

// RIGHT: Use NavigationStack (iOS 16+)
NavigationStack {
    List { ... }
}

Code Generation Guidelines

When generating Swift/SwiftUI code:

  1. Target iOS 17+/macOS 14+ unless user specifies otherwise
  2. Use @Observable instead of ObservableObject/@Published
  3. Use NavigationStack instead of NavigationView
  4. Use .task instead of .onAppear for async work
  5. Use Swift concurrency (async/await) instead of Combine for new code
  6. Make @State private always
  7. Prefer value types (structs, enums) over classes
  8. Use optionals correctly - never force unwrap without safety
  9. Handle errors explicitly - use do-catch, not try?
  10. Add accessibility - labels, hints, traits

Reference Documents

For detailed guidance, consult:

  • references/state-management.md - Property wrappers, @Observable, data flow
  • references/architecture.md - MVVM, TCA, Clean Architecture patterns
  • references/navigation.md - NavigationStack, programmatic navigation, deep links
  • references/performance.md - Lazy views, List optimization, render cycles
  • references/concurrency.md - async/await, actors, MainActor, Task
  • references/testing.md - Unit tests, ViewInspector, UI tests
  • references/accessibility.md - VoiceOver, Dynamic Type, accessibility modifiers
  • references/swiftdata.md - @Model, @Query, persistence patterns
  • references/anti-patterns.md - Common mistakes and how to fix them

Examples

Basic View with State

struct CounterView: View {
    @State private var count = 0

    var body: some View {
        VStack(spacing: 20) {
            Text("Count: \(count)")
                .font(.largeTitle)

            Button("Increment") {
                count += 1
            }
            .buttonStyle(.borderedProminent)
        }
        .accessibilityElement(children: .combine)
        .accessibilityLabel("Counter at \(count)")
        .accessibilityHint("Double tap the button to increment")
    }
}

ViewModel with @Observable

@Observable
class TaskListViewModel {
    var tasks: [Task] = []
    var isLoading = false
    var errorMessage: String?

    @MainActor
    func loadTasks() async {
        isLoading = true
        defer { isLoading = false }

        do {
            tasks = try await TaskService.shared.fetchTasks()
        } catch {
            errorMessage = error.localizedDescription
        }
    }
}

struct TaskListView: View {
    @State private var viewModel = TaskListViewModel()

    var body: some View {
        NavigationStack {
            Group {
                if viewModel.isLoading {
                    ProgressView()
                } else {
                    List(viewModel.tasks) { task in
                        TaskRow(task: task)
                    }
                }
            }
            .navigationTitle("Tasks")
        }
        .task {
            await viewModel.loadTasks()
        }
    }
}

Navigation with Type-Safe Routes

enum Route: Hashable {
    case detail(Item)
    case settings
    case profile(userId: String)
}

struct ContentView: View {
    @State private var path = NavigationPath()

    var body: some View {
        NavigationStack(path: $path) {
            List(items) { item in
                Button(item.name) {
                    path.append(Route.detail(item))
                }
            }
            .navigationDestination(for: Route.self) { route in
                switch route {
                case .detail(let item):
                    DetailView(item: item)
                case .settings:
                    SettingsView()
                case .profile(let userId):
                    ProfileView(userId: userId)
                }
            }
        }
    }

    // Programmatic navigation
    func navigateToSettings() {
        path.append(Route.settings)
    }

    func popToRoot() {
        path.removeLast(path.count)
    }
}

Usage

This skill activates automatically when working with Swift/SwiftUI files or when the user mentions iOS/macOS/SwiftUI development.

Explicit invocation:

/swift-swiftui help me refactor this view to use @Observable
/swift-swiftui create a settings screen with navigation
/swift-swiftui fix state management in this component

Matrix Warnings

Manage "personal grudges" - warnings for problematic files or packages.

Parse user arguments from the skill invocation (text after the trigger phrase).

Use the matrix_warn tool with the appropriate action parameter.

Actions

List warnings (default, or "list"): Use matrix_warn with action: "list" to show all warnings.

  • Optional: type: "file" or type: "package" to filter
  • Optional: repoOnly: true to show only repo-specific warnings

Add warning ("add "): Use matrix_warn with action: "add" and:

  • type: "file" or "package"
  • target: file path/pattern or package name
  • reason: why this is problematic
  • severity: "info", "warn", or "block" (default: warn)
  • repoSpecific: true if warning should only apply to current repo

Remove warning ("remove " or "rm "): Use matrix_warn with action: "remove" and either:

  • id: the warning ID to remove, or
  • type + target: to remove by type and target

Check target ("check "): Use matrix_warn with action: "check" and:

  • type: "file" or "package"
  • target: file path or package name

Examples

  • /matrix:warn - list all warnings
  • /matrix:warn add file src/legacy/*.ts "Deprecated, do not modify"
  • /matrix:warn add package moment "Use date-fns instead"
  • /matrix:warn remove moment
  • /matrix:warn check .env

MCP servers 2

Sponsors

Details

Marketplace
ojowwalker77/Claude-Matrix
Category
Community