This is the multi-page printable view of this section. Click here to print.

Return to the regular view of this page.

RawCull Packages

Pinned package revisions, imported products, dependency direction, and the recommended architecture reading order.

RawCull Packages

Start here: One Package, Three Imports: Understanding Swift Modules explains packages, products, targets and imports using PhotoEvidenceKit before you read the individual package architecture guides.

RawCull is the composition root for five architecture packages and four small rsync/persistence support packages. Package repositories are separately versioned; paths under Sources/ and Tests/ refer to the named repository, not files copied into this documentation site. The app translates between package contracts and owns selection, file access, caches, persistence, and review decisions.

The November 8, 2026 review uses RawCull 3.4.0 build 434. Existing guides retain their explicitly dated architecture audits and add current integration notes. PhotoEvidenceKit has a new guide covering the resolved 1.0.7 implementation. Sibling checkout HEADs do not redefine the application’s resolved baseline.

Build 466 resolved dependencies

The application lockfile records 24 remote pins. Since build 462, PhotoAIKit moved from 1.0.0 to 3.1.0 and PhotoAnalysisKit from 1.3.9 to 1.4.1. PhotoEvidenceKit changed its repository URL from SSH to HTTPS at the same version and revision. The MCP helper has a separate package graph. Application lockfile · MCP helper lockfile

IdentityVersionRevision
coreai-models1.0.05de95c6cd29e5e390fb36d87e13b2396668f7974
decodeencodegeneric1.0.0b5ecbbbe1b244191efec1532a979f6ae342d6617
eventsource1.6.0bb4b61273b5a976bb571859c17f903ebc3439df1
parsersyncoutput1.0.0e079e0c9d34bf07f7f2a4312b40feea79ae14847
photoaikit3.1.026647c62d9933968d92bd00b162290cdd7c78fee
photoanalysiskit1.4.12f41e8b756f006e0218f86b103801ebb47cf8983
photoevidencekit1.1.5e49d34adcfa2e2c43a4240c2e962dbe9defa4cad
rawcullcore1.1.5ea8ac2fc6611949af2b55ec433456bfe502cf886
rawparserkit1.3.326df4abc2178d5c07d08f3883d84d0648f5141d3
rsyncarguments1.0.00ff6518136c208dfbecc1a918f045048ca79853d
rsyncprocessstreaming1.0.0dd86f012b352888fd146e0b6e103740dc237f740
swift-asn11.7.4917b472dbe53ba699cbb0495f9a95a084bc6364d
swift-atomics1.3.10442cb5a3f98ab802acb777929fdb446bda11a34
swift-collections1.7.5f96b909e1a9e469620bc5037c1e24e00153f376f
swift-crypto4.5.2da9d28d69ebe3894b18376c8f2395c2f37b8448f
swift-huggingface1.0.0c30143a4616f3fa994ee3ab3e3464f752845c07c
swift-jinja3.0.0a091d6ae559ee97e904a0f3c2890b21949d0306f
swift-log1.17.0e3da04078777e6a1b72ce19981fbd6539b0847d8
swift-nio2.105.02f58d8ef84438d6517fc78bcea2f8527e3c72936
swift-sdk0.12.1a0ae212ebf6eab5f754c3129608bc5557637e605
swift-system1.8.1869129b7bf4ecc57b97d0193ad29690ca2134750
swift-transformers1.4.0402a8a1105f52038b0949d9596981fc9e32bed17
xgrammar0.2.24d145cc13d878c751ebeed36af1c013074be76bc
yyjson0.13.06447536015f3d600f3d65323b10976103b337ca7

November 9 Close Up Development Build

At the November 9 review, the version-3.4.5 branch used two local package references. Its source baseline is RawCull 3.4.5, build 436, commit a68253b73cbad14a7b1030dba6b439e6bce7d3da. The revisions identify the sibling checkouts used to verify the integration.

PackageXcode pathCheckout revisionClose Up responsibility
PhotoAnalysisKit../PhotoAnalysisKit27d422b100214dd1520f7ca11123f58a86f04e99Human face rectangles and preview detail
PhotoEvidenceKit../PhotoEvidenceKit35e8aca4135ac2151cbce033e4e9baefb8bafabcCrop rendering and manual inspection UI

The animal head and eye pilot lives in RawCull and uses Apple’s Vision framework. It required no package release or dependency update. The November 8 table below is the historical remote snapshot. Build 436 retains the other 17 entries at their recorded revisions. See the Close Up guide for the workflow and the distinction between detected and manual crops.

November 8 Resolved Dependency Snapshot

This table is derived from the local RawCull RawCull.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved, reviewed November 8, 2026 alongside project.pbxproj and source imports. “App” means RawCull directly consumes package products; “transitive” means a package owns the dependency. There are 19 resolved entries.

IdentityRelationshipVersion/branchRevision
DecodeEncodeGenericapp1.0.0b5ecbbbe1b244191efec1532a979f6ae342d6617
ParseRsyncOutputapp1.0.0e079e0c9d34bf07f7f2a4312b40feea79ae14847
PhotoAIKitapp1.0.04b85056e6c2603b5e382987710ca2f16f4c5c155
PhotoAnalysisKitapp1.3.12a1466e04d821fa2628d6985296643e0d0c7e465
PhotoEvidenceKitapp1.0.77614fd1528bb7cf2549799fb937678ea39d90228
RawCullCoreapp1.1.2d25a51e65ad32a82bf82f86fa0ec07d6e14498e9
RawParserKitapp1.3.326df4abc2178d5c07d08f3883d84d0648f5141d3
RsyncArgumentsapp1.0.00ff6518136c208dfbecc1a918f045048ca79853d
RsyncProcessStreamingapp1.0.0dd86f012b352888fd146e0b6e103740dc237f740
coreai-modelstransitive1.0.05de95c6cd29e5e390fb36d87e13b2396668f7974
EventSourcetransitive1.6.0bb4b61273b5a976bb571859c17f903ebc3439df1
swift-asn1transitive1.7.4917b472dbe53ba699cbb0495f9a95a084bc6364d
swift-collectionstransitive1.7.5f96b909e1a9e469620bc5037c1e24e00153f376f
swift-cryptotransitive4.5.2da9d28d69ebe3894b18376c8f2395c2f37b8448f
swift-huggingfacetransitive1.0.0c30143a4616f3fa994ee3ab3e3464f752845c07c
swift-jinjatransitive3.0.0a091d6ae559ee97e904a0f3c2890b21949d0306f
swift-transformerstransitive1.4.0402a8a1105f52038b0949d9596981fc9e32bed17
xgrammartransitive0.2.24d145cc13d878c751ebeed36af1c013074be76bc
yyjsontransitive0.13.06447536015f3d600f3d65323b10976103b337ca7

Do not infer the app boundary from every transitive pin. Xcode product references and source imports define what RawCull actually consumes.

Imported Products And Boundary Types

PackageProducts imported by RawCullValues or protocols crossing the boundary
RawParserKitRawParserKitRawImageLoader, RawImageMetadata, RawFocusPoint, RawFormatRegistry, CGImage results; the app maps them through RawParserKitImageLoader
PhotoAnalysisKitPhotoAnalysisKitPhotoAnalyzer, PhotoAnalysisInput, PhotoAnalysisDescriptor, PhotoAnalysisResult, focus evidence and mask values
RawCullCoreRawCullCoreRawCullFileItem, RawCullSourceCatalog, ExifMetadata, burst inputs/results/configurations, ranking evidence, histograms; the app exposes compatibility typealiases such as FileItem
PhotoAIKitPhotoAIContracts, CoreAICLIPBackend, CoreAIQwenBackend, CoreAISAM3Backend, CoreAIEfficientSAMBackend, VisionFeaturePrintBackend, PhotoAIWorkflows, PhotoAIStorageAIImageSource, model identities/resources, similarity artifacts/descriptors, provider protocols, segmentation requests/results, mask stores and workflows
PhotoEvidenceKitPhotoEvidenceContracts, PhotoEvidenceEngine, PhotoEvidenceUICloseUpFrame, region/viewport/source descriptors, AF availability, renderer and region-store protocols, CloseUpModel, CloseUpPanel
RsyncArgumentsRsyncArgumentsrsync argument builders used by Params and ArgumentsSynchronize
RsyncProcessStreamingRsyncProcessStreamingRsyncProcess and ProcessHandlers used by the copy executor
ParseRsyncOutputParseRsyncOutputparsed transfer progress and totals used by RemoteDataNumbers
DecodeEncodeGenericDecodeEncodeGenericgeneric JSON encode/decode used by saved-file persistence

RawCull owns the translations between these vocabularies. None of the five architecture packages imports another merely to share an app model.

Dependency Direction

flowchart TD
    UI["RawCull SwiftUI"] --> Host["RawCull composition, adapters, policy, persistence"]
    Host --> Parser["RawParserKit\nRAW decode + normalized metadata"]
    Host --> Analysis["PhotoAnalysisKit\nmeasurements + masks"]
    Host --> AI["PhotoAIKit products\nAI contracts + backends + workflows"]
    Host --> Core["RawCullCore\npure grouping + ranking"]
    Host --> Evidence["PhotoEvidenceKit products\nmanual close-up inspection"]
    Host --> Args["RsyncArguments"]
    Host --> Process["RsyncProcessStreaming"]
    Host --> Output["ParseRsyncOutput"]
    Host --> JSON["DecodeEncodeGeneric"]
    Parser -. "app adapter" .-> Core
    Analysis -. "app adapter" .-> Core
    AI -. "app adapter" .-> Core

Solid arrows are compile-time imports by the app. Dotted arrows are value translation performed by RawCull, not package dependencies.

The three rsync support packages do not depend on one another. RawCull connects argument building, process execution and streamed-output parsing in its copy workflow. The runtime sequence is not a package import chain.

  1. RawParserKit — a file becomes an orientation-normalized image and neutral metadata.
  2. PhotoAnalysisKit — a decoded image becomes sharpness, saliency, focus evidence, and masks.
  3. RawCullCore — measurements become burst boundaries, recommendations, and review state.
  4. PhotoAIKit — optional CLIP similarity/semantic search and segmentation run behind typed contracts.
  5. PhotoEvidenceKit — manual regions, retained references, source-labeled crops, and optional recorded AF-point assistance.
  6. Return to the app pages to see RawCull compose those independent boundaries, persist results, and present policy.

When a package pin changes, compare its manifest and public source at the new resolved revision before updating this documentation. A sibling checkout may be ahead of the revision RawCull actually builds.

November 8 Dependency Delta

Compared with the October 31 snapshot, PhotoEvidenceKit is newly resolved at 1.0.7. EventSource moves from 1.5.1 to 1.6.0, swift-asn1 from 1.7.3 to 1.7.4, swift-collections from 1.7.3 to 1.7.5, swift-jinja from 2.5.1 to 3.0.0, swift-transformers from 1.3.5 to 1.4.0, and yyjson from 0.12.0 to 0.13.0. The eight previously direct package pins and the other transitive pins retain the revisions recorded in the October 31 table.

The Xcode project also lists PhotoEvidenceDemo, the package’s executable example, as a product reference. RawCull source imports the three library products above; the demo is not a fourth library API.

End-to-End Ownership

StepPackage outputRawCull responsibility
DecodeRawParserKit image and metadataRetain sandbox access, select preview/development policy, cache decoded work
MeasurePhotoAnalysisKit scores, evidence, masksCombine source identity with analysis descriptor and reject stale results
InferPhotoAIKit embeddings, semantic results, segmentationInstall models, admit requests, choose fallback and publish current results
RecommendRawCullCore grouping and ranking valuesSupply ordered inputs and evidence; preserve photographer decisions
InspectPhotoEvidenceKit crops and session stateSupply truthful source labels, file/settings revisions, AF mapping and region storage

PhotoEvidenceKit consumes host-rendered images through an injected renderer. It does not import the decoder, analysis, AI, or ranking packages. A close-up can help a photographer evaluate a recommendation without becoming new ranking evidence automatically. See the individual guides for invalidation and failure behavior at each boundary.

1 - One Package, Three Imports: Understanding Swift Modules

Learn how Swift packages, products, targets, modules, imports, and linking fit together using PhotoEvidenceKit as a concrete example.

One Package, Three Imports: Understanding Swift Modules

PhotoEvidenceKit is one package containing three library modules. That is why RawCull can contain these three imports:

import PhotoEvidenceContracts
import PhotoEvidenceEngine
import PhotoEvidenceUI

Each import names a module. PhotoEvidenceKit is the package name, but this package does not define a module with that name. Consequently, adding the package to Xcode does not make import PhotoEvidenceKit valid.

This guide uses the actual PhotoEvidenceKit manifest at the RawCull-resolved 1.0.7 revision. Alternative designs later in this guide are teaching examples, not changes made to that package.

1. The Names Describe Different Things

TermMeaning in this exampleWhere it appears
RepositoryThe Git repository containing the packageGitHub URL and checkout directory
PackageThe overall SwiftPM definition, named PhotoEvidenceKitPackage(name: ...) in Package.swift
ProductA library or executable offered to consumersThe manifest’s products array and Xcode’s product selection
TargetA build unit with source files, dependencies and settingsThe manifest’s targets array
ModuleThe namespace and access-control boundary compiled from a regular Swift library targetimport PhotoEvidenceContracts, for example
Source fileOne contribution to a target’s moduleSources/PhotoEvidenceContracts/CloseUpContracts.swift

In this package, each library product and its target have the same name. That makes integration convenient, but it can hide the difference between selecting a product and importing a module. SwiftPM’s Product documentation explains that a product is assembled from build artifacts of one or more targets. A product name does not itself create a new module.

Think of the package as the complete distribution, products as the choices offered to its consumer, and targets as the units that actually build the code. They do not have to share a name.

2. Read The Real Manifest From The Outside In

The beginning of the manifest declares the tools version, imports the manifest API, and creates the package description:

// swift-tools-version: 6.2
import PackageDescription

let package = Package(
    name: "PhotoEvidenceKit",
    // products, targets, platform and language settings follow
)

This is a shortened excerpt. import PackageDescription is used while evaluating the manifest. It does not become an application import or add PackageDescription to the photo-inspection runtime.

The package name identifies the whole package. It does not instruct SwiftPM to collect all source files into a PhotoEvidenceKit module.

Products: What Consumers Can Select

The actual library product declarations are:

.library(name: "PhotoEvidenceContracts", targets: ["PhotoEvidenceContracts"]),
.library(name: "PhotoEvidenceEngine", targets: ["PhotoEvidenceEngine"]),
.library(name: "PhotoEvidenceUI", targets: ["PhotoEvidenceUI"]),

Each exposes one same-named target as a library product. There is also an executable product, PhotoEvidenceDemo, for running the synthetic example. The demo is not a fourth library that a host should import to display close-ups.

Targets: What Gets Compiled And What It May Depend On

The three library targets are declared as:

.target(name: "PhotoEvidenceContracts"),
.target(name: "PhotoEvidenceEngine", dependencies: ["PhotoEvidenceContracts"]),
.target(name: "PhotoEvidenceUI", dependencies: ["PhotoEvidenceContracts", "PhotoEvidenceEngine"]),

The first target has no dependencies on another target in this package. Engine can use Contracts, while UI can use both Contracts and Engine. There are no external package dependencies in this manifest. Apple frameworks such as Foundation, CoreGraphics and SwiftUI are SDK modules used by source files, rather than downloaded Swift package dependencies.

These declarations establish the build graph. They are not an instruction to insert import statements into every source file.

3. How Folders Become Importable Modules

For these regular targets, SwiftPM uses the conventional source directories:

PhotoEvidenceKit/
├── Package.swift
├── Sources/
│   ├── PhotoEvidenceContracts/
│   │   ├── CloseUpContracts.swift
│   │   ├── CloseUpRenderSource.swift
│   │   └── CloseUpAFPoint.swift
│   ├── PhotoEvidenceEngine/
│   │   ├── CloseUpCropGeometry.swift
│   │   ├── CloseUpRasterizer.swift
│   │   └── CloseUpRendering.swift
│   └── PhotoEvidenceUI/
│       ├── CloseUpModel.swift
│       ├── CloseUpCardModel.swift
│       └── CloseUpPanel.swift
├── Examples/PhotoEvidenceDemo/
└── Tests/PhotoEvidenceKitTests/

The example executable has an explicit path in the manifest because it lives outside the default Sources/PhotoEvidenceDemo location.

All three files under Sources/PhotoEvidenceContracts contribute declarations to the same PhotoEvidenceContracts module. There is no import CloseUpContracts for the individual file. Source-file names organize the repository; the target determines the module boundary.

Similarly, a nested folder added inside a target does not automatically become another module. A separate target declaration and appropriate source layout are needed to create another regular Swift module. See SwiftPM’s Target documentation for the target’s role in compilation.

4. Follow The Build In Dependency Order

flowchart BT
    Contracts["PhotoEvidenceContracts\nframes, regions, requests, source identity"]
    Engine["PhotoEvidenceEngine\ngeometry, rasterizer, render protocol"]
    UI["PhotoEvidenceUI\nmodel, panel, card loading"]
    App["RawCull\nhost adapters and application policy"]
    Engine --> Contracts
    UI --> Contracts
    UI --> Engine
    App --> Contracts
    App --> Engine
    App --> UI

An arrow means “depends on.” Contracts can be compiled before Engine; UI needs the lower modules’ interfaces. The build system schedules work according to this graph and can reuse outputs when they remain valid.

Conceptually, the build proceeds through these stages:

  1. Resolve the package revision and evaluate its manifest.
  2. Locate source files and establish the required target dependencies.
  3. Compile each required module with its dependencies available.
  4. Produce module information for the compiler and object/library artifacts for linking, according to the build configuration.
  5. Compile the host’s source files against the modules it uses.
  6. Link the required executable code into the final application arrangement.

The exact artifact layout varies between Xcode and command-line builds. Three imports do not imply three separately downloaded packages, three runtime processes, or necessarily three dynamic frameworks. These .library declarations do not explicitly choose a static or dynamic library type.

An import is a compile-time language operation. It does not download the package, run the demo or instantiate a renderer.

5. Why Divide This Particular Package Into Three Modules?

The division follows three different responsibilities in the existing source. It makes those responsibilities enforceable through dependencies rather than relying only on folder names and developer convention.

Contracts: Agree On The Vocabulary

Contracts defines values such as CloseUpFrame, CloseUpRegion, CloseUpRequest, CloseUpRenderSource and CloseUpAFPoint, plus the CloseUpRegionStoring protocol.

For example, a frame identifies a source and its revision, while a request specifies the region and rendering source. A renderer and a view can exchange these values without either defining its own incompatible version.

This module uses Foundation and CoreGraphics, but it does not import SwiftUI or contain decoded image buffers. A client can use the region-record format without adopting the panel. “Contracts” describes a responsibility; it is not a special Swift keyword or a promise of permanent API stability.

Engine: Produce Inspection Pixels

Engine defines CloseUpRendering, CloseUpRender, crop geometry and rasterization. It imports Contracts because it needs the request and coordinate values.

A host can use CloseUpRasterizer with a custom user interface. The engine does not need to know which SwiftUI panel displays the resulting images, which photo is rated, or which RAW loader produced the source.

Notice that not every protocol is in Contracts. CloseUpRendering lives in Engine because it returns the engine’s image-bearing CloseUpRender. The division follows the actual API’s dependencies, rather than placing everything named “protocol” into the lowest module.

UI: Present And Coordinate Inspection

UI defines CloseUpPanel, CloseUpModel and its internal card model. It needs Contracts for frame/region values and Engine for rendering requests and results. It adds SwiftUI and Observation behavior on top of those lower layers.

This direction prevents a change in presentation from requiring the engine to import a view. If Contracts tried to depend on UI while UI already depended on Contracts, that would create a cycle. Shared low-level values must stay in a layer both higher-level components can depend on.

The split also creates access-control boundaries. For example, the actual CloseUpPanel and CloseUpModel are public, while CloseUpCardModel is internal to PhotoEvidenceUI. Moving everything into one module would remove those particular cross-module boundaries. Other access levels still apply within it.

6. Why Does A RawCull File Need All Three Imports?

Look at RawCull’s BurstCloseUpsView.swift. It performs several jobs at once:

Code used by the adapterDefining moduleImport
Frame, request and render-source valuesContractsimport PhotoEvidenceContracts
Rendering protocol, result and rasterizerEngineimport PhotoEvidenceEngine
Panel and session modelUIimport PhotoEvidenceUI

A file that merely handles saved-region values may need only Contracts. A custom renderer may need Contracts and Engine. The composition file uses declarations from all three, so it explicitly imports all three.

Imports apply to the source file containing them. Adding an import to another RawCull file does not provide that import to every file in the app target. Declarations in the app’s own module are a different matter: app files can refer to that module’s accessible declarations without importing each other by filename.

The dependency graph and source imports serve different purposes:

  • Target/product dependencies make required modules available to the build.
  • Source imports state which modules a particular file uses.
  • Access control determines which declarations that file may use across the module boundary.

An ordinary import PhotoEvidenceUI is not a designed umbrella export of all Contracts and Engine names. Do not rely on incidental transitive visibility. Import the modules that define the APIs your file directly uses. The current package provides no explicit PhotoEvidenceKit facade module.

7. Selecting Products In Xcode Or SwiftPM

In Xcode, adding the repository makes its products available for assignment to application targets. Select the library products the app directly consumes. Selecting UI also brings the lower target dependencies required to build UI; you do not separately download Contracts and Engine repositories.

For a Swift package consumer, the same distinction is explicit in its manifest. The following is an illustrative consumer configuration:

// In the consumer Package.swift, within Package(...):
dependencies: [
    .package(url: "https://github.com/rsyncOSX/PhotoEvidenceKit.git", from: "1.0.7")
],
targets: [
    .target(
        name: "MyInspectionFeature",
        dependencies: [
            .product(name: "PhotoEvidenceContracts", package: "PhotoEvidenceKit"),
            .product(name: "PhotoEvidenceEngine", package: "PhotoEvidenceKit"),
            .product(name: "PhotoEvidenceUI", package: "PhotoEvidenceKit")
        ]
    )
]

This excerpt belongs inside a complete manifest, not in a runtime Swift file. The package requirement permits compatible versions starting at 1.0.7; it is not an exact revision pin. The consumer’s resolution records the chosen revision. SwiftPM’s dependency guide describes package requirements and product dependencies separately.

Once configured, that consumer’s source files import the modules they use. Adding a product dependency alone does not create an import in their source text.

8. Why Not Offer Only import PhotoEvidenceKit?

It is possible. There are several designs, with different consequences.

Design A: Put Everything In One Target

The package could define one library product and one target, both named PhotoEvidenceKit, and move the three source groups into that target. Consumers would then use import PhotoEvidenceKit.

This reduces integration choices and can suit a small, cohesive library. However, Contracts, Engine and UI would share a module. A contracts-only consumer would consume that combined module, and the compiler would no longer enforce the current separation between those three internal layers.

Design B: Rename Only The Product

Suppose a maintainer instead changes the product declaration to:

.library(
    name: "PhotoEvidenceKit",
    targets: ["PhotoEvidenceContracts", "PhotoEvidenceEngine", "PhotoEvidenceUI"]
)

That offers one product containing multiple targets. It still does not create a PhotoEvidenceKit module. The module names remain the target names, so a single product selection alone does not deliver the desired single import.

Design C: Add A Facade Target

A fourth library target named PhotoEvidenceKit could depend on the three existing targets and expose a deliberate convenience API. Consumers of that facade could write import PhotoEvidenceKit, while advanced consumers could keep using the smaller modules.

The facade must actually provide the intended public API through wrappers, forwarding functions, public aliases or a consciously chosen export mechanism. An empty target that merely imports three dependencies does not automatically create a supported umbrella API for all their declarations. Export mechanisms also need language/toolchain review; underscored compiler features should not be presented as an ordinary stable-language recommendation.

The benefit is convenience. The cost is another API surface to design, document, test and maintain. A convenience name does not remove the underlying dependency graph or make all three lower layers independently unnecessary.

9. What This Design Buys, And What It Costs

AspectThree-module PhotoEvidenceKit design
ReuseContracts and Engine can be consumed without the SwiftUI panel
Dependency directionThe build graph enforces lower layers’ independence from UI
API boundariesCross-module use requires suitable access control
IntegrationConsumers choose products and write explicit module imports
MaintenanceMore target configuration and public boundary design
Build performanceDependencies can be reused independently, but module count alone guarantees no speedup
VersioningAll targets ship under the same package revision; three modules do not mean independent release versions

For PhotoEvidenceKit, the source demonstrates a useful boundary: describe an inspection, render it, then present it. Those steps can be reused separately. The decision is an architectural tradeoff, not a rule that every Swift package should have three modules.

10. Diagnose Import Problems By Checking The Correct Layer

SymptomCheck
No such module 'PhotoEvidenceKit'The package currently has no module with that name; use the actual module names
No such module 'PhotoEvidenceEngine'Product/target dependency, resolution, platform/toolchain requirements and successful dependency build
A type is unavailable in one fileThat file’s imports, the spelling of the type, its defining module and access level
Adding a folder did not create a new importA folder inside a target is not a new target/module
Linking fails after compilationRequired linked products/artifacts and target configuration; imports alone do not supply executable code

Start with the manifest, then identify the target owning the declaration, then inspect the consuming file’s imports. This follows the same structure the build system uses and avoids confusing a repository name with a module name.

Source Map

TopicPhotoEvidenceKit source
Package, products and targetsPackage.swift
Shared request and region valuesSources/PhotoEvidenceContracts/CloseUpContracts.swift
Engine imports and rendering boundarySources/PhotoEvidenceEngine/CloseUpRendering.swift
UI imports and public panelSources/PhotoEvidenceUI/CloseUpPanel.swift
Internal UI implementationSources/PhotoEvidenceUI/CloseUpCardModel.swift

Continue with How PhotoEvidenceKit Is Constructed for the detailed runtime contracts and RawCull integration, or return to the package catalog.

2 - How PhotoAIKit Is Constructed

A detailed guide to PhotoAIKit’s contracts, CLIP image and text inference, semantic comparison, SAM 3 and EfficientSAM, workflows, storage, concurrency, and model identity.

How PhotoAIKit Is Constructed

Revision scope: Updated against the RawCull dependency pin 4b85056e6c2603b5e382987710ca2f16f4c5c155 on 16 October 2026. The original walkthrough used 20e57359603313af7c2d38cae3e8b6e37f8838ef. Current application policy is described in AI Models in RawCull and AI Runtime.

PhotoAIKit is a reusable Swift package extracted from application code. Its most important achievement is not merely that CLIP, SAM 3, and EfficientSAM run. It is that reusable AI behavior has been separated from RawCull’s UI, RAW-file handling, paths, sandbox rules, and culling policy.

This document explains the construction from the bottom up and gives the reason for each boundary.

Build 466 integration

RawCull resolves PhotoAIKit 3.1.0. Its Vision feature-print backend accepts a VisionWorkSerializing instance and defaults to SerialVisionWorkQueue.shared in standalone clients. RawCull supplies an adapter to PhotoAnalysisKit’s Vision gate. This lets feature prints and measurement requests share a queue without adding a dependency between the packages. Review obtains SAM 3 instance segmentation and optional CLIP relevance through its live backend. The detailed walkthrough below describes the earlier audited revision. VisionWorkSerializing · CombinedReviewLiveBackend

For Full Review, CoreAIQwenProvider validates the host-supplied bundle URL and creates the local vision-language model. RawCull builds the instructions, then supplies the text and image attachment through LanguageModelSession. The Full Review execution chapter traces that handoff and the SAM 3 and CLIP request paths against the resolved package.

1. Begin With The Package Boundary

The package owns:

  • typed, Sendable contracts;
  • model-bundle validation and fingerprinted model identity;
  • Core AI CLIP image and text inference plus SAM 3 and EfficientSAM inference;
  • validated image/text semantic comparison;
  • Apple Vision feature-print generation and comparison;
  • bounded similarity indexing and explicit fallback;
  • segmentation, mask selection, geometry, and catalog workflows;
  • optional artifact codecs and mask stores.

The host application owns:

  • model download, installation, candidate URLs, and sandbox bookmarks;
  • RAW decoding and application image models;
  • SwiftUI, Observation state, and display wording;
  • app-specific task staleness such as “latest selection wins”;
  • query admission, result ordering, filtering, and semantic-search presentation;
  • culling, burst ranking, sharpness, saliency, and rating policy;
  • helper-process launch and application restart behavior.

This boundary makes PhotoAIKit reusable. A package that imports FileItem or searches Bundle.main for a RawCull resource might be convenient for one app, but it would silently encode application policy into the AI layer.

2. Read Package.swift As An Architecture Diagram

PhotoAIKit/Package.swift declares Swift tools 6.4, macOS 27, Swift 6 language mode, eight library products and one test target. CoreAIQwenBackend is the eighth library product. The inspected manifest requires apple/coreai-models exactly at 1.0.0; RawCull resolves it to 5de95c6cd29e5e390fb36d87e13b2396668f7974; it declares huggingface/swift-transformers from 1.3.3 and the October app resolved 1.3.5. Build 466 resolves swift-transformers 1.4.0.

flowchart TD
    Contracts["PhotoAIContracts\nvalues + protocols"]
    CLIP["CoreAICLIPBackend"] --> Contracts
    Efficient["CoreAIEfficientSAMBackend"] --> Contracts
    SAM3["CoreAISAM3Backend"] --> Contracts
    Vision["VisionFeaturePrintBackend"] --> Contracts
    Qwen["CoreAIQwenBackend"] --> Contracts
    CoreLM["coreai-models CoreAILM"] --> Qwen
    Workflows["PhotoAIWorkflows"] --> Contracts
    Storage["PhotoAIStorage"] --> Contracts
    CoreAI["apple/coreai-models\nCoreAISegmentation product"] --> CLIP
    CoreAI --> Efficient
    CoreAI --> SAM3
    Transformers["swift-transformers\nTokenizers product"] --> CLIP
    Tests["PhotoAIKitTests"] --> Contracts
    Tests --> CLIP
    Tests --> Efficient
    Tests --> SAM3
    Tests --> Vision
    Tests --> Workflows
    Tests --> Storage

There is intentionally no large umbrella target in which every feature can reach every implementation. Each higher-level product depends on PhotoAIContracts, but the backends, workflows, and storage products do not depend on one another.

Why this shape helps:

  • A host can import only the products it uses.
  • Workflow code is testable with fake providers and decoders.
  • Storage does not need to know which inference backend produced a value.
  • A backend cannot accidentally reach into RawCull or into another backend.
  • Framework-heavy dependencies remain concentrated in concrete backend targets.

3. PhotoAIContracts: The Stable Center

Contracts are the innermost layer. They contain data and protocol definitions, not application decisions.

3.1 Translate Host Photos Into AIImageSource

Sources/PhotoAIContracts/AIImageSource.swift defines the package-owned source value:

public struct AIImageSource: Codable, Hashable, Identifiable, Sendable {
    public let id: UUID
    public let url: URL
    public let displayName: String
}

RawCull maps FileItem into this type at its integration boundary. PhotoAIKit therefore receives only what a reusable indexing or segmentation workflow needs. It never learns ratings, focus data, camera metadata, or view state.

SourceFileIdentity reads size and modification date. SourceFingerprint adds the standardized path. These values let persisted artifacts answer a crucial cache question: “Was this result produced for the current contents of this source file?”

3.2 Invert Image Decoding

PhotoAIKit declares:

public protocol ImageDecoding: Sendable {
    func image(for source: AIImageSource) async throws -> CGImage
}

The package needs a CGImage, but it should not prescribe how one is obtained. A JPEG host can use ImageIO; RawCull can try RawParserKit first; tests can return a generated image. The workflow depends on the capability, not on a camera-format implementation.

This is the dependency-inversion principle in a small, concrete form:

flowchart LR
    Workflow["PhotoAIKit indexer"] --> Protocol["ImageDecoding protocol"]
    Raw["RawCull RAW decoder"] -. conforms .-> Protocol
    Test["Test decoder"] -. conforms .-> Protocol

3.3 Separate Generation From Comparison

Sources/PhotoAIContracts/SimilarityArtifact.swift defines two protocols:

  • ImageSimilarityArtifactProviding creates an artifact from a CGImage and source.
  • ImageSimilarityArtifactComparing computes the distance between two compatible artifacts.

The combined ImageSimilarityBackend type alias requires both.

The split matters because generation can be actor-isolated and expensive, while comparison may be synchronous and nonisolated. It also keeps distance semantics with the backend that understands its payload. RawCull does not decode a VNFeaturePrintObservation, nor does it implement CLIP cosine distance from unverified arbitrary data.

3.4 Keep Text Queries Query-Scoped

Sources/PhotoAIContracts/TextEmbedding.swift defines a second, deliberately different similarity value. TextEmbedding contains a normalized text vector and a TextEmbeddingDescriptor with the complete backend identity, dimensions, tokenizer version, and schema version.

Text embeddings are not file-backed SimilarityArtifact values. They have no source fingerprint and are intended to live for one query. The split public protocols mirror the image API:

  • TextEmbeddingProviding tokenizes and encodes a query.
  • ImageTextSimilarityComparing compares a compatible image artifact with the text embedding.
  • ImageTextSimilarityBackend combines both capabilities.

The comparison returns cosine similarity in -1...1, where a larger value is a closer semantic match. It is a relative retrieval score, not a confidence or a keep/reject decision.

3.5 Make Persisted Artifacts Self-Describing

A SimilarityArtifact has two fields:

SimilarityArtifact
├── descriptor
│   ├── backend
│   ├── model fingerprint
│   ├── dimensions
│   ├── representation
│   ├── preprocessing version
│   ├── normalization version
│   ├── configuration version
│   ├── source fingerprint
│   └── schema version
└── payload (backend-owned Data)

This looks more elaborate than storing [Float], but it prevents subtle cache bugs. A vector is not reusable merely because its dimension matches. Reuse is valid only if the source, model asset, preprocessing, normalization, configuration, representation, and schema are still the same.

SimilarityArtifactDescriptor.isCompatibleForDistance(with:) intentionally compares every backend/configuration field but excludes the source fingerprint. Two different photos must have different source fingerprints, yet their artifacts can still be compared when they were produced by the same backend definition.

3.6 Treat Model Identity As Data

The model types are spread across:

ModelIdentity.cacheIdentifier preserves compatibility with older cache naming. artifactIdentifier adds the selected asset fingerprint for new artifacts. This distinction allows migration without pretending that two different model binaries are the same model.

ModelResourceDescriptor.clip and .sam3 describe package-neutral requirements and version strings. ModelCapabilityStatus reports available, missing, or invalid without user-facing wording. The host translates that status into its own settings UI.

4. Model Bundles Are Supplied, Not Discovered

PhotoAIKit never chooses an application directory. The host supplies one URL or an ordered list of candidates.

A valid bundle has this conceptual layout:

ModelBundle/
├── metadata.json
├── tokenizer/
│   └── tokenizer.json
└── selected-model.aimodel  (or .aimodelc)

metadata.json names the selected model in assets.main. New exports can also provide asset_fingerprints.main.

ModelBundleResolver validates, in order:

  1. the URL exists and is a directory;
  2. metadata.json decodes;
  3. assets.main is present and non-empty;
  4. the asset extension is accepted;
  5. the selected asset exists;
  6. required resources such as tokenizer/tokenizer.json exist;
  7. the model asset can be fingerprinted;
  8. a manifest checksum, when present, matches the actual asset.

For a file asset, the cryptographic algorithm is SHA-256. For a compiled model directory, PhotoAIKit hashes a stable sorted tree representation. Older manifests without a checksum receive a size/modification-time fallback fingerprint. That fallback can detect replacement in place but is marked as not cryptographically verified.

ModelProviderFactory<Provider> connects validation to a backend constructor. A backend supplies “how to make me from a validated URL”; the host supplies “which URLs should be considered, and in what order.”

Candidate order is policy, not just presentation. ModelResourceResolver skips a candidate that is missing, but returns immediately when it finds an invalid candidate. This prevents a damaged higher-priority installation from being silently hidden by a lower-priority fallback.

CLIP has a second validation layer after generic bundle resolution. CLIPRuntimeConfiguration reads the model contract from metadata: source model and revision, architecture, pretrained checkpoint, embedding dimensions, preprocessing dimensions and normalization, tokenizer context and padding, named image/text functions, normalization version, and configuration version. Current bundles use shortest-side resize, a centered square crop, and bicubic interpolation. Older PhotoAIKit bundles remain compatible through the original 224-pixel stretch and bilinear defaults.

This separation prevents a library update from unexpectedly changing an application’s installation or sandbox policy.

5. Concrete Backend Products

5.1 CoreAICLIPBackend

CoreAICLIPProvider is an actor conforming to image embedding, artifact generation/comparison, text embedding, and image/text comparison protocols.

Its responsibilities are deliberately backend-specific:

  • validate the supplied CLIP bundle;
  • lazily load and cache the named image and text Core AI functions;
  • validate tensor names, shapes, scalar types, dimensions, and metadata;
  • create the image, token, and attention-mask NDArrays;
  • apply the model-declared resize/crop policy in sRGB and CLIP channel normalization;
  • L2-normalize image vectors through ImageEmbedding;
  • validate that the exported graph’s text vector is finite, non-empty, correctly shaped, and already L2-normalized;
  • encode the vector as an artifact payload;
  • compute cosine distance only after descriptor and payload validation.

The actor owns loadedModel, so lazy initialization is isolated from concurrent callers.

For a semantic query, the same provider creates a TextEmbedding and similarity(image:text:) rejects every incompatible model, representation, dimension, preprocessing, normalization, configuration, tokenizer, schema, or payload before computing a dot product. Vision artifacts are rejected because they are not in CLIP’s image/text embedding space.

RawCull’s RawCullCLIPSemanticSearchService keeps the product policy outside the backend: it trims and admits a literal query, selects already-persisted compatible image artifacts, isolates per-file failures, reports progress, and orders equal scores deterministically. It never decodes an image or persists a query embedding.

5.2 CoreAIEfficientSAMBackend

CoreAIEfficientSAMProvider is an actor conforming to SubjectSegmenting. It validates the EfficientSAM bundle, lazily owns ImageSegmenter, uses the model’s empty point query (center point or regular grid depending on the export), selects the highest-scoring mask, and adapts it to the same SubjectSegmentationResult contract used by SAM 3. The pinned provider uses a 0.5 mask threshold and at most one segment.

5.3 CoreAISAM3Backend

CoreAISAM3Provider conforms to SubjectSegmenting. It owns tokenizer setup, lazy model loading, request inference, query selection, confidence conversion, mask decoding, resizing, thresholding, feathering, timing, and diagnostics.

The provider creates CoreAIClipTokenizer and asks Core AI for up to five segments. Postprocessing prefers the exhaustive semantic probability map when the exporter supplies one. Otherwise it unions every returned instance mask, rather than selecting only the highest-scoring instance. The resulting SubjectSegmentationResult therefore represents all subjects matching the prompt. SAM3MultiSubjectTests protects both the semantic-map and instance-union paths.

The public contract speaks in SubjectSegmentationRequest and SubjectSegmentationResult, not Core AI tensors. This lets workflows and hosts work at the domain level while the backend handles framework details.

5.4 VisionFeaturePrintBackend

This actor uses VNGenerateImageFeaturePrintRequest. The produced VNFeaturePrintObservation is securely archived into an opaque artifact payload.

Comparison returns to this backend, which unarchives the observations and calls Vision’s native computeDistance. The observation never becomes part of RawCull’s persistence API. This is an example of information hiding: callers can store and route the artifact without learning its private representation.

6. PhotoAIWorkflows: Reusable Orchestration

Backends operate on one image or request. Workflows coordinate many sources and reusable policies.

6.1 Similarity Indexing

EmbeddingIndexer is the vector-specific API. SimilarityArtifactIndexer is the more general API used when the fallback might have an opaque representation such as a Vision feature print.

Both indexers accept:

  • package-owned sources;
  • an injected decoder;
  • a primary provider;
  • an optional fallback provider;
  • an explicit fallback policy;
  • a concurrency limit;
  • an async progress callback.

They use a throwing task group but enqueue only concurrencyLimit children. Each time one finishes, one new source is added. This is bounded concurrency: a catalog with 20,000 files does not create 20,000 live tasks and decoded images.

The fallback policies are:

PolicyBehaviorAppropriate when
.noneKeep primary successes and failuresThere is no compatible fallback
.perItemRetry only a failed itemPrimary and fallback results can safely coexist
.wholeBatchIf any primary item fails, rerun every requested source through fallbackA batch must use one comparable representation

The indexer does not decide which policy is correct for a host. RawCull’s current CLIP service selects .none: it keeps successful CLIP artifacts and reports per-file failures. RawCull selects Vision before indexing when CLIP is disabled or no validated provider exists. The generic .wholeBatch mechanism remains available to other hosts, but is not the current RawCull CLIP path.

6.2 Segmentation Workflows

The SAM 3 side is split into focused units:

TypeResponsibility
SegmentationServiceResize/preprocess coordination, cache lookup, inference, persistence, partitioning, and prefetch
SegmentationBatchPipelineBatch generation, progress events, summary, and versioned JSON-lines transport
SubjectMaskRepositoryCache-only access using explicit prompt/model/size configuration
SubjectMaskSelectorOrdered prompt fallback, quality/confidence thresholds, and best-mask selection
SubjectMaskCatalogIndexIncremental cache inventory without invoking inference
SubjectMaskGeometryAlpha coverage, bounds, centroid, and freshness
SubjectMaskQualityReusable geometry-based quality classification

The package can decide which mask best satisfies a general selection strategy. RawCull still decides which photo is a culling candidate or winner. Reusable mask quality is not the same concern as product ranking policy.

7. PhotoAIStorage: Optional Persistence Mechanics

Storage depends only on contracts.

For similarity data:

  • SimilarityArtifactCodec wraps an artifact in a versioned envelope.
  • EmbeddingCodec writes descriptor-complete CLIP artifacts.
  • decodeMigrating reads current data and two version-1 formats, but legacy values are accepted only against the real current model identity and are marked for immediate rewrite.
  • LegacyCLIPEmbeddingCodec remains a staged migration reader; its identity-incomplete writer is deprecated.

For segmentation:

  • SubjectMaskMemoryStore is an injected actor-backed dictionary.
  • SubjectMaskDiskStore stores PNG mask data plus JSON metadata, validates the storage key, reports disk usage, supports pruning, and rejects stale or corrupt entries.

The host injects the disk directory. PhotoAIKit owns how the record is encoded and validated, while the application owns where records live and when they are removed.

8. Concurrency And Isolation

PhotoAIKit targets Swift 6 and makes boundary values Sendable.

The main patterns are:

  • Actors for mutable runtime state: providers lazily cache loaded models; services and stores protect mutable state.
  • Value types for transport: sources, identities, descriptors, progress, failures, and configuration values cross tasks safely.
  • Bounded task groups: indexers and prefetch workflows limit simultaneous work.
  • Cooperative cancellation: workflow boundaries and expensive stages call Task.checkCancellation().
  • Async progress callbacks: the package reports neutral progress values; a host decides how and where to publish UI state.

Actor isolation does not remove the need for a host policy. RawCull still owns generation tokens and catalog checks that prevent an older task from replacing results for a newer selection.

9. RawCull integration at the October audit

RawCull imports the package products and assembles concrete providers in RawCullAIModelRuntime. RawCullApplicationState binds those providers to stable features owned by RawCullIntelligenceRuntime:

Package contract or implementationRawCull adapter/consumerPolicy that remains in RawCull
CoreAICLIPProvider, ImageSimilarityArtifactProviding, and ImageSimilarityArtifactComparingRawCullCLIPSimilarityService, SimilarityScoringModel, and RawCullSimilarityFeaturemanaged model locations, selected CLIP model, RAW decoding, concurrency 1, retry/replacement recovery, per-file persistence, burst thresholds, and subject-mismatch adjustment
VisionFeaturePrintBackendRawCullVisionSimilarityServicealways-available startup service, concurrency 4, service selection, cache admission, and UI state
TextEmbeddingProviding and ImageTextSimilarityComparingRawCullCLIPSemanticSearchService and RawCullSemanticSearchFeaturequery admission, progress, catalog/rating filters, deterministic ties, result count, selection/navigation binding, and ephemeral query lifetime
SubjectSegmenting, SegmentationService, mask stores, repository, and selectorRawCullAIModelRuntime, DeepAIReviewFeature, and DeepAIReviewControllerSAM 3 versus EfficientSAM selection, application-support paths, saved-evidence status, candidate admission, review presentation, group-signature validation, and culling decisions

The package owns validation, descriptors, backend actors, mathematical comparison, bounded generic workflows, and reusable codecs/stores. The app owns filesystem/security scope, camera decoding, settings, capability wording, generation tokens, catalog identity, cache policy, culling rules, and UI. In particular, PhotoAIKit does not know FileItem, a burst winner, or where RawCull installs a model. RawCullIntelligenceRuntime owns stable feature lifetimes and applies revisioned configuration; views consume the focused features and controller rather than low-level package providers.

10. Testing The Architecture, Not Only The Math

Most of Tests/PhotoAIKitTests/ exercises the products through public APIs. The CLIP text suite also uses @testable import for deterministic tokenizer, batch, tensor-shape, and preprocessing checks that sit below the provider boundary. Together the tests cover architectural promises such as:

  • model bundles are accepted through supplied URLs;
  • manifest fingerprints become artifact identity;
  • provider factories and resource resolvers share validation;
  • CLIP normalization and cosine distance remain stable;
  • model-declared CLIP preprocessing and legacy preprocessing remain compatible;
  • token batches, attention masks, text-output validation, and image/text compatibility checks reject malformed or mismatched data;
  • the generic whole-batch fallback policy produces a homogeneous result set (RawCull currently uses .none for CLIP);
  • Vision artifacts stay opaque and use the native metric;
  • segmentation caches by package-owned source values;
  • disk stores reject stale or corrupt entries;
  • legacy data is a rewrite candidate, not silently current data;
  • batch transport has an explicit versioned schema;
  • cancellation crosses the service boundary.
  • SAM 3 preserves all matching subjects through its semantic-map or union fallback.

Fake decoders, providers, and stores make these tests possible. That testability is a direct consequence of putting protocols in the innermost target.

11. Developer Tools And Model Assets

The package includes tools under Tools/ for exporting CLIP and SAM 3 assets, selecting a SAM 3 asset, generating fingerprints, and producing reference CLIP image/text similarities. Output paths are explicit.

export_clip.py supports the existing OpenAI clip-vit-base-patch32 model and OpenCLIP ViT-B-32-256 with datacomp_s34b_b86k weights. It writes the image and text encoders as named functions in one Core AI asset, verifies tokenizer parity for the OpenCLIP export, and records the runtime metadata consumed by CLIPRuntimeConfiguration.

The Swift package itself declares no model resources. It does not embed .aimodel, .aimodelc, tokenizer, or metadata assets. Model binaries are large deployment inputs with their own lifecycle; keeping them out of the library avoids coupling package source, application installation, and model distribution.

12. How To Add Another Similarity Backend

Use the existing layering as a checklist:

  1. Add or reuse package-neutral contract values in PhotoAIContracts; do not add host types.
  2. Create a separate backend target that depends on contracts.
  3. Conform to artifact providing and comparing protocols.
  4. Give the backend a complete SimilarityBackendDescriptor.
  5. Put framework-specific payload encoding and distance semantics inside that backend.
  6. If the backend supports text, add a query-scoped descriptor and keep image/text compatibility checks with that backend.
  7. Reuse SimilarityArtifactIndexer and inject the host’s decoder.
  8. Decide explicitly whether fallback is none, per-item, or whole-batch.
  9. Add public-API tests with fake sources and model-free inputs where possible.
  10. Let the host choose model URLs, cache locations, settings, and product policy.

If a proposed type needs SwiftUI, FileItem, a RawCull path, or a burst rating, it probably belongs in RawCull’s adapter layer instead.

Source Map

TopicPhotoAIKit source
Products and dependency graphPackage.swift
Host-neutral image and decoder boundarySources/PhotoAIContracts/AIImageSource.swift, ImageEmbedding.swift
Model validation and identitySources/PhotoAIContracts/ModelBundleResolver.swift, ModelResource.swift, ModelIdentity.swift, ModelAssetFingerprint.swift
Similarity descriptors and protocolsSources/PhotoAIContracts/SimilarityArtifact.swift
Text embeddings and image/text comparisonSources/PhotoAIContracts/TextEmbedding.swift
Segmentation contractsSources/PhotoAIContracts/SubjectSegmentation.swift, SubjectMaskStorage.swift
CLIP runtime and backendSources/CoreAICLIPBackend/CLIPRuntimeConfiguration.swift, CoreAICLIPProvider.swift
EfficientSAM backendSources/CoreAIEfficientSAMBackend/CoreAIEfficientSAMProvider.swift
SAM 3 backendSources/CoreAISAM3Backend/CoreAISAM3Provider.swift
Vision backendSources/VisionFeaturePrintBackend/VisionFeaturePrintBackend.swift
Similarity orchestrationSources/PhotoAIWorkflows/EmbeddingIndexer.swift, SimilarityArtifactIndexer.swift
Segmentation orchestrationSources/PhotoAIWorkflows/SegmentationService.swift, SegmentationBatchPipeline.swift, SubjectMask*.swift
Codecs and storesSources/PhotoAIStorage/
Package boundary auditDocumentation/ExtractionMap.md
Public behavior testsTests/PhotoAIKitTests/
RawCull semantic-search policyRawCull/Intelligence/SemanticSearch/RawCullSemanticSearchService.swift, RawCull/Intelligence/SemanticSearch/RawCullSemanticSearchFeature.swift, RawCull/Intelligence/Similarity/SimilarityScoringModel.swift

Next, follow these abstractions into the host application in How RawCull Enables and Uses CLIP.

Historical October 13 package additions and application boundaries

CoreAIQwenBackend validates and configures a local Qwen provider and constructs the model used by the host’s inference runtime. RawCull owns session creation, request caps, criteria, retries and photo/object schemas. A package backend can be correct while an application’s generated response fails its stricter contract.

Objects crosses the package boundary through SegmentationConcept, instance segmentation results and object-mask storage contracts. ObjectSegmentationService coordinates providers/stores; RawCull chooses concept mode, deduplicates retained instances, renders a numbered board and validates Qwen’s descriptions. Subject mask stores for Deep Review and object-mask stores are separate concerns.

The CLIP provider’s descriptor includes model, representation, preprocessing, normalization and configuration versions. In the inspected implementation, center-crop bicubic preprocessing includes a Pillow-compatible implementation version in the effective descriptor. Two embeddings with the same vector length but different preprocessing identities are not automatically compatible.

Reusable geometry and mask contracts can carry source-normalized registration, foreground and scorer semantics. The host must preserve those identities when cropping, measuring, displaying and persisting evidence. A SAM producer box alone is not a substitute for decoding foreground against the declared source raster. Combined’s ReviewMaskRegistration performs that application-owned registration.

Study the layers in order: package values/protocols, backend actors, package workflows/stores, application feature, SwiftUI presentation. Do not place Qwen photo prompt policy into CLIP or segmentation contracts merely because all three use a CGImage. Their outputs and acceptance conditions differ.

Host semantic-state ownership

The semantic-state extraction kept the package pin used at that time. RawCull’s RawCullSemanticSearchModel owns cached evidence, capability, hydration and query presentation, retained behind SimilarityScoringModel’s existing API. The package still owns encoding and comparison of compatible embeddings; this host extraction does not alter its models, artifact compatibility or ranking algorithms.

November 8 Integration Review: Identity Across Workflows

The November 8 application resolved PhotoAIKit 1.0.0 at 4b85056e6c2603b5e382987710ca2f16f4c5c155. The newer transitive versions in the package snapshot do not imply a new PhotoAIKit API revision. Review backend behavior against the resolved source when changing the lockfile; a sibling development checkout can contain later code.

Treat an AI artifact’s identity as more than its file URL. Backend, model asset fingerprint, preprocessing/configuration and representation dimensions establish whether two artifacts can be compared. Source identity determines whether an artifact still belongs to the current photo. Equal vector length alone is not proof that representations share an embedding space.

ChangeHost integration consequence
Replace a model assetResolve its identity again and invalidate artifacts that no longer match
Switch CLIP/Vision backendRebuild or retrieve compatible artifacts and use that backend’s comparator
Change source pixels or preprocessingRevise the corresponding source/configuration identity
Change the active query or selectionSuppress publication from the previous host request generation
Open a manual close-upRender inspection pixels through the host; do not treat the crop as an AI result

Cancellation and artifact validation solve different problems: a cancelled task can finish native work late, while an incompatible persisted artifact can arrive from a perfectly current task. Keep both request-generation checks and descriptor validation at publication boundaries.

Relationship To PhotoEvidenceKit

PhotoEvidenceKit provides manual inspection, including pinned references and independently positioned regions. It neither runs PhotoAIKit providers nor converts segmentation masks into selected subjects. If a host later offers an AI-assisted region action, the host must explicitly translate coordinates, identify the source revision and distinguish that action from a photographer’s existing manual region.

Model-download errors, incompatible artifacts, and unavailable inference should remain observable in the AI workflow. They do not prevent a host from offering manual close-ups when a renderable image is available. Conversely, a close-up render failure says nothing about whether an existing embedding is valid.

3 - How PhotoAnalysisKit Is Constructed

A detailed guide to PhotoAnalysisKit’s image-analysis boundary, sharpness pipeline, focus evidence, masks, calibration, batching, feature prints, resources, and concurrency.

How PhotoAnalysisKit Is Constructed

Revision audited: The formula walkthrough uses PhotoAnalysisKit 1.3.1 at 2a1466e04d821fa2628d6985296643e0d0c7e465. The facade, descriptors, presets, batch behavior, calibration, evidence, and mask APIs below describe that revision.

PhotoAnalysisKit is the reusable measurement layer extracted from RawCull. It turns a decoded CGImage plus neutral capture metadata into sharpness, saliency, focus evidence, and an optional focus-mask image. It can also create opaque Apple Vision feature prints.

The package measures a photo; it does not decide whether to keep it. That distinction prevents image-processing code from becoming coupled to RawCull’s files, settings, views, caches, or culling policy.

Build 466 integration

RawCull resolves PhotoAnalysisKit 1.4.1. Version 1.4.0 moved blocking saliency, classification, face, animal and feature-print requests onto the shared Vision gate. Version 1.4.1 also shares a lazily initialized Core Image context across focus engine instances. Treat queue admission and render reuse separately when investigating latency. The real-catalog comparison in the performance guide evaluated the gate change. VisionRequestGate · FocusMaskEngine · Performance measurements

1. Begin With The Package Boundary

PhotoAnalysisKit owns:

  • sRGB normalization for predictable analysis input;
  • Core Image and Metal Laplacian processing;
  • Vision saliency and optional subject classification;
  • scalar sharpness metrics and failure classification;
  • AF-point, subject, local-patch, and global focus evidence;
  • focus-mask selection and rendering;
  • numeric configuration, presets, quality levels, and analysis identity;
  • bounded batch analysis and calibration;
  • Vision feature-print generation and native comparison.

The host application owns:

  • RAW, JPEG, or other source decoding;
  • file URLs, security-scoped access, and sandbox bookmarks;
  • source identity, cache keys, cache directories, and persistence;
  • observable task state, progress presentation, and cancellation policy;
  • settings labels and saved-settings migration;
  • sorting, ratings, burst decisions, and culling actions.

The input boundary is intentionally small:

flowchart LR
    Source["RAW or rendered source"] --> Decoder["Host decoder"]
    Decoder --> Input["PhotoAnalysisInput\nCGImage + ISO + aperture + AF point"]
    Input --> Analyzer["PhotoAnalyzer"]
    Analyzer --> Result["PhotoAnalysisResult\nsaliency + breakdown + optional mask"]
    Result --> Host["Host cache, UI, and culling policy"]

PhotoAnalysisKit does not import RawParserKit or RawCullCore. RawCull provides the adapters between them.

2. Read Package.swift As The First Design Document

The manifest declares Swift tools 6.2, Swift 6 language mode, macOS 26, one library product, and one test target.

PhotoAnalysisKit package
├── PhotoAnalysisKit library
│   ├── public contracts and facade
│   ├── Core Image, Vision, and Accelerate implementation
│   └── packaged default.metallib
└── PhotoAnalysisKitTests

There are no third-party package dependencies. The implementation uses Apple frameworks including Core Graphics, Core Image, Vision, Accelerate, and Foundation.

The target enables InferIsolatedConformances and NonisolatedNonsendingByDefault. The package is therefore built under the same strict Swift 6 concurrency assumptions as the host without adopting UI isolation.

3. PhotoAnalysisInput Is The Decoding Boundary

Sources/PhotoAnalysisKit/PhotoAnalysisInput.swift defines the package’s source value:

public struct PhotoAnalysisInput: Sendable {
    public let image: CGImage
    public let iso: Int
    public let aperture: Double?
    public let normalizedAFPoint: CGPoint?
}

The AF point uses normalized 0...1 coordinates with the origin at the visual top-left. This matches the camera metadata shape used by RawCull. Vision uses a bottom-left coordinate system, so the package performs the vertical conversion internally.

ISO is clamped to at least 1. Aperture and AF point are optional because not every image or camera provides them. The package can still compute a global result when either is absent.

This value has no URL or file identifier. Two consequences follow:

  1. The package cannot reopen a source behind the host’s back.
  2. The host must associate returned results with the correct file and invalidate them when that file or decode policy changes.

RawCull makes that ownership concrete in RawCullPhotoAnalysisAdapter. The adapter chooses an embedded-preview decode through RawParserKit or a host-owned RAW demosaic, bounds the requested pixel size, and then constructs PhotoAnalysisInput. It also translates the returned neutral saliency value into RawCullCore’s SaliencyInfo. Neither package needs to import the other to participate in that flow.

PhotoAnalysisResult returns:

FieldMeaning
saliencyOptional neutral subject label and confidence
breakdownScalar score plus detailed evidence and diagnostics
focusMaskOptional rendered overlay image
scoreConvenience access to breakdown.finalScore

An absent breakdown means analysis could not produce a valid result or was cancelled. It is different from a valid score of zero.

4. PhotoAnalyzer Is The Public Facade

Sources/PhotoAnalysisKit/PhotoAnalyzer.swift keeps the public entry points small:

APIWork performed
analyzeSaliency, classification, scalar scoring, and focus evidence; no overlay rendering
analyzeWithFocusMaskAnalysis plus a mask derived from the same evidence
focusMaskMask rendering, optionally reusing previously computed evidence
calibrateCatalog-sample calibration of the visual edge threshold
sharpnessDescriptorStable identity for cacheable non-mask analysis behavior

The facade contains an immutable FocusMaskEngine. Both types are @unchecked Sendable because CIContext does not declare sendability even though this package holds no mutable model or UI state and reuses the context concurrently.

For each input, PhotoAnalyzer copies the supplied configuration, replaces its ISO with the input ISO, and derives an aperture hint from the input aperture. Callers can safely reuse one base configuration across many files.

When a host already stores SharpnessBreakdown.focusEvidence, passing it to focusMask avoids repeating the saliency selection step. This makes the measurement result useful as an input to later presentation work.

5. Follow The Scalar Sharpness Pipeline

The core implementation is in FocusMaskEngine+Scoring.swift.

flowchart TD
    Image["CGImage"] --> SRGB["8-bit sRGB normalization"]
    SRGB --> Vision["Vision saliency + optional classification"]
    SRGB --> Preblur["ISO- and aperture-aware Gaussian pre-blur"]
    Preblur --> Laplacian["Metal focusLaplacian kernel"]
    Laplacian --> Samples["Global, saliency, AF, and local-patch samples"]
    Vision --> Samples
    Samples --> Tail["Robust p90-p97 tail scores"]
    Tail --> Blend["Subject/global blend"]
    Blend --> Adjust["Silhouette, subject-size, and blur-gate adjustments"]
    Adjust --> Breakdown["SharpnessBreakdown"]

5.1 Normalize Before Measuring

normalizeToSRGB redraws the input into an 8-bit sRGB RGBA bitmap. The Metal pipeline therefore receives a predictable pixel format regardless of the source image’s bit depth or color space.

5.2 Find Candidate Subject Regions

VNGenerateAttentionBasedSaliencyImageRequest supplies salient-object rectangles. Small weak objects are removed, and candidates are ordered using AF overlap or distance, saliency confidence, interior detail, area, and deterministic coordinates.

When classification is enabled, VNClassifyImageRequest supplies a neutral subject label. The package filters out broad environment descriptions and prefers likely subjects such as animals or people. This label is evidence, not a keep/reject decision.

5.3 Build Edge Energy

The packaged focusLaplacian Metal kernel runs after Gaussian pre-blur. The pre-blur grows with ISO so high-frequency sensor noise is less likely to masquerade as detail. Aperture hints damp or strengthen parts of this behavior for wide, middle, and landscape apertures.

The result is rendered as floating-point RGBA data. The red channel carries edge energy.

5.4 Score Several Regions

The engine samples:

  • the full image after excluding a configurable border;
  • the selected salient region;
  • the camera AF region;
  • smaller AF-center and AF-neighborhood regions;
  • ranked local patches within subject or AF regions.

robustTailScore sorts the sample values, measures the p90-p97 energy band relative to a p20 noise floor, and penalizes a band that is too sparse. microContrast computes the standard deviation of finite edge samples.

The normal blend combines full-frame and subject evidence. When both AF and saliency scores exist, AF has the larger share of the subject score. A conservative local-detail component can then refine the broad subject measurement.

The final value may be adjusted for:

  • a silhouette-dominated subject whose strongest energy is mostly at the outer rim;
  • the area of a saliency-only subject;
  • an aperture-aware soft blur gate driven by subject micro-contrast.

SharpnessBreakdown preserves the component scores and selected evidence so a host can explain the result instead of presenting a single unexplained number.

5.5 Distinguish Failure Shapes

FocusFailureKind classifies the evidence as:

  • .motionBlur when global, subject, and AF detail are all weak and micro-contrast is low;
  • .missedFocus when the frame has usable global detail but the subject is much weaker;
  • .none when neither pattern is established.

These are algorithmic classifications, not final user-facing copy or culling actions.

Scalar scoring answers “how much reliable detail is present?” Mask rendering answers “where should the UI draw visible focused edges?” They share evidence but have different configuration needs.

FocusEvidence records the winning region, AF scores, selected patch rankings, spatial alignment, dominance, silhouette handling, visual threshold, coverage, and confidence diagnostics. FocusPatchRanking exposes the detail, coverage, shape, position, and penalty components behind each candidate patch.

The overlay pipeline:

  1. chooses AF-center, AF-neighborhood, AF, saliency, mixed, or global evidence;
  2. builds one native-pixel fine-detail Laplacian with clamped edges for every region;
  3. ranks local patches and selects the best evidence patches;
  4. chooses an adaptive percentile threshold from the complete selected search regions;
  5. applies optional erosion and dilation to the binary edge mask;
  6. colorizes, clips to the full search regions, feathers, and crops the mask;
  7. measures visible coverage after rendering with GPU reductions;
  8. returns updated evidence and render diagnostics with the image.

The renderer deliberately does not lower the threshold to force visible pixels. guaranteeVisibleFocusEvidence remains in the public configuration for source compatibility, but a weak or unfocused image may produce an empty mask.

FocusMaskRegionSource describes whether saliency, AF, both, or neither provided the overlay region. FocusEvidenceOverlayStyle distinguishes subject edges from global edges. RawCull decides how these neutral values appear in its interface.

7. Configuration, Presets, And Cache Identity

SharpnessConfiguration is a value snapshot containing numeric algorithm settings. It separates host-editable behavior from observable settings models.

Notable groups are:

Configuration groupExamples
Edge pipelinepreBlurRadius, threshold, energyMultiplier
Mask morphologydilationRadius, erosionRadius, featherRadius
VisibilityguaranteeVisibleFocusEvidence, minimumEvidenceCoverage
Region selectionAF radii, border inset, saliency weight
Scoring adjustmentssubject-size factor, silhouette strength, fine-detail weight
Capture hintsiso, apertureHint

SharpnessPreset applies high-level subject tuning for automatic, birds and wildlife, portrait, landscape, or general action use. SharpnessQuality selects fast, balanced, or high-precision fine-detail work. The host may persist its own UI enums, but should map them into these package values instead of duplicating constants.

Persisted results need more than a filename. SharpnessAnalysisDescriptor records:

  • descriptor schema version;
  • scalar algorithm version;
  • ISO-scaling policy version;
  • aperture-hint policy version;
  • every host-configurable value that affects non-mask scoring;
  • the stable scoring energy multiplier.

The descriptor deliberately excludes per-image ISO and aperture, mask-only presentation settings, decoded dimensions, source choice, and source-file identity. A host must account for changes in those inputs and decode policy when deciding whether a persisted result is reusable.

RawCull persisted sharpness identity
├── PhotoAnalysisKit SharpnessAnalysisDescriptor
├── selected embedded-preview or RAW source
├── effective maximum pixel size
└── source file size and modification date

RawCull’s signature records requested effective size rather than every actual decoded dimension. Per-image metadata is supplied with each analysis input; source size/modification checks invalidate replaced input files. See Focus Mask and Sharpness for the exact host signature and restoration contract.

8. Bounded Batch Analysis

PhotoAnalysisBatchRequest<Identifier> contains an identifier and an async input provider. The provider inversion is important: PhotoAnalysisKit coordinates work, while the host retains file access and decoding policy.

analyzeBatch starts only up to maximumConcurrentTasks child tasks. When one completes, it enqueues one more request. This prevents a large catalog from creating an unbounded number of decoded bitmaps.

The API has three ordering and failure guarantees:

  • progress is emitted in completion order;
  • the returned results preserve request order;
  • a decode failure is represented by a result whose analysis is nil.

If the parent task is cancelled, the method cancels the group and returns nil, telling the host to discard partial results rather than mistake them for a complete batch.

9. Calibration Changes The Overlay, Not The Score

Calibration samples Laplacian energies from host-provided decoded inputs with bounded concurrency. It downsamples the collected sample set, sorts it, and returns p50, p90, p95, and p99 statistics plus a clamped threshold at the requested percentile.

At least minimumSuccessfulImages inputs must succeed. Cancellation or too few samples returns nil.

Calibration changes only the visual edge threshold. Core sharpness scores keep a stable gain and do not depend on the current catalog. This prevents the same photo from receiving a different scalar score merely because unrelated photos were added or removed.

10. Vision Feature Prints Stay Opaque

VisionFeaturePrintBackend is an actor that creates a VNFeaturePrintObservation using Vision revision 2 by default. The observation is securely archived inside VisionFeaturePrint.payload.

The value also stores its Vision revision and representation version. Before comparison, the backend verifies both values, securely unarchives each observation, and calls Vision’s native computeDistance.

The host can persist the opaque payload, but it must associate it with source-file identity. Incompatible prints return nil; corrupt archives or failed Vision operations throw a typed VisionFeaturePrintError.

PhotoAnalysisKit intentionally does not copy PhotoAIKit’s general similarity artifact descriptors, CLIP fallback, or batch indexing. It supplies only the focused Vision measurement primitive.

11. Metal Resources Are Part Of The Algorithm

Sources/PhotoAnalysisKit/Resources/Kernels.ci.metal is the source for the Core Image kernel. SwiftPM copies Metal source resources but does not compile them for command-line builds, so the package also checks in default.metallib.

Tools/build_metallib.sh regenerates the binary. A kernel change is incomplete until the checked-in library has been rebuilt and tests have been run. The binary resource affects algorithm output and must be treated like source, not an optional deployment file.

12. Concurrency And Cancellation

The package uses four complementary techniques:

  • Immutable facade and engine: callers pass input and configuration snapshots; no app state is retained.
  • Explicit concurrent workers: synchronous Core Image and Vision work runs outside caller UI isolation while retaining task priority and task-local context.
  • Bounded task groups: batch analysis and calibration cap simultaneous inputs.
  • Cooperative checks: expensive stages test cancellation before Vision work, rendering, large loops, and result publication.

@unchecked Sendable is confined to the immutable Core Image facade and engine. Public transport values are Sendable value types.

13. RawCull Call Maps

The app has two deliberate entry paths into the same PhotoAnalyzer facade.

flowchart LR
    Settings["Settings + photo-type preset"] --> Sharp["SharpnessScoringModel"]
    Sharp --> Adapter["RawCullPhotoAnalysisAdapter"]
    Adapter --> Input["PhotoAnalysisInput: decoded CGImage + neutral metadata"]
    Input --> Batch["PhotoAnalyzer.analyzeBatch"]
    Batch --> Results["PhotoAnalysisResult per FileItem"]
    Results --> Core["RawCullCore ranking evidence + BurstAnalysisCache"]

