
harmonize
Architectural linting for Swift, for humans and AI agents: run Harmonize rules with machine-readable output, fix violations, and write new rules.
- GitHub stars
- 366
Install
/plugin install harmonize@harmonizeRun it inside Claude Code after adding the marketplace with /plugin marketplace add perrystreetsoftware/Harmonize.
Contents
Discovered from sourceSkills 2
Run Harmonize rules
Harmonize is a Swift architectural linter. Its rules are unit tests. This skill runs the rules and interprets the results. It works in any project that uses Harmonize.
Find the rules package
- Find the repository root: the directory that contains
.harmonize.yaml. - Find the Swift package that contains the rules: a
Package.swiftwith a test target that depends onHarmonize. Rungrep -rl --include=Package.swift "Harmonize" .and ignore the Harmonize library itself.
If the project has its own runner script or skill (for example run-harmonize.sh or a project run-harmonize skill), use it. It can filter the output or use a prebuilt workspace. The rest of this skill is the portable fallback.
Run
Run from the repository root. Send the log to a file. Request the JSON report with one environment variable:
rm -rf .harmonize-out && mkdir -p .harmonize-out
HARMONIZE_VIOLATIONS_FILE="$PWD/.harmonize-out/violations.json" \
swift test --package-path <rules-package> > .harmonize-out/test.log 2>&1
echo "exit code: $?"
- To run one rule, add
--filter <RuleTestClassName>to theswift testcommand. This does not work for Quick specs on macOS. A Quick spec is a rule class that extendsQuickSpec. With Quick specs,--filterselects no tests, andswift test --parallelskips them without an error. Build the tests withswift build --build-tests, find the bundle inswift build --show-bin-path, and runxcrun xctest -XCTest <Module>.<RuleTestClassName> <bundle>. Withxcodebuild, use-only-testing:<Module>/<RuleTestClassName>. - With
xcodebuild, name the variableTEST_RUNNER_HARMONIZE_VIOLATIONS_FILE. The prefix makes the variable reach the test process. - Always pass an absolute path for the output file.
- One run can have several test processes, for example Swift Testing tests or parallel workers. They all add their entries to the one file. Delete the output folder before each run, as the command above does. Harmonize recognizes the processes of one run by their parent process, so a file from an earlier run can keep old entries. To get one file per process instead, end the path with a slash:
HARMONIZE_VIOLATIONS_FILE="$PWD/.harmonize-out/". Each process then writes its ownviolations-<pid>.jsonfile. Read all of them. - Add
.harmonize-out/to.gitignore. - The test run fails on violations as usual. Harmonize writes the JSON file when the process exits.
Interpret the result
Read the log only when this section tells you to.
- Exit code 0: all rules pass.
violations.jsoncontains[]. - The log says
Executed 0 testsand has noTest run with ...line from Swift Testing: no rule ran. The filter matched no test, or the Quick specs did not run. Do not treat the result as a pass. Run the command again without--filterand without--parallel, or run the bundle as described above. - Exit code not 0, and
violations.jsonhas entries: read the file. Each entry has:ruleIdandtitle: the rule that failed.file,line,column,name: the location of the violating declaration.message: the rationale of the rule.howToFix: how to correct the code.
- An entry with
"kind": "assertion"is a rule-level failure, for example a stale baseline. A stale baseline entry is a known violation that now passes the rule. Remove the entry from thebaselinelist of the rule. Do not change production code for it. - Exit code not 0, and
violations.jsonis missing or[]: the rules did not run, or a test failed outside Harmonize. Search the log forerror:. Fix the build first.
Fix violations
- For each violation, apply
howToFix. If you need the examples, open the rule page of the generated skill:references/*/<ruleId>.md. If the project has no generated skill, open the rule source. Its file name is the rule id in PascalCase, unless the rule sets an explicitid. - Fix the production code. Change the rule only when the task is to change the rule.
- Do not hide a new violation with a
baselineentry. Use the baseline only for violations that existed before the rule. - Run the fixed rule alone. Use
--filter <RuleName>, or the bundle command for a Quick spec. Then run the full suite.
Learn the rules before you write code
If the project has a generated harmonize skill, use it before you write code. Its SKILL.md lists one reference file per layer. Open the file of the layer you will change. It lists the rules of that layer. Each rule links to a page with the rationale, the fix, and a bad and a good example. The skill does not list rules with .deferred disclosure, but Harmonize enforces them. Their test failures explain the fix.
The skill is generated from the rule sources. The generator does not build or run the tests:
swift package --package-path <rules-package> --allow-writing-to-package-directory \
--allow-writing-to-directory <skills-dir> harmonize-skills
The output directory and the skill name come from .harmonize.yaml (skills: { output: ..., name: ... }). Projects usually run this from a pre-commit hook when rule files change. A CI check makes sure that the committed skill is current.
Write a Harmonize rule
Harmonize rules are unit tests. They query the syntax tree of the codebase and assert architectural conventions. Write one rule per file. Name the file after the rule (for example ViewModelsInheritBaseViewModel.swift). Put it in the rules package of the project (see the run-harmonize skill). Use the test framework the package already uses: XCTest, Quick or swift-testing.
Template (XCTest)
import Harmonize
import XCTest
final class ViewModelsInheritBaseViewModel: XCTestCase {
func testViewModelsInheritBaseViewModel() {
Harmonize.productionCode()
.classes()
.withNameEndingWith("ViewModel")
.assertTrue(rule: Self.rule) { $0.inherits(from: "BaseViewModel") }
}
private static let rule = Rule(
title: "ViewModels must inherit from BaseViewModel.",
category: Categories.viewmodel,
disclosure: .progressive,
rationale: """
Lifecycle handling, state publishing, and error routing live in \
BaseViewModel. A ViewModel outside the hierarchy loses them.
""",
howToFix: "Declare the class as `final class MyViewModel: BaseViewModel`.",
badExample: "final class MyViewModel: ObservableObject { }",
goodExample: "final class MyViewModel: BaseViewModel { }"
)
}
Always provide the Rule metadata
Pass rule: to assertTrue, assertFalse or assertEmpty. The message: parameter is deprecated. All fields are required. Pass an empty string only when a field does not apply.
| Field | Purpose |
|---|---|
id | A stable kebab-case identifier. Harmonize derives it from the file name (ViewModelsInheritBase.swift → view-models-inherit-base). Set it only for a better name, when a file has several rules (two rules must not share an id), or when the derived form breaks an acronym. Use lowercase letters, digits, and single hyphens. Do not change an id after you publish it. |
title | One sentence that says what the rule checks. |
category | The layer of the rule. Pass a case of the category enum of the project (see below). |
disclosure | When agents must learn the rule. .upfront: the rule applies to almost every task. Use it rarely, because each upfront title goes into the skill description and the description has a limit of 1024 characters. .progressive: the rule applies to one layer (the default). .deferred: the fix is mechanical, and the test failure explains it. The value does not change enforcement. |
rationale | Why the rule exists. Without it, agents and teammates avoid the rule instead of correcting the code. |
howToFix | The steps that correct a violation. Generated docs show it next to the title, so make it complete for the common case. |
badExample | A short code sample that violates the rule. |
goodExample | A short code sample that obeys the rule. |
Each rule becomes documentation. The harmonize-skills plugin reads the declarations from the source code and generates the harmonize agent skill: one reference page per layer and one per rule. For this reason, every value must be a literal: a string literal or an enum case. Do not use Self.sharedText or string interpolation. If you do, the generator stops with an error at that line. Put dynamic detail, such as the names of the declarations that a check found, in the test description or in the violation names, not in the Rule.
Category vocabulary
Define the categories of the project once, as an enum that conforms to RuleCategory. Always pass a case. The compiler then rejects a misspelled category ("view-model" against "viewmodel"). The skill generator also stops when two category names differ only in case or punctuation.
enum Categories: String, RuleCategory {
case viewmodel, logic, networking
var categoryName: String { rawValue }
var categoryDescription: String {
switch self {
case .viewmodel: "Rules for ViewModels and UIModels. Read before you create or change a ViewModel."
case .logic: "Rules for Logic classes (use cases). Read before you add business logic."
case .networking: "Rules for APIs and DTOs. Read before you change network code."
}
}
}
Give each case a categoryDescription of one or two sentences. The generated skill shows it next to the layer. Write it as a trigger ("Rules for X. Read before you create or change Y."). Before you add a case, check whether an existing category covers the layer. Each category becomes one reference page in the skill.
Scope and filter
- Scope with
Harmonize.productionCode(),.testCode()or.on("path/Or/Folder"). If the project has its own scope helpers (a class that wrapsHarmonize), use them. - Prefer the built-in filters (
withNameEndingWith,withoutModifier,conforming(to:),withImport, ...) to.filter { }closures and regular expressions. - If you need a regular expression, compile it once as a
static let. Do not construct it inside a per-element predicate.
Record the known violations
Pass the known violations to the baseline: parameter of the assertion. Use declaration names or File.swift names:
.assertTrue(rule: Self.rule, baseline: ["LegacyViewModel"]) { ... }
The assertion reports a stale baseline error when an entry starts to pass, or when it matches nothing. The list then becomes shorter over time. Do not filter the scope with .withoutName(baseline). That hides stale entries. Omit baseline: when there are no violations.
Verify
- Run the new rule alone (see
run-harmonize). Expect a failure on each known violation and a pass otherwise. - Add a temporary violation to confirm that the rule catches it. Then remove it.
- Run the full rule suite to confirm that nothing else broke.
- Regenerate the agent skill (
swift package ... harmonize-skills, seerun-harmonize), or let the pre-commit hook do it. Commit the skill with the rule.
Sponsors
Details
- Marketplace
- perrystreetsoftware/Harmonize
- Category
- Community