• Swift Testing
  • XCTest
  • swift-syntax
  • Swift 6
  • MIT

Architecture rules
your agents can read.

Write your codebase's rules as Swift tests. When one breaks, the failure lands on the offending line with the rule's title, why it exists, how to fix it, and a bad and a good example. That is everything a teammate or an AI agent needs to fix it without asking.

swift test
Packages/TelaioCLI/Tests/TelaioCLITests/RunCommandTests.swift:100:11: await withKnownIssue {

RULE: withKnownIssue says what the known issue is. [known-issues-explain-themselves, testing]
WHY: A known issue hides a failing expectation. Without a reason in the call, the next reader cannot tell a bug
     waiting for a fix from a test nobody understood.
HOW TO FIX: Pass the reason as the first argument: name the bug and where it is tracked.
BAD:
    await withKnownIssue { try await sync.upload() }
GOOD:
    await withKnownIssue("sqlite-data 1.12 drops quotaExceeded (bug 1)") { try await sync.upload() }

A real failure from Telaio's rules, recorded at the file, line and column of the violation.

Why

Your conventions live in documents and reviews.
The code is written somewhere else.

Every codebase has rules: which layer may do I/O, how a reducer splits its actions, why a database read is never synchronous. They sit in a standards document, a decision record or a reviewer's memory. An agent writing code sees none of them at the moment it matters.

A written rule

Nobody runs it.

A standard that is checked by grep or by review fails silently. The comment a reviewer leaves is the first time the author hears of it, after the code is written.

A terse lint message

It starts a guessing game.

Violation: no_print says what tripped, not why it matters or what to write instead. An agent guesses, or disables the check.

swift-llm-check

The explanation travels with the failure.

The rule, its reason, the fix and two examples are printed at the violation, in the test output an agent already reads. The same text is rendered as a document the agent reads before it starts.

How it works

A rule is a test. Its failure is the documentation.

No new tool, no configuration language: rules are Swift, they run with swift test or in Xcode, and they live in a small test-only package beside your code.

Describe the rule

A Rule value: an id, a title, a category, the rationale, how to fix it, and a bad and a good example. Cite where it comes from: a decision record, a measured hang, a line of your standards.

Query the code

Scope the codebase with .gitignore-style patterns, then ask for declarations, calls, references, imports or any syntax node, on the real syntax tree from swift-syntax.

Assert

expectNone or expectAll records one issue per violation at its file, line and column, with the offending line and the rule's full text. In Xcode, the failure sits on the line to fix.

Then render the rules with RuleCatalog and link the generated file from AGENTS.md or CLAUDE.md. An agent reads each rule twice: before it writes the code, and again at the line where it broke it.

Features

Small, fast, and precise where it counts.

One package with one dependency: the queries a rule needs, the assertions that report it, and the tools to land it on a codebase that does not follow it yet.

Swift Testing and XCTest

Rules are @Test functions or XCTestCase methods. They run wherever your tests run: swift test, Xcode, CI, an agent's loop.

The exact line and column

Every finding points at the offending token, with the line it is on. Nothing is reported at line 1 of a file.

The whole syntax tree

Calls inside closures, await, try, switch and #if are found. References skip comments and strings, where a grep would match.

Baselines that only shrink

Land a rule on code that breaks it with Baseline(covering:). An entry that no longer matches fails as stale, so the list can only get shorter.

Rules for agents, generated

RuleCatalog renders the rules as Markdown for AGENTS.md or a skill, and a test fails when that file falls behind the rules.

Fast and safe in parallel

Each file is read and parsed once per process, on every core, and only if a text filter lets it through. Everything is Sendable; parallel suites never deadlock.

Code tour

Rules read like the sentence they enforce.

Every example below is taken from the README.

A rule is a value with everything a reader needs: a title, why it exists, how to fix it, and a bad and a good example. The test finds the violations and hands them to expectNone.

LoggingRules.swift
import LLMCheck
import Testing

extension RuleCategory {
  static let logging = RuleCategory("logging", description: "Logging and secrets. Read before you log anything.")
}

extension Rule {
  static let noPrint = Rule(
    id: "no-print",
    title: "The app never calls print.",
    category: .logging,
    rationale: "print output is lost in a shipped app and cannot be private.",
    howToFix: "Use a `Logger(subsystem:category:)` and interpolate with `privacy: .private`.",
    badExample: #"print("loaded \(url)")"#,
    goodExample: #"logger.debug("loaded \(url, privacy: .private)")"#
  )
}

@Suite struct LoggingRules {
  @Test func noPrint() throws {
    let calls = try Codebase().productionCode.in("/Sources").calls(named: "print").filter { $0.node.receiver == nil }
    expectNone(calls, rule: .noPrint)
  }
}

Start from the whole codebase and narrow with patterns that read like a .gitignore line. containing(_:) filters on raw text before anything is parsed, so a rule about reducers never parses the rest of the app.

Scopes
let codebase = try Codebase()            // or Codebase(root: url)
codebase.productionCode                  // everything that is not test code
codebase.testCode                        // under a folder ending in Tests or named Fixtures
codebase.allCode
  .in("Packages/Features")               // several patterns are a union, chained calls narrow
  .excluding("DocumentFeature", "*.generated.swift")
  .containing("@Reducer")                // only files whose raw text contains this, before parsing
Scope(files: [SourceFile(path: "A.swift", source: "…")])  // in-memory, to test a rule

Structs, classes, enums, actors, protocols, extensions, functions and variables, nested ones included, with their attributes, modifiers and inheritance clause as written.

ReducerRules.swift
let reducers = codebase.productionCode.containing("@Reducer").structs.withAttribute("Reducer")
let states = reducers.flatMap(\.structs).named("State")
expectAll(states, rule: .stateIsObservable) { $0.hasAttribute("ObservableState") }

let actions = reducers.flatMap(\.enums).named("Action").filter { $0.cases.contains { $0.name == "view" } }
expectAll(actions, rule: .actionsAreSplit) { $0.inherits(from: "ViewAction") }

Search the whole tree, closures, await and #if included. References skip comments and strings, which is what a grep gets wrong.

Queries
scope.calls(named: "withKnownIssue")         // `await withKnownIssue { }`, `return .run { await f() }`…
scope.calls(named: names)                    // a Set<String> built at run time
call.node.calledName                         // "apply" in `edit.apply(to: &doc)`
call.node.receiver                           // `edit`; nil for `print(x)`
call.node.argument(labeled: "database")      // `database: db` in `load(r, database: db)`
call.node.passesClosure                      // `db.read { }`, `run(work: { })`
call.node.isAwaited                          // `try await f()`, `(try? await f()) ?? []`; not `Task { f() }`
scope.imports(of: "Foundation", "Yams")      // `import Foundation`, `import struct Foundation.URL`, in `#if` too
scope.imports                                // every import; `import.node.moduleName` is `Foundation`
node.enclosingIfConfigClauses                // the `#if`/`#elseif`/`#else` clauses around a node, innermost first
clause.ifCondition, clause.isElse            // `canImport(FoundationEssentials)` and true for that `#if`'s `#else`
scope.references(to: "URLSession", "FileManager")  // code only: comments and strings never match
statement.node.attachedComments              // the comments above a node and the one at the end of its line
scope.references(to: "CommandLine") + calls.map(\.erased)  // matches of different node types, for one rule

Render every rule as Markdown for AGENTS.md, CLAUDE.md or a SKILL.md, so an agent reads the rules before it writes the code. expectFile fails when the file is stale, and LLM_CHECK_RECORD=1 rewrites it.

CatalogTests.swift
@Test func rulesMarkdownIsUpToDate() throws {
  let catalog = RuleCatalog([.noPrint, .stateIsObservable])
  #expect(catalog.duplicateIDs.isEmpty)
  try expectFile("docs/RULES.md", in: Codebase(), matches: catalog.markdown(title: "Architecture rules"))
}

Inside an XCTestCase, the same calls record XCTest failures at the violation's file and line.

LoggingRules.swift
import LLMCheck
import XCTest

final class LoggingRules: XCTestCase {
  func testNoPrint() throws {
    let calls = try Codebase().productionCode.calls(named: "print").filter { $0.node.receiver == nil }
    expectNone(calls, rule: .noPrint)
  }
}

In production

Many codebases. Every rule came from somewhere real.

Apps, libraries, SwiftPM plugins and the library itself run their rules on swift-llm-check, and the list keeps growing. Here are a few of them. They arrived at the same setup independently.

macOS app · TCA

Telaio

Nineteen rules from decision records and owner issues: reducer shape, layering, dependencies, logging, testing, design tokens, database access. The first run found 29 violations; all were fixed or settled by a decision, and no baseline is left.

  • 992 files
  • 19 rules
  • 29 findings, all fixed
iOS app · SQLiteData

forum-offline

Profiling found main-thread hangs from SQLite work: a synchronous read in a view hung 1.75 s, a write 2.7 s. Four rules encode the fix, each rationale quoting its hang. They landed with 96 existing violations in a baseline, and the baseline was deleted once all were converted.

  • 4 rules
  • 96 violations converted
  • baseline deleted
Swift library · Linux

swift-arazzo

Its CODING_STANDARDS.md and CONSTRAINTS.md became eight rules: purity, the import budget, Sendable models, Swift Testing only. The library supports Linux and Swift 6.0, so the rules run in CI's macOS job only.

  • 8 rules
  • 0 findings
  • gave back import queries
Swift library · no imports

swift-jsonpath

Copied swift-arazzo's setup on the first try. Nine rules, among them "Sources imports nothing". The first run found two public types that were not Sendable; both were fixed.

  • 9 rules
  • 2 findings, fixed
  • gave back Match.erased
This library

swift-llm-check

The library checks itself: nine rules that keep the README's promises, from the dependency budget to "locks only in Locked.swift". Built against the working copy, so a change is checked by the rules it touches.

  • 9 rules
  • 0 findings
  • runs in CI
Your codebase

Start with one rule

Pick the rule reviewers repeat most often, write it with its reason and examples, and run it. If the code already breaks it, baseline today's findings and let the list shrink.

  • one test-only package
  • one YAML file

Also checked by swift-llm-check: swift-har, swift-curl, swift-keychain, swift-snapshot, urkel, PackageGeneratorPlugin, PackageGeneratorCLI, SchemeGeneratorPlugin, EnvironmentVariationPreview and more.

  1. A standalone, test-only package. The app or library never builds it, so swift-syntax never holds back the product's own macros or toolchain.
  2. .llm-check.yaml at the root, excluding the rules package and folders with no product code.
  3. Rules written from rules you already have, each citing its source. A rule with no source is a rule nobody can argue with or retire.
  4. Detectors apart from the codebase, tested on in-memory snippets: what they catch, and the look-alikes they let through.
  5. A sanity count where a scope could be empty, since a rule over nothing passes.
  6. A generated rules document, linked from AGENTS.md or CLAUDE.md instead of restating the rules.
  7. Agent instructions next to the rules: run the package, a failure explains itself, fix the code, never add to a baseline.
  8. Baselines only on the way in, deleted when empty.

From the adoption notes, which compare the setups in detail.

Speed

Fast enough to run on every change.

Rules are cheap when the parser only sees the files a rule can match. Text filters run on the raw bytes first, each file is parsed at most once per process, and the work is spread over every core.

0.7 seight rules on Telaio's 992 files and 220,000 lines
50×faster than the same rules on Harmonize (35 s)
4–20×faster queries on main, measured on swift-syntax's own sources
1dependency: swift-syntax, any version from 601 to below 700
Harmonize 2.0.0-beta.2swift-llm-check
Parallel suitesDeadlock when two suites warm the cacheSafe, stress-tested
CallsWhole-statement calls onlyThe whole tree
LocationFile-level matches report line 1Exact line and column, with the offending line
Swift 6Types not SendableEverything Sendable
Speed (Telaio, 8 rules, debug)35 s0.7 s
BaselinesFile names, fail when staleFile names, paths or File.swift:Decl, fail when stale
Dependenciesswift-syntax, Yamsswift-syntax

Harmonize inspired this library: its rule text at the violation is the part that helps agents most. The full comparison and the benchmarks are in the README.

Install

Add a rules package. Write one rule.

  1. Create a test-only package beside your code, such as Packages/Architecture, so your app's build never sees the rules.
  2. Put .llm-check.yaml at the root of the code to check. Codebase() walks up from the test file to find it.
  3. Write a rule from one you already enforce in review, with its reason and a bad and a good example. Run swift test.
  4. Tell your agents. Generate the rules document with RuleCatalog and link it from AGENTS.md: "run the rules; a failure explains itself; fix the code."
Package.swift
// Packages/Architecture/Package.swift
// swift-tools-version: 6.0
import PackageDescription

let package = Package(
  name: "Architecture",
  platforms: [.macOS(.v14)],
  dependencies: [.package(url: "https://github.com/mackoj/swift-llm-check.git", from: "0.5.0")],
  targets: [
    .testTarget(name: "ArchitectureTests", dependencies: [.product(name: "LLMCheck", package: "swift-llm-check")])
  ]
)
.llm-check.yaml
# Paths never read. A name matches any folder or file; a path with a slash matches from the root; * is a wildcard.
excludes:
  - build
  - DerivedData
  - Packages/Architecture
# Optional. A folder whose name ends with one of these holds test code (default: Tests).
testSuffixes: [Tests]
# Optional. A folder with one of these names holds test code (default: Fixtures).
testFolders: [Fixtures]

Swift 6 (Xcode 16 or later), macOS 14 or iOS 17. The README covers scopes, queries, baselines, XCTest and the rules document in full.