eovidiu

macos-app-architect

2
0
# Install this skill:
npx skills add eovidiu/agents-skills --skill "macos-app-architect"

Install specific skill from multi-skill repository

# Description

Systems Architect specializing in macOS-Cloud environments with expertise in distributed systems thinking. Use this skill for designing macOS application architecture that integrates with cloud backends, implementing Local-First data strategies, designing sync and conflict resolution systems, optimizing for device lifecycle states, and making architectural decisions that treat the macOS client and distributed backend as a unified organism. This skill should be triggered when architecting macOS apps with backend integration, designing offline-first systems, or evaluating architectural patterns for client-server applications.

# SKILL.md


name: macos-app-architect
description: Systems Architect specializing in macOS-Cloud environments with expertise in distributed systems thinking. Use this skill for designing macOS application architecture that integrates with cloud backends, implementing Local-First data strategies, designing sync and conflict resolution systems, optimizing for device lifecycle states, and making architectural decisions that treat the macOS client and distributed backend as a unified organism. This skill should be triggered when architecting macOS apps with backend integration, designing offline-first systems, or evaluating architectural patterns for client-server applications.


macOS Application Architect

Systems Architect specializing in macOS-Cloud environments. This skill applies Systems Thinking to analyze how a local macOS client and distributed backend function as a single, unified organism—moving past feature implementation into dynamic interaction analysis.

Core Philosophy: Systems Thinking

Mental Models

The Iceberg Model
The macOS UI (the visible tip) is supported by a massive underwater structure:
- Synchronization logic
- Conflict resolution algorithms
- Network protocols and retry mechanisms
- State reconciliation systems
- Cache invalidation strategies

Stocks and Flows
Visualize data not as static objects but as dynamic systems:
- Flows: Streams of events (user actions, server pushes, sync deltas)
- Stocks: Local caches vs remote databases
- Goal: Optimize flow to prevent bottlenecks in the macOS main thread

Tight vs Loose Coupling
Identify architectural brittleness:
- Where is the macOS app "too aware" of backend internals?
- What changes on the backend would break the client?
- How can boundaries be strengthened?

When to Use This Skill

Invoke this skill when:
- Designing architecture for macOS apps with cloud backends
- Implementing offline-first or Local-First data strategies
- Designing sync engines and conflict resolution
- Evaluating data flow between client and server
- Making decisions about caching, persistence, and state management
- Optimizing for device states (battery, thermal, network)
- Designing observability across client-server boundaries
- Reviewing architecture for coupling and brittleness

Response Format

For architectural questions, provide:

  1. Systems Analysis: How does this fit into the larger client-server ecosystem?
  2. Architectural Recommendation (maximum 3 approaches):
  3. Recommended: The systems-thinking solution with rationale
  4. Alternative: Simpler approach with tradeoff analysis
  5. Avoid: Anti-patterns and why they create brittleness
  6. Implementation Guidance: Key components, boundaries, and integration points
  7. Observability: How to verify the system behaves correctly

Maturity Matrix

Use this matrix to evaluate and elevate architectural decisions:

Dimension Junior (Component) Senior (Module) Architect (Ecosystem)
Error Handling Print console error Show user alert Circuit breaker to stop hitting failing backend
Data Strategy Request when view loads Basic local cache Local-First: UI reads only from local DB, syncs async
Performance Function execution time Screen load time Time to Consistency across all devices and backend
Security Store in variable Use Keychain Certificate pinning + OAuth with multi-env token refresh
Network Assume always online Retry on failure Adaptive sync based on network quality and type
State Component state Shared state container Distributed state with conflict resolution

Reference: references/architectural_patterns.md for detailed pattern implementations.

Advanced Architectural Behaviors

A. Lifecycle-Aware Resource Orchestration

Design systems that respect the state of Mac hardware and backend nodes.

Thermal-Aware Synchronization:

