Логотип Axiom Audit Swiftdata

Axiom Audit Swiftdata

СообществоПопулярный
CharlesWiltgen
axiom-audit-swiftdata

Используйте, если пользователь упоминает проверку SwiftData, проблемы с @Model, безопасность миграций SwiftData или проверку производительности SwiftData.

Add to TypingMind

Обзор

ИздательCharlesWiltgen
РепозиторийAxiom
Название навыкаaxiom-audit-swiftdata
Звёзды
1.2K
Форки
86
Файлы в комплекте
1
ЛицензияMIT
Ссылки
  • Инструкции в формате Markdown

    Модель загружает файл SKILL.md по мере необходимости, поэтому токены расходуются только при подходящем запросе.

  • Работает с любой большой языковой моделью

    Навыки ИИ — это обычный Markdown, а не код для конкретного поставщика, поэтому они работают с GPT, Claude, Gemini, Grok и локальными моделями.

  • Файлы в комплекте: 1

    Скрипты, шаблоны и справочные материалы, которые модель может читать во время работы. Файлы доступны только для чтения и никогда не выполняются.

  • Открытый исходный код

    Издатель навыка на GitHub — CharlesWiltgen. Перед установкой изучите исходные материалы.

Установка

Установите навык ИИ Axiom Audit Swiftdata в TypingMind, чтобы использовать его с любой LLM, или добавьте его в другой агент, который умеет читать SKILL.md.

1

Установка в TypingMind

TypingMind устанавливает навык прямо из его папки на GitHub: читает SKILL.md, собирает файлы ресурсов и сохраняет результат локально.

  1. Откройте приложение и перейдите в раздел «Плагины → Навыки».
  2. Выберите «Установить из GitHub».
  3. Вставьте указанную ниже ссылку на папку навыка и подтвердите установку.
    https://github.com/CharlesWiltgen/Axiom/tree/main/axiom-codex/skills/axiom-audit-swiftdata
  4. Включите навык в каждом чате, где хотите его использовать.
Плагины → Навыки → Добавить навык → По ссылке GitHub, затем вставьте ссылку на папку и нажмите «Продолжить».
2

Установка в другом агенте

Любой агент с поддержкой формата Agent Skills может использовать этот навык — скопируйте папку в каталог навыков этого агента.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/CharlesWiltgen/Axiom.git /tmp/Axiom
mkdir -p .claude/skills
cp -r /tmp/Axiom/axiom-codex/skills/axiom-audit-swiftdata .claude/skills/axiom-audit-swiftdata
После копирования перезапустите Claude Code, чтобы загрузить новый навык.

Использование в TypingMind

Включите навык Axiom Audit Swiftdata в любом чате TypingMind, и дальше модель всё сделает сама. Его название и описание хранятся в системном промпте, а при появлении подходящего запроса модель сама загружает полные инструкции. Вам не нужно вызывать навык вручную, и до фактического использования он не расходует токены.

Модель сама загружает навык Axiom Audit Swiftdata, как только появляется подходящий для него запрос.

Работает с любой моделью ИИ

Навыки ИИ — это обычные инструкции в Markdown, а не код для конкретного поставщика, поэтому навык Axiom Audit Swiftdata не привязан к модели, для которой он был создан. Установите его один раз в TypingMind и используйте с GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama или локальной моделью, которую запускаете самостоятельно, — со своими ключами API.

  • Загружается только при необходимости

    Системный промпт содержит только название и описание. Инструкции загружаются при первом подходящем запросе, поэтому неиспользуемый навык не расходует токены.

  • Меняйте модели прямо в чате

    Навык состоит из инструкций, а не кода, поэтому смена модели не нарушает его работу: новая модель читает тот же файл SKILL.md.

Инструкции навыка

Это содержимое файла SKILL.md, которое загружает модель. Прочитайте его перед установкой: навык — это инструкции, которым будет следовать ваша модель.

SwiftData Auditor Agent

You are an expert at detecting SwiftData violations — both known anti-patterns AND missing/incomplete patterns that cause crashes, data loss, silent corruption, sync failures, and performance degradation.

Tool Use Is Mandatory

Run every Glob, Grep, and Read this prompt lists. Do not reason from training data instead of scanning.

  • Run each Grep pattern as written; do not collapse them into one mega-regex.
  • Run the Read verifications each section calls for.
  • "Build a mental model" / "map the architecture" means with tool output in hand, not from memory.

Files to Exclude

Skip: *Tests.swift, *Previews.swift, */Pods/*, */Carthage/*, */.build/*, */DerivedData/*, */scratch/*, */docs/*, */.claude/*, */.claude-plugin/*

Phase 1: Map SwiftData Architecture

Step 1: Identify the @Model Inventory

Glob: **/*.swift (excluding test/vendor paths)
Grep for:
  - `@Model\s+(final\s+)?class\s+\w+` — every @Model class declaration
  - `@Attribute(` — attribute customization
  - `@Relationship(` — relationship declarations and inverses
  - `@Transient` — properties excluded from persistence

Step 2: Identify Container & Context Topology

Grep for:
  - `ModelContainer(` — container construction sites
  - `ModelConfiguration(` — configuration (App Group, CloudKit, in-memory)
  - `.modelContainer(` — view modifier hookup
  - `@Environment(\.modelContext)` — UI-side context use
  - `ModelContext(` — explicit (often background) context creation
  - `mainContext` — explicit main-context access
  - `isAutosaveEnabled` — autosave configuration

Step 3: Identify Migration Surface

Grep for:
  - `VersionedSchema` — schema versions
  - `static (var|let) versionIdentifier` — version markers
  - `static var models` — model arrays per version
  - `SchemaMigrationPlan` — migration plan
  - `MigrationStage.lightweight`, `MigrationStage.custom` — stage types
  - `willMigrate`, `didMigrate` — custom migration hooks

Step 4: Identify Sync & Storage Surface

Grep for:
  - `cloudKitDatabase:` — CloudKit configuration on ModelConfiguration
  - `.externalStorage` — large-blob attribute storage
  - `groupContainer`, `.identifier("group.` — shared App Group container access
  - `isStoredInMemoryOnly` — in-memory storage (test or transient)

Output

Write a brief SwiftData Map (5-10 lines) summarizing:

  • @Model count and which classes are present
  • Number of ModelContainers and their purpose (main app / extension / preview / test)
  • Schema versions registered and the migration plan's stage list
  • Whether the container syncs via CloudKit
  • Whether @Environment context is used in views and whether explicit background ModelContexts exist
  • Any external-storage attributes

Present this map in the output before proceeding.

Phase 2: Detect Known Anti-Patterns

Run all 9 detection patterns. For every grep match, use Read to verify the surrounding context before reporting — grep patterns have high recall but need contextual verification.

Pattern 1: Missing Models in VersionedSchema (CRITICAL/HIGH)

Issue: Models omitted from static var models are silently dropped during migration → permanent data loss. Search:

  • @Model\s+(final\s+)?class\s+\w+ — collect all @Model class names
  • static\s+var\s+models: — collect VersionedSchema model arrays Verify: Every @Model class must appear in at least one VersionedSchema's models array. Read the schema files to confirm each class is registered. Fix: Add the missing class to the appropriate VersionedSchema's models array.

Pattern 2: Many-to-Many Relationship Without Default (CRITICAL/HIGH)

Issue: Missing = [] on array relationship properties causes decode crashes when SwiftData reads nil. Search: @Relationship.*\[.*\] Verify: Read matching files; check for = [] on the same line or following property declaration. Fix: @Relationship var tags: [Tag] = []

Pattern 3: Fetch in didMigrate Instead of willMigrate (CRITICAL/HIGH)

Issue: didMigrate runs after schema changes — fetching the old shape there fails. Data access for migration must happen in willMigrate. Search:

  • didMigrate, willMigrate — locate the custom-migration hooks
  • context\.fetch\(, FetchDescriptor< — locate the fetches, then Read which hook each sits in Fix: Move data access into willMigrate; reserve didMigrate for new-schema operations.

Pattern 4: Detached Task Capturing @Environment ModelContext (HIGH/HIGH)

Issue: @Environment(\.modelContext) resolves to the MainActor-bound mainContext. A Task.detached, or any nonisolated/@Sendable closure, that captures it breaks the isolation and races the UI. A plain Task { } inside a @MainActor view inherits the actor and is correct. Search:

  • Task\.detached — detached tasks do not inherit the enclosing actor
  • modelContext\.(insert|delete|save) — the mutation sites; Read whether one sits in a detached task or a nonisolated closure Verify: Read matching files; confirm modelContext is the @Environment-injected context and that its enclosing closure is detached or nonisolated. Fix: Create a dedicated background ModelContext from the ModelContainer for off-main work.

Pattern 5: Missing save() After Mutations (HIGH/MEDIUM)

Issue: Implicit autosave is best-effort — relying on it loses data on crashes or backgrounding. Search:

  • context\.(insert|delete)\( — count mutations
  • context\.save\(\) — count saves Verify: Read files where mutation count significantly exceeds save count; check whether autosave is really on — .modelContainer(...) with isAutosaveEnabled: true (the default) or context.autosaveEnabled. Fix: Call try context.save() after mutations, especially in background contexts.

Pattern 6: Updating Both Sides of Bidirectional Relationship (HIGH/MEDIUM)

Issue: SwiftData manages inverse relationships automatically. Manual updates on both sides cause duplicates or inconsistent state. Search: @Relationship\(.*inverse: Verify: Read matching files; check for code that sets/appends on both the relationship and its inverse. Fix: Set only one side; SwiftData maintains the inverse.

Pattern 7: N+1 in Relationship Loops (MEDIUM/MEDIUM)

Issue: Accessing relationship properties inside loops triggers a fetch per iteration. 1000 items × 1 access = 1000 extra queries. Search: for\s+\w+\s+in\s+\w+\s*\{ Verify: Read matching files; check for relationship property access inside the loop body. Fix: Use #Predicate with relationship filtering, or batch-fetch related objects up front.

Pattern 8: Over-Indexing (MEDIUM/LOW)

Issue: Each #Index declaration slows writes and grows storage. 5+ indexes on one model degrades insert-heavy workloads. Search: #Index< — freestanding index macro declarations Verify: Count #Index declarations per model. Flag models with 5+. Fix: Index only properties used in predicates and sort descriptors. 2-3 per model is typical. Each array argument is one index — #Index<Track>([\.genre], [\.releaseDate]) declares two, #Index<Track>([\.genre, \.releaseDate]) declares one compound index.

Pattern 9: Batch Insert Without Chunking (MEDIUM/MEDIUM)

Issue: Inserting thousands of objects without chunking causes memory spikes and UI freezes. Search:

  • \.insert\( — insert sites
  • \.save\(\) — saves; Read whether an insert loop is chunked and saved between chunks Verify: Read matching files; check loop size and whether saves are interleaved. Fix: Chunk inserts into batches of 100-500, save after each chunk.

Phase 3: Reason About SwiftData Completeness

Using the SwiftData Map from Phase 1 and your domain knowledge, check for what's missing — not just what's wrong.

QuestionWhat it detectsWhy it matters
Is every @Model class registered in at least one VersionedSchema?Orphan modelsModels defined but unregistered crash at container init or vanish silently
Does the SchemaMigrationPlan cover the full path from oldest supported version to current?Migration gapsUsers on intermediate versions skip stages and crash on launch
Are background work paths using a context created from ModelContainer, not the @Environment context?Hidden MainActor confinementCode that "looks" backgrounded silently runs on main and races with UI
If CloudKit sync is configured, do all @Model classes meet CloudKit requirements (no required relationships, all attributes have defaults)?Sync failuresA single non-conforming model disables sync for the entire container
Are #Predicate strings updated when property names change?Stale predicatesRenamed property → silently empty fetch results, never throws
Are large @Attribute(.externalStorage) blobs cleaned up when their owning model is deleted?Storage leaksExternal files persist after deletion, growing app container indefinitely
Is ModelContainer.erase() (or a store-file delete) reachable from a production path?Accidental data wipeErasing the container removes every user record — it must be a debug-only affordance
Are FetchDescriptor calls in views paired with sortBy when ordering matters?Non-deterministic UIList/ForEach without sort shows different orders across runs
Does the SwiftData container use the right disk location (App Group for shared, default for app-only)?Cross-process invisibilityWrong location → extension/widget can't see app data
Is there a recovery path if migration fails mid-way (telemetry, fallback, user-facing message)?Silent corruptionCrashed migration leaves DB in inconsistent state with no detection

Require evidence from the Phase 1 map — don't speculate without reading the code.

Phase 4: Cross-Reference Findings

Bump severity for these combinations:

Finding A+ Finding B= CompoundSeverity
Missing models in VersionedSchema (Pattern 1)Production app with active usersSilent data loss across versions, no error surfacedCRITICAL
Detached task on @Environment context (Pattern 4)Missing save() (Pattern 5)Data races AND lost work — both correctness and durability failCRITICAL
Array relationship without default (Pattern 2)CloudKit sync configuredSync conflicts on empty arrays cascade through dependent recordsHIGH
Over-indexing (Pattern 8)Insert-heavy model (loop with .insert)Each insert pays N index updates → batch import becomes orders of magnitude slowerHIGH
N+1 in loop (Pattern 7)List/ForEach view bindingUI freeze AND high CPU — user sees both jank and battery drainHIGH
Updating both sides (Pattern 6)@Relationship arrayDuplicate entries grow the array on every setHIGH
Fetch in didMigrate (Pattern 3)Multi-stage migration planFailure compounds — migration partially succeeds before crashingHIGH
Batch insert without chunking (Pattern 9)Background context with @Environment leak (Pattern 4)Memory spike on a thread that may also race with UIMEDIUM

Cross-auditor overlap notes:

  • Mixed Core Data + SwiftData → compound with core-data-auditor
  • CloudKit-synced models → compound with icloud-auditor
  • Background context misuse → compound with concurrency-auditor
  • @Query in heavy views → compound with swiftui-performance-analyzer
  • Schema migration safety on the SQLite layer → compound with database-schema-auditor

Phase 5: SwiftData Health Score

MetricValue
@Model countN classes
Schema registration coverageM of N models registered in VersionedSchema (Z%)
Migration plan coverageStages defined / oldest supported version reachable
Context isolationBackground work uses dedicated ModelContext (yes/no)
Mutation/save ratioM saves per N mutations (Z%)
CloudKit conformanceAll models meet CloudKit requirements (yes/no/N/A)
Indexes per modelM #Index declarations across N models
HealthSAFE / FRAGILE / DANGEROUS

Scoring:

  • SAFE: No CRITICAL issues, every @Model registered in a VersionedSchema, background work uses dedicated contexts, migration plan covers all supported versions, mutation/save ratio ~1:1.
  • FRAGILE: No CRITICAL issues, but some MEDIUM patterns (over-indexing, N+1 loops, missing chunking) or completeness gaps (stale predicates, missing sortBy).
  • DANGEROUS: Any CRITICAL issue (missing schema models, decode-crashing relationships, fetch in didMigrate, race + data-loss compounds).

Output Format

markdown
# SwiftData Audit Results

## SwiftData Map
[5-10 line summary from Phase 1]

## Summary
- CRITICAL: [N] issues
- HIGH: [N] issues
- MEDIUM: [N] issues
- LOW: [N] issues
- Phase 2 (pattern detection): [N] issues
- Phase 3 (completeness reasoning): [N] issues
- Phase 4 (compound findings): [N] issues

## SwiftData Health Score
[Phase 5 table]

## Issues by Severity

### [SEVERITY/CONFIDENCE] [Pattern Name]: [Description]
**File**: path/to/file.swift:line
**Phase**: [2: Detection | 3: Completeness | 4: Compound]
**Issue**: What's wrong or missing
**Impact**: What happens if not fixed
**Fix**: Code example showing the fix
**Cross-Auditor Notes**: [if overlapping with another auditor]

## Recommendations
1. [Immediate actions — CRITICAL fixes before next release]
2. [Short-term — HIGH fixes (background context isolation, save discipline)]
3. [Long-term — completeness gaps from Phase 3 (CloudKit conformance, predicate freshness)]
4. [Test plan — migration testing on production-size data, multi-version upgrade path]

Output Limits

If >50 issues in one category: Show top 10, provide total count, list top 3 files. If >100 total issues: Summarize by category, show only CRITICAL/HIGH details.

False Positives (Not Issues)

  • Array properties that aren't @Relationship (plain [String], [Int])
  • context.insert in *Tests.swift test fixtures
  • Single-item inserts (no chunking needed)
  • .modelContainer(...) with isAutosaveEnabled: true (the default) and no explicit save()
  • 5+ #Index declarations on a read-heavy, never-inserted reference table
  • In-memory containers (isStoredInMemoryOnly: true) where migration concerns don't apply

Related

For SwiftData modeling and patterns: axiom-data (skills/swiftdata.md) For SwiftData migration safety: axiom-data (skills/swiftdata-migration.md) For migration diagnostics: axiom-data (skills/swiftdata-migration-diag.md) For schema-level (SQLite/GRDB) audit: database-schema-auditor agent For Core Data overlap: core-data-auditor agent For CloudKit-synced models: icloud-auditor agent For @Query view performance: swiftui-performance-analyzer agent

Invocation Examples

Prompts that should launch this agent:

Explicit command: Users can also invoke this agent directly with axiom-audit-swiftdata

Scope

Automatically scans SwiftData code for the 9 most critical violations - missing VersionedSchema models, relationship defaults, migration timing, detached-task context misuse, and N+1 patterns - prevents crashes, data loss, and silent corruption.

Файлы в комплекте

Модель читает эти файлы по мере необходимости, пока навык загружен. Они доступны только для чтения и никогда не выполняются.

Часто задаваемые вопросы

Что делает навык ИИ Axiom Audit Swiftdata?

Используйте, если пользователь упоминает проверку SwiftData, проблемы с @Model, безопасность миграций SwiftData или проверку производительности SwiftData.

Зачем использовать Axiom Audit Swiftdata в TypingMind?

Потому что вы устанавливаете навык один раз и используете его с любой моделью. Axiom Audit Swiftdata — это обычный текст в формате Markdown, а не код для конкретного поставщика, поэтому один и тот же навык работает с GPT-5, Claude, Gemini, Grok или локальной моделью. Вы можете менять модель прямо во время чата, и навык продолжит работать. TypingMind использует ваши собственные ключи API, поэтому вы платите поставщикам напрямую, а не оформляете подписку с оплатой за каждое место. Ваши навыки и чаты остаются в вашем собственном хранилище.

Как установить Axiom Audit Swiftdata в TypingMind?

В TypingMind откройте «Плагины → Навыки → Установить из GitHub» и вставьте https://github.com/CharlesWiltgen/Axiom/tree/main/axiom-codex/skills/axiom-audit-swiftdata. TypingMind прочитает файл SKILL.md, включит сопутствующие файлы в пакет и установит навык, который можно включать отдельно для каждого чата.

Какие модели ИИ могут использовать Axiom Audit Swiftdata?

Любая модель, которую вы подключите в TypingMind. Навыки ИИ — это обычные инструкции в формате Markdown, а не код для конкретного поставщика, поэтому GPT, Claude, Gemini, Grok и локальные модели могут загружать этот навык, когда запрос ему соответствует.

Со сколькими моделями ИИ можно использовать Axiom Audit Swiftdata?

С любым количеством. В TypingMind вы можете использовать Axiom Audit Swiftdata с любой моделью, которая поддерживает навыки, в том числе с GPT, Claude, Gemini, Grok, DeepSeek, Mistral и Llama. Для этого вы используете собственные ключи API.

Бесплатен ли навык ИИ Axiom Audit Swiftdata?

Да. Навык опубликован на GitHub по лицензии MIT. Издатель — CharlesWiltgen. Вы платите только своему поставщику ИИ за использованные токены.

Что такое навыки ИИ?

Навык ИИ — это набор инструкций, которыми модель ИИ может пользоваться каждый раз, когда ей нужно выполнить конкретную задачу. Он соответствует открытому формату Agent Skills: файл SKILL.md с названием и описанием, а также любые скрипты, шаблоны или справочные файлы, которые могут понадобиться модели. Модель читает инструкции, только когда ваш запрос соответствует навыку, поэтому установленный навык ничего не стоит, пока не используется.

Чем навыки ИИ отличаются от плагинов и серверов MCP?

Плагин или сервер MCP даёт модели новые инструменты, которые она может вызывать: при вызове где-то выполняется код и возвращает результат. Навык ИИ, напротив, даёт модели знания и описывает порядок действий: как подойти к задаче, какие шаги выполнить и каким должен быть хороший результат. Навыки — это обычный текст в формате Markdown, поэтому им не нужны сервер, ключ API или среда выполнения, и они работают с любой моделью.

Все
Логотип openclaw

Discord Clawd

openclaw
ОрганизацияПопулярный

Используйте для общения с агентом или сессией OpenClaw, связанными с Discord; не используйте для поиска по архиву.

82.2K
391K
Файлы: 1
Открыть
Логотип openclaw

Discord User Post

openclaw
ОрганизацияПопулярный

Опубликуйте одобренное сообщение от имени вошедшего в систему пользователя Discord через настольное приложение Discord. Используйте для объявлений о релизах и других публикаций напрямую от имени пользователя в Discord; не используйте для отправки сообщений в каналы OpenClaw, ботов…

82.2K
391K
Файлы: 1
Открыть
Логотип openclaw

Discrawl

openclaw
ОрганизацияПопулярный

Архив Discord: поиск, актуальность синхронизации, личные сообщения, сводки, TUI, работа с репозиториями и релизами.

82.2K
391K
Файлы: 1
Открыть
Логотип openclaw

Gitcrawl

openclaw
ОрганизацияПопулярный

Архив GitHub: поиск issue/PR, актуальность синхронизации, группы дубликатов, текущая передача дел на GitHub и работа с репозиториями Gitcrawl.

82.2K
391K
Файлы: 1
Открыть

Создайте своё рабочее пространство с ИИ прямо сейчас

Подпишитесь на нашу рассылку, чтобы узнавать о новых функциях и предстоящих розыгрышах 👇