From fea79926544de4a299d5c2147af1e902411e7555 Mon Sep 17 00:00:00 2001 From: Fernando Fernandes Date: Fri, 6 Nov 2026 23:45:36 +0100 Subject: [PATCH 1/3] Squashed 'AgentGuidelines/' changes from 94421d6..1c95766 1c95766 Add versioned Codex review policy and review-only adoption (#57) 2dd4e5e Use active runner toolchains and clarify package badges (0.0.46) (#56) df2b521 Add Apple-native networking policy and prepare 0.0.45 (#55) fee5191 Add xcode-upgrade skill and prepare 0.0.44 (#54) 836c993 Document tvOS current-user CloudKit diagnosis (#53) 77ff8bc Align Reduce Motion policy and support claims with Apple criteria (#52) 80e0a9e Guide smooth SwiftUI interactions and efficient image rendering (#51) a14a901 Preserve Apple control placement and add guidance update workflow (#50) 21f579c Document Device Hub and physical-device verification (#49) 3a3f970 Guide size-based ScrollView bounce behavior (#48) dc26d7c Require native SwiftUI components and presentation lifecycle audit (#47) aa5f04b Define native SwiftUI animation policy for 0.0.36 (#45) fa2f6d1 Require evidence and bounded monitoring for Codex reviews (#44) 51fbe8c Require unique package emojis (#42) 1e053ee Add Swift package compiler settings parity (#41) 7d766ec Require lifecycle observability (#40) 33668ef Add private repository workflow authentication (#39) 21fcef9 Release agent-guidelines 0.0.30 (#38) 01b89b2 Add shared gitignore and tooling policy (#37) f17fb0d Add shared App Store synchronization guidance (#36) 57b29f6 Preserve GitHub alerts in Markdown audit (#35) b065e23 Replace repository automation with native Swift (#33) 6460f45 Require String Catalog editor evidence in audits (#32) 103f092 Release agent guidelines 0.0.25 (#31) e10f1a9 Add external dependency policy (#30) 4dccb71 Strengthen documentation maintenance audits (#29) 6e57dbf Require AppLogger integration audits (#28) f2fe3a8 Clarify Codex review budget (#27) a36b756 Release agent-guidelines 0.0.20 (#26) 8276c92 Document squash merge default (#25) efc4740 Add canonical package badge examples (#24) git-subtree-dir: AgentGuidelines git-subtree-split: 1c957669005eea010131c53f0a4146db2ccf7859 --- .agents/skills/agent-guidelines-audit | 1 - .../skills/agent-guidelines-audit/SKILL.md | 284 ++++ .../agent-guidelines-audit/agents/openai.yaml | 0 .../scripts/check_markdown_wrapping.swift | 261 ++++ .../scripts/check_xcstrings_inspection.swift | 260 ++++ .../skills/update-agent-guidelines/SKILL.md | 42 + .agents/skills/xcode-upgrade/SKILL.md | 51 + .editorconfig | 1 - .gitattributes | 2 - .../actions/codex-review-policy/action.yml | 15 + .github/workflows/ci-pr.yml | 45 - .github/workflows/ci.yml | 45 +- .github/workflows/nightly.yml | 31 - .github/workflows/release.yml | 125 +- .gitignore | 67 +- .swift-format | 1 - AGENTS.md | 119 +- .../skills/agent-guidelines-audit/SKILL.md | 73 - AgentGuidelines/.github/workflows/ci.yml | 23 - AgentGuidelines/.github/workflows/release.yml | 44 - AgentGuidelines/.gitignore | 3 - AgentGuidelines/AGENTS.md | 75 - AgentGuidelines/CHANGELOG.md | 168 --- AgentGuidelines/Guidelines/CICD.md | 63 - AgentGuidelines/Guidelines/Development.md | 32 - AgentGuidelines/Guidelines/Documentation.md | 40 - .../Guidelines/GitHub/PullRequests.md | 178 --- AgentGuidelines/Guidelines/Packages.md | 105 -- .../Guidelines/Swift/Localization.md | 43 - AgentGuidelines/Guidelines/Swift/SwiftUI.md | 63 - AgentGuidelines/LICENSE | 22 - AgentGuidelines/README.md | 174 --- .../Scripts/validate_consumer_setup.py | 304 ---- .../Scripts/validate_guidelines.py | 349 ----- AgentGuidelines/Templates/AGENTS.md | 74 - .../Templates/GlobalCodexInstructions.md | 30 - .../Tests/test_validate_consumer_setup.py | 253 ---- .../Tests/test_validate_guidelines.py | 144 -- AgentGuidelines/VERSION | 1 - CHANGELOG.md | 420 ++++++ .../Swift/.editorconfig | 0 .../Swift/.swift-format | 0 .../AgentWorkflow.md | 0 Guidelines/AppStore.md | 42 + .../Architecture/Redux.md | 2 +- Guidelines/CICD.md | 124 ++ Guidelines/Development.md | 60 + Guidelines/Documentation.md | 78 + Guidelines/Git/IgnoreFiles.md | 15 + .../Git/Repositories.md | 0 Guidelines/GitHub/PullRequests.md | 86 ++ Guidelines/Localization.md | 94 ++ .../Guidelines => Guidelines}/Logging.md | 2 + Guidelines/Networking.md | 65 + Guidelines/Packages.md | 174 +++ .../Guidelines => Guidelines}/Swift/Swift.md | 1 + .../Swift/SwiftFormat.md | 0 .../Swift/SwiftStyle.md | 0 Guidelines/Swift/SwiftUI.md | 150 ++ .../Testing/UnitTesting.md | 2 + Guidelines/Xcode/DeviceInteraction.md | 109 ++ .../Guidelines => Guidelines}/Xcode/MCP.md | 15 +- Guidelines/Xcode/ProjectSettings.md | 80 + .../Xcode/Security.md | 2 +- LICENSE | 1 + Package.resolved | 33 - Package.swift | 44 - README.md | 361 +++-- ReviewPolicy/Policy.md | 21 + ReviewPolicy/README.md | 38 + ReviewPolicy/VERSION | 1 + Scripts/prepare_localizable_symbols.swift | 236 +++ .../Scripts => Scripts}/swift_format.sh | 0 Scripts/sync_codex_review_policy.swift | 283 ++++ Scripts/validate_consumer_setup.swift | 474 ++++++ Scripts/validate_guidelines.swift | 1145 +++++++++++++++ Scripts/validate_string_catalogs.swift | 421 ++++++ Sources/ProgressionKit/PKConfig.swift | 47 - Sources/ProgressionKit/PKEngine.swift | 122 -- Sources/ProgressionKit/PKEvent.swift | 35 - Sources/ProgressionKit/PKLogging.swift | 42 - Sources/ProgressionKit/PKProfile.swift | 23 - Sources/ProgressionKit/PKTierProgress.swift | 14 - Sources/ProgressionKit/PKTrackProgress.swift | 23 - Sources/ProgressionKit/PKUpdate.swift | 47 - .../ProgressionKit.docc/ProgressionKit.md | 69 - Sources/ProgressionKit/ProgressionKit.swift | 1 - Templates/.gitignore | 66 + Templates/AGENTS.md | 132 ++ Templates/GlobalCodexInstructions.md | 19 + .../Templates => Templates}/Store.swift | 0 .../ProgressionKitTests/PKLoggingTests.swift | 101 -- .../ProgressionKitTests.swift | 197 --- Tests/run_review_policy_tests.swift | 250 ++++ Tests/run_tests.swift | 1281 +++++++++++++++++ VERSION | 1 + 96 files changed, 7125 insertions(+), 3535 deletions(-) delete mode 120000 .agents/skills/agent-guidelines-audit create mode 100644 .agents/skills/agent-guidelines-audit/SKILL.md rename {AgentGuidelines/.agents => .agents}/skills/agent-guidelines-audit/agents/openai.yaml (100%) create mode 100755 .agents/skills/agent-guidelines-audit/scripts/check_markdown_wrapping.swift create mode 100755 .agents/skills/agent-guidelines-audit/scripts/check_xcstrings_inspection.swift create mode 100644 .agents/skills/update-agent-guidelines/SKILL.md create mode 100644 .agents/skills/xcode-upgrade/SKILL.md delete mode 120000 .editorconfig delete mode 100644 .gitattributes create mode 100644 .github/actions/codex-review-policy/action.yml delete mode 100644 .github/workflows/ci-pr.yml delete mode 100644 .github/workflows/nightly.yml delete mode 120000 .swift-format delete mode 100644 AgentGuidelines/.agents/skills/agent-guidelines-audit/SKILL.md delete mode 100644 AgentGuidelines/.github/workflows/ci.yml delete mode 100644 AgentGuidelines/.github/workflows/release.yml delete mode 100644 AgentGuidelines/.gitignore delete mode 100644 AgentGuidelines/AGENTS.md delete mode 100644 AgentGuidelines/CHANGELOG.md delete mode 100644 AgentGuidelines/Guidelines/CICD.md delete mode 100644 AgentGuidelines/Guidelines/Development.md delete mode 100644 AgentGuidelines/Guidelines/Documentation.md delete mode 100644 AgentGuidelines/Guidelines/GitHub/PullRequests.md delete mode 100644 AgentGuidelines/Guidelines/Packages.md delete mode 100644 AgentGuidelines/Guidelines/Swift/Localization.md delete mode 100644 AgentGuidelines/Guidelines/Swift/SwiftUI.md delete mode 100644 AgentGuidelines/LICENSE delete mode 100644 AgentGuidelines/README.md delete mode 100755 AgentGuidelines/Scripts/validate_consumer_setup.py delete mode 100644 AgentGuidelines/Scripts/validate_guidelines.py delete mode 100644 AgentGuidelines/Templates/AGENTS.md delete mode 100644 AgentGuidelines/Templates/GlobalCodexInstructions.md delete mode 100644 AgentGuidelines/Tests/test_validate_consumer_setup.py delete mode 100644 AgentGuidelines/Tests/test_validate_guidelines.py delete mode 100644 AgentGuidelines/VERSION create mode 100644 CHANGELOG.md rename {AgentGuidelines/Configurations => Configurations}/Swift/.editorconfig (100%) rename {AgentGuidelines/Configurations => Configurations}/Swift/.swift-format (100%) rename {AgentGuidelines/Guidelines => Guidelines}/AgentWorkflow.md (100%) create mode 100644 Guidelines/AppStore.md rename {AgentGuidelines/Guidelines => Guidelines}/Architecture/Redux.md (99%) create mode 100644 Guidelines/CICD.md create mode 100644 Guidelines/Development.md create mode 100644 Guidelines/Documentation.md create mode 100644 Guidelines/Git/IgnoreFiles.md rename {AgentGuidelines/Guidelines => Guidelines}/Git/Repositories.md (100%) create mode 100644 Guidelines/GitHub/PullRequests.md create mode 100644 Guidelines/Localization.md rename {AgentGuidelines/Guidelines => Guidelines}/Logging.md (86%) create mode 100644 Guidelines/Networking.md create mode 100644 Guidelines/Packages.md rename {AgentGuidelines/Guidelines => Guidelines}/Swift/Swift.md (94%) rename {AgentGuidelines/Guidelines => Guidelines}/Swift/SwiftFormat.md (100%) rename {AgentGuidelines/Guidelines => Guidelines}/Swift/SwiftStyle.md (100%) create mode 100644 Guidelines/Swift/SwiftUI.md rename {AgentGuidelines/Guidelines => Guidelines}/Testing/UnitTesting.md (96%) create mode 100644 Guidelines/Xcode/DeviceInteraction.md rename {AgentGuidelines/Guidelines => Guidelines}/Xcode/MCP.md (75%) create mode 100644 Guidelines/Xcode/ProjectSettings.md rename {AgentGuidelines/Guidelines => Guidelines}/Xcode/Security.md (94%) delete mode 100644 Package.resolved delete mode 100644 Package.swift create mode 100644 ReviewPolicy/Policy.md create mode 100644 ReviewPolicy/README.md create mode 100644 ReviewPolicy/VERSION create mode 100755 Scripts/prepare_localizable_symbols.swift rename {AgentGuidelines/Scripts => Scripts}/swift_format.sh (100%) create mode 100755 Scripts/sync_codex_review_policy.swift create mode 100755 Scripts/validate_consumer_setup.swift create mode 100755 Scripts/validate_guidelines.swift create mode 100755 Scripts/validate_string_catalogs.swift delete mode 100644 Sources/ProgressionKit/PKConfig.swift delete mode 100644 Sources/ProgressionKit/PKEngine.swift delete mode 100644 Sources/ProgressionKit/PKEvent.swift delete mode 100644 Sources/ProgressionKit/PKLogging.swift delete mode 100644 Sources/ProgressionKit/PKProfile.swift delete mode 100644 Sources/ProgressionKit/PKTierProgress.swift delete mode 100644 Sources/ProgressionKit/PKTrackProgress.swift delete mode 100644 Sources/ProgressionKit/PKUpdate.swift delete mode 100644 Sources/ProgressionKit/ProgressionKit.docc/ProgressionKit.md delete mode 100644 Sources/ProgressionKit/ProgressionKit.swift create mode 100644 Templates/.gitignore create mode 100644 Templates/AGENTS.md create mode 100644 Templates/GlobalCodexInstructions.md rename {AgentGuidelines/Templates => Templates}/Store.swift (100%) delete mode 100644 Tests/ProgressionKitTests/PKLoggingTests.swift delete mode 100644 Tests/ProgressionKitTests/ProgressionKitTests.swift create mode 100755 Tests/run_review_policy_tests.swift create mode 100755 Tests/run_tests.swift create mode 100644 VERSION diff --git a/.agents/skills/agent-guidelines-audit b/.agents/skills/agent-guidelines-audit deleted file mode 120000 index 9e33ff8..0000000 --- a/.agents/skills/agent-guidelines-audit +++ /dev/null @@ -1 +0,0 @@ -../../AgentGuidelines/.agents/skills/agent-guidelines-audit \ No newline at end of file diff --git a/.agents/skills/agent-guidelines-audit/SKILL.md b/.agents/skills/agent-guidelines-audit/SKILL.md new file mode 100644 index 0000000..f0ecbce --- /dev/null +++ b/.agents/skills/agent-guidelines-audit/SKILL.md @@ -0,0 +1,284 @@ +--- +name: agent-guidelines-audit +description: Audit completed repository work and checked-in consumer integration against applicable agent-guidelines, local AGENTS.md instructions, requested scope, and declared validation workflow. Use after implementing changes and before claiming completion, handing work to the user, preparing, opening, or updating a pull request, declaring merge readiness, or preparing a release. Do not use for simple answers, read-only exploration, or work that is still actively being implemented. +--- + +# Agent Guidelines Audit + +Perform a final, evidence-based compliance pass. Treat the applicable guidelines and local instructions as the source of truth; do not duplicate their full content in this skill. + +## Establish the audit scope + +1. Re-read the user request and list every requested outcome and explicit constraint. +2. Locate the repository root and every applicable `AGENTS.md` from the current directory to that root. +3. Read the shared guides referenced by those instructions that apply to the changed files and workflow. +4. Inspect `git status`, the complete diff, and relevant untracked files. Preserve unrelated user changes. +5. Check the consumer's `AgentGuidelines/VERSION` and provenance when the task changes or depends on the synchronized subtree. Do not update it implicitly. +6. When the repository contains an `AgentGuidelines/` subtree, run `AgentGuidelines/Scripts/validate_consumer_setup.swift` from the consumer root. The validator detects Swift-format adoption from the root `AGENTS.md`; add `--require-swift-format` only when the repository must adopt it before that link is present. Treat failures as integration drift to fix or report before handoff. +7. Audit the root `.gitignore` against the shared [Git ignore guide](../../../Guidelines/Git/IgnoreFiles.md) and [`Templates/.gitignore`](../../../Templates/.gitignore). Compare active patterns rather than comments, blank lines, section order, or duplicates. When implementation is authorized, add every missing non-conflicting shared pattern using the template spelling, then verify its effect with `git check-ignore -v` and inspect matching tracked files with `git ls-files`; do not untrack files merely because a new rule matches them. Preserve rule order and negation semantics, and report a conflict instead of silently changing behavior. Treat an active pattern absent from the template as project-specific: accept it only when an adjacent `# Project-specific: ` comment contains a concrete non-placeholder repository-owner-approved rationale. Otherwise report the exact extra pattern and ask the repository owner to choose between updating agent-guidelines or documenting it locally; do not remove, rewrite, or silently approve it. A missing root `.gitignore`, an unresolved missing shared pattern, or an undecided undocumented extra pattern blocks audit completion. + +Do not inspect or require the user's global Codex instructions. They are user-level state outside the repository audit boundary; validate the checked-in root `AGENTS.md` contract instead. + +## Audit the implementation + +Review the actual change rather than only checking whether files exist: + +- Confirm every requested outcome is implemented and no material behavior was dropped. +- Confirm physical folders, familiar domain grouping, filenames, declaration order, type ownership, namespacing, documentation, and `MARK` organization follow the applicable guides. Distinguish values that describe data from tools that primarily execute algorithms or accumulate behavior. +- For Redux applications, trace actions, state, reducers, middleware, services, tools, presentation models, views, and side-effect results through the complete data flow. Confirm each Redux component folder contains only that component type. +- Check that framework objects, persistence, logging, and asynchronous work remain in their allowed boundaries. +- Perform the mandatory [networking check](#audit-networking) for network implementation, dependency changes, and networking-policy adoption. +- Check SwiftUI composition, narrow inputs, local versus durable state, localization, accessibility, and safe deterministic previews where applicable. +- For each new or changed SwiftUI `ScrollView`, apply the shared [scrolling guidance](../../../Guidelines/Swift/SwiftUI.md#scrolling): verify `.scrollBounceBehavior(.basedOnSize)` covers its scrolling axes on supported deployment targets, including scroll views in modal sheets. Check the modifier's environment scope around nested scrollables and require a documented interaction reason for a different bounce behavior. +- Perform the mandatory [native-component and presentation decision check](#audit-native-components-and-presentation) for changed SwiftUI controls and presentation behavior. +- Perform the mandatory [system-control placement check](#audit-system-control-placement) for changed navigation, toolbars, dismissal controls, and window chrome, including affected UIKit/AppKit wrappers. +- Perform the mandatory [animation and image-rendering check](#audit-animation-and-image-rendering) for changed visual transitions, reusable control styles, and dynamic image paths, including directly affected consumers. +- Perform the [Reduce Motion check](#audit-reduce-motion) for affected motion and for Reduced Motion support declarations. +- Perform the [tvOS current-user identity check](#audit-tvos-current-user-identity) when changed behavior relies on selected-profile preferences, CloudKit accounts, or personal store binding. +- Check tests for the required framework, mirrored paths, shared tags, Given/When/Then structure, deterministic seams, and coverage of changed behavior and failure paths. +- Trace every new or changed stateful, asynchronous, fallible, or lifecycle-oriented behavior and verify that its owning artifact emits privacy-safe AppLogger events for the meaningful success, failure, cancellation, recovery, and state-transition outcomes needed to diagnose it. Dependency declaration and target linkage alone do not establish logging coverage. Accept silence for pure values or utilities only when there is no meaningful event boundary and the implementation handoff records that deliberate decision. +- Check logging ownership, subsystem, categories, emoji, privacy, severity, metadata stability, noise controls, and focused formatter or sink tests when logging changed. +- For every in-scope package that emits logs, resolve its canonical emoji from local instructions or documentation and the package list on the current `main` branch of the [ThatFactory Swift Package Collection](https://github.com/thatfactory/swift-package-collection). Enumerate the registered package entries and require each canonical emoji to identify exactly one package, treating visually identical presentation-selector variants as a collision. Confirm the package documentation, package-local logging gateway, and registry entry use the same emoji. When creating a package or assigning or changing its emoji, verify the intended emoji is unused before accepting it and require the registry update in the publication work. A collision, a missing registry entry for a published package, an unreachable current registry, or disagreement among these sources blocks audit completion and release readiness. +- For every Apple-platform application or Swift package in scope, except the AppLogger provider repository itself, verify integration with the shared [Logging guide](../../../Guidelines/Logging.md): confirm the AppLogger dependency is declared, the `AppLogger` library product is linked to every target that emits diagnostics, and any new project has it available in its primary runtime target before its first log call. Search the actual package or Xcode dependency graph rather than relying on an `import` alone, and treat `print`, direct `Logger` instances, or duplicate logging backends as incomplete integration when they emit project diagnostics. When implementation is authorized, add or repair the dependency and target linkage and migrate affected calls while preserving the guide's ownership, subsystem, category, emoji, privacy, severity, and noise rules; report an exact blocker when target or platform constraints make safe integration ambiguous. +- Inspect dependency manifests, resolver or lock files, Xcode package references, vendored source or binary frameworks, and equivalent dependency declarations. Compare the change with the baseline and identify every new third-party dependency or expansion of an existing third-party dependency into a new target or runtime role. Apply the shared [external dependency policy](../../../Guidelines/Development.md#external-dependencies): verify any explicit standing approval covers the exact dependency and role; otherwise require explicit repository-owner approval before the dependency is introduced and require the durable exception record in repository documentation. Do not infer approval merely from an execution plan, pull-request description, implementation convenience, package popularity, or the dependency already appearing in the diff. Treat an unapproved or undocumented third-party dependency as a blocker to completion. Do not flag Apple system frameworks, the Swift standard library, ThatFactory-owned packages, or guideline-mandated tooling used only for its documented tooling role. Apply the [networking standing approval](../../../Guidelines/Networking.md#standing-dependency-approval) only within its documented scope. If a newly resolved transitive third-party package will be linked into or shipped with the product, verify that its owning direct dependency is covered by an approved role and the transitive package fits that role rather than dismissing it solely because it is transitive. +- Search dependency manifests, generated directories, project files, and documentation for CocoaPods or Carthage adoption. The shared [external dependency policy](../../../Guidelines/Development.md#external-dependencies) forbids both without an exception path and requires Swift Package Manager for package dependencies. When implementation is authorized, remove newly introduced adoption and its generated or configuration files; report pre-existing adoption as a completion blocker when safe migration is outside the task scope. +- Check package configuration, CI/CD, Xcode project configuration, security-sensitive changes, and physical-device limitations when they are in scope. For every Xcode project, perform the project-settings audit below. Compare documented Swift and concurrency settings with the effective application and test-target settings; flag both redundant isolation annotations and missing annotations at compiler-verified boundaries. +- Search for stale type names, superseded files, direct APIs forbidden by the new architecture, empty folders, and references to removed behavior. +- Apply the shared [CI/CD guide](../../../Guidelines/CICD.md) to workflow and repository-automation changes. Search scripts, generated directories, workflow files, and documentation for fastlane adoption and treat it as forbidden without an exception path. Require focused ThatFactory tooling or repository-owned Swift scripts for CI/CD and delivery, and inspect new repository-owned executable scripts for compliance. For Swift-focused applications, games, and packages, accept Python or POSIX shell only when durable repository documentation identifies the missing Swift capability, exact script and task scope, runtime and dependency requirements, security and maintenance impact, validation method, and revisit or removal condition. Reject convenience, familiarity, shorter code, an existing interpreter, or another non-Swift script as justification. Treat every exception as narrow; the central `Scripts/swift_format.sh` wrapper is the retained documented exception for invoking Xcode's `swift-format` modes. +- For pull-request or merge readiness, apply the root review and lifecycle contracts and [review-policy integration](../../../ReviewPolicy/README.md). Rerun the latest published policy check immediately before merge. Require a completed initial Codex review for its recorded head, or that review plus a recorded locally verified remediation-only delta; do not claim the newer head was bot-reviewed. Confirm no allowed review is pending, every thread is dispositioned and resolved, and no unresolved P0/P1 blocker remains. Treat P2/P3 observations as non-blocking and never request another review unless the owner explicitly authorizes it. Review-only adoption enforces only these contracts, not unrelated engineering audits. + +## Audit runner toolchains + +Apply the [runner toolchain policy](../../../Guidelines/CICD.md#runner-toolchain) when reviewing or changing Apple build automation, adopting that policy, or performing an Xcode upgrade: + +1. Inspect every applicable workflow and its invoked scripts, setup actions, environment overrides, and runner labels. Search for Xcode/Swift version comparisons, build-number checks, allowlists, upper bounds, and versioned installation paths; inspecting workflow YAML alone is insufficient when a script performs the check. +2. Verify ordinary CI uses and logs the runner's active toolchain. Distinguish version pins from minimum package tools versions, Swift language modes, SDK/deployment requirements, simulator destinations, and actual capability/readiness checks. A documented historical test version and a process-scoped selection for an explicit upgrade are not permanent CI constraints. +3. For each retained pin, inspect the canonical guide's required repository exception and evidence. Do not invent a compatibility reason or treat the previous upgrade target as one. When implementation is authorized, remove unjustified pins and reconcile current setup documentation; in review-only work, report their locations and missing justification. An unjustified pin in scope prevents audit completion. +4. Run affected toolchain reporting and the repository's build/test validation with the active installation. Record the selected Xcode/Swift versions, commands, outcomes, and any justified exception. Do not claim compatibility with untested future releases; removing a string check ensures those releases reach real validation. + +| Scenario | Audit outcome | +| --- | --- | +| New runner Xcode passes compilation and tests, but an old equality check fails | Remove the unjustified check and rerun affected validation | +| Workflow accepts the runner, but its invoked script requires one build number | Treat the script as the same pin and require removal or a documented exception | +| A supported package declares its minimum Swift tools version and language mode | Preserve the capability requirements | +| An exact toolchain has a documented incompatibility or external requirement with evidence and a revisit condition | Accept only the scoped exception and report it | + +## Audit Swift package badges + +When creating or changing a Swift package README, adopting the badge policy, or auditing package documentation, inspect the actual README badge URLs and labels against [README badges](../../../Guidelines/Packages.md#readme-badges). Omit Updated/last-commit-date and Revision/latest-release-version badges unless the repository documents the guide's specific exception. Distinguish release-version endpoints from Release/publishing workflow-status badges; keep the latter when they describe the package's own workflow. A Release label alone does not identify which kind it is. + +For authorized implementation, remove unjustified date/version badges and correct affected documentation; for review-only work, report the badge and missing rationale. An undocumented date/version badge in scope prevents audit completion. Record the inspected README, retained workflow-status badges, and any accepted exception. Do not create badges or release workflows solely to fill an inapplicable slot. + +## Audit networking + +Apply [Networking](../../../Guidelines/Networking.md) to Apple-platform applications, games, and Swift packages: + +1. Identify changed networking, dependency declarations, and directly affected existing request paths. On first adoption of this networking policy, inventory all existing network implementations and dependencies. For unrelated changes, do not expand into a whole-repository migration. Record evidence-backed `not applicable` when there is no networking in scope, or distinguish non-HTTP and framework-owned traffic from owned HTTP. +2. Inspect actual transport calls, request construction, response handling, package manifests, resolver files, Xcode product references, and target linkage. For owned HTTP, verify `HTTPTypes` and `HTTPTypesFoundation` from Apple's `swift-http-types` are available to the appropriate targets and that requests, responses, methods, header fields/names, and statuses use the guide's typed representations with native `URLSession`. Dependency presence or imports alone do not establish compliance. Verify the selected release and compatibility evidence against supported platforms and toolchains. +3. Inspect native Foundation bridges in context. Require the native API reason, conversions at that boundary, failure handling, and retained typed request/response ownership. Accept non-HTTP Apple APIs and framework-owned traffic without artificial HTTP wrappers. Search directly affected code for parallel string/integer HTTP models and hidden alternative transports; a first-party wrapper does not exempt its implementation. +4. For an alternative networking dependency, require the guide's demonstrated Apple capability gap, explicit repository-owner approval, durable scoped exception, and validation. An existing dependency is not approval for a new role. For adoption debt outside authorized migration scope, require an explicit owner-approved migration deferral identifying paths, rationale, and follow-up condition; report it as deferred compliance, never full networking compliance. A deferral does not authorize new noncompliant networking. +5. Require the guide's relevant deterministic request/response, status, failure, cancellation, and bridge tests for changed implementation. Record source paths, target/dependency evidence, exceptions or deferrals, commands, and outcomes. Documentation-only policy work uses scenario walkthroughs; do not invent live-network requirements for pure policy changes. +6. Missing typed implementation or native transport in scope, unapproved alternatives, undocumented bridges, unaccounted adoption debt, or missing applicable validation prevents audit completion. Fix authorized in-scope violations; report exact blockers instead of rewriting unrelated consumers. + +Use these scenarios to distinguish valid outcomes: + +| Scenario | Audit outcome | +| --- | --- | +| Owned HTTP uses typed requests/responses and both products at the appropriate targets with `URLSession` | Accept with implementation and validation evidence | +| Dependency/import is present but the service still owns untyped HTTP | Incomplete | +| Native background/delegate API uses a documented, tested Foundation conversion boundary | Accept with retained typed HTTP ownership | +| Only CloudKit, WebKit, or non-HTTP Apple networking is in scope | No artificial HTTP dependency; verify the relevant native boundary | +| Alternative library chosen for convenience, including behind a ThatFactory wrapper | Block until compliant or covered by the capability-gap exception | +| Adoption discovers untouched legacy HTTP | Migrate within scope or record an explicit owner-approved deferral; no full-compliance claim | +| No networking implementation or dependency change, and no policy adoption | Evidence-backed not applicable | + +## Audit native components and presentation + +Apply the authoritative [SwiftUI native-component policy](../../../Guidelines/Swift/SwiftUI.md#native-components-and-presentation) to changed controls and presentation flows: + +1. Inspect changed custom modal hosts, overlay/scrim/offset code, and gesture routing in context. These are investigation signals, not blanket prohibitions on overlays or styling. Include existing hosts directly affected by the change, including discard dialogs; do not assume a native child makes every surrounding presentation compliant. +2. Record the supported interaction, native alternative, deployment-target availability, and who owns presentation and dismissal. Distinguish branded content within a native component from replacing its lifecycle. +3. For each custom equivalent, verify the capability-gap evidence, explicit repository-owner approval, durable consumer exception, and compensating validation required by the policy. A suitable native alternative without the required approved and documented exception blocks audit completion. Do not treat a mockup or unchanged mounted state as approval. +4. Trace child dismissal, parent draft ownership, nested picker/editor presenters, cancellation, and dismissal-completion cleanup through the affected hierarchy and asynchronous work. Confirm that a native nested sheet with branded content is accepted when ownership and evidence satisfy the policy. +5. Require the policy's [interaction evidence](../../../Guidelines/Swift/SwiftUI.md#required-interaction-evidence) for each affected flow. Inspect actual actions and observed outcomes, including recorded manual gesture verification when needed; static screenshots and no-op automation do not establish gesture behavior. Missing relevant runtime evidence blocks audit completion. Record an exact blocker for unavailable verification and include decisions, exception references, and evidence in the handoff. + +## Audit system control placement + +Apply the authoritative [system control placement policy](../../../Guidelines/Swift/SwiftUI.md#system-control-placement): + +1. Identify the owner and intent of each affected Back, Close, Cancel, Done, confirmation, or window control. Trace native toolbar placements and roles, app-authored headers, hidden Back controls, and surrounding system picker/editor presentations. Inspect directly affected existing code as well as added lines. +2. Verify that semantic placement and roles describe the action rather than force a physical side. Treat explicit leading/trailing slots, spacers, offsets, custom headers, and hidden native controls as investigation signals, not blanket failures. For standard controls, require the policy's documented platform reason for explicit placement or its approved capability-gap exception for a custom equivalent. Do not require such an exception for ordinary app-specific content layout that does not replace native system behavior. +3. Accept valid system-selected differences across platforms, OS versions, window sizes, and layout directions. Reject a universal left/right requirement, relocation of system-owned picker/editor controls, or replacement of native Back solely for visual consistency. Check affected design artifacts and durable documentation for conflicting placement mandates. +4. For changed navigation or toolbar behavior, record supported target/OS and targeted runtime actions and outcomes: Back navigates, dismissal closes the intended presentation, and cancellation/confirmation retain their actual semantics. Check relevant layout direction, accessibility, keyboard/remote, and gesture behavior. When presentation lifecycle also changes, apply the existing [interaction evidence requirements](../../../Guidelines/Swift/SwiftUI.md#required-interaction-evidence) to that affected flow. Documentation-only policy changes do not require simulator evidence. +5. An unjustified placement override or missing relevant interaction evidence blocks audit completion. Report the exact control, ownership, violated policy, and missing evidence; do not report an Apple-selected side as a defect. + +## Audit animation and image rendering + +Apply the authoritative [animation policy](../../../Guidelines/Swift/SwiftUI.md#animation) and [image-rendering policy](../../../Guidelines/Swift/SwiftUI.md#image-rendering) to changed components and directly affected consumers; do not expand the audit into unrelated screens. + +1. Identify each meaningful visual transition, its owner, and its intended animation or justified immediate feedback. Inspect stable view identity and transaction scope, including simultaneous changes and surrounding layout animations; an `.animation` modifier alone is not evidence of correct scope. Accept appropriate native feedback without additional animation. +2. Verify reusable defaults without caller-added animation. Exercise enabled to disabled and disabled to enabled, ordinary presses, rapid reversals, and relevant show/hide behavior. Confirm enabled state, hit-testing, accessibility state, and action availability change immediately while appearance animates. +3. Inspect affected image paths for repeated preparation, oversized drawable content, unstable identity, unbounded caches, and stale publication. Verify derivative refresh for changed source or presentation requirements, bounded intermediate memory, preservation of authoritative originals, and rejection of stale results after replacement, cancellation, or removal. Use applicable deterministic tests for asynchronous races alongside interaction evidence. +4. Exercise representative large-image content when images participate in the interaction. For image-related regressions, compare with an image-free scenario and record the actual representation drawn; do not infer a provider defect from the source of one expensive image. +5. Require recorded runtime actions and outcomes for meaningful motion changes: platform/OS, scenario, actions, and observed behavior. Compilation, static screenshots, and idle captures do not prove smooth interaction. Documentation-only policy changes require scenario walkthroughs rather than simulator evidence. +6. For reported stutter, use Apple performance tools where available and authorized. Record the active interaction window, workload, observations, and limitations. Distinguish recorded manual verification from instrumented measurements; an idle capture reporting zero hitches is insufficient. Do not require profiling every cosmetic change or impose a universal frame-rate threshold. +7. Unexplained abrupt transitions in affected reusable controls, demonstrated performance regressions, or missing applicable interaction evidence prevent audit completion. Record the exact component, violated policy, required correction or justified intentional exception, and unavailable evidence. + +Use these scenario walkthroughs when evaluating the check: + +| Scenario | Audit outcome | +| --- | --- | +| Custom main-button style changes colors abruptly | Blocked until shared behavior is corrected or an intentional immediate transition is justified | +| Shared style animates both directions; actions remain immediate | Accepted with runtime evidence, including ordinary presses and rapid reversals | +| Appropriate native control already supplies feedback | Accepted without additional animation | +| Animated thumbnail repeatedly processes a large original | Requires correction and relevant verification | +| Prepared derivative preserves originals and rejects stale results | Accepted with applicable tests and interaction evidence | +| Zero hitches recorded without actual interaction | Insufficient performance evidence; applicable verification remains blocked | + +## Audit Reduce Motion + +Apply the canonical [Reduce Motion policy](../../../Guidelines/Swift/SwiftUI.md#reduce-motion) and its [support declaration requirements](../../../Guidelines/Swift/SwiftUI.md#declaring-support): + +1. For changed motion and directly affected components, identify each potential trigger, its owner, and its chosen adaptation or evidence that no adaptation is needed. Inspect custom styles and surrounding transactions as well as native controls. Do not require removal of harmless feedback or a separate task request for an applicable adaptation. +2. Verify the source of the preference, response to changes during use, and preserved information, functional state, and native accessibility behavior. For an in-app alternative, inspect the consumer's rationale and criteria coverage. Reject blanket suppression that loses meaningful feedback and unresolved problematic motion. +3. Require runtime actions and outcomes with Reduce Motion on and off, plus a preference change while running. Record platform/OS, app revision, scenarios, results, and verification limits. Static screenshots, compilation, an environment read, or the use of a native component alone do not prove support. Accept recorded manual verification when automation cannot exercise the setting; missing applicable evidence blocks completion of the affected work. +4. For an app-wide support declaration, expand the evidence scope to all common tasks on the declared platform, following the linked Apple criteria for content and advertising. Check the consumer evidence and current release scope; withhold or correct unsupported claims. A local component check or guideline adoption is insufficient. Re-evaluate existing declarations during app updates; do not demand an unrelated whole-app audit for an isolated motion change when no declaration is in scope. +5. Documentation-only policy work uses scenario walkthroughs rather than simulator testing. Report the exact trigger, missing evidence, or unsupported declaration that prevents audit completion; do not claim this central audit establishes any consumer app's support. + +| Scenario | Audit outcome | +| --- | --- | +| Decorative depth effect ignores the enabled preference | Blocked until adapted and exercised | +| Informative movement becomes a fade and retains its meaning | Accepted with on/off and live preference-change evidence | +| Native control already adapts correctly | Accepted with interaction evidence; no duplicate guard required | +| Every animation is removed and a status change becomes imperceptible | Blocked until meaningful feedback is restored | +| No problematic motion across evaluated common tasks | Support declaration may pass with platform-specific evidence | +| One compliant component or guideline adoption used to claim app-wide support | Declaration blocked pending common-task evaluation | + +## Audit tvOS current-user identity + +Apply the [tvOS current-user and CloudKit guidance](../../../Guidelines/Xcode/DeviceInteraction.md#tvos-current-user-data-and-cloudkit) only when the change implements or materially affects selected-profile storage, CloudKit account routing, or personal-store transitions on tvOS. Documentation-only work and unrelated UI changes do not require a physical multi-user run. + +For applicable implementation, inspect the effective signed tvOS entitlement and provisioning privilege, then require privacy-safe real-device evidence from two distinct full Apple Accounts: native profile selection, fresh app process/build identity, the account verified by the CloudKit boundary, its bound store/checkpoint, and distinct A/B content across repeated A → B → A switches and a cold launch. A profile label, `shouldStorePreferencesForCurrentUser`, a new PID, unit tests, or an unsigned/simulator build does not establish account isolation. If CloudKit verifies one account while the store belongs to another, treat the host binding as a defect; if it verifies the default account under a selected secondary profile, preserve evidence and diagnose the device context before proposing app code. Do not retain raw account IDs, record IDs, credentials, or user-authored content in audit evidence. + +When the consumer's acceptance contract requires genuine two-account behavior and that evidence is absent or contradictory, report the gate as incomplete and withhold completion or merge readiness. Record an explicit consumer-approved deferral only when its product contract permits one; never silently substitute compilation for physical isolation. + +| Scenario | Audit outcome | +| --- | --- | +| A and B each verify distinct CloudKit accounts and stores through repeated native switches | Accept the isolation evidence for the tested build and path | +| B is selected but CloudKit verifies A despite a fresh, correctly entitled process | Block isolation acceptance and diagnose device profile context without app-side account guessing | +| CloudKit verifies B but the host opens A's store | Block as a host account-to-store binding defect | +| Only build, simulator, or profile-label evidence exists | Record the real-device isolation gate as unverified when applicable | + +## Audit Xcode project settings + +For every checked-in `.xcodeproj`, read and apply the shared [Xcode project-settings guide](../../../Guidelines/Xcode/ProjectSettings.md): + +1. Identify the selected Xcode and its newest stable Swift language mode. Inspect every `PBXProject` build configuration and project-level `.xcconfig`; target-only values do not satisfy project-level ownership. +2. Require `GCC_TREAT_WARNINGS_AS_ERRORS`, `MTL_TREAT_WARNINGS_AS_ERRORS`, and `SWIFT_TREAT_WARNINGS_AS_ERRORS` to be `YES`; require `SWIFT_APPROACHABLE_CONCURRENCY = YES`, `SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor`, and `SWIFT_STRICT_CONCURRENCY = complete`; require `SWIFT_VERSION` to select that newest stable language mode; and require application targets to inherit `INFOPLIST_KEY_ITSAppUsesNonExemptEncryption = NO` in every configuration. +3. Discover every build setting exposed by the active Xcode whose name begins with `SWIFT_UPCOMING_FEATURE_`. For the selected Swift language mode, use the setting documentation and compiler diagnostics to identify which features remain opt-in. Require those settings to be `YES` at project level, and require flags for features already incorporated into the language mode to be absent so warnings-as-errors cannot turn a redundant-feature diagnostic into a build failure. Treat the settings listed in the shared guide as the Xcode 27 discovery inventory, not as flags that must all be enabled and not as a future-exhaustive list. +4. Enumerate every target and configuration, including application, unit-test, and UI-test targets, and inspect effective values with Xcode project-aware tooling or `xcodebuild -showBuildSettings`. For every application target, inspect the built `Info.plist` and confirm the `ITSAppUsesNonExemptEncryption` Boolean is `NO`. Remove redundant target copies and language-mode-redundant upcoming-feature flags. Treat a disabling or different target override for an applicable baseline setting as a violation unless an exact exception applies. +5. Before reporting a failure, search the nearest applicable `AGENTS.md` and durable project documentation linked from it for an exception naming the exact setting, scope, concrete incompatibility, replacement, impact, validation, and revisit condition. Accept and report an applicable documented exception; do not infer one from transient discussion, generic project prose, or the existing build setting itself. An application may use `INFOPLIST_KEY_ITSAppUsesNonExemptEncryption = YES` only when that exact exception documents the shipped non-exempt cryptography and resulting export-compliance workflow. +6. When implementation is authorized, move or add compliant values at project level, remove redundant target copies, and rerun build-setting inspection plus relevant builds. For review-only work, report undocumented gaps without editing. + +## Audit Swift package settings + +Enumerate every checked-in `Package.swift` that belongs to repository source, ignoring `.build` and other generated build artifacts, and treat each manifest's directory as a package root. For every package, read and apply [the shared package compiler-settings baseline](../../../Guidelines/Packages.md#compiler-settings-baseline); do not infer package rules solely from the Xcode guide. + +1. Identify the selected Swift/Xcode toolchain, inspect `// swift-tools-version:` and `swiftLanguageModes`, and require the newest stable language mode from the shared baseline, currently Swift 6. Reject an older effective mode unless an exact documented exception applies. +2. Run `swift package --package-path dump-package`, or the selected-toolchain equivalent, and use the evaluated manifest to enumerate locally defined targets and their effective settings. Do not rely only on textual grep because manifests may construct or mutate settings programmatically. +3. For every locally defined target that compiles Swift and for which SwiftPM exposes `swiftSettings`, including production, test, and other applicable Swift target kinds, require unconditional `.treatAllWarnings(as: .error)` plus `ExistentialAny`, `InferIsolatedConformances`, `InternalImportsByDefault`, `MemberImportVisibility`, and `NonisolatedNonsendingByDefault` as `.enableUpcomingFeature(...)` settings. Do not require Swift settings on binary targets, system-library targets, or package plug-in targets because `Target.plugin(...)` does not expose `swiftSettings`. +4. For locally compiled C or Objective-C targets, require the applicable typed `CSetting.treatAllWarnings(as: .error)`; require the corresponding `CXXSetting` where C++ is compiled. Do not require C-family settings when those languages are absent, and do not accept `unsafeFlags` in place of available typed APIs. +5. In Swift 6 mode, treat complete strict concurrency as supplied by the language mode and require every redundant explicit `StrictConcurrency` opt-in to be removed, including `.enableUpcomingFeature("StrictConcurrency")`, `.enableExperimentalFeature("StrictConcurrency")`, and `StrictConcurrency=complete` representations found in the evaluated manifest or effective compiler arguments. Require other upcoming-feature declarations to be removed when they become unconditional in the selected language mode, especially because warnings-as-errors can promote the resulting diagnostics. +6. Do not require or automatically add `.defaultIsolation(MainActor.self)`. Its absence is compliant with the shared package baseline; source-level actor-isolation review remains a separate Swift and concurrency concern. +7. Search the nearest applicable `AGENTS.md` and linked durable documentation before reporting a package-setting failure. Accept only an exception that names the exact setting or feature, package and targets, incompatibility, replacement or omission, impact, compensating validation where applicable, and revisit condition. Do not infer an exception from the manifest. +8. Run the package's documented validation workflow and, at minimum where applicable, `swift build` and `swift test`. Warnings promoted to errors must leave both warning-clean. When conditions or helper logic make the effective invocation uncertain, use verbose SwiftPM output to verify `-warnings-as-errors`, the language mode, and every `-enable-upcoming-feature` argument. + +For authorized implementation work, repair the manifest and rerun evaluated-manifest inspection plus builds. For review-only work, report the exact missing, conditional, redundant, or conflicting setting without modifying the package. + +## Audit localization + +When the repository contains localized targets or String Catalogs, read the shared [Localization guide](../../../Guidelines/Localization.md) and the consumer's local translation guidance: + +1. Keep supported languages, catalog and source paths, product voice, glossary, non-translatable terms, and project-specific exceptions in consumer documentation. Do not move those specifics into shared guidance or infer them from another product. +2. Confirm the project uses generated localizable symbols for maintained Swift catalog entries, does not check generated Swift into source control, and does not add localizable Swift literals that bypass the generated API. +3. Require the synchronized `prepare_localizable_symbols.swift` and `validate_string_catalogs.swift` logic. A local wrapper may supply project paths and languages to preserve a stable developer or CI command, but it must not retain a forked copy of shared migration or validation logic. +4. Run the consumer's documented nonmutating preparation check and catalog validator. Confirm CI runs the validator for localized projects and that every configured catalog and Swift source root is covered. +5. Inspect stale entries, required-language coverage, translation states, plural variants, and format placeholders in context. Require source/translated-language, long-text, plural, and right-to-left verification when affected. +6. Establish the explicit Git base for the completed change. If any added, copied, modified, renamed, or untracked `.xcstrings` file exists relative to that base, open every changed catalog in Xcode and inspect its String Catalog editor diagnostics. Record the repository-relative catalog path, selected Xcode version and build, and an explicit result of zero editor errors and zero editor warnings for each catalog. +7. From the consumer root, run `AgentGuidelines/.agents/skills/agent-guidelines-audit/scripts/check_xcstrings_inspection.swift --base-ref --inspected-catalog --evidence-output `, repeating `--inspected-catalog` for every changed catalog. In this source repository, use `.agents/skills/agent-guidelines-audit/scripts/check_xcstrings_inspection.swift`. Keep the JSON evidence outside the repository and summarize its catalog paths, Xcode build, and zero-diagnostic results in the completion handoff and pull-request description. +8. Fail closed when a changed catalog lacks that recorded editor evidence. A catalog validator, `xcstringstool`, warning-clean build, test run, or unrecorded statement that Xcode was checked is not a substitute. Do not claim audit success, open or update a pull request, or declare merge readiness until the evidence gate passes. +9. Preserve machine-translation state until fluent review. Treat missing required validation, unresolved catalog errors or warnings, missing catalog-editor evidence, or undocumented project-specific deviations as incomplete implementation. + +## Audit App Store metadata + +When a repository contains an `AppStore/` directory or the change affects storefront content, read the shared [App Store metadata guide](../../../Guidelines/AppStore.md) and the consumer's product-specific App Store documentation: + +1. Confirm the repository remains the source of truth and follows the app-store-connect-mcp directory format. Keep the app identity, platform versions, locales, product copy, screenshot production, reviewer prerequisites, and export-compliance rationale in consumer documentation. +2. Verify that changed fields and files match the requested domains and locales. Treat omitted fields as unmanaged, preserve curated content outside scope, and apply the consumer's localization voice and terminology to storefront copy. +3. Require scope-matched `validate_repository` and immutable plan evidence for any requested remote synchronization. Inspect additions, changes, removals, destructive modes, operation IDs, plan identity, and digest before application. +4. After an authorized apply, inspect uncertain outcomes through `get_operation_status` without replaying writes, then plan the unchanged scope again and require `noOp: true` remote reconciliation. +5. Confirm `.appstore-connect-mcp/` is ignored and that repository content, diffs, logs, and evidence contain no credentials, private contacts, demo secrets, upload URLs, or operational journals. +6. Treat App Store submission and release as separately authorized operations. Ordinary metadata or asset synchronization never proves release readiness and never authorizes submission. + +## Audit documentation consistency + +When implementation, configuration, or workflow behavior changed, perform an explicit documentation-drift pass: + +1. Read the applicable [Documentation guide](../../../Guidelines/Documentation.md) and identify code-level or durable project documentation that describes the affected feature, API, configuration, workflow, or invariant. +2. Compare those documented claims with the final implementation. Require a documentation update when the change alters durable or core behavior, or when any existing documented claim becomes inaccurate, incomplete, misleading, or obsolete, regardless of change size. +3. Search relevant durable documentation for changed names, removed behavior, defaults, examples, diagrams, setup steps, and references. Inspect matches in context rather than assuming a keyword search alone proves consistency. +4. Do not require new project-level prose for incidental implementation details that are not durable and do not affect an existing documented claim. +5. When implementation is authorized, update or remove stale documentation in the same change. For review-only work, report the drift without editing. Known stale documentation blocks completion. + +## Audit documentation formatting + +Apply the conventions in the applicable [Documentation guide](../../../Guidelines/Documentation.md) to governed Markdown: + +1. Audit every added or changed Markdown file outside a synchronized, provenance-verified `AgentGuidelines/` subtree. +2. When the completed change adds or changes a documentation convention, or updates a consumer to a guideline release that does so, also audit the consumer's existing root Markdown files and declared durable documentation folders. This adoption pass is required even when those files did not otherwise change. +3. From the repository root, run `.agents/skills/agent-guidelines-audit/scripts/check_markdown_wrapping.swift ` against those files or folders. The checker is read-only and reports prose paragraphs, list items, ordinary blockquotes, and GitHub alert body paragraphs that span multiple physical lines while excluding alert marker lines, fenced code, and other common verbatim Markdown constructs. +4. Inspect each reported span in context. Join confirmed hard-wrapped prose so each paragraph, list item, or blockquote occupies one physical line. Preserve intentional structure such as headings, separate list items, tables, fenced code, and ASCII diagrams. +5. When implementation is authorized, fix confirmed violations and rerun the checker. For review-only work, report them without editing. Do not claim the audit passes while a confirmed line-wrapping violation remains in scope. + +## Validate the evidence + +Run the repository's declared non-destructive checks in proportion to the change: + +- formatter and strict lint; +- focused tests, followed by the declared broader test plan when warranted; +- relevant builds or package validation; +- repository-specific validators; +- `git diff --check`. + +When the shared Swift-format guide applies: + +- For implementation work, run `AgentGuidelines/Scripts/swift_format.sh format-and-lint` over every changed or applicable checked-in Swift source root before tests. For review-only work, use `lint-strict` so the audit does not mutate files. +- Confirm the root `.swift-format` and `.editorconfig` symlinks resolve to the synchronized shared configurations. +- Confirm pull-request and protected-branch CI run the shared wrapper with `lint-strict` in a dedicated non-mutating job. Reject `format` or `format-and-lint` in CI and verify the listed paths cover the repository's checked-in Swift roots. +- For Xcode projects, verify every independently buildable app or test target has the target-scoped pre-compilation phase described by the guide, including its `CI=true` bypass. +- For Swift packages, format `Package.swift`, `Sources`, `Tests`, and other checked-in Swift roots that exist before running `swift test`. Do not require `swift build` or `swift test` themselves to rewrite source; formatting and testing are consecutive, independently visible checks. + +Use fresh successful evidence already produced in the same task instead of rerunning expensive checks without reason. Distinguish automated compilation and simulator evidence from hardware, signing, deployment, or manual validation that automation cannot prove. + +## Resolve findings + +- When the user authorized implementation, fix safe in-scope findings and rerun the affected checks. +- For review-only work, report findings without modifying code. +- Do not broaden the feature, rewrite unrelated files, edit a synchronized `AgentGuidelines/` subtree, or perform commits, pushes, pull requests, merges, tags, or releases without the required authority. +- Treat an unresolved required guideline violation or missing relevant validation as a blocker to claiming completion. + +## Hand off + +Summarize: + +- the instruction and guideline areas audited; +- consumer-integration validation and any drift found; +- networking applicability, typed/native implementation evidence, exceptions or migration deferrals, and relevant validation; +- `.gitignore` reconciliation, including added shared patterns and every accepted or unresolved project-specific entry; +- findings fixed during the audit; +- documentation updated or removed, or why no documentation change was required; +- validation commands and outcomes; +- changed-String-Catalog detection and, when applicable, the recorded Xcode version, catalog paths, and zero catalog-editor errors and warnings; +- any deliberate deviations, unavailable evidence, or remaining blockers. + +Do not say the work is done merely because the audit ran. Say it is ready only when the requested outcome is complete and the relevant evidence passes. diff --git a/AgentGuidelines/.agents/skills/agent-guidelines-audit/agents/openai.yaml b/.agents/skills/agent-guidelines-audit/agents/openai.yaml similarity index 100% rename from AgentGuidelines/.agents/skills/agent-guidelines-audit/agents/openai.yaml rename to .agents/skills/agent-guidelines-audit/agents/openai.yaml diff --git a/.agents/skills/agent-guidelines-audit/scripts/check_markdown_wrapping.swift b/.agents/skills/agent-guidelines-audit/scripts/check_markdown_wrapping.swift new file mode 100755 index 0000000..703d581 --- /dev/null +++ b/.agents/skills/agent-guidelines-audit/scripts/check_markdown_wrapping.swift @@ -0,0 +1,261 @@ +#!/usr/bin/env swift +import Foundation + +#if canImport(Darwin) + import Darwin +#else + import Glibc +#endif + +/// A prose block that should occupy one physical line. +struct Finding { + let path: String + let start: Int + let end: Int + let kind: String +} + +/// A candidate prose block being assembled. +struct Block { + let kind: String + let start: Int + var end: Int +} + +let fencePattern = #"^\s*(`{3,}|~{3,})"# +let headingPattern = #"^\s{0,3}#{1,6}(?:\s|$)"# +let listItemPattern = #"^(\s{0,3})(?:[-+*]|\d+[.)])\s+(.*)$"# +let linkDefinitionPattern = #"^\s{0,3}\[[^]]+\]:\s*\S+"# +let thematicBreakPattern = #"^\s{0,3}(?:(?:\*\s*){3,}|(?:-\s*){3,}|(?:_\s*){3,})$"# +let setextUnderlinePattern = #"^\s{0,3}(?:=+|-+)\s*$"# +let tableDelimiterPattern = #"^\s*\|?(?:\s*:?-+:?\s*\|)+\s*:?-+:?\s*\|?\s*$"# +let quotePattern = #"^\s{0,3}>\s?"# +let alertMarkerPattern = #"^\[!(?:NOTE|TIP|IMPORTANT|WARNING|CAUTION)\]$"# + +/// Returns the first regular-expression match in a string. +func firstMatch(_ pattern: String, in value: String) -> NSTextCheckingResult? { + let expression = try? NSRegularExpression(pattern: pattern) + let range = NSRange(value.startIndex.. String? { + let range = match.range(at: index) + guard range.location != NSNotFound, let swiftRange = Range(range, in: value) else { + return nil + } + return String(value[swiftRange]) +} + +/// Returns whether a line has the shape of a Markdown table row. +func isTableRow(_ line: String) -> Bool { + let stripped = line.trimmingCharacters(in: .whitespacesAndNewlines) + return firstMatch(tableDelimiterPattern, in: stripped) != nil + || (stripped.hasPrefix("|") && stripped.hasSuffix("|")) +} + +/// Returns whether a line should terminate prose-block detection. +func isVerbatimOrStructure(_ line: String) -> Bool { + let stripped = line.trimmingCharacters(in: .whitespacesAndNewlines) + return stripped.isEmpty + || firstMatch(headingPattern, in: line) != nil + || firstMatch(thematicBreakPattern, in: line) != nil + || firstMatch(setextUnderlinePattern, in: line) != nil + || firstMatch(linkDefinitionPattern, in: line) != nil + || firstMatch(listItemPattern, in: line) != nil + || isTableRow(line) + || line.hasPrefix(" ") + || stripped.hasPrefix("<") +} + +/// Expands file and directory arguments into unique Markdown files. +func markdownFiles(_ paths: [String]) throws -> [String] { + let fileManager = FileManager.default + var files = Set() + for path in paths { + var isDirectory: ObjCBool = false + guard fileManager.fileExists(atPath: path, isDirectory: &isDirectory) else { + throw NSError( + domain: "MarkdownWrapping", code: 2, + userInfo: [ + NSLocalizedDescriptionKey: "path does not exist: \(path)" + ]) + } + if isDirectory.boolValue { + guard let enumerator = fileManager.enumerator(atPath: path) else { + continue + } + for case let candidate as String in enumerator where candidate.lowercased().hasSuffix(".md") { + let fullPath = URL(fileURLWithPath: path).appendingPathComponent(candidate).path + var candidateIsDirectory: ObjCBool = false + if fileManager.fileExists(atPath: fullPath, isDirectory: &candidateIsDirectory), + !candidateIsDirectory.boolValue + { + files.insert(fullPath) + } + } + } else if URL(fileURLWithPath: path).pathExtension.lowercased() == "md" { + files.insert(path) + } + } + return files.sorted() +} + +/// Finds prose blocks that span multiple physical lines in one Markdown file. +func findings(for path: String) throws -> [Finding] { + let contents = try String(contentsOfFile: path, encoding: .utf8) + let lines = contents.components(separatedBy: .newlines) + var findings: [Finding] = [] + var block: Block? + var fenceMarker: Character? + var inComment = false + var inFrontmatter = lines.first?.trimmingCharacters(in: .whitespacesAndNewlines) == "---" + var previousQuoteDepth = 0 + + func finishBlock() { + if let block, block.end > block.start { + findings.append(Finding(path: path, start: block.start, end: block.end, kind: block.kind)) + } + block = nil + } + + for (offset, line) in lines.enumerated() { + let lineNumber = offset + 1 + let stripped = line.trimmingCharacters(in: .whitespacesAndNewlines) + var quoteDepth = 0 + var quoteContent = line + while let match = firstMatch(quotePattern, in: quoteContent), + let range = Range(match.range, in: quoteContent) + { + quoteContent.removeSubrange(range) + quoteDepth += 1 + } + defer { + previousQuoteDepth = quoteDepth + } + + if inFrontmatter { + if lineNumber > 1, stripped == "---" { + inFrontmatter = false + } + continue + } + + if let match = firstMatch(fencePattern, in: line), let marker = capture(1, from: match, in: line)?.first { + if fenceMarker == nil { + finishBlock() + fenceMarker = marker + } else if fenceMarker == marker { + fenceMarker = nil + } + continue + } + if fenceMarker != nil { + continue + } + + if inComment { + if line.contains("-->") { + inComment = false + } + continue + } + if line.contains("") { + inComment = true + } + continue + } + + if quoteDepth > 0 { + let trimmedQuoteContent = quoteContent.trimmingCharacters(in: .whitespacesAndNewlines) + if quoteDepth == 1, previousQuoteDepth == 0, + firstMatch(alertMarkerPattern, in: trimmedQuoteContent) != nil + { + finishBlock() + continue + } + if isVerbatimOrStructure(quoteContent) { + finishBlock() + continue + } + let kind = "block quote (depth \(quoteDepth))" + if block?.kind == kind { + block?.end = lineNumber + } else { + finishBlock() + block = Block(kind: kind, start: lineNumber, end: lineNumber) + } + continue + } + + if let match = firstMatch(listItemPattern, in: line) { + finishBlock() + let content = capture(2, from: match, in: line) ?? "" + if !content.isEmpty, !isVerbatimOrStructure(content) { + block = Block(kind: "list item", start: lineNumber, end: lineNumber) + } + continue + } + + if block?.kind == "list item", line.hasPrefix(" ") || line.hasPrefix("\t") { + if isVerbatimOrStructure(line.trimmingCharacters(in: .whitespaces)) { + finishBlock() + } else { + block?.end = lineNumber + } + continue + } + + if isVerbatimOrStructure(line) { + finishBlock() + continue + } + + if block?.kind == "paragraph" { + block?.end = lineNumber + } else { + finishBlock() + block = Block(kind: "paragraph", start: lineNumber, end: lineNumber) + } + } + finishBlock() + return findings +} + +/// Writes text to standard error. +func writeError(_ value: String) { + FileHandle.standardError.write(Data((value + "\n").utf8)) +} + +/// Runs the wrapping audit and returns a lint-style status code. +func main() -> Int32 { + let paths = Array(CommandLine.arguments.dropFirst()) + if paths.isEmpty || paths.contains("--help") { + print("Usage: check_markdown_wrapping.swift ") + return paths.isEmpty ? 2 : 0 + } + do { + let files = try markdownFiles(paths) + let allFindings = try files.flatMap { try findings(for: $0) } + for finding in allFindings { + print( + "\(finding.path):\(finding.start): \(finding.kind) spans physical lines " + + "\(finding.start)-\(finding.end); keep its prose on one line" + ) + } + if !allFindings.isEmpty { + writeError("Found \(allFindings.count) hard-wrapped Markdown prose block(s).") + return 1 + } + print("Checked \(files.count) Markdown file(s); no hard-wrapped prose found.") + return 0 + } catch { + writeError("Markdown wrapping audit failed: \(error.localizedDescription)") + return 2 + } +} + +exit(main()) diff --git a/.agents/skills/agent-guidelines-audit/scripts/check_xcstrings_inspection.swift b/.agents/skills/agent-guidelines-audit/scripts/check_xcstrings_inspection.swift new file mode 100755 index 0000000..1478467 --- /dev/null +++ b/.agents/skills/agent-guidelines-audit/scripts/check_xcstrings_inspection.swift @@ -0,0 +1,260 @@ +#!/usr/bin/env swift +import Foundation + +#if canImport(Darwin) + import Darwin +#else + import Glibc +#endif + +/// Parsed command-line values for String Catalog inspection evidence. +struct Arguments { + var repository = FileManager.default.currentDirectoryPath + var baseRef: String? + var inspectedCatalogs: [String] = [] + var evidenceOutput: String? +} + +/// Runs a process in a repository and returns its standard output. +func run(_ command: [String], repositoryRoot: String) throws -> Data { + let process = Process() + let output = Pipe() + process.currentDirectoryURL = URL(fileURLWithPath: repositoryRoot) + process.executableURL = URL(fileURLWithPath: "/usr/bin/env") + process.arguments = command + process.standardOutput = output + process.standardError = output + try process.run() + let outputData = output.fileHandleForReading.readDataToEndOfFile() + process.waitUntilExit() + guard process.terminationStatus == 0 else { + let detail = + String(data: outputData, encoding: .utf8)?.trimmingCharacters(in: .whitespacesAndNewlines) + ?? "command failed" + throw NSError( + domain: "StringCatalogInspection", code: Int(process.terminationStatus), + userInfo: [ + NSLocalizedDescriptionKey: "\(command.joined(separator: " ")): \(detail)" + ]) + } + return outputData +} + +/// Returns the Git repository root containing a requested path. +func repositoryRoot(containing repository: String) throws -> String { + let data = try run(["git", "rev-parse", "--show-toplevel"], repositoryRoot: repository) + guard let root = String(data: data, encoding: .utf8)?.trimmingCharacters(in: .whitespacesAndNewlines), + !root.isEmpty + else { + throw NSError( + domain: "StringCatalogInspection", code: 2, + userInfo: [ + NSLocalizedDescriptionKey: "git returned no repository root" + ]) + } + return URL(fileURLWithPath: root).standardizedFileURL.path +} + +/// Parses NUL-separated Git paths and retains String Catalogs. +func catalogPaths(from data: Data) -> Set { + guard let output = String(data: data, encoding: .utf8) else { + return [] + } + return Set(output.split(separator: "\0").map(String.init).filter { $0.hasSuffix(".xcstrings") }) +} + +/// Returns added, copied, modified, renamed, and untracked String Catalogs. +func changedCatalogs(root: String, baseRef: String) throws -> Set { + _ = try run(["git", "rev-parse", "--verify", "\(baseRef)^{commit}"], repositoryRoot: root) + let tracked = try run( + ["git", "diff", "--name-only", "-z", "--diff-filter=ACMR", baseRef, "--"], + repositoryRoot: root + ) + let untracked = try run( + ["git", "ls-files", "--others", "--exclude-standard", "-z"], + repositoryRoot: root + ) + return catalogPaths(from: tracked).union(catalogPaths(from: untracked)) +} + +/// Normalizes repository-relative catalog paths supplied as inspection evidence. +func normalizedInspections(_ values: [String]) throws -> Set { + var inspections = Set() + for value in values { + let components = NSString(string: value).pathComponents + guard !NSString(string: value).isAbsolutePath, + !components.contains(".."), + value.hasSuffix(".xcstrings") + else { + throw NSError( + domain: "StringCatalogInspection", code: 2, + userInfo: [ + NSLocalizedDescriptionKey: + "--inspected-catalog values must be repository-relative .xcstrings paths" + ]) + } + inspections.insert(NSString(string: value).standardizingPath) + } + return inspections +} + +/// Returns fail-closed coverage errors for catalog-editor inspection evidence. +func inspectionCoverageErrors(changed: Set, inspected: Set) -> [String] { + let missing = changed.subtracting(inspected).sorted().map { + "missing Xcode catalog-editor inspection evidence: \($0)" + } + let unexpected = inspected.subtracting(changed).sorted().map { + "inspection evidence does not match a changed String Catalog: \($0)" + } + return missing + unexpected +} + +/// Returns the selected Xcode version and build used for the inspection record. +func selectedXcodeVersion(root: String) throws -> String { + let data = try run(["xcodebuild", "-version"], repositoryRoot: root) + return String(data: data, encoding: .utf8)?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" +} + +/// Writes structured, non-repository evidence for a completed editor inspection. +func writeEvidence( + output: String, + root: String, + baseRef: String, + xcodeVersion: String, + catalogs: Set +) throws { + let rootURL = URL(fileURLWithPath: root).standardizedFileURL.resolvingSymlinksInPath() + let outputURL = URL(fileURLWithPath: output).standardizedFileURL.resolvingSymlinksInPath() + let rootPath = rootURL.path.hasSuffix("/") ? rootURL.path : rootURL.path + "/" + guard outputURL.path != rootURL.path, !outputURL.path.hasPrefix(rootPath) else { + throw NSError( + domain: "StringCatalogInspection", code: 2, + userInfo: [ + NSLocalizedDescriptionKey: "--evidence-output must be outside the repository" + ]) + } + try FileManager.default.createDirectory( + at: outputURL.deletingLastPathComponent(), + withIntermediateDirectories: true + ) + let formatter = ISO8601DateFormatter() + formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds] + let evidence: [String: Any] = [ + "schemaVersion": 1, + "recordedAt": formatter.string(from: Date()), + "baseRef": baseRef, + "xcodeVersion": xcodeVersion, + "catalogs": catalogs.sorted().map { + [ + "path": $0, + "catalogEditorErrors": 0, + "catalogEditorWarnings": 0, + ] + }, + ] + let data = try JSONSerialization.data(withJSONObject: evidence, options: [.prettyPrinted, .sortedKeys]) + var contents = data + contents.append(0x0A) + try contents.write(to: outputURL, options: .atomic) +} + +/// Parses command-line arguments. +func parseArguments(_ values: [String]) throws -> Arguments { + var arguments = Arguments() + var index = 0 + while index < values.count { + let value = values[index] + if value == "--help" { + print( + "Usage: check_xcstrings_inspection.swift --base-ref " + + "[--repository ] [--inspected-catalog ...] " + + "[--evidence-output ]" + ) + exit(0) + } + guard index + 1 < values.count else { + throw NSError( + domain: "StringCatalogInspection", code: 2, + userInfo: [ + NSLocalizedDescriptionKey: "missing value for \(value)" + ]) + } + let next = values[index + 1] + switch value { + case "--repository": arguments.repository = next + case "--base-ref": arguments.baseRef = next + case "--inspected-catalog": arguments.inspectedCatalogs.append(next) + case "--evidence-output": arguments.evidenceOutput = next + default: + throw NSError( + domain: "StringCatalogInspection", code: 2, + userInfo: [ + NSLocalizedDescriptionKey: "unknown argument: \(value)" + ]) + } + index += 2 + } + guard arguments.baseRef != nil else { + throw NSError( + domain: "StringCatalogInspection", code: 2, + userInfo: [ + NSLocalizedDescriptionKey: "--base-ref is required" + ]) + } + return arguments +} + +/// Writes text to standard error. +func writeError(_ value: String) { + FileHandle.standardError.write(Data((value + "\n").utf8)) +} + +/// Validates inspection coverage and writes the structured evidence record. +func main() -> Int32 { + do { + let arguments = try parseArguments(Array(CommandLine.arguments.dropFirst())) + let root = try repositoryRoot(containing: arguments.repository) + guard let baseRef = arguments.baseRef else { + return 2 + } + let changed = try changedCatalogs(root: root, baseRef: baseRef) + let inspected = try normalizedInspections(arguments.inspectedCatalogs) + var errors = inspectionCoverageErrors(changed: changed, inspected: inspected) + if !changed.isEmpty, arguments.evidenceOutput == nil { + errors.append("--evidence-output is required when String Catalogs changed") + } + if !errors.isEmpty { + for error in errors { + writeError("String Catalog inspection audit failed: \(error)") + } + return 1 + } + if changed.isEmpty { + print( + "No changed String Catalogs relative to \(baseRef); " + + "Xcode catalog-editor inspection evidence is not required." + ) + return 0 + } + guard let evidenceOutput = arguments.evidenceOutput else { + return 1 + } + try writeEvidence( + output: evidenceOutput, + root: root, + baseRef: baseRef, + xcodeVersion: try selectedXcodeVersion(root: root), + catalogs: changed + ) + print( + "Recorded zero Xcode catalog-editor errors and warnings for " + + "\(changed.count) changed String Catalog(s) at \(evidenceOutput)." + ) + return 0 + } catch { + writeError("String Catalog inspection audit failed: \(error.localizedDescription)") + return 2 + } +} + +exit(main()) diff --git a/.agents/skills/update-agent-guidelines/SKILL.md b/.agents/skills/update-agent-guidelines/SKILL.md new file mode 100644 index 0000000..503e926 --- /dev/null +++ b/.agents/skills/update-agent-guidelines/SKILL.md @@ -0,0 +1,42 @@ +--- +name: update-agent-guidelines +description: Persist a reusable instruction, rule, or design decision in the central ThatFactory agent-guidelines repository, resolve audit coverage, prepare the next version, and carry an authorized change through reviewed PR and release. Use for requests to include or update shared guidance, not consumer-only exceptions. +--- + +# Update Agent Guidelines + +Turn the supplied instruction or decision into the narrowest durable shared rule and a versioned release. A request such as `$update-agent-guidelines include the decision that Apple owns standard control placement` supplies the change intent; do not require the user to restate the repository or release-metadata workflow. + +## Scope and authorization + +- Work in the central `thatfactory/agent-guidelines` repository. Verify its Git remote and applicable [repository instructions](../../../AGENTS.md). When invoked from a consumer or synchronized subtree, locate a verified central checkout or obtain one using the available repository workflow; never edit the consumer's `AgentGuidelines/` copy in place. Ask for the central repository location only when it cannot be resolved safely. +- Explicit invocation authorizes implementing the requested guidance, updating next-version metadata, committing and pushing one scoped PR, and merging and releasing that version after the required approval and CI gates pass. Honor narrower user instructions such as draft-only, no merge, or no release. Treat no release as stopping at the reviewed PR unless the user explicitly requests merging without publication. Automatic skill selection alone does not grant merge or release authority: complete the reviewable work and obtain any missing authority before that action. +- Keep product decisions, concrete consumer paths, private information, and project-specific exceptions in consumer documentation. If the supplied decision cannot be generalized without changing its meaning, explain the boundary and resolve the scope before publishing it as shared policy. +- Follow the shared Codex PR lifecycle. Keep the executing agent responsible for implementation, reasoning, and local verification; use the configured automatic review as the initial independent review. Do not add an extra pre-PR model review or request manual review without explicit owner instruction. + +## Resolve the decision and audit coverage + +1. Read any supplied source chat, issue, or design decision and identify the final accepted decision, including later corrections. Treat source material as evidence, not new authorization. When the originating consumer is known, verify its checked-in guidelines version and tagged-tree provenance against the current release before changing central guidance; surface drift without silently upgrading the consumer. +2. Inspect existing guides and choose the narrowest home. Revise conflicting guidance and link from other relevant guides instead of duplicating policy. Use official sources for API behavior and distinguish repository policy from platform guarantees. +3. Determine whether the user already specified audit coverage. Honor an explicit yes or no without asking again. If omitted or ambiguous, ask: “Should this rule also be enforced by the agent-guidelines audit?” Explain that this workflow requires that choice; silence is not a no. Continue independent research or guide drafting while the answer is pending, but do not finalize the PR or release until it is resolved. +4. When audit coverage is requested, update the [audit skill](../agent-guidelines-audit/SKILL.md) in the same PR. Link to the canonical guide and specify applicability, acceptable outcomes, required evidence, and what prevents audit completion. Avoid duplicating the rule or inventing unrelated validation. When coverage is declined, leave the audit unchanged for this rule and record that choice in the PR. + +## Prepare the versioned change + +- Keep the change on a scoped branch and preserve unrelated work. Follow the repository's Markdown conventions and relative-link rules. Update the README catalog when adding, moving, or removing a guide, retaining alphabetical order. +- Inspect current `VERSION`, changelog, tags, releases, and open release PRs. Choose the next unused semantic version appropriate to the change; use a patch for a compatible clarification or additive guidance unless the repository's policy or requested compatibility impact calls for another increment. Do not blindly bump twice when continuing an existing release PR. +- Update `VERSION`, a dated `CHANGELOG.md` entry, and both README subtree commands together. Describe the final policy and audit behavior. Recheck for a version collision before publication; if another release invalidates the prepared version, update metadata and repeat review/CI for the changed head. +- Run `Scripts/validate_guidelines.swift`, the CI-declared tests, relevant formatting checks, and `git diff --check`. Invoke the completion audit and fix in-scope failures. Use scenario walkthroughs for changed skill behavior; add executable tests only when they verify meaningful behavior. + +## Review, merge, and release + +1. Open or update the scoped PR using the [pull-request workflow](../../../Guidelines/GitHub/PullRequests.md). Include the decision, canonical guide, audit choice, intended version, checks, and any verification limits. +2. Obtain the required review for the actual PR and exact base/head. Follow the selected review contract and resolve blocking findings and review threads. Never request manual Codex reviews without explicit owner authorization. +3. Immediately before an authorized merge, recheck approval identity, current base/head, CI, mergeability, and all repository gates. For remediation after a completed initial review, record and locally verify the remediation-only delta without claiming bot coverage of the newer head. Follow the shared workflow for material scope or integration changes; do not bypass a pending required review or failed check. +4. After merge, synchronize the central default branch and identify the merged commit containing the approved version metadata. Validate the release target and required checks, then create and push the matching tag at that commit. Never move or overwrite a published tag. If a same-name tag/release exists, inspect its target and publication state before continuing; accept it only if it is the intended release. +5. Follow the repository's release automation. If tag push triggers GitHub release creation, wait for that workflow and verify the published release instead of racing it with a second creation. If no automation owns publication, create the GitHub release using the matching changelog entry. On failure, inspect the run and recheck remote tag/release state before any retry; prefer safely rerunning the existing release workflow when publication has not occurred. Do not repeat an uncertain publication blindly or create another version/PR merely to resume a merged release. +6. Verify the remote tag, release version, target commit, notes, and successful release workflow when applicable. Report the PR and release links, audit choice, and validation. Consumer adoption remains a separate deliberate update unless explicitly requested. + +## Review-policy publication + +When either canonical review contract changes, increment `ReviewPolicy/VERSION`, synchronize the central root, full template, and global reviewer section, and update policy tests. After the regular reviewed guidelines release is published, create the immutable `codex-review-vN` tag at the same release commit. Verify its remote target and include the authorized full/review-only consumer rollout; unrelated guidelines changes retain the policy revision. Use the central Swift synchronizer for managed blocks and never publish private consumer inventories here. diff --git a/.agents/skills/xcode-upgrade/SKILL.md b/.agents/skills/xcode-upgrade/SKILL.md new file mode 100644 index 0000000..af833a2 --- /dev/null +++ b/.agents/skills/xcode-upgrade/SKILL.md @@ -0,0 +1,51 @@ +--- +name: xcode-upgrade +description: Upgrade a ThatFactory Apple-platform application or Swift package to a requested Xcode version, including dependencies, compiler settings, CI, validation, and optional project-format conversion. Use for /xcode-upgrade, moving to a new Xcode, or adopting a requested Xcode project format. +--- + +# Xcode Upgrade + +Deliver a coherent, verified toolchain upgrade in the current repository. In Codex, explicitly invoke `$xcode-upgrade to Xcode 27.2 and use the new JSON format` or select the skill. Also recognize `/xcode-upgrade ...` when supplied as request text by a client; this skill does not register a client slash command. Parse the requested version and stable, beta, or RC channel, and treat trailing instructions as scope and constraints. Ask only when the target or an incompatible requirement cannot be resolved from the request and repository evidence. + +Read linked guidance relative to this skill's real location in the central checkout or the consumer's `AgentGuidelines/` subtree. Keep concrete schemes, paths, runner identities, simulator choices, and exceptions in the consumer. + +## Establish the upgrade boundary + +1. Read the nearest applicable `AGENTS.md` and local build, testing, dependency, and delivery documentation. Follow the [guidelines-version workflow](../../../Guidelines/Development.md#guidelines-version) before implementation; verify the checked-in release and provenance when updating a subtree, and keep that update in its own commit. Never edit synchronized guidance in place. +2. Record the starting Git state and current Xcode/Swift versions. Inventory authored projects and workspaces, shared schemes and test plans, targets and configurations, checked-in `Package.swift` manifests and resolved files, configuration files, automation, CI toolchain selection, and documented supported platforms. Exclude generated checkouts and build output. For a package-only repository, skip project-document and simulator steps unless its actual tests require them. +3. Locate the requested Xcode and verify its version and build with `xcodebuild -version`, its Swift compiler with `xcrun swift --version`, and readiness with `xcodebuild -checkFirstLaunchStatus`, all under that installation's `DEVELOPER_DIR`. Use process-scoped `DEVELOPER_DIR` for subsequent commands; do not change machine-global `xcode-select` as part of the upgrade. If the toolchain or required component is missing, continue independent inspection and report the exact installation or first-launch prerequisite; do not claim target-toolchain validation. +4. Read the selected version's official [Xcode release notes](https://developer.apple.com/documentation/xcode-release-notes), relevant Swift release documentation, and installed command help. Distinguish compiler version, stable Swift language mode, SDK version, deployment target, and project-format compatibility. An Xcode upgrade does not itself request higher minimum OS versions or beta language features. +5. Present the concrete scope, including requested format changes, dependency candidates, settings migration, CI/runtime requirements, and validation. Continue changes already authorized by the user; obtain only genuinely missing decisions or authority. Skill invocation alone does not authorize remote runner administration, publication, distribution, or merging. + +## Align the toolchain and project document + +- Discover every current toolchain pin and version check in workflows, configuration, scripts, badges, and current-setup documentation. Apply the [runner toolchain policy](../../../Guidelines/CICD.md#runner-toolchain): validate the requested installation for this upgrade, then leave ordinary CI using the runner's active toolchain. Remove unjustified exact-version checks instead of updating them to the newly tested version, and retain a pin only with the guide's documented repository-specific exception. Preserve capability requirements and the repository's runner-label policy. Inspect Xcode Cloud configuration when used; a local workflow-file edit does not prove the remote workflow selected the new Xcode. +- Verify required runner capabilities and simulator runtimes through available authorized read-only tools. Keep infrastructure readiness distinct from repository correctness. Missing runner access or capacity is an explicit validation gap, not evidence that CI will pass. Never invent host addresses, require SSH universally, or change shared machines without authorization. +- Open each authored project in the selected Xcode and inspect **Editor > Validate Settings** with the project selected. Evaluate proposed changes against local exceptions and the canonical settings guides. Apply in-scope recommendations and inspect the resulting diff; report an unavailable editor check honestly. Use project-aware tooling and selected-Xcode output for document compatibility and upgrade markers, including shared schemes. Do not blindly stamp version markers to imply that validation occurred. +- If projects are generated, update the generator inputs and compatible tooling, then regenerate through the documented workflow instead of editing disposable output. + +### Requested JSON project conversion + +Convert only when the user requests it. Follow Apple's [project configuration format migration](https://developer.apple.com/documentation/xcode/updating-your-xcode-project-configuration-file-format) and verify support in the selected Xcode and the oldest Xcode the repository promises to support. + +1. Before converting, inventory tools that read or write the project: repository Swift scripts, version/release automation, project generators, linters, validators, CI paths, and external tooling. Search for `project.pbxproj`, `.pbxproj`, and assumptions about legacy keys. Verify support for the installed tool versions rather than copying a historical compatibility list. Adapt and validate repository-owned consumers within scope; legacy assumptions alone are not a blocker. Stop the conversion if a required consumer cannot be made compatible; explain the exact conflict and available options without silently abandoning the requested format. +2. Preserve a recoverable Git state and close the project in Xcode before a CLI conversion to avoid competing writes. Use Xcode's Project Format control or the conversion command supported by that installation's `xcodebuild -help`. Let Xcode generate `project.xcproj`; do not hand-translate the project or assume a strict JSON parser accepts its syntax. +3. Inspect the complete conversion diff for preserved targets, configurations, build phases, package references, resources, membership exceptions, signing, and entitlements. Update format-dependent automation and documentation in the same PR. Keep conversion separate from settings and dependency changes where practical so its effect can be reviewed independently. +4. Reopen the project, list its schemes/targets, resolve packages, and build before layering further changes. Exercise affected versioning, generation, and delivery tools through nonpublishing checks or disposable copies; restore only task-owned temporary changes. A successful Xcode build alone does not establish automation compatibility. If conversion fails, preserve the evidence and restore only conversion-owned edits before reporting the blocker. + +## Apply compiler settings and dependency updates + +- For every checked-in Xcode project, apply [Xcode project settings](../../../Guidelines/Xcode/ProjectSettings.md), including project-level ownership, effective values in all configurations and targets, selected-language-mode upcoming-feature discovery, and documented exceptions. Fix compiler diagnostics instead of weakening required warnings or concurrency settings to make the upgrade pass. +- For every in-scope Swift package, separately apply [the package compiler-settings baseline](../../../Guidelines/Packages.md#compiler-settings-baseline) using its evaluated manifest. Do not copy an application's default actor isolation or application-only settings into reusable packages. If a new toolchain requires a shared compiler-policy change, that central change needs its own authorization, package-parity, audit, validation, and reviewed release before consumer adoption. Continue only when that authority exists; otherwise report the dependency as incomplete rather than editing the subtree or silently expanding the task. +- Review available updates for the repository's actual package dependencies, build/documentation plugins, formatter/linter, and CI actions. Use release notes and declared compatibility to choose current compatible versions; update dependencies intentionally under [Packages](../../../Guidelines/Packages.md#consumer-updates) and the [external dependency policy](../../../Guidelines/Development.md#external-dependencies). Review major-version migrations and exact-pin history before changing requirements. Preserve deliberate pins with a reason, and avoid unrelated resolver churn. +- Check changed direct and transitive dependency roles, platform/toolchain requirements, licensing, security, and maintenance impact. Obtain the required approval and durable exception for new third-party runtime dependencies or expanded roles. Do not introduce fastlane, CocoaPods, or Carthage while adapting automation. New repository-owned executable automation follows the Swift policy in [CI/CD](../../../Guidelines/CICD.md#tooling-and-automation). +- Update requirement declarations and the appropriate checked-in resolved files together, and prove that the final remote dependency versions resolve without local-path overrides. Do not publish sibling packages merely to move a version pin; any necessary package change follows its own reviewed release workflow and authorization. + +## Verify and hand off + +1. Use isolated build output and explicit repository-supported destinations with the selected toolchain. Follow the declared formatter/lint workflow and resolve dependencies. Build a coverage matrix for every applicable declared project, scheme/test plan, package, supported platform, and Debug, Release, or custom configuration; run its builds/tests and document the reason for any exclusion. Require warning-clean results under the canonical baseline and report test execution counts so zero tests cannot pass as coverage. +2. Run applicable UI/snapshot suites and targeted runtime checks for changed behavior. Re-record only explained baseline differences after examining them; do not blanket-accept new snapshots or delete unaffected baselines. Follow [device interaction](../../../Guidelines/Xcode/DeviceInteraction.md) when runtime evidence is needed, and distinguish simulator, physical-device, signing, and distribution evidence. +3. Check format-dependent versioning/release tools without uploads, tags, distribution, or publication. Do not assume a lane or script is safe from its name; inspect its effects and use supported dry-run modes or disposable copies. Record unavailable checks and their impact. +4. Update current-setup documentation, README badges, toolchain prerequisites, supported developer/CI Xcode versions, simulator instructions, dependency integration notes, and format references that changed. Search for stale version strings and legacy file assumptions in context; preserve historical release and incident records. +5. Invoke [agent-guidelines-audit](../agent-guidelines-audit/SKILL.md), reuse fresh validation evidence, and run `git diff --check`. Report the requested and verified Xcode/build, Swift mode, format decision, dependency changes and retained pins, settings exceptions, CI/runner readiness, commands/results, and unresolved prerequisites. Keep unavailable required evidence visibly incomplete. +6. Commit and prepare the scoped PR when authorized, with logical separation of guideline adoption, project conversion, settings, dependencies, and automation where useful. Follow [the pull-request workflow](../../../Guidelines/GitHub/PullRequests.md) and any user-requested review mechanism. Merge, tag, release, or distribute only within the user's authorization and after the relevant gates pass. diff --git a/.editorconfig b/.editorconfig deleted file mode 120000 index 1e825fd..0000000 --- a/.editorconfig +++ /dev/null @@ -1 +0,0 @@ -AgentGuidelines/Configurations/Swift/.editorconfig \ No newline at end of file diff --git a/.gitattributes b/.gitattributes deleted file mode 100644 index 38ec4db..0000000 --- a/.gitattributes +++ /dev/null @@ -1,2 +0,0 @@ -# Synced from thatfactory/agent-guidelines; keep tracked but collapse GitHub diffs. -AgentGuidelines/** linguist-generated diff --git a/.github/actions/codex-review-policy/action.yml b/.github/actions/codex-review-policy/action.yml new file mode 100644 index 0000000..5a39c46 --- /dev/null +++ b/.github/actions/codex-review-policy/action.yml @@ -0,0 +1,15 @@ +name: Validate Codex review policy +description: Verify managed AGENTS.md sections against the latest published ThatFactory review policy. +inputs: + profile: + description: Consumer adoption profile (full or review-only). + required: true +runs: + using: composite + steps: + - name: Check latest published review policy + shell: bash + env: + POLICY_ACTION_PATH: ${{ github.action_path }} + POLICY_PROFILE: ${{ inputs.profile }} + run: swift "$POLICY_ACTION_PATH/../../../Scripts/sync_codex_review_policy.swift" check --consumer-root "$GITHUB_WORKSPACE" --profile "$POLICY_PROFILE" diff --git a/.github/workflows/ci-pr.yml b/.github/workflows/ci-pr.yml deleted file mode 100644 index 7ed9b55..0000000 --- a/.github/workflows/ci-pr.yml +++ /dev/null @@ -1,45 +0,0 @@ ---- -name: Pull Request CI - -on: - pull_request: - types: [opened, synchronize, reopened] - -concurrency: - group: ${{ github.workflow }}-${{ github.ref }} - cancel-in-progress: true - -jobs: - format: - name: Swift Format - runs-on: [self-hosted, macOS] - steps: - - name: Checkout Repository - uses: actions/checkout@v7 - - - name: Lint Swift Sources - run: | - AgentGuidelines/Scripts/swift_format.sh lint-strict \ - Package.swift \ - Sources \ - Tests - - test: - name: Test - runs-on: [self-hosted, macOS] - steps: - - name: Checkout Repository - uses: actions/checkout@v7 - with: - clean: true - - - name: Clear SwiftPM Caches - run: | - rm -rf ~/.swiftpm - rm -rf ~/Library/Caches/org.swift.swiftpm - rm -rf ~/Library/org.swift.swiftpm - rm -rf .swiftpm - rm -rf .build - - - name: Run Tests - run: swift test -v diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3b68c6d..d52ab0d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,46 +1,25 @@ ---- name: CI on: + pull_request: push: branches: - main -concurrency: - group: ${{ github.workflow }}-${{ github.ref }} - cancel-in-progress: true +permissions: + contents: read jobs: - format: - name: Swift Format - runs-on: [self-hosted, macOS] + validate: + name: Validate guidelines + runs-on: macos-latest steps: - - name: Checkout Repository + - name: Checkout uses: actions/checkout@v7 - - name: Lint Swift Sources + - name: Validate run: | - AgentGuidelines/Scripts/swift_format.sh lint-strict \ - Package.swift \ - Sources \ - Tests - - test: - name: Test - runs-on: [self-hosted, macOS] - steps: - - name: Checkout Repository - uses: actions/checkout@v7 - with: - clean: true - - - name: Clear SwiftPM Caches - run: | - rm -rf ~/.swiftpm - rm -rf ~/Library/Caches/org.swift.swiftpm - rm -rf ~/Library/org.swift.swiftpm - rm -rf .swiftpm - rm -rf .build - - - name: Run Tests - run: swift test -v + Tests/run_tests.swift + Tests/run_review_policy_tests.swift + Scripts/validate_guidelines.swift + Scripts/sync_codex_review_policy.swift check --local-source . --profile central diff --git a/.github/workflows/nightly.yml b/.github/workflows/nightly.yml deleted file mode 100644 index df1de94..0000000 --- a/.github/workflows/nightly.yml +++ /dev/null @@ -1,31 +0,0 @@ ---- -name: Nightly Tests - -on: - schedule: - - cron: '0 4 * * *' - -concurrency: - group: ${{ github.workflow }}-${{ github.ref }} - cancel-in-progress: true - -jobs: - nightly_tests: - name: Nightly Tests - runs-on: [self-hosted, macOS] - steps: - - name: Checkout Repository - uses: actions/checkout@v7 - with: - clean: true - - - name: Clear SwiftPM Caches - run: | - rm -rf ~/.swiftpm - rm -rf ~/Library/Caches/org.swift.swiftpm - rm -rf ~/Library/org.swift.swiftpm - rm -rf .swiftpm - rm -rf .build - - - name: Run Tests - run: swift test -v diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 0d98226..e35642c 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,109 +1,48 @@ ---- name: Release -run-name: Release ${{ github.event.release.tag_name }} on: - release: - types: - - published + push: + tags: + - "*.*.*" permissions: - contents: read - pages: write - id-token: write - -concurrency: - group: ${{ github.workflow }}-${{ github.ref }} - cancel-in-progress: true + contents: write jobs: - test: - name: Test Release - runs-on: [self-hosted, macOS] + release: + name: Create GitHub release + runs-on: macos-latest steps: - - name: Checkout Repository + - name: Checkout uses: actions/checkout@v7 - with: - clean: true - - name: Clear SwiftPM Caches + - name: Validate guidelines run: | - rm -rf ~/.swiftpm - rm -rf ~/Library/Caches/org.swift.swiftpm - rm -rf ~/Library/org.swift.swiftpm - rm -rf .swiftpm - rm -rf .build - - - name: Run Tests - run: swift test -v + Tests/run_tests.swift + Tests/run_review_policy_tests.swift + Scripts/validate_guidelines.swift + Scripts/sync_codex_review_policy.swift check --local-source . --profile central - build_docs: - name: Build DocC - runs-on: [self-hosted, macOS] - needs: test - steps: - - name: Checkout Repository - uses: actions/checkout@v7 - with: - clean: true - - - name: Generate DocC + - name: Validate tag run: | - set -euo pipefail - swift package --allow-writing-to-directory ./public generate-documentation \ - --target ProgressionKit \ - --disable-indexing \ - --output-path ./public \ - --transform-for-static-hosting \ - --hosting-base-path progressionkit - - cat > ./public/index.html <<'INDEX' - - - ProgressionKit Documentation - INDEX + version="$(tr -d '[:space:]' < VERSION)" + test "$GITHUB_REF_NAME" = "$version" - - name: Upload Pages Artifact - uses: actions/upload-pages-artifact@v5 - with: - path: ./public - name: github-pages - - deploy_docs: - name: Deploy DocC - needs: build_docs - runs-on: ubuntu-latest - environment: - name: github-pages - url: ${{ steps.deployment.outputs.page_url }} - steps: - - name: Deploy to GitHub Pages - id: deployment - uses: actions/deploy-pages@v5 - - notify_package_collection: - name: Notify Package Collection - runs-on: ubuntu-latest - needs: deploy_docs - steps: - - name: Trigger Swift Package Collection Rebuild + - name: Prepare release notes + run: | + version="$(tr -d '[:space:]' < VERSION)" + awk -v version="$version" ' + index($0, "## [" version "]") == 1 { capture = 1; next } + capture && /^## \[/ { exit } + capture { print } + ' CHANGELOG.md > release-notes.md + test -s release-notes.md + + - name: Create release env: - COLLECTION_REPO: thatfactory/swift-package-collection - WORKFLOW_FILE: publish.yml - REF: main - GH_TOKEN: ${{ secrets.COLLECTION_TRIGGER_TOKEN }} - SOURCE_REPO: ${{ github.repository }} - SOURCE_VERSION: ${{ github.event.release.tag_name }} + GH_TOKEN: ${{ github.token }} run: | - set -euo pipefail - - if [ -z "${GH_TOKEN:-}" ]; then - echo "Missing COLLECTION_TRIGGER_TOKEN secret" - exit 1 - fi - - curl -sS -X POST \ - -H "Accept: application/vnd.github+json" \ - -H "Authorization: Bearer $GH_TOKEN" \ - "https://api.github.com/repos/$COLLECTION_REPO/actions/workflows/$WORKFLOW_FILE/dispatches" \ - -d "{\"ref\":\"$REF\",\"inputs\":{\"source_repo\":\"$SOURCE_REPO\",\"source_version\":\"$SOURCE_VERSION\"}}" + gh release create "$GITHUB_REF_NAME" \ + --verify-tag \ + --title "$GITHUB_REF_NAME" \ + --notes-file release-notes.md diff --git a/.gitignore b/.gitignore index 08c2ed7..3a3fc11 100644 --- a/.gitignore +++ b/.gitignore @@ -1,11 +1,66 @@ +# macOS .DS_Store -/.build -/Packages -/*.xcodeproj -*.xcworkspace + +# Xcode user data, build output, and archives xcuserdata/ -Package.resolved -DerivedData/ +*.pbxuser +!default.pbxuser +*.mode1v3 +!default.mode1v3 +*.mode2v3 +!default.mode2v3 +*.perspectivev3 +!default.perspectivev3 +*.moved-aside +*.xccheckout +*.xcscmblueprint +*.hmap +/build/ +/DerivedData/ +*.ipa +*.dSYM +*.dSYM.zip + +# Xcode playground generated state +timeline.xctimeline +playground.xcworkspace + +# Swift Package Manager +/.build/ +/Packages/ .swiftpm/configuration/registries.json + +# Node.js +node_modules/ +dist/ +coverage/ +*.tgz +npm-debug.log* +yarn-debug.log* +yarn-error.log* + +# Python +__pycache__/ +*.py[cod] +.venv/ +venv/ +.pytest_cache/ +.mypy_cache/ +.ruff_cache/ +.coverage +htmlcov/ + +# Local credentials and environment configuration +.env +.env.* +!.env.example +!.env.*.example .netrc + +# ThatFactory tooling state +.appstore-connect-mcp/ +.devspace/ /public-check/ + +# Project-specific entries require a durable rationale after repository-owner review. +# Project-specific: diff --git a/.swift-format b/.swift-format deleted file mode 120000 index 06f3229..0000000 --- a/.swift-format +++ /dev/null @@ -1 +0,0 @@ -AgentGuidelines/Configurations/Swift/.swift-format \ No newline at end of file diff --git a/AGENTS.md b/AGENTS.md index 2516863..7db1e04 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,69 +1,94 @@ -# ProgressionKit +# Agent Guidelines -## Context +## Purpose -ProgressionKit is a pure Swift package for deterministic XP, player levels, track mastery, and tier unlocks. Read [README.md](README.md) and the DocC catalog before changing public behavior. +This public repository is the versioned source of truth for reusable ThatFactory agent guidance. Keep it generic enough to apply to multiple applications and Swift packages. Product decisions, concrete project paths, and exceptions belong in each consumer repository. -The package is content-, storage-, UI-, and application-architecture agnostic. Host applications decide what content, tracks, tiers, persistence, and presentation mean. +## Sources of truth -## Shared guidelines +- Use official Apple documentation for Apple APIs and Xcode behavior. +- Distill durable policy from Xcode-provided skills; do not copy exported Apple skills into this repository. +- Do not include private company information, credentials, personal absolute paths, or consumer-specific implementation details. +- When shared and consumer guidance differ, the consumer's nearest applicable `AGENTS.md` is the explicit specialization. +- Before changing this repository, verify that the consumer's checked-in guidelines version is current where applicable. -Read only the guides relevant to the task: +## Documentation changes -- [Agent workflow](AgentGuidelines/Guidelines/AgentWorkflow.md) -- [Swift](AgentGuidelines/Guidelines/Swift/Swift.md) -- [Swift style](AgentGuidelines/Guidelines/Swift/SwiftStyle.md) -- [Swift format](AgentGuidelines/Guidelines/Swift/SwiftFormat.md) -- [Unit and integration testing](AgentGuidelines/Guidelines/Testing/UnitTesting.md) -- [Documentation](AgentGuidelines/Guidelines/Documentation.md) -- [Logging](AgentGuidelines/Guidelines/Logging.md) -- [Packages](AgentGuidelines/Guidelines/Packages.md) -- [Development workflow](AgentGuidelines/Guidelines/Development.md) -- [CI/CD](AgentGuidelines/Guidelines/CICD.md) -- [Git repositories and SSH-first cloning](AgentGuidelines/Guidelines/Git/Repositories.md) -- [GitHub pull requests](AgentGuidelines/Guidelines/GitHub/PullRequests.md) -- [Xcode MCP](AgentGuidelines/Guidelines/Xcode/MCP.md) -- [Xcode security audits](AgentGuidelines/Guidelines/Xcode/Security.md) +- Keep each rule in the narrowest relevant guide and link to it rather than duplicating it. +- Use physical folder terminology for Xcode projects. Do not call filesystem folders Xcode groups. +- Keep examples generic and concise. +- Use relative Markdown links inside this repository. +- Update `README.md` when adding, moving, or removing a guide. +- Keep the README guideline catalog sorted alphabetically by link label. +- Update `CHANGELOG.md` and `VERSION` for a release. +- When releasing a new version, update the version in both the README installation command and the README consumer-update command. Keep both commands aligned with the new release, for example: -Redux, SwiftUI, and application-localization guidance do not apply to the package target. + ```sh + git subtree add \ + --prefix=AgentGuidelines \ + https://github.com/thatfactory/agent-guidelines.git \ + \ + --squash - + git subtree pull \ + --prefix=AgentGuidelines \ + https://github.com/thatfactory/agent-guidelines.git \ + \ + --squash + ``` + +## Repository scripts + +- Write new repository-owned executable scripts in Swift using the standard library and Foundation. +- `Scripts/swift_format.sh` is the sole retained shell-script exception because it is the existing command wrapper around Xcode's `swift-format`; do not use it as precedent for new shell automation. +- Do not add Python, Ruby, JavaScript, or other scripting-language runtimes for repository automation. + + + ## Code Review Rules -Review for release-blocking defects introduced or materially exposed by the pull request. A clean review means no unresolved P0/P1 findings; it does not mean exhaustive or perfect software. +Report only substantiated P0/P1 defects introduced or materially exposed by this change. Require a concrete, reachable failure in a supported use case or documented threat model, with serious impact such as a security-boundary bypass, durable data loss or corruption, a crash or deadlock in an important workflow, loss of availability, or a serious compatibility regression. An acceptance-criterion violation alone does not establish P1 severity. + +For each finding, state severity, preconditions, execution path, impact, evidence, and actionable remediation. Group manifestations of one root cause. Report substantiated blockers together. Omit unsolicited P2/P3 observations, style preferences, speculative hardening, optional tests, and refactors. A clean review means no unresolved P0/P1 blockers, not perfect software. + +A follow-up review covers unresolved P0/P1 findings, changes since the previous reviewed commit, and directly affected code. Do not restart a full review of unchanged code. New follow-up findings must be P0/P1 defects introduced by remediation or genuinely hidden by the previous blocker. + + + +## Pull Request Lifecycle + +Finish implementation, inspect the diff, and run relevant local validation before opening a ready-for-review PR. Drafts are for incomplete preparation; mark ready before waiting for automatic review. Keep the review head stable while the initial review runs. One automatic Codex review is the initial review; never duplicate it with a manual request or repeatedly toggle draft/ready state. + +Establish review configuration from repository-specific evidence. Verify the bot, PR, review round, and reviewed commit using PR/request-comment reactions, review submissions, inline threads, and checks. Eyes means processing, not approval; a thumbs-up means no suggestions only for its verified review round. Historical reactions, missing comments, and elapsed time never certify a newer head. Monitor at most five minutes total with bounded, non-accelerating polls; timeout leaves a required gate unresolved and never authorizes merge. -A blocking finding must identify a concrete, reachable path in a supported use case or the documented threat model that can cause a credible security-boundary bypass, durable data loss or corruption, a crash or deadlock, loss of availability, violation of an explicit acceptance criterion, or a serious compatibility regression. +Batch accepted P0/P1 fixes, verify them locally, rerun affected checks, and disposition and resolve every review thread. A completed initial review plus an explicitly recorded, locally verified remediation-only delta can satisfy the review gate; do not claim Codex reviewed the newer head. New unrelated scope belongs in another PR. Request at most one delta-scoped verification only when the owner explicitly authorizes it. Do not request reviews after every fix or casually mention the bot to start extra work. Separate Security Review is manual and requires explicit owner instruction. -For every blocking finding, state the severity, preconditions, execution path, impact, evidence, and actionable remediation. Group manifestations that share the same root cause into one finding. +Before merge, rerun the latest published review-policy check, confirm no required review is pending, no unresolved P0/P1 blocker remains, every thread is dispositioned and resolved, required checks pass on the current head, and existing human approval or merge authorization is satisfied. A bot thumbs-up is not a substitute for required GitHub approval. Opening a PR does not authorize merging it. + -Treat P2/P3 observations as non-blocking, including defense-in-depth, theoretical completeness, unsupported use cases, malformed state that trusted code cannot produce, behavior by components outside the threat model, style preferences, and speculative refactoring. Record a useful lower-severity observation once as deferred, declined, duplicate, or follow-up work; do not keep the review loop open for it. +## Validation -In an initial review, report substantiated blockers together. A follow-up review is limited to unresolved P0/P1 findings, changes since the last reviewed commit, and code directly affected by those changes. Do not restart an unrestricted review of unchanged code. A new follow-up finding must be a P0/P1 defect introduced by the remediation or genuinely hidden by the previous blocker. +Run: -Automatic Codex review is the initial review. Do not request a manual Codex review unless the repository owner explicitly asks. Never request another review after each remediation commit. Within the normal review budget, at most one owner-authorized, delta-scoped verification review may be requested under [the pull-request review workflow](AgentGuidelines/Guidelines/GitHub/PullRequests.md). - +```sh +Scripts/validate_guidelines.swift +Tests/run_tests.swift +Scripts/sync_codex_review_policy.swift check --local-source . --profile central +``` -## Physical folder map +Fix every validation failure before releasing a version. -| Role | Physical folder | -|---|---| -| Package sources | `Sources/ProgressionKit/` | -| DocC catalog | `Sources/ProgressionKit/ProgressionKit.docc/` | -| Unit tests | `Tests/ProgressionKitTests/` | +## Consumer pull-request review scope -## CI/CD +When reviewing a consumer pull request, do not review or comment on files under `AgentGuidelines/**` after exact tagged-tree provenance has been verified. That subtree is a tracked, synchronized copy marked `linguist-generated`; substantive guideline changes are reviewed in this repository. Verify the intended `AgentGuidelines/VERSION`, compare the subtree tree with the matching central tag (for example by comparing `git rev-parse HEAD:AgentGuidelines` with the fetched tag's root tree), and verify the required `.gitattributes` rule. If provenance does not match exactly, review the subtree contents and stop the merge. Report substantive guideline feedback against the central `agent-guidelines` pull request instead. -- Swift package CI uses the self-hosted runner labels `self-hosted` and `macOS`. -- Pull-request validation runs from `.github/workflows/ci-pr.yml`; protected-branch validation runs from `.github/workflows/ci.yml`. +## Releases -## Package specialization +- Use semantic versioning. +- Create a Git tag and GitHub release matching `VERSION`. +- Consumer repositories adopt releases deliberately through Git subtree updates. +- Follow [the pull-request review workflow](Guidelines/GitHub/PullRequests.md) before merging any release change. -- Keep progression updates deterministic for the same profile, event, and configuration. -- Do not add storage, network, UI, Redux, or game-content dependencies. -- Host applications own mapping from their domain identifiers and outcomes into `PKEvent`. -- Preserve compiler-synthesized value semantics and serialization when evolving public models. -- Update tests, DocC, README examples, and release notes when public behavior changes. -- Use logging subsystem `com.thatfactory.progressionkit`, category `progression`, and canonical package emoji `📈`. -## Codex review scope +## Repository review configuration -For consumer pull requests, do not substantively review `AgentGuidelines/**` after exact tagged-tree provenance has been verified. Verify its `VERSION`, compare its tree with the matching central tag, and verify the required `.gitattributes` rule. If provenance does not match exactly, review the subtree contents and stop the merge. Report substantive guideline feedback against the central `agent-guidelines` pull request. +The owner confirmed automatic Codex review is enabled for this repository on 2026-11-06. Use all PR authors and the opening/ready trigger, keep exhaustive review off, and keep separate Security Review manual. Apply the managed lifecycle and [review-policy integration](ReviewPolicy/README.md). diff --git a/AgentGuidelines/.agents/skills/agent-guidelines-audit/SKILL.md b/AgentGuidelines/.agents/skills/agent-guidelines-audit/SKILL.md deleted file mode 100644 index 2110942..0000000 --- a/AgentGuidelines/.agents/skills/agent-guidelines-audit/SKILL.md +++ /dev/null @@ -1,73 +0,0 @@ ---- -name: agent-guidelines-audit -description: Audit completed repository work and checked-in consumer integration against applicable agent-guidelines, local AGENTS.md instructions, requested scope, and declared validation workflow. Use after implementing changes and before claiming completion, handing work to the user, preparing, opening, or updating a pull request, declaring merge readiness, or preparing a release. Do not use for simple answers, read-only exploration, or work that is still actively being implemented. ---- - -# Agent Guidelines Audit - -Perform a final, evidence-based compliance pass. Treat the applicable guidelines and local instructions as the source of truth; do not duplicate their full content in this skill. - -## Establish the audit scope - -1. Re-read the user request and list every requested outcome and explicit constraint. -2. Locate the repository root and every applicable `AGENTS.md` from the current directory to that root. -3. Read the shared guides referenced by those instructions that apply to the changed files and workflow. -4. Inspect `git status`, the complete diff, and relevant untracked files. Preserve unrelated user changes. -5. Check the consumer's `AgentGuidelines/VERSION` and provenance when the task changes or depends on the synchronized subtree. Do not update it implicitly. -6. When the repository contains an `AgentGuidelines/` subtree, run `python3 AgentGuidelines/Scripts/validate_consumer_setup.py` from the consumer root. The validator detects Swift-format adoption from the root `AGENTS.md`; add `--require-swift-format` only when the repository must adopt it before that link is present. Treat failures as integration drift to fix or report before handoff. - -Do not inspect or require the user's global Codex instructions. They are user-level state outside the repository audit boundary; validate the checked-in root `AGENTS.md` contract instead. - -## Audit the implementation - -Review the actual change rather than only checking whether files exist: - -- Confirm every requested outcome is implemented and no material behavior was dropped. -- Confirm physical folders, familiar domain grouping, filenames, declaration order, type ownership, namespacing, documentation, and `MARK` organization follow the applicable guides. Distinguish values that describe data from tools that primarily execute algorithms or accumulate behavior. -- For Redux applications, trace actions, state, reducers, middleware, services, tools, presentation models, views, and side-effect results through the complete data flow. Confirm each Redux component folder contains only that component type. -- Check that framework objects, persistence, logging, and asynchronous work remain in their allowed boundaries. -- Check SwiftUI composition, narrow inputs, local versus durable state, localization, accessibility, and safe deterministic previews where applicable. -- Check tests for the required framework, mirrored paths, shared tags, Given/When/Then structure, deterministic seams, and coverage of changed behavior and failure paths. -- Check logging ownership, subsystem, categories, emoji, privacy, severity, metadata stability, and noise controls when logging changed. -- Check durable documentation, package configuration, CI/CD, Xcode project configuration, security-sensitive changes, and physical-device limitations when they are in scope. Compare documented Swift and concurrency settings with the effective application and test-target settings; flag both redundant isolation annotations and missing annotations at compiler-verified boundaries. -- Search for stale type names, superseded files, direct APIs forbidden by the new architecture, empty folders, and references to removed behavior. -- For pull-request or merge readiness, apply the root `## Code Review Rules`: confirm the review covers the current head, no allowed review round is pending, every thread has a disposition, and no unresolved P0/P1 blocker remains. Treat P2/P3 observations as non-blocking and never request another Codex review unless the repository owner explicitly authorizes it. - -## Validate the evidence - -Run the repository's declared non-destructive checks in proportion to the change: - -- formatter and strict lint; -- focused tests, followed by the declared broader test plan when warranted; -- relevant builds or package validation; -- repository-specific validators; -- `git diff --check`. - -When the shared Swift-format guide applies: - -- For implementation work, run `AgentGuidelines/Scripts/swift_format.sh format-and-lint` over every changed or applicable checked-in Swift source root before tests. For review-only work, use `lint-strict` so the audit does not mutate files. -- Confirm the root `.swift-format` and `.editorconfig` symlinks resolve to the synchronized shared configurations. -- Confirm pull-request and protected-branch CI run the shared wrapper with `lint-strict` in a dedicated non-mutating job. Reject `format` or `format-and-lint` in CI and verify the listed paths cover the repository's checked-in Swift roots. -- For Xcode projects, verify every independently buildable app or test target has the target-scoped pre-compilation phase described by the guide, including its `CI=true` bypass. -- For Swift packages, format `Package.swift`, `Sources`, `Tests`, and other checked-in Swift roots that exist before running `swift test`. Do not require `swift build` or `swift test` themselves to rewrite source; formatting and testing are consecutive, independently visible checks. - -Use fresh successful evidence already produced in the same task instead of rerunning expensive checks without reason. Distinguish automated compilation and simulator evidence from hardware, signing, deployment, or manual validation that automation cannot prove. - -## Resolve findings - -- When the user authorized implementation, fix safe in-scope findings and rerun the affected checks. -- For review-only work, report findings without modifying code. -- Do not broaden the feature, rewrite unrelated files, edit a synchronized `AgentGuidelines/` subtree, or perform commits, pushes, pull requests, merges, tags, or releases without the required authority. -- Treat an unresolved required guideline violation or missing relevant validation as a blocker to claiming completion. - -## Hand off - -Summarize: - -- the instruction and guideline areas audited; -- consumer-integration validation and any drift found; -- findings fixed during the audit; -- validation commands and outcomes; -- any deliberate deviations, unavailable evidence, or remaining blockers. - -Do not say the work is done merely because the audit ran. Say it is ready only when the requested outcome is complete and the relevant evidence passes. diff --git a/AgentGuidelines/.github/workflows/ci.yml b/AgentGuidelines/.github/workflows/ci.yml deleted file mode 100644 index 5831117..0000000 --- a/AgentGuidelines/.github/workflows/ci.yml +++ /dev/null @@ -1,23 +0,0 @@ -name: CI - -on: - pull_request: - push: - branches: - - main - -permissions: - contents: read - -jobs: - validate: - name: Validate guidelines - runs-on: ubuntu-latest - steps: - - name: Checkout - uses: actions/checkout@v7 - - - name: Validate - run: | - python3 -m unittest discover -s Tests - python3 Scripts/validate_guidelines.py diff --git a/AgentGuidelines/.github/workflows/release.yml b/AgentGuidelines/.github/workflows/release.yml deleted file mode 100644 index 20b4c8f..0000000 --- a/AgentGuidelines/.github/workflows/release.yml +++ /dev/null @@ -1,44 +0,0 @@ -name: Release - -on: - push: - tags: - - "*.*.*" - -permissions: - contents: write - -jobs: - release: - name: Create GitHub release - runs-on: ubuntu-latest - steps: - - name: Checkout - uses: actions/checkout@v7 - - - name: Validate guidelines - run: python3 Scripts/validate_guidelines.py - - - name: Validate tag - run: | - version="$(tr -d '[:space:]' < VERSION)" - test "$GITHUB_REF_NAME" = "$version" - - - name: Prepare release notes - run: | - version="$(tr -d '[:space:]' < VERSION)" - awk -v version="$version" ' - index($0, "## [" version "]") == 1 { capture = 1; next } - capture && /^## \[/ { exit } - capture { print } - ' CHANGELOG.md > release-notes.md - test -s release-notes.md - - - name: Create release - env: - GH_TOKEN: ${{ github.token }} - run: | - gh release create "$GITHUB_REF_NAME" \ - --verify-tag \ - --title "$GITHUB_REF_NAME" \ - --notes-file release-notes.md diff --git a/AgentGuidelines/.gitignore b/AgentGuidelines/.gitignore deleted file mode 100644 index dff2f41..0000000 --- a/AgentGuidelines/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -.DS_Store -__pycache__/ -*.py[cod] diff --git a/AgentGuidelines/AGENTS.md b/AgentGuidelines/AGENTS.md deleted file mode 100644 index f82a61c..0000000 --- a/AgentGuidelines/AGENTS.md +++ /dev/null @@ -1,75 +0,0 @@ -# Agent Guidelines - -## Purpose - -This public repository is the versioned source of truth for reusable ThatFactory agent guidance. Keep it generic enough to apply to multiple applications and Swift packages. Product decisions, concrete project paths, and exceptions belong in each consumer repository. - -## Sources of truth - -- Use official Apple documentation for Apple APIs and Xcode behavior. -- Distill durable policy from Xcode-provided skills; do not copy exported Apple skills into this repository. -- Do not include private company information, credentials, personal absolute paths, or consumer-specific implementation details. -- When shared and consumer guidance differ, the consumer's nearest applicable `AGENTS.md` is the explicit specialization. -- Before changing this repository, verify that the consumer's checked-in guidelines version is current where applicable. - -## Documentation changes - -- Keep each rule in the narrowest relevant guide and link to it rather than duplicating it. -- Use physical folder terminology for Xcode projects. Do not call filesystem folders Xcode groups. -- Keep examples generic and concise. -- Use relative Markdown links inside this repository. -- Update `README.md` when adding, moving, or removing a guide. -- Keep the README guideline catalog sorted alphabetically by link label. -- Update `CHANGELOG.md` and `VERSION` for a release. -- When releasing a new version, update the version in both the README installation command and the README consumer-update command. Keep both commands aligned with the new release, for example: - - ```sh - git subtree add \ - --prefix=AgentGuidelines \ - https://github.com/thatfactory/agent-guidelines.git \ - \ - --squash - - git subtree pull \ - --prefix=AgentGuidelines \ - https://github.com/thatfactory/agent-guidelines.git \ - \ - --squash - ``` - - -## Code Review Rules - -Review for release-blocking defects introduced or materially exposed by the pull request. A clean review means no unresolved P0/P1 findings; it does not mean exhaustive or perfect software. - -A blocking finding must identify a concrete, reachable path in a supported use case or the documented threat model that can cause a credible security-boundary bypass, durable data loss or corruption, a crash or deadlock, loss of availability, violation of an explicit acceptance criterion, or a serious compatibility regression. - -For every blocking finding, state the severity, preconditions, execution path, impact, evidence, and actionable remediation. Group manifestations that share the same root cause into one finding. - -Treat P2/P3 observations as non-blocking, including defense-in-depth, theoretical completeness, unsupported use cases, malformed state that trusted code cannot produce, behavior by components outside the threat model, style preferences, and speculative refactoring. Record a useful lower-severity observation once as deferred, declined, duplicate, or follow-up work; do not keep the review loop open for it. - -In an initial review, report substantiated blockers together. A follow-up review is limited to unresolved P0/P1 findings, changes since the last reviewed commit, and code directly affected by those changes. Do not restart an unrestricted review of unchanged code. A new follow-up finding must be a P0/P1 defect introduced by the remediation or genuinely hidden by the previous blocker. - -Automatic Codex review is the initial review. Do not request a manual Codex review unless the repository owner explicitly asks. Never request another review after each remediation commit. Within the normal review budget, at most one owner-authorized, delta-scoped verification review may be requested under [the pull-request review workflow](Guidelines/GitHub/PullRequests.md). - - -## Validation - -Run: - -```sh -python3 Scripts/validate_guidelines.py -``` - -Fix every validation failure before releasing a version. - -## Consumer pull-request review scope - -When reviewing a consumer pull request, do not review or comment on files under `AgentGuidelines/**` after exact tagged-tree provenance has been verified. That subtree is a tracked, synchronized copy marked `linguist-generated`; substantive guideline changes are reviewed in this repository. Verify the intended `AgentGuidelines/VERSION`, compare the subtree tree with the matching central tag (for example with `git subtree split --prefix=AgentGuidelines HEAD` and a tree comparison after fetching that tag), and verify the required `.gitattributes` rule. If provenance does not match exactly, review the subtree contents and stop the merge. Report substantive guideline feedback against the central `agent-guidelines` pull request instead. - -## Releases - -- Use semantic versioning. -- Create a Git tag and GitHub release matching `VERSION`. -- Consumer repositories adopt releases deliberately through Git subtree updates. -- Follow [the pull-request review workflow](Guidelines/GitHub/PullRequests.md) before merging any release change. diff --git a/AgentGuidelines/CHANGELOG.md b/AgentGuidelines/CHANGELOG.md deleted file mode 100644 index 1600a67..0000000 --- a/AgentGuidelines/CHANGELOG.md +++ /dev/null @@ -1,168 +0,0 @@ -# Changelog - -All notable changes to this project are documented in this file. - -## [0.0.18] - 2026-08-18 - -### Changed - -- Corrected the standard README badge order to place DocC/documentation before license, updated date, revision, CI badges, and release/publishing status. - -## [0.0.17] - 2026-08-18 - -### Added - -- A version-marked consumer Code Review contract that defines P0/P1 release blockers, non-blocking P2/P3 observations, and bounded follow-up review scope. -- A deterministic consumer-setup validator for review-contract drift, subtree review scope, `.gitattributes`, local guide links, audit-skill wiring, and Swift-format adoption. - -### Changed - -- Expanded the global Codex instruction template and pull-request workflow to prioritize concrete release risk, group shared root causes, and stop review loops after blockers are resolved. -- Extended the completion-audit skill to verify consumer integration, review convergence, Swift-format configuration, local execution, and non-mutating CI coverage. -- Documented explicit Swift package formatting before tests and added a strict Swift-format CI template with package path coverage. - -## [0.0.16] - 2026-08-13 - -### Changed - -- Required SwiftUI dynamic properties to precede ordinary stored properties and clarified deterministic preview expectations. -- Required one top-level type per file, focused function decomposition, logical enum grouping, and consistent declaration-modifier and multiline-signature layout. -- Documented which declaration layout conventions remain review-guided because swift-format cannot enforce them without broad source reflow. - -## [0.0.15] - 2026-07-27 - -### Added - -- A shared agent-workflow guide for bounded grouping of independent repository inspections, with dependency, ordering, scope, and output-size safeguards. -- A versioned global Codex instruction template that bootstraps discovery of repository-local guidance without duplicating engineering policy. - -### Changed - -- Linked the workflow guide from the consumer template, documented the manual global Codex setup, and required alphabetical ordering of the README guideline catalog. -- Clarified that Codex review requests are automatic by default and must not be triggered manually without an explicit user request. - -## [0.0.14] - 2026-07-27 - -### Changed - -- Clarify Store/Middleware @MainActor usage. -- Removed workaround for a resolved Xcode issue. - -## [0.0.13] - 2026-07-26 - -### Added - -- A reusable `agent-guidelines-audit` skill and mandatory completion gate before handoff, pull requests, merge readiness, and releases. -- A canonical Redux Store template plus dependency-container and middleware-composition guidance. -- Consumer Stack guidance for recording toolchain, platform, strict-concurrency, and actor-isolation settings. - -### Changed - -- Clarified Redux folder ownership, familiar domain grouping, model-versus-tool classification, service-local helpers, presentation models, and one-component-per-file organization. -- Required documentation for new Swift declarations, meaningful `MARK` sections, one meaningful SwiftUI view per file, and deterministic previews where possible. -- Clarified when target isolation defaults replace explicit annotations and when compiler-verified boundaries still require them. -- Enabled conditional-import sorting and expanded validation for Swift templates, the audit skill, Stack guidance, and formatting policy. - -## [0.0.12] - 2026-07-25 - -### Added - -- Login-shell guidance for using explicitly authorized `gh` credentials exported by local shell startup configuration without exposing token values. - -## [0.0.11] - 2026-07-25 - -### Added - -- Pre-compilation Xcode build-phase guidance and a reusable `format-and-lint` command for human and agent workflows. -- An easy-to-find record of Xcode-aligned layout settings, enabled rule overrides, and deliberate non-adoptions. -- Pull-request guidance that prevents duplicate manual Codex requests when automatic review is enabled. - -### Changed - -- Enabled empty-array literals, force-try rejection, brace whitespace cleanup, `where` clauses in eligible loops, and documentation-comment validation. - -## [0.0.10] - 2026-07-24 - -### Added - -- Shared Xcode-aligned swift-format and EditorConfig configuration. -- Reusable format, warning-lint, and strict-lint commands for Swift consumers. - -### Changed - -- Replaced SwiftLint guidance with toolchain-native swift-format guidance. - -## [0.0.9] - 2026-07-23 - -### Added - -- Consumer pull-request review scope that excludes synchronized `AgentGuidelines/**` files from substantive Codex and human review outside the central repository. - -## [0.0.8] - 2026-07-23 - -### Added - -- Consumer guidance for keeping `AgentGuidelines/` tracked while collapsing synchronized files in GitHub pull-request diffs with `.gitattributes`. -- Pull-request conventions for isolated subtree commits, explicit version notes, central review links, and continued CI validation. - -## [0.0.7] - 2026-07-23 - -### Added - -- Shared logging ownership, subsystem, package emoji, message design, privacy, testing, and filtering guidance. -- Logging pointers for application development, Swift packages, and consumer instruction templates. - -## [0.0.6] - 2026-07-22 - -### Added - -- Generic Redux store contracts, state/action, service-boundary, projection, and middleware guidance. -- Generic GitHub Actions workflow, self-hosted runner, build strategy, and failure-investigation guidance. -- Shared documentation conventions and test-tag/mock guidance. - -## [0.0.5] - 2026-07-21 - -### Added - -- Default DocC documentation and GitHub Pages publishing guidance for Swift packages. - -## [0.0.4] - 2026-07-21 - -### Added - -- Development guidance for reusability-first design and checking the latest shared-guidelines version before project work. - -### Changed - -- Require an approved pull request before releasing `agent-guidelines` or any consumer package. - -## [0.0.3] - 2026-07-21 - -### Added - -- A Codex review-monitoring workflow covering paginated processing reactions and review threads, clean reviews, inline feedback, replies, thread resolution, and CI checks. - -## [0.0.2] - 2026-07-21 - -### Added - -- Standard README badge conventions for ThatFactory projects and packages. -- Git repository guidance that defaults push-capable clones to SSH remotes. -- GitHub pull-request review and merge-gate guidance. -- Updated and Revision badges to the repository README. - -### Changed - -- Updated GitHub workflows to `actions/checkout@v7` and documented using current stable action versions in new workflows. -- Clarified the Redux side-effect loop and the canonical view-projection test path. -- Expanded and tested semantic-version validation to support prerelease plus build metadata and reject invalid numeric identifiers. -- Removed the redundant README license section while retaining the MIT license badge and root license file. - -## [0.0.1] - 2026-07-21 - -### Added - -- Initial shared guidelines for Redux, Swift, SwiftUI, SwiftLint, localization, testing, documentation, package maintenance, CI/CD, Xcode MCP, and Xcode security audits. -- A consumer `AGENTS.md` template and Git subtree installation workflow. -- Structural validation for links, the documentation catalog, version metadata, subtree instructions, and public-repository safety. -- A tag-driven GitHub release workflow that validates the tag against `VERSION` and publishes changelog notes. diff --git a/AgentGuidelines/Guidelines/CICD.md b/AgentGuidelines/Guidelines/CICD.md deleted file mode 100644 index c420331..0000000 --- a/AgentGuidelines/Guidelines/CICD.md +++ /dev/null @@ -1,63 +0,0 @@ -# CI/CD - -## Workflow principles - -- Keep CI deterministic, reproducible, and aligned with the repository's supported Xcode, Swift, and platform versions. -- Treat warnings introduced by a change as failures even when the compiler does not. -- Prefer the smallest permissions required by each workflow and job. -- For a new workflow, use the latest stable major version of every GitHub Action available at the time of creation. -- Do not copy an older major version into a fresh workflow unless a documented compatibility constraint requires it. -- For existing workflows, review action release notes and update deliberately rather than allowing runtime deprecation warnings to accumulate. -- Pin third-party actions to an intentional version and review updates. -- Do not place secrets in workflow files, logs, fixtures, or command arguments that may be echoed. -- Keep release workflows separate from pull-request validation when their permissions differ. - -## `ci-pr.yml` - -Projects using GitHub Actions should keep pull-request validation in `.github/workflows/ci-pr.yml`, triggered by `pull_request` events for `opened`, `synchronize`, and `reopened`. - -Use GitHub-hosted runners for jobs that can run on the hosted operating system and toolchain. When a job uses a self-hosted runner, document and select it through the repository's `Runner labels:` rather than hard-coding a machine name in shared guidance. - -### Runner labels: - -When a workflow uses self-hosted runners, document the labels required by each job in this section of the consumer's CI/CD guide. Always include `self-hosted` and add only stable capability or environment labels needed to select the runner, such as an operating system, architecture, toolchain, or signing capability. Keep machine names and changing fleet details out of shared guidance. - -A typical Swift package validates: - -- package resolution; -- build; -- Swift Testing tests; -- DocC generation when the package publishes documentation; -- repository-specific lint or validation scripts. - -An Xcode application validates its declared scheme and test plan. Use the same project/workspace, configuration, and platform assumptions documented for local development. - -Xcode projects and Swift packages must run on self-hosted macOS runners with the required Xcode, Swift toolchains, simulators, certificates, and signing environment. Do not use `macos-latest` for those jobs. For Xcode projects, test with `xcodebuild test` and explicit simulators, then validate compilation with `xcodebuild build CODE_SIGNING_ALLOWED=NO` across the supported platforms. For Swift packages, use Swift Package Manager commands such as `swift test` and `swift build`; packages do not require simulator selection, but may require the self-hosted signing environment for packaging or collection workflows. Generic jobs that do not require Apple tooling may use GitHub-hosted Linux or other suitable runners. CI validates tests and compile health, not app-store distribution. - -## `ci.yml` - -Validation of merges to `main` should live in `.github/workflows/ci.yml`, triggered by `push` on `main`. Use the same build, test, lint, and platform coverage as pull-request validation unless the repository documents a deliberate difference. - -## Failure investigation - -1. Use GitHub MCP connector tools to inspect check runs and logs for the failing commit or pull request. -2. Use `gh` for fast local triage when needed. -3. Reproduce locally with the exact build or test command shown in the failing job logs. - -Useful commands: - -```bash -gh run list --limit 10 -gh run view -gh run view --log -``` - -Distinguish compiler errors from lint violations, test failures from simulator or runtime infrastructure failures, and single-job failures from cross-platform matrix failures. Identify the first meaningful failing step, fix the narrowest root cause, and re-run affected validation. - -## Releases - -- A release tag and GitHub release must match the intended semantic version. -- Release notes summarize user- or integrator-relevant changes since the previous release. -- Use a notes file for multiline CLI release descriptions. -- Do not publish a release from an unverified or dirty worktree. -- Follow the consumer's local instructions for deployment, signing, notarization, App Store, or documentation publishing steps. diff --git a/AgentGuidelines/Guidelines/Development.md b/AgentGuidelines/Guidelines/Development.md deleted file mode 100644 index c733ca1..0000000 --- a/AgentGuidelines/Guidelines/Development.md +++ /dev/null @@ -1,32 +0,0 @@ -# Development - -## Reusability first - -When developing a new feature or responding to a feature request, consider shared code first. If the code fits an existing package, suggest extending that package instead of adding the implementation directly to an application. Also consider whether the change belongs in a new Swift package, even when that package does not exist yet. Prefer reusable, focused package APIs when they can serve more than one consumer. - -## Guidelines version - -Before changing a project, verify that it uses the latest released version of `agent-guidelines`. Check the project's `AgentGuidelines/VERSION` against the latest release, update the subtree or equivalent when it is behind, and read the updated applicable guides before starting implementation. This check is manual and must be performed at the beginning of each project task. - -## Guidelines changes in pull requests - -Keep `AgentGuidelines/` tracked so consumers retain a reproducible, versioned copy for agents and CI. Do not add the subtree to `.gitignore`. Instead, add this rule to the consumer's tracked `.gitattributes` so GitHub collapses synchronized guideline files in pull-request diffs by default while reviewers can still expand them: - -```gitattributes -# Synced from thatfactory/agent-guidelines; keep tracked but collapse GitHub diffs. -AgentGuidelines/** linguist-generated -``` - -Keep each subtree update in its own commit. In the pull-request description, state the old and new guideline versions and link to the central release or pull request where the guideline changes were reviewed. Continue validating the checked-in subtree in CI. Because generated-file diffs are collapsed by default, never edit the subtree locally; make shared changes in the source repository and consume a tagged release. - -## Completion audit - -Before claiming implementation is complete, handing work to the user, preparing, opening, or updating a pull request, declaring merge readiness, or preparing a release, invoke `$agent-guidelines-audit`. - -If the skill is not discoverable in a subtree consumer, read and follow its [SKILL.md](../.agents/skills/agent-guidelines-audit/SKILL.md) directly. The audit is a final verification gate, not a substitute for reading and applying the relevant guidelines during implementation. Resolve in-scope findings and rerun affected checks before handoff. Do not broaden the requested scope merely to satisfy the audit. - -For subtree consumers, the audit runs `python3 AgentGuidelines/Scripts/validate_consumer_setup.py` to detect drift in the root Code Review contract, Codex subtree-review scope, `.gitattributes`, local guide links, and repository skill symlink. When the root `AGENTS.md` links the shared Swift-format guide, the validator also requires the shared configuration symlinks and strict non-mutating CI adoption. User-level global Codex instructions are outside this repository audit. - -## Logging - -Applications own their orchestration, lifecycle, and product-domain diagnostics. Follow the shared [logging guide](Logging.md) and rely on each dependency to log its own implementation. Do not duplicate or reformat package-internal operations in the application log. diff --git a/AgentGuidelines/Guidelines/Documentation.md b/AgentGuidelines/Guidelines/Documentation.md deleted file mode 100644 index 4cc60c5..0000000 --- a/AgentGuidelines/Guidelines/Documentation.md +++ /dev/null @@ -1,40 +0,0 @@ -# Documentation - -- Use PascalCase Markdown filenames without spaces. -- Keep the folder flat until one topic genuinely requires several files. -- Prefer current implementation over speculative future design; label known gaps explicitly. - -## Code-level documentation - -- Document every new struct, class, enum, protocol, actor, and function with focused `///` DocC comments. -- Use `// MARK: -` pragmas to separate meaningful logical sections so source files remain easy to scan and navigate. -- Update documentation when changing a documented API, parameter, behavior, or invariant. -- End documentation sentences with periods. -- Explain intent, contracts, units, side effects, isolation, and non-obvious constraints; do not restate syntax. -- Add a short Swift example when it materially clarifies correct use. -- Keep documentation close to the declaration it describes. - -## Project-level documentation - -- Keep durable architecture and cross-cutting guides in the consumer's declared documentation folder. -- Update a guide when a change alters the documented architecture, data flow, public API, persistence, navigation, localization process, testing workflow, or delivery workflow. -- Do not update broad guides for minor implementation changes already explained by code and DocC. -- Remove or rewrite stale documentation when its feature or workflow is removed. -- Keep investigations, temporary plans, and one-time spike notes out of durable documentation unless they become lasting guidance. -- Prefer ASCII diagrams in fenced code blocks when universal rendering matters. - -## Review checklist - -When reviewing a change, ask: - -- Does it alter a documented public API or invariant? -- Does it introduce a reusable architectural pattern? -- Does it change data flow, ownership, persistence, localization, testing, or delivery? -- Does it remove or supersede an existing guide? -- Are code comments and project guides consistent with the implementation? - -Flag missing documentation only when the change affects durable knowledge. Avoid documentation churn for small fixes. - -## Shared versus local guidance - -This repository owns reusable policy. Consumer documentation owns its product domain, concrete paths, package relationships, feature registries, and explicit exceptions. Link across those layers instead of copying shared prose locally. diff --git a/AgentGuidelines/Guidelines/GitHub/PullRequests.md b/AgentGuidelines/Guidelines/GitHub/PullRequests.md deleted file mode 100644 index 80c12b1..0000000 --- a/AgentGuidelines/Guidelines/GitHub/PullRequests.md +++ /dev/null @@ -1,178 +0,0 @@ -# GitHub Pull Requests - -Use this guide whenever creating, reviewing, updating, or merging a GitHub pull request. - -## Before opening - -- Review the complete diff and exclude unrelated changes. -- Keep each pull request to a coherent review unit with a bounded set of invariants. Split changes that combine independent architecture, persistence, security, transport, and CI concerns when they can be reviewed and delivered separately; do not split merely to minimize line count. -- State the supported use cases, explicit acceptance criteria, and relevant threat model for behavior whose review priority depends on those boundaries. -- For security guarantees based on enumerating formats or signatures, define the finite coverage contract and residual risk, or use a systemic boundary that enforces the guarantee without exhaustive enumeration. -- Follow the repository's pull-request template and local contribution instructions. -- Run the relevant local validation and document anything that could not be run. -- Open the pull request without auto-merge and keep it unmerged while automated or agent review is pending. Use draft state only when configured reviewers also run on drafts. -- When automatic Codex review is enabled, opening the pull request schedules the review. Do not also post `@codex review` or make another manual request; duplicate reviews waste review capacity and tokens. Do not request a Codex review manually unless the user explicitly asks for one. - -## Consumer subtree review scope - -When reviewing a consumer pull request, do not review or comment on files under `AgentGuidelines/**` after exact tagged-tree provenance has been verified. The subtree is a tracked, synchronized copy marked `linguist-generated`; substantive guideline changes are reviewed in the central `thatfactory/agent-guidelines` pull request. Verify `AgentGuidelines/VERSION`, compare the subtree tree with the matching central tag (for example with `git subtree split --prefix=AgentGuidelines HEAD` and a tree comparison after fetching that tag), and verify the required `.gitattributes` rule. If provenance does not match exactly, review the subtree contents and stop the merge. Report substantive guideline feedback against the central pull request instead. - -## Review objective - -Automated review identifies release-blocking regressions; it does not attempt to eliminate every possible improvement. - -Classify findings by impact and reachable scope: - -- **P0 — critical:** an actively exploitable critical security issue, catastrophic durable data loss, or critical production outage. -- **P1 — blocking:** a supported use case, explicit acceptance criterion, or documented threat-model boundary has a concrete reachable failure path that causes a security-boundary bypass, durable data loss or corruption, a crash or deadlock, loss of availability, or a serious compatibility regression. -- **P2 — non-blocking:** robustness, defense-in-depth, bounded edge cases, malformed state that trusted code cannot produce, unsupported scenarios, theoretical completeness, or useful hardening. -- **P3 — non-blocking:** style, naming, preferred refactoring, documentation polish, or optional test improvements. - -Only unresolved P0 and P1 findings block merge. A finding may be technically correct without being release-blocking. - -## Review gate - -Opening a pull request starts review; it does not authorize merging it. - -1. Wait for the configured Codex review to finish. No review yet means pending, not approved. -2. Record the reviewed head SHA and inspect all review summaries, inline threads, checks, and requested changes. -3. Assess each comment for technical correctness, severity, supported reachability, and root cause. -4. Give every thread one explicit disposition: `BLOCKER-P0`, `BLOCKER-P1`, `DEFER-P2`, `DEFER-P3`, `DECLINE`, or `DUPLICATE`. -5. Batch accepted P0/P1 corrections into one remediation pass and add regression coverage where reasonably possible. Lower-severity improvements may be included when they are small and clearly in scope, but they do not keep the review loop open. -6. Reply in the original thread with the disposition and either what changed or the concise technical reason for deferring, declining, or grouping it. -7. Resolve a thread only after its disposition is recorded. Reference a follow-up issue for deferred work when its value justifies one. -8. Rerun affected validation, then update the pull-request description so it matches the current implementation, validation, deferred work, and remaining limitations. -9. Recheck the pull request immediately before merge for late P0/P1 findings and check-state changes. - -When replying with a commit reference, write the commit hash as raw text without backticks (for example, the hash 185c04f should remain 185c04f). GitHub then auto-links the hash to the commit. - -A thumbs-up or clean Codex review satisfies the agent-review step, but it does not replace any human approval required by the repository. Do not enable auto-merge before all review gates are satisfied. - -### Review state and round budget - -Track enough state to prevent duplicate requests and unbounded review loops: - -```text -initial_review_sha -last_reviewed_sha -review_requested_sha -review_round -pending_review -unresolved_p0 -unresolved_p1 -deferred_findings -``` - -The automatic review is the one initial full review. Do not request another review after each fix. A repository owner may explicitly authorize at most one delta-scoped verification review after the known P0/P1 findings have been batch-remediated. - -Before sending that request, verify that no Codex review is pending, no existing request targets the current head SHA, the current head differs from `last_reviewed_sha`, and the verification-round budget is unused. Persist `review_requested_sha`, increment `review_round`, and mark `pending_review` before waiting for a result so a retry cannot submit a duplicate request. - -When authorized, scope the verification request explicitly: - -```text -@codex review only unresolved P0/P1 findings and changes since . -Do not search unchanged code for new P2/P3 issues. -``` - -Do not request a third review or restart a full review without separate, explicit repository-owner authorization and a named unresolved P0/P1 concern. A new finding in verification must be a P0/P1 defect introduced by the remediation or genuinely hidden by the previous blocker. - -Stop the review loop when no unresolved P0/P1 finding remains, every thread has an explicit disposition, required checks pass, and required human authorization is present. Zero comments, zero possible improvements, and zero technical debt are not completion criteria. - -### Codex review monitoring - -Use GitHub review data, reactions, and checks together. An eyes reaction means Codex is processing the pull request; it is not an approval. A thumbs-up means the review completed without suggestions. A submitted review means its inline threads must be assessed individually. - -```text -PR opened at stable head - | - v -One automatic full review - | - +--> thumbs-up ----------------> No P0/P1 blockers - | - `--> Review comments ----------> Classify and group - | - batch P0/P1 fixes - | - owner-authorized delta review? - | | - no yes - | | - stop one verification pass - | - no unresolved P0/P1 - | - stop -``` - -When using the GitHub CLI, monitor all three surfaces: - -```sh -gh api --paginate repos///issues//reactions -gh pr view --repo / --json reviews,headRefOid -gh pr checks --repo / -``` - -Retrieve inline review threads and their resolution state through GraphQL; top-level pull-request comments do not include this information: - -```sh -gh api graphql --paginate \ - -f query='query($owner: String!, $repository: String!, $number: Int!, $endCursor: String) { - repository(owner: $owner, name: $repository) { - pullRequest(number: $number) { - reviewThreads(first: 100, after: $endCursor) { - nodes { id isResolved } - pageInfo { hasNextPage endCursor } - } - } - } - }' \ - -F owner= \ - -F repository= \ - -F number= -``` - -For every unresolved thread identifier returned above, retrieve its complete comment history with a second paginated query: - -```sh -gh api graphql --paginate \ - -f query='query($thread: ID!, $endCursor: String) { - node(id: $thread) { - ... on PullRequestReviewThread { - comments(first: 100, after: $endCursor) { - nodes { id author { login } body url } - pageInfo { hasNextPage endCursor } - } - } - } - }' \ - -F thread= -``` - -Continue polling only while an allowed review round is pending. Inspect every returned page for reactions, review threads, and thread comments. Do not treat missing comments, a pending reaction, truncated results, or elapsed time as review completion, and do not submit a duplicate request merely because polling has not completed. - -## Merge requirements - -Do not merge while any of the following is true: - -- Codex review is still pending; -- an unresolved P0/P1 finding remains; -- a review thread lacks an explicit disposition or remains unresolved; -- a required check is pending or failing; -- the branch is out of date when the repository requires an up-to-date branch; -- required human approval or explicit owner authorization is missing. - -## Late findings - -If a review arrives after merge, assess and disposition its findings. A valid late P0/P1 finding requires prompt remediation through a corrective pull request and indicates that a review gate was missed. A late P2/P3 observation becomes backlog work when useful and is not by itself a process failure. - -## Repository protection - -Prefer GitHub rulesets or branch protection for the default branch. At minimum: - -- require changes to arrive through a pull request; -- require conversations to be resolved before merging; -- require the repository's mandatory status checks; -- prevent bypass except for an intentional emergency path. - -A formal one-approval rule works only when someone other than the pull-request author can submit an approving review. In a solo repository where the owner account also authors pull requests, use a bot or service account for authored changes before requiring owner approval; GitHub does not count self-approval. Until that separation exists, require explicit owner authorization operationally and keep conversation resolution enforced technically. diff --git a/AgentGuidelines/Guidelines/Packages.md b/AgentGuidelines/Guidelines/Packages.md deleted file mode 100644 index a9b0576..0000000 --- a/AgentGuidelines/Guidelines/Packages.md +++ /dev/null @@ -1,105 +0,0 @@ -# Swift Packages - -## README badges - -Start a new ThatFactory project or package README with a centered HTML badge block: - -```html -

- -

-``` - -Use only badges that describe the repository, in this order: - -1. Swift version. -2. Xcode version. -3. Supported platforms. -4. Relevant package manager, runtime, or ecosystem badges, such as SPM or NPM. -5. Relevant agent or tooling badges, such as Xcode MCP, Codex, or Claude. -6. DocC, documentation. -7. License. -8. Updated date. -9. Revision or latest release. -10. CI badges. -11. Release/publishing status when applicable. - -The common package baseline is Swift, Xcode, Platforms, License, and CI. Add optional badges only when they convey useful repository-specific information. Keep the order stable even when some positions are omitted. - -- Point CI, publishing, and documentation badges at workflows in the current repository; never copy another repository's badge URL unchanged. -- Use descriptive `alt` text. Preserve a repository's established Xcode badge convention when the label intentionally records the last verified Xcode version. -- Prefer dynamic Updated and Revision badges backed by repository history or releases so maintainers do not edit dates and versions by hand. -- Do not advertise a platform, integration, package manager, or agent that the repository does not support. -- Keep the repository's license in a root `LICENSE` file when reuse or redistribution is permitted. A README license heading is optional; the badge is a summary, not the license grant. -- Do not add a license to an existing repository without the owner's explicit choice of terms. - -## Package boundaries - -- Keep a reusable package focused on one coherent capability. -- Prefer UI-agnostic domain APIs unless UI is the package's explicit purpose. -- Do not add application Redux, navigation, persistence, or product policy to a generic package. -- Keep public APIs minimal and stable. Prefer composing focused types over introducing umbrella abstractions before multiple consumers need them. -- Declare platform and Swift toolchain requirements explicitly in `Package.swift`. -- New Swift packages must start on the latest supported Swift language and toolchain version. Before adding a major package capability to an older package, plan and complete the required Swift/toolchain modernization first. -- Put sources under `Sources//` and tests under `Tests/Tests/`. -- Keep resources in the target that owns them and use the package bundle for lookup. - -## Logging - -Packages own any diagnostics emitted by their implementation. Follow the shared [logging guide](Logging.md) for AppLogger usage, subsystem identity, package emoji prefixes, domain-owned categories, concise messages, privacy, and test coverage. A consuming application must not reproduce package-internal logs. - -## Development workflow - -1. Read the package's local `AGENTS.md`, README, DocC, and public API before changing behavior. -2. Add or update tests in the package itself. -3. Update DocC and README examples when public behavior changes. -4. Run the focused tests, then `swift test` or the package's declared Xcode test workflow. -5. Integrate the package into a consumer locally only when consumer behavior must also be verified. -6. Avoid committing consumer-specific workarounds into the package when the behavior belongs in the consumer. - -## DocC documentation - -DocC is the default documentation format for public Swift packages. Document public APIs with `///` DocC comments and keep package-level conceptual material in a DocC catalog when it needs more than declaration comments. - -Before adopting the DocC command, an existing package must be updated to the latest supported Swift toolchain and declare the Swift-DocC plugin dependency in `Package.swift` (for example, `.package(url: "https://github.com/swiftlang/swift-docc-plugin", from: "")`). New packages must declare this prerequisite from the beginning when they publish DocC. - -Packages that publish documentation must build and deploy their DocC site as part of the release workflow: - -1. Run tests before documentation generation. -2. Generate static-hosting documentation with `swift package generate-documentation --target --disable-indexing --output-path ./public --transform-for-static-hosting --hosting-base-path `. -3. Add a root redirect to `//documentation//`. -4. Upload `./public` with `actions/upload-pages-artifact` and deploy it with `actions/deploy-pages`. -5. Grant the workflow `pages: write` and `id-token: write` permissions and expose the deployed URL in the README through a DocC badge. - -The release job must publish documentation only after the release has been approved, merged, tagged, and published. Verify the generated site locally when practical and keep the README badge URL aligned with the repository's GitHub Pages site. - -## Local integration - -- Use Xcode's local-package workflow or an explicit temporary local dependency while developing package and consumer changes together. -- Do not commit machine-specific absolute package paths. -- Before release, restore the consumer to the tagged remote dependency unless its local instructions intentionally retain a monorepo relationship. -- Verify the final remote version resolves on a clean checkout. - -## Releases - -Never release a package directly from unreviewed changes. Every release change must first be submitted through a pull request, reviewed, and approved. This rule applies to `agent-guidelines` itself as well as every consumer package. Create and publish the release only after the PR has merged. - -For ThatFactory packages, “release a new version” means: - -1. Choose a semantic version appropriate to compatibility. -2. Update public documentation and release notes. -3. Run the declared CI/test workflow. -4. Open a pull request containing the release state and wait for approval. -5. Merge the approved pull request. -6. Create and push the matching Git tag. -7. Create a GitHub release for that tag. -8. Use real multiline release notes and backticks around technical names and versions. - -When using a CLI, pass multiline notes through a file so GitHub renders line breaks correctly. - -## Consumer updates - -- Review package release notes and API changes before updating. -- Update one dependency relationship intentionally; do not rewrite unrelated resolved versions. -- Build and test the affected consumer behavior. -- Update the consumer's package integration documentation when roles, mappings, or workflows change. diff --git a/AgentGuidelines/Guidelines/Swift/Localization.md b/AgentGuidelines/Guidelines/Swift/Localization.md deleted file mode 100644 index 02725c1..0000000 --- a/AgentGuidelines/Guidelines/Swift/Localization.md +++ /dev/null @@ -1,43 +0,0 @@ -# Localization - -Follow Apple's [Localizing your app using agents](https://developer.apple.com/documentation/xcode/localizing-your-app-using-agents) workflow and current Xcode localization tools. Consumer repositories declare their supported languages, catalog locations, key conventions, and generated-symbol policy locally. - -## Source artifacts - -- Use the consumer's existing String Catalogs (`.xcstrings`) as the source of truth. -- Do not create a parallel catalog or migrate an existing `.strings` setup unless the task includes that migration. -- An app target uses its main bundle by default. Swift packages and frameworks must resolve localized resources from their own bundle, using the current Apple-recommended bundle API. -- Keep one source of truth for translator context: either the source comment or the catalog comment. - -## User-facing values - -- Let SwiftUI's localized string initializers preserve localization context. -- Use `LocalizedStringResource` when a model, view state, notification, or other non-view value carries user-facing text that should resolve later. -- Use `String(localized:)` when a resolved localized `String` is genuinely required outside SwiftUI. -- Use `Text(verbatim:)` for intentional non-localized literals such as debug identifiers. -- Do not pass a runtime `String` to a localized initializer and expect Xcode to extract it as a catalog key. - -## Sentences and formatting - -- Interpolate values into one localizable sentence rather than concatenating translated fragments. -- Add translator comments for ambiguous language and describe interpolated placeholders by position and meaning. -- Use locale-aware `FormatStyle` APIs for dates, numbers, lists, measurements, and currencies. -- Avoid runtime case transformations for localized interface text; allow translations to choose appropriate casing. - -## Layout - -- Use leading and trailing instead of left and right for directional layout. -- Avoid fixed text frames that cannot accommodate translation length or script height. -- Prefer semantic text styles to fixed point sizes. -- Use the SwiftUI environment locale for view behavior that must respond to preview or subtree locale overrides. - -## Agent workflow - -1. Inspect the consumer's local localization instructions and catalogs. -2. Ask Xcode's current documentation or localization capability for the supported workflow. -3. Add or update source-language content and translator context. -4. Update only the languages in scope. -5. Build to validate catalog syntax, extraction, generated symbols, and bundle lookup. -6. Use previews or runtime visual verification for truncation, layout direction, and formatting when relevant. - -Do not invent translations from an unrelated project's conventions. Product vocabulary and tone remain consumer-specific. diff --git a/AgentGuidelines/Guidelines/Swift/SwiftUI.md b/AgentGuidelines/Guidelines/Swift/SwiftUI.md deleted file mode 100644 index cbc3185..0000000 --- a/AgentGuidelines/Guidelines/Swift/SwiftUI.md +++ /dev/null @@ -1,63 +0,0 @@ -# SwiftUI - -Use official Apple documentation and Xcode's current SwiftUI skills for API-specific behavior. This guide captures stable project policy rather than reproducing the current SDK's API catalog. - -## View structure - -- Put SwiftUI dynamic properties such as `@Environment`, `@Query`, `@State`, and `@Binding` before ordinary stored `let` and `var` properties. Keep injected environment dependencies before locally owned state when both are present. -- Keep a parent view focused on composition. -- Model meaningful sections such as headers, lists, metadata, sidebars, and footers as separate `View` types with narrow inputs. -- Keep each independently meaningful `View` in its own file, including private supporting views. Give every view its own deterministic preview when the required dependencies can be represented safely; when they cannot, document the concrete limitation in the handoff. -- Do not extract sections into computed `some View` properties merely to shorten `body`; computed properties remain in the parent's invalidation boundary. -- Tiny fragments reused within one body may use a small helper when they have no independent state, input, or invalidation story. -- Keep view initializers cheap. Do not decode data, access files, build large structures, or allocate formatters in `init`. -- Avoid a single-child `Group` that adds no structure or behavior. - -## Data flow - -- Pass a view only the value-type fields it reads or forwards. -- Use private `@State` for state genuinely owned by the view. -- Use `Binding` when a child edits state owned by its parent. -- In non-Redux designs, prefer `@Observable` to `ObservableObject` for new shared reference models when platform support allows it. -- In Redux applications, keep durable app and domain state in Redux. Do not introduce an observable view model as a parallel source of truth. -- Make observable stored-property types `Equatable` when equality matches their semantics, allowing redundant assignments to avoid unnecessary invalidation. -- Isolate side effects in `.task`, `.onChange`, actions, or explicit async functions rather than hiding them in rendering logic. -- Use the current `.onChange(of:)` form and read the updated captured value when the previous value is unnecessary. -- Avoid closure-based bindings when a writable key-path binding expresses the same relationship. - -With SDKs where `@State` is a macro, do not give a state property a declaration default and then attempt to replace that value in `init`. Choose one initialization source and verify current compiler guidance when migrating existing code. - -## Collections and identity - -- Give `ForEach`, `List`, `Table`, and similar data-driven views stable, unique element identity. -- Prefer meaningful `Identifiable` conformance when the model has natural identity. -- Do not use collection indices, offsets, or transient UUIDs as identity for mutable collections. -- Do not sort, filter, or map large collections inline inside a frequently evaluated view body. Prepare the collection before rendering. -- Use a dedicated row `View` for meaningful rows and pass it narrow inputs. -- Avoid `AnyView` in collection rows. - -## Modifiers and environment - -- Preserve stable view identity. Prefer modifiers whose values change over conditionally adding and removing modifier branches. -- Do not place high-frequency values in the environment when explicit narrow inputs work. -- Avoid unstable environment defaults and freshly created closures that invalidate large subtrees. -- Do not hide unstable values behind fake `Equatable` implementations. - -## Modern APIs and scope - -- Do not introduce APIs that current Xcode documentation identifies as deprecated or soft-deprecated. -- When fixing a feature, modernize only the code directly required by the task unless the user requests a broader migration. -- For SDK-sensitive features, search current Apple documentation through Xcode rather than relying on remembered signatures. -- Apply the current Xcode SwiftUI skill when a new SDK changes source behavior, builder resolution, state initialization, or modifier availability. - -## Previews - -- Put previews at the end of the file under `// MARK: - Preview`. -- Use `#Preview`. -- Use `@Previewable` for interactive preview state when appropriate. -- Keep preview fixtures deterministic and lightweight. -- After UI changes, follow [Xcode MCP and visual verification](../Xcode/MCP.md) when runtime verification adds meaningful confidence. - -## Localization - -Follow [Localization](Localization.md) for user-facing text, layout direction, formatting, and package bundles. diff --git a/AgentGuidelines/LICENSE b/AgentGuidelines/LICENSE deleted file mode 100644 index 42d8021..0000000 --- a/AgentGuidelines/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -MIT License - -Copyright (c) 2026 ThatFactory - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - diff --git a/AgentGuidelines/README.md b/AgentGuidelines/README.md deleted file mode 100644 index b6ab81a..0000000 --- a/AgentGuidelines/README.md +++ /dev/null @@ -1,174 +0,0 @@ -

- Xcode - Codex - Updated - Revision - License - CI -

- -# Agent Guidelines - -`agent-guidelines` is ThatFactory's public, versioned source of truth for reusable instructions and development configuration. It centralizes stable decisions about Swift development, Redux architecture, testing, documentation, logging, packages, CI/CD, localization, and Xcode tooling while leaving product context and exceptions in each consuming repository. - -The repository contains documentation and supporting configuration, not a Swift product. Consumers install a tagged release as a Git subtree at `AgentGuidelines/`, so every agent and supported tool sees ordinary version-controlled files at predictable paths. - -## How it fits together - -```text - thatfactory/agent-guidelines - versioned GitHub repository - | - tagged release - e.g. 0.0.3 - | - git subtree add/pull - | - v -+---------------- Consumer project or package -----------------+ -| | -| AGENTS.md | -| |-- local product/package context | -| |-- concrete project paths | -| |-- local exceptions | -| `-- pointers to shared guidelines -----------------+ | -| | | -| AgentGuidelines/ | | -| |-- VERSION | | -| |-- Configurations/ | | -| `-- Guidelines/ <----------------------------------+ | -| |-- Architecture/Redux.md | -| |-- Swift/SwiftUI.md | -| |-- Testing/UnitTesting.md | -| `-- Xcode/MCP.md | -| | -| Sources and project files | -+----------------------------+---------------------------------+ - | - reads instructions and project files - +----------+----------+ - v v - Codex Xcode agent - | - | Xcode MCP (`xcrun mcpbridge`) - v - Xcode -``` - -The subtree does not automatically import every guide into an agent's context. A consumer's root or folder-scoped `AGENTS.md` tells the agent which shared guides to read for the task. The nearest local `AGENTS.md` can specialize or override the shared baseline. - -## Guideline catalog - -- [Agent workflow and tool execution](Guidelines/AgentWorkflow.md) -- [CI/CD](Guidelines/CICD.md) -- [Development and reusability](Guidelines/Development.md) -- [Documentation](Guidelines/Documentation.md) -- [Git repositories and SSH-first cloning](Guidelines/Git/Repositories.md) -- [GitHub pull requests](Guidelines/GitHub/PullRequests.md) -- [Localization](Guidelines/Swift/Localization.md) -- [Logging](Guidelines/Logging.md) -- [Redux architecture and physical folder organization](Guidelines/Architecture/Redux.md) -- [Swift](Guidelines/Swift/Swift.md) -- [Swift format](Guidelines/Swift/SwiftFormat.md) -- [Swift packages](Guidelines/Packages.md) -- [Swift style](Guidelines/Swift/SwiftStyle.md) -- [SwiftUI](Guidelines/Swift/SwiftUI.md) -- [Unit and integration testing](Guidelines/Testing/UnitTesting.md) -- [Xcode MCP and visual verification](Guidelines/Xcode/MCP.md) -- [Xcode security audits](Guidelines/Xcode/Security.md) - -Only reference the guides that apply. Agent workflow normally applies to both applications and packages. A UI-agnostic package normally also uses Swift, style, testing, documentation, logging, packages, CI/CD, and Xcode guidance, but not Redux or SwiftUI guidance. - -## Add to a consumer - -From the consumer repository root, install a tagged release: - -```sh -git subtree add \ - --prefix=AgentGuidelines \ - https://github.com/thatfactory/agent-guidelines.git \ - 0.0.18 \ - --squash -``` - -Swift consumers that adopt the shared formatter expose its configuration at the repository root so Xcode and other tools discover it: - -```sh -ln -s AgentGuidelines/Configurations/Swift/.swift-format .swift-format -ln -s AgentGuidelines/Configurations/Swift/.editorconfig .editorconfig -``` - -Keep the subtree tracked, but add this to the consumer's tracked `.gitattributes` so GitHub collapses synchronized guideline files in pull-request diffs by default: - -```gitattributes -# Synced from thatfactory/agent-guidelines; keep tracked but collapse GitHub diffs. -AgentGuidelines/** linguist-generated -``` - -Copy and adapt [the consumer template](Templates/AGENTS.md). Keep the consumer file small: describe the product or package, map its concrete physical folders, point to the applicable shared guides, and state only genuine exceptions. Keep the version-marked code-review contract directly in the repository-root `AGENTS.md`; Markdown links to shared guides are navigation, not automatic instruction includes. - -### Configure global Codex instructions - -Copy the contents of [`Templates/GlobalCodexInstructions.md`](Templates/GlobalCodexInstructions.md) into the user's global Codex instructions. - -These instructions bootstrap discovery of repository-local `AGENTS.md` files and shared guides and provide generic high-signal code-review defaults. Repository engineering policy and specialized threat models remain versioned in this repository or the consumer rather than duplicated in each user's global configuration. - -Review this template when upgrading `agent-guidelines`, because the recommended global bootstrap instructions may change between releases. Installing or updating the Git subtree does not update a user's global Codex configuration. - -Redux applications also copy [the canonical Store](Templates/Store.swift) as is, following the composition and placement rules in [Redux architecture](Guidelines/Architecture/Redux.md). - -Expose the completion-audit skill at the consumer repository root so Codex can discover it: - -```sh -mkdir -p .agents/skills -ln -s ../../AgentGuidelines/.agents/skills/agent-guidelines-audit \ - .agents/skills/agent-guidelines-audit -``` - -Validate the checked-in consumer integration directly or through the completion-audit skill: - -```sh -python3 AgentGuidelines/Scripts/validate_consumer_setup.py -``` - -The validator checks the version-marked root Code Review contract, Codex subtree-review scope, `.gitattributes`, local guide links, and the audit-skill symlink. When the root `AGENTS.md` links the shared Swift-format guide, it also requires both configuration symlinks and a non-mutating `lint-strict` CI invocation. Pass `--require-swift-format` only when auditing formatter adoption before adding that guide link. - -## Update a consumer - -Review the target release's changelog, then pull it deliberately: - -```sh -git subtree pull \ - --prefix=AgentGuidelines \ - https://github.com/thatfactory/agent-guidelines.git \ - 0.0.18 \ - --squash -``` - -Confirm `AgentGuidelines/VERSION`, review the subtree diff, synchronize the marked code-review contract when its version changes, run `python3 AgentGuidelines/Scripts/validate_consumer_setup.py`, and run the consumer's relevant tests. Keep the subtree update in its own commit, and identify the old and new versions plus the central release or pull request in the consumer pull-request description. Updates are intentionally not automatic: one guideline release cannot silently change every project. - -## Maintain the source of truth - -1. Export current Xcode skills to a temporary review location when a new Xcode release materially changes agent behavior: - - ```sh - xcrun agent skills export --output-dir - ``` - -2. Compare relevant guidance with this repository and official Apple documentation. -3. Bring over durable policy, not the exported skill text or an SDK API catalog. -4. Remove obsolete or conflicting rules instead of accumulating historical alternatives. -5. Run `python3 Scripts/validate_guidelines.py`. -6. Update `VERSION` and `CHANGELOG.md`, open a pull request, and wait for approval before merging. -7. After the pull request has merged, create the matching tag and GitHub release. - -## Precedence - -For a consumer task, apply instructions in this order: - -1. The user's explicit request. -2. The nearest applicable consumer `AGENTS.md`. -3. The consumer root `AGENTS.md`. -4. The shared guides explicitly referenced by those files. - -Official Apple documentation remains authoritative for API behavior. A local convention can deliberately narrow a choice, but it must not rely on behavior contradicted by the current SDK documentation. diff --git a/AgentGuidelines/Scripts/validate_consumer_setup.py b/AgentGuidelines/Scripts/validate_consumer_setup.py deleted file mode 100755 index 687e1a1..0000000 --- a/AgentGuidelines/Scripts/validate_consumer_setup.py +++ /dev/null @@ -1,304 +0,0 @@ -#!/usr/bin/env python3 -"""Validate a consumer repository's checked-in agent-guidelines integration.""" - -from __future__ import annotations - -import argparse -import re -import sys -from pathlib import Path - - -GUIDELINES_ROOT = Path(__file__).resolve().parents[1] -CONTRACT_BEGIN = "" -CONTRACT_END = "" -MARKDOWN_LINK = re.compile(r"\[[^\]]+\]\(([^)]+)\)") -SWIFT_FORMAT_GUIDE = "AgentGuidelines/Guidelines/Swift/SwiftFormat.md" -STRICT_FORMAT_COMMAND = re.compile( - r"(?m)^[ \t]*(?:-\s+)?(?:run:\s*)?(?:\./)?" - r"AgentGuidelines/Scripts/swift_format\.sh\s+lint-strict(?=\s|\\|$)", -) -MUTATING_FORMAT_COMMAND = re.compile( - r"(?m)^[ \t]*(?:-\s+)?(?:run:\s*)?(?:\./)?" - r"AgentGuidelines/Scripts/swift_format\.sh\s+format(?:-and-lint)?(?=\s|\\|$)", -) -GENERATED_ATTRIBUTE = re.compile( - r"^\s*AgentGuidelines/\*\*\s+linguist-generated\s*$", - re.MULTILINE, -) - - -def read_text(path: Path, errors: list[str], label: str) -> str | None: - try: - return path.read_text(encoding="utf-8") - except OSError as error: - errors.append(f"{label}: cannot read {path}: {error}") - return None - - -def extract_contract(contents: str, errors: list[str], label: str) -> str | None: - if contents.count(CONTRACT_BEGIN) != 1 or contents.count(CONTRACT_END) != 1: - errors.append( - f"{label}: expected exactly one {CONTRACT_BEGIN!r} and {CONTRACT_END!r}" - ) - return None - - start = contents.index(CONTRACT_BEGIN) - end = contents.index(CONTRACT_END, start) + len(CONTRACT_END) - return contents[start:end].strip() - - -def validate_symlink(path: Path, expected: Path, errors: list[str], label: str) -> None: - if not path.is_symlink(): - errors.append(f"{label}: {path} must be a symlink to {expected}") - return - - if not path.exists(): - errors.append(f"{label}: {path} is a broken symlink") - return - - if path.resolve() != expected.resolve(): - errors.append(f"{label}: {path} resolves to {path.resolve()}, expected {expected.resolve()}") - - -def validate_agent_links( - agents_path: Path, - contents: str, - errors: list[str], -) -> None: - for raw_target in MARKDOWN_LINK.findall(contents): - target = raw_target.strip().strip("<>").split("#", maxsplit=1)[0] - if not target or target.startswith(("#", "http://", "https://", "mailto:")): - continue - - resolved = (agents_path.parent / target).resolve() - if not resolved.exists(): - errors.append(f"AGENTS.md: missing local link target {raw_target!r}") - - -def adopts_swift_format(contents: str) -> bool: - for raw_target in MARKDOWN_LINK.findall(contents): - target = raw_target.strip().strip("<>").split("#", maxsplit=1)[0] - if target.endswith(SWIFT_FORMAT_GUIDE): - return True - return False - - -def shell_invocations(contents: str, command: re.Pattern[str]) -> list[str]: - lines = contents.splitlines() - invocations: list[str] = [] - index = 0 - while index < len(lines): - line = lines[index] - if line.lstrip().startswith("#") or not command.search(line): - index += 1 - continue - - invocation = [line] - while invocation[-1].rstrip().endswith("\\") and index + 1 < len(lines): - index += 1 - invocation.append(lines[index]) - invocations.append("\n".join(invocation)) - index += 1 - return invocations - - -def validate_swift_format_ci(consumer_root: Path, errors: list[str]) -> None: - workflows_root = consumer_root / ".github" / "workflows" - workflows = sorted(workflows_root.glob("*.yml")) + sorted( - workflows_root.glob("*.yaml") - ) - if not workflows: - errors.append( - "consumer Swift format CI: no GitHub Actions workflows found under " - ".github/workflows" - ) - return - - strict_workflows: list[tuple[Path, str, list[str]]] = [] - for workflow in workflows: - contents = read_text( - workflow, - errors, - f"consumer Swift format CI workflow {workflow.relative_to(consumer_root)}", - ) - if contents is None: - continue - if shell_invocations(contents, MUTATING_FORMAT_COMMAND): - errors.append( - "consumer Swift format CI: " - f"{workflow.relative_to(consumer_root)} must not mutate sources with " - "format or format-and-lint" - ) - invocations = shell_invocations(contents, STRICT_FORMAT_COMMAND) - if invocations: - strict_workflows.append((workflow, contents, invocations)) - - if not strict_workflows: - errors.append( - "consumer Swift format CI: missing " - "'AgentGuidelines/Scripts/swift_format.sh lint-strict' invocation" - ) - return - - if not any( - re.search(r"(?m)^\s*pull_request\s*:", contents) - for _, contents, _ in strict_workflows - ): - errors.append("consumer Swift format CI: lint-strict does not run for pull requests") - - if not any( - re.search(r"(?m)^\s*push\s*:", contents) - and re.search(r"(?m)^\s*-?\s*main\s*$|branches\s*:\s*\[[^]]*\bmain\b", contents) - for _, contents, _ in strict_workflows - ): - errors.append("consumer Swift format CI: lint-strict does not run for pushes to main") - - if (consumer_root / "Package.swift").is_file(): - required_paths = ["Package.swift"] - required_paths.extend( - name for name in ("Sources", "Tests") if (consumer_root / name).is_dir() - ) - combined = "\n".join( - invocation - for _, _, invocations in strict_workflows - for invocation in invocations - ) - for path in required_paths: - if not re.search(rf"(? None: - consumer_root = consumer_root.resolve() - guidelines_root = guidelines_root.resolve() - subtree = consumer_root / "AgentGuidelines" - - if not subtree.exists(): - errors.append(f"consumer root: missing {subtree}") - elif subtree.resolve() != guidelines_root: - errors.append( - f"consumer root: {subtree} resolves to {subtree.resolve()}, " - f"expected the active guidelines at {guidelines_root}" - ) - - version_path = guidelines_root / "VERSION" - version = read_text(version_path, errors, "AgentGuidelines/VERSION") - if version is not None and not version.strip(): - errors.append("AgentGuidelines/VERSION: version is empty") - - template_path = guidelines_root / "Templates" / "AGENTS.md" - agents_path = consumer_root / "AGENTS.md" - template = read_text(template_path, errors, "AgentGuidelines template") - agents = read_text(agents_path, errors, "consumer AGENTS.md") - - swift_format_adopted = require_swift_format - if template is not None and agents is not None: - expected_contract = extract_contract(template, errors, "AgentGuidelines template") - actual_contract = extract_contract(agents, errors, "consumer AGENTS.md") - if ( - expected_contract is not None - and actual_contract is not None - and actual_contract != expected_contract - ): - errors.append( - "consumer AGENTS.md: code-review contract does not match " - "AgentGuidelines/Templates/AGENTS.md" - ) - - required_scope_values = ( - "## Codex review scope", - "AgentGuidelines/**", - "exact tagged-tree provenance", - ".gitattributes", - ) - for value in required_scope_values: - if value not in agents: - errors.append(f"consumer AGENTS.md: missing Codex review scope value {value!r}") - - validate_agent_links(agents_path, agents, errors) - swift_format_adopted = swift_format_adopted or adopts_swift_format(agents) - - attributes_path = consumer_root / ".gitattributes" - attributes = read_text(attributes_path, errors, "consumer .gitattributes") - if attributes is not None and not GENERATED_ATTRIBUTE.search(attributes): - errors.append( - "consumer .gitattributes: missing exact " - "'AgentGuidelines/** linguist-generated' rule" - ) - - expected_skill = guidelines_root / ".agents" / "skills" / "agent-guidelines-audit" - consumer_skill = consumer_root / ".agents" / "skills" / "agent-guidelines-audit" - validate_symlink(consumer_skill, expected_skill, errors, "consumer audit skill") - - formatter_links = { - ".swift-format": guidelines_root / "Configurations" / "Swift" / ".swift-format", - ".editorconfig": guidelines_root / "Configurations" / "Swift" / ".editorconfig", - } - for name, expected in formatter_links.items(): - path = consumer_root / name - if swift_format_adopted or path.is_symlink(): - validate_symlink(path, expected, errors, f"consumer {name}") - - if swift_format_adopted: - validate_swift_format_ci(consumer_root, errors) - - -def parse_arguments() -> argparse.Namespace: - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument( - "--consumer-root", - type=Path, - help="Consumer repository root. Defaults to the parent of an AgentGuidelines subtree.", - ) - parser.add_argument( - "--require-swift-format", - action="store_true", - help=( - "Require shared Swift-format configuration links and strict CI even when " - "AGENTS.md does not link the Swift-format guide." - ), - ) - return parser.parse_args() - - -def main() -> int: - arguments = parse_arguments() - consumer_root = arguments.consumer_root - if consumer_root is None: - if GUIDELINES_ROOT.name != "AgentGuidelines": - print( - "Consumer setup validation failed:\n" - "- --consumer-root is required when this checkout is not installed " - "as an AgentGuidelines subtree" - ) - return 1 - consumer_root = GUIDELINES_ROOT.parent - - errors: list[str] = [] - validate_consumer_setup( - errors, - consumer_root, - require_swift_format=arguments.require_swift_format, - ) - if errors: - print("Consumer setup validation failed:") - for error in errors: - print(f"- {error}") - return 1 - - version = (GUIDELINES_ROOT / "VERSION").read_text(encoding="utf-8").strip() - print(f"Validated consumer setup for agent-guidelines {version}.") - return 0 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/AgentGuidelines/Scripts/validate_guidelines.py b/AgentGuidelines/Scripts/validate_guidelines.py deleted file mode 100644 index 95fa1e3..0000000 --- a/AgentGuidelines/Scripts/validate_guidelines.py +++ /dev/null @@ -1,349 +0,0 @@ -#!/usr/bin/env python3 -"""Validate the structure and public safety of the guideline repository.""" - -from __future__ import annotations - -import json -import os -import re -import sys -from pathlib import Path, PurePosixPath - - -ROOT = Path(__file__).resolve().parents[1] -README = ROOT / "README.md" -VERSION = ROOT / "VERSION" -CHANGELOG = ROOT / "CHANGELOG.md" -SWIFT_FORMAT_CONFIGURATION = ROOT / "Configurations" / "Swift" / ".swift-format" -EDITOR_CONFIGURATION = ROOT / "Configurations" / "Swift" / ".editorconfig" -SWIFT_FORMAT_SCRIPT = ROOT / "Scripts" / "swift_format.sh" -SWIFT_FORMAT_GUIDELINE = ROOT / "Guidelines" / "Swift" / "SwiftFormat.md" -CONSUMER_SETUP_SCRIPT = ROOT / "Scripts" / "validate_consumer_setup.py" -AUDIT_SKILL = ROOT / ".agents" / "skills" / "agent-guidelines-audit" / "SKILL.md" -DEVELOPMENT_GUIDELINE = ROOT / "Guidelines" / "Development.md" -AGENTS_TEMPLATE = ROOT / "Templates" / "AGENTS.md" -EXPECTED_SWIFT_FORMAT_RULES = { - "AllPublicDeclarationsHaveDocumentation": False, - "AlwaysUseLiteralForEmptyCollectionInit": True, - "AlwaysUseLowerCamelCase": True, - "AmbiguousTrailingClosureOverload": True, - "AvoidRetroactiveConformances": True, - "BeginDocumentationCommentWithOneLineSummary": False, - "DoNotUseSemicolons": True, - "DontRepeatTypeInStaticProperties": True, - "FileScopedDeclarationPrivacy": True, - "FullyIndirectEnum": True, - "GroupNumericLiterals": True, - "IdentifiersMustBeASCII": True, - "NeverForceUnwrap": False, - "NeverUseForceTry": True, - "NeverUseImplicitlyUnwrappedOptionals": False, - "NoAccessLevelOnExtensionDeclaration": True, - "NoAssignmentInExpressions": True, - "NoBlockComments": True, - "NoCasesWithOnlyFallthrough": True, - "NoEmptyLinesOpeningClosingBraces": True, - "NoEmptyTrailingClosureParentheses": True, - "NoLabelsInCasePatterns": True, - "NoLeadingUnderscores": False, - "NoParensAroundConditions": True, - "NoPlaygroundLiterals": True, - "NoVoidReturnOnFunctionSignature": True, - "OmitExplicitReturns": False, - "OneCasePerLine": True, - "OneVariableDeclarationPerLine": True, - "OnlyOneTrailingClosureArgument": True, - "OrderedImports": True, - "ReplaceForEachWithForLoop": True, - "ReturnVoidInsteadOfEmptyTuple": True, - "TypeNamesShouldBeCapitalized": True, - "UseEarlyExits": False, - "UseExplicitNilCheckInConditions": True, - "UseLetInEveryBoundCaseVariable": True, - "UseShorthandTypeNames": True, - "UseSingleLinePropertyGetter": True, - "UseSynthesizedInitializer": True, - "UseTripleSlashForDocumentationComments": True, - "UseWhereClausesInForLoops": True, - "ValidateDocumentationComments": True, -} - -MARKDOWN_LINK = re.compile(r"\[[^\]]+\]\(([^)]+)\)") -SEMVER = re.compile( - r"^(0|[1-9][0-9]*)\." - r"(0|[1-9][0-9]*)\." - r"(0|[1-9][0-9]*)" - r"(?:-((?:0|[1-9][0-9]*|[0-9]*[A-Za-z-][0-9A-Za-z-]*)" - r"(?:\.(?:0|[1-9][0-9]*|[0-9]*[A-Za-z-][0-9A-Za-z-]*))*))?" - r"(?:\+([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$" -) -FORBIDDEN = { - "/" + "Users" + "/": "personal absolute path", - "file" + "://": "local file URL", - "mobile-ios-" + "chauffeur": "work-repository identifier", - "black" + "lane": "work-repository identifier", -} - - -def text_files() -> list[Path]: - suffixes = {".md", ".py", ".swift", ".yml", ".yaml", ".txt"} - files = [path for path in ROOT.rglob("*") if path.is_file() and path.suffix in suffixes] - files.extend(path for path in (ROOT / "VERSION", ROOT / "LICENSE") if path.is_file()) - files.extend( - path - for path in (SWIFT_FORMAT_CONFIGURATION, EDITOR_CONFIGURATION) - if path.is_file() - ) - return sorted(set(files)) - - -def resolve_link(source: Path, raw_target: str) -> Path | None: - target = raw_target.strip().strip("<>").split("#", maxsplit=1)[0] - if not target or target.startswith(("#", "http://", "https://", "mailto:")): - return None - - parts = PurePosixPath(target).parts - if "AgentGuidelines" in parts: - index = parts.index("AgentGuidelines") - return ROOT.joinpath(*parts[index + 1 :]).resolve() - - return (source.parent / target).resolve() - - -def validate_links(errors: list[str]) -> None: - for source in sorted(ROOT.rglob("*.md")): - for raw_target in MARKDOWN_LINK.findall(source.read_text(encoding="utf-8")): - resolved = resolve_link(source, raw_target) - if resolved is not None and not resolved.exists(): - relative_source = source.relative_to(ROOT) - errors.append(f"{relative_source}: missing link target {raw_target!r}") - - -def validate_catalog(errors: list[str]) -> None: - readme = README.read_text(encoding="utf-8") - for guide in sorted((ROOT / "Guidelines").rglob("*.md")): - relative = guide.relative_to(ROOT).as_posix() - if f"]({relative})" not in readme: - errors.append(f"README.md: guideline is not cataloged: {relative}") - - -def validate_version(errors: list[str]) -> None: - version = VERSION.read_text(encoding="utf-8").strip() - if not SEMVER.fullmatch(version): - errors.append(f"VERSION: invalid semantic version {version!r}") - - changelog = CHANGELOG.read_text(encoding="utf-8") - if f"## [{version}]" not in changelog: - errors.append(f"CHANGELOG.md: missing release heading for {version}") - - -def validate_readme_contract(errors: list[str]) -> None: - readme = README.read_text(encoding="utf-8") - required = { - 'alt="Xcode"': "Xcode badge alt text", - "thatfactory/agent-guidelines/actions/workflows/ci.yml": "CI badge repository", - "--prefix=AgentGuidelines": "subtree destination", - "https://github.com/thatfactory/agent-guidelines.git": "subtree remote", - "git subtree add": "subtree installation command", - "git subtree pull": "subtree update command", - "AgentGuidelines/** linguist-generated": "generated subtree attribute", - "AgentGuidelines/Configurations/Swift/.swift-format": "swift-format symlink command", - "AgentGuidelines/Configurations/Swift/.editorconfig": "EditorConfig symlink command", - ".agents/skills/agent-guidelines-audit": "completion-audit skill setup", - "validate_consumer_setup.py": "consumer setup validation command", - "--require-swift-format": "explicit Swift-format adoption validation", - } - for value, description in required.items(): - if value not in readme: - errors.append(f"README.md: missing {description}: {value!r}") - - -def validate_public_content(errors: list[str]) -> None: - for path in text_files(): - contents = path.read_text(encoding="utf-8") - relative = path.relative_to(ROOT) - for forbidden, description in FORBIDDEN.items(): - if forbidden.lower() in contents.lower(): - errors.append(f"{relative}: contains {description}: {forbidden!r}") - - -def validate_swift_format_configuration(errors: list[str]) -> None: - try: - configuration = json.loads(SWIFT_FORMAT_CONFIGURATION.read_text(encoding="utf-8")) - except (OSError, json.JSONDecodeError) as error: - errors.append(f"{SWIFT_FORMAT_CONFIGURATION.relative_to(ROOT)}: invalid JSON: {error}") - return - - expected_values = { - "indentation": {"spaces": 4}, - "indentSwitchCaseLabels": False, - "lineLength": 120, - "tabWidth": 4, - "version": 1, - } - for key, expected in expected_values.items(): - actual = configuration.get(key) - if actual != expected: - errors.append( - f"{SWIFT_FORMAT_CONFIGURATION.relative_to(ROOT)}: " - f"{key} must be {expected!r}, found {actual!r}" - ) - - include_conditional_imports = configuration.get("orderedImports", {}).get( - "includeConditionalImports" - ) - if include_conditional_imports is not True: - errors.append( - f"{SWIFT_FORMAT_CONFIGURATION.relative_to(ROOT)}: " - "orderedImports.includeConditionalImports must be True, " - f"found {include_conditional_imports!r}" - ) - - rules = configuration.get("rules") - if not isinstance(rules, dict) or not rules: - errors.append( - f"{SWIFT_FORMAT_CONFIGURATION.relative_to(ROOT)}: " - "rules must be an exhaustive non-empty object" - ) - else: - missing = sorted(set(EXPECTED_SWIFT_FORMAT_RULES) - set(rules)) - unexpected = sorted(set(rules) - set(EXPECTED_SWIFT_FORMAT_RULES)) - if missing or unexpected: - errors.append( - f"{SWIFT_FORMAT_CONFIGURATION.relative_to(ROOT)}: " - f"rule map mismatch; missing={missing!r}, unexpected={unexpected!r}" - ) - for rule in sorted(set(rules) & set(EXPECTED_SWIFT_FORMAT_RULES)): - expected = EXPECTED_SWIFT_FORMAT_RULES[rule] - actual = rules[rule] - if actual != expected: - errors.append( - f"{SWIFT_FORMAT_CONFIGURATION.relative_to(ROOT)}: " - f"{rule} must be {expected!r}, found {actual!r}" - ) - - -def validate_editor_configuration(errors: list[str]) -> None: - try: - contents = EDITOR_CONFIGURATION.read_text(encoding="utf-8") - except OSError as error: - errors.append( - f"{EDITOR_CONFIGURATION.relative_to(ROOT)}: cannot read configuration: {error}" - ) - return - required = { - "root = true", - "[*.swift]", - "indent_style = space", - "indent_size = 4", - "tab_width = 4", - "max_line_length = 120", - "end_of_line = lf", - "insert_final_newline = true", - "trim_trailing_whitespace = true", - } - for value in sorted(required): - if value not in contents: - errors.append( - f"{EDITOR_CONFIGURATION.relative_to(ROOT)}: missing {value!r}" - ) - - -def validate_swift_format_script(errors: list[str]) -> None: - if not SWIFT_FORMAT_SCRIPT.is_file(): - errors.append(f"{SWIFT_FORMAT_SCRIPT.relative_to(ROOT)}: missing script") - elif not os.access(SWIFT_FORMAT_SCRIPT, os.X_OK): - errors.append(f"{SWIFT_FORMAT_SCRIPT.relative_to(ROOT)}: script is not executable") - - -def validate_swift_format_guideline(errors: list[str]) -> None: - contents = SWIFT_FORMAT_GUIDELINE.read_text(encoding="utf-8") - required = { - "## Swift package integration": "Swift package workflow", - "format-and-lint \\": "local package formatting command", - "Package.swift": "package manifest formatting scope", - "## CI integration": "CI workflow", - "lint-strict \\": "strict CI command", - "Never run `format` or `format-and-lint` in CI": "non-mutating CI rule", - } - for value, description in required.items(): - if value not in contents: - errors.append( - f"{SWIFT_FORMAT_GUIDELINE.relative_to(ROOT)}: " - f"missing {description}: {value!r}" - ) - - -def validate_consumer_setup_script(errors: list[str]) -> None: - if not CONSUMER_SETUP_SCRIPT.is_file(): - errors.append(f"{CONSUMER_SETUP_SCRIPT.relative_to(ROOT)}: missing script") - elif not os.access(CONSUMER_SETUP_SCRIPT, os.X_OK): - errors.append( - f"{CONSUMER_SETUP_SCRIPT.relative_to(ROOT)}: script is not executable" - ) - - -def validate_audit_skill(errors: list[str]) -> None: - if not AUDIT_SKILL.is_file(): - errors.append(f"{AUDIT_SKILL.relative_to(ROOT)}: missing audit skill") - return - - skill = AUDIT_SKILL.read_text(encoding="utf-8") - required_skill_values = { - "name: agent-guidelines-audit": "skill name", - "before claiming completion": "completion trigger", - "git diff --check": "diff validation", - "validate_consumer_setup.py": "consumer integration validation", - "format-and-lint": "local Swift-format audit", - "lint-strict": "strict Swift-format CI audit", - "no unresolved P0/P1 blocker remains": "Codex review stopping rule", - } - for value, description in required_skill_values.items(): - if value not in skill: - errors.append( - f"{AUDIT_SKILL.relative_to(ROOT)}: missing {description}: {value!r}" - ) - - development = DEVELOPMENT_GUIDELINE.read_text(encoding="utf-8") - if "$agent-guidelines-audit" not in development: - errors.append( - f"{DEVELOPMENT_GUIDELINE.relative_to(ROOT)}: " - "missing mandatory $agent-guidelines-audit invocation" - ) - - agents_template = AGENTS_TEMPLATE.read_text(encoding="utf-8") - if "AgentGuidelines/Guidelines/Development.md" not in agents_template: - errors.append( - f"{AGENTS_TEMPLATE.relative_to(ROOT)}: missing Development.md pointer" - ) - if "## Stack" not in agents_template: - errors.append(f"{AGENTS_TEMPLATE.relative_to(ROOT)}: missing Stack section") - - -def main() -> int: - errors: list[str] = [] - validate_links(errors) - validate_catalog(errors) - validate_version(errors) - validate_readme_contract(errors) - validate_public_content(errors) - validate_swift_format_configuration(errors) - validate_editor_configuration(errors) - validate_swift_format_script(errors) - validate_swift_format_guideline(errors) - validate_consumer_setup_script(errors) - validate_audit_skill(errors) - - if errors: - print("Guideline validation failed:") - for error in errors: - print(f"- {error}") - return 1 - - guide_count = len(list((ROOT / "Guidelines").rglob("*.md"))) - print(f"Validated {guide_count} guidelines for version {VERSION.read_text().strip()}.") - return 0 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/AgentGuidelines/Templates/AGENTS.md b/AgentGuidelines/Templates/AGENTS.md deleted file mode 100644 index 2728920..0000000 --- a/AgentGuidelines/Templates/AGENTS.md +++ /dev/null @@ -1,74 +0,0 @@ -# Project Instructions - -## Context - -Describe the product or package, supported platforms, and durable constraints. Link to the project README or product documentation instead of duplicating it. - -## Shared guidelines - -Read only the guides relevant to the task: - -- [Agent workflow](AgentGuidelines/Guidelines/AgentWorkflow.md) -- [Swift](AgentGuidelines/Guidelines/Swift/Swift.md) -- [Swift style](AgentGuidelines/Guidelines/Swift/SwiftStyle.md) -- [SwiftUI](AgentGuidelines/Guidelines/Swift/SwiftUI.md) -- [Swift format](AgentGuidelines/Guidelines/Swift/SwiftFormat.md) -- [Localization](AgentGuidelines/Guidelines/Swift/Localization.md) -- [Unit and integration testing](AgentGuidelines/Guidelines/Testing/UnitTesting.md) -- [Documentation](AgentGuidelines/Guidelines/Documentation.md) -- [Logging](AgentGuidelines/Guidelines/Logging.md) -- [Packages](AgentGuidelines/Guidelines/Packages.md) -- [Development workflow](AgentGuidelines/Guidelines/Development.md) -- [CI/CD](AgentGuidelines/Guidelines/CICD.md) -- [Git repositories and SSH-first cloning](AgentGuidelines/Guidelines/Git/Repositories.md) -- [GitHub pull requests](AgentGuidelines/Guidelines/GitHub/PullRequests.md) -- [Xcode MCP and visual verification](AgentGuidelines/Guidelines/Xcode/MCP.md) -- [Xcode security audits](AgentGuidelines/Guidelines/Xcode/Security.md) - -For an application that uses Redux, also read [Redux architecture](AgentGuidelines/Guidelines/Architecture/Redux.md). - -Keep the following marked contract in the consumer repository's root `AGENTS.md` so it is loaded directly for root-level Codex and pull-request work. Copy it unchanged and update it when the marker version changes in this template; a Markdown link to the detailed workflow is not an instruction include. - -```md - -## Code Review Rules - -Review for release-blocking defects introduced or materially exposed by the pull request. A clean review means no unresolved P0/P1 findings; it does not mean exhaustive or perfect software. - -A blocking finding must identify a concrete, reachable path in a supported use case or the documented threat model that can cause a credible security-boundary bypass, durable data loss or corruption, a crash or deadlock, loss of availability, violation of an explicit acceptance criterion, or a serious compatibility regression. - -For every blocking finding, state the severity, preconditions, execution path, impact, evidence, and actionable remediation. Group manifestations that share the same root cause into one finding. - -Treat P2/P3 observations as non-blocking, including defense-in-depth, theoretical completeness, unsupported use cases, malformed state that trusted code cannot produce, behavior by components outside the threat model, style preferences, and speculative refactoring. Record a useful lower-severity observation once as deferred, declined, duplicate, or follow-up work; do not keep the review loop open for it. - -In an initial review, report substantiated blockers together. A follow-up review is limited to unresolved P0/P1 findings, changes since the last reviewed commit, and code directly affected by those changes. Do not restart an unrestricted review of unchanged code. A new follow-up finding must be a P0/P1 defect introduced by the remediation or genuinely hidden by the previous blocker. - -Automatic Codex review is the initial review. Do not request a manual Codex review unless the repository owner explicitly asks. Never request another review after each remediation commit. Within the normal review budget, at most one owner-authorized, delta-scoped verification review may be requested under [the pull-request review workflow](AgentGuidelines/Guidelines/GitHub/PullRequests.md). - - -## Codex review scope - -For consumer pull requests, do not substantively review `AgentGuidelines/**` after exact tagged-tree provenance has been verified. Verify its `VERSION`, compare its tree with the matching central tag, and verify the required `.gitattributes` rule. If provenance does not match exactly, review the subtree contents and stop the merge. Report substantive guideline feedback against the central `agent-guidelines` pull request. -``` - -The marked block is intentional controlled duplication of the shared review policy. The tracked, synchronized subtree is reviewed centrally in `thatfactory/agent-guidelines`; the root-level instructions ensure the review contract and subtree scope are loaded even when Codex starts from the repository root. - -## Physical folder map - -Replace these examples with exact repository paths: - -| Role | Physical folder | -|---|---| -| Application sources | `/` | -| Redux | `/Redux/` | -| Views | `/View/` | -| Services | `/Services/` | -| Unit tests | `Tests/` | - -## Stack - -Record the supported Xcode, Swift, and platform versions. State strict-concurrency mode, default actor isolation, infer-isolated-conformance behavior, and `nonisolated(nonsending)` defaults when they apply. Clarify whether application, package, and test targets share those settings. - -## Local specialization - -State only rules that specialize or override the shared baseline. Explain their scope and point to local source-of-truth documentation. diff --git a/AgentGuidelines/Templates/GlobalCodexInstructions.md b/AgentGuidelines/Templates/GlobalCodexInstructions.md deleted file mode 100644 index abe4578..0000000 --- a/AgentGuidelines/Templates/GlobalCodexInstructions.md +++ /dev/null @@ -1,30 +0,0 @@ -# Global Codex Instructions - -For repositories containing an `AGENTS.md`, read and follow the applicable repository instructions before starting substantive work. - -When a repository includes shared agent guidelines, read only the guides referenced by the applicable `AGENTS.md`. Treat those guides as the source of truth for language conventions, architecture, development workflow, testing, and agent execution. - -Repository and folder-level instructions may specialize the shared baseline within their scope. Do not replace deliberate repository conventions with generic global preferences. - -Do not duplicate repository-specific guidance in global instructions. Global instructions should bootstrap discovery of the repository's own sources of truth. - -## Code review behavior - -When acting as a code reviewer, optimize for high-signal release risk and convergence rather than exhaustive perfection. - -Create an inline finding only when all of the following are true: - -1. The issue is introduced or materially exposed by the proposed change. -2. There is a concrete, reachable failure path in a supported use case or the documented threat model. -3. The impact is P0 or P1: a credible security-boundary bypass, durable data loss or corruption, a crash or deadlock, loss of availability, violation of an explicit acceptance criterion, or a serious compatibility regression. -4. The evidence and remediation are specific enough to be actionable. - -State the finding's severity, preconditions, execution path, impact, and evidence. Group findings that share the same root cause. Do not create separate serial comments for additional manifestations of an already reported root cause. - -Treat P2 and P3 observations as non-blocking. This includes defense-in-depth, theoretical completeness, unsupported use cases, malformed state that trusted code cannot produce, adversarial behavior by components outside the threat model, style preferences, speculative refactoring, and exhaustive enumeration of equivalent input formats. Summarize valuable lower-severity observations once or recommend a follow-up issue. - -In the initial review, report substantiated blockers together rather than drip-feeding them across repeated reviews. - -In a follow-up review, verify previously reported P0/P1 findings and review only changes since the previously reviewed commit plus code directly affected by those changes. Do not restart an unrestricted search of unchanged code. A newly introduced follow-up finding must be a P0/P1 issue introduced by the remediation or genuinely hidden by the previous defect. - -A clean review means that there are no unresolved P0/P1 blockers. It does not mean perfect software, zero possible improvements, or zero technical debt. diff --git a/AgentGuidelines/Tests/test_validate_consumer_setup.py b/AgentGuidelines/Tests/test_validate_consumer_setup.py deleted file mode 100644 index 4db91af..0000000 --- a/AgentGuidelines/Tests/test_validate_consumer_setup.py +++ /dev/null @@ -1,253 +0,0 @@ -"""Tests for consumer agent-guidelines integration validation.""" - -from __future__ import annotations - -import importlib.util -import tempfile -import unittest -from pathlib import Path - - -VALIDATOR_PATH = ( - Path(__file__).resolve().parents[1] / "Scripts" / "validate_consumer_setup.py" -) -SPEC = importlib.util.spec_from_file_location("validate_consumer_setup", VALIDATOR_PATH) -assert SPEC is not None -assert SPEC.loader is not None -VALIDATOR = importlib.util.module_from_spec(SPEC) -SPEC.loader.exec_module(VALIDATOR) - - -class ConsumerSetupTests(unittest.TestCase): - """Verifies checked-in consumer guidance and symlink wiring.""" - - def setUp(self) -> None: - self.temporary_directory = tempfile.TemporaryDirectory(dir=VALIDATOR.GUIDELINES_ROOT) - self.consumer_root = Path(self.temporary_directory.name) - (self.consumer_root / "AgentGuidelines").symlink_to( - VALIDATOR.GUIDELINES_ROOT, - target_is_directory=True, - ) - - template = ( - VALIDATOR.GUIDELINES_ROOT / "Templates" / "AGENTS.md" - ).read_text(encoding="utf-8") - contract_errors: list[str] = [] - contract = VALIDATOR.extract_contract(template, contract_errors, "template") - self.assertEqual(contract_errors, []) - self.assertIsNotNone(contract) - - agents = f"""# Project Instructions - -{contract} - -## Codex review scope - -For consumer pull requests, verify exact tagged-tree provenance before excluding -`AgentGuidelines/**`, and confirm the required `.gitattributes` rule. -""" - (self.consumer_root / "AGENTS.md").write_text(agents, encoding="utf-8") - (self.consumer_root / ".gitattributes").write_text( - "AgentGuidelines/** linguist-generated\n", - encoding="utf-8", - ) - - skill_parent = self.consumer_root / ".agents" / "skills" - skill_parent.mkdir(parents=True) - (skill_parent / "agent-guidelines-audit").symlink_to( - VALIDATOR.GUIDELINES_ROOT - / ".agents" - / "skills" - / "agent-guidelines-audit", - target_is_directory=True, - ) - - def tearDown(self) -> None: - self.temporary_directory.cleanup() - - def validate(self, require_swift_format: bool = False) -> list[str]: - errors: list[str] = [] - VALIDATOR.validate_consumer_setup( - errors, - self.consumer_root, - require_swift_format=require_swift_format, - ) - return errors - - def adopt_swift_format(self) -> None: - agents_path = self.consumer_root / "AGENTS.md" - agents = agents_path.read_text(encoding="utf-8") - agents_path.write_text( - f"{agents}\n[Swift format]({VALIDATOR.SWIFT_FORMAT_GUIDE})\n", - encoding="utf-8", - ) - - def add_swift_format_links(self) -> None: - (self.consumer_root / ".swift-format").symlink_to( - VALIDATOR.GUIDELINES_ROOT / "Configurations" / "Swift" / ".swift-format" - ) - (self.consumer_root / ".editorconfig").symlink_to( - VALIDATOR.GUIDELINES_ROOT / "Configurations" / "Swift" / ".editorconfig" - ) - - def add_package(self) -> None: - (self.consumer_root / "Package.swift").write_text( - "// swift-tools-version: 6.0\n", - encoding="utf-8", - ) - (self.consumer_root / "Sources").mkdir() - (self.consumer_root / "Tests").mkdir() - - def add_strict_format_ci(self, paths: tuple[str, ...] = ()) -> None: - workflows = self.consumer_root / ".github" / "workflows" - workflows.mkdir(parents=True) - command = " AgentGuidelines/Scripts/swift_format.sh lint-strict" - if paths: - path_lines = [] - for index, path in enumerate(paths): - continuation = " \\" if index < len(paths) - 1 else "" - path_lines.append(f" {path}{continuation}") - command += " \\\n" + "\n".join(path_lines) - (workflows / "ci-pr.yml").write_text( - f"""name: CI (PR) -on: - pull_request: - push: - branches: [main] -jobs: - swift-format: - name: Swift Format - steps: - - name: Run strict swift-format lint - run: | -{command} -""", - encoding="utf-8", - ) - - def test_valid_consumer_setup(self) -> None: - """Accepts a synchronized root contract and repository skill symlink.""" - self.assertEqual(self.validate(), []) - - def test_rejects_stale_code_review_contract(self) -> None: - """Rejects a consumer root contract that drifted from the template.""" - agents_path = self.consumer_root / "AGENTS.md" - agents = agents_path.read_text(encoding="utf-8") - agents_path.write_text(agents.replace("P0/P1", "P0", 1), encoding="utf-8") - - self.assertTrue( - any("code-review contract does not match" in error for error in self.validate()) - ) - - def test_rejects_copied_audit_skill(self) -> None: - """Rejects a stale-copy risk in place of the repository symlink.""" - skill = self.consumer_root / ".agents" / "skills" / "agent-guidelines-audit" - skill.unlink() - skill.mkdir() - (skill / "SKILL.md").write_text("stale copy\n", encoding="utf-8") - - self.assertTrue(any("must be a symlink" in error for error in self.validate())) - - def test_requires_generated_attribute(self) -> None: - """Rejects a consumer without the collapsed subtree diff rule.""" - (self.consumer_root / ".gitattributes").write_text("*.md text\n", encoding="utf-8") - - self.assertTrue(any("linguist-generated" in error for error in self.validate())) - - def test_rejects_missing_local_agent_link(self) -> None: - """Rejects a local guideline pointer that does not resolve.""" - agents_path = self.consumer_root / "AGENTS.md" - agents = agents_path.read_text(encoding="utf-8") - agents_path.write_text( - f"{agents}\n[Missing guide](AgentGuidelines/Guidelines/Missing.md)\n", - encoding="utf-8", - ) - - self.assertTrue( - any("missing local link target" in error for error in self.validate()) - ) - - def test_explicitly_requires_formatter_adoption(self) -> None: - """Allows an audit to require formatting before AGENTS.md links the guide.""" - self.assertEqual(self.validate(), []) - - errors = self.validate(require_swift_format=True) - - self.assertTrue(any("consumer .swift-format" in error for error in errors)) - self.assertTrue(any("consumer .editorconfig" in error for error in errors)) - self.assertTrue(any("Swift format CI" in error for error in errors)) - - def test_adopted_formatter_requires_links_and_ci(self) -> None: - """Detects incomplete adoption from the consumer AGENTS.md link.""" - self.adopt_swift_format() - - errors = self.validate() - - self.assertTrue(any("consumer .swift-format" in error for error in errors)) - self.assertTrue(any("consumer .editorconfig" in error for error in errors)) - self.assertTrue(any("Swift format CI" in error for error in errors)) - - def test_accepts_adopted_package_formatter(self) -> None: - """Accepts package configuration links and complete strict CI coverage.""" - self.adopt_swift_format() - self.add_swift_format_links() - self.add_package() - self.add_strict_format_ci(("Package.swift", "Sources", "Tests")) - - self.assertEqual(self.validate(), []) - - def test_rejects_mutating_ci_formatter(self) -> None: - """Rejects source rewriting inside CI even when strict lint is also present.""" - self.adopt_swift_format() - self.add_swift_format_links() - self.add_strict_format_ci() - workflow = self.consumer_root / ".github" / "workflows" / "ci-pr.yml" - workflow.write_text( - workflow.read_text(encoding="utf-8") - + " AgentGuidelines/Scripts/swift_format.sh format Sources\n", - encoding="utf-8", - ) - - self.assertTrue(any("must not mutate sources" in error for error in self.validate())) - - def test_rejects_ci_without_required_triggers(self) -> None: - """Requires strict lint for pull requests and main-branch merges.""" - self.adopt_swift_format() - self.add_swift_format_links() - self.add_strict_format_ci() - workflow = self.consumer_root / ".github" / "workflows" / "ci-pr.yml" - contents = workflow.read_text(encoding="utf-8") - workflow.write_text( - contents.replace(" pull_request:\n", "").replace( - " push:\n branches: [main]\n", - "", - ), - encoding="utf-8", - ) - - errors = self.validate() - - self.assertTrue(any("does not run for pull requests" in error for error in errors)) - self.assertTrue(any("does not run for pushes to main" in error for error in errors)) - - def test_rejects_incomplete_package_ci_scope(self) -> None: - """Requires all standard package Swift roots in strict CI.""" - self.adopt_swift_format() - self.add_swift_format_links() - self.add_package() - self.add_strict_format_ci(("Sources",)) - workflow = self.consumer_root / ".github" / "workflows" / "ci-pr.yml" - workflow.write_text( - workflow.read_text(encoding="utf-8") - + " - run: echo Package.swift Tests\n", - encoding="utf-8", - ) - - errors = self.validate() - - self.assertTrue(any("'Package.swift'" in error for error in errors)) - self.assertTrue(any("'Tests'" in error for error in errors)) - - -if __name__ == "__main__": - unittest.main() diff --git a/AgentGuidelines/Tests/test_validate_guidelines.py b/AgentGuidelines/Tests/test_validate_guidelines.py deleted file mode 100644 index 1216b37..0000000 --- a/AgentGuidelines/Tests/test_validate_guidelines.py +++ /dev/null @@ -1,144 +0,0 @@ -"""Tests for the guideline repository validator.""" - -from __future__ import annotations - -import importlib.util -import json -import tempfile -import unittest -from pathlib import Path -from unittest import mock - - -VALIDATOR_PATH = Path(__file__).resolve().parents[1] / "Scripts" / "validate_guidelines.py" -SPEC = importlib.util.spec_from_file_location("validate_guidelines", VALIDATOR_PATH) -assert SPEC is not None -assert SPEC.loader is not None -VALIDATOR = importlib.util.module_from_spec(SPEC) -SPEC.loader.exec_module(VALIDATOR) - - -class SemanticVersionTests(unittest.TestCase): - """Verifies the supported Semantic Versioning grammar.""" - - def test_valid_versions(self) -> None: - """Accepts core, prerelease, and build metadata forms.""" - versions = ( - "0.0.2", - "1.2.3-rc.1+build.5", - "1.0.0-alpha-beta", - "1.0.0+001", - ) - - for version in versions: - with self.subTest(version=version): - self.assertIsNotNone(VALIDATOR.SEMVER.fullmatch(version)) - - def test_invalid_versions(self) -> None: - """Rejects leading zeroes and incomplete identifiers.""" - versions = ( - "01.2.3", - "1.02.3", - "1.2.03", - "1.2.3-01", - "1.2.3-rc.01", - "1.2.3+", - "1.2.3-", - ) - - for version in versions: - with self.subTest(version=version): - self.assertIsNone(VALIDATOR.SEMVER.fullmatch(version)) - - -class SwiftFormattingConfigurationTests(unittest.TestCase): - """Verifies the shared Swift formatting contract.""" - - def test_swift_format_configuration(self) -> None: - """Accepts the exhaustive Xcode-aligned swift-format configuration.""" - errors: list[str] = [] - - VALIDATOR.validate_swift_format_configuration(errors) - - self.assertEqual(errors, []) - - def test_swift_format_configuration_rejects_undocumented_rule_change(self) -> None: - """Rejects a changed rule value even when the exhaustive key set is unchanged.""" - configuration = json.loads( - VALIDATOR.SWIFT_FORMAT_CONFIGURATION.read_text(encoding="utf-8") - ) - configuration["rules"]["NeverForceUnwrap"] = True - - with tempfile.TemporaryDirectory(dir=VALIDATOR.ROOT) as directory: - path = Path(directory) / ".swift-format" - path.write_text(json.dumps(configuration), encoding="utf-8") - errors: list[str] = [] - - with mock.patch.object(VALIDATOR, "SWIFT_FORMAT_CONFIGURATION", path): - VALIDATOR.validate_swift_format_configuration(errors) - - self.assertTrue( - any("NeverForceUnwrap must be False, found True" in error for error in errors) - ) - - def test_swift_format_configuration_requires_conditional_import_sorting(self) -> None: - """Rejects disabling conditional import sorting.""" - configuration = json.loads( - VALIDATOR.SWIFT_FORMAT_CONFIGURATION.read_text(encoding="utf-8") - ) - configuration["orderedImports"]["includeConditionalImports"] = False - - with tempfile.TemporaryDirectory(dir=VALIDATOR.ROOT) as directory: - path = Path(directory) / ".swift-format" - path.write_text(json.dumps(configuration), encoding="utf-8") - errors: list[str] = [] - - with mock.patch.object(VALIDATOR, "SWIFT_FORMAT_CONFIGURATION", path): - VALIDATOR.validate_swift_format_configuration(errors) - - self.assertTrue( - any( - "orderedImports.includeConditionalImports must be True" in error - for error in errors - ) - ) - - def test_editor_configuration(self) -> None: - """Accepts the shared Swift EditorConfig values.""" - errors: list[str] = [] - - VALIDATOR.validate_editor_configuration(errors) - - self.assertEqual(errors, []) - - def test_swift_format_guideline(self) -> None: - """Accepts the documented package and non-mutating CI workflows.""" - errors: list[str] = [] - - VALIDATOR.validate_swift_format_guideline(errors) - - self.assertEqual(errors, []) - - -class AgentGuidelinesAuditSkillTests(unittest.TestCase): - """Verifies the mandatory completion-audit skill contract.""" - - def test_audit_skill_contract(self) -> None: - """Accepts the skill, Development rule, and consumer template.""" - errors: list[str] = [] - - VALIDATOR.validate_audit_skill(errors) - - self.assertEqual(errors, []) - - def test_consumer_setup_script(self) -> None: - """Accepts the executable deterministic consumer validator.""" - errors: list[str] = [] - - VALIDATOR.validate_consumer_setup_script(errors) - - self.assertEqual(errors, []) - - -if __name__ == "__main__": - unittest.main() diff --git a/AgentGuidelines/VERSION b/AgentGuidelines/VERSION deleted file mode 100644 index 32786aa..0000000 --- a/AgentGuidelines/VERSION +++ /dev/null @@ -1 +0,0 @@ -0.0.18 diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..4c7ad3c --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,420 @@ +# Changelog + +All notable changes to this project are documented in this file. + +## [0.0.47] - 2026-11-06 + +### Added + +- Added independently versioned Codex review policy with full and review-only adoption profiles, exact managed root contracts, a Swift synchronizer, and a pinned shared CI action. Latest-policy checks reject stale or modified content and uncertain provenance. +- Added regression coverage for synchronization, preservation of local instructions, profile boundaries, duplicate contracts, publication identities, and unavailable policy sources. + +### Changed + +- Restricted review output to substantiated P0/P1 defects, clarified one automatic opening/ready review with local verification of batched remediation, and retained bounded monitoring and explicit owner authorization for extra review. +- Made reviewer rules and PR lifecycle available directly in every root instruction file without adopting unrelated guidance. Removed retired delegated-review exceptions and aligned audit, release, and global instruction templates. + +## [0.0.46] - 2026-11-05 + +### Changed + +- Made the self-hosted runner's active Xcode/Swift toolchain the CI default, with environment logging and real build/test validation. Exact version or build pins require a documented, evidence-backed repository exception with a revisit condition. +- Updated the Xcode-upgrade skill to remove unjustified CI pins instead of moving them to the newly validated version. +- Clarified Swift package badges: omit Updated and Revision/latest-release-version badges unless a documented reader need justifies them; retain Release/publishing workflow-status badges for the package's own workflows. + +### Added + +- Added completion-audit checks for toolchain constraints in workflows and invoked scripts, documented exceptions, active-toolchain validation, and Swift package badge semantics. + +## [0.0.45] - 2026-11-04 + +### Added + +- Added the canonical Networking guide requiring Apple-native networking and typed HTTP through Apple's `swift-http-types` HTTPTypes and HTTPTypesFoundation products with URLSession transport, including native bridges and justified capability-gap exceptions. +- Added networking audit coverage for actual typed implementation, target linkage, native transport, validation, and explicit adoption deferrals without a false full-compliance claim. + +### Changed + +- Centralized network transport ownership and validation guidance with links from architecture, package, testing, and security guides. +- Updated the consumer external-dependency contract to v2 for the narrow standing approval of `swift-http-types`; consumers must synchronize the root contract on adoption. Other external runtime dependencies retain their approval requirements. + +## [0.0.44] - 2026-10-30 + +### Added + +- Added the reusable `xcode-upgrade` skill for intentional Xcode, dependency, compiler-settings, and CI upgrades in applications and Swift packages, including requested project-format conversion and evidence-based validation. +- Documented consumer discovery through a subtree skill symlink and explicit invocation with a target Xcode and additional instructions. + +## [0.0.43] - 2026-10-29 + +### Added + +- Documented a bounded physical Apple TV diagnostic for current-user CloudKit and local-store identity, including the observed secondary-profile account crossover, privacy-safe comparisons, profile re-addition, and limits on attributing a tvOS cause. +- Added audit coverage for real two-account evidence when a consumer changes tvOS per-user storage or CloudKit account binding; unrelated changes and documentation-only work remain outside that gate. + +## [0.0.42] - 2026-10-20 + +### Changed + +- Replaced the explicit-request restriction on Reduce Motion adaptations with Apple-aligned evaluation of individual motion triggers, responsive preference handling, and preservation of useful feedback. +- Required platform-specific common-task evidence before declaring Reduced Motion support, with re-evaluation on app updates and a link from App Store metadata guidance. +- Added focused Reduce Motion audit checks, scenario walkthroughs, and validator regression coverage for policy, evidence, and support claims. + +## [0.0.41] - 2026-10-20 + +### Added + +- Required reusable custom-styled controls to own smooth visual transitions while functional state changes immediately, preserving native feedback, stable identity, and narrow animation scope. +- Added display-appropriate image preparation, bounded memory, derivative invalidation, original preservation, and stale-result rejection guidance. +- Added an animation and image-rendering audit with targeted runtime evidence, honest performance measurements, scenario walkthroughs, and validator mutation coverage. Existing Reduce Motion policy is unchanged. + +## [0.0.40] - 2026-10-20 + +### Added + +- Made Apple-owned placement authoritative for standard navigation, dismissal, confirmation, and window controls, with semantic toolbar intent and native Back behavior preserved across platforms. +- Added a completion-audit check for control ownership, unjustified placement overrides, conflicting design mandates, and relevant interaction evidence. +- Added the `update-agent-guidelines` skill to persist shared decisions, ask about audit coverage when unspecified, update release metadata, and deliver an authorized reviewed PR and release. + +## [0.0.39] - 2026-10-19 + +### Added + +- Added shared Device Hub, physical-device, and simulator guidance covering tool and skill discovery, authorization, signing, keyboard controls, resource coordination, runtime evidence, controlled comparisons, and cleanup. +- Linked the workflow from Xcode MCP, Development, the guideline catalog, and the consumer instructions template while keeping product-specific environment constraints in consumers. + +## [0.0.38] - 2026-10-15 + +### Added + +- Made size-based scroll bounce the SwiftUI `ScrollView` default on supported deployment targets, with axis and environment-scope guidance for nested scrolling and modal sheets. +- Added a completion-audit check for new or changed `ScrollView` bounce behavior and documented exceptions. + +## [0.0.37] - 2026-10-14 + +### Added + +- Made native SwiftUI and platform components the default for supported interactions, with approved durable exceptions required for verified native capability gaps. +- Defined presentation hierarchy, independent child dismissal, parent draft retention, cancellation, dismissal-completion cleanup, and required runtime interaction evidence. +- Added a mandatory completion-audit decision check for custom component and presentation lifecycle replacements, with validator and regression coverage. + +## [0.0.36] - 2026-10-09 + +### Added + +- Added SwiftUI animation guidance favoring purposeful native feedback, default SwiftUI animation, system transitions, and SF Symbol effects while keeping animations scoped and interactions responsive. +- Required an explicit task-prompt request before adding app-level Reduce Motion guards, while preserving accessibility behavior supplied automatically by native system components. + +## [0.0.35] - 2026-09-27 + +### Changed + +- Require positive repository-specific evidence before automatic Codex review becomes a merge gate. Track configuration separately from current-head execution, default undiscoverable settings to `unknown`, and bound deduplicated start-signal monitoring to five minutes. + +## [0.0.34] - 2026-09-20 + +### Changed + +- Required every ThatFactory package emoji to be unique in the Swift Package Collection and synchronized across package documentation, the logging gateway, and the collection registry. +- Extended the completion audit to block package publication when emoji uniqueness cannot be verified or the registered and emitted identities disagree. + +## [0.0.33] - 2026-09-19 + +### Added + +- Added a Swift Package compiler-settings baseline aligned with the applicable Xcode project warning, Swift language-mode, concurrency, and upcoming-feature policies. +- Added completion-audit enforcement for compiler settings in checked-in Swift packages. + +### Changed + +- Required future Xcode compiler-policy changes to evaluate and update Swift Package Manager parity when an equivalent package setting is applicable. + +## [0.0.32] - 2026-09-13 + +### Changed + +- Made runtime observability an explicit consumer contract for changed stateful, asynchronous, fallible, and lifecycle behavior, while preserving silence for pure values and utilities without meaningful diagnostic boundaries. +- Extended the completion audit to require useful privacy-safe AppLogger outcome coverage instead of accepting dependency declaration and target linkage alone. + +## [0.0.31] - 2026-09-13 + +### Added + +- Added a least-privilege GitHub App authentication pattern for workflows that resolve private sibling repositories, including short-lived read-only tokens, process-scoped Git configuration, exact repository selection, and fork pull-request and self-hosted-runner security boundaries. + +## [0.0.30] - 2026-09-12 + +### Changed + +- Prohibited dedicated License headings and conventional standalone license-description paragraphs in Swift package READMEs while retaining root license files and standard license badges. + +## [0.0.29] - 2026-09-12 + +### Added + +- Added a reusable `.gitignore` template for Xcode, Swift Package Manager, and supported development tooling, plus shared guidance for reviewed project-specific exceptions. + +### Changed + +- Extended the completion audit to reconcile consumer `.gitignore` files with the shared template and escalate undocumented extra patterns for a repository-owner decision. +- Prohibited CocoaPods and Carthage under the external-dependency policy, and prohibited fastlane under CI/CD guidance while requiring first-party Swift or ThatFactory delivery tooling and narrowing Python or shell automation to documented Swift capability gaps. + +## [0.0.28] - 2026-09-09 + +### Added + +- Added a shared version-controlled App Store metadata and app-store-connect-mcp synchronization workflow, including scoped planning, immutable application, reconciliation, screenshot, credential, and submission boundaries. +- Added `ITSAppUsesNonExemptEncryption = NO` to the Xcode application baseline and completion audit, with a documented-exception path for apps that ship non-exempt encryption. +- Added mandatory post-merge cleanup of merged local feature branches after returning to an updated primary branch. + +### Changed + +- Linked localization guidance to the shared App Store metadata workflow while keeping product voice, locales, and concrete storefront content in consumer repositories. + +## [0.0.27] - 2026-09-05 + +### Fixed + +- Preserved valid GitHub alert syntax in the Markdown wrapping audit while continuing to reject hard-wrapped alert bodies, ordinary blockquotes, malformed alert markers, and nested alerts. + +## [0.0.26] - 2026-09-02 + +### Added + +- Added a fail-closed completion-audit helper that requires structured Xcode String Catalog editor evidence for every changed `.xcstrings` file. +- Added native Swift tests for guideline, consumer-integration, Markdown, and String Catalog automation. + +### Changed + +- Moved the shared localization guide from `Guidelines/Swift/` to `Guidelines/` and updated repository and consumer-template links. +- Replaced Python validation, localization, and audit-helper scripts with native Swift executables, and moved CI and release validation to macOS runners. +- Required new repository-owned executable scripts in Swift-focused repositories to use Swift, with the existing `swift_format.sh` wrapper retained as a narrow exception. + +## [0.0.25] - 2026-09-02 + +### Added + +- Added generic generated-symbol localization guidance plus reusable String Catalog preparation and validation scripts with consumer-configured paths and languages. +- Added an Xcode project-settings baseline covering warnings-as-errors, strict and approachable concurrency, default MainActor isolation, the latest stable Swift language mode, and every upcoming feature that remains opt-in for that language mode. +- Added documentation conventions for single-line Markdown prose and aligned ASCII diagrams, together with a deterministic wrapping checker. + +### Changed + +- Expanded the completion audit to verify localization workflows, project-level Xcode setting inheritance and documented exceptions, documentation formatting, and convention adoption across existing durable documentation. +- Updated the consumer template and guideline catalog for the new Xcode project-settings and localization workflows. + +## [0.0.24] - 2026-08-31 + +### Added + +- Added a versioned external-dependency contract to consumer `AGENTS.md` files so applications, games, and reusable packages default to native or ThatFactory-owned implementations and require explicit repository-owner approval plus a durable decision record for third-party product dependencies. +- Extended the completion audit and consumer-setup validation to detect unapproved or undocumented dependency additions and contract drift. + +### Changed + +- Clarified package guidance so first-party packages cannot conceal third-party runtime dependencies and guideline-mandated tooling remains tooling-only. + +## [0.0.23] - 2026-08-26 + +### Added + +- Added a versioned documentation-maintenance contract to the consumer `AGENTS.md` template and consumer-setup validation so guideline upgrades detect projects that have not adopted the contract. + +### Changed + +- Strengthened documentation guidance and the completion audit so durable behavior changes and any change that makes existing documentation stale require documentation updates, while incidental implementation details do not create documentation churn. + +## [0.0.22] - 2026-08-24 + +### Added + +- Required completion audits to verify and repair shared AppLogger integration for ThatFactory Apple-platform applications and Swift packages. + +## [0.0.21] - 2026-08-23 + +### Changed + +- Clarified that the bounded review-round policy applies to Codex GitHub reviews, while other explicitly selected advisory workflows used their own limits. +- Namespaced Codex review tracking fields and advanced the consumer code-review contract to v2. + +## [0.0.20] - 2026-08-21 + +### Changed + +- Documented squash merge as the default for ThatFactory repositories and instructed agents to use `gh pr merge --squash` instead of attempting merge commits. + +## [0.0.19] - 2026-08-19 + +### Added + +- Added a complete README badge-block example covering Swift, Xcode, platform, package manager, agent/tooling, DocC, license, updated, revision, CI, and publishing badges. + +### Changed + +- Updated this repository's README badges to use the canonical order and applicable tooling, release, and maintenance badges. +- Updated the README contract validator to require the canonical `Xcode MCP` badge alt text. + +## [0.0.18] - 2026-08-18 + +### Changed + +- Corrected the standard README badge order to place DocC/documentation before license, updated date, revision, CI badges, and release/publishing status. + +## [0.0.17] - 2026-08-18 + +### Added + +- A version-marked consumer Code Review contract that defines P0/P1 release blockers, non-blocking P2/P3 observations, and bounded follow-up review scope. +- A deterministic consumer-setup validator for review-contract drift, subtree review scope, `.gitattributes`, local guide links, audit-skill wiring, and Swift-format adoption. + +### Changed + +- Expanded the global Codex instruction template and pull-request workflow to prioritize concrete release risk, group shared root causes, and stop review loops after blockers are resolved. +- Extended the completion-audit skill to verify consumer integration, review convergence, Swift-format configuration, local execution, and non-mutating CI coverage. +- Documented explicit Swift package formatting before tests and added a strict Swift-format CI template with package path coverage. + +## [0.0.16] - 2026-08-13 + +### Changed + +- Required SwiftUI dynamic properties to precede ordinary stored properties and clarified deterministic preview expectations. +- Required one top-level type per file, focused function decomposition, logical enum grouping, and consistent declaration-modifier and multiline-signature layout. +- Documented which declaration layout conventions remain review-guided because swift-format cannot enforce them without broad source reflow. + +## [0.0.15] - 2026-07-27 + +### Added + +- A shared agent-workflow guide for bounded grouping of independent repository inspections, with dependency, ordering, scope, and output-size safeguards. +- A versioned global Codex instruction template that bootstraps discovery of repository-local guidance without duplicating engineering policy. + +### Changed + +- Linked the workflow guide from the consumer template, documented the manual global Codex setup, and required alphabetical ordering of the README guideline catalog. +- Clarified that Codex review requests are automatic by default and must not be triggered manually without an explicit user request. + +## [0.0.14] - 2026-07-27 + +### Changed + +- Clarify Store/Middleware @MainActor usage. +- Removed workaround for a resolved Xcode issue. + +## [0.0.13] - 2026-07-26 + +### Added + +- A reusable `agent-guidelines-audit` skill and mandatory completion gate before handoff, pull requests, merge readiness, and releases. +- A canonical Redux Store template plus dependency-container and middleware-composition guidance. +- Consumer Stack guidance for recording toolchain, platform, strict-concurrency, and actor-isolation settings. + +### Changed + +- Clarified Redux folder ownership, familiar domain grouping, model-versus-tool classification, service-local helpers, presentation models, and one-component-per-file organization. +- Required documentation for new Swift declarations, meaningful `MARK` sections, one meaningful SwiftUI view per file, and deterministic previews where possible. +- Clarified when target isolation defaults replace explicit annotations and when compiler-verified boundaries still require them. +- Enabled conditional-import sorting and expanded validation for Swift templates, the audit skill, Stack guidance, and formatting policy. + +## [0.0.12] - 2026-07-25 + +### Added + +- Login-shell guidance for using explicitly authorized `gh` credentials exported by local shell startup configuration without exposing token values. + +## [0.0.11] - 2026-07-25 + +### Added + +- Pre-compilation Xcode build-phase guidance and a reusable `format-and-lint` command for human and agent workflows. +- An easy-to-find record of Xcode-aligned layout settings, enabled rule overrides, and deliberate non-adoptions. +- Pull-request guidance that prevents duplicate manual Codex requests when automatic review is enabled. + +### Changed + +- Enabled empty-array literals, force-try rejection, brace whitespace cleanup, `where` clauses in eligible loops, and documentation-comment validation. + +## [0.0.10] - 2026-07-24 + +### Added + +- Shared Xcode-aligned swift-format and EditorConfig configuration. +- Reusable format, warning-lint, and strict-lint commands for Swift consumers. + +### Changed + +- Replaced SwiftLint guidance with toolchain-native swift-format guidance. + +## [0.0.9] - 2026-07-23 + +### Added + +- Consumer pull-request review scope that excludes synchronized `AgentGuidelines/**` files from substantive Codex and human review outside the central repository. + +## [0.0.8] - 2026-07-23 + +### Added + +- Consumer guidance for keeping `AgentGuidelines/` tracked while collapsing synchronized files in GitHub pull-request diffs with `.gitattributes`. +- Pull-request conventions for isolated subtree commits, explicit version notes, central review links, and continued CI validation. + +## [0.0.7] - 2026-07-23 + +### Added + +- Shared logging ownership, subsystem, package emoji, message design, privacy, testing, and filtering guidance. +- Logging pointers for application development, Swift packages, and consumer instruction templates. + +## [0.0.6] - 2026-07-22 + +### Added + +- Generic Redux store contracts, state/action, service-boundary, projection, and middleware guidance. +- Generic GitHub Actions workflow, self-hosted runner, build strategy, and failure-investigation guidance. +- Shared documentation conventions and test-tag/mock guidance. + +## [0.0.5] - 2026-07-21 + +### Added + +- Default DocC documentation and GitHub Pages publishing guidance for Swift packages. + +## [0.0.4] - 2026-07-21 + +### Added + +- Development guidance for reusability-first design and checking the latest shared-guidelines version before project work. + +### Changed + +- Require an approved pull request before releasing `agent-guidelines` or any consumer package. + +## [0.0.3] - 2026-07-21 + +### Added + +- A Codex review-monitoring workflow covering paginated processing reactions and review threads, clean reviews, inline feedback, replies, thread resolution, and CI checks. + +## [0.0.2] - 2026-07-21 + +### Added + +- Standard README badge conventions for ThatFactory projects and packages. +- Git repository guidance that defaults push-capable clones to SSH remotes. +- GitHub pull-request review and merge-gate guidance. +- Updated and Revision badges to the repository README. + +### Changed + +- Updated GitHub workflows to `actions/checkout@v7` and documented using current stable action versions in new workflows. +- Clarified the Redux side-effect loop and the canonical view-projection test path. +- Expanded and tested semantic-version validation to support prerelease plus build metadata and reject invalid numeric identifiers. +- Removed the redundant README license section while retaining the MIT license badge and root license file. + +## [0.0.1] - 2026-07-21 + +### Added + +- Initial shared guidelines for Redux, Swift, SwiftUI, SwiftLint, localization, testing, documentation, package maintenance, CI/CD, Xcode MCP, and Xcode security audits. +- A consumer `AGENTS.md` template and Git subtree installation workflow. +- Structural validation for links, the documentation catalog, version metadata, subtree instructions, and public-repository safety. +- A tag-driven GitHub release workflow that validates the tag against `VERSION` and publishes changelog notes. diff --git a/AgentGuidelines/Configurations/Swift/.editorconfig b/Configurations/Swift/.editorconfig similarity index 100% rename from AgentGuidelines/Configurations/Swift/.editorconfig rename to Configurations/Swift/.editorconfig diff --git a/AgentGuidelines/Configurations/Swift/.swift-format b/Configurations/Swift/.swift-format similarity index 100% rename from AgentGuidelines/Configurations/Swift/.swift-format rename to Configurations/Swift/.swift-format diff --git a/AgentGuidelines/Guidelines/AgentWorkflow.md b/Guidelines/AgentWorkflow.md similarity index 100% rename from AgentGuidelines/Guidelines/AgentWorkflow.md rename to Guidelines/AgentWorkflow.md diff --git a/Guidelines/AppStore.md b/Guidelines/AppStore.md new file mode 100644 index 0000000..9729c12 --- /dev/null +++ b/Guidelines/AppStore.md @@ -0,0 +1,42 @@ +# App Store metadata + +Use a version-controlled `AppStore/` directory as the source of truth for managed App Store Connect content. Edit repository files first, then synchronize them with ThatFactory's [app-store-connect-mcp](https://github.com/thatfactory/app-store-connect-mcp). Do not maintain managed descriptions, promotional text, screenshots, or review notes through independent browser edits. + +## Repository structure + +Follow the MCP's current [AppStore directory format](https://github.com/thatfactory/app-store-connect-mcp/blob/main/Documentation/AppStore-Format.md). Keep structured values in JSON, prose in UTF-8 text files, and reusable screenshot originals under `AppStore/assets/`. One `AppStore/` root represents one App Store app; require an explicit root when a repository contains more than one app. + +Keep product-specific values in the consumer repository, including the Apple ID, bundle identifier, platforms, version strings, storefront locales, categories, URLs, product copy, review instructions, screenshot sets, and any narrower synchronization commands. Storefront locale identifiers and files are distinct from application String Catalogs, but the consumer's documented voice and terminology apply to both. + +Omission means unmanaged. Add only fields and domains the project intends to reconcile. Do not infer missing translations, version values, categories, availability, capabilities, or release choices from another project. + +## Synchronization workflow + +1. Edit only the requested files and fields in `AppStore/`. Preserve curated content outside the requested scope and obtain the project's required translation review for localized copy. +2. Run `validate_repository` with the explicit App Store root, platform, version, locales, and selected domains. Treat validation as scope-aware: unfinished content outside the intended operation must not expand that operation. +3. Run the applicable planning tool with the same scope. Use `plan_metadata_changes` for listing and review metadata, `plan_screenshot_changes` for screenshot sets, and the corresponding dedicated planner for commerce, provisioning, signing, or submission. Inspect the exact app, platform version, locales, operation IDs, additions, changes, removals, and destructive effects. +4. Apply only an inspected immutable plan within the owner's authorized scope. Supply the exact `planId`, digest, operation IDs, and required host confirmation to `apply_plan`. Plans are process-bound, so keep planning and application in the same MCP server process. +5. If an outcome is uncertain, inspect `get_operation_status` and remote state. Never replay a write whose execution may have started. +6. Plan the same scope again against unchanged repository inputs and require `noOp: true`. Record the reconciliation result alongside the repository change. + +Ordinary metadata, screenshot, commerce, provisioning, or signing synchronization does not authorize submitting a version for review or releasing it. Use the MCP's explicit readiness and submission workflow only when the owner has separately placed submission in scope. + +## Accessibility support claims + +Before adding or retaining a Reduced Motion support declaration, apply the shared [Reduce Motion support evaluation](Swift/SwiftUI.md#declaring-support). Keep the platform-specific consumer evidence current; adopting these guidelines alone does not establish support. Include any requested metadata change in the inspected synchronization plan above rather than inferring publication authority from a policy or implementation change. + +## Screenshots + +Treat each localization's `screenshots.json` as the ordered manifest for its selected display sets. Paths are relative to `AppStore/`, and the explicit array order is the storefront order. Preserve reusable originals in the repository; do not silently resize, transcode, substitute another locale, or derive ordering from filenames. + +Use `merge` when unrelated remote screenshots must remain unmanaged. Use `replace` only when the selected set should match the manifest exactly, and inspect every planned removal before applying it. After upload, allow Apple processing to finish and reconcile the final remote bytes and order. A temporarily absent source checksum is processing-pending evidence, not proof of a mismatch. + +## Credentials and operational state + +Keep `.appstore-connect-mcp/` as an ignored sibling of `AppStore/`; it contains process and recovery state, not repository content. Never commit or print App Store Connect keys, signing keys, certificates, private contacts, demo credentials, upload URLs, environment files, or MCP journals. Represent supported App Review secrets through the MCP's narrow environment-variable references, and pass credential variable names rather than values when configuring an MCP client. + +If the MCP process does not inherit credentials that are available to an authorized shell, correct or deliberately bridge the process environment without exposing values. Do not diagnose a credential as invalid merely because a different process did not inherit it. + +## Project-specific documentation + +Consumer documentation should identify its concrete `AppStore/` paths and managed domains, explain how product voice and locale coverage apply to storefront copy, describe screenshot production, and record any review, export-compliance, or release prerequisites. Keep generic MCP mechanics in this guide and link to them instead of copying the workflow into every repository. diff --git a/AgentGuidelines/Guidelines/Architecture/Redux.md b/Guidelines/Architecture/Redux.md similarity index 99% rename from AgentGuidelines/Guidelines/Architecture/Redux.md rename to Guidelines/Architecture/Redux.md index 4a28847..7c3920e 100644 --- a/AgentGuidelines/Guidelines/Architecture/Redux.md +++ b/Guidelines/Architecture/Redux.md @@ -216,7 +216,7 @@ Do not put SwiftUI types, colors, images, localized display strings, or render-r Put focused external-boundary abstractions in `Services/`. Services wrap APIs, persistence, packages, frameworks, sensors, system features, and other impure operations. Keep this folder flat while a capability has only one file; introduce a familiar capability folder such as `Services/FaceService/` or `Services/CalibrationService/` when that capability genuinely requires several related files. Middleware calls services; views and reducers do not. -Prefer a protocol or otherwise injectable contract when a service must be replaced in tests. Keep transport-specific details behind the service boundary. +Prefer a protocol or otherwise injectable contract when a service must be replaced in tests. Follow [Networking](../Networking.md) for networking implementation, transport ownership, and validation. Keep a supporting delegate, adapter, or helper beside its service when only that capability uses it. Local ownership is clearer than promoting a service-private framework bridge to a global `Tools/` folder. diff --git a/Guidelines/CICD.md b/Guidelines/CICD.md new file mode 100644 index 0000000..c96e469 --- /dev/null +++ b/Guidelines/CICD.md @@ -0,0 +1,124 @@ +# CI/CD + +## Workflow principles + +- Keep CI deterministic and reproducible through declared inputs, compiler settings, and validation, using the [runner toolchain policy](#runner-toolchain). +- Treat warnings introduced by a change as failures even when the compiler does not. +- Prefer the smallest permissions required by each workflow and job. +- For a new workflow, use the latest stable major version of every GitHub Action available at the time of creation. +- Do not copy an older major version into a fresh workflow unless a documented compatibility constraint requires it. +- For existing workflows, review action release notes and update deliberately rather than allowing runtime deprecation warnings to accumulate. +- Pin third-party actions to an intentional version and review updates. +- Do not place secrets in workflow files, logs, fixtures, or command arguments that may be echoed. +- Keep release workflows separate from pull-request validation when their permissions differ. + +## Runner toolchain + +Use the active Xcode and Swift toolchain supplied by the self-hosted runner. Log the selected developer directory, Xcode version/build, and Swift version so failures identify the actual environment. Let dependency resolution, compilation, tests, and required validation expose real incompatibilities after an update; a different version string alone must not fail a job. + +Do not pin an exact Xcode release, build number, or bundled Swift compiler version by default. This applies to workflow conditions, equality or text checks, setup-action inputs, versioned installation paths, runner labels, and scripts invoked by CI. Do not replace an exact check with an allowlist or upper bound that still rejects a compatible newer toolchain. Preserve legitimate minimum tools versions, Swift language modes, SDK/deployment requirements, simulator destinations, and capability or first-launch checks. These express supported capabilities rather than the last environment an agent happened to validate. + +A version pin is permitted only for a concrete repository-specific reason documented in that repository's `AGENTS.md` or linked durable build/CI documentation. Record the affected workflows and scripts, exact constraint, demonstrated incompatibility or external requirement, evidence, and the condition for revisiting or removing it. A historical upgrade target or a generic claim of reproducibility is not sufficient justification. Keep the exception as narrow as the demonstrated requirement, and report it during the completion audit. + +Respect the runner's configured selection, including an inherited `DEVELOPER_DIR`. A process-scoped override for an explicitly requested toolchain investigation or upgrade is appropriate; it does not authorize adding a permanent CI pin or changing machine-global `xcode-select`. Record historical validation versions as evidence without turning them into future acceptance conditions. + +For example, a workflow can report its environment without comparing version strings: + +```yaml +- name: Log active toolchain + run: | + xcode-select -p + xcodebuild -version + xcrun swiftc --version +``` + +## Tooling and automation + +Fastlane is forbidden in every ThatFactory project and has no exception path. Build repository-owned CI/CD and delivery automation with focused ThatFactory tooling such as `xcode-cloud-mcp` and `app-store-connect-mcp`, plus Swift scripts where repository-specific orchestration is needed. + +Use Swift for new repository-owned executable scripts in Swift-focused applications, games, and packages. Prefer the Swift standard library and Foundation so automation uses the same native toolchain and dependency policy as the codebase. Convenience, familiarity, shorter code, or an existing interpreter is not a reason to choose another language. + +Fall back to Python or a POSIX shell script only when the required behavior cannot be implemented with the repository's supported Swift toolchain and Foundation APIs. Document the exception in durable repository documentation in the same change, including the missing Swift capability, exact script and task scope, runtime and dependency requirements, security and maintenance impact, validation method, and condition for revisiting or removing the exception. Keep the fallback narrow; an existing non-Swift script does not authorize another one. The central `Scripts/swift_format.sh` command wrapper is the retained documented exception for invoking Xcode's `swift-format` modes. + +## Private repository dependencies + +The workflow repository's `GITHUB_TOKEN` does not grant access to private dependencies in sibling repositories. When Swift Package Manager or another build tool must clone private ThatFactory repositories, use a GitHub App installed on every required dependency repository. The app does not need access to the workflow repository unless that repository is also an intended token target. Grant the app only read access to repository contents, mint a short-lived installation token with `actions/create-github-app-token`, and list the exact dependency repositories in the action's `repositories` input. Do not use a personal access token, a long-lived machine credential, or an organization-wide token when the GitHub App can provide the required scope. + +Expose the installation token only to steps that resolve or build the private dependencies. Supply HTTPS authentication through Git's process-level `GIT_CONFIG_COUNT`, `GIT_CONFIG_KEY_0`, and `GIT_CONFIG_VALUE_0` environment variables so the credential is not persisted in repository or global Git configuration. Keep the existing dependency URLs as `https://github.com//` URLs. For example: + +```yaml +- name: Create private dependency token + id: private-dependencies + uses: actions/create-github-app-token@v3 + with: + client-id: ${{ vars.PRIVATE_DEPENDENCIES_APP_CLIENT_ID }} + private-key: ${{ secrets.PRIVATE_DEPENDENCIES_APP_PRIVATE_KEY }} + owner: ${{ github.repository_owner }} + repositories: | + first-private-package + second-private-package + permission-contents: read + +- name: Test + env: + GIT_CONFIG_COUNT: 1 + GIT_CONFIG_KEY_0: url.https://x-access-token:${{ steps.private-dependencies.outputs.token }}@github.com/.insteadOf + GIT_CONFIG_VALUE_0: https://github.com/ + run: swift test +``` + +The GitHub App's installation and repository selection are part of the security boundary. Consumer documentation must name the app variable and secret, list the private repositories the workflow requires, record the required `Contents: read` permission, and identify the jobs or steps that receive the token. Keep pull-request and protected-branch workflows consistent unless a documented trust boundary requires otherwise. Because `GIT_CONFIG_*` values are ordinary inherited environment variables, treat the credential-bearing resolve or build step and its complete subprocess tree as privileged. Tests, build scripts, SwiftPM plugins, and other code executed beneath that step must be trusted to receive read access to every repository in the token scope. + +Repository secrets are unavailable to workflows triggered by pull requests from forks. A repository that accepts fork-originated or otherwise untrusted pull requests must keep a secretless validation path or deliberately skip private-dependency jobs with an explicit, documented condition. Untrusted code must not execute on a persistent self-hosted runner that is later reused for credential-bearing work. Use an isolated disposable or ephemeral self-hosted runner, an appropriate GitHub-hosted runner where possible, or a separate runner pool or host that never subsequently receives secrets; otherwise skip the untrusted validation. + +This trust rule is event-independent. Do not combine credentials with code that is not trusted at that privilege level under `pull_request`, `pull_request_target`, `issue_comment`, `workflow_run`, or another trigger. On self-hosted runners, do not expose the token to unrelated steps, caches, artifacts, logs, or persistent configuration; retain the action's default post-job token revocation. + +## `ci-pr.yml` + +Projects using GitHub Actions should keep pull-request validation in `.github/workflows/ci-pr.yml`, triggered by `pull_request` events for `opened`, `synchronize`, and `reopened`. + +Use GitHub-hosted runners for jobs that can run on the hosted operating system and toolchain. When a job uses a self-hosted runner, document and select it through the repository's `Runner labels:` rather than hard-coding a machine name in shared guidance. + +### Runner labels: + +When a workflow uses self-hosted runners, document the labels required by each job in this section of the consumer's CI/CD guide. Always include `self-hosted` and add only stable capability or environment labels needed to select the runner, such as an operating system, architecture, toolchain, or signing capability. Keep machine names and changing fleet details out of shared guidance. + +A typical Swift package validates: + +- package resolution; +- build; +- Swift Testing tests; +- DocC generation when the package publishes documentation; +- repository-specific lint or validation scripts. + +An Xcode application validates its declared scheme and test plan. Use the same project/workspace, configuration, and platform assumptions documented for local development. + +Xcode projects and Swift packages must run on self-hosted macOS runners with the required Xcode, Swift toolchains, simulators, certificates, and signing environment. Do not use `macos-latest` for those jobs. For Xcode projects, test with `xcodebuild test` and explicit simulators, then validate compilation with `xcodebuild build CODE_SIGNING_ALLOWED=NO` across the supported platforms. For Swift packages, use Swift Package Manager commands such as `swift test` and `swift build`; packages do not require simulator selection, but may require the self-hosted signing environment for packaging or collection workflows. Generic jobs that do not require Apple tooling may use GitHub-hosted Linux or other suitable runners. CI validates tests and compile health, not app-store distribution. + +## `ci.yml` + +Validation of merges to `main` should live in `.github/workflows/ci.yml`, triggered by `push` on `main`. Use the same build, test, lint, and platform coverage as pull-request validation unless the repository documents a deliberate difference. + +## Failure investigation + +1. Use GitHub MCP connector tools to inspect check runs and logs for the failing commit or pull request. +2. Use `gh` for fast local triage when needed. +3. Reproduce locally with the exact build or test command shown in the failing job logs. + +Useful commands: + +```bash +gh run list --limit 10 +gh run view +gh run view --log +``` + +Distinguish compiler errors from lint violations, test failures from simulator or runtime infrastructure failures, and single-job failures from cross-platform matrix failures. Identify the first meaningful failing step, fix the narrowest root cause, and re-run affected validation. + +## Releases + +- A release tag and GitHub release must match the intended semantic version. +- Release notes summarize user- or integrator-relevant changes since the previous release. +- Use a notes file for multiline CLI release descriptions. +- Do not publish a release from an unverified or dirty worktree. +- Follow the consumer's local instructions for deployment, signing, notarization, App Store, or documentation publishing steps. diff --git a/Guidelines/Development.md b/Guidelines/Development.md new file mode 100644 index 0000000..38f650f --- /dev/null +++ b/Guidelines/Development.md @@ -0,0 +1,60 @@ +# Development + +## Reusability first + +When developing a new feature or responding to a feature request, consider shared code first. If the code fits an existing package, suggest extending that package instead of adding the implementation directly to an application. Also consider whether the change belongs in a new Swift package, even when that package does not exist yet. Prefer reusable, focused package APIs when they can serve more than one consumer. + +## External dependencies + +ThatFactory applications, games, and reusable packages are first-party by default. Do not introduce a new third-party source or binary dependency during normal feature development. Prefer Apple platform APIs, the Swift standard library, code owned by the current repository, or a focused ThatFactory-owned package. If reusable capability is missing, implement it natively at the appropriate boundary and consider extracting it into a first-party package when it can serve multiple consumers. + +Do not add a third-party dependency merely to save implementation time, reduce code volume, or avoid learning a platform API. Do not make an external dependency acceptable by hiding it behind a first-party wrapper. + +Unless these guidelines explicitly pre-approve the dependency for that role, an exception requires explicit approval from the repository owner for the specific dependency and use before changing the dependency graph. If approved, record the decision in durable repository documentation in the same change, such as the architecture document or an ADR. Record the dependency and source, purpose and target scope, why a native or first-party implementation is not appropriate, relevant license, security, and maintenance considerations, version or update policy when material, and the approval context. Do not infer approval from an execution plan, pull-request description, agent choice, or transient chat that merely mentions or uses the dependency. Regardless of where explicit approval occurs, reflect the exception in durable repository documentation. + +An existing approved dependency does not authorize a different dependency. Expanding an existing third-party dependency to a new target or runtime role requires the same approval and documentation. Routine version updates that do not change the approved role remain governed by the intentional consumer-update workflow in [Packages](Packages.md). + +For this policy, a third-party dependency is externally maintained source or binary code linked into or shipped with the product, including externally maintained Swift packages, vendored libraries, frameworks or XCFrameworks, CocoaPods, Carthage dependencies, and equivalent runtime libraries. Apple system frameworks and the Swift standard library are platform dependencies, not third-party dependencies. Packages maintained by ThatFactory are first-party dependencies. + +Tooling dependencies explicitly required by these shared guidelines, such as documentation or build plugins used only by tooling, are pre-approved for that documented role. They must not be linked into or shipped with product runtime targets unless the repository owner separately approves and documents that use. + +For networking, follow [Networking](Networking.md), including its narrow [standing dependency approval](Networking.md#standing-dependency-approval) and capability-gap requirements. That approval does not make every Apple-maintained package a platform dependency. + +CocoaPods and Carthage are forbidden in every ThatFactory project and are not eligible for the exception process above. Use Swift Package Manager for package dependencies. + +## Guidelines version + +Before changing a project, verify that it uses the latest released version of `agent-guidelines`. Check the project's `AgentGuidelines/VERSION` against the latest release, update the subtree or equivalent when it is behind, and read the updated applicable guides before starting implementation. This check is manual and must be performed at the beginning of each project task. + +## Guidelines changes in pull requests + +Keep `AgentGuidelines/` tracked so consumers retain a reproducible, versioned copy for agents and CI. Do not add the subtree to `.gitignore`. Instead, add this rule to the consumer's tracked `.gitattributes` so GitHub collapses synchronized guideline files in pull-request diffs by default while reviewers can still expand them: + +```gitattributes +# Synced from thatfactory/agent-guidelines; keep tracked but collapse GitHub diffs. +AgentGuidelines/** linguist-generated +``` + +Keep each subtree update in its own commit. In the pull-request description, state the old and new guideline versions and link to the central release or pull request where the guideline changes were reviewed. Continue validating the checked-in subtree in CI. Because generated-file diffs are collapsed by default, never edit the subtree locally; make shared changes in the source repository and consume a tagged release. + +## Completion audit + +For runtime UI verification, follow [Device Hub, physical devices, and simulators](Xcode/DeviceInteraction.md) together with the consumer's local environment constraints. Plan the observable outcome and cleanup before starting a session. + +Before claiming implementation is complete, handing work to the user, preparing, opening, or updating a pull request, declaring merge readiness, or preparing a release, invoke `$agent-guidelines-audit`. + +If the skill is not discoverable in a subtree consumer, read and follow its [SKILL.md](../.agents/skills/agent-guidelines-audit/SKILL.md) directly. The audit is a final verification gate, not a substitute for reading and applying the relevant guidelines during implementation. Resolve in-scope findings and rerun affected checks before handoff. Do not broaden the requested scope merely to satisfy the audit. + +For subtree consumers, the audit runs `AgentGuidelines/Scripts/validate_consumer_setup.swift` to detect drift in the root Code Review and Documentation Maintenance contracts, Codex subtree-review scope, `.gitattributes`, local guide links, and repository skill symlink. When the root `AGENTS.md` links the shared Swift-format guide, the validator also requires the shared configuration symlinks and strict non-mutating CI adoption. User-level global Codex instructions are outside this repository audit. + +## Post-merge cleanup + +After an in-scope feature pull request merges, switch the original checkout back to the repository's primary branch, update it from its upstream with a fast-forward-only pull, and delete the merged local feature branch. Confirm the remote feature branch is absent when the repository deletes merged branches automatically. Do this before declaring the feature workflow complete so stale branches do not accumulate. + +Never discard unrelated changes to perform cleanup. If the original checkout is dirty, another worktree still uses the feature branch, the merge did not complete, or the primary branch cannot fast-forward, leave the branch intact and report the exact blocker. Do not use force deletion merely to hide an unmerged branch. + +## Logging + +Applications own their orchestration, lifecycle, and product-domain diagnostics. Follow the shared [logging guide](Logging.md) and rely on each dependency to log its own implementation. Do not duplicate or reformat package-internal operations in the application log. + +Treat observability as part of implementing or changing stateful, asynchronous, fallible, or lifecycle-oriented behavior. Before handoff, trace those boundaries and verify that privacy-safe AppLogger events distinguish the outcomes needed to diagnose the behavior in context. Merely adding the dependency or linking its product is not sufficient. Keep pure value and utility code silent when it has no meaningful event boundary, and record that deliberate decision in the handoff rather than manufacturing noisy logs. diff --git a/Guidelines/Documentation.md b/Guidelines/Documentation.md new file mode 100644 index 0000000..2d8325c --- /dev/null +++ b/Guidelines/Documentation.md @@ -0,0 +1,78 @@ +# Documentation + +Documentation is part of implementation. For every codebase change, evaluate whether durable project knowledge or any existing documentation is affected; do not treat documentation as optional cleanup after code and tests are complete. + +## Conventions + +- Use PascalCase Markdown filenames without spaces. +- Keep the folder flat until one topic genuinely requires several files. +- Prefer current implementation over speculative future design; label known gaps explicitly. + +### Line wrapping + +**Write each paragraph as a single physical line — do not hard-wrap prose at a fixed column width.** A paragraph hand-wrapped at ~100 columns shows up with breaks mid-sentence, which looks broken. Let your editor **soft-wrap** instead of inserting newlines. + +The same rule applies to multi-sentence **list items** and **blockquotes** — keep each item/quote on one line. GitHub alerts are the exception: keep the alert marker on its required quoted line and keep each following body paragraph on one physical quoted line. Do not nest alerts. This concerns **prose only**: fenced code blocks and ASCII diagrams are published verbatim, so wrap those exactly as they should appear (one line per row). + +### Diagrams + +Use ASCII art inside fenced code blocks: + +``` +┌──────────┐ ┌──────────┐ ┌──────────┐ +│ View │──────>│ Store │──────>│ Service │ +└──────────┘ └──────────┘ └──────────┘ +``` + +Use box-drawing characters (`─`, `│`, `┌`, `┐`, `└`, `┘`) and arrows (`──>`, `<──`, `v`, `^`). + +#### Keep diagrams aligned + +Diagrams are published verbatim, so a diagram that is misaligned in the repo will look misaligned on MD readers/editors. Misalignment is also the most common defect in these files — it creeps in when someone edits a label without re-padding the rest of the row. + +- **Every vertical rule must sit in the same character column on every row.** Decide the column positions up front, then pad each row with spaces to hit them. In a sequence diagram, each participant's lifeline (`│`) is one such column. +- **A box's interior width must match its border width.** `┌──────────┐` (10 dashes) needs exactly 10 characters between the `│` on the rows below it. +- **Put arrowheads beside the target rule, not on top of it** — `│─────>│`, so the lifeline stays unbroken. An arrow that spans intermediate participants simply passes through their columns. +- **When a label is too long for its cell, wrap it onto a second row** rather than letting it push the rules out of alignment. +- **Count characters, not bytes.** Box-drawing glyphs are 3-byte UTF-8, so `wc -c` and `awk '{print length}'` report well above the visual width — around 2× for a typical row, up to 3× for one that is mostly box-drawing. Measure with `swift -e 'import Foundation; let value = String(data: FileHandle.standardInput.readDataToEndOfFile(), encoding: .utf8) ?? ""; print(value.split(separator: "\n", omittingEmptySubsequences: false).map(\.count).max() ?? 0)' < FILE` or an editor's column indicator. + +Check the result in a monospace view before committing: scan down each vertical rule and confirm it never jogs left or right. For a large or heavily edited diagram, it is quicker and safer to generate the block from a list of column positions in a throwaway script than to count spaces by hand. + +## Code-level documentation + +- Document every new struct, class, enum, protocol, actor, and function with focused `///` DocC comments. +- Use `// MARK: -` pragmas to separate meaningful logical sections so source files remain easy to scan and navigate. +- Update documentation when changing a documented API, parameter, behavior, or invariant. +- End documentation sentences with periods. +- Explain intent, contracts, units, side effects, isolation, and non-obvious constraints; do not restate syntax. +- Add a short Swift example when it materially clarifies correct use. +- Keep documentation close to the declaration it describes. + +## Project-level documentation + +- Keep durable architecture and cross-cutting guides in the consumer's declared documentation folder. +- Update project documentation when a change alters durable or core feature behavior, architecture, data flow, public API, persistence, navigation, localization process, testing workflow, delivery workflow, configuration, or another documented contract. +- Regardless of change size, update or remove existing documentation when the implementation makes a documented statement inaccurate, incomplete, misleading, or obsolete. +- Do not create broad documentation for incidental implementation details that are neither durable knowledge nor already documented. A small change that leaves durable knowledge and existing documentation accurate needs no project-level documentation edit. +- When renaming or removing behavior, search durable documentation for old names, examples, defaults, diagrams, setup steps, and references that may now be stale. +- Keep investigations, temporary plans, and one-time spike notes out of durable documentation unless they become lasting guidance. +- Prefer ASCII diagrams in fenced code blocks when universal rendering matters. + +## Review checklist + +When reviewing a change, ask: + +- Which existing documentation describes the changed feature, API, configuration, workflow, or invariant? +- Does the change alter durable or core feature behavior? +- Would any existing statement become inaccurate, incomplete, misleading, or obsolete even if the implementation change is small? +- Does it introduce a reusable architectural pattern? +- Does it change data flow, ownership, persistence, localization, testing, or delivery? +- Does it remove or supersede an existing guide? +- Are code comments and project guides consistent with the implementation? +- If no documentation changed, is that because no durable knowledge changed and no existing documented claim was affected? + +Treat known stale documentation as incomplete implementation. Avoid documentation churn when the change neither affects durable knowledge nor changes an existing documented claim. + +## Shared versus local guidance + +This repository owns reusable policy. Consumer documentation owns its product domain, concrete paths, package relationships, feature registries, and explicit exceptions. Link across those layers instead of copying shared prose locally. diff --git a/Guidelines/Git/IgnoreFiles.md b/Guidelines/Git/IgnoreFiles.md new file mode 100644 index 0000000..d1f7a26 --- /dev/null +++ b/Guidelines/Git/IgnoreFiles.md @@ -0,0 +1,15 @@ +# Git Ignore Files + +Use the shared [`.gitignore` template](../../Templates/.gitignore) for new Xcode projects and Swift packages. It covers generated Xcode and Swift Package Manager state plus the local output, caches, and credentials used by supported Node.js, Python, App Store, and ThatFactory development tooling. + +The template deliberately does not ignore `Package.resolved`, `.xcodeproj`, or `.xcworkspace` files. Decide whether a package lockfile belongs in source control based on the package's role, and keep authored Xcode project and workspace definitions tracked. Narrow generated files are ignored instead of ignoring containers that may hold shared configuration. + +## Consumer reconciliation + +Compare a consumer's active `.gitignore` patterns with the template without requiring comments, blank lines, section order, or duplicate rules to match. Add missing shared patterns using their template spelling, preserving the consumer's rule order and negation semantics. Before adding a pattern, check whether a later consumer rule negates it or whether it would hide a currently tracked source or configuration path; report a conflict instead of changing behavior silently. + +Treat every active consumer pattern that is not in the template as a project-specific entry. Do not remove it or silently accept it. Report it to the repository owner so they can choose whether the reusable template should gain the pattern or the consumer should retain it as a local exception. + +When the repository owner chooses a local exception, document the rationale immediately above the entry in the consumer `.gitignore` using `# Project-specific: `. A concrete non-placeholder rationale marks that entry as reviewed, so later completion audits may accept it without reporting it again. Keep exception comments and their patterns adjacent; each independently motivated group needs its own rationale. + +Do not copy ignored caches or generated artifacts into the repository merely to make the comparison pass. Existing tracked files remain tracked even when a matching ignore rule is added, so inspect `git ls-files` and `git check-ignore -v` when a rule's effect is uncertain. diff --git a/AgentGuidelines/Guidelines/Git/Repositories.md b/Guidelines/Git/Repositories.md similarity index 100% rename from AgentGuidelines/Guidelines/Git/Repositories.md rename to Guidelines/Git/Repositories.md diff --git a/Guidelines/GitHub/PullRequests.md b/Guidelines/GitHub/PullRequests.md new file mode 100644 index 0000000..60f4309 --- /dev/null +++ b/Guidelines/GitHub/PullRequests.md @@ -0,0 +1,86 @@ +# GitHub Pull Requests + +Use this guide whenever creating, reviewing, updating, or merging a GitHub pull request. The self-contained root contracts come from [the canonical review policy](../../ReviewPolicy/Policy.md); [review-policy integration](../../ReviewPolicy/README.md) describes both adoption profiles and freshness checks. + +## Before opening + +- Review the complete diff, keep one coherent review unit, and exclude unrelated changes. State supported use cases, acceptance criteria, threat-model boundaries, validation, and limitations in the PR description. +- Run relevant local validation and follow the repository's contribution instructions. Open a ready-for-review PR at a stable head without auto-merge. Drafts are appropriate for incomplete preparation, data approval, and source promotion; mark ready before waiting for automatic Codex review. +- Configure automatic review for all PR authors on opening a ready PR or marking ready, disable exhaustive review, and keep separate Security Review manual. Record actual repository configuration separately from the generic template; this template does not establish that automatic review is configured. +- One automatic full review is the initial review. Do not post a duplicate manual request, toggle draft/ready to force another round, or casually mention the bot. A mention can start extra cloud work. Manual review and Security Review require explicit owner instruction. + +## Consumer subtree review scope + +After exact tagged-tree provenance has been verified, do not substantively review `AgentGuidelines/**` in a consumer PR. Verify `AgentGuidelines/VERSION`, compare `git rev-parse HEAD:AgentGuidelines` with the matching central tag's root tree, and verify `.gitattributes` contains `AgentGuidelines/** linguist-generated`. A tree-object comparison avoids reconstructing subtree history. If provenance differs, review the discrepancy and stop merge. Substantive shared-policy feedback belongs in the central PR. Review-only consumers have no subtree to exclude. + +## Review objective + +Report only substantiated P0/P1 regressions introduced or materially exposed by the change. P0 is a critical security failure, catastrophic durable data loss, or critical outage. P1 requires serious, concrete impact in a supported workflow or documented threat boundary. An acceptance-criterion violation alone does not establish P1. Omit unsolicited P2/P3 hardening, style, optional tests, speculative refactoring, and theoretical completeness. Group one root cause into one finding and report blockers together. + +## Review evidence and gate + +Track configuration and execution separately in the active task, without adding runtime journals to the repository: + +```text +codex_review_configuration = enabled | disabled | unknown +codex_review_configuration_evidence = | unset +codex_review_execution = not_started | scheduled | processing | completed +codex_review_expected_sha = +codex_review_completed_sha = | unset +codex_initial_reviewed_base = | unset +codex_remediation_verified_sha = | unset +``` + +Only positive repository-specific evidence establishes configuration: an observed setting, a durable local declaration, or explicit owner confirmation for this repository. Generic templates, another repository, old PR behavior, and an automation prompt are insufficient. With no signal, `unknown` plus no signal remains `not_started`. Discovering `enabled` alone does not schedule a review; the PR must meet its configured trigger. A declared required review with a conflicting disabled setting is a configuration problem to resolve, not a waived gate. + +Verify bot identity, repository, PR, review round, and commit. Inspect PR-body reactions for automatic reviews and the exact request-comment reactions for authorized manual reviews, plus review submissions, inline threads, checks, and failure comments. Eyes is processing, not approval. A thumbs-up means no suggestions only when tied to the verified round and stable head; a historical reaction never certifies a newer head. A review with a commit ID must match the expected round SHA. Neither absent comments nor elapsed time establishes completion. + +| Evidence | Execution | Merge gate | Start monitor | +| --- | --- | --- | --- | +| Enabled and positively eligible, no start signal | `scheduled` | Pending | Yes, at most five minutes | +| Enabled with a current-head processing signal | `processing` | Pending | Continue within original deadline | +| Enabled with a completed review covering the expected head and dispositioned findings | `completed` | Satisfied | No | +| Unknown with no signal or configuration evidence | `not_started` | Not blocked by absent Codex review | No | +| Disabled with no review | `not_started` | Not blocked by absent Codex review | No | +| Review completed for an old head | Re-establish for new head | Historical reaction alone is insufficient | No inherited monitor | +| Completed initial review plus a locally verified remediation-only delta | `completed` | Satisfied after all blockers and checks are cleared | No new review | + +For the disabled outcome, the repository must not independently require Codex review. None of these outcomes grants merge authority or replaces required checks or human approval. + +### Remediation and convergence + +1. Record the initial reviewed base/head and inspect every review summary and inline thread. Classify each thread as `BLOCKER-P0`, `BLOCKER-P1`, `DEFER-P2`, `DEFER-P3`, `DECLINE`, or `DUPLICATE`. +2. Batch accepted P0/P1 fixes and add meaningful regression coverage where appropriate. Record useful unsolicited lower-priority feedback once; it does not keep the review loop open. +3. Reply in the original thread with its disposition and the change or technical rationale. Resolve only after recording the disposition. Write commit hashes as raw text, for example 185c04f, so GitHub links them. +4. Rerun affected validation, inspect the complete delta from the actual reviewed head, and record the final verified SHA and why the delta only remediates known findings. The completed initial review remains evidence for its original head; never relabel the newer head as bot-reviewed. +5. A completed initial review plus a locally verified remediation-only delta satisfies the agent-review step when no unresolved P0/P1 blocker remains. New unrelated functionality belongs in another PR. A material base/integration change requires renewed assessment and an owner-authorized targeted review when the original review no longer covers the risk. +6. Update PR metadata and immediately before merge rerun the latest review-policy check, inspect late findings and current-head checks, and verify existing merge authority. A thumbs-up is not a formal GitHub approving review. + +Never request another review after each fix. The owner may explicitly authorize at most one delta-scoped verification after batching remediation. Before requesting it, confirm no review is pending, no request targets that head already, the head differs from the last reviewed SHA, and the verification budget is unused. Record the requested SHA and round before waiting. Scope the request to unresolved P0/P1 findings, changes since the actual reviewed SHA, and directly affected code. A new verification finding must be a P0/P1 defect introduced by remediation or genuinely hidden by the prior blocker. A third review requires separate explicit owner authorization and a named unresolved P0/P1 concern. + +### Bounded monitoring + +Monitor at most five minutes total from entry into `scheduled`, including time spent in `processing`. If processing is first observed without a known scheduling time, start the single bounded observation window then. Take an initial snapshot and at most one each around 30, 90, 180, and 300 seconds. A processing signal changes the execution state but does not reset the deadline or poll budget. A completion signal ends monitoring. + +Keep the expected SHA, request identity, start, deadline, poll count, and a fingerprint covering base/head, signals, review commit, threads, checks, and mergeability. An identical fingerprint causes no substantive re-analysis or user notification. Without configuration evidence, do not create a monitor for an absent review. If the head changes during monitoring, terminate the old monitor; do not transfer `scheduled`, `processing`, or `completed` to a new round or infer that a push triggers another review. + +At the deadline, stop and terminate the monitor, report the observed facts once, and never infer approval. An unresolved required round remains a merge blocker. Do not submit another request, create a recurring automation, or start fresh observation windows to evade the budget. Continue independent work or report the unresolved gate. + +Use all relevant GitHub surfaces with complete pagination: + +```sh +gh api --paginate repos///issues//reactions +gh api --paginate repos///issues/comments//reactions +gh pr view --repo / --json reviews,headRefOid,baseRefOid +gh pr checks --repo / +``` + +Use GraphQL `reviewThreads` with `isResolved` and paginated comment histories. Top-level PR comments omit inline thread state. Missing pages, unresolved threads, a processing reaction, and a timeout are never approval. + +## Merge and late findings + +Opening a PR does not authorize merging it. Squash merge only after current-head required checks, resolved/dispositioned threads, required review completion or verified remediation closure, and existing owner/human authorization are satisfied. Do not enable auto-merge while a gate remains pending. Prefer rulesets requiring PRs, conversation resolution, mandatory checks, and an intentional emergency bypass path. Require an up-to-date branch where repository policy calls for it. + +GitHub does not count author self-approval. In a solo repository, do not impose an impossible one-approval gate; preserve explicit owner authorization and enforce the available technical gates. Review-policy validation is a required hosting check, not a substitute for code review. + +Assess late findings individually. A valid late P0/P1 finding requires prompt corrective work and indicates a missed gate. A late P2/P3 observation can become backlog work and is not itself a process failure. diff --git a/Guidelines/Localization.md b/Guidelines/Localization.md new file mode 100644 index 0000000..4cb53f1 --- /dev/null +++ b/Guidelines/Localization.md @@ -0,0 +1,94 @@ +# Localization + +Follow Apple's [Localizing your app using agents](https://developer.apple.com/documentation/xcode/localizing-your-app-using-agents) workflow and current Xcode localization tools. Consumer repositories declare their supported languages, catalog and source locations, product voice, terminology, and narrow exceptions locally. + +Storefront metadata uses separate App Store locale identifiers and files. Follow [App Store metadata](AppStore.md) for the repository structure and App Store Connect synchronization workflow; apply the consumer's local voice and product terminology to both application and storefront copy. + +## Source artifacts + +- Use the consumer's existing String Catalogs (`.xcstrings`) as the source of truth. +- Do not create a parallel catalog or migrate an existing `.strings` setup unless the task includes that migration. +- An app target uses its main bundle by default. Swift packages and frameworks must resolve localized resources from their own bundle, using the current Apple-recommended bundle API. +- Keep one source of truth for translator context: either the source comment or the catalog comment. + +## Generated symbols + +- Define user-facing text in the appropriate String Catalog first and use Xcode-generated `LocalizedStringResource` symbols from Swift. Enable Generate String Catalog Symbols when an older project does not already generate them. +- Give a string a semantic catalog key when deriving a readable symbol from its source value would be ambiguous. Name formatted variables in the source value so Xcode generates labeled parameters. +- Use generated properties and functions directly in SwiftUI, and resolve them with `String(localized:)` or `AttributedString(localized:)` only where that concrete value is required. +- Generated Swift is build output. Inspect it through Xcode or `xcstringstool` when useful, but never edit or check it in. +- Do not add new localizable Swift literals after a project adopts generated symbols. Use `Text(verbatim:)` only for nonlinguistic punctuation, identifiers, and other intentionally unlocalized content. + +## User-facing values + +- Let SwiftUI's localized string initializers preserve localization context. +- Use `LocalizedStringResource` when a model, view state, notification, or other non-view value carries user-facing text that should resolve later. +- Use `String(localized:)` when a resolved localized `String` is genuinely required outside SwiftUI. +- Use `Text(verbatim:)` for intentional non-localized literals such as debug identifiers. +- Do not pass a runtime `String` to a localized initializer and expect Xcode to extract it as a catalog key. + +## Sentences and formatting + +- Interpolate values into one localizable sentence rather than concatenating translated fragments. +- Add translator comments for ambiguous language and describe interpolated placeholders by position and meaning. +- Use locale-aware `FormatStyle` APIs for dates, numbers, lists, measurements, and currencies. +- Avoid runtime case transformations for localized interface text; allow translations to choose appropriate casing. +- Keep placeholder positions, semantic names, and conversion types identical across source and translated variants. +- Add language-specific plural variants for counts instead of branching between singular and plural text in Swift. +- Preserve the distinction between unavailable data and numeric zero. + +## Layout + +- Use leading and trailing instead of left and right for directional layout. +- Avoid fixed text frames that cannot accommodate translation length or script height. +- Prefer semantic text styles to fixed point sizes. +- Use the SwiftUI environment locale for view behavior that must respond to preview or subtree locale overrides. + +## Agent workflow + +1. Inspect the consumer's local localization instructions and catalogs. +2. Ask Xcode's current documentation or localization capability for the supported workflow. +3. Add the key, source-language value, and translator comment directly to the catalog. Mark an explicitly maintained generated-symbol entry as manual and use named placeholders for formatted values. +4. Inspect the generated API through Xcode's catalog inspector or, when needed, `xcrun xcstringstool generate-symbols`. Use the generated property or function from Swift. +5. For a legacy catalog whose keys were extracted from Swift literals, run the shared preparation script once. It preserves comments, variants, and translations, leaves stale entries for an explicit decision, and refuses to invent a missing source value for an already-manual semantic key. Use `--check` for a nonmutating readiness check. +6. Use Xcode's localization coordinator and String Catalog tools to add or update only the languages in scope. Do not replace contextual translation decisions with ad hoc JSON-rewriting scripts. +7. Resolve every stale extracted entry and every active translated value marked `new` or `needs_review`. Keep agent output machine-translated until a fluent reviewer approves it. +8. Run the shared catalog validator after every catalog or localization-source change. It checks generated-symbol readiness, stale entries, required languages, translation states, format signatures, and Swift literals that bypass generated symbols. +9. Open each changed catalog in Xcode and require zero catalog-editor errors or warnings; these diagnostics do not necessarily become compiler warnings. Record the inspected catalog paths, selected Xcode version and build, and explicit zero-error and zero-warning result. Automated catalog validation, a warning-clean build, or an unrecorded visual check does not satisfy this editor-evidence gate. +10. Build and test source and translated languages. Exercise long strings, every plural branch, and right-to-left layout even when no right-to-left locale ships. +11. Have a fluent reviewer inspect machine translations before recording them as reviewed. + +## Shared scripts + +Supply project-specific paths and supported languages at the consumer boundary: + +```sh +AgentGuidelines/Scripts/prepare_localizable_symbols.swift \ + \ + --check + +AgentGuidelines/Scripts/validate_string_catalogs.swift \ + --catalog-directory \ + --source-directory \ + --required-language +``` + +Repeat directory, catalog, or language options when the project has several. A consumer may keep a small repository-owned wrapper so existing developer and CI commands supply its paths and languages consistently; the wrapper must delegate to the synchronized shared script rather than copy its validation or migration logic. + +The completion audit discovers changed String Catalogs relative to an explicit Git base and fails closed until every catalog has a recorded Xcode editor inspection. After opening each changed catalog and confirming zero editor errors and warnings, run the audit helper from the consumer root and keep its JSON outside the repository: + +```sh +AgentGuidelines/.agents/skills/agent-guidelines-audit/scripts/check_xcstrings_inspection.swift \ + --base-ref \ + --inspected-catalog \ + --evidence-output +``` + +Repeat `--inspected-catalog` for every changed catalog. The helper records the selected Xcode version and build together with the zero-diagnostic result. Summarize that record in the completion handoff and pull-request description; do not commit the temporary JSON evidence. + +Do not invent translations from an unrelated project's conventions. Product vocabulary and tone remain consumer-specific. + +## References + +- [Using generated localizable symbols in your code](https://developer.apple.com/documentation/xcode/using-generated-localizable-symbols-in-your-code) +- [Localizing your app using agents](https://developer.apple.com/documentation/xcode/localizing-your-app-using-agents) diff --git a/AgentGuidelines/Guidelines/Logging.md b/Guidelines/Logging.md similarity index 86% rename from AgentGuidelines/Guidelines/Logging.md rename to Guidelines/Logging.md index 498c356..4cf3bb3 100644 --- a/AgentGuidelines/Guidelines/Logging.md +++ b/Guidelines/Logging.md @@ -8,6 +8,7 @@ Use this guide for Apple-platform applications and Swift packages that emit runt - A consuming application logs its own orchestration and lifecycle events. It must not reproduce or reformat a dependency's internal steps or outcomes. - A reusable package describes events using its own domain language. Do not introduce concepts from one current client into package categories or messages. - Ownership does not require every API or package to emit logs. Pure utilities and operations without a meaningful diagnostic event may emit nothing. +- New or changed stateful, asynchronous, fallible, or lifecycle-oriented behavior must identify its meaningful diagnostic boundaries during implementation. Emit a privacy-safe outcome for success and each operationally distinct failure, cancellation, recovery, or state transition that a developer needs to distinguish. If an artifact is limited to pure values or utilities and has no such boundary, keep it silent and state that decision in the implementation handoff instead of adding initializer or property-access noise. - Logging is a side effect. It must not affect returned values, state transitions, error handling, or control flow. - Architectures that isolate side effects must call a logging package from an allowed side-effect boundary, such as middleware or a service, rather than from a pure reducer. @@ -56,6 +57,7 @@ Use this guide for Apple-platform applications and Swift packages that emit runt - Verify that every package message starts with its canonical emoji. - Verify the stable category, meaningful fields, privacy choice, log level, and single-emission behavior for each logged operation. - Do not make tests depend on querying the operating system's persisted log store. +- For every changed lifecycle covered by the observability requirement, test the event formatter or sink for its successful and operationally distinct unsuccessful outcomes. Dependency declaration and target linkage alone do not establish logging coverage. ## Filtering diff --git a/Guidelines/Networking.md b/Guidelines/Networking.md new file mode 100644 index 0000000..ca965f7 --- /dev/null +++ b/Guidelines/Networking.md @@ -0,0 +1,65 @@ +# Networking + +Use this guide for networking in ThatFactory Apple-platform applications, games, and Swift packages. These are repository requirements; official Apple documentation defines API behavior and availability. + +## Apple networking APIs + +- Use Apple's native networking APIs. Use Foundation's `URLSession` for HTTP and HTTPS transport, including data, upload, download, and streaming tasks. +- Use the appropriate Apple framework for other networking needs, such as Network for supported lower-level protocols or `URLSessionWebSocketTask` for WebSockets. Verify support on every deployment target; do not build an HTTP transport on sockets when `URLSession` covers the requirement. +- Preserve framework-owned networking, such as CloudKit or WebKit operations. Do not replace those APIs merely to expose their internal HTTP traffic. +- Do not add a third-party networking client, transport, wrapper, or protocol stack when Apple covers the required capability. A first-party wrapper must not conceal such a dependency. Follow the [capability-gap exception](#capability-gap-exceptions) before introducing an alternative. + +## Typed HTTP with native transport + +For HTTP requests and responses owned by the application or package, add Apple's `swift-http-types` package through Swift Package Manager and use its `HTTPTypes` and `HTTPTypesFoundation` products with native `URLSession` transport. `HTTPTypes` supplies HTTP values; `HTTPTypesFoundation` supplies Foundation conversion and `URLSession` conveniences. Neither product replaces the transport. + +Use the following types throughout the owned HTTP boundary: + +| HTTP concept | Required representation | +| --- | --- | +| Request | `HTTPRequest` | +| Response | `HTTPResponse` | +| Method | `HTTPRequest.Method`, such as `.get` or `.post` | +| Header fields and names | `HTTPFields` and `HTTPField.Name` | +| Response status | `HTTPResponse.Status`, including named values or status kinds as appropriate | + +Do not maintain parallel string-based method/header models or integer status enums where these types apply. Custom protocol methods, header names, and statuses still use the extensible HTTP types; header values and encoded bodies remain protocol data. Validate response status before treating a completed transfer as application success. + +Declare both products in the package or Xcode dependency graph and link them to the targets that use them. A pure HTTP-model target may depend only on `HTTPTypes`; the Foundation transport target also needs `HTTPTypesFoundation`. An import, unused dependency, or dependency declaration without actual typed request and response handling does not satisfy this policy. + +Use the typed `URLSession` overloads where they support the operation. When a native API requires `URLRequest` or `HTTPURLResponse`, such as a delegate, background-task, or Foundation-only request-configuration boundary, use `HTTPTypesFoundation` conversion there and retain typed HTTP in the code that owns request construction and response handling. Document the native API reason, handle failed conversions, and preserve bodies and required transport configuration. A Foundation bridge needs no third-party exception and is not permission to retain an untyped HTTP implementation throughout the service. + +The [1.8.0 release](https://github.com/apple/swift-http-types/tree/1.8.0) is the minimum baseline for this policy, for example `.package(url: "https://github.com/apple/swift-http-types.git", from: "1.8.0")`. Its manifest requires Swift tools 6.1. Select a compatible released version, verify its Swift and deployment requirements, and record the version requirement and resolution according to the [package update workflow](Packages.md). Do not silently lower consumer platform support or substitute another library to resolve an incompatibility. + +### Standing dependency approval + +Apple's `swift-http-types` products `HTTPTypes` and `HTTPTypesFoundation` are pre-approved for the typed HTTP and Foundation integration role above. Consumers do not need a separate owner exception for that role. Record the dependency, source, target linkage, and version policy in normal package or architecture documentation. This approval does not extend to other Apple open-source packages, third-party networking libraries, or unrelated runtime roles; the general [external dependency policy](Development.md#external-dependencies) still applies. + +Do not add these products to a target that has no owned HTTP behavior merely because it uses a network-backed Apple framework or a first-party service. Non-HTTP networking and framework-owned traffic follow the native-API rule without requiring artificial HTTP wrappers. These exclusions do not exempt external SDKs or a first-party service's own networking implementation from dependency and networking policy. + +## Ownership and validation + +Keep transport-specific details behind the service or package boundary that owns networking. Use an injectable boundary for deterministic tests. Follow [Redux service ownership](Architecture/Redux.md#services) where applicable and the shared [testing guide](Testing/UnitTesting.md) for test structure. + +- Verify typed request construction, headers and body encoding, expected success and failure statuses, transport errors, and cancellation for the changed behavior. Test conversion failures when a Foundation bridge is involved. +- Use controlled responses or local fixtures for ordinary tests; do not make normal CI depend on an external service. Run a live integration check only when needed to verify behavior fixtures cannot establish, and report its limits. +- Preserve native transport security and authentication behavior. For security-sensitive changes, follow [Xcode security audits](Xcode/Security.md) and record affected network configuration and relevant runtime evidence. +- Follow [Logging](Logging.md) for privacy-safe diagnostics owned by the networking implementation; do not expose credentials, headers containing secrets, or user content. + +## Capability-gap exceptions + +An alternative networking dependency is eligible only when a required capability is unavailable through Apple's APIs on the supported platforms. Convenience, familiarity, popularity, and reduced code volume are not capability gaps. Check current official Apple documentation and demonstrate the missing behavior before proposing an exception; do not assume Apple covers every possible protocol or deployment constraint. + +Before changing the dependency graph, obtain explicit repository-owner approval for the specific alternative and role under the [external dependency policy](Development.md#external-dependencies). Keep a durable consumer exception identifying the requirement, Apple APIs evaluated and their concrete limitation, affected platforms and targets, dependency/source, license/security/maintenance impact, version policy, validation, approval context, and condition for revisiting the exception. An undocumented or unapproved alternative prevents audit completion. + +## Adoption and audit + +New or changed networking must follow this guide, including directly affected existing request paths. On adoption of this networking policy, inventory existing networking and either migrate noncompliant paths within authorized scope or record an explicit owner-approved, scoped migration deferral with rationale, affected paths, and a follow-up condition. Existing code alone is not an exception; do not silently rewrite unrelated consumers or claim full compliance while a deferral remains. + +Use the [networking completion audit](../.agents/skills/agent-guidelines-audit/SKILL.md#audit-networking) to record applicability, dependency and implementation evidence, native bridges, exceptions or migration deferrals, and validation results. + +## Official references + +- [URLSession](https://developer.apple.com/documentation/foundation/urlsession). +- [Network](https://developer.apple.com/documentation/network). +- [Swift HTTP Types and Foundation integration](https://github.com/apple/swift-http-types/tree/1.8.0). diff --git a/Guidelines/Packages.md b/Guidelines/Packages.md new file mode 100644 index 0000000..5580a07 --- /dev/null +++ b/Guidelines/Packages.md @@ -0,0 +1,174 @@ +# Swift Packages + +## README badges + +Start a new ThatFactory project or package README with a centered HTML badge block: + +```html +

+ +

+``` + +For example, a repository using the baseline and relevant optional badge configurations could use: + +```html +

+ Swift Version + Xcode Version + Platforms + Platforms + SPM + NPM + Xcode MCP + Codex MCP + Claude MCP + DocC + License + CI + Publish + Nightly +

+``` + +Use only badges that describe the repository, in this order: + +1. Swift version. +2. Xcode version. +3. Supported platforms. +4. Relevant package manager, runtime, or ecosystem badges, such as SPM or NPM. +5. Relevant agent or tooling badges, such as Xcode MCP, Codex, or Claude. +6. DocC, documentation. +7. License. +8. CI badges. +9. Release/publishing workflow status when applicable. + +The common package baseline is Swift, Xcode, Platforms, License, and CI, plus a Release/publishing workflow-status badge when the package has that workflow. Add optional badges only when they convey useful repository-specific information. Keep the order stable even when some positions are omitted. + +Swift package READMEs omit Updated/last-commit-date and Revision/latest-release-version badges by default. Add or retain one only when the repository's `AGENTS.md` or linked durable documentation records the specific badge, its source, and the reader need that justifies the exception. A publishing workflow's success/failure badge remains part of the normal convention; it reports operational status rather than a revision or release version. An approved date/version badge belongs after License and before CI, uses a dynamic source, and must not require manual version/date edits. + +- Point CI, publishing, and documentation badges at workflows in the current repository; never copy another repository's badge URL unchanged. +- Use descriptive `alt` text. Preserve a repository's established Xcode badge convention when the label intentionally records the last verified Xcode version. +- Do not advertise a platform, integration, package manager, or agent that the repository does not support. +- Keep the repository's license in a root `LICENSE` file when reuse or redistribution is permitted. +- Retain the README license badge when the standard badge set applies, but do not add a dedicated License heading or license-description section to a package README. GitHub already presents the repository license beside the README, and the badge provides the summary without duplicating license prose. +- Do not add a license to an existing repository without the owner's explicit choice of terms. + +## Package boundaries + +- Keep a reusable package focused on one coherent capability. +- Prefer UI-agnostic domain APIs unless UI is the package's explicit purpose. +- Do not add application Redux, navigation, persistence, or product policy to a generic package. +- A first-party package must not introduce or conceal a third-party runtime dependency outside an explicitly approved role. Follow the [external dependency policy](Development.md#external-dependencies) before changing the dependency graph and [Networking](Networking.md) for network implementation and its standing approval. +- Keep public APIs minimal and stable. Prefer composing focused types over introducing umbrella abstractions before multiple consumers need them. +- Declare platform and Swift toolchain requirements explicitly in `Package.swift`. +- New Swift packages must start on the latest supported Swift language and toolchain version. Before adding a major package capability to an older package, plan and complete the required Swift/toolchain modernization first. +- Put sources under `Sources//` and tests under `Tests/Tests/`. +- Keep resources in the target that owns them and use the package bundle for lookup. + +## Compiler settings baseline + +Host Xcode build settings are not a substitute for package configuration. Each package must express its applicable compiler policy in `Package.swift` so independently invoked SwiftPM builds, Xcode builds, and dependency builds receive the same strictness. This baseline is the SwiftPM representation of the applicable compiler policy in [Xcode project settings](Xcode/ProjectSettings.md), not a mechanical copy of Xcode build-setting names. + +New packages must use the newest supported Swift tools version. Every package must use the newest stable Swift language mode supported by the selected toolchain, currently Swift 6, preferably owned once at package level: + +```swift +swiftLanguageModes: [.v6] +``` + +Do not repeat `.swiftLanguageMode(.v6)` target by target when package-level ownership is sufficient. A target may specialize the language mode only under a documented package exception. An older manifest that cannot express this baseline must first modernize its tools version; `.treatAllWarnings(as:)` requires PackageDescription 6.2 or later. + +Every locally defined target that compiles Swift and for which SwiftPM exposes `swiftSettings`, including test targets and other applicable Swift target kinds, must unconditionally use the typed PackageDescription API: + +```swift +swiftSettings: [ + .treatAllWarnings(as: .error), + .enableUpcomingFeature("ExistentialAny"), + .enableUpcomingFeature("InferIsolatedConformances"), + .enableUpcomingFeature("InternalImportsByDefault"), + .enableUpcomingFeature("MemberImportVisibility"), + .enableUpcomingFeature("NonisolatedNonsendingByDefault"), +] +``` + +A setting restricted only to Debug, Release, a platform, or another build condition does not satisfy this package-wide baseline unless a documented exception covers that scope. Do not use `unsafeFlags` for warning handling when the typed API is available. + +When a locally compiled target contains C or Objective-C, require `cSettings: [.treatAllWarnings(as: .error)]`. Where C++ settings apply, require `cxxSettings: [.treatAllWarnings(as: .error)]`. Pure-Swift packages do not need C or C++ settings, and packages must not introduce `-Werror` through `unsafeFlags` when the typed APIs are available. + +Swift 6 language mode enables complete concurrency checking unconditionally, so a Swift 6 package must not retain any explicit `StrictConcurrency` opt-in. Remove `.enableUpcomingFeature("StrictConcurrency")`, `.enableExperimentalFeature("StrictConcurrency")`, and `StrictConcurrency=complete` spellings instead of treating one representation as special. For an older package, modernize to the required language mode instead of preserving the legacy mode with a compatibility flag. + +Do not invent a direct SwiftPM equivalent for `SWIFT_APPROACHABLE_CONCURRENCY`. Its applicable opt-in language behavior is represented by the individual upcoming features above, including `InferIsolatedConformances` and `NonisolatedNonsendingByDefault`. + +`.defaultIsolation(MainActor.self)` is intentionally not part of this shared package baseline. Reusable packages must express actor isolation according to their public and internal API semantics rather than inherit an application's default isolation policy. A package may choose a default isolation as an intentional package-specific architectural decision, but the completion audit must not add or require it merely for Xcode-project parity. + +Require the listed upcoming features on every applicable locally defined Swift target, but not on binary or system-library targets that SwiftPM does not compile as Swift source or package plug-in targets for which `Target.plugin(...)` does not expose `swiftSettings`. Reevaluate the list whenever the selected Xcode/Swift toolchain or language mode changes. When a feature becomes unconditional in the selected language mode, remove its `.enableUpcomingFeature(...)` declaration from packages, remove it from this baseline, and update the audit contract in the same change. Retain no redundant upcoming features merely for historical consistency because they can produce diagnostics under warnings-as-errors. + +Metal warnings-as-errors and application `Info.plist` export-compliance declarations have no package equivalent in this baseline. SwiftPM has no first-class Metal warning setting, and a reusable package does not own its consuming application's generated `Info.plist`. + +Accept a deviation only when the nearest applicable `AGENTS.md`, or durable documentation linked from it, records the exact package compiler setting or feature, affected package and targets, concrete incompatibility, replacement or omission, engineering impact, compensating validation where applicable, and condition for revisiting or removing the exception. Do not infer an exception from the existing `Package.swift`. + +## Logging + +Packages own any diagnostics emitted by their implementation. Follow the shared [logging guide](Logging.md) for AppLogger usage, subsystem identity, package emoji prefixes, domain-owned categories, concise messages, privacy, and test coverage. A consuming application must not reproduce package-internal logs. + +Before assigning or changing a package's canonical emoji, inspect the package list on the current `main` branch of the [ThatFactory Swift Package Collection](https://github.com/thatfactory/swift-package-collection) and confirm that no other package uses it. Each package emoji must be unique across ThatFactory so a log prefix identifies one package unambiguously. Treat visually identical emoji spellings that differ only by presentation selectors as the same emoji; do not use an encoding variation to create an apparent distinction. + +Declare the selected emoji in the package's local instructions or documentation, use that exact emoji in its package-local logging gateway, and add or update the matching Swift Package Collection entry as part of the package's publication work. An existing collision, a missing registry entry for a published package, or disagreement among the registry, documentation, and emitted prefix blocks release readiness until reconciled. + +## Development workflow + +1. Read the package's local `AGENTS.md`, README, DocC, and public API before changing behavior. +2. Add or update tests in the package itself. +3. Update DocC and README examples when public behavior changes. +4. Run the focused tests, then `swift test` or the package's declared Xcode test workflow. +5. Integrate the package into a consumer locally only when consumer behavior must also be verified. +6. Avoid committing consumer-specific workarounds into the package when the behavior belongs in the consumer. + +## DocC documentation + +DocC is the default documentation format for public Swift packages. Document public APIs with `///` DocC comments and keep package-level conceptual material in a DocC catalog when it needs more than declaration comments. + +Before adopting the DocC command, an existing package must be updated to the latest supported Swift toolchain and declare the Swift-DocC plugin dependency in `Package.swift` (for example, `.package(url: "https://github.com/swiftlang/swift-docc-plugin", from: "")`). New packages must declare this prerequisite from the beginning when they publish DocC. + +The Swift-DocC plugin is a guideline-mandated tooling dependency under the [external dependency policy](Development.md#external-dependencies). Keep it tooling-only; do not link it into library or product runtime targets. + +Packages that publish documentation must build and deploy their DocC site as part of the release workflow: + +1. Run tests before documentation generation. +2. Generate static-hosting documentation with `swift package generate-documentation --target --disable-indexing --output-path ./public --transform-for-static-hosting --hosting-base-path `. +3. Add a root redirect to `//documentation//`. +4. Upload `./public` with `actions/upload-pages-artifact` and deploy it with `actions/deploy-pages`. +5. Grant the workflow `pages: write` and `id-token: write` permissions and expose the deployed URL in the README through a DocC badge. + +The release job must publish documentation only after the release has been approved, merged, tagged, and published. Verify the generated site locally when practical and keep the README badge URL aligned with the repository's GitHub Pages site. + +## Local integration + +- Use Xcode's local-package workflow or an explicit temporary local dependency while developing package and consumer changes together. +- Do not commit machine-specific absolute package paths. +- Before release, restore the consumer to the tagged remote dependency unless its local instructions intentionally retain a monorepo relationship. +- Verify the final remote version resolves on a clean checkout. + +## Releases + +Never release a package directly from unreviewed changes. Every release change must first be submitted through a pull request, reviewed, and approved. This rule applies to `agent-guidelines` itself as well as every consumer package. Create and publish the release only after the PR has merged. + +For ThatFactory packages, “release a new version” means: + +1. Choose a semantic version appropriate to compatibility. +2. Update public documentation and release notes. +3. Run the declared CI/test workflow. +4. Open a pull request containing the release state and wait for approval. +5. Merge the approved pull request. +6. Create and push the matching Git tag. +7. Create a GitHub release for that tag. +8. Use real multiline release notes and backticks around technical names and versions. + +When using a CLI, pass multiline notes through a file so GitHub renders line breaks correctly. + +## Consumer updates + +- Review package release notes and API changes before updating. +- Update one dependency relationship intentionally; do not rewrite unrelated resolved versions. +- Build and test the affected consumer behavior. +- Update the consumer's package integration documentation when roles, mappings, or workflows change. diff --git a/AgentGuidelines/Guidelines/Swift/Swift.md b/Guidelines/Swift/Swift.md similarity index 94% rename from AgentGuidelines/Guidelines/Swift/Swift.md rename to Guidelines/Swift/Swift.md index 6ae523d..17a29f1 100644 --- a/AgentGuidelines/Guidelines/Swift/Swift.md +++ b/Guidelines/Swift/Swift.md @@ -7,6 +7,7 @@ - Use current `swift-collections` documentation when working with its collection types. - Import the module that owns an API. For example, APIs specific to `OrderedCollections` require `import OrderedCollections`. - Maintain a zero-warning policy for warnings introduced by the change. +- For Xcode projects, apply the shared [project-settings baseline](../Xcode/ProjectSettings.md) at project level so every application and test target inherits it. ## Implementation diff --git a/AgentGuidelines/Guidelines/Swift/SwiftFormat.md b/Guidelines/Swift/SwiftFormat.md similarity index 100% rename from AgentGuidelines/Guidelines/Swift/SwiftFormat.md rename to Guidelines/Swift/SwiftFormat.md diff --git a/AgentGuidelines/Guidelines/Swift/SwiftStyle.md b/Guidelines/Swift/SwiftStyle.md similarity index 100% rename from AgentGuidelines/Guidelines/Swift/SwiftStyle.md rename to Guidelines/Swift/SwiftStyle.md diff --git a/Guidelines/Swift/SwiftUI.md b/Guidelines/Swift/SwiftUI.md new file mode 100644 index 0000000..1c01cbf --- /dev/null +++ b/Guidelines/Swift/SwiftUI.md @@ -0,0 +1,150 @@ +# SwiftUI + +Use official Apple documentation and Xcode's current SwiftUI skills for API-specific behavior. This guide captures stable project policy rather than reproducing the current SDK's API catalog. + +## View structure + +- Put SwiftUI dynamic properties such as `@Environment`, `@Query`, `@State`, and `@Binding` before ordinary stored `let` and `var` properties. Keep injected environment dependencies before locally owned state when both are present. +- Keep a parent view focused on composition. +- Model meaningful sections such as headers, lists, metadata, sidebars, and footers as separate `View` types with narrow inputs. +- Keep each independently meaningful `View` in its own file, including private supporting views. Give every view its own deterministic preview when the required dependencies can be represented safely; when they cannot, document the concrete limitation in the handoff. +- Do not extract sections into computed `some View` properties merely to shorten `body`; computed properties remain in the parent's invalidation boundary. +- Tiny fragments reused within one body may use a small helper when they have no independent state, input, or invalidation story. +- Keep view initializers cheap. Do not decode data, access files, build large structures, or allocate formatters in `init`. +- Avoid a single-child `Group` that adds no structure or behavior. + +## Data flow + +- Pass a view only the value-type fields it reads or forwards. +- Use private `@State` for state genuinely owned by the view. +- Use `Binding` when a child edits state owned by its parent. +- In non-Redux designs, prefer `@Observable` to `ObservableObject` for new shared reference models when platform support allows it. +- In Redux applications, keep durable app and domain state in Redux. Do not introduce an observable view model as a parallel source of truth. +- Make observable stored-property types `Equatable` when equality matches their semantics, allowing redundant assignments to avoid unnecessary invalidation. +- Isolate side effects in `.task`, `.onChange`, actions, or explicit async functions rather than hiding them in rendering logic. +- Use the current `.onChange(of:)` form and read the updated captured value when the previous value is unnecessary. +- Avoid closure-based bindings when a writable key-path binding expresses the same relationship. + +With SDKs where `@State` is a macro, do not give a state property a declaration default and then attempt to replace that value in `init`. Choose one initialization source and verify current compiler guidance when migrating existing code. + +## Collections and identity + +- Give `ForEach`, `List`, `Table`, and similar data-driven views stable, unique element identity. +- Prefer meaningful `Identifiable` conformance when the model has natural identity. +- Do not use collection indices, offsets, or transient UUIDs as identity for mutable collections. +- Do not sort, filter, or map large collections inline inside a frequently evaluated view body. Prepare the collection before rendering. +- Use a dedicated row `View` for meaningful rows and pass it narrow inputs. +- Avoid `AnyView` in collection rows. + +## Modifiers and environment + +- Preserve stable view identity. Prefer modifiers whose values change over conditionally adding and removing modifier branches. +- Do not place high-frequency values in the environment when explicit narrow inputs work. +- Avoid unstable environment defaults and freshly created closures that invalidate large subtrees. +- Do not hide unstable values behind fake `Equatable` implementations. + +## Scrolling + +- Apply `.scrollBounceBehavior(.basedOnSize)` to new or changed `ScrollView` instances on supported deployment targets, especially inside modally presented sheets. Content that fits should stay still; content that exceeds the viewport can still scroll and bounce. +- Match the modifier's `axes` to the scroll view. The default affects only the vertical axis, so specify `.horizontal` for horizontal scrolling and both axes when needed. +- Keep the modifier on the intended scroll view or its narrowest suitable container. The setting propagates through the environment to descendant scrollable views, so check nested scrolling before applying it to a broader hierarchy. +- Preserve a different bounce behavior only when the supported interaction requires it, and record that reason in consumer guidance. Check Apple API availability for the consumer's deployment targets before applying the modifier. + +## Modern APIs and scope + +- Do not introduce APIs that current Xcode documentation identifies as deprecated or soft-deprecated. +- When fixing a feature, modernize only the code directly required by the task unless the user requests a broader migration. +- For SDK-sensitive features, search current Apple documentation through Xcode rather than relying on remembered signatures. +- Apply the current Xcode SwiftUI skill when a new SDK changes source behavior, builder resolution, state initialization, or modifier availability. + +## Native components and presentation + +- Prefer native SwiftUI or platform controls and presentation APIs whenever they express the supported interaction. Evaluate sheets, alerts, confirmation dialogs, navigation, menus, pickers, popovers, and similar components before implementing an equivalent. Consult official Apple/Xcode documentation for behavior and availability on the current deployment target, following [documentation lookup](../Xcode/MCP.md#documentation-lookup). +- Keep branded content and styling inside native components. Custom fonts, button styles, and content inside a native sheet are compatible with this policy when the system retains presentation and dismissal ownership. +- Do not substitute a sheet-shaped `ZStack`, offset animation, or custom scrim for a suitable native sheet API. The same rule applies to other simulated system components, including custom discard dialogs. Pixel fidelity to a static design and preserving mounted state are insufficient reasons to replace native presentation behavior; a mockup is not approval for an exception. +- Use a custom equivalent only for an actual native capability gap verified against the supported platform and deployment target. Before implementation, obtain explicit repository-owner approval and record a durable exception in consumer documentation: the required interaction, evaluated native alternatives, concrete missing capability and documentation or reproducible evidence, approved scope, lifecycle ownership, compensating validation, and revisit condition. Do not invent a capability gap or infer approval from existing custom code. An unapproved or undocumented replacement blocks completion. + +### System control placement + +- Let Apple determine the platform-appropriate placement and behavior of standard navigation, dismissal, confirmation, and window controls. Use native containers and controls for Back, Close, Cancel, Done, and similar actions; preserve the system's adaptation to platform, OS version, available space, and layout direction. Do not impose a universal left/right rule. +- Express an action's actual intent with supported semantic toolbar placements and button roles, letting the system resolve their position. For example, use `.cancellationAction` for cancellation and `.confirmationAction` for confirmation when those semantics apply. Do not choose a role merely to obtain a desired side, treat every Close action as Cancel, or replace an appropriate semantic placement with `.automatic` merely for its current visual result. Check current Apple documentation and API availability for the target. +- Preserve native Back navigation and its supported gestures, accessibility behavior, and keyboard or remote interactions. Do not hide and recreate Back, relocate system picker/editor controls, or add a competing close control solely to match another screen or a mockup. +- Treat apparent placement inconsistencies as an ownership question first: identify whether Apple or app-authored layout controls the position. Keep valid system-selected differences. For app-authored headers or toolbars, remove deliberate placement overrides where a native semantic equivalent supports the interaction. A custom equivalent remains subject to the capability-gap, owner-approval, and durable-exception requirements above; existing custom code is not an exception. +- Keep app-specific content actions within their intended scope; ordinary custom content layout does not itself replace native system behavior or require a capability-gap exception. An app-authored Close button is not automatically system-owned: determine its action semantics and whether it replaces a supported native control. For standard controls, explicit placement APIs can express a documented platform requirement when semantic APIs do not cover it; record the Apple guidance and target-specific reason. This does not permit overriding system-owned controls for visual uniformity. Align design artifacts with the supported native behavior rather than treating fixed mockup coordinates as authoritative. + +Consult Apple's [toolbar design guidance](https://developer.apple.com/design/human-interface-guidelines/toolbars) and [toolbar placement semantics](https://developer.apple.com/documentation/swiftui/toolbaritemplacement) for current platform behavior. Apply the same ownership principle to UIKit/AppKit navigation bars, toolbars, and window chrome. + +### Presentation ownership + +- Present from the active hierarchy. When a child presentation launches a system picker or editor, attach that presentation to the active child hierarchy rather than an obscured ancestor or unrelated host. +- Give each child independent dismissal. Read the dismissal action in the child's presentation environment or use its own presentation binding; do not route a child close button or downward dismissal gesture to the parent editor. Keep parent-owned draft state alive across child presentation and dismissal without committing or discarding it implicitly. +- Make cancellation idempotent across explicit cancel, interactive dismissal, parent dismissal, and asynchronous callbacks. Cancel owned work and reject stale completions after dismissal or replacement so an old result cannot mutate a retained draft or a later presentation. +- Perform cleanup that depends on completed dismissal through the presentation's dismissal-completion callback, such as `onDismiss`, rather than treating a dismiss request, animation delay, or arbitrary disappearance as proof of completion. Coordinate cleanup with cancellation so repeated callbacks cannot clear parent state or a newer child session. + +### Required interaction evidence + +For changed native presentations and approved custom equivalents, exercise the supported lifecycle on a simulator or device using [runtime interaction and reporting](../Xcode/MCP.md#build-run-and-interaction). Record the platform, scenario, action, observed outcome, and relevant hierarchy or visual evidence: + +- Verify presentation and dismissal animation/dimming, supported interactive dismissal and gesture routing, and parent survival with draft retention. If interactive dismissal is intentionally disabled, verify the restriction and the explicit exit path. Exercise reopening and repeated cancellation. +- Launch and dismiss any nested system picker or editor from the active child; confirm the expected presentation remains active after each exit. +- Inspect safe areas, controls and shadow clipping, keyboard/focus restoration, and relevant Dynamic Type and localization layouts during the flow. +- Exercise asynchronous cancellation and stale completion after dismissal or replacement when work can outlive the presentation; use deterministic tests where they improve coverage of these races alongside runtime interaction. + +A static screenshot or a no-op automation call is not evidence that gestures work. Require an actual gesture and its observed result, or recorded manual verification when automation cannot exercise it. Missing relevant runtime evidence blocks completion; report the exact unverified behavior instead of claiming the lifecycle passed. + +Use these decisions when auditing an implementation: + +| Decision | Audit outcome | +| --- | --- | +| Simulated sheet with a suitable native API and no approved durable exception | Blocked | +| Native nested sheet with branded content, correct ownership, and required interaction evidence | Accepted | +| Custom equivalent for a verified capability gap with owner approval, durable exception, and compensating evidence | Accepted within the approved scope | +| Presentation with missing relevant runtime evidence | Blocked | + +## Animation + +- Use native SwiftUI animation to make apps fluid rather than static. Apply it purposefully to buttons, transitions, interactions, selection, colors, and other visible state changes that benefit from feedback; do not animate every update or add motion for its own sake. +- Prefer the default SwiftUI animation, using `withAnimation { ... }` or `.animation(.default, value: ...)`, unless the task prompt explicitly requests a specific animation. Prefer system-provided transitions and SF Symbol effects when they fit the interaction instead of recreating them with custom timing, curves, or rendering. +- Reusable custom-styled controls own their basic visual transitions. Animate enabled/disabled appearance smoothly by default in both directions, without screen-level opt-in. A native `Button` preserves interaction semantics, but does not define transitions for every custom foreground, background, or shadow. Preserve system-owned feedback instead of layering duplicate animation over it. +- Change enabled state, hit-testing, accessibility state, and action availability immediately. Animate appearance; never delay functional state until an animation finishes. Immediate press, focus, or selection feedback remains appropriate when it improves responsiveness; record an intentional immediate transition and its reason. +- Preserve stable view identity when only appearance changes. Prefer changing fill, opacity, or shadow values over replacing equivalent view branches. +- Scope animation to the intended state and visual attributes. Preserve responsive controls, stable layout, and uninterrupted user interaction; animating surrounding layout must not accidentally animate every control inside it. The presence of `.animation` does not prove correct scope: value-triggered animation can affect other changes in the same transaction. Use narrower modifier or closure scope where necessary and supported by the deployment target. +- Apply the [Reduce Motion policy](#reduce-motion) alongside these animation defaults, including in reusable custom-styled controls. + +Consult Apple's [Explore SwiftUI animation](https://developer.apple.com/videos/play/wwdc2023/10156/) for transaction propagation and scoped animation behavior. The reusable-control defaults above are repository policy. + +### Reduce Motion + +Follow Apple's [Reduced Motion evaluation criteria](https://developer.apple.com/help/app-store-connect/manage-app-accessibility/reduced-motion-evaluation-criteria/) and [motion design guidance](https://developer.apple.com/design/human-interface-guidelines/motion). Evaluate individual animations; do not disable all animation indiscriminately. + +- Respect the user's reduced-motion preference as part of normal implementation; no separate task request is required. Preserve native accessibility adaptations and verify custom styling and surrounding animations do not defeat them. +- Use SwiftUI's [accessibilityReduceMotion](https://developer.apple.com/documentation/swiftui/environmentvalues/accessibilityreducemotion) environment value when app-authored motion needs adaptation. Follow preference changes during use. System preference integration is the repository default; document any equivalent or more granular in-app alternative and verify it meets Apple's criteria rather than requiring a redundant setting. +- Identify potentially problematic scaling, spinning, peripheral motion, depth simulation (including parallax or animated blur), and multi-axis or multi-speed movement. Remove decorative triggers or replace them with lower-motion feedback when reduced motion is requested. For ongoing motion such as an auto-advancing carousel, stop it or provide a discoverable stop control. +- Preserve information and usability: replace meaningful motion with suitable alternatives such as a dissolve, highlight fade, or color change. Retain harmless feedback, immediate functional state, and system-owned behavior. A reduced-motion preference does not justify losing status, navigation context, or action availability. +- Exercise affected flows with the preference on and off, including changing it while the app is running. Record the platform/OS, app revision, actions, outcomes, and limitations. Test custom and native behavior rather than assuming an environment read or native control proves support. + +#### Declaring support + +Claim Reduced Motion support only after evaluating all common tasks for the platform being declared against Apple's criteria. Follow Apple's [Accessibility Nutrition Labels guidance](https://developer.apple.com/help/app-store-connect/manage-app-accessibility/overview-of-accessibility-nutrition-labels) for task coverage, required third-party or user-generated content, and advertising. Record the evaluated tasks, evidence, remaining limitations, and declaration scope in consumer documentation. An app with no problematic motion can qualify; a guideline update or a single compliant component cannot establish app-wide support. Re-evaluate support with each app update, and withhold or correct a claim when relevant evidence is missing or a regression invalidates it. Updating App Store Connect remains a separately scoped metadata operation under [App Store metadata](../AppStore.md). + +## Image rendering + +- Use retained, display-appropriate derivatives for large dynamic images in small, frequently updated views instead of repeatedly rendering the original bitmap. This applies to photos, downloaded images, generated images, and other bitmap sources; an expensive rendering path does not by itself establish a provider defect. +- Account for display scale, aspect-fit/fill requirements, orientation, fidelity, and bounded intermediate/cache memory. Refresh derivatives when their source or relevant presentation requirements change. +- Keep expensive loading, decoding, resizing, and conversion outside view construction and repeated interaction paths. Perform expensive preparation off the main actor when supported and concurrency-safe; do not prescribe detached tasks as a universal solution. +- Reject stale asynchronous results after replacement, cancellation, or removal. Keep presentation derivatives separate from authoritative originals needed for editing, saving, or export. +- Inspect the representation actually drawn. A small display frame does not establish a small decoded image, and caching a `UIImage` alone does not remove rendering cost. Choose preparation based on measured cost and required fidelity; do not impose blanket bans on `Image`, `UIImage(data:)`, or full-resolution presentation, or universal pixel sizes, color formats, cache architectures, or `drawingGroup()` requirements. + +Apple's [iOS Memory Deep Dive](https://developer.apple.com/videos/play/wwdc2018/416/) explains image memory costs and demonstrates ImageIO downsampling for thumbnails without first decoding the full image. Use the [animation and image-rendering audit](../../.agents/skills/agent-guidelines-audit/SKILL.md#audit-animation-and-image-rendering) to verify affected interactions and record performance evidence. + +## Previews + +- Put previews at the end of the file under `// MARK: - Preview`. +- Use `#Preview`. +- Use `@Previewable` for interactive preview state when appropriate. +- Keep preview fixtures deterministic and lightweight. +- After UI changes, follow [Xcode MCP and visual verification](../Xcode/MCP.md) when runtime verification adds meaningful confidence. + +## Localization + +Follow [Localization](../Localization.md) for user-facing text, layout direction, formatting, and package bundles. diff --git a/AgentGuidelines/Guidelines/Testing/UnitTesting.md b/Guidelines/Testing/UnitTesting.md similarity index 96% rename from AgentGuidelines/Guidelines/Testing/UnitTesting.md rename to Guidelines/Testing/UnitTesting.md index a694331..cc14fb3 100644 --- a/AgentGuidelines/Guidelines/Testing/UnitTesting.md +++ b/Guidelines/Testing/UnitTesting.md @@ -50,3 +50,5 @@ - Report which tests ran and whether any relevant tests could not be executed. Follow [Xcode MCP](../Xcode/MCP.md) for build and runtime verification. + +Follow [Networking](../Networking.md#ownership-and-validation) for networking test boundaries and required evidence. diff --git a/Guidelines/Xcode/DeviceInteraction.md b/Guidelines/Xcode/DeviceInteraction.md new file mode 100644 index 0000000..da9267c --- /dev/null +++ b/Guidelines/Xcode/DeviceInteraction.md @@ -0,0 +1,109 @@ +# Device Hub, Physical Devices, and Simulators + +Use this guide when verifying an Apple-platform interface or investigating runtime behavior. Follow [Xcode MCP](MCP.md) for tool priority and documentation lookup. A successful build proves compilation; it does not prove that taps, focus, keyboard transitions, presentation, or cancellation work. + +## Select the environment + +1. Read the consumer's nearest `AGENTS.md` for its designated simulator, account, signing, CI, resource, and accessibility-testing constraints. Reuse that environment; do not create, erase, or boot extra simulators merely for convenience. +2. Use a physical device only when the owner explicitly requests physical-device interaction for the current task. A request for an iPhone-sized interface or visual verification does not imply permission to use a paired personal device. Existing task authorization remains valid; do not ask again for each ordinary test action. +3. Verify that the feature is available on the selected runtime and hardware using current Apple documentation and the framework's availability API. Simulator support varies: a fallback screen or unavailable Apple Intelligence feature does not verify the real native feature. Report that limitation and obtain physical-device authorization if needed. +4. Record the app revision/build, scheme, configuration, Xcode/SDK versions, device model, OS, locale, and relevant input settings. Resolve the exact destination identifier locally; do not publish personal device names, serial numbers, or identifiers in shared documentation. +5. Assign one operator to the interactive session. Concurrent agents must not tap, launch, install, or change settings on the same device. Coordinate builds and simulator use with CI before starting. + +Apple describes simulator limitations and run destinations in [Running your app on simulated or physical devices](https://developer.apple.com/documentation/xcode/running-your-app-on-simulated-or-physical-devices). Simulator success is not physical-device performance or feature evidence. + +## Discover tools and skills + +Inspect the tools actually exposed by the host before choosing a workflow. Prefer native Xcode MCP operations on the open project; external access uses `xcrun mcpbridge` and requires the user's Xcode permission. Use XcodeBuildMCP when native tooling is unavailable or cannot perform the needed operation. It can provide build, install, launch, and logging support without necessarily providing physical-device touch control. + +Read the installed `device-interaction` skill when available. It describes workspace-backed versus already-installed-app sessions, install/run, event synthesis, hierarchy capture, and session cleanup. If that installed skill requires a subagent, give it exclusive session ownership. Read an installed iOS debugger skill for XcodeBuildMCP workflows when relevant; a simulator-oriented skill does not establish physical-device support. Skill and tool names vary by installation: discover their current schemas, and do not call an operation merely because a guide mentions it. Distill policy rather than copying exported skill implementations into the repository. + +For native device sessions, prefer a workspace-backed session when building the app and an existing-app session when no build is needed. Use one-run arguments and environment variables instead of editing shared schemes. Capture the hierarchy and screenshot, interact, recapture, then end the session. When a hierarchy provides hit points or application-activation annotations, follow the installed tool's contract. A remote placeholder without children requires visual targeting; it does not prove that the device has no controls. + +When the required interaction is unavailable through MCP, use the host's supported computer-use capability to operate Device Hub. Do not invent touch support in a build-only tool or replace a missing physical test with simulator evidence. + +## Prepare and run a physical device + +Use the owner's already paired, unlocked device when possible. Pairing, trust confirmation, Developer Mode, account sign-in, and passcodes are security prerequisites for the owner to complete when required; do not automate around them or reset trust to repair a test. Select the authorized device in Device Hub and verify its model and OS before installing anything. See Apple's [device management](https://developer.apple.com/documentation/xcode/managing-your-simulated-and-physical-devices-in-device-hub) and [Device Hub access](https://support.apple.com/guide/personal-safety/ips37dbab2a1/web) documentation. + +Build for the exact destination with the project's normal development signing, provisioning, bundle identifier, and required entitlements. An unsigned CI build is not an interactive device build. Keep install, launch, and UI verification as separate evidence: installation can succeed while launch fails, and launch can succeed while the intended screen is absent. Preserve the existing app container and user data; uninstalling the user's app or resetting its storage is not a routine troubleshooting step. + +If MCP cannot perform an operation, Apple's command-line tools are a fallback. Inspect the installed help first, because options and device support change. These examples use placeholders, not literal device identifiers: + +```sh +xcodebuild -version +xcrun devicectl list devices +xcrun devicectl help device install app +xcrun devicectl help device process launch + +xcrun devicectl device install app --device '' '' +xcrun devicectl device process launch --device '' '' +``` + +Select the correct signed build before installation; discovering a device is not authorization to use it. Keep command output containing identifiers local. For console capture, the installed `devicectl device process launch --console` can attach the app's standard streams and wait for exit. Use the supported per-launch environment options for diagnostic configuration. A console stream is not automatically a complete unified-log archive; verify that the required events actually arrive. Stopping that console can forward signals to the app, so coordinate termination and restore an ordinary launch afterward. + +## Operate Device Hub + +Open **Xcode → Open Developer Tool → Device Hub**, select the target, and choose **View Screen** for a physical device. The Xcode 27 Device Hub app identifier is `com.apple.dt.Devices`; confirm the app/window in the host's current inventory rather than relying on a fixed filesystem path. Apple's [interaction guide](https://developer.apple.com/documentation/xcode/interacting-with-your-app-in-device-hub) describes the canvas, bezel, and platform-specific controls. + +Use the following observation loop: + +1. Select the intended device window and read its accessibility tree. If multiple windows exist, identify the right one by its title and visible device before acting. +2. Capture a fresh screenshot. The Mac accessibility tree may expose only Device Hub's toolbar and menus, not the mirrored app's controls. Prefer semantic controls where available; otherwise derive targets from the current screenshot. +3. Use the coordinate system documented by the active computer-use tool. A Device Hub window screenshot includes its toolbar and bezel; it is not the same coordinate space as a raw device screenshot or UIKit points. Do not assume Retina scaling or divide coordinates by two. Re-observe after resizing, changing windows, or rotating. +4. Perform the smallest action, then refresh the hierarchy and screenshot before choosing the next target. A tool reporting success proves input delivery, not the expected UI transition. +5. If an action has no effect, recapture and retry once with fresh evidence. Check focus, animation, overlays, and device connection before attempting a different path. Stop guessing when the target remains inaccessible. + +Use the tools' state capture and animation handling for synchronization. Do not add arbitrary waits as the default way to make interactions succeed. + +In observed Xcode 27 automation, the expanded hub could return `noWindowsAvailable` even though Device Hub was open. Selecting the target's compact device window made capture available. Treat this as a bounded workaround to verify against the current UI, not a guaranteed API behavior. Do not repeatedly relaunch the app or reset the phone to repair a window-capture problem. + +Accessory cards, notifications, and permission sheets can intercept input. Exclude a trial if the intended app action never occurred. Dismiss only a visible, understood obstruction within task scope, then re-establish the starting state; do not change unrelated notification or accessory settings. + +### Keyboard and tvOS controls + +Before testing a software-keyboard issue, inspect **Device → Keyboard** and record the current **Simulate Hardware Keyboard** and keyboard-capture settings when present. Hardware-keyboard simulation can suppress the onscreen keyboard and invalidate a comparison. With authorization for the diagnostic configuration, disable simulation as needed and use an ordinary disposable text field as a positive control: verify that the software keyboard visibly appears. **Toggle Software Keyboard** alone is not proof that normal focus will present it. Keep the configuration identical across trials and restore the original settings afterward. + +Focus the device canvas before sending Mac keyboard input, and check where it lands. For tvOS, move focus with arrow keys, activate with Return, and go back with Escape; use the current Device Hub controls or simulated remote for actions such as Home and Play/Pause. tvOS uses focus navigation, not touchscreen coordinate taps. Product-specific navigation and fixture instructions remain in the consumer repository. + +### tvOS current-user data and CloudKit + +Apple's [current-user guidance](https://developer.apple.com/documentation/tvservices/personalizing-your-app-for-each-user-on-apple-tv) and [multi-user sample](https://developer.apple.com/documentation/tvservices/mapping-apple-tv-users-to-app-profiles) say that the User Management capability gives each selected tvOS user separate preferences and iCloud data. For tvOS 16 and later, the sample uses `runs-as-current-user-with-user-independent-keychain`. That entitlement value does not itself opt data into the shared Keychain; `kSecUseUserIndependentKeychain` is a separate API for apps that deliberately share a service login. A personal-data app should not add manual `TVUserManager` profile mapping to compensate for an unverified system account context. + +When testing an app that depends on this separation, use two distinct, fully signed-in Apple TV accounts on an authorized physical device. Confirm the current profile in native Settings, then launch the same signed build through the app grid under each profile. Record the effective app entitlement and embedded provisioning privilege, a fresh process and loaded-build identity, and the account identity returned by the app's CloudKit boundary. Compare that verified account, the bound local store/checkpoint, and a synthetic entry set across A → B → A and cold launches. Retain only privacy-safe equality results; do not publish account or record identifiers or learner content. A changed Settings selection, new process, successful build, `shouldStorePreferencesForCurrentUser == true`, or distinct-looking UI alone does not prove that CloudKit supplied a different account. + +If B is selected but CloudKit verifies A, separate that observation from an app bug where CloudKit verifies B but the host opens A's store. A temporary debug-only `UserDefaults` marker written under A and checked without a B write can independently test preference isolation; remove it afterward. Preserve the signed build, process timeline, account/store comparisons, and any existing containers before trying a repair. On one observed tvOS device, both supported current-user entitlement values and a full restart still routed the secondary profile to the default account; removing and re-adding only that secondary profile restored distinct CloudKit accounts and stores across repeated switches. That result does not establish the internal tvOS cause or guarantee the same repair elsewhere. + +After one normal restart fails, [removing a secondary Apple Account profile](https://support.apple.com/guide/tv/atvb0753b37d/tvos) is a later owner-coordinated diagnostic: verify the secondary user's local data is replaceable, obtain action-time confirmation, let the owner handle Apple Account sign-in, and leave the default and unrelated profiles untouched. Repeat the same native account/store comparisons after re-addition. Do not uninstall the app, clear checkpoints, change entitlements, or factory-reset the device as a speculative account-routing fix. If separation still fails, preserve a bounded reproduction for Apple support; do not conceal the mismatch with an unverified app-side account mapping. + +### Sensor limitations + +Apple documents camera and microphone conflicts during physical-device remote interaction. An active Device Hub screen session can prevent sensor access or be interrupted by higher-priority apps. Stop remote interaction and arrange an owner-operated check when real camera or microphone behavior is the test target. Do not label an empty capture caused by the test environment as an application defect, and do not terminate an unrelated call or recording to continue testing. + +## Simulator basics + +Reuse the consumer-designated simulator by its resolved identifier and check its current boot state. Build for that simulator's platform and architecture, install a normally signed interactive build with the required entitlements, and verify launch before interaction. For entitlement-dependent services such as CloudKit, inspect signing and entitlements before retrying a startup failure. Do not reuse `CODE_SIGNING_ALLOWED=NO` CI output for those UI checks. A project's `CI=true` format-phase bypass is separate from code signing; follow the consumer's build instructions. + +On a shared CI host, check active CI before booting or using simulators and obey the consumer's exclusivity rule. Xcode Canvas can create a separate preview simulator even when a different run destination is selected. On constrained hosts, hide Canvas and disable automatic refresh while testing the designated simulator; stop the designated simulator before an intentional preview session, then stop the preview environment before resuming it. Do not shut down a device or session owned by another task or CI. + +For CLI fallback, inspect `xcrun simctl help` and the installed subcommand help, and resolve destinations with `xcrun simctl list devices`. Avoid blanket boot, shutdown, erase, or device-creation commands. Keep changes to locale, appearance, accessibility sizes, keyboard settings, and synthetic fixtures scoped to the test and restore them afterward. + +## Capture and interpret evidence + +Define the expected result before acting. For ordinary navigation, capture the starting state, action, and settled result. For a transient issue, such as a keyboard flashing during presentation, the transient itself is the acceptance target; do not dismiss it merely because the final screen looks correct. + +Use [Device Hub screenshots and recording](https://developer.apple.com/documentation/xcode/capturing-screenshots-and-videos-from-devices) when supported by the selected device and tool. Native device screenshots and host-window captures have different framing and resolution. Apple's recording instructions cover simulated devices; do not assume the same recording command supports a physical device. If recording is unavailable, capture a bounded sequence of screenshots around the action with timestamps. Call it a screenshot sequence, not a video, and report sampling gaps that could miss a short event. + +Correlate inspected frames with privacy-safe lifecycle, focus, keyboard, cancellation, and completion events under the [logging policy](../Logging.md). Prefer monotonic time and local attempt counters. Record where capture timing begins; an offset measured after a click or hierarchy request differs from an app log measured at presentation request. Notification delivery alone does not prove visible keyboard coverage or identify the first responder. Conversely, a visible flash without an app-owned focus event does not prove which system component caused it. + +For a controlled comparison, change one candidate cause at a time, keep the device, build configuration, input state, locale, and synthetic content equivalent, and repeat valid trials. Mark interrupted or confounded trials as excluded. When app-specific presentation is still a candidate, an authorized minimal native host can isolate it: use a separate bundle identifier, the same relevant public API configuration, no real account or app data, and no persistence of generated results. Cancel the workflow and preserve the reproduction locally. Reproduction in that host shows the removed app layers are unnecessary to trigger the symptom; it does not establish an exact internal framework defect or justify an untested production workaround. + +Keep screenshots, logs, and reproduction artifacts out of public commits when they contain personal names, notifications, accounts, device identifiers, or authored content. Use synthetic inputs, inspect retained evidence, and sanitize any report before sharing it. Do not log text-field contents or generated images to make timing easier to measure. + +## Cleanup and handoff + +- Cancel test editors and discard only the synthetic drafts created for the test; confirm the original data remains intact. +- Remove temporary diagnostics and one-run overrides, restore changed keyboard/environment settings, and relaunch the ordinary signed app when the test displaced it. Reuse the existing correct build when possible. +- Stop owned console captures, recordings, device-interaction sessions, and disposable simulator/preview processes. Restore the prior device environment without unpairing devices or changing security settings. +- Remove only a known disposable harness created for this test when its deletion is authorized and it contains no user data. Never uninstall an existing user app as cleanup. Preserve the minimal source and useful sanitized evidence separately when needed for a report. +- Report the exact tested configuration, actions, observed results, excluded trials, diagnostics, evidence locations, limitations, and cleanup status. Separate confirmed observations from hypotheses and unavailable verification. A negative comparison is a useful result; do not ship a speculative fix to make the investigation appear successful. diff --git a/AgentGuidelines/Guidelines/Xcode/MCP.md b/Guidelines/Xcode/MCP.md similarity index 75% rename from AgentGuidelines/Guidelines/Xcode/MCP.md rename to Guidelines/Xcode/MCP.md index bed3e38..5a852e4 100644 --- a/AgentGuidelines/Guidelines/Xcode/MCP.md +++ b/Guidelines/Xcode/MCP.md @@ -39,20 +39,7 @@ After a meaningful SwiftUI change: ## Build, run, and interaction -Use runtime interaction when static compilation cannot establish that a user-visible workflow behaves correctly. - -1. Start or select an appropriate simulator/device session. -2. Build, install, and launch through Xcode tooling. -3. Prefer one-run launch arguments and environment variables to editing a shared scheme for temporary configuration. -4. Capture the accessibility or UI hierarchy before interaction. -5. Capture a screenshot when visual state matters. -6. Derive interaction targets from the hierarchy; do not guess coordinates when semantic information is available. -7. Perform the smallest interaction sequence that proves the behavior. -8. Capture the resulting hierarchy and screenshot. -9. Report both functional and visible defects. -10. End resource-heavy sessions when verification is complete. - -Retry a slow launch or interaction once when the application may still be settling. Do not add arbitrary waits as a default synchronization strategy. +Use runtime interaction when static compilation cannot establish that a user-visible workflow behaves correctly. Follow [Device Hub, physical devices, and simulators](DeviceInteraction.md) for authorization, tool and skill discovery, signed builds, session ownership, hierarchy and screenshot targeting, keyboard diagnostics, evidence, and cleanup. Keep consumer-specific destinations and CI/Canvas constraints in the consumer's `AGENTS.md`. ## Reporting diff --git a/Guidelines/Xcode/ProjectSettings.md b/Guidelines/Xcode/ProjectSettings.md new file mode 100644 index 0000000..9d00f99 --- /dev/null +++ b/Guidelines/Xcode/ProjectSettings.md @@ -0,0 +1,80 @@ +# Xcode Project Settings + +Use Apple's [Build settings reference](https://developer.apple.com/documentation/xcode/build-settings-reference) for the current setting names and behavior. Apply this baseline to every checked-in Xcode project. + +## Project-level ownership + +Define the required settings in every project build configuration so application, extension, framework, unit-test, UI-test, and other targets inherit one baseline. An `.xcconfig` counts as project-level ownership only when the project's build configurations reference it; a target-only configuration does not. + +Do not satisfy this policy with repeated target-level values. Remove redundant target copies so inheritance remains visible. A target may override a project value only under a documented exception that names that target and setting. + +## Required baseline + +Set all warning policies to `YES`: + +- `GCC_TREAT_WARNINGS_AS_ERRORS` +- `MTL_TREAT_WARNINGS_AS_ERRORS` +- `SWIFT_TREAT_WARNINGS_AS_ERRORS` + +Set the concurrency baseline: + +- `SWIFT_APPROACHABLE_CONCURRENCY = YES` +- `SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor` +- `SWIFT_STRICT_CONCURRENCY = complete` + +For application targets, set `INFOPLIST_KEY_ITSAppUsesNonExemptEncryption = NO` at project level so every configuration generates Apple's [`ITSAppUsesNonExemptEncryption`](https://developer.apple.com/documentation/bundleresources/information-property-list/itsappusesnonexemptencryption) Boolean with the value `NO`. This declares that the shipped app does not use non-exempt encryption and avoids App Store Connect's recurring missing-compliance questionnaire. Verify the generated Boolean in the built app before upload and reassess it whenever the app or a linked dependency introduces cryptography. + +Set `SWIFT_VERSION` to the newest stable Swift language mode supported by the selected Xcode. The current language mode is Swift 6, serialized as `SWIFT_VERSION = 6.0`; move to 7, 8, 9, and later stable modes when their supporting Xcode releases are adopted. Do not confuse the compiler's minor release, such as Swift 6.4, with the Swift language mode. + +Inspect every build setting exposed by the selected Xcode whose name begins with `SWIFT_UPCOMING_FEATURE_`. Enable each feature that remains opt-in under the selected Swift language mode. Do not set an upcoming-feature flag when that language mode already enables the feature unconditionally: Swift diagnoses some redundant flags, and warnings-as-errors can turn that diagnostic into a build failure. `SWIFT_APPROACHABLE_CONCURRENCY` enables a subset of concurrency features but does not replace the applicable explicit upcoming-feature settings. + +The Xcode 27 inventory to evaluate is: + +- `SWIFT_UPCOMING_FEATURE_CONCISE_MAGIC_FILE` +- `SWIFT_UPCOMING_FEATURE_DEPRECATE_APPLICATION_MAIN` +- `SWIFT_UPCOMING_FEATURE_DISABLE_OUTWARD_ACTOR_ISOLATION` +- `SWIFT_UPCOMING_FEATURE_DYNAMIC_ACTOR_ISOLATION` +- `SWIFT_UPCOMING_FEATURE_EXISTENTIAL_ANY` +- `SWIFT_UPCOMING_FEATURE_FORWARD_TRAILING_CLOSURES` +- `SWIFT_UPCOMING_FEATURE_GLOBAL_ACTOR_ISOLATED_TYPES_USABILITY` +- `SWIFT_UPCOMING_FEATURE_GLOBAL_CONCURRENCY` +- `SWIFT_UPCOMING_FEATURE_IMPLICIT_OPEN_EXISTENTIALS` +- `SWIFT_UPCOMING_FEATURE_IMPORT_OBJC_FORWARD_DECLS` +- `SWIFT_UPCOMING_FEATURE_INFER_ISOLATED_CONFORMANCES` +- `SWIFT_UPCOMING_FEATURE_INFER_SENDABLE_FROM_CAPTURES` +- `SWIFT_UPCOMING_FEATURE_INTERNAL_IMPORTS_BY_DEFAULT` +- `SWIFT_UPCOMING_FEATURE_ISOLATED_DEFAULT_VALUES` +- `SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY` +- `SWIFT_UPCOMING_FEATURE_NONFROZEN_ENUM_EXHAUSTIVITY` +- `SWIFT_UPCOMING_FEATURE_NONISOLATED_NONSENDING_BY_DEFAULT` +- `SWIFT_UPCOMING_FEATURE_REGION_BASED_ISOLATION` + +Treat this list as discovery input for Xcode 27, not as a set of flags that must all be present and not as a permanent exhaustive list. When adopting a newer Xcode, compare its build settings with this prefix and evaluate newly exposed settings against the selected Swift language mode. Require each still-upcoming feature at project level; omit each feature already incorporated into the language mode. + +## Swift package parity + +Whenever this Xcode project baseline adds, removes, or changes a Swift or Clang compiler policy, evaluate whether Swift Package Manager exposes a semantically equivalent setting and whether that policy is appropriate for reusable packages. When it is, update the [Swift package compiler-settings baseline](../Packages.md#compiler-settings-baseline), the Swift-package completion audit, and their structural validation in the same change. Do not mechanically copy application-only policy such as `Info.plist` declarations, Metal settings without a SwiftPM equivalent, or default MainActor isolation into the package baseline. + +## Audit procedure + +1. Identify the selected Xcode version and its newest stable Swift language mode. +2. Inspect the `PBXProject` build configurations and any project-level `.xcconfig` files. Confirm every Debug, Release, and custom configuration defines the complete baseline. +3. Compare the active Xcode's build settings with the `SWIFT_UPCOMING_FEATURE_` prefix so newly introduced settings are not missed. Use the setting documentation and compiler diagnostics for the selected language mode to distinguish still-upcoming features from features that are already unconditional. +4. Enumerate every target, including application targets and unit-test and UI-test targets, and every supported configuration. Use Xcode project-aware tooling or `xcodebuild -showBuildSettings` to verify the effective values. For each application target, also inspect the built `Info.plist` and require the `ITSAppUsesNonExemptEncryption` Boolean to be `NO`. +5. Inspect target build configurations for redundant copies, disabling values, overrides, or upcoming-feature flags that are redundant in the selected language mode. Remove redundant copies and resolve undocumented overrides. +6. Build the relevant configurations and treat every warning as a failure unless an applicable documented exception explicitly covers the setting that would otherwise promote it. + +## Exceptions + +An incompatible project or target requirement may specialize one or more settings only when the nearest applicable `AGENTS.md`, or durable project documentation linked from it, records: + +- each exact setting name; +- the affected project, configurations, and targets; +- the concrete requirement that prevents the baseline value; +- the replacement value or omitted setting and its engineering impact; +- compensating validation where relevant; and +- the condition for removing or revisiting the exception. + +The audit accepts an applicable documented exception and reports the deviation without failing the project for that setting. A transient discussion, generic statement that a project uses different settings, or the existing target configuration by itself is not an exception. + +An application that uses non-exempt encryption must set `INFOPLIST_KEY_ITSAppUsesNonExemptEncryption = YES` and document that exact setting as an exception, including the cryptography that requires the declaration and the resulting export-compliance workflow. The audit accepts a generated `ITSAppUsesNonExemptEncryption = YES` under that documented exception instead of reporting a false positive. diff --git a/AgentGuidelines/Guidelines/Xcode/Security.md b/Guidelines/Xcode/Security.md similarity index 94% rename from AgentGuidelines/Guidelines/Xcode/Security.md rename to Guidelines/Xcode/Security.md index 5817b01..948a26f 100644 --- a/AgentGuidelines/Guidelines/Xcode/Security.md +++ b/Guidelines/Xcode/Security.md @@ -16,7 +16,7 @@ Confirm the requested targets and configurations, then inspect only relevant are - code-signing and entitlements; - application capabilities; - privacy manifests and required-reason APIs; -- network security configuration; +- network security configuration under [Networking](../Networking.md#ownership-and-validation); - debug-only behavior and diagnostics; - sensitive data storage and logging; - unsafe interoperability boundaries. diff --git a/LICENSE b/LICENSE index 45f5b45..42d8021 100644 --- a/LICENSE +++ b/LICENSE @@ -19,3 +19,4 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + diff --git a/Package.resolved b/Package.resolved deleted file mode 100644 index 06507de..0000000 --- a/Package.resolved +++ /dev/null @@ -1,33 +0,0 @@ -{ - "originHash" : "537618524d8febb222b9556d3d27add53e153103a47050a496e01cc2e96f821f", - "pins" : [ - { - "identity" : "applogger", - "kind" : "remoteSourceControl", - "location" : "https://github.com/thatfactory/applogger", - "state" : { - "revision" : "75dbe6e22170cb7e7507645cc23ab31611a07c84", - "version" : "1.1.0" - } - }, - { - "identity" : "swift-docc-plugin", - "kind" : "remoteSourceControl", - "location" : "https://github.com/swiftlang/swift-docc-plugin", - "state" : { - "revision" : "647c708be89f834fa6a6d4945442793a77ddf5b6", - "version" : "1.5.0" - } - }, - { - "identity" : "swift-docc-symbolkit", - "kind" : "remoteSourceControl", - "location" : "https://github.com/swiftlang/swift-docc-symbolkit", - "state" : { - "revision" : "b45d1f2ed151d057b54504d653e0da5552844e34", - "version" : "1.0.0" - } - } - ], - "version" : 3 -} diff --git a/Package.swift b/Package.swift deleted file mode 100644 index cf26039..0000000 --- a/Package.swift +++ /dev/null @@ -1,44 +0,0 @@ -// swift-tools-version:6.4 - -import PackageDescription - -let package = Package( - name: "ProgressionKit", - platforms: [ - .iOS(.v26), - .macOS(.v26), - .tvOS(.v26), - .watchOS(.v26), - ], - products: [ - .library( - name: "ProgressionKit", - targets: ["ProgressionKit"] - ) - ], - dependencies: [ - .package(url: "https://github.com/thatfactory/applogger", from: "1.1.0"), - .package(url: "https://github.com/swiftlang/swift-docc-plugin", from: "1.5.0"), - ], - targets: [ - .target( - name: "ProgressionKit", - dependencies: [ - .product( - name: "AppLogger", - package: "applogger" - ) - ] - ), - .testTarget( - name: "ProgressionKitTests", - dependencies: [ - "ProgressionKit", - .product( - name: "AppLogger", - package: "applogger" - ), - ] - ), - ] -) diff --git a/README.md b/README.md index b062f81..dbaa196 100644 --- a/README.md +++ b/README.md @@ -1,248 +1,209 @@

- Swift - Xcode - Platforms - SPM - DocC + Xcode MCP + Codex MCP License - CI - Release + Updated + Revision + CI + Release

-# ProgressionKit -A reusable progression engine that turns player performance into configurable XP, levels, and unlocks across games and apps. 📈 - -`ProgressionKit` is a pure Swift package for apps and games that need deterministic progression logic without coupling progression rules to storage or UI frameworks. - -It models: - -- `XP` gain from successful performance. -- Player levels derived from total XP. -- Track-scoped mastery across distinct content. -- Tier unlocks such as `beginner`, `intermediate`, and `advanced`. - -The package is deliberately content-agnostic. Host apps decide what a track, content item, and tier mean, then feed those identifiers into `ProgressionKit`. - -## Logging - -ProgressionKit logs concise progression outcomes through [AppLogger](https://github.com/thatfactory/applogger) with subsystem `com.thatfactory.progressionkit` and category `progression`. - -Every package-owned line starts with `📈` and includes only the XP granted, resulting player level, and number of newly unlocked tiers. ProgressionKit does not log content, track, or tier identifiers. - -## Implemented APIs - -- `PKEngine`: applies a progression event to a profile and returns the updated profile plus derived progress values. -- `PKProfile`: persisted progression state for a player. -- `PKConfig`: tunable progression rules such as level size, XP reward, tier order, and unlock thresholds. -- `PKEvent`: a single outcome emitted by the host app. -- `PKUpdate`: the result of applying one event. - -## Structure - -```mermaid -flowchart TB - subgraph HOST["Host App/Game"] - EVENTS["Performance Events"] - STORAGE["Storage Layer"] - UI["UI / HUD / XP Bar"] - end - - subgraph PK[" "] - ENGINE["ProgressionKit"] - PROFILE["PKProfile"] - CONFIG["PKConfig"] - UPDATE["PKUpdate"] - end - - EVENTS --> ENGINE - CONFIG --> ENGINE - ENGINE --> PROFILE - ENGINE --> UPDATE - PROFILE --> STORAGE - UPDATE --> UI +# Agent Guidelines + +`agent-guidelines` is ThatFactory's public, versioned source of truth for reusable instructions and development configuration. It centralizes stable decisions about Swift development, Redux architecture, testing, documentation, logging, packages, CI/CD, localization, and Xcode tooling while leaving product context and exceptions in each consuming repository. + +The repository contains documentation and supporting configuration, not a Swift product. Consumers install a tagged release as a Git subtree at `AgentGuidelines/`, so every agent and supported tool sees ordinary version-controlled files at predictable paths. + +## How it fits together + +```text + thatfactory/agent-guidelines + versioned GitHub repository + | + tagged release + e.g. 0.0.3 + | + git subtree add/pull + | + v ++---------------- Consumer project or package -----------------+ +| | +| AGENTS.md | +| |-- local product/package context | +| |-- concrete project paths | +| |-- local exceptions | +| `-- pointers to shared guidelines -----------------+ | +| | | +| AgentGuidelines/ | | +| |-- VERSION | | +| |-- Configurations/ | | +| `-- Guidelines/ <----------------------------------+ | +| |-- Architecture/Redux.md | +| |-- Swift/SwiftUI.md | +| |-- Testing/UnitTesting.md | +| `-- Xcode/MCP.md | +| | +| Sources and project files | ++----------------------------+---------------------------------+ + | + reads instructions and project files + +----------+----------+ + v v + Codex Xcode agent + | + | Xcode MCP (`xcrun mcpbridge`) + v + Xcode ``` -## Quick Start - -Import the package and create an initial player profile: - -```swift -import ProgressionKit - -let profile = PKProfile() +The subtree does not automatically import every guide into an agent's context. A consumer's root or folder-scoped `AGENTS.md` tells the agent which shared guides to read for the task. The nearest local `AGENTS.md` can specialize or override the shared baseline. + +## Guideline catalog + +- [Agent workflow and tool execution](Guidelines/AgentWorkflow.md) +- [App Store metadata](Guidelines/AppStore.md) +- [CI/CD](Guidelines/CICD.md) +- [Codex review policy](ReviewPolicy/README.md) +- [Development and reusability](Guidelines/Development.md) +- [Device Hub, physical devices, and simulators](Guidelines/Xcode/DeviceInteraction.md) +- [Documentation](Guidelines/Documentation.md) +- [Git ignore files](Guidelines/Git/IgnoreFiles.md) +- [Git repositories and SSH-first cloning](Guidelines/Git/Repositories.md) +- [GitHub pull requests](Guidelines/GitHub/PullRequests.md) +- [Localization](Guidelines/Localization.md) +- [Logging](Guidelines/Logging.md) +- [Networking](Guidelines/Networking.md) +- [Redux architecture and physical folder organization](Guidelines/Architecture/Redux.md) +- [Swift](Guidelines/Swift/Swift.md) +- [Swift format](Guidelines/Swift/SwiftFormat.md) +- [Swift packages](Guidelines/Packages.md) +- [Swift style](Guidelines/Swift/SwiftStyle.md) +- [SwiftUI](Guidelines/Swift/SwiftUI.md) +- [Unit and integration testing](Guidelines/Testing/UnitTesting.md) +- [Xcode MCP and visual verification](Guidelines/Xcode/MCP.md) +- [Xcode project settings](Guidelines/Xcode/ProjectSettings.md) +- [Xcode security audits](Guidelines/Xcode/Security.md) + +Only reference the guides that apply. Agent workflow normally applies to both applications and packages. A UI-agnostic package normally also uses Swift, style, testing, documentation, logging, packages, CI/CD, and Xcode guidance, but not Redux or SwiftUI guidance. + +## Add to a consumer + +From the consumer repository root, install a tagged release: + +```sh +git subtree add \ + --prefix=AgentGuidelines \ + https://github.com/thatfactory/agent-guidelines.git \ + 0.0.47 \ + --squash ``` -Create an event whenever the player finishes one unit of content: +Swift consumers that adopt the shared formatter expose its configuration at the repository root so Xcode and other tools discover it: -```swift -let event = PKEvent( - contentID: "lesson.greetings.001", - trackID: "japanese-basics", - tierID: "beginner", - wasSuccessful: true -) +```sh +ln -s AgentGuidelines/Configurations/Swift/.swift-format .swift-format +ln -s AgentGuidelines/Configurations/Swift/.editorconfig .editorconfig ``` -Apply the event to the profile: +Keep the subtree tracked, but add this to the consumer's tracked `.gitattributes` so GitHub collapses synchronized guideline files in pull-request diffs by default: -```swift -let update = PKEngine.apply( - event: event, - to: profile -) +```gitattributes +# Synced from thatfactory/agent-guidelines; keep tracked but collapse GitHub diffs. +AgentGuidelines/** linguist-generated ``` -`update` is a `PKUpdate` value that contains the updated `PKProfile` and derived progression values your app can render immediately. +Copy and adapt [the consumer template](Templates/AGENTS.md). Keep the consumer file small: describe the product or package, map its concrete physical folders, point to the applicable shared guides, and state only genuine exceptions. Keep the version-marked code-review contract, PR-lifecycle contract, documentation-maintenance contract, external-dependency contract, and runtime-observability contract directly in the repository-root `AGENTS.md`; Markdown links to shared guides are navigation, not automatic instruction includes. -Common `PKUpdate` values you will typically use: +Copy the shared [`.gitignore` template](Templates/.gitignore) into a new Xcode project or Swift package. Keep authored project files, workspaces, and package lockfiles eligible for version control, and follow the [Git ignore guidance](Guidelines/Git/IgnoreFiles.md) when an established consumer needs an additional project-specific rule. -- `update.profile`: persist this as the new `PKProfile`. -- `update.playerLevel`: current player level. -- `update.xpIntoLevel` and `update.xpForNextLevel`: useful for progress bars. -- `update.newlyUnlockedTierIDs`: tiers unlocked by the latest event. -- `update.didGrantXP`: whether the event changed XP. +### Adopt review instructions only -## Configure Progression Rules +For a repository that needs only Codex reviewer rules and the PR flow, use the [review-only profile](ReviewPolicy/README.md). It installs managed root instructions and CI validation without the shared subtree or unrelated engineering contracts. Both profiles require the latest independently published review-policy revision. Use the central synchronizer rather than hand-copying policy text. -Use `PKConfig` when you want to customize level size, XP rewards, tier unlock order, and the mastery requirement for unlocking the next tier: +### Configure global Codex instructions -```swift -let config = PKConfig( - levelXP: 120, - masteryXP: 15, - tierOrder: ["beginner", "intermediate", "advanced"], - masteryRequirement: 4 -) -``` +Copy the contents of [`Templates/GlobalCodexInstructions.md`](Templates/GlobalCodexInstructions.md) into the user's global Codex instructions. -Apply the same event with your custom config: +Copy only its code-review section into Settings → Code Review → Review Instructions for manually started reviews. Automatic GitHub reviews use the checked-in root contracts. -```swift -let configuredUpdate = PKEngine.apply( - event: event, - to: profile, - config: config -) -``` - -In practice: +These instructions bootstrap discovery of repository-local `AGENTS.md` files and shared guides and provide generic high-signal code-review defaults. Repository engineering policy and specialized threat models remain versioned in this repository or the consumer rather than duplicated in each user's global configuration. -- Persist `configuredUpdate.profile` (your new `PKProfile`) after each event. -- Read other `PKUpdate` values to update your UI (XP gain, level changes, unlock state, and mastery). +Review this template when upgrading `agent-guidelines`, because the recommended global bootstrap instructions may change between releases. Installing or updating the Git subtree does not update a user's global Codex configuration. -## SwiftUI Example (Simple Progress Bar) +Redux applications also copy [the canonical Store](Templates/Store.swift) as is, following the composition and placement rules in [Redux architecture](Guidelines/Architecture/Redux.md). -This example shows a simple integration pattern: apply progression events, keep the latest `PKUpdate`, and render a progress bar from the returned values. +Expose the completion-audit skill at the consumer repository root so Codex can discover it: -### Video +```sh +mkdir -p .agents/skills +ln -s ../../AgentGuidelines/.agents/skills/agent-guidelines-audit \ + .agents/skills/agent-guidelines-audit +``` -https://github.com/user-attachments/assets/3920bbde-7b6b-40f6-b02f-f5506410b4fb +Validate the checked-in consumer integration directly or through the completion-audit skill: -### Code +```sh +AgentGuidelines/Scripts/validate_consumer_setup.swift +``` -```swift -import ProgressionKit -import SwiftUI +The native Swift validator checks the version-marked root Code Review, PR Lifecycle, Documentation Maintenance, External Dependency, and Runtime Observability contracts, Codex subtree-review scope, `.gitattributes`, local guide links, and the audit-skill symlink. When the root `AGENTS.md` links the shared Swift-format guide, it also requires both configuration symlinks and a non-mutating `lint-strict` CI invocation. Pass `--require-swift-format` only when auditing formatter adoption before adding that guide link. -struct ProgressionDemoView: View { - @State private var profile = PKProfile() - @State private var lessonNumber = 1 +## Update a consumer - private let config = PKConfig() +Review the target release's changelog, then pull it deliberately: - private var progress: Double { - min(Double(profile.totalXP) / Double(config.levelXP), 1) - } +```sh +git subtree pull \ + --prefix=AgentGuidelines \ + https://github.com/thatfactory/agent-guidelines.git \ + 0.0.47 \ + --squash +``` - var body: some View { - VStack(spacing: 16) { - Text(progress < 1 ? "Level 1" : "Level 2 🥳") - .font(.headline) +Confirm `AgentGuidelines/VERSION`, review the subtree diff, synchronize the marked code-review contract, PR-lifecycle contract, documentation-maintenance contract, external-dependency contract, and runtime-observability contract when their versions change, run `AgentGuidelines/Scripts/validate_consumer_setup.swift`, and run the consumer's relevant tests. Keep the subtree update in its own commit, and identify the old and new versions plus the central release or pull request in the consumer pull-request description. Updates are intentionally not automatic: one guideline release cannot silently change every project. - GeometryReader { geometry in - let totalWidth = geometry.size.width - let fillWidth = totalWidth * progress +When first adopting [Networking](Guidelines/Networking.md), synchronize external-dependency contract v2 and perform the [networking adoption audit](.agents/skills/agent-guidelines-audit/SKILL.md#audit-networking), including existing paths and any explicitly approved migration deferrals. - ZStack(alignment: .leading) { - RoundedRectangle(cornerRadius: 10) - .fill(.gray.opacity(0.25)) +## Upgrade a consumer's Xcode - RoundedRectangle(cornerRadius: 10) - .fill(.green) - .frame(width: fillWidth) - .animation(.snappy, value: progress) - } - } - .frame(height: 16) +Use the [`xcode-upgrade` skill](.agents/skills/xcode-upgrade/SKILL.md) to move an Apple-platform application or Swift package to a requested Xcode, update dependencies and compiler settings, align CI, and validate the result. In Codex, invoke `$xcode-upgrade to Xcode 27.2 and use the new JSON format` or select the skill. The skill also recognizes `/xcode-upgrade ...` as request text when the client passes it through; it does not register a client slash command. The skill follows the shared [project-settings guide](Guidelines/Xcode/ProjectSettings.md) and [package compiler-settings baseline](Guidelines/Packages.md#compiler-settings-baseline), preserving consumer-specific exceptions and the user's authorization boundaries. - Text("\(Int(progress * 100))%") - .font(.caption) - .foregroundStyle(.secondary) +The skill is discoverable in this central checkout. To use it in a consumer that has adopted this release, expose it from the subtree: - Button("Complete Lesson") { - let event = PKEvent( - contentID: "lesson.greetings.\(lessonNumber)", - trackID: "japanese-basics", - tierID: "beginner", - wasSuccessful: true - ) +```sh +mkdir -p .agents/skills +ln -s ../../AgentGuidelines/.agents/skills/xcode-upgrade \ + .agents/skills/xcode-upgrade +``` - let update = PKEngine.apply( - event: event, - to: profile, - config: config - ) +Alternatively, explicitly provide `AgentGuidelines/.agents/skills/xcode-upgrade/SKILL.md` with the request. Keep the skill beside its linked guides in the subtree; copying only `SKILL.md` loses those references. Subtree adoption and skill exposure do not upgrade a consumer's toolchain until requested. - withAnimation(.snappy) { - profile = update.profile - } - lessonNumber += 1 - } - } - .padding() - } -} +## Maintain the source of truth -// MARK: - Preview +Use the repository-local [`update-agent-guidelines` skill](.agents/skills/update-agent-guidelines/SKILL.md) with a request such as `$update-agent-guidelines include/update the rule that ...`. It chooses the guide, asks whether to add audit coverage when that choice is missing, and prepares the next version's metadata. Explicit invocation also authorizes the scoped PR, merge after required approval and green CI, and release; narrower instructions such as draft-only or no release take precedence. Consumer adoption remains separate. -#Preview { - ProgressionDemoView() -} -``` +The skill is discoverable when working in this central checkout. For a consumer on an older release, open a chat in the central checkout or explicitly supply the path to its `.agents/skills/update-agent-guidelines/SKILL.md` with the request; updating the consumer subtree is not a prerequisite. For use across repositories, the user can install the skill independently with Codex's skill installer from `thatfactory/agent-guidelines`, path `.agents/skills/update-agent-guidelines`, at a published tag. Do not implicitly install it or alter global configuration as part of a guideline change. -## Integration +1. Export current Xcode skills to a temporary review location when a new Xcode release materially changes agent behavior: -### Xcode -Use Xcode's [built-in support for SPM](https://developer.apple.com/documentation/xcode/adding_package_dependencies_to_your_app). + ```sh + xcrun agent skills export --output-dir + ``` -*or...* +2. Compare relevant guidance with this repository and official Apple documentation. +3. Bring over durable policy, not the exported skill text or an SDK API catalog. +4. Remove obsolete or conflicting rules instead of accumulating historical alternatives. +5. Run `Scripts/validate_guidelines.swift`. +6. Update `VERSION` and `CHANGELOG.md`, open a pull request, and wait for approval before merging. +7. After the pull request has merged, create the matching tag and GitHub release. -### Package.swift -In your `Package.swift`, add `ProgressionKit` as a dependency: +## Precedence -```swift -dependencies: [ - .package( - url: "https://github.com/thatfactory/progressionkit", - from: "0.1.5" - ) -] -``` +For a consumer task, apply instructions in this order: -Associate the dependency with your target: - -```swift -targets: [ - .target( - name: "YourTarget", - dependencies: [ - .product( - name: "ProgressionKit", - package: "progressionkit" - ) - ] - ) -] -``` +1. The user's explicit request. +2. The nearest applicable consumer `AGENTS.md`. +3. The consumer root `AGENTS.md`. +4. The shared guides explicitly referenced by those files. -Run: `swift build` +Official Apple documentation remains authoritative for API behavior. A local convention can deliberately narrow a choice, but it must not rely on behavior contradicted by the current SDK documentation. diff --git a/ReviewPolicy/Policy.md b/ReviewPolicy/Policy.md new file mode 100644 index 0000000..cc525f9 --- /dev/null +++ b/ReviewPolicy/Policy.md @@ -0,0 +1,21 @@ + +## Code Review Rules + +Report only substantiated P0/P1 defects introduced or materially exposed by this change. Require a concrete, reachable failure in a supported use case or documented threat model, with serious impact such as a security-boundary bypass, durable data loss or corruption, a crash or deadlock in an important workflow, loss of availability, or a serious compatibility regression. An acceptance-criterion violation alone does not establish P1 severity. + +For each finding, state severity, preconditions, execution path, impact, evidence, and actionable remediation. Group manifestations of one root cause. Report substantiated blockers together. Omit unsolicited P2/P3 observations, style preferences, speculative hardening, optional tests, and refactors. A clean review means no unresolved P0/P1 blockers, not perfect software. + +A follow-up review covers unresolved P0/P1 findings, changes since the previous reviewed commit, and directly affected code. Do not restart a full review of unchanged code. New follow-up findings must be P0/P1 defects introduced by remediation or genuinely hidden by the previous blocker. + + + +## Pull Request Lifecycle + +Finish implementation, inspect the diff, and run relevant local validation before opening a ready-for-review PR. Drafts are for incomplete preparation; mark ready before waiting for automatic review. Keep the review head stable while the initial review runs. One automatic Codex review is the initial review; never duplicate it with a manual request or repeatedly toggle draft/ready state. + +Establish review configuration from repository-specific evidence. Verify the bot, PR, review round, and reviewed commit using PR/request-comment reactions, review submissions, inline threads, and checks. Eyes means processing, not approval; a thumbs-up means no suggestions only for its verified review round. Historical reactions, missing comments, and elapsed time never certify a newer head. Monitor at most five minutes total with bounded, non-accelerating polls; timeout leaves a required gate unresolved and never authorizes merge. + +Batch accepted P0/P1 fixes, verify them locally, rerun affected checks, and disposition and resolve every review thread. A completed initial review plus an explicitly recorded, locally verified remediation-only delta can satisfy the review gate; do not claim Codex reviewed the newer head. New unrelated scope belongs in another PR. Request at most one delta-scoped verification only when the owner explicitly authorizes it. Do not request reviews after every fix or casually mention the bot to start extra work. Separate Security Review is manual and requires explicit owner instruction. + +Before merge, rerun the latest published review-policy check, confirm no required review is pending, no unresolved P0/P1 blocker remains, every thread is dispositioned and resolved, required checks pass on the current head, and existing human approval or merge authorization is satisfied. A bot thumbs-up is not a substitute for required GitHub approval. Opening a PR does not authorize merging it. + diff --git a/ReviewPolicy/README.md b/ReviewPolicy/README.md new file mode 100644 index 0000000..54108c4 --- /dev/null +++ b/ReviewPolicy/README.md @@ -0,0 +1,38 @@ +# Codex Review Policy + +The [canonical policy](Policy.md) contains the only authored reviewer and PR-lifecycle contracts. [VERSION](VERSION) is its independent positive integer revision. Full consumers adopt engineering guides through `AgentGuidelines/`; review-only consumers install the two managed sections directly in root `AGENTS.md` and a small CI integration. The central root, global review instructions, and full consumer template mirror this canonical text and are validated together. A Markdown link is navigation, not an instruction include. + +## Profiles and synchronization + +Start a review-only repository with a root `AGENTS.md` describing its actual purpose and local constraints. Do not install unrelated Apple development guidance. Run the central synchronizer against the consumer: + +```sh +Scripts/sync_codex_review_policy.swift update --consumer-root --profile review-only +Scripts/sync_codex_review_policy.swift check --consumer-root --profile review-only +``` + +Use `--profile full` for a repository with an `AgentGuidelines/` subtree. Repeated `--consumer-root` options synchronize several repositories against one source resolution. The synchronizer updates only the provenance comment and complete managed contracts; it preserves local instructions, removes obsolete/duplicate complete contracts, and refuses malformed marker pairs. `check` never writes files. Review-only consumers need no vendored directory, formatter setup, or completion-audit symlink. + +The provenance comment records profile, policy revision, and the exact published source commit. Latest-policy verification always uses `thatfactory/agent-guidelines`. `--policy-repository` exists for isolated test fixtures; production CI never accepts a consumer-controlled repository override. Source documents are data and are never executed. `--local-source` is restricted to central/template development, whose source is `local` because a commit cannot contain its own hash; it cannot satisfy a consumer's published-provenance check. + +## CI and freshness + +Run the shared `.github/actions/codex-review-policy` composite action from an immutable full commit SHA, with `profile: full` or `profile: review-only`. Reuse an existing Swift-capable job after checkout, or add a small hosted `macos-latest` job when the repository has none. Make the hosting job a required check. The action invokes the pinned Swift validator; it downloads only canonical policy text and never runs executable code from a newly discovered tag. Do not run consumer scripts to validate policy text. + +The validator resolves the highest published `codex-review-vN` tag once per invocation, verifies the fetched tag object, peels its commit, checks that `ReviewPolicy/VERSION` agrees, and compares the exact managed contracts and provenance. Missing/modified/obsolete/duplicated sections, incorrect profile/source, older policy revisions, unavailable sources, and uncertain tag identity fail closed. An unrelated guideline release leaves the review-policy tag unchanged and does not force review-only updates. + +A green CI run cannot invalidate itself when a later policy tag appears. The executor must rerun the latest-policy check immediately before merge. Publishing a policy revision includes a coordinated consumer rollout; CI never edits files, opens PRs, or merges updates itself. Keep consumer inventories and private repository names in the authorized local task, not in this public repository. + +## Publishing and bootstrapping + +Change the canonical contracts, increment the independent policy revision, synchronize mirrors, and validate through the central PR. Prepare the regular guidelines release metadata as usual. After the reviewed release commit is merged and validated, publish its normal guidelines tag/release, then create the immutable `codex-review-vN` tag at that same commit. Never move a published policy tag. Only policy changes need a new policy tag; all other guidelines releases retain the existing policy revision. + +The central PR and release validation use owned local policy data, allowing a new revision to be tested before publication. The first consumer rollout starts only after the policy tag is public. Central development commands are: + +```sh +Scripts/sync_codex_review_policy.swift update --local-source . --profile central +Scripts/sync_codex_review_policy.swift update --local-source . --profile template --agents-file Templates/AGENTS.md +Scripts/sync_codex_review_policy.swift check --local-source . --profile central +``` + +Synchronize the global template's review-only section from the same canonical reviewer block. Copy the global template into user-level Codex instructions; copy only its reviewer section into Settings → Code Review → Review Instructions for reviews started with Review with Codex. These settings are a matching user-level layer, not the source of automatic GitHub review policy. Configure all PR authors, opening/ready triggers, exhaustive review off, and separate automatic Security Review off. Record repository-specific configuration outside managed contracts. diff --git a/ReviewPolicy/VERSION b/ReviewPolicy/VERSION new file mode 100644 index 0000000..d00491f --- /dev/null +++ b/ReviewPolicy/VERSION @@ -0,0 +1 @@ +1 diff --git a/Scripts/prepare_localizable_symbols.swift b/Scripts/prepare_localizable_symbols.swift new file mode 100755 index 0000000..220de6f --- /dev/null +++ b/Scripts/prepare_localizable_symbols.swift @@ -0,0 +1,236 @@ +#!/usr/bin/env swift +import Foundation + +#if canImport(Darwin) + import Darwin +#else + import Glibc +#endif + +/// Marks every source-language string unit in a localization as translated. +func markStringUnitsTranslated(_ value: Any) -> Any { + if var dictionary = value as? [String: Any] { + if var stringUnit = dictionary["stringUnit"] as? [String: Any] { + stringUnit["state"] = "translated" + dictionary["stringUnit"] = stringUnit + } + for (key, child) in dictionary { + dictionary[key] = markStringUnitsTranslated(child) + } + return dictionary + } + if let array = value as? [Any] { + return array.map(markStringUnitsTranslated) + } + return value +} + +/// Returns one symbol-ready entry while preserving comments and translations. +func prepareEntry(key: String, entry: [String: Any], sourceLanguage: String) throws -> [String: Any] { + if entry["extractionState"] as? String == "stale" { + return entry + } + var localizations = entry["localizations"] as? [String: Any] ?? [:] + if let sourceLocalization = localizations[sourceLanguage] as? [String: Any] { + localizations[sourceLanguage] = markStringUnitsTranslated(sourceLocalization) + } else { + if entry["extractionState"] as? String == "manual" { + throw NSError( + domain: "SymbolPreparation", code: 1, + userInfo: [ + NSLocalizedDescriptionKey: "\(key): manual entry has no \(sourceLanguage) source value" + ]) + } + localizations[sourceLanguage] = [ + "stringUnit": [ + "state": "translated", + "value": key, + ] + ] + } + var prepared = entry + prepared["extractionState"] = "manual" + prepared["localizations"] = localizations + return prepared +} + +/// Returns a catalog whose active entries generate localized Swift symbols. +func prepareCatalog(_ catalog: [String: Any]) throws -> [String: Any] { + guard let sourceLanguage = catalog["sourceLanguage"] as? String, !sourceLanguage.isEmpty else { + throw NSError( + domain: "SymbolPreparation", code: 1, + userInfo: [ + NSLocalizedDescriptionKey: "catalog has no sourceLanguage" + ]) + } + guard let strings = catalog["strings"] as? [String: Any] else { + throw NSError( + domain: "SymbolPreparation", code: 1, + userInfo: [ + NSLocalizedDescriptionKey: "catalog has no strings dictionary" + ]) + } + var preparedStrings: [String: Any] = [:] + for key in strings.keys.sorted() { + guard let entry = strings[key] as? [String: Any] else { + throw NSError( + domain: "SymbolPreparation", code: 1, + userInfo: [ + NSLocalizedDescriptionKey: "catalog contains a non-dictionary string entry" + ]) + } + preparedStrings[key] = try prepareEntry(key: key, entry: entry, sourceLanguage: sourceLanguage) + } + var prepared = catalog + prepared["strings"] = preparedStrings + return prepared +} + +/// Returns active catalog entries that cannot generate expected Swift symbols. +func symbolIssues(_ catalog: [String: Any]) -> [String] { + guard let sourceLanguage = catalog["sourceLanguage"] as? String, + let strings = catalog["strings"] as? [String: Any] + else { + return ["catalog structure is invalid"] + } + var issues: [String] = [] + for key in strings.keys.sorted() { + guard let entry = strings[key] as? [String: Any] else { + issues.append("\(key): entry is not a dictionary") + continue + } + if entry["extractionState"] as? String == "stale" { + continue + } + if entry["extractionState"] as? String != "manual" { + issues.append("\(key): extractionState is not manual") + } + let localizations = entry["localizations"] as? [String: Any] + if localizations?[sourceLanguage] as? [String: Any] == nil { + issues.append("\(key): source localization \(sourceLanguage) is missing") + } + } + return issues +} + +/// Renders a JSON string scalar. +func renderJSONString(_ value: String) throws -> String { + let data = try JSONSerialization.data(withJSONObject: [value]) + let rendered = String(data: data, encoding: .utf8) ?? "[]" + return String(rendered.dropFirst().dropLast()) +} + +/// Renders JSON with deterministic Xcode-style spacing. +func renderJSON(_ value: Any, indentation: Int = 0) throws -> String { + if let dictionary = value as? [String: Any] { + if dictionary.isEmpty { + return "{}" + } + let keys = dictionary.keys.sorted() + var lines = ["{"] + for (index, key) in keys.enumerated() { + guard let child = dictionary[key] else { + continue + } + var rendered = try renderJSON(child, indentation: indentation + 2).components(separatedBy: "\n") + let prefix = String(repeating: " ", count: indentation + 2) + (try renderJSONString(key)) + " : " + rendered[0] = prefix + rendered[0] + if index < keys.count - 1 { + rendered[rendered.count - 1] += "," + } + lines.append(contentsOf: rendered) + } + lines.append(String(repeating: " ", count: indentation) + "}") + return lines.joined(separator: "\n") + } + if let array = value as? [Any] { + if array.isEmpty { + return "[]" + } + var lines = ["["] + for (index, child) in array.enumerated() { + var rendered = try renderJSON(child, indentation: indentation + 2).components(separatedBy: "\n") + rendered[0] = String(repeating: " ", count: indentation + 2) + rendered[0] + if index < array.count - 1 { + rendered[rendered.count - 1] += "," + } + lines.append(contentsOf: rendered) + } + lines.append(String(repeating: " ", count: indentation) + "]") + return lines.joined(separator: "\n") + } + let data = try JSONSerialization.data(withJSONObject: value, options: [.fragmentsAllowed]) + guard let rendered = String(data: data, encoding: .utf8) else { + throw NSError( + domain: "SymbolPreparation", code: 1, + userInfo: [ + NSLocalizedDescriptionKey: "could not render JSON value" + ]) + } + return rendered +} + +/// Returns whether two JSON objects are semantically equal. +func jsonObjectsEqual(_ lhs: Any, _ rhs: Any) -> Bool { + (lhs as AnyObject).isEqual(rhs) +} + +/// Writes text to standard error. +func writeError(_ value: String) { + FileHandle.standardError.write(Data((value + "\n").utf8)) +} + +/// Prepares explicit catalogs in place or checks whether preparation is needed. +func main() -> Int32 { + var checkOnly = false + var catalogs: [String] = [] + for argument in CommandLine.arguments.dropFirst() { + if argument == "--check" { + checkOnly = true + } else if argument == "--help" { + print("Usage: prepare_localizable_symbols.swift [--check]") + return 0 + } else if argument.hasPrefix("-") { + writeError("Unknown argument: \(argument)") + return 2 + } else { + catalogs.append(argument) + } + } + guard !catalogs.isEmpty else { + writeError("At least one String Catalog path is required.") + return 2 + } + var failed = false + for path in catalogs { + do { + let data = try Data(contentsOf: URL(fileURLWithPath: path)) + guard let catalog = try JSONSerialization.jsonObject(with: data) as? [String: Any] else { + throw NSError( + domain: "SymbolPreparation", code: 1, + userInfo: [ + NSLocalizedDescriptionKey: "catalog root is not a dictionary" + ]) + } + let prepared = try prepareCatalog(catalog) + if jsonObjectsEqual(prepared, catalog) { + print("\(path): already symbol-ready.") + continue + } + if checkOnly { + writeError("\(path): run this script without --check to prepare generated symbols.") + failed = true + continue + } + try (renderJSON(prepared) + "\n").write(toFile: path, atomically: true, encoding: .utf8) + let count = (prepared["strings"] as? [String: Any])?.count ?? 0 + print("\(path): prepared \(count) generated symbols.") + } catch { + writeError("\(path): \(error.localizedDescription)") + failed = true + } + } + return failed ? 1 : 0 +} + +exit(main()) diff --git a/AgentGuidelines/Scripts/swift_format.sh b/Scripts/swift_format.sh similarity index 100% rename from AgentGuidelines/Scripts/swift_format.sh rename to Scripts/swift_format.sh diff --git a/Scripts/sync_codex_review_policy.swift b/Scripts/sync_codex_review_policy.swift new file mode 100755 index 0000000..b8cdca0 --- /dev/null +++ b/Scripts/sync_codex_review_policy.swift @@ -0,0 +1,283 @@ +#!/usr/bin/env swift +import Foundation + +#if canImport(Darwin) + import Darwin +#else + import Glibc +#endif + +// MARK: - Policy identity + +/// The only production source of published policy text. +let policyRepository = "https://github.com/thatfactory/agent-guidelines.git" +let scriptRoot = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent() +let families = ["CODE REVIEW", "PR LIFECYCLE"] +let provenancePrefix = "", in: text) + let ends = try regions("", in: text) + let blocks = try regions("[\\s\\S]*?", in: text) + guard begins.count == ends.count, begins.count == blocks.count, + text.components(separatedBy: "" +} + +/// Validates exact content, policy freshness, profile, and immutable source identity. +func check(_ text: String, snapshot: Snapshot, profile: String) throws { + let metadata = try regions("", in: text) + guard metadata.count == 1, text.components(separatedBy: provenancePrefix).count - 1 == 1, + metadata[0].text == provenance(snapshot, profile: profile) + else { + throw PolicyError( + "missing, outdated, duplicated, or incorrect review-policy provenance; expected \(provenance(snapshot, profile: profile))" + ) + } + for (index, family) in families.enumerated() { + let actual = try contracts(text, family: family) + guard actual.count == 1, actual[0].text == snapshot.blocks[index] else { + throw PolicyError("missing, obsolete, duplicated, or modified \(family.lowercased()) contract") + } + } +} + +/// Replaces only complete managed regions, preserving every byte of local instructions. +func updated(_ text: String, snapshot: Snapshot, profile: String) throws -> String { + if (try? check(text, snapshot: snapshot, profile: profile)) != nil { return text } + var managed = try families.flatMap { try contracts(text, family: $0) } + managed += try regions("", in: text) + let payload = provenance(snapshot, profile: profile) + "\n" + snapshot.blocks.joined(separator: "\n\n") + guard !managed.isEmpty else { return text + (text.hasSuffix("\n\n") ? "" : "\n\n") + payload + "\n" } + managed.sort { $0.range.lowerBound < $1.range.lowerBound } + var result = "" + var cursor = text.startIndex + for (index, region) in managed.enumerated() { + guard region.range.lowerBound >= cursor else { throw PolicyError("overlapping managed regions") } + result += text[cursor.. Options { + var result = Options() + guard let mode = values.first, ["check", "update"].contains(mode) else { + throw PolicyError( + "Usage: sync_codex_review_policy.swift check|update [--consumer-root ] [--profile full|review-only] [--local-source --profile central|template] [--agents-file ] [--policy-repository ]" + ) + } + result.mode = mode + var index = 1 + while index < values.count { + guard index + 1 < values.count else { throw PolicyError("missing value for \(values[index])") } + let value = values[index + 1] + switch values[index] { + case "--consumer-root": result.roots.append(URL(fileURLWithPath: value).standardizedFileURL) + case "--profile": result.profile = value + case "--local-source": result.localSource = URL(fileURLWithPath: value).standardizedFileURL + case "--policy-repository": result.repository = value + case "--agents-file": + guard !value.hasPrefix("/"), !value.split(separator: "/").contains("..") else { + throw PolicyError("--agents-file must stay within the consumer root") + } + result.agentsFile = value + default: throw PolicyError("unknown argument: \(values[index])") + } + index += 2 + } + if result.roots.isEmpty { result.roots = [URL(fileURLWithPath: FileManager.default.currentDirectoryPath)] } + return result +} + +/// Synchronizes all requested roots against one verified source and reports every failed root. +func main() -> Int32 { + do { + let options = try parse(Array(CommandLine.arguments.dropFirst())) + let snapshot = try loadSnapshot(options) + var failures = 0 + for root in options.roots { + do { + let profile = try profile(for: root, options: options) + let file = root.appendingPathComponent(options.agentsFile) + let original = try String(contentsOf: file, encoding: .utf8) + if options.mode == "update" { + let replacement = try updated(original, snapshot: snapshot, profile: profile) + if replacement != original { try replacement.write(to: file, atomically: true, encoding: .utf8) } + } + let final = try String(contentsOf: file, encoding: .utf8) + try check(final, snapshot: snapshot, profile: profile) + print( + "Validated \(root.lastPathComponent): \(profile), review policy \(snapshot.revision), source \(snapshot.commit)." + ) + } catch { + failures += 1 + FileHandle.standardError.write(Data("\(root.lastPathComponent): \(error)\n".utf8)) + } + } + return failures == 0 ? 0 : 1 + } catch { + FileHandle.standardError.write(Data("Review policy verification failed: \(error)\n".utf8)) + return 1 + } +} + +exit(main()) diff --git a/Scripts/validate_consumer_setup.swift b/Scripts/validate_consumer_setup.swift new file mode 100755 index 0000000..1e17b99 --- /dev/null +++ b/Scripts/validate_consumer_setup.swift @@ -0,0 +1,474 @@ +#!/usr/bin/env swift +import Foundation + +#if canImport(Darwin) + import Darwin +#else + import Glibc +#endif + +let guidelinesRoot = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent() +let contractBegin = "" +let contractEnd = "" +let lifecycleContractBegin = "" +let lifecycleContractEnd = "" +let documentationContractBegin = "" +let documentationContractEnd = "" +let externalDependencyContractBegin = "" +let externalDependencyContractEnd = "" +let observabilityContractBegin = "" +let observabilityContractEnd = "" +let markdownLinkPattern = #"\[[^\]]+\]\(([^)]+)\)"# +let swiftFormatGuide = "AgentGuidelines/Guidelines/Swift/SwiftFormat.md" +let strictFormatCommandPattern = + #"(?m)^[ \t]*(?:-\s+)?(?:run:\s*)?(?:\./)?AgentGuidelines/Scripts/swift_format\.sh\s+lint-strict(?=\s|\\|$)"# +let mutatingFormatCommandPattern = + #"(?m)^[ \t]*(?:-\s+)?(?:run:\s*)?(?:\./)?AgentGuidelines/Scripts/swift_format\.sh\s+format(?:-and-lint)?(?=\s|\\|$)"# +let generatedAttributePattern = #"(?m)^\s*AgentGuidelines/\*\*\s+linguist-generated\s*$"# +let readmeLicenseHeadingPattern = #"(?im)^[ \t]{0,3}#{1,6}[ \t]+license[ \t]*#*[ \t]*$"# +let readmeSetextUnderlinePattern = #"^[ \t]{0,3}(?:=+|-+)[ \t]*$"# +let readmeLicenseParagraphPattern = + #"(?i)^.+?\s+is\s+available\s+under\s+the\s+.+?\s+license\.\s+See\s+\[LICENSE\]\((?:\./)?LICENSE\)\.$"# + +/// Parsed consumer-validation command-line values. +struct Arguments { + var consumerRoot: String? + var requireSwiftFormat = false +} + +/// Returns all regular-expression matches in a string. +func matches(_ pattern: String, in value: String) -> [NSTextCheckingResult] { + guard let expression = try? NSRegularExpression(pattern: pattern) else { + return [] + } + return expression.matches(in: value, range: NSRange(value.startIndex.. String? { + let range = match.range(at: index) + guard range.location != NSNotFound, let swiftRange = Range(range, in: value) else { + return nil + } + return String(value[swiftRange]) +} + +/// Reads UTF-8 text and records a labeled error on failure. +func readText(_ url: URL, errors: inout [String], label: String) -> String? { + do { + return try String(contentsOf: url, encoding: .utf8) + } catch { + errors.append("\(label): cannot read \(url.path): \(error.localizedDescription)") + return nil + } +} + +/// Extracts one uniquely marked contract block. +func extractMarkedBlock( + _ contents: String, + begin: String, + end: String, + errors: inout [String], + label: String +) -> String? { + guard contents.components(separatedBy: begin).count - 1 == 1, + contents.components(separatedBy: end).count - 1 == 1, + let start = contents.range(of: begin), + let finish = contents.range(of: end, range: start.upperBound..")) + target = target.components(separatedBy: "#").first ?? target + if target.isEmpty || ["#", "http://", "https://", "mailto:"].contains(where: target.hasPrefix) { + continue + } + let resolved = agentsURL.deletingLastPathComponent().appendingPathComponent(target).standardizedFileURL + if !FileManager.default.fileExists(atPath: resolved.path) { + errors.append("AGENTS.md: missing local link target '\(target)'") + } + } +} + +/// Returns whether root instructions link the shared Swift-format guide. +func adoptsSwiftFormat(_ contents: String) -> Bool { + for match in matches(markdownLinkPattern, in: contents) { + guard var target = capture(1, from: match, in: contents) else { + continue + } + target = target.trimmingCharacters(in: .whitespacesAndNewlines).trimmingCharacters( + in: CharacterSet(charactersIn: "<>")) + target = target.components(separatedBy: "#").first ?? target + if target.hasSuffix(swiftFormatGuide) { + return true + } + } + return false +} + +/// Returns complete shell invocations matching a command pattern. +func shellInvocations(_ contents: String, pattern: String) -> [String] { + let lines = contents.components(separatedBy: .newlines) + var invocations: [String] = [] + var index = 0 + while index < lines.count { + let line = lines[index] + if line.trimmingCharacters(in: .whitespaces).hasPrefix("#") || matches(pattern, in: line).isEmpty { + index += 1 + continue + } + var invocation = [line] + while invocation.last?.trimmingCharacters(in: .whitespaces).hasSuffix("\\") == true, + index + 1 < lines.count + { + index += 1 + invocation.append(lines[index]) + } + invocations.append(invocation.joined(separator: "\n")) + index += 1 + } + return invocations +} + +/// Returns direct files with one of the requested extensions. +func files(in directory: URL, extensions: Set) -> [URL] { + guard + let values = try? FileManager.default.contentsOfDirectory( + at: directory, + includingPropertiesForKeys: [.isRegularFileKey], + options: [.skipsHiddenFiles] + ) + else { + return [] + } + return values.filter { extensions.contains($0.pathExtension.lowercased()) }.sorted { $0.path < $1.path } +} + +/// Returns a Markdown fence marker and run length when a line can open or close a fenced code block. +func markdownFence(in line: String) -> (character: Character, length: Int, suffix: Substring)? { + let indentation = line.prefix(while: { $0 == " " }).count + let content = line.dropFirst(indentation) + guard indentation <= 3, let character = content.first, character == "`" || character == "~" + else { + return nil + } + let length = content.prefix(while: { $0 == character }).count + guard length >= 3 else { return nil } + return (character, length, content.dropFirst(length)) +} + +/// Returns whether a line is eligible to be the title of a Setext License heading. +func isSetextLicenseTitle(_ line: String) -> Bool { + let indentation = line.prefix(while: { $0 == " " }).count + guard indentation <= 3 else { return false } + return line.dropFirst(indentation).trimmingCharacters(in: .whitespaces) + .localizedCaseInsensitiveCompare("License") == .orderedSame +} + +/// Validates package README license content without inspecting vendored or non-package documentation. +func validatePackageReadme(consumerRoot: URL, errors: inout [String]) { + guard FileManager.default.fileExists(atPath: consumerRoot.appendingPathComponent("Package.swift").path) else { + return + } + let readmeURL = consumerRoot.appendingPathComponent("README.md") + guard FileManager.default.fileExists(atPath: readmeURL.path), + let contents = readText(readmeURL, errors: &errors, label: "consumer package README") + else { + return + } + var outsideFences: [String] = [] + var activeFence: (character: Character, length: Int)? + for line in contents.components(separatedBy: .newlines) { + if let currentFence = activeFence { + if let marker = markdownFence(in: line), marker.character == currentFence.character, + marker.length >= currentFence.length, + marker.suffix.trimmingCharacters(in: .whitespaces).isEmpty + { + activeFence = nil + } + outsideFences.append("") + } else if let marker = markdownFence(in: line), + marker.character == "~" || !marker.suffix.contains("`") + { + activeFence = (marker.character, marker.length) + outsideFences.append("") + } else { + outsideFences.append(line) + } + } + let governedContents = outsideFences.joined(separator: "\n") + let lines = governedContents.components(separatedBy: .newlines) + let hasSetextLicenseHeading = lines.indices.dropLast().contains { index in + isSetextLicenseTitle(lines[index]) && !matches(readmeSetextUnderlinePattern, in: lines[index + 1]).isEmpty + } + if !matches(readmeLicenseHeadingPattern, in: governedContents).isEmpty || hasSetextLicenseHeading { + errors.append("consumer package README: README.md must not contain a dedicated License heading") + } + let paragraphs = governedContents.components(separatedBy: "\n\n").map { + $0.split(whereSeparator: \.isNewline).joined(separator: " ") + .trimmingCharacters(in: .whitespacesAndNewlines) + } + if paragraphs.contains(where: { !matches(readmeLicenseParagraphPattern, in: $0).isEmpty }) { + errors.append("consumer package README: README.md must not contain a standalone license-description paragraph") + } +} + +/// Validates non-mutating Swift-format CI integration. +func validateSwiftFormatCI(consumerRoot: URL, errors: inout [String]) { + let workflowsRoot = consumerRoot.appendingPathComponent(".github/workflows") + let workflows = files(in: workflowsRoot, extensions: ["yml", "yaml"]) + if workflows.isEmpty { + errors.append("consumer Swift format CI: no GitHub Actions workflows found under .github/workflows") + return + } + var strictWorkflows: [(URL, String, [String])] = [] + for workflow in workflows { + let relative = workflow.path.replacingOccurrences(of: consumerRoot.path + "/", with: "") + guard let contents = readText(workflow, errors: &errors, label: "consumer Swift format CI workflow \(relative)") + else { + continue + } + if !shellInvocations(contents, pattern: mutatingFormatCommandPattern).isEmpty { + errors.append( + "consumer Swift format CI: \(relative) must not mutate sources with format or format-and-lint") + } + let invocations = shellInvocations(contents, pattern: strictFormatCommandPattern) + if !invocations.isEmpty { + strictWorkflows.append((workflow, contents, invocations)) + } + } + if strictWorkflows.isEmpty { + errors.append( + "consumer Swift format CI: missing 'AgentGuidelines/Scripts/swift_format.sh lint-strict' invocation") + return + } + if !strictWorkflows.contains(where: { !matches(#"(?m)^\s*pull_request\s*:"#, in: $0.1).isEmpty }) { + errors.append("consumer Swift format CI: lint-strict does not run for pull requests") + } + let pushPattern = #"(?m)^\s*push\s*:"# + let mainPattern = #"(?m)^\s*-?\s*main\s*$|branches\s*:\s*\[[^]]*\bmain\b"# + if !strictWorkflows.contains(where: { + !matches(pushPattern, in: $0.1).isEmpty && !matches(mainPattern, in: $0.1).isEmpty + }) { + errors.append("consumer Swift format CI: lint-strict does not run for pushes to main") + } + if FileManager.default.fileExists(atPath: consumerRoot.appendingPathComponent("Package.swift").path) { + var requiredPaths = ["Package.swift"] + for name in ["Sources", "Tests"] { + var isDirectory: ObjCBool = false + if FileManager.default.fileExists( + atPath: consumerRoot.appendingPathComponent(name).path, + isDirectory: &isDirectory + ), isDirectory.boolValue { + requiredPaths.append(name) + } + } + let combined = strictWorkflows.flatMap(\.2).joined(separator: "\n") + for path in requiredPaths { + let escaped = NSRegularExpression.escapedPattern(for: path) + if matches("(? Arguments { + var arguments = Arguments() + var index = 0 + while index < values.count { + let value = values[index] + switch value { + case "--help": + print("Usage: validate_consumer_setup.swift [--consumer-root ] [--require-swift-format]") + exit(0) + case "--require-swift-format": + arguments.requireSwiftFormat = true + index += 1 + case "--consumer-root": + guard index + 1 < values.count else { + throw NSError( + domain: "ConsumerSetup", code: 2, + userInfo: [ + NSLocalizedDescriptionKey: "missing value for --consumer-root" + ]) + } + arguments.consumerRoot = values[index + 1] + index += 2 + default: + throw NSError( + domain: "ConsumerSetup", code: 2, + userInfo: [ + NSLocalizedDescriptionKey: "unknown argument: \(value)" + ]) + } + } + return arguments +} + +/// Writes text to standard error. +func writeError(_ value: String) { + FileHandle.standardError.write(Data((value + "\n").utf8)) +} + +/// Runs consumer integration validation. +func main() -> Int32 { + do { + let arguments = try parseArguments(Array(CommandLine.arguments.dropFirst())) + let root: URL + if let consumerRoot = arguments.consumerRoot { + root = URL(fileURLWithPath: consumerRoot) + } else { + guard guidelinesRoot.lastPathComponent == "AgentGuidelines" else { + print( + "Consumer setup validation failed:\n" + + "- --consumer-root is required when this checkout is not installed as an AgentGuidelines subtree" + ) + return 1 + } + root = guidelinesRoot.deletingLastPathComponent() + } + var errors: [String] = [] + validateConsumerSetup( + errors: &errors, + consumerRoot: root, + requireSwiftFormat: arguments.requireSwiftFormat + ) + if !errors.isEmpty { + print("Consumer setup validation failed:") + for error in errors { print("- \(error)") } + return 1 + } + let version = try String( + contentsOf: guidelinesRoot.appendingPathComponent("VERSION"), + encoding: .utf8 + ).trimmingCharacters(in: .whitespacesAndNewlines) + print("Validated consumer setup for agent-guidelines \(version).") + return 0 + } catch { + writeError("Consumer setup validation failed: \(error.localizedDescription)") + return 2 + } +} + +exit(main()) diff --git a/Scripts/validate_guidelines.swift b/Scripts/validate_guidelines.swift new file mode 100755 index 0000000..4550257 --- /dev/null +++ b/Scripts/validate_guidelines.swift @@ -0,0 +1,1145 @@ +#!/usr/bin/env swift +import Foundation + +#if canImport(Darwin) + import Darwin +#else + import Glibc +#endif + +let root = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent() +let readme = root.appendingPathComponent("README.md") +let versionFile = root.appendingPathComponent("VERSION") +let changelog = root.appendingPathComponent("CHANGELOG.md") +let swiftFormatConfiguration = root.appendingPathComponent("Configurations/Swift/.swift-format") +let editorConfiguration = root.appendingPathComponent("Configurations/Swift/.editorconfig") +let swiftFormatScript = root.appendingPathComponent("Scripts/swift_format.sh") +let swiftFormatGuideline = root.appendingPathComponent("Guidelines/Swift/SwiftFormat.md") +let swiftUIGuideline = root.appendingPathComponent("Guidelines/Swift/SwiftUI.md") +let localizationGuideline = root.appendingPathComponent("Guidelines/Localization.md") +let appStoreGuideline = root.appendingPathComponent("Guidelines/AppStore.md") +let xcodeProjectSettingsGuideline = root.appendingPathComponent("Guidelines/Xcode/ProjectSettings.md") +let localizationPreparationScript = root.appendingPathComponent("Scripts/prepare_localizable_symbols.swift") +let localizationValidationScript = root.appendingPathComponent("Scripts/validate_string_catalogs.swift") +let consumerSetupScript = root.appendingPathComponent("Scripts/validate_consumer_setup.swift") +let testRunner = root.appendingPathComponent("Tests/run_tests.swift") +let auditSkill = root.appendingPathComponent(".agents/skills/agent-guidelines-audit/SKILL.md") +let markdownWrappingScript = root.appendingPathComponent( + ".agents/skills/agent-guidelines-audit/scripts/check_markdown_wrapping.swift" +) +let stringCatalogInspectionScript = root.appendingPathComponent( + ".agents/skills/agent-guidelines-audit/scripts/check_xcstrings_inspection.swift" +) +let developmentGuideline = root.appendingPathComponent("Guidelines/Development.md") +let cicdGuideline = root.appendingPathComponent("Guidelines/CICD.md") +let documentationGuideline = root.appendingPathComponent("Guidelines/Documentation.md") +let packagesGuideline = root.appendingPathComponent("Guidelines/Packages.md") +let agentsTemplate = root.appendingPathComponent("Templates/AGENTS.md") +let pullRequestsGuideline = root.appendingPathComponent("Guidelines/GitHub/PullRequests.md") +let gitignoreTemplate = root.appendingPathComponent("Templates/.gitignore") +let gitignoreGuideline = root.appendingPathComponent("Guidelines/Git/IgnoreFiles.md") + +let expectedSwiftFormatRules: [String: Bool] = [ + "AllPublicDeclarationsHaveDocumentation": false, + "AlwaysUseLiteralForEmptyCollectionInit": true, + "AlwaysUseLowerCamelCase": true, + "AmbiguousTrailingClosureOverload": true, + "AvoidRetroactiveConformances": true, + "BeginDocumentationCommentWithOneLineSummary": false, + "DoNotUseSemicolons": true, + "DontRepeatTypeInStaticProperties": true, + "FileScopedDeclarationPrivacy": true, + "FullyIndirectEnum": true, + "GroupNumericLiterals": true, + "IdentifiersMustBeASCII": true, + "NeverForceUnwrap": false, + "NeverUseForceTry": true, + "NeverUseImplicitlyUnwrappedOptionals": false, + "NoAccessLevelOnExtensionDeclaration": true, + "NoAssignmentInExpressions": true, + "NoBlockComments": true, + "NoCasesWithOnlyFallthrough": true, + "NoEmptyLinesOpeningClosingBraces": true, + "NoEmptyTrailingClosureParentheses": true, + "NoLabelsInCasePatterns": true, + "NoLeadingUnderscores": false, + "NoParensAroundConditions": true, + "NoPlaygroundLiterals": true, + "NoVoidReturnOnFunctionSignature": true, + "OmitExplicitReturns": false, + "OneCasePerLine": true, + "OneVariableDeclarationPerLine": true, + "OnlyOneTrailingClosureArgument": true, + "OrderedImports": true, + "ReplaceForEachWithForLoop": true, + "ReturnVoidInsteadOfEmptyTuple": true, + "TypeNamesShouldBeCapitalized": true, + "UseEarlyExits": false, + "UseExplicitNilCheckInConditions": true, + "UseLetInEveryBoundCaseVariable": true, + "UseShorthandTypeNames": true, + "UseSingleLinePropertyGetter": true, + "UseSynthesizedInitializer": true, + "UseTripleSlashForDocumentationComments": true, + "UseWhereClausesInForLoops": true, + "ValidateDocumentationComments": true, +] + +let markdownLinkPattern = #"\[[^\]]+\]\(([^)]+)\)"# +let semanticVersionPattern = + #"^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(?:-((?:0|[1-9][0-9]*|[0-9]*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9][0-9]*|[0-9]*[A-Za-z-][0-9A-Za-z-]*))*))?(?:\+([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$"# +let forbiddenContent = [ + "/" + "Users" + "/": "personal absolute path", + "file" + "://": "local file URL", + "mobile-ios-" + "chauffeur": "work-repository identifier", + "black" + "lane": "work-repository identifier", +] +let upcomingFeatureSettings = [ + "SWIFT_UPCOMING_FEATURE_CONCISE_MAGIC_FILE", + "SWIFT_UPCOMING_FEATURE_DEPRECATE_APPLICATION_MAIN", + "SWIFT_UPCOMING_FEATURE_DISABLE_OUTWARD_ACTOR_ISOLATION", + "SWIFT_UPCOMING_FEATURE_DYNAMIC_ACTOR_ISOLATION", + "SWIFT_UPCOMING_FEATURE_EXISTENTIAL_ANY", + "SWIFT_UPCOMING_FEATURE_FORWARD_TRAILING_CLOSURES", + "SWIFT_UPCOMING_FEATURE_GLOBAL_ACTOR_ISOLATED_TYPES_USABILITY", + "SWIFT_UPCOMING_FEATURE_GLOBAL_CONCURRENCY", + "SWIFT_UPCOMING_FEATURE_IMPLICIT_OPEN_EXISTENTIALS", + "SWIFT_UPCOMING_FEATURE_IMPORT_OBJC_FORWARD_DECLS", + "SWIFT_UPCOMING_FEATURE_INFER_ISOLATED_CONFORMANCES", + "SWIFT_UPCOMING_FEATURE_INFER_SENDABLE_FROM_CAPTURES", + "SWIFT_UPCOMING_FEATURE_INTERNAL_IMPORTS_BY_DEFAULT", + "SWIFT_UPCOMING_FEATURE_ISOLATED_DEFAULT_VALUES", + "SWIFT_UPCOMING_FEATURE_MEMBER_IMPORT_VISIBILITY", + "SWIFT_UPCOMING_FEATURE_NONFROZEN_ENUM_EXHAUSTIVITY", + "SWIFT_UPCOMING_FEATURE_NONISOLATED_NONSENDING_BY_DEFAULT", + "SWIFT_UPCOMING_FEATURE_REGION_BASED_ISOLATION", +] +let packageUpcomingFeatures = [ + "ExistentialAny", + "InferIsolatedConformances", + "InternalImportsByDefault", + "MemberImportVisibility", + "NonisolatedNonsendingByDefault", +] + +/// Returns all regular-expression matches in a string. +func matches(_ pattern: String, in value: String) -> [NSTextCheckingResult] { + guard let expression = try? NSRegularExpression(pattern: pattern) else { + return [] + } + return expression.matches(in: value, range: NSRange(value.startIndex.. String? { + let range = match.range(at: index) + guard range.location != NSNotFound, let swiftRange = Range(range, in: value) else { + return nil + } + return String(value[swiftRange]) +} + +/// Returns a repository-relative path. +func relativePath(_ url: URL) -> String { + url.standardizedFileURL.path.replacingOccurrences(of: root.standardizedFileURL.path + "/", with: "") +} + +/// Reads UTF-8 text or records an error. +func readText(_ url: URL, errors: inout [String]) -> String? { + do { + return try String(contentsOf: url, encoding: .utf8) + } catch { + errors.append("\(relativePath(url)): cannot read file: \(error.localizedDescription)") + return nil + } +} + +/// Recursively discovers regular files while excluding repository internals and build caches. +func recursiveFiles(below directory: URL) -> [URL] { + guard + let enumerator = FileManager.default.enumerator( + at: directory, + includingPropertiesForKeys: [.isRegularFileKey], + options: [] + ) + else { + return [] + } + var files: [URL] = [] + for case let url as URL in enumerator { + let relative = relativePath(url) + if relative.split(separator: "/").contains(where: { $0 == ".git" || $0 == ".build" || $0 == "__pycache__" }) { + if (try? url.resourceValues(forKeys: [.isDirectoryKey]).isDirectory) == true { + enumerator.skipDescendants() + } + continue + } + if (try? url.resourceValues(forKeys: [.isRegularFileKey]).isRegularFile) == true { + files.append(url) + } + } + return files.sorted { $0.path < $1.path } +} + +/// Returns all public-text files governed by the privacy scan. +func textFiles() -> [URL] { + let suffixes: Set = ["md", "sh", "swift", "txt", "yml", "yaml"] + var files = recursiveFiles(below: root).filter { suffixes.contains($0.pathExtension.lowercased()) } + for url in [versionFile, root.appendingPathComponent("LICENSE"), swiftFormatConfiguration, editorConfiguration] + where FileManager.default.fileExists(atPath: url.path) { + files.append(url) + } + return Array(Set(files)).sorted { $0.path < $1.path } +} + +/// Resolves a relative Markdown link target within the source repository. +func resolveLink(source: URL, rawTarget: String) -> URL? { + var target = rawTarget.trimmingCharacters(in: .whitespacesAndNewlines) + .trimmingCharacters(in: CharacterSet(charactersIn: "<>")) + target = target.components(separatedBy: "#").first ?? target + if target.isEmpty || ["#", "http://", "https://", "mailto:"].contains(where: target.hasPrefix) { + return nil + } + let parts = NSString(string: target).pathComponents + if let index = parts.firstIndex(of: "AgentGuidelines") { + let suffix = parts.dropFirst(index + 1).joined(separator: "/") + return root.appendingPathComponent(suffix).standardizedFileURL + } + return source.deletingLastPathComponent().appendingPathComponent(target).standardizedFileURL +} + +/// Validates all relative Markdown link targets. +func validateLinks(_ errors: inout [String]) { + for source in recursiveFiles(below: root).filter({ $0.pathExtension.lowercased() == "md" }) { + guard let contents = readText(source, errors: &errors) else { + continue + } + for match in matches(markdownLinkPattern, in: contents) { + guard let rawTarget = capture(1, from: match, in: contents), + let resolved = resolveLink(source: source, rawTarget: rawTarget) + else { + continue + } + if !FileManager.default.fileExists(atPath: resolved.path) { + errors.append("\(relativePath(source)): missing link target '\(rawTarget)'") + } + } + } +} + +/// Validates that the README catalogs every shared guide. +func validateCatalog(_ errors: inout [String]) { + guard let contents = readText(readme, errors: &errors) else { + return + } + let guideRoot = root.appendingPathComponent("Guidelines") + for guide in recursiveFiles(below: guideRoot).filter({ $0.pathExtension.lowercased() == "md" }) { + let relative = relativePath(guide) + if !contents.contains("](\(relative))") { + errors.append("README.md: guideline is not cataloged: \(relative)") + } + } +} + +/// Validates the semantic version and matching changelog heading. +func validateVersion(_ errors: inout [String]) { + guard let version = readText(versionFile, errors: &errors)?.trimmingCharacters(in: .whitespacesAndNewlines) else { + return + } + if matches(semanticVersionPattern, in: version).isEmpty { + errors.append("VERSION: invalid semantic version '\(version)'") + } + if let contents = readText(changelog, errors: &errors), !contents.contains("## [\(version)]") { + errors.append("CHANGELOG.md: missing release heading for \(version)") + } +} + +/// Validates required README installation and integration contracts. +func validateReadmeContract(_ errors: inout [String]) { + guard let contents = readText(readme, errors: &errors) else { + return + } + if let version = readText(versionFile, errors: &errors)?.trimmingCharacters(in: .whitespacesAndNewlines), + contents.components(separatedBy: version).count - 1 != 2 + { + errors.append("README.md: installation and consumer-update commands must both use VERSION \(version)") + } + let required = [ + "alt=\"Xcode MCP\"": "Xcode MCP badge alt text", + "thatfactory/agent-guidelines/actions/workflows/ci.yml": "CI badge repository", + "--prefix=AgentGuidelines": "subtree destination", + "https://github.com/thatfactory/agent-guidelines.git": "subtree remote", + "git subtree add": "subtree installation command", + "git subtree pull": "subtree update command", + "AgentGuidelines/** linguist-generated": "generated subtree attribute", + "AgentGuidelines/Configurations/Swift/.swift-format": "swift-format symlink command", + "AgentGuidelines/Configurations/Swift/.editorconfig": "EditorConfig symlink command", + ".agents/skills/agent-guidelines-audit": "completion-audit skill setup", + "validate_consumer_setup.swift": "consumer setup validation command", + "--require-swift-format": "explicit Swift-format adoption validation", + "documentation-maintenance contract": "documentation contract synchronization", + "external-dependency contract": "external dependency contract synchronization", + "runtime-observability contract": "runtime observability contract synchronization", + ] + for (value, description) in required where !contents.contains(value) { + errors.append("README.md: missing \(description): '\(value)'") + } +} + +/// Validates that public files contain no private or consumer-specific content. +func validatePublicContent(_ errors: inout [String]) { + for url in textFiles() { + guard let contents = readText(url, errors: &errors) else { + continue + } + for (forbidden, description) in forbiddenContent + where contents.localizedCaseInsensitiveContains(forbidden) { + errors.append("\(relativePath(url)): contains \(description): '\(forbidden)'") + } + } +} + +/// Returns whether two Foundation JSON values are equal. +func jsonEqual(_ lhs: Any?, _ rhs: Any?) -> Bool { + guard let lhs, let rhs else { + return lhs == nil && rhs == nil + } + return (lhs as AnyObject).isEqual(rhs) +} + +/// Validates the shared swift-format configuration. +func validateSwiftFormatConfiguration(_ errors: inout [String]) { + let configuration: [String: Any] + do { + let data = try Data(contentsOf: swiftFormatConfiguration) + guard let parsed = try JSONSerialization.jsonObject(with: data) as? [String: Any] else { + throw NSError( + domain: "GuidelineValidation", code: 1, + userInfo: [ + NSLocalizedDescriptionKey: "root value is not an object" + ]) + } + configuration = parsed + } catch { + errors.append("Configurations/Swift/.swift-format: invalid JSON: \(error.localizedDescription)") + return + } + let expectedValues: [String: Any] = [ + "indentation": ["spaces": 4], + "indentSwitchCaseLabels": false, + "lineLength": 120, + "tabWidth": 4, + "version": 1, + ] + for (key, expected) in expectedValues where !jsonEqual(configuration[key], expected) { + errors.append( + "Configurations/Swift/.swift-format: \(key) must be \(expected), found \(String(describing: configuration[key]))" + ) + } + let orderedImports = configuration["orderedImports"] as? [String: Any] + if orderedImports?["includeConditionalImports"] as? Bool != true { + errors.append( + "Configurations/Swift/.swift-format: orderedImports.includeConditionalImports must be true, found " + + String(describing: orderedImports?["includeConditionalImports"]) + ) + } + guard let rules = configuration["rules"] as? [String: Any], !rules.isEmpty else { + errors.append("Configurations/Swift/.swift-format: rules must be an exhaustive non-empty object") + return + } + let expectedKeys = Set(expectedSwiftFormatRules.keys) + let actualKeys = Set(rules.keys) + let missing = expectedKeys.subtracting(actualKeys).sorted() + let unexpected = actualKeys.subtracting(expectedKeys).sorted() + if !missing.isEmpty || !unexpected.isEmpty { + errors.append( + "Configurations/Swift/.swift-format: rule map mismatch; missing=\(missing), unexpected=\(unexpected)") + } + for rule in expectedKeys.intersection(actualKeys).sorted() { + let expected = expectedSwiftFormatRules[rule] ?? false + if rules[rule] as? Bool != expected { + errors.append( + "Configurations/Swift/.swift-format: \(rule) must be " + + "\(expected), found \(String(describing: rules[rule]))" + ) + } + } +} + +/// Validates the shared EditorConfig values. +func validateEditorConfiguration(_ errors: inout [String]) { + guard let contents = readText(editorConfiguration, errors: &errors) else { + return + } + let required = [ + "root = true", "[*.swift]", "indent_style = space", "indent_size = 4", "tab_width = 4", + "max_line_length = 120", "end_of_line = lf", "insert_final_newline = true", + "trim_trailing_whitespace = true", + ] + for value in required.sorted() where !contents.contains(value) { + errors.append("Configurations/Swift/.editorconfig: missing '\(value)'") + } +} + +/// Validates that an expected executable file exists. +func validateExecutable(_ url: URL, description: String, errors: inout [String]) { + guard FileManager.default.fileExists(atPath: url.path) else { + errors.append("\(relativePath(url)): missing \(description)") + return + } + if !FileManager.default.isExecutableFile(atPath: url.path) { + errors.append("\(relativePath(url)): \(description) is not executable") + } +} + +/// Validates native Swift ownership for repository automation. +func validateScriptLanguages(_ errors: inout [String]) { + let scriptsRoot = root.appendingPathComponent("Scripts") + let allowedShellPath = "Scripts/swift_format.sh" + for url in recursiveFiles(below: scriptsRoot) { + let relative = relativePath(url) + if url.pathExtension == "swift" || relative == allowedShellPath { + continue + } + errors.append("\(relative): repository scripts must use Swift; only \(allowedShellPath) is retained") + } + let auditScriptsRoot = root.appendingPathComponent(".agents/skills/agent-guidelines-audit/scripts") + for url in recursiveFiles(below: auditScriptsRoot) where url.pathExtension != "swift" { + errors.append("\(relativePath(url)): audit helper scripts must use Swift") + } + let testsRoot = root.appendingPathComponent("Tests") + for url in recursiveFiles(below: testsRoot) where url.pathExtension != "swift" { + errors.append("\(relativePath(url)): repository test automation must use Swift") + } + validateExecutable(testRunner, description: "native Swift test runner", errors: &errors) + for workflowPath in [".github/workflows/ci.yml", ".github/workflows/release.yml"] { + let workflow = root.appendingPathComponent(workflowPath) + guard let contents = readText(workflow, errors: &errors) else { continue } + for required in ["Tests/run_tests.swift", "Scripts/validate_guidelines.swift"] + where !contents.contains(required) { + errors.append("\(workflowPath): missing native validation command '\(required)'") + } + if contents.localizedCaseInsensitiveContains("python") { + errors.append("\(workflowPath): repository validation must not require Python") + } + } +} + +/// Validates the shared Swift-format workflow guide. +func validateSwiftFormatGuideline(_ errors: inout [String]) { + guard let contents = readText(swiftFormatGuideline, errors: &errors) else { + return + } + let required = [ + "## Swift package integration": "Swift package workflow", + "format-and-lint \\": "local package formatting command", + "Package.swift": "package manifest formatting scope", + "## CI integration": "CI workflow", + "lint-strict \\": "strict CI command", + "Never run `format` or `format-and-lint` in CI": "non-mutating CI rule", + ] + for (value, description) in required where !contents.contains(value) { + errors.append("Guidelines/Swift/SwiftFormat.md: missing \(description): '\(value)'") + } +} + +/// Validates the documentation-maintenance policy. +func validateDocumentationGuideline(_ errors: inout [String]) { + guard let contents = readText(documentationGuideline, errors: &errors) else { + return + } + let required = [ + "Documentation is part of implementation": "implementation-time documentation rule", + "Regardless of change size": "existing-document staleness rule", + "inaccurate, incomplete, misleading, or obsolete": "stale documentation criteria", + "A small change that leaves durable knowledge and existing documentation accurate": + "minor-change documentation churn guardrail", + ] + for (value, description) in required where !contents.contains(value) { + errors.append("Guidelines/Documentation.md: missing \(description): '\(value)'") + } +} + +/// Validates the generated-symbol localization workflow. +func validateLocalizationGuideline(_ errors: inout [String]) { + guard let contents = readText(localizationGuideline, errors: &errors) else { + return + } + let required = [ + "using-generated-localizable-symbols-in-your-code": "Apple generated-symbol reference", + "localizing-your-app-using-agents": "Apple agent-localization reference", + "Xcode-generated `LocalizedStringResource` symbols": "generated-symbol default", + "prepare_localizable_symbols.swift": "shared symbol-preparation workflow", + "validate_string_catalogs.swift": "shared catalog-validation workflow", + "stale extracted entry": "stale-entry policy", + "marked `new` or `needs_review`": "translation-state policy", + "placeholder positions, semantic names, and conversion types": "format-signature policy", + "product voice, terminology": "consumer-specific translation boundary", + "small repository-owned wrapper": "consumer configuration boundary", + ] + for (value, description) in required where !contents.contains(value) { + errors.append("Guidelines/Localization.md: missing \(description): '\(value)'") + } +} + +/// Validates native reusable localization scripts. +func validateLocalizationScripts(_ errors: inout [String]) { + let scripts: [(URL, [String])] = [ + (localizationPreparationScript, ["prepareCatalog", "symbolIssues", "--check"]), + ( + localizationValidationScript, + [ + "--catalog-directory", "--source-directory", "--required-language", "formatSignatureIssues", + "translationStateIssues", "literalLocalizationReferences", + ] + ), + ] + for (script, requiredValues) in scripts { + validateExecutable(script, description: "localization script", errors: &errors) + guard let contents = readText(script, errors: &errors) else { + continue + } + if contents.contains("Headroom") { + errors.append("\(relativePath(script)): contains consumer-specific logic") + } + for value in requiredValues where !contents.contains(value) { + errors.append("\(relativePath(script)): missing localization behavior '\(value)'") + } + } +} + +/// Validates the Xcode project-settings contract. +func validateXcodeProjectSettingsGuideline(_ errors: inout [String]) { + guard let contents = readText(xcodeProjectSettingsGuideline, errors: &errors) else { + return + } + let required = [ + "https://developer.apple.com/documentation/xcode/build-settings-reference": + "official Apple build-settings reference", + "GCC_TREAT_WARNINGS_AS_ERRORS": "C and Objective-C warning policy", + "MTL_TREAT_WARNINGS_AS_ERRORS": "Metal warning policy", + "SWIFT_TREAT_WARNINGS_AS_ERRORS": "Swift warning policy", + "SWIFT_APPROACHABLE_CONCURRENCY = YES": "approachable concurrency baseline", + "SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor": "default actor isolation baseline", + "SWIFT_STRICT_CONCURRENCY = complete": "strict concurrency baseline", + "INFOPLIST_KEY_ITSAppUsesNonExemptEncryption = NO": "export-compliance build-setting baseline", + "ITSAppUsesNonExemptEncryption`](https://developer.apple.com/": "official export-compliance key reference", + "built `Info.plist`": "built export-compliance verification", + "INFOPLIST_KEY_ITSAppUsesNonExemptEncryption = YES": "documented non-exempt encryption exception", + "newest stable Swift language mode": "future-facing Swift language policy", + "Enable each feature that remains opt-in": "language-mode-aware upcoming-feature policy", + "warnings-as-errors can turn that diagnostic into a build failure": "redundant upcoming-feature safety rule", + "Xcode 27 inventory to evaluate": "Xcode 27 upcoming-feature inventory", + "project-level `.xcconfig`": "project-level configuration ownership", + "unit-test and UI-test targets": "test-target effective-value audit", + "nearest applicable `AGENTS.md`": "local exception source", + "condition for removing or revisiting the exception": "exception lifecycle", + "## Swift package parity": "Swift package parity section", + "../Packages.md#compiler-settings-baseline": "Swift package baseline cross-reference", + "Whenever this Xcode project baseline adds, removes, or changes a Swift or Clang compiler policy": + "package applicability maintenance rule", + ] + for (value, description) in required where !contents.contains(value) { + errors.append("Guidelines/Xcode/ProjectSettings.md: missing \(description): '\(value)'") + } + for setting in upcomingFeatureSettings where !contents.contains(setting) { + errors.append( + "Guidelines/Xcode/ProjectSettings.md: missing Xcode 27 upcoming-feature inventory entry: '\(setting)'") + } +} + +/// Validates the Swift package compiler-settings contract. +func validatePackageCompilerSettingsGuideline(_ errors: inout [String]) { + guard let contents = readText(packagesGuideline, errors: &errors) else { + return + } + let required = [ + "## Compiler settings baseline": "compiler-settings baseline section", + "Xcode/ProjectSettings.md": "Xcode baseline cross-reference", + "swiftLanguageModes": "package-level Swift language mode", + ".treatAllWarnings(as: .error)": "typed warnings-as-errors policy", + "Swift 6 language mode enables complete concurrency checking unconditionally": + "Swift 6 strict-concurrency explanation", + ".enableUpcomingFeature(\"StrictConcurrency\")": + "upcoming StrictConcurrency redundancy rule", + ".enableExperimentalFeature(\"StrictConcurrency\")": + "experimental StrictConcurrency redundancy rule", + "StrictConcurrency=complete": "explicit StrictConcurrency redundancy rule", + "`.defaultIsolation(MainActor.self)` is intentionally not part": + "default MainActor isolation exclusion", + "package plug-in targets for which `Target.plugin(...)` does not expose `swiftSettings`": + "unsupported plug-in target exclusion", + "Retain no redundant upcoming features": "redundant upcoming-feature prohibition", + "condition for revisiting or removing the exception": "package-setting exception lifecycle", + ] + for (value, description) in required where !contents.contains(value) { + errors.append("Guidelines/Packages.md: missing package compiler policy \(description): '\(value)'") + } + for feature in packageUpcomingFeatures where !contents.contains(".enableUpcomingFeature(\"\(feature)\")") { + errors.append("Guidelines/Packages.md: missing required SwiftPM upcoming feature '\(feature)'") + } + let emojiRequired = [ + "Each package emoji must be unique across ThatFactory": "uniqueness policy", + "visually identical emoji spellings": "presentation-selector collision policy", + "matching Swift Package Collection entry": "registry synchronization", + ] + for (value, description) in emojiRequired where !contents.contains(value) { + errors.append("Guidelines/Packages.md: missing package emoji \(description): '\(value)'") + } +} + +/// Validates the shared App Store metadata workflow. +func validateAppStoreGuideline(_ errors: inout [String]) { + guard let contents = readText(appStoreGuideline, errors: &errors) else { + return + } + let required = [ + "app-store-connect-mcp": "MCP source", + "AppStore/": "repository metadata root", + "validate_repository": "repository validation", + "plan_metadata_changes": "metadata planning", + "plan_screenshot_changes": "screenshot planning", + "apply_plan": "immutable plan application", + "get_operation_status": "uncertain-outcome recovery", + "noOp: true": "remote reconciliation", + ".appstore-connect-mcp/": "ignored operational state", + "does not authorize submitting": "submission boundary", + ] + for (value, description) in required where !contents.contains(value) { + errors.append("Guidelines/AppStore.md: missing \(description): '\(value)'") + } +} + +/// Validates the native-first dependency policy. +func validateExternalDependencyPolicy(_ errors: inout [String]) { + if let contents = readText(developmentGuideline, errors: &errors) { + let required = [ + "## External dependencies": "external dependency policy section", + "Do not introduce a new third-party source or binary dependency": "native and first-party default", + "explicit approval from the repository owner": "repository-owner approval gate", + "durable repository documentation": "durable exception record", + "Tooling dependencies explicitly required by these shared guidelines": "tooling-only exception", + "CocoaPods and Carthage are forbidden": "forbidden package managers", + "Use Swift Package Manager for package dependencies": "Swift Package Manager requirement", + "## Post-merge cleanup": "post-merge cleanup section", + "fast-forward-only pull": "safe primary-branch update", + "delete the merged local feature branch": "merged local branch removal", + "Confirm the remote feature branch is absent": "remote branch cleanup verification", + ] + for (value, description) in required where !contents.contains(value) { + errors.append("Guidelines/Development.md: missing \(description): '\(value)'") + } + } + if let contents = readText(cicdGuideline, errors: &errors) { + let required = [ + "## Tooling and automation": "CI/CD tooling policy section", + "## Private repository dependencies": "private repository dependency authentication section", + "Fastlane is forbidden": "forbidden delivery tooling", + "xcode-cloud-mcp": "first-party Xcode Cloud tooling", + "app-store-connect-mcp": "first-party App Store tooling", + "required behavior cannot be implemented": "non-Swift capability-gap threshold", + "missing Swift capability": "documented non-Swift exception", + "actions/create-github-app-token@v3": "short-lived GitHub App token workflow", + "client-id:": "current GitHub App client identifier input", + "permission-contents: read": "read-only private dependency permission", + "GIT_CONFIG_KEY_0": "process-level Git authentication", + "GIT_CONFIG_VALUE_0: https://github.com/": "GitHub HTTPS rewrite source", + "complete subprocess tree as privileged": "credential-bearing subprocess trust boundary", + "isolated disposable or ephemeral self-hosted runner": "untrusted-code runner isolation", + "This trust rule is event-independent": "event-independent credential boundary", + "pull_request_target": "untrusted pull-request credential boundary", + ] + for (value, description) in required where !contents.contains(value) { + errors.append("Guidelines/CICD.md: missing \(description): '\(value)'") + } + } + if let contents = readText(packagesGuideline, errors: &errors) { + let required = [ + "[external dependency policy](Development.md#external-dependencies)": "package dependency policy pointer", + "must not introduce or conceal a third-party runtime dependency outside an explicitly approved role": + "first-party package boundary and approved roles", + "guideline-mandated tooling dependency": "DocC tooling exception", + "root `LICENSE` file": "root license-file retention", + "Retain the README license badge": "README license-badge retention", + "do not add a dedicated License heading or license-description section": + "README license-section prohibition", + ] + for (value, description) in required where !contents.contains(value) { + errors.append("Guidelines/Packages.md: missing \(description): '\(value)'") + } + } + if let contents = readText(agentsTemplate, errors: &errors), + !contents.contains("BEGIN THATFACTORY EXTERNAL DEPENDENCY CONTRACT v2") + { + errors.append("Templates/AGENTS.md: missing external-dependency contract") + } +} + +/// Protects the canonical networking policy and its completion-audit integration. +func validateNetworkingPolicy(_ errors: inout [String]) { + let requirements: [(String, [String])] = [ + ( + "Guidelines/Networking.md", + [ + "## Apple networking APIs", "`URLSession`", "`swift-http-types`", + "`HTTPTypes` and `HTTPTypesFoundation`", "`HTTPRequest`", "`HTTPResponse`", + "`HTTPRequest.Method`", "`HTTPFields` and `HTTPField.Name`", "`HTTPResponse.Status`", + "## Capability-gap exceptions", "explicit repository-owner approval", + "### Standing dependency approval", "does not extend to other Apple open-source packages", + "handle failed conversions", "## Adoption and audit", "owner-approved, scoped migration deferral", + "https://github.com/apple/swift-http-types/tree/1.8.0", + ] + ), + ( + ".agents/skills/agent-guidelines-audit/SKILL.md", + [ + "[networking check](#audit-networking)", "## Audit networking", "Guidelines/Networking.md", + "Dependency presence or imports alone do not establish compliance", + "report it as deferred compliance, never full networking compliance", + "A deferral does not authorize new noncompliant networking", + "missing applicable validation prevents audit completion", + ] + ), + ( + "Guidelines/Development.md", + ["Networking.md#standing-dependency-approval", "Unless these guidelines explicitly pre-approve"] + ), + ( + "Templates/AGENTS.md", + [ + "AgentGuidelines/Guidelines/Networking.md", "narrow standing approval", + "does not approve other Apple open-source packages", + ] + ), + ] + for (path, fragments) in requirements { + guard let contents = readText(root.appendingPathComponent(path), errors: &errors) else { continue } + for fragment in fragments where !contents.contains(fragment) { + errors.append("\(path): missing networking requirement: '\(fragment)'") + } + } +} + +/// Protects the native-component decision, ownership, and runtime-evidence policy. +func validateNativeComponentPolicy(_ errors: inout [String]) { + guard let contents = readText(swiftUIGuideline, errors: &errors) else { return } + let required = [ + "## Native components and presentation", + "Prefer native SwiftUI or platform controls and presentation APIs", + "sheets, alerts, confirmation dialogs, navigation, menus, pickers, popovers", + "Custom fonts, button styles, and content inside a native sheet are compatible", + "Do not substitute a sheet-shaped `ZStack`, offset animation, or custom scrim", + "Pixel fidelity to a static design and preserving mounted state are insufficient", + "actual native capability gap verified against the supported platform and deployment target", + "Before implementation, obtain explicit repository-owner approval and record a durable exception", + "Do not invent a capability gap or infer approval from existing custom code", + "An unapproved or undocumented replacement blocks completion", + "attach that presentation to the active child hierarchy", + "Give each child independent dismissal", + "Keep parent-owned draft state alive", + "Make cancellation idempotent", + "reject stale completions after dismissal or replacement", + "presentation's dismissal-completion callback", + "## Required interaction evidence", + "presentation and dismissal animation/dimming", + "interactive dismissal and gesture routing", + "parent survival with draft retention", + "safe areas, controls and shadow clipping, keyboard/focus restoration", + "Dynamic Type and localization", + "Exercise asynchronous cancellation and stale completion", + "A static screenshot or a no-op automation call is not evidence that gestures work", + "Require an actual gesture and its observed result, or recorded manual verification", + "Missing relevant runtime evidence blocks completion", + "Simulated sheet with a suitable native API and no approved durable exception | Blocked", + "Native nested sheet with branded content, correct ownership, and required interaction evidence | Accepted", + "Custom equivalent for a verified capability gap with owner approval, durable exception, and compensating evidence | Accepted within the approved scope", + "Presentation with missing relevant runtime evidence | Blocked", + ] + for value in required where !contents.contains(value) { + errors.append("Guidelines/Swift/SwiftUI.md: missing native-component policy: '\(value)'") + } +} + +/// Protects interaction policy and audit evidence requirements, not consumer runtime performance. +func validateInteractionRenderingPolicy(_ errors: inout [String]) { + let requirements: [(URL, [String])] = [ + ( + swiftUIGuideline, + [ + "## Animation", + "Reusable custom-styled controls own their basic visual transitions", + "both directions, without screen-level opt-in", + "Preserve system-owned feedback instead of layering duplicate animation", + "never delay functional state until an animation finishes", + "Preserve stable view identity when only appearance changes", + "value-triggered animation can affect other changes in the same transaction", + "Use narrower modifier or closure scope", + "[Reduce Motion policy](#reduce-motion)", + "### Reduce Motion", + "https://developer.apple.com/help/app-store-connect/manage-app-accessibility/reduced-motion-evaluation-criteria/", + "no separate task request is required", + "do not disable all animation indiscriminately", + "Follow preference changes during use", + "document any equivalent or more granular in-app alternative", + "Remove decorative triggers or replace them with lower-motion feedback", + "stop it or provide a discoverable stop control", + "replace meaningful motion with suitable alternatives", + "Claim Reduced Motion support only after evaluating all common tasks for the platform being declared", + "required third-party or user-generated content, and advertising", + "An app with no problematic motion can qualify", + "Re-evaluate support with each app update", + "withhold or correct a claim", + "## Image rendering", + "retained, display-appropriate derivatives", + "display scale, aspect-fit/fill requirements, orientation, fidelity, and bounded intermediate/cache memory", + "Refresh derivatives when their source or relevant presentation requirements change", + "outside view construction and repeated interaction paths", + "off the main actor when supported and concurrency-safe", + "Reject stale asynchronous results after replacement, cancellation, or removal", + "separate from authoritative originals needed for editing, saving, or export", + "Inspect the representation actually drawn", + "do not impose blanket bans", + ] + ), + ( + auditSkill, + [ + "Perform the mandatory [animation and image-rendering check](#audit-animation-and-image-rendering)", + "## Audit animation and image rendering", + "Guidelines/Swift/SwiftUI.md#animation", + "Guidelines/Swift/SwiftUI.md#image-rendering", + "do not expand the audit into unrelated screens", + "its owner, and its intended animation or justified immediate feedback", + "Verify reusable defaults without caller-added animation", + "enabled to disabled and disabled to enabled, ordinary presses, rapid reversals", + "hit-testing, accessibility state, and action availability change immediately", + "repeated preparation, oversized drawable content, unstable identity, unbounded caches, and stale publication", + "Exercise representative large-image content", + "compare with an image-free scenario", + "Require recorded runtime actions and outcomes for meaningful motion changes", + "Compilation, static screenshots, and idle captures do not prove smooth interaction", + "Documentation-only policy changes require scenario walkthroughs", + "use Apple performance tools where available and authorized", + "Record the active interaction window", + "Distinguish recorded manual verification from instrumented measurements", + "Do not require profiling every cosmetic change or impose a universal frame-rate threshold", + "missing applicable interaction evidence prevent audit completion", + "| Scenario | Audit outcome |", + "| Appropriate native control already supplies feedback | Accepted without additional animation |", + "| Zero hitches recorded without actual interaction | Insufficient performance evidence", + "[Reduce Motion check](#audit-reduce-motion)", + "## Audit Reduce Motion", + "Guidelines/Swift/SwiftUI.md#reduce-motion", + "Guidelines/Swift/SwiftUI.md#declaring-support", + "Require runtime actions and outcomes with Reduce Motion on and off", + "plus a preference change while running", + "missing applicable evidence blocks completion of the affected work", + "expand the evidence scope to all common tasks on the declared platform", + "withhold or correct unsupported claims", + "do not demand an unrelated whole-app audit for an isolated motion change", + "Documentation-only policy work uses scenario walkthroughs", + ] + ), + ( + appStoreGuideline, + [ + "## Accessibility support claims", + "Swift/SwiftUI.md#declaring-support", + "adopting these guidelines alone does not establish support", + ] + ), + ] + for (file, required) in requirements { + guard let contents = readText(file, errors: &errors) else { continue } + for value in required where !contents.contains(value) { + errors.append("\(file.lastPathComponent): missing interaction/rendering requirement: '\(value)'") + } + if contents.contains( + "Do not introduce app-level Reduce Motion guards unless the task prompt explicitly requests them") + { + errors.append("\(file.lastPathComponent): obsolete Reduce Motion opt-in restriction") + } + } +} + +/// Validates the completion-audit skill and native helper scripts. +func validateAuditSkill(_ errors: inout [String]) { + guard let contents = readText(auditSkill, errors: &errors) else { + return + } + let required = [ + "name: agent-guidelines-audit": "skill name", + "before claiming completion": "completion trigger", + "git diff --check": "diff validation", + "validate_consumer_setup.swift": "consumer integration validation", + "Perform the mandatory [native-component and presentation decision check]": "mandatory native-component audit", + "## Audit native components and presentation": "native-component audit section", + "Guidelines/Swift/SwiftUI.md#native-components-and-presentation": "authoritative native-component policy link", + "custom modal hosts, overlay/scrim/offset code, and gesture routing": "custom presentation inspection", + "native alternative, deployment-target availability": "native alternative decision evidence", + "explicit repository-owner approval, durable consumer exception": "custom component exception validation", + "required approved and documented exception blocks audit completion": "native-component audit stopping rule", + "child dismissal, parent draft ownership, nested picker/editor presenters": "presentation hierarchy audit", + "cancellation, and dismissal-completion cleanup": "presentation cancellation audit", + "native nested sheet with branded content is accepted": "native branded content acceptance", + "Guidelines/Swift/SwiftUI.md#required-interaction-evidence": "presentation runtime evidence link", + "static screenshots and no-op automation do not establish gesture behavior": "gesture evidence audit", + "Missing relevant runtime evidence blocks audit completion": "runtime evidence stopping rule", + "format-and-lint": "local Swift-format audit", + "lint-strict": "strict Swift-format CI audit", + "AppLogger": "AppLogger integration audit", + "Logging.md": "shared Logging guide reference", + "Dependency declaration and target linkage alone": "lifecycle observability coverage audit", + "Enumerate the registered package entries": "package emoji registry enumeration", + "visually identical presentation-selector variants as a collision": + "package emoji presentation-selector collision audit", + "blocks audit completion and release readiness": "package emoji audit stopping rule", + "## Audit documentation consistency": "documentation drift audit", + "Known stale documentation blocks completion": "stale documentation stopping rule", + "## Audit documentation formatting": "documentation formatting audit", + "check_markdown_wrapping.swift": "Markdown line-wrapping check", + "existing root Markdown files and declared durable documentation folders": + "documentation-convention adoption pass", + "new third-party dependency": "third-party dependency audit", + "repository-owner approval": "third-party dependency approval gate", + "no unresolved P0/P1 blocker remains": "Codex review stopping rule", + "## Audit Xcode project settings": "Xcode project-settings audit", + "Xcode/ProjectSettings.md": "shared Xcode project-settings guide reference", + "GCC_TREAT_WARNINGS_AS_ERRORS": "warnings-as-errors project audit", + "SWIFT_UPCOMING_FEATURE_": "future-facing upcoming-feature audit", + "SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor": "actor-isolation project audit", + "SWIFT_VERSION": "Swift language-version project audit", + "INFOPLIST_KEY_ITSAppUsesNonExemptEncryption = NO": "export-compliance project audit", + "## Audit App Store metadata": "App Store metadata audit", + "noOp: true": "App Store remote reconciliation audit", + "xcodebuild -showBuildSettings": "effective target build-setting inspection", + "nearest applicable `AGENTS.md`": "project-setting exception lookup", + "## Audit localization": "localization audit", + "Guidelines/Localization.md": "shared Localization guide reference", + "prepare_localizable_symbols.swift": "generated-symbol preparation audit", + "validate_string_catalogs.swift": "String Catalog validation audit", + "check_xcstrings_inspection.swift": "String Catalog editor evidence gate", + "Fail closed when a changed catalog lacks that recorded editor evidence": + "missing String Catalog editor evidence stopping rule", + "pull-request description": "durable pull-request evidence summary", + "A local wrapper may": "consumer localization-wrapper boundary", + "new repository-owned executable scripts": "native Swift script audit", + "Templates/.gitignore": "shared gitignore template comparison", + "# Project-specific: ": "project-specific gitignore exception marker", + "git check-ignore -v": "gitignore behavior verification", + "git ls-files": "tracked-file safety check", + "CocoaPods or Carthage": "forbidden package-manager audit", + "Guidelines/CICD.md": "shared CI/CD guide reference", + "fastlane adoption": "forbidden delivery-tooling audit", + "missing Swift capability": "non-Swift script exception audit", + "## Audit Swift package settings": "Swift package-settings audit", + "Guidelines/Packages.md#compiler-settings-baseline": "shared package compiler-settings guide reference", + "Package.swift": "package manifest discovery", + "swift package --package-path dump-package": "evaluated manifest inspection", + "swiftLanguageModes": "package language-mode audit", + ".treatAllWarnings(as: .error)": "package warnings-as-errors audit", + ".enableUpcomingFeature(...)": "package upcoming-feature audit", + "complete strict concurrency as supplied by the language mode": "Swift 6 strict-concurrency handling", + ".enableUpcomingFeature(\"StrictConcurrency\")": "upcoming StrictConcurrency removal audit", + ".enableExperimentalFeature(\"StrictConcurrency\")": "experimental StrictConcurrency removal audit", + "StrictConcurrency=complete": "explicit StrictConcurrency removal audit", + ".defaultIsolation(MainActor.self)": "default MainActor isolation exclusion", + "package plug-in targets": "unsupported plug-in target exclusion", + "package-setting failure": "package-setting exception lookup", + ] + for (value, description) in required where !contents.contains(value) { + errors.append(".agents/skills/agent-guidelines-audit/SKILL.md: missing \(description): '\(value)'") + } + for feature in packageUpcomingFeatures where !contents.contains(feature) { + errors.append(".agents/skills/agent-guidelines-audit/SKILL.md: missing package feature audit '\(feature)'") + } + validateExecutable(markdownWrappingScript, description: "Markdown wrapping checker", errors: &errors) + validateExecutable(stringCatalogInspectionScript, description: "String Catalog inspection checker", errors: &errors) + if let development = readText(developmentGuideline, errors: &errors), + !development.contains("$agent-guidelines-audit") + { + errors.append("Guidelines/Development.md: missing mandatory $agent-guidelines-audit invocation") + } + if let template = readText(agentsTemplate, errors: &errors) { + let requiredTemplateValues = [ + "AgentGuidelines/Guidelines/Development.md": "Development.md pointer", + "BEGIN THATFACTORY DOCUMENTATION MAINTENANCE CONTRACT v1": "documentation-maintenance contract", + "BEGIN THATFACTORY EXTERNAL DEPENDENCY CONTRACT v2": "external-dependency contract", + "BEGIN THATFACTORY RUNTIME OBSERVABILITY CONTRACT v1": "runtime-observability contract", + "AgentGuidelines/Guidelines/Documentation.md": "Documentation.md pointer", + "## Stack": "Stack section", + ] + for (value, description) in requiredTemplateValues where !template.contains(value) { + errors.append("Templates/AGENTS.md: missing \(description)") + } + } +} + +/// Validates positive evidence, bounded monitoring, and remediation-only closure. +func validateCodexReviewEvidence(_ errors: inout [String]) { + guard let guide = readText(pullRequestsGuideline, errors: &errors) else { return } + let required = [ + "codex_review_configuration = enabled | disabled | unknown", + "codex_review_execution = not_started | scheduled | processing | completed", + "codex_review_expected_sha = ", + "Only positive repository-specific evidence", + "unknown` plus no signal remains `not_started`", + "Discovering `enabled` alone does not schedule a review", + "including time spent in `processing`", + "A processing signal changes the execution state but does not reset the deadline or poll budget", + "An identical fingerprint causes no substantive re-analysis or user notification", + "Without configuration evidence, do not create a monitor", + "do not transfer `scheduled`, `processing`, or `completed`", + "At the deadline, stop and terminate the monitor, report the observed facts once, and never infer approval", + "If the head changes during monitoring, terminate the old monitor", + "codex_remediation_verified_sha", + "never relabel the newer head as bot-reviewed", + "the exact request-comment reactions", + "rerun the latest review-policy check", + ] + for concept in required where !guide.contains(concept) { + errors.append("Guidelines/GitHub/PullRequests.md: missing Codex review evidence rule: \(concept)") + } + for forbidden in ["No review yet means pending", "Wait for the configured Codex review to finish"] + where guide.contains(forbidden) { + errors.append("Guidelines/GitHub/PullRequests.md: unconditional Codex review gate: \(forbidden)") + } + let outcomes = [ + "Enabled with a current-head processing signal | `processing` | Pending", + "Enabled with a completed review covering the expected head and dispositioned findings | `completed` | Satisfied", + "Unknown with no signal or configuration evidence | `not_started` | Not blocked by absent Codex review | No", + "Disabled with no review | `not_started` | Not blocked by absent Codex review | No", + "Review completed for an old head | Re-establish for new head", + "Completed initial review plus a locally verified remediation-only delta | `completed` | Satisfied", + ] + for outcome in outcomes where !guide.contains(outcome) { + errors.append("Guidelines/GitHub/PullRequests.md: missing Codex review scenario outcome: \(outcome)") + } + if let template = readText(agentsTemplate, errors: &errors), + !template.contains("this template does not establish that automatic review is configured") + { + errors.append("Templates/AGENTS.md: missing unknown-configuration safeguard") + } +} + +/// Ensures every owned policy mirror has one exact canonical contract and no old versions. +func validateReviewPolicyMirrors(_ errors: inout [String]) { + let canonicalURL = root.appendingPathComponent("ReviewPolicy/Policy.md") + guard let canonical = readText(canonicalURL, errors: &errors), + let revisionText = readText(root.appendingPathComponent("ReviewPolicy/VERSION"), errors: &errors), + let revision = Int(revisionText.trimmingCharacters(in: .whitespacesAndNewlines)), revision > 0 + else { + errors.append("ReviewPolicy/VERSION: expected a positive policy revision") + return + } + let mirrors = ["AGENTS.md", "Templates/AGENTS.md", "Templates/GlobalCodexInstructions.md"] + for family in ["CODE REVIEW", "PR LIFECYCLE"] { + let escaped = NSRegularExpression.escapedPattern(for: family) + let pattern = + "[\\s\\S]*?" + let source = matches(pattern, in: canonical) + guard source.count == 1, let expected = capture(0, from: source[0], in: canonical) else { + errors.append("ReviewPolicy/Policy.md: expected one canonical \(family) contract") + continue + } + for relative in mirrors where family == "CODE REVIEW" || relative != "Templates/GlobalCodexInstructions.md" { + guard let value = readText(root.appendingPathComponent(relative), errors: &errors) else { continue } + let found = matches(pattern, in: value) + if found.count != 1 || capture(0, from: found[0], in: value) != expected + || value.components(separatedBy: "" + if !value.contains(expected) + || value.components(separatedBy: " +## Runtime Observability + +Treat privacy-safe runtime observability as part of implementing or changing stateful, asynchronous, fallible, or lifecycle-oriented behavior. Identify the meaningful success, failure, cancellation, recovery, and state-transition boundaries before handoff, and emit concise AppLogger events owned by the artifact that implements them. Dependency declaration or target linkage alone does not satisfy this requirement. + +Every ThatFactory package log starts with its canonical emoji and uses its own stable subsystem. Never log credentials, account or record identifiers, share URLs, captured content, images, or other user-generated values as public metadata. Keep pure values and utilities silent when they have no meaningful diagnostic event; record that deliberate decision in the implementation handoff instead of adding initializer or property-access noise. Follow [Logging](AgentGuidelines/Guidelines/Logging.md) for ownership, privacy, severity, message design, and tests. + +``` + +Keep the following marked external-dependency contract in the consumer repository's root `AGENTS.md` so implementation agents receive the rule directly before they make dependency choices. Copy it unchanged and update it when the marker version changes in this template. + +```md + +## External Dependency Policy + +Do not introduce third-party source or binary dependencies into ThatFactory applications, games, or reusable packages during normal development. Prefer Apple platform APIs, the Swift standard library, code owned by the current repository, or focused ThatFactory-owned packages. If reusable capability is missing, implement it natively at the appropriate boundary and consider extracting it into a first-party package instead of selecting an external library. + +A third-party dependency may be added, or expanded to a new target or runtime role, only under an explicit standing approval in these guidelines or with explicit repository-owner approval for that specific use before modifying the dependency graph. Convenience, reduced implementation effort, popularity, or an agent's preference for an existing library are not sufficient justification. Do not make an external library acceptable merely by hiding it behind a first-party wrapper. + +Document every approved exception in durable repository documentation in the same change. Record the dependency and source, purpose and target scope, why a native or first-party implementation is not appropriate, relevant license, security, and maintenance considerations, and the approval context. Merely mentioning or using the dependency in an execution plan, pull-request description, or transient chat is not approval. Regardless of where explicit approval occurs, reflect the exception in durable repository documentation. + +Apple system frameworks and the Swift standard library are not third-party dependencies. ThatFactory-owned packages are first-party dependencies. Tooling explicitly required by the shared guidelines is allowed only for its documented tooling role and must not be linked into or shipped with product runtime targets unless separately approved and documented. + +Follow [Networking](AgentGuidelines/Guidelines/Networking.md) for Apple-native networking and typed HTTP. Its narrow standing approval for Apple's `swift-http-types` applies only to the documented HTTPTypes and HTTPTypesFoundation runtime role; it does not approve other Apple open-source packages or unrelated roles. Use the guide's normal dependency documentation for that role instead of requesting a separate consumer exception. + +Follow [Development workflow](AgentGuidelines/Guidelines/Development.md) for the detailed policy. + +``` + +Keep the following documentation-maintenance contract in the consumer repository's root `AGENTS.md` so implementation agents receive it directly rather than only through a linked guide. Copy it unchanged and update it when the marker version changes in this template. + +```md + +## Documentation Maintenance + +Treat documentation as part of implementation, not optional follow-up. At the start of implementation, identify code-level or project-level documentation likely to describe the affected behavior; before handoff, reconcile that documentation with the final implementation. + +Update documentation when a change alters durable or core feature behavior or another documented contract. Regardless of change size, if the implementation makes existing documentation inaccurate, incomplete, misleading, or obsolete, update or remove that documentation in the same change. + +Do not create documentation churn for incidental implementation details that are not durable and do not affect an existing documented claim. Follow [Documentation](AgentGuidelines/Guidelines/Documentation.md) for detailed scope and the completion checklist. + +``` + +Keep the following code-review and PR-lifecycle contracts directly in the consumer repository's root `AGENTS.md`. Synchronize them with `Scripts/sync_codex_review_policy.swift`; both full and review-only profiles use identical canonical text. The template provenance below is development-only: consumer synchronization replaces it with the profile, latest policy revision, and immutable published commit. A Markdown link is not an instruction include. + +```md + + +## Code Review Rules + +Report only substantiated P0/P1 defects introduced or materially exposed by this change. Require a concrete, reachable failure in a supported use case or documented threat model, with serious impact such as a security-boundary bypass, durable data loss or corruption, a crash or deadlock in an important workflow, loss of availability, or a serious compatibility regression. An acceptance-criterion violation alone does not establish P1 severity. + +For each finding, state severity, preconditions, execution path, impact, evidence, and actionable remediation. Group manifestations of one root cause. Report substantiated blockers together. Omit unsolicited P2/P3 observations, style preferences, speculative hardening, optional tests, and refactors. A clean review means no unresolved P0/P1 blockers, not perfect software. + +A follow-up review covers unresolved P0/P1 findings, changes since the previous reviewed commit, and directly affected code. Do not restart a full review of unchanged code. New follow-up findings must be P0/P1 defects introduced by remediation or genuinely hidden by the previous blocker. + + + +## Pull Request Lifecycle + +Finish implementation, inspect the diff, and run relevant local validation before opening a ready-for-review PR. Drafts are for incomplete preparation; mark ready before waiting for automatic review. Keep the review head stable while the initial review runs. One automatic Codex review is the initial review; never duplicate it with a manual request or repeatedly toggle draft/ready state. + +Establish review configuration from repository-specific evidence. Verify the bot, PR, review round, and reviewed commit using PR/request-comment reactions, review submissions, inline threads, and checks. Eyes means processing, not approval; a thumbs-up means no suggestions only for its verified review round. Historical reactions, missing comments, and elapsed time never certify a newer head. Monitor at most five minutes total with bounded, non-accelerating polls; timeout leaves a required gate unresolved and never authorizes merge. + +Batch accepted P0/P1 fixes, verify them locally, rerun affected checks, and disposition and resolve every review thread. A completed initial review plus an explicitly recorded, locally verified remediation-only delta can satisfy the review gate; do not claim Codex reviewed the newer head. New unrelated scope belongs in another PR. Request at most one delta-scoped verification only when the owner explicitly authorizes it. Do not request reviews after every fix or casually mention the bot to start extra work. Separate Security Review is manual and requires explicit owner instruction. + +Before merge, rerun the latest published review-policy check, confirm no required review is pending, no unresolved P0/P1 blocker remains, every thread is dispositioned and resolved, required checks pass on the current head, and existing human approval or merge authorization is satisfied. A bot thumbs-up is not a substitute for required GitHub approval. Opening a PR does not authorize merging it. + + +## Codex review scope + +For consumer pull requests, do not substantively review `AgentGuidelines/**` after exact tagged-tree provenance has been verified. Verify its `VERSION`, compare its tree with the matching central tag, and verify the required `.gitattributes` rule. If provenance does not match exactly, review the subtree contents and stop the merge. Report substantive guideline feedback against the central `agent-guidelines` pull request. +``` + +The marked block is intentional controlled duplication of the shared review policy. The tracked, synchronized subtree is reviewed centrally in `thatfactory/agent-guidelines`; the root-level instructions ensure the review contract and subtree scope are loaded even when Codex starts from the repository root. + +## Physical folder map + +Replace these examples with exact repository paths: + +| Role | Physical folder | +|---|---| +| Application sources | `/` | +| Redux | `/Redux/` | +| Views | `/View/` | +| Services | `/Services/` | +| Unit tests | `Tests/` | + +## Stack + +Record the supported Xcode, Swift, and platform versions. Follow the shared Xcode project-settings baseline and record any exact, scoped exception in the local specialization or linked durable documentation. + +## Local specialization + +State only rules that specialize or override the shared baseline. Explain their scope and point to local source-of-truth documentation. diff --git a/Templates/GlobalCodexInstructions.md b/Templates/GlobalCodexInstructions.md new file mode 100644 index 0000000..4906621 --- /dev/null +++ b/Templates/GlobalCodexInstructions.md @@ -0,0 +1,19 @@ +# Global Codex Instructions + +For repositories containing an `AGENTS.md`, read and follow the applicable repository instructions before starting substantive work. + +When a repository includes shared agent guidelines, read the relevant guides referenced by the applicable `AGENTS.md` on demand. Treat those guides as the source of truth for language conventions, architecture, development workflow, testing, and agent execution. + +Repository and folder-level instructions may specialize the shared baseline within their scope. Do not replace deliberate repository conventions with generic global preferences. + +Do not duplicate repository-specific guidance in global instructions. Global instructions should bootstrap discovery of the repository's own sources of truth. + + +## Code Review Rules + +Report only substantiated P0/P1 defects introduced or materially exposed by this change. Require a concrete, reachable failure in a supported use case or documented threat model, with serious impact such as a security-boundary bypass, durable data loss or corruption, a crash or deadlock in an important workflow, loss of availability, or a serious compatibility regression. An acceptance-criterion violation alone does not establish P1 severity. + +For each finding, state severity, preconditions, execution path, impact, evidence, and actionable remediation. Group manifestations of one root cause. Report substantiated blockers together. Omit unsolicited P2/P3 observations, style preferences, speculative hardening, optional tests, and refactors. A clean review means no unresolved P0/P1 blockers, not perfect software. + +A follow-up review covers unresolved P0/P1 findings, changes since the previous reviewed commit, and directly affected code. Do not restart a full review of unchanged code. New follow-up findings must be P0/P1 defects introduced by remediation or genuinely hidden by the previous blocker. + diff --git a/AgentGuidelines/Templates/Store.swift b/Templates/Store.swift similarity index 100% rename from AgentGuidelines/Templates/Store.swift rename to Templates/Store.swift diff --git a/Tests/ProgressionKitTests/PKLoggingTests.swift b/Tests/ProgressionKitTests/PKLoggingTests.swift deleted file mode 100644 index 68c4778..0000000 --- a/Tests/ProgressionKitTests/PKLoggingTests.swift +++ /dev/null @@ -1,101 +0,0 @@ -import AppLogger -import Foundation -import Testing - -@testable import ProgressionKit - -@Suite struct PKLoggingTests { - @Test func applyingEventLogsOnePackageOwnedOutcome() throws { - // Given - let recorder = PKLogRecorder() - let event = PKEvent( - contentID: "Sensitive content", - trackID: "Sensitive track", - tierID: "beginner", - wasSuccessful: true - ) - let config = PKConfig( - levelXP: 10, - masteryXP: 15, - tierOrder: ["beginner", "intermediate"], - masteryRequirement: 1 - ) - - // When - PKLogging.$sink.withValue(recorder.record) { - _ = PKEngine.apply( - event: event, - to: PKProfile(), - config: config - ) - } - - // Then - let entry = try #require(recorder.entries.first) - #expect(recorder.entries.count == 1) - #expect(entry.category == .progression) - #expect(!entry.isPrivate) - #expect(entry.message == "📈 apply | xpGranted=15, level=2, unlocked=1") - #expect(!entry.message.contains(event.contentID)) - #expect(!entry.message.contains(event.trackID)) - #expect(!entry.message.contains(event.tierID)) - #expect(PKLogging.subsystem == "com.thatfactory.progressionkit") - expectDebug(entry.level) - } -} - -// MARK: - Private - -private func expectDebug( - _ level: AppLogLevel, - sourceLocation: SourceLocation = #_sourceLocation -) { - guard case .debug = level else { - Issue.record( - "Expected a debug log level.", - sourceLocation: sourceLocation - ) - return - } -} - -/// Records ProgressionKit log entries emitted during a test. -private final class PKLogRecorder: @unchecked Sendable { - private var internalEntries: [PKRecordedLog] = [] - private let lock = NSLock() - - var entries: [PKRecordedLog] { - lock.lock() - defer { - lock.unlock() - } - return internalEntries - } - - func record( - _ level: AppLogLevel, - _ category: PKLogCategory, - _ message: String, - _ isPrivate: Bool - ) { - lock.lock() - defer { - lock.unlock() - } - internalEntries.append( - PKRecordedLog( - level: level, - category: category, - message: message, - isPrivate: isPrivate - ) - ) - } -} - -private struct PKRecordedLog { - let level: AppLogLevel - let category: PKLogCategory - let message: String - let isPrivate: Bool -} diff --git a/Tests/ProgressionKitTests/ProgressionKitTests.swift b/Tests/ProgressionKitTests/ProgressionKitTests.swift deleted file mode 100644 index 8832c4b..0000000 --- a/Tests/ProgressionKitTests/ProgressionKitTests.swift +++ /dev/null @@ -1,197 +0,0 @@ -import Testing - -@testable import ProgressionKit - -@Test func grantsXPForFirstSuccessfulCompletion() { - // Given - let event = PKEvent( - contentID: "lesson-1", - trackID: "a11-reading", - tierID: "beginner", - wasSuccessful: true - ) - - // When - let update = PKEngine.apply( - event: event, - to: PKProfile() - ) - - // Then - #expect(update.didGrantXP) - #expect(update.profile.totalXP == 10) - #expect(update.playerLevel == 1) - #expect(update.xpIntoLevel == 10) -} - -@Test func doesNotGrantXPForRepeatedSuccessfulCompletion() { - // Given - let event = PKEvent( - contentID: "lesson-1", - trackID: "a11-reading", - tierID: "beginner", - wasSuccessful: true - ) - let firstUpdate = PKEngine.apply( - event: event, - to: PKProfile() - ) - - // When - let secondUpdate = PKEngine.apply( - event: event, - to: firstUpdate.profile - ) - - // Then - #expect(!secondUpdate.didGrantXP) - #expect(secondUpdate.profile.totalXP == 10) -} - -@Test func doesNotGrantXPForIncorrectAttempts() { - // Given - let event = PKEvent( - contentID: "lesson-1", - trackID: "a11-reading", - tierID: "beginner", - wasSuccessful: false - ) - - // When - let update = PKEngine.apply( - event: event, - to: PKProfile() - ) - - // Then - #expect(!update.didGrantXP) - #expect(update.profile.totalXP == 0) -} - -@Test func unlocksIntermediateAfterDistinctBeginnerMastery() { - // Given - let events = (1...5).map { index in - PKEvent( - contentID: "lesson-\(index)", - trackID: "a11-reading", - tierID: "beginner", - wasSuccessful: true - ) - } - - // When - let finalUpdate = events.reduce( - PKUpdate( - didGrantXP: false, - newlyUnlockedTierIDs: [], - playerLevel: 1, - profile: PKProfile(), - xpForNextLevel: 100, - xpIntoLevel: 0 - ) - ) { partialUpdate, event in - PKEngine.apply( - event: event, - to: partialUpdate.profile - ) - } - - // Then - #expect(finalUpdate.newlyUnlockedTierIDs == ["intermediate"]) - #expect( - finalUpdate.profile.trackProgress["a11-reading"]?.unlockedTierIDs.contains("intermediate") == true - ) -} - -@Test func unlocksAdvancedAfterDistinctIntermediateMastery() { - // Given - let beginnerEvents = (1...5).map { index in - PKEvent( - contentID: "beginner-\(index)", - trackID: "a11-writing", - tierID: "beginner", - wasSuccessful: true - ) - } - let intermediateEvents = (1...5).map { index in - PKEvent( - contentID: "intermediate-\(index)", - trackID: "a11-writing", - tierID: "intermediate", - wasSuccessful: true - ) - } - - let unlockedIntermediateProfile = beginnerEvents.reduce(PKProfile()) { profile, event in - PKEngine.apply( - event: event, - to: profile - ).profile - } - - // When - let finalUpdate = intermediateEvents.reduce( - PKUpdate( - didGrantXP: false, - newlyUnlockedTierIDs: [], - playerLevel: 1, - profile: unlockedIntermediateProfile, - xpForNextLevel: 100, - xpIntoLevel: 0 - ) - ) { partialUpdate, event in - PKEngine.apply( - event: event, - to: partialUpdate.profile - ) - } - - // Then - #expect(finalUpdate.newlyUnlockedTierIDs == ["advanced"]) - #expect( - finalUpdate.profile.trackProgress["a11-writing"]?.unlockedTierIDs.contains("advanced") == true - ) -} - -@Test func derivesLevelAcrossBoundary() { - // Given - let config = PKConfig( - levelXP: 100, - masteryXP: 25, - tierOrder: ["beginner", "intermediate", "advanced"], - masteryRequirement: 5 - ) - let events = (1...4).map { index in - PKEvent( - contentID: "lesson-\(index)", - trackID: "a11-listening", - tierID: "beginner", - wasSuccessful: true - ) - } - - // When - let finalProfile = events.reduce(PKProfile()) { profile, event in - PKEngine.apply( - event: event, - to: profile, - config: config - ).profile - } - let finalUpdate = PKEngine.apply( - event: PKEvent( - contentID: "lesson-5", - trackID: "a11-listening", - tierID: "beginner", - wasSuccessful: false - ), - to: finalProfile, - config: config - ) - - // Then - #expect(finalUpdate.profile.totalXP == 100) - #expect(finalUpdate.playerLevel == 2) - #expect(finalUpdate.xpIntoLevel == 0) - #expect(finalUpdate.xpForNextLevel == 100) -} diff --git a/Tests/run_review_policy_tests.swift b/Tests/run_review_policy_tests.swift new file mode 100755 index 0000000..7b028c7 --- /dev/null +++ b/Tests/run_review_policy_tests.swift @@ -0,0 +1,250 @@ +#!/usr/bin/env swift +import Foundation + +#if canImport(Darwin) + import Darwin +#else + import Glibc +#endif + +let sourceRoot = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent() +let manager = FileManager.default + +/// One executed process with complete combined diagnostics. +struct Result { + let status: Int32 + let output: String +} + +/// A focused regression-test failure. +struct Failure: Error, CustomStringConvertible { + let description: String +} + +/// Executes an argument vector without interpreting repository text as shell syntax. +func run(_ arguments: [String], at root: URL? = nil) throws -> Result { + let process = Process() + let output = Pipe() + process.executableURL = URL(fileURLWithPath: "/usr/bin/env") + process.arguments = arguments + process.currentDirectoryURL = root + process.standardOutput = output + process.standardError = output + try process.run() + let bytes = output.fileHandleForReading.readDataToEndOfFile() + process.waitUntilExit() + return Result(status: process.terminationStatus, output: String(decoding: bytes, as: UTF8.self)) +} + +/// Asserts a condition with actionable diagnostics. +func require(_ condition: @autoclosure () throws -> Bool, _ message: String) throws { + if try !condition() { throw Failure(description: message) } +} + +/// Writes fixture data while preserving its literal content. +func write(_ text: String, _ url: URL) throws { + try manager.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true) + try text.write(to: url, atomically: true, encoding: .utf8) +} + +/// Reads a UTF-8 fixture. +func read(_ url: URL) throws -> String { + try String(contentsOf: url, encoding: .utf8) +} + +/// Runs a Git fixture mutation and verifies success. +func git(_ arguments: [String], at root: URL) throws -> String { + let result = try run(["git"] + arguments, at: root) + try require(result.status == 0, result.output) + return result.output.trimmingCharacters(in: .whitespacesAndNewlines) +} + +/// Owns isolated, locally published policy tags and consumer repositories. +struct Fixture { + let root: URL + let repository: URL + let canonical: String + + /// Creates a minimal source repository, including an annotated policy tag. + init() throws { + root = manager.temporaryDirectory.appendingPathComponent("policy-tests-\(UUID().uuidString)") + repository = root.appendingPathComponent("policy") + canonical = try read(sourceRoot.appendingPathComponent("ReviewPolicy/Policy.md")) + try write(canonical, repository.appendingPathComponent("ReviewPolicy/Policy.md")) + try write("1\n", repository.appendingPathComponent("ReviewPolicy/VERSION")) + _ = try git(["init", "--quiet"], at: repository) + _ = try git(["config", "user.name", "Policy test"], at: repository) + _ = try git(["config", "user.email", "policy@example.com"], at: repository) + _ = try git(["add", "."], at: repository) + _ = try git(["commit", "--quiet", "-m", "Policy one"], at: repository) + _ = try git(["tag", "-a", "codex-review-v1", "-m", "Immutable policy one"], at: repository) + } + + /// Creates a consumer with identifiable local instructions and optional obsolete copies. + func consumer(_ name: String, full: Bool = false, obsolete: Bool = false) throws -> URL { + let consumer = root.appendingPathComponent(name) + var value = "# Local project\n\nPreserve local BEFORE instructions.\n" + if obsolete { + let old = canonical.components(separatedBy: "\n\n\n## Code Review Rules"), "obsolete review contract survived") + let second = try fixture.sync("update", root, profile: profile) + try require(second.status == 0, second.output) + try require(try read(root.appendingPathComponent("AGENTS.md")) == first, "update is not idempotent") + let check = try fixture.sync("check", root, profile: profile) + try require(check.status == 0, check.output) + } + } + ), + ( + "modified, duplicate, stale, and incorrect-source policies fail without writing", + { + let fixture = try Fixture() + defer { fixture.cleanup() } + let root = try fixture.consumer("consumer") + let update = try fixture.sync("update", root) + try require(update.status == 0, update.output) + let file = root.appendingPathComponent("AGENTS.md") + let good = try read(file) + let mutations = [ + good.replacingOccurrences(of: "P0/P1", with: "P0"), + good + "\n" + fixture.canonical, + good.replacingOccurrences(of: "revision=1", with: "revision=0"), + good.replacingOccurrences(of: "source=", with: "incorrect-source="), + good + "\n\n", + ] + for value in mutations { + try write(value, file) + let check = try fixture.sync("check", root) + try require(check.status != 0, "invalid policy passed") + try require(try read(file) == value, "check mutated instructions") + } + try write(mutations.last!, file) + let invalidUpdate = try fixture.sync("update", root) + try require(invalidUpdate.status != 0, "malformed update unexpectedly succeeded") + try require(try read(file) == mutations.last!, "failed update changed instructions") + } + ), + ( + "a new policy revision blocks old consumers while unrelated releases do not", + { + let fixture = try Fixture() + defer { fixture.cleanup() } + let root = try fixture.consumer("consumer") + let first = try fixture.sync("update", root) + try require(first.status == 0, first.output) + try write("Unrelated guide change.\n", fixture.repository.appendingPathComponent("README.md")) + _ = try git(["add", "."], at: fixture.repository) + _ = try git(["commit", "--quiet", "-m", "Unrelated guide release"], at: fixture.repository) + let unchanged = try fixture.sync("check", root) + try require(unchanged.status == 0, unchanged.output) + try write("2\n", fixture.repository.appendingPathComponent("ReviewPolicy/VERSION")) + _ = try git(["add", "."], at: fixture.repository) + _ = try git(["commit", "--quiet", "-m", "Policy two"], at: fixture.repository) + _ = try git(["tag", "codex-review-v2"], at: fixture.repository) + let stale = try fixture.sync("check", root) + try require(stale.status != 0, "old revision accepted") + let updated = try fixture.sync("update", root) + try require(updated.status == 0, updated.output) + let checked = try fixture.sync("check", root) + try require(checked.status == 0, checked.output) + } + ), + ( + "unavailable sources, tag/version disagreement, and profile bypass fail closed", + { + let fixture = try Fixture() + defer { fixture.cleanup() } + let root = try fixture.consumer("consumer") + let unavailable = try fixture.sync( + "check", root, extra: ["--policy-repository", fixture.root.appendingPathComponent("absent").path]) + try require(unavailable.status != 0, "unavailable source passed") + let wrongProfile = try fixture.sync("update", root, profile: "full") + try require(wrongProfile.status != 0, "wrong profile passed") + let localBypass = try fixture.sync("update", root, extra: ["--local-source", sourceRoot.path]) + try require(localBypass.status != 0, "consumer bypassed immutable source verification") + _ = try git(["tag", "codex-review-v2"], at: fixture.repository) + let mismatch = try fixture.sync("update", root) + try require(mismatch.status != 0 && mismatch.output.contains("disagree"), mismatch.output) + } + ), + ( + "current review, stale signals, remediation closure, and timeout remain distinct", + { + let guide = try read(sourceRoot.appendingPathComponent("Guidelines/GitHub/PullRequests.md")) + let source = try read(sourceRoot.appendingPathComponent("Scripts/validate_guidelines.swift")) + let invariants = [ + "the exact request-comment reactions", + "never relabel the newer head as bot-reviewed", + "Completed initial review plus a locally verified remediation-only delta | `completed` | Satisfied", + "At the deadline, stop and terminate the monitor, report the observed facts once, and never infer approval", + ] + for invariant in invariants { + try require( + guide.contains(invariant) && source.contains(invariant), + "missing protected review scenario: \(invariant)") + } + try require( + try fixturelessPolicy().contains("New unrelated scope belongs in another PR"), "scope boundary missing") + } + ), +] + +/// Reads canonical policy for assertions without constructing a remote fixture. +func fixturelessPolicy() throws -> String { + try read(sourceRoot.appendingPathComponent("ReviewPolicy/Policy.md")) +} + +var failures = 0 +for (name, test) in tests { + do { + try test() + print("PASS \(name)") + } catch { + failures += 1 + FileHandle.standardError.write(Data("FAIL \(name): \(error)\n".utf8)) + } +} +if failures > 0 { exit(1) } +print("All \(tests.count) review-policy test groups passed.") diff --git a/Tests/run_tests.swift b/Tests/run_tests.swift new file mode 100755 index 0000000..5255035 --- /dev/null +++ b/Tests/run_tests.swift @@ -0,0 +1,1281 @@ +#!/usr/bin/env swift +import Foundation + +#if canImport(Darwin) + import Darwin +#else + import Glibc +#endif + +struct CommandResult { + let status: Int32 + let output: String + + var succeeded: Bool { status == 0 } +} + +struct TestFailure: Error, CustomStringConvertible { + let description: String +} + +let repositoryRoot = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent() +let fileManager = FileManager.default + +func require(_ condition: @autoclosure () -> Bool, _ message: String) throws { + guard condition() else { throw TestFailure(description: message) } +} + +func run(_ arguments: [String], directory: URL = repositoryRoot) throws -> CommandResult { + let process = Process() + let output = Pipe() + process.currentDirectoryURL = directory + process.executableURL = URL(fileURLWithPath: "/usr/bin/env") + process.arguments = arguments + process.standardOutput = output + process.standardError = output + try process.run() + let data = output.fileHandleForReading.readDataToEndOfFile() + process.waitUntilExit() + return CommandResult(status: process.terminationStatus, output: String(decoding: data, as: UTF8.self)) +} + +func withTemporaryDirectory(_ body: (URL) throws -> Void) throws { + let directory = fileManager.temporaryDirectory.appendingPathComponent(UUID().uuidString) + try fileManager.createDirectory(at: directory, withIntermediateDirectories: true) + defer { try? fileManager.removeItem(at: directory) } + try body(directory) +} + +func write(_ value: String, to url: URL) throws { + try fileManager.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true) + try value.write(to: url, atomically: true, encoding: .utf8) +} + +func script(_ path: String) -> String { + repositoryRoot.appendingPathComponent(path).path +} + +func copyRepositoryFixture(to destination: URL) throws { + try fileManager.createDirectory(at: destination, withIntermediateDirectories: true) + let children = try fileManager.contentsOfDirectory(at: repositoryRoot, includingPropertiesForKeys: nil) + for child in children where ![".git", ".build"].contains(child.lastPathComponent) { + try fileManager.copyItem(at: child, to: destination.appendingPathComponent(child.lastPathComponent)) + } +} + +func git(_ arguments: String..., in directory: URL) throws { + let result = try run(["git"] + arguments, directory: directory) + try require(result.succeeded, "git \(arguments.joined(separator: " ")) failed: \(result.output)") +} + +func initializeRepository(at root: URL) throws { + try git("init", in: root) + try git("config", "user.email", "agent@example.com", in: root) + try git("config", "user.name", "Agent", in: root) +} + +func createConsumerFixture(at root: URL, isPackage: Bool, readme: String? = nil) throws { + try fileManager.createSymbolicLink( + at: root.appendingPathComponent("AgentGuidelines"), withDestinationURL: repositoryRoot) + try fileManager.copyItem( + at: repositoryRoot.appendingPathComponent("Templates/AGENTS.md"), + to: root.appendingPathComponent("AGENTS.md")) + try write("AgentGuidelines/** linguist-generated\n", to: root.appendingPathComponent(".gitattributes")) + let skillParent = root.appendingPathComponent(".agents/skills") + try fileManager.createDirectory(at: skillParent, withIntermediateDirectories: true) + try fileManager.createSymbolicLink( + at: skillParent.appendingPathComponent("agent-guidelines-audit"), + withDestinationURL: repositoryRoot.appendingPathComponent(".agents/skills/agent-guidelines-audit") + ) + try fileManager.createSymbolicLink( + at: root.appendingPathComponent(".swift-format"), + withDestinationURL: repositoryRoot.appendingPathComponent("Configurations/Swift/.swift-format")) + try fileManager.createSymbolicLink( + at: root.appendingPathComponent(".editorconfig"), + withDestinationURL: repositoryRoot.appendingPathComponent("Configurations/Swift/.editorconfig")) + try write( + """ + name: CI + on: + pull_request: + push: + branches: [main] + jobs: + swift-format: + steps: + - run: AgentGuidelines/Scripts/swift_format.sh lint-strict Package.swift Sources Tests + """ + "\n", + to: root.appendingPathComponent(".github/workflows/ci.yml") + ) + if isPackage { + try write("// swift-tools-version: 6.0\n", to: root.appendingPathComponent("Package.swift")) + } + if let readme { + try write(readme, to: root.appendingPathComponent("README.md")) + } +} + +func localization(_ value: String, state: String = "translated") -> String { + #"{"stringUnit":{"state":"\#(state)","value":"\#(value)"}}"# +} + +let tests: [(String, () throws -> Void)] = [ + ( + "networking validator rejects missing policy and audit gates", + { + let mutations: [(String, String)] = [ + ("Guidelines/Networking.md", "`HTTPTypes` and `HTTPTypesFoundation`"), + ("Guidelines/Networking.md", "## Capability-gap exceptions"), + ("Guidelines/Development.md", "Networking.md#standing-dependency-approval"), + ( + ".agents/skills/agent-guidelines-audit/SKILL.md", + "Dependency presence or imports alone do not establish compliance" + ), + ( + ".agents/skills/agent-guidelines-audit/SKILL.md", + "report it as deferred compliance, never full networking compliance" + ), + ] + try withTemporaryDirectory { temporary in + let fixture = temporary.appendingPathComponent("repository") + try copyRepositoryFixture(to: fixture) + let validator = fixture.appendingPathComponent("Scripts/validate_guidelines.swift").path + let baseline = try run([validator]) + try require(baseline.succeeded, baseline.output) + for (path, fragment) in mutations { + let file = fixture.appendingPathComponent(path) + let original = try String(contentsOf: file, encoding: .utf8) + try require(original.contains(fragment), "missing test fixture text: \(fragment)") + try write(original.replacingOccurrences(of: fragment, with: "REMOVED"), to: file) + let result = try run([validator]) + try require(!result.succeeded, "networking drift unexpectedly passed: \(fragment)") + try require(result.output.contains("missing networking requirement"), result.output) + try write(original, to: file) + } + } + } + ), + ( + "consumer validator requires dependency contract v2 and its standing approval", + { + try withTemporaryDirectory { root in + try createConsumerFixture(at: root, isPackage: true) + let agents = root.appendingPathComponent("AGENTS.md") + let original = try String(contentsOf: agents, encoding: .utf8) + let command = [script("Scripts/validate_consumer_setup.swift"), "--consumer-root", root.path] + let baseline = try run(command) + try require(baseline.succeeded, baseline.output) + try write( + original.replacingOccurrences( + of: "EXTERNAL DEPENDENCY CONTRACT v2", with: "EXTERNAL DEPENDENCY CONTRACT v1"), + to: agents) + let stale = try run(command) + try require(!stale.succeeded, "stale dependency contract unexpectedly passed") + try require(stale.output.contains("EXTERNAL DEPENDENCY CONTRACT v2"), stale.output) + try write(original.replacingOccurrences(of: "narrow standing approval", with: "approval"), to: agents) + let drift = try run(command) + try require(!drift.succeeded, "changed standing approval unexpectedly passed") + try require(drift.output.contains("external-dependency contract does not match"), drift.output) + } + } + ), + ( + "interaction/rendering validator rejects guide and audit drift", + { + let mutations: [(String, [String])] = [ + ( + "Guidelines/Swift/SwiftUI.md", + [ + "## Animation", + "both directions, without screen-level opt-in", + "Preserve system-owned feedback instead of layering duplicate animation", + "never delay functional state until an animation finishes", + "Preserve stable view identity when only appearance changes", + "value-triggered animation can affect other changes in the same transaction", + "Use narrower modifier or closure scope", + "[Reduce Motion policy](#reduce-motion)", + "### Reduce Motion", + "https://developer.apple.com/help/app-store-connect/manage-app-accessibility/reduced-motion-evaluation-criteria/", + "no separate task request is required", + "do not disable all animation indiscriminately", + "Follow preference changes during use", + "document any equivalent or more granular in-app alternative", + "Remove decorative triggers or replace them with lower-motion feedback", + "stop it or provide a discoverable stop control", + "replace meaningful motion with suitable alternatives", + "Claim Reduced Motion support only after evaluating all common tasks for the platform being declared", + "required third-party or user-generated content, and advertising", + "An app with no problematic motion can qualify", + "Re-evaluate support with each app update", + "withhold or correct a claim", + "## Image rendering", + "retained, display-appropriate derivatives", + "display scale, aspect-fit/fill requirements, orientation, fidelity, and bounded intermediate/cache memory", + "Refresh derivatives when their source or relevant presentation requirements change", + "outside view construction and repeated interaction paths", + "off the main actor when supported and concurrency-safe", + "Reject stale asynchronous results after replacement, cancellation, or removal", + "separate from authoritative originals needed for editing, saving, or export", + "Inspect the representation actually drawn", + "do not impose blanket bans", + ] + ), + ( + ".agents/skills/agent-guidelines-audit/SKILL.md", + [ + "Perform the mandatory [animation and image-rendering check](#audit-animation-and-image-rendering)", + "## Audit animation and image rendering", + "Guidelines/Swift/SwiftUI.md#animation", + "Guidelines/Swift/SwiftUI.md#image-rendering", + "do not expand the audit into unrelated screens", + "its owner, and its intended animation or justified immediate feedback", + "Verify reusable defaults without caller-added animation", + "enabled to disabled and disabled to enabled, ordinary presses, rapid reversals", + "hit-testing, accessibility state, and action availability change immediately", + "repeated preparation, oversized drawable content, unstable identity, unbounded caches, and stale publication", + "Exercise representative large-image content", + "compare with an image-free scenario", + "Require recorded runtime actions and outcomes for meaningful motion changes", + "Compilation, static screenshots, and idle captures do not prove smooth interaction", + "Documentation-only policy changes require scenario walkthroughs", + "use Apple performance tools where available and authorized", + "Record the active interaction window", + "Distinguish recorded manual verification from instrumented measurements", + "Do not require profiling every cosmetic change or impose a universal frame-rate threshold", + "missing applicable interaction evidence prevent audit completion", + "| Appropriate native control already supplies feedback | Accepted without additional animation |", + "| Zero hitches recorded without actual interaction | Insufficient performance evidence", + "[Reduce Motion check](#audit-reduce-motion)", + "## Audit Reduce Motion", + "Guidelines/Swift/SwiftUI.md#reduce-motion", + "Guidelines/Swift/SwiftUI.md#declaring-support", + "Require runtime actions and outcomes with Reduce Motion on and off", + "plus a preference change while running", + "missing applicable evidence blocks completion of the affected work", + "expand the evidence scope to all common tasks on the declared platform", + "withhold or correct unsupported claims", + "do not demand an unrelated whole-app audit for an isolated motion change", + "Documentation-only policy work uses scenario walkthroughs", + ] + ), + ( + "Guidelines/AppStore.md", + [ + "## Accessibility support claims", + "Swift/SwiftUI.md#declaring-support", + "adopting these guidelines alone does not establish support", + ] + ), + ] + try withTemporaryDirectory { temporary in + let fixture = temporary.appendingPathComponent("repository") + try copyRepositoryFixture(to: fixture) + let validator = fixture.appendingPathComponent("Scripts/validate_guidelines.swift").path + let baseline = try run([validator]) + try require(baseline.succeeded, "unmodified interaction policy failed: \(baseline.output)") + for (path, fragments) in mutations { + let file = fixture.appendingPathComponent(path) + let contents = try String(contentsOf: file, encoding: .utf8) + for original in fragments { + try require(contents.contains(original), "missing test fixture text: \(original)") + try write(contents.replacingOccurrences(of: original, with: "REMOVED"), to: file) + let result = try run([validator]) + try require(!result.succeeded, "interaction policy mutation unexpectedly passed: \(original)") + try require(result.output.contains("missing interaction/rendering requirement"), result.output) + try write(contents, to: file) + } + } + } + } + ), + ( + "interaction validator rejects restored Reduce Motion opt-in restriction", + { + try withTemporaryDirectory { temporary in + let fixture = temporary.appendingPathComponent("repository") + try copyRepositoryFixture(to: fixture) + let guide = fixture.appendingPathComponent("Guidelines/Swift/SwiftUI.md") + let contents = try String(contentsOf: guide, encoding: .utf8) + try write( + contents + + "\nDo not introduce app-level Reduce Motion guards unless the task prompt explicitly requests them.\n", + to: guide) + let result = try run([fixture.appendingPathComponent("Scripts/validate_guidelines.swift").path]) + try require(!result.succeeded, "obsolete Reduce Motion restriction unexpectedly passed") + try require(result.output.contains("obsolete Reduce Motion opt-in restriction"), result.output) + } + } + ), + ( + "native-component validator rejects policy and decision drift", + { + let mutations = [ + "Do not substitute a sheet-shaped `ZStack`, offset animation, or custom scrim", + "sheets, alerts, confirmation dialogs, navigation, menus, pickers, popovers", + "Before implementation, obtain explicit repository-owner approval and record a durable exception", + "Pixel fidelity to a static design and preserving mounted state are insufficient", + "Give each child independent dismissal", + "Keep parent-owned draft state alive", + "attach that presentation to the active child hierarchy", + "Make cancellation idempotent", + "reject stale completions after dismissal or replacement", + "presentation's dismissal-completion callback", + "Require an actual gesture and its observed result, or recorded manual verification", + "safe areas, controls and shadow clipping, keyboard/focus restoration", + "Dynamic Type and localization", + "Simulated sheet with a suitable native API and no approved durable exception | Blocked", + "Native nested sheet with branded content, correct ownership, and required interaction evidence | Accepted", + "Custom equivalent for a verified capability gap with owner approval, durable exception, and compensating evidence | Accepted within the approved scope", + "Presentation with missing relevant runtime evidence | Blocked", + ] + for original in mutations { + try withTemporaryDirectory { temporary in + let fixture = temporary.appendingPathComponent("repository") + try copyRepositoryFixture(to: fixture) + let guide = fixture.appendingPathComponent("Guidelines/Swift/SwiftUI.md") + let contents = try String(contentsOf: guide, encoding: .utf8) + try require(contents.contains(original), "missing test fixture text: \(original)") + try write(contents.replacingOccurrences(of: original, with: "REMOVED"), to: guide) + let result = try run([fixture.appendingPathComponent("Scripts/validate_guidelines.swift").path]) + try require(!result.succeeded, "native-component policy mutation unexpectedly passed: \(original)") + try require(result.output.contains("missing native-component policy"), result.output) + } + } + } + ), + ( + "native-component validator rejects audit gate drift", + { + let mutations = [ + "Perform the mandatory [native-component and presentation decision check]", + "Guidelines/Swift/SwiftUI.md#native-components-and-presentation", + "custom modal hosts, overlay/scrim/offset code, and gesture routing", + "native alternative, deployment-target availability", + "explicit repository-owner approval, durable consumer exception", + "required approved and documented exception blocks audit completion", + "child dismissal, parent draft ownership, nested picker/editor presenters", + "cancellation, and dismissal-completion cleanup", + "native nested sheet with branded content is accepted", + "Guidelines/Swift/SwiftUI.md#required-interaction-evidence", + "static screenshots and no-op automation do not establish gesture behavior", + "Missing relevant runtime evidence blocks audit completion", + ] + for original in mutations { + try withTemporaryDirectory { temporary in + let fixture = temporary.appendingPathComponent("repository") + try copyRepositoryFixture(to: fixture) + let skill = fixture.appendingPathComponent(".agents/skills/agent-guidelines-audit/SKILL.md") + let contents = try String(contentsOf: skill, encoding: .utf8) + try require(contents.contains(original), "missing test fixture text: \(original)") + try write(contents.replacingOccurrences(of: original, with: "REMOVED"), to: skill) + let result = try run([fixture.appendingPathComponent("Scripts/validate_guidelines.swift").path]) + try require(!result.succeeded, "native-component audit mutation unexpectedly passed: \(original)") + try require(result.output.contains("SKILL.md: missing"), result.output) + } + } + } + ), + ( + "review evidence validator rejects an unconditional pending gate", + { + try withTemporaryDirectory { temporary in + let fixture = temporary.appendingPathComponent("repository") + try copyRepositoryFixture(to: fixture) + let guide = fixture.appendingPathComponent("Guidelines/GitHub/PullRequests.md") + let contents = try String(contentsOf: guide, encoding: .utf8) + try write(contents + "\nNo review yet means pending.\n", to: guide) + let result = try run([fixture.appendingPathComponent("Scripts/validate_guidelines.swift").path]) + try require(!result.succeeded, "unconditional Codex gate unexpectedly passed") + try require(result.output.contains("unconditional Codex review gate"), result.output) + } + } + ), + ( + "review evidence validator requires unknown state", + { + try withTemporaryDirectory { temporary in + let fixture = temporary.appendingPathComponent("repository") + try copyRepositoryFixture(to: fixture) + let guide = fixture.appendingPathComponent("Guidelines/GitHub/PullRequests.md") + let contents = try String(contentsOf: guide, encoding: .utf8) + try write( + contents.replacingOccurrences(of: "enabled | disabled | unknown", with: "enabled | disabled"), + to: guide) + let result = try run([fixture.appendingPathComponent("Scripts/validate_guidelines.swift").path]) + try require(!result.succeeded, "missing unknown state unexpectedly passed") + try require(result.output.contains("missing Codex review evidence rule"), result.output) + } + } + ), + ( + "review evidence validator protects scenario outcomes and deadline", + { + let mutations = [ + ( + "Disabled with no review | `not_started` | Not blocked by absent Codex review | No", + "Disabled with no review | `not_started` | Pending | Yes" + ), + ( + "Enabled with a current-head processing signal | `processing` | Pending", + "Enabled with a current-head processing signal | `processing` | Satisfied" + ), + ( + "Enabled with a completed review covering the expected head and dispositioned findings | `completed` | Satisfied", + "Enabled with a completed review covering the expected head and dispositioned findings | `completed` | Pending" + ), + ( + "Review completed for an old head | Re-establish for new head", + "Review completed for an old head | Completed for new head" + ), + ( + "An identical fingerprint causes no substantive re-analysis or user notification", + "An identical fingerprint may trigger another notification" + ), + ("including time spent in `processing`", "excluding time spent in `processing`"), + ( + "At the deadline, stop and terminate the monitor, report the observed facts once, and never infer approval", + "At the deadline, keep waiting" + ), + ] + for (original, replacement) in mutations { + try withTemporaryDirectory { temporary in + let fixture = temporary.appendingPathComponent("repository") + try copyRepositoryFixture(to: fixture) + let guide = fixture.appendingPathComponent("Guidelines/GitHub/PullRequests.md") + let contents = try String(contentsOf: guide, encoding: .utf8) + try require(contents.contains(original), "missing test fixture text: \(original)") + try write(contents.replacingOccurrences(of: original, with: replacement), to: guide) + let result = try run([fixture.appendingPathComponent("Scripts/validate_guidelines.swift").path]) + try require(!result.succeeded, "review scenario mutation unexpectedly passed: \(original)") + try require(result.output.contains("Codex review"), result.output) + } + } + } + ), + ( + "repository validator accepts the source tree", + { + let result = try run([script("Scripts/validate_guidelines.swift")]) + try require(result.succeeded, result.output) + try require(result.output.contains("Validated"), "validator did not report success") + } + ), + ( + "repository validator rejects configuration drift", + { + try withTemporaryDirectory { temporary in + let fixture = temporary.appendingPathComponent("repository") + try copyRepositoryFixture(to: fixture) + let configuration = fixture.appendingPathComponent("Configurations/Swift/.swift-format") + var contents = try String(contentsOf: configuration, encoding: .utf8) + contents = contents.replacingOccurrences( + of: "\"NeverForceUnwrap\" : false", with: "\"NeverForceUnwrap\" : true") + try require(contents.contains("\"NeverForceUnwrap\" : true"), "could not mutate fixture configuration") + try write(contents, to: configuration) + let result = try run([fixture.appendingPathComponent("Scripts/validate_guidelines.swift").path]) + try require(!result.succeeded, "configuration drift unexpectedly passed") + try require(result.output.contains("NeverForceUnwrap must be false"), result.output) + } + } + ), + ( + "repository validator rejects missing package compiler policy", + { + try withTemporaryDirectory { temporary in + let fixture = temporary.appendingPathComponent("repository") + try copyRepositoryFixture(to: fixture) + let guideline = fixture.appendingPathComponent("Guidelines/Packages.md") + var contents = try String(contentsOf: guideline, encoding: .utf8) + contents = contents.replacingOccurrences( + of: ".treatAllWarnings(as: .error)", with: ".warningsAsErrors()") + try write(contents, to: guideline) + let result = try run([fixture.appendingPathComponent("Scripts/validate_guidelines.swift").path]) + try require(!result.succeeded, "missing package warning policy unexpectedly passed") + try require(result.output.contains("missing package compiler policy"), result.output) + } + } + ), + ( + "repository validator rejects package upcoming-feature drift", + { + try withTemporaryDirectory { temporary in + let fixture = temporary.appendingPathComponent("repository") + try copyRepositoryFixture(to: fixture) + let guideline = fixture.appendingPathComponent("Guidelines/Packages.md") + var contents = try String(contentsOf: guideline, encoding: .utf8) + contents = contents.replacingOccurrences( + of: ".enableUpcomingFeature(\"NonisolatedNonsendingByDefault\")", + with: ".enableUpcomingFeature(\"ExampleFeature\")" + ) + try write(contents, to: guideline) + let result = try run([fixture.appendingPathComponent("Scripts/validate_guidelines.swift").path]) + try require(!result.succeeded, "package upcoming-feature drift unexpectedly passed") + try require( + result.output.contains( + "missing required SwiftPM upcoming feature 'NonisolatedNonsendingByDefault'"), + result.output + ) + } + } + ), + ( + "repository validator rejects missing package plug-in exclusion", + { + try withTemporaryDirectory { temporary in + let fixture = temporary.appendingPathComponent("repository") + try copyRepositoryFixture(to: fixture) + let guideline = fixture.appendingPathComponent("Guidelines/Packages.md") + var contents = try String(contentsOf: guideline, encoding: .utf8) + contents = contents.replacingOccurrences( + of: "package plug-in targets for which `Target.plugin(...)` does not expose `swiftSettings`", + with: "other package targets" + ) + try write(contents, to: guideline) + let result = try run([fixture.appendingPathComponent("Scripts/validate_guidelines.swift").path]) + try require(!result.succeeded, "missing package plug-in exclusion unexpectedly passed") + try require( + result.output.contains("missing package compiler policy unsupported plug-in target exclusion"), + result.output) + } + } + ), + ( + "repository validator rejects missing experimental StrictConcurrency rule", + { + try withTemporaryDirectory { temporary in + let fixture = temporary.appendingPathComponent("repository") + try copyRepositoryFixture(to: fixture) + let guideline = fixture.appendingPathComponent("Guidelines/Packages.md") + var contents = try String(contentsOf: guideline, encoding: .utf8) + contents = contents.replacingOccurrences( + of: ".enableExperimentalFeature(\"StrictConcurrency\")", + with: ".enableExperimentalFeature(\"ExampleFeature\")" + ) + try write(contents, to: guideline) + let result = try run([fixture.appendingPathComponent("Scripts/validate_guidelines.swift").path]) + try require(!result.succeeded, "missing experimental StrictConcurrency rule unexpectedly passed") + try require( + result.output.contains( + "missing package compiler policy experimental StrictConcurrency redundancy rule"), result.output + ) + } + } + ), + ( + "repository validator rejects missing upcoming StrictConcurrency rule", + { + try withTemporaryDirectory { temporary in + let fixture = temporary.appendingPathComponent("repository") + try copyRepositoryFixture(to: fixture) + let guideline = fixture.appendingPathComponent("Guidelines/Packages.md") + var contents = try String(contentsOf: guideline, encoding: .utf8) + contents = contents.replacingOccurrences( + of: ".enableUpcomingFeature(\"StrictConcurrency\")", + with: ".enableUpcomingFeature(\"ExampleFeature\")" + ) + try write(contents, to: guideline) + let result = try run([fixture.appendingPathComponent("Scripts/validate_guidelines.swift").path]) + try require(!result.succeeded, "missing upcoming StrictConcurrency rule unexpectedly passed") + try require( + result.output.contains( + "missing package compiler policy upcoming StrictConcurrency redundancy rule"), result.output + ) + } + } + ), + ( + "repository validator rejects missing explicit StrictConcurrency rule", + { + try withTemporaryDirectory { temporary in + let fixture = temporary.appendingPathComponent("repository") + try copyRepositoryFixture(to: fixture) + let guideline = fixture.appendingPathComponent("Guidelines/Packages.md") + var contents = try String(contentsOf: guideline, encoding: .utf8) + contents = contents.replacingOccurrences( + of: "StrictConcurrency=complete", + with: "StrictConcurrency=minimal" + ) + try write(contents, to: guideline) + let result = try run([fixture.appendingPathComponent("Scripts/validate_guidelines.swift").path]) + try require(!result.succeeded, "missing explicit StrictConcurrency rule unexpectedly passed") + try require( + result.output.contains( + "missing package compiler policy explicit StrictConcurrency redundancy rule"), result.output + ) + } + } + ), + ( + "repository validator rejects missing Xcode package-parity maintenance", + { + try withTemporaryDirectory { temporary in + let fixture = temporary.appendingPathComponent("repository") + try copyRepositoryFixture(to: fixture) + let guideline = fixture.appendingPathComponent("Guidelines/Xcode/ProjectSettings.md") + var contents = try String(contentsOf: guideline, encoding: .utf8) + contents = contents.replacingOccurrences( + of: "../Packages.md#compiler-settings-baseline", with: "package-policy") + try write(contents, to: guideline) + let result = try run([fixture.appendingPathComponent("Scripts/validate_guidelines.swift").path]) + try require(!result.succeeded, "missing Xcode package-parity maintenance unexpectedly passed") + try require(result.output.contains("missing Swift package baseline cross-reference"), result.output) + } + } + ), + ( + "repository validator rejects missing package emoji uniqueness policy", + { + try withTemporaryDirectory { temporary in + let fixture = temporary.appendingPathComponent("repository") + try copyRepositoryFixture(to: fixture) + let guideline = fixture.appendingPathComponent("Guidelines/Packages.md") + var contents = try String(contentsOf: guideline, encoding: .utf8) + contents = contents.replacingOccurrences( + of: "Each package emoji must be unique across ThatFactory", + with: "Package emojis should be recognizable" + ) + try write(contents, to: guideline) + let result = try run([fixture.appendingPathComponent("Scripts/validate_guidelines.swift").path]) + try require(!result.succeeded, "missing package emoji uniqueness policy unexpectedly passed") + try require(result.output.contains("missing package emoji uniqueness policy"), result.output) + } + } + ), + ( + "repository validator rejects missing package audit section", + { + try withTemporaryDirectory { temporary in + let fixture = temporary.appendingPathComponent("repository") + try copyRepositoryFixture(to: fixture) + let skill = fixture.appendingPathComponent(".agents/skills/agent-guidelines-audit/SKILL.md") + var contents = try String(contentsOf: skill, encoding: .utf8) + contents = contents.replacingOccurrences( + of: "## Audit Swift package settings", with: "## Inspect Swift manifests") + try write(contents, to: skill) + let result = try run([fixture.appendingPathComponent("Scripts/validate_guidelines.swift").path]) + try require(!result.succeeded, "missing package audit section unexpectedly passed") + try require(result.output.contains("missing Swift package-settings audit"), result.output) + } + } + ), + ( + "repository validator rejects package audit behavior drift", + { + try withTemporaryDirectory { temporary in + let fixture = temporary.appendingPathComponent("repository") + try copyRepositoryFixture(to: fixture) + let skill = fixture.appendingPathComponent(".agents/skills/agent-guidelines-audit/SKILL.md") + var contents = try String(contentsOf: skill, encoding: .utf8) + contents = contents.replacingOccurrences( + of: "swift package --package-path dump-package", + with: "inspect the manifest" + ) + try write(contents, to: skill) + let result = try run([fixture.appendingPathComponent("Scripts/validate_guidelines.swift").path]) + try require(!result.succeeded, "package audit behavior drift unexpectedly passed") + try require(result.output.contains("missing evaluated manifest inspection"), result.output) + } + } + ), + ( + "repository validator rejects package emoji audit drift", + { + try withTemporaryDirectory { temporary in + let fixture = temporary.appendingPathComponent("repository") + try copyRepositoryFixture(to: fixture) + let skill = fixture.appendingPathComponent(".agents/skills/agent-guidelines-audit/SKILL.md") + var contents = try String(contentsOf: skill, encoding: .utf8) + contents = contents.replacingOccurrences( + of: "Enumerate the registered package entries", + with: "Inspect the package registry" + ) + try write(contents, to: skill) + let result = try run([fixture.appendingPathComponent("Scripts/validate_guidelines.swift").path]) + try require(!result.succeeded, "package emoji audit drift unexpectedly passed") + try require(result.output.contains("missing package emoji registry enumeration"), result.output) + } + } + ), + ( + "repository validator rejects missing observability adoption guidance", + { + try withTemporaryDirectory { temporary in + let fixture = temporary.appendingPathComponent("repository") + try copyRepositoryFixture(to: fixture) + let readme = fixture.appendingPathComponent("README.md") + var contents = try String(contentsOf: readme, encoding: .utf8) + contents = contents.replacingOccurrences(of: "runtime-observability contract", with: "runtime contract") + try write(contents, to: readme) + let result = try run([fixture.appendingPathComponent("Scripts/validate_guidelines.swift").path]) + try require(!result.succeeded, "missing observability adoption guidance unexpectedly passed") + try require( + result.output.contains("missing runtime observability contract synchronization"), result.output) + } + } + ), + ( + "repository validator rejects private dependency authentication drift", + { + try withTemporaryDirectory { temporary in + let fixture = temporary.appendingPathComponent("repository") + try copyRepositoryFixture(to: fixture) + let guideline = fixture.appendingPathComponent("Guidelines/CICD.md") + var contents = try String(contentsOf: guideline, encoding: .utf8) + contents = contents.replacingOccurrences( + of: "isolated disposable or ephemeral self-hosted runner", + with: "self-hosted runner") + try write(contents, to: guideline) + let result = try run([fixture.appendingPathComponent("Scripts/validate_guidelines.swift").path]) + try require(!result.succeeded, "private dependency authentication drift unexpectedly passed") + try require( + result.output.contains("missing untrusted-code runner isolation"), + result.output + ) + } + } + ), + ( + "repository validator rejects gitignore template drift", + { + try withTemporaryDirectory { temporary in + let fixture = temporary.appendingPathComponent("repository") + try copyRepositoryFixture(to: fixture) + let template = fixture.appendingPathComponent("Templates/.gitignore") + var contents = try String(contentsOf: template, encoding: .utf8) + contents = contents.replacingOccurrences(of: "node_modules/\n", with: "") + try write(contents, to: template) + let result = try run([fixture.appendingPathComponent("Scripts/validate_guidelines.swift").path]) + try require(!result.succeeded, "gitignore template drift unexpectedly passed") + try require( + result.output.contains("Templates/.gitignore: missing required pattern 'node_modules/'"), + result.output + ) + } + } + ), + ( + "repository validator rejects forbidden tooling in gitignore template", + { + try withTemporaryDirectory { temporary in + let fixture = temporary.appendingPathComponent("repository") + try copyRepositoryFixture(to: fixture) + let template = fixture.appendingPathComponent("Templates/.gitignore") + var contents = try String(contentsOf: template, encoding: .utf8) + contents += "fastlane/test_output/\n" + try write(contents, to: template) + let result = try run([fixture.appendingPathComponent("Scripts/validate_guidelines.swift").path]) + try require(!result.succeeded, "forbidden tooling pattern unexpectedly passed") + try require( + result.output.contains("must not include forbidden tooling pattern 'fastlane/'"), + result.output + ) + } + } + ), + ( + "Markdown checker reports governed wrapping", + { + try withTemporaryDirectory { root in + let markdown = root.appendingPathComponent("Example.md") + try write( + """ + # Example + + This paragraph was split + across physical lines. + + - This list item was split + across physical lines too. + + > This quotation was split + > across physical lines as well. + """ + "\n", + to: markdown + ) + let result = try run([ + script(".agents/skills/agent-guidelines-audit/scripts/check_markdown_wrapping.swift"), + markdown.path, + ]) + try require(!result.succeeded, "wrapped prose unexpectedly passed") + for expected in [ + ":3: paragraph spans physical lines 3-4", + ":6: list item spans physical lines 6-7", + ":9: block quote (depth 1) spans physical lines 9-10", + ] { + try require(result.output.contains(expected), "missing diagnostic: \(expected)\n\(result.output)") + } + } + } + ), + ( + "Markdown checker accepts GitHub alerts", + { + try withTemporaryDirectory { root in + let markdown = root.appendingPathComponent("Alerts.md") + try write( + """ + # Alerts + + > [!NOTE] + > Note body. + + > [!TIP] + > Tip body. + + > [!IMPORTANT] + > Important body. + + > [!WARNING] + > Warning body. + + > [!CAUTION] + > Caution body. + """ + "\n", + to: markdown + ) + let result = try run([ + script(".agents/skills/agent-guidelines-audit/scripts/check_markdown_wrapping.swift"), + markdown.path, + ]) + try require(result.succeeded, result.output) + } + } + ), + ( + "Markdown checker rejects wrapped or malformed GitHub alerts", + { + try withTemporaryDirectory { root in + let markdown = root.appendingPathComponent("Alerts.md") + try write( + """ + # Alerts + + > [!NOTE] + > This alert body was split + > across physical lines. + + > [!UNKNOWN] + > Unknown alert body. + + > > [!TIP] + > > Nested alert body. + + > Ordinary quote begins. + > [!NOTE] + > Ordinary quote continues. + """ + "\n", + to: markdown + ) + let result = try run([ + script(".agents/skills/agent-guidelines-audit/scripts/check_markdown_wrapping.swift"), + markdown.path, + ]) + try require(!result.succeeded, "invalid alerts unexpectedly passed") + for expected in [ + ":4: block quote (depth 1) spans physical lines 4-5", + ":7: block quote (depth 1) spans physical lines 7-8", + ":10: block quote (depth 2) spans physical lines 10-11", + ":13: block quote (depth 1) spans physical lines 13-15", + ] { + try require(result.output.contains(expected), "missing diagnostic: \(expected)\n\(result.output)") + } + } + } + ), + ( + "Markdown checker accepts verbatim structures", + { + try withTemporaryDirectory { root in + let markdown = root.appendingPathComponent("Example.md") + try write( + """ + --- + title: Example + --- + + # Example + + One physical line of prose. + + | Role | Folder | + |---|---| + | App | `App/` | + + ```text + diagram + ``` + +

+ Badge +

+ + - Parent item. + - Nested item. + """ + "\n", + to: markdown + ) + let result = try run([ + script(".agents/skills/agent-guidelines-audit/scripts/check_markdown_wrapping.swift"), + markdown.path, + ]) + try require(result.succeeded, result.output) + } + } + ), + ( + "String Catalog inspection fails closed for every Git change kind", + { + try withTemporaryDirectory { root in + try initializeRepository(at: root) + for name in ["Modified.xcstrings", "DeletedThenRenamed.xcstrings", "Copied.xcstrings"] { + try write("{}\n", to: root.appendingPathComponent(name)) + } + try git("add", ".", in: root) + try git("commit", "-m", "Fixture", in: root) + try write(#"{"sourceLanguage":"en"}"# + "\n", to: root.appendingPathComponent("Modified.xcstrings")) + try git("mv", "DeletedThenRenamed.xcstrings", "Renamed.xcstrings", in: root) + try fileManager.copyItem( + at: root.appendingPathComponent("Copied.xcstrings"), + to: root.appendingPathComponent("Added.xcstrings") + ) + try git("add", "Added.xcstrings", in: root) + try write("{}\n", to: root.appendingPathComponent("Untracked.xcstrings")) + let result = try run( + [ + script(".agents/skills/agent-guidelines-audit/scripts/check_xcstrings_inspection.swift"), + "--repository", root.path, "--base-ref", "HEAD", + ] + ) + try require(!result.succeeded, "missing editor evidence unexpectedly passed") + for name in ["Added.xcstrings", "Modified.xcstrings", "Renamed.xcstrings", "Untracked.xcstrings"] { + try require( + result.output.contains("missing Xcode catalog-editor inspection evidence: \(name)"), + "missing changed catalog \(name): \(result.output)") + } + try require(result.output.contains("--evidence-output is required"), result.output) + } + } + ), + ( + "String Catalog inspection records structured zero-diagnostic evidence", + { + try withTemporaryDirectory { temporary in + let root = temporary.appendingPathComponent("repository") + try fileManager.createDirectory(at: root, withIntermediateDirectories: true) + try initializeRepository(at: root) + let catalog = root.appendingPathComponent("Localizable.xcstrings") + try write("{}\n", to: catalog) + try git("add", ".", in: root) + try git("commit", "-m", "Fixture", in: root) + try write(#"{"sourceLanguage":"en"}"# + "\n", to: catalog) + let evidence = temporary.appendingPathComponent("evidence.json") + let result = try run( + [ + script(".agents/skills/agent-guidelines-audit/scripts/check_xcstrings_inspection.swift"), + "--repository", root.path, "--base-ref", "HEAD", "--inspected-catalog", + "Localizable.xcstrings", "--evidence-output", evidence.path, + ] + ) + try require(result.succeeded, result.output) + let data = try Data(contentsOf: evidence) + let object = try JSONSerialization.jsonObject(with: data) as? [String: Any] + let catalogs = object?["catalogs"] as? [[String: Any]] + try require(object?["baseRef"] as? String == "HEAD", "base ref was not recorded") + try require( + (object?["xcodeVersion"] as? String)?.contains("Xcode") == true, "Xcode version was not recorded") + try require( + catalogs?.first?["path"] as? String == "Localizable.xcstrings", "catalog path was not recorded") + try require(catalogs?.first?["catalogEditorWarnings"] as? Int == 0, "warning count was not zero") + try require(catalogs?.first?["catalogEditorErrors"] as? Int == 0, "error count was not zero") + } + } + ), + ( + "symbol preparation preserves translations and stale entries", + { + try withTemporaryDirectory { root in + let catalog = root.appendingPathComponent("Localizable.xcstrings") + try write( + """ + {"sourceLanguage":"en","strings":{ + "Legacy value":{"comment":"Visible title","extractionState":"extracted_with_value","localizations":{"de":\(localization("Alter Wert"))}}, + "Old value":{"extractionState":"stale","localizations":{"en":\(localization("Old"))}} + },"version":"1.1"} + """ + "\n", + to: catalog + ) + let check = try run([script("Scripts/prepare_localizable_symbols.swift"), catalog.path, "--check"]) + try require(!check.succeeded, "unprepared catalog unexpectedly passed") + let preparation = try run([script("Scripts/prepare_localizable_symbols.swift"), catalog.path]) + try require(preparation.succeeded, preparation.output) + let data = try Data(contentsOf: catalog) + let object = try JSONSerialization.jsonObject(with: data) as? [String: Any] + let strings = object?["strings"] as? [String: Any] + let active = strings?["Legacy value"] as? [String: Any] + let activeLocalizations = active?["localizations"] as? [String: Any] + let stale = strings?["Old value"] as? [String: Any] + try require(active?["extractionState"] as? String == "manual", "active key was not made manual") + try require(active?["comment"] as? String == "Visible title", "comment was not preserved") + try require( + activeLocalizations?["de"] != nil && activeLocalizations?["en"] != nil, + "translations were not preserved") + try require(stale?["extractionState"] as? String == "stale", "stale key was revived") + let finalCheck = try run([script("Scripts/prepare_localizable_symbols.swift"), catalog.path, "--check"]) + try require(finalCheck.succeeded, finalCheck.output) + } + } + ), + ( + "symbol preparation rejects manual entries without source copy", + { + try withTemporaryDirectory { root in + let catalog = root.appendingPathComponent("Localizable.xcstrings") + try write( + #"{"sourceLanguage":"en","strings":{"semanticKey":{"extractionState":"manual","localizations":{"de":{"stringUnit":{"state":"translated","value":"Wert"}}}}}}"#, + to: catalog + ) + let result = try run([script("Scripts/prepare_localizable_symbols.swift"), catalog.path]) + try require(!result.succeeded, "invalid manual key unexpectedly passed") + try require(result.output.contains("manual entry has no en source value"), result.output) + } + } + ), + ( + "String Catalog validator accepts valid symbols, states, and formats", + { + try withTemporaryDirectory { root in + let catalogs = root.appendingPathComponent("Catalogs") + let sources = root.appendingPathComponent("Sources") + try fileManager.createDirectory(at: sources, withIntermediateDirectories: true) + try write( + """ + {"sourceLanguage":"en","strings":{"summary":{"extractionState":"manual","localizations":{ + "en":\(localization("%1$(count)lld items")), + "de":\(localization("%1$(count)lld Einträge", state: "machine_translated")) + }}}} + """ + "\n", + to: catalogs.appendingPathComponent("Localizable.xcstrings") + ) + let result = try run( + [ + script("Scripts/validate_string_catalogs.swift"), "--catalog-directory", catalogs.path, + "--source-directory", sources.path, "--required-language", "de", + ] + ) + try require(result.succeeded, result.output) + } + } + ), + ( + "String Catalog validator reports independent catalog defects", + { + try withTemporaryDirectory { root in + let catalogs = root.appendingPathComponent("Catalogs") + let sources = root.appendingPathComponent("Sources") + try fileManager.createDirectory(at: sources, withIntermediateDirectories: true) + try write( + """ + {"sourceLanguage":"en","strings":{ + "count":{"extractionState":"manual","localizations":{"en":\(localization("%1$(count)lld items")),"de":\(localization("%1$(value)@ Einträge", state: "needs_review"))}}, + "Old":{"extractionState":"stale"} + }} + """ + "\n", + to: catalogs.appendingPathComponent("Localizable.xcstrings") + ) + let result = try run( + [ + script("Scripts/validate_string_catalogs.swift"), "--catalog-directory", catalogs.path, + "--source-directory", sources.path, "--required-language", "de", "--required-language", "fr", + ] + ) + try require(!result.succeeded, "invalid catalog unexpectedly passed") + for expected in [ + "stale extracted strings", "format specifiers", "required localization is missing", + "unfinished states needs_review", + ] { + try require(result.output.contains(expected), "missing diagnostic \(expected): \(result.output)") + } + } + } + ), + ( + "consumer validator rejects package README License headings", + { + for readme in [ + "# Package\n\n## License\n", "# Package\n\n#### lIcEnSe ####\n", + "# Package\n\nLicense\n-------\n", "# Package\n\nLICENSE\n=======\n", + ] { + try withTemporaryDirectory { root in + try createConsumerFixture(at: root, isPackage: true, readme: readme) + let result = try run([ + script("Scripts/validate_consumer_setup.swift"), "--consumer-root", root.path, + ]) + try require(!result.succeeded, "package License heading unexpectedly passed") + try require(result.output.contains("must not contain a dedicated License heading"), result.output) + } + } + } + ), + ( + "consumer validator rejects standalone package README license prose", + { + try withTemporaryDirectory { root in + try createConsumerFixture( + at: root, + isPackage: true, + readme: "# Example\n\nExample is available under the MIT license. See [LICENSE](LICENSE).\n" + ) + let result = try run([ + script("Scripts/validate_consumer_setup.swift"), "--consumer-root", root.path, + ]) + try require(!result.succeeded, "standalone package license prose unexpectedly passed") + try require( + result.output.contains("must not contain a standalone license-description paragraph"), + result.output + ) + } + } + ), + ( + "consumer validator accepts package license badge and absent README", + { + try withTemporaryDirectory { root in + try createConsumerFixture( + at: root, + isPackage: true, + readme: """ + # Example + + ![License](https://img.shields.io/badge/License-MIT-green.svg) + + See [LICENSE](LICENSE) when verifying redistribution terms. + + ````markdown + ```markdown + ## License section example + + Example is available under the MIT license. See [LICENSE](LICENSE). + ``` + ```` + + ~~~text + # License + ~~~ + """ + "\n" + ) + let result = try run([ + script("Scripts/validate_consumer_setup.swift"), "--consumer-root", root.path, + ]) + try require(result.succeeded, result.output) + } + try withTemporaryDirectory { root in + try createConsumerFixture(at: root, isPackage: true) + let result = try run([ + script("Scripts/validate_consumer_setup.swift"), "--consumer-root", root.path, + ]) + try require(result.succeeded, result.output) + } + } + ), + ( + "consumer validator limits README license policy to package roots", + { + try withTemporaryDirectory { root in + try createConsumerFixture(at: root, isPackage: false, readme: "# App\n\n## License\n") + try write( + "# License\n\nStandalone documentation may discuss licensing.\n", + to: root.appendingPathComponent("Documentation/README.md") + ) + let result = try run([ + script("Scripts/validate_consumer_setup.swift"), "--consumer-root", root.path, + ]) + try require(result.succeeded, result.output) + } + } + ), + ( + "consumer validator accepts synchronized integration", + { + try withTemporaryDirectory { root in + try fileManager.createSymbolicLink( + at: root.appendingPathComponent("AgentGuidelines"), withDestinationURL: repositoryRoot) + try fileManager.copyItem( + at: repositoryRoot.appendingPathComponent("Templates/AGENTS.md"), + to: root.appendingPathComponent("AGENTS.md")) + try write("AgentGuidelines/** linguist-generated\n", to: root.appendingPathComponent(".gitattributes")) + let skillParent = root.appendingPathComponent(".agents/skills") + try fileManager.createDirectory(at: skillParent, withIntermediateDirectories: true) + try fileManager.createSymbolicLink( + at: skillParent.appendingPathComponent("agent-guidelines-audit"), + withDestinationURL: repositoryRoot.appendingPathComponent(".agents/skills/agent-guidelines-audit") + ) + try fileManager.createSymbolicLink( + at: root.appendingPathComponent(".swift-format"), + withDestinationURL: repositoryRoot.appendingPathComponent("Configurations/Swift/.swift-format") + ) + try fileManager.createSymbolicLink( + at: root.appendingPathComponent(".editorconfig"), + withDestinationURL: repositoryRoot.appendingPathComponent("Configurations/Swift/.editorconfig") + ) + try write( + """ + name: CI + on: + pull_request: + push: + branches: [main] + jobs: + swift-format: + steps: + - run: AgentGuidelines/Scripts/swift_format.sh lint-strict Sources + """ + "\n", + to: root.appendingPathComponent(".github/workflows/ci.yml") + ) + let result = try run([script("Scripts/validate_consumer_setup.swift"), "--consumer-root", root.path]) + try require(result.succeeded, result.output) + } + } + ), + ( + "consumer validator rejects copied audit skill and contract drift", + { + try withTemporaryDirectory { root in + try fileManager.createSymbolicLink( + at: root.appendingPathComponent("AgentGuidelines"), withDestinationURL: repositoryRoot) + let template = try String( + contentsOf: repositoryRoot.appendingPathComponent("Templates/AGENTS.md"), encoding: .utf8) + try write( + template.replacingOccurrences( + of: "P0/P1", with: "P0", options: [], range: template.range(of: "P0/P1")), + to: root.appendingPathComponent("AGENTS.md")) + try write("*.md text\n", to: root.appendingPathComponent(".gitattributes")) + let skill = root.appendingPathComponent(".agents/skills/agent-guidelines-audit") + try fileManager.createDirectory(at: skill, withIntermediateDirectories: true) + try write("stale copy\n", to: skill.appendingPathComponent("SKILL.md")) + let result = try run([script("Scripts/validate_consumer_setup.swift"), "--consumer-root", root.path]) + try require(!result.succeeded, "invalid consumer unexpectedly passed") + for expected in ["code-review contract does not match", "linguist-generated", "must be a symlink"] { + try require(result.output.contains(expected), "missing diagnostic \(expected): \(result.output)") + } + } + } + ), +] + +var failures = 0 +for (name, test) in tests { + do { + try test() + print("PASS \(name)") + } catch { + failures += 1 + FileHandle.standardError.write(Data("FAIL \(name): \(error)\n".utf8)) + } +} + +if failures > 0 { + FileHandle.standardError.write(Data("\(failures) of \(tests.count) tests failed.\n".utf8)) + exit(1) +} + +print("All \(tests.count) native Swift tests passed.") diff --git a/VERSION b/VERSION new file mode 100644 index 0000000..fad9d0a --- /dev/null +++ b/VERSION @@ -0,0 +1 @@ +0.0.47 From 2a0e606d73324c53634f0b34cc11b4e57a59c9dc Mon Sep 17 00:00:00 2001 From: Fernando Fernandes Date: Fri, 6 Nov 2026 23:54:16 +0100 Subject: [PATCH 2/3] Squashed 'AgentGuidelines/' changes from 1c95766..6aadcc2 6aadcc2 Simplify the automatic Codex review declaration (#58) git-subtree-dir: AgentGuidelines git-subtree-split: 6aadcc2fef5d9dcf7a64f91526dbfac453378200 --- AGENTS.md | 2 +- CHANGELOG.md | 6 ++++++ README.md | 4 ++-- VERSION | 2 +- 4 files changed, 10 insertions(+), 4 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 7db1e04..0f37c0a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -91,4 +91,4 @@ When reviewing a consumer pull request, do not review or comment on files under ## Repository review configuration -The owner confirmed automatic Codex review is enabled for this repository on 2026-11-06. Use all PR authors and the opening/ready trigger, keep exhaustive review off, and keep separate Security Review manual. Apply the managed lifecycle and [review-policy integration](ReviewPolicy/README.md). +Automatic Codex PR review is enabled. Use all PR authors and the opening/ready trigger, keep exhaustive review off, and keep separate Security Review manual. Apply the managed lifecycle and [review-policy integration](ReviewPolicy/README.md). diff --git a/CHANGELOG.md b/CHANGELOG.md index 4c7ad3c..1ece3b4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,12 @@ All notable changes to this project are documented in this file. +## [0.0.48] - 2026-11-06 + +### Changed + +- Simplified the repository review declaration to state directly that automatic Codex PR review is enabled. The canonical review contracts and independent review-policy revision remain unchanged. + ## [0.0.47] - 2026-11-06 ### Added diff --git a/README.md b/README.md index dbaa196..bea794f 100644 --- a/README.md +++ b/README.md @@ -94,7 +94,7 @@ From the consumer repository root, install a tagged release: git subtree add \ --prefix=AgentGuidelines \ https://github.com/thatfactory/agent-guidelines.git \ - 0.0.47 \ + 0.0.48 \ --squash ``` @@ -156,7 +156,7 @@ Review the target release's changelog, then pull it deliberately: git subtree pull \ --prefix=AgentGuidelines \ https://github.com/thatfactory/agent-guidelines.git \ - 0.0.47 \ + 0.0.48 \ --squash ``` diff --git a/VERSION b/VERSION index fad9d0a..a24809a 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -0.0.47 +0.0.48 From 72ebd0b4b724c365cdcda3b414b0a83ca8ce1f9d Mon Sep 17 00:00:00 2001 From: Fernando Fernandes Date: Sat, 7 Nov 2026 00:03:00 +0100 Subject: [PATCH 3/3] Integrate the managed Codex review policy and PR lifecycle --- .github/workflows/ci-pr.yml | 4 ++++ .github/workflows/ci.yml | 4 ++++ AGENTS.md | 47 +++++++++++++++++-------------------- 3 files changed, 30 insertions(+), 25 deletions(-) diff --git a/.github/workflows/ci-pr.yml b/.github/workflows/ci-pr.yml index 812d031..585d0f8 100644 --- a/.github/workflows/ci-pr.yml +++ b/.github/workflows/ci-pr.yml @@ -17,6 +17,10 @@ jobs: - name: Checkout Repository uses: actions/checkout@v7 + - name: Validate latest Codex review policy + uses: thatfactory/agent-guidelines/.github/actions/codex-review-policy@1c957669005eea010131c53f0a4146db2ccf7859 + with: + profile: full - name: Validate Consumer Integration run: AgentGuidelines/Scripts/validate_consumer_setup.swift diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index cea53a9..7fc8f82 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -18,6 +18,10 @@ jobs: - name: Checkout Repository uses: actions/checkout@v7 + - name: Validate latest Codex review policy + uses: thatfactory/agent-guidelines/.github/actions/codex-review-policy@1c957669005eea010131c53f0a4146db2ccf7859 + with: + profile: full - name: Validate Consumer Integration run: AgentGuidelines/Scripts/validate_consumer_setup.swift diff --git a/AGENTS.md b/AGENTS.md index 268ceac..8e9d753 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -27,21 +27,28 @@ Read only the guides relevant to the task: Redux, SwiftUI, and application-localization guidance do not apply to the package target. - + + ## Code Review Rules -Review for release-blocking defects introduced or materially exposed by the pull request. A clean review means no unresolved P0/P1 findings; it does not mean exhaustive or perfect software. +Report only substantiated P0/P1 defects introduced or materially exposed by this change. Require a concrete, reachable failure in a supported use case or documented threat model, with serious impact such as a security-boundary bypass, durable data loss or corruption, a crash or deadlock in an important workflow, loss of availability, or a serious compatibility regression. An acceptance-criterion violation alone does not establish P1 severity. -A blocking finding must identify a concrete, reachable path in a supported use case or the documented threat model that can cause a credible security-boundary bypass, durable data loss or corruption, a crash or deadlock, loss of availability, violation of an explicit acceptance criterion, or a serious compatibility regression. +For each finding, state severity, preconditions, execution path, impact, evidence, and actionable remediation. Group manifestations of one root cause. Report substantiated blockers together. Omit unsolicited P2/P3 observations, style preferences, speculative hardening, optional tests, and refactors. A clean review means no unresolved P0/P1 blockers, not perfect software. -For every blocking finding, state the severity, preconditions, execution path, impact, evidence, and actionable remediation. Group manifestations that share the same root cause into one finding. +A follow-up review covers unresolved P0/P1 findings, changes since the previous reviewed commit, and directly affected code. Do not restart a full review of unchanged code. New follow-up findings must be P0/P1 defects introduced by remediation or genuinely hidden by the previous blocker. + -Treat P2/P3 observations as non-blocking, including defense-in-depth, theoretical completeness, unsupported use cases, malformed state that trusted code cannot produce, behavior by components outside the threat model, style preferences, and speculative refactoring. Record a useful lower-severity observation once as deferred, declined, duplicate, or follow-up work; do not keep the review loop open for it. + +## Pull Request Lifecycle -In an initial review, report substantiated blockers together. A follow-up review is limited to unresolved P0/P1 findings, changes since the last reviewed commit, and code directly affected by those changes. Do not restart an unrestricted review of unchanged code. A new follow-up finding must be a P0/P1 defect introduced by the remediation or genuinely hidden by the previous blocker. +Finish implementation, inspect the diff, and run relevant local validation before opening a ready-for-review PR. Drafts are for incomplete preparation; mark ready before waiting for automatic review. Keep the review head stable while the initial review runs. One automatic Codex review is the initial review; never duplicate it with a manual request or repeatedly toggle draft/ready state. -Automatic Codex review is the initial review. Do not request a manual Codex review unless the repository owner explicitly asks. Never request another review after each remediation commit. Within the normal review budget, at most one owner-authorized, delta-scoped verification review may be requested under [the pull-request review workflow](AgentGuidelines/Guidelines/GitHub/PullRequests.md). - +Establish review configuration from repository-specific evidence. Verify the bot, PR, review round, and reviewed commit using PR/request-comment reactions, review submissions, inline threads, and checks. Eyes means processing, not approval; a thumbs-up means no suggestions only for its verified review round. Historical reactions, missing comments, and elapsed time never certify a newer head. Monitor at most five minutes total with bounded, non-accelerating polls; timeout leaves a required gate unresolved and never authorizes merge. + +Batch accepted P0/P1 fixes, verify them locally, rerun affected checks, and disposition and resolve every review thread. A completed initial review plus an explicitly recorded, locally verified remediation-only delta can satisfy the review gate; do not claim Codex reviewed the newer head. New unrelated scope belongs in another PR. Request at most one delta-scoped verification only when the owner explicitly authorizes it. Do not request reviews after every fix or casually mention the bot to start extra work. Separate Security Review is manual and requires explicit owner instruction. + +Before merge, rerun the latest published review-policy check, confirm no required review is pending, no unresolved P0/P1 blocker remains, every thread is dispositioned and resolved, required checks pass on the current head, and existing human approval or merge authorization is satisfied. A bot thumbs-up is not a substitute for required GitHub approval. Opening a PR does not authorize merging it. + ## Physical folder map @@ -76,19 +83,21 @@ Treat privacy-safe runtime observability as part of implementing or changing sta Every ThatFactory package log starts with its canonical emoji and uses its own stable subsystem. Never log credentials, account or record identifiers, share URLs, captured content, images, or other user-generated values as public metadata. Keep pure values and utilities silent when they have no meaningful diagnostic event; record that deliberate decision in the implementation handoff instead of adding initializer or property-access noise. Follow [Logging](AgentGuidelines/Guidelines/Logging.md) for ownership, privacy, severity, message design, and tests. - + ## External Dependency Policy Do not introduce third-party source or binary dependencies into ThatFactory applications, games, or reusable packages during normal development. Prefer Apple platform APIs, the Swift standard library, code owned by the current repository, or focused ThatFactory-owned packages. If reusable capability is missing, implement it natively at the appropriate boundary and consider extracting it into a first-party package instead of selecting an external library. -A third-party dependency may be added, or expanded to a new target or runtime role, only with explicit repository-owner approval for that specific use before modifying the dependency graph. Convenience, reduced implementation effort, popularity, or an agent's preference for an existing library are not sufficient justification. Do not make an external library acceptable merely by hiding it behind a first-party wrapper. +A third-party dependency may be added, or expanded to a new target or runtime role, only under an explicit standing approval in these guidelines or with explicit repository-owner approval for that specific use before modifying the dependency graph. Convenience, reduced implementation effort, popularity, or an agent's preference for an existing library are not sufficient justification. Do not make an external library acceptable merely by hiding it behind a first-party wrapper. Document every approved exception in durable repository documentation in the same change. Record the dependency and source, purpose and target scope, why a native or first-party implementation is not appropriate, relevant license, security, and maintenance considerations, and the approval context. Merely mentioning or using the dependency in an execution plan, pull-request description, or transient chat is not approval. Regardless of where explicit approval occurs, reflect the exception in durable repository documentation. Apple system frameworks and the Swift standard library are not third-party dependencies. ThatFactory-owned packages are first-party dependencies. Tooling explicitly required by the shared guidelines is allowed only for its documented tooling role and must not be linked into or shipped with product runtime targets unless separately approved and documented. +Follow [Networking](AgentGuidelines/Guidelines/Networking.md) for Apple-native networking and typed HTTP. Its narrow standing approval for Apple's `swift-http-types` applies only to the documented HTTPTypes and HTTPTypesFoundation runtime role; it does not approve other Apple open-source packages or unrelated roles. Use the guide's normal dependency documentation for that role instead of requesting a separate consumer exception. + Follow [Development workflow](AgentGuidelines/Guidelines/Development.md) for the detailed policy. - + ## Documentation Maintenance @@ -100,20 +109,8 @@ Update documentation when a change alters durable or core feature behavior or an Do not create documentation churn for incidental implementation details that are not durable and do not affect an existing documented claim. Follow [Documentation](AgentGuidelines/Guidelines/Documentation.md) for detailed scope and the completion checklist. - -## Code Review Rules - -Review for release-blocking defects introduced or materially exposed by the pull request. A clean review means no unresolved P0/P1 findings; it does not mean exhaustive or perfect software. - -A blocking finding must identify a concrete, reachable path in a supported use case or the documented threat model that can cause a credible security-boundary bypass, durable data loss or corruption, a crash or deadlock, loss of availability, violation of an explicit acceptance criterion, or a serious compatibility regression. - -For every blocking finding, state the severity, preconditions, execution path, impact, evidence, and actionable remediation. Group manifestations that share the same root cause into one finding. - -Treat P2/P3 observations as non-blocking, including defense-in-depth, theoretical completeness, unsupported use cases, malformed state that trusted code cannot produce, behavior by components outside the threat model, style preferences, and speculative refactoring. Record a useful lower-severity observation once as deferred, declined, duplicate, or follow-up work; do not keep the review loop open for it. -In an initial review, report substantiated blockers together. A follow-up review is limited to unresolved P0/P1 findings, changes since the last reviewed commit, and code directly affected by those changes. Do not restart an unrestricted review of unchanged code. A new follow-up finding must be a P0/P1 defect introduced by the remediation or genuinely hidden by the previous blocker. -The review-round budget below applies only to Codex GitHub reviews: the configured automatic Codex review and any manual `@codex review` request. It does not apply to ChatGPT review or reasoning delegated through Reasoning Relay. An otherwise-authorized Reasoning Relay workflow may request as many Relay review or follow-up delegations as its own governing workflow requires; those requests neither consume the Codex budget nor require repository-owner authorization under it. +## Codex review configuration -Automatic Codex review is the initial Codex review. Do not request a manual Codex review unless the repository owner explicitly asks. Never request another Codex review after each remediation commit. Within the normal Codex review budget, at most one owner-authorized, delta-scoped Codex verification review may be requested under [the pull-request review workflow](AgentGuidelines/Guidelines/GitHub/PullRequests.md). - +Automatic Codex PR review is enabled. Use all PR authors and the opening/ready trigger, keep exhaustive review off, and keep separate Security Review manual. Apply the managed lifecycle; do not request a duplicate manual review. The policy-validation hosting check is required for merge.