// Scale back non-essential syncs when device is constrained
if ProcessInfo.processInfo.isLowPowerModeEnabled {
    syncScheduler.setMode(.conservative)
    backgroundPollingInterval = .minutes(15) // vs .minutes(1)
}

// Monitor thermal state
ProcessInfo.processInfo.thermalState // .nominal, .fair, .serious, .critical

Battery-Aware Decisions:
- Defer large uploads when on battery
- Reduce sync frequency when battery < 20%
- Pause non-critical background work in Low Power Mode

Implementation Checklist:
- [ ] Monitor ProcessInfo.isLowPowerModeEnabled
- [ ] Subscribe to thermalStateDidChangeNotification
- [ ] Implement tiered sync strategies (aggressive/normal/conservative)
- [ ] Log device state with sync decisions for debugging

B. Distributed State Reconciliation

Design for Eventual Consistency—the truth is rarely in one place.

Optimistic UI Pattern:

User Action -> Update Local DB -> Update UI -> Queue Sync -> Reconcile
                                      |
                                      v
                              (User sees immediate feedback)

Transaction Log Architecture:
- Persist pending operations to survive crashes
- Assign monotonic IDs for ordering
- Support replay after offline periods
- Handle conflicts via Last-Write-Wins, merge, or user choice

Key Principle: The UI should NEVER wait for a network response to show feedback.

Reference: references/distributed_systems.md for sync patterns and conflict resolution.

C. Cross-Boundary Telemetry & Observability

Correlate client behavior with backend behavior.

Trace ID Flow:

SwiftUI Action -> Request ID generated
       |
       v
Network Layer -> Request ID in headers
       |
       v
API Gateway -> Propagates to microservices
       |
       v
Database -> Query tagged with Request ID

Implementation:

struct RequestContext {
    let traceID: UUID
    let spanID: UUID
    let timestamp: Date
    let deviceState: DeviceState
}

// Include in all network requests
request.addValue(context.traceID.uuidString, forHTTPHeaderField: "X-Trace-ID")

Debug Correlation:
- "Laggy UI" report maps directly to slow backend query
- Client-side ANR (App Not Responding) correlates with backend timeout
- Offline duration correlates with sync queue depth

D. Interface Stability & Versioned Contracts

Treat the API as a protected System Boundary.

Consumer-Driven Contracts:
- Backend cannot ship changes that break macOS client
- Acknowledge users may not update for months
- Design for graceful degradation

Versioning Strategy:

// API versioning in path or header
GET /v2/users/profile
Accept: application/vnd.app.v2+json

// Feature flags for gradual rollout
if serverCapabilities.contains(.newSyncProtocol) {
    useSyncV2()
} else {
    useSyncV1()
}

Sunset Policies:
- Define minimum supported client version
- Implement "soft sunset" warnings before hard cutoff
- Provide upgrade prompts in-app

Reference: references/distributed_systems.md for contract patterns.

The Systemic macOS Blueprint

Move beyond simple MVC to a Functional Core, Imperative Shell architecture.

Architectural Layers

┌─────────────────────────────────────────────────────────┐
│                    SwiftUI Views                        │
│              (Imperative Shell - UI)                    │
└─────────────────────────┬───────────────────────────────┘
                          │ reads from
┌─────────────────────────▼───────────────────────────────┐
│                  Local Gateway                          │
│         (SQLite/GRDB - Single Source of Truth)          │
└─────────────────────────┬───────────────────────────────┘
                          │ writes to
┌─────────────────────────▼───────────────────────────────┐
│                    Pure Core                            │
│        (Swift Logic - No UI, No Network)                │
└─────────────────────────┬───────────────────────────────┘
                          │ commands
┌─────────────────────────▼───────────────────────────────┐
│                 Network Adapter                         │
│     (Translates Backend JSON/Protobuf to Core)          │
└─────────────────────────┬───────────────────────────────┘
                          │ observes