SharpnessScoringModel applies the selected package preset, builds requests through RawCullPhotoAnalysisAdapter, and calls the facade’s bounded batch API. The adapter owns source loading and file-to-identifier mapping; the package owns measurement and its descriptor. BurstAnalysisCache records PhotoAnalyzer.sharpnessDescriptor(for:), so a configuration-identity change invalidates incompatible cached scores.

flowchart LR
    UI["Focus overlay or calibration action"] --> Model["FocusMaskModel"]
    Model --> Analyze["PhotoAnalyzer.analyzeWithFocusMask / focusMask / calibrate"]
    Analyze --> Evidence["FocusEvidence + FocusCalibrationResult + CGImage mask"]
    Evidence --> Presentation["RawCull FocusMaskResult + overlay state"]

FocusMaskTypes.swift aliases neutral package types such as FocusEvidence, FocusFailureKind, and FocusCalibrationResult, then layers RawCull presentation metadata over SharpnessBreakdown. FocusMaskModel consumes the returned mask image on app-owned isolation; scoring and evidence remain package values.

14. Testing The Public Contract

The executable contracts are split by concern:

Package testRequired behavior
Tests/PhotoAnalysisKitTests/SharpnessMetricsTests.swiftScalar metric and normalized sharpness calculations
Tests/PhotoAnalysisKitTests/PhotoAnalysisBatchTests.swiftBounded batch completion, ordering, failure isolation, and cancellation
Tests/PhotoAnalysisKitTests/SharpnessAnalysisDescriptorTests.swiftStable configuration identity and descriptor changes
Tests/PhotoAnalysisKitTests/PhotoAnalyzerTests.swiftFacade behavior, focus evidence, calibration, and mask rendering
Tests/PhotoAnalysisKitTests/VisionFeaturePrintTests.swiftOpaque Vision feature-print creation and comparison

Tests/PhotoAnalysisKitTests/ imports the library through import PhotoAnalysisKit, not @testable import. Tests therefore exercise the public surface used by a host.

The suite covers:

  • end-to-end sharpness analysis with the packaged Metal kernel;
  • focus-mask images, evidence, and diagnostics;
  • calibration from decoded images and neutral metadata;
  • bounded concurrency, order preservation, progress, decode failure, and cancellation;
  • descriptor encoding and changes in identity-affecting settings;
  • robust-tail, micro-contrast, ISO scaling, and focus-failure metrics;
  • configuration presets and aperture behavior;
  • Vision feature-print compatibility, round trips, and malformed payloads.

Synthetic images keep the suite deterministic and independent of RAW files, model downloads, cache directories, and application state.

15. How To Add Another Analysis

Use the existing boundary as a checklist:

  1. Accept CGImage and only the neutral metadata the algorithm needs.
  2. Keep URLs, camera decoding, settings state, and source selection in the host.
  3. Return a Sendable package-owned result with enough evidence to explain it.
  4. Put numeric tuning in a value configuration, not UI preferences.
  5. Define a versioned descriptor when hosts may persist the output.
  6. Make synchronous framework work cancellation-aware and independent of UI isolation.
  7. Bound multi-image work instead of spawning one live task per catalog item.
  8. Test through the public API with synthetic images and values.

If the proposed API needs FileItem, SwiftUI, a cache directory, or a rating, that concern belongs in RawCull’s adapter or policy layer.

Source Map

TopicPhotoAnalysisKit source
Product and resource declarationPackage.swift
Input and result boundarySources/PhotoAnalysisKit/PhotoAnalysisInput.swift
Public analysis facade and metricsSources/PhotoAnalysisKit/PhotoAnalyzer.swift
Batch orchestrationSources/PhotoAnalysisKit/PhotoAnalysisBatch.swift
Configuration and presetsSources/PhotoAnalysisKit/SharpnessConfiguration.swift, SharpnessPresets.swift
Cache descriptorSources/PhotoAnalysisKit/SharpnessAnalysisDescriptor.swift
Public evidence valuesSources/PhotoAnalysisKit/FocusMaskTypes.swift
Engine isolationSources/PhotoAnalysisKit/FocusMaskEngine.swift
Saliency and scalar scoringSources/PhotoAnalysisKit/FocusMaskEngine+Scoring.swift
Overlay generation and patch rankingSources/PhotoAnalysisKit/FocusMaskEngine+MaskGeneration.swift
CalibrationSources/PhotoAnalysisKit/FocusMaskCalibration.swift
Vision feature printsSources/PhotoAnalysisKit/VisionFeaturePrintBackend.swift
Metal source and compiled resourceSources/PhotoAnalysisKit/Resources/
Extraction decisionsDocumentation/ExtractionMap.md
Public behavior testsTests/PhotoAnalysisKitTests/
RawCull decode and result adapterRawCull/Model/ViewModels/FocusandSharpness/RawCullPhotoAnalysisAdapter.swift

Next, see how package-neutral measurements become culling-domain decisions in How RawCullCore Is Constructed.

Current host AF evidence hydration

RawCull’s workspace fills missing AF-center evidence from older cached analysis without replacing blended scores or recommended winners. Cancellation and scoring identity guard publication. The resolved PhotoAnalysisKit 1.3.1 formula is unchanged. The host’s optional releaseafcomparison workflow exports crops for a separately labeled comparison; it is not photographic qualification.

November 8 Integration Review: Measurement And Inspection

RawCull continues to resolve PhotoAnalysisKit 1.3.1 at 2a1466e04d821fa2628d6985296643e0d0c7e465. Its measurement boundary is unchanged by the addition of PhotoEvidenceKit. The latter displays manually chosen regions; it does not call PhotoAnalyzer or recompute a score when a photographer moves or zooms a crop.

Build Cache Identity Around The Actual Analysis Input

SharpnessAnalysisDescriptor describes algorithm/policy versions and configurable non-mask analysis settings. The host must additionally identify the source file, the chosen decoding path and decoded resolution. A score computed from an embedded preview must not silently become the score for a developed RAW image after a source toggle. Per-image ISO and aperture belong to PhotoAnalysisInput and must remain consistent with the metadata used for that cached computation.

A manual inspection’s CloseUpRenderSource is a separate identity. It enables fresh display pixels without overwriting analysis identity or implying that a previous score was computed from the newly displayed crop.

Interpret Batch Outcomes Precisely

Batch outcomeMeaningHost behavior
Empty inputSuccessful empty arrayFinish with no work
Result with analysis == nilThat input provider failed to supply a usable imageRetain the item’s failure state rather than inventing a zero score
Outer result is nilParent task was cancelledDiscard partial publication for that batch
Progress callbackNext completion, not next input positionUpdate progress using the supplied identifier
Final result arrayOriginal request orderAssociate results with their stable identifiers

The default maximumConcurrentTasks is eight; the implementation clamps it to at least one and at most the request count. Input providers execute within that bounded work, so hosts can avoid eagerly decoding a whole catalog. This bounds active batch tasks, not every cache or retained image elsewhere in the app.

Keep AF Evidence And Manual Placement Distinct

Analysis AF evidence contributes to measurement interpretation. PhotoEvidenceKit’s recorded AF point assists region placement in canonical oriented coordinates. Neither the presence of an AF location nor successful region placement establishes that the subject is sharp. Supply metadata appropriate to each API and perform sensor-to-oriented coordinate conversion in the host adapter.

Close Up Integration

Build 466 uses PhotoAnalysisKit 1.4.1. FaceEvidenceAnalyzer runs Vision face rectangle detection on an upright embedded preview and can return a local luminance-gradient measurement for each face. RawCull owns the disposable evidence cache. It keys compatibility on the source revision, preview configuration and dimensions, algorithm version, Vision revision and OS version.

RawCull calls the package’s AnimalCloseUpDetector for animal head and eye crops. Animal tiles are visual crops. The human face detail measurement stays with the human tiles. See the Close Up guide for how these tiles appear beside manual comparisons.

Changes at 1.3.9

The package can reuse supplied focus evidence without repeating Vision. Scoring uses the configured capture fallbacks when metadata is missing, includes those fallbacks in scalar cache identity, and uses the global score when subject evidence is unavailable. Calibration records its decode size alongside the mask cutoff. Historical metric tables above describe their pinned audits.

4 - How RawCullCore Is Constructed

A detailed guide to RawCullCore’s package-safe models, capture-time and EV-aware burst grouping, ranking evidence, confidence rules, histograms, concurrency, and tests.

How RawCullCore Is Constructed

Revision audited: The original walkthrough used RawCullCore 1.1.2 at d25a51e65ad32a82bf82f86fa0ec07d6e14498e9.

RawCullCore is the small domain layer at the center of RawCull. It does not decode or analyze photos. Instead, it receives file metadata and measurements already produced elsewhere, groups sequential files into bursts, and ranks the candidates using deterministic culling rules.

Its main architectural value is that a recommendation can be tested without opening a RAW file, running Vision, creating a Metal context, loading application settings, or constructing a view model.

1. Begin With The Package Boundary

RawCullCore owns:

  • package-safe file, EXIF, source-catalog, and saliency values;
  • normalized focus-point parsing;
  • burst group, boundary-evidence, ranking, confidence, and review-state models;
  • pure burst grouping rules;
  • pure burst ranking and one-click-safety rules;
  • a lightweight 256-bin luminance histogram.

RawCullCore deliberately does not own:

  • TIFF, MakerNote, ARW, or NEF parsing;
  • thumbnail, preview, or full RAW decoding;
  • Vision, Core Image, Metal, CLIP, or SAM 3 analysis;
  • caches, settings, security-scoped URLs, and saved-file coordination;
  • observable view models, SwiftUI, selection, sorting, and culling actions.

This produces a clear flow:

flowchart LR
    Parser["RawParserKit\nmetadata + AF location"] --> Adapter["RawCull adapter"]
    Analysis["PhotoAnalysisKit\nsharpness + saliency"] --> Adapter
    AI["PhotoAIKit\nvisual distance"] --> Adapter
    Adapter --> Values["RawCullCore values"]
    Values --> Group["BurstGroupingEngine"]
    Group --> Rank["BurstRankingEngine"]
    Rank --> Decision["RawCull presentation and action"]

The arrows describe how RawCull composes runtime values. RawCullCore imports none of the other packages.

2. The Manifest Optimizes For A Small Domain Library

Package.swift declares Swift tools 6.2, Swift 6 language mode, macOS 26, one RawCullCore library target, and one test target. It has no external package dependencies and no bundled resources.

The target uses:

.defaultIsolation(MainActor.self)
.enableUpcomingFeature("InferIsolatedConformances")
.enableUpcomingFeature("NonisolatedNonsendingByDefault")

Default main-actor isolation matches the surrounding application environment, but the package’s public value types and pure engines are explicitly nonisolated. Background grouping and ranking therefore do not acquire unnecessary main-actor hops.

This is a useful distinction: the build default is conservative, while each proven pure API opts out explicitly.

3. Package-Safe Models Replace Application State

The package uses transport values instead of importing RawCull’s FileItem or view models.

3.1 ExifMetadata

ExifMetadata is a Codable, Hashable, and Sendable snapshot containing display strings and numeric values for shutter speed, focal length, aperture, ISO, exposure compensation, camera, lens, RAW type, size class, and pixel dimensions.

It contains both strings and numbers because they serve different purposes:

  • strings preserve display-ready metadata such as shutter notation and lens names;
  • numeric exposure time, focal length, aperture, ISO, and exposure compensation support deterministic stop-based rules without reparsing display text.

RawCull or an adapter constructs this value from RawParserKit’s RawImageMetadata. RawCullCore does not know where the values came from.

At the app boundary, RawCull/Main/RawCullFileItem.swift deliberately preserves familiar app names:

typealias FileItem = RawCullFileItem
typealias ARWSourceCatalog = RawCullSourceCatalog
typealias ExifMetadata = RawCullCore.ExifMetadata

These aliases are migration conveniences, not permission for the package to import application state. Feature code may say FileItem, while the stored value and package API remain RawCullFileItem.

3.2 RawCullFileItem

RawCullFileItem contains an ID, URL, name, byte size, modification date, optional capture date and capture-time-zone offset, optional EXIF snapshot, and optional normalized AF point.

Equality and hashing use only id. Two snapshots with the same ID are the same logical file item even if another stored field changed. This matches the identity behavior expected by RawCull collections.

effectiveCaptureDate prefers the EXIF capture instant and falls back to the file modification date. usesFileModificationDateForCaptureTime exposes which path was used so grouping and confidence can treat the fallback conservatively. formattedSize is a lightweight Foundation convenience. File access and mutable scan state remain outside the value.

3.3 Catalog And Saliency Summaries

RawCullSourceCatalog identifies a named source URL without adding bookmark or access-lifecycle behavior.

SaliencyInfo stores only an optional subject label and confidence. It deliberately does not import Vision or expose a Vision observation. A PhotoAnalysisKit result can be translated into this small culling-domain value at the host boundary.

4. Focus-Point Parsing Connects Vendor Metadata To Analysis

RawParserKit’s vendor parsers return a focus string in this shape:

imageWidth imageHeight focusX focusY

FocusPointParser.normalizedPoint(from:) splits on arbitrary whitespace, requires exactly four numeric values and positive image dimensions, and returns:

x = focusX / imageWidth
y = focusY / imageHeight

The origin remains at the visual top-left. PhotoAnalysisKit accepts that convention and performs its own Vision coordinate conversion.

The parser does not clamp the returned point. Vendor parsers and host validation are expected to supply meaningful sensor coordinates. Malformed input or non-positive dimensions return nil.

5. Burst Models Preserve Evidence, Not Just A Winner

BurstAnalysisModels.swift defines the values exchanged by the two engines.

BurstGroupingOutput
├── groups: [BurstGroup]
└── boundaryEvidence: [BurstBoundaryEvidence]

BurstAnalysisResult
├── ordered candidate scores
├── recommended and second-best IDs
├── confidence and review state
├── one-click safety flag
├── reasons
└── cautions

This design avoids throwing away intermediate decisions. RawCull can show why a boundary was created, why a file won, and why automation is or is not considered safe.

BurstGroupingConfig.algorithmVersion is currently 4. Its defaults are visual distance 0.25, EXIF gap 2 seconds, modification-date fallback gap 10 seconds, same camera required, similar focal length required within 3 mm, shutter/ aperture/ISO change at most 0.5 EV, and exposure compensation at most 0.34 EV. The version gives hosts an identity marker for persisted grouping output. Custom decoding supplies defaults for fields that are absent from older saved configurations.

BurstReviewState has the current workflow states .none, .needsReview, .reviewed, and .deferred, plus compatibility states .algorithmReviewed, .manualWinnerOverride, and .decisionApplied retained for older caches. Unknown decoded raw values fall back to .none. BurstWinnerOverride likewise migrates older data by generating a missing ID and defaulting missing member filenames to an empty array.

6. BurstGroupingEngine: Decide Where A Burst Splits

The grouping engine expects files in shot order. It starts with the first file and evaluates each adjacent pair.

flowchart TD
    Pair["Previous + current file"] --> Visual{"Visual distance present\nand below threshold?"}
    Visual -- No --> Split["Start new group"]
    Visual -- Yes --> Time{"Time gap allowed?"}
    Time -- No --> Split
    Time -- Yes --> Camera{"Required camera same?"}
    Camera -- No --> Split
    Camera -- Yes --> Focal{"Required focal delta allowed?"}
    Focal -- No --> Split
    Focal -- Yes --> Exposure{"Exposure stable?"}
    Exposure -- No --> Split
    Exposure -- Yes --> Continue["Append to current group"]

A new group begins when any enabled boundary rule fires:

  • similarity evidence is missing;
  • visual distance is greater than or equal to visualDistanceThreshold;
  • the absolute capture gap exceeds maxTimeGapSeconds, or maxFallbackTimeGapSeconds when either file lacks a parsed EXIF capture instant;
  • camera identity changes when requireSameCamera is enabled;
  • numeric or parsed focal length changes by more than maxFocalLengthDeltaMM when similarity is required;
  • shutter speed, aperture, ISO, or exposure compensation changes by more than its configured EV threshold.

The default EXIF capture gap is 2 seconds; the default file-date fallback gap is 10 seconds. Each boundary records captureTimeUsedFallback, allowing later ranking to distinguish precise camera time from filesystem time.

Exposure comparison works in photographic stops:

shutter delta  = |log2(current seconds / previous seconds)|
aperture delta = 2 × |log2(current f-number / previous f-number)|
ISO delta      = |log2(current ISO / previous ISO)|
compensation   = |current EV - previous EV|

The defaults are 0.5 EV for shutter, aperture, and ISO and 0.34 EV for exposure compensation. The engine prefers numeric values. When a numeric shutter, aperture, or ISO comparison is unavailable but both normalized display strings are present and differ, it still treats the exposure as changed. The largest available adjustment is retained as exposureAdjustmentEV.

Focal length similarly prefers focalLengthMM and falls back to the first number in the display string. If either side has no usable value, that rule has no delta to evaluate.

Lens changes are recorded in BurstBoundaryEvidence, but do not by themselves split a group. They later make the group’s ranking metadata unstable. Keeping evidence separate from the grouping decision makes this behavior visible rather than implicit.

Missing similarity is conservative: it creates a boundary instead of assuming two files belong together. BurstPairKey.cacheKey standardizes the ordered adjacent-pair key used to supply those distances.

