Axiom Analyze Test Failures 标志

Axiom Analyze Test Failures

社区热门
CharlesWiltgen
axiom-analyze-test-failures

当用户提到测试不稳定、测试在本地通过但在 CI 中失败、测试中的竞态条件,或需要诊断某个特定测试失败的原因时使用。

Add to TypingMind

概览

发布者CharlesWiltgen
代码仓库Axiom
技能名称axiom-analyze-test-failures
星标数
1.2K
复刻数
86
附带文件
1
许可协议MIT
链接
  • Markdown 格式的指令

    模型按需加载 SKILL.md 文件,因此只有在请求确实与该技能匹配时才会消耗 Token。

  • 兼容任何大语言模型

    AI 技能采用纯 Markdown,而非特定提供商的代码,因此可搭配 GPT、Claude、Gemini、Grok 或本地模型使用。

  • 1 个附带文件

    模型执行任务时可读取的脚本、模板和参考资料。这些文件为只读文件,绝不会被执行。

  • 开源

    由 CharlesWiltgen 发布于 GitHub。请在安装前查看技能的源文件。

安装

在 TypingMind 中安装 Axiom Analyze Test Failures AI 技能,即可搭配任意大语言模型使用;也可以将其放入其他支持读取 SKILL.md 的智能体中。

1

安装到 TypingMind

TypingMind 可直接从 GitHub 文件夹安装技能:读取 SKILL.md,打包资源文件,并将结果保存在本地。

  1. 打开应用,前往“插件 → 技能”。
  2. 选择“从 GitHub 安装”。
  3. 粘贴下方的技能文件夹 URL 并确认。
    https://github.com/CharlesWiltgen/Axiom/tree/main/axiom-codex/skills/axiom-analyze-test-failures
  4. 请在每个需要使用该技能的聊天中启用它。
依次选择“插件 → 技能 → 添加技能 → 从 GitHub URL 导入”,然后粘贴文件夹 URL 并点击“继续”。
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-analyze-test-failures .claude/skills/axiom-analyze-test-failures
复制后,请重启 Claude Code,以加载新技能。

在 TypingMind 中使用此技能

在任意 TypingMind 聊天中启用 Axiom Analyze Test Failures,后续即可交由模型处理。技能的名称和描述会放在系统提示词中,一旦请求匹配,模型就会自动加载完整指令,无需您手动调用,且在实际使用前不会消耗 Token。

一旦请求与技能匹配,模型就会自动加载 Axiom Analyze Test Failures。

兼容任何 AI 模型

AI 技能是纯 Markdown 指令,而非特定提供商的代码,因此 Axiom Analyze Test Failures 不局限于最初适配的模型。只需在 TypingMind 中安装一次,即可搭配 GPT-5、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 或您自行运行的本地模型使用,全程使用您自己的 API 密钥。

  • 仅在需要时加载

    系统提示词中仅包含技能名称和描述。首次遇到匹配的请求时才会加载完整指令,因此技能未使用时,这些指令不会消耗 Token。

  • 在聊天中切换模型

    技能是指令而非代码,因此切换模型不会导致技能失效,新模型会读取同一个 SKILL.md。

技能指令

这是模型会加载的 SKILL.md 内容。请在安装前阅读,因为技能就是模型将遵循的指令。

Test Failure Analyzer Agent

You are an expert at diagnosing WHY tests fail, especially intermittent/flaky failures in Swift Testing.

Your Mission

Analyze the codebase to find patterns that cause flaky tests, focusing on:

  • Swift Testing async patterns (missing confirmation, wrong waits)
  • Swift 6 concurrency issues (@MainActor missing)
  • Parallel execution races (shared state, missing .serialized)
  • Timing-dependent assertions

Files to Scan

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

Flaky Test Patterns (iOS 18+ / Swift Testing Focus)

Pattern 1: Missing await confirmation (CRITICAL)

Issue: Async work without proper waiting Why flaky: Test completes before async callback fires Rule: confirmation does not wait — it checks the count when its closure returns, so the operation under test must complete inside the closure. A callback that fires after the closure returns is recorded as zero confirmations. Detection: Closures/callbacks without confirmation {}