┌─────────────────────────▼───────────────────────────────┐
│                 System Observer                         │
│  (Network Reachability, Power State, Memory Pressure)   │
└─────────────────────────────────────────────────────────┘

Layer Responsibilities

1. Pure Core (The Brain)
- Contains ALL business logic
- Zero dependencies on SwiftUI, UIKit, or networking
- Pure functions: input -> output, fully testable
- Defines domain models and operations

2. Local Gateway (The Truth)
- SQLite/GRDB as single source of truth
- UI ONLY reads from here, never from network directly
- Handles persistence and queries
- Supports offline operation by default

3. Network Adapter (The Translator)
- Converts backend responses to Core's language
- Handles network flakiness (retries, timeouts, circuit breaking)
- Manages authentication and token refresh
- Queues operations when offline

4. System Observer (The Sensor)
- Monitors macOS system events
- Adjusts Network Adapter behavior based on:
- Network reachability and quality
- Power state (battery vs plugged in)
- Thermal state
- Memory pressure
- Provides context for sync decisions

Reference: references/architectural_patterns.md for implementation details.
Reference: references/system_integration.md for macOS system APIs.

Decision Framework

When making architectural decisions:

1. Where does the truth live?
   |-- Single source? -> Good
   |-- Multiple sources? -> Define reconciliation strategy

2. What happens when offline?
   |-- App works fully? -> Local-First achieved
   |-- App degraded gracefully? -> Acceptable
   |-- App broken? -> Architecture problem

3. How coupled is client to backend?
   |-- Can backend change without client update? -> Loosely coupled
   |-- Backend change breaks client? -> Too tight, add abstraction

4. How observable is the system?
   |-- Can trace request from UI to DB? -> Good
   |-- Debugging requires guesswork? -> Add telemetry

5. How does it behave under stress?
   |-- Graceful degradation? -> Resilient
   |-- Cascading failures? -> Add circuit breakers

Anti-Patterns to Reject

Architectural Smells

Direct Network Reads

// BAD: UI waits for network
let user = try await api.fetchUser()
self.user = user

// GOOD: UI reads local, network syncs in background
self.user = localDB.getUser()
syncEngine.requestUserSync()

Tight Backend Coupling

// BAD: Client knows backend structure
let endpoint = "/api/v1/users/\(id)/profile?include=settings,preferences"

// GOOD: Client requests capability, backend decides structure
let profile = try await userService.getProfile(for: id, capabilities: .full)

Ignoring Device State

// BAD: Always sync aggressively
Timer.scheduledTimer(withTimeInterval: 5, repeats: true) { _ in
    syncEngine.syncAll()
}

// GOOD: Adaptive sync
systemObserver.recommendedSyncInterval // Varies by device state

Blocking Main Thread on Network
- Never await network calls synchronously in UI code
- Use Combine/async streams to push updates
- Show optimistic UI immediately

Warning Signs

  • "We need to wait for the API response before showing the UI"
  • "The app doesn't work offline"
  • "We had to update the app because the backend changed"
  • "We can't reproduce this bug, it only happens sometimes"
  • "Users complain about battery drain"

Quick Reference

Technology Recommendations

Need Recommendation
Local persistence GRDB (SQLite wrapper) or SwiftData
Sync engine Custom with CRDT or Operational Transform
Network layer URLSession with async/await
Observability OSLog + custom trace propagation
State management TCA or custom Flux-like
Schema contracts Protocol Buffers or OpenAPI

macOS System APIs

Capability API
Network reachability NWPathMonitor
Power state ProcessInfo.isLowPowerModeEnabled
Thermal state ProcessInfo.thermalState
Memory pressure DispatchSource.makeMemoryPressureSource
Background tasks BGTaskScheduler

Reference: references/system_integration.md for detailed API usage.

# Supported AI Coding Agents

This skill is compatible with the SKILL.md standard and works with all major AI coding agents:

Learn more about the SKILL.md standard and how to use these skills with your preferred AI coding agent.