# Copilot Instructions ## Project Details * .NET bindings of the Apple Keychain for iOS and Mac Catalyst: a C# Objective-C binding project over a native Swift library, built with an F# FAKE script * .NET SDK pinned in #file:'global.json' * Common parameters specified in #file:'Directory.Build.props' * Central NuGet package version management – versions go in #file:'Directory.Packages.props', not in `.csproj` or `.fsproj` files * Build: `dotnet build Apple.CryptoKit.slnx` – needs macOS, Xcode and the `ios` and `maccatalyst` .NET workloads (`dotnet workload restore `). A machine without them cannot build the solution * Build script: `./build.sh ` (`build.cmd` on Windows) runs the FAKE script in `build/`. Without a target it packs the solution ## Solution Structure ```text / ├── build/ – FAKE build scripts and release automation (F#) ├── docsSrc/ – FSharp.Formatting documentation source ├── src/ – the binding library │ ├── ApiDefinition.cs – the Objective-C API of the native library as C# interfaces │ ├── StructsAndEnums.cs – the native structs and enums that ApiDefinition.cs uses │ ├── Apple.CryptoKit.csproj – the binding project for iOS and Mac Catalyst │ └── NativeLib/ – the native library │ ├── KeychainStorage/ – the Xcode project (Swift); build-xcframework.sh rebuilds the xcframeworks │ ├── KeychainStorage-ios.xcframework │ └── KeychainStorage-catalyst.xcframework └── tests/ – tests of the library ``` After a change of the native code, run `build-xcframework.sh` in `src/NativeLib/KeychainStorage` and commit the rebuilt xcframeworks together with the change of `ApiDefinition.cs`. ## Libraries in Use * [.NET for iOS and Mac Catalyst](https://learn.microsoft.com/en-us/dotnet/maui/ios/) – the Objective-C bindings (`ObjcBindingApiDefinition`) * [`XHarness`](https://github.com/dotnet/xharness) – installs and runs the test apps of the mobile platforms * [`FAKE`](https://fake.build/) – build and release scripting * [`Argu`](https://github.com/fsprojects/Argu) – command-line parsing for build tooling * [`Fantomas`](https://github.com/fsprojects/fantomas) – formatting of the F# code, run by the build * [`FSharp.Formatting`](https://fsprojects.github.io/FSharp.Formatting/) – the documentation (`fsdocs`) Use GitHub MCP tools for code search in these repositories when needed. ## MCP Servers Agents discover servers from #file:'.mcp.json'; these are only hints on when to prefer one. * For F# work, prefer the `F#` server ([FsLangMCP](https://github.com/Neftedollar/FsLangMCP)) over `rg`/plain text search whenever the task depends on symbol meaning, compile context, cross-project usage, diagnostics, or safe refactoring preview. Its tool package is pinned in #file:'.config/dotnet-tools.json' – run `dotnet tool restore` before first use. * Use the `GitHub` server for code search in dependency repositories. In Claude Code it authenticates through `.claude/scripts/github-mcp-headers.ps1`, which reuses the GitHub token stored by Git Credential Manager, because the server does not support the OAuth dynamic client registration Claude Code needs. * Use the `Microsoft Docs` server for official Microsoft and Azure documentation. * When adding or changing a server, keep `servers` (VS Code / GitHub Copilot) and `mcpServers` (Claude Code) in sync and sorted alphabetically by key. ## F# Coding Guidelines ### Language and Tooling * Always use the latest F# 10 features over old syntax. * If you are running outside of an IDE, or the IDE does not provide F# semantic tools, use FsLangMCP as the primary tool for F# code navigation, symbol discovery, diagnostics, usage search and refactoring preview. Prefer its semantic tools over plain text search. * The compiler generates `IsCaseName` instance properties (for example `IsOk`, `IsNotFound`) for each DU case – use them when a single-case check is needed. * Write at most one level of a type in the postfix ML style: `int[] seq`, `int voption[]`, `seq` – never `int array seq` or `int list list`. Only the postfix levels count: `seq` and `struct (int array * int array)` have one each. ### Asynchrony and Cancellation * Prefer `task` CE over `async` CE. * When a method must return non-generic `Task`, annotate the return type explicitly: `member _.MyMethod (...) : Task = task { ... }`. Never cast through pipelines. * `task` CE can await `ValueTask` APIs directly. * Curried functions take the `CancellationToken` as their **first** parameter, so that it can be partially applied. * Never hand-roll wrappers such as `ValueTask (task { ... })`, `.AsTask ()` round-trips or manual `unit -> Task` thunks. Use the matching [`IcedTasks`](https://github.com/TheAngryByrd/IcedTasks) CE instead (`valueTask`, `valueTaskUnit`, `taskUnit`, `coldTask`, `cancellableTask`, `cancellableValueTask`, `backgroundTask`, …) and always use the full CE names, not the short aliases (`vTask`, `pvTask`, …). ### Values and Collections * Prefer `voption` (`ValueSome`/`ValueNone`) over `option`. Fields, members, parameters and values shared between threads included: none of them is a reason to pick `option`. Exception: when an API hands you `'T option` and has no `voption` counterpart, unwrap it with `Option.defaultValue`/`Option.defaultWith` directly – do not insert `ValueOption.ofOption` just to switch modules. * The mirror case, an API that *takes* `'T option` (an optional argument `?name = …`, a field typed `'T option`): stay in `ValueOption` through the whole chain and convert once, last – `x |> ValueOption.bind _.Value |> ValueOption.toOption`, never `x |> ValueOption.toOption |> Option.bind _.Value`. * Prefer `struct ('T1 * 'T2)` over reference tuples, and anonymous struct records (`struct {| ... |}`) over tuples for return types of public functions and methods. * Never group with `Seq.groupBy` – use `ToLookup` from `System.Linq`. It groups once into an `ILookup<'Key, 'T>` instead of re-grouping on every enumeration and does not allocate a tuple per group. Pass a lambda (`xs.ToLookup (fun x -> keyOf x)`), not a bare function value. * When casting sequence items use `Seq.cast` instead of `Seq.map (fun item -> item :> TargetType)`. * When concatenating two sequences or lists, prefer `seq { yield! xs; yield! ys }` (or `[ yield! xs; yield! ys ]` for lists) over the `@` operator or `Seq.append`. * When pipe operators are used on a materializable collection multiple times in a row, prefer `Seq` module for the chain and materialize at the end. * Keep a pipeline in harmony: when consecutive steps can come from one module, take them from that module, the conversion at the end included – `xs |> Seq.filter isValid |> Seq.sort |> Seq.toArray`, not `… |> Seq.sort |> Array.ofSeq`, and `items |> List.map _.Id |> List.toArray`, not `… |> Array.ofList`. Change the module only where the steps that follow need the other collection. * Compare `System.Type` values with `Type.(=) (a, b)`, the `Type.op_Equality` operator. The F# `=` goes through generic equality and is several times slower, and comparing names is both slow and wrong: `FullName.StartsWith` is culture-sensitive without a `StringComparison`, and the full name of an array of a generic type, such as ``FSharpOption`1[[System.Int32, ...]][]``, starts with the name of the generic type. To recognize a generic type, check `t.IsGenericType` and compare `t.GetGenericTypeDefinition ()` with its definition, such as `typedefof<_ option>`, through `Type.(=)`. ### Functions, Lambdas and Strings * Prefer underscore lambda syntax like `Seq.map _.Name` over `Seq.map (fun x -> x.Name)`, but only when the expression is a simple member access. Complex expressions like `Seq.where (fun x -> x.Name = name)` or `Seq.map (fun x -> x.Field1, x.Field2)` cannot be simplified. A member chain ending in a method call is not complex: `_.Changed.Subscribe(handler)`. The shorthand needs its input type known, so pipe the value in first – `value |> ValueOption.map _.Id`, not `ValueOption.map _.Id value` (FS0072). Never write a space in `_.MethodCall()` – it breaks parsing. * Simplify `Seq.map (fun x -> someFunction x)` to `Seq.map someFunction`. * Prefer interpolated strings over `printf` functions for string formatting. Format specifiers like `$"%s{value}"` are valid in interpolated strings and help type inference. * Pass an explicit `StringComparison` to every `Equals`, `StartsWith`, `EndsWith`, `IndexOf`, `Contains` and `Compare`, and an explicit comparer to every `HashSet` and `Dictionary`. `Ordinal` by default; culture-sensitive comparison is a decision, never a default. Use `OrdinalIgnoreCase` only where the thing compared really is case-insensitive. * A slice of a string that is only inspected – compared, trimmed, scanned, matched against a prefix – is a `ReadOnlySpan` (`text.AsSpan (start, length)`), not a `Substring`: the substring allocates a copy per call, the span does not. Materialize with `Substring`/`ToString ()` only for the value that leaves the function or is stored. * The `StringComparison` rule applies to spans unchanged: `MemoryExtensions` has `StringComparison` overloads of `StartsWith`, `EndsWith`, `Equals`, `CompareTo`, `IndexOf` and `Contains` for `ReadOnlySpan` – `s.AsSpan().TrimStart(' ').StartsWith("//", StringComparison.Ordinal)`. The overloads without one are the generic element-wise `ReadOnlySpan<'T>` ones – ordinal for `char` by accident, not by statement. * A slice that must be stored – kept in a record or class field, captured by a closure or used across a `let!`/`do!` in a `task` CE, put into a tuple, option or collection – is `ReadOnlyMemory` (`text.AsMemory (...)`), never a `ReadOnlySpan`: a byref-like value cannot be stored. Returning a `ReadOnlySpan` sliced from a string or from a span parameter is fine. * To compare two slices without building either, use `String.CompareOrdinal (a, aIndex, b, bIndex, length)` or `spanA.Equals (spanB, StringComparison.Ordinal)`. ### Nullable Reference Types * Declare variables non-nullable; check for `null` at entry points only. * Trust the SDK null annotations – do not add null checks when the type system says a value cannot be null. * Use `withNull` for null checks instead of boxing delegates/functions (avoid `isNull (box value)`). * Prefer `match` on `null` over `if isNull` – it narrows the type and suppresses nullness warnings: ```fsharp // Preferred match someObject with | null -> () | someObject -> someObject.SomeProperty ``` * Before suppressing a nullness warning (3261, 3262, …), exhaust these alternatives in order: 1. `nonNull value` – asserts non-null at runtime and fails fast. 2. `Unchecked.nonNull value` – skips the runtime check; only when non-null was already verified upstream. 3. An inline `#nowarn` / `#warnon` pair around the smallest possible scope – last resort for interop boundaries, centralised in a single helper rather than scattered across call sites. * Never suppress warnings file-wide; `#nowarn` and `#warnon` are valid anywhere in a file. ### XML Documentation Comments * A doc comment is either plain text with no tags at all, or fully explicit XML starting with `` – never a mixture. The compiler adds `` by itself only when the comment has no tags, and silently escapes tags otherwise: * No tags anywhere → bare `///` lines, no ``. * Any tag at all (``, ``, ``, ``, ``, …) → the comment must start with an explicit ``, and every `` must be inside it. ```fsharp // ✅ plain text — the compiler supplies /// Represents the result of a read operation. // ❌ a sibling tag without — the is escaped into the summary and lost /// Reads an item. /// Item Id // ✅ any tag present, so the comment is explicit XML throughout /// Reads an item. /// Item Id ``` * Keep `` and `` on one line each only when both are short – up to 60 characters of text each. When either is longer, write both over several lines, with each opening and closing tag on a line of its own: ```fsharp /// Returns the number of elements. /// This is an O(1) operation. /// /// The inputs of the set contracts as rows of DynamicData: none, one and several elements. /// /// /// The property builds new arrays on each read, so that no test sees a row that another one changed. /// ``` * Every public API must have XML documentation. * On an explicit interface implementation (`interface X with member _.M (...) = ...`), write `/// ` alone instead of restating the interface member's documentation, unless this implementation has behavior worth calling out beyond what the interface already documents – write a normal ``/`` there instead. * Refer to types and members through ``, never through `` or plain text. `` is for literal values only (JSON, SQL, setting names). Refer to language keywords through ``. * Split multi-paragraph documentation into `` elements inside `` – bare line breaks are collapsed by documentation renderers. * Write enumerations as `` (or `type="number"`) with `…`, never as Markdown-style bullets. ### Opens Sorting Sort `open` statements alphabetically within groups: `System` first, `Microsoft` second, `FSharp` third; then other external namespaces; then this solution's namespaces. `open type` goes last in each group. Type and module aliases form a separate final group. ### Class Constructors This is how to define a non-default F# class constructor: ```fsharp type DerivedClass = inherit BaseClass new (``arguments here``) as ``created object`` = // create any objects used in the base class constructor let fieldValue = "" { inherit BaseClass (``arguments here``) } then ``created object``.otherField <- fieldValue [] val mutable otherField : FieldType ``` ### Class Instantiation Always prefer F# class initializers over property assignment! **You absolutely must use F# class initializers instead of property assignment**! Class declaration: ```fsharp type MyClass (someConstructorParam : string) = member ReadOnlyProperty = someConstructorParam member val MutableProperty1 = "" with get, set member val MutableProperty2 = "" with get, set ``` Wrong: ```fsharp let myClass = MyClass("some value") myClass.MutableProperty1 <- "new value" myClass.MutableProperty2 <- "new value" ``` Right: ```fsharp let myClass = MyClass( // constructor parameters go first without names "some value", // then mutable properties go next with names MutableProperty1 = "new value", MutableProperty2 = // operations must be placed into parentheses (5 |> string) ) ``` ### C#-Consumable Extension Members ```fsharp // AutoOpen makes the module automatically available without an explicit open statement // Extension makes the members visible to C# [] module MyTypeExtensions = type MyType with // Extension is visible to C# // CompiledName makes the method name friendly to C# [] member this.ExtensionMethod (param1 : string) : ReturnType = () ``` ## Naming Conventions * Use PascalCase for modules, types, and public members. * Use camelCase for `let` bindings, functions, private fields, and local variables. * Prefix interface names with `I`. * Do not prefix type parameters with `T` (e.g., use `'Result` instead of `'TResult`). ## Testing * The tests of the mobile platforms are test apps (`OutputType` `Exe`), which XHarness installs and runs on an iOS simulator or on Mac Catalyst. `dotnet test` does not run them. * Check what a test app needs to run before changing it: the signing and the entitlements decide whether the Keychain accepts its calls. ## General * Make only high-confidence suggestions when reviewing code changes. * Write code with good maintainability practices, including comments on why certain design decisions were made. * Handle edge cases and write clear exception handling. * Never duplicate code unless explicitly allowed. * All comments, documentation, README files, and markdown files must be written in **English only**.