Each boundary record stores the measured values, boolean changes, final decision, and human-readable reasons. The output assigns stable sequential group IDs beginning at zero for that run.

7. BurstRankingEngine: Turn Evidence Into A Recommendation

Ranking consumes groups, files keyed by ID, sharpness scores, a score normalization maximum, saliency summaries, boundary evidence, and optional review states.

7.1 Determine Group Conditions

For each group, the engine derives:

  • metadata stability: none of its internal boundaries report exposure, camera, or lens changes;
  • capture-time reliability: every member has a parsed EXIF capture date rather than the modification-date fallback;
  • tight similarity: every internal boundary has a visual distance below 0.22;
  • dominant subject: the most frequent non-nil saliency label;
  • burst-relative sharpness: a within-group 0...1 normalization when at least two valid scores exist and their normalized spread is at least 0.03.

The configured grouping threshold decides membership; the fixed tighter 0.22 check contributes to ranking confidence. They answer different questions.

7.2 Score Each Candidate

If burst-relative sharpness is available, the ranking sharpness component is:

ranking sharpness = 0.65 × catalog-normalized sharpness
                  + 0.35 × burst-relative sharpness

The final candidate score is:

overall = 0.62 × ranking sharpness
        + 0.12 × focus-point evidence
        + 0.10 × saliency consistency
        + 0.16 × metadata evidence

The supporting components are deliberately simple and inspectable:

ComponentRule
Focus point0.70 when AF metadata exists, otherwise 0.45
Saliency0.75 for the dominant label, 0.25 for a different label, 0.45 when absent
Metadata base0.70 when stable, otherwise 0.40
Tight-similarity adjustment+0.15
ISO adjustmentAbove ISO 1600, -0.05 per stop, capped at -0.15
Wide-aperture adjustment+0.05 at f/5.6 or wider
Motion-risk adjustment+0.05 for a clearly fast shutter; up to -0.15 for a slower shutter

Every component is clamped or normalized into a predictable range before use. Candidates are sorted by descending overall score; equal scores preserve the group’s original shot order.

Motion risk uses exposureTimeSeconds with focalLengthMM when both are available. A shutter at least twice as fast as the reciprocal focal-length rule gets the positive adjustment; a shutter slower than the reciprocal rule gets a stop-based penalty. Without focal length, 1/500 second or faster is treated as lower risk and 1/60 second or slower as elevated risk.

Each candidate also carries reasons and cautions such as measured sharpness, available AF evidence, classified subject, missing sharpness, changed metadata, fast or slow shutter behavior, and high ISO.

7.3 Assign Confidence Separately

Winning a group does not automatically mean a decision is safe to automate.

High confidence requires:

  • at least one sharpness score;
  • at least three files in the group;
  • a best-versus-second score gap of at least 0.12;
  • best absolute sharpness of at least 0.65 after normalization;
  • stable metadata;
  • tight visual similarity;
  • parsed capture times for every member.

Medium confidence requires a gap of at least 0.05 and stable metadata. Other results are low confidence.

isSafeForOneClickCulling is true only for high confidence. canApplyOneClickCulling(hasSharpnessScores:) adds an explicit host-supplied confirmation that sharpness data is available before an action is enabled. RawCull still owns the action itself.

Reasons and cautions on BurstAnalysisResult are capped to three each so the result remains concise enough for inspection UI and persistence.

A modification-date fallback therefore does not prevent grouping, but it does prevent high-confidence automation and adds a capture-time caution.

8. Histogram Calculation Is Intentionally Lightweight

HistogramCalculator.normalizedLuminanceHistogram(from:) directly reads an 8-bit RGB or RGBA-style CGImage buffer. Each pixel is placed in one of 256 bins using Rec. 601 luminance:

Y = 0.299R + 0.587G + 0.114B

The bins are normalized by the largest bin count, so the peak has value 1. This is shape normalization, not probability normalization; the bins do not necessarily sum to 1.

The implementation requires positive dimensions, provider data, 8 bits per component, and at least three bytes per pixel. Unsupported input returns a zero-filled 256-bin array, preserving a stable return shape for views and callers.

The helper is appropriate for display and lightweight comparisons. Color conversion, RAW development, high-bit-depth analysis, and channel-layout generalization are outside this package.

9. Concurrency Is Achieved Through Purity

RawCullCore contains no actor because it owns no shared mutable runtime state. Models are Sendable values and engines are namespaces of nonisolated static functions.

The package performs no asynchronous I/O. Callers do expensive decoding, Vision work, embeddings, and sharpness analysis on the appropriate tasks, then pass snapshots into RawCullCore.

This design has several practical benefits:

  • grouping and ranking are deterministic for the same inputs;
  • no application singleton can change a result midway through a call;
  • tests do not require async setup or framework assets;
  • background work does not cross the main actor merely because the host uses main-actor default isolation.

10. Testing Rules And Migrations

Tests/RawCullCoreTests/ uses Swift Testing and synthetic values. Coverage includes:

  • model coding, hashing, identity, and source-catalog values;
  • valid, decimal, whitespace-varied, and malformed focus strings;
  • empty and stable groups;
  • boundaries caused by missing distance, time, camera, focal length, and exposure;
  • EXIF capture ordering, time-zone offsets, modification-date fallback, and the different fallback gap;
  • numeric and display-string exposure comparisons in photographic stops;
  • boundary evidence content;
  • absolute and burst-relative sharpness ranking, motion risk, and progressive ISO penalties;
  • missing scores, stable tie order, confidence, review-state propagation, and one-click eligibility;
  • RGB and RGBA histogram bins, peak normalization, and unsupported input.

No test needs an actual catalog, RAW file, Vision model, Metal device, cache directory, or settings store. That is the strongest evidence that the package boundary is doing useful work.

11. How To Extend Culling Logic

Use these constraints when adding a rule:

  1. Pass the required fact into a Sendable package value; do not reach into a view model.
  2. Preserve raw evidence separately from the final boolean or winner.
  3. Keep scoring weights and confidence thresholds deterministic and testable.
  4. Decide whether a rule affects group membership, candidate ranking, confidence, or only a caution.
  5. If evidence changes a grouping boundary or its meaning, bump BurstGroupingConfig.algorithmVersion and add migration/engine tests.
  6. If the app’s persisted result shape, validation, or pipeline identity changes, bump BurstAnalysisCache.schemaVersion (currently 9) and update cache tests.
  7. Maintain decoding fallbacks for existing review and override data.
  8. Leave framework observations and heavy image processing in the producing package.
  9. Leave user actions and presentation state in RawCull.

Source Map

TopicRawCullCore source
Product and concurrency settingsPackage.swift
EXIF transport valueSources/RawCullCore/ExifMetadata.swift
File and source identitySources/RawCullCore/RawCullFileItem.swift, RawCullSourceCatalog.swift
Saliency summarySources/RawCullCore/SaliencyInfo.swift
Focus normalizationSources/RawCullCore/FocusPointParser.swift
Burst contracts and migrationsSources/RawCullCore/BurstAnalysisModels.swift
Boundary decisionsSources/RawCullCore/BurstGroupingEngine.swift
Ranking and confidenceSources/RawCullCore/BurstRankingEngine.swift
HistogramSources/RawCullCore/HistogramCalculator.swift
Behavior testsTests/RawCullCoreTests/
RawCull metadata adapter and burst orchestrationRawCull/Model/RawImageLoading.swift, RawCull/Model/ViewModels/BurstWorkflowController+Grouping.swift

Return to the package overview in RawCull Packages, or continue with the file-decoding layer in How RawParserKit Is Constructed.

The exposure histogram is an app-level display product

RawCull’s temporary exposure-inspection histogram uses three RGB channels and near-black/near-white fractions from the completed sRGB preview. It does not replace or call this package’s single normalized luminance histogram. Keep the two algorithms and their interpretation separate when changing display code. See RAW Formats and Exposure Inspection.

Live review ownership remains in the application

RawCull stores live decisions in BurstReviewSessionModel and maps snapshots through BurstReviewStateMapping. The app restores membership signatures onto current group IDs and coordinates persistence. This extraction does not change RawCullCore’s pure grouping/ranking models or its resolved 1.1.2 pin.

November 8 Integration Review: Recommendations And Close-ups

The resolved RawCullCore baseline remains 1.1.2 at d25a51e65ad32a82bf82f86fa0ec07d6e14498e9. The new PhotoEvidenceKit integration adds a manual inspection surface beside grouping and ranking. It introduces no compile-time dependency into RawCullCore.

Three Kinds Of State Have Different Lifetimes

StateOwnerEffect
Grouping/ranking evidenceRawCullCore values produced from host inputsExplains boundaries, candidate scores and recommendation confidence
Photographer review decisionsRawCull host review/persistence layerRecords explicit choices independently of recomputation
Close-up region/reference/viewportPhotoEvidenceKit session plus injected region storeSupports visual comparison without setting a winner or rating

Pinning a close-up reference does not select a recommended winner. Moving a manual region does not alter the analysis score. Selecting several comparison frames does not regroup the burst. RawCull’s BurstCloseUpSelection keeps comparison membership separate from the active review frame, including command-toggle and shift-range interactions.

Preserve Missing Evidence And Time Provenance

Grouping consumes files in shot order and adjacent-pair similarity evidence. A missing comparison is a reason for a boundary, not a zero-distance match. Capture-time fallback is recorded in boundary evidence and influences the allowed time gap. Keep the distinction between capture metadata and file modification time when constructing the input values.

Ranking also records cautions for missing sharpness or AF evidence. Reliable capture times participate in the high-confidence gate, alongside score separation and metadata conditions. A candidate appearing first in a ranked result does not by itself establish that a one-click action is safe. Preserve the package’s confidence and eligibility fields when adapting results for the UI.

Recompute Without Overwriting Review Intent

When upstream source identity, sharpness configuration or similarity backend changes, regenerate the affected input evidence before ranking again. Publish the new recommendation only for the current host request and preserve separately owned photographer decisions. Refresh a pinned close-up’s source revision through updateReference so manual inspection can stay current without modifying the ranking input or host selection.

Resolved app revision

Build 466 pins RawCullCore 1.1.5 at ea8ac2fc6611949af2b55ec433456bfe502cf886. The app’s burst workflow invokes the package algorithms through app-side adapters. Earlier examples and results retain their original audit revision.

5 - How RawParserKit Is Constructed

A detailed guide to RawParserKit’s vendor dispatch, TIFF and MakerNote parsing, embedded previews, structured capture and exposure metadata, orientation, decode limiting, cancellation, compatibility APIs, and tests.

How RawParserKit Is Constructed

Revision scope: This walkthrough was written against RawParserKit 1.3.0 at d2175ed880d39021bdb5f5a2a842b460af0b316c. The current RawCull checkout resolves 1.3.3 at 26df4abc2178d5c07d08f3883d84d0648f5141d3. The earlier audit remains explicitly historical. The 1.3.1 RAW 9 and 1.3.2 generic-format additions below describe the current application boundary.

RawParserKit is RawCull’s camera-file boundary. It knows how Sony ARW, Nikon NEF, and Adobe DNG files are structured, how to locate their embedded JPEGs and AF metadata, and how to turn those sources into orientation-normalized images and display-ready metadata.

The package stops at decoding. It does not score sharpness, generate embeddings, group bursts, cache application results, or decide which photo should be kept.

1. Begin With The Package Boundary

RawParserKit owns:

  • vendor-neutral RAW format dispatch;
  • Sony ARW, Nikon NEF, and Adobe DNG format knowledge;
  • TIFF IFD and vendor MakerNote traversal;
  • focus-location and embedded-JPEG offset parsing;
  • RAW and rendered-image thumbnails and previews;
  • source-orientation normalization;
  • display-ready and numeric EXIF/RAW metadata extraction, including a structured capture instant and time-zone offset;
  • Sony full sensor development to JPEG;
  • decode task deduplication, concurrency limiting, and cooperative cancellation;
  • diagnostics and staged compatibility APIs.

The host application owns:

  • security-scoped URL access and sandbox bookmarks;
  • directory discovery, catalogs, and source selection;
  • memory and disk cache locations and eviction policy;
  • image-analysis inputs and result identity;
  • observable loading state, placeholders, retries, and presentation;
  • ratings, burst grouping, ranking, and saved-file behavior.

RawParserKit supplies inputs to higher layers without importing them:

flowchart LR
    File["ARW, NEF, DNG, JPEG, PNG, or TIFF"] --> Parser["RawParserKit"]
    Parser --> Image["CGImage or NSImage"]
    Parser --> Metadata["RawImageMetadata + RawFocusPoint"]
    Image --> Host["RawCull adapters"]
    Metadata --> Host
    Host --> Analysis["PhotoAnalysisKit / PhotoAIKit"]
    Host --> Core["RawCullCore"]

2. Package Shape And Framework Boundary

Package.swift declares Swift tools 6.2, Swift 6 language mode, macOS 26, one library product, and one test target. There are no third-party package dependencies.

The implementation uses Apple frameworks appropriate to file decoding: Foundation, AppKit, Core Graphics, ImageIO, Core Image, OSLog, and synchronization primitives from os.

Like RawCullCore, the target enables main-actor default isolation plus InferIsolatedConformances and NonisolatedNonsendingByDefault. Pure parsing and static format APIs opt out with nonisolated; the stateful loader and limiter use actors.

The source is arranged in layers:

RawImageLoader                         high-level deduplicated facade
├── RawFormatRegistry + RawFormat      vendor-neutral dispatch
│   ├── SonyRawFormat
│   ├── NikonRawFormat
│   └── DNGRawFormat
├── thumbnail and preview extractors   ImageIO + binary fallback
├── MakerNote parsers                  TIFF byte traversal
├── OrientationNormalizedImageLoader   rendered/embedded image helpers
└── cancellation + decode limiter      concurrency control

Callers can use the facade for normal browser behavior or a lower layer when they need explicit control.

3. RawFormat Makes Vendor Dispatch Explicit

Sources/RawParserKit/RawFormat.swift describes the static capabilities every camera format supplies:

  • supported filename extensions and a display name;
  • thumbnail extraction;
  • embedded-preview extraction;
  • AF focus-location parsing;
  • a readable label for compression codes;
  • camera-specific megapixel thresholds for S, M, and L size classes.

Conformers are stateless enums. RawFormatRegistry.all currently registers:

ConformerExtensionVendor responsibilities
SonyRawFormat.arwSony extractors, MakerNote parser, compression labels, body thresholds, and full sensor JPEG creation
NikonRawFormat.nefNikon extractors, MakerNote parser, compression labels, and body thresholds
DNGRawFormat.dngDNG TIFF/SubIFD parser, extractors, compression labels, and generic/camera-family thresholds

format(for:) lowercases a URL’s extension and returns a format metatype. Callers invoke static protocol requirements on that value without switching on brands.

The default rawSizeClass implementation converts dimensions to megapixels, obtains body-specific L and M thresholds, and returns L, M, or S. Unknown bodies use a generic fallback supplied by the conformer.

This is a simple plugin architecture inside the package. Adding a camera brand means adding a conformer and registering it, not adding vendor switches throughout the loader.

4. RawImageLoader Is The High-Level Facade

RawImageLoader.shared is an actor. It offers four current operations:

APIResult
thumbnail(for:maxPixelSize:)An NSImage suitable for grids and browsers
thumbnailCGImage(for:maxPixelSize:)The same thumbnail as CGImage
previewImage(for:)A larger sidecar or embedded preview
metadata(for:)A neutral RawImageMetadata snapshot

4.1 Deduplicate Equivalent Work

The actor stores in-flight tasks:

  • thumbnails keyed by URL and requested pixel size;
  • previews keyed by URL;
  • metadata keyed by URL.

If another caller requests the same work while it is running, both await the existing task. The entry is removed after completion. This prevents rapid view updates from decoding the same large image repeatedly.

4.2 Bound Expensive Decodes

The facade uses two DecodeConcurrencyLimiter actors:

  • up to six concurrent thumbnail decodes;
  • up to two concurrent full-size preview decodes.

These limits control memory as much as CPU. A few full-resolution bitmaps can consume substantially more memory than the compressed RAW files that produced them.

4.3 Follow The Thumbnail Strategy

For a rendered JPEG, PNG, or TIFF, the loader asks ImageIO for an orientation-aware thumbnail. For RAW input, it tries an embedded ImageIO thumbnail first and then dispatches to the registered vendor extractor. The vendor result is orientation-normalized before it becomes an NSImage.

4.4 Follow The Preview Strategy

The preview path checks for a same-basename .jpg sidecar first. If absent, it tries an orientation-aware embedded preview and then the registered format’s embedded-preview extractor. Vendor output is normalized using the source orientation.

The sidecar-first decision is host-facing convenience, not RAW parsing. A caller that requires only bytes physically embedded in the RAW can call the format or extractor API directly.

5. Metadata Is Normalized Into A Neutral Snapshot

RawImageMetadata contains optional display and numeric values for camera, lens, shutter speed, exposure time in seconds, aperture, focal length in millimeters, ISO, exposure compensation in EV, capture time, dimensions, focus point, RAW compression label, size class, and pixel dimensions.

RawImageLoader.metadata(for:) combines several sources:

  1. ImageIO properties from the source or a sidecar fallback;
  2. TIFF make, model, compression, and display-date fields;
  3. EXIF exposure time, aperture, focal length, ISO, exposure bias, lens, and dimensions;
  4. EXIF DateTimeOriginal, SubsecTimeOriginal, and OffsetTimeOriginal;
  5. the registered vendor MakerNote parser for an AF point;
  6. EXIF subject-area coordinates when vendor focus data is unavailable;
  7. vendor-specific compression labels and size-class thresholds.

captureDate parses the original capture timestamp as a real Date, preserving variable-length fractional seconds. OffsetTimeOriginal accepts Z, +HH:MM, -HH:MM, and compact +HHMM/-HHMM forms; the parsed offset is also retained as captureTimeZoneOffsetSeconds. When the EXIF offset is missing, parsing uses the current time zone. A missing or invalid DateTimeOriginal leaves captureDate nil rather than substituting the TIFF display date.

capturedAt remains a display string and can fall back to TIFF DateTime. Keeping it separate from captureDate prevents formatted UI text from becoming burst-ordering evidence.

rows returns non-empty display label/value pairs, while isEmpty lets the facade omit an empty metadata object. Numeric exposure time, aperture, focal length, ISO, exposure compensation, width, and height remain available so hosts do not have to parse formatted strings for analysis or domain rules.

RawFocusPoint stores normalized X and Y coordinates. Its failable focus-string initializer accepts the common "width height x y" shape, checks positive dimensions, and rejects coordinates outside 0...1.

RawCull’s RawParserKitImageLoader maps this parser-owned snapshot into its own ExifMetadata and RawCullFileItem values. ScanFiles carries the parsed capture instant and offset into the catalog; RawCullCore can then prefer camera time and explicitly detect a modification-date fallback. The similar types exist on purpose: each package owns the vocabulary at its boundary and neither must depend on the other.

6. Thumbnail Extraction Prefers Embedded Work

Thumbnails should not require full RAW development when a camera already stored a usable JPEG.

6.1 Sony

SonyThumbnailExtractor first asks SonyMakerNoteParser for embedded JPEG locations and decodes a selected JPEG directly. This bypasses macOS RAW decoder failures seen with newer ARW layouts. If the binary path cannot locate a JPEG, it falls back to ImageIO’s embedded-thumbnail behavior.

6.2 Nikon

NikonThumbnailExtractor asks ImageIO for a transformed embedded thumbnail. Both vendor extractors then redraw into an 8-bit premultiplied sRGB bitmap using interpolation quality derived from qualityCost.

6.3 DNG

DNGThumbnailExtractor follows the same cancellation-aware contract. Its binary fallback uses DNGMakerNoteParser and TIFF IFD/SubIFD classification to avoid treating JPEG-compressed raw image data as a display preview.

Both APIs run their synchronous ImageIO work through CancellableImageIOWork and throw ThumbnailError for an invalid source, failed generation, or failed bitmap context.

ThumbnailSharpener is an optional lower-level Core Image helper for producing a sharpened preview at a requested maximum dimension. The high-level boundary does not force sharpening on every caller.

7. Embedded Preview Extraction Has Two Paths

The three formats use the same building blocks in a different order. SonyEmbeddedJPEGExtractor prefers the binary TIFF locator, avoiding RAW decoder initialization on affected ARW files, then falls back to ImageIO. NikonEmbeddedJPEGExtractor inspects ImageIO sub-images first and uses the binary locator when the preview is not exposed there.

flowchart TD
    Source["RAW URL"] --> ImageIO["Inspect ImageIO image indexes"]
    Source --> Parser["Vendor TIFF parser"]
    ImageIO -->|usable JPEG| Decode["Decode or downsample"]
    Parser --> Offset["Absolute JPEG offset + length"]
    Offset --> Bytes["Read JPEG bytes"]
    Bytes --> Decode
    Decode --> Result["CGImage"]

fullSize: true permits a longest edge up to 8640 pixels. The normal preview path limits large images to 4320 pixels.

The Nikon fallback prefers the full-resolution SubIFD preview for full-size requests and IFD1 for smaller requests. Sony chooses the largest available JPEG first, with preview and thumbnail fallbacks.

DNG prefers standards-classified preview IFDs using NewSubFileType and Compression; files that omit NewSubFileType retain the positional fallback needed by older or nonconforming writers.

Extractor-level limiters default to two concurrent operations, and a caller can inject a shared limiter. This allows a host facade to enforce one budget across several decode paths instead of accidentally stacking independent limits.

8. Sony Full-Size JPEG Creation Is Different From Extraction

SonyRawFormat.createFullSizeJPEG(from:quality:) does not return a camera-embedded preview. SonyRAWJPEGCreator develops the ARW sensor data through macOS CIRAWFilter, renders it into sRGB, and encodes JPEG data.

Quality must be in 0...1. The operation can fail with:

  • invalidQuality;
  • unsupportedOrInvalidRAW when the installed macOS RAW decoder cannot develop that file;
  • encodingFailed.

This distinction matters in UI and caching. An embedded preview and a developed sensor image have different cost, pixels, appearance, and invalidation semantics even if both are JPEG-encoded at the end.

9. Sony MakerNote And TIFF Parsing

Sony ARW is TIFF-based. Focus parsing follows this structure:

TIFF IFD0
└── ExifIFD tag 0x8769
    └── MakerNote tag 0x927C
        └── Sony MakerNote IFD
            └── FocusLocation tag 0x2027
                (fallback: 0x204A)

The focus tag contains four unsigned 16-bit values: image width, image height, X, and Y. Sony MakerNote IFD offsets are interpreted as absolute file offsets.

The production parser uses a fast path and a fallback:

  • focus location reads the first 4 MB, then retries with the full file when necessary;
  • embedded-JPEG discovery reads the first 512 KB, then retries the full file when no locations were found.

The embedded locator walks TIFF IFDs and returns optional absolute locations for a small thumbnail, preview, and full JPEG. readEmbeddedJPEGData seeks directly to a validated location and reads its byte range.

The fast path keeps normal scans inexpensive; the full-file fallback supports bodies that place relevant TIFF structures near the end of the file.

10. Nikon MakerNote And TIFF Parsing

Nikon NEF is also TIFF-based, but modern Nikon Type-3 MakerNotes contain their own TIFF header:

TIFF IFD0
└── ExifIFD tag 0x8769
    └── MakerNote tag 0x927C
        ├── "Nikon\0" signature + version
        └── inner TIFF header
            └── Nikon IFD
                └── AFInfo2 tag 0x00B7

Offsets in the inner TIFF are relative to the MakerNote TIFF-header base, not the start of the NEF file. Keeping this offset rule inside the Nikon parser prevents a generic loader from acquiring vendor-specific exceptions.

For supported modern AFInfo2 layouts, the parser reads AF image dimensions, area position, and area size, and returns the same "width height x y" shape as Sony. The public shape lets all downstream code use one focus-point adapter.

Nikon embedded preview discovery examines Compression=6 SubIFDs referenced from IFD0 and the IFD1 JPEG interchange fields. It returns optional locations for the largest preview and IFD1 JPEG.

As on Sony, focus parsing starts with 4 MB and falls back to the full file. Embedded-location parsing uses a 1 MB fast path followed by a full-file retry when required.

10.1 DNG TIFF And SubIFD Parsing

DNG uses the same neutral focus-location string but has no single camera-vendor MakerNote layout. DNGMakerNoteParser walks TIFF IFD0 and SubIFDs, uses standard EXIF focus evidence when present, and exposes DNGEmbeddedJPEGLocations with thumbnail, preview, and full-JPEG candidates. Standards-classified previews are selected from TIFF NewSubFileType and Compression values; positional rules are used only when the classification tag is absent.

DNGRawFormat reports container-appropriate compression names for uncompressed, JPEG, Deflate, PackBits, Lossy DNG, and JPEG XL values. Its size-class policy is megapixel-based with small camera-family overrides because DNG is a cross-vendor container rather than a single body line.

11. Diagnostics Report The Failed Stage

The ordinary parser APIs return optionals because missing or unsupported MakerNote data is expected during normal browsing.

For troubleshooting, each vendor also exposes diagnostic forms for focus and embedded-JPEG lookup. RawParserDiagnostics<Value> contains:

  • the optional parsed value;
  • an ordered trace of stages and offsets checked;
  • an optional final failure explanation.

This keeps logging policy outside the binary parser while allowing RawCull’s diagnostics UI to show whether failure occurred at file access, TIFF validation, IFD lookup, MakerNote traversal, tag interpretation, or fallback.

12. Orientation Helpers Normalize Visual Coordinates

OrientationNormalizedImageLoader provides lower-level operations for rendered URLs, encoded JPEG data, source thumbnails, embedded thumbnails, and embedded previews.

ImageIO’s transform option is used when available. The loader also implements the eight EXIF orientation transforms, including mirrored and transposed cases, and can read orientation from the RAW source when decoding separately extracted JPEG data.

SupportedFileType enumerates .arw, .nef, .jpeg, .jpg, .png, .tif, and .tiff. Its rendered-image set distinguishes sources that can be loaded directly from formats that need RAW dispatch.

Orientation is part of the parser boundary because AF coordinates and subject analysis must refer to the same visual image the user sees.

13. Cancellation And Decode Limiting Solve Different Problems

CancellableImageIOWork bridges a synchronous ImageIO closure to async code on a global dispatch queue. It creates an ImageIOCancellationToken and uses a locked state machine to ensure the checked continuation is resumed exactly once, even when cancellation races completion.

Cancellation is cooperative. The token is checked before and after synchronous framework calls and between multi-stage loops. A framework function already executing may not stop internally, but its result is discarded when cancellation is observed.

DecodeConcurrencyLimiter is an actor that solves admission control. It:

  1. grants work immediately while slots are available;
  2. queues additional continuations;
  3. removes and resumes a cancelled waiter;
  4. transfers a released slot directly to the next waiter;
  5. releases the slot with defer when work completes.

Cancellation prevents obsolete work; limiting prevents too much valid work from running simultaneously. The loader needs both.

14. RawCull Adapter And Image Ownership

RawCull depends on its own RawImageLoading: Sendable protocol. The RawParserKitImageLoader value forwards to RawImageLoader.shared and performs the package-to-app translation:

RawCull requestPackage facade callBoundary result
fileMetadata(for:)metadata(for:)RawImageMetadata becomes app ExifMetadata, capture date/offset, legacy focus string, and normalized CGPoint
thumbnailCGImage(for:maxPixelSize:)thumbnailCGImage(for:maxPixelSize:)CGImage for cache and analysis paths
thumbnailImage(for:maxPixelSize:)thumbnail(for:maxPixelSize:)NSImage consumed by app/UI-isolated code
previewCGImage(for:)previewImage(for:)CGImage for the preview and analysis pipeline

App code should enter through this facade or the vendor-neutral registry. Sony and Nikon conformers remain implementation details except in diagnostics and package tests.

NSImage and CGImage are framework reference objects rather than ordinary Sendable values. RawCull therefore keeps their lifetime inside the actor or UI operation that needs them. RequestThumbnail converts a CGImage to JPEG Data inside its actor before starting the detached disk save; the value crossing that task boundary is Data, not the image object. Prefer the CGImage facade methods for background analysis and convert to presentation objects at the presentation boundary.

15. Compatibility APIs Support Staged Migration

The package retains deprecated names such as:

  • BrowserExifInfo and BrowserFocusPoint;
  • thumbnail200px, extractembeddedJPG, and exifInfo;
  • JPGSonyARWExtractor and JPGNikonNEFExtractor;
  • extractFullJPEG on RawFormat.

Each shim forwards to a current neutral name. This lets RawCull migrate call sites without forcing an all-at-once source break, while deprecation warnings make the intended direction visible.

New code should use RawImageMetadata, RawFocusPoint, thumbnail, previewImage, metadata, the embedded-JPEG extractors, and extractEmbeddedPreview.

16. Test Binary Rules Without Shipping Camera Files

Tests/RawParserKitTests/ uses Swift Testing and mostly synthetic TIFF-like byte buffers. The suite covers:

  • registry extension matching and dispatch;
  • Sony focus tags, offset rules, invalid byte-order markers, fallback tags, embedded JPEG locations, and diagnostics;
  • Nikon Type-3 MakerNote and AFInfo2 layouts, SubIFDs, IFD1 JPEGs, offset rules, and diagnostics;
  • DNG TIFF/SubIFD classification, focus and embedded-JPEG locations, compression labels, size classes, and malformed-data behavior;
  • direct reading of embedded JPEG bytes;
  • cancellation before decode and cancellation behavior in vendor extractors;
  • decode-limiter capacity;
  • Sony full-size JPEG quality validation and generated JPEG properties;
  • numeric exposure-time, focal-length, aperture, ISO, and exposure-compensation metadata;
  • capture-date offsets, subsecond precision, invalid-date behavior, and offset parsing;
  • current public naming and format-helper behavior.

Synthetic binary fixtures make edge cases reproducible and avoid committing large proprietary ARW, NEF, and DNG samples. Framework integration is tested with small generated images where needed.

17. How To Add Another Camera Vendor

Use the existing extension points:

  1. Add a stateless RawFormat conformer with its extension and display name.
  2. Implement vendor-specific thumbnail, preview, focus, compression, and size-class behavior.
  3. Put TIFF or MakerNote byte rules in a dedicated parser, including explicit offset bases and bounds checks.
  4. Return the common normalized focus-location string at the public boundary.
  5. Add ImageIO behavior first and a binary embedded-JPEG fallback when the framework does not expose the preview reliably.
  6. Make blocking decode stages cooperative with CancellableImageIOWork.
  7. Register the conformer in RawFormatRegistry.all.
  8. Add synthetic binary tests for endian, offsets, missing tags, corrupt lengths, and diagnostics.
  9. Leave analysis, cache placement, and UI policy in their owning layers.

Source Map

TopicRawParserKit source
Product and concurrency settingsPackage.swift
Format contract and dispatchSources/RawParserKit/RawFormat.swift, RawFormatRegistry.swift
Format conformersSources/RawParserKit/SonyRawFormat.swift, NikonRawFormat.swift, DNGRawFormat.swift
High-level facadeSources/RawParserKit/RawImageLoader.swift
Metadata and focus valuesSources/RawParserKit/BrowserExifInfo.swift, BrowserFocusPoint.swift
Sony TIFF and MakerNote parsingSources/RawParserKit/SonyMakerNoteParser.swift
Nikon TIFF and MakerNote parsingSources/RawParserKit/NikonMakerNoteParser.swift
DNG TIFF and preview parsingSources/RawParserKit/DNGMakerNoteParser.swift
Embedded preview extractionJPGSonyARWExtractor.swift, JPGNikonNEFExtractor.swift, DNEmbeddedJPEGExtractor.swift
Thumbnail extractionSonyThumbnailExtractor.swift, NikonThumbnailExtractor.swift, DNGThumbnailExtractor.swift
Full Sony sensor developmentSources/RawParserKit/SonyRAWJPEGCreator.swift
Orientation and rendered filesSources/RawParserKit/OrientationNormalizedImageLoader.swift
Cancellation bridgeSources/RawParserKit/CancellableImageIOWork.swift
Decode admission controlSources/RawParserKit/DecodeConcurrencyLimiter.swift
Parser diagnosticsSources/RawParserKit/RawParserDiagnostics.swift
Behavior and binary-fixture testsTests/RawParserKitTests/
RawCull metadata adapter and catalog scanRawCull/Model/RawImageLoading.swift, RawCull/Actors/ScanFiles.swift

Continue from decoded images into How PhotoAnalysisKit Is Constructed, or return to the package overview.

Version 1.3.1: explicit RAW 9 development

RawImageLoader.thumbnail(for:maxPixelSize:useRAW9:), thumbnailCGImage and previewImage(for:useRAW9:) accept an opt-in boolean, defaulting to false. The in-flight image key includes that flag, so an embedded-preview request does not coalesce with a RAW 9 request. Internal/RAWDecoder.swift selects version9, then version9DNG when available, and returns nil when neither can develop the file; callers preserve their existing embedded/sidecar fallback.

The renderer caps scale to the requested longest edge without upscaling and renders RGBA8 sRGB. CIRAWFilter applies source orientation. Its detached render checks cancellation before and after work; cancellation does not interrupt a framework call already executing. See Tests/RawParserKitTests/RAWDecoderTests.swift. In RawCull, Model/RawImageLoading.swift adapts these APIs and retains catalog access. Embedded export deliberately uses EmbeddedJPGExportLoader.swift rather than this display-oriented facade.

Version 1.3.2: generic macOS-backed RAW formats

The delta from 1.3.1 adds GenericRawFormat, GenericRawThumbnailExtractor and GenericEmbeddedPreviewExtractor, registers the generic conformer and adds registry/preview tests. It does not replace the dedicated Sony, Nikon or DNG parsers explained above. The current manifest is Package.swift.

GenericRawFormat admits the explicit extension set in GenericRawFormat.swift. Metadata can fall back to EXIF SubjectArea, but no new vendor MakerNote parser is provided. Thumbnail work uses the existing cancellation-aware ImageIO bridge; preview work has a two-operation limiter and selects ImageIO-exposed JPEG candidates without a binary vendor fallback. Orientation is applied at the facade boundary after generic preview extraction.

Read RAW Formats and Exposure Inspection for the full call sequence, pixel limits, extension list and display/export distinction. Current tests are RawFormatRegistryTests.swift and GenericEmbeddedPreviewExtractorTests.swift. Adding an extension is not sufficient evidence for a camera-support promise; qualify a real file on the intended macOS decoder.

Current preload-save boundary is app-owned

RawCull preload returns encoded JPEG data to its bounded worker, which releases the file’s grid gate, awaits saving, then returns its slot. Each preload group bounds pending saves and retains its catalog grant through completion. Interactive saving is unchanged. RawParserKit’s decode limiter, coalescing and public thumbnail APIs remain unchanged by this host-side change. Version 1.3.3 changes executor placement as described below.

Version 1.3.3: bounded concurrent thumbnail execution

The app now pins 26df4abc2178d5c07d08f3883d84d0648f5141d3 (1.3.3). RawImageLoader.thumbnail calls a private static @concurrent decodeThumbnail inside the existing six-slot limiter. Admission alone did not move synchronous ImageIO work onto the concurrent executor under the package isolation settings. The slot stays held until decode returns. Request coalescing, priority, cancellation checks, fallback order, orientation and public APIs are preserved; full-size preview loading is unchanged. Synchronous decode remains non-preemptive between cancellation checks.

The package evaluation records 105 passing tests in each Debug/Release package suite and ARW throughput experiments. Paired host-application empty-cache cohorts improved; warm disk cohorts showed no established benefit. Those are separate package-evaluation observations, not a fresh RawCull whole-catalog speed or UI smoothness measurement.

November 8 Integration Review: Close-up Source Delivery

The app still resolves RawParserKit 1.3.3 at 26df4abc2178d5c07d08f3883d84d0648f5141d3. Adding PhotoEvidenceKit does not make the parser depend on a UI package. RawCull implements CloseUpRendering and supplies decoded pixels to the evidence engine.

Follow The Actual Host Renderer

BurstCloseUpRenderer in RawCull’s RawCull/Views/ComparisonGridView/BurstCloseUpsView.swift is the adapter:

  1. Retain catalog access for the requested file.
  2. Check the file revision and render-source descriptor before decoding.
  3. For developed RAW, call ZoomPreviewHandler.loadDevelopedRAWPreview; for a preview, call FullSizePreviewLoader.shared.loadEmbeddedPreview.
  4. Label the returned source as developed RAW/full-size JPEG, sidecar JPG preview, or embedded preview as appropriate.
  5. Check cancellation and both identities again before rasterizing the crop.

These are host pipelines, not new RawImageLoader public methods. A developed image may be labeled RAW 9 only when the decoder reports RAW 9 support. A sidecar preview’s modification changes the preview render descriptor independently of the RAW file revision. The adapter does not silently replace unavailable preview pixels with a different source class.

Separate Decode Limits From Raster Limits

The package’s DecodeConcurrencyLimiter queues work and transfers a released slot to the next waiter. Cancellation while waiting removes that waiter; native work already running remains subject to cooperative cancellation behavior. In 1.3.3, thumbnail work runs on the concurrent executor under its existing bounded policy.

RawCull’s close-up renderer additionally serializes its own render tasks across actor suspension. PhotoEvidenceKit bounds returned crop/overview buffers, but it does not cap the memory needed to decode the full source. Audit thumbnail, full-preview and close-up concurrency together when assessing peak image memory.

Map AF Coordinates Once At The Host Boundary

The host reads EXIF orientation and maps sensor-normalized AF positions through all eight orientation cases into canonical top-left, x-right, y-down coordinates. Invalid points or unavailable orientation produce unavailable AF assistance. Do not pass sensor coordinates directly to a close-up whose pixels are already orientation-corrected, or apply orientation normalization a second time.

A close-up source change invalidates displayed pixels; a file-revision change also invalidates saved source-bound regions and stale AF targets. This distinction allows preview/development toggles to preserve a photographer’s manual region.

6 - How PhotoEvidenceKit Is Constructed

PhotoEvidenceKit contracts, close-up geometry, bounded rendering, retained references, region persistence, AF assistance, and RawCull integration.

How PhotoEvidenceKit Is Constructed

November 8 baseline: RawCull resolved PhotoEvidenceKit 1.0.7 at 7614fd1528bb7cf2549799fb937678ea39d90228. This guide reviews that source and the RawCull 3.4.0 build 434 integration on November 8, 2026. The package README and changelog still use initial/unreleased wording; the lockfile records that historical remote version.

PhotoEvidenceKit on GitHub is a reusable manual image-inspection package. It lets a photographer compare selected regions, retain a reference while navigating, and inspect crops with explicit pixel-source attribution. It was extracted from RawBrowse and preserves the original MIT attribution.

The package requires Swift tools 6.2, Swift 6 language mode, and macOS 26 or newer. It has no external package dependencies, bundled photo assets or model downloads.

Repository references: README, package manifest, and MIT license.

1. Products And Dependency Direction

ProductResponsibility
PhotoEvidenceContractsSendable frames, regions, viewports, requests, render-source descriptors, coordinate transforms and AF targets; main-actor region-store protocol
PhotoEvidenceEnginePure crop geometry, bounded rasterization, render results, errors and asynchronous rendering protocol
PhotoEvidenceUIEmbeddable SwiftUI panel and observable comparison-session model
PhotoEvidenceDemoExecutable example using synthetic portrait/landscape fixtures and public APIs
flowchart TD
    Host["RawCull host adapters"] --> UI["PhotoEvidenceUI"]
    Host --> Engine["PhotoEvidenceEngine"]
    Host --> Contracts["PhotoEvidenceContracts"]
    UI --> Engine
    UI --> Contracts
    Engine --> Contracts
    Host --> Decode["Host preview / RAW pipelines"]
    Host --> Store["Host region storage"]

No product imports RawCull, RawBrowse, RawParserKit, PhotoAnalysisKit, PhotoAIKit, or RawCullCore. Contracts contain no SwiftUI views or image buffers. The engine has no filesystem access, model inference or application file model.

The host owns file permissions, image loading, cache/concurrency policy, comparison membership, active selection, ratings and review decisions. The package does not identify subjects, track eyes or animals, score sharpness, choose winners or write XMP. Comparing several crops is an inspection activity, not an automatically calibrated measurement.

2. Separate File Identity From Render Identity

CloseUpFrame contains a stable URL id, a display name, and a host-supplied revision. The revision must remain stable across launches for an unchanged source and change when the source changes. A random session token would defeat saved-region reuse.

CloseUpRenderSource independently describes the pixels requested for display:

FieldMeaning
kindunspecified, original, embeddedPreview, or developedRAW
backendIDStable identifier for the host rendering pipeline
revisionSettings/source token that changes whenever that pipeline’s pixels can change

A preview/developed-RAW toggle changes the render descriptor without changing the file revision or the saved manual region. Development settings, crop, straightening, bit depth and color-pipeline changes should also revise the rendering token. The .unspecified default supports hosts with a single fixed pipeline.

A CloseUpRequest combines frame, region, scale mode, display scale, viewport, viewport size and render source. The renderer must honor the source and scale or fail. Returning a different source with the requested label would break the inspection contract.

3. Manual Regions And Coordinate Spaces

CloseUpRegion uses canonical orientation-corrected image coordinates: origin at the top left, x to the right, y downward. Its default center is (0.5, 0.5) and its default fraction is 0.25. Bounds clamp the fraction to 0.05...1 and keep the region within the image. Nonfinite values receive finite defaults.

The fraction applies independently to normalized width and height, so a region covering one quarter of each dimension in a landscape image is not necessarily a square in source pixels. pixelBounds(width:height:) expands to integral pixel bounds and intersects the source extent. The normalized representation is used for persistence and geometry.

CloseUpViewport represents temporary inspection around a frame’s own region. Its offset is measured in region fractions, not full-image fractions. Normalization limits each offset component to -4...4 and zoom to 0.25...8.

CloseUpCoordinateTransform maps canonical normalized coordinates into the actual rendered image, including developed crop/straightening. It must be finite and invertible. Supply the real transform when rendered pixels differ geometrically from the canonical source; identity is appropriate only when those spaces agree. Inverse mapping supports overview interactions back into canonical coordinates.

4. Fit Region And Source-Pixel Scale

CloseUpScaleMode.fitRegion fits the requested inspection region to the viewport. sourcePixels uses zoom in display points per source pixel; zoom 1 means one source pixel per display point. On a high-density display this is distinct from one source pixel per physical screen pixel. Display scale controls raster output resolution separately.

Requests default to a 280 × 210-point viewport. Viewport dimensions are normalized to 1...4096 and display scale to 1...4. The panel is 304 points wide and can be embedded on either side of a host workspace; placement belongs to the host.

The engine’s crop geometry computes bounds for the selected mode, viewport and transform. A region outside a developed crop yields regionOutsideRender rather than an unrelated fallback image.

5. Rendering And Memory Ownership

CloseUpRendering is a Sendable asynchronous provider with render(_:) async throws -> CloseUpRender. The host implements decoding and calls CloseUpRasterizer.render off the UI actor. Rasterization itself is synchronous.

A render returns independently owned crop and overview CGImage buffers, source width/height, a truthful source label, displayed bounds, render-source identity and the coordinate transform used. The rasterizer checks cancellation before and after work. Its maximum artifact dimension is derived from the larger viewport dimension multiplied by display scale, and it does not upscale a source.

The rasterizer redraws both artifacts into new 8-bit premultiplied RGB buffers. This matters because a CGImage crop alone can retain the whole decoded source. Bounded artifacts avoid that accidental ownership, but decoding a full-resolution source can still allocate a large transient image. Host decode concurrency and cache eviction remain necessary.

Failure And Stale-Result Handling

Error/stateMeaning
unavailableRequested pixels or raster buffers could not be produced
sourceChangedHost detected a changed file or render source
renderMismatchReturned source identity, dimensions or transform failed validation
regionOutsideRenderRequested canonical region cannot produce a valid developed crop
Cancelled/older generationCard ignores completion instead of publishing obsolete pixels

The card model increments a generation for each load. It validates the returned render descriptor, positive source dimensions and valid transform before displaying a result. It clears old pixels on frame/source changes; during region editing it can keep the overview mounted so an active drag is not destroyed by its own load. Releasing an offscreen card invalidates its generation and releases artifacts.

The UI cannot verify file contents from an opaque result alone. The host must check file/source revision before and after decoding as RawCull’s adapter does.

6. Comparison Session And Retained References

CloseUpModel is a main-actor observable session model. updateFrames deduplicates selected frames by URL and refreshes state for changed revisions. comparisonFrames places the reference first and includes it only once even if it is also selected.

pin, replacement by another pin, and unpin affect inspection state only. A reference survives removal from host selection. updateReference refreshes its metadata/revision without adding it back to selection. The host must continue supplying render-source and AF information for that retained reference.

Regions remain independent per frame. setLinked shares relative viewport offsets and zoom around each frame’s existing region; it does not copy one frame’s region onto another or establish subject correspondence. resetViews resets temporary viewports, while resetRegion restores a frame’s default manual region.

Current-frame labels and the optional activation callback let the host distinguish inspection membership from active review selection. Activation, rating changes and winner selection remain explicit host actions.

7. Region Persistence And Retry

Inject CloseUpRegionStoring into CloseUpModel to make regions durable. Its load(for:) and save(_:) methods are synchronous main-actor operations, so use fast preference-sized storage or an already hydrated repository.

CloseUpRegionRecord stores schema version 1, source URL, source revision and a normalized region. Loading accepts a record only when schema, URL and revision match. Crops, overview buffers, model output and temporary pan/zoom are not part of that record.

Without an injected store, regions live only in the current/pinned working set. Inactive state is trimmed. Failed saves are retained as pending records and expose persistenceFailure; retrySaving retries them and can retry failed loads. Pending choices remain available for retry even after leaving the active selection.

RawCull’s BurstCloseUpRegionStore encodes records as JSON in UserDefaults. Keys use the PhotoEvidenceKit.ManualRegion.v1. prefix plus a SHA-256 hash of the standardized URL string. The stored record performs source-revision validation; the key alone is not enough to establish freshness.

8. Recorded AF-Point Assistance

The panel accepts an afPoints dictionary keyed by frame URL. Omitting an entry hides assistance; .unavailable(reason:) displays a disabled action with an explanation. .available(CloseUpAFPoint) supplies a frame/revision-bound target. The target’s failable initializer rejects nonfinite and out-of-range coordinates.

The host decodes camera AF metadata, resolves any active-point ambiguity and maps orientation into canonical coordinates. A target from an obsolete frame revision is disabled/rejected. Supply entries for a retained reference as well as selected frames, and refresh them when metadata changes.

There are two related behaviors in 1.0.7:

  • useAFPoint(_:) performs one placement for one active frame. It preserves region size, viewport and linking, and persists through the normal store. Existing pan can still offset the displayed view.
  • usesAFPoint is a session preference. When enabled, updating frames or AF entries reapplies valid AF centers and clears displaced viewport offsets. Linked viewport propagation still follows the model’s normal linked behavior.

Both operate on manual regions and neither establishes focus quality or tracks a subject. The region remains editable. RawCull synchronizes this preference with its AF overlay state in the burst workspace.

9. RawCull Integration

RawCull/Views/ComparisonGridView/BurstCloseUpsView.swift defines the adapters:

TypeResponsibility
BurstCloseUpIdentityFile revision from standardized URL, size, modification time and inode; separate preview/RAW render descriptors
BurstCloseUpRendererRetain catalog access, serialize rendering, decode the requested source, validate identities twice and rasterize
BurstCloseUpRegionStorePersist source-bound region records in UserDefaults
BurstCloseUpAFPointRead EXIF orientation and map all eight orientation cases
BurstCloseUpSelectionPlain selection, command-toggle and shift-range comparison membership
BurstCloseUpsViewAssemble frames, render sources, retained-reference metadata, AF availability and host callbacks

The preview pipeline uses FullSizePreviewLoader; the RAW pipeline uses ZoomPreviewHandler.loadDevelopedRAWPreview. Source labels distinguish sidecar JPG, embedded preview, and developed RAW/full-size JPEG, including RAW 9 when supported. The preview descriptor includes sidecar identity so a changed sidecar can rerender without resetting a manual region bound to the RAW source.

BurstCullingWorkspaceView owns panel visibility, the model, renderer and comparison membership. The package has no knowledge of the app’s ranking results, rsync transfers, rating persistence or selected winner.

Detected crops in the local integration

The November 9 development build uses the sibling ../PhotoEvidenceKit checkout. RawCull’s BurstDetectedFacesView supplies normalized rectangles to DetectedFaceRasterizer, which adds context and clips the crop to the upright preview. The app obtains human face rectangles from PhotoAnalysisKit and derives animal head and eye rectangles from Vision landmarks in AnimalCloseUpDetector. These tiles sit above the manual CloseUpPanel and have no region records of their own.

See using Close Up for the source picker, manual regions and detected tiles.

10. Tests And Qualification

Run package checks from the PhotoEvidenceKit repository:

swift test
swift build -c release
swift run PhotoEvidenceDemo

The synthetic demo exercises the exported APIs without importing a host app. Package tests cover regions/geometry, AF validation, pin/replace/unpin, independent and linked viewports, saved-record revision checks, persistence retry, render-source changes, coordinate transforms and cancelled/out-of-order providers. RawCull’s RawCullTests/BurstCloseUpTests.swift additionally covers AF orientation, comparison selection, persisted regions and preview-versus-file source identity.

For host qualification, inspect portrait/mirrored sources, previews smaller than the requested viewport, mixed source classes, a retained deselected reference, rapid selection changes, source/settings changes during decoding, persistence failures and peak memory during full-resolution loads. The package tests establish contract behavior; they do not measure a host decoder’s cold/warm latency or memory budget.

Changes at 1.1.5

Source-pixel zoom 1 now maps a source pixel to one physical display pixel at the active display scale. Detected-face crops are redrawn into bounded, owned buffers. The earlier geometry walkthrough describes the original 1.0.7 implementation.

Source Map

Paths below belong to the PhotoEvidenceKit repository at the reviewed revision:

TopicPhotoEvidenceKit source
Products, platform and dependency graphPackage.swift
Frame, region, request, viewport and storage contractsSources/PhotoEvidenceContracts/CloseUpContracts.swift
Render identity and affine coordinate transformSources/PhotoEvidenceContracts/CloseUpRenderSource.swift
Validated AF targets and availabilitySources/PhotoEvidenceContracts/CloseUpAFPoint.swift
Fit/source-pixel bounds and coordinate mappingSources/PhotoEvidenceEngine/CloseUpCropGeometry.swift
Owned bounded raster buffersSources/PhotoEvidenceEngine/CloseUpRasterizer.swift
Async provider, result and error contractsSources/PhotoEvidenceEngine/CloseUpRendering.swift
Reference, regions, AF session preference, linked inspection and retrySources/PhotoEvidenceUI/CloseUpModel.swift
Generation checks, result validation and releaseSources/PhotoEvidenceUI/CloseUpCardModel.swift
Embedding API and controlsSources/PhotoEvidenceUI/CloseUpPanel.swift
Synthetic public-contract testsTests/PhotoEvidenceKitTests/

Continue with RawParserKit for decoding, PhotoAnalysisKit for measurements, RawCullCore for recommendations, and PhotoAIKit for optional inference workflows.

Build 466 resolves PhotoEvidenceKit 1.1.5 at e49d34adcfa2e2c43a4240c2e962dbe9defa4cad over HTTPS. This is the same source revision as build 462. Application lockfile