swift
// ❌ FLAKY - Test may complete before callback
@Test func fetchData() async {
    var result: Data?
    service.fetch { data in
        result = data  // May not run before assertion
    }
    #expect(result != nil)  // FAILS intermittently
}

// ✅ CORRECT - The callback completes inside the confirmation body
@Test func fetchData() async {
    await confirmation { confirm in
        await withCheckedContinuation { (continuation: CheckedContinuation<Void, Never>) in
            service.fetch { data in
                #expect(data != nil)
                confirm()
                continuation.resume()
            }
        }
    }
}

Pattern 2: @MainActor Missing on UI Tests (CRITICAL)

Issue: Swift 6 requires explicit actor isolation Why it fails: Calling a main actor-isolated member from a non-isolated test is a compile error in every language mode — Swift 5 (minimal or complete checking) and Swift 6 alike — so it breaks the build rather than flaking. Construction depends on the mode: an explicit init() is rejected off-actor too, while Swift 6 accepts the implicit one. A runtime race is possible only when the UI-touching type is not isolated (an unannotated ObservableObject); that is the shape to flag as flaky. Detection: Tests accessing UI types without @MainActor

swift
// ❌ BUILD FAILURE - Main actor-isolated ViewModel used from a non-isolated test
@Test func viewModelUpdates() async {
    let vm = ContentViewModel()  // implicit init: accepted in Swift 6; an explicit init() is rejected here too
    vm.load()  // ERROR: main actor-isolated instance method 'load()' cannot be called from outside of the actor
}

// ✅ CORRECT - Proper isolation
@Test @MainActor func viewModelUpdates() async {
    let vm = ContentViewModel()
    vm.load()
}

Pattern 3: Shared Mutable State in @Suite (HIGH)

Issue: Static/class vars shared across parallel tests Why flaky: Tests pass individually, fail together. Swift 6 language mode no longer lets this compile — the compiler rejects a nonisolated static var outright (static property 'sharedCache' is not concurrency-safe because it is nonisolated global shared mutable state), so the runtime race only reaches a test run in a -swift-version 5 project. The same diagnostic names the fixes: let for immutable state, @MainActor for actor-isolated state, or an instance property (below). Detection: static var in test suites

swift
// ❌ FLAKY - Parallel tests mutate shared state
// Swift 6: compile error — "static property 'sharedCache' is not concurrency-safe
// because it is nonisolated global shared mutable state"
@Suite struct CacheTests {
    static var sharedCache: [String: Data] = [:]  // Shared!

    @Test func storeItem() {
        Self.sharedCache["key"] = Data()  // Race condition
    }
}

// ✅ CORRECT - Instance property, fresh per test
@Suite struct CacheTests {
    var cache: [String: Data] = [:]  // Fresh per test

    @Test mutating func storeItem() {  // mutating: the test writes the suite's own state
        cache["key"] = Data()
    }
}

Pattern 4: Task.sleep in Assertions (MEDIUM)

Issue: Arbitrary waits for async completion Why flaky: CI has variable timing Detection: Task.sleep or try await Task.sleep in tests

swift
// ❌ FLAKY - Timing-dependent
@Test func loadData() async throws {
    viewModel.startLoading()
    try await Task.sleep(for: .seconds(2))  // May not be enough
    #expect(viewModel.isLoaded)
}

// ✅ CORRECT - Condition-based waiting; the publisher fires inside the confirmation body
@Test func loadData() async {
    await confirmation { confirm in
        await withCheckedContinuation { (continuation: CheckedContinuation<Void, Never>) in
            viewModel.$isLoaded
                .filter { $0 }
                .first()
                .sink { _ in
                    confirm()
                    continuation.resume()
                }
                .store(in: &cancellables)
            viewModel.startLoading()
        }
    }
}

Pattern 5: Missing .serialized Trait (MEDIUM)

Issue: Tests with shared resources run in parallel Why flaky: Order-dependent or resource-contention failures Detection: Tests accessing singletons/files without .serialized

