Skip to content

Updates from Mistico v1.0.0-alpha.2 - #511

Merged
leogdion merged 31 commits into
v1.0.0-beta.6from
mistico
Nov 25, 2026
Merged

leogdion merged 31 commits into
v1.0.0-beta.6from
mistico

Conversation

@leogdion

@leogdion leogdion commented Nov 24, 2026 •

Copy link
Copy Markdown
Member

Syncs the CloudKit code that Mistico (v1.0.0-alpha.2) moved into MistKit, so Mistico can depend on MistKit instead of carrying its own copies. Targets v1.0.0-beta.6. The branch is a sync, so it stays as one PR. The commits are grouped by feature (Mistico #116, #119, #136, #137-1 … #137-6, #160) to keep it bisectable. ReleaseNotes.md has the full beta.6 list.

GitHub can't render the diff (629 files). Most of the size is the Examples change below: about 31k of the 32k deleted lines are Examples/CelestraCloud, and 132 of the files are the BushelCloud → SwoopMistKit rename. The library change is roughly +20k lines under Sources/MistKit and Tests/MistKitTests.

New public API

  • CloudKit Management API: CloudKitManagementService with exportSchemaText(environment:) and exportSchema(environment:), plus ManagementToken, CloudKitManagementError, ManagementRequestFailure and ExportedSchema.
    • Generated from a new management-openapi.yaml into a new MistKitManagementOpenAPI product. It's separate from openapi.yaml because the service has a different host, auth and error shape.
    • Verified live on 2026-11-24. The test fixtures are the recorded responses.
  • Schema language: CloudKitSchema(parsing:) and schemaText, plus the schema sources (ExportedSchemaSource, file and inferred sources).
  • Queries: QueryDescriptor, the predicate parser and validation, QueryFilter.near(_:_:distance:), QueryFilter.recordName(equals:) / (notEquals:), FilterComparator, SchemaFieldType.allowedComparators.
  • Wire codecs: WireFieldValue, WireRecordOperation, ModifyRecordsRequestBody and FieldTypeTagging.
  • Service conveniences: modifyAllRecords(_:atomicZones:database:batchSize:), queryRecordPages(...), verifyCredentials, lookupRecords / lookupAllRecords(zoneID:), and fetchWebAuthSignInURL().
  • Errors: retry hints retryAfter / redirectURL / isRetryable on CloudKitError (MistKit still never retries), CloudKitError.invalidFieldValue(...), RecordFieldErrorContext, and ConversionError.integerOutOfRange.
  • Hashable / Identifiable: FieldValue, Reference, Asset, Location, ZoneInfo, RecordInfo and RecordTimestamp are Hashable. RecordInfo and ZoneInfo are Identifiable, and Environment is CaseIterable.

Breaking changes

  • FieldValue's Codable only accepts the tagged {"value": …, "type": …} shape. Untagged JSON and {"value": null} now fail to decode, including JSON written by earlier versions. CloudKit requests and responses are unaffected.
  • listZones, lookupZones, fetchDatabaseChanges, fetchAllDatabaseChanges, fetchRecordZoneChanges, fetchAllRecordZoneChanges and the deprecated fetchZoneChanges / fetchAllZoneChanges no longer default database: to .private. Pass it explicitly, like every other operation.

Deprecations

  • lookupUsersByEmail(_:) and lookupUsersByRecordName(_:) wrap Apple-deprecated users/lookup/* endpoints. Use discoverUserIdentities(lookupInfos:).

Examples

  • Examples/BushelCloud is now Examples/SwoopMistKit, because the repo was renamed to brightdigit/SwoopMistKit. The package inside is still BushelCloud. The subrepo's .gitrepo, examples.yml, Scripts/release.sh (PIN_FILES) and Scripts/update-subrepo.sh point at the new path.
  • Examples/CelestraCloud is removed from MistKit. It continues as its standalone repo.

Fixes in this PR

  • wasm: an INT64 above Int32.max used to trap on 32-bit platforms. It now throws ConversionError.integerOutOfRange.
  • Server-to-server signing: a body-less request (every signed GET) is signed with the hash of empty data. Before, it failed with AUTHENTICATION_FAILED (#136).
  • rereferenceAsset looked up and updated the target record in the default zone instead of the given zoneID.
  • Example-schema tests: the tests that read Examples/*/schema.ckdb are skipped where the source tree isn't on disk (WASI). On Android, CI copies just the staged schema files to the emulator.
  • Review follow-ups:
    • ManagementErrorBodyMiddleware now logs a .warning on the network subsystem when it drops an error body that is over the 1 MiB cap or fails mid-read. The warning names only the operation, status and error type, never the body or headers.
    • modifyAllRecords used to convert and JSON-encode every request twice: once in its preflight check and again when sending. The preflight now finds NaN and infinite numbers on the domain values and keeps the converted operations, so each request is converted and encoded once. The error it reports is unchanged, and a parameterized test pins the check to JSONEncoder's behavior.

CI runners

  • Android and the lint jobs are pinned to ubuntu-24.04. ubuntu-latest (26.04) has no swift.org toolchain and no libxml2.so.2 for SwiftLint.
  • Windows drops windows-2025, whose MSVC STL needs Clang 22. It also drops Swift 6.2, which aborts while emitting MistKitTests (Windows Swift 6.2: MistKitTests emit tip-over returns (blocks #392 / PR #485) #488), so Windows runs 6.1 and 6.3 on windows-2022.
  • The Xcode 27 lanes move to Xcode_27.2.app with the 27.2 simulators (iPhone 18 Pro, Apple Watch Ultra 4 (49mm), Apple TV 4K (4th generation)). That covers MistKit, MistDemo, MistKitConfiguration and the example workflows.
  • The generated-code check now diffs both Sources/MistKitOpenAPI and Sources/MistKitManagementOpenAPI, and fails on untracked generated files too.

Documentation

  • AGENTS.md (which CLAUDE.md links to) covers MistKitManagementOpenAPI, the Management API, modifyAllRecords, the stricter FieldValue Codable, and the new CloudKitService operation files.
  • New DocC guides cover the beta.6 features, sync, sharing, assets and subscriptions, and broken links are fixed.

Testing

  • swift test: 1005 tests pass on macOS (Xcode 27.2 toolchain, Swift 6.4.2), and ./Scripts/lint.sh is clean (swift-format, SwiftLint, headers, Periphery).
  • CI runs the full matrix: Ubuntu, wasm, Android, Windows, every macOS / Xcode platform lane, and the examples.
  • Live: swift run mistdemo export-schema against iCloud.com.brightdigit.MistDemo (development and production), plus curl captures of the error responses. The details are in .claude/docs/research/135-management-api-request-format.md.

🤖 Generated with Claude Code

leogdion and others added 11 commits November 24, 2026 13:39
…#55, #56, #59)

- SchemaKit: SchemaModel, .ckdb parser/writer, File and Inferred sources
- CommitKit: commit planning, results, conflicts, audit log
- Codecs: Copy As formats, private pasteboard payload, paste decoding
- PredicateKit: operator catalog, MistKit query translation, schema
  validation, Rows <-> Text parser and formatter
- ConnectionKit: JSON connection repository and connection rules
- MistKit: management-token auth and schema export (#135 Phase 1)
- KeychainCredentials: Keychain SecretStore, web sign-in, Test Connection
- Connections window and Connection editor
- Review fixes and recorded decisions for each

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V3TXo3doXTbUtinhW7GufV
…, #63)

- MistKit: public transport initializers, pinned listZones atomic flag,
  modifyRecords maps transport errors
- CloudKitClient: live MistKit adapter with retry policy; record MistKit gaps
- ChangeKit: ChangeSet staging with undoable inverses
- SessionStore: per-connection session, lock, status, staging, commit

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V3TXo3doXTbUtinhW7GufV
… MistKit (#116, #119)

- Rename MistKitAdminKit to MisticoKit (Linux) and add MisticoApp
  (AppUI, MisticoAppKit, MisticoKeychain leaves)
- CredentialKit, FeatureModels; localization and Apple-only APIs move
  to AppUI; import rules enforced in tooling and docs
- Generic CloudKit Web Services code moves into MistKit
- Stop the Connections list clipping rows loaded after first layout;
  re-resolve packages

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V3TXo3doXTbUtinhW7GufV
…36) (#144)

* Sign body-less server-to-server requests with the empty-body hash (MistKit#507)

CloudKit expects base64(SHA-256 of empty data) in the signed payload for a
request without a body, not the empty string; every GET signed with "" got
401 AUTHENTICATION_FAILED. cloudKitBodyHash(of:) now hashes nil and Data()
alike. Fix the RequestSignature and DocC docs, and pin the hash and a GET
signature payload in tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V3TXo4YjhX9WoY1bQyecs2

* Sign body-less recorder requests with the empty-body hash; add --public-zones

ck() signed server-to-server GETs with an empty body hash, so CloudKit
answered public zones/list with 401. Hash empty data instead, as MistKit now
does. Add --public-zones to re-record only that read-only fixture (and its
manifest line) without seeding records or needing the web auth token, and
factor the secret scrub and check into functions both modes share.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V3TXo4YjhX9WoY1bQyecs2

* Re-record public zones/list with the fixed signature (200)

Recorded with Scripts/record-fixtures.sh --public-zones; the zone owner is
scrubbed to the same placeholder as the rest of the set.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V3TXo4YjhX9WoY1bQyecs2

* Test that Test Connection's key check signs GET zones/list with the empty-body hash

Drives MistKitConnectionProbe.listPublicZones through a recording transport
and verifies the captured SignatureV1 against <date>:<sha256("")>:<path>
with the key's public half, and that it does not verify against the old
empty-string payload.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V3TXo4YjhX9WoY1bQyecs2

* Drop the probe test's signature check and its Crypto import (#136)

The test generated a P-256 key and verified the captured signature, which
needed Crypto, a module CredentialKitTests doesn't declare. MistKit's
RequestSignatureBodyHashTests already pin the empty-body hash and verify a
GET signature. The probe test now uses a fixed throwaway key and checks the
request it sends: one body-less GET of public zones/list with the three
signing headers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V3TXo4YjhX9WoY1bQyecs2

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
…137-1) (#149)

* MistKit: Hashable, Identifiable and CaseIterable for record value types (MistKit #501)

FieldValue (and Arity where T: Hashable), Reference, Asset, Location,
ZoneInfo, RecordInfo and RecordTimestamp are Hashable (so the last three
gain Equatable). RecordInfo is Identifiable by recordName; ZoneInfo by a
ZoneID of its name and owner (no zoneType, like a reference's zone).
Environment is CaseIterable. Tests check hashing agrees with == for
doubles (0.0/-0.0, NaN), lists, optionals and the record types.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V3TXo4ufnFcd3uGsVZmbhz

* Use MistKit's record value types in Mistico (#137, MistKit #501)

AdminDomain now depends on MistKit and drops its own FieldValue, ZoneID,
ZoneInfo, RecordReference, AssetValue, LocationValue, RecordSnapshot,
RecordStamp, ReferenceAction and CloudEnvironment. CloudKitClient loses its
conversion files and CloudKitClientError; RecordOperation still converts
AdminDomain.RecordOperation to MistKit's.

- Records are MistKit's RecordInfo (immutable; AdminDomain adds
  replacing/setting and zoneOrDefault). recordType and zoneID are optional:
  staging an edit or copy of a typeless record throws
  ChangeSetError.recordTypeUnknown; a missing zone reads as the default zone.
- CloudKitClient keeps normalising what CloudKit returns
  (RecordInfo+RequestZone): records take the request's zone, default-zone
  references read as no zone, private-database zones drop the owner, and the
  default zone is matched by name when sending.
- Lists are typed: switches use Arity, and AdminDomain adds listElements,
  init(listOf:), emptyList(of:) and fieldType. Paste builds an empty list
  from its type tag or schema field and refuses an untyped []. The
  unreachable CodecError mixed/nested list cases and their text are gone.
- QueryCondition and FieldChange encode values as typed wire dictionaries
  (WireFieldValue), since MistKit's FieldValue coding is untagged. Saved
  queries in the old format are dropped one by one and logged, so they
  can't lock out Connections.json.
- Asset keeps referenceChecksum/wrappingKey; downloadURL is a String (a
  staged local file is its file: URL string). Reference.action is optional.
- Copy As golden files gain the empty list's STRING_LIST tag and lose the
  action NONE that sample references no longer carry.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V3TXo4ufnFcd3uGsVZmbhz

* Notes: #137 stack run, typed empty lists, alpha saved-data format

Agent notes record the owner's run authorization and the two decisions;
memory notes and ISSUE-PLAN's contract list follow AdminDomain now using
MistKit's record types.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V3TXo4ufnFcd3uGsVZmbhz

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
…-2) (#150)

* MistKit: resolved field types, merged grants, schema sources (MistKit #502)

- FieldType: a field's type as values carry it (a primitive or LIST of one).
  FieldValue.fieldType, SchemaFieldType.resolved (ENCRYPTED dropped, NUMBER
  is INT64 when PREFERRED AS INT64, DOUBLE otherwise) and
  SchemaFieldType(FieldType); SchemaField.resolvedType.
- SchemaRecordType.mergedGrants (one grant per role, READ/CREATE/WRITE order),
  permissions(for:) and fieldIncludingImplicit(named:). SchemaField and
  SchemaRecordType are Identifiable by name.
- CloudKitSchema(contentsOf:) reads a .ckdb file.
- InferredSchema(inferringFrom:recordTypes:): fields seen, sorted by name, no
  indexes or grants, with SchemaNotice for no records and conflicting types.
- SchemaSource protocol (loadSchema, schemaChanges) with ExportedSchemaSource
  (Management API export), FileSchemaSource (injected change stream, yields
  only when the bytes change) and InferredSchemaSource (one page per record
  type through CloudKitService). Non-CloudKit failures are SchemaSourceError.
- Tests ported from Mistico's SchemaKitTests, with its .ckdb and query
  fixtures inlined; the inferred source runs over MockTransport.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V3TXo4ufnFcd3uGsVZmbhz

* Load schemas through MistKit's schema sources (#137, MistKit #502)

SchemaKit is gone (sources, tests, target, imports), and so are AdminDomain's
DatabaseSchema, RecordTypeSchema, FieldSchema, FieldType, SecurityRole,
SecurityPermission and SchemaSource. Mistico reads MistKit's CloudKitSchema,
SchemaRecordType and SchemaField; MistKit's FieldType (the resolved type)
replaces AdminDomain's, which carried nothing app-only.

- AdminDomain: LoadedSchema { schema, origin, loadedAt, referenceTargets }
  is what SchemaLoadState.loaded carries; SessionSchemaSource pairs a MistKit
  SchemaSource with the origin a session stamps; SchemaInferring makes the
  inferred source (CloudKitClient, and LiveCloudKitClient lazily after the
  keychain read). SchemaOrigin stays; SchemaSourceKind moves to FeatureModels
  for the Connection editor.
- SessionStore stamps what a source loads, maps MistKit errors to AdminError
  (parse errors to invalidFile, unreadable files and a missing record type to
  schemaUnavailable, the rest through CloudKitClient's mapping) and picks the
  starting source with initialSchemaSource(for:file:export:): a .ckdb
  preference opens the file; Live (no team ID on a connection yet) and
  Inferred start with none, as before.
- Reference targets come from LoadedSchema and are passed to the editors,
  References and Structure rows instead of living on each field.
- Structure's .ckdb text, Copy .ckdb Line and Export Schema use MistKit's
  schemaText; the roles table uses mergedGrants.
- The coordinator and the app's file preference build MistKit's
  FileSchemaSource with FileChangeWatcher as the change stream.
- TestSupport: FakeSchemaSource adopts MistKit's protocol; StubTransport runs
  a real CloudKitService over in-memory records for inference tests and the
  preview default. The live export test now loads ExportedSchemaSource into
  a session. The provisional schema fixtures moved into MistKit's tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V3TXo4ufnFcd3uGsVZmbhz

* Notes: schema sources live in MistKit (#137-2)

schemakit.md becomes schema-sources.md (what MistKit owns, what Mistico keeps,
fieldsIncludingImplicit, reference targets, error mapping, starting source).
Structure tab, SessionStore, Wave 0 contracts, live suite, recorded fixtures
and ISSUE-PLAN's contract list follow; the duplicate SchemaKit index line is
gone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V3TXo4ufnFcd3uGsVZmbhz

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
…dicateKit (#137-3) (#151)

* MistKit: NSPredicate format strings, query model and validation (MistKit #500)

Ports Mistico's PredicateKit and AdminDomain query types into MistKit as
generic API:

- QueryDescriptor (+ Condition, Comparator, Sort): an editable
  Codable/Hashable/Sendable query model (record type, zone, conditions,
  sorts, desired keys, limit) that converts to Query/QueryFilter/QuerySort.
  Condition values encode via WireFieldValue with .always type tagging.
  One Comparator case per FilterComparator, plus near(meters:).
- QueryFilter.containsAnyTokens(_:_:).
- QueryPredicate.parse/format: a hand-written lexer, parser and
  formatter for CKQuery's NSPredicate subset (CAST(…, "NSDate"),
  REFERENCE, LOCATION, BYTES, IN {…}, #name escaping, comments,
  TRUEPREDICATE; OR/NOT are errors; kilometres in text, metres in the
  model). Errors are QueryPredicateParseError with a structured reason,
  range, line and column.
- QueryDescriptor.validate(against:): QUERYABLE/SEARCHABLE/SORTABLE
  index checks and per-type comparators via SchemaFieldType
  .allowedComparators, returning structured QueryValidationIssues.
- Swift Testing ports of Mistico's PredicateKit tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V3TXo4ufnFcd3uGsVZmbhz

* Query with MistKit's QueryDescriptor and predicate parser (#137, MistKit #500)

PredicateKit is gone (sources, tests, target, imports), and so are AdminDomain's
PredicateQuery, QueryCondition, QueryComparator and QuerySort. Mistico reads
MistKit's QueryDescriptor (Condition, Comparator, Sort), QueryPredicate
parse/format and QueryDescriptor validation.

- CloudKitClient calls QueryDescriptor.query() and passes limit, desiredKeys
  and zone to queryRecords; QueryTranslating and PredicateQueryTranslator are
  deleted. A condition that can't become a filter throws MistKit's
  QueryDescriptorError before any request.
- AdminDomain: SavedQuery, RecordQuerying and RecordCounting take
  QueryDescriptor; QueryDescriptor.validate(against: LoadedSchema) checks
  indexes unless the schema was inferred.
- FeatureModels: operator pop-ups hold FilterComparator.
  SchemaField.offeredComparators keeps SPEC §4.1's per-type order and filters
  it to MistKit's allowedComparators (so ENCRYPTED fields offer nothing);
  descriptorComparator turns a choice into Comparator (within starts at 1 km).
  The record's name is ___recordID in conditions and recordName on screen
  (QueryFieldName). PredicateBarIssue carries MistKit's QueryValidationIssue;
  its fix-it moves to AppUI.
- AppUI words validation issues, fix-its and parse errors (line, column,
  reason) in +Text extensions with QueryTab.xcstrings entries; operator titles
  stay = ≠ < ≤ > ≥ / begins with / contains / within.
- Stricter, as CloudKit is: a record-name filter needs ___recordID QUERYABLE
  in the schema; token filters need SEARCHABLE.
- Saved queries in the old PredicateQuery shape are dropped and logged by
  ConnectionKit's per-query decode (no migration); tests cover that and the
  QueryDescriptor round trip.
- Tests: Mistico's operator table, origin → index checks, record-name rules,
  ___recordID in the text editor, and AppUI wording. MistKit's own tests cover
  the parser, translation and validation rules.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V3TXo4ufnFcd3uGsVZmbhz

* Notes: queries live in MistKit (#137-3)

Predicate bar, Query tab and Wave 0 contracts describe MistKit's
QueryDescriptor, QueryPredicate and validation, Mistico's operator table and
the ___recordID ↔ recordName naming (and that record-name filters now need
___recordID QUERYABLE). Schema sources, the MEMORY.md index and ISSUE-PLAN's
module and contract lists follow.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V3TXo4ufnFcd3uGsVZmbhz

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
* MistKit: WireRecord, wire JSON decoding and cloudKitReadable encoder (MistKit #503)

WireRecord is a whole record dictionary (recordName, recordType,
recordChangeTag, zoneID, typed fields, created/modified, deleted), Codable
and Hashable, built from RecordInfo and converted back with
RecordInfo.init(_:). WireRecordDocument decodes records from an array, a
single record, a query response ({"records": [...]}) or a records/modify
body (deletes skipped, the body's zoneID filled in).

Untagged field values are typed by CodingUserInfoKey.cloudKitFieldTypes
([String: SchemaFieldType]) and then by their JSON shape. Decoding
caller-supplied JSON throws a ConversionError without the DEBUG trap used
for CloudKit responses.

JSONEncoder.cloudKitReadable is [.prettyPrinted, .sortedKeys,
.withoutEscapingSlashes]; its docs name userInfo as the place for future
wire options.

RecordOperation (with ShareParticipant, UserIdentity, NameComponents and
UserIdentityLookupInfo), WireFieldValue, WireRecordOperation and
ModifyRecordsRequestBody are Hashable. WireRecord and WireRecordOperation
share one internal fields codec.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V3TXo4ufnFcd3uGsVZmbhz

* MistKit: refuse untyped empty lists in wire JSON (MistKit #503)

An untagged `[]` with no cloudKitFieldTypes hint no longer decodes as an
empty STRING_LIST: an empty list's type comes from its `type` or the
schema. WireFieldValue throws DecodingError.dataCorrupted at the field,
with ConversionError.ambiguousEmptyList(fieldName:) as its underlying
error.

JSONDecoder reads an untagged `5.0` the same as `5` (macOS and Linux
Swift 6.1), so it decodes as INT64; the docs say to pass a type or a
schema type for DOUBLE, BYTES and TIMESTAMP values.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V3TXo4ufnFcd3uGsVZmbhz

* MistKit: wire decoding errors carry their coding path (MistKit #503)

A ConversionError thrown while decoding caller-supplied wire JSON (a field
value that contradicts its type, an unknown zoneType, a negative timestamp)
came out bare, so a caller decoding an array of records couldn't tell which
record or field was wrong. WireFieldValue, WireRecord, WireRecordDocument and
ModifyRecordsRequestBody now throw DecodingError.dataCorrupted at the field or
record, with the ConversionError as its underlyingError, as the untyped empty
list already did. ModifyRecordsRequestBody's zoneID also no longer hits the
DEBUG conversion trap.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V3TXo4ufnFcd3uGsVZmbhz

* MistKit: encoding errors name the record field (MistKit #503)

WireRecord and WireRecordOperation wrote `fields` through
nestedContainer(keyedBy:forKey:), and JSONEncoder leaves a nested
container's key out of an EncodingError's coding path: a NaN came back at
[0].ratio.value instead of [0].fields.ratio.value. WireFields now encodes
as a value, so the path has `fields` and the field name, as decoding does.
The output is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V3TXo4ufnFcd3uGsVZmbhz

* Copy As and Paste use MistKit's wire format (#137, MistKit #503)

Codecs writes and reads CloudKit JSON through MistKit's WireRecord,
WireRecordDocument and ModifyRecordsRequestBody with
JSONEncoder.cloudKitReadable. Codecs/CloudKitJSON/, Codecs/JSON/ (JSONValue
and its encoder) and ModifyRecordsBody are gone.

- Copy As JSON is [WireRecord]; Copy As modifyRecords Request Body is
  ModifyRecordsRequestBody(updating:) with every type written. A NaN or
  infinite number is EncodingError.invalidValue; its coding path names the
  record and field in CodecError.nonFiniteNumber.
- RecordsPasteboardPayload is an Encodable {formatVersion, recordType,
  records: [WireRecord]}; Paste reads the version and type first.
- Paste decodes WireRecordDocument with the schema's field types (NUMBER
  resolved as the grid reads it) as cloudKitFieldTypes. An untyped empty
  list in a field the schema doesn't know is MistKit's ambiguousEmptyList,
  shown as "Can't tell the empty list's element type."; DecodingErrors map
  onto PasteError by their coding path, and an unknown operationType is an
  invalid record. Pasted zones keep the default zone as ZoneID.defaultZone
  (owner and zoneType dropped) and default-zone references as no zone
  (CloudKitClient's withNormalizedReferences, now public).
- The four JSON goldens are regenerated from the encoder
  (MISTICO_RECORD_GOLDENS=1); the values are unchanged, only formatting:
  keys sorted at every level, "key" : value, empty arrays on three lines,
  5.0 written as 5. CSV, TSV and record names are unchanged.

User-visible: Copy As JSON and the modify body are now key-sorted, and an
encrypted field is written with "isEncrypted": true, a tombstone with
"deleted": true.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V3TXo4ufnFcd3uGsVZmbhz

* Notes: Copy As and Paste JSON are MistKit's wire format (#137-4)

Copy, export, drag describes WireRecord, ModifyRecordsRequestBody and the
private payload through JSONEncoder.cloudKitReadable, Paste's
WireRecordDocument decoding with schema field types, how DecodingErrors map
onto PasteError, pasted zone normalisation and the golden regeneration flag.
Wave 0 contracts, the MEMORY.md index and ISSUE-PLAN's Codecs row and 1E
acceptance follow.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V3TXo4ufnFcd3uGsVZmbhz

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
…137-5) (#153)

* MistKit: modifyAllRecords reports completed and unsent operations on failure (MistKit #504)

modifyAllRecords now throws CloudKitError.modifyIncomplete(completed:unsent:
underlying:) when any request fails or the task is cancelled between
requests, including the first (completed is then empty), so callers handle
one shape. completed holds the results of every request that came back;
unsent holds the failed request's operations and every later one, in send
order. The failed request's operations may have been applied by CloudKit
(e.g. a dropped connection after send), so re-sending can hit CONFLICT.

reason, retryAfter, redirectURL, isRetryable, httpStatusCode and
serverErrorCode read through to the underlying error. Single-request
modifyRecords and chunkedBatches are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V3TXo4ufnFcd3uGsVZmbhz

* MistKit: rename ModifyRecords network-error tests to match their type (file_name lint)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V3TXo4ufnFcd3uGsVZmbhz

* Commit banner says unsent rows may already be saved (#137-5)

When a commit stops at a request whose answer never came (offline after
send, cancelled, an unreadable response), CloudKit may have applied it
(MistKit #504). CommitReport.unsentMayHaveBeenSaved says so; a request
CloudKit refused (throttled, sign-in expired, no credentials, access
denied) applied nothing. The partial-commit banner adds "Some of them may
already be saved and come back as conflicts." after "Commit again to send
the rest." in that case.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V3TXo4ufnFcd3uGsVZmbhz

* Commit with MistKit's modifyAllRecords; delete CommitPlanner and CommitExecutor (#137-5, MistKit #504)

RecordCommitting.commit(_:atomicZones:in:) now takes a whole commit and
returns a CommitResponse (results + the error that stopped it) instead of
one CommitBatch per request. CloudKitClient makes one modifyAllRecords call,
atomic in the zones the server reports as atomic; on modifyIncomplete it
keeps the completed results (stamped with each operation's zone, found by
record name) and maps the underlying error, or .cancelled, so unsent rows
come back notSent and stay staged. AdminError(mapping:) unwraps
modifyIncomplete to its underlying error.

CommitKit keeps the planner's checks as StagedCommit (duplicate record,
asset without a created/updated record, atomic zones) and
RecordCommitting.send(_:in:) runs asset uploads then the commit.
SessionError/PreviewCommitError .planning becomes .invalidCommit.
CommitBatch, CommitPlan, CommitPlanner, CommitPlanningError and
CommitExecutor are gone.

FakeRecordCommitting splits like modifyAllRecords (configurable batch
size), can fail at a given request and cancel the task after one. New
tests: partial failure keeps unsent rows staged, full success clears,
cancellation keeps completed rows, multi-zone and atomic zones, plus
fixture-backed CloudKitClient tests for a later-request failure and
cancellation.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V3TXo4ufnFcd3uGsVZmbhz

* Notes: commits go through MistKit's modifyAllRecords (#137-5)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V3TXo4ufnFcd3uGsVZmbhz

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
…rror mapping (#137-6) (#154)

* MistKit: verifyCredentials for Test Connection (MistKit #505)

Add CloudKitService.verifyCredentials(), which checks each configured
credential concurrently and returns a CredentialVerification with one
CredentialStatus (accepted / rejected(CloudKitError) / notConfigured)
per CredentialKind:

- webAuth: users/caller via fetchCaller()
- serverToServer: public zones/list signed with the key
- apiTokenOnly: users/caller signed with the API token alone;
  AUTHENTICATION_REQUIRED counts as accepted (valid, needs sign-in)

A failing credential is reported, never thrown; the call throws only
CancellationError. Results hold no credential material.
fetchWebAuthSignInURL now shares the API-token-only users/caller request.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V3TXo4ufnFcd3uGsVZmbhz

* One MistKit → AdminError mapping in AdminDomain (#137-6)

Merge CloudKitClient's AdminError+Mapping and CredentialKit's
CloudKitErrorMapping into AdminDomain's AdminError+MistKit, with Test
Connection's stricter rules everywhere: server reason text keeps every
secret redacted (CloudKitClient now takes the service's secrets, from
Credentials.secrets), free text only for errors with no case of their
own, and wrapped errors are never described (raw HTTP bodies and
decoding/conversion/underlying descriptions are dropped).

Kept from CloudKitClient: notQueryable/notSortable 400 refusals,
URLError → offline, throttled/tryAgainLater with retryAfter, the
modifyIncomplete unwrap, cancellation and credentialReferences.

Folded in the stragglers: AdminError(schemaLoading:origin:) moves from
SessionStore to AdminDomain, and the small fallbacks in CommitKit send,
SessionRules, GridModel and ReferencesModel now call
AdminError(mapping:). A QueryDescriptorError (a condition MistKit can't
turn into a filter, before any request) maps to the new
AdminError.invalidFilter(fieldName:), worded in the query tab.

Mapping tests move to AdminDomainTests (mapping, redaction, schema
loading); ErrorMappingTests stays in CloudKitClientTests since it replays
fixtures through a client.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V3TXo4ufnFcd3uGsVZmbhz

* MistKit: a malformed raw PEM is invalidPrivateKey (MistKit #505)

Credentials.makeTokenManager wrapped only a failed PEM file read in
CloudKitError.invalidPrivateKey; a key that loaded but wasn't a P-256
PEM escaped as a TokenManagerError, so verifyCredentials reported it as
rejected(underlyingError(TokenManagerError)) and callers couldn't tell a
bad key from any other local failure. HandlingErrors.md already documents
invalidPrivateKey for "not a valid ECDSA P-256 PEM"; this makes it so.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V3TXo4ufnFcd3uGsVZmbhz

* Test Connection uses MistKit's verifyCredentials, per credential (#137-6, MistKit #505)

ConnectionTester makes one verifyCredentials() call through
ConnectionProbing (MistKitConnectionProbe → services.makeService(target))
instead of users/caller then public zones/list, and reports a
CredentialCheck per CredentialKind: accepted, rejected (401
AUTHENTICATION_FAILED or an unreadable key: the credential itself) or
failed(AdminError) through the one mapping, secrets redacted. A rejected
credential no longer hides the others'. fetchCallerRecordName stays only
for web sign-in's token check; Test Connection no longer reads the user
record name (the UI never showed it).

LiveConnectionTester builds the report per kind: an accepted key reaches
Public, a signed-in user credential Public/Private/Shared, an API token
alone is "needs sign-in". The report now carries problems alongside what
was reached, so a wrong API token or server-to-server key (401) reads as
"CloudKit rejected the API token / server-to-server key" instead of "Web
sign-in expired" (421), and a key that works still shows Public reached
when the sign-in expired.

Live suite: key + rejected web token, API token alone (421 → needs
sign-in) and a wrong API token (401 → rejected) against Tabletop.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V3TXo4ufnFcd3uGsVZmbhz

* Notes: Test Connection is MistKit's verifyCredentials; one AdminError mapping (#137-6)

Update the memory notes and ISSUE-PLAN this branch makes stale: the
mapping lives in AdminDomain (AdminError+MistKit, +SchemaLoading); the
401-vs-421 question is answered for Test Connection (verified live) but
still open for sessions; web sign-in keeps fetchCallerRecordName; the
malformed-PEM MistKit gap is closed. Drop duplicate index lines.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V3TXo4ufnFcd3uGsVZmbhz

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
…160)

* Move duplicated and generic CloudKit code from Mistico into MistKit

One commit for the 2026-11-23 review. The steps overlap in shared files,
so they can't be split into commits that each build:

- Move AppIdentity out of its folder in MisticoCore.
- Use MistKit's CloudKitServerErrorCode and RecordOperationFailure instead
  of Mistico's ServerErrorCode and RecordFailure; make MistKit's FieldValue
  list helpers public.
- Rename Mistico's RecordOperation to PlannedOperation; MistKit gains
  RecordOperation(fieldUpdates:).
- Move generic pieces into MistKit: zone identity and isDefaultZone fix,
  ZoneInfo.isAtomic, RecordInfo helpers, OperationResult.recordName,
  CloudKitError.completedResults/unsentOperations, query error fieldName,
  Database.Scope, RecordOperation.saving, CKDBHighlighter, QueryFieldName.
- Delete redundant Mistico helpers (UNKNOWN_ERROR fallbacks,
  Environment.isProduction); add Environment.allowsColorTag.
- Move plain code out of MisticoObservables into MisticoCore, MisticoCoding,
  MisticoTracking, MisticoCredentials and MisticoFakes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V3TXo4APHkzx6tPpi18edS

* Delete RecordPage, RecordInfo.setting and Reference.wireZoneID

MistKit's QueryResult gains Hashable and hasMore, so Mistico uses it
directly instead of its own RecordPage; RecordPage.maximumSize callers
use CloudKitService.maxRecordsPerRequest. RecordInfo.setting(_:to:)
goes: its preview and test callers build the fields and call MistKit's
RecordInfo.replacing(fields:). Reference.wireZoneID is inlined at its
one caller in FieldValueRequest.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V3TXo4APHkzx6tPpi18edS

* Merge the two filter-value readers into ConditionValueText

The Query tab's condition rows (ConditionValueText) and the predicate bar
(PredicateRowValue) each read a typed filter value in POSIX format. There
is now one reader, ConditionValueText in MisticoCore. It switches on
MistKit's FieldType.elementType with no recursive list unwrap, so a list
of lists has no row form. It reads strings as typed, numbers, record
names, yyyy-MM-dd[ HH:mm] dates, "lat, lon" locations in range, and
"within" distances in kilometres (nearMeters(fromKilometres:)).

PredicateRowValue now only maps a row to a condition or a
PredicateBarIssue. It still trims the row's text first (strings included),
reports an empty value as missing, and takes a TIMESTAMP row's value from
its date picker.

Behaviour changes: Query tab rows on a location field now read and show
"lat, lon", where before they showed nothing and stayed flagged. The bar
reads a list field's value as its element for any operator, not only
contains, which is the only operator it offers for lists.

FieldValueParser stays separate: cell editing reads the user's locale.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V3TXo4APHkzx6tPpi18edS

* Delete PlannedOperation; commit StagedChange directly

PlannedOperation was a StagedChange without the old values. StagedCommit
and CommitReport used only its kind, record name, type and zone, which
StagedChange has, so RecordCommitting.commit(_:atomicZones:in:) now takes
[StagedChange], StagedCommit holds `changes` and CommitReport.Row holds
the `change` that was sent (with uploaded assets filled in).

StagedChange.zoned builds MistKit's RecordOperation with today's rules:
deletes send no fields, creates send no change tag, a nil new value
clears the field. StagedChangeKind maps privately to MistKit's
OperationType and replaces PlannedOperation.Kind in AuditEntry and
AuditLogLine; the raw strings are the same, and a new test decodes
audit-log lines written before the change. The PlannedOperation
conversion tests move to StagedChangeZonedTests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V3TXo4APHkzx6tPpi18edS

* Name the record and field when a number isn't finite

A NaN or infinite DOUBLE, location number or timestamp made encoding the
records/modify body throw, which surfaced as CLIENT_ERROR: ClientError.

MistKit:
- RecordFieldErrorContext, a protocol for errors about a record's field,
  adopted by CloudKitError (reading through modifyIncomplete) and
  ConversionError.
- CloudKitError.invalidFieldValue(recordName:fieldName:underlying:), thrown
  by modifyRecords (and so per request by modifyAllRecords) with nothing
  sent.
- CloudKitError(encodingError:recordNames:), which resolves a JSONEncoder
  failure on [WireRecord], ModifyRecordsRequestBody or the generated modify
  body to the record and field.

Mistico:
- Failable init?(_: some RecordFieldErrorContext) on CodecError and
  AdminError. CloudKitJSONWriting uses MistKit's resolver and drops its own
  coding-path parsing.
- AdminError.invalidFieldValue(recordName:fieldName:), mapped from MistKit;
  the commit banner names the record and field, and the report doesn't
  claim unsent rows may have been saved.
- FieldValueParser refuses nan, inf and overflowing text as not a number.
  The paste decoder reads JSON, which can't hold one; tests pin that.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V3TXo4APHkzx6tPpi18edS

* Make FieldValue's Codable keep its type

MistKit's FieldValue now encodes and decodes only the CloudKit field
dictionary with its type, {"value": …, "type": …}, by delegating to
WireFieldValue with .always tagging. Untagged input and {"value": null}
are decoding errors, so TIMESTAMP, BYTES, whole-valued DOUBLE and empty
lists round-trip. CloudKit requests and responses still go through
FieldValueRequest / FieldValueResponse.

QueryDescriptor.Condition and Mistico's FieldChange drop their custom
WireFieldValue coding for plain Codable. They already wrote this shape,
so saved queries and audit-log lines still decode; new tests decode a
saved query and an audit-log line in the earlier format and re-encode
them byte for byte.

MistDemo's web API now takes typed fields (app.js tags them), and its
JSON output and tests use the tagged shape. ReleaseNotes notes the
breaking format change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V3TXo4APHkzx6tPpi18edS

* One client type: CloudKitAdapter over a ServiceProvider

CloudKitClient becomes CloudKitAdapter, still a struct in MisticoClient.
Instead of a fixed CloudKitService it holds a ServiceProvider actor that
either answers with a ready service (tests, previews) or builds one from
the keychain on first use (CredentialResolver + CloudKitServiceFactory),
caches it, and forgets it after authenticationExpired or
credentialsMissing. Error text is scrubbed with the secrets the provider
resolved.

LiveCloudKitClient and its two extensions are deleted; their behaviour
is the keychain-backed provider. LiveInferredSchemaSource moves to
MisticoClient and resolves the service when the schema loads.
MisticoClient now depends on MisticoCredentials. New ServiceProvider and
keychain-adapter tests cover build-once, caching, reset, and forgetting
after a failed read or commit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V3TXo4APHkzx6tPpi18edS

* Send nothing when any modify request can't be encoded; reject NaN in filters

- modifyAllRecords encodes every request before sending the first, so a
  NaN or infinite number stops the call with nothing saved (completed is
  empty, unsent holds every operation).
- ConditionValueText rejects non-finite numbers and distances, so filter
  rows can't send NaN or infinity either.
- MistKit release notes: invalidFieldValue, RecordFieldErrorContext and
  CloudKitError(encodingError:recordNames:).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V3TXo4APHkzx6tPpi18edS

* Update project memory for the 2026-11-23 MistKit cleanup

CloudKitAdapter/ServiceProvider, StagedChange commits, ConditionValueText
as the shared filter reader, strict FieldValue Codable, NaN handling, and
worktree/mise/MistKit toolchain gotchas.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V3TXo4APHkzx6tPpi18edS

* Add DocC catalogs for every Mistico module and a make docs target

One catalog per module in MisticoKit and MisticoApp (overview plus topic
groups over the existing public types), swift-docc-plugin 1.5.0 in both
packages, and `make docs` building a combined archive per package into
build/docs. Nothing is published.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V3TXo4APHkzx6tPpi18edS

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 0f6ef1e3-701d-4ce6-8c53-96ef507cf200

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • Trigger review
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

@claude

claude Bot commented Nov 24, 2026

Copy link
Copy Markdown

Review of #511 (Updates from Mistico v1.0.0-alpha.2)

Scope caveat: this PR is 257 files and about 17.8k added lines, and its description is empty. I sampled the highest-risk areas: FieldValue+Codable, the new Management/ client, WireFormat/, the openapi.yaml and generated-type changes, and the docs. I did not read every file or build and run the test suite. Please treat this as a targeted review, not a full sign-off.

Suggestions

  1. Split it up or add a description. The PR bundles several separate features:

    • the Management API client and schema parsing/writing
    • the query predicate parser, validation and descriptors
    • public wire codecs
    • modifyAllRecords, queryRecordPages and verifyCredentials
    • lookupAllRecords(zoneID:)
    • error retry hints and web-auth sign-in
    • the MistDemo web changes

    An empty body makes it hard to review and hard to bisect. At the least, list the new public API and the breaking changes.

  2. Breaking change to FieldValue's public Codable. FieldValue+Codable.swift used to decode untagged JSON by inference ("x", 1, arrays, location/reference/asset). It now only accepts {"value":…, "type":…}. Untagged input and {"value":null} throw. This is documented in AGENTS.md as intentional, and it is the better round-trip behavior. It is still source- and behavior-breaking for anyone who decodes FieldValue from plain JSON, so it should go in ReleaseNotes.md as an explicit breaking change. Please also check the MistDemo call sites (WebJSON, WebRequests, OutputFormatting+Implementations). They were touched, which suggests they depended on the old behavior.

  3. The Management API is unverified against a live service. The docs and memory notes say the host, path and header come from reading CKTool JS 1.3.2, with no captured wire exchange, and the tests use hand-written ProvisionalManagementFixtures. Shipping a public CloudKitManagementService on that basis is risky. I'd either mark it clearly experimental in the DocC and API docs or do one live export first. Two smaller points:

    • ManagementToken redacts itself in description, which is good. But the token travels in the X-Apple-CloudKit-Management-Token header, and the middleware logs headers at .debug. Confirm that path redacts or omits this header, and add a test.
    • send caps the response at 32 MiB, which is reasonable. A cap-exceeded error should surface as a clear CloudKitManagementError, not a raw OpenAPIRuntime error. Please confirm.
  4. Docs and memory files look out of sync. The AGENTS.md hunks for WireFieldValue, the strict Codable, and lookupAllRecords(zoneID:) are in the diff. The CLAUDE.md in this checkout has none of them: it has no Management API section, and its lookupAllRecords signature is the old one. Decide which file is canonical, or make sure both carry the new material. .claude/memory/project_fieldvalue_bytes_is_base64_string.md and the MEMORY.md index changed alongside the code, so those edits look right.

  5. Generated code. Sources/MistKitOpenAPI/Types.swift gained Filter.distance, RecordResponse.zoneID and others. Confirm that ./Scripts/generate-openapi.sh produced it from the final openapi.yaml, and that git diff is clean after regenerating. CLAUDE.md forbids hand edits there.

  6. Test coverage looks broad. There is a lot of new test material for the predicate parser, schema parser/writer goldens, wire format, batch chunking cancellation, and credentials verification, and it uses Swift Testing. Gaps I'd want closed:

    • a negative test pinning the new strict FieldValue decoding (untagged and null throw)
    • a test that the management header never reaches logs
    • a live or recorded fixture for the Management API, to replace the provisional one
  7. Convention checks. I did not run these:

    • every new import should carry an explicit access modifier. The files I sampled do.
    • ./Scripts/lint.sh (swiftlint, header.sh, periphery) should pass. A lot of new public surface can trip periphery.
    • the per-file license headers and the type ordering rules should hold.

Positives

  • Redacted ManagementToken, and a bounded response body in send.
  • Fail-loud decoding and the round-trip design for FieldValue are consistent with the project's existing philosophy.
  • Docs and memory notes record the reasoning, and unverified facts are flagged as unverified.

No security vulnerabilities found in the sampled code. The main risks are the API-compat surprise (item 2) and shipping an unverified external API contract (item 3).

@codecov

codecov Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
⚠️ Please upload report for BASE (v1.0.0-beta.6@0c731a9). Learn more about missing BASE report.

Additional details and impacted files
@@               Coverage Diff                @@
##             v1.0.0-beta.6     #511   +/-   ##
================================================
  Coverage                 ?   90.66%           
================================================
  Files                    ?      302           
  Lines                    ?     7638           
  Branches                 ?        0           
================================================
  Hits                     ?     6925           
  Misses                   ?      713           
  Partials                 ?        0           
Flag Coverage Δ
mistdemo-spm-macos 9.95% <ø> (?)
mistdemo-swift-6.4-jammy 9.95% <ø> (?)
mistdemo-swift-6.4-noble 9.95% <ø> (?)
spm 89.69% <ø> (?)
swift-6.1-jammy 89.77% <ø> (?)
swift-6.1-noble 89.85% <ø> (?)
swift-6.2-jammy 89.77% <ø> (?)
swift-6.2-noble 89.61% <ø> (?)
swift-6.3-jammy 89.68% <ø> (?)
swift-6.3-noble 89.65% <ø> (?)
swift-6.4-jammy 89.77% <ø> (?)
swift-6.4-noble 89.74% <ø> (?)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

leogdion and others added 2 commits November 24, 2026 14:47
- Narrow CloudKit INT64 to Int with Int(exactly:) and throw the new
  ConversionError.integerOutOfRange where Int is 32-bit (WASI) instead of
  trapping ("Not enough bits to represent the passed value").
- Skip the example .ckdb schema suite on WASI, whose sandbox can't read the
  source tree.
- Android: pin ubuntu-24.04; ubuntu-latest is 26.04, which has no swift.org
  host toolchain.
- Windows: drop windows-2025; its MSVC 14.52 STL needs Clang 22.
- Xcode 27 lanes: pin /Applications/Xcode_27.2.app with 27.2 simulators and
  the renamed devices (iPhone 18 Pro, Apple Watch Ultra 4 (49mm),
  Apple TV 4K (4th generation)) across MistKit, MistDemo,
  MistKitConfiguration and the example workflows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The CloudKit Management API client was hand-written. It now has its own
OpenAPI spec, management-openapi.yaml (host api.icloud.apple.com,
X-Apple-CloudKit-Management-Token auth, JSON RequestError), generated into a
new MistKitManagementOpenAPI target, the same way openapi.yaml feeds
MistKitOpenAPI. The public CloudKitManagementService API is unchanged.

- ManagementTokenMiddleware sets the token header; there is no logging
  middleware, and ClientError (whose description includes the request
  headers) is never rethrown.
- ManagementErrorBodyMiddleware buffers non-2xx bodies so an undecodable
  error body still reaches CloudKitManagementError.httpError.
- Success bodies over 32 MiB throw invalidResponse; ManagementToken is
  hidden from Mirror/dump too.
- generate-openapi.sh, the regenerate-and-diff CI check, SwiftLint and
  Codecov cover the new target.
- MistDemo: add export-schema (CLOUDKIT_MANAGEMENT_TOKEN, CLOUDKIT_TEAM_ID)
  for live verification.
- Tests: request shape and encoding, success/error bodies including
  single-read streams, token exposure, and both middlewares.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@claude

claude Bot commented Nov 24, 2026

Copy link
Copy Markdown

Review of #511 (Updates from Mistico v1.0.0-alpha.2)

Scope caveat: GitHub refuses to render this diff (over 20,000 lines), so I couldn't review all of it. I read the file list and spot-checked the Management API token and error middleware and CloudKitError+Retry. Treat this as a partial review.

Process

  • The PR body is empty. A change this large (Management API, credential verification, modifyAllRecords, query pages, error taxonomy, FieldValue Codable rewrite, CI workflow changes, MistDemo export-schema) needs a description. It should say what is in it and what was verified live.
  • Consider splitting it. The diff mixes a new public API surface, a Codable behavior change, CI refactors and docs. That makes it hard to review and to revert.

Code quality and best practices

  • ManagementToken is well done. description, debugDescription and customMirror are all redacted, and the value is internal. One gap: it is Hashable and Equatable over the raw secret. That is fine, but make sure no log line interpolates the value field directly.
  • ManagementErrorBodyMiddleware uses try? await Data(collecting:upTo:) and returns nil when the body is over 1 MiB. It also returns nil if a read error occurs mid-stream. In both cases the caller gets no body, with no indication of why. Consider a log line or a distinct signal.
  • CloudKitError+Retry is clear and consistent. isRetryable and retryAfter both read through .modifyIncomplete, which is good. redirectURL is exposed as String?. Consider URL?, or document that callers must validate the scheme and host before opening it, since it comes from a server response.
  • Repo conventions:
    • Please confirm every new file uses internal import or public import, per CLAUDE.md.
    • AGENTS.md and CLAUDE.md have drifted. CLAUDE.md still describes a single MistKitOpenAPI target and no Management API, while AGENTS.md documents MistKitManagementOpenAPI. If AGENTS.md is meant to mirror CLAUDE.md, sync them.

Potential bugs and risks

  • The Management API contract is unverified. The new docs say it is based on CKTool JS 1.3.2 and that unit tests use hand-written "provisional" fixtures, with no live call made. The host (api.icloud.apple.com), path and header all come from reading an npm package. I'd gate the feature as experimental, or run one live export before release. The first live call could invalidate the fixtures.
  • FieldValue Codable changes (FieldValue+Codable.swift: +37/−127). Decoding is now strict, so untagged input and {"value": null} are errors. That is a behavior change for anyone persisting or decoding FieldValue JSON. Please add a release note under the breaking or behavioral section.
  • FieldValue+Components+Scalar.swift has the type-recovery logic from FieldValueRequest can't tag scalar TIMESTAMP — Date/Time writes fail with BAD_REQUEST #375. Make sure the new FieldValue+FieldType and ListElements paths have tests for the fail-loud typeValueMismatch cases.
  • modifyAllRecords groups operations by zone and sets atomic per zone. On a mid-run failure the new modifyIncomplete(completed:unsent:underlying:) reports progress, which is good. Please confirm tests cover a failure on the second or later chunk, and that unsent contains exactly the operations not yet attempted. A chunk that was partially applied but returned an error is the hard case.
  • queryRecordPages has a stuck-marker guard. Please confirm it throws rather than silently terminating, which matches the existing fetchAll* convention.

Performance

  • ManagementErrorBodyMiddleware caps buffering at 1 MiB, and the notes say success bodies are capped at 32 MiB. Both are reasonable.
  • Debug logging: the request-signing HashFunction+CloudKitBodyHash change touches a hot path. Confirm it doesn't buffer the whole body twice for large asset or record payloads.

Security

  • Token handling: the management token is sent only as a header. The ClientError is mapped so request headers don't leak into error descriptions, which is the right call. Please add a test asserting that no error description or localizedDescription contains the token.
  • Debug traces: the existing middleware logs headers at .debug. Confirm the new X-Apple-CloudKit-Management-Token header can't reach that logger. The notes say there is no logging middleware on the management client, so this looks fine. A regression test would lock it in.
  • MistDemo: CLOUDKIT_MANAGEMENT_TOKEN is read from env, .env or CLI. A CLI argument shows up in process listings, so prefer env or .env and say so in the help text.
  • CI workflows (MistDemo.yml, MistKit.yml, check-generated-openapi.yml and the example workflows): I didn't review these in detail. Check that no secrets are exposed to pull_request runs from forks.

Test coverage

  • Good: new web-server tests (WebServerTests+FieldTypes), JSON formatter tests, and Management tests with fixtures.
  • Gaps to check:
    • Retry/retryAfter semantics across .modifyIncomplete.
    • verifyCredentials result matrix (CredentialStatus × CredentialKind).
    • The Reference+NormalizedZone edge cases (owner name, default zone).
    • An integration or live test for export-schema.

Summary

The pieces I read are careful: secrets are redacted, errors are typed, and the failure modes are documented. The main concerns are the unverified Management API, the strict FieldValue decode behavior change, the empty description, and the size of the PR. Once the live Management API check and the release notes are in, I'd be comfortable with the parts I saw. I can't speak for the parts I couldn't read.

…MENT_TEAM

Ran `mistdemo export-schema` and curl against api.icloud.apple.com for
iCloud.com.brightdigit.MistDemo on 2026-11-24. The management-openapi.yaml
contract held: token header alone, 200 text/plain, JSON RequestError whose
code equals the HTTP status. Beyond CKTool JS: RequestError.message is a
kebab-case code, an unknown container is 403, and the environment segment is
case-sensitive.

- Replace ProvisionalManagementFixtures with RecordedManagementFixtures: the
  live export and four live error bodies (request UUIDs scrubbed); only the
  all-optional-keys RequestError stays hand-written.
- export-schema reads the team from DEVELOPMENT_TEAM, the value .env already
  sets for Xcode signing, instead of a second CLOUDKIT_TEAM_ID; document it
  and CLOUDKIT_MANAGEMENT_TOKEN in .env.example.
- Update the spec, research notes, AGENTS.md and project memory.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@claude

claude Bot commented Nov 24, 2026

Copy link
Copy Markdown

Review: Updates from Mistico v1.0.0-alpha.2

This is a sampled review. The PR has 290 files and about 20k added lines, so GitHub can't render the full diff. I read the Management API plumbing, modifyAllRecords, queryRecordPages, the predicate parser, ManagementToken, and the build, CI and Package changes. I didn't build or run the tests, and I didn't read most of the added tests, the schema parser and tokenizer, WireFormat/*, or the retry code.

Overall

The code I read follows the repo conventions: explicit ACLs, internal import, typed throws, and doc comments that record the live-verified behaviour. The Management API is its own spec and target, which is a sensible split. The issues below are small.

Scope and process

  • PR size. The PR mixes at least six features:

    • the Management API and schema export
    • the FieldValue wire codec
    • a query predicate parser and validator
    • modifyAllRecords and queryRecordPages
    • credential verification
    • CI runner pins

    The title is "Updates from Mistico v1.0.0-alpha.2" and the body is empty. A description listing the features, linking the issues, and saying which parts are public API additions would help a lot. If it can still be split, a smaller PR per feature is much easier to review.

  • Working-tree state. The checkout here shows AGENTS.md and .claude/* as modified relative to HEAD, with the Management API sections removed. That looks like a stale or reverted copy. Please make sure the committed AGENTS.md and .claude/memory entries are the intended versions.

  • CLAUDE.md vs AGENTS.md. The PR documents the new targets, commands and features only in AGENTS.md. The repo's CLAUDE.md mentions only the MistKitOpenAPI target and the old lookupAllRecords signature. If CLAUDE.md is a separate file rather than a symlink to AGENTS.md, it will drift.

  • Release notes. ReleaseNotes.md gets 7 new lines for a very large feature set. Please check the notes cover the public API additions, especially the new MistKitManagementOpenAPI product. Per the repo's release rules, new entries should be flat bullets.

Code quality and bugs

  • queryRecordPages return type (CloudKitService+QueryPages.swift). The docs say "A stream of pages whose errors are CloudKitError", but the type is AsyncThrowingStream<QueryResult, any Error>. Callers can't match on CloudKitError without a cast. This matches the typed-throws direction elsewhere only in the doc comment, not in the code. Either fix the doc or box the errors explicitly.
  • Stuck-marker guard (same file). The guard fires only when the page is empty and the marker repeats. A server that repeats the marker with non-empty pages would loop forever. That matches queryAllRecords, but unlike queryAllRecords there is no maxPages ceiling. A consumer can cancel the stream, so this is acceptable, but I'd call it out in the docs.
  • modifyAllRecords.
    • The sequential send and the modifyIncomplete(completed:unsent:underlying:) design is clear. The warning that the failed batch may have been partially applied is exactly right.
    • encodingFailure(in:) runs try? on RecordOperation conversion and then encodes with JSONEncoder.shared. Every operation is therefore converted twice, once in the pre-flight and again in modifyRecords. That's fine for correctness, but it doubles the conversion cost for large batches. Consider caching the converted operations per request.
    • Atomic zones are matched by ZoneID.normalized. A test where atomicZones holds a zone with an ownerName or type and the operation's zone is built from the name only would pin that behaviour.
  • ManagementErrorBodyMiddleware. When the error body exceeds 1 MiB it returns nil for the body, which discards the status text and any RequestError JSON. That's a reasonable trade-off. A short comment saying so at the try? site would help, since the error is silently swallowed.
  • Predicate parser. parse() reads tokens[position + 1] after seeing TRUEPREDICATE. That is safe only if the lexer always appends an .end token. A precondition or a test with "TRUEPREDICATE" as the last token would make this robust against lexer changes.

Security

  • ManagementToken is redacted in description, debugDescription and Mirror. The middleware sets the header on every request, and there's no logging middleware for the Management client. The summary says CloudKitManagementError.translating(_:) avoids rethrowing ClientError, which would leak headers. This all looks good.
  • Please confirm the token can't reach Codable or Hashable-based logging by accident. The struct is Hashable, so hashing the value into a dictionary key is possible but harmless. It has no Codable conformance, which is the safe default.
  • ExportSchemaCommand reads CLOUDKIT_MANAGEMENT_TOKEN and the unprefixed DEVELOPMENT_TEAM. Please make sure .env.example carries only placeholders. I saw the file change but didn't read it.
  • The error-body cap (1 MiB) and success-body cap (32 MiB) bound memory use. This is good.

Performance

  • Everything is sequential by design, which is right for the ordering and atomicity guarantees.
  • The JSONEncoder pre-flight in modifyAllRecords is the only extra cost I noticed.

CI and build

  • The Windows matrix is pinned to windows-2022 and Android to ubuntu-24.04. Both have explanatory comments. These are pins that need revisiting; consider linking an issue so they don't become permanent.
  • The Xcode 27.2 lanes depend on a preview image, and the device names change with the Xcode version. The comments explain this well.
  • check-generated-openapi.yml now checks untracked files in Sources/MistKitManagementOpenAPI/, which is a good catch for new generated files.
  • Please confirm Scripts/generate-openapi.sh produces the committed Sources/MistKitManagementOpenAPI/ byte for byte. This is what the CI job checks.
  • Package: MistKit now depends on MistKitManagementOpenAPI. As with MistKitOpenAPI, that target must not get InternalImportsByDefault. The comment in Package.swift says so.

Test coverage

  • The PR adds many test files, and the Management tests use recorded fixtures with scrubbed request UUIDs. That is the right approach.
  • I didn't read the tests for the predicate parser, schema parser, WireFormat round-trips, retry hints, verifyCredentials, or modifyAllRecords. They're what I'd check next. In particular:
    • cancellation mid-batch in modifyAllRecords
    • the queryRecordPages stuck-marker case
    • the FieldValue+Codable change (37 added and 127 removed lines), which changes how FieldValue encodes. If it's a behaviour change for existing consumers, it needs a release-notes entry.
  • Examples/MistDemo tests were edited in places (WebServerTests+CRUD lost 21 lines net). Please confirm no coverage was dropped.

Summary

The code I read is solid and well documented. My main requests are a real PR description, a check that AGENTS.md and CLAUDE.md don't drift, a fix to the queryRecordPages error-type doc (or the type), and release-notes coverage for the public API changes.

With Android back on a working runner, its emulator showed the same failure
as WASI: the test binary runs away from the checkout, so reading
Examples/*/schema.ckdb through #filePath fails. Gate the suite on
Platform.isPackageSourceTreeReachable (Package.swift exists at the package
root) instead of a platform list.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@leogdion

Copy link
Copy Markdown
Member Author

Replying to the review, one point at a time. The changes are in a1812e3, e0bb279, 6d0ea69 and c83ee01.

1. Split or describe. The PR now has a description listing the new public API and the breaking changes. It stays as one PR because it syncs code that Mistico moved into MistKit. The commits are grouped by Mistico feature, so it can still be bisected.

2. FieldValue Codable breaking change. Already covered: the first ReleaseNotes.md bullet under Unreleased is a Breaking entry, and it names the MistDemo call sites (web API and JSON output now use the tagged shape).

3. Management API unverified. Two changes:

  • The client is no longer hand-written. It's generated from a new management-openapi.yaml into a new MistKitManagementOpenAPI target. The regenerate-and-diff CI check covers both specs.

  • It was verified live on 2026-11-24 against iCloud.com.brightdigit.MistDemo. The new command is swift run mistdemo export-schema, and I also captured raw responses with curl. The CKTool JS contract held:

    • the token header alone is enough
    • success is 200 text/plain
    • errors are a JSON RequestError whose code equals the HTTP status

    The live service also showed things CKTool doesn't document: message is a kebab-case code (invalid-or-expired-session), an unknown container returns 403 rather than 404, and the environment segment is case-sensitive.

  • ProvisionalManagementFixtures has been replaced by RecordedManagementFixtures: the real export and error bodies, with request UUIDs scrubbed.

On the two sub-points:

  • Token in logs: the token can't reach the logging middleware. The Management client has only a token middleware and an error-body middleware, with no logging. A ClientError is never rethrown either, because its description includes the request headers. Tests check that the service and every thrown error leave the token out of description, debugDescription and dump. ManagementToken now hides its value from Mirror too; before, dump exposed it.
  • 32 MiB cap: exceeding it now throws CloudKitManagementError.invalidResponse instead of a raw runtime error. This is tested for both a known Content-Length and a streamed body.

4. AGENTS.md vs CLAUDE.md. CLAUDE.md is a symlink to AGENTS.md, so they can't drift. The Management section is updated for the generated target and the live results.

5. Generated code. The "Regenerate … and diff" check passed for Sources/MistKitOpenAPI. It now also diffs Sources/MistKitManagementOpenAPI.

6. Test gaps.

  • Strict decoding: already pinned by fieldValueRejectsUntagged (untagged values and {"value":null} throw).
  • Header never logged: covered by the token-exposure tests above.
  • Live Management fixture: done.
  • About 30 new Management tests cover request encoding, success and error bodies (including bodies that can only be read once), the size cap and both middlewares.

7. Conventions. Every new import has an explicit access modifier, new files carry the license header, and the changed files are clean under SwiftLint and swift-format. I ran the locally installed versions, not the mise-pinned ones, and periphery wasn't run.

CI. CI failures from the previous run are fixed as well:

  • wasm: an INT64 above Int32.max trapped on 32-bit platforms. It now throws ConversionError.integerOutOfRange.
  • Example-schema tests: the tests that read Examples/*/schema.ckdb are skipped where the source tree isn't on disk (WASI, the Android emulator).
  • Runners: Android is pinned to ubuntu-24.04, Windows drops windows-2025, and the Xcode 27 lanes move to Xcode 27.2 with its renamed simulators.

🤖 Generated with Claude Code

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@claude

claude Bot commented Nov 24, 2026

Copy link
Copy Markdown

Review of #511: Updates from Mistico v1.0.0-alpha.2

I couldn't review the whole diff. It is about 20k lines across 291 files, and the GitHub API refuses to return it. I read the new hand-written code that matters most: the Management service and its middleware, the wire codecs, FieldValue's Codable, modifyAllRecords and queryRecordPages. I did not read the generated MistKitManagementOpenAPI output, the schema parser or the query-predicate parser, and I did not run the tests. Please treat this as a partial review.

What looks good

  • Secret handling. ManagementToken redacts description, debugDescription and Mirror. CloudKitManagementError.translating(_:) never rethrows a ClientError, which would leak request headers. There is also no logging middleware on the management client.
  • Bounded reads. Error bodies are capped at 1 MiB and success bodies at 32 MiB. Collecting the success body chunk by chunk lets you tell "too large" apart from a transport failure.
  • Fail-loud conversion. ConversionError.integerOutOfRange fixes the 32-bit trap on INT64 values above Int32.max. It matches the existing typeValueMismatch philosophy.
  • Live verification. The management contract was checked live and the fixtures are recorded responses. The PR records which fixture is hand-written, which is the right call.
  • Commit structure. Grouping commits by Mistico issue keeps a 20k-line sync bisectable.

Issues and suggestions

  1. queryRecordPages stuck-marker guard is narrower than it looks (CloudKitService+QueryPages.swift). It breaks only when the page is empty and the marker is unchanged. A server that keeps returning the same marker with non-empty pages loops forever, re-yielding the same data. Break on page.continuationMarker == marker whatever the records are. If you do want to tolerate it, add a maxPages ceiling like fetchAllRecordChanges has. Silently ending the stream here also differs from the "throw on stuck token" behavior of the other paginators. Either throw, or document why this one ends quietly.

  2. modifyAllRecords encodes every operation twice (CloudKitService+ModifyAllRecords.swift). encodingFailure(in:) builds Components.Schemas.RecordOperation and JSON-encodes the whole batch up front, and modifyRecords does it again per request. The up-front check is a good design, because a bad field stops the call before anything is saved. For large inputs, though, the cost doubles and every encoded batch is held in memory briefly. Consider encoding once and reusing the result. Also, try? operations.map(...) returns nil when RecordOperation(from:) throws, so that failure is deferred to the send loop. A late failure after earlier chunks have been saved defeats the "nothing saved" guarantee. Please confirm that is intended.

  3. atomicZones only applies within one chunk. A zone with more than 200 operations is split into several requests, each atomic on its own, so the zone as a whole is not atomic. The docs should say so, and the type or parameter name could make it clearer. It is easy to misread as "this zone is all-or-nothing".

  4. FieldValue.init(from:) and encode(to:) are a breaking change that the release notes should show. The PR body mentions it. Beyond that, FieldValue is public and Codable, so any consumer who persisted untagged JSON, for example in a cache or fixtures, now gets a decoding error. A one-line migration example (WireFieldValue(..., typeTagging: .whenRequired)) in ReleaseNotes.md would help. Please also make sure a test pins the old untagged and null inputs as errors, so the strictness doesn't regress.

  5. WireFieldValue.init(from:) decodes the response path twice. It reads the container for value and then builds FieldValueResponse(from: decoder). That works, but it relies on the generated type tolerating a decoder it has already read from. Add a short comment, or a test, so a generator upgrade doesn't break it unnoticed.

  6. Docs and memory in the working tree don't match the PR. The checkout has uncommitted edits that delete the Management API research doc and memory entry and revert AGENTS.md and CLAUDE.md sections. They are not part of the PR diff I could see. Check that CI isn't running against a tree that differs from the branch. The PR body also points at .claude/docs/research/135-management-api-request-format.md, so that file must not be removed.

  7. Environment spelling. The live check showed a lower-case environment gives 400 and only upper case works. Environment+Management.swift maps this correctly. A test that asserts the exact path segment (DEVELOPMENT / PRODUCTION) would make that a regression guard.

  8. CI changes. The Android pin to ubuntu-24.04, the dropped windows-2025 and the move to Xcode 27.2 are reasonable. Pinning to a single point release (Xcode_27.2.app) will break when the runner image rotates. Add a comment saying when to revisit it.

Security

  • No credentials are logged, and error and success sizes are bounded.
  • The token goes only in a header, and path segments are percent-encoded, which prevents injection through team or container IDs. Please add a test with / or .. in teamId / containerId to lock that in.

Test coverage

The PR reports 999 passing tests and recorded fixtures, which is strong. The gaps I'd close:

  • non-empty pages with a repeated continuation marker (point 1);
  • a modifyAllRecords test where encoding fails in the second chunk;
  • a path-injection test for the management client.

Overall this is a well-structured sync with careful secret handling. The main things I'd fix before merging are the paginator guard (1) and the modifyAllRecords encoding and atomicity semantics (2 and 3).

@claude

claude Bot commented Nov 24, 2026

Copy link
Copy Markdown

Review of #511 (Mistico sync)

The PR diff is over GitHub's 20k-line limit, so I read the security-sensitive and behavior-heavy files directly instead of the full diff. These were Management/*, CloudKitService+ModifyAllRecords.swift and CloudKitService+WebAuthSignIn.swift. I did not build the package or run the tests. This review does not cover the generated code, the CI workflow changes, the docs, or MistDemo.

What looks good

  • ManagementToken redacts itself in description, debugDescription and customMirror. value is internal, and the header is set in one place (ManagementTokenMiddleware).
  • ManagementErrorBodyMiddleware caps the buffered error body at 1 MiB. It buffers only non-success responses, so there is no unbounded memory use on the success path.
  • modifyAllRecords has a clear contract. It encodes every request before sending the first, and it reports completed and unsent on failure. Its docs warn that an "unsent" request may have been applied, which is the right caveat.
  • The typed throws are consistent (throws(CloudKitError)), and the explicit internal import convention is followed.

Suggestions

  1. fetchWebAuthSignInURL() returns a server-supplied URL without checking it (CloudKitService+WebAuthSignIn.swift). URL(string: redirectURL) accepts any scheme. The caller is told to open the result in ASWebAuthenticationSession. It would be cheap to require https (and probably an apple.com or icloud.com host family) and throw incompleteResponse otherwise. That keeps a compromised or misconfigured proxy from handing back a file: or custom-scheme URL.
  2. atomicZones is silently ignored in some cases. The docs say the default zone ignores it, and that only custom zones in a private database support atomic commits. Consider a doc note, or a .debug log line, when atomic: true is requested with database: .public or .shared. Callers will otherwise assume atomicity they don't have.
  3. encodingFailure(in:) converts every operation twice (once to validate, once inside modifyRecords). It also swallows conversion errors with try?. This is fine at today's batch sizes, but it doubles the work for large imports. You could cache the converted operations on ModifyRequest.
  4. Breaking FieldValue Codable change. Rejecting untagged JSON and {"value": null} is called out in ReleaseNotes.md, which is good. Please confirm that nothing persisted (caches, fixtures, MistDemo web JSON) was written in the old shape. WebServerTests+FieldTypes suggests MistDemo was handled. A decode test that pins the failure for the untagged shape would guard the contract.
  5. PR scope. About 10 features are in one PR, with a bisectable commit layout. That is acceptable for a sync, but a reviewer can't realistically verify it all. A short "review guide" listing the riskiest files (auth, FieldValue+Codable, the wasm Int32 change) would help.
  6. Test coverage. The PR description claims 999 passing tests, and the recorded live fixtures for the management API are a strong point. Please make sure these have direct tests:
    • ManagementToken redaction ("\(token)", dump, String(reflecting:))
    • ManagementErrorBodyMiddleware with a body over the cap, which currently returns nil silently
    • fetchWebAuthSignInURL when redirectURL is missing or malformed
    • modifyAllRecords cancellation between batches

Performance

Nothing alarming. The requests are sequential by design, so atomic ordering is preserved. Zone grouping is O(n).

Security

  • Credentials are handled well. The token never appears in logs or reflection.
  • The one real gap is the unvalidated redirect URL (item 1).
  • ManagementToken's synthesized Hashable and == are not constant-time. That is not a practical concern for a client-side token.

Overall this is solid work. I'd address item 1 before merge, and the rest are non-blocking.

Instead of skipping the example-schema suite on WASI and Android, resolve
committed files through PackageFile.url(_:), modeled on SyndiKit's
Content.Directories: the working directory first, then its parents, then
the #filePath checkout.

- WASI: swift-build runs the test binary with `--dir .`, so the package
  root is the working directory.
- Android: `android-copy-files: "Examples"` copies Examples/ next to the
  test binary, which runs from that folder on the emulator. (Copying each
  schema.ckdb individually would flatten them into one name.)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@claude

claude Bot commented Nov 24, 2026

Copy link
Copy Markdown

Review of #511 (Mistico sync)

I reviewed the Management API wrapper and the wire-format codecs in detail. GitHub refuses to render the full diff (over 20,000 lines), so I did not read the other areas line by line. That includes the query predicate parser, the schema parser, modifyAllRecords and the CI changes.

Strengths

  • Token handling is careful. ClientError is never rethrown, because its description includes the request headers. CloudKitManagementError.translating(_:) maps it to the transport error, .httpError or .invalidResponse. ManagementToken is redacted in description, debugDescription and Mirror.
  • Response sizes are bounded. Error bodies are capped at 1 MiB and success bodies at 32 MiB. The success body is read chunk by chunk, with an early body.length check.
  • The spec is separate. management-openapi.yaml gets its own target. That fits the different host, auth and error shape.
  • Tests use recorded fixtures. The recordings come from the 2026-11-24 live run. Only the never-observed optional RequestError keys are hand-written, and the PR says so.
  • Imports follow the CLAUDE.md convention. Every import carries an explicit internal or public.

Concerns

  1. The PR is too large to review.
    • The description says the commits are grouped by feature. A reviewer can't use that if the diff view fails to load.
    • Consider stacking it as separate PRs: Management API, schema and query descriptors, wire codecs, then CI. At minimum, CI runner and toolchain bumps (Android ubuntu-24.04, Xcode 27.2, dropping windows-2025) should be separate from the feature work. They are easy to revert independently and they muddy bisecting.
  2. Dropping windows-2025 reduces CI coverage. The reason given is that its MSVC needs Clang 22. Please link an issue to re-enable it, so the coverage loss isn't permanent.
  3. Breaking FieldValue Codable change.
    • Untagged JSON and {"value": null} now fail to decode. Any downstream code that persists or ingests untagged FieldValue JSON will break.
    • It's in ReleaseNotes.md, which is good. Consider an upgrade note showing the migration: use WireFieldValue for the lenient decode path with a schema type from cloudKitFieldTypes.
    • Add a test that pins the exact error for the untagged case, so the failure stays actionable.
  4. WireFieldValue.init(from:) and ConversionFailureReporter.decodingWithoutTrapping.
    • The doc says caller-supplied JSON skips the DEBUG trap used for responses. Please make sure no other path decodes caller JSON through the trapping variant.
    • A whole-number 5.0 reading as INT64 is a documented limitation. It is a silent type change for anyone omitting type. I'd add a test that pins this behavior, so a future decoder change can't alter it unnoticed.
  5. ManagementErrorBodyMiddleware over-cap behavior. If an error body exceeds 1 MiB, the middleware returns nil for the body. The caller then sees a bare status with no hint that a body was dropped. A short note in the error, or a test for this path, would help. If a test already covers it, ignore this.
  6. Unverified assumption (already noted in the research doc). The management token's required team role is unconfirmed. Only one account was tested. Mention this in the public docs for CloudKitManagementService, so users who get a 403 aren't misled. The 403-for-unknown-container behavior is already recorded.
  7. The lookupAllRecords(zoneID:) signature change. It adds a parameter ahead of database:. If a default of nil isn't given, this is source-breaking for positional callers. Labels make it fine, but please confirm it has a default. The same goes for the lookupRecords primitive.

Performance and security

  • No performance concerns. Buffering is bounded, and the debug-logging guards are unchanged.
  • Security looks good. One thing to check: the MistDemo export-schema command and .env.example should never echo CLOUDKIT_MANAGEMENT_TOKEN in --verbose output. Please confirm.

Test coverage

The reported 999 passing tests and the live verification are good. Gaps I'd like covered:

  • the over-limit error body path
  • the over-limit success body path (32 MiB, both the length header and chunked variants)
  • the integerOutOfRange trap on 32-bit platforms, via a test that doesn't depend on running on wasm

Overall this is solid work with good defensive design. I'd approve once the CI changes are split out or justified, and the points above are confirmed or addressed.

leogdion and others added 2 commits November 24, 2026 15:11
- modifyAllRecords: the pre-flight now runs every check modifyRecords runs
  before sending (encrypted-field validation and operation conversion, not
  only encoding). A bad operation in a later chunk used to be skipped by the
  pre-flight's `try?` and fail only after earlier chunks were saved.
- queryRecordPages: stop when the server repeats the continuation marker
  even on a page with records (yielded once). It used to re-request the same
  page forever. Document that every stream error is a CloudKitError.
- fetchWebAuthSignInURL: return only an https apple.com / icloud.com page;
  refuse file:, custom-scheme and other-host redirectURLs.
- PredicateParser: bounds-check the TRUEPREDICATE lookahead.
- Comment why ManagementErrorBodyMiddleware drops oversized error bodies and
  why WireFieldValue reads its decoder twice.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Replace "## Unreleased" with "## 1.0.0-beta.6". Scripts/release.sh reads the
first "## " heading as the latest tag, so "Unreleased" broke notes-draft
(generate-notes "since Unreleased") and verify-tag. The section now covers
everything since 1.0.0-beta.5: the Mistico sync (#511), encrypted fields
(#485), and #480/#482/#483, as flat bullets with PR links.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@claude

claude Bot commented Nov 24, 2026

Copy link
Copy Markdown

Review of #511 (Mistico sync)

The PR is too large for GitHub's diff API (over 20k lines), so I read the highest-risk files directly instead of the whole diff. Those were the Management API auth and error path, modifyAllRecords, fetchWebAuthSignInURL and the retry hints. I did not build the package or run the tests.

What looks good

  • ManagementToken redaction. description, debugDescription and customMirror are all redacted, and the raw value is internal. This is a good guard against the token leaking into logs.
  • fetchWebAuthSignInURL URL check. isAppleSignInURL requires https and an apple.com or icloud.com host. It uses a proper suffix match on .domain, so evilapple.com is rejected.
  • modifyAllRecords structure. It checks and encodes every request before sending the first. Atomicity is documented as per-request, and modifyIncomplete returns completed and unsent results. The Important note about operations that may have been applied is useful.
  • Retry hints. CloudKitError.retryAfter, redirectURL and isRetryable read through modifyIncomplete. MistKit still doesn't retry on its own.
  • ManagementErrorBodyMiddleware. The error body is capped at 1 MiB, and it only buffers non-success responses.
  • Package layout. The Management API is a separate OpenAPI target with a separate product.
  • Generated code. The generated Management code is kept apart from openapi.yaml.

Issues and suggestions

  1. Breaking FieldValue Codable change (important). Untagged JSON and {"value": null} now fail to decode.

    • It is called out in ReleaseNotes.md, but it affects anyone who persisted or cached FieldValue JSON.
    • Consider a deprecation window or a lenient decoding path. If it stays strict, the release notes should say it is a breaking change and give a migration hint.
    • Please confirm tests cover a clear decode error for old payloads.
  2. Double encoding in modifyAllRecords (performance). preflightFailure builds and JSON-encodes every RecordOperation. modifyRecords then converts and encodes them again when sending.

    • This doubles the CPU and memory cost for large batches. That matters on WASI and in 32-bit builds.
    • Consider caching the converted request bodies per ModifyRequest, or running a cheaper validation-only pass.
    • Also, unsent: operations and completed: [] on a preflight failure is correct. The encoding error does lose which request failed.
  3. Sequential requests in modifyAllRecords. Requests are sent one at a time. That is the safe choice for ordering and for modifyIncomplete semantics. A short doc line saying it is intentional would stop a future "parallelize" change that breaks the guarantees.

  4. ManagementErrorBodyMiddleware hides failures. try? await Data(collecting:upTo:) returns a nil body when the body is over the cap or the read fails.

    • The caller then sees only the status code, with no sign that the body was dropped.
    • Consider logging at .debug or .warning on the .network subsystem.
  5. Redirect URL scope. isAppleSignInURL accepts any *.apple.com or *.icloud.com host. Live CloudKit sends idmsa.apple.com. Narrowing to the hosts actually observed would be stricter, at the cost of future flexibility. Consider at least an allowlist with a comment.

  6. ManagementToken equality. Hashable is synthesized, so == is non-constant-time. That is low risk for a client-side token, but worth knowing if the type is ever compared against secrets.

  7. ManagementRequestFailure.init(from:) loses the status code. It sets statusCode = code until the response status replaces it. A public Decodable that can return a placeholder statusCode is a trap for external users. Either make decoding internal or document it clearly. The doc comment mentions it, but a statusCode placeholder in a public API is fragile.

  8. Retry computed properties. retryAfter, redirectURL and isRetryable each repeat the modifyIncomplete unwrap. A small private underlyingOrSelf helper would reduce duplication and the chance of a missed case.

  9. Repo conventions.

    • CLAUDE.md says new agent memory belongs in .claude/memory/. The PR adds files there, which is fine, but it also adds a large .agents/skills/ tree (OpenAI-style agents/openai.yaml) that is not mentioned in the PR description. Please confirm that is intentional.
    • The PR description says it targets v1.0.0-beta.6. Under the release rules in CLAUDE.md, example workflows must pin the release branch (with v) before the merge and the tag (without v) after publishing. Please verify with ./Scripts/release.sh pins.
  10. Scope and CI.

    • This is about 20k lines across about 10 features. It is bisectable by commit, which helps, but it is hard to review as one PR.
    • The CI runner changes (Android pinned to ubuntu-24.04, windows-2025 dropped, Xcode 27.2) are unrelated to the feature sync. Reviewers would find them easier to check in a separate PR.
    • Dropping Windows windows-2025 reduces coverage. Please make sure there is a tracking issue to restore it.

Test coverage

There are about 43 test files matching management, modify-all, query pages, web-auth sign-in, verify-credentials or retry. The PR reports 999 passing tests on macOS only.

Please confirm the new code is covered on Linux, WASI and Android too. The INT64 above Int32.max fix (ConversionError.integerOutOfRange) in particular needs a 32-bit test. Skipping the example-schema tests on WASI and Android is reasonable.

Security summary

I found no blocking security issues. The token redaction, the redirect URL check and the bounded error-body read are all sound. Items 4 and 5 are hardening suggestions.

Overall this is solid work. Item 1, the breaking Codable change, is the one I'd resolve or document more thoroughly before merging.

brightdigit/BushelCloud was renamed brightdigit/SwoopMistKit. Move the
subrepo to Examples/SwoopMistKit and point its .gitrepo remote at the new
repo (branch mistkit, same commit). The package inside is unchanged and
still named BushelCloud. Remove Examples/CelestraCloud; CelestraCloud
continues as its standalone repo.

- CI: examples.yml tests SwoopMistKit; Scripts/release.sh pins and
  update-subrepo.sh target Examples/SwoopMistKit; project.yml drops
  Celestra; the example-schema test reads Examples/SwoopMistKit/schema.ckdb.
- Docs: README, AGENTS.md, DocC articles, MistKitConfiguration docs,
  .claude docs, the release skill and memory now use the new path and repo
  URL. CelestraCloud links point at its standalone repo. Prose about the
  Bushel and Celestra apps and the talk is unchanged.
- ReleaseNotes: note the change under 1.0.0-beta.6.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Copying all of Examples/ failed in `adb push`: it can't create symlinks on
the device (Examples/CelestraCloud/CLAUDE.md was one) and pushed megabytes
the tests never read. Stage the tracked Examples/*/schema.ckdb files with
their paths and copy just .android-test-data/Examples.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@claude

claude Bot commented Nov 24, 2026

Copy link
Copy Markdown

Review of #511 (Mistico sync)

I could not read all of this PR. GitHub's diff API refuses it (over 300 files), and it adds about 19k lines. I read the code that is riskiest for security and correctness. That was the Management API client, modifyAllRecords, fetchWebAuthSignInURL, the FieldValue codec change, and the Package, CI and lint changes. I did not build or run the tests. The wire codecs, the predicate parser, the schema parser and the generated code got only a skim or no read.

What looks good

  • Token handling. ManagementToken redacts itself in description, debugDescription and customMirror. CloudKitManagementService leaves out the logging middleware on purpose, so the token can't reach a log. The header is set in one middleware.
  • Export body limit. exportSchemaText caps the body at 32 MiB. It checks the declared length first and then the running size, so a lying Content-Length can't defeat it. It also reports non-UTF-8 text as a typed error.
  • Sign-in URL check. fetchWebAuthSignInURL only returns a server-supplied redirectURL if it is https and its host is apple.com, icloud.com or a subdomain. The match uses host == d || hasSuffix(".d"), so evilapple.com is rejected. That closes an open-redirect and phishing path.
  • modifyAllRecords.
    • Every request is checked and encoded before the first one is sent.
    • A partial failure throws modifyIncomplete(completed:unsent:underlying:), and the caller can see exactly what was sent.
    • The doc comment says atomicity is per request, not per zone, and warns that "unsent" operations may have been applied. Both are accurate and useful.
    • Batch size is clamped to 1...200.
  • Generated code. MistKitManagementOpenAPI is a separate target, excluded from SwiftLint, and checked by check-generated-openapi.yml. The check now also fails on untracked generated files.

Issues and suggestions

  1. Docs not updated. CLAUDE.md is untouched, and the PR adds a lot of public surface it describes.
    • The "CloudKitService Operations" table has no rows for ModifyAllRecords, QueryPages, VerifyCredentials or WebAuthSignIn.
    • The package structure lists only two targets, but there are now three (MistKitManagementOpenAPI).
    • Management/, Schema/, Queries/Predicate, WireFormat/ and SchemaSources/ are not described.
    • The FieldValue section does not mention the stricter Codable. A "Never edit Sources/MistKitManagementOpenAPI/" note is also missing. AGENTS.md changed, so the two files may drift apart.
  2. Breaking FieldValue: Codable. Untagged JSON and {"value": null} now throw. That is defensible and the PR calls it out. Still, it is a silent runtime break for anyone persisting FieldValue JSON, because it compiles fine. Please add a test that pins the exact error messages. A short migration snippet in ReleaseNotes.md would help too.
  3. ManagementRequestFailure.init(from:). It is public and sets statusCode to the body's code, a placeholder until with(statusCode:) replaces it. A caller who decodes it directly gets a status that may be wrong. Either make that initializer internal or document the caveat on the property.
  4. Redirects and the token. URLSessionTransport follows redirects by default. If api.icloud.apple.com ever redirects, URLSession can forward custom headers such as X-Apple-CloudKit-Management-Token to the new host. I am not sure that is a real risk here. It may be worth rejecting a 3xx in ManagementErrorBodyMiddleware, or documenting that the transport must not follow redirects.
  5. PR scope. The PR bundles the CI runner changes, skill and doc sync, deletion of about 60 Examples/CelestraCloud/.agents and .claude files, and the new feature set. Please confirm that deleting the CelestraCloud files is intended and that nothing there is referenced elsewhere. The grouped commits make it bisectable, but this will be hard to review as one PR. If that's unavoidable, a short list of the load-bearing files would help reviewers.
  6. CI.
    • Dropping windows-2025 and pinning Android to ubuntu-24.04 look reasonable. Please add a comment or issue link on each pin saying when to revisit it.
    • Hard-coding Xcode_27.2.app and specific simulator names in four workflows will need touching on every Xcode bump. A single shared env or matrix source would stop them drifting.
  7. Tests. The Management tests use recorded live fixtures, which is good. The PR description says 999 tests pass on macOS only. I would like to see the Linux, WASI and Windows results before merging, since the Int64 overflow fix (ConversionError.integerOutOfRange) and the skipped example-schema tests are platform-specific. Please confirm there are dedicated tests for:
    • modifyAllRecords partial-failure and cancellation paths
    • isAppleSignInURL negatives (http://, evilapple.com, apple.com.evil.com)
    • the 32 MiB over-limit path
    • the INT64 > Int32.max throw on a 32-bit target

No blocking bugs found in the files I read. Item 1 is the one I'd fix before merging. Items 3 and 4 are worth a decision.

ubuntu-latest moved to Ubuntu 26.04, which doesn't ship libxml2.so.2, so
the mise-installed SwiftLint 0.62.2 binary failed to start ("error while
loading shared libraries: libxml2.so.2") and Linting reported an error.
Pin lint in MistKit, MistDemo, MistKitConfiguration and SwoopMistKit, as
the Android jobs already are.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@claude

claude Bot commented Nov 24, 2026

Copy link
Copy Markdown

Review: Updates from Mistico v1.0.0-alpha.2

This PR has 300+ files, so I read the security- and correctness-sensitive parts rather than every file. I did not build it or run the tests. The files I read were the management token and middleware, fetchWebAuthSignInURL, modifyAllRecords and the CloudKitError retry hints. I did not read the predicate parser, schema parser or wire codecs in detail.

What looks good

  • ManagementToken redacts itself in description, debugDescription and customMirror, and value is internal. That keeps the token out of logs and dump.
  • isAppleSignInURL requires https and an apple.com or icloud.com host, matching the host exactly or as a .domain suffix. A tampered redirectURL can't send a browser session to an arbitrary URL. mapToCloudKitError passes CloudKitError through unchanged, so the incompleteResponse thrown inside the do block survives the catch.
  • modifyAllRecords
    • It validates and encodes every request before the first send, so a bad operation saves nothing.
    • modifyIncomplete(completed:unsent:underlying:) reports partial progress. The doc comment warns that "unsent" operations may have been applied.
    • It uses ZoneID.normalized consistently when grouping.
  • The retry hints (retryAfter, redirectURL, isRetryable) read through modifyIncomplete, and MistKit still never retries on its own.
  • ConversionError.integerOutOfRange replaces a trap on 32-bit platforms.

Concerns

  1. Scope and reviewability.
    • Size: this is one PR with 300+ files, and the GitHub diff API rejects it (HTTP 406).
    • Deletions: it deletes the whole Examples/CelestraCloud/.claude, .agents, .devcontainer and .env.example trees. The description doesn't mention that. If it's intentional, e.g. a submodule or overlay change, please say so. Otherwise it looks like an accident that would remove the example's tooling.
    • Suggestion: the grouped commits help, but consider splitting out the CI runner changes, the Management API and the schema/query/wire work.
  2. Breaking FieldValue Codable.
    • Change: untagged JSON and {"value": null} now fail to decode. That is source-compatible but behaviorally breaking.
    • Gaps: it needs a prominent ReleaseNotes.md entry, which the description says exists. Please also check that no persisted or cached JSON in the examples (MistDemo, Bushel, Celestra) relies on the untagged shape.
  3. Double encoding in modifyAllRecords. preflightFailure builds the API operations and runs JSONEncoder.shared.encode over them. modifyRecords then converts and encodes the same operations again. For large batches (thousands of records) that is 2x conversion and encoding work. Passing the preflight output through, or an internal modifyRecords overload that takes pre-converted operations, would avoid it. It's not urgent.
  4. ManagementErrorBodyMiddleware drops errors silently. try? await Data(collecting:) returns nil for the body on overflow or a mid-read failure, with no log. A debug-level log on the .network or .middleware subsystem would make "why is my error body empty" diagnosable. The comment justifying the drop is good.
  5. fetchWebAuthSignInURL:
    • Control flow: the throw-inside-do followed by a catch that maps and reassigns is hard to follow. Restructure it so the success case is handled after the do/catch rather than thrown into it.
    • Edge cases: URL(string:) parsing quirks (userinfo, backslashes) can make url.host differ from what a browser resolves. Add tests for https://evil.com\@apple.com, https://apple.com.evil.com and http://apple.com.
  6. CI pins. The Android ubuntu-24.04 pin and the Xcode 27.2 / simulator names are brittle but reasonable. Keep a tracking note to unpin when ubuntu-latest gets a swift.org toolchain.

Test coverage

  • The description says 999 tests pass on macOS only. Please confirm the WASI, Android and Windows lanes are green, since skip conditions were added for the example-schema tests and the Int32 overflow fix is specific to 32-bit platforms.
  • I'd like explicit tests for:
    • modifyAllRecords when cancelled mid-batch.
    • modifyAllRecords across zones with mixed atomicZones.
    • A body over maxErrorBodyBytes in the management middleware.
    • The redirect-URL validator cases above.
  • Management fixtures are recorded live responses, which is good. Check they contain no real tokens or identifiers.

Convention check (CLAUDE.md)

  • I didn't check the internal import rule across all files. The files I read follow it.
  • Please run ./Scripts/lint.sh (swiftlint, header and periphery) given the number of new public types.

Overall the design is careful, especially the error and credential handling. My main asks are to confirm the Celestra deletions are intentional and to cover the URL-validation edge cases with tests.

leogdion and others added 6 commits November 24, 2026 17:03
Add ManagingSchemas, BuildingQueries, EncodingRecordsAsJSON and
BatchingAndPagination; cover retry hints, record/field error context,
verifyCredentials and fetchWebAuthSignInURL; bring FieldTypePolymorphism
up to date with Arity lists and *_LIST response tags; regroup the landing
page Topics by feature area; fix the 20 DocC link warnings.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…le notes

Add SyncingChanges, SharingAndUsers, WorkingWithAssets and
SubscriptionsAndNotifications to the DocC catalog and its Topics. Correct
the asset upload method (POST, not PUT) and the fileChecksum doc comment
(a server-minted identity token, not a SHA-256). In AGENTS.md, fix the
fetchRecordChanges/fetchAllRecordChanges signatures, remove the
nonexistent no-argument discoverAllUserIdentities(), and correct what
RecordTypeIterating is used by.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…neID

- Drop the `.private` default from listZones, lookupZones,
  fetchDatabaseChanges, fetchAllDatabaseChanges, fetchRecordZoneChanges,
  fetchAllRecordZoneChanges and the deprecated fetchZoneChanges /
  fetchAllZoneChanges, matching every other operation (no silent
  database default).
- rereferenceAsset now forwards zoneID to its target lookupRecords and
  updateRecord calls, which previously hit the default zone; add a
  regression test that checks both request bodies.
- Deprecate lookupUsersByEmail / lookupUsersByRecordName (Apple-deprecated
  users/lookup/*); tests call them through a non-deprecated protocol, as
  the FetchZoneChanges tests do.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Swift 6.2 on Windows silently aborts while emitting MistKitTests (#488);
drop it rather than keep a permanently red, non-gating job.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
lint.sh exited 127 in Claude Code web sessions because the toolchain
exposes only a swift symlink on PATH. Fall back to the toolchain's bin
directory for swift-format. Also apply the header script's normalization
of FieldValue+Codable.swift.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V3TXo4Ap5WPp9rBvzBYYuk
@claude

claude Bot commented Nov 24, 2026

Copy link
Copy Markdown

Review of #511 (Mistico sync)

I could only read the checked-out tree. The GitHub diff is over 300 files, mostly deletions under Examples/CelestraCloud, so it can't be fetched. I read the new Management layer, modifyAllRecords, and the integerOutOfRange path. I did not build or run tests. I did not review the CI workflow edits, the predicate parser, or the schema sources in depth.

What looks good

  • ManagementToken redacts itself in description, debugDescription and customMirror, so it won't leak through logs or dump.
  • ManagementErrorBodyMiddleware caps buffered error bodies at 1 MiB and drops the body on a mid-read failure. The status code still reaches the caller.
  • modifyAllRecords checks and encodes every request before sending the first. A client-side failure therefore sends nothing. The completed and unsent fields of modifyIncomplete make partial failure recoverable, and the docs warn that an "unsent" operation may already have been applied.
  • The Int64 above Int32.max trap on 32-bit platforms now throws ConversionError.integerOutOfRange. This fits the codebase's fail-loud approach.
  • The new endpoints follow the repo's explicit-ACL and internal import conventions in the files I read.

Concerns

  1. Breaking FieldValue Codable change. Untagged JSON and {"value": null} now fail to decode. The PR describes this and ReleaseNotes.md covers it. Please confirm no persisted or fixture data in Examples/* still uses the untagged shape. A Codable-compat migration test would pin this.
  2. Preflight encodes every operation twice. preflightFailure JSON-encodes the whole request, and modifyRecords then encodes it again. The cost is small for 200-item batches. For very large inputs, a note or a shared encoded body would help.
  3. preflightFailure reports an encoding failure for the whole request. Its CloudKitError(encodingError:recordNames:) lists every record name in the request. A NaN has a specific field, which invalidFieldValue is meant to name. Please confirm the encode path in the preflight hits the same per-field mapping as the path inside modifyRecords. The doc comment claims they match, so a test asserting equal errors for both would back that claim.
  4. modifyRequests buffering and ordering. Operations are grouped by zone, so output order is not input order when zones interleave. The doc says "grouped by zone", but callers matching results to inputs by index will be surprised. An explicit - Note: in the Returns section would help.
  5. Management auth. The token is sent as a plain header. That is fine over HTTPS to api.icloud.apple.com. baseURL is a public static URL(string:)!, which is acceptable for a constant. Make sure the initializer's serverURL override can't be pointed at a non-HTTPS host by accident. Otherwise the token would be sent in cleartext.
  6. Scope and reviewability. A 300+ file sync with a CelestraCloud deletion, generated code, workflow changes, and new APIs is hard to review as one PR. The commits are grouped by feature, which helps. Consider noting in the description that the Examples/CelestraCloud removals are intentional (moved to another repo?). They are not mentioned.
  7. CI pins. Pinning Android to ubuntu-24.04 and dropping windows-2025 reduces coverage. Add a tracking issue or TODO to restore them once the toolchains support them.

Tests

The PR reports 999 tests passing on macOS (Xcode 27.2). Please confirm CI is green on Linux, WASI, Windows and Android. The 32-bit integerOutOfRange fix is only meaningful on WASI, so check that its test actually runs there and isn't skipped by the new source-tree-absent guards.

No security blockers found.

leogdion and others added 2 commits November 24, 2026 20:38
ManagementErrorBodyMiddleware dropped an error body over the 1 MiB cap,
or one that failed mid-read, with no trace: the caller saw a bare status.
It now logs a .warning on the network subsystem naming the operation,
the status and the error type. The body, the request and its headers
(which carry the management token) are never logged. Behavior is
otherwise unchanged.

Tests capture the warning with a small AsyncStream-backed LogHandler.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The preflight check converted and JSON-encoded every request, and
modifyRecords then converted and encoded it again when sending. The
preflight now finds a NaN or infinite number directly on the domain
values (DOUBLE, TIMESTAMP as wire milliseconds, every Location number),
producing the same invalidFieldValue(recordName:fieldName:) the encoder
path does, and keeps the converted operations. Both modifyRecords and
modifyAllRecords send through a new internal sendModifyRecords, which
keeps the EncodingError mapping as a safety net.

A parameterized test pins the new check to JSONEncoder's behavior on
the converted request, including a finite date that overflows in
milliseconds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@claude

claude Bot commented Nov 25, 2026

Copy link
Copy Markdown

Review of #511 (Mistico sync)

I could not read the full diff. GitHub refuses to render it at 629 files, so this covers the PR description and a spot check of the Management API, S2S signing and INT64 narrowing code. I did not run the build or tests. I'm relying on the reported 1005 passing tests and the clean lint run.

What looks good

  • ManagementToken redacts itself in description, debugDescription and customMirror, and value is internal. That is the right shape for a credential type.
  • ManagementErrorBodyMiddleware caps buffered error bodies at 1 MiB. The new drop warning logs only the status, operation ID and error type, never the body or headers. That fits the "no built-in redaction" stance in CLAUDE.md.
  • cloudKitBodyHash(of:) treats nil and Data() the same, with the empty-data hash documented. That fixes the body-less signed GET (#136) in one place.
  • platformInt turns the 32-bit Int64 trap into a thrown ConversionError.integerOutOfRange, which matches the fail-loud convention.
  • Keeping management-openapi.yaml and MistKitManagementOpenAPI separate from openapi.yaml is sound, given the different host, auth and error shape.

Concerns

  1. Breaking changes in a beta bump.
    • FieldValue's Codable now rejects untagged JSON and {"value": null}. Anyone who persisted FieldValue JSON with an earlier version can no longer read it. The release notes should say so, and a migration or fallback decoder is worth considering. If this was a deliberate decision, record it in agent-notes or the memory files.
    • Removing the .private default on database: is consistent with the "no default" rule, but it is source-breaking. Make sure ReleaseNotes.md lists every affected method.
  2. CLAUDE.md is stale after this PR.
    • It still describes Examples/BushelCloud and Examples/CelestraCloud as live examples. The PR renames one and removes the other.
    • It lacks the Management API, modifyAllRecords and the stricter FieldValue Codable, which the PR adds to AGENTS.md. If CLAUDE.md links to AGENTS.md, confirm the link resolves. Otherwise the two will drift.
  3. Memory deletions.
    • The PR deletes .claude/memory/project_change_tracking_custom_zones_only.md and reference_management_api_request_format.md, plus the research doc .claude/docs/research/135-management-api-request-format.md. The PR description cites that research doc as the evidence for the live verification.
    • My checkout shows these three files as deleted, while the PR file list shows them as added. Please confirm they are actually present on the branch. Also check that MEMORY.md has no dangling index entries.
  4. Body drop in ManagementErrorBodyMiddleware.
    • return (response, nil) after a failed read is fine for oversize bodies. For a mid-read transport error, swallowing the error hides a possible connection problem behind the status-only failure.
    • The warning mitigates this. A test that checks the status still maps to the right CloudKitManagementError would be worth adding if there isn't one.
  5. CI pins. ubuntu-24.04 and windows-2022 are reasonable, but they are hard pins that will need a later bump. Windows no longer tests Swift 6.2 because of Windows Swift 6.2: MistKitTests emit tip-over returns (blocks #392 / PR #485) #488. Leave a tracking comment in the workflow so it comes back.
  6. PR shape.
    • The size is mostly deleted CelestraCloud files plus the rename.
    • The Examples removal and rename are independent of the library sync, and bundling them makes review hard. Splitting them out, or at least noting that the library change is about +20k lines under Sources/MistKit and Tests/MistKitTests, would help reviewers.
    • Reviewers can use gh api repos/brightdigit/MistKit/pulls/511/files --paginate to view the files.

Tests, security, performance

  • Tests: coverage looks thorough from the description, including the JSONEncoder-parity test for the NaN/infinity preflight and the recorded live fixtures. Since FieldValue decoding is now a breaking change, add explicit negative tests for the untagged and null shapes if they aren't already there.
  • Security: no issues found in the files I read. Check that management tokens never reach .debug request logging. The middleware logs headers at debug level, so confirm X-Apple-CloudKit-Management-Token is excluded or masked.
  • Performance: converting and encoding each request once in modifyAllRecords is a good fix.

🤖 Generated with Claude Code

With Xcode 27.2's SDK, swiftc 6.3.x fails every package manifest
(swift-crypto, swift-openapi-urlsession, ...) with "unknown argument:
'-target-arch-variant'" and then crashes with signal 11, so a plain
`swift test` built nothing. swift.org 6.4.2 matches Xcode 27.2's Swift
and passes all 1005 tests.

CI is unaffected: every lane passes its toolchain explicitly and none
reads .swift-version. The pin is read only by swiftly and by
Scripts/cloud-setup.sh, whose fallback moves to 6.4.2 too; swift.org
publishes 6.4.2 for Ubuntu 24.04.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@claude

claude Bot commented Nov 25, 2026

Copy link
Copy Markdown

Review of #511 (Mistico v1.0.0-alpha.2 sync)

Scope caveat: GitHub can't render this diff (629 files), so I reviewed the PR description in full and read the new Management API code in Sources/MistKit/Management/ and the body-hash signing helper locally. I did not read the roughly +20k lines of library and test changes line by line. Treat this as a spot-check, not a full audit.

What I read, and it looks good

  • ManagementToken redacts its value in description, debugDescription and customMirror. The raw value is internal, so it can't leak through logs or dump.
  • ManagementTokenMiddleware only sets the header and has no logging path.
  • ManagementErrorBodyMiddleware caps buffered error bodies at 1 MiB, drops oversized or unreadable bodies, and logs only status, operation and error type. That is the right call for secret hygiene.
  • SHA256.cloudKitBodyHash(of:) hashes body ?? Data(), so a nil body and an empty body sign identically. This matches the #136 fix for signed GETs.
  • The imports follow the explicit-ACL convention in CLAUDE.md.

Concerns and suggestions

  1. Breaking changes in a beta. FieldValue's Codable now rejects untagged JSON, and the database: defaults are removed from several operations. Both are called out in the PR, and the second is consistent with the "no default database:" rule. Please make sure ReleaseNotes.md has a migration snippet for the Codable change. Anyone who persisted FieldValue JSON will fail to decode it with no fallback.
  2. Mixing concerns in one PR. The sync is bisectable by commit, but the PR also carries the CelestraCloud removal (about 31k deleted lines), the BushelCloud→SwoopMistKit rename, and CI runner and Xcode pin changes. Those are hard to review next to the library changes. If you can, land the Examples removal and rename in a separate PR, or at least merge with rebase so the per-feature commits survive.
  3. CI pin hygiene. ubuntu-24.04 and Xcode_27.2.app are pinned. Please confirm that ./Scripts/release.sh pins --expect-branch v1.0.0-beta.6 passes. The examples workflows must pin the branch (not the tag) before the merge, per the release runbook.
  4. Memory store drift. The PR adds .claude/memory/ entries and also touches .claude/agent-notes.md. Check that MEMORY.md indexes every new file. It also adds both project_examples_swoopmistkit.md and project_examples_dir_is_for_mistkit_dev.md, so make sure they don't contradict each other.
  5. Test coverage. The PR reports 1005 passing tests on macOS plus recorded live fixtures for the Management API. That is solid. I'd still want explicit tests for:
    • ConversionError.integerOutOfRange on a 32-bit/wasm path. Does CI actually run it there, or only on 64-bit?
    • The rereferenceAsset zoneID fix, covering a non-default zone. Check that it is pinned by a regression test.
    • modifyAllRecords preflight NaN/∞ detection. The PR says a parameterized test pins it to JSONEncoder, which is good.
  6. Performance. The modifyAllRecords double-conversion fix is a welcome improvement. Nothing else stood out in the parts I read.
  7. Security. I saw nothing concerning in the parts I read: no token logging, bounded body buffering, and no new transport sharing with the CDN. I did not audit the new query predicate parser (QueryDescriptor). If it takes user-supplied strings, fuzz or negative tests for it would be worthwhile.

Overall the parts I could check are high quality and match the repo's conventions. My main request is the migration notes for the FieldValue Codable break. The second is a decision on splitting the Examples churn out of the library review.

@leogdion
leogdion merged commit e1b1d6a into v1.0.0-beta.6 Nov 25, 2026
106 of 107 checks passed
@claude claude Bot mentioned this pull request Nov 25, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants