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.


Last modified November 24, 2026: update (c1748b4)