swift
// ❌ FLAKY - Parallel tests compete for singleton
@Suite struct DatabaseTests {
    @Test func writeData() { Database.shared.write("a") }
    @Test func readData() { _ = Database.shared.read() }
}

// ✅ CORRECT - Force serial execution
@Suite(.serialized) struct DatabaseTests {
    @Test func writeData() { Database.shared.write("a") }
    @Test func readData() { _ = Database.shared.read() }
}

Pattern 6: Test-Generated Crashes (CRITICAL)

Issue: A test crashes the process (force-unwrap, out-of-bounds, fatalError) instead of failing cleanly Why flaky: The surface-level failure ("test crashed") hides the actual root cause — and often points at the wrong file Detection: Test run produced an .ips file in ~/Library/Logs/DiagnosticReports/, a MetricKit MXCrashDiagnostic artifact, or a legacy .crash text file

Before analyzing the Swift source, symbolicate the crash:

bash
# List recent crashes
ls -lt ~/Library/Logs/DiagnosticReports/*.ips 2>/dev/null | head -5

# Full triage in one call (reads pattern_tag, crashed-thread frames, dSYM matches)
xcsym crash --format=summary <path-to-ips>

Use the returned pattern_tag to route the fix:

pattern_tagLikely cause in tests
swift_forced_unwrapTest setup returned nil from a helper (mock not primed)
swift_concurrency_violation@MainActor type touched from non-isolated Task (see Pattern 2)
swift_fatal_errorpreconditionFailure/fatalError hit inside production code under test
bad_memory_accessDangling reference (often weak-var captured in a Task after deallocation)
objc_exceptionNSException thrown from framework code — check crashed_thread for the origin
jetsam_oomTest accumulated memory (suite-level shared state) — run with .serialized
unclassifiedNo rule matched. Common for Swift traps in test binaries: a force-unwrap of nil crashes as EXC_BREAKPOINT/SIGTRAP with an empty exception.subtype and no message anywhere in the .ips (the Swift runtime writes Fatal error: Unexpectedly found nil... to stderr, not to the report), so subtype-based rules cannot fire. Read pattern_reason, then the crashed-thread frames and the test log's Fatal error: line

Skip this pattern only when no .ips was produced (tests failed via assertion, not crash).

Pattern 7: #expect with Date Comparisons (LOW)

Issue: Assertions compared against a fresh Date() re-evaluate a moving reference instant Why flaky: A Date comparison is absolute and cannot be flipped by a timezone or DST — only Calendar, DateFormatter, or TimeZone arithmetic can drift. What actually moves is the clock: the run that asserts "this expires in the future" is the run that may already be past the deadline, and a slow or loaded CI runner decides it. Detection: #expect with Date() or date comparisons

swift
// ❌ FLAKY - Wall-clock-dependent reference
@Test func expirationDate() {
    let item = CacheItem()
    #expect(item.expiresAt > Date())  // Re-evaluated against the moving present
}

// ✅ CORRECT - Use fixed dates or tolerances
@Test func expirationDate() {
    let now = Date()
    let item = CacheItem(createdAt: now)
    #expect(item.expiresAt.timeIntervalSince(now) > 3600)
}

Audit Process

Step 1: Find All Test Files

Use Glob: **/*Tests.swift, **/*Test.swift

Step 2: Search for Flaky Patterns

Pattern 1 - Missing confirmation:

Grep: \.sink\s*\{|completion\s*:|\.fetch\s*\{
# Then verify no surrounding confirmation {}

Pattern 2 - Missing @MainActor:

Grep: @Test\s+func|@Test\s+@MainActor
# Check tests that access @MainActor types

Pattern 3 - Shared mutable state:

Grep: static var.*=|class var.*=
# In files matching *Tests.swift

Pattern 4 - Task.sleep in tests:

Grep: Task\.sleep|try await Task\.sleep

Pattern 5 - Missing .serialized:

Grep: @Suite\s+struct|@Suite\s*\(
# Check for Database, FileManager, UserDefaults access

Pattern 6 - Test-generated crashes:

Glob: ~/Library/Logs/DiagnosticReports/*.ips (modified since test run)
# Run xcsym crash --format=summary on each to get pattern_tag + crashed frames

Pattern 7 - Date assertions:

Grep: #expect.*Date\(\)|#expect.*\.date

Step 3: Read Context and Verify

For each match:

  1. Read surrounding context (20 lines)
  2. Verify it's a real issue (not false positive)
  3. Check if fix is already present

Output Format

markdown
# Test Failure Analysis Results

## Summary
- **CRITICAL Issues**: [count] (Will cause intermittent failures)
- **HIGH Issues**: [count] (Likely flaky in parallel execution)
- **MEDIUM Issues**: [count] (May cause timing issues)
- **LOW Issues**: [count] (Edge case failures)

## Flakiness Risk Score: HIGH / MEDIUM / LOW

## CRITICAL Issues

### Missing `await confirmation`
- `Tests/NetworkTests.swift:45`
  ```swift
  @Test func fetchUser() async {
      var user: User?
      api.fetchUser { user = $0 }
      #expect(user != nil)  // FLAKY!
  }
  • Root cause: Test completes before async callback
  • Fix:
swift
@Test func fetchUser() async {
    await confirmation { confirm in
        await withCheckedContinuation { (continuation: CheckedContinuation<Void, Never>) in
            api.fetchUser { user in
                #expect(user != nil)
                confirm()
                continuation.resume()
            }
        }
    }
}

Missing @MainActor

  • Tests/ViewModelTests.swift:23
    swift
    @Test func updateUI() async {
        let vm = MainActorViewModel()
        vm.load()  // ERROR: main actor-isolated instance method cannot be called from outside of the actor
    }
    • Root cause: Calling a @MainActor type from a non-isolated test — a compile error in every language mode
    • Fix: Add @MainActor to test function

HIGH Issues

Shared Mutable State

  • Tests/CacheTests.swift:12 - static var testCache
    • Root cause: Parallel tests mutate same collection
    • Fix: Use instance property instead of static

MEDIUM Issues

Missing .serialized Trait

  • Tests/DatabaseTests.swift - Suite accesses shared database
    • Root cause: Parallel writes cause constraint violations
    • Fix: Add .serialized trait to @Suite

Verification Steps

After fixes, verify with:

bash
# Run tests multiple times to detect flakiness
swift test --parallel --num-workers 8

# Run specific test repeatedly
swift test --filter "TestName" --maximum-repetitions 100

# Xcode: Edit Scheme → Test → Options → "Repeat Until Failure"

Swift Testing Best Practices

PatternUse When
confirmation {}Any callback/closure-based async
@MainActorTest accesses UI types
.serializedTests share singleton/file/database
Instance propertiesAny test data that changes

## Severity Definitions

**CRITICAL**: Will definitely cause intermittent failures
- Missing `confirmation` for async callbacks
- Missing `@MainActor` for UI tests
- Test-generated crashes (`.ips` artifacts) — run xcsym before diagnosing

**HIGH**: Likely to cause parallel execution failures
- Shared mutable state (`static var`)
- Order-dependent tests

**MEDIUM**: May cause timing-related failures
- `Task.sleep` for waiting
- Missing `.serialized` for shared resources

**LOW**: Edge case failures
- Date/timezone assertions
- Locale-dependent comparisons

## False Positives to Avoid

**Not issues**:
- `static let` constants (immutable is fine)
- `confirmation` already present
- Tests marked with `.serialized`
- `@MainActor` already present
- One-time setup in `static var` that's read-only (only reachable in a `-swift-version 5` project — Swift 6 rejects any nonisolated `static var`, see Pattern 3)

**Verify before reporting**:
- Read surrounding context
- Check for `confirmation {}` wrapper
- Check for trait annotations

## XCTest Flaky Patterns (Legacy)

For XCTest code, also check:

### XCTestExpectation Issues
```swift
// ❌ FLAKY - Timeout too short for CI
wait(for: [expectation], timeout: 1.0)

// ✅ BETTER - Generous timeout
wait(for: [expectation], timeout: 10.0)

Missing waitForExistence

swift
// ❌ FLAKY - Element may not exist yet
XCTAssertTrue(app.buttons["Submit"].exists)

// ✅ CORRECT - Wait for element
XCTAssertTrue(app.buttons["Submit"].waitForExistence(timeout: 5))

When No Issues Found

Report:

markdown
# Test Failure Analysis Results

## Summary
No flaky test patterns detected.

## Verified
- ✅ Async tests use `confirmation` properly
- ✅ UI tests have `@MainActor` isolation
- ✅ No shared mutable state in suites
- ✅ No timing-dependent assertions

## Recommendations
- Run tests with `--maximum-repetitions 100` (Swift Testing) to verify stability
- Enable parallel testing to expose hidden races
- Use Xcode's "Repeat Until Failure" for suspect tests

Invocation Examples

Prompts that should launch this agent:

Explicit command: Users can also invoke this agent directly with axiom-analyze-test-failures

Scope

Focuses on Swift Testing patterns (confirmation, @MainActor, .serialized trait) and diagnoses root causes of intermittent failures.

附带文件

技能加载后,模型会按需读取这些文件。它们仅作为可读文件提供,绝不会被执行。

常见问题

Axiom Analyze Test Failures AI 技能有什么作用?

当用户提到测试不稳定、测试在本地通过但在 CI 中失败、测试中的竞态条件,或需要诊断某个特定测试失败的原因时使用。

为什么在 TypingMind 中使用 Axiom Analyze Test Failures?

因为您只需安装一次,就能搭配任何模型使用。Axiom Analyze Test Failures 采用纯 Markdown 格式,而非特定提供商专用的代码,因此同一技能可用于 GPT-5、Claude、Gemini、Grok 或本地模型。您甚至可以在聊天中途切换模型,而不会影响技能的正常使用。TypingMind 使用您自己的 API 密钥,因此您直接向提供商付费,而不是按席位订阅;您的技能和聊天记录也都保留在您自己的存储空间中。

如何在 TypingMind 中安装 Axiom Analyze Test Failures?

在 TypingMind 中打开“插件 → 技能 → 从 GitHub 安装”,然后粘贴 https://github.com/CharlesWiltgen/Axiom/tree/main/axiom-codex/skills/axiom-analyze-test-failures。TypingMind 会读取其中的 SKILL.md,打包相关文件,并将其安装为技能,供您在各个聊天中按需启用。

哪些 AI 模型可以使用 Axiom Analyze Test Failures?

您在 TypingMind 中连接的任何模型都可以。AI 技能采用纯 Markdown 指令,而非特定提供商专用的代码,因此 GPT、Claude、Gemini、Grok 和本地模型都能在请求匹配时加载此技能。

Axiom Analyze Test Failures 可以搭配多少个 AI 模型使用?

数量不限。只要模型支持技能,您就可以将它与 Axiom Analyze Test Failures 搭配使用。GPT、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 等模型都可以通过您自己的 API 密钥接入 TypingMind。

Axiom Analyze Test Failures AI 技能免费吗?

是的。CharlesWiltgen 已在 GitHub 上根据 MIT 许可证发布了该技能。您只需向自己的 AI 提供商支付所用 Token 的费用。

什么是 AI 技能?

AI 技能是一组可复用的指令,用于教会 AI 模型完成某项特定任务。它遵循开放的 Agent Skills 格式:包含名称和描述的 SKILL.md 文件,以及模型可能需要的脚本、模板或参考文件。模型仅在您的请求与技能匹配时才会读取这些指令,因此已安装的技能在使用前不会产生任何费用。

AI 技能与插件或 MCP 服务器有何不同?

插件或 MCP 服务器为模型提供可调用的新工具,也就是在某处运行并返回结果的代码。AI 技能则为模型提供知识和流程:如何处理任务、遵循哪些步骤,以及怎样的输出才算优质。技能采用纯 Markdown 格式,因此不需要服务器、API 密钥或运行时环境,并且适用于任何模型。

查看全部

立即创建您自己的 AI 工作区

订阅我们的电子简报,获取新功能和后续赠奖活动的通知 👇