From 393f15249f96ed0a5a6167d87a563aff497b79d6 Mon Sep 17 00:00:00 2001 From: Ravi Shankar Date: Fri, 6 Nov 2026 18:56:50 +0530 Subject: [PATCH] feat(map,build,review): "must not" rules per folder, enforced by checks (#116) map surveys framework use per folder (new tested folder-imports.sh), suggests 3-6 rules, asks which to keep, and installs each as a SwiftLint rule or fitness test proven green on real code and red on a planted break. Existing breaks become known exceptions that only shrink. CODEBASE.md gets a Folder Rules table that build agents follow and review checks. expect-red.sh gains --no-build-check for lint commands. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 12 +++ CLAUDE.md | 3 +- commands/build.md | 9 ++ commands/map.md | 93 ++++++++++++++++++- commands/review.md | 6 ++ scripts/test-scripts.sh | 18 ++++ templates/_scripts/expect-red.sh | 8 +- templates/_scripts/folder-imports.sh | 53 +++++++++++ tests/fixtures/app/App/Models/Note.swift | 7 ++ .../app/App/Services/Sync Service.swift | 8 ++ .../app/Watch App/Views/Home View.swift | 1 + 11 files changed, 214 insertions(+), 4 deletions(-) create mode 100755 templates/_scripts/folder-imports.sh create mode 100644 tests/fixtures/app/App/Models/Note.swift create mode 100644 tests/fixtures/app/App/Services/Sync Service.swift diff --git a/CHANGELOG.md b/CHANGELOG.md index bd8cf0a..a50ddfc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,18 @@ commands, or moved skill-reference paths. ### Added +- **"Must not" rules per folder** (#116). `map` surveys which frameworks + each folder uses (new tested script `folder-imports.sh`), suggests 3–6 + rules such as "Models must not import SwiftUI" or "only Payments/ uses + StoreKit", each marked true today or broken in N files, and asks which + to keep. Each kept rule becomes a SwiftLint rule or a fitness test, + proven to pass on the real code and fail on a planted break in a + throwaway copy. Files that already break it are listed as known + exceptions, a list that only shrinks. CODEBASE.md gets a Folder Rules + table; build agents follow it, and `review` flags new breaks and any + growth in the exceptions. `expect-red.sh` gains `--no-build-check` for + lint commands. + - **One-page review guide per phase** (#113). `verify` writes `.planning/REVIEW-GUIDE.md` (new template) in plain English: what changed, the choices agents made and what they rejected, the proof (promised diff --git a/CLAUDE.md b/CLAUDE.md index 3e96cc4..252be82 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -217,7 +217,8 @@ Some commands can act directly on an external service (push App Store metadata v - `debt-measure.sh`, `baseline-refresh.sh` (`debt`) - `design-pin.sh` (`plan`) - `design-compare.sh` (`verify`) -- `expect-red.sh` (`build`, `verify`): runs tests in a throwaway git worktree with new tests copied in, or a planted bug swapped in, and reports whether they went red (#111) +- `folder-imports.sh` (`map`): which frameworks each folder uses, for suggesting folder rules (#116) +- `expect-red.sh` (`build`, `verify`, `map`): runs tests in a throwaway git worktree with new tests copied in, or a planted bug swapped in, and reports whether they went red (#111) Logic that must give the same answer every run lives here, not pasted into command text (#112). Each script is tested against fixture projects in `tests/fixtures/` by `scripts/test-scripts.sh`, which `validate.sh` runs. A fake `swiftlint` stands in, so CI needs no Xcode. When adding a script, add a fixture test and prove it fails on a planted bug. diff --git a/commands/build.md b/commands/build.md index 386f261..cc8f5f0 100644 --- a/commands/build.md +++ b/commands/build.md @@ -251,6 +251,11 @@ Task({ [Contents of .planning/UTILITIES.md if it exists. Omit if none.] + + [The "## Folder Rules" table from .planning/CODEBASE.md, if it has + one. Omit otherwise.] + + [UI tasks only, when the project has one: the token map, text styles and component list from .planning/DESIGN-SYSTEM.md. Omit otherwise.] @@ -273,6 +278,10 @@ Task({ components (states through ContentStateView), accessibilityIdentifier on interactive elements, view files under ~300 lines. A missing token goes into the token file and is reported, never inlined. + 7. If is present: put code in the folder whose rules + allow it, and never add a file to a rule's known exceptions. If the + task can't be done without breaking a rule, stop and report it + instead of working around it. After completing, report: - Files created/modified diff --git a/commands/map.md b/commands/map.md index 282568f..47c90e6 100644 --- a/commands/map.md +++ b/commands/map.md @@ -1,6 +1,6 @@ --- description: Analyze existing codebase before adding SwiftShip workflow -allowed-tools: Read, Write, Edit, Glob, Grep, Bash +allowed-tools: Read, Write, Edit, Glob, Grep, Bash, AskUserQuestion --- # Map Existing Codebase @@ -203,6 +203,16 @@ Create `.planning/CODEBASE.md`: [Directory tree] ``` +## Folder Rules + +What each folder is for, and the lines it must not cross (Step 5.7). +Known exceptions are files that broke the rule before it existed; the list +only shrinks. + +| Folder | For | Must not | Enforced by | Known exceptions | +|--------|-----|----------|-------------|------------------| +| [App/Views/] | [screens] | [use CloudKit, StoreKit or URLSession directly] | [SwiftLint `folder_views_no_data` / FolderRuleTests / not enforced] | [none / 2 files] | + ## Architecture **Pattern:** [Detected: MVVM / MVC / TCA / Mixed] @@ -329,6 +339,86 @@ using the **real** directories/files as globs (prefer a directory glob over listing every file). 3–5 rows at most; no hits → skip the file. If the file already exists, add only new areas — never remove or rewrite the user's rows. +## Step 5.7: Folder Rules ("must not") + +Agents copy whatever patterns they see and put code wherever it works. +CODEBASE.md says what each folder holds; this step adds the lines a folder +must not cross ("Views must not talk to CloudKit", "Models must not import +SwiftUI", "only Payments/ uses StoreKit"), and turns each one you keep into +a check that fails when it's broken. + +**1. Survey** which frameworks each folder uses: +```bash +bash ~/.claude/swiftship-templates/_scripts/folder-imports.sh # folder framework files +bash ~/.claude/swiftship-templates/_scripts/folder-imports.sh --files CloudKit # which files use one +``` +Names starting `api:` are direct calls (`api:URLSession`, +`api:CKContainer`, `api:Product.purchase`) that need no import of their +own. If the script is missing, SwiftShip is out of date: tell the user to +update it (`claude plugin update apple@indie-apple-stack`, or `git pull` +for a manual install), and skip this step. + +**2. Suggest 3–6 rules** the survey supports. Common shapes: +- a views folder (`Views/`, `Screens/`, `Features/*/Views`) must not use + CloudKit, StoreKit or networking directly (data goes through a service or store) +- a models folder must not import SwiftUI, UIKit or AppKit +- only one folder uses StoreKit / CloudKit / `URLSession` (pick the folder + that holds most of it today) + +For each, say whether it's **true today** or **broken in N files** (list +them with `--files`). Don't suggest a rule broken in most of the files it +covers: that's how the app is built, not an exception. No folder structure +to speak of (everything in one folder) → skip this step and say so. + +**3. Ask once** (`AskUserQuestion`, multiSelect) which rules to keep, each +with its plain status ("true today" / "broken in 3 files; they'd be listed +as known exceptions"). Nothing chosen → skip to step 5 and write the table +with "not enforced". + +**4. Turn each kept rule into a check**, the way `/apple:learn` does +(its "For Enforcement" section): +- **One folder, one framework** → a SwiftLint custom rule in `.swiftlint.yml`: + ```yaml + custom_rules: + folder_models_no_ui: # folder rule: Models must not import SwiftUI + name: "Models must not import SwiftUI" + regex: '^\s*(@\w+\s+)*import\s+(SwiftUI|UIKit|AppKit)\b' + included: ["App/Models/"] + excluded: ["App/Models/Legacy Note\\.swift"] # known exceptions; this list only shrinks + message: "Models stay UI-free; put view code in Views/." + severity: error + ``` + For a direct-call rule, match the call (`URLSession`, `CKContainer`) too. +- **"Only X may use Y"** → a fitness-function test (import-boundary + allowlist plus API scan) in the app's test target: + ``` + Read: ~/.claude/swiftship-skills/testing/fitness-functions/SKILL.md + ``` + The allowlist is folder X plus the known exceptions. +- **Known exceptions:** files that break the rule today are listed in the + rule itself (`excluded:` or the allowlist), each with a comment that the + list only shrinks. The rule then passes today and fails on any new break. +- **Prove each check**, without touching the user's files: + - *Passes on the real code:* `swiftlint lint --strict --quiet`, or the + fitness test by name. + - *Fails on a new break:* plant the forbidden import in a file inside + the folder, in a throwaway copy, with the new rule copied in: + ```bash + bash ~/.claude/swiftship-templates/_scripts/expect-red.sh --no-build-check \ + --copy .swiftlint.yml --swap "" 'import Foundation' $'import Foundation\nimport CloudKit' \ + -- swiftlint lint --strict --quiet + ``` + (For a fitness test: `--copy` the test file, drop `--no-build-check`, + and run the test by name.) `RED` = proven. Anything else: fix the rule + and try again; still not red → don't install it, and mark the rule + "not enforced (check didn't work)". +- No SwiftLint and no test target → keep the rule in the table as "not + enforced yet" and suggest `/apple:test` to set up a test target. + +**5. Write the table** into CODEBASE.md's `## Folder Rules` section (see +Step 5's template): one row per folder that has a purpose worth stating, +with the rules kept. Build agents and `/apple:review` read this table. + ## Step 6: Vendor Agents (optional, recommended for cloud/remote work) Apply `~/.claude/swiftship-templates/_conventions/AGENT-VENDORING.md`: offer to @@ -365,6 +455,7 @@ Codebase mapped! Created: .planning/CODEBASE.md .planning/UTILITIES.md ([N] shared helpers agents will reuse — or "none found") .planning/CRITICAL.md ([areas] — /apple:build pauses for review on these — or "none found") + Folder rules: [n] kept, [n] enforced by a check ([n] known exceptions) — or "none" Summary: - [X] Swift files found diff --git a/commands/review.md b/commands/review.md index 34c1a8c..eef76e4 100644 --- a/commands/review.md +++ b/commands/review.md @@ -27,6 +27,7 @@ Read: .planning/APP.md (if exists) Read: .planning/ROADMAP.md (if exists) Read: .planning/STATE.md (if exists) Read: .planning/UTILITIES.md (if exists — pass to Agent 1 for the reimplemented-helper check) +Read: .planning/CODEBASE.md (if exists — pass its "## Folder Rules" table to Agent 1) ``` ## Lint Baseline (pre-pass) @@ -174,6 +175,11 @@ Task({ client) — cite both the duplicate and the helper it should use. Shared helpers missing from UTILITIES.md: note them as a Low finding ("add to inventory") so agents learn to reuse them + - **Folder rules:** if CODEBASE.md has a "Folder Rules" table, flag + any changed file that breaks a "must not" (High: cite the file, + line and rule), and any rule whose known-exceptions list grew + (`git diff` of the rule's `excluded:` or allowlist; High: the + list may only shrink). A shrunk list is good news; say so. 9. **Design System (restyle cost)**: rules from ~/.claude/swiftship-skills/design/design-system/SKILL.md diff --git a/scripts/test-scripts.sh b/scripts/test-scripts.sh index 17b9b95..9760f56 100755 --- a/scripts/test-scripts.sh +++ b/scripts/test-scripts.sh @@ -86,6 +86,22 @@ expect "design-compare: added" "$out" "added Onboarding.png" expect "design-compare: changed (name with spaces)" "$out" "changed Profile Edit.png" expect "design-compare: removed" "$out" "removed Settings.png" +# --- folder-imports.sh (#116) --------------------------------------------------- +out=$(cd "$APP" && bash "$SCRIPTS/folder-imports.sh" 2>&1) +expect "folder-imports: models folder importing SwiftUI is seen" "$out" "App/Models SwiftUI 1" +expect "folder-imports: folder with spaces keeps its name" "$out" "Watch App/Views CloudKit 1" +expect "folder-imports: @preconcurrency import counted" "$out" "App/Services CloudKit 1" +expect "folder-imports: 'import struct Foundation.URL' is Foundation" "$out" "App/Services Foundation 1" +expect "folder-imports: direct API use without its own import" "$out" "App/Services api:URLSession 1" +printf '%s' "$out" | grep -q "App/Models api:URLSession" && bad "folder-imports: an API named in a comment was counted" || ok "folder-imports: API named in a comment ignored" +printf '%s' "$out" | grep -q "StoreKit" && bad "folder-imports: a commented-out import was counted" || ok "folder-imports: commented-out import ignored" +printf '%s' "$out" | grep -q "AppTests" && bad "folder-imports: test folder included" || ok "folder-imports: test folders skipped" +out=$(cd "$APP" && bash "$SCRIPTS/folder-imports.sh" --files CloudKit 2>&1) +[ "$out" = "$(printf 'App/Services/Sync Service.swift\nWatch App/Views/Home View.swift')" ] && ok "folder-imports --files: exact file list, spaces kept" || bad "folder-imports --files: got: $out" +printf 'import SwiftUI\n' > "$APP/App/Views/Draft.swift" +expect "folder-imports: new uncommitted files included" "$(cd "$APP" && bash "$SCRIPTS/folder-imports.sh")" "App/Views SwiftUI 2" +rm "$APP/App/Views/Draft.swift" + # --- expect-red.sh (#111) -------------------------------------------------------- R="$WORK/red"; mkdir -p "$R/tests" ( cd "$R" && git init -q && git config user.email t@t && git config user.name t \ @@ -120,6 +136,8 @@ out=$(cd "$R" && bash "$SCRIPTS/expect-red.sh" --swap calc.sh 'echo' 'true' -- b [ $rc = 2 ] && ok "expect-red: --swap text found twice is refused" || bad "expect-red: ambiguous --swap wanted exit 2, got $rc: $out" out=$(cd "$R" && bash "$SCRIPTS/expect-red.sh" -- sh -c 'echo "/x/Foo.swift:3:5: error: cannot find Bar in scope"; exit 1'); rc=$? [ $rc = 3 ] && ok "expect-red: compile error is NO-BUILD, not red" || bad "expect-red: compile error wanted exit 3, got $rc: $out" +out=$(cd "$R" && bash "$SCRIPTS/expect-red.sh" --no-build-check -- sh -c 'echo "/x/Note.swift:2:1: error: Models must not import SwiftUI (folder_rule)"; exit 2'); rc=$? +[ $rc = 0 ] && ok "expect-red: --no-build-check reads a lint break as red" || bad "expect-red: lint break wanted exit 0, got $rc: $out" out=$(cd "$R" && bash "$SCRIPTS/expect-red.sh" -- sh -c 'echo "/x/FooTests.swift:12: error: -[FooTests testA] : XCTAssertEqual failed"; exit 1'); rc=$? [ $rc = 0 ] && ok "expect-red: failed assertion is red" || bad "expect-red: assertion failure wanted exit 0, got $rc: $out" out=$(cd "$R" && bash "$SCRIPTS/expect-red.sh" -- sh -c 'echo "Executed 0 tests, with 0 failures"; exit 0'); rc=$? diff --git a/templates/_scripts/expect-red.sh b/templates/_scripts/expect-red.sh index d99d25d..8797595 100755 --- a/templates/_scripts/expect-red.sh +++ b/templates/_scripts/expect-red.sh @@ -9,6 +9,9 @@ # in the copy, replace the exact text OLD (must occur once) # with NEW (verify: a planted bug, run against the finished code) # --patch FILE apply this diff to the copy first (same use as --swap) +# --no-build-check +# the command isn't a compiler (e.g. swiftlint, whose rule +# breaks look like compiler errors): any failure is RED # Run from the project root. The copy is removed afterwards, whatever happens. # # Prints one line and exits: @@ -18,7 +21,7 @@ # 3 NO-BUILD code didn't compile (fine for a brand-new type in build; # a planted bug must compile, so pick another in verify) set -u -ref=HEAD; patch=""; log=""; copies=(); swaps=() +ref=HEAD; patch=""; log=""; copies=(); swaps=(); buildcheck=1 while [ $# -gt 0 ]; do case "$1" in --at) ref="$2"; shift 2 ;; @@ -26,6 +29,7 @@ while [ $# -gt 0 ]; do --swap) [ $# -ge 4 ] || { echo "SETUP: --swap needs PATH OLD NEW"; exit 2; }; swaps+=("$2" "$3" "$4"); shift 4 ;; --patch) patch="$2"; shift 2 ;; --log) log="$2"; shift 2 ;; + --no-build-check) buildcheck=0; shift ;; --) shift; break ;; *) echo "usage: expect-red.sh [--at REF] [--copy PATH]... [--swap PATH OLD NEW] [--patch FILE] [--log FILE] -- TEST-COMMAND..." >&2; exit 2 ;; esac @@ -64,7 +68,7 @@ done code=$? # A compiler error has file:line:column; a failed XCTest assertion has only file:line. -if grep -qE '\*\* BUILD FAILED \*\*|\.swift:[0-9]+:[0-9]+: error:|error: compile command failed' "$log"; then +if [ "$buildcheck" = 1 ] && grep -qE '\*\* BUILD FAILED \*\*|\.swift:[0-9]+:[0-9]+: error:|error: compile command failed' "$log"; then echo "NO-BUILD (log: $log)"; exit 3 fi if grep -qE 'Executed 0 tests|0 tests in 0 suites|No matching test cases' "$log"; then diff --git a/templates/_scripts/folder-imports.sh b/templates/_scripts/folder-imports.sh new file mode 100755 index 0000000..0ccf539 --- /dev/null +++ b/templates/_scripts/folder-imports.sh @@ -0,0 +1,53 @@ +#!/bin/bash +# folder-imports.sh → which frameworks each folder uses +# folder-imports.sh --files X → the files that use X +# +# Used by /apple:map to suggest "must not" folder rules (#116). Run from the +# project root. Shipping code only: test folders, Pods, .build, DerivedData +# and generated code are skipped. +# +# Table output, one line per folder and framework, tab-separated: +# folder name files +# name is an imported module (SwiftUI, CloudKit, StoreKit, …) or a direct API +# use that needs no import of its own: api:URLSession, api:CKContainer, +# api:CKDatabase, api:Product.purchase, api:AppStore.sync. Commented-out +# lines don't count. Files at the root are folder ".". +set -u +mode=table; want="" +if [ "${1:-}" = "--files" ]; then + [ $# -eq 2 ] || { echo "usage: folder-imports.sh [--files NAME]" >&2; exit 2; } + mode=files; want="$2" +fi + +if git rev-parse --is-inside-work-tree >/dev/null 2>&1; then + git -c core.quotepath=off ls-files --cached --others --exclude-standard -- '*.swift' | sort -u +else + find . -name '*.swift' -type f | sed 's|^\./||' +fi | grep -vE '(^|/)[^/]*Tests?/|(^|/)(Pods|\.build|DerivedData|Generated|build)/' > "${TMPDIR:-/tmp}/fi.$$" + +while IFS= read -r f; do + [ -f "$f" ] || continue + d=$(dirname "$f") + awk -v d="$d" -v f="$f" ' + /^[[:space:]]*\/\// { next } + /^[[:space:]]*(@[A-Za-z_]+[[:space:]]+)*import[[:space:]]/ { + s = $0 + sub(/^[[:space:]]*(@[A-Za-z_]+[[:space:]]+)*import[[:space:]]+/, "", s) + if (s ~ /^(struct|class|enum|protocol|typealias|func|var|let)[[:space:]]/) sub(/^[a-z]+[[:space:]]+/, "", s) + split(s, a, /[.[:space:]]/); seen[a[1]] = 1 + } + /URLSession/ { seen["api:URLSession"] = 1 } + /CKContainer/ { seen["api:CKContainer"] = 1 } + /CKDatabase/ { seen["api:CKDatabase"] = 1 } + /Product[^ ]*\.purchase|\.purchase\(/ { seen["api:Product.purchase"] = 1 } + /AppStore\.sync/ { seen["api:AppStore.sync"] = 1 } + END { for (n in seen) print d "\t" n "\t" f } + ' "$f" +done < "${TMPDIR:-/tmp}/fi.$$" > "${TMPDIR:-/tmp}/fi.$$.out" + +if [ "$mode" = files ]; then + awk -F'\t' -v w="$want" '$2 == w { print $3 }' "${TMPDIR:-/tmp}/fi.$$.out" | sort +else + awk -F'\t' '{ c[$1 "\t" $2]++ } END { for (k in c) print k "\t" c[k] }' "${TMPDIR:-/tmp}/fi.$$.out" | sort +fi +rm -f "${TMPDIR:-/tmp}/fi.$$" "${TMPDIR:-/tmp}/fi.$$.out" diff --git a/tests/fixtures/app/App/Models/Note.swift b/tests/fixtures/app/App/Models/Note.swift new file mode 100644 index 0000000..e9d31a0 --- /dev/null +++ b/tests/fixtures/app/App/Models/Note.swift @@ -0,0 +1,7 @@ +import Foundation +import SwiftUI + + // Models never call URLSession: the sync service does (a comment, never counted) +struct Note { + var title: String +} diff --git a/tests/fixtures/app/App/Services/Sync Service.swift b/tests/fixtures/app/App/Services/Sync Service.swift new file mode 100644 index 0000000..7f45763 --- /dev/null +++ b/tests/fixtures/app/App/Services/Sync Service.swift @@ -0,0 +1,8 @@ +// import StoreKit is not allowed here (a comment, never counted) +@preconcurrency import CloudKit +import struct Foundation.URL + +final class SyncService { + let container = CKContainer.default() + func fetch() async throws { _ = try await URLSession.shared.data(from: URL(string: "https://example.com")!) } +} diff --git a/tests/fixtures/app/Watch App/Views/Home View.swift b/tests/fixtures/app/Watch App/Views/Home View.swift index a6de7e7..2ede255 100644 --- a/tests/fixtures/app/Watch App/Views/Home View.swift +++ b/tests/fixtures/app/Watch App/Views/Home View.swift @@ -1,4 +1,5 @@ import SwiftUI +import CloudKit struct HomeView: View { var body: some View {