Accepted PDF import, quiet review, editable restaurant prefill and confirmed meal deletion.
34 XCTest +439 Swift Testing cases passed at c67b012060b4ff4cddca2950bbdb7788e94575ff.
108 host package cases; lint/config/boundary/startup isolation passed. Actual deletion Cancel/Delete/list/relaunch UI passed. No private receipts or screenshots in the diff.
No coverage percentage is claimed. Automated JUnit runner detection does not cover this nested Xcode project; actual .xcresult and host logs remain the evidence.
Ready to push
Four independent pre-push reviews are clear after the provider-budget correction. Exact committed source passed 473 native cases;108 host package cases passed. Final PR review and merge gates remain separate.
### What changed Share one PDF receipt to Foodnotes or choose Import PDF receipt from Files. Foodnotes keeps the original, reads its pages locally and fills an editable meal. Check the restaurant, dishes, quantities and prices before saving. Prices are GST-inclusive per item when the receipt supplies a clear basis. Unknown details remain editable rather than invented. ### Why it matters Screenshots are unnecessary and the source stays available from review and saved meals. The normal screens show the meal instead of processing traces; Settings → Display → Debug information reveals those traces when needed. Delete meal asks for confirmation and removes only the chosen visit. Cancel keeps it. ### Key concepts An original is the unchanged receipt, separate from food photos. Provenance records which receipt evidence supported a field. A deletion tombstone is a retained “removed” marker that keeps synchronised copies from making a deleted meal reappear.
### Changes overview The share extension and Files route converge on durable original admission. PDFKit selectable text and bounded Vision OCR feed page/row evidence into the existing validated extraction/review engine. PDF provenance survives draft save, typed transport, strict versioned archives and readable export. Existing image flows remain supported. ### Implementation approach Admission limits one receipt to 32 MiB and 20 pages, bounds alias verification to four PDF attachment providers before loading any, preserves bytes and rechecks identity. Geometry-aware row assembly separates table descriptions, quantities, GST and net amounts; declared merchant metadata remains separate from item rows. The deterministic table path derives gross unit cents from evidenced row net/GST and quantity, preserving calculation metadata. Model work is local and bounded; omission remains visible and manually recoverable. Draft edit versions, source/generation checks and canonical row identities protect user corrections and retries. Deletion reuses Meal.isPresent and the ordinary revision-checked replaceDocument/outbox transaction. App session/document/write guards protect the selected visit; the native destructive alert supplies explicit Delete and Cancel. Snapshot refresh removes inaccessible detail routes. Original/file references and shared place/dish profiles are retained under existing lifetime rules, so deletion adds no ad hoc cleanup. ### Trade-offs Bounded extraction can require manual completion. It does not guarantee every receipt layout is understood. Restaurant text is prefilled but does not guess a saved-place identity; explicit selections remain authoritative. Debug preference changes presentation, not stored provenance. Tombstones keep sync metadata and immutable originals rather than promising immediate disk-space reclamation.
### Technical detail Input publication is atomic and owned before handoff. Account and destination identity remain explicit. Raster dimensions, page count, per-call evidence and document model work are bounded; synchronous validation/raster work runs away from the main actor, with cancellation checks between units. Evidence fields and optional integer-cent calculations use validated nested archive contracts. Rounding occurs at final per-item division; ambiguous bases, double-tax ambiguity and ungrounded order-fee allocation stay manual. ### Architecture impact No new backend, currency model, cloud OCR, photo-repair path or live-library migration is introduced. PDF envelopes/archives use their approved versioned compatibility policy. Meal deletion introduces no persisted field or wire command: the existing false-wins presence merge is published through existing cloud control records. Fetch additionally preserves a committed same-epoch tombstone after its local outbox has been acknowledged, preventing a later whole-record projection from resurrecting it. Epoch/library/partition separation and frozen-transfer restrictions remain intact. ### Potential issues and limits The owner accepted the installed PDF import; that acceptance does not identify every external share host or establish each CloudKit account combination. Simulator success alone cannot establish those results. Deletion is tested with synthetic repositories/transports and native simulator UI, without deleting anything on the phone. Old builds cannot fully read new PDF attachments under the approved updated-device prerequisite. Existing saved meals are not reparsed or rewritten automatically.
Foodnotes/SharedCapture/PDFHandoffInput.swift
Why it matters. One byte-exact receipt through share and Files, with bounded admission and provider work.
What to look at. PDFHandoffInput.prepare
Foodnotes/Foodnotes/Services/Capture/Extraction/PDFCaptureExtractor.swift
Why it matters. Native text and local OCR retain canonical identities and honest completeness across retries.
What to look at. PDFCaptureExtractor.events
Foodnotes/Packages/FoodnotesCore/Sources/FoodnotesDomain/ReceiptPriceCalculation.swift
Why it matters. Explicit row net/GST and quantity derive per-item cents with retained calculation provenance.
What to look at. ReceiptPriceCalculation.unitPriceCents
Foodnotes/Packages/FoodnotesCore/Sources/FoodnotesArchives/ArchiveValidation.swift
Why it matters. PDF source provenance survives validated archives and typed persistence.
What to look at. ArchiveValidation
Foodnotes/Foodnotes/Features/Settings/DebugInformation.swift
Why it matters. Default-off preference gates provenance in review and saved meals while originals/failures remain available.
What to look at. DebugInformationToggle
Foodnotes/Foodnotes/App/AppMealDeletion.swift
Why it matters. Native explicit confirmation and guarded existing transaction remove only the selected visit.
What to look at. AppDependencies.deleteMeal
Foodnotes/Foodnotes/Persistence/RepositoryCloudFetch.swift
Why it matters. Later same-epoch whole-record fetch cannot resurrect a committed deletion after outbox acknowledgement.
What to look at. StorageWriter.applyOpenControl
Retain original bytes,32MiB/20pages,20modelcalls and per-call evidence limits. Four-provider pre-load cap bounds alias verification.
GST-inclusive per-item price, quantity separate; use evidenced row tax and final half-up cent division, never ungrounded order fee allocation.
Reuse transactional presence tombstones and sync; preserve files/profiles and refuse stale/account/frozen mutations.
| Severity | Area | Finding | Resolution |
|---|---|---|---|
| major | PDF provider intake | Unbounded duplicate provider copies before byte deduplication. | Pre-load four-provider cap; actual-loader red/green and valid-alias regressions passed. |
| minor | Current-stage and evidence documentation | Stale merge-authority summary and external-host acceptance wording. | Current authority corrected; owner acceptance limited to known installed import. |
Source: local run at 2026-10-28T10:48:05.826365+11:00 · snapshot c67b012060b4ff4cddca2950bbdb7788e94575ff
Baseline: none
Execution: passed · JUnit: none · Coverage: none · Baseline: absent
Coverage scope: as the project configures it
The test runner could not be detected.
Derived by declaration name, from the diff (no baseline run).
Files that import a changed file on the left, changed files in the centre, files a changed file imports on the right. Snapshot working-tree against base 0128d2c0158fa69a754edceea31bb85a4d99e5c6.
123 files: 105 code · 18 docs. Click to expand.
diff --git a/Foodnotes/Config/FoodnotesShare-Info.plist b/Foodnotes/Config/FoodnotesShare-Info.plistindex 88be543..92f3852 100644--- a/Foodnotes/Config/FoodnotesShare-Info.plist+++ b/Foodnotes/Config/FoodnotesShare-Info.plist@@ -9,10 +9,7 @@ <key>NSExtensionAttributes</key> <dict> <key>NSExtensionActivationRule</key>- <dict>- <key>NSExtensionActivationSupportsImageWithMaxCount</key>- <integer>1</integer>- </dict>+ <string>SUBQUERY(extensionItems, $item, SUBQUERY($item.attachments, $attachment, ANY $attachment.registeredTypeIdentifiers UTI-CONFORMS-TO "com.adobe.pdf").@count > 0).@count > 0 OR SUBQUERY(extensionItems, $item, SUBQUERY($item.attachments, $attachment, ANY $attachment.registeredTypeIdentifiers UTI-CONFORMS-TO "public.image").@count == 1).@count == 1</string> </dict> <key>NSExtensionPointIdentifier</key> <string>com.apple.share-services</string>
diff --git a/Foodnotes/Foodnotes/App/AppCapture.swift b/Foodnotes/Foodnotes/App/AppCapture.swiftindex 4a47869..cb45f8e 100644--- a/Foodnotes/Foodnotes/App/AppCapture.swift+++ b/Foodnotes/Foodnotes/App/AppCapture.swift@@ -23,6 +23,7 @@ extension AppDependencies { captureUnassigned = [] captureDuplicates = [] captureDeferred = []+ captureCompatibility = [] if let session { for coordinator in [captureCoordinator, sharedCaptureCoordinator].compactMap({ $0 }) { Task {@@ -73,13 +74,15 @@ extension AppDependencies { guard self.session == session else { return } guard let result = try await scanCapture(coordinator, session: session, dinerID: diner.id, destination: destination, pendingSharedSetup: needsSetup) else { continue }- for id in result.unassigned.map(\.operationID) + result.duplicates.map(\.operationID) + result.deferred.map(\.operationID) {+ let pending = result.unassigned + result.deferred + result.compatibilityRequired+ for id in pending.map(\.operationID) + result.duplicates.map(\.operationID) { routes[id] = coordinator } combined.importedDraftIDs += result.importedDraftIDs combined.unassigned += result.unassigned combined.duplicates += result.duplicates combined.deferred += result.deferred+ combined.compatibilityRequired += result.compatibilityRequired } guard self.session == session else { return } captureInputRoutes = routes@@ -120,7 +123,7 @@ extension AppDependencies { } func beginCapture(_ route: CaptureRoute) async {- guard route == .camera || route == .photos, let session, !accountCommitInProgress else { return }+ guard route == .camera || route == .photos || route == .files, let session, !accountCommitInProgress else { return } let destination = defaultLibrary ?? .personal(accountID: session.accountID) let needsSetup = sharedSetupRequired(for: destination) await refreshCapture(openIncoming: false)@@ -132,18 +135,41 @@ extension AppDependencies { } func acceptCapture(_ url: URL, request: CaptureInputRequest, coordinator: CaptureInputCoordinator) async {- defer { try? FileManager.default.removeItem(at: url) }+ defer { if request.route != .files { try? FileManager.default.removeItem(at: url) } } guard !captureBusy else { return } captureBusy = true defer { if session == request.session { captureBusy = false } } do {- let result = try await coordinator.retain(url, request: request)+ let retained: URL+ if request.route == .files {+ let directory = await coordinator.directory.appendingPathComponent("OwnedFiles")+ retained = try await Task.detached { try PDFReceiptFilesInput.copy(url, directory: directory) }.value+ } else { retained = url }+ defer { if request.route == .files { try? FileManager.default.removeItem(at: retained) } }+ let result = try await coordinator.retain(retained, request: request) guard session == request.session else { return } await consumeCapture(result, session: request.session, openIncoming: true) await refreshCapture(openIncoming: false) } catch is CancellationError {} catch StorageError.staleSession {} catch { guard session == request.session else { return }- self.error = "We couldn’t open this image for review. Any published source is kept for this library. You can still type a meal."+ self.error = request.route == .files+ ? "Couldn’t open this PDF. Choose one unlocked PDF with 1–20 pages, no larger than 32 MiB. Your selected file is unchanged."+ : "We couldn’t open this image for review. Any published source is kept for this library. You can still type a meal."+ }+ }++ func acceptPDFCompatibility() async {+ guard let session else { return }+ do {+ for coordinator in [captureCoordinator, sharedCaptureCoordinator].compactMap({ $0 }) {+ let directory = await coordinator.directory+ try await Task.detached { try PDFCompatibilityAcknowledgement(directory: directory).accept() }.value+ guard self.session == session else { return }+ }+ await refreshCapture()+ } catch {+ guard self.session == session else { return }+ self.error = "Couldn’t keep the acknowledgement. Your PDF is still kept. Try again." } } @@ -185,6 +211,7 @@ extension AppDependencies { captureUnassigned = result.unassigned captureDuplicates = result.duplicates captureDeferred = result.deferred+ captureCompatibility = result.compatibilityRequired await refresh() guard self.session == session, openIncoming, editingDraft == nil, let id = result.importedDraftIDs.first, let draft = drafts.first(where: { $0.id == id }) else { return }
diff --git a/Foodnotes/Foodnotes/App/AppDependencies.swift b/Foodnotes/Foodnotes/App/AppDependencies.swiftindex 3605d08..83fc904 100644--- a/Foodnotes/Foodnotes/App/AppDependencies.swift+++ b/Foodnotes/Foodnotes/App/AppDependencies.swift@@ -30,6 +30,7 @@ final class AppDependencies { var captureReviews: [UUID: CaptureReviewModel] = [:] var captureUnassigned: [CaptureHandoff.SourceEnvelope] = [] var captureDuplicates: [HandoffDuplicate] = []+ var captureCompatibility: [CaptureHandoff.SourceEnvelope] = [] var captureDeferred: [CaptureHandoff.SourceEnvelope] = [] var captureBusy = false var captureShareUnavailable = false@@ -107,6 +108,7 @@ final class AppDependencies { self.lifecycle = lifecycle await lifecycle.resume() #if DEBUG+ try await PDFReceiptUIFixture.seed(self) if ThumbnailFramingFixture.enabled { try await ThumbnailFramingFixture.seed(self) } #endif } catch { self.error = "Couldn’t open your journal. \(error.localizedDescription)" }
diff --git a/Foodnotes/Foodnotes/App/AppLaunchContext.swift b/Foodnotes/Foodnotes/App/AppLaunchContext.swiftindex 3411846..6507e46 100644--- a/Foodnotes/Foodnotes/App/AppLaunchContext.swift+++ b/Foodnotes/Foodnotes/App/AppLaunchContext.swift@@ -14,7 +14,8 @@ nonisolated enum AppLaunchContext: Equatable { let testing = testRuntime || environment.keys.contains { $0.lowercased().hasPrefix("xctest") || $0.lowercased().hasPrefix("xcinject") } || environment["DYLD_INSERT_LIBRARIES"]?.lowercased().contains("xctest") == true- if arguments.contains("--service-diagnostics-fixture") || arguments.contains("--thumbnail-framing-fixture"),+ if arguments.contains("--service-diagnostics-fixture") || arguments.contains("--thumbnail-framing-fixture")+ || arguments.contains("--pdf-receipt-fixture"), !arguments.contains("--ui-testing") { return .blocked } if environment["XCODE_RUNNING_FOR_PREVIEWS"] == "1" { return .blocked } if arguments.contains("--ui-testing") || arguments.contains("--test-store") {
diff --git a/Foodnotes/Foodnotes/App/AppMealDeletion.swift b/Foodnotes/Foodnotes/App/AppMealDeletion.swiftnew file mode 100644index 0000000..eaf6c28--- /dev/null+++ b/Foodnotes/Foodnotes/App/AppMealDeletion.swift@@ -0,0 +1,27 @@+import FoodnotesDomain+import Foundation++@MainActor extension AppDependencies {+ /// Reuse the existing delete-wins presence field and ordinary transactional outbox.+ /// Originals and scoped profiles keep their existing reference/lifetime rules.+ @discardableResult+ func deleteMeal(_ original: MealDocument, session expected: AccountSession,+ confirmed: Bool, operationID: UUID = UUID()) async throws -> Bool {+ guard confirmed else { return false }+ guard session == expected, let repository, let snapshot, snapshot.session == expected else {+ throw StorageError.staleSession+ }+ guard document(id: original.meal.id, library: original.meal.libraryID) == original,+ !nonWritableMeals.contains(MealWriteKey(original.meal)) else { throw StorageError.revisionConflict }+ var removed = original+ var clock = PersistedClockState(milliseconds: 0, logicalCounter: 0)+ clock.observe(original)+ let stamp = try clock.tick(wallClockMilliseconds: Int64(Date().timeIntervalSince1970 * 1_000), replicaID: installationID)+ removed.meal.isPresent = Stamped(value: false, stamp: stamp)+ _ = try await repository.apply(.replaceDocument(removed, expectedRevision: snapshot.revision),+ operationID: operationID, session: expected)+ guard session == expected else { throw StorageError.staleSession }+ await refresh()+ return true+ }+}
diff --git a/Foodnotes/Foodnotes/App/PDFReceiptUIFixture.swift b/Foodnotes/Foodnotes/App/PDFReceiptUIFixture.swiftnew file mode 100644index 0000000..f0fd099--- /dev/null+++ b/Foodnotes/Foodnotes/App/PDFReceiptUIFixture.swift@@ -0,0 +1,38 @@+#if DEBUG+import CaptureHandoff+import FoodnotesDomain+import UIKit++/// Synthetic launch only. Publishes through the real durable share inbox, never a live library.+@MainActor enum PDFReceiptUIFixture {+ static let operation = UUID(uuidString: "B0000000-0000-0000-0000-000000002488")!+ static func seed(_ app: AppDependencies) async throws {+ guard case .synthetic = AppLaunchContext.current,+ ProcessInfo.processInfo.arguments.contains("--pdf-receipt-fixture"),+ let session = app.session, let store = app.store, let directory = app.directory else { return }+ let snapshot = try await store.snapshot(scope: .both)+ let drafts = try await store.drafts(session: session)+ guard !snapshot.documents.contains(where: { $0.meal.id == operation }),+ !drafts.contains(where: { $0.id == operation }) else { return }+ let group = try app.captureSharedDirectory(), handoff = try CaptureHandoffContainer.open(directory: group)+ guard try await handoff.pending(partitionID: session.partitionID).allSatisfy({ $0.operationID != operation }) else { return }+ let file = directory.appendingPathComponent("SyntheticReceipt.pdf")+ let bytes = UIGraphicsPDFRenderer(bounds: CGRect(x: 0, y: 0, width: 612, height: 792)).pdfData { context in+ for text in ["SYNTHETIC CAFE\n2 x Noodles $12.50", "CONTINUED\n1 x Rice $5.00"] {+ context.beginPage()+ text.draw(at: CGPoint(x: 40, y: 40),+ withAttributes: [.font: UIFont.systemFont(ofSize: 20), .foregroundColor: UIColor.black])+ }+ }+ try bytes.write(to: file)+ let metadata = try OriginalHandoffPDFFile.metadata(file)+ let sourceID = UUID()+ let envelope = SourceEnvelope(schemaVersion: 2, operationID: operation, partitionID: session.partitionID,+ sourceID: sourceID, filename: "\(sourceID.uuidString).original", mediaType: metadata.mediaType, byteLength: metadata.length,+ sha256: metadata.digest, capturedAt: Date(), origin: .shareExtension, capturedTimeZone: "UTC",+ destination: SourceCaptureDestination(.personal(accountID: session.accountID)))+ try await handoff.publish(envelope, source: file)+ await app.refreshCapture()+ }+}+#endif
diff --git a/Foodnotes/Foodnotes/Features/Capture/ManualReviewView.swift b/Foodnotes/Foodnotes/Features/Capture/ManualReviewView.swiftindex defcb8c..9aa537a 100644--- a/Foodnotes/Foodnotes/Features/Capture/ManualReviewView.swift+++ b/Foodnotes/Foodnotes/Features/Capture/ManualReviewView.swift@@ -1,6 +1,5 @@ import FoodnotesDomain import SwiftUI- struct ManualReviewView: View { let model: AppDependencies @State private var review: CaptureReviewModel@@ -16,13 +15,14 @@ struct ManualReviewView: View { @State private var saving = false @State private var operationID = UUID() @State private var showingSource: SourceImage?+ @State private var sourcePage = 0 @State private var newPlace: PlaceEditorInput?+ @AppStorage(DebugInformation.preferenceKey) private var debugInformation = false @Environment(\.dismiss) private var dismiss init(model: AppDependencies, review: CaptureReviewModel) { self.model = model _review = State(initialValue: review) }- var body: some View { reviewContent .opacity(model.accountPresentationHidden ? 0 : 1)@@ -35,7 +35,6 @@ struct ManualReviewView: View { if model.accountPresentationHidden { showingSource = nil } } }- private var reviewContent: some View { NavigationStack { ScrollView {@@ -53,18 +52,12 @@ struct ManualReviewView: View { TextField("Anything to remember", text: field(\.notes), axis: .vertical) .accessibilityIdentifier("capture.notes") }- if !draft.sources.isEmpty {- PageSurface {- Text("Source images").font(PageTypography.rowTitle)- ForEach(Array(draft.sources.enumerated()), id: \.element.id) { index, source in- Button("View source image \(index + 1) of \(draft.sources.count)") { showingSource = source }- .frame(minHeight: 44)- .accessibilityIdentifier("capture.source.\(source.id)")- }- }- }+ CaptureOriginalSourceButtons(sources: draft.sources, fields: supportingFields,+ names: Dictionary(draft.occurrences.map { ($0.id, $0.name.value ?? "Dish") },+ uniquingKeysWith: { first, _ in first }),+ open: { source in sourcePage = 0; showingSource = source },+ openPage: { source, page in sourcePage = page; showingSource = source }) libraryCard- Button("Discard draft", role: .destructive) { Task { guard let session = model.session else { return }@@ -111,7 +104,7 @@ struct ManualReviewView: View { knownPlaces = snapshot.places knownOptions = snapshot.orderingOptions }- if let source = draft.sources.first {+ if let source = draft.sources.first, source.mediaType != OriginalMedia.pdf.rawValue { sourceThumbnail = await Task.detached { MealImage.thumbnail(url: source.url, maximumPixels: 160) }.value } }@@ -132,7 +125,11 @@ struct ManualReviewView: View { } } .sheet(item: $showingSource) { source in- if model.accountPresentationHidden { DraftAccountTransitionNotice(model: model, owner: review.session) } else {+ if model.accountPresentationHidden {+ DraftAccountTransitionNotice(model: model, owner: review.session)+ } else if source.mediaType == OriginalMedia.pdf.rawValue {+ ReceiptSourceViewer(source: source, initialPage: sourcePage)+ } else { OriginalImageView(url: source.url, label: draft.sources.contains { $0.id == source.id } ? "Source image" : "Food photo") } }@@ -141,42 +138,19 @@ struct ManualReviewView: View { } } }-- @ViewBuilder private var extractionCard: some View {- if review.reading || review.needsManualEntry || !review.suggestions.isEmpty || review.persistenceFailed {- PageSurface {- if review.reading { Label("Reading your image…", systemImage: "text.viewfinder").font(PageTypography.rowTitle)- .accessibilityIdentifier("capture.reading") }- if review.needsManualEntry {- Text("We couldn’t read every detail. Your image is kept; you can enter the rest here.")- .accessibilityIdentifier("capture.manualFallback")- }- if review.persistenceFailed { Text("Couldn’t keep the latest edit. Save again before leaving.") }- ForEach(["place", "ordering"], id: \.self) { path in- if let suggestion = review.suggestions[path] {- VStack(alignment: .leading, spacing: 8) {- Text(path == "place" ? "Suggested place" : "Suggested method").font(PageTypography.caption)- Text(suggestion.proposal.value)- Button("Use suggestion") { review.confirm(path) }.frame(minHeight: 44)- .accessibilityLabel("Use suggested \(path == "place" ? "place" : "method") \(suggestion.proposal.value)")- }- }- }- }- }- }- private var titleCard: some View { VStack(alignment: .leading, spacing: 12) { HStack(alignment: .top) { Text("What was this?").font(PageTypography.rowTitle) Spacer() if let source = draft.sources.first {- Button { showingSource = source } label: {+ Button { sourcePage = 0; showingSource = source } label: { if let sourceThumbnail { Image(uiImage: sourceThumbnail).resizable().scaledToFit().frame(width: 52, height: 64) } else { Image(systemName: "doc").frame(width: 52, height: 64) }- }.accessibilityLabel("View source image").accessibilityIdentifier("capture.source.primary")+ }+ .accessibilityLabel(source.mediaType == OriginalMedia.pdf.rawValue ? "View original PDF" : "View source image")+ .accessibilityIdentifier("capture.source.primary") } } TextField(ManualMeal.suggestedTitle(draft), text: field(\.title), axis: .vertical)@@ -191,7 +165,6 @@ struct ManualReviewView: View { .padding(18).frame(maxWidth: .infinity, alignment: .leading) .background(PageColor.tint(for: draft.id), in: RoundedRectangle(cornerRadius: 28)) }- private var peopleCard: some View { PageSurface { Text("Who was there").font(PageTypography.rowTitle)@@ -250,6 +223,49 @@ struct ManualReviewView: View { } private extension ManualReviewView {+ @ViewBuilder private var extractionCard: some View {+ if review.reading || review.needsManualEntry || !review.suggestions.isEmpty+ || review.persistenceFailed || showReceiptStatus {+ PageSurface {+ if review.reading { Label("Reading your source…", systemImage: "text.viewfinder").font(PageTypography.rowTitle)+ .accessibilityIdentifier("capture.reading") }+ if review.needsManualEntry {+ Text("We couldn’t read every detail. Your original is kept; you can enter the rest here.")+ .accessibilityIdentifier("capture.manualFallback")+ }+ if let pages = draft.receiptPages, !pages.isEmpty {+ if debugInformation || !review.reading {+ ReceiptPageStatusSummary(pages: pages, showsNormalNotice: !review.needsManualEntry) { page in+ sourcePage = page.pageIndex+ showingSource = draft.sources.first { $0.id == page.sourceID }+ }+ }+ if debugInformation || (!review.reading &&+ (review.needsManualEntry || ReceiptPageStatusSummary.needsAttention(pages))) {+ Button("Retry receipt reading") { review.retryReceipt() }.disabled(review.reading)+ .frame(minHeight: 44).accessibilityIdentifier("receipt.retry")+ }+ }+ if review.persistenceFailed { Text("Couldn’t keep the latest edit. Save again before leaving.") }+ ForEach(["ordering"], id: \.self) { path in+ if let suggestion = review.suggestions[path] {+ VStack(alignment: .leading, spacing: 8) {+ Text("Suggested method").font(PageTypography.caption)+ Text(suggestion.proposal.value)+ Button("Use suggestion") { review.confirm(path) }.frame(minHeight: 44)+ .accessibilityLabel("Use suggested \(path == "place" ? "place" : "method") \(suggestion.proposal.value)")+ }+ }+ }+ }+ }+ }++ private var showReceiptStatus: Bool {+ let pages = draft.receiptPages ?? []+ return !pages.isEmpty && (debugInformation || ReceiptPageStatusSummary.needsAttention(pages))+ }+ private var people: [Person] { let rows = availablePeople.filter { $0.libraryID == draft.intendedLibrary } var seen = Set<UUID>()@@ -286,7 +302,9 @@ private extension ManualReviewView { draft.date = RecordedDate(value: ManualMeal.localDate($0, zone: zone), provenance: .manual) }), displayedComponents: .date) .environment(\.timeZone, TimeZone(identifier: draft.date.value.timeZoneIdentifier) ?? .current)- Text(dateProvenance).font(PageTypography.caption).accessibilityIdentifier("capture.date.provenance")+ if debugInformation || draft.date.provenance == .defaultValue {+ Text(dateProvenance).font(PageTypography.caption).accessibilityIdentifier("capture.date.provenance")+ } MealTimeControl(value: Binding(get: { draft.time }, set: { draft.time = $0 }), identifier: "capture.time") Divider() Text("Where").font(PageTypography.rowTitle)@@ -340,7 +358,7 @@ private extension ManualReviewView { TextField("Dish name", text: lineField(index, \.name), axis: .vertical).accessibilityIdentifier("capture.dish.\(index)") HStack { TextField("Quantity", text: lineField(index, \.quantity)).keyboardType(.decimalPad)- TextField("Price · AUD", text: lineField(index, \.price)).keyboardType(.decimalPad)+ TextField("Price each · AUD", text: lineField(index, \.price)).keyboardType(.decimalPad) } CaptureDishLinks(line: $review.draft.occurrences[index], placeID: draft.confirmedPlaceID, library: draft.intendedLibrary, catalog: model.snapshot?.dishes ?? []).disabled(draft.pendingSharedSetup == true)@@ -357,6 +375,14 @@ private extension ManualReviewView { } } + private var supportingFields: [ReceiptFieldProvenance] {+ let accepted = draft.receiptSupportingFields+ let paths = Set(accepted.map(\.fieldPath))+ return accepted + review.suggestions.values.compactMap {+ paths.contains($0.proposal.fieldPath) ? nil : draft.receiptSupportingField($0)+ }+ }+ private var libraryCard: some View { DraftLibraryControls(app: model, review: review) } private var dateProvenance: String {@@ -370,19 +396,3 @@ private extension ManualReviewView { } extension SourceImage: @retroactive Identifiable {}--struct OriginalImageView: View {- let url: URL- let label: String- @Environment(\.dismiss) private var dismiss- var body: some View {- NavigationStack {- Group {- if url.isFileURL, let image = UIImage(contentsOfFile: url.path) {- OriginalPhotoZoom(image: image, label: label, identity: url)- } else { Text("Original image isn’t available on this iPhone yet.") }- }- .navigationTitle(label).toolbar { Button("Done", systemImage: "xmark", role: .close) { dismiss() }.labelStyle(.iconOnly) }- }- }-}
diff --git a/Foodnotes/Foodnotes/Features/Capture/NativeImagePicker.swift b/Foodnotes/Foodnotes/Features/Capture/NativeImagePicker.swiftindex ce619fd..d24c5ac 100644--- a/Foodnotes/Foodnotes/Features/Capture/NativeImagePicker.swift+++ b/Foodnotes/Foodnotes/Features/Capture/NativeImagePicker.swift@@ -12,6 +12,8 @@ struct NativeImagePicker: View { var body: some View { if request.route == .photos { CapturePhotosPicker(result: result).ignoresSafeArea()+ } else if request.route == .files {+ CapturePDFPicker(result: result).ignoresSafeArea() } else { CaptureCameraPicker(result: result).ignoresSafeArea() }@@ -188,3 +190,23 @@ nonisolated private final class CaptureCameraPipeline: NSObject, AVCapturePhotoC Task { @MainActor in result(outcome) } } }++private struct CapturePDFPicker: UIViewControllerRepresentable {+ let result: @MainActor (Result<URL?, Error>) -> Void+ func makeCoordinator() -> Coordinator { Coordinator(result: result) }+ func makeUIViewController(context: Context) -> UIDocumentPickerViewController {+ let picker = UIDocumentPickerViewController(forOpeningContentTypes: [.pdf], asCopy: false)+ picker.allowsMultipleSelection = false; picker.delegate = context.coordinator+ return picker+ }+ func updateUIViewController(_ picker: UIDocumentPickerViewController, context: Context) {}+ @MainActor final class Coordinator: NSObject, UIDocumentPickerDelegate {+ let result: @MainActor (Result<URL?, Error>) -> Void+ init(result: @escaping @MainActor (Result<URL?, Error>) -> Void) { self.result = result }+ func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {+ guard urls.count == 1, let url = urls.first else { result(.failure(HandoffError.invalidSource)); return }+ result(.success(url))+ }+ func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) { result(.success(nil)) }+ }+}
diff --git a/Foodnotes/Foodnotes/Features/Capture/OriginalImageView.swift b/Foodnotes/Foodnotes/Features/Capture/OriginalImageView.swiftnew file mode 100644index 0000000..e9b112d--- /dev/null+++ b/Foodnotes/Foodnotes/Features/Capture/OriginalImageView.swift@@ -0,0 +1,17 @@+import SwiftUI++struct OriginalImageView: View {+ let url: URL+ let label: String+ @Environment(\.dismiss) private var dismiss+ var body: some View {+ NavigationStack {+ Group {+ if url.isFileURL, let image = UIImage(contentsOfFile: url.path) {+ OriginalPhotoZoom(image: image, label: label, identity: url)+ } else { Text("Original image isn’t available on this iPhone yet.") }+ }+ .navigationTitle(label).toolbar { Button("Done", systemImage: "xmark", role: .close) { dismiss() }.labelStyle(.iconOnly) }+ }+ }+}
diff --git a/Foodnotes/Foodnotes/Features/Capture/ReceiptSourceViewer.swift b/Foodnotes/Foodnotes/Features/Capture/ReceiptSourceViewer.swiftnew file mode 100644index 0000000..68fa6f8--- /dev/null+++ b/Foodnotes/Foodnotes/Features/Capture/ReceiptSourceViewer.swift@@ -0,0 +1,171 @@+import FoodnotesDomain+import Observation+import PDFKit+import SwiftUI++@MainActor @Observable final class ReceiptSourceViewModel {+ let source: SourceImage+ private let read: @Sendable (SourceImage) async throws -> PDFReceiptAdmission.Document+ private var generation = UUID()+ private var invalidated = false+ private(set) var bytes: Data?+ private(set) var pageCount = 0+ private(set) var currentPage = 0+ private(set) var error: String?+ private(set) var unavailablePages: Set<Int> = []+ var pageLabel: String { "Page \(currentPage + 1) of \(pageCount)" }+ init(source: SourceImage,+ read: @escaping @Sendable (SourceImage) async throws -> PDFReceiptAdmission.Document = { source in+ try await Task.detached { try PDFReceiptAdmission().read(source) }.value+ }) {+ self.source = source; self.read = read+ }+ func load() async {+ guard !invalidated else { return }+ let token = UUID(); generation = token+ bytes = nil; pageCount = 0; error = nil+ do {+ let document = try await read(source)+ guard generation == token, !invalidated, !Task.isCancelled else { return }+ bytes = document.bytes; pageCount = document.pageCount+ } catch {+ guard generation == token, !invalidated else { return }+ self.error = "Original PDF is unavailable. It may be missing or not downloaded. Your meal is still editable."+ }+ }+ func select(pageIndex: Int) {+ guard (0..<pageCount).contains(pageIndex) else { return }+ currentPage = pageIndex+ }+ func markUnavailable(pageIndex: Int) {+ guard (0..<pageCount).contains(pageIndex) else { return }+ unavailablePages.insert(pageIndex)+ }+ func invalidate() { invalidated = true; generation = UUID(); bytes = nil; pageCount = 0 }+}++struct ReceiptSourceViewer: View {+ @State private var model: ReceiptSourceViewModel+ let initialPage: Int+ @Environment(\.dismiss) private var dismiss+ init(source: SourceImage, initialPage: Int = 0) {+ _model = State(initialValue: ReceiptSourceViewModel(source: source)); self.initialPage = initialPage+ }+ var body: some View {+ NavigationStack {+ VStack(spacing: 12) {+ if let bytes = model.bytes {+ VStack(spacing: 8) {+ Text(model.pageLabel).accessibilityIdentifier("receipt.pdf.pageLabel")+ HStack {+ Button("Previous", systemImage: "chevron.left") { model.select(pageIndex: model.currentPage - 1) }+ .disabled(model.currentPage == 0).accessibilityIdentifier("receipt.pdf.previous")+ Spacer()+ Button("Next", systemImage: "chevron.right") { model.select(pageIndex: model.currentPage + 1) }+ .disabled(model.currentPage + 1 >= model.pageCount).accessibilityIdentifier("receipt.pdf.next")+ }.labelStyle(.iconOnly).frame(minHeight: 44)+ }.padding(.horizontal)+ if model.unavailablePages.contains(model.currentPage) {+ Text("This page can’t be displayed. The original PDF is kept.").padding()+ }+ ReceiptPDFView(bytes: bytes, pageIndex: model.currentPage) { model.markUnavailable(pageIndex: $0) }+ } else if let error = model.error {+ ContentUnavailableView("Original PDF unavailable", systemImage: "doc.badge.exclamationmark", description: Text(error))+ } else { ProgressView("Opening original PDF…") }+ }+ .background(PageColor.paper).navigationTitle("Original PDF").navigationBarTitleDisplayMode(.inline)+ .toolbar { ToolbarItem(placement: .confirmationAction) { Button("Done") { dismiss() } } }+ .task { await model.load(); model.select(pageIndex: initialPage) }+ .onDisappear { model.invalidate() }+ }+ }+}++struct ReceiptPDFView: UIViewRepresentable {+ let bytes: Data+ let pageIndex: Int+ let unavailable: (Int) -> Void+ final class Coordinator { var document: PDFDocument? }+ func makeCoordinator() -> Coordinator { Coordinator() }+ func makeUIView(context: Context) -> PDFView {+ let view = PDFView(); view.autoScales = true; view.displayMode = .singlePage+ view.displayDirection = .vertical; view.backgroundColor = .secondarySystemBackground+ context.coordinator.document = PDFDocument(data: bytes)+ view.document = context.coordinator.document+ return view+ }+ func updateUIView(_ view: PDFView, context: Context) {+ guard let document = context.coordinator.document, let page = document.page(at: pageIndex), page.pageRef != nil,+ Self.validBounds(page.bounds(for: .cropBox)) else {+ view.document = nil; view.isHidden = true; view.accessibilityElementsHidden = true+ Task { @MainActor in unavailable(pageIndex) }; return+ }+ view.document = document; view.isHidden = false; view.accessibilityElementsHidden = false+ view.go(to: page)+ }+ private static func validBounds(_ bounds: CGRect) -> Bool {+ bounds.origin.x.isFinite && bounds.origin.y.isFinite && bounds.width.isFinite && bounds.height.isFinite+ && bounds.width > 0 && bounds.height > 0+ }+}++enum ReceiptPageStatusText {+ static func label(_ page: ReceiptPageState) -> String {+ let prefix = "Page \(page.pageIndex + 1): "+ switch page.status {+ case .pending: return prefix + "Not processed"+ case .processing: return prefix + "Reading"+ case .processed: return prefix + "Processed"+ case .incomplete(let reason): return prefix + "Incomplete — " + reason+ }+ }+}++struct ReceiptPageStatusSummary: View {+ let pages: [ReceiptPageState]+ var showsNormalNotice = true+ let openPage: (ReceiptPageState) -> Void+ @AppStorage(DebugInformation.preferenceKey) private var debugInformation = false+ var body: some View {+ if debugInformation {+ VStack(alignment: .leading, spacing: 8) {+ Text("Receipt pages").font(PageTypography.rowTitle)+ ForEach(pages, id: \.pageIndex) { page in+ Button(ReceiptPageStatusText.label(page)) { openPage(page) }+ .frame(minHeight: 44).accessibilityIdentifier("receipt.page.\(page.pageIndex)")+ }+ Text("Processed pages may still have missing details. Check and edit the meal before saving.")+ .font(PageTypography.caption)+ }.accessibilityIdentifier("receipt.debug.pages")+ } else if showsNormalNotice && Self.needsAttention(pages) {+ Text("Receipt reading was incomplete. Check the meal details against the original receipt.")+ .font(PageTypography.caption).accessibilityIdentifier("receipt.needsAttention")+ }+ }+ static func needsAttention(_ pages: [ReceiptPageState]) -> Bool {+ pages.contains { $0.status != .processed }+ }+}++struct CaptureOriginalSourceButtons: View {+ let sources: [SourceImage]+ let fields: [ReceiptFieldProvenance]+ let names: [UUID: String]+ let open: (SourceImage) -> Void+ let openPage: (SourceImage, Int) -> Void+ var body: some View {+ if !sources.isEmpty {+ PageSurface {+ Text("Original sources").font(PageTypography.rowTitle)+ ForEach(Array(sources.enumerated()), id: \.element.id) { index, source in+ Button(source.mediaType == OriginalMedia.pdf.rawValue ? "View original PDF"+ : "View source image \(index + 1) of \(sources.count)") { open(source) }+ .frame(minHeight: 44).accessibilityIdentifier("capture.source.\(source.id)")+ if source.mediaType == OriginalMedia.pdf.rawValue {+ ReceiptSupportingPages(fields: fields, names: names) { openPage(source, $0) }+ }+ }+ }+ }+ }+}
diff --git a/Foodnotes/Foodnotes/Features/Capture/ReceiptSupportingPages.swift b/Foodnotes/Foodnotes/Features/Capture/ReceiptSupportingPages.swiftnew file mode 100644index 0000000..d63a480--- /dev/null+++ b/Foodnotes/Foodnotes/Features/Capture/ReceiptSupportingPages.swift@@ -0,0 +1,38 @@+import FoodnotesDomain+import SwiftUI++enum ReceiptSupportingPageLabel {+ static func field(_ field: ReceiptFieldProvenance, names: [UUID: String]) -> String? {+ let titles = ["date": "Date", "time": "Time", "title": "Meal title", "place": "Place",+ "ordering": "Ordering method", "notes": "Meal note", "name": "Dish name",+ "quantity": "Quantity", "price": "Price", "note": "Dish note"]+ guard let key = field.fieldPath.split(separator: ".").last, let title = titles[String(key)] else { return nil }+ guard let occurrence = field.occurrenceID else { return title }+ return title + " for " + (names[occurrence].flatMap { $0.isEmpty ? nil : $0 } ?? "dish")+ }+}++struct ReceiptSupportingPages: View {+ let fields: [ReceiptFieldProvenance]+ let names: [UUID: String]+ let openPage: (Int) -> Void+ @AppStorage(DebugInformation.preferenceKey) private var debugInformation = false+ var body: some View {+ if debugInformation {+ VStack(alignment: .leading, spacing: 8) {+ ForEach(fields, id: \.fieldPath) { field in+ if let label = ReceiptSupportingPageLabel.field(field, names: names) {+ if let calculation = field.priceCalculation {+ Text(calculation.explanation).font(PageTypography.caption)+ }+ ForEach(field.pageIndices, id: \.self) { page in+ Button("\(label) · Page \(page + 1)") { openPage(page) }+ .font(PageTypography.caption).frame(minHeight: 44)+ .accessibilityHint("Open the original receipt page supporting this detail")+ }+ }+ }+ }.accessibilityIdentifier("receipt.debug.fields")+ }+ }+}
diff --git a/Foodnotes/Foodnotes/Features/Journal/JournalView.swift b/Foodnotes/Foodnotes/Features/Journal/JournalView.swiftindex 660c28a..da0c688 100644--- a/Foodnotes/Foodnotes/Features/Journal/JournalView.swift+++ b/Foodnotes/Foodnotes/Features/Journal/JournalView.swift@@ -65,6 +65,7 @@ struct JournalView: View { : draft.intendedLibrary.displayLabel) { model.editingDraft = draft }+ .accessibilityIdentifier("journal.draft.\(draft.id.uuidString)") } } if !unfinished.isEmpty {@@ -100,6 +101,7 @@ struct JournalView: View { .confirmationDialog("Add a meal", isPresented: $chooseCapture, titleVisibility: .visible) { Button("Take a photo") { Task { await model.beginCapture(.camera) } } Button("Choose from Photos") { Task { await model.beginCapture(.photos) } }+ Button("Import PDF receipt") { Task { await model.beginCapture(.files) } } Button("Type it in") { Task { await model.newMeal() } } } message: { if model.captureShareUnavailable {@@ -109,6 +111,16 @@ struct JournalView: View { } @ViewBuilder private var captureInbox: some View {+ if !model.captureCompatibility.isEmpty {+ PageSurface {+ Text("Update every Foodnotes installation first").font(PageTypography.rowTitle)+ Text("PDF receipts need this updated version on every installation using this library or restoring its archives. "+ + "Older versions can’t read PDF originals. Your PDF is kept while you check.")+ Button("All installations are updated") { Task { await model.acceptPDFCompatibility() } }+ .frame(minHeight: 44).accessibilityIdentifier("receipt.compatibility.accept")+ Text("You can come back later. No meal has been created from this PDF yet.").font(PageTypography.caption)+ }+ } if model.captureBusy { Label("Keeping your image…", systemImage: "photo").font(PageTypography.caption) } if !model.captureDeferred.isEmpty { PageSurface {
diff --git a/Foodnotes/Foodnotes/Features/Meals/MealCaptureOriginals.swift b/Foodnotes/Foodnotes/Features/Meals/MealCaptureOriginals.swiftindex e5c230c..82cab78 100644--- a/Foodnotes/Foodnotes/Features/Meals/MealCaptureOriginals.swift+++ b/Foodnotes/Foodnotes/Features/Meals/MealCaptureOriginals.swift@@ -6,6 +6,7 @@ struct MealCaptureOriginals: View { let model: AppDependencies let document: MealDocument @State private var presentation: OriginalPresentation?+ @AppStorage(DebugInformation.preferenceKey) private var debugInformation = false private var available: Bool { MealImageOwner(document.meal).admits(model.document(id: document.meal.id, library: document.meal.libraryID)) }@@ -15,18 +16,24 @@ struct MealCaptureOriginals: View { VStack(alignment: .leading, spacing: 10) { Text("Original capture").font(PageTypography.rowTitle) ForEach(document.assets.filter { $0.role == .source }, id: \.assetID) { asset in- Button("View captured image") { Task { await open(asset) } }- .accessibilityIdentifier("meal.sourceOriginal")- .frame(minHeight: 44)+ originalControls(asset)+ }+ if debugInformation {+ Text("Original bytes are kept separately from meal and dish photos.").font(PageTypography.caption) }- Text("Original bytes are kept separately from meal and dish photos.").font(PageTypography.caption) }.frame(maxWidth: .infinity, alignment: .leading) } .sheet(item: $presentation) { item in if model.session == item.session && available {- if let url = item.url { OriginalImageView(url: url, label: "Source image") } else {+ if let url = item.url {+ if item.asset.mediaType == OriginalMedia.pdf.rawValue {+ ReceiptSourceViewer(source: SourceImage(id: item.asset.assetID, url: url,+ mediaType: item.asset.mediaType, byteLength: item.asset.byteLength, sha256: item.asset.sha256),+ initialPage: item.pageIndex)+ } else { OriginalImageView(url: url, label: "Source image") }+ } else { NavigationStack {- Text("Original image isn’t available on this iPhone. It may not have downloaded or may be missing.")+ Text("Original source isn’t available on this iPhone. It may not have downloaded or may be missing.") .padding().toolbar { Button("Done") { presentation = nil } } } }@@ -37,14 +44,35 @@ struct MealCaptureOriginals: View { .onChange(of: MealImageOwner(document.meal)) { presentation = nil } } }- private func open(_ asset: AssetManifestEntry) async {+ private var occurrenceNames: [UUID: String] {+ Dictionary(document.occurrences.map { ($0.id, $0.displayName.value) }, uniquingKeysWith: { first, _ in first })+ }+ @ViewBuilder private func originalControls(_ asset: AssetManifestEntry) -> some View {+ Button(asset.mediaType == OriginalMedia.pdf.rawValue ? "View original PDF" : "View captured image") {+ Task { await open(asset) }+ }+ .accessibilityIdentifier("meal.sourceOriginal")+ .frame(minHeight: 44)+ if let fields = asset.receiptProvenance?.fields {+ ReceiptSupportingPages(fields: fields,+ names: occurrenceNames) { page in+ Task { await open(asset, pageIndex: page) }+ }+ }+ if let pages = asset.receiptProvenance?.pages {+ ReceiptPageStatusSummary(pages: pages) { page in+ Task { await open(asset, pageIndex: page.pageIndex) }+ }+ }+ }+ private func open(_ asset: AssetManifestEntry, pageIndex: Int = 0) async { guard let session = model.session, let store = model.store else { return } let url = try? await store.assetURL(id: asset.assetID, session: session) guard model.session == session, model.document(id: document.meal.id, library: document.meal.libraryID)?.meal.epoch == document.meal.epoch else { return }- presentation = OriginalPresentation(session: session, url: url)+ presentation = OriginalPresentation(session: session, url: url, asset: asset, pageIndex: pageIndex) } } @@ -52,4 +80,6 @@ private struct OriginalPresentation: Identifiable { let id = UUID() let session: AccountSession let url: URL?+ let asset: AssetManifestEntry+ let pageIndex: Int }
diff --git a/Foodnotes/Foodnotes/Features/Meals/MealDeletionControl.swift b/Foodnotes/Foodnotes/Features/Meals/MealDeletionControl.swiftnew file mode 100644index 0000000..c7de4af--- /dev/null+++ b/Foodnotes/Foodnotes/Features/Meals/MealDeletionControl.swift@@ -0,0 +1,51 @@+import FoodnotesDomain+import SwiftUI++struct MealDeletionControl: View {+ let app: AppDependencies+ let document: MealDocument+ @State private var confirming = false+ @State private var deleting = false+ @State private var request: Request?+ @State private var error: String?++ var body: some View {+ PageSurface {+ Button("Delete meal…", role: .destructive) {+ guard let session = app.session else { return }+ request = Request(document: document, session: session)+ confirming = true+ }.buttonStyle(.bordered).tint(.red).frame(minHeight: 44).accessibilityIdentifier("meal.delete")+ .disabled(deleting || app.nonWritableMeals.contains(MealWriteKey(document.meal)))+ if let error { Text(error).font(PageTypography.caption).accessibilityIdentifier("meal.delete.error") }+ }+ .alert("Delete this meal?", isPresented: $confirming) {+ Button("Delete meal", role: .destructive) { remove() }.accessibilityIdentifier("meal.delete.confirm")+ Button("Cancel", role: .cancel) { request = nil }+ } message: {+ Text(document.meal.libraryID.displayLabel == "Shared"+ ? "This can’t be undone. This meal will also disappear for others using Shared when it syncs. "+ + "Other meals and saved places are kept."+ : "This can’t be undone. Other meals and saved places are kept.")+ }+ .onChange(of: app.session) { confirming = false; request = nil; error = nil }+ }+ private func remove() {+ guard let request, !deleting else { return }+ deleting = true; error = nil+ Task { @MainActor in+ defer { deleting = false }+ do {+ try await app.deleteMeal(request.document, session: request.session, confirmed: true, operationID: request.id)+ } catch {+ guard app.session == request.session else { return }+ self.error = "Couldn’t delete this meal. It may have changed or be moving. Reopen it and try again."+ }+ }+ }+ private struct Request {+ let id = UUID()+ let document: MealDocument+ let session: AccountSession+ }+}
diff --git a/Foodnotes/Foodnotes/Features/Meals/MealDetailView.swift b/Foodnotes/Foodnotes/Features/Meals/MealDetailView.swiftindex 286cb5d..2d4b8ca 100644--- a/Foodnotes/Foodnotes/Features/Meals/MealDetailView.swift+++ b/Foodnotes/Foodnotes/Features/Meals/MealDetailView.swift@@ -96,6 +96,7 @@ struct MealDetailView: View { } } }+ MealDeletionControl(app: model, document: document) }.padding(.horizontal, 20) }.padding(.bottom, 20) }
diff --git a/Foodnotes/Foodnotes/Features/Settings/DebugInformation.swift b/Foodnotes/Foodnotes/Features/Settings/DebugInformation.swiftnew file mode 100644index 0000000..25ef3b3--- /dev/null+++ b/Foodnotes/Foodnotes/Features/Settings/DebugInformation.swift@@ -0,0 +1,14 @@+import SwiftUI++nonisolated enum DebugInformation {+ static let preferenceKey = "Foodnotes.debugInformation"+}++struct DebugInformationToggle: View {+ @AppStorage(DebugInformation.preferenceKey) private var enabled = false+ var body: some View {+ Toggle("Debug information", isOn: $enabled)+ .tint(PageColor.ink).padding(.vertical, 14)+ .accessibilityIdentifier("settings.debugInformation")+ }+}
diff --git a/Foodnotes/Foodnotes/Features/Settings/SettingsView.swift b/Foodnotes/Foodnotes/Features/Settings/SettingsView.swiftindex 9f1bc37..0a63945 100644--- a/Foodnotes/Foodnotes/Features/Settings/SettingsView.swift+++ b/Foodnotes/Foodnotes/Features/Settings/SettingsView.swift@@ -8,6 +8,7 @@ struct SettingsView: View { @State private var dinerEditor: DinerEditor? @State private var sharing = false @State private var destination: SettingsDestination?+ @AppStorage(DebugInformation.preferenceKey) private var debugInformation = false init(model: AppDependencies) { _settings = State(initialValue: SettingsModel(app: model)) } @@ -18,6 +19,7 @@ struct SettingsView: View { PageIconButton(symbol: "chevron.left", label: "Home") { dismiss() } Text("Settings").font(PageTypography.screenTitle) group("New meals") { newMeals }+ group("Display") { DebugInformationToggle() } group("People") { people } group("Your data") { ForEach([SettingsDestination.archive, .markdown, .restore]) { target in@@ -26,7 +28,7 @@ struct SettingsView: View { .accessibilityIdentifier("settings.\(target.rawValue)") } }- PhotoReferenceDiagnosticPanel(app: settings.app)+ if debugInformation { PhotoReferenceDiagnosticPanel(app: settings.app) } Button("Acknowledgements") { destination = .acknowledgements } .font(PageTypography.body).foregroundStyle(PageColor.inkMuted).frame(minHeight: 44) if let error = settings.error { Text(error).font(PageTypography.caption).accessibilityIdentifier("settings.error") }
diff --git a/Foodnotes/Foodnotes/Persistence/AssetIdentity.swift b/Foodnotes/Foodnotes/Persistence/AssetIdentity.swiftindex a3309ba..564910f 100644--- a/Foodnotes/Foodnotes/Persistence/AssetIdentity.swift+++ b/Foodnotes/Foodnotes/Persistence/AssetIdentity.swift@@ -23,7 +23,8 @@ nonisolated extension StorageWriter { let old = try decode(StoredAsset.self, object) guard object.value(forKey: "mealID") as? UUID == mealID, old.manifest.sha256 == value.manifest.sha256, old.manifest.byteLength == value.manifest.byteLength,- old.manifest.mediaType == value.manifest.mediaType else { throw StorageError.revisionConflict }+ old.manifest.mediaType == value.manifest.mediaType,+ old.manifest.receiptProvenance == value.manifest.receiptProvenance else { throw StorageError.revisionConflict } if object.value(forKey: "libraryKey") as? String == StorageCoding.libraryKey(library), object.value(forKey: "key") as? String != key { context.delete(object) } }
diff --git a/Foodnotes/Foodnotes/Persistence/CoreDataHandoffStore.swift b/Foodnotes/Foodnotes/Persistence/CoreDataHandoffStore.swiftindex 97b061f..95fb572 100644--- a/Foodnotes/Foodnotes/Persistence/CoreDataHandoffStore.swift+++ b/Foodnotes/Foodnotes/Persistence/CoreDataHandoffStore.swift@@ -30,10 +30,10 @@ nonisolated final class CoreDataHandoffStore: @unchecked Sendable { } } let publication = try await Task.detached {- try self.writer.assets.prepare(draft.allImageSources, partitionID: session.partitionID)+ try self.writer.assets.prepare(draft.allOriginalSources, partitionID: session.partitionID) }.value defer { writer.assets.release(publication.lease) }- var durable = draft; durable.replaceImageLocators(publication.sources)+ var durable = draft; durable.replaceOriginalLocators(publication.sources) let prepared = durable return try await writer.context.perform { try self.writer.importHandoff(prepared, operationID: operationID, inputDigest: inputDigest,
diff --git a/Foodnotes/Foodnotes/Persistence/CoreDataMealRepository.swift b/Foodnotes/Foodnotes/Persistence/CoreDataMealRepository.swiftindex 4705db9..61a7825 100644--- a/Foodnotes/Foodnotes/Persistence/CoreDataMealRepository.swift+++ b/Foodnotes/Foodnotes/Persistence/CoreDataMealRepository.swift@@ -90,11 +90,11 @@ nonisolated final class CoreDataMealRepository: MealRepository, HandoffDraftSink // Keep the editable input before file publication. Failure retains it rather than exposing a saved meal. try await writer.context.perform { try self.writer.saveDraft(draft, session: session) } let publication = try await Task.detached {- try self.writer.assets.prepare(draft.allImageSources, partitionID: session.partitionID)+ try self.writer.assets.prepare(draft.allOriginalSources, partitionID: session.partitionID) }.value defer { writer.assets.release(publication.lease) } var durable = draft- durable.replaceImageLocators(publication.sources)+ durable.replaceOriginalLocators(publication.sources) let prepared = durable try await writer.context.perform { try self.writer.saveDraft(prepared, session: session) } return prepared
diff --git a/Foodnotes/Foodnotes/Persistence/DraftMaterializer.swift b/Foodnotes/Foodnotes/Persistence/DraftMaterializer.swiftindex c3893eb..b719767 100644--- a/Foodnotes/Foodnotes/Persistence/DraftMaterializer.swift+++ b/Foodnotes/Foodnotes/Persistence/DraftMaterializer.swift@@ -21,6 +21,7 @@ nonisolated extension StorageWriter { partition: state.session.partitionID), try decode(Draft.self, draftRow) == draft else { throw StorageError.revisionConflict }+ let receiptProvenance = try draft.savedReceiptProvenance() let now = configuration.now() let stamp = try state.clock.tick(wallClockMilliseconds: milliseconds(now), replicaID: configuration.installationID)@@ -36,22 +37,13 @@ nonisolated extension StorageWriter { isFinished: Stamped(value: false, stamp: stamp), isPresent: Stamped(value: true, stamp: stamp), photos: photoReferences(draft.mealPhotoAssetIDs, framing: draft.mealPhotoFraming, stamp: stamp), selectedPhotoAssetID: draft.selectedMealPhoto.map { Stamped(value: $0.assetID, stamp: stamp) })- let occurrences = try draft.occurrences.map { line in- Occurrence(id: line.id, mealID: meal.id, originalSourceLine: line.name.value ?? "",- displayName: Stamped(value: line.name.value ?? "", stamp: stamp),- quantity: Stamped(value: try decimal(line.quantity.value), stamp: stamp),- price: Stamped(value: try AUDPrice.parse(line.price.value), stamp: stamp),- note: Stamped(value: line.note.value, stamp: stamp),- menuDishID: Stamped(value: try materializeDish(line, placeID: placeID, library: draft.intendedLibrary,- operationID: operationID, stamp: stamp, state: state), stamp: stamp),- sortKey: Stamped(value: line.sortKey, stamp: stamp),- isPresent: Stamped(value: true, stamp: stamp),- photos: photoReferences(line.photoAssetIDs, framing: line.photoFraming, stamp: stamp))- }+ let occurrences = try materializeOccurrences(draft, meal: meal, placeID: placeID, operationID: operationID,+ stamp: stamp, state: &state) let diners = try materializeDiners(draft, meal: meal, stamp: stamp, session: state.session)- let manifests = try materializeAssets(draft.sources, role: .source, meal: meal, session: state.session)+ let manifests = try materializeAssets(draft.sources, role: .source, meal: meal, session: state.session,+ provenance: receiptProvenance) + materializeAssets(draft.foodPhotos ?? [], role: .food, meal: meal, session: state.session)- try replaceMealFileReferences(draft.allImageSources.map(\.url), mealID: meal.id, library: meal.libraryID, session: state.session)+ try replaceMealFileReferences(draft.allOriginalSources.map(\.url), mealID: meal.id, library: meal.libraryID, session: state.session) let reminder = StoredReminder(mealID: meal.id, creationDeviceID: configuration.installationID, dueAt: now.addingTimeInterval(7_200), suppressedByRestore: false) try put("FNReminderLedger", key: "\(state.session.partitionID).\(meal.id)", partition: state.session.partitionID,@@ -62,6 +54,27 @@ nonisolated extension StorageWriter { occurrences: occurrences, opinions: [], assets: manifests) } + private func materializeOccurrences(+ _ draft: Draft, meal: Meal, placeID: UUID?, operationID: UUID,+ stamp: FieldStamp, state: inout PartitionState+ ) throws -> [Occurrence] {+ let dismissed = Set((draft.receiptDismissedOccurrences ?? []).map(\.id))+ return try (draft.occurrences + (draft.receiptDismissedOccurrences ?? [])).map { line in+ let removed = dismissed.contains(line.id)+ return Occurrence(id: line.id, mealID: meal.id, originalSourceLine: line.name.value ?? "",+ displayName: Stamped(value: line.name.value ?? "", stamp: stamp),+ quantity: Stamped(value: removed ? nil : try decimal(line.quantity.value), stamp: stamp),+ price: Stamped(value: removed ? nil : try AUDPrice.parse(line.price.value), stamp: stamp),+ note: Stamped(value: line.note.value, stamp: stamp),+ menuDishID: Stamped(value: removed ? nil : try materializeDish(line, placeID: placeID,+ library: draft.intendedLibrary,+ operationID: operationID, stamp: stamp, state: state), stamp: stamp),+ sortKey: Stamped(value: line.sortKey, stamp: stamp),+ isPresent: Stamped(value: !removed, stamp: stamp),+ photos: removed ? nil : photoReferences(line.photoAssetIDs, framing: line.photoFraming, stamp: stamp))+ }+ }+ private func materializeDiners(_ draft: Draft, meal: Meal, stamp: FieldStamp, session: AccountSession) throws -> [MealDiner] { let people = try rows("FNPerson", partition: session.partitionID).map { try decode(Person.self, $0) }@@ -79,12 +92,16 @@ nonisolated extension StorageWriter { } private func materializeAssets(_ sources: [SourceImage], role: AssetRole,- meal: Meal, session: AccountSession) throws -> [AssetManifestEntry] {+ meal: Meal, session: AccountSession,+ provenance: [UUID: ReceiptProvenance] = [:]) throws -> [AssetManifestEntry] { try sources.map { source in if let existing = try assetRow(id: source.id, library: meal.libraryID, partition: session.partitionID), existing.value(forKey: "mealID") as? UUID != meal.id { throw StorageError.revisionConflict } let manifest = AssetManifestEntry(assetID: source.id, address: nil, role: role,- mediaType: source.mediaType, byteLength: source.byteLength, sha256: source.sha256)+ mediaType: source.mediaType, byteLength: source.byteLength, sha256: source.sha256,+ receiptProvenance: provenance[source.id])+ try manifest.validate()+ try assets.verifyOwned(manifest, partition: session.partitionID) try storeAsset(StoredAsset(manifest: manifest, localURL: source.url), mealID: meal.id, library: meal.libraryID, partition: session.partitionID) return manifest
diff --git a/Foodnotes/Foodnotes/Persistence/DraftStorage.swift b/Foodnotes/Foodnotes/Persistence/DraftStorage.swiftindex 4e54beb..985444b 100644--- a/Foodnotes/Foodnotes/Persistence/DraftStorage.swift+++ b/Foodnotes/Foodnotes/Persistence/DraftStorage.swift@@ -44,8 +44,8 @@ nonisolated extension StorageWriter { try put("FNDraft", key: "\(session.partitionID).\(draft.id)", partition: session.partitionID, value: draft, domainID: draft.id, library: draft.intendedLibrary) // Reserve final locators before publication, so a crash after rename cannot make retained draft bytes look orphaned.- let planned = draft.allImageSources.map { assets.plannedURL(id: $0.id, partitionID: session.partitionID) }- try replaceFileReferences(draft.allImageSources.map(\.url) + planned, ownerID: draft.id, kind: "draft", session: session)+ let planned = draft.allOriginalSources.map { assets.plannedURL(id: $0.id, partitionID: session.partitionID) }+ try replaceFileReferences(draft.allOriginalSources.map(\.url) + planned, ownerID: draft.id, kind: "draft", session: session) try commit() } catch { context.rollback(); context.reset(); throw error } }@@ -109,7 +109,7 @@ nonisolated extension StorageWriter { } } for draft in try drafts(session: session) {- if let source = draft.allImageSources.first(where: { $0.id == id }), source.url.isFileURL { return source.url }+ if let source = draft.allOriginalSources.first(where: { $0.id == id }), source.url.isFileURL { return source.url } } for pending in try outbox(session: session) { if let url = pending.localAssetURLs?[id], url.isFileURL { return url }
diff --git a/Foodnotes/Foodnotes/Persistence/LocalAssetPayload.swift b/Foodnotes/Foodnotes/Persistence/LocalAssetPayload.swiftindex cbc970d..d054a82 100644--- a/Foodnotes/Foodnotes/Persistence/LocalAssetPayload.swift+++ b/Foodnotes/Foodnotes/Persistence/LocalAssetPayload.swift@@ -37,14 +37,14 @@ nonisolated extension StorageWriter { private func localDraft(_ input: Draft, partition: UUID, reading: Bool) throws -> Draft { guard input.partitionID == partition else { throw StorageError.wrongPartition } var draft = input- let images = try draft.allImageSources.map { image -> SourceImage in+ let images = try draft.allOriginalSources.map { image -> SourceImage in var copy = image let manifest = AssetManifestEntry(assetID: image.id, address: nil, role: .source, mediaType: image.mediaType, byteLength: image.byteLength, sha256: image.sha256) copy.url = try assets.imageURL(image.url, manifest: manifest, partition: partition, reading: reading, allowUnpublished: true) return copy }- draft.replaceImageLocators(images); return draft+ draft.replaceOriginalLocators(images); return draft } private func localOutbox(_ entry: StoredOutboxEntry, partition: UUID, reading: Bool) throws -> StoredOutboxEntry { try assets.localOutbox(entry, partition: partition, reading: reading)
diff --git a/Foodnotes/Foodnotes/Persistence/RepositoryCloudFetch.swift b/Foodnotes/Foodnotes/Persistence/RepositoryCloudFetch.swiftindex a997d76..de51a0c 100644--- a/Foodnotes/Foodnotes/Persistence/RepositoryCloudFetch.swift+++ b/Foodnotes/Foodnotes/Persistence/RepositoryCloudFetch.swift@@ -201,6 +201,13 @@ nonisolated extension StorageWriter { projected.version = local.version if projected != local { projected.version = UUID() } }+ // A fetched whole record must not resurrect a committed same-epoch tombstone,+ // including after its local outbox entry has already been acknowledged.+ if let current, current.meal.epoch == projected.meal.epoch,+ !current.meal.isPresent.value, projected.meal.isPresent.value {+ projected.meal.isPresent = current.meal.isPresent+ projected.version = UUID()+ } let localURLs = try storeDocument(projected, partition: session.partitionID) try retireMembershipSources(destination: snapshot.control, session: session) if let latest, latest.document.meal.epoch == projected.meal.epoch {
diff --git a/Foodnotes/Foodnotes/Persistence/RepositoryHandoff.swift b/Foodnotes/Foodnotes/Persistence/RepositoryHandoff.swiftindex 7cf12fb..4aca138 100644--- a/Foodnotes/Foodnotes/Persistence/RepositoryHandoff.swift+++ b/Foodnotes/Foodnotes/Persistence/RepositoryHandoff.swift@@ -44,8 +44,8 @@ nonisolated extension StorageWriter { try draft.validatePhotoReferences() try draft.date.validate() try draft.time?.validate()- guard Set(draft.allImageSources.map(\.id)).count == draft.allImageSources.count,- draft.allImageSources.allSatisfy({ assets.owns($0.url, partitionID: session.partitionID) }) else {+ guard Set(draft.allOriginalSources.map(\.id)).count == draft.allOriginalSources.count,+ draft.allOriginalSources.allSatisfy({ assets.owns($0.url, partitionID: session.partitionID) }) else { throw StorageError.missingAsset } guard try row("FNDraft", key: "\(session.partitionID).\(draft.id)", partition: session.partitionID) == nil else {@@ -54,7 +54,7 @@ nonisolated extension StorageWriter { do { try put("FNDraft", key: "\(session.partitionID).\(draft.id)", partition: session.partitionID, value: draft, domainID: draft.id, library: draft.intendedLibrary)- try replaceFileReferences(draft.allImageSources.map(\.url), ownerID: draft.id, kind: "draft", session: session)+ try replaceFileReferences(draft.allOriginalSources.map(\.url), ownerID: draft.id, kind: "draft", session: session) let receipt = HandoffImportReceipt(operationID: operationID, draftID: draft.id, partitionID: session.partitionID, inputDigest: inputDigest, destination: capturedDestination ?? draft.intendedLibrary)
diff --git a/Foodnotes/Foodnotes/Persistence/RepositoryStorage.swift b/Foodnotes/Foodnotes/Persistence/RepositoryStorage.swiftindex 9dae869..a158be4 100644--- a/Foodnotes/Foodnotes/Persistence/RepositoryStorage.swift+++ b/Foodnotes/Foodnotes/Persistence/RepositoryStorage.swift@@ -134,7 +134,8 @@ nonisolated extension StorageWriter { value.meal.id as NSUUID)) .map { try decode(StoredAsset.self, $0) } localURL = aliases.first { $0.manifest.sha256 == asset.sha256 && $0.manifest.byteLength == asset.byteLength &&- $0.manifest.mediaType == asset.mediaType && $0.localURL != nil }?.localURL+ $0.manifest.mediaType == asset.mediaType &&+ $0.manifest.receiptProvenance == asset.receiptProvenance && $0.localURL != nil }?.localURL } if let localURL { localURLs[asset.assetID] = localURL } try storeAsset(StoredAsset(manifest: asset, localURL: localURL), mealID: value.meal.id,
diff --git a/Foodnotes/Foodnotes/Services/Archives/ArchiveImportPlanner.swift b/Foodnotes/Foodnotes/Services/Archives/ArchiveImportPlanner.swiftindex a9c898e..df07bc5 100644--- a/Foodnotes/Foodnotes/Services/Archives/ArchiveImportPlanner.swift+++ b/Foodnotes/Foodnotes/Services/Archives/ArchiveImportPlanner.swift@@ -19,6 +19,7 @@ nonisolated enum ArchiveImportPlanner { } for index in records.meals.indices { records.meals[index].controllingOwnerID = state.snapshot.session.adultID } ArchiveImportDefinition.install(definitions.inserted, into: &records)+ records.schemaVersion = records.meals.contains { $0.assets.contains { $0.mediaType == "application/pdf" } } ? 2 : 1 try validateProspective(records, state: state) let origins = try incoming.map { original in ArchiveMealOrigin(mealID: original.id, sourceDigest: try ArchiveCanonical.digest(original),@@ -90,6 +91,7 @@ nonisolated enum ArchiveImportPlanner { meal.assets = source.assets.map { original in var value = original value.id = identity(original.id, kind: "asset", mealID: source.id, account: account, owners: &assets)+ value.receiptProvenance = original.receiptProvenance?.reidentified(sourceID: value.id, occurrenceIDs: lines) imageIDs[original.id] = value.id sources[value.id] = original.id if value.id != original.id { variants.insert(value.id) }@@ -131,6 +133,7 @@ nonisolated enum ArchiveImportPlanner { records.orderingOptions += incoming.orderingOptions records.dishes += incoming.dishes // Existing library tokens remain scoped; incoming definitions are Personal only.+ records.schemaVersion = records.meals.contains { $0.assets.contains { $0.mediaType == "application/pdf" } } ? 2 : 1 try ArchiveGraphValidator.validate(records) } }
diff --git a/Foodnotes/Foodnotes/Services/Archives/CoreDataArchiveScratchStore.swift b/Foodnotes/Foodnotes/Services/Archives/CoreDataArchiveScratchStore.swiftindex c1f393f..3eaec0d 100644--- a/Foodnotes/Foodnotes/Services/Archives/CoreDataArchiveScratchStore.swift+++ b/Foodnotes/Foodnotes/Services/Archives/CoreDataArchiveScratchStore.swift@@ -56,7 +56,8 @@ actor CoreDataArchiveScratchStore: ArchiveScratchStore { return source } let publication = try await Task.detached {- for source in sources { try ArchiveIO.image(source.url, mediaType: source.mediaType) }+ for source in sources { try ArchiveIO.original(source.url, mediaType: source.mediaType,+ expectedPageCount: assets[source.id]?.receiptProvenance?.pages.count) } return try writer.assets.prepare(sources, partitionID: session.partitionID) }.value defer { writer.assets.release(publication.lease) }@@ -95,12 +96,14 @@ actor CoreDataArchiveScratchStore: ArchiveScratchStore { } return (graph, sources) }+ let capturedAssets = try ArchiveGraphValidator.assets(in: ArchiveRecords(graph: captured.0)) try await Task.detached { for source in captured.1 { try ArchiveIO.regular(source.url) guard try source.url.resourceValues(forKeys: [.fileSizeKey]).fileSize.map(Int64.init) == source.byteLength, try ArchiveIO.digest(source.url) == source.sha256 else { throw ArchiveValidationError.checksumMismatch }- try ArchiveIO.image(source.url, mediaType: source.mediaType)+ try ArchiveIO.original(source.url, mediaType: source.mediaType,+ expectedPageCount: capturedAssets[source.id]?.receiptProvenance?.pages.count) } }.value return captured.0
diff --git a/Foodnotes/Foodnotes/Services/Archives/MarkdownExport/MarkdownExporter.swift b/Foodnotes/Foodnotes/Services/Archives/MarkdownExport/MarkdownExporter.swiftindex 656410a..443a10c 100644--- a/Foodnotes/Foodnotes/Services/Archives/MarkdownExport/MarkdownExporter.swift+++ b/Foodnotes/Foodnotes/Services/Archives/MarkdownExport/MarkdownExporter.swift@@ -93,10 +93,10 @@ nonisolated enum MarkdownZIP { try ArchiveIO.regular(source) guard try source.resourceValues(forKeys: [.fileSizeKey]).fileSize.map(Int64.init) == asset.byteLength, try ArchiveIO.digest(source) == asset.sha256 else { throw ArchiveValidationError.checksumMismatch }- try ArchiveIO.image(source, mediaType: asset.mediaType)+ try ArchiveIO.original(source, mediaType: asset.mediaType, expectedPageCount: asset.receiptProvenance?.pages.count) let handle = try FileHandle(forReadingFrom: source) defer { try? handle.close() }- try zip.addEntry(with: ArchiveGraphValidator.imagePath(asset), type: .file, uncompressedSize: asset.byteLength,+ try zip.addEntry(with: ArchiveGraphValidator.originalPath(asset), type: .file, uncompressedSize: asset.byteLength, bufferSize: ArchiveIO.chunkSize) { offset, count in try resources.check(bytes: Int64(count), directory: output.deletingLastPathComponent()) try handle.seek(toOffset: UInt64(offset))@@ -110,7 +110,7 @@ nonisolated enum MarkdownZIP { private static func verify(_ output: URL, data: Data, assets: [UUID: ArchiveAssetRecord], resources: ArchiveResources) throws { let zip = try Archive(url: output, accessMode: .read) let expected = try Dictionary(uniqueKeysWithValues: assets.values.map {- (try ArchiveGraphValidator.imagePath($0), ($0.byteLength, $0.sha256))+ (try ArchiveGraphValidator.originalPath($0), ($0.byteLength, $0.sha256)) }).merging(["Foodnotes.md": (Int64(data.count), ArchiveIO.digest(data))]) { first, _ in first } guard Set(zip.map(\.path)) == Set(expected.keys) else { throw ArchiveValidationError.invalidManifest } for entry in zip {
diff --git a/Foodnotes/Foodnotes/Services/Archives/MarkdownExport/MarkdownText.swift b/Foodnotes/Foodnotes/Services/Archives/MarkdownExport/MarkdownText.swiftindex 9e3ceef..f4b1203 100644--- a/Foodnotes/Foodnotes/Services/Archives/MarkdownExport/MarkdownText.swift+++ b/Foodnotes/Foodnotes/Services/Archives/MarkdownExport/MarkdownText.swift@@ -16,7 +16,7 @@ nonisolated enum MarkdownText { case .both: scope = "Both libraries" } var lines = ["# Foodnotes", "", "Scope: \(scope)", "",- "Readable notes with original images. This ZIP is not a restore archive.", ""]+ "Readable notes with original sources. This ZIP is not a restore archive.", ""] if let first = selection.firstDate { lines += ["From: \(day(first))", ""] } if let last = selection.lastDate { lines += ["Through: \(day(last))", ""] } let images = try ArchiveGraphValidator.assets(in: ArchiveRecords(graph: graph))@@ -30,14 +30,19 @@ nonisolated enum MarkdownText { } for asset in document.assets.sorted(by: { $0.assetID.uuidString < $1.assetID.uuidString }) { guard let record = images[asset.assetID] else { throw ArchiveValidationError.missingAsset }- let path = try ArchiveGraphValidator.imagePath(record)- let label = asset.role == .food ? "Food photo" : "Original source image"- lines += [")", ""]+ lines += [try originalLink(asset, record: record), ""] } } return lines.joined(separator: "\n") } + private static func originalLink(_ asset: AssetManifestEntry, record: ArchiveAssetRecord) throws -> String {+ let path = try ArchiveGraphValidator.originalPath(record)+ if asset.mediaType == "application/pdf" { return "[Original PDF receipt](\(path))" }+ let label = asset.role == .food ? "Food photo" : "Original source image"+ return ")"+ }+ private static func mealLines(_ document: MealDocument, graph: ArchiveGraph) -> [String] { let meal = document.meal let place = graph.places.first { $0.id == meal.placeID.value && $0.libraryID == meal.libraryID }?.name.value
diff --git a/Foodnotes/Foodnotes/Services/Capture/CaptureInputCoordinator.swift b/Foodnotes/Foodnotes/Services/Capture/CaptureInputCoordinator.swiftindex dcdcaa3..67a409c 100644--- a/Foodnotes/Foodnotes/Services/Capture/CaptureInputCoordinator.swift+++ b/Foodnotes/Foodnotes/Services/Capture/CaptureInputCoordinator.swift@@ -34,14 +34,15 @@ actor CaptureInputCoordinator { } func retain(_ url: URL, request: CaptureInputRequest) async throws -> HandoffScan {- let metadata = try OriginalHandoffImageFile.metadata(url)+ let metadata = try request.route == .files ? OriginalHandoffPDFFile.metadata(url) : OriginalHandoffImageFile.metadata(url) let origin: SourceCaptureOrigin switch request.route { case .camera: origin = .camera case .photos: origin = .photos+ case .files: origin = .files default: throw HandoffError.invalidSource }- let envelope = SourceEnvelope(schemaVersion: 1, operationID: request.id,+ let envelope = SourceEnvelope(schemaVersion: metadata.mediaType == "application/pdf" ? 2 : 1, operationID: request.id, partitionID: request.session.partitionID, sourceID: request.sourceID, filename: "\(request.sourceID.uuidString).original", mediaType: metadata.mediaType, byteLength: metadata.length, sha256: metadata.digest, capturedAt: request.capturedAt,
diff --git a/Foodnotes/Foodnotes/Services/Capture/CaptureReviewModel.swift b/Foodnotes/Foodnotes/Services/Capture/CaptureReviewModel.swiftindex 6c0eed8..91ef8f8 100644--- a/Foodnotes/Foodnotes/Services/Capture/CaptureReviewModel.swift+++ b/Foodnotes/Foodnotes/Services/Capture/CaptureReviewModel.swift@@ -9,8 +9,22 @@ final class CaptureReviewModel { typealias Events = @Sendable (SourceImage, UUID) -> AsyncThrowingStream<CaptureExtractionEvent, Error> var draft: Draft { didSet {- guard !closed else { return }+ guard !closed, !recordingDismissals else { return } if !applyingProposal {+ let removed = Set(oldValue.occurrences.map(\.id)).subtracting(draft.occurrences.map(\.id))+ if !removed.isEmpty, let rows = draft.receiptRows {+ recordingDismissals = true+ let retained = Set((draft.receiptDismissedOccurrences ?? []).map(\.id))+ let receiptIDs = Set(rows.map(\.occurrenceID))+ let dismissed = oldValue.occurrences.filter {+ removed.contains($0.id) && receiptIDs.contains($0.id) && !retained.contains($0.id)+ }+ draft.receiptDismissedOccurrences = (draft.receiptDismissedOccurrences ?? []) + dismissed+ draft.receiptRows = rows.map { row in+ var row = row; if removed.contains(row.occurrenceID) { row.dismissed = true }; return row+ }+ recordingDismissals = false+ } for path in Self.changedPaths(old: oldValue, new: draft) { _ = engine.updateDraft(draft, fieldPath: path) }@@ -38,7 +52,10 @@ final class CaptureReviewModel { @ObservationIgnored private var started = false @ObservationIgnored private var closed = false @ObservationIgnored private var applyingProposal = false+ @ObservationIgnored private var recordingDismissals = false @ObservationIgnored private var run = UUID()+ @ObservationIgnored private var receiptBindings: [UUID: ReceiptRowAnchor] = [:]+ @ObservationIgnored private var neverAttemptedPages: Set<String> = [] init(draft: Draft, session: AccountSession, events: Events?, retainPhoto: @escaping MealPhotoAdmission.Retain = MealPhotoAdmission.retain,@@ -59,6 +76,8 @@ final class CaptureReviewModel { needsManualEntry = draft.extractionStatus != .finished return }+ neverAttemptedPages = Set((draft.receiptPages ?? []).filter { $0.status == .pending }+ .map { "\($0.sourceID):\($0.pageIndex)" }) reading = true draft.extractionStatus = .started let claim = writes@@ -85,18 +104,21 @@ final class CaptureReviewModel { } } guard !closed, run == token else { return }+ finishReceiptPages(reason: "Page was not processed") draft.extractionStatus = .finished } catch { guard !closed, run == token else { return } needsManualEntry = true+ finishReceiptPages(reason: "Reading was interrupted") } guard run == token else { return } reading = false } func confirm(_ path: String) {+ let accepted = engine.suggestions[path] guard !closed, engine.confirm(fieldPath: path) else { return }- replaceWithProposal()+ replaceWithProposal(accepted: accepted) } /// Cancel and drain before final Save/discard/close. Late non-cooperative producers@@ -106,7 +128,14 @@ final class CaptureReviewModel { run = UUID() extraction?.cancel() engine.cancel()- if reading { needsManualEntry = true }+ if reading {+ needsManualEntry = true+ draft.receiptPages = draft.receiptPages?.map { page in+ var page = page+ if page.status == .processing || page.status == .pending { page.status = .incomplete("Reading cancelled") }+ return page+ }+ } reading = false suggestions = [:] await writes?.value@@ -127,16 +156,79 @@ final class CaptureReviewModel { private func accept(_ event: CaptureExtractionEvent) { switch event { case let .proposal(value):- if engine.apply(value) { replaceWithProposal() }+ if let value = mappedReceiptProposal(value), engine.apply(value) {+ replaceWithProposal(accepted: value.proposal.fieldPath == "ordering" ? nil : value)+ }+ case let .receiptPage(page, generation):+ guard generation == draft.generation, draft.sources.contains(where: { $0.id == page.sourceID }),+ let index = draft.receiptPages?.firstIndex(where: {+ $0.sourceID == page.sourceID && $0.pageIndex == page.pageIndex+ }) else { return }+ draft.receiptPages?[index] = page+ case let .receiptRows(rows, pageIndex, sourceID, generation):+ guard generation == draft.generation,+ draft.sources.contains(where: { $0.id == sourceID && $0.mediaType == "application/pdf" }),+ rows.allSatisfy({ $0.sourceID == sourceID && $0.pageIndex == pageIndex }) else { return }+ let old = (draft.receiptRows ?? []).filter { $0.sourceID == sourceID && $0.pageIndex == pageIndex }+ let matches = PDFReceiptRowRegistry.match(incoming: rows, existing: old,+ allowNew: neverAttemptedPages.contains("\(sourceID):\(pageIndex)"))+ receiptBindings.merge(matches) { _, new in new }+ let known = Set((draft.receiptRows ?? []).map(\.id))+ draft.receiptRows = (draft.receiptRows ?? []) + matches.values.filter { !known.contains($0.id) }+ .sorted { $0.bounds.y > $1.bounds.y }+ if matches.count != rows.count { needsManualEntry = true } case .manualFallback: needsManualEntry = true- case .completed, .evidence: break+ case let .evidence(values): rememberReceiptEvidence(values)+ case .completed: break+ }+ }++ private func finishReceiptPages(reason: String) {+ guard let pages = draft.receiptPages else { return }+ let unfinished = pages.contains { $0.status == .pending || $0.status == .processing }+ guard unfinished else { return }+ needsManualEntry = true+ draft.receiptPages = pages.map { page in+ var page = page+ if page.status == .pending || page.status == .processing { page.status = .incomplete(reason) }+ return page+ }+ }++ private func mappedReceiptProposal(_ value: ValidatedCaptureProposal) -> ValidatedCaptureProposal? {+ guard draft.sources.contains(where: { $0.id == value.sourceID && $0.mediaType == "application/pdf" }),+ value.proposal.fieldPath.hasPrefix("occurrences.") else { return value }+ let parts = value.proposal.fieldPath.split(separator: ".")+ guard parts.count == 3, let incoming = UUID(uuidString: String(parts[1])), let anchor = receiptBindings[incoming],+ draft.receiptRows?.contains(where: { $0.id == anchor.id && !$0.dismissed }) == true else { return nil }+ if parts[2] == "name", !draft.occurrences.contains(where: { $0.id == anchor.occurrenceID }),+ !neverAttemptedPages.contains("\(anchor.sourceID):\(anchor.pageIndex)") {+ needsManualEntry = true+ return nil }+ var proposal = value.proposal+ proposal.fieldPath = "occurrences.\(anchor.occurrenceID).\(parts[2])"+ proposal.evidenceIDs = [anchor.id]+ return ValidatedCaptureProposal(proposal: proposal, sourceID: value.sourceID) } - private func replaceWithProposal() {+ func retryReceipt() {+ guard !closed, !reading, draft.sources.contains(where: { $0.mediaType == "application/pdf" }) else { return }+ needsManualEntry = false+ run = UUID(); extraction?.cancel(); engine = DraftExtractionReview(draft: draft)+ receiptBindings = [:]; started = false; draft.extractionStatus = .pending+ start()+ }++ private func replaceWithProposal(accepted: ValidatedCaptureProposal? = nil) {+ var updated = engine.draft+ if let accepted { updated.rememberReceiptProposal(accepted) } applyingProposal = true- draft = engine.draft+ draft = updated applyingProposal = false+ if updated.receiptAcceptedFields != engine.draft.receiptAcceptedFields {+ _ = engine.updateDraft(updated, fieldPath: "receiptProvenance")+ } suggestions = engine.suggestions } @@ -173,3 +265,20 @@ final class CaptureReviewModel { return result } }++extension CaptureReviewModel {+ private func rememberReceiptEvidence(_ values: [SourceEvidence]) {+ let pdfIDs = Set(draft.sources.filter { $0.mediaType == "application/pdf" }.map(\.id))+ guard !pdfIDs.isEmpty else { return }+ let retained = Set((draft.receiptAcceptedFields ?? []).flatMap(\.rowIDs))+ let previous = (draft.receiptEvidence ?? []).filter { retained.contains($0.id) }+ let incoming = values.prefix(10_000).compactMap { value -> ReceiptEvidenceAnchor? in+ guard pdfIDs.contains(value.sourceID), let page = value.pageIndex,+ PDFReceiptRows.valid(value.boundingBox) else { return nil }+ return .init(id: value.id, sourceID: value.sourceID, pageIndex: page, bounds: value.boundingBox)+ }+ let known = Set(incoming.map(\.id))+ draft.receiptEvidence = incoming + previous.filter { !known.contains($0.id) }+ }++}
diff --git a/Foodnotes/Foodnotes/Services/Capture/Extraction/CaptureEvidenceChunks.swift b/Foodnotes/Foodnotes/Services/Capture/Extraction/CaptureEvidenceChunks.swiftnew file mode 100644index 0000000..9fdcf49--- /dev/null+++ b/Foodnotes/Foodnotes/Services/Capture/Extraction/CaptureEvidenceChunks.swift@@ -0,0 +1,28 @@+import Foundation+import FoodnotesDomain++nonisolated struct CaptureEvidenceChunks {+ static let maximumBytes = 1_800+ static let maximumLines = 12+ static let maximumChunks = 24++ static func make(_ evidence: [SourceEvidence]) -> [[SourceEvidence]] {+ var chunks: [[SourceEvidence]] = []+ var current: [SourceEvidence] = []+ var size = 0+ for line in evidence {+ let bytes = line.text.utf8.count + 40+ guard bytes <= maximumBytes else { continue }+ if size + bytes > maximumBytes || current.count == maximumLines {+ chunks.append(current)+ current = []+ size = 0+ }+ guard chunks.count < maximumChunks else { break }+ current.append(line)+ size += bytes+ }+ if !current.isEmpty && chunks.count < maximumChunks { chunks.append(current) }+ return chunks+ }+}
diff --git a/Foodnotes/Foodnotes/Services/Capture/Extraction/CaptureReceiptTimestamps.swift b/Foodnotes/Foodnotes/Services/Capture/Extraction/CaptureReceiptTimestamps.swiftnew file mode 100644index 0000000..5c61aeb--- /dev/null+++ b/Foodnotes/Foodnotes/Services/Capture/Extraction/CaptureReceiptTimestamps.swift@@ -0,0 +1,39 @@+import FoodnotesDomain+import Foundation++/// Image and PDF receipts share conservative invalid/conflicting-date semantics.+nonisolated enum CaptureReceiptTimestamps {+ static func values(_ evidence: [SourceEvidence], generation: UUID, editVersions: [String: UInt64] = [:],+ timeZoneIdentifier: String, localeIdentifier: String,+ candidates: [CaptureCandidate]? = nil) -> [ValidatedCaptureProposal] {+ let pairs = (candidates ?? ReceiptTimestampCandidates().candidates(evidence)).map { candidate in+ (candidate, CaptureProposalValidator().validate(candidate, evidence: evidence, generation: generation,+ expectedEditVersion: editVersions[candidate.kind.rawValue] ?? 0,+ timeZoneIdentifier: timeZoneIdentifier, localeIdentifier: localeIdentifier))+ }+ let dates = pairs.filter { $0.0.kind == .date }+ guard dates.allSatisfy({ $0.1 != nil }), Set(dates.compactMap { $0.1?.proposal.value }).count <= 1 else { return [] }+ let groups = Dictionary(grouping: pairs.compactMap { $0.1 }, by: \.proposal.fieldPath)+ return groups.keys.sorted().compactMap { key in+ guard let values = groups[key], Set(values.map(\.proposal.value)).count == 1 else { return nil }+ return values.sorted { $0.proposal.evidenceIDs[0].uuidString < $1.proposal.evidenceIDs[0].uuidString }.first+ }+ }+ static func pdfValues(pages: [[SourceEvidence]], generation: UUID,+ timeZoneIdentifier: String, localeIdentifier: String) -> [ValidatedCaptureProposal] {+ var candidates: [CaptureCandidate] = [], seen: Set<String> = []+ for page in pages {+ // One-line overlap preserves split labels across the existing bounded parser windows.+ for offset in stride(from: 0, to: page.count, by: 287) {+ for candidate in ReceiptTimestampCandidates().candidates(Array(page[offset..<min(offset + 288, page.count)])) {+ // The overlapping row is context only; its prior window already checked its preceding label.+ if offset > 0, candidate.evidenceID == page[offset].id { continue }+ let key = "\(candidate.evidenceID):\(candidate.kind):\(candidate.copiedText)"+ if seen.insert(key).inserted { candidates.append(candidate) }+ }+ }+ }+ return values(pages.flatMap { $0 }, generation: generation, timeZoneIdentifier: timeZoneIdentifier,+ localeIdentifier: localeIdentifier, candidates: candidates)+ }+}
diff --git a/Foodnotes/Foodnotes/Services/Capture/Extraction/ExtractionReview.swift b/Foodnotes/Foodnotes/Services/Capture/Extraction/ExtractionReview.swiftindex 822d4aa..34eafb2 100644--- a/Foodnotes/Foodnotes/Services/Capture/Extraction/ExtractionReview.swift+++ b/Foodnotes/Foodnotes/Services/Capture/Extraction/ExtractionReview.swift@@ -13,7 +13,7 @@ nonisolated struct DraftExtractionReview { mutating func apply(_ value: ValidatedCaptureProposal) -> Bool { guard canApply(value) else { return false } let path = value.proposal.fieldPath- if path == "place" || path == "ordering" { suggestions[path] = value; return true }+ if path == "ordering" { suggestions[path] = value; return true } return assign(value) } @@ -41,6 +41,16 @@ nonisolated struct DraftExtractionReview { let proposal = value.proposal guard active, draft.generation == proposal.generation, !blocked.contains(proposal.fieldPath), draft.sources.contains(where: { $0.id == value.sourceID }) else { return false }+ if proposal.fieldPath == "place", draft.confirmedPlaceID != nil || draft.confirmedOrdering != nil { return false }+ if draft.sources.contains(where: { $0.id == value.sourceID && $0.mediaType == "application/pdf" }),+ proposal.fieldPath.hasPrefix("occurrences.") {+ let parts = proposal.fieldPath.split(separator: ".")+ guard parts.count == 3, let occurrenceID = UUID(uuidString: String(parts[1])),+ draft.receiptRows?.contains(where: {+ $0.sourceID == value.sourceID && $0.occurrenceID == occurrenceID && !$0.dismissed+ }) == true+ else { return false }+ } if proposal.fieldPath == "date" { return proposal.expectedEditVersion == 0 && draft.date.provenance == .defaultValue } if proposal.fieldPath == "time" { return proposal.expectedEditVersion == 0 && draft.time == nil } guard let field = field(at: proposal.fieldPath) else {
diff --git a/Foodnotes/Foodnotes/Services/Capture/Extraction/ExtractionTypes.swift b/Foodnotes/Foodnotes/Services/Capture/Extraction/ExtractionTypes.swiftindex 232bf58..ca8569a 100644--- a/Foodnotes/Foodnotes/Services/Capture/Extraction/ExtractionTypes.swift+++ b/Foodnotes/Foodnotes/Services/Capture/Extraction/ExtractionTypes.swift@@ -1,16 +1,23 @@ import Foundation import FoodnotesDomain -nonisolated enum CaptureFieldKind: String, Codable, Sendable {+nonisolated enum CaptureFieldKind: String, Codable, Sendable, Hashable { case place, ordering, date, time, dish, quantity, price } -nonisolated struct CaptureCandidate: Codable, Sendable, Equatable {+nonisolated struct CaptureCandidate: Codable, Sendable, Hashable { var kind: CaptureFieldKind var copiedText: String var evidenceID: UUID } +nonisolated struct CaptureModelBatch: Sendable {+ static let maximumCandidates = 12+ let candidates: [CaptureCandidate]+ /// Raw generation reached its limit, including entries rejected during decoding.+ let outputLimitReached: Bool+}+ nonisolated enum CaptureFallback: String, Codable, Sendable { case modelUnavailable, unsupportedLanguage, ocrFailed, noText, generationFailed, evidenceUnavailable, inputLimit }@@ -28,6 +35,8 @@ nonisolated enum CaptureExtractionEvent: Sendable { case evidence([SourceEvidence]) case proposal(ValidatedCaptureProposal) case manualFallback(CaptureFallback)+ case receiptPage(ReceiptPageState, generation: UUID)+ case receiptRows([ReceiptRowAnchor], pageIndex: Int, sourceID: UUID, generation: UUID) case completed } @@ -38,6 +47,14 @@ nonisolated protocol CaptureOCR: Sendable { nonisolated protocol CaptureProposalModel: Sendable { func availability(localeIdentifier: String) async -> CaptureModelAvailability func candidates(in evidence: [SourceEvidence], localeIdentifier: String) async throws -> [CaptureCandidate]+ func batch(in evidence: [SourceEvidence], localeIdentifier: String) async throws -> CaptureModelBatch+}++nonisolated extension CaptureProposalModel {+ func batch(in evidence: [SourceEvidence], localeIdentifier: String) async throws -> CaptureModelBatch {+ let values = try await candidates(in: evidence, localeIdentifier: localeIdentifier)+ return .init(candidates: values, outputLimitReached: values.count >= CaptureModelBatch.maximumCandidates)+ } } nonisolated protocol CaptureEvidenceStore: Sendable {
diff --git a/Foodnotes/Foodnotes/Services/Capture/Extraction/FoundationCaptureModel.swift b/Foodnotes/Foodnotes/Services/Capture/Extraction/FoundationCaptureModel.swiftindex 85c8b36..1bd9725 100644--- a/Foodnotes/Foodnotes/Services/Capture/Extraction/FoundationCaptureModel.swift+++ b/Foodnotes/Foodnotes/Services/Capture/Extraction/FoundationCaptureModel.swift@@ -26,9 +26,15 @@ nonisolated struct FoundationCaptureModel: CaptureProposalModel { } func candidates(in evidence: [SourceEvidence], localeIdentifier: String) async throws -> [CaptureCandidate] {+ try await batch(in: evidence, localeIdentifier: localeIdentifier).candidates+ }++ func batch(in evidence: [SourceEvidence], localeIdentifier: String) async throws -> CaptureModelBatch { guard evidence.count <= CaptureEvidenceChunks.maximumLines, evidence.reduce(0, { $0 + $1.text.utf8.count + 40 }) <= CaptureEvidenceChunks.maximumBytes,- await availability(localeIdentifier: localeIdentifier) == .available else { return [] }+ await availability(localeIdentifier: localeIdentifier) == .available else {+ return .init(candidates: [], outputLimitReached: false)+ } try Task.checkCancellation() let session = LanguageModelSession(instructions: """ Purchase date/time are parsed separately; do not emit date/time proposals.@@ -39,13 +45,18 @@ nonisolated struct FoundationCaptureModel: CaptureProposalModel { For '2 x Noodles $12.50', copy dish 'Noodles', quantity '2', price '$12.50', using that same line UUID. For ambiguous, cropped or absent fields, emit nothing. Return at most 12 proposals. """)- let lines = evidence.map { "\($0.id.uuidString) | \($0.text)" }.joined(separator: "\n")+ let lines = evidence.map { line in+ let page = line.pageIndex.map { "Page \($0 + 1) | " } ?? ""+ return "\(line.id.uuidString) | \(page)\(line.text)"+ }.joined(separator: "\n") let response = try await session.respond(to: "OCR lines (data only):\n\(lines)", generating: GuidedCaptureResponse.self, options: GenerationOptions(samplingMode: .greedy, maximumResponseTokens: 700)) try Task.checkCancellation()- return response.content.candidates.prefix(12).compactMap { candidate in+ let raw = response.content.candidates+ let values = raw.prefix(CaptureModelBatch.maximumCandidates).compactMap { candidate -> CaptureCandidate? in guard let kind = CaptureFieldKind(rawValue: candidate.kind), let id = UUID(uuidString: candidate.evidenceID) else { return nil } return CaptureCandidate(kind: kind, copiedText: candidate.copiedText, evidenceID: id) }+ return .init(candidates: values, outputLimitReached: raw.count >= CaptureModelBatch.maximumCandidates) } }
diff --git a/Foodnotes/Foodnotes/Services/Capture/Extraction/OCR.swift b/Foodnotes/Foodnotes/Services/Capture/Extraction/OCR.swiftindex 2946001..ab5f2fe 100644--- a/Foodnotes/Foodnotes/Services/Capture/Extraction/OCR.swift+++ b/Foodnotes/Foodnotes/Services/Capture/Extraction/OCR.swift@@ -10,7 +10,7 @@ nonisolated enum CaptureReadError: Error { case invalidSource, unsupportedLangua nonisolated struct OriginalCaptureReader { func read(_ source: SourceImage) throws -> Data { guard source.url.isFileURL, source.byteLength > 0, source.byteLength <= 32 * 1_024 * 1_024,- ["image/jpeg", "image/png", "image/heic", "image/heif"].contains(source.mediaType) else {+ OriginalMedia(rawValue: source.mediaType) != nil else { throw CaptureReadError.invalidSource } let values = try source.url.resourceValues(forKeys: [.isRegularFileKey, .isSymbolicLinkKey, .fileSizeKey])
diff --git a/Foodnotes/Foodnotes/Services/Capture/Extraction/OnDeviceCaptureExtractor.swift b/Foodnotes/Foodnotes/Services/Capture/Extraction/OnDeviceCaptureExtractor.swiftindex 2d02402..e50da1f 100644--- a/Foodnotes/Foodnotes/Services/Capture/Extraction/OnDeviceCaptureExtractor.swift+++ b/Foodnotes/Foodnotes/Services/Capture/Extraction/OnDeviceCaptureExtractor.swift@@ -1,32 +1,6 @@ import Foundation import FoodnotesDomain -nonisolated struct CaptureEvidenceChunks {- static let maximumBytes = 1_800- static let maximumLines = 12- static let maximumChunks = 24-- static func make(_ evidence: [SourceEvidence]) -> [[SourceEvidence]] {- var chunks: [[SourceEvidence]] = []- var current: [SourceEvidence] = []- var size = 0- for line in evidence {- let bytes = line.text.utf8.count + 40- guard bytes <= maximumBytes else { continue }- if size + bytes > maximumBytes || current.count == maximumLines {- chunks.append(current)- current = []- size = 0- }- guard chunks.count < maximumChunks else { break }- current.append(line)- size += bytes- }- if !current.isEmpty && chunks.count < maximumChunks { chunks.append(current) }- return chunks- }-}- nonisolated struct OnDeviceCaptureExtractor: CaptureExtractor { let ocr: any CaptureOCR let model: any CaptureProposalModel@@ -58,7 +32,11 @@ nonisolated struct OnDeviceCaptureExtractor: CaptureExtractor { /// Rich events retain provenance and manual-fallback state for the existing review UI. func events(_ source: SourceImage, generation: UUID, editVersions: [String: UInt64] = [:]) -> AsyncThrowingStream<CaptureExtractionEvent, Error> {- AsyncThrowingStream { continuation in+ if source.mediaType == "application/pdf" {+ return PDFCaptureExtractor(model: model, evidenceStore: evidenceStore,+ localeIdentifier: localeIdentifier, timeZoneIdentifier: timeZoneIdentifier).events(source, generation: generation)+ }+ return AsyncThrowingStream { continuation in let worker = Task { do { try await run(source, generation: generation, editVersions: editVersions, continuation: continuation)@@ -138,15 +116,8 @@ nonisolated struct OnDeviceCaptureExtractor: CaptureExtractor { private func receiptValues(_ evidence: [SourceEvidence], generation: UUID, editVersions: [String: UInt64]) -> [ValidatedCaptureProposal] {- let validator = CaptureProposalValidator(), candidates = ReceiptTimestampCandidates().candidates(evidence)- let pairs = candidates.map { candidate in- (candidate, validator.validate(candidate, evidence: evidence, generation: generation,- expectedEditVersion: editVersions[candidate.kind.rawValue] ?? 0,- timeZoneIdentifier: timeZoneIdentifier, localeIdentifier: localeIdentifier))- }- let dates = pairs.filter { $0.0.kind == .date }- guard dates.allSatisfy({ $0.1 != nil }), Set(dates.compactMap { $0.1?.proposal.value }).count <= 1 else { return [] }- return unambiguous(pairs.compactMap { $0.1 })+ CaptureReceiptTimestamps.values(evidence, generation: generation, editVersions: editVersions,+ timeZoneIdentifier: timeZoneIdentifier, localeIdentifier: localeIdentifier) } private func validated(_ candidates: [CaptureCandidate], evidence: [SourceEvidence], generation: UUID,
diff --git a/Foodnotes/Foodnotes/Services/Capture/Extraction/PDFCaptureExtractor.swift b/Foodnotes/Foodnotes/Services/Capture/Extraction/PDFCaptureExtractor.swiftnew file mode 100644index 0000000..7044f53--- /dev/null+++ b/Foodnotes/Foodnotes/Services/Capture/Extraction/PDFCaptureExtractor.swift@@ -0,0 +1,170 @@+import FoodnotesDomain+import Foundation++/// PDF work is page-aware. Existing-size batches and a per-page cap bound model work;+/// omitted evidence is explicitly incomplete and remains available for manual review.+nonisolated struct PDFCaptureExtractor: Sendable {+ static let maximumModelBatchesPerPage = CaptureEvidenceChunks.maximumChunks+ static let maximumModelBatchesPerDocument = 20+ let model: any CaptureProposalModel+ let evidenceStore: any CaptureEvidenceStore+ var loadPages: @Sendable (SourceImage) async throws -> [PDFPageEvidence] = { source in+ try await PDFReceiptEvidence().collect(source, preferNative: true, consume: VisionPDFReceiptOCR(sourceID: source.id).recognize)+ }+ var localeIdentifier = "en_AU"+ var timeZoneIdentifier = "Australia/Melbourne"++ func events(_ source: SourceImage, generation: UUID) -> AsyncThrowingStream<CaptureExtractionEvent, Error> {+ AsyncThrowingStream { continuation in+ let worker = Task {+ do {+ try await run(source, generation: generation, continuation: continuation)+ continuation.yield(.completed)+ continuation.finish()+ } catch is CancellationError { continuation.finish(throwing: CancellationError()) } catch {+ continuation.yield(.manualFallback(.ocrFailed)); continuation.finish()+ }+ }+ continuation.onTermination = { _ in worker.cancel() }+ }+ }+ private func run(_ source: SourceImage, generation: UUID,+ continuation: AsyncThrowingStream<CaptureExtractionEvent, Error>.Continuation) async throws {+ let pages = try await loadPages(source).sorted { $0.pageIndex < $1.pageIndex }+ guard (1...20).contains(pages.count), pages.map(\.pageIndex) == Array(0..<pages.count) else {+ throw CaptureReadError.invalidSource+ }+ let assemblies = PDFReceiptRows.document(pages.map { Array($0.evidence.prefix(500)) })+ let rows = assemblies.map(\.rows)+ let tables = PDFReceiptTable.document(rows)+ let evidence = rows.flatMap { $0.map(\.evidence) }+ guard evidence.allSatisfy({ $0.sourceID == source.id }), Set(evidence.map(\.id)).count == evidence.count else {+ throw CaptureReadError.invalidSource+ }+ do {+ try await evidenceStore.save(evidence, source: source, generation: generation,+ parserVersion: CaptureProposalValidator.parserVersion)+ } catch is CancellationError { throw CancellationError() } catch {+ for page in pages { publish(page.pageIndex, source: source, generation: generation,+ status: .incomplete("Evidence could not be retained"), continuation: continuation) }+ continuation.yield(.manualFallback(.evidenceUnavailable)); return+ }+ continuation.yield(.evidence(evidence))+ let availability = await model.availability(localeIdentifier: localeIdentifier)+ var metadata = CaptureReceiptTimestamps.pdfValues(pages: rows.map { $0.map(\.evidence) }, generation: generation,+ timeZoneIdentifier: timeZoneIdentifier, localeIdentifier: localeIdentifier)+ let declared = PDFReceiptMetadata.values(evidence, generation: generation)+ let declaredPaths = Set(declared.map(\.proposal.fieldPath))+ var remainingBatches = Self.maximumModelBatchesPerDocument+ for (index, original) in pages.enumerated() {+ try Task.checkCancellation()+ let page = PDFPageEvidence(pageIndex: original.pageIndex, evidence: original.evidence,+ failure: original.failure ?? (assemblies[index].omitted ? "Page columns could not be associated safely" : nil))+ // Reserve a fair share for every remaining page; unused work carries forward.+ let allowance = min(Self.maximumModelBatchesPerPage, remainingBatches / (pages.count - index))+ let chunks = Array(CaptureEvidenceChunks.make(rows[index].map(\.evidence)).prefix(allowance))+ if availability == .available { remainingBatches -= chunks.count }+ metadata += try await process(page, rows: rows[index], table: tables[index], chunks: chunks,+ source: source, generation: generation,+ availability: availability, declaredPaths: declaredPaths, continuation: continuation)+ }+ metadata = metadata.filter { !declaredPaths.contains($0.proposal.fieldPath) } + declared+ for values in Dictionary(grouping: metadata, by: \.proposal.fieldPath).values+ where Set(values.map(\.proposal.value)).count == 1 {+ if let value = values.first { continuation.yield(.proposal(value)) }+ }+ }++ private func process(_ page: PDFPageEvidence, rows: [PDFReceiptRow], table: PDFReceiptTable.Page,+ chunks: [[SourceEvidence]], source: SourceImage, generation: UUID,+ availability: CaptureModelAvailability,+ declaredPaths: Set<String>,+ continuation: AsyncThrowingStream<CaptureExtractionEvent, Error>.Continuation)+ async throws -> [ValidatedCaptureProposal] {+ publish(page.pageIndex, source: source, generation: generation, status: .processing, continuation: continuation)+ var incomplete = page.failure+ if table.omitted { incomplete = "Table columns could not be associated safely" }+ if page.evidence.count > 500 { incomplete = "Page text limit reached" }+ if chunks.flatMap({ $0 }).count != rows.count {+ incomplete = "Page contains more text than the automatic reading budget"+ }+ var metadata: [ValidatedCaptureProposal] = []+ if rows.isEmpty {+ continuation.yield(.manualFallback(.noText))+ } else if availability != .available {+ incomplete = "On-device extraction is unavailable"+ } else {+ let selected = Set(chunks.flatMap { $0 }.map(\.id))+ let anchors = rows.filter { $0.role == .item && selected.contains($0.evidence.id) }.map { row in+ ReceiptRowAnchor(id: row.evidence.id, sourceID: source.id, pageIndex: page.pageIndex,+ bounds: row.evidence.boundingBox, occurrenceID: row.evidence.id)+ }+ continuation.yield(.receiptRows(anchors, pageIndex: page.pageIndex, sourceID: source.id, generation: generation))+ let selectedEvidence = chunks.flatMap { $0 }+ for candidate in table.candidates where selected.contains(candidate.evidenceID) {+ if let value = CaptureProposalValidator().validate(candidate, evidence: selectedEvidence, generation: generation,+ timeZoneIdentifier: timeZoneIdentifier, localeIdentifier: localeIdentifier) {+ continuation.yield(.proposal(value))+ } else { incomplete = "Some table values could not be associated safely" }+ }+ for price in table.unitPrices where selected.contains(price.evidenceID) {+ if let value = PDFReceiptTable.proposal(price, evidence: selectedEvidence, generation: generation) {+ continuation.yield(.proposal(value))+ } else { incomplete = "Some table prices could not be associated safely" }+ }+ let result = try await generate(chunks, rows: rows, protectedRows: table.protectedRows,+ declaredPaths: declaredPaths, generation: generation, continuation: continuation)+ metadata = result.metadata+ incomplete = result.failure ?? incomplete+ }+ if let incomplete {+ continuation.yield(.manualFallback(availability == .unavailable ? .modelUnavailable : .inputLimit))+ publish(page.pageIndex, source: source, generation: generation,+ status: .incomplete(incomplete), continuation: continuation)+ } else { publish(page.pageIndex, source: source, generation: generation, status: .processed, continuation: continuation) }+ return metadata+ }++ private func generate(_ chunks: [[SourceEvidence]], rows: [PDFReceiptRow], protectedRows: Set<UUID>,+ declaredPaths: Set<String>, generation: UUID,+ continuation: AsyncThrowingStream<CaptureExtractionEvent, Error>.Continuation)+ async throws -> (metadata: [ValidatedCaptureProposal], failure: String?) {+ var metadata: [ValidatedCaptureProposal] = [], failure: String?+ let roles = Dictionary(uniqueKeysWithValues: rows.map { ($0.evidence.id, $0.role) })+ for chunk in chunks {+ try Task.checkCancellation()+ let work = chunk.filter {+ !PDFModelWork.kinds(for: $0.text, role: roles[$0.id] ?? .unknown,+ protected: protectedRows.contains($0.id), declaredPaths: declaredPaths).isEmpty+ }+ guard !work.isEmpty else { continue }+ do {+ let batch = try await model.batch(in: work, localeIdentifier: localeIdentifier)+ if batch.outputLimitReached { failure = "Automatic proposal limit reached; check remaining items manually" }+ try Task.checkCancellation()+ var seen: Set<CaptureCandidate> = []+ for candidate in batch.candidates.prefix(CaptureModelBatch.maximumCandidates)+ .sorted(by: { $0.kind == .dish && $1.kind != .dish }) {+ guard seen.insert(candidate).inserted, let line = work.first(where: { $0.id == candidate.evidenceID }),+ PDFModelWork.kinds(for: line.text, role: roles[line.id] ?? .unknown,+ protected: protectedRows.contains(line.id), declaredPaths: declaredPaths).contains(candidate.kind)+ else { continue }+ guard let value = CaptureProposalValidator().validate(candidate, evidence: work, generation: generation,+ timeZoneIdentifier: timeZoneIdentifier, localeIdentifier: localeIdentifier) else { continue }+ if value.proposal.fieldPath.hasPrefix("occurrences.") {+ continuation.yield(.proposal(value))+ } else { metadata.append(value) }+ }+ } catch is CancellationError { throw CancellationError() } catch {+ failure = "Automatic reading failed for this page"+ continuation.yield(.manualFallback(.generationFailed))+ }+ }+ return (metadata, failure)+ }++ private func publish(_ page: Int, source: SourceImage, generation: UUID, status: ReceiptPageState.Status,+ continuation: AsyncThrowingStream<CaptureExtractionEvent, Error>.Continuation) {+ continuation.yield(.receiptPage(.init(sourceID: source.id, pageIndex: page, status: status), generation: generation))+ }+}
diff --git a/Foodnotes/Foodnotes/Services/Capture/Extraction/PDFModelWork.swift b/Foodnotes/Foodnotes/Services/Capture/Extraction/PDFModelWork.swiftnew file mode 100644index 0000000..1b9870a--- /dev/null+++ b/Foodnotes/Foodnotes/Services/Capture/Extraction/PDFModelWork.swift@@ -0,0 +1,16 @@+import Foundation++/// Ask the model only for fields it can still contribute. Date/time and typed-table fields have other readers.+nonisolated enum PDFModelWork {+ static func kinds(for text: String, role: PDFReceiptRow.Role, protected: Bool,+ declaredPaths: Set<String>) -> Set<CaptureFieldKind> {+ var kinds: Set<CaptureFieldKind> = []+ if role == .item && !protected { kinds.formUnion([.dish, .quantity, .price]) }+ if !declaredPaths.contains("place") { kinds.insert(.place) }+ if !declaredPaths.contains("ordering"), !PDFReceiptMetadata.isFulfilmentEvent(text),+ text.range(of: "\\b(?:delivery|pick[ -]?up|dine[ -]in)\\b", options: [.regularExpression, .caseInsensitive]) != nil {+ kinds.insert(.ordering)+ }+ return kinds+ }+}
diff --git a/Foodnotes/Foodnotes/Services/Capture/Extraction/PDFReceiptEvidence.swift b/Foodnotes/Foodnotes/Services/Capture/Extraction/PDFReceiptEvidence.swiftnew file mode 100644index 0000000..b03c94a--- /dev/null+++ b/Foodnotes/Foodnotes/Services/Capture/Extraction/PDFReceiptEvidence.swift@@ -0,0 +1,123 @@+import CoreGraphics+import FoodnotesDomain+import Foundation+import PDFKit++nonisolated struct PDFPageEvidence: Sendable {+ let pageIndex: Int+ let evidence: [SourceEvidence]+ let failure: String?+}++/// Each detached worker owns its PDFKit objects. The page consumer must finish before the next raster is allocated.+nonisolated struct PDFReceiptEvidence: Sendable {+ typealias Allocator = @Sendable (Int, Int) -> CGContext?+ var allocate: Allocator = { width, height in+ CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: width * 4,+ space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)+ }++ func collect(_ source: SourceImage, preferNative: Bool = false,+ consume: @escaping @Sendable (Int, CGImage) throws -> [SourceEvidence]) async throws -> [PDFPageEvidence] {+ let worker = Task.detached(priority: .userInitiated) {+ let admitted = try PDFReceiptAdmission().read(source)+ guard let document = PDFDocument(data: admitted.bytes) else { throw CaptureReadError.invalidSource }+ var results: [PDFPageEvidence] = []+ for index in 0..<admitted.pageCount {+ try Task.checkCancellation()+ let result: PDFPageEvidence = try autoreleasepool {+ do {+ guard let page = document.page(at: index) else { throw CaptureReadError.invalidSource }+ let native = preferNative ? nativeText(page, sourceID: source.id, pageIndex: index) :+ PDFPageEvidence(pageIndex: index, evidence: [], failure: nil)+ if PDFReceiptRows.nativeUsable(native.evidence) { return native }+ guard let image = render(page) else {+ throw CaptureReadError.invalidSource+ }+ let evidence = try consume(index, image)+ try Task.checkCancellation()+ let bounded = Self.boundedPage(evidence, pageIndex: index)+ return PDFPageEvidence(pageIndex: index, evidence: bounded.evidence, failure: native.failure ?? bounded.failure)+ } catch is CancellationError { throw CancellationError() } catch {+ return PDFPageEvidence(pageIndex: index, evidence: [], failure: "Page could not be processed")+ }+ }+ results.append(result)+ }+ return results+ }+ return try await withTaskCancellationHandler { try await worker.value } onCancel: { worker.cancel() }+ }++ private func nativeText(_ page: PDFPage, sourceID: UUID, pageIndex: Int) -> PDFPageEvidence {+ guard let reference = page.pageRef,+ let selection = page.selection(for: page.bounds(for: .cropBox)) else {+ return .init(pageIndex: pageIndex, evidence: [], failure: nil)+ }+ let transform = reference.getDrawingTransform(.cropBox, rect: CGRect(x: 0, y: 0, width: 1, height: 1),+ rotate: 0, preserveAspectRatio: false)+ let selections = selection.selectionsByLine().prefix(501).enumerated().map { index, line in+ let text = (line.string ?? "").components(separatedBy: .controlCharacters).joined(separator: " ")+ .trimmingCharacters(in: .whitespacesAndNewlines)+ let rect = line.bounds(for: page).applying(transform)+ let box = EvidenceRectangle(x: rect.minX, y: rect.minY, width: rect.width, height: rect.height)+ return SourceEvidence(id: PDFEvidenceIdentity.make(source: sourceID, page: pageIndex,+ method: "native.v1", index: index, text: text), sourceID: sourceID,+ text: text, boundingBox: box, pageIndex: pageIndex)+ }+ return Self.boundedPage(selections, pageIndex: pageIndex)+ }++ static func boundedPage(_ raw: [SourceEvidence], pageIndex: Int) -> PDFPageEvidence {+ let admitted = raw.prefix(500)+ let evidence = admitted.filter { !$0.text.isEmpty && $0.text.utf8.count <= 1_800 && PDFReceiptRows.valid($0.boundingBox) }+ return .init(pageIndex: pageIndex, evidence: evidence,+ failure: raw.count > 500 || evidence.count != admitted.count ? "Some page text exceeded processing limits" : nil)+ }++ /// Divide by the long edge first so neither tiny products nor huge crop boxes can overflow.+ static func rasterDimensions(width: Double, height: Double) -> (width: Int, height: Int)? {+ guard width.isFinite, height.isFinite, width > 0, height > 0 else { return nil }+ let long = max(width, height)+ let ratio = min(width, height) / long+ guard ratio.isFinite, ratio > 0 else { return nil }+ let edge = min(2_048, sqrt(4_000_000 / ratio))+ let projectedWidth = max(1, floor(width / long * edge))+ let projectedHeight = max(1, floor(height / long * edge))+ guard projectedWidth.isFinite, projectedHeight.isFinite,+ (1...2_048).contains(projectedWidth), (1...2_048).contains(projectedHeight),+ projectedWidth * projectedHeight <= 4_000_000 else { return nil }+ return (Int(projectedWidth), Int(projectedHeight))+ }++ static func pixelScale(width: Double, height: Double, pixelsWide: Int, pixelsHigh: Int) -> CGAffineTransform? {+ guard width.isFinite, height.isFinite, width > 0, height > 0,+ (1...2_048).contains(pixelsWide), (1...2_048).contains(pixelsHigh) else { return nil }+ let x = Double(pixelsWide) / width, y = Double(pixelsHigh) / height+ guard x.isFinite, y.isFinite, x > 0, y > 0 else { return nil }+ return CGAffineTransform(scaleX: x, y: y)+ }++ private func render(_ page: PDFPage) -> CGImage? {+ let bounds = page.bounds(for: .cropBox)+ guard [bounds.minX, bounds.minY, bounds.maxX, bounds.maxY, bounds.width, bounds.height].allSatisfy(\.isFinite),+ bounds.width > 0, bounds.height > 0 else { return nil }+ let rotated = abs(page.rotation % 180) == 90+ let width = rotated ? bounds.height : bounds.width+ let height = rotated ? bounds.width : bounds.height+ guard let size = Self.rasterDimensions(width: width, height: height) else { return nil }+ let pixelsWide = size.width, pixelsHigh = size.height+ guard let scale = Self.pixelScale(width: width, height: height, pixelsWide: pixelsWide, pixelsHigh: pixelsHigh),+ let reference = page.pageRef else { return nil }+ let transform = reference.getDrawingTransform(.cropBox,+ rect: CGRect(x: 0, y: 0, width: width, height: height), rotate: 0, preserveAspectRatio: true).concatenating(scale)+ guard [transform.a, transform.b, transform.c, transform.d, transform.tx, transform.ty].allSatisfy(\.isFinite),+ let context = allocate(pixelsWide, pixelsHigh) else { return nil }+ context.setFillColor(CGColor(gray: 1, alpha: 1))+ context.fill(CGRect(x: 0, y: 0, width: pixelsWide, height: pixelsHigh))+ // CGPDF drawing transforms center a page rather than upscaling it. Scale explicitly first.+ context.concatenate(transform)+ context.drawPDFPage(reference)+ return context.makeImage()+ }+}
diff --git a/Foodnotes/Foodnotes/Services/Capture/Extraction/PDFReceiptMetadata.swift b/Foodnotes/Foodnotes/Services/Capture/Extraction/PDFReceiptMetadata.swiftnew file mode 100644index 0000000..c15147d--- /dev/null+++ b/Foodnotes/Foodnotes/Services/Capture/Extraction/PDFReceiptMetadata.swift@@ -0,0 +1,51 @@+import Foundation+import FoodnotesDomain++/// Explicit receipt declarations outrank model guesses; values still require verbatim source validation.+nonisolated enum PDFReceiptMetadata {+ static func values(_ evidence: [SourceEvidence], generation: UUID) -> [ValidatedCaptureProposal] {+ evidence.flatMap { line -> [ValidatedCaptureProposal] in+ var candidates: [CaptureCandidate] = []+ if let merchant = capture("^We adjusted the total for your recent order from (.+)\\.$", in: line.text) {+ candidates.append(.init(kind: .place, copiedText: merchant, evidenceID: line.id))+ }+ if let mode = capture("^Uber (Delivery|Pick-up|Pickup|Dine in)$", in: line.text) {+ candidates.append(.init(kind: .ordering, copiedText: mode, evidenceID: line.id))+ }+ return candidates.compactMap {+ CaptureProposalValidator().validate($0, evidence: [line], generation: generation)+ }+ } + invoiceMerchants(evidence, generation: generation)+ }++ private static func invoiceMerchants(_ evidence: [SourceEvidence], generation: UUID) -> [ValidatedCaptureProposal] {+ guard evidence.count >= 5 else { return [] }+ return (2..<(evidence.count - 2)).compactMap { index in+ let issuer = evidence[index - 2], label = evidence[index - 1]+ let company = evidence[index], merchant = evidence[index + 1], locality = evidence[index + 2]+ guard issuer.text.localizedCaseInsensitiveContains("Invoice issued by Portier Pacific Pty Ltd on"),+ label.text.lowercased().hasSuffix("behalf of:"),+ company.text.range(of: "\\bPTY\\.?\\s+LTD\\.?$", options: [.regularExpression, .caseInsensitive]) != nil,+ merchant.text.contains(where: \.isLetter),+ locality.text.range(of: "^[0-9]{4},", options: .regularExpression) != nil,+ [issuer, label, merchant, locality].allSatisfy({ $0.pageIndex == company.pageIndex && $0.sourceID == company.sourceID }),+ abs(company.boundingBox.x - merchant.boundingBox.x) <= 0.02,+ abs(merchant.boundingBox.x - locality.boundingBox.x) <= 0.02,+ company.boundingBox.y > merchant.boundingBox.y, merchant.boundingBox.y > locality.boundingBox.y else { return nil }+ return CaptureProposalValidator().validate(.init(kind: .place,+ copiedText: merchant.text, evidenceID: merchant.id), evidence: [merchant], generation: generation)+ }+ }++ static func isFulfilmentEvent(_ text: String) -> Bool {+ text.range(of: "^[0-9]{1,2}:[0-9]{2}\\s*[ap]m\\s*[-–]\\s*(?:Pick-up|Delivery)$",+ options: [.regularExpression, .caseInsensitive]) != nil+ }++ private static func capture(_ pattern: String, in text: String) -> String? {+ guard let expression = try? NSRegularExpression(pattern: pattern, options: .caseInsensitive),+ let match = expression.firstMatch(in: text, range: NSRange(text.startIndex..., in: text)),+ let range = Range(match.range(at: 1), in: text) else { return nil }+ return String(text[range])+ }+}
diff --git a/Foodnotes/Foodnotes/Services/Capture/Extraction/PDFReceiptRows.swift b/Foodnotes/Foodnotes/Services/Capture/Extraction/PDFReceiptRows.swiftnew file mode 100644index 0000000..3f6d4a7--- /dev/null+++ b/Foodnotes/Foodnotes/Services/Capture/Extraction/PDFReceiptRows.swift@@ -0,0 +1,157 @@+import FoodnotesDomain+import Foundation++nonisolated struct PDFReceiptRow: Sendable {+ enum Role: Sendable { case item, metadata, excluded, unknown }+ var evidence: SourceEvidence+ let role: Role+}++nonisolated enum PDFReceiptRows {+ static func nativeUsable(_ fragments: [SourceEvidence]) -> Bool { assemble(fragments).contains { $0.role == .item } }++ static func assemble(_ fragments: [SourceEvidence]) -> [PDFReceiptRow] { assembly(fragments).rows }++ static func assembly(_ fragments: [SourceEvidence]) -> (rows: [PDFReceiptRow], omitted: Bool) {+ finish(positionedLines(fragments), repeatedHeaders: [])+ }+ static func document(_ pages: [[SourceEvidence]]) -> [(rows: [PDFReceiptRow], omitted: Bool)] {+ let prepared = pages.map(positionedLines)+ let headers = repeatedHeaders(in: prepared.map(\.lines))+ return prepared.map { finish($0, repeatedHeaders: headers) }+ }+ private static func positionedLines(_ fragments: [SourceEvidence]) -> (lines: [SourceEvidence], omitted: Bool) {+ let ordered = fragments.filter { valid($0.boundingBox) && !$0.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }+ .sorted { lhs, rhs in+ if lhs.pageIndex != rhs.pageIndex { return (lhs.pageIndex ?? 0) < (rhs.pageIndex ?? 0) }+ return lhs.boundingBox.y == rhs.boundingBox.y ?+ lhs.boundingBox.x < rhs.boundingBox.x : lhs.boundingBox.y > rhs.boundingBox.y+ }+ var omitted = ordered.count != fragments.count+ var groups: [[SourceEvidence]] = []+ for fragment in ordered {+ if let last = groups.last, let first = last.first, first.pageIndex == fragment.pageIndex,+ first.sourceID == fragment.sourceID, verticalOverlap(first.boundingBox, fragment.boundingBox) > 0.5 {+ groups[groups.count - 1].append(fragment)+ } else { groups.append([fragment]) }+ }+ let lines = groups.map { values -> SourceEvidence in+ let values = values.sorted { $0.boundingBox.x < $1.boundingBox.x }+ var line = values[0]; line.id = UUID()+ line.text = values.map(\.text).joined(separator: " ")+ line.boundingBox = union(values.map(\.boundingBox))+ // Overlapping columns cannot safely provide an item-number association.+ if zip(values, values.dropFirst()).contains(where: { $0.boundingBox.x + $0.boundingBox.width > $1.boundingBox.x + 0.01 }) {+ line.text = ""+ omitted = true+ }+ return line+ }+ return (lines, omitted)+ }+ private static func finish(_ prepared: (lines: [SourceEvidence], omitted: Bool), repeatedHeaders: Set<UUID>)+ -> (rows: [PDFReceiptRow], omitted: Bool) {+ var lines = prepared.lines+ var index = 0+ while index + 1 < lines.count {+ let first = lines[index], next = lines[index + 1]+ let gap = first.boundingBox.y - (next.boundingBox.y + next.boundingBox.height)+ if first.sourceID == next.sourceID, first.pageIndex == next.pageIndex,+ !repeatedHeaders.contains(first.id), role(first.text) == .unknown, role(next.text) == .item,+ gap >= -0.005, gap <= max(first.boundingBox.height, next.boundingBox.height) * 0.8,+ next.boundingBox.x >= first.boundingBox.x - 0.02,+ next.boundingBox.x - first.boundingBox.x < 0.25 {+ lines[index].text += " " + next.text+ lines[index].boundingBox = union([first.boundingBox, next.boundingBox])+ lines.remove(at: index + 1)+ } else { index += 1 }+ }+ let rows = lines.filter { !$0.text.isEmpty }.map {+ PDFReceiptRow(evidence: $0, role: repeatedHeaders.contains($0.id) ? .metadata : role($0.text))+ }+ return (rows, prepared.omitted)+ }+ /// Repetition alone never excludes an item. A top unknown line must recur at matching+ /// geometry on another page and precede an independently named quantity-led item.+ private static func repeatedHeaders(in pages: [[SourceEvidence]]) -> Set<UUID> {+ let candidates = pages.flatMap { lines in+ zip(lines, lines.dropFirst()).compactMap { first, next -> SourceEvidence? in+ let gap = first.boundingBox.y - (next.boundingBox.y + next.boundingBox.height)+ guard first.sourceID == next.sourceID, first.pageIndex == next.pageIndex,+ first.boundingBox.y >= 0.85, role(first.text) == .unknown,+ next.text.range(of: "^[1-9][0-9]{0,3}\\s*[x×]\\s+[\\p{L}]", options: .regularExpression) != nil,+ gap >= -0.005, gap <= max(first.boundingBox.height, next.boundingBox.height) * 0.8 else { return nil }+ return first+ }+ }+ let byText = Dictionary(grouping: candidates, by: { headingKey($0.text) })+ return Set(candidates.filter { line in+ (byText[headingKey(line.text)] ?? []).contains { other in+ line.sourceID == other.sourceID && line.pageIndex != other.pageIndex &&+ headingKey(line.text) == headingKey(other.text) &&+ abs(line.boundingBox.x - other.boundingBox.x) <= 0.02 &&+ abs(line.boundingBox.y - other.boundingBox.y) <= 0.015 &&+ abs(line.boundingBox.width - other.boundingBox.width) <= 0.05 &&+ abs(line.boundingBox.height - other.boundingBox.height) <= 0.01+ }+ }.map(\.id))+ }+ private static func headingKey(_ text: String) -> String {+ text.split(whereSeparator: \.isWhitespace).joined(separator: " ").lowercased()+ }+ static func valid(_ box: EvidenceRectangle) -> Bool {+ [box.x, box.y, box.width, box.height].allSatisfy(\.isFinite) && box.x >= 0 && box.y >= 0 &&+ box.width > 0 && box.height > 0 && box.x + box.width <= 1.0001 && box.y + box.height <= 1.0001+ }+ private static func role(_ text: String) -> PDFReceiptRow.Role {+ let excluded = "^(?:receipt|invoice|page\\s*[0-9]+|sub\\s*total|grand\\s*total|total|balance|carried|brought|" ++ "amount\\s*(?:due|paid)|" ++ "tax|gst|tip|change|cash|visa|mastercard|service\\s*fee|delivery\\s*fee)\\b"+ let trimmed = text.replacingOccurrences(of: "\u{fffc}", with: " ").trimmingCharacters(in: .whitespacesAndNewlines)+ let financial = "^(?:item\\s*subtotal|previous\\s*total|new\\s*total|delivery\\s*discount|" ++ "promotion|refund(?:\\s*adjustment)?|uber\\s*cash)\\s+(?:-?\\s*(?:AUD\\s*)?\\$?[0-9]+\\.[0-9]{2})$"+ if trimmed.range(of: financial, options: [.regularExpression, .caseInsensitive]) != nil { return .excluded }+ if trimmed.range(of: excluded, options: [.regularExpression, .caseInsensitive]) != nil { return .excluded }+ if trimmed.range(of: "^[1-9][0-9]{0,3}\\s*[x×]\\s+[\\p{L}]", options: .regularExpression) != nil { return .item }+ if trimmed.contains(where: \.isLetter),+ trimmed.range(of: "(?:AUD\\s*)?\\$?[0-9]+\\.[0-9]{2}(?:\\s|$)", options: .regularExpression) != nil {+ return .item+ }+ let metadata = "(?i)(?:cafe|restaurant|receipt|invoice|dine.?in|delivery|pick.?up|date|time)"+ if trimmed.range(of: metadata, options: .regularExpression) != nil {+ return .metadata+ }+ return .unknown+ }+ private static func verticalOverlap(_ lhs: EvidenceRectangle, _ rhs: EvidenceRectangle) -> Double {+ max(0, min(lhs.y + lhs.height, rhs.y + rhs.height) - max(lhs.y, rhs.y)) / min(lhs.height, rhs.height)+ }+ private static func union(_ boxes: [EvidenceRectangle]) -> EvidenceRectangle {+ let x = boxes.map(\.x).min() ?? 0, y = boxes.map(\.y).min() ?? 0+ return .init(x: x, y: y, width: (boxes.map { $0.x + $0.width }.max() ?? x) - x,+ height: (boxes.map { $0.y + $0.height }.max() ?? y) - y)+ }+}++nonisolated enum PDFReceiptRowRegistry {+ static func match(incoming: [ReceiptRowAnchor], existing: [ReceiptRowAnchor], allowNew: Bool) -> [UUID: ReceiptRowAnchor] {+ if existing.isEmpty && allowNew { return Dictionary(uniqueKeysWithValues: incoming.map { ($0.id, $0) }) }+ var result: [UUID: ReceiptRowAnchor] = [:]+ for row in incoming {+ let candidates = existing.filter { compatible(row, $0) }+ guard candidates.count == 1, let old = candidates.first, !old.dismissed,+ incoming.filter({ compatible($0, old) }).count == 1 else { continue }+ result[row.id] = old+ }+ return result+ }+ private static func compatible(_ lhs: ReceiptRowAnchor, _ rhs: ReceiptRowAnchor) -> Bool {+ guard lhs.sourceID == rhs.sourceID, lhs.pageIndex == rhs.pageIndex,+ PDFReceiptRows.valid(lhs.bounds), PDFReceiptRows.valid(rhs.bounds) else { return false }+ let a = lhs.bounds, b = rhs.bounds+ let overlap = max(0, min(a.x + a.width, b.x + b.width) - max(a.x, b.x)) *+ max(0, min(a.y + a.height, b.y + b.height) - max(a.y, b.y))+ let union = a.width * a.height + b.width * b.height - overlap+ return union > 0 && overlap / union > 0.6+ }+}
diff --git a/Foodnotes/Foodnotes/Services/Capture/Extraction/PDFReceiptTable.swift b/Foodnotes/Foodnotes/Services/Capture/Extraction/PDFReceiptTable.swiftnew file mode 100644index 0000000..aaa05d3--- /dev/null+++ b/Foodnotes/Foodnotes/Services/Capture/Extraction/PDFReceiptTable.swift@@ -0,0 +1,104 @@+import Foundation+import FoodnotesDomain++/// Explicit headers determine amount basis; model guesses cannot replace typed item values.+nonisolated enum PDFReceiptTable {+ fileprivate enum Schema: Sendable { case netRow, grossRow, grossUnit, netRowWithGrossUnit, ambiguous }+ struct UnitPrice: Sendable {+ let evidenceID: UUID+ let calculation: ReceiptPriceCalculation+ fileprivate let schema: Schema+ }+ struct Page: Sendable {+ var candidates: [CaptureCandidate] = []+ var unitPrices: [UnitPrice] = []+ var protectedRows: Set<UUID> = []+ var omitted = false+ }+ private struct Values {+ let name: String+ let quantity: String+ let calculation: ReceiptPriceCalculation+ }++ static func document(_ pages: [[PDFReceiptRow]]) -> [Page] {+ var active: Schema?+ return pages.map { rows in+ var result = Page()+ for row in rows {+ let text = normalized(row.evidence.text)+ if let schema = header(text) { active = schema; continue }+ guard let schema = active else { continue }+ if row.role == .excluded {+ if text.range(of: "^(?:total net amount|total amount payable|grand total|amount due|amount paid)\\b",+ options: [.regularExpression, .caseInsensitive]) != nil { active = nil }+ continue+ }+ guard row.role == .item || text.range(of: "^[0-9]{1,4}[ /.-]", options: .regularExpression) != nil else { continue }+ result.protectedRows.insert(row.evidence.id)+ guard let values = columns(text, schema: schema) else { result.omitted = true; continue }+ result.candidates += [.init(kind: .dish, copiedText: values.name, evidenceID: row.evidence.id),+ .init(kind: .quantity, copiedText: values.quantity, evidenceID: row.evidence.id)]+ result.unitPrices.append(.init(evidenceID: row.evidence.id, calculation: values.calculation, schema: schema))+ }+ return result+ }+ }++ /// Revalidate derived values against the explicit schema and source row, not a copied model string.+ static func proposal(_ price: UnitPrice, evidence: [SourceEvidence], generation: UUID) -> ValidatedCaptureProposal? {+ let matches = evidence.filter { $0.id == price.evidenceID }+ guard matches.count == 1, let line = matches.first, PDFReceiptRows.valid(line.boundingBox),+ let values = columns(normalized(line.text), schema: price.schema), values.calculation == price.calculation,+ let value = try? price.calculation.unitPriceText() else { return nil }+ return .init(proposal: .init(generation: generation, fieldPath: "occurrences.\(line.id).price", value: value,+ evidenceIDs: [line.id], expectedEditVersion: 0, parserVersion: "foodnotes.capture.invoice-unit.v1",+ priceCalculation: price.calculation), sourceID: line.sourceID)+ }++ private static func header(_ text: String) -> Schema? {+ let prefix = "tax point date description qty "+ switch text.lowercased() {+ case prefix + "gst gst amount net amount": return .netRow+ case prefix + "gst gst amount net amount unit price incl gst": return .netRowWithGrossUnit+ case prefix + "amount incl gst": return .grossRow+ case prefix + "unit price incl gst": return .grossUnit+ default: return text.lowercased().hasPrefix(prefix) ? .ambiguous : nil+ }+ }++ private static func columns(_ text: String, schema: Schema) -> Values? {+ guard schema != .ambiguous else { return nil }+ let date = "(?:[0-9]{1,2} [\\p{L}]{3,12},? [0-9]{4}|[0-9]{1,2}[./-][0-9]{1,2}[./-][0-9]{4}|[0-9]{4}[-/][0-9]{1,2}[-/][0-9]{1,2})"+ let money = "(?:AUD ?)?\\$?[0-9]{1,7}\\.[0-9]{2}"+ let amounts = schema == .grossRow || schema == .grossUnit ? "(\(money))" :+ "[0-9]{1,2}(?:\\.[0-9]+)?% (\(money)) (\(money))" + (schema == .netRowWithGrossUnit ? " (\(money))" : "")+ let pattern = "^(\(date)) (.+?) ([1-9][0-9]{0,3}) \(amounts)$"+ guard let expression = try? NSRegularExpression(pattern: pattern),+ let match = expression.firstMatch(in: text, range: NSRange(text.startIndex..., in: text)) else { return nil }+ func value(_ index: Int) -> String? { Range(match.range(at: index), in: text).map { String(text[$0]) } }+ guard let dateText = value(1), ReceiptTimestamp.date(dateText, zone: "Australia/Melbourne") != nil,+ let name = value(2), name.contains(where: \.isLetter), let quantity = value(3), let count = Int(quantity),+ let first = value(4).flatMap(cents) else { return nil }+ let calculation: ReceiptPriceCalculation+ if schema == .grossUnit || schema == .grossRow {+ calculation = .init(basis: schema == .grossUnit ? .printedGrossUnit : .grossRow, quantity: count, amountCents: first)+ } else {+ guard let net = value(5).flatMap(cents) else { return nil }+ if schema == .netRowWithGrossUnit {+ guard let unit = value(6).flatMap(cents), abs(unit * Int64(count) - (net + first)) * 2 <= Int64(count) else { return nil }+ calculation = .init(basis: .printedGrossUnit, quantity: count, amountCents: unit)+ } else { calculation = .init(basis: .netRowPlusGST, quantity: count, amountCents: net, gstCents: first) }+ }+ guard (try? calculation.unitPriceCents()) != nil else { return nil }+ return Values(name: name, quantity: quantity, calculation: calculation)+ }++ private static func cents(_ text: String) -> Int64? {+ let parts = text.replacingOccurrences(of: "AUD", with: "").replacingOccurrences(of: "$", with: "")+ .trimmingCharacters(in: .whitespaces).split(separator: ".")+ guard parts.count == 2, let whole = Int64(parts[0]), let fraction = Int64(parts[1]) else { return nil }+ return whole * 100 + fraction+ }+ private static func normalized(_ text: String) -> String { text.split(whereSeparator: \.isWhitespace).joined(separator: " ") }+}
diff --git a/Foodnotes/Foodnotes/Services/Capture/Extraction/ReceiptTimestamp.swift b/Foodnotes/Foodnotes/Services/Capture/Extraction/ReceiptTimestamp.swiftindex cbaa51e..bd81dcd 100644--- a/Foodnotes/Foodnotes/Services/Capture/Extraction/ReceiptTimestamp.swift+++ b/Foodnotes/Foodnotes/Services/Capture/Extraction/ReceiptTimestamp.swift@@ -9,15 +9,17 @@ nonisolated enum ReceiptTimestamp { } static func date(_ text: String, zone: String, locale: String = "en_AU") -> LocalDate? { if let numeric = numericDate(text, zone: zone) { return numeric }- let named = "^(?:[0-9]{1,2}\\.?\\s+[\\p{L}]{3,12}\\.?\\s+[0-9]{4}|[\\p{L}]{3,12}\\.?\\s+[0-9]{1,2},?\\s+[0-9]{4})$"+ let named = "^(?:[0-9]{1,2}\\.?\\s+[\\p{L}]{3,12}\\.?,?\\s+[0-9]{4}|[\\p{L}]{3,12}\\.?\\s+[0-9]{1,2},?\\s+[0-9]{4})$" guard text.range(of: named, options: .regularExpression) != nil else { return nil }+ let parseText = text.replacingOccurrences(of: "\\bSept\\b", with: "Sep", options: [.regularExpression, .caseInsensitive]) for format in ["d MMM yyyy", "dd MMM yyyy", "d MMMM yyyy", "dd MMMM yyyy", "d. MMMM yyyy",+ "d MMM, yyyy", "dd MMM, yyyy", "d MMMM, yyyy", "dd MMMM, yyyy", "MMM d, yyyy", "MMMM d, yyyy", "MMMM d yyyy"] { let parser = DateFormatter(); parser.locale = Locale(identifier: locale) parser.calendar = Calendar(identifier: .gregorian); parser.timeZone = TimeZone(secondsFromGMT: 0) parser.dateFormat = format; parser.isLenient = false- if let parsed = parser.date(from: text),- normalized(parser.string(from: parsed), locale: locale) == normalized(text, locale: locale) {+ if let parsed = parser.date(from: parseText),+ normalized(parser.string(from: parsed), locale: locale) == normalized(parseText, locale: locale) { var calendar = Calendar(identifier: .gregorian); calendar.timeZone = TimeZone(secondsFromGMT: 0)! let parts = calendar.dateComponents([.year, .month, .day], from: parsed) let value = LocalDate(year: parts.year!, month: parts.month!, day: parts.day!, timeZoneIdentifier: zone)@@ -65,7 +67,7 @@ nonisolated enum ReceiptTimestamp { nonisolated struct ReceiptTimestampCandidates { private let datePattern = "\\b(?:[0-9]{4}[-/][0-9]{1,2}[-/][0-9]{1,2}|[0-9]{1,2}[./-][0-9]{1,2}[./-][0-9]{4}|"- + "[0-9]{1,2}\\.?\\s+[\\p{L}]{3,12}\\.?\\s+[0-9]{4}|[\\p{L}]{3,12}\\.?\\s+[0-9]{1,2},?\\s+[0-9]{4})\\b"+ + "[0-9]{1,2}\\.?\\s+[\\p{L}]{3,12}\\.?,?\\s+[0-9]{4}|[\\p{L}]{3,12}\\.?\\s+[0-9]{1,2},?\\s+[0-9]{4})\\b" private let timePattern = "\\b[0-9]{1,2}:[0-9]{2}(?::[0-9]{2})?(?:\\s*[ap]\\.?m\\.?)?\\b" func candidates(_ evidence: [SourceEvidence]) -> [CaptureCandidate] { evidence.prefix(288).enumerated().flatMap { index, line in
diff --git a/Foodnotes/Foodnotes/Services/Capture/Extraction/VisionPDFReceiptOCR.swift b/Foodnotes/Foodnotes/Services/Capture/Extraction/VisionPDFReceiptOCR.swiftnew file mode 100644index 0000000..7bf4b6f--- /dev/null+++ b/Foodnotes/Foodnotes/Services/Capture/Extraction/VisionPDFReceiptOCR.swift@@ -0,0 +1,38 @@+import CoreGraphics+import CryptoKit+import FoodnotesDomain+import Foundation+import Vision++nonisolated enum PDFEvidenceIdentity {+ static func make(source: UUID, page: Int, method: String, index: Int, text: String) -> UUID {+ let bytes = Array(SHA256.hash(data: Data("\(source):\(page):\(method):\(index):\(text)".utf8)).prefix(16))+ return UUID(uuid: (bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7],+ bytes[8], bytes[9], bytes[10], bytes[11], bytes[12], bytes[13], bytes[14], bytes[15]))+ }+}++nonisolated struct VisionPDFReceiptOCR: Sendable {+ var sourceID = UUID()+ func recognize(_ pageIndex: Int, _ image: CGImage) throws -> [SourceEvidence] {+ try Task.checkCancellation()+ let request = VNRecognizeTextRequest()+ request.recognitionLevel = .accurate+ request.usesLanguageCorrection = false+ let supported = try request.supportedRecognitionLanguages()+ guard supported.contains("en-AU") || supported.contains("en-US") else { throw CaptureReadError.unsupportedLanguage }+ request.recognitionLanguages = [supported.contains("en-AU") ? "en-AU" : "en-US"]+ try VNImageRequestHandler(cgImage: image, orientation: .up, options: [:]).perform([request])+ try Task.checkCancellation()+ return (request.results ?? []).sorted {+ abs($0.boundingBox.midY - $1.boundingBox.midY) > 0.01 ?+ $0.boundingBox.midY > $1.boundingBox.midY : $0.boundingBox.minX < $1.boundingBox.minX+ }.prefix(501).enumerated().map { index, observation in+ let text = observation.topCandidates(1).first?.string ?? ""+ let box = observation.boundingBox+ return SourceEvidence(id: PDFEvidenceIdentity.make(source: sourceID, page: pageIndex,+ method: "vision.v1", index: index, text: text), sourceID: sourceID, text: text,+ boundingBox: .init(x: box.minX, y: box.minY, width: box.width, height: box.height), pageIndex: pageIndex)+ }+ }+}
diff --git a/Foodnotes/Foodnotes/Services/Capture/HandoffImportCoordinator.swift b/Foodnotes/Foodnotes/Services/Capture/HandoffImportCoordinator.swiftindex 2f6a145..4f98e7f 100644--- a/Foodnotes/Foodnotes/Services/Capture/HandoffImportCoordinator.swift+++ b/Foodnotes/Foodnotes/Services/Capture/HandoffImportCoordinator.swift@@ -12,6 +12,7 @@ nonisolated struct HandoffScan: Sendable { var unassigned: [SourceEnvelope] = [] var duplicates: [HandoffDuplicate] = [] var deferred: [SourceEnvelope] = []+ var compatibilityRequired: [SourceEnvelope] = [] } nonisolated enum HandoffImportFault: Sendable { case beforeImport, afterImport, beforeAcknowledge } @@ -160,6 +161,9 @@ actor HandoffImportCoordinator { } return try await acknowledge(envelope, receipt: receipt, current: current) }+ if envelope.mediaType == "application/pdf", !PDFCompatibilityAcknowledgement(directory: directory).accepted {+ result.compatibilityRequired.append(envelope); return nil+ } let destination = try await sink.resolveHandoffDestination(capturedDestination, session: current) try require(current) let snapshot = try await repository.snapshot(scope: .both)@@ -239,12 +243,18 @@ actor HandoffImportCoordinator { let route: CaptureRoute = switch envelope.origin { case .camera: .camera case .photos: .photos+ case .files: .files case .shareExtension, nil: .shareExtension }- return Draft(id: envelope.operationID, partitionID: current.partitionID, intendedLibrary: destination, route: route,+ var draft = Draft(id: envelope.operationID, partitionID: current.partitionID, intendedLibrary: destination, route: route, createdAt: envelope.capturedAt, generation: UUID(), date: RecordedDate(value: date, provenance: .defaultValue), time: nil, title: empty, place: empty, ordering: empty, notes: empty, dinerIDs: [defaultDinerID ?? current.adultID], occurrences: [], sources: [source], extractionStatus: .pending, pendingSharedSetup: envelope.pendingSharedSetup)+ if source.mediaType == "application/pdf" {+ let admitted = try PDFReceiptAdmission().read(source)+ draft.receiptPages = (0..<admitted.pageCount).map { .init(sourceID: sourceID, pageIndex: $0) }+ }+ return draft } } nonisolated private struct HandoffImportInput: Encodable {@@ -262,8 +272,11 @@ nonisolated enum CaptureHandoffContainer { } static func open(directory: URL) throws -> FileSourceHandoff { try FileSourceHandoff(directory: directory) { envelope, url in- _ = try OriginalCaptureReader().read(SourceImage(id: envelope.sourceID, url: url, mediaType: envelope.mediaType,- byteLength: envelope.byteLength, sha256: envelope.sha256))+ let source = SourceImage(id: envelope.sourceID, url: url, mediaType: envelope.mediaType,+ byteLength: envelope.byteLength, sha256: envelope.sha256)+ if source.mediaType == "application/pdf" {+ _ = try PDFReceiptAdmission().read(source)+ } else { _ = try OriginalCaptureReader().read(source) } } } }
diff --git a/Foodnotes/Foodnotes/Services/Capture/PDFReceiptAdmission.swift b/Foodnotes/Foodnotes/Services/Capture/PDFReceiptAdmission.swiftnew file mode 100644index 0000000..98d93b1--- /dev/null+++ b/Foodnotes/Foodnotes/Services/Capture/PDFReceiptAdmission.swift@@ -0,0 +1,19 @@+import CryptoKit+import FoodnotesDomain+import Foundation+import PDFKit++nonisolated struct PDFReceiptAdmission {+ static let maximumBytes = 32 * 1_024 * 1_024+ static let maximumPages = 20+ struct Document: Sendable { let bytes: Data; let pageCount: Int }++ /// Caller owns this file. Verify exact bytes before any draft or page derivative is made.+ func read(_ source: SourceImage) throws -> Document {+ guard source.mediaType == OriginalMedia.pdf.rawValue else { throw CaptureReadError.invalidSource }+ let bytes = try OriginalCaptureReader().read(source)+ guard let document = PDFDocument(data: bytes), !document.isLocked,+ (1...Self.maximumPages).contains(document.pageCount) else { throw CaptureReadError.invalidSource }+ return Document(bytes: bytes, pageCount: document.pageCount)+ }+}
diff --git a/Foodnotes/Foodnotes/Services/Capture/PDFReceiptFilesInput.swift b/Foodnotes/Foodnotes/Services/Capture/PDFReceiptFilesInput.swiftnew file mode 100644index 0000000..4c6e74d--- /dev/null+++ b/Foodnotes/Foodnotes/Services/Capture/PDFReceiptFilesInput.swift@@ -0,0 +1,26 @@+import Foundation++nonisolated enum PDFReceiptFilesInput {+ static func copy(_ url: URL, directory: URL,+ start: (URL) -> Bool = { $0.startAccessingSecurityScopedResource() },+ stop: (URL) -> Void = { $0.stopAccessingSecurityScopedResource() },+ duringCopy: () throws -> Void = {}) throws -> URL {+ let scoped = start(url)+ defer { if scoped { stop(url) } }+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)+ let owned = directory.appendingPathComponent("\(UUID()).pdf")+ try duringCopy()+ try OriginalHandoffPDFFile.copyFile(url, to: owned)+ return owned+ }+}++nonisolated struct PDFCompatibilityAcknowledgement {+ let directory: URL+ private var url: URL { directory.appendingPathComponent("PDFCompatibility-v1") }+ var accepted: Bool { (try? Data(contentsOf: url)) == Data("updated-builds-required".utf8) }+ func accept() throws {+ try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)+ try Data("updated-builds-required".utf8).write(to: url, options: .atomic)+ }+}
diff --git a/Foodnotes/Foodnotes/Services/Capture/ReceiptProvenanceCapture.swift b/Foodnotes/Foodnotes/Services/Capture/ReceiptProvenanceCapture.swiftnew file mode 100644index 0000000..148450d--- /dev/null+++ b/Foodnotes/Foodnotes/Services/Capture/ReceiptProvenanceCapture.swift@@ -0,0 +1,77 @@+import FoodnotesDomain+import Foundation++nonisolated extension Draft {+ mutating func rememberReceiptProposal(_ value: ValidatedCaptureProposal) {+ guard sources.contains(where: { $0.id == value.sourceID && $0.mediaType == "application/pdf" }) else { return }+ if var field = receiptField(path: value.proposal.fieldPath, evidenceIDs: value.proposal.evidenceIDs, source: value.sourceID) {+ field.priceCalculation = value.proposal.priceCalculation+ receiptAcceptedFields = (receiptAcceptedFields ?? []).filter { $0.fieldPath != field.fieldPath } + [field]+ }+ }+ var receiptSupportingFields: [ReceiptFieldProvenance] {+ var fields = Dictionary((receiptAcceptedFields ?? []).map { ($0.fieldPath, $0) }, uniquingKeysWith: { first, _ in first })+ for (path, provenance) in receiptFieldOrigins {+ guard case let .extracted(source, evidence, _) = provenance, fields[path] == nil else { continue }+ fields[path] = receiptField(path: path, evidenceIDs: evidence, source: source)+ }+ return fields.values.sorted { $0.fieldPath < $1.fieldPath }+ }+ func receiptSupportingField(_ proposal: ValidatedCaptureProposal) -> ReceiptFieldProvenance? {+ var field = receiptField(path: proposal.proposal.fieldPath, evidenceIDs: proposal.proposal.evidenceIDs, source: proposal.sourceID)+ field?.priceCalculation = proposal.proposal.priceCalculation+ return field+ }+ func savedReceiptProvenance() throws -> [UUID: ReceiptProvenance] {+ let pdfs = sources.filter { $0.mediaType == "application/pdf" }+ guard let source = pdfs.first else { return [:] }+ guard pdfs.count == 1, sources.count == 1 else { throw DomainError.invalidValue("one PDF receipt required") }+ let accepted = receiptAcceptedFields ?? []+ guard Set(accepted.map(\.fieldPath)).count == accepted.count,+ (receiptPages ?? []).allSatisfy({ $0.sourceID == source.id }),+ (receiptRows ?? []).allSatisfy({ $0.sourceID == source.id }),+ (receiptEvidence ?? []).allSatisfy({ $0.sourceID == source.id }) else {+ throw DomainError.invalidValue("receipt provenance source/field identity")+ }+ var fields = Dictionary(uniqueKeysWithValues: accepted.map { ($0.fieldPath, $0) })+ for (path, provenance) in receiptFieldOrigins {+ guard case let .extracted(id, evidenceIDs, _) = provenance, id == source.id, fields[path] == nil else { continue }+ guard let field = receiptField(path: path, evidenceIDs: evidenceIDs, source: id) else {+ throw DomainError.invalidValue("PDF extraction evidence is unavailable; keep the draft for review")+ }+ fields[path] = field+ }+ let ids = occurrences.map(\.id) + (receiptDismissedOccurrences ?? []).map(\.id)+ guard Set(ids).count == ids.count else { throw DomainError.invalidValue("duplicate retained receipt occurrence") }+ let actual = Set(ids), registered = receiptRows ?? []+ let selected = Set(fields.values.flatMap(\.rowIDs))+ let compact = (receiptEvidence ?? []).filter { $0.sourceID == source.id && selected.contains($0.id) }+ let compactIDs = Set(compact.map(\.id))+ let unmaterialized = registered.filter { !actual.contains($0.occurrenceID) && !compactIDs.contains($0.id) }.map {+ ReceiptEvidenceAnchor(id: $0.id, sourceID: $0.sourceID, pageIndex: $0.pageIndex, bounds: $0.bounds)+ }+ let value = ReceiptProvenance(pages: (receiptPages ?? []).filter { $0.sourceID == source.id },+ rows: registered.filter { actual.contains($0.occurrenceID) },+ fields: fields.values.sorted { $0.fieldPath < $1.fieldPath }, evidence: compact + unmaterialized)+ try value.validate(sourceID: source.id, occurrenceIDs: Set(ids))+ return [source.id: value]+ }+ private var receiptFieldOrigins: [(String, FieldProvenance)] {+ var fields = [("date", date.provenance), ("title", title.provenance), ("place", place.provenance),+ ("ordering", ordering.provenance), ("notes", notes.provenance)]+ for line in occurrences + (receiptDismissedOccurrences ?? []) {+ fields += [("name", line.name), ("quantity", line.quantity), ("price", line.price), ("note", line.note)].map {+ ("occurrences.\(line.id).\($0.0)", $0.1.provenance)+ }+ }+ return fields+ }+ private func receiptField(path: String, evidenceIDs: [UUID], source: UUID) -> ReceiptFieldProvenance? {+ let pageIndices = Set((receiptRows ?? []).filter { $0.sourceID == source && evidenceIDs.contains($0.id) }.map(\.pageIndex) ++ (receiptEvidence ?? []).filter { $0.sourceID == source && evidenceIDs.contains($0.id) }.map(\.pageIndex))+ guard !pageIndices.isEmpty else { return nil }+ let parts = path.split(separator: ".")+ let occurrence = parts.count == 3 && parts[0] == "occurrences" ? UUID(uuidString: String(parts[1])) : nil+ return .init(fieldPath: path, occurrenceID: occurrence, pageIndices: pageIndices.sorted(), rowIDs: evidenceIDs)+ }+}
diff --git a/Foodnotes/FoodnotesShare/ShareViewController.swift b/Foodnotes/FoodnotesShare/ShareViewController.swiftindex 64ef89f..2e302b9 100644--- a/Foodnotes/FoodnotesShare/ShareViewController.swift+++ b/Foodnotes/FoodnotesShare/ShareViewController.swift@@ -13,7 +13,7 @@ final class ShareViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .systemBackground- status.text = "Saving image for review…"+ status.text = "Saving receipt for review…" status.numberOfLines = 0 done.setTitle("Done", for: .normal) done.isEnabled = false@@ -44,13 +44,7 @@ final class ShareViewController: UIViewController { private func saveImage() async { do {- let providers = (extensionContext?.inputItems as? [NSExtensionItem] ?? []).flatMap { $0.attachments ?? [] }- .compactMap { provider -> (NSItemProvider, String)? in- guard let type = representation(provider) else { return nil }- return (provider, type)- }- guard providers.count == 1,- let root = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.me.nore.ig.apps.foodnotes")+ guard let root = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.me.nore.ig.apps.foodnotes") else { throw HandoffError.invalidSource } let directory = root.appendingPathComponent("CaptureHandoff", isDirectory: true) let operation = UUID()@@ -58,33 +52,30 @@ final class ShareViewController: UIViewController { let originatingSession = HandoffSessionFile.read(directory: directory) let capturedAt = Date() let capturedTimeZone = TimeZone.current.identifier- let original = try await OriginalHandoffImageFile.copy(providers[0].0, typeIdentifier: providers[0].1, directory: directory)+ let retained = try await PDFHandoffInput.prepare(extensionContext?.inputItems as? [NSExtensionItem] ?? [], directory: directory)+ let original = retained.url defer { try? FileManager.default.removeItem(at: original) } try Task.checkCancellation()- let metadata = try OriginalHandoffImageFile.metadata(original)- let envelope = SourceEnvelope(schemaVersion: 1, operationID: operation,+ let metadata = retained.metadata+ let envelope = SourceEnvelope(schemaVersion: metadata.mediaType == "application/pdf" ? 2 : 1, operationID: operation, partitionID: originatingSession?.partitionID, sourceID: sourceID, filename: "\(sourceID.uuidString).original", mediaType: metadata.mediaType, byteLength: metadata.length, sha256: metadata.digest, capturedAt: capturedAt, origin: .shareExtension, capturedTimeZone: capturedTimeZone, destination: originatingSession?.destination, pendingSharedSetup: originatingSession?.pendingSharedSetup)- let handoff = try FileSourceHandoff(directory: directory, verify: OriginalHandoffImageFile.verify)+ let handoff = try FileSourceHandoff(directory: directory, verify: { envelope, url in+ if envelope.mediaType == "application/pdf" {+ try OriginalHandoffPDFFile.verify(envelope, url)+ } else { try OriginalHandoffImageFile.verify(envelope, url) }+ }) try await handoff.publish(envelope, source: original) try Task.checkCancellation() status.text = "Saved for review. Open Foodnotes to continue." done.isEnabled = true } catch is CancellationError { return } catch {- status.text = "The image could not be saved. Try again or add a meal in Foodnotes."+ status.text = "Choose one unlocked PDF receipt (1–20 pages, up to 32 MiB) or one image, then try again." } } - private func representation(_ provider: NSItemProvider) -> String? {- for identifier in provider.registeredTypeIdentifiers {- if let type = UTType(identifier), [UTType.png, .jpeg, .heic, .heif].contains(where: { type.conforms(to: $0) }) {- return identifier- }- }- return provider.registeredTypeIdentifiers.contains(UTType.image.identifier) ? UTType.image.identifier : nil- } }
diff --git a/Foodnotes/FoodnotesTests/CaptureExtraction/ExtractionCorpusTests.swift b/Foodnotes/FoodnotesTests/CaptureExtraction/ExtractionCorpusTests.swiftindex a5c9e2e..5727062 100644--- a/Foodnotes/FoodnotesTests/CaptureExtraction/ExtractionCorpusTests.swift+++ b/Foodnotes/FoodnotesTests/CaptureExtraction/ExtractionCorpusTests.swift@@ -31,8 +31,8 @@ struct ExtractionCorpusTests { } #expect(review.draft.createdAt == draft.createdAt) #expect(review.draft.sources == draft.sources)- #expect(review.draft.place.value == nil)- #expect(review.suggestions["place"] != nil)+ #expect(review.draft.place.value == fixture.candidates.first { $0.kind == .place }?.text)+ #expect(review.suggestions["place"] == nil) if fixture.unknownFields.contains("date") { #expect(review.draft.date == draft.date) } if fixture.unknownFields.contains("time") { #expect(review.draft.time == nil) } let extracted = review.draft.occurrences.filter { $0.id != storageUUID(502) }
diff --git a/Foodnotes/FoodnotesTests/CaptureExtraction/ExtractionValidationTests.swift b/Foodnotes/FoodnotesTests/CaptureExtraction/ExtractionValidationTests.swiftindex 36d55b0..d17b5aa 100644--- a/Foodnotes/FoodnotesTests/CaptureExtraction/ExtractionValidationTests.swift+++ b/Foodnotes/FoodnotesTests/CaptureExtraction/ExtractionValidationTests.swift@@ -31,7 +31,7 @@ struct ExtractionValidationTests { #expect(result?.proposal.evidenceIDs == [dateEvidence.id]) } - @Test func manualEditGenerationCancellationAndExplicitConfirmationGuardReview() throws {+ @Test func manualEditGenerationAndCancellationGuardAutomaticPlacePrefill() throws { let evidence = captureEvidence("Saffron & Salt") let proposal = try #require(CaptureProposalValidator().validate( CaptureCandidate(kind: .place, copiedText: evidence.text, evidenceID: evidence.id),@@ -41,10 +41,10 @@ struct ExtractionValidationTests { var review = DraftExtractionReview(draft: draft) let applied = review.apply(proposal) #expect(applied)- #expect(review.draft.place.value == nil)- #expect(review.suggestions["place"] != nil)+ #expect(review.draft.place.value == evidence.text)+ #expect(review.suggestions["place"] == nil) let confirmed = review.confirm(fieldPath: "place")- #expect(confirmed)+ #expect(!confirmed) #expect(review.draft.place.value == evidence.text) var edited = DraftExtractionReview(draft: draft) var corrected = draft
diff --git a/Foodnotes/FoodnotesTests/CaptureExtraction/PDFEvidenceCompletenessTests.swift b/Foodnotes/FoodnotesTests/CaptureExtraction/PDFEvidenceCompletenessTests.swiftnew file mode 100644index 0000000..cdf175e--- /dev/null+++ b/Foodnotes/FoodnotesTests/CaptureExtraction/PDFEvidenceCompletenessTests.swift@@ -0,0 +1,100 @@+import Foundation+import FoodnotesDomain+import Testing+@testable import Foodnotes++@Suite struct PDFEvidenceCompletenessTests {+ @Test func rawNativeOverflowCannotDisappearWhenSelectionsAreFiltered() throws {+ let overlong = pdfEvidence(String(repeating: "x", count: 1_801))+ let input = Array(repeating: overlong, count: 500) + [pdfEvidence("2 x Noodles $12.50")]+ let page = PDFReceiptEvidence.boundedPage(input, pageIndex: 0)+ #expect(page.failure != nil)+ #expect(page.evidence.isEmpty)+ let filtered = PDFReceiptEvidence.boundedPage([overlong, pdfEvidence("2 x Noodles")], pageIndex: 0)+ #expect(filtered.failure != nil && filtered.evidence.count == 1)+ }+ @Test func clearQuantityLedUnpricedItemRemainsGroundedWithBlankPrice() throws {+ let rows = PDFReceiptRows.assemble([pdfEvidence("2 x Noodles")])+ let row = try #require(rows.first)+ #expect(row.role == .item)+ let validator = CaptureProposalValidator(), generation = UUID()+ #expect(validator.validate(.init(kind: .dish, copiedText: "Noodles", evidenceID: row.evidence.id),+ evidence: [row.evidence], generation: generation) != nil)+ #expect(validator.validate(.init(kind: .quantity, copiedText: "2", evidenceID: row.evidence.id),+ evidence: [row.evidence], generation: generation) != nil)+ #expect(validator.validate(.init(kind: .price, copiedText: "$12.50", evidenceID: row.evidence.id),+ evidence: [row.evidence], generation: generation) == nil)+ }+ @Test func invalidOrConflictingDatesOnAnotherPageBlockDocumentDate() throws {+ let valid = pdfEvidence("Purchase date: 2026-10-22", page: 0)+ let invalid = pdfEvidence("Purchase date: 32/13/2026", page: 1)+ let conflicting = pdfEvidence("Purchase date: 2026-10-23", page: 1)+ for other in [invalid, conflicting] {+ let values = CaptureReceiptTimestamps.pdfValues(pages: [[valid], [other]], generation: UUID(),+ timeZoneIdentifier: "Australia/Melbourne", localeIdentifier: "en_AU")+ #expect(values.isEmpty)+ }+ let late = (0..<400).map { pdfEvidence("Synthetic header \($0)", page: 0) } + [valid]+ #expect(CaptureReceiptTimestamps.pdfValues(pages: [late], generation: UUID(),+ timeZoneIdentifier: "Australia/Melbourne", localeIdentifier: "en_AU").count == 1)+ var boundary = (0..<300).map { pdfEvidence("Synthetic header \($0)") }+ boundary[286] = pdfEvidence("Printed")+ boundary[287] = pdfEvidence("2026-10-23 12:30")+ let values = CaptureReceiptTimestamps.pdfValues(pages: [boundary + [valid]], generation: UUID(),+ timeZoneIdentifier: "Australia/Melbourne", localeIdentifier: "en_AU")+ #expect(values.map(\.proposal.value) == ["2026-10-22"])+ }+}++extension PDFEvidenceCompletenessTests {+ @Test func pricedExplicitReceiptHeaderIsExcludedWithoutSuppressingCafeLatte() throws {+ let rows = PDFReceiptRows.assemble([pdfEvidence("RECEIPT COPY #123 $20.00", y: 0.95),+ pdfEvidence("Cafe Latte $4.50", y: 0.7), pdfEvidence("Cafe Latte $4.50", y: 0.5)])+ #expect(rows.first?.role == .excluded)+ #expect(rows.filter { $0.role == .item }.count == 2)+ #expect(rows[1].evidence.id != rows[2].evidence.id)+ }+}++extension PDFEvidenceCompletenessTests {+ @Test func injectedModelCannotBypassInvalidDocumentDate() async throws {+ let source = captureSourceValuePDF()+ let pages = [PDFPageEvidence(pageIndex: 0, evidence: [pdfEvidence("Purchase date: 2026-10-22", page: 0)], failure: nil),+ PDFPageEvidence(pageIndex: 1, evidence: [pdfEvidence("Purchase date: 32/13/2026", page: 1)], failure: nil)]+ let extractor = PDFCaptureExtractor(model: PDFDateInjectionModel(), evidenceStore: MemoryCaptureEvidence(),+ loadPages: { _ in pages })+ var dates: [ValidatedCaptureProposal] = []+ for try await event in extractor.events(source, generation: UUID()) {+ if case let .proposal(value) = event, value.proposal.fieldPath == "date" { dates.append(value) }+ }+ #expect(dates.isEmpty)+ }+}++nonisolated private struct PDFDateInjectionModel: CaptureProposalModel {+ func availability(localeIdentifier: String) async -> CaptureModelAvailability { .available }+ func candidates(in evidence: [SourceEvidence], localeIdentifier: String) async throws -> [CaptureCandidate] {+ evidence.filter { $0.text.contains("2026-10-22") }.map {+ .init(kind: .date, copiedText: "2026-10-22", evidenceID: $0.id)+ }+ }+}++extension PDFEvidenceCompletenessTests {+ @Test func ambiguousOverlappingColumnsRemainExplicitlyIncomplete() async throws {+ let source = captureSourceValuePDF()+ let page = PDFPageEvidence(pageIndex: 0, evidence: [+ pdfEvidence("Noodles", x: 0.1, y: 0.5, width: 0.5),+ pdfEvidence("$12.50", x: 0.4, y: 0.5, width: 0.4)+ ], failure: nil)+ let extractor = PDFCaptureExtractor(model: PDFDateInjectionModel(), evidenceStore: MemoryCaptureEvidence(),+ loadPages: { _ in [page] })+ var final: ReceiptPageState.Status?, proposals: [ValidatedCaptureProposal] = []+ for try await event in extractor.events(source, generation: UUID()) {+ if case let .receiptPage(state, _) = event { final = state.status }+ if case let .proposal(value) = event { proposals.append(value) }+ }+ #expect(proposals.isEmpty)+ #expect(final.map { if case .incomplete = $0 { true } else { false } } == true)+ }+}
diff --git a/Foodnotes/FoodnotesTests/CaptureExtraction/PDFItemisedInvoiceTests.swift b/Foodnotes/FoodnotesTests/CaptureExtraction/PDFItemisedInvoiceTests.swiftnew file mode 100644index 0000000..7eca4ae--- /dev/null+++ b/Foodnotes/FoodnotesTests/CaptureExtraction/PDFItemisedInvoiceTests.swift@@ -0,0 +1,172 @@+import CryptoKit+import Foundation+import FoodnotesDomain+import Testing+import UIKit+@testable import Foodnotes++@MainActor @Suite struct PDFItemisedInvoiceTests {+ @Test func completeInvoiceReviewSaveAndReopenKeepsAllThreeGrossUnitPrices() async throws {+ let root = try temporaryStorageDirectory()+ defer { try? FileManager.default.removeItem(at: root) }+ let bytes = syntheticItemisedInvoice(), url = root.appendingPathComponent("synthetic.pdf")+ try bytes.write(to: url)+ let source = SourceImage(id: UUID(), url: url, mediaType: "application/pdf", byteLength: Int64(bytes.count),+ sha256: SHA256.hash(data: bytes).map { String(format: "%02x", $0) }.joined())+ let session = storageSession(), configuration = storageConfiguration(root.appendingPathComponent("store"))+ let repository = try await CoreDataMealRepository.open(configuration: configuration, session: session)+ var initial = storageDraft(); initial.sources = [source]; initial.occurrences = []; initial.extractionStatus = .pending+ initial.receiptPages = [.init(sourceID: source.id, pageIndex: 0)]+ let extractor = PDFCaptureExtractor(model: WrongInvoiceModel(), evidenceStore: MemoryCaptureEvidence())+ let review = CaptureReviewModel(draft: initial, session: session,+ events: { extractor.events($0, generation: $1) }, persist: { value, owner in+ try await repository.save(value, session: owner)+ })+ review.start()+ let deadline = ContinuousClock.now.advanced(by: .seconds(10))+ while review.reading, ContinuousClock.now < deadline { await Task.yield() }+ try #require(!review.reading)+ #expect(review.draft.place.value == "Example Noodle House")+ #expect(review.suggestions["place"] == nil && review.draft.confirmedPlaceID == nil)+ #expect(review.draft.occurrences.count == 3)+ await review.flush()+ let durable = try #require(try await repository.drafts(session: session).first)+ _ = try await repository.apply(.saveDraft(durable), operationID: UUID(), session: session)+ try await repository.close()+ let reopened = try await CoreDataMealRepository.open(configuration: configuration, session: session)+ let snapshot = try await reopened.snapshot(scope: .both)+ let saved = try #require(snapshot.documents.first)+ let placeID = try #require(saved.meal.placeID.value)+ #expect(snapshot.places.first { $0.id == placeID }?.name.value == "Example Noodle House")+ let placeOrigin = try #require(saved.assets.first?.receiptProvenance?.fields?.first { $0.fieldPath == "place" })+ #expect(placeOrigin.pageIndices == [0] && !placeOrigin.rowIDs.isEmpty)+ #expect(saved.occurrences.count == 3)+ for (name, quantity, cents) in [("Spiced Tofu", 3, 440), ("Garden Noodles", 1, 2_530), ("Brown Rice", 2, 990)] {+ let item = try #require(saved.occurrences.first { $0.displayName.value == name })+ #expect(item.quantity.value == Decimal(quantity))+ #expect(item.price.value == Money(cents: Int64(cents), currencyCode: "AUD"))+ let field = try #require(saved.assets.first?.receiptProvenance?.fields?.first {+ $0.occurrenceID == item.id && $0.fieldPath.hasSuffix(".price")+ })+ let calculation = try #require(field.priceCalculation)+ #expect(try calculation.unitPriceCents() == Int64(cents))+ #expect(calculation.quantity == quantity && calculation.basis == .netRowPlusGST)+ }+ let original = try await reopened.assetURL(id: source.id, session: session)+ #expect(try Data(contentsOf: original) == bytes)+ try await reopened.close()+ }+ @Test func malformedTableRowCannotFallBackToModelGSTPrice() async throws {+ let source = captureSourceValuePDF()+ let pages = [PDFPageEvidence(pageIndex: 0, evidence: [+ pdfEvidence("Tax Point Date Description Qty GST GST Amount Net amount", y: 0.9, source: source.id),+ pdfEvidence("25 Sept 2026 Spiced Tofu 10% $1.20 $12.00", y: 0.8, source: source.id)+ ], failure: nil)]+ let extractor = PDFCaptureExtractor(model: WrongInvoiceModel(), evidenceStore: MemoryCaptureEvidence(), loadPages: { _ in pages })+ var proposals: [ValidatedCaptureProposal] = [], states: [ReceiptPageState.Status] = []+ for try await event in extractor.events(source, generation: UUID()) {+ if case let .proposal(value) = event { proposals.append(value) }+ if case let .receiptPage(state, _) = event { states.append(state.status) }+ }+ #expect(!proposals.contains { $0.proposal.fieldPath.hasPrefix("occurrences.") })+ #expect(states.last == .incomplete("Table columns could not be associated safely"))+ }+ @Test func repeatedDishNamesKeepSeparateTableRowsAndTotalsCannotSupplyItemValues() {+ let page = [pdfEvidence("Tax Point Date Description Qty GST GST Amount Net amount", y: 0.9),+ pdfEvidence("25 Sept 2026 Garden Noodles 1 10% $2.30 $23.00", y: 0.8),+ pdfEvidence("25 Sept 2026 Garden Noodles 2 10% $4.60 $46.00", y: 0.7),+ pdfEvidence("Total net amount $69.00", y: 0.6)]+ let result = PDFReceiptTable.document(PDFReceiptRows.document([page]).map(\.rows))[0]+ #expect(result.candidates.filter { $0.kind == .dish }.map(\.copiedText) == ["Garden Noodles", "Garden Noodles"])+ #expect(result.unitPrices.compactMap { try? $0.calculation.unitPriceText() } == ["25.30", "25.30"])+ #expect(result.protectedRows.count == 2 && !result.omitted)+ }+ @Test func paginationHeadersKeepTableMeaningUntilClosingTotals() {+ let pages = [+ [pdfEvidence("Tax Point Date Description Qty GST GST Amount Net amount", y: 0.9),+ pdfEvidence("25 Sept 2026 Spiced Tofu 3 10% $1.20 $12.00", y: 0.8), pdfEvidence("Page 1 of 2", y: 0.1)],+ [pdfEvidence("Tax Invoice", page: 1, y: 0.95),+ pdfEvidence("25 Sept 2026 Garden Noodles 1 10% $2.30 $23.00", page: 1, y: 0.8),+ pdfEvidence("Total net amount $35.00", page: 1, y: 0.6)]+ ]+ let result = PDFReceiptTable.document(PDFReceiptRows.document(pages).map(\.rows))+ #expect(result[0].unitPrices.compactMap { try? $0.calculation.unitPriceText() } == ["4.40"])+ #expect(result[1].unitPrices.compactMap { try? $0.calculation.unitPriceText() } == ["25.30"])+ #expect(result.allSatisfy { !$0.omitted && $0.protectedRows.count == 1 })+ }+ @Test func invoiceColumnsRecoverEveryDishGrossUnitPriceAndMerchantDespiteWrongModelPrices() async throws {+ let root = try temporaryStorageDirectory()+ defer { try? FileManager.default.removeItem(at: root) }+ let bytes = syntheticItemisedInvoice(), url = root.appendingPathComponent("synthetic-invoice.pdf")+ try bytes.write(to: url)+ let source = SourceImage(id: UUID(), url: url, mediaType: "application/pdf", byteLength: Int64(bytes.count),+ sha256: SHA256.hash(data: bytes).map { String(format: "%02x", $0) }.joined())+ let extractor = PDFCaptureExtractor(model: WrongInvoiceModel(), evidenceStore: MemoryCaptureEvidence())+ var proposals: [ValidatedCaptureProposal] = [], states: [ReceiptPageState.Status] = []+ for try await event in extractor.events(source, generation: UUID()) {+ if case let .proposal(value) = event { proposals.append(value) }+ if case let .receiptPage(state, _) = event { states.append(state.status) }+ }+ let items = Dictionary(grouping: proposals.filter { $0.proposal.fieldPath.hasPrefix("occurrences.") },+ by: { String($0.proposal.fieldPath.split(separator: ".")[1]) })+ #expect(items.count == 3)+ for (name, quantity, price) in [("Spiced Tofu", "3", "4.40"), ("Garden Noodles", "1", "25.30"), ("Brown Rice", "2", "9.90")] {+ let fields = try #require(items.values.first { $0.contains { $0.proposal.value == name } })+ #expect(fields.filter { $0.proposal.fieldPath.hasSuffix(".quantity") }.map(\.proposal.value) == [quantity])+ #expect(fields.filter { $0.proposal.fieldPath.hasSuffix(".price") }.map(\.proposal.value) == [price])+ }+ #expect(proposals.contains { $0.proposal.fieldPath == "place" && $0.proposal.value == "Example Noodle House" })+ #expect(states.last == .processed)+ #expect(try Data(contentsOf: url) == bytes)+ }+}++@MainActor func syntheticItemisedInvoice() -> Data {+ let bounds = CGRect(x: 0, y: 0, width: 612, height: 792)+ return UIGraphicsPDFRenderer(bounds: bounds).pdfData { context in+ context.beginPage()+ func draw(_ text: String, x: CGFloat, y: CGFloat) {+ (text as NSString).draw(at: CGPoint(x: x, y: y),+ withAttributes: [.font: UIFont.systemFont(ofSize: 9), .foregroundColor: UIColor.black])+ }+ draw("Tax Invoice", x: 280, y: 30)+ draw("Synthetic Customer", x: 35, y: 70)+ draw("Australia", x: 35, y: 85)+ draw("Invoice issued by Portier Pacific Pty Ltd on", x: 360, y: 70)+ draw("behalf of:", x: 360, y: 85)+ draw("SYNTHETIC FOODS PTY LTD", x: 360, y: 100)+ draw("Example Noodle House", x: 360, y: 115)+ draw("3000, Example, VIC", x: 360, y: 130)+ draw("Australia", x: 360, y: 145)+ draw("Invoice number: SYNTHETIC-ONLY", x: 35, y: 190)+ draw("Invoice date: 25 Sept 2026", x: 35, y: 205)+ for (text, x) in [("Tax Point Date", 35), ("Description", 150), ("Qty", 300),+ ("GST", 360), ("GST Amount", 410), ("Net amount", 500)] {+ draw(text, x: CGFloat(x), y: 250)+ }+ let items = [("Spiced Tofu", "3", "$1.20", "$12.00"), ("Garden Noodles", "1", "$2.30", "$23.00"),+ ("Brown Rice", "2", "$1.80", "$18.00")]+ for (index, item) in items.enumerated() {+ let y = CGFloat(270 + index * 20)+ for (text, x) in [("25 Sept 2026", 35), (item.0, 150), (item.1, 300), ("10%", 360), (item.2, 410), (item.3, 500)] {+ draw(text, x: CGFloat(x), y: y)+ }+ }+ draw("Total net amount", x: 360, y: 345); draw("$53.00", x: 500, y: 345)+ draw("Total GST 10%", x: 360, y: 365); draw("$5.30", x: 500, y: 365)+ draw("Total amount payable", x: 360, y: 385); draw("$58.30", x: 500, y: 385)+ draw("Portier Pacific Pty Ltd is not the seller of the goods.", x: 35, y: 425)+ }+}++private struct WrongInvoiceModel: CaptureProposalModel {+ func availability(localeIdentifier: String) async -> CaptureModelAvailability { .available }+ func candidates(in evidence: [SourceEvidence], localeIdentifier: String) async throws -> [CaptureCandidate] {+ evidence.flatMap { line -> [CaptureCandidate] in+ guard line.text.contains("Spiced Tofu") else { return [] }+ return [.init(kind: .dish, copiedText: "Spiced Tofu", evidenceID: line.id),+ .init(kind: .quantity, copiedText: "3", evidenceID: line.id),+ .init(kind: .price, copiedText: "$1.20", evidenceID: line.id)]+ }+ }+}
diff --git a/Foodnotes/FoodnotesTests/CaptureExtraction/PDFOrdinaryReceiptBudgetTests.swift b/Foodnotes/FoodnotesTests/CaptureExtraction/PDFOrdinaryReceiptBudgetTests.swiftnew file mode 100644index 0000000..5cb53e0--- /dev/null+++ b/Foodnotes/FoodnotesTests/CaptureExtraction/PDFOrdinaryReceiptBudgetTests.swift@@ -0,0 +1,169 @@+import CryptoKit+import Foundation+import FoodnotesDomain+import Testing+@testable import Foodnotes++@Suite struct PDFOrdinaryReceiptBudgetTests {+ @MainActor @Test func syntheticRefundPDFReadsBothPagesWithoutCreatingFinancialDishes() async throws {+ let texts = syntheticRefundReceiptTexts()+ let root = try temporaryStorageDirectory()+ defer { try? FileManager.default.removeItem(at: root) }+ let bytes = syntheticTextReceiptPDF(texts), url = root.appendingPathComponent("synthetic.pdf")+ try bytes.write(to: url)+ let source = SourceImage(id: UUID(), url: url, mediaType: "application/pdf", byteLength: Int64(bytes.count),+ sha256: SHA256.hash(data: bytes).map { String(format: "%02x", $0) }.joined())+ let extractor = PDFCaptureExtractor(model: RefundAdversarialModel(), evidenceStore: MemoryCaptureEvidence())+ var states: [Int: ReceiptPageState.Status] = [:], values: [ValidatedCaptureProposal] = []+ for try await event in extractor.events(source, generation: UUID()) {+ if case let .receiptPage(state, _) = event { states[state.pageIndex] = state.status }+ if case let .proposal(value) = event { values.append(value) }+ }+ #expect(states == [0: .processed, 1: .processed])+ #expect(values.contains { $0.proposal.fieldPath == "place" && $0.proposal.value == "Synthetic Bistro" })+ #expect(values.contains { $0.proposal.fieldPath == "ordering" && $0.proposal.value == "Delivery" })+ #expect(values.contains { $0.proposal.fieldPath == "date" && $0.proposal.value == "2026-09-25" })+ #expect(values.contains { $0.proposal.fieldPath == "time" && $0.proposal.value == "18:36" })+ #expect(!values.contains { $0.proposal.fieldPath.hasPrefix("occurrences.") })+ #expect(try Data(contentsOf: url) == bytes)+ }+ @Test func sparePageBudgetCarriesForwardWithoutExceedingDocumentLimit() async throws {+ let source = captureSourceValuePDF(), model = OrdinaryReceiptModel()+ let pages = [PDFPageEvidence(pageIndex: 0, evidence: [pdfEvidence("Synthetic header", source: source.id)], failure: nil),+ PDFPageEvidence(pageIndex: 1, evidence: (0..<216).map {+ pdfEvidence($0 == 215 ? "Delivery" : "Synthetic detail \($0)", page: 1,+ y: 0.99 - Double($0) * 0.004, height: 0.002, source: source.id)+ }, failure: nil)]+ let extractor = PDFCaptureExtractor(model: model, evidenceStore: MemoryCaptureEvidence(), loadPages: { _ in pages })+ var states: [Int: ReceiptPageState.Status] = [:]+ for try await event in extractor.events(source, generation: UUID()) {+ if case let .receiptPage(state, _) = event { states[state.pageIndex] = state.status }+ }+ #expect(states == [0: .processed, 1: .processed])+ #expect(await model.calls == 19)+ #expect(await model.seenCount == 217)+ }+ @Test func denseFirstPageCannotStarveLaterPageOrHideOmissions() async throws {+ let source = captureSourceValuePDF(), model = OrdinaryReceiptModel()+ let pages = [PDFPageEvidence(pageIndex: 0, evidence: (0..<240).map {+ pdfEvidence("Synthetic detail \($0)", y: 0.99 - Double($0) * 0.004, height: 0.002, source: source.id)+ }, failure: nil), PDFPageEvidence(pageIndex: 1, evidence: [pdfEvidence("Delivery", page: 1, source: source.id)], failure: nil)]+ let extractor = PDFCaptureExtractor(model: model, evidenceStore: MemoryCaptureEvidence(), loadPages: { _ in pages })+ var states: [Int: ReceiptPageState.Status] = [:], values: [ValidatedCaptureProposal] = []+ for try await event in extractor.events(source, generation: UUID()) {+ if case let .receiptPage(state, _) = event { states[state.pageIndex] = state.status }+ if case let .proposal(value) = event { values.append(value) }+ }+ #expect(states[0] == .incomplete("Page contains more text than the automatic reading budget"))+ #expect(states[1] == .processed)+ #expect(await model.calls == 11)+ #expect(values.contains { $0.proposal.fieldPath == "ordering" && $0.proposal.value == "Delivery" })+ }+ @Test func refundSummaryProvidesOnlyExplicitMerchantAndOrderMode() throws {+ let source = captureSourceValuePDF()+ let rows = [pdfEvidence("We adjusted the total for your recent order from Synthetic Bistro.", source: source.id),+ pdfEvidence("Uber Delivery", page: 1, source: source.id)]+ let values = PDFReceiptMetadata.values(rows, generation: UUID())+ #expect(values.contains { $0.proposal.fieldPath == "place" && $0.proposal.value == "Synthetic Bistro" })+ #expect(values.contains { $0.proposal.fieldPath == "ordering" && $0.proposal.value == "Delivery" })+ #expect(PDFReceiptMetadata.values([pdfEvidence("Delivered by Synthetic Courier")], generation: UUID()).isEmpty)+ #expect(!values.contains { $0.proposal.fieldPath.hasPrefix("occurrences.") })+ }+ @Test func refundFinancialRowsCannotBecomeDishesAndCommaOrderDateIsRead() throws {+ let labels = ["Item Subtotal $57.38", "Delivery discount -$3.49", "Promotion -$17.21",+ "Refund adjustment -$8.65", "Previous total $45.91", "Refund -$8.65", "New Total $37.26",+ "Uber Cash $45.91", "\u{fffc} Uber Cash -$8.65"]+ for label in labels {+ #expect(PDFReceiptRows.assemble([pdfEvidence(label)]).allSatisfy { $0.role != .item })+ }+ let rows = [pdfEvidence("Order completed 25 Sept, 2026 at 6:36 pm")]+ let values = CaptureReceiptTimestamps.pdfValues(pages: [rows], generation: UUID(),+ timeZoneIdentifier: "Australia/Melbourne", localeIdentifier: "en_AU")+ #expect(values.contains { $0.proposal.fieldPath == "date" && $0.proposal.value == "2026-09-25" })+ #expect(values.contains { $0.proposal.fieldPath == "time" && $0.proposal.value == "18:36" })+ #expect(PDFReceiptRows.assemble([pdfEvidence("1 x Refund sandwich $8.50")]).first?.role == .item)+ }+ @Test func ordinaryTwoPageReceiptProcessesEveryBoundedBatchIncludingLateMetadata() async throws {+ let source = captureSourceValuePDF()+ let pages = (0..<2).map { page in+ PDFPageEvidence(pageIndex: page, evidence: (0..<28).map { index in+ pdfEvidence(index == 27 ? "Delivery" : "Synthetic receipt detail \(index)",+ page: page, y: 0.96 - Double(index) * 0.03, height: 0.015, source: source.id)+ }, failure: nil)+ }+ let model = OrdinaryReceiptModel()+ let extractor = PDFCaptureExtractor(model: model, evidenceStore: MemoryCaptureEvidence(), loadPages: { _ in pages })+ var states: [Int: ReceiptPageState.Status] = [:], values: [ValidatedCaptureProposal] = []+ for try await event in extractor.events(source, generation: UUID()) {+ if case let .receiptPage(state, _) = event { states[state.pageIndex] = state.status }+ if case let .proposal(value) = event { values.append(value) }+ }+ #expect(states == [0: .processed, 1: .processed])+ #expect(await model.seenCount == 56)+ #expect(await model.calls == 6)+ #expect(values.contains { $0.proposal.fieldPath == "ordering" && $0.proposal.value == "Delivery" })+ #expect(!values.contains { $0.proposal.fieldPath.hasPrefix("occurrences.") })+ }+}++private struct RefundAdversarialModel: CaptureProposalModel {+ func availability(localeIdentifier: String) async -> CaptureModelAvailability { .available }+ func candidates(in evidence: [SourceEvidence], localeIdentifier: String) async throws -> [CaptureCandidate] {+ evidence.compactMap { line in+ if line.text.hasPrefix("Refund ") { return .init(kind: .dish, copiedText: "Refund", evidenceID: line.id) }+ if line.text == "Uber Delivery" { return .init(kind: .place, copiedText: "Delivery", evidenceID: line.id) }+ if line.text == "6:20 pm - Pick-up" { return .init(kind: .ordering, copiedText: "Pick-up", evidenceID: line.id) }+ return nil+ }+ }+}++private actor OrdinaryReceiptModel: CaptureProposalModel {+ private(set) var seenCount = 0+ private(set) var calls = 0+ func availability(localeIdentifier: String) async -> CaptureModelAvailability { .available }+ func candidates(in evidence: [SourceEvidence], localeIdentifier: String) async throws -> [CaptureCandidate] {+ seenCount += evidence.count; calls += 1+ return evidence.filter { $0.text == "Delivery" }.map {+ CaptureCandidate(kind: .ordering, copiedText: "Delivery", evidenceID: $0.id)+ }+ }+}++private func syntheticRefundReceiptTexts() -> [String] {+ return ["""+ 25 Sept, 2026+ 5:54 pm+ Refunded+ Just a quick update, Synthetic Customer+ We adjusted the total for your recent order from Synthetic Bistro.+ Total $30.00+ Your refund has been applied.+ Uber One savings and other promotions applied+ Item Subtotal $35.00+ Delivery Fee $3.00+ Service Fee $2.00+ Delivery discount -$3.00+ Promotion -$2.00+ Refund adjustment -$5.00+ Previous total $35.00+ Refund -$5.00+ New Total $30.00+ """, """+ Payments+ Uber Cash $35.00+ 25/9/26 6:37 pm+ Uber Cash -$5.00+ 26/9/26 12:30 am Refund+ Portier Pacific is not the seller of the goods.+ Order details+ Uber Delivery+ 6:20 pm - Pick-up+ Synthetic pickup address+ 6:36 pm - Delivery+ Synthetic delivery address+ Delivered by Synthetic Courier+ Order completed 25 Sept, 2026 at 6:36 pm+ Want to review your order history? My orders+ """]+}
diff --git a/Foodnotes/FoodnotesTests/CaptureExtraction/PDFProposalAccountingTests.swift b/Foodnotes/FoodnotesTests/CaptureExtraction/PDFProposalAccountingTests.swiftnew file mode 100644index 0000000..7149681--- /dev/null+++ b/Foodnotes/FoodnotesTests/CaptureExtraction/PDFProposalAccountingTests.swift@@ -0,0 +1,90 @@+import CryptoKit+import Foundation+import FoodnotesDomain+import Testing+@testable import Foodnotes++@MainActor @Suite struct PDFProposalAccountingTests {+ @Test func completeTypedInvoiceDoesNotSpendProposalCapacityOnAlreadyHandledFields() async throws {+ let root = try temporaryStorageDirectory()+ defer { try? FileManager.default.removeItem(at: root) }+ let bytes = syntheticItemisedInvoice(), url = root.appendingPathComponent("synthetic.pdf")+ try bytes.write(to: url)+ let source = SourceImage(id: UUID(), url: url, mediaType: "application/pdf", byteLength: Int64(bytes.count),+ sha256: SHA256.hash(data: bytes).map { String(format: "%02x", $0) }.joined())+ let model = RedundantCappedInvoiceModel()+ let extractor = PDFCaptureExtractor(model: model, evidenceStore: MemoryCaptureEvidence())+ var values: [ValidatedCaptureProposal] = [], states: [ReceiptPageState.Status] = [], fallbacks: [CaptureFallback] = []+ for try await event in extractor.events(source, generation: UUID()) {+ if case let .proposal(value) = event { values.append(value) }+ if case let .receiptPage(state, _) = event { states.append(state.status) }+ if case let .manualFallback(reason) = event { fallbacks.append(reason) }+ }+ #expect(values.filter { $0.proposal.fieldPath.hasSuffix(".name") }.count == 3)+ #expect(Set(values.filter { $0.proposal.fieldPath.hasSuffix(".price") }.map(\.proposal.value)) == ["4.40", "25.30", "9.90"])+ #expect(values.contains { $0.proposal.fieldPath == "place" && $0.proposal.value == "Example Noodle House" })+ #expect(states.last == .processed && fallbacks.isEmpty)+ var draft = storageDraft(); draft.sources = [source]; draft.occurrences = []; draft.extractionStatus = .pending+ draft.receiptPages = [.init(sourceID: source.id, pageIndex: 0)]+ let review = CaptureReviewModel(draft: draft, session: storageSession(),+ events: { extractor.events($0, generation: $1) }, persist: { _, _ in })+ review.start()+ try await finished(review)+ #expect(!review.needsManualEntry && review.draft.receiptPages?.first?.status == .processed)+ #expect(review.draft.occurrences.count == 3)+ #expect(await model.calls == 0)+ }++ @Test func retryNoticeReflectsTheNewAttemptAndStillShowsNewFailures() async throws {+ for failsAgain in [false, true] {+ var draft = storageDraft(); draft.sources = [captureSourceValuePDF()]+ draft.extractionStatus = .pending; draft.receiptPages = [.init(sourceID: draft.sources[0].id, pageIndex: 0)]+ let first = AsyncThrowingStream<CaptureExtractionEvent, Error>.makeStream()+ let second = AsyncThrowingStream<CaptureExtractionEvent, Error>.makeStream()+ let streams = LockedReceiptStreams([first.stream, second.stream])+ let review = CaptureReviewModel(draft: draft, session: storageSession(), events: { _, _ in streams.next() },+ persist: { _, _ in })+ review.start()+ first.continuation.yield(.manualFallback(.inputLimit))+ first.continuation.yield(.receiptPage(.init(sourceID: draft.sources[0].id, pageIndex: 0,+ status: .incomplete("Previous limit")), generation: draft.generation))+ first.continuation.finish()+ try await finished(review)+ #expect(review.needsManualEntry)+ review.retryReceipt()+ if failsAgain { second.continuation.yield(.manualFallback(.generationFailed)) }+ second.continuation.yield(.receiptPage(.init(sourceID: draft.sources[0].id, pageIndex: 0,+ status: failsAgain ? .incomplete("New failure") : .processed), generation: draft.generation))+ second.continuation.finish()+ try await finished(review)+ #expect(review.needsManualEntry == failsAgain)+ #expect(review.draft.occurrences == draft.occurrences)+ }+ }+ private func finished(_ review: CaptureReviewModel) async throws {+ let deadline = ContinuousClock.now.advanced(by: .seconds(3))+ while review.reading, ContinuousClock.now < deadline { await Task.yield() }+ try #require(!review.reading)+ }+}++private actor RedundantCappedInvoiceModel: CaptureProposalModel {+ private(set) var calls = 0+ func availability(localeIdentifier: String) async -> CaptureModelAvailability { .available }+ func candidates(in evidence: [SourceEvidence], localeIdentifier: String) async throws -> [CaptureCandidate] {+ calls += 1+ guard let line = evidence.first else { return [] }+ return (0..<12).map { _ in .init(kind: .place, copiedText: "Not present in source", evidenceID: line.id) }+ }+}++nonisolated private final class LockedReceiptStreams: @unchecked Sendable {+ private let lock = NSLock()+ private let streams: [AsyncThrowingStream<CaptureExtractionEvent, Error>]+ private var index = 0+ init(_ streams: [AsyncThrowingStream<CaptureExtractionEvent, Error>]) { self.streams = streams }+ func next() -> AsyncThrowingStream<CaptureExtractionEvent, Error> {+ lock.lock(); defer { lock.unlock() }+ let result = streams[min(index, streams.count - 1)]; index += 1; return result+ }+}
diff --git a/Foodnotes/FoodnotesTests/CaptureExtraction/PDFProposalLimitTests.swift b/Foodnotes/FoodnotesTests/CaptureExtraction/PDFProposalLimitTests.swiftnew file mode 100644index 0000000..93f6800--- /dev/null+++ b/Foodnotes/FoodnotesTests/CaptureExtraction/PDFProposalLimitTests.swift@@ -0,0 +1,65 @@+import Foundation+import FoodnotesDomain+import Testing+@testable import Foodnotes++@Suite struct PDFProposalLimitTests {+ @Test func genuinelyCappedUnresolvedItemsRemainIncomplete() async throws {+ let result = try await run(model: CappedUnresolvedItems(), count: 5)+ #expect(result.states.last == .incomplete("Automatic proposal limit reached; check remaining items manually"))+ #expect(result.values.filter { $0.proposal.fieldPath.hasSuffix(".name") }.count == 4)+ }+ @Test func rawLimitSurvivesRejectedOrUndecodableCandidates() async throws {+ let result = try await run(model: RawCappedBatch(), count: 1)+ #expect(result.values.isEmpty)+ #expect(result.states.last == .incomplete("Automatic proposal limit reached; check remaining items manually"))+ }+ @Test func uncappedDuplicatesRejectedAndSystemProposalsDoNotBecomeExtraFields() async throws {+ let result = try await run(model: UncappedDuplicateBatch(), count: 1)+ #expect(result.states.last == .processed)+ #expect(result.values.count == 1 && result.values[0].proposal.value == "Noodles")+ }+ private struct Result { let values: [ValidatedCaptureProposal]; let states: [ReceiptPageState.Status] }+ private func run(model: any CaptureProposalModel, count: Int) async throws -> Result {+ let source = captureSourceValuePDF()+ let lines = (0..<count).map {+ pdfEvidence("2 x Noodles $12.50", y: 0.9 - Double($0) * 0.1, source: source.id)+ }+ let extractor = PDFCaptureExtractor(model: model, evidenceStore: MemoryCaptureEvidence(),+ loadPages: { _ in [.init(pageIndex: 0, evidence: lines, failure: nil)] })+ var values: [ValidatedCaptureProposal] = [], states: [ReceiptPageState.Status] = []+ for try await event in extractor.events(source, generation: UUID()) {+ if case let .proposal(value) = event { values.append(value) }+ if case let .receiptPage(state, _) = event { states.append(state.status) }+ }+ return .init(values: values, states: states)+ }+}++private struct CappedUnresolvedItems: CaptureProposalModel {+ func availability(localeIdentifier: String) async -> CaptureModelAvailability { .available }+ func candidates(in evidence: [SourceEvidence], localeIdentifier: String) async throws -> [CaptureCandidate] {+ Array(evidence.flatMap { line in+ [CaptureCandidate(kind: .dish, copiedText: "Noodles", evidenceID: line.id),+ .init(kind: .quantity, copiedText: "2", evidenceID: line.id),+ .init(kind: .price, copiedText: "$12.50", evidenceID: line.id)]+ }.prefix(12))+ }+}+private struct RawCappedBatch: CaptureProposalModel {+ func availability(localeIdentifier: String) async -> CaptureModelAvailability { .available }+ func candidates(in evidence: [SourceEvidence], localeIdentifier: String) async throws -> [CaptureCandidate] { [] }+ func batch(in evidence: [SourceEvidence], localeIdentifier: String) async throws -> CaptureModelBatch {+ .init(candidates: [], outputLimitReached: true)+ }+}+private struct UncappedDuplicateBatch: CaptureProposalModel {+ func availability(localeIdentifier: String) async -> CaptureModelAvailability { .available }+ func candidates(in evidence: [SourceEvidence], localeIdentifier: String) async throws -> [CaptureCandidate] {+ guard let line = evidence.first else { return [] }+ return Array(repeating: .init(kind: .dish, copiedText: "Noodles", evidenceID: line.id), count: 3) ++ [.init(kind: .price, copiedText: "$99.99", evidenceID: line.id),+ .init(kind: .date, copiedText: "2026-10-30", evidenceID: line.id),+ .init(kind: .time, copiedText: "12:00", evidenceID: line.id)]+ }+}
diff --git a/Foodnotes/FoodnotesTests/CaptureExtraction/PDFRasterBoundsTests.swift b/Foodnotes/FoodnotesTests/CaptureExtraction/PDFRasterBoundsTests.swiftnew file mode 100644index 0000000..c07476d--- /dev/null+++ b/Foodnotes/FoodnotesTests/CaptureExtraction/PDFRasterBoundsTests.swift@@ -0,0 +1,20 @@+import Foundation+import Testing+@testable import Foodnotes++@Suite struct PDFRasterBoundsTests {+ @Test func finiteInputsCannotOverflowDerivedRasterArithmetic() throws {+ for pair in [(1e-320, 1e-320), (1e308, 1e308), (1e-100, 1e100), (612.0, 792.0)] {+ if let size = PDFReceiptEvidence.rasterDimensions(width: pair.0, height: pair.1) {+ #expect(size.width > 0 && size.height > 0)+ #expect(max(size.width, size.height) <= 2_048)+ #expect(size.width * size.height <= 4_000_000)+ }+ }+ #expect(PDFReceiptEvidence.pixelScale(width: 1e-320, height: 1e-320, pixelsWide: 2_000, pixelsHigh: 2_000) == nil)+ #expect(PDFReceiptEvidence.pixelScale(width: 612, height: 792, pixelsWide: 1_582, pixelsHigh: 2_048) != nil)+ for pair in [(Double.infinity, 1.0), (Double.nan, 1.0), (0.0, 1.0), (-1.0, 1.0)] {+ #expect(PDFReceiptEvidence.rasterDimensions(width: pair.0, height: pair.1) == nil)+ }+ }+}
diff --git a/Foodnotes/FoodnotesTests/CaptureExtraction/PDFReceiptExtractionTests.swift b/Foodnotes/FoodnotesTests/CaptureExtraction/PDFReceiptExtractionTests.swiftnew file mode 100644index 0000000..cd90cd7--- /dev/null+++ b/Foodnotes/FoodnotesTests/CaptureExtraction/PDFReceiptExtractionTests.swift@@ -0,0 +1,201 @@+import CoreGraphics+import Darwin+import CryptoKit+import Foundation+import FoodnotesDomain+import Testing+import UIKit+@testable import Foodnotes++@MainActor func syntheticTextReceiptPDF(_ texts: [String], scanned: Bool = false, nativeHeading: String? = nil) -> Data {+ let bounds = CGRect(x: 0, y: 0, width: 612, height: 792)+ return UIGraphicsPDFRenderer(bounds: bounds).pdfData { context in+ for text in texts {+ context.beginPage()+ let draw = {+ UIColor.white.setFill(); UIRectFill(bounds)+ (text as NSString).draw(in: CGRect(x: 40, y: 50, width: 530, height: 700),+ withAttributes: [.font: UIFont.monospacedSystemFont(ofSize: 12, weight: .regular), .foregroundColor: UIColor.black])+ }+ if scanned {+ let format = UIGraphicsImageRendererFormat(); format.scale = 2+ let image = UIGraphicsImageRenderer(bounds: bounds, format: format).image { _ in draw() }+ image.draw(in: bounds)+ } else { draw() }+ if let nativeHeading {+ (nativeHeading as NSString).draw(at: CGPoint(x: 40, y: 20),+ withAttributes: [.font: UIFont.systemFont(ofSize: 12), .foregroundColor: UIColor.black])+ }+ }+ }+}++nonisolated func pdfEvidence(+ _ text: String, page: Int = 0, x: Double = 0.1, y: Double = 0.8,+ width: Double = 0.8, height: Double = 0.02, source: UUID = storageUUID(700)+) -> SourceEvidence {+ SourceEvidence(id: UUID(), sourceID: source, text: text,+ boundingBox: .init(x: x, y: y, width: width, height: height), pageIndex: page)+}++@MainActor @Suite struct PDFReceiptExtractionTests {+ @Test func columnsWrappedNamesAndRepeatedItemsRetainSeparateOrderedRows() throws {+ let fragments = [pdfEvidence("SYNTHETIC CAFE", y: 0.96),+ pdfEvidence("2", x: 0.05, y: 0.8, width: 0.04), pdfEvidence("Roasted", x: 0.2, y: 0.8, width: 0.2),+ pdfEvidence("Vegetable Noodles", x: 0.2, y: 0.77, width: 0.4), pdfEvidence("$12.50", x: 0.8, y: 0.77, width: 0.15),+ pdfEvidence("2 x Noodles $12.50", y: 0.6), pdfEvidence("2 x Noodles $12.50", y: 0.5),+ pdfEvidence("Carried total $37.50", y: 0.1)]+ let rows = PDFReceiptRows.assemble(fragments)+ let items = rows.filter { $0.role == .item }+ #expect(items.count == 3)+ #expect(items[0].evidence.text.contains("Roasted Vegetable Noodles"))+ #expect(items[1].evidence.id != items[2].evidence.id)+ #expect(rows.last?.role == .excluded)+ #expect(items.allSatisfy { $0.evidence.pageIndex == 0 })+ }+ @Test func seededGeometryRetryKeepsCanonicalIdentityAndBlocksSplitsMergesAndTombstones() throws {+ for seed in 0..<32 {+ let original = ReceiptRowAnchor(id: UUID(), sourceID: storageUUID(700), pageIndex: seed % 20,+ bounds: .init(x: 0.1, y: 0.5, width: 0.8, height: 0.02), occurrenceID: UUID())+ var retry = original; retry.id = UUID(); retry.occurrenceID = UUID()+ let matches = PDFReceiptRowRegistry.match(incoming: [retry], existing: [original], allowNew: false)+ #expect(matches[retry.id] == original)+ var dismissed = original; dismissed.dismissed = true+ #expect(PDFReceiptRowRegistry.match(incoming: [retry], existing: [dismissed], allowNew: false).isEmpty)+ var split = retry; split.id = UUID()+ #expect(PDFReceiptRowRegistry.match(incoming: [retry, split], existing: [original], allowNew: false).isEmpty)+ var unmatched = retry; unmatched.bounds.y = 0.9+ #expect(PDFReceiptRowRegistry.match(incoming: [unmatched], existing: [original], allowNew: false).isEmpty)+ #expect(PDFReceiptRowRegistry.match(incoming: [retry], existing: [], allowNew: false).isEmpty)+ }+ }+ @Test func nativeTextScansAndSelectableTitleOverScanUseSourcePageEvidence() async throws {+ let root = try temporaryStorageDirectory()+ defer { try? FileManager.default.removeItem(at: root) }+ for (scanned, heading) in [(false, nil as String?), (true, nil), (true, "Synthetic Cafe")] {+ let bytes = syntheticTextReceiptPDF(["SYNTHETIC CAFE\n2 x Noodles $12.50\nTOTAL $25.00"],+ scanned: scanned, nativeHeading: heading)+ let source = try pdfSource(bytes, root: root)+ let pages = try await PDFReceiptEvidence().collect(source, preferNative: true,+ consume: VisionPDFReceiptOCR(sourceID: source.id).recognize)+ #expect(pages.count == 1)+ print("PDF_NATIVE_SCAN scanned=\(scanned) failure=\(String(describing: pages[0].failure)) " ++ "text=\(pages[0].evidence.map(\.text))")+ #expect(pages[0].evidence.contains { $0.text.localizedCaseInsensitiveContains("Noodles") })+ #expect(pages[0].evidence.allSatisfy { $0.pageIndex == 0 && $0.sourceID == source.id })+ #expect(try Data(contentsOf: source.url) == bytes)+ }+ #expect(!PDFReceiptRows.nativeUsable([pdfEvidence("SYNTHETIC CAFE", y: 0.95)]))+ }+ @Test func twentyPageInjectedModelWorkIsBoundedAndAccountsForFailuresAndOverflow() async throws {+ let source = captureSourceValuePDF(), generation = UUID(), model = PDFDynamicTestModel(failingCall: 7)+ let pages = (0..<20).map { page in+ PDFPageEvidence(pageIndex: page, evidence: (0..<501).map { row in+ pdfEvidence("2 x Noodles $12.50", page: page, y: 0.99 - Double(row) * 0.0019,+ height: 0.001, source: source.id)+ }, failure: nil)+ }+ let extractor = PDFCaptureExtractor(model: model, evidenceStore: MemoryCaptureEvidence(), loadPages: { _ in pages })+ var states: [Int: ReceiptPageState.Status] = [:], proposals: [ValidatedCaptureProposal] = []+ for try await event in extractor.events(source, generation: generation) {+ if case let .receiptPage(state, _) = event { states[state.pageIndex] = state.status }+ if case let .proposal(value) = event { proposals.append(value) }+ }+ #expect(states.count == 20 && states.values.allSatisfy { if case .incomplete = $0 { true } else { false } })+ #expect(await model.calls == PDFCaptureExtractor.maximumModelBatchesPerDocument)+ #expect(await model.maximumLines <= 12)+ #expect(await model.maximumBytes <= 1_800)+ #expect(!proposals.isEmpty)+ #expect(Set(proposals.filter { $0.proposal.fieldPath.hasSuffix(".name") }.map(\.proposal.fieldPath)).count > 1)+ }+ @Test func unavailableModelKeepsEveryPageExplicitlyIncomplete() async throws {+ let source = captureSourceValuePDF(), model = PDFDynamicTestModel(status: .unavailable)+ let pages = (0..<20).map { PDFPageEvidence(pageIndex: $0,+ evidence: [pdfEvidence("2 x Noodles $12.50", page: $0, source: source.id)], failure: nil) }+ let extractor = PDFCaptureExtractor(model: model, evidenceStore: MemoryCaptureEvidence(), loadPages: { _ in pages })+ var states: [Int: ReceiptPageState.Status] = [:]+ for try await event in extractor.events(source, generation: UUID()) {+ if case let .receiptPage(state, _) = event { states[state.pageIndex] = state.status }+ }+ #expect(states.count == 20)+ #expect(states.values.allSatisfy { if case .incomplete = $0 { true } else { false } })+ #expect(await model.calls == 0)+ }+ @Test func twentyScannedPagesRenderOCRAndRunTheBoundedInjectedModelTogether() async throws {+ let root = try temporaryStorageDirectory()+ defer { try? FileManager.default.removeItem(at: root) }+ let bytes = syntheticTextReceiptPDF(Array(repeating: "SYNTHETIC CAFE\n2 x Noodles $12.50\nTOTAL $25.00", count: 20), scanned: true)+ let source = try pdfSource(bytes, root: root), model = PDFDynamicTestModel()+ let extractor = OnDeviceCaptureExtractor(ocr: FixedCaptureOCR(lines: []), model: model, evidenceStore: MemoryCaptureEvidence())+ var before = rusage(), after = rusage()+ _ = getrusage(RUSAGE_SELF, &before)+ let start = ContinuousClock.now+ var states: [Int: ReceiptPageState.Status] = [:], names: Set<String> = []+ for try await event in extractor.events(source, generation: UUID()) {+ if case let .receiptPage(state, _) = event { states[state.pageIndex] = state.status }+ if case let .proposal(value) = event, value.proposal.fieldPath.hasSuffix(".name") { names.insert(value.proposal.fieldPath) }+ }+ _ = getrusage(RUSAGE_SELF, &after)+ #expect(states.count == 20 && states.values.allSatisfy { $0 == .processed })+ #expect(names.count == 20)+ #expect(await model.calls == 20)+ #expect(try Data(contentsOf: source.url) == bytes)+ print("PDF_RENDER_VISION_INJECTED_MODEL pages=20 elapsed=\(start.duration(to: .now)) " ++ "maxRSSBefore=\(before.ru_maxrss) maxRSSAfter=\(after.ru_maxrss) actualModel=false")+ }+ @Test func missingRegistryCannotBypassPDFDeletionProtectionAtVersionZero() throws {+ var draft = storageDraft(); draft.occurrences = []; draft.sources = [captureSourceValuePDF()]+ let line = pdfEvidence("2 x Noodles $12.50")+ let candidate = CaptureCandidate(kind: .dish, copiedText: "Noodles", evidenceID: line.id)+ let proposal = try #require(CaptureProposalValidator().validate(candidate, evidence: [line], generation: draft.generation))+ var engine = DraftExtractionReview(draft: draft)+ let blocked = engine.apply(proposal); #expect(!blocked)+ let anchor = ReceiptRowAnchor(id: line.id, sourceID: line.sourceID, pageIndex: 0,+ bounds: line.boundingBox, occurrenceID: line.id)+ draft.receiptRows = [anchor]; engine = DraftExtractionReview(draft: draft)+ let applied = engine.apply(proposal); #expect(applied)+ var dismissed = anchor; dismissed.dismissed = true+ draft.receiptRows = [dismissed]+ let restored = try JSONDecoder().decode(Draft.self, from: JSONEncoder().encode(draft))+ var resumed = DraftExtractionReview(draft: restored)+ let restoredBlocked = resumed.apply(proposal); #expect(!restoredBlocked)+ }+ private func pdfSource(_ bytes: Data, root: URL) throws -> SourceImage {+ let url = root.appendingPathComponent("\(UUID()).pdf"); try bytes.write(to: url)+ return SourceImage(id: storageUUID(700), url: url, mediaType: "application/pdf", byteLength: Int64(bytes.count),+ sha256: SHA256.hash(data: bytes).map { String(format: "%02x", $0) }.joined())+ }+}++nonisolated func captureSourceValuePDF() -> SourceImage {+ var value = captureSourceValue(); value.mediaType = "application/pdf"; return value+}++nonisolated final class PDFDynamicTestModel: CaptureProposalModel, @unchecked Sendable {+ private let lock = NSLock()+ private var count = 0, lines = 0, bytes = 0+ var calls: Int { get async { lock.withLock { count } } }+ var maximumLines: Int { get async { lock.withLock { lines } } }+ var maximumBytes: Int { get async { lock.withLock { bytes } } }+ let status: CaptureModelAvailability+ let failingCall: Int?+ init(status: CaptureModelAvailability = .available, failingCall: Int? = nil) {+ self.status = status; self.failingCall = failingCall+ }+ func availability(localeIdentifier: String) async -> CaptureModelAvailability { status }+ func candidates(in evidence: [SourceEvidence], localeIdentifier: String) async throws -> [CaptureCandidate] {+ let call = lock.withLock {+ count += 1; lines = max(lines, evidence.count)+ bytes = max(bytes, evidence.reduce(0) { $0 + $1.text.utf8.count + 40 })+ return count+ }+ try await Task.sleep(for: .milliseconds(1))+ if call == failingCall { throw CaptureReadError.invalidSource }+ return evidence.flatMap { line -> [CaptureCandidate] in+ guard line.text.contains("Noodles") else { return [] }+ return [CaptureCandidate(kind: .dish, copiedText: "Noodles", evidenceID: line.id),+ CaptureCandidate(kind: .quantity, copiedText: "2", evidenceID: line.id),+ CaptureCandidate(kind: .price, copiedText: "$12.50", evidenceID: line.id)]+ }+ }+}
diff --git a/Foodnotes/FoodnotesTests/CaptureExtraction/PDFReceiptReaderTests.swift b/Foodnotes/FoodnotesTests/CaptureExtraction/PDFReceiptReaderTests.swiftnew file mode 100644index 0000000..9f9e5d9--- /dev/null+++ b/Foodnotes/FoodnotesTests/CaptureExtraction/PDFReceiptReaderTests.swift@@ -0,0 +1,161 @@+import CoreGraphics+import CryptoKit+import Foundation+import PDFKit+import Testing+import FoodnotesDomain+@testable import Foodnotes++nonisolated func syntheticReceiptPDF(pages: Int, size: CGSize = CGSize(width: 612, height: 792)) throws -> Data {+ if pages == 0 {+ var text = "%PDF-1.7\n"+ let first = text.utf8.count+ text += "1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n"+ let second = text.utf8.count+ text += "2 0 obj\n<< /Type /Pages /Kids [] /Count 0 >>\nendobj\n"+ let xref = text.utf8.count+ text += "xref\n0 3\n0000000000 65535 f \n"+ text += String(format: "%010d 00000 n \n%010d 00000 n \n", first, second)+ text += "trailer\n<< /Size 3 /Root 1 0 R >>\nstartxref\n\(xref)\n%%EOF\n"+ return Data(text.utf8)+ }+ let bytes = NSMutableData()+ let consumer = try #require(CGDataConsumer(data: bytes))+ var bounds = CGRect(origin: .zero, size: size)+ let context = try #require(CGContext(consumer: consumer, mediaBox: &bounds, nil))+ for _ in 0..<pages {+ context.beginPDFPage(nil)+ context.setFillColor(CGColor(gray: 1, alpha: 1)); context.fill(bounds)+ context.setFillColor(CGColor(gray: 0, alpha: 1)); context.fill(CGRect(x: 30, y: 100, width: 200, height: 10))+ context.endPDFPage()+ }+ context.closePDF()+ return bytes as Data+}++@Suite struct PDFReceiptReaderTests {+ private func source(_ bytes: Data, directory: URL) throws -> SourceImage {+ let url = directory.appendingPathComponent("\(UUID()).pdf")+ try bytes.write(to: url)+ return SourceImage(id: UUID(), url: url, mediaType: "application/pdf", byteLength: Int64(bytes.count),+ sha256: SHA256.hash(data: bytes).map { String(format: "%02x", $0) }.joined())+ }+ @Test func inclusivePageLimitsAndOriginalBytes() throws {+ let directory = try temporaryStorageDirectory()+ defer { try? FileManager.default.removeItem(at: directory) }+ for count in [1, 20] {+ let bytes = try syntheticReceiptPDF(pages: count)+ let input = try source(bytes, directory: directory)+ let admitted = try PDFReceiptAdmission().read(input)+ #expect(admitted.pageCount == count)+ #expect(admitted.bytes == bytes)+ #expect(try Data(contentsOf: input.url) == bytes)+ }+ for count in [0, 21] {+ let input = try source(syntheticReceiptPDF(pages: count), directory: directory)+ #expect(throws: Error.self) { try PDFReceiptAdmission().read(input) }+ }+ }+ @Test func byteBoundaryIsInclusive() throws {+ let directory = try temporaryStorageDirectory()+ defer { try? FileManager.default.removeItem(at: directory) }+ var bytes = try syntheticReceiptPDF(pages: 1)+ bytes.append(Data(repeating: 32, count: 32 * 1_024 * 1_024 - bytes.count))+ let input = try source(bytes, directory: directory)+ #expect(try PDFReceiptAdmission().read(input).bytes.count == bytes.count)+ bytes.append(32)+ let oversized = try source(bytes, directory: directory)+ #expect(throws: Error.self) { try PDFReceiptAdmission().read(oversized) }+ }+ @Test func rejectsSpoofTruncationHashMismatchSymlinkAndLockedDocument() throws {+ let directory = try temporaryStorageDirectory()+ defer { try? FileManager.default.removeItem(at: directory) }+ for bytes in [Data("not a PDF".utf8), Data("%PDF-1.7\ntruncated".utf8)] {+ let input = try source(bytes, directory: directory)+ #expect(throws: Error.self) { try PDFReceiptAdmission().read(input) }+ }+ var input = try source(syntheticReceiptPDF(pages: 1), directory: directory)+ input.sha256 = String(repeating: "0", count: 64)+ #expect(throws: Error.self) { try PDFReceiptAdmission().read(input) }+ let target = try source(syntheticReceiptPDF(pages: 1), directory: directory)+ let link = directory.appendingPathComponent("link.pdf")+ try FileManager.default.createSymbolicLink(at: link, withDestinationURL: target.url)+ input = target; input.url = link+ #expect(throws: Error.self) { try PDFReceiptAdmission().read(input) }+ let document = try #require(PDFDocument(data: syntheticReceiptPDF(pages: 1)))+ let locked = directory.appendingPathComponent("locked.pdf")+ #expect(document.write(to: locked, withOptions: [.userPasswordOption: "synthetic", .ownerPasswordOption: "owner"]))+ let lockedSource = try source(Data(contentsOf: locked), directory: directory)+ #expect(throws: Error.self) { try PDFReceiptAdmission().read(lockedSource) }+ }+ @Test func boundedTwentyPageRenderingHasOneLiveRasterAndExplicitFailures() async throws {+ let directory = try temporaryStorageDirectory()+ defer { try? FileManager.default.removeItem(at: directory) }+ let input = try source(syntheticReceiptPDF(pages: 20, size: CGSize(width: 10_000, height: 14_000)), directory: directory)+ let clock = ContinuousClock(); let start = clock.now+ let lifetime = PDFRasterLifetimeSpy()+ let results = try await PDFReceiptEvidence().collect(input) { index, image in+ lifetime.observe(image)+ #expect(max(image.width, image.height) <= 2_048)+ #expect(image.width * image.height <= 4_000_000)+ if index == 7 { throw CaptureReadError.invalidSource }+ return []+ }+ #expect(results.count == 20)+ #expect(results.map(\.pageIndex) == Array(0..<20))+ #expect(results[7].failure != nil)+ #expect(results.filter { $0.failure == nil }.count == 19)+ print("PDF_RENDER_NATIVE_SIM pages=20 elapsed=\(start.duration(to: clock.now)) priorRasterRetained=\(lifetime.overlapped)")+ #expect(!lifetime.overlapped)+ #expect(try Data(contentsOf: input.url).count == input.byteLength)+ }+ @Test func cancellationStopsBetweenPages() async throws {+ let directory = try temporaryStorageDirectory()+ defer { try? FileManager.default.removeItem(at: directory) }+ let input = try source(syntheticReceiptPDF(pages: 20), directory: directory)+ let task = Task { try await PDFReceiptEvidence().collect(input) { _, _ in throw CancellationError() } }+ await #expect(throws: CancellationError.self) { try await task.value }+ }+ @Test func rotationCropAndAllocationFailureAreBounded() async throws {+ let directory = try temporaryStorageDirectory()+ defer { try? FileManager.default.removeItem(at: directory) }+ let document = try #require(PDFDocument(data: syntheticReceiptPDF(pages: 1)))+ let page = try #require(document.page(at: 0))+ page.rotation = 90+ page.setBounds(CGRect(x: 30, y: 40, width: 200, height: 300), for: .cropBox)+ let bytes = try #require(document.dataRepresentation())+ let input = try source(bytes, directory: directory)+ let result = try await PDFReceiptEvidence(allocate: { _, _ in nil }).collect(input) { _, _ in [] }+ #expect(result.count == 1 && result[0].failure != nil)+ let rendered = try await PDFReceiptEvidence().collect(input) { _, image in+ #expect(image.width > image.height)+ let bytes = try #require(image.dataProvider?.data)+ let pixels = try #require(CFDataGetBytePtr(bytes))+ var xs: [Int] = [], ys: [Int] = []+ for y in stride(from: 0, to: image.height, by: 8) {+ for x in stride(from: 0, to: image.width, by: 8) {+ let offset = y * image.bytesPerRow + x * 4+ if Int(pixels[offset]) + Int(pixels[offset + 1]) + Int(pixels[offset + 2]) < 150 { xs.append(x); ys.append(y) }+ }+ }+ let left = try #require(xs.min()), right = try #require(xs.max())+ let bottom = try #require(ys.min()), top = try #require(ys.max())+ #expect(right - left < image.width / 8)+ #expect(top - bottom > image.height * 3 / 4)+ #expect(Double(left + right) / 2 / Double(image.width) > 0.18)+ #expect(Double(left + right) / 2 / Double(image.width) < 0.25)+ return []+ }+ #expect(rendered.count == 1 && rendered[0].failure == nil)+ }+}++nonisolated private final class PDFRasterLifetimeSpy: @unchecked Sendable {+ private let lock = NSLock()+ private weak var previous: CGImage?+ private var overlap = false+ var overlapped: Bool { lock.withLock { overlap } }+ func observe(_ image: CGImage) {+ lock.withLock { if previous != nil { overlap = true }; previous = image }+ }+}
diff --git a/Foodnotes/FoodnotesTests/CaptureExtraction/PDFRepeatedHeaderTests.swift b/Foodnotes/FoodnotesTests/CaptureExtraction/PDFRepeatedHeaderTests.swiftnew file mode 100644index 0000000..6d75e58--- /dev/null+++ b/Foodnotes/FoodnotesTests/CaptureExtraction/PDFRepeatedHeaderTests.swift@@ -0,0 +1,70 @@+import FoodnotesDomain+import Foundation+import Testing+@testable import Foodnotes++@Suite struct PDFRepeatedHeaderTests {+ @Test func repeatedPositionedMerchantHeadingCannotBorrowTheNamedItemsNumbers() async throws {+ let pages = (0..<2).map { page in+ PDFPageEvidence(pageIndex: page, evidence: [+ pdfEvidence("CHIN CHIN", page: page, y: 0.95),+ pdfEvidence("2 x Noodles $12.50", page: page, y: 0.92),+ pdfEvidence("Cafe Latte $4.50", page: page, y: 0.8),+ pdfEvidence("Roasted", page: page, y: 0.7),+ pdfEvidence("Vegetable Noodles $12.50", page: page, y: 0.67)+ ], failure: nil)+ }+ let names = try await extractedNames(pages)+ #expect(!names.contains("CHIN CHIN"))+ #expect(names.filter { $0 == "Noodles" }.count == 2)+ #expect(names.filter { $0 == "Cafe Latte" }.count == 2)+ #expect(names.filter { $0 == "Roasted Vegetable Noodles" }.count == 2)+ }+ @Test func repeatedTopItemsAndRealWrappedNamesRemainItems() async throws {+ for (first, second, expected) in [("Cafe Latte $4.50", "2 x Noodles $12.50", "Cafe Latte"),+ ("Roasted", "Vegetable Noodles $12.50", "Roasted Vegetable Noodles")] {+ let pages = (0..<2).map { page in+ PDFPageEvidence(pageIndex: page, evidence: [pdfEvidence(first, page: page, y: 0.95),+ pdfEvidence(second, page: page, y: 0.92)], failure: nil)+ }+ #expect(try await extractedNames(pages).filter { $0 == expected }.count == 2)+ }+ }+ @Test func topHeaderClassificationHasNoArbitraryFirstLineCutoff() {+ let pages = (0..<2).map { page in+ (0..<9).map { pdfEvidence("Receipt header \($0)", page: page, y: 0.99 - Double($0) * 0.002, height: 0.001) }+ + [pdfEvidence("CHIN CHIN", page: page, y: 0.95), pdfEvidence("2 x Noodles $12.50", page: page, y: 0.92)]+ }+ let result = PDFReceiptRows.document(pages)+ #expect(result.allSatisfy { $0.rows.first { $0.evidence.text == "CHIN CHIN" }?.role == .metadata })+ #expect(result.allSatisfy { $0.rows.filter { $0.role == .item }.map(\.evidence.text) == ["2 x Noodles $12.50"] })+ }+ private func extractedNames(_ pages: [PDFPageEvidence]) async throws -> [String] {+ let extractor = PDFCaptureExtractor(model: PDFHeaderInjectionModel(), evidenceStore: MemoryCaptureEvidence(),+ loadPages: { _ in pages })+ var names: [String] = []+ for try await event in extractor.events(captureSourceValuePDF(), generation: UUID()) {+ if case let .proposal(value) = event, value.proposal.fieldPath.hasSuffix(".name") { names.append(value.proposal.value) }+ }+ return names+ }+}++nonisolated private struct PDFHeaderInjectionModel: CaptureProposalModel {+ func availability(localeIdentifier: String) async -> CaptureModelAvailability { .available }+ func candidates(in evidence: [SourceEvidence], localeIdentifier: String) async throws -> [CaptureCandidate] {+ evidence.compactMap { line in+ let name: String+ if line.text.contains("CHIN CHIN") {+ name = "CHIN CHIN"+ } else if line.text.contains("Roasted Vegetable Noodles") {+ name = "Roasted Vegetable Noodles"+ } else if line.text.contains("Noodles") {+ name = "Noodles"+ } else if line.text.contains("Cafe Latte") {+ name = "Cafe Latte"+ } else { return nil }+ return .init(kind: .dish, copiedText: name, evidenceID: line.id)+ }+ }+}
diff --git a/Foodnotes/FoodnotesTests/CaptureExtraction/PDFUnitPriceBasisTests.swift b/Foodnotes/FoodnotesTests/CaptureExtraction/PDFUnitPriceBasisTests.swiftnew file mode 100644index 0000000..e4be5cf--- /dev/null+++ b/Foodnotes/FoodnotesTests/CaptureExtraction/PDFUnitPriceBasisTests.swift@@ -0,0 +1,51 @@+import Foundation+import FoodnotesDomain+import Testing+@testable import Foodnotes++@Suite struct PDFUnitPriceBasisTests {+ @Test func printedGrossUnitAndGrossRowNeverAddTaxTwiceOrDivideUnitPrices() throws {+ for (header, row, expected, basis) in [+ ("Unit price incl GST", "3 $4.40", "4.40", ReceiptPriceCalculation.Basis.printedGrossUnit),+ ("Amount incl GST", "3 $13.20", "4.40", .grossRow),+ ("GST GST Amount Net amount Unit price incl GST", "3 10% $1.20 $12.00 $4.40", "4.40", .printedGrossUnit),+ ("Amount incl GST", "3 $10.00", "3.33", .grossRow),+ ("Amount incl GST", "2 $0.01", "0.01", .grossRow)+ ] {+ let evidence = [pdfEvidence("Tax Point Date Description Qty " + header, y: 0.9),+ pdfEvidence("25 Sept 2026 Synthetic Noodles " + row, y: 0.8)]+ let rows = PDFReceiptRows.document([evidence])[0].rows+ let page = PDFReceiptTable.document([rows])[0], value = try #require(page.unitPrices.first)+ let proposal = try #require(PDFReceiptTable.proposal(value, evidence: rows.map(\.evidence), generation: UUID()))+ #expect(proposal.proposal.value == expected)+ #expect(try value.calculation.unitPriceText() == expected)+ #expect(value.calculation.basis == basis)+ #expect(!page.omitted)+ }+ }+ @Test func ambiguousBasisMissingRowTaxAndConflictingPrintedUnitStayUnpriced() {+ for (header, body) in [+ ("Amount", "3 $13.20"),+ ("GST GST Amount Net amount", "3 10% $12.00"),+ ("GST GST Amount Net amount Unit price incl GST", "3 10% $1.20 $12.00 $5.00"),+ ("Amount incl GST", "0 $13.20")+ ] {+ let evidence = [pdfEvidence("Tax Point Date Description Qty " + header, y: 0.9),+ pdfEvidence("25 Sept 2026 Synthetic Noodles " + body, y: 0.8),+ pdfEvidence("Total GST $1.20", y: 0.6)]+ let page = PDFReceiptTable.document(PDFReceiptRows.document([evidence]).map(\.rows))[0]+ #expect(page.unitPrices.isEmpty && page.omitted && page.protectedRows.count == 1)+ }+ }+ @Test func derivedPriceRevalidatesSourceAndCarriesCalculationRatherThanPretendingCopiedText() throws {+ let evidence = [pdfEvidence("Tax Point Date Description Qty GST GST Amount Net amount", y: 0.9),+ pdfEvidence("25 Sept 2026 Synthetic Noodles 3 10% $1.20 $12.00", y: 0.8)]+ let rows = PDFReceiptRows.document([evidence])[0].rows+ let page = PDFReceiptTable.document([rows])[0], price = try #require(page.unitPrices.first)+ let proposal = try #require(PDFReceiptTable.proposal(price, evidence: rows.map(\.evidence), generation: UUID()))+ #expect(proposal.proposal.value == "4.40" && proposal.proposal.priceCalculation == price.calculation)+ var changed = rows.map(\.evidence); changed[1].text = "25 Sept 2026 Synthetic Noodles 3 10% $2.00 $12.00"+ #expect(PDFReceiptTable.proposal(price, evidence: changed, generation: UUID()) == nil)+ #expect(PDFReceiptTable.proposal(price, evidence: [], generation: UUID()) == nil)+ }+}
diff --git a/Foodnotes/FoodnotesTests/CaptureExtraction/PlacePrefillTests.swift b/Foodnotes/FoodnotesTests/CaptureExtraction/PlacePrefillTests.swiftnew file mode 100644index 0000000..1638bb8--- /dev/null+++ b/Foodnotes/FoodnotesTests/CaptureExtraction/PlacePrefillTests.swift@@ -0,0 +1,49 @@+import Foundation+import FoodnotesDomain+import Testing+@testable import Foodnotes++@Suite struct PlacePrefillTests {+ @Test func recognisedPlacePrefillsEditableTextWithoutInventingIdentity() throws {+ let proposal = try value(), draft = initial()+ var review = DraftExtractionReview(draft: draft)+ let applied = review.apply(proposal); #expect(applied)+ #expect(review.draft.place.value == "Recognised restaurant")+ #expect(review.draft.confirmedPlaceID == nil && review.draft.confirmedOrdering == nil)+ #expect(review.suggestions["place"] == nil)+ if case .extracted = review.draft.place.provenance {} else { Issue.record("Prefill must retain extracted provenance") }+ }+ @Test func existingSelectionOrManualEditIncludingClearCannotBeReplaced() throws {+ let proposal = try value()+ for mode in 0..<4 {+ var draft = initial()+ if mode == 0 { draft.confirmedPlaceID = UUID() }+ if mode == 1 { draft.place = .init(value: "User choice", provenance: .manual, editVersion: 1) }+ if mode == 2 { draft.place = .init(value: "", provenance: .manual, editVersion: 1) }+ if mode == 3 {+ draft.confirmedOrdering = .init(optionID: UUID(), label: "Saved method", type: nil, url: nil, phone: nil, note: nil)+ }+ var review = DraftExtractionReview(draft: draft)+ let applied = review.apply(proposal); #expect(!applied)+ #expect(review.draft == draft)+ }+ }+ @Test func manualCorrectionSurvivesResumeAndRetry() throws {+ let proposal = try value()+ var review = DraftExtractionReview(draft: initial())+ let applied = review.apply(proposal); #expect(applied)+ var edited = review.draft+ edited.place = .init(value: "My branch", provenance: .manual, editVersion: 1)+ let updated = review.updateDraft(edited, fieldPath: "place"); #expect(updated)+ let restored = try JSONDecoder().decode(Draft.self, from: JSONEncoder().encode(review.draft))+ var retry = DraftExtractionReview(draft: restored)+ let reapplied = retry.apply(proposal); #expect(!reapplied)+ #expect(retry.draft.place.value == "My branch")+ }+ private func initial() -> Draft { var draft = storageDraft(); draft.sources = [captureSource()]; return draft }+ private func value() throws -> ValidatedCaptureProposal {+ let evidence = captureEvidence("Recognised restaurant")+ return try #require(CaptureProposalValidator().validate(.init(kind: .place, copiedText: evidence.text, evidenceID: evidence.id),+ evidence: [evidence], generation: storageUUID(501)))+ }+}
diff --git a/Foodnotes/FoodnotesTests/CaptureInputs/CaptureReviewTests.swift b/Foodnotes/FoodnotesTests/CaptureInputs/CaptureReviewTests.swiftindex 498a65e..c488a6f 100644--- a/Foodnotes/FoodnotesTests/CaptureInputs/CaptureReviewTests.swift+++ b/Foodnotes/FoodnotesTests/CaptureInputs/CaptureReviewTests.swift@@ -35,7 +35,7 @@ import Testing #expect(review.suggestions.isEmpty) } - @Test func confirmedSuggestionsRemainLabelsAndManualDateTimeWin() async throws {+ @Test func placePrefillsWhileOrderingNeedsConfirmationAndManualDateTimeWin() async throws { var initial = storageDraft() initial.sources = [captureSource()] initial.extractionStatus = .pending@@ -44,9 +44,8 @@ import Testing review.start() continuation.yield(.proposal(proposal(initial, "place", "Suggested cafe"))) continuation.yield(.proposal(proposal(initial, "ordering", "Something copied")))- try await waitReview { review.suggestions.count == 2 }- #expect(review.draft.place.value == nil && review.draft.ordering.value == nil)- review.confirm("place")+ try await waitReview { review.suggestions["ordering"] != nil && review.draft.place.value == "Suggested cafe" }+ #expect(review.suggestions["place"] == nil && review.draft.ordering.value == nil) review.confirm("ordering") #expect(review.draft.place.value == "Suggested cafe" && review.draft.ordering.value == "Something copied") #expect(review.draft.confirmedPlaceID == nil && review.draft.confirmedOrdering == nil)
diff --git a/Foodnotes/FoodnotesTests/CaptureInputs/PDFProviderBudgetTests.swift b/Foodnotes/FoodnotesTests/CaptureInputs/PDFProviderBudgetTests.swiftnew file mode 100644index 0000000..491c66b--- /dev/null+++ b/Foodnotes/FoodnotesTests/CaptureInputs/PDFProviderBudgetTests.swift@@ -0,0 +1,45 @@+import CaptureHandoff+import Foundation+import Testing+import UIKit+import UniformTypeIdentifiers+@testable import Foodnotes++@MainActor @Suite struct PDFProviderBudgetTests {+ @Test func excessivePDFAliasesRejectBeforeLoadingAnyProvider() async throws {+ let root = try temporaryStorageDirectory()+ defer { try? FileManager.default.removeItem(at: root) }+ let marker = root.appendingPathComponent("loaded")+ let providers = (0..<5).map { _ in+ let provider = NSItemProvider()+ provider.registerFileRepresentation(forTypeIdentifier: UTType.pdf.identifier, fileOptions: [], visibility: .all) {+ try? Data([1]).write(to: marker)+ $0(nil, false, HandoffError.invalidSource); return nil+ }+ return provider+ }+ let item = NSExtensionItem(); item.attachments = providers+ await #expect(throws: HandoffError.invalidSource) {+ try await PDFHandoffInput.prepare([item], directory: root)+ }+ #expect(!FileManager.default.fileExists(atPath: marker.path))+ #expect(!FileManager.default.fileExists(atPath: root.appendingPathComponent("ProviderStaging").path))+ }+ @Test func fourIdenticalPDFProvidersStillAdmitOneReceipt() async throws {+ let root = try temporaryStorageDirectory()+ defer { try? FileManager.default.removeItem(at: root) }+ let bytes = try syntheticReceiptPDF(pages: 1), url = root.appendingPathComponent("synthetic.pdf")+ try bytes.write(to: url)+ let providers = (0..<4).map { _ in+ let provider = NSItemProvider()+ provider.registerFileRepresentation(forTypeIdentifier: UTType.pdf.identifier, fileOptions: [], visibility: .all) {+ $0(url, false, nil); return nil+ }+ return provider+ }+ let item = NSExtensionItem(); item.attachments = providers+ let retained = try await PDFHandoffInput.prepare([item], directory: root)+ #expect(try Data(contentsOf: retained.url) == bytes)+ #expect(retained.metadata.mediaType == "application/pdf")+ }+}
diff --git a/Foodnotes/FoodnotesTests/CaptureInputs/PDFReceiptEntryTests.swift b/Foodnotes/FoodnotesTests/CaptureInputs/PDFReceiptEntryTests.swiftnew file mode 100644index 0000000..41246af--- /dev/null+++ b/Foodnotes/FoodnotesTests/CaptureInputs/PDFReceiptEntryTests.swift@@ -0,0 +1,87 @@+import CaptureHandoff+import FoodnotesDomain+import Foundation+import Testing+@testable import Foodnotes++@MainActor @Suite struct PDFReceiptEntryTests {+ @Test func filesEntryOpensPDFRequestAlongsideCameraAndPhotos() async throws {+ let fixture = try await PDFEntryFixture.open()+ defer { try? FileManager.default.removeItem(at: fixture.root) }+ for route in [CaptureRoute.files, .camera, .photos] {+ fixture.app.captureInput = nil+ await fixture.app.beginCapture(route)+ #expect(fixture.app.captureInput?.route == route)+ }+ try await fixture.app.close()+ }+ @Test func pickedFilesOriginalSurvivesNoticeManualCorrectionSaveAndReopen() async throws {+ let fixture = try await PDFEntryFixture.open()+ defer { try? FileManager.default.removeItem(at: fixture.root) }+ await fixture.app.refreshCapture(openIncoming: false)+ let coordinator = try #require(fixture.app.captureCoordinator)+ let request = fixture.request()+ await fixture.app.acceptCapture(fixture.original, request: request, coordinator: coordinator)+ #expect(FileManager.default.fileExists(atPath: fixture.original.path))+ #expect(fixture.app.editingDraft == nil && fixture.app.captureCompatibility.count == 1)+ await fixture.app.acceptPDFCompatibility()+ let metadata = try #require(fixture.app.editingDraft)+ var draft = try #require(try await fixture.repository.reviewDraft(id: metadata.id, session: fixture.session))+ #expect(draft.route == .files && draft.receiptPages?.count == 2)+ draft.title = ManualMeal.field("Corrected PDF meal")+ var line = ManualMeal.line(index: 0); line.name = ManualMeal.field("Manual noodles")+ line.quantity = ManualMeal.field("2.5"); line.price = ManualMeal.field("12.50")+ draft.occurrences = [line]; draft.extractionStatus = .finished+ try await fixture.repository.save(draft, session: fixture.session)+ _ = try await fixture.repository.apply(.saveDraft(draft), operationID: UUID(), session: fixture.session)+ let document = try #require(try await fixture.repository.snapshot(scope: .both).documents.first)+ #expect(document.occurrences.first?.quantity.value == Decimal(string: "2.5"))+ #expect(document.occurrences.first?.price.value?.cents == 1_250)+ let asset = try #require(document.assets.first)+ let url = try await fixture.repository.assetURL(id: asset.assetID, session: fixture.session)+ let viewer = ReceiptSourceViewModel(source: .init(id: asset.assetID, url: url, mediaType: asset.mediaType,+ byteLength: asset.byteLength, sha256: asset.sha256))+ await viewer.load(); viewer.select(pageIndex: 1)+ #expect(viewer.bytes == fixture.bytes && viewer.currentPage == 1)+ try await fixture.app.close()+ let reopened = try await CoreDataMealRepository.open(configuration: storageConfiguration(fixture.root), session: fixture.session)+ #expect(try await reopened.snapshot(scope: .both).documents.first?.assets.first?.receiptProvenance?.pages.count == 2)+ #expect(try Data(contentsOf: fixture.original) == fixture.bytes)+ try await reopened.close()+ }+ @Test func rejectedFilesNeverDeleteSelectionOrCreateDraft() async throws {+ let fixture = try await PDFEntryFixture.open()+ defer { try? FileManager.default.removeItem(at: fixture.root) }+ try Data("not a PDF".utf8).write(to: fixture.original)+ await fixture.app.refreshCapture(openIncoming: false)+ let coordinator = try #require(fixture.app.captureCoordinator)+ await fixture.app.acceptCapture(fixture.original, request: fixture.request(), coordinator: coordinator)+ #expect(FileManager.default.fileExists(atPath: fixture.original.path))+ #expect(try await fixture.repository.drafts(session: fixture.session).isEmpty)+ #expect(fixture.app.error != nil)+ try await fixture.app.close()+ }+}++@MainActor private struct PDFEntryFixture {+ let root: URL+ let app: AppDependencies+ let repository: CoreDataMealRepository+ let session: AccountSession+ let original: URL+ let bytes: Data+ static func open() async throws -> Self {+ let root = try temporaryStorageDirectory(), session = storageSession()+ let repository = try await CoreDataMealRepository.open(configuration: storageConfiguration(root), session: session)+ let app = AppDependencies(); app.directory = root+ app.captureSharedDirectory = { root.appendingPathComponent("SharedSyntheticInbox") }+ try await app.attach(repository, session: session)+ let original = root.appendingPathComponent("PickedOriginal.pdf"), bytes = try syntheticReceiptPDF(pages: 2)+ try bytes.write(to: original)+ return Self(root: root, app: app, repository: repository, session: session, original: original, bytes: bytes)+ }+ func request() -> CaptureInputRequest {+ .init(id: UUID(), sourceID: UUID(), route: .files, session: session,+ destination: .personal(accountID: session.accountID), capturedAt: Date(), timeZoneIdentifier: "UTC")+ }+}
diff --git a/Foodnotes/FoodnotesTests/CaptureInputs/PDFReceiptIntakeTests.swift b/Foodnotes/FoodnotesTests/CaptureInputs/PDFReceiptIntakeTests.swiftnew file mode 100644index 0000000..2bfc6ba--- /dev/null+++ b/Foodnotes/FoodnotesTests/CaptureInputs/PDFReceiptIntakeTests.swift@@ -0,0 +1,213 @@+import CaptureHandoff+import Foundation+import FoodnotesDomain+import Testing+import UIKit+import UniformTypeIdentifiers+@testable import Foodnotes++@MainActor @Suite struct PDFReceiptIntakeTests {+ private func provider(_ url: URL, alternate: Bool = false) -> NSItemProvider {+ let provider = NSItemProvider()+ for type in alternate ? [UTType.pdf.identifier, UTType.data.identifier] : [UTType.pdf.identifier] {+ provider.registerFileRepresentation(forTypeIdentifier: type, fileOptions: [], visibility: .all) { completion in+ completion(url, false, nil); return nil+ }+ }+ return provider+ }+ private func item(_ attachments: [NSItemProvider]) -> NSExtensionItem {+ let item = NSExtensionItem(); item.attachments = attachments; return item+ }+ @Test func realProvidersPreferPDFOverDecorativeThumbnailAndDeduplicateBytes() async throws {+ let root = try temporaryStorageDirectory()+ defer { try? FileManager.default.removeItem(at: root) }+ let url = root.appendingPathComponent("synthetic.pdf")+ let bytes = try syntheticReceiptPDF(pages: 2); try bytes.write(to: url)+ let thumbnail = NSItemProvider(item: handoffPNG() as NSData, typeIdentifier: UTType.png.identifier)+ let retained = try await PDFHandoffInput.prepare(+ [item([provider(url, alternate: true), thumbnail, provider(url)])], directory: root)+ defer { try? FileManager.default.removeItem(at: retained.url) }+ #expect(retained.metadata.mediaType == "application/pdf")+ #expect(try Data(contentsOf: retained.url) == bytes)+ }+ @Test func differentPDFProvidersRejectWithoutPublishing() async throws {+ let root = try temporaryStorageDirectory()+ defer { try? FileManager.default.removeItem(at: root) }+ let first = root.appendingPathComponent("first.pdf"), second = root.appendingPathComponent("second.pdf")+ try syntheticReceiptPDF(pages: 1).write(to: first); try syntheticReceiptPDF(pages: 2).write(to: second)+ await #expect(throws: Error.self) {+ try await PDFHandoffInput.prepare([item([provider(first), provider(second)])], directory: root)+ }+ #expect(!FileManager.default.fileExists(atPath: root.appendingPathComponent("Incoming").path))+ }+ @Test func imagePayloadRemainsImageAndCancellationPublishesNothing() async throws {+ let root = try temporaryStorageDirectory()+ defer { try? FileManager.default.removeItem(at: root) }+ let url = root.appendingPathComponent("image.png"); try handoffPNG().write(to: url)+ let image = NSItemProvider(contentsOf: url)!+ let result = try await PDFHandoffInput.prepare([item([image])], directory: root)+ #expect(result.metadata.mediaType == "image/png")+ try FileManager.default.removeItem(at: result.url)+ let task = Task { try Task.checkCancellation(); return try await PDFHandoffInput.prepare([item([image])], directory: root) }+ task.cancel()+ await #expect(throws: CancellationError.self) { try await task.value }+ }+ @Test func boundedCopyRejectsMutationAndKeepsOwnedOriginalExact() throws {+ let root = try temporaryStorageDirectory()+ defer { try? FileManager.default.removeItem(at: root) }+ let input = root.appendingPathComponent("input.pdf"), output = root.appendingPathComponent("copy.pdf")+ let bytes = try syntheticReceiptPDF(pages: 1); try bytes.write(to: input)+ try OriginalHandoffPDFFile.copyFile(input, to: output)+ #expect(try Data(contentsOf: output) == bytes)+ try FileManager.default.removeItem(at: output)+ #expect(throws: Error.self) {+ try OriginalHandoffPDFFile.copyFile(input, to: output, beforeVerification: { try Data("changed".utf8).write(to: input) })+ }+ #expect(!FileManager.default.fileExists(atPath: output.path))+ }+ @Test func filesV2WaitsForInstallationAcknowledgementThenDurablyAdmitsOnce() async throws {+ let root = try temporaryStorageDirectory()+ defer { try? FileManager.default.removeItem(at: root) }+ let session = storageSession(), library = LibraryID.personal(accountID: session.accountID)+ let repository = try await CoreDataMealRepository.open(configuration: storageConfiguration(root), session: session)+ let group = root.appendingPathComponent("group"), input = root.appendingPathComponent("receipt.pdf")+ let bytes = try syntheticReceiptPDF(pages: 2); try bytes.write(to: input)+ let coordinator = try CaptureInputCoordinator(directory: group, sink: repository, repository: repository)+ _ = try await coordinator.activate(session: session, destination: library, dinerID: session.adultID, zone: "UTC")+ let request = CaptureInputRequest(id: UUID(), sourceID: UUID(), route: .files, session: session,+ destination: library, capturedAt: Date(), timeZoneIdentifier: "UTC")+ let scan = try await coordinator.retain(input, request: request)+ #expect(scan.compatibilityRequired.map(\.operationID) == [request.id])+ #expect(try await repository.drafts(session: session).isEmpty)+ let acknowledgement = PDFCompatibilityAcknowledgement(directory: group)+ try acknowledgement.accept()+ #expect(PDFCompatibilityAcknowledgement(directory: group).accepted)+ let result = try await coordinator.activate(session: session, destination: library, dinerID: session.adultID, zone: "UTC")+ #expect(result.importedDraftIDs == [request.id])+ let draft = try #require(try await repository.drafts(session: session).first)+ #expect(draft.route == .files && draft.receiptPages?.count == 2)+ #expect(try Data(contentsOf: draft.sources[0].url) == bytes)+ let replay = try await coordinator.activate(session: session, destination: library, dinerID: session.adultID, zone: "UTC")+ #expect(replay.importedDraftIDs.isEmpty)+ try await repository.close()+ }+ @Test func filesScopeIsHeldUntilOwnedCopyFinishes() throws {+ let root = try temporaryStorageDirectory()+ defer { try? FileManager.default.removeItem(at: root) }+ let url = root.appendingPathComponent("selected.pdf"); try syntheticReceiptPDF(pages: 1).write(to: url)+ var held = false, released = false+ let copy = try PDFReceiptFilesInput.copy(url, directory: root, start: { _ in held = true; return true },+ stop: { _ in held = false; released = true }, duringCopy: { #expect(held && !released) })+ #expect(!held && released)+ #expect(try Data(contentsOf: copy) == Data(contentsOf: url))+ }+}++extension PDFReceiptIntakeTests {+ @Test func builtExtensionActivationAdmitsPDFWithThumbnailAndRetainsImageRule() throws {+ let plugins = try #require(Bundle.main.builtInPlugInsURL)+ let bundle = try #require(Bundle(url: plugins.appendingPathComponent("FoodnotesShare.appex")))+ let info = try #require(bundle.infoDictionary?["NSExtension"] as? [String: Any])+ let attributes = try #require(info["NSExtensionAttributes"] as? [String: Any])+ let rule = try #require(attributes["NSExtensionActivationRule"] as? String)+ let predicate = NSPredicate(format: rule)+ let pdf = NSItemProvider(item: NSData(), typeIdentifier: UTType.pdf.identifier)+ let thumbnail = NSItemProvider(item: NSData(), typeIdentifier: UTType.png.identifier)+ #expect(predicate.evaluate(with: ["extensionItems": [item([pdf, thumbnail])]]))+ #expect(predicate.evaluate(with: ["extensionItems": [item([thumbnail])]]))+ let text = NSItemProvider(item: "unrelated" as NSString, typeIdentifier: UTType.plainText.identifier)+ #expect(!predicate.evaluate(with: ["extensionItems": [item([text])]]))+ }+ @Test func unsupportedVersionRemainsOnDiskWithoutBeingAdmitted() async throws {+ let root = try temporaryStorageDirectory()+ defer { try? FileManager.default.removeItem(at: root) }+ let url = root.appendingPathComponent("receipt.pdf"); try syntheticReceiptPDF(pages: 1).write(to: url)+ let metadata = try OriginalHandoffPDFFile.metadata(url), source = UUID()+ let envelope = SourceEnvelope(schemaVersion: 2, operationID: UUID(), partitionID: storageSession().partitionID,+ sourceID: source, filename: "\(source).original", mediaType: "application/pdf", byteLength: metadata.length,+ sha256: metadata.digest, capturedAt: Date())+ let group = root.appendingPathComponent("group")+ let handoff = try FileSourceHandoff(directory: group, verify: OriginalHandoffPDFFile.verify)+ try await handoff.publish(envelope, source: url)+ let file = group.appendingPathComponent("Incoming/\(envelope.operationID)/envelope.json")+ var unsupported = envelope; unsupported.schemaVersion = 99+ try JSONEncoder().encode(unsupported).write(to: file, options: .atomic)+ #expect(try await handoff.pending(partitionID: storageSession().partitionID).isEmpty)+ #expect(FileManager.default.fileExists(atPath: file.path))+ }+ @Test func staleFilesCaptureRemainsInCapturedAccountAndSharedDestinationWaits() async throws {+ let root = try temporaryStorageDirectory()+ defer { try? FileManager.default.removeItem(at: root) }+ let session = storageSession(), library = LibraryID.personal(accountID: session.accountID)+ let repository = try await CoreDataMealRepository.open(configuration: storageConfiguration(root), session: session)+ let group = root.appendingPathComponent("group"), input = root.appendingPathComponent("receipt.pdf")+ try syntheticReceiptPDF(pages: 1).write(to: input)+ try PDFCompatibilityAcknowledgement(directory: group).accept()+ let coordinator = try CaptureInputCoordinator(directory: group, sink: repository, repository: repository)+ _ = try await coordinator.activate(session: session, destination: library, dinerID: nil, zone: "UTC")+ let request = CaptureInputRequest(id: UUID(), sourceID: UUID(), route: .files, session: session,+ destination: .shared(householdID: UUID()), capturedAt: Date(), timeZoneIdentifier: "UTC")+ let deferred = try await coordinator.retain(input, request: request)+ #expect(deferred.deferred.map(\.operationID) == [request.id])+ let other = storageSession(2)+ try await repository.activate(other)+ _ = try await coordinator.activate(session: other, destination: .personal(accountID: other.accountID), dinerID: nil, zone: "UTC")+ var stale = request+ stale = CaptureInputRequest(id: UUID(), sourceID: UUID(), route: .files, session: session,+ destination: library, capturedAt: Date(), timeZoneIdentifier: "UTC")+ await #expect(throws: StorageError.staleSession) { try await coordinator.retain(input, request: stale) }+ #expect(try await repository.drafts(session: other).isEmpty)+ let handoff = await coordinator.handoff+ #expect(try await handoff.pending(partitionID: session.partitionID).count == 2)+ try await repository.close()+ }+}++extension PDFReceiptIntakeTests {+ @Test func unsupportedImageRepresentationDoesNotHideSupportedOriginal() async throws {+ let root = try temporaryStorageDirectory()+ defer { try? FileManager.default.removeItem(at: root) }+ let gif = root.appendingPathComponent("unsupported.gif"), png = root.appendingPathComponent("original.png")+ try Data("GIF89a unsupported synthetic representation".utf8).write(to: gif); try handoffPNG().write(to: png)+ let representations = NSItemProvider()+ representations.registerFileRepresentation(forTypeIdentifier: UTType.gif.identifier, fileOptions: [], visibility: .all) {+ $0(gif, false, nil); return nil+ }+ representations.registerFileRepresentation(forTypeIdentifier: UTType.png.identifier, fileOptions: [], visibility: .all) {+ $0(png, false, nil); return nil+ }+ let retained = try await PDFHandoffInput.prepare([item([representations])], directory: root)+ #expect(retained.metadata.mediaType == "image/png")+ #expect(try Data(contentsOf: retained.url) == handoffPNG())+ }+ @Test func ownedPDFValidationDoesNotBlockTheMainActor() async throws {+ let root = try temporaryStorageDirectory()+ defer { try? FileManager.default.removeItem(at: root) }+ let input = root.appendingPathComponent("receipt.pdf"); try syntheticReceiptPDF(pages: 1).write(to: input)+ let gate = PDFIntakeValidationGate()+ let task = Task { try await PDFHandoffInput.prepare([item([provider(input)])], directory: root, pdfMetadata: { url in+ gate.block(); return try OriginalHandoffPDFFile.metadata(url)+ }) }+ for _ in 0..<200 where !gate.started { try await Task.sleep(for: .milliseconds(5)) }+ #expect(gate.started)+ // Reaching this line while the synchronous validation seam is blocked proves actor responsiveness.+ #expect(!gate.timedOut)+ gate.release()+ _ = try await task.value+ #expect(!gate.timedOut)+ }+}++nonisolated private final class PDFIntakeValidationGate: @unchecked Sendable {+ private let lock = NSLock()+ private let semaphore = DispatchSemaphore(value: 0)+ private var began = false, timeout = false+ var started: Bool { lock.withLock { began } }+ var timedOut: Bool { lock.withLock { timeout } }+ func block() {+ lock.withLock { began = true }+ if semaphore.wait(timeout: .now() + 2) == .timedOut { lock.withLock { timeout = true } }+ }+ func release() { semaphore.signal() }+}
diff --git a/Foodnotes/FoodnotesTests/CaptureInputs/PDFReceiptRetryTests.swift b/Foodnotes/FoodnotesTests/CaptureInputs/PDFReceiptRetryTests.swiftnew file mode 100644index 0000000..29b4f6c--- /dev/null+++ b/Foodnotes/FoodnotesTests/CaptureInputs/PDFReceiptRetryTests.swift@@ -0,0 +1,156 @@+import Foundation+import FoodnotesDomain+import Testing+@testable import Foodnotes++@MainActor @Suite struct PDFReceiptRetryTests {+ @Test func persistedRetryReusesOccurrenceAndKeepsManualQuantity() async throws {+ let initial = makeDraft()+ let first = AsyncThrowingStream<CaptureExtractionEvent, Error>.makeStream()+ let review = CaptureReviewModel(draft: initial, session: storageSession(), events: { _, _ in first.stream }, persist: { _, _ in })+ review.start()+ let old = anchor(initial)+ emit(first.continuation, draft: initial, anchor: old, price: false)+ try await wait { review.draft.occurrences.count == 1 && review.draft.occurrences[0].quantity.value == "2" }+ review.draft.occurrences[0].quantity = .init(value: "7", provenance: .manual, editVersion: 3)+ first.continuation.finish()+ try await wait { !review.reading }+ await review.flush()+ let restored = try JSONDecoder().decode(Draft.self, from: JSONEncoder().encode(review.draft))+ let second = AsyncThrowingStream<CaptureExtractionEvent, Error>.makeStream()+ let resumed = CaptureReviewModel(draft: restored, session: storageSession(), events: { _, _ in second.stream },+ persist: { _, _ in })+ resumed.retryReceipt()+ var retry = old; retry.id = UUID(); retry.occurrenceID = retry.id+ emit(second.continuation, draft: restored, anchor: retry)+ second.continuation.finish()+ try await wait { !resumed.reading }+ #expect(resumed.draft.occurrences.count == 1 && resumed.draft.occurrences[0].id == old.occurrenceID)+ #expect(resumed.draft.occurrences[0].quantity.value == "7" && resumed.draft.occurrences[0].quantity.editVersion == 3)+ #expect(resumed.draft.occurrences[0].price.value == "12.50")+ #expect(resumed.draft.receiptRows?.map(\.id) == [old.id])+ }+ @Test func deletionTombstoneSurvivesResumeAndStopsChangedOCRResurrection() async throws {+ let initial = makeDraft(), stream = AsyncThrowingStream<CaptureExtractionEvent, Error>.makeStream()+ let review = CaptureReviewModel(draft: initial, session: storageSession(), events: { _, _ in stream.stream }, persist: { _, _ in })+ review.start()+ let old = anchor(initial)+ emit(stream.continuation, draft: initial, anchor: old)+ try await wait { review.draft.occurrences.count == 1 }+ review.draft.occurrences.removeAll()+ #expect(review.draft.receiptRows?.first?.dismissed == true)+ stream.continuation.finish()+ try await wait { !review.reading }+ let restored = try JSONDecoder().decode(Draft.self, from: JSONEncoder().encode(review.draft))+ let retryStream = AsyncThrowingStream<CaptureExtractionEvent, Error>.makeStream()+ let resumed = CaptureReviewModel(draft: restored, session: storageSession(), events: { _, _ in retryStream.stream },+ persist: { _, _ in })+ resumed.retryReceipt()+ var incoming = old; incoming.id = UUID(); incoming.occurrenceID = incoming.id+ emit(retryStream.continuation, draft: restored, anchor: incoming)+ retryStream.continuation.finish()+ try await wait { !resumed.reading }+ #expect(resumed.draft.occurrences.isEmpty && resumed.needsManualEntry)+ #expect(resumed.draft.receiptRows?.first?.dismissed == true)+ }+ @Test func attemptedIncompletePageCannotCreateFreshVersionZeroRows() async throws {+ var initial = makeDraft()+ initial.receiptPages?[0].status = .incomplete("Previously cancelled")+ let stream = AsyncThrowingStream<CaptureExtractionEvent, Error>.makeStream()+ let review = CaptureReviewModel(draft: initial, session: storageSession(), events: { _, _ in stream.stream }, persist: { _, _ in })+ review.start()+ emit(stream.continuation, draft: initial, anchor: anchor(initial))+ stream.continuation.finish()+ try await wait { !review.reading }+ #expect(review.draft.occurrences.isEmpty && review.needsManualEntry)+ }+ @Test func stalePageAndRegistryEventsCannotChangeAnInvalidatedReview() async throws {+ let initial = makeDraft(), stream = AsyncThrowingStream<CaptureExtractionEvent, Error>.makeStream()+ let review = CaptureReviewModel(draft: initial, session: storageSession(), events: { _, _ in stream.stream }, persist: { _, _ in })+ review.start(); review.invalidate()+ let before = review.draft+ emit(stream.continuation, draft: initial, anchor: anchor(initial))+ stream.continuation.finish()+ await Task.yield()+ #expect(review.draft == before)+ }+ private func makeDraft() -> Draft {+ var value = storageDraft(); value.sources = [captureSourceValuePDF()]; value.occurrences = []+ value.extractionStatus = .pending+ value.receiptPages = [.init(sourceID: value.sources[0].id, pageIndex: 0)]+ return value+ }+ private func anchor(_ draft: Draft) -> ReceiptRowAnchor {+ let id = UUID()+ return .init(id: id, sourceID: draft.sources[0].id, pageIndex: 0,+ bounds: .init(x: 0.1, y: 0.5, width: 0.8, height: 0.02), occurrenceID: id)+ }+ private func emit(_ output: AsyncThrowingStream<CaptureExtractionEvent, Error>.Continuation, draft: Draft,+ anchor: ReceiptRowAnchor, price: Bool = true) {+ output.yield(.receiptPage(.init(sourceID: anchor.sourceID, pageIndex: 0, status: .processing), generation: draft.generation))+ output.yield(.receiptRows([anchor], pageIndex: 0, sourceID: anchor.sourceID, generation: draft.generation))+ for (field, value) in [("name", "Noodles"), ("quantity", "2"), ("price", price ? "12.50" : "")] where !value.isEmpty {+ output.yield(.proposal(.init(proposal: .init(generation: draft.generation,+ fieldPath: "occurrences.\(anchor.id).\(field)", value: value, evidenceIDs: [anchor.id],+ expectedEditVersion: 0, parserVersion: "synthetic-changed-parser"), sourceID: anchor.sourceID)))+ }+ output.yield(.receiptPage(.init(sourceID: anchor.sourceID, pageIndex: 0, status: .processed), generation: draft.generation))+ }+ private func wait(_ condition: () -> Bool) async throws {+ let end = ContinuousClock.now.advanced(by: .seconds(3))+ while !condition(), ContinuousClock.now < end { await Task.yield() }+ try #require(condition())+ }+}++extension PDFReceiptRetryTests {+ @Test func calculatedPriceSourceSurvivesManualQuantityPriceAndRetryWithoutOverwritingEdits() async throws {+ let initial = makeDraft(), first = AsyncThrowingStream<CaptureExtractionEvent, Error>.makeStream()+ let review = CaptureReviewModel(draft: initial, session: storageSession(), events: { _, _ in first.stream }, persist: { _, _ in })+ review.start()+ let old = anchor(initial)+ let calculation = ReceiptPriceCalculation(basis: .netRowPlusGST, quantity: 2, amountCents: 800, gstCents: 80)+ emit(first.continuation, draft: initial, anchor: old, price: false)+ first.continuation.yield(.proposal(.init(proposal: .init(generation: initial.generation,+ fieldPath: "occurrences.\(old.id).price", value: "4.40", evidenceIDs: [old.id], expectedEditVersion: 0,+ parserVersion: "synthetic-derived-unit", priceCalculation: calculation), sourceID: old.sourceID)))+ first.continuation.finish()+ try await wait { !review.reading }+ review.draft.occurrences[0].quantity = .init(value: "7", provenance: .manual, editVersion: 1)+ review.draft.occurrences[0].price = .init(value: "9.99", provenance: .manual, editVersion: 1)+ let restored = try JSONDecoder().decode(Draft.self, from: JSONEncoder().encode(review.draft))+ let second = AsyncThrowingStream<CaptureExtractionEvent, Error>.makeStream()+ let resumed = CaptureReviewModel(draft: restored, session: storageSession(), events: { _, _ in second.stream },+ persist: { _, _ in })+ resumed.retryReceipt()+ var incoming = old; incoming.id = UUID(); incoming.occurrenceID = incoming.id+ emit(second.continuation, draft: restored, anchor: incoming)+ second.continuation.finish()+ try await wait { !resumed.reading }+ #expect(resumed.draft.occurrences[0].quantity.value == "7" && resumed.draft.occurrences[0].price.value == "9.99")+ let field = try #require(resumed.draft.receiptSupportingFields.first { $0.fieldPath.hasSuffix(".price") })+ #expect(field.priceCalculation == calculation)+ #expect(field.priceCalculation?.explanation.hasPrefix("Receipt:") == true)+ #expect(try resumed.draft.savedReceiptProvenance()[old.sourceID]?.fields?.contains(field) == true)+ }+ @Test func previouslyUnmaterializedRowRequiresConfirmationAfterManualCompletion() async throws {+ var initial = makeDraft()+ let old = anchor(initial)+ initial.receiptRows = [old]+ initial.receiptPages?[0].status = .incomplete("Initial model did not produce this item")+ let manual = DraftField(value: "Noodles", provenance: .manual, editVersion: 1)+ let blank = DraftField(value: nil, provenance: .manual, editVersion: 0)+ let manualID = UUID()+ initial.occurrences = [.init(id: manualID, name: manual, quantity: blank, price: blank, note: blank, sortKey: "manual")]+ let channel = AsyncThrowingStream<CaptureExtractionEvent, Error>.makeStream()+ let review = CaptureReviewModel(draft: initial, session: storageSession(), events: { _, _ in channel.stream },+ persist: { _, _ in })+ review.retryReceipt()+ var incoming = old; incoming.id = UUID(); incoming.occurrenceID = incoming.id+ emit(channel.continuation, draft: initial, anchor: incoming)+ channel.continuation.finish()+ try await wait { !review.reading }+ #expect(review.draft.occurrences.map(\.id) == [manualID])+ #expect(review.needsManualEntry)+ }+}
diff --git a/Foodnotes/FoodnotesTests/CaptureInputs/PDFReceiptViewerTests.swift b/Foodnotes/FoodnotesTests/CaptureInputs/PDFReceiptViewerTests.swiftnew file mode 100644index 0000000..5d6c250--- /dev/null+++ b/Foodnotes/FoodnotesTests/CaptureInputs/PDFReceiptViewerTests.swift@@ -0,0 +1,182 @@+import CryptoKit+import FoodnotesDomain+import Foundation+import PDFKit+import SwiftUI+import Testing+import UIKit+import XCTest+@testable import Foodnotes++@MainActor @Suite struct PDFReceiptViewerTests {+ @Test func verifiedOriginalNavigationNeverChangesOriginalBytes() async throws {+ let root = try temporaryStorageDirectory()+ defer { try? FileManager.default.removeItem(at: root) }+ let source = try viewerPDFSource(root), original = try Data(contentsOf: source.url)+ let model = ReceiptSourceViewModel(source: source)+ await model.load()+ #expect(model.bytes == original && model.pageCount == 2)+ model.select(pageIndex: 1)+ #expect(model.currentPage == 1 && model.pageLabel == "Page 2 of 2")+ model.select(pageIndex: 99)+ #expect(model.currentPage == 1)+ model.markUnavailable(pageIndex: 1)+ #expect(model.unavailablePages.contains(1))+ #expect(try Data(contentsOf: source.url) == original)+ }+ @Test func missingAndCorruptOriginalRemainUnavailableWithoutReplacement() async throws {+ let root = try temporaryStorageDirectory()+ defer { try? FileManager.default.removeItem(at: root) }+ var source = try viewerPDFSource(root)+ source.sha256 = String(repeating: "0", count: 64)+ let corrupt = ReceiptSourceViewModel(source: source)+ await corrupt.load()+ #expect(corrupt.bytes == nil && corrupt.pageCount == 0 && corrupt.error?.contains("unavailable") == true)+ try FileManager.default.removeItem(at: source.url)+ let missing = ReceiptSourceViewModel(source: source)+ await missing.load()+ #expect(missing.bytes == nil && missing.error != nil)+ #expect(!FileManager.default.fileExists(atPath: source.url.path))+ }+ @Test func lateReadCannotReopenInvalidatedPresentation() async throws {+ let root = try temporaryStorageDirectory()+ defer { try? FileManager.default.removeItem(at: root) }+ let source = try viewerPDFSource(root), bytes = try Data(contentsOf: source.url)+ let channel = AsyncStream<Void>.makeStream()+ let model = ReceiptSourceViewModel(source: source, read: { _ in+ var iterator = channel.stream.makeAsyncIterator(); _ = await iterator.next()+ return PDFReceiptAdmission.Document(bytes: bytes, pageCount: 2)+ })+ let work = Task { await model.load() }+ await Task.yield(); model.invalidate()+ channel.continuation.yield(()); channel.continuation.finish()+ await work.value+ #expect(model.bytes == nil && model.pageCount == 0)+ }+ @Test func supportingFieldLabelsUseCorrectedDishNamesWithoutInternalPaths() {+ let id = UUID()+ let field = ReceiptFieldProvenance(fieldPath: "occurrences.\(id).quantity", occurrenceID: id,+ pageIndices: [1], rowIDs: [UUID()])+ #expect(ReceiptSupportingPageLabel.field(field, names: [id: "Corrected noodles"]) == "Quantity for Corrected noodles")+ let place = ReceiptFieldProvenance(fieldPath: "place", occurrenceID: nil, pageIndices: [0], rowIDs: [UUID()])+ #expect(ReceiptSupportingPageLabel.field(place, names: [:]) == "Place")+ let unknown = ReceiptFieldProvenance(fieldPath: "internal.unknown", occurrenceID: nil, pageIndices: [0], rowIDs: [])+ #expect(ReceiptSupportingPageLabel.field(unknown, names: [:]) == nil)+ }+ @Test func pageStatusLabelsIdentifyIncompleteAndUnprocessedPages() throws {+ let source = UUID()+ let states: [ReceiptPageState.Status] = [.processed, .incomplete("Reading cancelled"), .pending, .processing]+ let labels = states.enumerated().map {+ ReceiptPageStatusText.label(.init(sourceID: source, pageIndex: $0.offset, status: $0.element))+ }+ #expect(labels[0] == "Page 1: Processed")+ #expect(labels[1].contains("Page 2: Incomplete") && labels[1].contains("Reading cancelled"))+ #expect(labels[2] == "Page 3: Not processed")+ #expect(labels[3] == "Page 4: Reading")+ }+}++@MainActor final class PDFReceiptRenderTests: XCTestCase {+ func testUnitPriceCalculationDisclosureInLightDarkAndAccessibility() async throws {+ let suite = "PDFUnitPriceRenders-" + UUID().uuidString+ let defaults = try XCTUnwrap(UserDefaults(suiteName: suite))+ defer { defaults.removePersistentDomain(forName: suite) }+ defaults.set(true, forKey: DebugInformation.preferenceKey)+ let output = FileManager.default.temporaryDirectory.appendingPathComponent("PDFUnitPriceRenders")+ try FileManager.default.createDirectory(at: output, withIntermediateDirectories: true)+ let id = UUID(), calculation = ReceiptPriceCalculation(basis: .netRowPlusGST, quantity: 3, amountCents: 1_200, gstCents: 120)+ let field = ReceiptFieldProvenance(fieldPath: "occurrences.\(id).price", occurrenceID: id,+ pageIndices: [0], rowIDs: [UUID()], priceCalculation: calculation)+ for (name, scheme, size) in [("light", ColorScheme.light, DynamicTypeSize.large),+ ("dark", .dark, .large), ("accessibility", .light, .accessibility3)] {+ let view = ScrollView {+ VStack(alignment: .leading, spacing: 16) {+ Text("Price each · AUD 4.40").font(.title2)+ ReceiptSupportingPages(fields: [field], names: [id: "Synthetic noodles"], openPage: { _ in })+ }.padding()+ }.defaultAppStorage(defaults).preferredColorScheme(scheme).environment(\.dynamicTypeSize, size)+ let host = UIHostingController(rootView: view)+ let scene = try XCTUnwrap(UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first)+ let window = UIWindow(windowScene: scene); window.frame = CGRect(x: 0, y: 0, width: 390, height: 844)+ window.rootViewController = host; window.makeKeyAndVisible()+ try await Task.sleep(for: .milliseconds(150)); host.view.layoutIfNeeded()+ let image = UIGraphicsImageRenderer(bounds: host.view.bounds).image { _ in+ host.view.drawHierarchy(in: host.view.bounds, afterScreenUpdates: true)+ }+ try XCTUnwrap(image.pngData()).write(to: output.appendingPathComponent(name + ".png"))+ window.isHidden = true+ }+ print("PDF_UNIT_PRICE_RENDER_DIRECTORY=\(output.path)")+ }+ func testPDFViewerLightDarkAndAccessibilityUsesActualPDFKitAndKeepsBytes() async throws {+ let root = try temporaryStorageDirectory()+ defer { try? FileManager.default.removeItem(at: root) }+ let source = try viewerPDFSource(root), bytes = try Data(contentsOf: source.url)+ let output = FileManager.default.temporaryDirectory.appendingPathComponent("PDFReceiptRenders")+ try FileManager.default.createDirectory(at: output, withIntermediateDirectories: true)+ for (name, scheme, size) in [("light", ColorScheme.light, DynamicTypeSize.large),+ ("dark", .dark, .large), ("accessibility", .light, .accessibility3)] {+ let view = ReceiptSourceViewer(source: source, initialPage: 1)+ .preferredColorScheme(scheme).environment(\.dynamicTypeSize, size)+ let host = UIHostingController(rootView: view)+ let scene = try XCTUnwrap(UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first)+ let window = UIWindow(windowScene: scene)+ window.frame = CGRect(x: 0, y: 0, width: 390, height: 844)+ window.rootViewController = host; window.makeKeyAndVisible()+ let end = ContinuousClock.now.advanced(by: .seconds(3))+ while descendants(host.view).allSatisfy({ !($0 is PDFView) }), ContinuousClock.now < end {+ try await Task.sleep(for: .milliseconds(20)); host.view.layoutIfNeeded()+ }+ let pdf = try XCTUnwrap(descendants(host.view).compactMap { $0 as? PDFView }.first)+ XCTAssertEqual(pdf.document?.pageCount, 2)+ let page = try XCTUnwrap(pdf.currentPage), document = try XCTUnwrap(pdf.document)+ XCTAssertEqual(document.index(for: page), 1)+ let image = UIGraphicsImageRenderer(bounds: host.view.bounds).image { _ in+ host.view.drawHierarchy(in: host.view.bounds, afterScreenUpdates: true)+ }+ try XCTUnwrap(image.pngData()).write(to: output.appendingPathComponent(name + ".png"))+ let attachment = XCTAttachment(image: image); attachment.name = "pdf-source-" + name+ attachment.lifetime = .keepAlways; add(attachment)+ window.isHidden = true+ }+ XCTAssertEqual(try Data(contentsOf: source.url), bytes)+ print("PDF_RECEIPT_RENDER_DIRECTORY=\(output.path)")+ }+ func testUnavailablePageClearsPriorPDFAndValidNavigationRestoresIt() async throws {+ let root = try temporaryStorageDirectory()+ defer { try? FileManager.default.removeItem(at: root) }+ let source = try viewerPDFSource(root), bytes = try Data(contentsOf: source.url)+ let selection = PDFViewerSelection()+ let host = UIHostingController(rootView: PDFViewerSelectionView(bytes: bytes, selection: selection))+ let scene = try XCTUnwrap(UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first)+ let window = UIWindow(windowScene: scene); window.frame = CGRect(x: 0, y: 0, width: 390, height: 844)+ window.rootViewController = host; window.makeKeyAndVisible()+ defer { window.isHidden = true }+ try await Task.sleep(for: .milliseconds(150))+ let view = try XCTUnwrap(descendants(host.view).compactMap { $0 as? PDFView }.first)+ XCTAssertEqual(view.document?.pageCount, 2)+ selection.page = 99+ try await Task.sleep(for: .milliseconds(150))+ XCTAssertNil(view.document, "An unavailable page must not display the previous page under a different label")+ selection.page = 1+ try await Task.sleep(for: .milliseconds(150))+ let document = try XCTUnwrap(view.document), page = try XCTUnwrap(view.currentPage)+ XCTAssertEqual(document.index(for: page), 1)+ XCTAssertEqual(try Data(contentsOf: source.url), bytes)+ }+ private func descendants(_ view: UIView) -> [UIView] { [view] + view.subviews.flatMap(descendants) }+}++@MainActor private func viewerPDFSource(_ root: URL) throws -> SourceImage {+ let bytes = syntheticTextReceiptPDF(["SYNTHETIC CAFE\n2 x Noodles $12.50", "CONTINUED\n1 x Rice $5.00"])+ let file = root.appendingPathComponent("viewer.pdf"); try bytes.write(to: file)+ return .init(id: UUID(), url: file, mediaType: "application/pdf", byteLength: Int64(bytes.count),+ sha256: SHA256.hash(data: bytes).map { String(format: "%02x", $0) }.joined())+}++@MainActor @Observable private final class PDFViewerSelection { var page = 0 }+private struct PDFViewerSelectionView: View {+ let bytes: Data+ let selection: PDFViewerSelection+ var body: some View { ReceiptPDFView(bytes: bytes, pageIndex: selection.page) { _ in } }+}
diff --git a/Foodnotes/FoodnotesTests/Persistence/MealDeletionTests.swift b/Foodnotes/FoodnotesTests/Persistence/MealDeletionTests.swiftnew file mode 100644index 0000000..d19cf32--- /dev/null+++ b/Foodnotes/FoodnotesTests/Persistence/MealDeletionTests.swift@@ -0,0 +1,147 @@+import Foundation+import FoodnotesDomain+import Testing+@testable import Foodnotes++@MainActor @Suite struct MealDeletionTests {+ @Test func cancellationChangedMealSessionAndMovingGuardsDoNotDelete() async throws {+ let fixture = try await SyncFixture.make()+ let app = AppDependencies(); try await app.attach(fixture.repository, session: fixture.session)+ let original = try #require(app.snapshot?.documents.first)+ let before = try await fixture.repository.snapshot(scope: .both)+ let cancelled = try await app.deleteMeal(original, session: fixture.session, confirmed: false)+ #expect(!cancelled)+ #expect(try await fixture.repository.snapshot(scope: .both) == before)+ await #expect(throws: StorageError.staleSession) {+ try await app.deleteMeal(original, session: storageSession(99), confirmed: true)+ }+ app.nonWritableMeals.insert(MealWriteKey(original.meal))+ await #expect(throws: StorageError.revisionConflict) {+ try await app.deleteMeal(original, session: fixture.session, confirmed: true)+ }+ app.nonWritableMeals = []+ var changed = original; changed.meal.title.value = "Changed while confirming"+ await #expect(throws: StorageError.revisionConflict) {+ try await app.deleteMeal(changed, session: fixture.session, confirmed: true)+ }+ #expect(try await fixture.repository.snapshot(scope: .both) == before)+ await fixture.publisher.stop(); try await app.close()+ }++ @Test func deletingOneVisitKeepsOtherVisitSharedPlaceAndOriginalBytesAcrossReopen() async throws {+ let root = try temporaryStorageDirectory(), session = storageSession()+ defer { try? FileManager.default.removeItem(at: root) }+ let configuration = storageConfiguration(root.appendingPathComponent("store"))+ let store = try await CoreDataMealRepository.open(configuration: configuration, session: session)+ var first = storageDraft(session)+ first.place = .init(value: "Synthetic shared place", provenance: .manual, editVersion: 1)+ let source = try sourceImage(root); first.sources = [source]+ _ = try await store.apply(.saveDraft(first), operationID: UUID(), session: session)+ let one = try await store.snapshot(scope: .both)+ let removed = try #require(one.documents.first), placeID = try #require(removed.meal.placeID.value)+ var second = storageDraft(session); second.id = UUID(); second.occurrences[0].id = UUID()+ second.place = first.place; second.confirmedPlaceID = placeID+ var otherSource = source; otherSource.id = UUID(); second.sources = [otherSource]+ _ = try await store.apply(.saveDraft(second), operationID: UUID(), session: session)+ let before = try await store.snapshot(scope: .both)+ let other = try #require(before.documents.first { $0.meal.id == second.id })+ let url = try await store.assetURL(id: otherSource.id, session: session), bytes = try Data(contentsOf: url)+ let removedURL = try await store.assetURL(id: source.id, session: session)+ #expect(try Data(contentsOf: removedURL) == bytes)+ let app = AppDependencies(); try await app.attach(store, session: session)+ app.path = [.meal(removed.meal.id, removed.meal.libraryID)]+ try await app.deleteMeal(removed, session: session, confirmed: true)+ #expect(app.path.isEmpty)+ #expect(app.snapshot?.documents == [other])+ #expect(app.snapshot?.places == before.places && app.snapshot?.dishes == before.dishes)+ try await store.cleanupAssets(session: session)+ #expect(try Data(contentsOf: url) == bytes)+ #expect(try Data(contentsOf: removedURL) == bytes)+ let pending = try await store.outbox(session: session)+ #expect(pending.contains { $0.document.meal.id == removed.meal.id && !$0.document.meal.isPresent.value })+ try await app.close()+ let reopened = try await CoreDataMealRepository.open(configuration: configuration, session: session)+ #expect(try await reopened.snapshot(scope: .both).documents == [other])+ #expect(try await reopened.snapshot(scope: .both).places == before.places)+ let reopenedURL = try await reopened.assetURL(id: otherSource.id, session: session)+ #expect(try Data(contentsOf: reopenedURL) == bytes)+ try await reopened.close()+ }++ @Test func failedDeletionKeepsMealAndNavigation() async throws {+ let fault = OneShotStorageFault(), fixture = try await SyncFixture.make(fault: fault)+ let app = AppDependencies(); try await app.attach(fixture.repository, session: fixture.session)+ let original = try #require(app.snapshot?.documents.first)+ app.path = [.meal(original.meal.id, original.meal.libraryID)]+ let before = try await fixture.repository.snapshot(scope: .both)+ fault.arm(.beforeMutationSave)+ await #expect(throws: StorageError.injectedFailure) {+ try await app.deleteMeal(original, session: fixture.session, confirmed: true)+ }+ #expect(try await fixture.repository.snapshot(scope: .both) == before)+ #expect(!app.path.isEmpty)+ await fixture.publisher.stop(); try await app.close()+ }++ @Test func deletionPublishesAndLaterRemoteEditsCannotResurrectIt() async throws {+ let fixture = try await SyncFixture.make()+ #expect(try await fixture.publisher.publishNext())+ let app = AppDependencies(); try await app.attach(fixture.repository, session: fixture.session)+ let original = try #require(app.snapshot?.documents.first)+ try await app.deleteMeal(original, session: fixture.session, confirmed: true)+ try await drain(fixture)+ #expect(try await fixture.repository.outbox(session: fixture.session).isEmpty)+ let batch = try #require(await fixture.transport.batches().last)+ let payload = try #require(batch.writes.first { $0.address == batch.guardControl.address }?.payload)+ let removed = try StorageCoding.decode(MealDocument.self, payload)+ #expect(!removed.meal.isPresent.value && removed.meal.id == original.meal.id)+ let peerRoot = try temporaryStorageDirectory()+ defer { try? FileManager.default.removeItem(at: peerRoot) }+ let peer = try await CoreDataMealRepository.open(configuration: storageConfiguration(peerRoot), session: fixture.session)+ try await peer.configureCloud(syncBinding(fixture.session), session: fixture.session, confirmLocalBinding: true)+ for (index, value) in [original, removed, laterEdit(original)].enumerated() {+ let control = try syncControl(value, operationID: value.version)+ try await peer.applyFetched(.init(database: .private, controls: [control], deletions: [], revokedZones: [],+ images: [], checkpoint: Data([UInt8(index)])), session: fixture.session)+ #expect(try await peer.snapshot(scope: .both).documents.isEmpty == (index > 0))+ }+ try await peer.close(); await fixture.publisher.stop(); try await app.close()+ }++ @Test func sharedDeletionUsesSharedPublicationWithoutRemovingPersonalMeal() async throws {+ let fixture = try await SyncFixture.make()+ try await installHousehold(fixture, participant: true)+ var draft = storageDraft(fixture.session); draft.id = UUID(); draft.occurrences[0].id = UUID()+ draft.intendedLibrary = .shared(householdID: storageUUID(950))+ _ = try await fixture.repository.apply(.saveDraft(draft), operationID: UUID(), session: fixture.session)+ let app = AppDependencies(); try await app.attach(fixture.repository, session: fixture.session)+ app.scope = .both; await app.refresh()+ let shared = try #require(app.snapshot?.documents.first { $0.meal.id == draft.id })+ let personal = app.snapshot?.documents.filter { $0.meal.id != draft.id }+ try await app.deleteMeal(shared, session: fixture.session, confirmed: true)+ #expect(app.snapshot?.documents == personal)+ try await drain(fixture)+ let batches = await fixture.transport.batches()+ let deletion = try #require(batches.last { $0.guardControl.mealID == draft.id })+ let data = try #require(deletion.writes.first { $0.address == deletion.guardControl.address }?.payload)+ #expect(deletion.guardControl.address.database == .shared)+ #expect(try StorageCoding.decode(MealDocument.self, data).meal.isPresent.value == false)+ await fixture.publisher.stop(); try await app.close()+ }++ private func drain(_ fixture: SyncFixture) async throws {+ // Profiles may be queued by attach; publish them before the dependent meal as in production.+ for _ in 0..<12 {+ if try await fixture.repository.outbox(session: fixture.session).isEmpty { return }+ #expect(try await fixture.publisher.publishNext())+ }+ #expect(try await fixture.repository.outbox(session: fixture.session).isEmpty)+ }++ private func laterEdit(_ original: MealDocument) -> MealDocument {+ var result = original; result.version = UUID()+ result.meal.title = .init(value: "Later remote edit", stamp: .init(milliseconds: Int64.max - 1,+ logicalCounter: 0, replicaID: UUID()))+ return result+ }+}
diff --git a/Foodnotes/FoodnotesTests/Persistence/PDFOriginalStorageTests.swift b/Foodnotes/FoodnotesTests/Persistence/PDFOriginalStorageTests.swiftnew file mode 100644index 0000000..f024af9--- /dev/null+++ b/Foodnotes/FoodnotesTests/Persistence/PDFOriginalStorageTests.swift@@ -0,0 +1,35 @@+import CryptoKit+import Foundation+import FoodnotesDomain+import Testing+@testable import Foodnotes++@Suite struct PDFOriginalStorageTests {+ @Test func pdfOriginalSurvivesPublicationReopenAndCleanup() async throws {+ for seed in 1...4 {+ let directory = try temporaryStorageDirectory()+ defer { try? FileManager.default.removeItem(at: directory) }+ let session = storageSession()+ let configuration = storageConfiguration(directory.appendingPathComponent("store"))+ let repository = try await CoreDataMealRepository.open(configuration: configuration, session: session)+ let bytes = Data("%PDF-1.7 synthetic storage contract \(seed)".utf8)+ let url = directory.appendingPathComponent("synthetic.pdf")+ try bytes.write(to: url)+ var draft = storageDraft()+ draft.sources = [SourceImage(id: storageUUID(700), url: url, mediaType: "application/pdf",+ byteLength: Int64(bytes.count), sha256: SHA256.hash(data: bytes).map { String(format: "%02x", $0) }.joined())]+ try await repository.save(draft, session: session)+ try await repository.cleanupAssets(session: session)+ try await repository.close()+ let reopened = try await CoreDataMealRepository.open(configuration: configuration, session: session)+ let restored = try #require(try await reopened.drafts(session: session).first)+ #expect(restored.allImageSources.isEmpty)+ let original = try #require(restored.allOriginalSources.first)+ #expect(original.url != url)+ #expect(try Data(contentsOf: original.url) == bytes)+ try await reopened.cleanupAssets(session: session)+ #expect(try Data(contentsOf: original.url) == bytes)+ try await reopened.close()+ }+ }+}
diff --git a/Foodnotes/FoodnotesTests/Persistence/PDFProvenanceStorageTests.swift b/Foodnotes/FoodnotesTests/Persistence/PDFProvenanceStorageTests.swiftnew file mode 100644index 0000000..9728499--- /dev/null+++ b/Foodnotes/FoodnotesTests/Persistence/PDFProvenanceStorageTests.swift@@ -0,0 +1,278 @@+import CloudKit+import CryptoKit+import FoodnotesDomain+import FoodnotesArchives+import ZIPFoundation+import Foundation+import Testing+@testable import Foodnotes++@MainActor @Suite struct PDFProvenanceStorageTests {+ @Test func saveReopenRetainsReviewedValuesAndSourceFieldPageLinks() async throws {+ let root = try temporaryStorageDirectory()+ defer { try? FileManager.default.removeItem(at: root) }+ let session = storageSession(), config = storageConfiguration(root.appendingPathComponent("store"))+ let repository = try await CoreDataMealRepository.open(configuration: config, session: session)+ let draft = try prepared(root)+ try await repository.save(draft, session: session)+ let durable = try #require(try await repository.drafts(session: session).first)+ _ = try await repository.apply(.saveDraft(durable), operationID: UUID(), session: session)+ #expect(try await repository.drafts(session: session).isEmpty)+ try await repository.close()+ let reopened = try await CoreDataMealRepository.open(configuration: config, session: session)+ let saved = try #require(try await reopened.snapshot(scope: .both).documents.first)+ let manifest = try #require(saved.assets.first)+ let provenance = try #require(manifest.receiptProvenance)+ #expect(provenance.pages == draft.receiptPages)+ #expect(provenance.rows == draft.receiptRows)+ #expect(provenance.fields?.first?.fieldPath == "occurrences.\(draft.occurrences[0].id).name")+ #expect(provenance.fields?.first?.pageIndices == [0])+ #expect(saved.occurrences[0].quantity.value == Decimal(string: "2.5"))+ #expect(saved.occurrences[0].price.value == Money(cents: 1_250, currencyCode: "AUD"))+ #expect(saved.mealPhotoAssets.isEmpty && manifest.assetID == draft.sources[0].id)+ let pending = try #require(try await reopened.outbox(session: session).first)+ #expect(pending.document.assets.first?.receiptProvenance == provenance)+ let original = try await reopened.assetURL(id: manifest.assetID, session: session)+ #expect(try Data(contentsOf: original) == Data(contentsOf: draft.sources[0].url))+ try FileManager.default.removeItem(at: original)+ #expect(try await reopened.snapshot(scope: .both).documents.count == 1)+ await #expect(throws: Error.self) { try await reopened.assetURL(id: manifest.assetID, session: session) }+ try await reopened.close()+ }+ @Test func dismissedOccurrenceAndPageLinksSurviveDraftRemoval() async throws {+ let root = try temporaryStorageDirectory()+ defer { try? FileManager.default.removeItem(at: root) }+ let session = storageSession()+ let repository = try await CoreDataMealRepository.open(configuration: storageConfiguration(root), session: session)+ var draft = try prepared(root)+ var removed = draft.occurrences[0]; removed.id = UUID()+ draft.receiptDismissedOccurrences = [removed]+ let old = ReceiptRowAnchor(id: UUID(), sourceID: draft.sources[0].id, pageIndex: 0,+ bounds: .init(x: 0.1, y: 0.3, width: 0.8, height: 0.02), occurrenceID: removed.id, dismissed: true)+ removed.name.provenance = .extracted(sourceID: draft.sources[0].id, evidenceIDs: [old.id], parserVersion: "synthetic")+ draft.receiptDismissedOccurrences = [removed]+ draft.receiptEvidence?.append(.init(id: old.id, sourceID: old.sourceID, pageIndex: 0, bounds: old.bounds))+ draft.receiptRows?.append(old)+ try await repository.save(draft, session: session)+ let durable = try #require(try await repository.drafts(session: session).first)+ _ = try await repository.apply(.saveDraft(durable), operationID: UUID(), session: session)+ let saved = try #require(try await repository.snapshot(scope: .both).documents.first)+ #expect(saved.occurrences.first { $0.id == removed.id }?.isPresent.value == false)+ #expect(saved.assets.first?.receiptProvenance?.rows.contains(old) == true)+ try await repository.close()+ }+ @Test func oversizedMetadataRejectsSaveWhileDraftAndOriginalRemain() async throws {+ let root = try temporaryStorageDirectory()+ defer { try? FileManager.default.removeItem(at: root) }+ let session = storageSession()+ let repository = try await CoreDataMealRepository.open(configuration: storageConfiguration(root), session: session)+ var draft = try prepared(root)+ draft.receiptPages?[0].status = .incomplete(String(repeating: "x", count: 1_000_001))+ try await repository.save(draft, session: session)+ let durable = try #require(try await repository.drafts(session: session).first)+ await #expect(throws: Error.self) {+ try await repository.apply(.saveDraft(durable), operationID: UUID(), session: session)+ }+ #expect(try await repository.snapshot(scope: .both).documents.isEmpty)+ #expect(try await repository.drafts(session: session).count == 1)+ #expect(try Data(contentsOf: durable.sources[0].url).count == durable.sources[0].byteLength)+ try await repository.close()+ }+ @Test func typedCloudOriginalPreservesPDFMetadataAndExactBytes() throws {+ let root = try temporaryStorageDirectory()+ defer { try? FileManager.default.removeItem(at: root) }+ let draft = try prepared(root), source = draft.sources[0]+ let provenance = ReceiptProvenance(pages: draft.receiptPages!, rows: draft.receiptRows!)+ let manifest = AssetManifestEntry(assetID: source.id, address: nil, role: .source, mediaType: source.mediaType,+ byteLength: source.byteLength, sha256: source.sha256, receiptProvenance: provenance)+ let record = CKRecord(recordType: "OriginalImage", recordID: .init(recordName: "synthetic-pdf"))+ record["manifest"] = try StorageCoding.encode(manifest) as CKRecordValue+ record["original"] = CKAsset(fileURL: source.url)+ let fetched = try AppleCloudCodec.image(record, partitionID: storageSession().partitionID, database: .private)+ #expect(fetched.manifest.receiptProvenance == provenance)+ #expect(fetched.source.mediaType == "application/pdf")+ #expect(try Data(contentsOf: fetched.source.url) == Data(contentsOf: source.url))+ }+ @Test func acceptedFieldOriginSurvivesManualCorrectionAndDuplicateMetadataRejects() throws {+ let root = try temporaryStorageDirectory()+ defer { try? FileManager.default.removeItem(at: root) }+ var draft = try prepared(root)+ let source = draft.sources[0], path = "occurrences.\(draft.occurrences[0].id).name"+ draft.rememberReceiptProposal(.init(proposal: .init(generation: draft.generation, fieldPath: path,+ value: "Noodles", evidenceIDs: [storageUUID(800)], expectedEditVersion: 0, parserVersion: "synthetic"), sourceID: source.id))+ draft.occurrences[0].name = .init(value: "Corrected Noodles", provenance: .manual, editVersion: 4)+ #expect(try draft.savedReceiptProvenance()[source.id]?.fields?.first?.fieldPath == path)+ let field = try #require(draft.receiptAcceptedFields?.first)+ draft.receiptAcceptedFields = [field, field]+ #expect(throws: DomainError.self) { try draft.savedReceiptProvenance() }+ }+ private func prepared(_ root: URL) throws -> Draft {+ var draft = storageDraft()+ let bytes = syntheticTextReceiptPDF(["SYNTHETIC CAFE\n2 x Noodles $12.50"])+ let url = root.appendingPathComponent("\(UUID()).pdf"); try bytes.write(to: url)+ let source = SourceImage(id: storageUUID(700), url: url, mediaType: "application/pdf", byteLength: Int64(bytes.count),+ sha256: SHA256.hash(data: bytes).map { String(format: "%02x", $0) }.joined())+ draft.sources = [source]+ draft.receiptPages = [.init(sourceID: source.id, pageIndex: 0, status: .processed)]+ let anchor = ReceiptRowAnchor(id: storageUUID(800), sourceID: source.id, pageIndex: 0,+ bounds: .init(x: 0.1, y: 0.5, width: 0.8, height: 0.02), occurrenceID: draft.occurrences[0].id)+ draft.receiptRows = [anchor]+ draft.receiptEvidence = [.init(id: anchor.id, sourceID: source.id, pageIndex: 0, bounds: anchor.bounds)]+ draft.occurrences[0].name = .init(value: "Noodles", provenance: .extracted(sourceID: source.id,+ evidenceIDs: [anchor.id], parserVersion: "synthetic-pdf-v1"), editVersion: 0)+ draft.occurrences[0].quantity = .init(value: "2.5", provenance: .manual, editVersion: 3)+ draft.occurrences[0].price = .init(value: "12.50", provenance: .manual, editVersion: 2)+ return draft+ }+}++extension PDFProvenanceStorageTests {+ @Test func missingOrRejectedModelItemsPermitManualCompletionSaveAndReopen() async throws {+ for mode in 0..<4 {+ let root = try temporaryStorageDirectory()+ defer { try? FileManager.default.removeItem(at: root) }+ let session = storageSession(), configuration = storageConfiguration(root.appendingPathComponent("store"))+ let repository = try await CoreDataMealRepository.open(configuration: configuration, session: session)+ var initial = try prepared(root)+ let bytes = syntheticTextReceiptPDF(["SYNTHETIC CAFE\n2 x Noodles $12.50\n1 x Rice $5.00"])+ try bytes.write(to: initial.sources[0].url)+ initial.sources[0].byteLength = Int64(bytes.count)+ initial.sources[0].sha256 = SHA256.hash(data: bytes).map { String(format: "%02x", $0) }.joined()+ initial.occurrences = []; initial.receiptRows = nil; initial.receiptEvidence = nil+ initial.extractionStatus = .pending+ initial.receiptPages?[0].status = .pending+ let lines = [pdfEvidence("2 x Noodles $12.50", y: 0.7), pdfEvidence("1 x Rice $5.00", y: 0.5)]+ let extractor = PDFCaptureExtractor(model: PDFManualFallbackModel(mode: mode), evidenceStore: MemoryCaptureEvidence(),+ loadPages: { _ in [.init(pageIndex: 0, evidence: lines, failure: nil)] })+ let review = CaptureReviewModel(draft: initial, session: session,+ events: { extractor.events($0, generation: $1) }, persist: { value, owner in+ try await repository.save(value, session: owner)+ })+ review.start()+ let deadline = ContinuousClock.now.advanced(by: .seconds(5))+ while review.reading, ContinuousClock.now < deadline { await Task.yield() }+ try #require(!review.reading)+ let manual = DraftField(value: "Manual completion", provenance: .manual, editVersion: 1)+ let blank = DraftField(value: nil, provenance: .manual, editVersion: 0)+ review.draft.occurrences.append(.init(id: UUID(), name: manual, quantity: blank, price: blank,+ note: blank, sortKey: "manual"))+ await review.flush()+ let durable = try #require(try await repository.drafts(session: session).first)+ _ = try await repository.apply(.saveDraft(durable), operationID: UUID(), session: session)+ try await repository.close()+ let reopened = try await CoreDataMealRepository.open(configuration: configuration, session: session)+ let saved = try #require(try await reopened.snapshot(scope: .both).documents.first)+ let provenance = try #require(saved.assets.first?.receiptProvenance)+ #expect(saved.occurrences.contains { $0.displayName.value == "Manual completion" })+ #expect(saved.occurrences.count == (mode == 2 ? 2 : 1))+ let actual = Set(saved.occurrences.map(\.id))+ #expect(provenance.rows.allSatisfy { actual.contains($0.occurrenceID) })+ let original = try await reopened.assetURL(id: initial.sources[0].id, session: session)+ #expect(try Data(contentsOf: original) == bytes)+ try await reopened.close()+ }+ }+}++nonisolated private struct PDFManualFallbackModel: CaptureProposalModel {+ let mode: Int+ func availability(localeIdentifier: String) async -> CaptureModelAvailability { .available }+ func candidates(in evidence: [SourceEvidence], localeIdentifier: String) async throws -> [CaptureCandidate] {+ if mode == 1 { throw CaptureReadError.invalidSource }+ guard mode >= 2, let row = evidence.first(where: { $0.text.contains("Noodles") }) else { return [] }+ return [.init(kind: .dish, copiedText: mode == 2 ? "Noodles" : "Invented Sushi", evidenceID: row.id)]+ }+}++extension PDFProvenanceStorageTests {+ @Test func readablePDFPackageLinksReceiptToMealWithoutEmbeddingOrChangingBytes() async throws {+ let root = try temporaryStorageDirectory()+ defer { try? FileManager.default.removeItem(at: root) }+ let fixture = try await archiveFixture(root)+ let records = ArchiveRecords(graph: fixture.graph)+ #expect(records.meals[0].assets[0].receiptProvenance != nil)+ let selection = ExportSelection(scope: .personal, session: fixture.session, firstDate: nil, lastDate: nil)+ let text = try MarkdownText.render(fixture.graph, selection: selection)+ let id = fixture.graph.documents[0].assets[0].assetID+ let path = "documents/\(id.uuidString.lowercased()).pdf"+ #expect(text.contains("[Original PDF receipt](\(path))"))+ #expect(!text.contains("![Original PDF receipt]"))+ let assets = try ArchiveGraphValidator.assets(in: records)+ let output = try MarkdownZIP.write(text: text, assets: assets, sources: [id: fixture.source],+ directory: root.appendingPathComponent("readable"), resources: .init())+ let zip = try Archive(url: output, accessMode: .read), entry = try #require(zip[path])+ var bytes = Data()+ _ = try zip.extract(entry) { bytes.append($0) }+ #expect(bytes == fixture.bytes)+ #expect(Set(zip.map { $0.path }) == Set(["Foodnotes.md", path]))+ try await fixture.repository.close()+ }+ @Test func PDFRestoreCollisionRehomesSourceAndOccurrenceLinksThenReplaysIdentically() async throws {+ let root = try temporaryStorageDirectory()+ defer { try? FileManager.default.removeItem(at: root) }+ let fixture = try await archiveFixture(root)+ let incoming = root.appendingPathComponent("incoming-pdf.zip")+ let id = fixture.graph.documents[0].assets[0].assetID+ _ = try ArchiveZIPCodec().write(ArchiveRecords(graph: fixture.graph), assets: [id: fixture.source],+ scope: .personal, to: incoming)+ let targetSession = storageSession(2)+ let repository = try await CoreDataMealRepository.open(configuration: storageConfiguration(root.appendingPathComponent("target")),+ session: targetSession)+ try await seedArchivePerson(repository, session: targetSession)+ var existing = try prepared(root)+ existing.id = storageUUID(9_999); existing.partitionID = targetSession.partitionID+ existing.intendedLibrary = .personal(accountID: targetSession.accountID); existing.dinerIDs = [targetSession.adultID]+ let image = root.appendingPathComponent("existing.png"), imageBytes = handoffPNG()+ try imageBytes.write(to: image)+ existing.sources = [.init(id: id, url: image, mediaType: "image/png", byteLength: Int64(imageBytes.count),+ sha256: ArchiveIO.digest(imageBytes))]+ existing.receiptPages = nil; existing.receiptRows = nil; existing.receiptEvidence = nil+ existing.receiptAcceptedFields = nil+ existing.occurrences[0].name.provenance = .manual+ try await repository.save(existing, session: targetSession)+ let durable = try #require(try await repository.drafts(session: targetSession).first)+ _ = try await repository.apply(.saveDraft(durable), operationID: UUID(), session: targetSession)+ let service = TransactionalArchiveService(repository: repository, directory: root.appendingPathComponent("restore-pdf"))+ _ = try await service.restore(service.preview(incoming), operationID: UUID())+ let snapshot = try await repository.snapshot(scope: .personal)+ let saved = try #require(snapshot.documents.first { $0.meal.id == fixture.graph.documents[0].meal.id })+ let manifest = try #require(saved.assets.first), provenance = try #require(manifest.receiptProvenance)+ #expect(manifest.assetID != id)+ #expect(saved.occurrences[0].id != fixture.graph.documents[0].occurrences[0].id)+ #expect(provenance.pages.allSatisfy { $0.sourceID == manifest.assetID })+ #expect(provenance.rows.allSatisfy { saved.occurrences.map(\.id).contains($0.occurrenceID) })+ let original = try await repository.assetURL(id: manifest.assetID, session: targetSession)+ #expect(try Data(contentsOf: original) == fixture.bytes)+ let repeated = try await service.preview(incoming)+ #expect(repeated.classifications.allSatisfy { $0.disposition == .identical })+ try await repository.close(); try await fixture.repository.close()+ }+ private struct ArchivePDFFixture {+ let repository: CoreDataMealRepository+ let graph: ArchiveGraph+ let source: URL+ let bytes: Data+ let session: AccountSession+ }+ private func archiveFixture(_ root: URL) async throws -> ArchivePDFFixture {+ let session = storageSession()+ let repository = try await CoreDataMealRepository.open(configuration: storageConfiguration(root.appendingPathComponent("source")),+ session: session)+ try await seedArchivePerson(repository, session: session)+ let draft = try prepared(root), bytes = try Data(contentsOf: draft.sources[0].url)+ try await repository.save(draft, session: session)+ let durable = try #require(try await repository.drafts(session: session).first)+ _ = try await repository.apply(.saveDraft(durable), operationID: UUID(), session: session)+ let snapshot = try await repository.snapshot(scope: .personal)+ let graph = ArchiveGraph(documents: snapshot.documents, people: snapshot.people, places: snapshot.places,+ orderingOptions: snapshot.orderingOptions, dishes: snapshot.dishes)+ let source = try await repository.assetURL(id: draft.sources[0].id, session: session)+ return .init(repository: repository, graph: graph, source: source, bytes: bytes, session: session)+ }+ private func seedArchivePerson(_ repository: CoreDataMealRepository, session: AccountSession) async throws {+ let stamp = FieldStamp(milliseconds: 1, logicalCounter: 0, replicaID: storageUUID(900))+ let person = Person(id: session.adultID, libraryID: .personal(accountID: session.accountID),+ displayName: .init(value: "Synthetic tester", stamp: stamp), linkedAdultID: session.adultID)+ _ = try await repository.enqueueScopedProfile(.person(person), operationID: UUID(), session: session)+ }+}
diff --git a/Foodnotes/FoodnotesTests/Settings/DebugInformationRenderTests.swift b/Foodnotes/FoodnotesTests/Settings/DebugInformationRenderTests.swiftnew file mode 100644index 0000000..a1e2303--- /dev/null+++ b/Foodnotes/FoodnotesTests/Settings/DebugInformationRenderTests.swift@@ -0,0 +1,59 @@+import FoodnotesDomain+import SwiftUI+import UIKit+import XCTest+@testable import Foodnotes++@MainActor final class DebugInformationRenderTests: XCTestCase {+ func testNormalDebugAndActionableFailureInLightDarkAndAccessibility() async throws {+ let suite = "DebugInformationRenders-" + UUID().uuidString+ let defaults = try XCTUnwrap(UserDefaults(suiteName: suite))+ defer { defaults.removePersistentDomain(forName: suite) }+ XCTAssertNil(defaults.object(forKey: DebugInformation.preferenceKey))+ let output = FileManager.default.temporaryDirectory.appendingPathComponent("DebugInformationRenders")+ try FileManager.default.createDirectory(at: output, withIntermediateDirectories: true)+ let id = UUID(), source = UUID()+ let field = ReceiptFieldProvenance(fieldPath: "occurrences.\(id).price", occurrenceID: id,+ pageIndices: [0], rowIDs: [UUID()],+ priceCalculation: .init(basis: .netRowPlusGST, quantity: 3, amountCents: 1_200, gstCents: 120))+ for (mode, scheme, size) in [("light", ColorScheme.light, DynamicTypeSize.large),+ ("dark", .dark, .large), ("ax3", .light, .accessibility3)] {+ for enabled in [false, true] {+ defaults.set(enabled, forKey: DebugInformation.preferenceKey)+ let page = ReceiptPageState(sourceID: source, pageIndex: 0, status: .processed)+ let failed = ReceiptPageState(sourceID: source, pageIndex: 1, status: .incomplete("Automatic limit reached"))+ XCTAssertFalse(ReceiptPageStatusSummary.needsAttention([page]))+ XCTAssertTrue(ReceiptPageStatusSummary.needsAttention([page, failed]))+ let view = ScrollView {+ VStack(alignment: .leading, spacing: 20) {+ DebugInformationToggle()+ Text("Original receipt").font(.title2)+ Button("View original PDF") {}+ ReceiptSupportingPages(fields: [field], names: [id: "Synthetic noodles"], openPage: { _ in })+ ReceiptPageStatusSummary(pages: [page], openPage: { _ in })+ Text("Receipt requiring attention").font(.headline)+ ReceiptPageStatusSummary(pages: [failed], openPage: { _ in })+ }.padding()+ }.defaultAppStorage(defaults).environment(\.colorScheme, scheme).environment(\.dynamicTypeSize, size)+ try await render(view, scheme: scheme, name: mode + (enabled ? "-debug" : "-normal"), output: output)+ XCTAssertEqual(try XCTUnwrap(UserDefaults(suiteName: suite)).bool(forKey: DebugInformation.preferenceKey), enabled)+ }+ }+ print("DEBUG_INFORMATION_RENDER_DIRECTORY=\(output.path)")+ }+ private func render(_ view: some View, scheme: ColorScheme, name: String, output: URL) async throws {+ let host = UIHostingController(rootView: view)+ host.overrideUserInterfaceStyle = scheme == .dark ? .dark : .light+ let scene = try XCTUnwrap(UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first)+ let window = UIWindow(windowScene: scene); window.frame = CGRect(x: 0, y: 0, width: 390, height: 844)+ window.rootViewController = host; window.makeKeyAndVisible()+ defer { window.isHidden = true }+ try await Task.sleep(for: .milliseconds(150)); host.view.layoutIfNeeded()+ let image = UIGraphicsImageRenderer(bounds: host.view.bounds).image { _ in+ host.view.drawHierarchy(in: host.view.bounds, afterScreenUpdates: true)+ }+ try XCTUnwrap(image.pngData()).write(to: output.appendingPathComponent(name + ".png"))+ let attachment = XCTAttachment(image: image); attachment.name = "debug-information-" + name+ attachment.lifetime = .keepAlways; add(attachment)+ }+}
diff --git a/Foodnotes/FoodnotesTests/Sync/SyncFixtures.swift b/Foodnotes/FoodnotesTests/Sync/SyncFixtures.swiftindex 08c7db4..662d750 100644--- a/Foodnotes/FoodnotesTests/Sync/SyncFixtures.swift+++ b/Foodnotes/FoodnotesTests/Sync/SyncFixtures.swift@@ -20,7 +20,7 @@ func syncControl(_ document: MealDocument, operationID: UUID = storageUUID(600)) return CloudControlSnapshot(control: control, operationID: operationID, changeTag: "tag", systemFields: Data(), documentData: data) } -actor FakeCloudTransport: CloudTransport, CloudRecordReader {+actor FakeCloudTransport { private var server: [RecordAddress: CloudControlSnapshot] = [:] private var commits: [ConditionalZoneBatch] = [] private var failure: SyncError?@@ -244,3 +244,6 @@ extension FakeCloudTransport: TransferAssetTransport { func closeFiles() { try? FileManager.default.removeItem(at: cloudFiles) } func original(at address: RecordAddress) -> SourceImage? { originals[address] } }++// Keep protocol conformances separate to avoid the Swift actor initializer isolation diagnostic.+extension FakeCloudTransport: CloudTransport, CloudRecordReader {}
diff --git a/Foodnotes/FoodnotesUITests/CaptureInputJourneyTests.swift b/Foodnotes/FoodnotesUITests/CaptureInputJourneyTests.swiftindex 394887b..8fcfefd 100644--- a/Foodnotes/FoodnotesUITests/CaptureInputJourneyTests.swift+++ b/Foodnotes/FoodnotesUITests/CaptureInputJourneyTests.swift@@ -12,6 +12,7 @@ final class CaptureInputJourneyTests: XCTestCase { XCTAssertTrue(app.buttons["Type it in"].waitForExistence(timeout: 5)) XCTAssertTrue(app.buttons["Take a photo"].exists, "Camera must lead to the same editable review") XCTAssertTrue(app.buttons["Choose from Photos"].exists, "One retained photo must start an editable draft")+ XCTAssertTrue(app.buttons["Import PDF receipt"].exists, "Files PDF entry must coexist with image and manual entry") } }
diff --git a/Foodnotes/FoodnotesUITests/ManualJourneyTests.swift b/Foodnotes/FoodnotesUITests/ManualJourneyTests.swiftindex 3b81609..05c3506 100644--- a/Foodnotes/FoodnotesUITests/ManualJourneyTests.swift+++ b/Foodnotes/FoodnotesUITests/ManualJourneyTests.swift@@ -2,7 +2,7 @@ import XCTest final class ManualJourneyTests: XCTestCase { @MainActor- func testManualSaveSurvivesRelaunchAndFinishesWithoutRatings() {+ func testManualSaveRestoresMealAndCurrentDateWithoutRatings() { let app = XCUIApplication() app.launchArguments = ["--ui-testing", "--test-store", UUID().uuidString] app.launch()@@ -12,7 +12,11 @@ final class ManualJourneyTests: XCTestCase { add.tap() app.buttons["Type it in"].tap() XCTAssertTrue(app.staticTexts["capture.date.provenance"].waitForExistence(timeout: 5))- XCTAssertTrue(app.staticTexts["capture.date.provenance"].label.contains("default"))+ let dateText = DateFormatter()+ dateText.locale = Locale(identifier: "en_US_POSIX"); dateText.dateFormat = "EEEE d MMMM"+ let shownDate = app.staticTexts["capture.date.provenance"].label+ print("MANUAL_CURRENT_DATE_LABEL=\(shownDate) EXPECTED=\(dateText.string(from: Date()))")+ XCTAssertEqual(shownDate, dateText.string(from: Date())) app.buttons["capture.save"].tap() XCTAssertTrue(app.staticTexts["capture.error"].waitForExistence(timeout: 5)) let place = app.descendants(matching: .any).matching(identifier: "capture.place").firstMatch@@ -20,7 +24,7 @@ final class ManualJourneyTests: XCTestCase { place.typeText("Journey noodle house") app.buttons["capture.save"].tap() XCTAssertTrue(app.buttons["meal.finish"].waitForExistence(timeout: 8))- XCTAssertTrue(app.staticTexts["Personal"].exists)+ XCTAssertEqual(app.buttons["meal.library.actions"].label, "Personal") app.terminate() app.launch() XCTAssertTrue(app.buttons["journal.add"].waitForExistence(timeout: 8))@@ -68,9 +72,10 @@ extension ManualJourneyTests { XCTAssertTrue(name.waitForExistence(timeout: 5)) name.tap() name.typeText(" revised")- app.swipeUp()+ app.buttons["Done"].tap() let method = app.descendants(matching: .any).matching(identifier: "edit.ordering").firstMatch- XCTAssertTrue(method.waitForExistence(timeout: 5))+ for _ in 0..<8 where !method.isHittable { app.swipeUp() }+ XCTAssertTrue(method.isHittable) method.tap() method.typeText("Phone order changed") app.buttons["Save"].tap()
diff --git a/Foodnotes/FoodnotesUITests/MealDeletionJourneyTests.swift b/Foodnotes/FoodnotesUITests/MealDeletionJourneyTests.swiftnew file mode 100644index 0000000..17cd636--- /dev/null+++ b/Foodnotes/FoodnotesUITests/MealDeletionJourneyTests.swift@@ -0,0 +1,34 @@+import XCTest++final class MealDeletionJourneyTests: XCTestCase {+ @MainActor func testCancelThenDeleteReturnsToJournalAndStaysDeletedAfterRelaunch() {+ let app = XCUIApplication()+ app.launchArguments = ["--ui-testing", "--test-store", UUID().uuidString]+ app.launch()+ XCTAssertTrue(app.buttons["journal.add"].waitForExistence(timeout: 10))+ app.buttons["journal.add"].tap(); app.buttons["Type it in"].tap()+ let place = app.descendants(matching: .any).matching(identifier: "capture.place").firstMatch+ XCTAssertTrue(place.waitForExistence(timeout: 5)); place.tap(); place.typeText("Synthetic delete visit")+ app.buttons["Done"].tap(); app.buttons["capture.save"].tap()+ XCTAssertTrue(app.buttons["meal.finish"].waitForExistence(timeout: 8))+ let remove = app.buttons["meal.delete"]+ for _ in 0..<6 where !remove.isHittable { app.swipeUp() }+ guard remove.exists else { XCTFail("Saved meals must offer confirmed deletion"); return }+ remove.tap()+ let confirm = app.alerts.buttons["Delete meal"].firstMatch+ XCTAssertTrue(confirm.waitForExistence(timeout: 5))+ record(app, "meal-delete-confirmation")+ app.alerts.buttons["Cancel"].tap()+ XCTAssertTrue(app.buttons["meal.finish"].exists, "Cancel keeps the meal")+ remove.tap(); confirm.tap()+ XCTAssertTrue(app.buttons["journal.add"].waitForExistence(timeout: 8), "Deleted detail returns to the journal")+ XCTAssertFalse(app.buttons.matching(NSPredicate(format: "label CONTAINS %@", "Synthetic delete visit")).firstMatch.exists)+ app.terminate(); app.launch()+ XCTAssertTrue(app.buttons["journal.add"].waitForExistence(timeout: 8))+ XCTAssertFalse(app.buttons.matching(NSPredicate(format: "label CONTAINS %@", "Synthetic delete visit")).firstMatch.exists)+ }+ @MainActor private func record(_ app: XCUIApplication, _ name: String) {+ let attachment = XCTAttachment(screenshot: app.screenshot()); attachment.name = name+ attachment.lifetime = .keepAlways; add(attachment)+ }+}
diff --git a/Foodnotes/FoodnotesUITests/PDFReceiptJourneyTests.swift b/Foodnotes/FoodnotesUITests/PDFReceiptJourneyTests.swiftnew file mode 100644index 0000000..cf11245--- /dev/null+++ b/Foodnotes/FoodnotesUITests/PDFReceiptJourneyTests.swift@@ -0,0 +1,57 @@+import XCTest++final class PDFReceiptJourneyTests: XCTestCase {+ @MainActor func testNativeFilesPickerCoexistsWithImageAndManualEntry() {+ let app = XCUIApplication()+ app.launchArguments = ["--ui-testing", "--test-store", UUID().uuidString]+ app.launch()+ XCTAssertTrue(app.buttons["journal.add"].waitForExistence(timeout: 10))+ app.buttons["journal.add"].tap()+ let entry = app.buttons["Import PDF receipt"]+ XCTAssertTrue(entry.waitForExistence(timeout: 5)); entry.tap()+ XCTAssertTrue(app.buttons["Browse"].waitForExistence(timeout: 10) || app.navigationBars["Recents"].exists)+ if app.buttons["Cancel"].exists { app.buttons["Cancel"].tap() }+ XCTAssertTrue(app.buttons["journal.add"].waitForExistence(timeout: 5))+ }+ @MainActor func testPendingShareNoticeReviewCorrectionSaveReopenAndOriginalPages() {+ let app = XCUIApplication(), id = UUID().uuidString+ app.launchArguments = ["--ui-testing", "--test-store", id, "--pdf-receipt-fixture"]+ app.launch()+ let acknowledgement = app.buttons["receipt.compatibility.accept"]+ XCTAssertTrue(acknowledgement.waitForExistence(timeout: 12))+ record(app, "pdf-compatibility")+ app.terminate(); app.launch()+ XCTAssertTrue(acknowledgement.waitForExistence(timeout: 12), "Pending PDF survives an app-closed interval")+ acknowledgement.tap()+ let save = app.buttons["capture.save"]+ XCTAssertTrue(save.waitForExistence(timeout: 12))+ let title = app.descendants(matching: .any).matching(identifier: "capture.title").firstMatch+ title.tap(); title.typeText("Corrected PDF dinner"); app.buttons["Done"].tap()+ let source = app.buttons["capture.source.primary"]+ source.tap()+ XCTAssertTrue(app.staticTexts["receipt.pdf.pageLabel"].waitForExistence(timeout: 8))+ XCTAssertEqual(app.staticTexts["receipt.pdf.pageLabel"].label, "Page 1 of 2")+ app.buttons["receipt.pdf.next"].tap()+ XCTAssertEqual(app.staticTexts["receipt.pdf.pageLabel"].label, "Page 2 of 2")+ record(app, "pdf-draft-page2"); app.buttons["Done"].tap()+ for _ in 0..<7 where !app.buttons["capture.addDish"].isHittable { app.swipeUp() }+ app.buttons["capture.addDish"].tap()+ let dish = app.descendants(matching: .any).matching(identifier: "capture.dish.0").firstMatch+ XCTAssertTrue(dish.waitForExistence(timeout: 5)); dish.tap(); dish.typeText("Manual PDF noodles")+ app.buttons["Done"].tap()+ save.tap()+ XCTAssertTrue(app.buttons["meal.finish"].waitForExistence(timeout: 10))+ for _ in 0..<8 where !app.buttons["meal.sourceOriginal"].isHittable { app.swipeUp() }+ app.buttons["meal.sourceOriginal"].tap()+ XCTAssertTrue(app.staticTexts["receipt.pdf.pageLabel"].waitForExistence(timeout: 8))+ app.buttons["receipt.pdf.next"].tap()+ XCTAssertEqual(app.staticTexts["receipt.pdf.pageLabel"].label, "Page 2 of 2")+ record(app, "pdf-saved-page2"); app.buttons["Done"].tap()+ app.terminate(); app.launch()+ XCTAssertTrue(app.staticTexts["Corrected PDF dinner"].waitForExistence(timeout: 10))+ }+ @MainActor private func record(_ app: XCUIApplication, _ name: String) {+ let attachment = XCTAttachment(screenshot: app.screenshot()); attachment.name = name+ attachment.lifetime = .keepAlways; add(attachment)+ }+}
diff --git a/Foodnotes/FoodnotesUITests/Settings/DebugInformationJourneyTests.swift b/Foodnotes/FoodnotesUITests/Settings/DebugInformationJourneyTests.swiftnew file mode 100644index 0000000..43cb559--- /dev/null+++ b/Foodnotes/FoodnotesUITests/Settings/DebugInformationJourneyTests.swift@@ -0,0 +1,66 @@+import XCTest++final class DebugInformationJourneyTests: XCTestCase {+ @MainActor func testDebugPreferencePersistsAndControlsReviewAndSavedReceipt() {+ let app = XCUIApplication(), id = UUID().uuidString+ app.launchArguments = ["--ui-testing", "--test-store", id]+ app.launch()+ let toggle = settings(app)+ guard toggle.waitForExistence(timeout: 5) else { XCTFail("Settings needs the Debug information toggle"); return }+ XCTAssertEqual(toggle.value as? String, "0")+ toggle.tap()+ app.terminate(); app.launch()+ let restored = settings(app)+ XCTAssertEqual(restored.value as? String, "1", "Debug preference must survive relaunch")+ restored.tap(); app.buttons["Home"].tap()+ app.terminate()+ app.launchArguments += ["--pdf-receipt-fixture"]+ app.launch()+ let acknowledgement = app.buttons["receipt.compatibility.accept"]+ if acknowledgement.waitForExistence(timeout: 10) { acknowledgement.tap() }+ guard app.buttons["capture.save"].waitForExistence(timeout: 12) else { XCTFail("PDF review did not open"); return }+ let title = app.descendants(matching: .any).matching(identifier: "capture.title").firstMatch+ title.tap(); title.typeText("Debug toggle meal"); app.buttons["Done"].tap()+ XCTAssertFalse(debugPages(app).exists)+ XCTAssertTrue(app.buttons["capture.source.primary"].exists)+ record(app, "review-normal")+ app.buttons["Cancel"].tap()+ let enabled = settings(app); enabled.tap(); app.buttons["Home"].tap()+ let draft = app.buttons["journal.draft.B0000000-0000-0000-0000-000000002488"]+ XCTAssertTrue(draft.waitForExistence(timeout: 8)); draft.tap()+ XCTAssertTrue(debugPages(app).waitForExistence(timeout: 8))+ record(app, "review-debug")+ app.buttons["capture.save"].tap()+ XCTAssertTrue(app.buttons["meal.finish"].waitForExistence(timeout: 10))+ XCTAssertTrue(debugPages(app).exists)+ record(app, "saved-debug")+ verifySavedNormal(app)+ }++ @MainActor private func verifySavedNormal(_ app: XCUIApplication) {+ for _ in 0..<8 where !app.buttons["Home"].isHittable { app.swipeDown() }+ app.buttons["Home"].tap()+ let toggle = settings(app); toggle.tap(); app.buttons["Home"].tap()+ app.terminate(); app.launch()+ let meal = app.buttons.containing(.staticText, identifier: "Debug toggle meal").firstMatch+ XCTAssertTrue(meal.waitForExistence(timeout: 10)); meal.tap()+ XCTAssertTrue(app.buttons["meal.finish"].waitForExistence(timeout: 10))+ XCTAssertFalse(debugPages(app).exists)+ XCTAssertFalse(app.descendants(matching: .any).matching(identifier: "receipt.debug.fields").firstMatch.exists)+ for _ in 0..<8 where !app.buttons["meal.sourceOriginal"].isHittable { app.swipeUp() }+ XCTAssertTrue(app.buttons["meal.sourceOriginal"].isHittable)+ record(app, "saved-normal")+ }+ @MainActor private func settings(_ app: XCUIApplication) -> XCUIElement {+ XCTAssertTrue(app.buttons["journal.scope"].waitForExistence(timeout: 10))+ app.buttons["journal.scope"].tap(); app.buttons["Settings"].tap()+ return app.switches["settings.debugInformation"]+ }+ @MainActor private func debugPages(_ app: XCUIApplication) -> XCUIElement {+ app.descendants(matching: .any).matching(identifier: "receipt.debug.pages").firstMatch+ }+ @MainActor private func record(_ app: XCUIApplication, _ name: String) {+ let attachment = XCTAttachment(screenshot: app.screenshot()); attachment.name = "debug-" + name+ attachment.lifetime = .keepAlways; add(attachment)+ }+}
diff --git a/Foodnotes/Packages/FoodnotesCore/Sources/CaptureHandoff/FileSourceHandoff.swift b/Foodnotes/Packages/FoodnotesCore/Sources/CaptureHandoff/FileSourceHandoff.swiftindex 18d4071..dd36b38 100644--- a/Foodnotes/Packages/FoodnotesCore/Sources/CaptureHandoff/FileSourceHandoff.swift+++ b/Foodnotes/Packages/FoodnotesCore/Sources/CaptureHandoff/FileSourceHandoff.swift@@ -107,10 +107,12 @@ public actor FileSourceHandoff: SourceHandoff { return envelope } private func validate(_ envelope: SourceEnvelope) throws {+ let validMedia = ["image/png", "image/jpeg", "image/heic", "image/heif"].contains(envelope.mediaType) &&+ envelope.schemaVersion == 1 || envelope.mediaType == "application/pdf" && envelope.schemaVersion == 2 guard envelope.capturedTimeZone == nil || TimeZone(identifier: envelope.capturedTimeZone!) != nil,- envelope.schemaVersion == 1, envelope.filename == "\(envelope.sourceID.uuidString).original",+ envelope.schemaVersion == 1 || envelope.schemaVersion == 2, envelope.filename == "\(envelope.sourceID.uuidString).original", envelope.byteLength > 0, envelope.byteLength <= 32 * 1_024 * 1_024,- ["image/png", "image/jpeg", "image/heic", "image/heif"].contains(envelope.mediaType),+ validMedia, envelope.sha256.count == 64, envelope.sha256.utf8.allSatisfy({ (48...57).contains($0) || (97...102).contains($0) }), envelope.capturedAt.timeIntervalSince1970.isFinite else { throw HandoffError.invalidEnvelope } }
diff --git a/Foodnotes/Packages/FoodnotesCore/Sources/CaptureHandoff/SourceEnvelope.swift b/Foodnotes/Packages/FoodnotesCore/Sources/CaptureHandoff/SourceEnvelope.swiftindex 25619cb..b9b8689 100644--- a/Foodnotes/Packages/FoodnotesCore/Sources/CaptureHandoff/SourceEnvelope.swift+++ b/Foodnotes/Packages/FoodnotesCore/Sources/CaptureHandoff/SourceEnvelope.swift@@ -1,6 +1,6 @@ import Foundation -public enum SourceCaptureOrigin: String, Sendable, Codable { case camera, photos, shareExtension }+public enum SourceCaptureOrigin: String, Sendable, Codable { case camera, photos, shareExtension, files } public enum SourceCaptureDestination: Sendable, Codable, Equatable { case personal(accountID: UUID)
diff --git a/Foodnotes/Packages/FoodnotesCore/Sources/FoodnotesArchives/ArchiveJSON.swift b/Foodnotes/Packages/FoodnotesCore/Sources/FoodnotesArchives/ArchiveJSON.swiftindex f88caa9..3c30a7c 100644--- a/Foodnotes/Packages/FoodnotesCore/Sources/FoodnotesArchives/ArchiveJSON.swift+++ b/Foodnotes/Packages/FoodnotesCore/Sources/FoodnotesArchives/ArchiveJSON.swift@@ -4,14 +4,20 @@ import FoodnotesDomain /// Foundation decoding supplies value/type validation; this layer also rejects unknown and duplicate keys. public enum ArchiveJSON { public static func records(_ data: Data) throws -> ArchiveRecords {- try validate(data, schema: recordsSchema)+ let root = try JSONSerialization.jsonObject(with: data) as? [String: Any]+ guard let version = root?["schemaVersion"] as? Int, [1, 2].contains(version) else {+ throw ArchiveValidationError.unsupportedVersion+ }+ try validate(data, schema: recordSchema(asset: version == 1 ? asset : pdfAsset)) let value = try JSONDecoder().decode(ArchiveRecords.self, from: data) try ArchiveGraphValidator.validate(value) return value } public static func manifest(_ data: Data) throws -> ArchiveManifest { try validate(data, schema: manifestSchema)- return try JSONDecoder().decode(ArchiveManifest.self, from: data)+ let value = try JSONDecoder().decode(ArchiveManifest.self, from: data)+ guard [1, 2].contains(value.schemaVersion) else { throw ArchiveValidationError.unsupportedVersion }+ return value } private indirect enum Schema: Sendable {@@ -51,25 +57,37 @@ public enum ArchiveJSON { private static let ordering = object("optionID label type url phone note") private static let money = object("cents currencyCode") private static let asset = object("id role mediaType byteLength sha256")+ private static let bounds = object("x y width height")+ private static let status = object("", children: ["pending": object(""), "processing": object(""),+ "processed": object(""), "incomplete": object("_0")])+ private static let pdfAsset = object("id role mediaType byteLength sha256", children: [+ "receiptProvenance": object("", children: [+ "pages": .array(object("sourceID pageIndex", children: ["status": status])),+ "rows": .array(object("id sourceID pageIndex occurrenceID dismissed", children: ["bounds": bounds])),+ "fields": .array(object("fieldPath occurrenceID pageIndices rowIDs", children: [+ "priceCalculation": object("basis quantity amountCents gstCents")+ ])),+ "evidence": .array(object("id sourceID pageIndex", children: ["bounds": bounds]))+ ])]) private static let photos = Schema.array(object("assetID isPresent", children: [ "framing": object("", children: ["value": object("centerX centerY zoom")])])) private static let occurrence = object("id originalSourceLine name quantity price note dishID sortKey isPresent", children: ["price": money, "photos": photos])- private static let meal = object(+ private static func mealSchema(_ asset: Schema) -> Schema { object( "id library originalCreatorID controllingOwnerID createdAt date time title placeID ordering notes isFinished", children: ["date": date, "time": object("hour minute"), "ordering": ordering, "photos": photos, "photoSelection": object("assetID"), "diners": .array(object("dinerID name")), "occurrences": .array(occurrence), "opinions": .array(object("occurrenceID dinerID response", children: [ "response": object("value enteredBy enteredAt")- ])), "assets": .array(asset)])- private static let recordsSchema = object("schemaVersion", children: [- "meals": .array(meal), "people": .array(object("id library name linkedAdultID")),+ ])), "assets": .array(asset)]) }+ private static func recordSchema(asset: Schema) -> Schema { object("schemaVersion", children: [+ "meals": .array(mealSchema(asset)), "people": .array(object("id library name linkedAdultID")), "places": .array(object("id library correspondenceID name branch mapIdentity area cuisine usualOptionID", children: [ "aliases": .array(object("id name")), "avoidance": object("isAvoided reason setterID setAt") ])), "orderingOptions": .array(object("id library placeID label url phone note type sortKey")), "dishes": .array(object("id library placeID correspondenceID name"))- ])+ ]) } private static let manifestSchema = object("schemaVersion scope exportedAt", children: [ "recordCounts": object("meals people places orderingOptions dishes occurrences diners opinions assets"), "entries": .array(object("path byteLength sha256"))
diff --git a/Foodnotes/Packages/FoodnotesCore/Sources/FoodnotesArchives/ArchiveResources.swift b/Foodnotes/Packages/FoodnotesCore/Sources/FoodnotesArchives/ArchiveResources.swiftindex 9d42601..58ca4fa 100644--- a/Foodnotes/Packages/FoodnotesCore/Sources/FoodnotesArchives/ArchiveResources.swift+++ b/Foodnotes/Packages/FoodnotesCore/Sources/FoodnotesArchives/ArchiveResources.swift@@ -1,4 +1,6 @@ import Foundation+import CoreGraphics+import FoodnotesDomain import CryptoKit import ImageIO import UniformTypeIdentifiers@@ -47,6 +49,18 @@ public enum ArchiveIO { let values = try url.resourceValues(forKeys: [.isRegularFileKey, .isSymbolicLinkKey]) guard url.isFileURL, values.isRegularFile == true, values.isSymbolicLink != true else { throw ArchiveValidationError.invalidEntry } }+ public static func original(_ url: URL, mediaType: String, expectedPageCount: Int? = nil) throws {+ try regular(url)+ guard let media = OriginalMedia(rawValue: mediaType) else { throw ArchiveValidationError.invalidEntry }+ guard media == .pdf else { try image(url, mediaType: mediaType); return }+ guard let size = try url.resourceValues(forKeys: [.fileSizeKey]).fileSize,+ size > 0, size <= 32 * 1_024 * 1_024,+ let provider = CGDataProvider(url: url as CFURL), let document = CGPDFDocument(provider),+ !document.isEncrypted || document.isUnlocked, (1...20).contains(document.numberOfPages),+ expectedPageCount.map({ $0 == document.numberOfPages }) ?? true else {+ throw ArchiveValidationError.invalidEntry+ }+ } public static func image(_ url: URL, mediaType: String) throws { guard let source = CGImageSourceCreateWithURL(url as CFURL, nil), CGImageSourceGetCount(source) > 0, let identifier = CGImageSourceGetType(source) as String?,
diff --git a/Foodnotes/Packages/FoodnotesCore/Sources/FoodnotesArchives/ArchiveValidation.swift b/Foodnotes/Packages/FoodnotesCore/Sources/FoodnotesArchives/ArchiveValidation.swiftindex 9a81fc7..c8ad851 100644--- a/Foodnotes/Packages/FoodnotesCore/Sources/FoodnotesArchives/ArchiveValidation.swift+++ b/Foodnotes/Packages/FoodnotesCore/Sources/FoodnotesArchives/ArchiveValidation.swift@@ -8,7 +8,8 @@ public enum ArchiveValidationError: Error, Equatable { public enum ArchiveGraphValidator { public static func validate(_ records: ArchiveRecords) throws {- guard records.schemaVersion == 1 else { throw ArchiveValidationError.unsupportedVersion }+ let hasPDF = records.meals.contains { $0.assets.contains { $0.mediaType == "application/pdf" } }+ guard records.schemaVersion == (hasPDF ? 2 : 1) else { throw ArchiveValidationError.unsupportedVersion } let graph = try records.graph(personalAccountID: UUID()) try unique(records.meals.map { $0.id.uuidString }) try unique(records.people.map { "\($0.library):\($0.id)" })@@ -28,21 +29,24 @@ public enum ArchiveGraphValidator { public static func assets(in records: ArchiveRecords) throws -> [UUID: ArchiveAssetRecord] { var result: [UUID: ArchiveAssetRecord] = [:] for asset in records.meals.flatMap(\.assets) {- guard imageExtension(asset.mediaType) != nil, asset.byteLength > 0,+ guard OriginalMedia(rawValue: asset.mediaType) != nil, asset.byteLength > 0, asset.sha256.utf8.count == 64, asset.sha256.utf8.allSatisfy({ (48...57).contains($0) || (97...102).contains($0) }) else { throw ArchiveValidationError.invalidGraph }+ try AssetManifestEntry(assetID: asset.id, address: nil, role: asset.role, mediaType: asset.mediaType,+ byteLength: asset.byteLength, sha256: asset.sha256, receiptProvenance: asset.receiptProvenance).validate() guard result[asset.id] == nil else { throw ArchiveValidationError.invalidGraph } result[asset.id] = asset } return result } - public static func imagePath(_ asset: ArchiveAssetRecord) throws -> String {- guard let suffix = imageExtension(asset.mediaType) else { throw ArchiveValidationError.invalidGraph }- return "images/\(asset.id.uuidString.lowercased()).\(suffix)"+ public static func originalPath(_ asset: ArchiveAssetRecord) throws -> String {+ guard let media = OriginalMedia(rawValue: asset.mediaType) else { throw ArchiveValidationError.invalidGraph }+ return "\(media == .pdf ? "documents" : "images")/\(asset.id.uuidString.lowercased()).\(media.suffix)" }+ public static func imagePath(_ asset: ArchiveAssetRecord) throws -> String { try originalPath(asset) } public static func counts(_ records: ArchiveRecords) throws -> [String: Int] { ["meals": records.meals.count, "people": records.people.count, "places": records.places.count,@@ -77,9 +81,6 @@ public enum ArchiveGraphValidator { for dish in records.dishes { try require(places.contains("\(dish.library):\(dish.placeID)")) } } - private static func imageExtension(_ type: String) -> String? {- ["image/png": "png", "image/jpeg": "jpg", "image/heic": "heic", "image/heif": "heif"][type]- } private static func unique(_ values: [String]) throws { try require(Set(values).count == values.count) } private static func require(_ condition: Bool) throws { if !condition { throw ArchiveValidationError.invalidGraph } } }
diff --git a/Foodnotes/Packages/FoodnotesCore/Sources/FoodnotesArchives/ArchiveZIPCodec.swift b/Foodnotes/Packages/FoodnotesCore/Sources/FoodnotesArchives/ArchiveZIPCodec.swiftindex 020927f..e84134e 100644--- a/Foodnotes/Packages/FoodnotesCore/Sources/FoodnotesArchives/ArchiveZIPCodec.swift+++ b/Foodnotes/Packages/FoodnotesCore/Sources/FoodnotesArchives/ArchiveZIPCodec.swift@@ -47,10 +47,10 @@ public struct ArchiveZIPCodec: Sendable { let asset = required[id]! let source = assets[id]! try verifyOriginal(source, asset: asset)- entries.append(ArchiveEntry(path: try ArchiveGraphValidator.imagePath(asset), byteLength: asset.byteLength,+ entries.append(ArchiveEntry(path: try ArchiveGraphValidator.originalPath(asset), byteLength: asset.byteLength, sha256: asset.sha256)) }- let manifest = ArchiveManifest(schemaVersion: 1, scope: scope, exportedAt: exportedAt,+ let manifest = ArchiveManifest(schemaVersion: records.schemaVersion, scope: scope, exportedAt: exportedAt, recordCounts: try ArchiveGraphValidator.counts(records), entries: entries) let manifestData = try JSONEncoder().encode(manifest) var complete = false@@ -71,7 +71,7 @@ public struct ArchiveZIPCodec: Sendable { guard paths.contains("manifest.json"), paths.contains("records.json") else { throw ArchiveValidationError.invalidManifest } let archive = try Archive(url: url, accessMode: .read) let manifest = try ArchiveJSON.manifest(metadata("manifest.json", from: archive))- guard manifest.schemaVersion == 1 else { throw ArchiveValidationError.unsupportedVersion }+ guard [1, 2].contains(manifest.schemaVersion) else { throw ArchiveValidationError.unsupportedVersion } try manifestEntries(manifest, paths: paths) let recordsData = try metadata("records.json", from: archive) guard let recordEntry = manifest.entries.first(where: { $0.path == "records.json" }),@@ -79,10 +79,11 @@ public struct ArchiveZIPCodec: Sendable { throw ArchiveValidationError.checksumMismatch } let records = try ArchiveJSON.records(recordsData)+ guard records.schemaVersion == manifest.schemaVersion else { throw ArchiveValidationError.unsupportedVersion } try validateScope(records, scope: manifest.scope) guard manifest.recordCounts == (try ArchiveGraphValidator.counts(records)) else { throw ArchiveValidationError.invalidManifest } let assets = try ArchiveGraphValidator.assets(in: records)- let expected = try Set(assets.values.map { try ArchiveGraphValidator.imagePath($0) } + ["records.json"])+ let expected = try Set(assets.values.map { try ArchiveGraphValidator.originalPath($0) } + ["records.json"]) guard expected == Set(manifest.entries.map(\.path)) else { throw ArchiveValidationError.invalidManifest } let owned = directory.appendingPathComponent("validated-\(UUID())", isDirectory: true) try FileManager.default.createDirectory(at: owned, withIntermediateDirectories: false)@@ -90,14 +91,14 @@ public struct ArchiveZIPCodec: Sendable { defer { if !complete { try? FileManager.default.removeItem(at: owned) } } var files: [UUID: URL] = [:] for asset in assets.values {- let path = try ArchiveGraphValidator.imagePath(asset)+ let path = try ArchiveGraphValidator.originalPath(asset) guard let entry = archive[path], let description = manifest.entries.first(where: { $0.path == path }), description.byteLength == asset.byteLength, description.sha256 == asset.sha256 else { throw ArchiveValidationError.invalidManifest } let destination = owned.appendingPathComponent("\(asset.id).original") try extract(entry, archive: archive, to: destination, expected: description)- try ArchiveIO.image(destination, mediaType: asset.mediaType)+ try ArchiveIO.original(destination, mediaType: asset.mediaType, expectedPageCount: asset.receiptProvenance?.pages.count) files[asset.id] = destination } complete = true@@ -107,13 +108,14 @@ public struct ArchiveZIPCodec: Sendable { private func path(_ path: String) throws { if path == "manifest.json" || path == "records.json" { return } let parts = path.split(separator: "/", omittingEmptySubsequences: false)- guard parts.count == 2, parts[0] == "images", !path.contains("\\"), !path.contains("\0") else {+ guard parts.count == 2, ["images", "documents"].contains(String(parts[0])), !path.contains("\\"), !path.contains("\0") else { throw ArchiveValidationError.invalidPath } let filename = String(parts[1]) as NSString let stem = filename.deletingPathExtension+ let suffixes = parts[0] == "documents" ? ["pdf"] : ["png", "jpg", "heic", "heif"] guard let id = UUID(uuidString: stem), stem == id.uuidString.lowercased(),- ["png", "jpg", "heic", "heif"].contains(filename.pathExtension) else { throw ArchiveValidationError.invalidPath }+ suffixes.contains(filename.pathExtension) else { throw ArchiveValidationError.invalidPath } } private func manifestEntries(_ manifest: ArchiveManifest, paths: [String]) throws {@@ -158,7 +160,7 @@ public struct ArchiveZIPCodec: Sendable { private func addFile(_ url: URL, asset: ArchiveAssetRecord, to archive: Archive, directory: URL) throws { let input = try FileHandle(forReadingFrom: url) defer { try? input.close() }- try archive.addEntry(with: ArchiveGraphValidator.imagePath(asset), type: .file, uncompressedSize: asset.byteLength,+ try archive.addEntry(with: ArchiveGraphValidator.originalPath(asset), type: .file, uncompressedSize: asset.byteLength, bufferSize: ArchiveIO.chunkSize) { position, count in try resources.check(bytes: Int64(count), directory: directory) try input.seek(toOffset: UInt64(position))@@ -193,7 +195,7 @@ public struct ArchiveZIPCodec: Sendable { try ArchiveIO.regular(url) guard try url.resourceValues(forKeys: [.fileSizeKey]).fileSize.map(Int64.init) == asset.byteLength, try ArchiveIO.digest(url) == asset.sha256 else { throw ArchiveValidationError.checksumMismatch }- try ArchiveIO.image(url, mediaType: asset.mediaType)+ try ArchiveIO.original(url, mediaType: asset.mediaType, expectedPageCount: asset.receiptProvenance?.pages.count) } private func validateScope(_ records: ArchiveRecords, scope: LibraryScope) throws { let libraries = records.meals.map(\.library) + records.people.map(\.library) + records.places.map(\.library)
diff --git a/Foodnotes/Packages/FoodnotesCore/Sources/FoodnotesDomain/Archives/ArchiveRecords.swift b/Foodnotes/Packages/FoodnotesCore/Sources/FoodnotesDomain/Archives/ArchiveRecords.swiftindex 1c0940b..b596f14 100644--- a/Foodnotes/Packages/FoodnotesCore/Sources/FoodnotesDomain/Archives/ArchiveRecords.swift+++ b/Foodnotes/Packages/FoodnotesCore/Sources/FoodnotesDomain/Archives/ArchiveRecords.swift@@ -61,6 +61,7 @@ public struct ArchiveAssetRecord: Sendable, Codable, Equatable { public var mediaType: String public var byteLength: Int64 public var sha256: String+ public var receiptProvenance: ReceiptProvenance? } public struct ArchivePersonRecord: Sendable, Codable, Equatable {
diff --git a/Foodnotes/Packages/FoodnotesCore/Sources/FoodnotesDomain/Archives/ArchiveRecordsMapping.swift b/Foodnotes/Packages/FoodnotesCore/Sources/FoodnotesDomain/Archives/ArchiveRecordsMapping.swiftindex 1306367..f7be440 100644--- a/Foodnotes/Packages/FoodnotesCore/Sources/FoodnotesDomain/Archives/ArchiveRecordsMapping.swift+++ b/Foodnotes/Packages/FoodnotesCore/Sources/FoodnotesDomain/Archives/ArchiveRecordsMapping.swift@@ -3,9 +3,9 @@ import Foundation extension ArchiveRecords { public init(graph: ArchiveGraph) { let tokens = Self.libraryTokens(graph)- schemaVersion = graph.schemaVersion+ schemaVersion = Self.archiveVersion(graph) meals = graph.documents.filter(\.meal.isPresent.value).map { document in- let meal = document.meal+ let meal = document.meal, retained = Self.receiptOccurrenceIDs(document) return ArchiveMealRecord(id: meal.id, library: tokens[meal.libraryID]!, originalCreatorID: meal.originalCreatorID, controllingOwnerID: meal.controllingOwnerID, createdAt: meal.createdAt, date: meal.date.value, time: meal.time.value, title: meal.title.value, placeID: meal.placeID.value,@@ -13,7 +13,9 @@ extension ArchiveRecords { diners: document.diners.filter(\.isPresent.value).map { ArchiveDinerRecord(dinerID: $0.dinerID, name: $0.nameSnapshot) }.sorted { $0.dinerID.uuidString < $1.dinerID.uuidString },- occurrences: document.occurrences.filter { $0.isPresent.value || $0.photos != nil }.map {+ occurrences: document.occurrences.filter {+ $0.isPresent.value || $0.photos != nil || retained.contains($0.id)+ }.map { ArchiveOccurrenceRecord(id: $0.id, originalSourceLine: $0.originalSourceLine, name: $0.displayName.value, quantity: $0.quantity.value, price: $0.price.value, note: $0.note.value, dishID: $0.menuDishID.value,@@ -23,7 +25,8 @@ extension ArchiveRecords { opinions: Self.opinions(document), assets: document.assets.map { ArchiveAssetRecord(id: $0.assetID, role: $0.role, mediaType: $0.mediaType,- byteLength: $0.byteLength, sha256: $0.sha256)+ byteLength: $0.byteLength, sha256: $0.sha256,+ receiptProvenance: $0.receiptProvenance) }.sorted { $0.id.uuidString < $1.id.uuidString }, photos: Self.photos(meal.photos), photoSelection: meal.selectedPhotoAssetID.map { ArchivePhotoSelection(assetID: $0.value) })@@ -50,6 +53,14 @@ extension ArchiveRecords { }.sorted { ($0.library, $0.id.uuidString) < ($1.library, $1.id.uuidString) } } + private static func archiveVersion(_ graph: ArchiveGraph) -> Int {+ guard graph.schemaVersion == 1 else { return graph.schemaVersion }+ return graph.documents.contains { $0.assets.contains { $0.mediaType == "application/pdf" } } ? 2 : 1+ }+ private static func receiptOccurrenceIDs(_ document: MealDocument) -> Set<UUID> {+ Set(document.assets.flatMap { ($0.receiptProvenance?.rows ?? []).map(\.occurrenceID) })+ }+ public func canonicalData() throws -> Data { let encoder = JSONEncoder() encoder.outputFormatting = [.sortedKeys, .withoutEscapingSlashes]@@ -88,7 +99,8 @@ extension ArchiveRecords { Opinion(occurrenceID: $0.occurrenceID, dinerID: $0.dinerID, response: field($0.response)) }, assets: record.assets.map { AssetManifestEntry(assetID: $0.id, address: nil, role: $0.role, mediaType: $0.mediaType,- byteLength: $0.byteLength, sha256: $0.sha256)+ byteLength: $0.byteLength, sha256: $0.sha256,+ receiptProvenance: $0.receiptProvenance) }) } return ArchiveGraph(schemaVersion: schemaVersion, documents: documents, people: try people.map {
diff --git a/Foodnotes/Packages/FoodnotesCore/Sources/FoodnotesDomain/CaptureContracts.swift b/Foodnotes/Packages/FoodnotesCore/Sources/FoodnotesDomain/CaptureContracts.swiftindex 8038635..53470f2 100644--- a/Foodnotes/Packages/FoodnotesCore/Sources/FoodnotesDomain/CaptureContracts.swift+++ b/Foodnotes/Packages/FoodnotesCore/Sources/FoodnotesDomain/CaptureContracts.swift@@ -27,17 +27,20 @@ public struct SourceEvidence: Sendable, Codable, Equatable { public var sourceID: UUID public var text: String public var boundingBox: EvidenceRectangle+ public var pageIndex: Int? public init( id: UUID, sourceID: UUID, text: String,- boundingBox: EvidenceRectangle+ boundingBox: EvidenceRectangle,+ pageIndex: Int? = nil ) { self.id = id self.sourceID = sourceID self.text = text self.boundingBox = boundingBox+ self.pageIndex = pageIndex } } @@ -102,6 +105,11 @@ public struct Draft: Sendable, Codable, Equatable { public var mealPhotoFraming: [DraftPhotoFraming]? public var pendingSharedSetup: Bool? public var extractionStatus: DraftExtractionStatus?+ public var receiptPages: [ReceiptPageState]?+ public var receiptRows: [ReceiptRowAnchor]?+ public var receiptEvidence: [ReceiptEvidenceAnchor]?+ public var receiptAcceptedFields: [ReceiptFieldProvenance]?+ public var receiptDismissedOccurrences: [DraftOccurrence]? public init( id: UUID,@@ -205,6 +213,7 @@ public struct ExtractionProposal: Sendable, Codable, Equatable { public var evidenceIDs: [UUID] public var expectedEditVersion: UInt64 public var parserVersion: String+ public var priceCalculation: ReceiptPriceCalculation? public init( generation: UUID,@@ -212,7 +221,8 @@ public struct ExtractionProposal: Sendable, Codable, Equatable { value: String, evidenceIDs: [UUID], expectedEditVersion: UInt64,- parserVersion: String+ parserVersion: String,+ priceCalculation: ReceiptPriceCalculation? = nil ) { self.generation = generation self.fieldPath = fieldPath@@ -220,5 +230,6 @@ public struct ExtractionProposal: Sendable, Codable, Equatable { self.evidenceIDs = evidenceIDs self.expectedEditVersion = expectedEditVersion self.parserVersion = parserVersion+ self.priceCalculation = priceCalculation } }
diff --git a/Foodnotes/Packages/FoodnotesCore/Sources/FoodnotesDomain/DraftPhotos.swift b/Foodnotes/Packages/FoodnotesCore/Sources/FoodnotesDomain/DraftPhotos.swiftindex f5a6f1f..c599dd6 100644--- a/Foodnotes/Packages/FoodnotesCore/Sources/FoodnotesDomain/DraftPhotos.swift+++ b/Foodnotes/Packages/FoodnotesCore/Sources/FoodnotesDomain/DraftPhotos.swift@@ -1,10 +1,12 @@ import Foundation extension Draft {- public var allImageSources: [SourceImage] { sources + (foodPhotos ?? []) }+ public var allOriginalSources: [SourceImage] { sources + (foodPhotos ?? []) }+ public var allImageSources: [SourceImage] { allOriginalSources.filter { OriginalMedia(rawValue: $0.mediaType)?.isFoodPhoto == true } } public func validatePhotoReferences() throws {- try requireValue(Set(allImageSources.map(\.id)).count == allImageSources.count, "duplicate draft image")- for image in allImageSources { try image.validate() }+ try requireValue(Set(allOriginalSources.map(\.id)).count == allOriginalSources.count, "duplicate draft image")+ for image in allOriginalSources { try image.validate() }+ try requireValue((foodPhotos ?? []).allSatisfy { OriginalMedia(rawValue: $0.mediaType)?.isFoodPhoto == true }, "food photo media") let admitted = Set(allImageSources.map(\.id)) for references in [mealPhotoAssetIDs] + occurrences.map(\.photoAssetIDs) { if let references {@@ -19,11 +21,15 @@ extension Draft { try requireValue(admitted.contains(selected) && membership.contains(selected), "draft selected photo") } }- public mutating func replaceImageLocators(_ published: [SourceImage]) {+ public mutating func replaceOriginalLocators(_ published: [SourceImage]) { let sourceIDs = Set(sources.map(\.id)) sources = published.filter { sourceIDs.contains($0.id) } if foodPhotos != nil { foodPhotos = published.filter { !sourceIDs.contains($0.id) } } }+ public mutating func replaceImageLocators(_ published: [SourceImage]) {+ let images = Dictionary(uniqueKeysWithValues: published.map { ($0.id, $0) })+ replaceOriginalLocators(allOriginalSources.map { images[$0.id] ?? $0 })+ } /// Only newly added food assets can be discarded; capture provenance is immutable. public mutating func pruneUnreferencedFoodPhotos() { guard let photos = foodPhotos else { return }
diff --git a/Foodnotes/Packages/FoodnotesCore/Sources/FoodnotesDomain/Identity.swift b/Foodnotes/Packages/FoodnotesCore/Sources/FoodnotesDomain/Identity.swiftindex 16bc64b..0571241 100644--- a/Foodnotes/Packages/FoodnotesCore/Sources/FoodnotesDomain/Identity.swift+++ b/Foodnotes/Packages/FoodnotesCore/Sources/FoodnotesDomain/Identity.swift@@ -18,7 +18,7 @@ public enum DatabaseScope: String, Sendable, Codable { } public enum CaptureRoute: String, Sendable, Codable {- case camera, photos, shareExtension, manual+ case camera, photos, shareExtension, manual, files } public enum OpinionValue: String, Sendable, Codable {
diff --git a/Foodnotes/Packages/FoodnotesCore/Sources/FoodnotesDomain/OriginalMedia.swift b/Foodnotes/Packages/FoodnotesCore/Sources/FoodnotesDomain/OriginalMedia.swiftnew file mode 100644index 0000000..89969f8--- /dev/null+++ b/Foodnotes/Packages/FoodnotesCore/Sources/FoodnotesDomain/OriginalMedia.swift@@ -0,0 +1,55 @@+import Foundation++/// Receipt originals and food photos share immutable storage, never photo eligibility.+public enum OriginalMedia: String, Sendable, Codable {+ case jpeg = "image/jpeg", png = "image/png", heic = "image/heic", heif = "image/heif"+ case pdf = "application/pdf"+ public var isFoodPhoto: Bool { self != .pdf }+ public var suffix: String {+ switch self {+ case .jpeg: "jpg"+ case .png: "png"+ case .heic: "heic"+ case .heif: "heif"+ case .pdf: "pdf"+ }+ }+}++public struct ReceiptPageState: Sendable, Codable, Equatable {+ public enum Status: Sendable, Codable, Equatable {+ case pending, processing, processed, incomplete(String)+ }+ public var sourceID: UUID+ public var pageIndex: Int+ public var status: Status+ public init(sourceID: UUID, pageIndex: Int, status: Status = .pending) {+ self.sourceID = sourceID; self.pageIndex = pageIndex; self.status = status+ }+}++/// Canonical identity is separate from parser text and retained after dismissal.+public struct ReceiptRowAnchor: Sendable, Codable, Equatable {+ public var id: UUID+ public var sourceID: UUID+ public var pageIndex: Int+ public var bounds: EvidenceRectangle+ public var occurrenceID: UUID+ public var dismissed: Bool+ public init(id: UUID, sourceID: UUID, pageIndex: Int, bounds: EvidenceRectangle,+ occurrenceID: UUID, dismissed: Bool = false) {+ self.id = id; self.sourceID = sourceID; self.pageIndex = pageIndex+ self.bounds = bounds; self.occurrenceID = occurrenceID; self.dismissed = dismissed+ }+}++public struct ReceiptProvenance: Sendable, Codable, Equatable {+ public var pages: [ReceiptPageState]+ public var rows: [ReceiptRowAnchor]+ public var fields: [ReceiptFieldProvenance]?+ public var evidence: [ReceiptEvidenceAnchor]?+ public init(pages: [ReceiptPageState], rows: [ReceiptRowAnchor], fields: [ReceiptFieldProvenance]? = nil,+ evidence: [ReceiptEvidenceAnchor]? = nil) {+ self.pages = pages; self.rows = rows; self.fields = fields; self.evidence = evidence+ }+}
diff --git a/Foodnotes/Packages/FoodnotesCore/Sources/FoodnotesDomain/PhotoReferences.swift b/Foodnotes/Packages/FoodnotesCore/Sources/FoodnotesDomain/PhotoReferences.swiftindex ceac913..cf35f9b 100644--- a/Foodnotes/Packages/FoodnotesCore/Sources/FoodnotesDomain/PhotoReferences.swift+++ b/Foodnotes/Packages/FoodnotesCore/Sources/FoodnotesDomain/PhotoReferences.swift@@ -54,14 +54,18 @@ extension MealDocument { func check(_ references: [PhotoReference]?) throws { for reference in references ?? [] { try reference.framing?.value?.validate() } let ids = (references ?? []).map(\.assetID)- guard Set(ids).count == ids.count, ids.allSatisfy({ id in assets.contains { $0.assetID == id } }) else {+ guard Set(ids).count == ids.count, ids.allSatisfy({ id in+ assets.contains { $0.assetID == id && OriginalMedia(rawValue: $0.mediaType)?.isFoodPhoto == true }+ }) else { throw DomainError.invalidValue("photo membership") } } try check(meal.photos) for line in occurrences { try check(line.photos) } if let chosen = meal.selectedPhotoAssetID?.value {- guard assets.contains(where: { $0.assetID == chosen }),+ guard assets.contains(where: {+ $0.assetID == chosen && OriginalMedia(rawValue: $0.mediaType)?.isFoodPhoto == true+ }), meal.photos?.contains(where: { $0.assetID == chosen }) != false else { throw DomainError.invalidValue("meal photo selection") }
diff --git a/Foodnotes/Packages/FoodnotesCore/Sources/FoodnotesDomain/PlaceModels.swift b/Foodnotes/Packages/FoodnotesCore/Sources/FoodnotesDomain/PlaceModels.swiftindex 3d2ba93..5a4f66e 100644--- a/Foodnotes/Packages/FoodnotesCore/Sources/FoodnotesDomain/PlaceModels.swift+++ b/Foodnotes/Packages/FoodnotesCore/Sources/FoodnotesDomain/PlaceModels.swift@@ -209,6 +209,7 @@ public struct AssetManifestEntry: Sendable, Codable, Equatable { public var mediaType: String public var byteLength: Int64 public var sha256: String+ public var receiptProvenance: ReceiptProvenance? public init( assetID: UUID,@@ -216,7 +217,8 @@ public struct AssetManifestEntry: Sendable, Codable, Equatable { role: AssetRole, mediaType: String, byteLength: Int64,- sha256: String+ sha256: String,+ receiptProvenance: ReceiptProvenance? = nil ) { self.assetID = assetID self.address = address@@ -224,6 +226,7 @@ public struct AssetManifestEntry: Sendable, Codable, Equatable { self.mediaType = mediaType self.byteLength = byteLength self.sha256 = sha256+ self.receiptProvenance = receiptProvenance } }
diff --git a/Foodnotes/Packages/FoodnotesCore/Sources/FoodnotesDomain/ReceiptPriceCalculation.swift b/Foodnotes/Packages/FoodnotesCore/Sources/FoodnotesDomain/ReceiptPriceCalculation.swiftnew file mode 100644index 0000000..d451500--- /dev/null+++ b/Foodnotes/Packages/FoodnotesCore/Sources/FoodnotesDomain/ReceiptPriceCalculation.swift@@ -0,0 +1,52 @@+import Foundation++/// Source amounts remain integer cents; only the final per-item value is rounded.+public struct ReceiptPriceCalculation: Sendable, Codable, Equatable {+ public enum Basis: String, Sendable, Codable { case netRowPlusGST, grossRow, printedGrossUnit }+ public var basis: Basis+ public var quantity: Int+ public var amountCents: Int64+ public var gstCents: Int64?++ public init(basis: Basis, quantity: Int, amountCents: Int64, gstCents: Int64? = nil) {+ self.basis = basis; self.quantity = quantity; self.amountCents = amountCents; self.gstCents = gstCents+ }++ public func unitPriceCents() throws -> Int64 {+ let maximum: Int64 = 999_999_999+ try requireValue((1...9_999).contains(quantity) && (0...maximum).contains(amountCents), "receipt unit price inputs")+ let gross: Int64+ switch basis {+ case .netRowPlusGST:+ guard let gstCents else { throw DomainError.invalidValue("receipt row GST is missing") }+ try requireValue((0...maximum).contains(gstCents), "receipt row GST")+ gross = amountCents + gstCents+ case .grossRow, .printedGrossUnit:+ try requireValue(gstCents == nil, "GST must not be added to an inclusive price")+ gross = amountCents+ }+ let divisor = basis == .printedGrossUnit ? 1 : Int64(quantity)+ let result = gross / divisor + ((gross % divisor) * 2 >= divisor ? 1 : 0)+ try requireValue((0...maximum).contains(result), "receipt unit price result")+ return result+ }++ public func unitPriceText() throws -> String { Self.money(try unitPriceCents()) }++ public var explanation: String {+ guard let result = try? unitPriceText() else { return "Receipt price calculation unavailable." }+ let amount = "AUD " + Self.money(amountCents)+ switch basis {+ case .printedGrossUnit: return "Receipt: \(amount) each, including GST (printed)."+ case .grossRow:+ return "Receipt: \(amount) including GST divided by \(quantity) = AUD \(result) each. Rounded half up to cents."+ case .netRowPlusGST:+ return "Receipt: (\(amount) net + AUD \(Self.money(gstCents ?? 0)) GST) divided by \(quantity) = AUD \(result) each. "+ + "Rounded half up to cents."+ }+ }++ private static func money(_ cents: Int64) -> String {+ "\(cents / 100)." + (cents % 100 < 10 ? "0" : "") + "\(cents % 100)"+ }+}
diff --git a/Foodnotes/Packages/FoodnotesCore/Sources/FoodnotesDomain/ReceiptProvenance.swift b/Foodnotes/Packages/FoodnotesCore/Sources/FoodnotesDomain/ReceiptProvenance.swiftnew file mode 100644index 0000000..e8e487c--- /dev/null+++ b/Foodnotes/Packages/FoodnotesCore/Sources/FoodnotesDomain/ReceiptProvenance.swift@@ -0,0 +1,100 @@+import Foundation++public struct ReceiptEvidenceAnchor: Sendable, Codable, Equatable {+ public var id: UUID+ public var sourceID: UUID+ public var pageIndex: Int+ public var bounds: EvidenceRectangle+ public init(id: UUID, sourceID: UUID, pageIndex: Int, bounds: EvidenceRectangle) {+ self.id = id; self.sourceID = sourceID; self.pageIndex = pageIndex; self.bounds = bounds+ }+}++public struct ReceiptFieldProvenance: Sendable, Codable, Equatable {+ public var fieldPath: String+ public var occurrenceID: UUID?+ public var pageIndices: [Int]+ public var rowIDs: [UUID]+ public var priceCalculation: ReceiptPriceCalculation?+ public init(fieldPath: String, occurrenceID: UUID?, pageIndices: [Int], rowIDs: [UUID],+ priceCalculation: ReceiptPriceCalculation? = nil) {+ self.fieldPath = fieldPath; self.occurrenceID = occurrenceID; self.pageIndices = pageIndices; self.rowIDs = rowIDs+ self.priceCalculation = priceCalculation+ }+}++extension ReceiptProvenance {+ public func validate(sourceID: UUID, occurrenceIDs: Set<UUID>? = nil) throws {+ try requireValue(try JSONEncoder().encode(self).count < 1_000_000, "receipt provenance exceeds payload limit")+ try requireValue((1...20).contains(pages.count) && pages.map(\.pageIndex) == Array(0..<pages.count), "receipt pages")+ try requireValue(pages.allSatisfy { $0.sourceID == sourceID }, "receipt page source")+ try requireValue(Set(rows.map(\.id)).count == rows.count, "duplicate receipt row")+ for row in rows {+ try anchor(source: row.sourceID, page: row.pageIndex, bounds: row.bounds, expected: sourceID)+ if let occurrenceIDs { try requireValue(occurrenceIDs.contains(row.occurrenceID), "receipt row occurrence") }+ }+ let evidence = evidence ?? []+ try requireValue(Set(evidence.map(\.id)).count == evidence.count, "duplicate receipt evidence")+ for value in evidence { try anchor(source: value.sourceID, page: value.pageIndex, bounds: value.bounds, expected: sourceID) }+ for value in evidence {+ if let row = rows.first(where: { $0.id == value.id }) {+ try requireValue(row.pageIndex == value.pageIndex && row.bounds == value.bounds, "conflicting receipt anchor identity")+ }+ }+ let locations = rows.map { ($0.id, $0.pageIndex) } + evidence.map { ($0.id, $0.pageIndex) }+ let fields = fields ?? []+ try requireValue(Set(fields.map(\.fieldPath)).count == fields.count, "duplicate receipt field")+ for field in fields {+ try validateField(field, locations: locations, occurrenceIDs: occurrenceIDs)+ }+ }+ private func anchor(source: UUID, page: Int, bounds: EvidenceRectangle, expected: UUID) throws {+ try requireValue(source == expected && (0..<pages.count).contains(page), "receipt anchor page/source")+ try requireValue([bounds.x, bounds.y, bounds.width, bounds.height].allSatisfy(\.isFinite) &&+ bounds.x >= 0 && bounds.y >= 0 && bounds.width > 0 && bounds.height > 0 &&+ bounds.x + bounds.width <= 1.0001 && bounds.y + bounds.height <= 1.0001, "receipt anchor bounds")+ }+ private func validateField(_ field: ReceiptFieldProvenance, locations: [(UUID, Int)], occurrenceIDs: Set<UUID>?) throws {+ if let calculation = field.priceCalculation {+ try requireValue(field.occurrenceID != nil && field.fieldPath.hasSuffix(".price"), "receipt calculation field")+ _ = try calculation.unitPriceCents()+ }+ try requireValue(!field.pageIndices.isEmpty && Set(field.pageIndices).count == field.pageIndices.count,+ "receipt field page identity")+ try requireValue(!field.rowIDs.isEmpty && Set(field.rowIDs).count == field.rowIDs.count, "receipt field anchors")+ let selected = locations.filter { field.rowIDs.contains($0.0) }+ try requireValue(Set(selected.map(\.0)) == Set(field.rowIDs) &&+ Set(selected.map(\.1)) == Set(field.pageIndices), "receipt field pages")+ if let occurrence = field.occurrenceID {+ let supporting = rows.filter { field.rowIDs.contains($0.id) }+ try requireValue(supporting.count == field.rowIDs.count && supporting.allSatisfy { $0.occurrenceID == occurrence },+ "receipt field row occurrence")+ let parts = field.fieldPath.split(separator: ".")+ try requireValue(parts.count == 3 && parts[0] == "occurrences" &&+ UUID(uuidString: String(parts[1])) == occurrence && ["name", "quantity", "price", "note"].contains(String(parts[2])),+ "receipt field path")+ if let occurrenceIDs { try requireValue(occurrenceIDs.contains(occurrence), "receipt field occurrence") }+ } else {+ try requireValue(["date", "time", "title", "place", "ordering", "notes"].contains(field.fieldPath), "receipt field path")+ }+ }+ public func reidentified(sourceID: UUID, occurrenceIDs: [UUID: UUID]) -> Self {+ var result = self+ result.pages = pages.map { var value = $0; value.sourceID = sourceID; return value }+ result.rows = rows.map {+ var value = $0; value.sourceID = sourceID+ value.occurrenceID = occurrenceIDs[value.occurrenceID] ?? value.occurrenceID; return value+ }+ result.evidence = evidence?.map { var value = $0; value.sourceID = sourceID; return value }+ result.fields = fields?.map {+ var value = $0+ if let old = value.occurrenceID, let new = occurrenceIDs[old] {+ value.occurrenceID = new+ let suffix = value.fieldPath.split(separator: ".").last.map(String.init) ?? "name"+ value.fieldPath = "occurrences.\(new).\(suffix)"+ }+ return value+ }+ return result+ }+}
diff --git a/Foodnotes/Packages/FoodnotesCore/Sources/FoodnotesDomain/Validation.swift b/Foodnotes/Packages/FoodnotesCore/Sources/FoodnotesDomain/Validation.swiftindex 7283688..2dcd4b7 100644--- a/Foodnotes/Packages/FoodnotesCore/Sources/FoodnotesDomain/Validation.swift+++ b/Foodnotes/Packages/FoodnotesCore/Sources/FoodnotesDomain/Validation.swift@@ -78,6 +78,11 @@ extension AssetManifestEntry { public func validate() throws { try address?.validate() try requireValue(byteLength > 0 && nonblank(mediaType), "asset metadata")+ try requireValue(mediaType != "application/pdf" || role == .source && byteLength <= 32 * 1_024 * 1_024, "PDF source role/size")+ if let receiptProvenance {+ try requireValue(mediaType == "application/pdf" && role == .source, "receipt provenance media")+ try receiptProvenance.validate(sourceID: assetID)+ } try requireValue(sha256.utf8.count == 64 && sha256.utf8.allSatisfy { (48...57).contains($0) || (97...102).contains($0) }, "asset digest")@@ -110,7 +115,13 @@ extension MealDocument { try requireValue(occurrenceIDs.contains(opinion.occurrenceID) && dinerIDs.contains(opinion.dinerID), "opinion membership") try requireValue(opinion.response.value.enteredAt.timeIntervalSince1970.isFinite, "opinion date") }- for asset in assets { try asset.validate() }+ for asset in assets {+ try asset.validate()+ if asset.mediaType == "application/pdf" {+ try requireValue(asset.receiptProvenance != nil, "PDF receipt provenance missing")+ try asset.receiptProvenance?.validate(sourceID: asset.assetID, occurrenceIDs: occurrenceIDs)+ }+ } try validatePhotos() } }@@ -165,6 +176,6 @@ extension Draft { try validatePhotoReferences() let hasPlace = place.value.map(nonblank) == true let hasDish = occurrences.contains { $0.name.value.map(nonblank) == true }- try requireValue(!allImageSources.isEmpty || hasPlace || hasDish, "save requires a source image, place name or dish name")+ try requireValue(!allOriginalSources.isEmpty || hasPlace || hasDish, "save requires a source image, place name or dish name") } }
diff --git a/Foodnotes/Packages/FoodnotesCore/Tests/FoodnotesArchivesTests/PDFArchiveTests.swift b/Foodnotes/Packages/FoodnotesCore/Tests/FoodnotesArchivesTests/PDFArchiveTests.swiftnew file mode 100644index 0000000..d28f558--- /dev/null+++ b/Foodnotes/Packages/FoodnotesCore/Tests/FoodnotesArchivesTests/PDFArchiveTests.swift@@ -0,0 +1,191 @@+import CoreGraphics+import CoreText+import Foundation+import FoodnotesDomain+import Testing+import ZIPFoundation+@testable import FoodnotesArchives++@Suite struct PDFArchiveTests {+ @Test func unitCalculationRoundTripKeepsBasisRoundingAndSourceAnchors() throws {+ let root = try archiveDirectory()+ defer { try? FileManager.default.removeItem(at: root) }+ var (graph, source) = try pdfArchiveGraph(root)+ let originalBytes = try Data(contentsOf: source)+ let id = archiveUUID(20), occurrence = archiveUUID(30)+ let calculation = ReceiptPriceCalculation(basis: .netRowPlusGST, quantity: 3, amountCents: 1_200, gstCents: 120)+ let field = ReceiptFieldProvenance(fieldPath: "occurrences.\(occurrence).price", occurrenceID: occurrence,+ pageIndices: [0], rowIDs: [archiveUUID(81)], priceCalculation: calculation)+ graph.documents[0].assets[0].receiptProvenance?.fields?.append(field)+ graph.documents[0].occurrences[0].quantity.value = 3+ graph.documents[0].occurrences[0].price.value = .init(cents: 440, currencyCode: "AUD")+ let output = root.appendingPathComponent("calculation.zip")+ _ = try ArchiveZIPCodec().write(ArchiveRecords(graph: graph), assets: [id: source], scope: .personal, to: output)+ let payload = try ArchiveZIPCodec().readValidated(output, directory: root)+ let decoded = try payload.records.graph(personalAccountID: archiveUUID(99))+ let restored = try #require(decoded.documents[0].assets[0].receiptProvenance?.fields?.first { $0.fieldPath == field.fieldPath })+ #expect(restored == field)+ #expect(try restored.priceCalculation?.unitPriceText() == "4.40")+ #expect(try Data(contentsOf: #require(payload.assets[id])) == originalBytes)+ #expect(try Data(contentsOf: source) == originalBytes)+ }+ @Test func unknownCalculationKeysStillRejectStrictArchiveJSON() throws {+ let root = try archiveDirectory()+ defer { try? FileManager.default.removeItem(at: root) }+ var (graph, _) = try pdfArchiveGraph(root)+ graph.documents[0].assets[0].receiptProvenance?.fields?[0].priceCalculation =+ .init(basis: .printedGrossUnit, quantity: 1, amountCents: 440)+ graph.documents[0].assets[0].receiptProvenance?.fields?[0].fieldPath = "occurrences.\(archiveUUID(30)).price"+ let valid = try JSONEncoder().encode(ArchiveRecords(graph: graph))+ _ = try ArchiveJSON.records(valid)+ var json = try #require(JSONSerialization.jsonObject(with: valid) as? [String: Any])+ var meals = try #require(json["meals"] as? [[String: Any]])+ var assets = try #require(meals[0]["assets"] as? [[String: Any]])+ var provenance = try #require(assets[0]["receiptProvenance"] as? [String: Any])+ var fields = try #require(provenance["fields"] as? [[String: Any]])+ var calculation = try #require(fields[0]["priceCalculation"] as? [String: Any])+ calculation["unexpected"] = true; fields[0]["priceCalculation"] = calculation+ provenance["fields"] = fields; assets[0]["receiptProvenance"] = provenance; meals[0]["assets"] = assets; json["meals"] = meals+ #expect(throws: Error.self) { try ArchiveJSON.records(JSONSerialization.data(withJSONObject: json)) }+ }+ @Test func seededV2RoundTripsKeepBytesProvenanceCorrectedValuesAndTombstones() throws {+ let root = try archiveDirectory()+ defer { try? FileManager.default.removeItem(at: root) }+ for seed in 0..<8 {+ let (graph, source) = try pdfArchiveGraph(root, seed: seed)+ let records = ArchiveRecords(graph: graph), id = archiveUUID(20)+ #expect(records.schemaVersion == 2)+ #expect(records.meals[0].assets[0].receiptProvenance == graph.documents[0].assets[0].receiptProvenance)+ let output = root.appendingPathComponent("pdf-\(seed).zip")+ let manifest = try ArchiveZIPCodec().write(records, assets: [id: source], scope: .personal, to: output)+ #expect(manifest.schemaVersion == 2)+ #expect(manifest.entries.contains { $0.path == "documents/\(id.uuidString.lowercased()).pdf" })+ let payload = try ArchiveZIPCodec().readValidated(output, directory: root)+ #expect(payload.manifest.schemaVersion == payload.records.schemaVersion)+ #expect(try Data(contentsOf: payload.assets[id]!) == Data(contentsOf: source))+ let restored = try payload.records.graph(personalAccountID: archiveUUID(99))+ #expect(restored.documents[0].assets[0].receiptProvenance == graph.documents[0].assets[0].receiptProvenance)+ #expect(restored.documents[0].occurrences.contains { !$0.isPresent.value })+ #expect(restored.documents[0].occurrences.first { $0.id == archiveUUID(30) }?.quantity.value == Decimal(string: "2.5"))+ }+ }+ @Test func strictV2JSONRejectsUnknownNestedProvenanceAndVersionCombinations() throws {+ let root = try archiveDirectory()+ defer { try? FileManager.default.removeItem(at: root) }+ let (graph, _) = try pdfArchiveGraph(root)+ let records = ArchiveRecords(graph: graph)+ var json = try #require(JSONSerialization.jsonObject(with: JSONEncoder().encode(records)) as? [String: Any])+ var meals = try #require(json["meals"] as? [[String: Any]])+ var assets = try #require(meals[0]["assets"] as? [[String: Any]])+ var provenance = try #require(assets[0]["receiptProvenance"] as? [String: Any])+ provenance["unknown"] = true; assets[0]["receiptProvenance"] = provenance+ meals[0]["assets"] = assets; json["meals"] = meals+ #expect(throws: Error.self) { try ArchiveJSON.records(JSONSerialization.data(withJSONObject: json)) }+ for version in [1, 99] {+ var wrong = records; wrong.schemaVersion = version+ #expect(throws: Error.self) { try ArchiveJSON.records(JSONEncoder().encode(wrong)) }+ }+ var imageV2 = ArchiveRecords(graph: archiveGraph()); imageV2.schemaVersion = 2+ #expect(throws: Error.self) { try ArchiveJSON.records(JSONEncoder().encode(imageV2)) }+ }+ @Test func PDFContentValidationRejectsSpoofLockedAndOverPageLimit() throws {+ let root = try archiveDirectory()+ defer { try? FileManager.default.removeItem(at: root) }+ for (index, bytes) in [Data("not PDF".utf8), Data("%PDF-1.7 truncated".utf8),+ try archivePDF(pages: 21), try archivePDF(locked: true)].enumerated() {+ let url = root.appendingPathComponent("invalid-\(index).pdf"); try bytes.write(to: url)+ #expect(throws: Error.self) { try ArchiveIO.original(url, mediaType: "application/pdf") }+ }+ let good = root.appendingPathComponent("valid.pdf"); try archivePDF().write(to: good)+ try ArchiveIO.original(good, mediaType: "application/pdf")+ }+ @Test func archiveRejectsOriginalAndDeclaredPageCountMismatch() throws {+ let root = try archiveDirectory()+ defer { try? FileManager.default.removeItem(at: root) }+ for actualPages in [1, 2] {+ var (graph, original) = try pdfArchiveGraph(root, seed: actualPages)+ let bytes = try archivePDF(pages: actualPages)+ try bytes.write(to: original)+ graph.documents[0].assets[0].byteLength = Int64(bytes.count)+ graph.documents[0].assets[0].sha256 = ArchiveIO.digest(bytes)+ let id = archiveUUID(20)+ if actualPages == 1 {+ graph.documents[0].assets[0].receiptProvenance?.pages.append(+ .init(sourceID: id, pageIndex: 1, status: .processed))+ }+ let records = ArchiveRecords(graph: graph)+ #expect(throws: Error.self) {+ try ArchiveZIPCodec().write(records, assets: [id: original], scope: .personal,+ to: root.appendingPathComponent("rejected-\(actualPages).zip"))+ }+ let recordBytes = try JSONEncoder().encode(records)+ let path = "documents/\(id.uuidString.lowercased()).pdf"+ let manifest = ArchiveManifest(schemaVersion: 2, scope: .personal, exportedAt: Date(),+ recordCounts: try ArchiveGraphValidator.counts(records), entries: [+ .init(path: "records.json", byteLength: Int64(recordBytes.count), sha256: ArchiveIO.digest(recordBytes)),+ .init(path: path, byteLength: Int64(bytes.count), sha256: ArchiveIO.digest(bytes))])+ let file = root.appendingPathComponent("external-\(actualPages).zip")+ let zip = try Archive(url: file, accessMode: .create)+ try addArchiveData(recordBytes, path: "records.json", archive: zip)+ try addArchiveData(JSONEncoder().encode(manifest), path: "manifest.json", archive: zip)+ try addArchiveData(bytes, path: path, archive: zip)+ #expect(throws: Error.self) { try ArchiveZIPCodec().readValidated(file, directory: root) }+ }+ }+ @Test func manifestAndRecordsVersionsMustMatchBeforeExtractionWrites() throws {+ let root = try archiveDirectory()+ defer { try? FileManager.default.removeItem(at: root) }+ let (graph, original) = try pdfArchiveGraph(root)+ let records = ArchiveRecords(graph: graph), bytes = try JSONEncoder().encode(records)+ let path = "documents/\(archiveUUID(20).uuidString.lowercased()).pdf", source = try Data(contentsOf: original)+ let manifest = ArchiveManifest(schemaVersion: 1, scope: .personal, exportedAt: Date(),+ recordCounts: try ArchiveGraphValidator.counts(records), entries: [+ .init(path: "records.json", byteLength: Int64(bytes.count), sha256: ArchiveIO.digest(bytes)),+ .init(path: path, byteLength: Int64(source.count), sha256: ArchiveIO.digest(source))])+ let file = root.appendingPathComponent("mismatched.zip"), zip = try Archive(url: file, accessMode: .create)+ try addArchiveData(bytes, path: "records.json", archive: zip)+ try addArchiveData(JSONEncoder().encode(manifest), path: "manifest.json", archive: zip)+ try addArchiveData(source, path: path, archive: zip)+ #expect(throws: Error.self) { try ArchiveZIPCodec().readValidated(file, directory: root) }+ #expect(try FileManager.default.contentsOfDirectory(atPath: root.path).allSatisfy { !$0.hasPrefix("validated-") })+ }+}++func archivePDF(pages: Int = 1, locked: Bool = false, seed: Int = 0) throws -> Data {+ let data = NSMutableData()+ let destination = try #require(CGDataConsumer(data: data))+ var bounds = CGRect(x: 0, y: 0, width: 612, height: 792)+ let options: [String: Any] = locked ? [kCGPDFContextUserPassword as String: "synthetic",+ kCGPDFContextOwnerPassword as String: "owner"] : [:]+ let context = try #require(CGContext(consumer: destination, mediaBox: &bounds, options as CFDictionary))+ for page in 0..<pages {+ context.beginPDFPage(nil)+ let font = CTFontCreateWithName("Helvetica" as CFString, 12, nil)+ let text = NSAttributedString(string: "2 x Noodles $12.50 synthetic \(seed) page \(page)",+ attributes: [.init(rawValue: kCTFontAttributeName as String): font])+ context.textPosition = CGPoint(x: 40, y: 700)+ CTLineDraw(CTLineCreateWithAttributedString(text), context)+ context.endPDFPage()+ }+ context.closePDF()+ return data as Data+}++func pdfArchiveGraph(_ root: URL, seed: Int = 0) throws -> (ArchiveGraph, URL) {+ var graph = archiveGraph()+ let id = archiveUUID(20), data = try archivePDF(seed: seed), file = root.appendingPathComponent("source-\(seed).pdf")+ try data.write(to: file)+ graph.documents[0].occurrences[0].quantity.value = Decimal(string: "2.5")+ graph.documents[0].occurrences[0].price.value = .init(cents: 1_250, currencyCode: "AUD")+ var tombstone = graph.documents[0].occurrences[0]; tombstone.id = archiveUUID(31); tombstone.isPresent.value = false+ graph.documents[0].occurrences.append(tombstone)+ let box = EvidenceRectangle(x: 0.1, y: 0.85, width: 0.8, height: 0.02)+ let rows = [ReceiptRowAnchor(id: archiveUUID(81), sourceID: id, pageIndex: 0, bounds: box, occurrenceID: archiveUUID(30)),+ ReceiptRowAnchor(id: archiveUUID(82), sourceID: id, pageIndex: 0, bounds: box, occurrenceID: tombstone.id, dismissed: true)]+ let provenance = ReceiptProvenance(pages: [.init(sourceID: id, pageIndex: 0, status: .processed)], rows: rows,+ fields: [.init(fieldPath: "occurrences.\(archiveUUID(30)).name", occurrenceID: archiveUUID(30),+ pageIndices: [0], rowIDs: [rows[0].id])])+ graph.documents[0].assets = [.init(assetID: id, address: nil, role: .source, mediaType: "application/pdf",+ byteLength: Int64(data.count), sha256: ArchiveIO.digest(data), receiptProvenance: provenance)]+ return (graph, file)+}
diff --git a/Foodnotes/Packages/FoodnotesCore/Tests/FoodnotesDomainTests/PDFOriginalContractsTests.swift b/Foodnotes/Packages/FoodnotesCore/Tests/FoodnotesDomainTests/PDFOriginalContractsTests.swiftnew file mode 100644index 0000000..fc1119e--- /dev/null+++ b/Foodnotes/Packages/FoodnotesCore/Tests/FoodnotesDomainTests/PDFOriginalContractsTests.swift@@ -0,0 +1,51 @@+import Foundation+import Testing+@testable import FoodnotesDomain++@Suite struct PDFOriginalContractsTests {+ private func source(_ id: Int, media: String = "application/pdf") -> SourceImage {+ SourceImage(id: uuid(id), url: URL(fileURLWithPath: "/synthetic/\(id).original"),+ mediaType: media, byteLength: 128, sha256: String(repeating: "a", count: 64))+ }+ @Test func receiptIsNeverAnImageOrFoodPhoto() throws {+ var value = draft()+ value.sources = [source(80), source(81, media: "image/jpeg")]+ #expect(value.allImageSources.map(\.id) == [uuid(81)])+ value.mealPhotoAssetIDs = [uuid(80)]+ #expect(throws: DomainError.self) { try value.validatePhotoReferences() }+ }+ @Test func pdfCannotEnterFoodPhotoCollection() throws {+ var value = draft()+ value.foodPhotos = [source(80)]+ #expect(throws: DomainError.self) { try value.validatePhotoReferences() }+ }+ @Test func pdfCannotBeSavedAsFoodManifest() throws {+ let asset = AssetManifestEntry(assetID: uuid(80), address: nil, role: .food,+ mediaType: "application/pdf", byteLength: 128, sha256: String(repeating: "a", count: 64))+ #expect(throws: DomainError.self) { try asset.validate() }+ }+ @Test func rebasingPreservesEveryOriginalAndImageEligibility() throws {+ for seed in 1...32 {+ var value = draft()+ value.sources = [source(80), source(81, media: "image/png")]+ value.foodPhotos = [source(82, media: "image/jpeg")]+ let published = value.allOriginalSources.map { original in+ var copy = original+ copy.url = URL(fileURLWithPath: "/relocated/\(seed)/\(copy.id).original")+ return copy+ }+ value.replaceOriginalLocators(published)+ #expect(value.allOriginalSources == published)+ #expect(value.allImageSources.count == 2)+ try value.validatePhotoReferences()+ }+ }+ @Test func oldImageCodableDefaultsRemainAbsent() throws {+ let value = draft()+ let decoded = try JSONDecoder().decode(Draft.self, from: JSONEncoder().encode(value))+ #expect(decoded.receiptPages == nil)+ let evidence = SourceEvidence(id: uuid(1), sourceID: uuid(80), text: "Synthetic",+ boundingBox: .init(x: 0, y: 0, width: 1, height: 1))+ #expect(try JSONDecoder().decode(SourceEvidence.self, from: JSONEncoder().encode(evidence)).pageIndex == nil)+ }+}
diff --git a/Foodnotes/Packages/FoodnotesCore/Tests/FoodnotesDomainTests/PDFProvenanceTests.swift b/Foodnotes/Packages/FoodnotesCore/Tests/FoodnotesDomainTests/PDFProvenanceTests.swiftnew file mode 100644index 0000000..ab5ad91--- /dev/null+++ b/Foodnotes/Packages/FoodnotesCore/Tests/FoodnotesDomainTests/PDFProvenanceTests.swift@@ -0,0 +1,65 @@+import Foundation+import Testing+@testable import FoodnotesDomain++@Suite struct PDFProvenanceTests {+ @Test func provenanceValidationRejectsWrongSourcePageAndOccurrence() throws {+ let source = uuid(80), occurrence = uuid(30)+ let row = ReceiptRowAnchor(id: uuid(81), sourceID: source, pageIndex: 0,+ bounds: .init(x: 0.1, y: 0.5, width: 0.8, height: 0.02), occurrenceID: occurrence)+ let value = ReceiptProvenance(pages: [.init(sourceID: source, pageIndex: 0, status: .processed)], rows: [row])+ try value.validate(sourceID: source, occurrenceIDs: [occurrence])+ #expect(throws: DomainError.self) { try value.validate(sourceID: uuid(99), occurrenceIDs: [occurrence]) }+ #expect(throws: DomainError.self) { try value.validate(sourceID: source, occurrenceIDs: []) }+ var invalid = value; invalid.rows[0].pageIndex = 20+ #expect(throws: DomainError.self) { try invalid.validate(sourceID: source, occurrenceIDs: [occurrence]) }+ }+ @Test func generatedReidentificationPreservesSourceLocalAnchorsAndTombstones() throws {+ for seed in 1...32 {+ let source = uuid(80), occurrence = uuid(30), mapped = uuid(100 + seed), target = uuid(200 + seed)+ let row = ReceiptRowAnchor(id: uuid(81), sourceID: source, pageIndex: 0,+ bounds: .init(x: 0.1, y: 0.5, width: 0.8, height: 0.02), occurrenceID: occurrence, dismissed: true)+ let field = ReceiptFieldProvenance(fieldPath: "occurrences.\(occurrence).name", occurrenceID: occurrence,+ pageIndices: [0], rowIDs: [row.id])+ let value = ReceiptProvenance(pages: [.init(sourceID: source, pageIndex: 0, status: .processed)],+ rows: [row], fields: [field])+ let copy = value.reidentified(sourceID: target, occurrenceIDs: [occurrence: mapped])+ #expect(copy.rows[0].id == row.id && copy.rows[0].dismissed)+ #expect(copy.rows[0].occurrenceID == mapped && copy.pages[0].sourceID == target)+ #expect(copy.fields?.first?.occurrenceID == mapped)+ try copy.validate(sourceID: target, occurrenceIDs: [mapped])+ }+ }+}++extension PDFProvenanceTests {+ @Test func immutableDivergentProvenanceCannotMerge() throws {+ var first = document()+ first.assets = [AssetManifestEntry(assetID: uuid(80), address: nil, role: .source, mediaType: "application/pdf",+ byteLength: 128, sha256: String(repeating: "a", count: 64),+ receiptProvenance: .init(pages: [.init(sourceID: uuid(80), pageIndex: 0, status: .processed)], rows: []))]+ try first.validate()+ var other = first+ other.assets[0].receiptProvenance?.pages[0].status = .incomplete("different immutable origin")+ #expect(throws: DomainError.self) { try first.merging(other) }+ }+ @Test func conflictingRowAndEvidenceAnchorIdentityRejects() throws {+ let source = uuid(80), id = uuid(81)+ let row = ReceiptRowAnchor(id: id, sourceID: source, pageIndex: 0,+ bounds: .init(x: 0.1, y: 0.5, width: 0.8, height: 0.02), occurrenceID: uuid(30))+ let value = ReceiptProvenance(pages: [.init(sourceID: source, pageIndex: 0), .init(sourceID: source, pageIndex: 1)],+ rows: [row], evidence: [.init(id: id, sourceID: source, pageIndex: 1, bounds: row.bounds)])+ #expect(throws: DomainError.self) { try value.validate(sourceID: source, occurrenceIDs: [uuid(30)]) }+ }+}++extension PDFProvenanceTests {+ @Test func fieldCannotClaimAnotherOccurrenceRow() throws {+ let source = uuid(80), row = ReceiptRowAnchor(id: uuid(81), sourceID: uuid(80), pageIndex: 0,+ bounds: .init(x: 0.1, y: 0.5, width: 0.8, height: 0.02), occurrenceID: uuid(30))+ let field = ReceiptFieldProvenance(fieldPath: "occurrences.\(uuid(31)).name", occurrenceID: uuid(31),+ pageIndices: [0], rowIDs: [row.id])+ let value = ReceiptProvenance(pages: [.init(sourceID: source, pageIndex: 0)], rows: [row], fields: [field])+ #expect(throws: DomainError.self) { try value.validate(sourceID: source, occurrenceIDs: [uuid(30), uuid(31)]) }+ }+}
diff --git a/Foodnotes/Packages/FoodnotesCore/Tests/FoodnotesDomainTests/ReceiptPriceCalculationTests.swift b/Foodnotes/Packages/FoodnotesCore/Tests/FoodnotesDomainTests/ReceiptPriceCalculationTests.swiftnew file mode 100644index 0000000..7ef2e97--- /dev/null+++ b/Foodnotes/Packages/FoodnotesCore/Tests/FoodnotesDomainTests/ReceiptPriceCalculationTests.swift@@ -0,0 +1,48 @@+import Foundation+import Testing+@testable import FoodnotesDomain++@Suite struct ReceiptPriceCalculationTests {+ @Test func evidencedBasesKeepTaxAndQuantitySeparate() throws {+ let net = ReceiptPriceCalculation(basis: .netRowPlusGST, quantity: 3, amountCents: 1_200, gstCents: 120)+ let gross = ReceiptPriceCalculation(basis: .grossRow, quantity: 3, amountCents: 1_320)+ let printed = ReceiptPriceCalculation(basis: .printedGrossUnit, quantity: 3, amountCents: 440)+ for value in [net, gross, printed] { #expect(try value.unitPriceCents() == 440) }+ #expect(net.explanation.contains("12.00 net + AUD 1.20 GST"))+ #expect(printed.explanation.contains("including GST (printed)"))+ }+ @Test func centsRoundHalfUpOnlyAfterDivision() throws {+ for (gross, quantity, expected) in [(1_000, 3, 333), (1, 2, 1), (3, 2, 2), (0, 3, 0)] {+ let value = ReceiptPriceCalculation(basis: .grossRow, quantity: quantity, amountCents: Int64(gross))+ #expect(try value.unitPriceCents() == Int64(expected))+ }+ }+ @Test func absentGSTDoubleTaxAndUnboundedInputsReject() {+ let invalid = [ReceiptPriceCalculation(basis: .netRowPlusGST, quantity: 3, amountCents: 100),+ .init(basis: .grossRow, quantity: 3, amountCents: 100, gstCents: 10),+ .init(basis: .printedGrossUnit, quantity: 3, amountCents: 100, gstCents: 10),+ .init(basis: .grossRow, quantity: 0, amountCents: 100),+ .init(basis: .grossRow, quantity: -1, amountCents: 100),+ .init(basis: .grossRow, quantity: 10_000, amountCents: 100),+ .init(basis: .grossRow, quantity: 1, amountCents: Int64.max),+ .init(basis: .netRowPlusGST, quantity: 1, amountCents: 100, gstCents: -1)]+ for value in invalid { #expect(throws: DomainError.self) { try value.unitPriceCents() } }+ }+ @Test func optionalCalculationPreservesOldDataAndReidentifiesWithSource() throws {+ let source = uuid(80), occurrence = uuid(30), row = ReceiptRowAnchor(id: uuid(81), sourceID: uuid(80), pageIndex: 0,+ bounds: .init(x: 0.1, y: 0.5, width: 0.8, height: 0.02), occurrenceID: uuid(30))+ var field = ReceiptFieldProvenance(fieldPath: "occurrences.\(occurrence).price", occurrenceID: occurrence,+ pageIndices: [0], rowIDs: [row.id])+ let legacy = try JSONEncoder().encode(field)+ #expect(try JSONDecoder().decode(ReceiptFieldProvenance.self, from: legacy).priceCalculation == nil)+ field.priceCalculation = .init(basis: .netRowPlusGST, quantity: 3, amountCents: 1_200, gstCents: 120)+ let value = ReceiptProvenance(pages: [.init(sourceID: source, pageIndex: 0)], rows: [row], fields: [field])+ let decoded = try JSONDecoder().decode(ReceiptProvenance.self, from: JSONEncoder().encode(value))+ #expect(decoded == value)+ let copy = decoded.reidentified(sourceID: uuid(99), occurrenceIDs: [occurrence: uuid(31)])+ try copy.validate(sourceID: uuid(99), occurrenceIDs: [uuid(31)])+ #expect(copy.fields?.first?.priceCalculation == field.priceCalculation)+ var bad = decoded; bad.fields?[0].fieldPath = "occurrences.\(occurrence).name"+ #expect(throws: DomainError.self) { try bad.validate(sourceID: source, occurrenceIDs: [occurrence]) }+ }+}
diff --git a/Foodnotes/SharedCapture/OriginalHandoffPDFFile.swift b/Foodnotes/SharedCapture/OriginalHandoffPDFFile.swiftnew file mode 100644index 0000000..b1c9dbf--- /dev/null+++ b/Foodnotes/SharedCapture/OriginalHandoffPDFFile.swift@@ -0,0 +1,50 @@+import CaptureHandoff+import CoreGraphics+import CryptoKit+import Darwin+import Foundation++/// The extension validates the source document without rendering or rewriting it.+nonisolated enum OriginalHandoffPDFFile {+ static let maximumBytes = 32 * 1_024 * 1_024+ static func metadata(_ url: URL) throws -> OriginalHandoffImageFile.Metadata {+ let values = try url.resourceValues(forKeys: [.isRegularFileKey, .isSymbolicLinkKey, .fileSizeKey])+ guard url.isFileURL, values.isRegularFile == true, values.isSymbolicLink != true,+ let count = values.fileSize, count > 0, count <= maximumBytes else { throw HandoffError.invalidSource }+ let bytes = try Data(contentsOf: url)+ guard bytes.count == count, let provider = CGDataProvider(data: bytes as CFData),+ let document = CGPDFDocument(provider), !document.isEncrypted || document.isUnlocked,+ (1...20).contains(document.numberOfPages) else { throw HandoffError.invalidSource }+ return .init(mediaType: "application/pdf", length: Int64(bytes.count),+ digest: SHA256.hash(data: bytes).map { String(format: "%02x", $0) }.joined())+ }+ static func verify(_ envelope: SourceEnvelope, _ url: URL) throws {+ let value = try metadata(url)+ guard value.length == envelope.byteLength, value.digest == envelope.sha256,+ envelope.mediaType == value.mediaType else { throw HandoffError.invalidSource }+ }+ static func copyFile(_ input: URL, to output: URL, beforeVerification: () throws -> Void = {}) throws {+ let expected = try metadata(input)+ let descriptor = open(input.path, O_RDONLY | O_NOFOLLOW)+ guard descriptor >= 0 else { throw HandoffError.invalidSource }+ let handle = FileHandle(fileDescriptor: descriptor, closeOnDealloc: true)+ defer { try? handle.close() }+ guard FileManager.default.createFile(atPath: output.path, contents: nil) else { throw HandoffError.invalidSource }+ var succeeded = false+ defer { if !succeeded { try? FileManager.default.removeItem(at: output) } }+ let destination = try FileHandle(forWritingTo: output)+ defer { try? destination.close() }+ var length = 0+ while let bytes = try handle.read(upToCount: 1_048_576), !bytes.isEmpty {+ length += bytes.count+ guard length <= maximumBytes else { throw HandoffError.invalidSource }+ try destination.write(contentsOf: bytes)+ }+ try destination.synchronize()+ try beforeVerification()+ let actual = try metadata(output), current = try metadata(input)+ guard length == expected.length, actual.digest == expected.digest, current.digest == expected.digest,+ actual.length == expected.length, current.length == expected.length else { throw HandoffError.invalidSource }+ succeeded = true+ }+}
diff --git a/Foodnotes/SharedCapture/PDFHandoffInput.swift b/Foodnotes/SharedCapture/PDFHandoffInput.swiftnew file mode 100644index 0000000..6951ad5--- /dev/null+++ b/Foodnotes/SharedCapture/PDFHandoffInput.swift@@ -0,0 +1,73 @@+import CaptureHandoff+import Foundation+import UniformTypeIdentifiers++nonisolated struct RetainedHandoffInput: Sendable {+ let url: URL+ let metadata: OriginalHandoffImageFile.Metadata+}++@MainActor enum PDFHandoffInput {+ // Bound alias verification before any provider I/O; the accepted payload is still one PDF.+ static let maximumPDFProviders = 4+ static func prepare(_ items: [NSExtensionItem], directory: URL,+ pdfMetadata: @escaping @Sendable (URL) throws -> OriginalHandoffImageFile.Metadata = OriginalHandoffPDFFile.metadata)+ async throws -> RetainedHandoffInput {+ try Task.checkCancellation()+ let providers = items.flatMap { $0.attachments ?? [] }+ let pdfs = providers.filter { $0.hasItemConformingToTypeIdentifier(UTType.pdf.identifier) }+ if !pdfs.isEmpty { return try await receipt(pdfs, directory: directory, metadata: pdfMetadata) }+ let images = providers.compactMap { provider -> (NSItemProvider, String)? in+ let supported: [UTType] = [.png, .jpeg, .heic, .heif]+ let preferred = provider.registeredTypeIdentifiers.first { identifier in+ guard let type = UTType(identifier) else { return false }+ return supported.contains { type.conforms(to: $0) }+ }+ guard let type = preferred ?? (provider.registeredTypeIdentifiers.contains(UTType.image.identifier) ? UTType.image.identifier : nil)+ else { return nil }+ return (provider, type)+ }+ guard images.count == 1 else { throw HandoffError.invalidSource }+ let url = try await OriginalHandoffImageFile.copy(images[0].0, typeIdentifier: images[0].1, directory: directory)+ do { try Task.checkCancellation(); return try RetainedHandoffInput(url: url, metadata: OriginalHandoffImageFile.metadata(url)) } catch { try? FileManager.default.removeItem(at: url); throw error }+ }+ private static func receipt(_ providers: [NSItemProvider], directory: URL,+ metadata: @escaping @Sendable (URL) throws -> OriginalHandoffImageFile.Metadata)+ async throws -> RetainedHandoffInput {+ guard providers.count <= maximumPDFProviders else { throw HandoffError.invalidSource }+ var retained: RetainedHandoffInput?+ var succeeded = false+ defer { if !succeeded, let retained { try? FileManager.default.removeItem(at: retained.url) } }+ for provider in providers {+ try Task.checkCancellation()+ let url = try await copy(provider, directory: directory)+ do {+ let metadata = try await Task.detached(priority: .userInitiated) { try metadata(url) }.value+ try Task.checkCancellation()+ if let previous = retained {+ guard previous.metadata.digest == metadata.digest, previous.metadata.length == metadata.length else {+ throw HandoffError.invalidSource+ }+ try FileManager.default.removeItem(at: url)+ } else { retained = RetainedHandoffInput(url: url, metadata: metadata) }+ } catch { try? FileManager.default.removeItem(at: url); throw error }+ }+ guard let retained else { throw HandoffError.invalidSource }+ succeeded = true+ return retained+ }+ private static func copy(_ provider: NSItemProvider, directory: URL) async throws -> URL {+ try await withCheckedThrowingContinuation { continuation in+ provider.loadFileRepresentation(forTypeIdentifier: UTType.pdf.identifier) { url, error in+ do {+ guard error == nil, let url else { throw HandoffError.invalidSource }+ let staging = directory.appendingPathComponent("ProviderStaging")+ try FileManager.default.createDirectory(at: staging, withIntermediateDirectories: true)+ let owned = staging.appendingPathComponent(UUID().uuidString)+ try OriginalHandoffPDFFile.copyFile(url, to: owned)+ continuation.resume(returning: owned)+ } catch { continuation.resume(throwing: error) }+ }+ }+ }+}
diff --git a/scripts/check-startup-isolation.swift b/scripts/check-startup-isolation.swiftindex ab9eb05..6b5a89a 100644--- a/scripts/check-startup-isolation.swift+++ b/scripts/check-startup-isolation.swift@@ -8,7 +8,9 @@ import Foundation precondition(AppLaunchContext.classify(arguments: valid, environment: [:], testRuntime: false) == .synthetic(id)) precondition(AppLaunchContext.classify(arguments: valid + ["--service-diagnostics-fixture"], environment: [:], testRuntime: false) == .synthetic(id))- for args in [["app", "--service-diagnostics-fixture"], ["app", "--ui-testing"], ["app", "--test-store", token],+ precondition(AppLaunchContext.classify(arguments: valid + ["--pdf-receipt-fixture"], environment: [:],+ testRuntime: false) == .synthetic(id))+ for args in [["app", "--pdf-receipt-fixture"], ["app", "--service-diagnostics-fixture"], ["app", "--ui-testing"], ["app", "--test-store", token], ["app", "--ui-testing", "--test-store", "bad"], valid + ["-sync-harness"]] { precondition(AppLaunchContext.classify(arguments: args, environment: [:], testRuntime: false) == .blocked) }
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c33a777..bce8254 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,27 @@ ## [Unreleased] +### Added — confirmed meal deletion++- Delete a saved meal through an explicit native Cancel/Delete alert. Reuse transactional delete-wins presence and sync, preserve other visits, shared places and originals, and prevent a later same-epoch fetch from resurrecting a committed deletion.+- Bound PDF share alias verification to four providers before any provider loading, while retaining normal duplicate-byte and image intake behavior.++### Added — PDF receipt import (T-2488)++- Default verbose receipt provenance and calculation details to hidden behind the persistent Debug information setting in review and saved meals, keeping originals and actionable failures visible. Prefill recognised restaurant text without overwriting manual edits or selected place identities.++- Avoid redundant model generation for already-parsed invoice fields, retain honest raw-cap warnings for unresolved work and clear stale notices on successful retry. Complete-original local runs keep all fields and report processed; 462 native regressions pass.++- Apply the owner-confirmed GST-inclusive per-item price basis to explicit invoice rows: add row net/GST and divide by quantity with final half-up cent rounding; prefer printed inclusive unit prices and keep ambiguous inputs manual. Persist and display source calculations. Verified 108 host / 457 native cases, exact-original local trials and light/dark/AX3 renders.++- Read all rows of the supported itemised tax-invoice table using its explicit quantity and net-amount columns, preserve schema across continued pages and recover the declared trading-name merchant. Two exact-original local/model/draft trials and the 452-case native suite pass; updated phone acceptance remains pending.++- Correct ordinary multi-batch PDF receipts by sharing the bounded 20-call reading budget across pages. Read explicit refund-summary merchant/order details and comma-formatted Sept dates; keep financial adjustments out of dishes. Verified the supplied receipt locally, 446 native aggregate cases and six focused synthetic regressions; no updated installation yet.++- Share or import one PDF receipt up to 32 MiB/20 pages, using selectable text or scanned-page OCR to prefill existing editable meal, quantity and AUD price fields. Preserve original bytes, page evidence and manual corrections across interruption and retries.+- Keep PDFs separate from food photos and preserve their source associations through sync, versioned archives, restore and readable export. Existing image-only data remains supported; PDF use communicates the approved updated-installation prerequisite.+- Verified 102 package tests, 441 native tests and six distinct UI journeys with no remaining P1/P2 review findings. Detailed receipts and coverage limits are in `specs/pdf-receipt-import/implementation-receipts.md`; no physical-device installation, deployment, push or merge performed.+ ### Neutral Meh verdict — T-2489 - Publication review removed duplicate photo-removal controls, limited queued-photo verification to the selected publication off the writer, and rebuilt invalidated sync engines after fresh same-account admission. Four new regressions, the 383-test native aggregate and all five final UI journeys pass; publication evidence and retained limitations are in `specs/neutral-meh-verdict/publication.md`.
diff --git a/docs/testing/capture-inputs.md b/docs/testing/capture-inputs.mdindex 71ca14b..6e056ed 100644--- a/docs/testing/capture-inputs.md+++ b/docs/testing/capture-inputs.md@@ -21,3 +21,11 @@ Under Q18, physical camera/Photos/Files/screenshot/share behavior, actual two-ac The final native capture/resume gate passed 26 tests across `CaptureInputTests`, `CaptureReviewTests`, `HandoffCoordinatorTests` and `ManualJournalTests` (command exit 0). The earlier focused gate also passed repository handoff/extraction dependencies and the isolated restore-count bridge. All 75 package tests and lint/configuration/boundary checks passed. The paired entry assertions passed; final real Photos light, dark and AX3 journeys each ended `TEST SUCCEEDED`/exit 0. AX3 also corrected a dish and saved into unfinished detail without forcing an opinion sheet. Native renders were inspected and retained under `.build-logs/capture/renders/`; full native/UI logs and exact Makefile selections remain under `.build-logs/`. Two successful UI runs needed only their owned stalled `simctl diagnose` child stopped after test completion; Xcode then finalized successfully. No unrelated simulator/process was reset or stopped.++## PDF receipt import++The journal's **Import PDF receipt** action opens the native single-document Files picker. Share intake prefers one distinct PDF over decorative thumbnails, deduplicates alternate representations, and retains a version 2 handoff. Admission accepts one unlocked PDF with 1–20 pages and at most 32 MiB; failures retain the selected file without creating a draft. Before first admission, the user acknowledges that all installations accessing the library or restoring PDF archives must be updated.++PDF coverage lives in `PDFReceiptReaderTests`, `PDFRasterBoundsTests`, `PDFReceiptExtractionTests`, `PDFEvidenceCompletenessTests`, `PDFReceiptIntakeTests`, `PDFReceiptRetryTests`, `PDFReceiptEntryTests`, `PDFReceiptViewerTests`, `PDFReceiptRenderTests`, `PDFProvenanceStorageTests`, and host `PDFArchiveTests`. Tests use synthetic receipts only. The actual production model workload receipt is separate from injected integrated pipeline coverage; see `specs/pdf-receipt-import/implementation-receipts.md` for timing and memory attribution limits.++`PDFReceiptJourneyTests` verifies the native Files picker opens/cancels and that a synthetic durable share inbox survives restart before acknowledgement, then reaches correction/save/reopen/original-page viewing. Its DEBUG fixture requires a valid `--ui-testing --test-store UUID --pdf-receipt-fixture` launch and cannot open production services. This does not claim automation of an external share host or selection from a live Files provider. Actual provider payloads, extension activation, picked-URL scope/lifetime and save/reopen are covered by native framework/composition tests. Existing Photos UI journeys still require the labelled tracked synthetic image seeded into the dedicated simulator as described above.
diff --git a/specs/bugfixes/gst-inclusive-unit-price/report.md b/specs/bugfixes/gst-inclusive-unit-price/report.mdnew file mode 100644index 0000000..a1b7177--- /dev/null+++ b/specs/bugfixes/gst-inclusive-unit-price/report.md@@ -0,0 +1,23 @@+# GST-inclusive per-item receipt prices++The owner clarified that Foodnotes Price AUD means per item including GST, with quantity separate. This explicitly supersedes the previous restriction against division for grounded row amounts. The 09d0cef net-column candidate was held and never installed; its passing tests established copying, not the desired price meaning.++## Corrected behavior++For supported explicit net/GST/quantity columns, add the printed row net and row GST amounts in integer cents, then divide by the explicit quantity. Round only the final per-item result half up to cents. Inclusive row amounts are divided once; inclusive printed unit prices are retained without adding tax or dividing again. Where an explicit unit price accompanies row amounts, require consistency within final cent rounding. Never distribute order-level tax or fees; missing/ambiguous quantities, row tax or amount bases remain manual/incomplete.++Example using only synthetic values: quantity 3, net AUD 12.00 and row GST AUD 1.20 now produce AUD 4.40 each, replacing the held net-row value AUD 12.00. The exact private receipt's complete expected values were independently calculated before implementation and retained outside git.++Typed derivations are revalidated against the complete source row and header. Model candidates cannot inject or overwrite table prices. Optional receipt calculation provenance records basis, quantity and source input cents, survives save/reopen/reidentity/archive, and remains visible as a Receipt calculation with the supporting page. The review label clarifies Price each. Manual price/quantity edits remain intact and retain the historical source calculation rather than being silently recalculated.++## Verification++- Runtime red: the revised existing synthetic extraction/save tests failed with six expected price mismatches on the old net-row implementation.+- Host: 82 domain, 18 archive and 8 handoff cases pass (108 total), including final-only half-up rounding, no double tax/division, bounded inputs, optional legacy decoding, provenance remap, strict ZIP round-trip and unknown calculation-key rejection.+- Native: 33 XCTest + 424 Swift Testing cases pass (457 total). Coverage includes three complete item prices/provenance through extraction/review/save/reopen, ambiguous/missing/contradictory bases, repeated/continued rows and manual quantity/price correction across JSON resume/retry. The manual-edit case validates the saved-provenance projection; separate repository tests establish actual calculated-price persistence.+- Two complete-original native Mac trials used production PDFKit/Vision/FoundationModels, draft application and saved-provenance validation. All three names, quantities, GST-inclusive unit prices, restaurant and date match the independently calculated private expectations; each price retains its source inputs. This is not another physical-phone receipt acceptance result.+- Strict lint/configuration/boundaries/startup checks pass. Light/dark/AX3 native calculation-disclosure pixels were inspected and remain readable. Critic, persistence and archive reviews have no remaining P1/P2.++The generic image/non-table source-copy path is unchanged. No existing saved values are rewritten. Older records without optional calculation metadata still decode; updated readers accept prior PDF archives. Older strict v2 PDF test readers may reject new calculation-bearing archives under the already-approved current-build prerequisite.++Phone installation uses the existing authorised identity and preserves app data. Exact source/artifact/install/launch receipts are retained separately under `.build-logs/installations/`; real external sharing/import acceptance remains with the user. No push or merge is part of this correction.
diff --git a/specs/bugfixes/itemised-pdf-invoice-columns/report.md b/specs/bugfixes/itemised-pdf-invoice-columns/report.mdnew file mode 100644index 0000000..b0adfc2--- /dev/null+++ b/specs/bugfixes/itemised-pdf-invoice-columns/report.md@@ -0,0 +1,25 @@+# Itemised PDF invoice columns++The 09d0cef net-column candidate was held before installation. Its tax-exclusive line-total mapping is superseded by the owner-approved GST-inclusive per-item correction in `../gst-inclusive-unit-price/report.md`; the row/merchant fixes remain.++## Observed failure and reproduction++The installed 206f149 build imported a supplied itemised invoice with one dish, a GST amount in its Price AUD field, and no restaurant. Local reproduction of the complete original with production PDFKit/Vision/Foundation Models retained all three text rows. That model run returned three dishes, but selected GST amounts for all three prices and omitted the merchant. The phone's exact one-dish output was not reproduced; model-dependent dish count was not assumed stable.++Visual inspection confirmed an explicit table with Description, Qty, GST, GST Amount and Net amount columns. Flattening retained row text but discarded column meaning, and the table header landed in a different bounded model batch from the items. The generic model prompt and substring validator did not identify which monetary value was the item amount. The explicit invoice issuer/company/trading-name block also lacked a structured metadata reader.++## Resolution++- Carry the explicit date/description/quantity/GST/net-amount schema across bounded model batches and continued pages. Validate every row's copied name, quantity and printed net amount through the existing proposal boundary, retaining its page/row occurrence anchor.+- Protect table item fields from model overrides, including GST proposals. Totals remain excluded; malformed rows remain incomplete and cannot fall back to a guessed tax price. Identical dish names at separate rows remain separate occurrences.+- Keep schema across pagination and repeated invoice titles; only explicit closing financial totals end it. This closes the independent review's continued-page P2.+- Resolve the declared restaurant from the supported on-behalf-of legal-company/trading-name/locality block, with source/page/geometry checks and verbatim validation. No customer, invoice number or address is copied into the restaurant field.+- Preserve the 20-call document limit, existing chunk bounds, editable review, account fences, originals and retry/deletion protections. Prices copy the printed Net amount column; no tax or unit-price arithmetic.++## Verification++The initial synthetic actual-PDF regression failed at runtime with three issues. A separate continued-page review regression failed with two issues, then passed after schema retention was fixed. Final focused PDF/retry verification passed 31 cases in six suites. The full final native run passed 32 XCTest + 420 Swift Testing cases, including synthetic extraction → review → merchant confirmation → save → reopen, exact original bytes, all three quantities/net prices, malformed rows, repeated names and continued pages. Static checks and independent review are clear. Earlier lint and runtime failures remain retained as failed evidence.++Two exact-original local trials used production PDFKit/Vision/Foundation Models and actual DraftExtractionReview application with fresh row UUIDs. Both privately matched the complete expected set of three dish names, quantities and printed net amounts, plus merchant/date; no extra dishes, ordering or time were introduced. These are native Mac results, not another phone acceptance result. Verbose private material remains outside git; durable fixtures use synthetic names, identifiers and values. Redacted summary: `.build-logs/pdf-itemised-exact-receipt.json`.++The source correction has not been installed, pushed or merged. A fresh import is required for full phone acceptance: existing retry intentionally preserves populated/manual fields and does not silently reconstruct previously omitted or deleted items. Other invoice schemas still use the existing conservative model/manual path; this result establishes the supplied table layout, not universal PDF extraction.
diff --git a/specs/bugfixes/ordinary-pdf-receipt-budget/report.md b/specs/bugfixes/ordinary-pdf-receipt-budget/report.mdnew file mode 100644index 0000000..b678df2--- /dev/null+++ b/specs/bugfixes/ordinary-pdf-receipt-budget/report.md@@ -0,0 +1,28 @@+# Ordinary PDF receipt reading budget++## Observed failure++After the authorised T-2488 installation, a supplied two-page receipt showed both pages incomplete because they exceeded the automatic reading budget. Local reproduction using unchanged production PDFKit/Vision/model sources confirmed 19 and 17 assembled rows, requiring two existing-size batches each. Only one batch per page was submitted. Private input, screenshots and verbose model output remain outside the repository.++## Root cause and related defects++The implementation's latency policy reduced each page to one 12-line/1,800-byte batch. Normal receipts therefore lost evidence even when their entire document needed fewer than the measured 20 model calls. Prior one-batch and intentional-overflow fixtures did not establish ordinary multi-batch usability.++The supplied document is a refund summary without itemised dishes. Its explicit merchant and order-mode declarations should be suggestions, not invented dishes. Financial adjustments/payment rows were eligible item rows. The named-date grammar rejected a comma after the month, and Foundation's abbreviated-month parser required Sep rather than the common Sept spelling. Because invalid document dates are conservatively withheld, the remaining order time could not repair the date.++## Resolution++- Retain the maximum 20 model calls per document. Share remaining capacity fairly across remaining pages and carry unused allocation forward. All pages retain capacity; omitted evidence stays explicitly incomplete. No unbounded limit increase or warning suppression.+- Keep existing per-call bounds, page/byte admission, response limits, cancellation, source validation and retry/edit protections.+- Recognise explicit refund-summary merchant and Uber order-mode declarations through exact copied substrings and the existing validator. Unambiguous declarations outrank model guesses; conflicting declarations are withheld. Timestamped pickup/delivery tracking events do not define order mode.+- Exclude explicit financial summary/payment amounts from item roles, retaining ordinary quantity-led dishes. Accept comma-formatted named dates and Sept while preserving strict date validation.++## Verification++The original budget regression failed at runtime with four expected issues: page completeness, submitted evidence count, batch count and omitted late metadata. A subsequent intermediate run exposed the Sept parsing failure; it is retained as a failed run, not counted green. An earlier intermediate selector failed compilation while a new helper test preceded its implementation; it executed no tests.++Final focused extraction/image/date regression: 39 cases across seven suites passed. Static lint, configuration, boundaries and startup isolation passed. The full native refresh passed 32 XCTest and 414 Swift Testing cases. The final six-case suite also passed, including the subsequently added synthetic selectable-text PDF pipeline case; it is not additional raster/OCR fallback evidence. Five cases overlap the aggregate, so these counts must not be added as independent coverage.++The supplied original was processed locally with production PDFKit/Vision/Foundation Models sources. Both pages finished processed in four selected batches, yielding the explicit merchant, Delivery mode and matching order-completed date/time, with zero dish proposals. This is native Mac reproduction, not another physical-device acceptance result. No private receipt was committed or sent to an external model.++Independent review closed the maximum-work finding after the 20-call document ceiling was restored; no remaining P1/P2 source finding. Redacted summaries and native/static logs are retained locally under `.build-logs/pdf-ordinary-*`; verbose private input/output is outside the repository. No new installation, push or merge was performed for this correction.
diff --git a/specs/bugfixes/pdf-proposal-limit-status/report.md b/specs/bugfixes/pdf-proposal-limit-status/report.mdnew file mode 100644index 0000000..8d2e1bd--- /dev/null+++ b/specs/bugfixes/pdf-proposal-limit-status/report.md@@ -0,0 +1,22 @@+# PDF proposal-limit status++## Observed behavior++The user accepted all three dishes, quantities, GST-inclusive unit prices and restaurant on installed 74ebe4b, but the screenshot inspected by the parent showed Page 1 incomplete: Automatic proposal limit reached. Its exact phone-generated candidate text was not accessed. The actual retained Mac baseline did not hit the cap in that run; a controlled complete synthetic invoice plus 12 capped irrelevant candidates reproduced the same incomplete page while all fields were correct.++## Cause and correction++The PDF code counted model candidates before ignoring already-handled typed item fields and declared metadata. Redundant generation could therefore exhaust its output limit without contributing useful fields. Dates/time already have a separate parser. The model wrapper additionally discarded raw-limit information when invalid kinds/UUIDs failed conversion. Finally, the general manual-entry notice was not cleared for a new successful retry.++Plan model work by eligible remaining field kinds before requesting generation. Keep generic item proposals only on unprotected item rows; do not regenerate declared merchant/order metadata or system dates/time. Ordering still requires a source term and excludes fulfilment tracking events. The same allowed-kind rule gates returned proposals. Retain raw generation-limit metadata before decoding, cap accepted iteration, and deduplicate repeated candidates. A true cap on remaining work still produces the existing incomplete warning, even when every returned entry is rejected. This avoids irrelevant work rather than suppressing its warning after the fact.++Retry clears the previous in-memory notice only after its existing closed/reading/PDF guards pass. New failures, unmatched/dismissed rows, cancellation and persistence failures retain their warnings; source/session/generation/manual-edit protection is unchanged. Existing page/evidence/chunk/document limits remain conservative, including original chunk allocation before work filtering.++## Evidence++- Runtime red: two tests, three expected issues. Complete typed invoice fields remained correct while the page was incomplete; a successful retry retained its stale notice.+- Final native aggregate: 33 XCTest + 429 Swift Testing cases passed (462 total). Explicit tests retain a real cap that omits a fifth item and a raw cap with zero decoded candidates; uncapped duplicates/rejected/system proposals do not create extra fields. Actual synthetic PDF/review has processed page/no notice, and retry success/failure paths behave separately.+- Two full original production PDFKit/Vision/real-adapter/draft/provenance runs now report processed/no fallback, with identical complete fields and zero inference calls because the useful fields are handled deterministically. No private original or raw output is committed or uploaded to an external model. Local summary: `.build-logs/pdf-proposal-status-exact-receipt.json`.+- Strict lint, configuration, boundaries and startup checks pass. Independent critic and UI reviews have no P1/P2. Core package source is unchanged, so the prior 108 host pass remains applicable and was not repeated.++Phone installation/launch receipts are separate from PDF acceptance. An existing draft needs explicit Retry or a fresh import; already-saved receipt page metadata is not rewritten automatically. No real-library repair, push or merge is performed.
diff --git a/specs/pdf-receipt-import/assessment.md b/specs/pdf-receipt-import/assessment.mdnew file mode 100644index 0000000..d0fe964--- /dev/null+++ b/specs/pdf-receipt-import/assessment.md@@ -0,0 +1,41 @@+# T-2488 scope assessment — PDF receipt import++Status: full-spec route approved by the owner; requirements drafting/review authorised. Requirements approval, design, tasks and implementation remain gated.++## Authoritative request and baseline++Actual Transit ticket: **T-2488 — Share and import PDF receipts with meal-detail review**, Feature, Medium, Foodnotes (Idea at assessment; now Spec after route approval). Read the complete native ticket description without saving edits. It asks for share-extension and in-app PDF receipt input (including Uber Eats), image-equivalent extraction/review/confirmation semantics, per-item quantity and price prefill, and retention of user corrections on save. Text versus scanned PDFs and multi-page handling are explicitly unresolved; no parser/OCR/page-selection/combination approach is locked in.++This assessment starts on branch `T-2488/pdf-receipt-import` in an isolated worktree from verified GitHub main `0128d2c0158fa69a754edceea31bb85a4d99e5c6`, after accepted Foodnotes PR #1 merged. Original feature branches and dirty local main remain preserved. No AGENTS.md or repository-local .agents skills were found. The current Transit and Starwave creating-spec skills and development guidance were read. Relevant recalled knowledge: share-extension activation must admit the representations actually consumed and should be tested against real item-provider payload shapes, including mixed attachments; this does not establish a PDF implementation.++## Verified existing behavior to reuse++- [ShareViewController](../../Foodnotes/FoodnotesShare/ShareViewController.swift) chooses image representations. [Share activation](../../Foodnotes/Config/FoodnotesShare-Info.plist) admits one image. It does not advertise PDF input.+- [NativeImagePicker](../../Foodnotes/Foodnotes/Features/Capture/NativeImagePicker.swift) uses a single-image Photos picker or camera. [AppCapture](../../Foodnotes/Foodnotes/App/AppCapture.swift) admits camera/Photos routes. No current Files/PDF picker or PDF parser was found.+- [FileSourceHandoff](../../Foodnotes/Packages/FoodnotesCore/Sources/CaptureHandoff/FileSourceHandoff.swift) validates a schema-version-1 envelope, 32 MiB maximum and PNG/JPEG/HEIC/HEIF media types. PDF cannot be passed through unchanged by merely adding a share-sheet option.+- [OriginalCaptureReader and VisionCaptureOCR](../../Foodnotes/Foodnotes/Services/Capture/Extraction/OCR.swift) verify original bytes, require image media types and perform bounded image OCR. [OnDeviceCaptureExtractor](../../Foodnotes/Foodnotes/Services/Capture/Extraction/OnDeviceCaptureExtractor.swift) then shares evidence validation, model proposals, cancellation and manual fallback. These semantics should remain common.+- Quantity and price already exist end to end: [model prompts](../../Foodnotes/Foodnotes/Services/Capture/Extraction/FoundationCaptureModel.swift), [proposal validation](../../Foodnotes/Foodnotes/Services/Capture/Extraction/ProposalValidation.swift), [DraftExtractionReview](../../Foodnotes/Foodnotes/Services/Capture/Extraction/ExtractionReview.swift), editable Quantity/Price AUD fields in [ManualReviewView](../../Foodnotes/Foodnotes/Features/Capture/ManualReviewView.swift), and typed persistence in [DraftMaterializer](../../Foodnotes/Foodnotes/Persistence/DraftMaterializer.swift). [Synthetic corpus tests](../../Foodnotes/FoodnotesTests/CaptureExtraction/ExtractionCorpusTests.swift) assert per-item quantities/prices. There is no established general image price/quantity gap to duplicate.+- [SourceEvidence](../../Foodnotes/Packages/FoodnotesCore/Sources/FoodnotesDomain/CaptureContracts.swift) identifies a source and bounding box but has no PDF page field. [CaptureReviewModel](../../Foodnotes/Foodnotes/Services/Capture/CaptureReviewModel.swift) consumes image-source streams with draft/account/generation guards. Multi-page evidence identity/order needs an explicit contract.+- Original-source retention, viewing, sync, archive/restore and readable export must be assessed if PDF becomes a durable source type. Existing [archive image validation](../../Foodnotes/Packages/FoodnotesCore/Sources/FoodnotesArchives/ArchiveResources.swift) and [image-path media mapping](../../Foodnotes/Packages/FoodnotesCore/Sources/FoodnotesArchives/ArchiveValidation.swift) are image-specific. No storage migration or representation choice is made by this assessment.++## Routing decision++Recommend **full spec**, kept proportionate to this feature. This is driven by decisions rather than file count:++1. **User-owned ambiguity fires.** The ticket deliberately leaves text/scanned and multi-page behavior open. Processing all pages as one receipt, page selection, and handling partially unreadable pages produce materially different user experiences. Limits and recoverable errors also need requirements.+2. **Persisted/shared compatibility trigger needs resolution.** If the original PDF is retained as a source, current handoff and archive readers reject its media type. Original retention and older-build compatibility must be agreed before changing those contracts. Raster-only derivatives versus original-plus-derived-pages are not interchangeable preservation policies.+3. **Central architectural choice is open.** Embedded text extraction, page rendering/OCR, or a mixed strategy affect evidence provenance and combined-page review. Source inspection does not settle the correct trade-off; the design must preserve existing evidence-backed/no-invention and manual-edit protections.++A smolspec is therefore not recommended now. No PDFKit/OCR strategy, page limit, page picker, storage schema or migration is preselected.++## Bounded intended scope++PDF intake through sharing and an appropriate in-app receipt import entry, safe immutable handoff, extraction into existing meal/item review fields, item-to-evidence association across approved PDF page behavior, correction/save semantics, cancellation/manual fallback and compatible original retention/export/restore as required by the chosen policy. Preserve existing camera/Photos behavior, blank/unknown values, AUD price handling, quantity semantics, account/library fences and source-byte integrity.++Exclude general price/quantity redesign, unrelated meal editing, delivery-service APIs, PDF export, cloud OCR services, installation/deployment and real-library mutation. Future test planning should cover synthetic text/scanned/multi-page/mixed/corrupt/protected cases, mixed share-provider payloads, retained user corrections and original-byte preservation. Real Uber Eats layout acceptance would require a deliberately supplied/de-identified fixture later; no private receipt contents were accessed here.++## Verification and next gate++Assessment only: actual ticket read, repository/source/spec inspection and recall-knowledge lookup. No application code changed; no PDF tests, builds or native jobs run. Existing image behavior is source/test evidence, not a claim that PDFs already work.++**Route decision resolved:** owner approved the full-spec route. Requirements are the current stage; their proposed policies require owner approval before design.
diff --git a/specs/pdf-receipt-import/decision_log.md b/specs/pdf-receipt-import/decision_log.mdnew file mode 100644index 0000000..c5b4c2d--- /dev/null+++ b/specs/pdf-receipt-import/decision_log.md@@ -0,0 +1,124 @@+# PDF receipt import — decisions++Current stage: the installed PDF-import/debug/prefill build is accepted. Meal deletion is authorised as an amendment before PR Pilot merge. Feature publication and reviewed PR merge are authorised; no further phone installation is authorised.++## Quick Decisions++| Decision | State and rationale |+| --- | --- |+| Use full-spec workflow | Approved by owner; route approval does not approve requirements or implementation. Transit was advanced to Spec with the route-approval comment; final UI state verified. |+| Retain feature name `pdf-receipt-import` | Existing assessment folder/branch explicitly named in the parent's continuation instruction; no redundant naming question. Owner may override it. |+| Support text, scanned and mixed-page PDFs | Explicit parent scope: cover text and scanned PDFs and multi-page handling. Extraction mechanism remains a design decision. |+| Preserve original PDF bytes | Explicit parent scope; page derivatives cannot replace the original. |+| Reuse image receipt quantity/price flow | Actual ticket and assessment establish existing prompts, validation, review fields, manual-edit fences and persistence. |+| Process all pages as one receipt | Approved with requirements; page selection excluded. Multiple receipts in one document are outside this feature. |+| Input limits: one PDF, 32 MiB, 20 pages | Approved with requirements. 32 MiB matches current handoff byte limit; 20 pages is a proposed explicit receipt bound, not a measured performance claim. No new page/file-combination UI proposed. |+| Updated-installations policy for PDF content | Approved with requirements; older image-only readers are outside the supported new-PDF contract. Exact format/version design remains gated. |+| Protected/corrupt PDFs | Approved rejection with explanation; password entry/unlocking excluded. Already admitted originals survive extraction failures. |++General questions were asked asynchronously about all-pages versus page selection and updated-installation versus older-build compatibility. No unreceived answer is treated as approval. The requirements packet labels proposals explicitly for the owner gate.++## Owner decisions++The requirements approval includes all-pages processing, one-PDF/32-MiB/20-page limits and updated-installation prerequisite. The next decision is design approval; task planning and implementation remain gated.++## Review clarifications (requirements remain proposed)++- Document-open/validation failure rejects before a new draft; an admitted document with page-level extraction failure or no usable evidence retains its original and manual-review draft. This boundary is proposed for owner approval.+- Every admitted page is accounted for as processed or incomplete; processing completion does not promise recognition of every field. Page provenance and legitimate duplicate item preservation are explicit.+- Compatibility proposal is a communicated, user-managed update prerequisite, not cross-device version enforcement. Older-build PDF access is explicitly unsupported; existing image-only data remains supported. Owner must accept or change this policy.+- Proposed limits are inclusive and count distinct PDFs, not representations or decorative attachments. Supported durable operations and the resulting readable-export artifact are stated without choosing formats or implementation.++- Peer clarifications: original document access preserves bytes while non-displayable pages receive identifiable unavailable-page status; page completion/incompleteness is explicitly user-visible. These clarify the proposed retained-draft failure policy without selecting an implementation.++- Phone delivery: attempted existing-helper transfer was denied by automatic approval review before execution for lack of explicit payload/destination authorisation. No transfer occurred; explicit permission to send these five spec files to `iphone181` has been requested. This is independent of requirements approval.+++## Requirements approval — 2026-10-27++Arjen: “For the foodnotes PDF ticket, requirements are approved. Continue with design”. This approves the complete requirements and proposed boundaries above; prior pending/proposed entries are historical. Requirements phone transfer succeeded once through the established helper to iphone181 (exit 0). New design payload delivery is not authorised by that transfer approval.++## Design ADR 1 — typed originals, compatible additive records++Use the existing SourceImage value as the source-byte descriptor, with its truthful application/pdf media type; its historical Swift name is not a content discriminator. Add a centralized original-media policy and keep food-photo eligibility strictly image-only. This avoids renaming every sync/storage protocol while requiring audited media dispatch at actual consumers. PDF-bearing archives and handoff use version 2; readers accept image-only version 1. No schema rewrite of existing originals or portable locators.++## Design ADR 2 — page extraction and bounded work++Use PDFKit selectable-text evidence first, with Vision raster OCR on pages without usable text. Do not concatenate native and OCR text for the same page: duplicate item proposals would be likely. Page-qualified evidence, document-wide reconciliation and explicit incomplete states are required; the existing global 24-chunk truncation cannot silently mark a PDF complete. Render sequentially at a maximum 2048-pixel long edge/4 megapixels, with cancellation between pages/chunks. Text-rich pages containing meaningful unrepresented graphics remain a recognition limitation, reported without promising every field.++## Design quick decisions++| Decision | Outcome |+| --- | --- |+| UI baseline | Existing ManualReviewView source controls, fallback notices and Quantity/Price AUD fields; add page status and a PDF source viewer, no photo-framing controls for PDFs. |+| New design review gate | Owner must approve design before task planning. New packet is prepared locally, not sent automatically. |++## Design ADR 3 — preserve page links beyond drafts++Store compact immutable source provenance in the saved source manifest and archive asset record, not only the temporary evidence archive. Page links must survive draft deletion and durable operations. Explicit row assembly bridges PDF columns into the existing single-evidence-line validator; unsafe associations are withheld. Full text OCR archives are not added as another synced asset. Metadata resource limits remain enforced without dropping page mappings.++| Minor decision | Outcome |+| --- | --- |+| Durable source aggregates | Introduce allOriginalSources/replaceOriginalLocators for publication, locator rebasing and cleanup; reserve allImageSources for image UI. |+| Design technical preference | Asked owner asynchronously about native text first vs OCR every page. No reply received; recommended native-text-first plan is proposed for the design approval gate, not treated as owner approval. |++## Design ADR 4 — retry identity distinct from OCR text++Canonical PDF row/occurrence identity is persisted independently of raw evidence hashes. Geometry-unique retry matching preserves edited paths; ambiguous split/merge/unmatched retry rows need explicit confirmation. Dismissal tombstones prevent resurrection. This extends the current image review apply path with PDF row admission rather than relying on its missing-name/version-zero shortcut.++## Design approval and task delivery — 2026-10-27++Arjen: “Design approved. Use send-Md-to-phone to send me the tasks file once done with it. Don't bother with a review packet, just the tasks”. Design7023a6c is approved. Prepare and internally review tasks; transfer only tasks.md through the established helper to iphone181. No extra user-facing review packet and no application implementation. Earlier design packet transfer completed with exit0; no broader standing transfer rule is inferred.++## Task-plan review and delivery++The plan contains 16 pending coding tasks in eight adjacent red/green pairs and one shared-file stream; all 15 criteria are covered. Rune list/stream parsing, dependency acyclicity and risk-first placement were verified. Critic and two independent native peer perspectives closed all findings, including model-workload gating in tasks7/8 and truthful injected versus actual-model evidence. External Codex/Kiro tools were unavailable; the documented fallback was used. No application tests/builds were run for this documentation-only stage.++Ran send-md-to-phone unchanged from this worktree, with exactly tasks.md selected by its normal uncommitted-file workflow. It completed with exit0, delivering pdf-receipt-import-tasks.md to established iphone181. No new review packet was created or sent. Owner task approval remains pending; no implementation is authorised by design or transfer approval.++## Implementation approval — 2026-10-27++Arjen: “Implement it”, replying to the delivered reviewed 16-task plan. Execute the approved red/green plan in T-2488/pdf-receipt-import; feature commits allowed, no install, deployment or merge without subsequent approval. Current fetched origin/main remains0128d2c, exact base of the specification commits. Reuse worktree .build/DerivedData/.build-logs; coordinate only actual simulator/screen conflicts.++## Implementation resource policy and completion — 2026-10-27++The initial per-page allocation below is superseded by the acceptance correction recorded next; its actual-model measurement remains evidence for the unchanged 20-call document ceiling, not for an expanded workload.++The implementation keeps the production model's ordinary 700-token/12-proposal budget. PDF processing submits at most one existing-size evidence batch per admitted page (at most 20 calls), considers all pages, and explicitly marks omitted evidence or failed work incomplete for manual completion/retry. It does not lower every receipt to three proposals. This applies the approved bounded-work/incomplete fallback policy; the helper's preliminary 295-second watchdog is not a product deadline. The final actual production-wrapper measurement completed 20 calls in 357.599 seconds, with actual cancellation in 0.106 seconds. Integrated renderer/OCR tests use an injected model and are reported separately; OS inference-service memory could not be attributed to the wrapper process.++## Ordinary-receipt acceptance correction — 2026-10-27++The first user-supplied two-page receipt reproduced an overly restrictive allocation: 19/17 assembled rows required two existing-size batches each, but only the first batch ran per page. Keep the measured maximum of 20 model calls per document and divide remaining capacity fairly across remaining pages, carrying unused allocations forward. Per-call 12-line/1,800-byte bounds, page admission, cancellation and truthful omission states remain intact. This avoids both truncating ordinary short receipts and expanding maximum work to 480 calls.++The supplied document is a refund summary without itemised dishes. Recognise its explicit merchant/order-mode declarations through verbatim validated metadata suggestions; exclude financial adjustments from dish rows. Accept comma-separated named-month dates including the common Sept abbreviation without weakening strict calendar validation. Private source bytes and diagnostic text stay outside the repository; durable regression fixtures are synthetic. No further installation, publication or merge is authorised by this diagnosis.++Document-level repeated unknown top headings are classified before item wrapping only with matching text/source/geometry on distinct pages and an independently named quantity-led item immediately below. Proven headings remain metadata evidence; legitimate repeated priced rows and wrapped item names remain distinct. All bounded top evidence participates.++All 16 implementation tasks are complete. Final application/test source is 495e526; final native aggregate passed 32 XCTest and 409 SwiftTesting cases, with 102 unchanged-package host cases and six distinct selected UI journeys passing. Independent milestone/UI/final critic findings are closed. See implementation-receipts.md for precise scopes, commands and retained failures. No physical-device installation, deployment, merge or push is authorized or performed.+++## GST-inclusive per-item decision and implementation authority — 2026-10-27++Arjen: “GST inclusive pricing. And my understanding of the pricing field in foodnotes is that its per item pricing, so we should keep that”. The parent explicitly authorised derivation from row net + row GST divided by explicit quantity, printed inclusive unit-price preference, rounding/provenance tests, exact-original actual-pipeline verification and updating the same authorised phone test installation after review. This supersedes the old no-division rule for these grounded inputs. It does not authorise global fee/tax allocation, existing-data rewrites, push or merge.++The held 09d0cef candidate copied printed tax-exclusive row totals. Those tests proved column copying but did not establish desired price meaning; it was not installed. The approved implementation now uses bounded integer cents and final half-up division, records optional receipt calculation metadata and clarifies Price each in review. Existing generic image/non-table copying remains unchanged; detected ambiguous table bases stay manual. Archive/read and source-provenance compatibility are verified; the single-device current-build policy remains applicable.++## Acceptance UI refinement — 2026-10-27++Arjen confirmed the corrected import and requested a persistent Settings “Debug information” toggle, off by default, covering both review and saved meals. Verbose per-field supporting pages, calculation traces, page statuses/internal reasons and the photo-reference diagnostic are display-gated; provenance remains stored. Original receipt controls, progress, concise actionable incomplete-reading notices, retry and persistence errors remain available normally. The preference is device-local and shared by both surfaces.++Recognised restaurant text now prefills the actual editable place field instead of requiring “Use suggestion”. This supersedes the prior place-suggestion confirmation rule for unselected text only. Ordering-method suggestions still require confirmation. Name extraction does not infer an existing place identity: explicit place/order selections and manual edits, including clears, are protected by existing edit/generation guards plus confirmed-identity checks. New imports or an explicitly requested retry apply the new prefill behavior; existing saved meals are not rewritten.++The parent authorises review, regression/visual verification and updating the same phone test build in place, preserving data/identity. No push or merge is authorised.++## Accepted-build publication and meal deletion amendment — 2026-10-28++Arjen accepted the installed PDF-import/debug/prefill build and authorised PR Pilot merge, then explicitly requested meal deletion before merge. Hold publication merge until the deletion amendment is implemented, tested and independently reviewed. No additional phone install or real-meal deletion is authorised.++The existing Meal.isPresent field, delete-wins presence merge, replaceDocument mutation/outbox, snapshot/projection filters and revision/session/epoch guards settle the approach. Add a native destructive Delete meal action with explicit confirmation; cancel does nothing. Stamp only that meal's presence false through the ordinary transactional replacement path, retain immutable originals/references for safe sync and existing asset lifetime rules, and preserve shared places/dishes/other meals. Shared deletion is visibly described as synchronised to others. Do not introduce physical file deletion, profile deletion, a persisted schema or a new wire command.++Capture the exact document/session at confirmation; refuse stale, changed, frozen/moving or unavailable meals. Refresh existing projections after success so detail navigation returns to the journal, and retain visible errors on failure. Verify cancellation, stale/session/write guards, disk reopen, other-meal/profile/shared-byte preservation and ordinary sync tombstone publication/delete-wins conflict handling with synthetic fixtures, plus the actual confirmation/list/detail UI. This is an incremental implementation amendment under the user's explicit request; no unrelated feature stack is included.++## Pre-push resource review correction — 2026-10-28++Independent efficiency review found that arbitrarily many PDF attachment providers could each be copied/validated before identical-byte deduplication. Bound request fan-in to four conforming PDF providers, checked before loading any provider. This preserves ordinary duplicate representations and decorative thumbnail behavior, with one admitted receipt and unchanged 32 MiB/20-page per-original limits; larger provider inventories reject with the existing choose-one-file guidance. This is a bounded intake safeguard, not support for multiple receipts. Synthetic actual-loader overflow and four-alias acceptance regressions establish the boundary. Private receipts remain outside git and review uploads.
diff --git a/specs/pdf-receipt-import/design-review-packet.md b/specs/pdf-receipt-import/design-review-packet.mdnew file mode 100644index 0000000..f21636f--- /dev/null+++ b/specs/pdf-receipt-import/design-review-packet.md@@ -0,0 +1,154 @@+# T-2488 PDF receipt import — design review packet++Requirements approved; design awaiting approval. This packet contains the complete proposed design and review result. No application implementation, new build or phone transfer occurred.++## Decisions for review++- Preserve one original PDF, with all pages contributing to one receipt; retain approved one-PDF/32-MiB/20-page boundaries.+- Prefer usable selectable text, OCR fallback for pages without usable receipt rows. Do not merge duplicate native/OCR text.+- Keep page provenance after saving and through sync/archive; reject PDFs as food-photo selections.+- Keep retries attached to existing item identities, including partial/cancelled work; ambiguous changes require confirmation and deleted items stay deleted.+- Use explicitly versioned PDF-bearing archives/handoff while retaining old image-only support. The approved user-managed update policy applies.++The technical choice question about text-first versus OCR-every-page received no answer; text-first remains the recommended plan for this approval. No claim of perfect PDF recognition or measured performance is made.++## Complete proposed design++# PDF receipt import — design (T-2488)++Status: design proposed; requirements approved. Source baseline: merged main `0128d2c`.++## Architecture++A PDF is one immutable receipt source, never twenty photo assets. PDFKit admission and page extraction live in the iOS application; portable domain/handoff contracts carry media identity, page provenance and status without importing PDFKit. Existing account admission, atomic asset publication and review/save fences remain authoritative.++### Pattern-extension audit++The table groups matching SourceImage, image-media and ArchiveIO.image consumers by responsibility; [parity-audit.md](parity-audit.md) lists the individual files and durable aggregate replacements. Implementation must repeat the search and account for new references.++| Existing consumer / hook | Needs equivalent | PDF contract |+| --- | --- | --- |+| ShareViewController; FoodnotesShare-Info.plist; SharedCapture/OriginalHandoffImageFile; SourceEnvelope; FileSourceHandoff | Yes | PDF provider selection and activation; representation deduplication; bounded atomic original publication; image v1/PDF v2 envelope decoding. |+| NativeImagePicker; AppCapture.beginCapture | Yes | Separate Files import action using `.pdf`, single selection, security-scoped URL copied while access is held; camera/Photos unchanged. |+| CaptureContracts; DraftPhotos; Validation; CaptureRoute | Yes | Add Files origin/route and optional page state; retain legacy SourceImage descriptor with application/pdf; all-source validation separate from image-only photo membership/framing. |+| OriginalCaptureReader; VisionCaptureOCR; ExtractionTypes; OnDeviceCaptureExtractor; CaptureReviewModel | Yes | Media dispatch, PDF page events and document aggregation; preserve image extraction path and per-draft generation/edit-version checks. |+| FoundationCaptureModel; ProposalValidation; ExtractionReview | Yes | Page-qualified evidence and stable item anchors, bounded chunks and document reconciliation; same source-backed quantity/price validation and manual protection. |+| ManualReviewView; DraftPhotoFields; source-original presentation; MealCaptureOriginals | Yes | PDF page viewer and status summary; existing review fields/notices; no PDF photo selection/crop/framing or UIImage decoding. |+| LocalAssetPayload; DraftMaterializer; RepositoryMutation; RepositoryStorage; AssetIdentity; AccountTransitionAuthority | Yes | PDF original admission/manifest/association through existing asset transactions and locator resolver; photo IDs reject PDF; no new absolute persisted paths. |+| SyncContracts; AppleCloudCodec; CloudPublisher; SharingContracts; TransferCapture | Yes | Carry truthful PDF media metadata and exact bytes through current typed integrity/ownership validation and lifecycle transport. Image-named carriers are not image decoders. |+| ArchiveResources; ArchiveValidation; ArchiveZIPCodec; ArchiveGraphMapper/Selection; scratch/restore/import/export services | Yes | Media-dispatched original validation, documents/<asset-id>.pdf entries, version-aware graph validation and original associations on restore/recovery. |+| MarkdownExporter; MarkdownText | Yes | Linked original in documents/, meal-identifiable receipt link, no image embedding; retain existing images/ paths. |+| SavedMealContentEditor; photo editor/framing; thumbnails | No parallel PDF photo UI | Filter by image eligibility; receipt source access uses PDF viewer. |+| Existing image corpus, archive and handoff fixtures | No replacement | Retain v1 fixtures and image semantics, add PDF suites alongside. |++## Components and interfaces++These are proposed additions/extensions, not existing APIs.++- `Services/Capture/PDFReceiptAdmission.swift`: preflight owned temporary bytes, verify regular file/no symlink, length/digest and PDF open, unlocked state, nonzero page count ≤20. Reject before publishing a draft. Recheck copied bytes; a provider URL changing during copy must not change the admitted document unnoticed.+- `Services/Capture/Extraction/PDFReceiptEvidence.swift`: one serial worker owns its PDFDocument/PDFPage objects; no non-Sendable PDFKit objects cross tasks. `collect(source, generation) -> page events` emits ordered text/evidence/status. PDF work and hashing run off the main actor. Temporary render buffers are released after each page; derivatives never enter source manifests.+- `Services/Capture/ReceiptSourceViewer.swift`: read-only PDFKit view with page navigation and unavailable-page labels. Open only a verified local source resolved through existing typed readers; never rewrite the PDF. Existing source buttons present this viewer by media dispatch.+- Central `OriginalMedia` policy in FoodnotesCore distinguishes receipt PDF from supported images, supplies suffix/media validation, and exposes `isFoodPhoto`. Use CoreGraphics CGPDFDocument for archive-package PDF-open/lock/page-count validation on supported iOS/macOS targets; PDFKit extraction/viewing stays in the app. SharedCapture adds a PDF counterpart to OriginalHandoffImageFile for the extension.++### Admission and handoff++Provider inventory prefers a PDF representation over its thumbnail and counts distinct PDF attachment providers; alternate type representations from one provider count once. Multiple providers resolving to identical original bytes count once after bounded hash comparison; different PDFs reject. Ignore unrelated decorative thumbnails only for an accepted PDF payload. Activation admits PDF/image combinations; runtime enforces the actual one-document/image rules. No URL fetching or network PDF loading is added.++The share extension bounds copy/validation and publishes an envelope/original atomically before completing. Main app revalidates before draft creation and acknowledges only durable admission; queued unsupported/unassigned input remains recoverable. Files import uses the same service and destination selection. Persist a per-install compatibility acknowledgement before first PDF draft; explain updates are required for other installations/restores, with no claim to enforce device versions.++### Evidence and review++Extend SourceEvidence with optional `pageIndex` (zero-based, absent for old images); normalize rectangles to upright page crop bounds after rotation. Native PDF selections provide text/geometry; sanitize control characters and reject empty/invalid selections. Native text is usable only when nonempty bounded selections assemble into plausible receipt rows; selectable headings alone do not qualify. If native text is absent or only headings/invalid geometry/ambiguous reading order is found, render that page at bounded resolution and pass its CGImage to existing Vision request configuration. Raw fragment IDs include source ID, page index, method/parser version, line position and text. Canonical row IDs are separate durable identities, not hashes of mutable text or parser version. Retry replacement is generation-scoped, never an append of duplicate evidence.++Before model proposals, a new `PDFReceiptRows` adapter groups same-baseline text fragments into page-local rows using normalized vertical overlap and left-to-right column order; wrapped names join only when indentation/vertical adjacency yields one unambiguous item row. Each assembled row retains its original fragment/page bounds and receives a persisted page-qualified row anchor mapped to one occurrence identity. Use that persisted row anchor as the common evidence ID passed to the existing single-line candidate validator so dish, quantity and price share the same occurrence ID. Ambiguous column/row associations produce no item-number proposal, not cross-row guesses. A bounded receipt-role classifier marks header, item, subtotal/total and unknown rows using explicit total/header labels, layout and repeated top-of-page geometry; excluded rows cannot generate dish candidates. Ambiguous roles remain manual review. Tests must include separate quantity/price columns and wrapped items, not only synthetic one-line receipts.++Process page order, then reconcile receipt metadata across the whole document. Keep page boundaries in model input, assign occurrence identity by supporting evidence anchor, not dish name, and sort by first supporting page/line. Merge duplicate proposals only for the same supporting anchors; identical names at distinct anchors remain separate. Identify repeated headers/carried totals through receipt-role validation, never a global text-name deduplication. Conflicting metadata or unsupported quantity/price proposals stay unconfirmed/blank; no dividing totals into unit prices.++Replace the PDF path's document-global 24-chunk cap with per-page bounded batches and page-aware document reconciliation. Cap each page to 500 evidence lines and 24 existing-size model chunks; any omitted evidence, failed model batch, cancellation, unsupported capability or failed render marks that page incomplete. Record exact page states (`pending`, `processing`, `processed`, `incomplete(reason)`) durably with the draft. “Processed” requires all admitted evidence batches handled, including explicit no-text result; it never promises every visible field was recognised. A final summary lists all pages and failed/unprocessed pages. Persist the PDF row-to-occurrence registry with draft page state. On retry, match rows against the prior page-local geometry/fragment footprint before applying proposals, retaining canonical row and occurrence IDs even when OCR text/parser changes. Match only a unique compatible footprint; splits, merges, unmatched new rows on any previously attempted page with a row registry (including incomplete/cancelled pages) and deleted/manual-dismissed rows require explicit confirmation, never a new missing-name path at editVersion zero. Only first processing of a never-attempted pending page without registry entries or dismissal tombstones can create rows normally. Retain dismissal tombstones so retry cannot resurrect removed items. Retrying preserves edit versions and never overwrites manual fields; PDF reconciliation reuses the current proposal validator and DraftExtractionReview apply path.++## Data and durable operations++Add optional PDF page-state/provenance fields to draft/evidence Codable payloads, decoding absence as existing image behavior. Before DraftMaterializer removes a draft, copy immutable `receiptProvenance` into the source AssetManifestEntry: page count/states plus accepted proposal field/occurrence IDs mapped to supporting page indices and row anchors. This records extraction origin rather than claiming later user edits are still verbatim PDF text. Full OCR text need not be synced. Extend StoredAsset encoding, typed manifest validation, ArchiveAssetRecord and both ArchiveRecordsMapping directions to preserve it; account rehome/remapping rewrites occurrence IDs with existing document mappings, page/row anchors stay source-local. All manifest-copy sites preserve this optional metadata, including TransferCapture and lifecycle transfers. Source provenance is immutable after initial materialization; divergent copies for the same source identity fail integrity validation rather than merge by last writer. Validate PDF role/source membership, page bounds, referenced occurrence IDs (including retained tombstoned occurrences) and existing payload-size limits before transactional save/import; oversized metadata yields an actionable save failure with draft retained, never silent truncation. Existing source manifests decode absence. Saved source viewer uses this map for page links after restart/sync/restore, independently of temporary SourceEvidenceArchive files. Use application/pdf on existing source/asset records; retain original source ID when materializing the meal. Receipt source associations remain distinct from food-photo references in DraftMaterializer and saved document validation. Asset paths remain managed portable locators; source bytes/digests are immutable.++Emit schema 2 only for PDF-bearing handoff/archive payloads; image-only writers retain schema 1. ArchiveZIPCodec manifest and ArchiveRecords versions must match exactly; ArchiveJSON strict schemas gain explicit v1/v2 alternatives and reject unknown fields/unsupported combinations before restore writes. Updated readers accept both, reject unknown versions before writes, and enforce that v1 cannot contain PDF. Existing sync asset mediaType and typed transport carry PDF bytes without re-encoding; audit all admission and cleanup membership checks so PDF receipt originals are retained. Archive v2 uses `documents/<UUID>.pdf`, validates entry paths, media, hash/size and PDF content before transactional restore; do not render all pages as an archive validation side effect. Keep image entries/paths and archive collision/rehome semantics unchanged. Readable ZIP export links the document from its meal Markdown and includes exact original bytes. Restore/recovery and account rehome remap associations using the existing asset-ID mapping, never convert PDFs to photos.++## Failure and interruption contracts++Pre-admission validation failure creates no draft. Once admitted, extraction failure retains original and editable draft; cancellation cannot rollback a published original or save a meal. Page-state/evidence writes use the same active-account/generation fences as review writes. Late completions are discarded, including page status. Missing or corrupt original produces an unavailable source notice; no deletion, automatic repair or invented thumbnail. A failed PDF source cannot cause image receipts or other drafts to change.++## Testing strategy and requirement mapping++| Criteria | Required verification |+| --- | --- |+| 1.1–1.3, 5.2 | Real NSItemProvider payload-shape tests (PDF+thumbnail, alternate representations, duplicate/split documents); Files security scope; 0/1/20/21 pages and 32MiB±1; locked/truncated/type-spoofed files; crash/relaunch pending handoff/account admission. |+| 2.1–2.3 | Synthetic native-text, scan, mixed, selectable-title-over-scanned-body, rotated/cropped and failed-page PDFs; page geometry/provenance; repeated header vs legitimate duplicate dishes; blank values; chunk overflow/model failure and complete page accounting. |+| 3.1–3.3, 5.1 | Existing image quantity/price corpus plus PDF adapter tests; manually edited/retried/resumed/stale-generation results, changed OCR text/parser and split/merged rows without duplicate/resurrected items; cancellation before/after admission; model unavailable; save/reopen exact Decimal/AUD values. |+| 4.1–4.4 | Original SHA256 and association across restart/relocation, synthetic sync, archive v2 roundtrip/rehome/recovery and Markdown ZIP; old v1 image fixtures; unknown-version rejection; PDF excluded from photo membership; acknowledgement UI. |++Use existing Swift Testing/XCTest, generated synthetic PDFs only. Seeded generated cases vary page order, repeated names and source bytes to assert identity stability, no name-based collapse, byte-exact roundtrips and no writes on rejected admission. Add deterministic interleaving tests for account/generation cancellation. UI journeys cover share/Files→review→save→source viewing, page failure/manual completion, accessible page labels and existing image flows. No real-library migration or photo mutation is part of verification.++## Risks requiring implementation measurement++Risk: worst-case 20-page PDF rendering/model work may exceed practical memory/latency | Verify: early synthetic bound tests on supported hardware before downstream integration | If wrong: reduce per-page raster/batch work and mark affected pages incomplete with manual fallback; retain approved admission limits and originals.++## Research references++- [Apple PDFDocument](https://developer.apple.com/documentation/pdfkit/pdfdocument): document opening, locking and page access.+- [Apple PDFPage](https://developer.apple.com/documentation/pdfkit/pdfpage), [PDFSelection](https://developer.apple.com/documentation/pdfkit/pdfselection): page content, selection geometry and rendering.+- [Apple Vision text recognition](https://developer.apple.com/documentation/vision/recognizing-text-in-images): image OCR adapter.++Apple documentation entry points were consulted; web retrieval of their Markdown detail failed. Installed SDK headers independently confirm PDFDocument.isLocked/pageCount, PDFPage selection/render/crop APIs and PDFSelection.selectionsByLine. Exact Swift signatures and crop/rotation transforms must be compiled and tested during implementation, rather than assumed to be repository APIs.+++## Review and verification++# PDF design validation++## Explain Like self-validation++### Beginner++The original PDF stays intact, like a receipt in an envelope. Foodnotes reads its pages to suggest meal details, shows which pages need attention, and leaves the user in control of saving. A page preview is a temporary aid, not a replacement receipt or food photo.++### Intermediate++PDF admission joins the existing durable handoff and asset-publication path. A media dispatcher selects PDFKit text extraction or bounded Vision OCR, preserving page-qualified evidence and using existing validation/edit-version fences. Additive page state makes interruption resumable; version 2 PDF-bearing archives explicitly distinguish new content while updated readers retain v1 image support.++### Expert++The transaction boundary is durable source admission, not successful inference. Per-page evidence identity and generation-scoped status writes prevent duplicates/stale completions; source membership, portable locators, rehome maps and leases remain the durability authority. Document reconciliation must not inherit silent global chunk truncation or merge items by name. Renderer memory and ambiguous text layouts require early synthetic measurements and explicit incomplete/manual fallback states.++### Findings resolved before review++- PDF eligibility must be separated from image-only photo membership despite the retained historical SourceImage type name.+- Page extraction completion cannot imply field recognition or silently drop work at the existing 24-chunk bound.+- SharedCapture requires an extension-safe PDF admission counterpart; archive byte validation belongs in the portable Apple-platform package using CoreGraphics rather than app extraction code.+- Full-source preservation needs archive/export/recovery parity, not only successful capture.++## Self-review checklist++All 15 acceptance criteria mapped in design testing table. Named integration points cover intake, evidence, review, persistence, sync, archive/recovery and readable export. Additive records preserve image absence defaults; no PDF/photo conflation. No implementation, new migration or unrelated repair is authorised. Design packet delivery remains separately gated.++## Required reviews++Completed sequential critic then peer-validator review with final closure checks. External Codex/Kiro tools absent after discovery; PERSONAL_PROJECTS=1. The documented fallback used two independent native subagents (technical correctness and architecture/user behavior); these are not reviews by distinct external models.++- Critic: row/column assembly, durable saved provenance and complete durable consumer inventory were initially blocking. Contracts now specify row assembly, saved source provenance and the tracked parity audit; archive strict-version handling and partial-native-text fixtures are explicit. Final result: no remaining blockers/minors.+- Both peers: mutable OCR text/parser hashes could bypass manual-edit protection through new version-zero occurrence paths. Persisted row-to-occurrence identity, confirmation of ambiguous retry matches and dismissal tombstones close this, including attempted incomplete/cancelled pages. Saved provenance admits retained tombstoned occurrence IDs. Final result: no remaining blockers.+- No peer disagreement remains. Resource performance and row-layout quality require implementation measurements with synthetic fixtures, not assumptions of accuracy. Proposed design is ready for owner approval, not implementation.++## Verification and limitations++- Baseline verified HEAD0128d2c; no application source changes or native jobs.+- Installed SDK headers confirm PDF document lock/page count and page selection/render interfaces; detailed Apple web Markdown retrieval failed and was supplemented by those local headers.+- Document links, Markdown audit table and all 15 criterion mappings checked. Documentation-only change: application tests/builds not run.+- Design packet prepared locally only. Earlier phone authorisation covered the five requirements files; this new payload has not been transferred.++## Owner gate++Does the design look good? Approval advances to task planning, not implementation. Text-first extraction with OCR fallback is the recommended technical approach; no unreceived preference reply was treated as approval.+++## Next decision++Does the design look good? Approve to proceed to the task plan, or identify changes. Implementation requires its later gate. New phone delivery requires separate authorisation; this packet is ready locally but has not been sent.
diff --git a/specs/pdf-receipt-import/design-review.md b/specs/pdf-receipt-import/design-review.mdnew file mode 100644index 0000000..0fd06f7--- /dev/null+++ b/specs/pdf-receipt-import/design-review.md@@ -0,0 +1,45 @@+# PDF design validation++## Explain Like self-validation++### Beginner++The original PDF stays intact, like a receipt in an envelope. Foodnotes reads its pages to suggest meal details, shows which pages need attention, and leaves the user in control of saving. A page preview is a temporary aid, not a replacement receipt or food photo.++### Intermediate++PDF admission joins the existing durable handoff and asset-publication path. A media dispatcher selects PDFKit text extraction or bounded Vision OCR, preserving page-qualified evidence and using existing validation/edit-version fences. Additive page state makes interruption resumable; version 2 PDF-bearing archives explicitly distinguish new content while updated readers retain v1 image support.++### Expert++The transaction boundary is durable source admission, not successful inference. Per-page evidence identity and generation-scoped status writes prevent duplicates/stale completions; source membership, portable locators, rehome maps and leases remain the durability authority. Document reconciliation must not inherit silent global chunk truncation or merge items by name. Renderer memory and ambiguous text layouts require early synthetic measurements and explicit incomplete/manual fallback states.++### Findings resolved before review++- PDF eligibility must be separated from image-only photo membership despite the retained historical SourceImage type name.+- Page extraction completion cannot imply field recognition or silently drop work at the existing 24-chunk bound.+- SharedCapture requires an extension-safe PDF admission counterpart; archive byte validation belongs in the portable Apple-platform package using CoreGraphics rather than app extraction code.+- Full-source preservation needs archive/export/recovery parity, not only successful capture.++## Self-review checklist++All 15 acceptance criteria mapped in design testing table. Named integration points cover intake, evidence, review, persistence, sync, archive/recovery and readable export. Additive records preserve image absence defaults; no PDF/photo conflation. No implementation, new migration or unrelated repair is authorised. Design packet delivery remains separately gated.++## Required reviews++Completed sequential critic then peer-validator review with final closure checks. External Codex/Kiro tools absent after discovery; PERSONAL_PROJECTS=1. The documented fallback used two independent native subagents (technical correctness and architecture/user behavior); these are not reviews by distinct external models.++- Critic: row/column assembly, durable saved provenance and complete durable consumer inventory were initially blocking. Contracts now specify row assembly, saved source provenance and the tracked parity audit; archive strict-version handling and partial-native-text fixtures are explicit. Final result: no remaining blockers/minors.+- Both peers: mutable OCR text/parser hashes could bypass manual-edit protection through new version-zero occurrence paths. Persisted row-to-occurrence identity, confirmation of ambiguous retry matches and dismissal tombstones close this, including attempted incomplete/cancelled pages. Saved provenance admits retained tombstoned occurrence IDs. Final result: no remaining blockers.+- No peer disagreement remains. Resource performance and row-layout quality require implementation measurements with synthetic fixtures, not assumptions of accuracy. Proposed design is ready for owner approval, not implementation.++## Verification and limitations++- Baseline verified HEAD0128d2c; no application source changes or native jobs.+- Installed SDK headers confirm PDF document lock/page count and page selection/render interfaces; detailed Apple web Markdown retrieval failed and was supplemented by those local headers.+- Document links, Markdown audit table and all 15 criterion mappings checked. Documentation-only change: application tests/builds not run.+- Design packet prepared locally only. Earlier phone authorisation covered the five requirements files; this new payload has not been transferred.++## Owner gate++Does the design look good? Approval advances to task planning, not implementation. Text-first extraction with OCR fallback is the recommended technical approach; no unreceived preference reply was treated as approval.
diff --git a/specs/pdf-receipt-import/design.md b/specs/pdf-receipt-import/design.mdnew file mode 100644index 0000000..544906f--- /dev/null+++ b/specs/pdf-receipt-import/design.md@@ -0,0 +1,91 @@+# PDF receipt import — design (T-2488)++Status: design, requirements and tasks approved by Arjen; implementation complete (see implementation-receipts.md). Source baseline: merged main `0128d2c`.++## Architecture++A PDF is one immutable receipt source, never twenty photo assets. PDFKit admission and page extraction live in the iOS application; portable domain/handoff contracts carry media identity, page provenance and status without importing PDFKit. Existing account admission, atomic asset publication and review/save fences remain authoritative.++### Pattern-extension audit++The table groups matching SourceImage, image-media and ArchiveIO.image consumers by responsibility; [parity-audit.md](parity-audit.md) lists the individual files and durable aggregate replacements. Implementation must repeat the search and account for new references.++| Existing consumer / hook | Needs equivalent | PDF contract |+| --- | --- | --- |+| ShareViewController; FoodnotesShare-Info.plist; SharedCapture/OriginalHandoffImageFile; SourceEnvelope; FileSourceHandoff | Yes | PDF provider selection and activation; representation deduplication; bounded atomic original publication; image v1/PDF v2 envelope decoding. |+| NativeImagePicker; AppCapture.beginCapture | Yes | Separate Files import action using `.pdf`, single selection, security-scoped URL copied while access is held; camera/Photos unchanged. |+| CaptureContracts; DraftPhotos; Validation; CaptureRoute | Yes | Add Files origin/route and optional page state; retain legacy SourceImage descriptor with application/pdf; all-source validation separate from image-only photo membership/framing. |+| OriginalCaptureReader; VisionCaptureOCR; ExtractionTypes; OnDeviceCaptureExtractor; CaptureReviewModel | Yes | Media dispatch, PDF page events and document aggregation; preserve image extraction path and per-draft generation/edit-version checks. |+| FoundationCaptureModel; ProposalValidation; ExtractionReview | Yes | Page-qualified evidence and stable item anchors, bounded chunks and document reconciliation; same source-backed quantity/price validation and manual protection. |+| ManualReviewView; DraftPhotoFields; source-original presentation; MealCaptureOriginals | Yes | PDF page viewer and status summary; existing review fields/notices; no PDF photo selection/crop/framing or UIImage decoding. |+| LocalAssetPayload; DraftMaterializer; RepositoryMutation; RepositoryStorage; AssetIdentity; AccountTransitionAuthority | Yes | PDF original admission/manifest/association through existing asset transactions and locator resolver; photo IDs reject PDF; no new absolute persisted paths. |+| SyncContracts; AppleCloudCodec; CloudPublisher; SharingContracts; TransferCapture | Yes | Carry truthful PDF media metadata and exact bytes through current typed integrity/ownership validation and lifecycle transport. Image-named carriers are not image decoders. |+| ArchiveResources; ArchiveValidation; ArchiveZIPCodec; ArchiveGraphMapper/Selection; scratch/restore/import/export services | Yes | Media-dispatched original validation, documents/<asset-id>.pdf entries, version-aware graph validation and original associations on restore/recovery. |+| MarkdownExporter; MarkdownText | Yes | Linked original in documents/, meal-identifiable receipt link, no image embedding; retain existing images/ paths. |+| SavedMealContentEditor; photo editor/framing; thumbnails | No parallel PDF photo UI | Filter by image eligibility; receipt source access uses PDF viewer. |+| Existing image corpus, archive and handoff fixtures | No replacement | Retain v1 fixtures and image semantics, add PDF suites alongside. |++## Components and interfaces++These are proposed additions/extensions, not existing APIs.++- `Services/Capture/PDFReceiptAdmission.swift`: preflight owned temporary bytes, verify regular file/no symlink, length/digest and PDF open, unlocked state, nonzero page count ≤20. Reject before publishing a draft. Recheck copied bytes; a provider URL changing during copy must not change the admitted document unnoticed.+- `Services/Capture/Extraction/PDFReceiptEvidence.swift`: one serial worker owns its PDFDocument/PDFPage objects; no non-Sendable PDFKit objects cross tasks. `collect(source, generation) -> page events` emits ordered text/evidence/status. PDF work and hashing run off the main actor. Temporary render buffers are released after each page; derivatives never enter source manifests.+- `Services/Capture/ReceiptSourceViewer.swift`: read-only PDFKit view with page navigation and unavailable-page labels. Open only a verified local source resolved through existing typed readers; never rewrite the PDF. Existing source buttons present this viewer by media dispatch.+- Central `OriginalMedia` policy in FoodnotesCore distinguishes receipt PDF from supported images, supplies suffix/media validation, and exposes `isFoodPhoto`. Use CoreGraphics CGPDFDocument for archive-package PDF-open/lock/page-count validation on supported iOS/macOS targets; PDFKit extraction/viewing stays in the app. SharedCapture adds a PDF counterpart to OriginalHandoffImageFile for the extension.++### Admission and handoff++Provider inventory prefers a PDF representation over its thumbnail and counts distinct PDF attachment providers; alternate type representations from one provider count once. A pre-load request guard limits conforming PDF attachment providers to four. Within that fan-in budget, multiple providers resolving to identical original bytes count once after bounded hash comparison; different PDFs reject. Ignore unrelated decorative thumbnails only for an accepted PDF payload. Activation admits PDF/image combinations; runtime enforces the actual one-document/image rules. No URL fetching or network PDF loading is added.++The share extension bounds copy/validation and publishes an envelope/original atomically before completing. Main app revalidates before draft creation and acknowledges only durable admission; queued unsupported/unassigned input remains recoverable. Files import uses the same service and destination selection. Persist a per-install compatibility acknowledgement before first PDF draft; explain updates are required for other installations/restores, with no claim to enforce device versions.++### Evidence and review++Extend SourceEvidence with optional `pageIndex` (zero-based, absent for old images); normalize rectangles to upright page crop bounds after rotation. Native PDF selections provide text/geometry; sanitize control characters and reject empty/invalid selections. Native text is usable only when nonempty bounded selections assemble into plausible receipt rows; selectable headings alone do not qualify. If native text is absent or only headings/invalid geometry/ambiguous reading order is found, render that page at bounded resolution and pass its CGImage to existing Vision request configuration. Raw fragment IDs include source ID, page index, method/parser version, line position and text. Canonical row IDs are separate durable identities, not hashes of mutable text or parser version. Retry replacement is generation-scoped, never an append of duplicate evidence.++Before model proposals, a new `PDFReceiptRows` adapter groups same-baseline text fragments into page-local rows using normalized vertical overlap and left-to-right column order; wrapped names join only when indentation/vertical adjacency yields one unambiguous item row. Each assembled row retains its original fragment/page bounds and receives a persisted page-qualified row anchor mapped to one occurrence identity. Use that persisted row anchor as the common evidence ID passed to the existing single-line candidate validator so dish, quantity and price share the same occurrence ID. Ambiguous column/row associations produce no item-number proposal, not cross-row guesses. A bounded receipt-role classifier marks header, item, subtotal/total and unknown rows using explicit total/header labels, layout and repeated top-of-page geometry; excluded rows cannot generate dish candidates. Ambiguous roles remain manual review. Tests must include separate quantity/price columns and wrapped items, not only synthetic one-line receipts.++Process page order, then reconcile receipt metadata across the whole document. Keep page boundaries in model input, assign occurrence identity by supporting evidence anchor, not dish name, and sort by first supporting page/line. Merge duplicate proposals only for the same supporting anchors; identical names at distinct anchors remain separate. Identify repeated headers/carried totals through receipt-role validation, never a global text-name deduplication. Conflicting metadata or unsupported quantity/price proposals stay unconfirmed/blank. The owner-approved per-item price amendment below supersedes the original no-division rule only for clearly evidenced row amounts and quantity.++Replace the PDF path's document-global 24-chunk cap with per-page bounded batches and page-aware document reconciliation. Cap each page to 500 evidence lines and 24 existing-size model chunks; any omitted evidence, failed model batch, cancellation, unsupported capability or failed render marks that page incomplete. Record exact page states (`pending`, `processing`, `processed`, `incomplete(reason)`) durably with the draft. “Processed” requires all admitted evidence batches handled, including explicit no-text result; it never promises every visible field was recognised. A final summary lists all pages and failed/unprocessed pages. Persist the PDF row-to-occurrence registry with draft page state. On retry, match rows against the prior page-local geometry/fragment footprint before applying proposals, retaining canonical row and occurrence IDs even when OCR text/parser changes. Match only a unique compatible footprint; splits, merges, unmatched new rows on any previously attempted page with a row registry (including incomplete/cancelled pages) and deleted/manual-dismissed rows require explicit confirmation, never a new missing-name path at editVersion zero. Only first processing of a never-attempted pending page without registry entries or dismissal tombstones can create rows normally. Retain dismissal tombstones so retry cannot resurrect removed items. Retrying preserves edit versions and never overwrites manual fields; PDF reconciliation reuses the current proposal validator and DraftExtractionReview apply path.++## Data and durable operations++Add optional PDF page-state/provenance fields to draft/evidence Codable payloads, decoding absence as existing image behavior. Before DraftMaterializer removes a draft, copy immutable `receiptProvenance` into the source AssetManifestEntry: page count/states plus accepted proposal field/occurrence IDs mapped to supporting page indices and row anchors. This records extraction origin rather than claiming later user edits are still verbatim PDF text. Full OCR text need not be synced. Extend StoredAsset encoding, typed manifest validation, ArchiveAssetRecord and both ArchiveRecordsMapping directions to preserve it; account rehome/remapping rewrites occurrence IDs with existing document mappings, page/row anchors stay source-local. All manifest-copy sites preserve this optional metadata, including TransferCapture and lifecycle transfers. Source provenance is immutable after initial materialization; divergent copies for the same source identity fail integrity validation rather than merge by last writer. Validate PDF role/source membership, page bounds, referenced occurrence IDs (including retained tombstoned occurrences) and existing payload-size limits before transactional save/import; oversized metadata yields an actionable save failure with draft retained, never silent truncation. Existing source manifests decode absence. Saved source viewer uses this map for page links after restart/sync/restore, independently of temporary SourceEvidenceArchive files. Use application/pdf on existing source/asset records; retain original source ID when materializing the meal. Receipt source associations remain distinct from food-photo references in DraftMaterializer and saved document validation. Asset paths remain managed portable locators; source bytes/digests are immutable.++Emit schema 2 only for PDF-bearing handoff/archive payloads; image-only writers retain schema 1. ArchiveZIPCodec manifest and ArchiveRecords versions must match exactly; ArchiveJSON strict schemas gain explicit v1/v2 alternatives and reject unknown fields/unsupported combinations before restore writes. Updated readers accept both, reject unknown versions before writes, and enforce that v1 cannot contain PDF. Existing sync asset mediaType and typed transport carry PDF bytes without re-encoding; audit all admission and cleanup membership checks so PDF receipt originals are retained. Archive v2 uses `documents/<UUID>.pdf`, validates entry paths, media, hash/size and PDF content before transactional restore; do not render all pages as an archive validation side effect. Keep image entries/paths and archive collision/rehome semantics unchanged. Readable ZIP export links the document from its meal Markdown and includes exact original bytes. Restore/recovery and account rehome remap associations using the existing asset-ID mapping, never convert PDFs to photos.++## Failure and interruption contracts++Pre-admission validation failure creates no draft. Once admitted, extraction failure retains original and editable draft; cancellation cannot rollback a published original or save a meal. Page-state/evidence writes use the same active-account/generation fences as review writes. Late completions are discarded, including page status. Missing or corrupt original produces an unavailable source notice; no deletion, automatic repair or invented thumbnail. A failed PDF source cannot cause image receipts or other drafts to change.++## Testing strategy and requirement mapping++| Criteria | Required verification |+| --- | --- |+| 1.1–1.3, 5.2 | Real NSItemProvider payload-shape tests (PDF+thumbnail, alternate representations, duplicate/split documents); Files security scope; 0/1/20/21 pages and 32MiB±1; locked/truncated/type-spoofed files; crash/relaunch pending handoff/account admission. |+| 2.1–2.3 | Synthetic native-text, scan, mixed, selectable-title-over-scanned-body, rotated/cropped and failed-page PDFs; page geometry/provenance; repeated header vs legitimate duplicate dishes; blank values; chunk overflow/model failure and complete page accounting. |+| 3.1–3.3, 5.1 | Existing image quantity/price corpus plus PDF adapter tests; manually edited/retried/resumed/stale-generation results, changed OCR text/parser and split/merged rows without duplicate/resurrected items; cancellation before/after admission; model unavailable; save/reopen exact Decimal/AUD values. |+| 4.1–4.4 | Original SHA256 and association across restart/relocation, synthetic sync, archive v2 roundtrip/rehome/recovery and Markdown ZIP; old v1 image fixtures; unknown-version rejection; PDF excluded from photo membership; acknowledgement UI. |++Use existing Swift Testing/XCTest, generated synthetic PDFs only. Seeded generated cases vary page order, repeated names and source bytes to assert identity stability, no name-based collapse, byte-exact roundtrips and no writes on rejected admission. Add deterministic interleaving tests for account/generation cancellation. UI journeys cover share/Files→review→save→source viewing, page failure/manual completion, accessible page labels and existing image flows. No real-library migration or photo mutation is part of verification.++## Risks requiring implementation measurement++Risk: worst-case 20-page PDF rendering/model work may exceed practical memory/latency | Verify: early synthetic bound tests on supported hardware before downstream integration | If wrong: reduce per-page raster/batch work and mark affected pages incomplete with manual fallback; retain approved admission limits and originals.++## Research references++- [Apple PDFDocument](https://developer.apple.com/documentation/pdfkit/pdfdocument): document opening, locking and page access.+- [Apple PDFPage](https://developer.apple.com/documentation/pdfkit/pdfpage), [PDFSelection](https://developer.apple.com/documentation/pdfkit/pdfselection): page content, selection geometry and rendering.+- [Apple Vision text recognition](https://developer.apple.com/documentation/vision/recognizing-text-in-images): image OCR adapter.++Apple documentation entry points were consulted; web retrieval of their Markdown detail failed. Installed SDK headers independently confirm PDFDocument.isLocked/pageCount, PDFPage selection/render/crop APIs and PDFSelection.selectionsByLine. Exact Swift signatures and crop/rotation transforms must be compiled and tested during implementation, rather than assumed to be repository APIs.+++## Approved GST-inclusive per-item price amendment++The owner clarified that Price AUD is per item and includes GST; quantity remains separate. For an explicit net-row/GST-row/quantity table, derive `(net cents + row GST cents) / quantity`, rounding only the final result to the nearest cent, half up. Explicit inclusive row amounts are divided once; explicit inclusive unit prices are copied directly and never taxed/divided again. Prefer a printed inclusive unit price when present and consistent with the rounded row evidence. Missing quantity, unknown amount basis, absent row tax, contradictory evidence and unsupported row shapes stay unpriced/incomplete; never distribute order-level fees or tax over dishes.++Use a separate typed derivation boundary that reparses the complete row under its explicit header, retaining generic model substring validation for copied values. Persist optional basis/input cents/quantity metadata on accepted receipt price fields, carry it through draft/save/reopen/reidentity/archives, and show a source-labelled calculation with page access. Manual changes keep their values and source history. Older records without this optional metadata still decode. The v2 PDF archive strict reader recognises the new optional nested keys; older test builds may reject those archives and must be updated under the existing current-build PDF policy. No existing prices are migrated or rewritten.
diff --git a/specs/pdf-receipt-import/implementation-receipts.md b/specs/pdf-receipt-import/implementation-receipts.mdnew file mode 100644index 0000000..d5a2a19--- /dev/null+++ b/specs/pdf-receipt-import/implementation-receipts.md@@ -0,0 +1,193 @@+# PDF receipt import — implementation receipts++Repository fixtures are synthetic. The implementation gates below used no real library, model secrets, physical device installation, publication or deployment. Subsequent authorised installation and local-only acceptance diagnosis are recorded separately at the end.++## Original contracts and reader (tasks 1–4)++- Missing original aggregate/page APIs first failed native Swift compilation; no cases were executed in this red receipt.+- Five focused domain cases pass, including 32 generated locator mappings. Full package gate passed 92 cases: 73 domain, 11 archives and 8 handoff.+- Native storage retention plus existing photo transport passed two cases. The storage-only synthetic bytes do not establish valid PDF admission.+- Six reader cases establish inclusive 32 MiB/20-page admission, valid zero/21-page rejection, locked/corrupt/spoofed/hash/symlink checks, cancellation, allocation failure and bounded serial rendering.++## Intake (tasks 5–6)++- Missing provider/Files/acknowledgement services first failed compilation. Eighteen native intake and retained image/account handoff cases passed; expanded PDF intake/reader/geometry aggregate passed 16.+- Real NSItemProvider/NSExtensionItem shapes and the built extension activation predicate are tested. Files scope tests inject the grant lifecycle; actual Files UI remains a later acceptance gate.+- Intake review fixes preserve supported image representation preference and detach full PDF validation from the main actor. A blocking validation seam proves actor responsiveness.++## Evidence and bounded work (tasks 7–8)++- Missing row assembly/registry/PDF pipeline/page-event APIs first failed compilation. A later runtime run exposed a recursive review observer and a raster scaling defect; these failures were repaired and preserved in `.build-logs`.+- Native PDFKit thumbnail comparison established that CoreGraphics drawing transforms center rather than enlarge small pages. Explicit scaling now precedes the crop/rotation transform; finite composed coefficients are checked. Asymmetric marker pixels and actual Vision OCR on scans and selectable-title-over-scan PDFs pass.+- Thirty-nine focused native behavior cases pass. Final renderer/extraction aggregate passes 14 cases after the scoped extractor refactor. Strict lint passes.+- Production PDF route with 20 scanned pages, real rendering/Vision and an injected model: 23.240 seconds, 20 calls, 20 separate same-name item identities, all page states accounted for and exact original bytes retained. Test-process high-water RSS was 538,640,384 bytes before and after this workload; this is not a fresh-process peak or real-model measurement.+- Actual production FoundationCaptureModel on native Mac: 20 sequential 12-row batches completed in 357.599 seconds. Cancellation returned CancellationError in 0.106 seconds. Sampled wrapper peak RSS was 23,855,104 bytes. OS inference-service and accelerator memory could not be attributed unambiguously and are excluded.+- Actual-model receipts and exact compiled source/binary hashes are retained under `.build-logs/pdf-model-probe/final-source-wrapper-*`. Renderer-only changes and formatting do not change the measured model prompt, budget or chunk behavior. The preliminary 295-second watchdog receipt is partial (15 completed calls), not a 20-page pass or an owner product deadline.+- Initial PDF work used one existing-size model batch per page, at most 20 calls. This per-page allocation was superseded by the ordinary-receipt acceptance fix below. Omitted evidence, batch failure, proposal-cap reach and capability loss produce explicit incomplete/manual page states. Admission remains inclusive 32 MiB/20 pages. Ordinary model defaults remain 700 tokens/12 proposals.+- Two method-level native selectors discovered zero cases; they are recorded as selection failures, never verification passes. A failed-run xcresult summary was unreadable; its valid native log remains. Subsequent supported `-collect-test-diagnostics never` runs retain valid xcresults.+- A known Swift actor initializer diagnostic was resolved by moving only FakeCloudTransport protocol conformances into an empty extension, following the existing thumbnail-framing workaround; no protocol requirements or actor state changed.++Full logs and xcresults remain in the reusable `.build-logs` and `DerivedData` directories; task details identify each milestone receipt. No downstream task is complete merely because these component checks passed.++### Extraction review follow-up++Raw native selection counts and invalid/overlong fragments now retain explicit incomplete status; OCR fallback does not erase those omissions. Clear quantity-led unpriced rows are eligible without an invented price, while explicit priced receipt/invoice/page headers are excluded. PDF model date/time output is ignored; the image and PDF paths share conservative timestamp validation across every page. Parser windows retain preceding-label context and do not reinterpret their overlap row. The first boundary fixture used an unsupported “Warranty” label; it was corrected to the existing parser's “Printed” label, without changing the expected conservative result.++The expanded completeness/PDF/image native aggregate passed 17 cases; the final shared-parser/model-date-injection aggregate passed 11. Strict lint passes. Model prompt, response budget and evidence chunk behavior remain unchanged from the measured actual-model workload.++An automatic approval rejection cited an obsolete T-2489 exclusion. The rejected command did not execute. The identical command was retried once and accepted only after the coordinating task supplied the scope-linked direct human T-2488 “Implement it” authorization. No bypass or alternate execution route was used.++The final assembly review added a genuine behavioral red: valid but overlapping columns produced no proposal yet incorrectly finished processed (six native cases, one failure). Assembly now reports omitted/ambiguous groups and the page becomes explicitly incomplete. The final scoped 13-case completeness/extraction aggregate passes, including the integrated 20-page workload.++Task 9's future failing test files were parked only to allow this dependency-order repair to compile; no target or exclusion configuration changed. Both files were restored byte-for-byte before task 10. Their exact paths and SHA256 verification are retained in `.build-logs/pdf-task9-pending-sources.json`. The task 8 scoped pass is not a full acceptance gate.++## Durable save and typed transport (tasks 9–10)++Missing accepted-field/tombstone/evidence/validation/remapping APIs first failed native and host domain compilation; no cases were executed in those red builds. The final full package gate passes 97 cases (78 domain, 11 archives, 8 handoff). The retained native PDF/retry/image/review aggregate passes 16 cases, and the stricter final provenance-only aggregate passes five. Strict lint passes.++Accepted extraction origin survives manual corrections and draft removal as compact source metadata. Dismissed rows retain inactive occurrence identities. Validation rejects duplicate or conflicting anchors, source/page/occurrence mismatches, divergent immutable metadata and payload overflow. Oversized saves retain the draft/original. Actual typed CloudKit original decoding and durable outbox entries preserve PDF metadata and exact bytes. Existing typed transfer value copies preserve optional metadata; byte-only verification descriptors do not substitute for stored manifests. Archive DTO/schema/export support remains tasks 11–12.++Two further automatic approval rejections (broad persistence scope and an obsolete generic native-slot restriction) were each known not to execute. Each identical action was retried once and accepted after new direct-human scope/design approvals or fresh distinct-target ownership/user parallel-build evidence. No route changes, indirect execution or real-library writes were used.++### Durable fallback review follow-up++The new behavioral regression reproduced a P1: an empty model left pre-registered rows without actual occurrences, and manual completion then failed Save. The six-case red run had one failure (`receipt row occurrence`). The saved projection now keeps real/tombstoned occurrence rows and represents unmaterialized rows as source evidence; the full registry remains available while editing/retrying a draft. No dish is fabricated. Empty, throwing, partial and rejected model responses now all permit manual completion, save and reopen with exact originals. A previously unmaterialized row cannot silently become another version-zero item on retry after manual completion. Eleven focused native provenance/retry cases pass; strict lint passes.++The exact regression-write/test command was initially rejected without execution. It was retried once and accepted after direct human approval history arrived inside the required trusted delegation/input envelope. Command text, target, original rejection and accepted-once metadata are retained under `.build-logs/pdf-task10-fallback-*`. An initial test missing-await compile error was fixed before the genuine behavioral red and is not counted as proof of the P1.++## Archive and readable export (tasks 11–12)++Missing archive provenance/original-media APIs first failed host and native compilation; native fixture initializer errors were corrected before execution. Four host PDF cases pass, including eight seeded byte/provenance/tombstone round trips. Full package parity passes 101 cases (78 domain, 15 archives, 8 handoff). Native PDF save/fallback/readable export/restore collision aggregate passes eight; affected legacy archive restore/fault/resource/collision/image aggregate passes 12. Strict lint passes.++PDF-bearing archives emit schema 2, image-only archives retain schema 1, and records/manifest versions must match before extraction writes. Strict nested provenance, version, path, checksum, media and actual PDF-open/lock/page/size validation are preserved without rasterizing archive sources. Inactive receipt occurrences and accepted field links survive both record mappings. Native restore tests cover source/occurrence collisions against an existing image-only library, remapped page links, exact source bytes and identical replay. Readable ZIP uses a normal receipt link under the meal and includes its exact PDF in `documents/`, never a food-photo embedding.++The first host archive test-write/run was automatically rejected before execution. Its single identical retry was accepted after fuller trusted parent input explicitly linked the delivered 16-task PDF plan to the human “Implement it” approval. Exact command/rejection/accepted-once receipts are retained under `.build-logs/pdf-task11-*`.++### Archive page-count review follow-up+- Public ZIP write/read regression: actual 1/declared 2 and actual 2/declared 1 produced four genuine failed expectations in one test (`.build-logs/pdf-archive-count-red.log`).+- Shared original validation now checks expected page count when provenance is known; ZIP read/write, Markdown and scratch restore/reopen pass it. Images and callers without metadata retain their existing validation.+- `swift test --package-path Foodnotes/Packages/FoodnotesCore --scratch-path .build/package --filter PDFArchiveTests`: 5 tests in 1 suite passed; outer exit 0 (`pdf-archive-count-green.log`). `make lint`: outer exit 0 (`pdf-archive-count-lint.log`). Native task13 future-API red source remains in source tree; no native pass claimed for this follow-up yet.++### Tasks13/14 — read-only PDF review/source UI+- Native compile red for missing ReceiptSourceViewModel/Viewer/ReceiptPageStatusText APIs preserved in pdf-task13-red-build.log. No cases claimed.+- First real render test failed (scene-less UIWindow), while viewer4/persistence8 SwiftTesting passed; pdf-task14-first-detail.log retained. Corrected fixture to actual connected UIWindowScene as existing render tests do.+- PDFKit read-only source, bounded verified data read off MainActor, page navigation/status, missing/corrupt original and late-read invalidation, draft/saved source dispatch and per-install compatibility inbox acknowledgement implemented. Existing image viewer extracted unchanged. No original writes.+- Final focused native: 1 actual PDFKit XCTest render case (three light/dark/accessibility variants) and 15 SwiftTesting cases in2 suites (viewer4/intake11), all pass, outer exit 0; pdf-task14-final-detail.log. Prior persistence8 passed after shared archive-count validation. Render inspection caught/cramped accessibility page buttons; fixed to separate page label and labelled icon-only navigation; inspected revised accessibility image. Strict lint outerexit0 pdf-task14-lint-final.log.++### Tasks15/16 entry and UI review follow-up+- Entry red: 3 native cases/4 issues (Files request absent; both accepted/rejected picked originals deleted). Earlier enum scaffolding compile error retained separately. `.build-logs/pdf-task15-red-detail.log`.+- Entry green: 3 native cases pass after Files action/native single-PDF UIDocumentPicker wiring and security-scoped owned copy off MainActor. Original selected files never removed. Includes compatibility acknowledgement, manual quantity2.5/price1250AUD, save/reopen and verified original page2; pdf-task16-entry-green-detail.log.+- Isolated DEBUG PDF UI fixture requires valid synthetic launch; publishes synthetic two-page PDF through real share inbox. Startup isolation checker rejects fixture flag alone. Added Files-picker coexistence and app-closed pending-share notice/review/correction/save/reopen/original-page UI acceptance journeys (execution pending).+- Required static/config/boundary/startup/package/build/build-tests chain passed, exit0 (`pdf-task16-gates.log`), package102 cases (78domain/16archives/8handoff). Subsequent UI review follow-up still requires final native/UI/static/build closure.+- UI review actual-representable stale page regression failed before fix (`pdf-viewer-stale-red-detail.log`): prior PDFDocument stayed visible under invalid page. Fix clears/hides PDFView+AX then restores valid navigation from original document. Adds contextual readable accepted/current/suggestion field→page links in draft and saved/restored provenance, using corrected dish names without UUID/path labels. Focused native2XCTest actual-render cases +13SwiftTesting (viewer5/provenance8) pass, `pdf-ui-review-green-detail.log`; strict lint exit0 `pdf-ui-review-lint2.log`. Two intermediate SwiftUI compilation errors retained, no executed cases claimed for them.++### Acceptance evidence map+| Criteria | Principal evidence |+| --- | --- |+|1.1/1.3|PDFReceiptIntakeTests actual NSItemProvider/NSExtensionItem payloads and built activation predicate; PDFReceiptReaderTests inclusive limits/locked/spoof/hash/symlink; PDFReceiptEntryTests Files app composition. Files UI opens/cancels native picker; selected URL acceptance is native composition, not a claimed external Files provider automation.|+|1.2/2.3|PDFReceiptViewerTests and real PDFReceiptRenderTests (navigation, unavailable stale-content clearing, exact original bytes, invalidation), page-status summaries and contextual field links.|+|2.1/2.2/3.1|PDFReceiptExtractionTests real native text/Vision scanned/mixed pages; evidence completeness/header/unpriced/date/overlap cases;20-page integrated renderer/OCR/injected model; actual production model20calls separately measured.|+|3.2/5.1|PDFReceiptRetryTests persisted identity/edit fences/tombstones; unavailable/cancelled/manual fallback cases and model cancellation receipt.|+|3.3/4.1|PDFReceiptEntryTests and PDFProvenanceStorageTests manual corrected quantities/prices/save/reopen, unavailable originals and accepted origins; original storage lifecycle and existing relocation/upgrade aggregate.|+|4.2/4.3|PDFArchiveTests strict v2 actual content/count/seeded byte roundtrips; native readable ZIP/restore collision/replay/typed CKRecord+CKAsset; full retained image/archive/native aggregate. No live cloud transmission.|+|4.4/5.2|Intake compatibility/deferred/account tests; actual synthetic pending-share UI restart→ack→review→save/reopen/source pages. Fixture publishes through production durable inbox; this is not live external share-host UI automation.|++### Final UI execution and corrections+- Full native aggregate on02c6e82 passed32XCTest +406SwiftTesting/106suites with no failures/skips (pdf-task16-native-full-detail.log; xcresult21-28-16).+- Initial new UI aggregate: capture-entry coexistence and actual native PDF Files picker open/cancel passed; pending-share journey failed because DEBUG synthetic envelope filename was noncanonical (production validator correctly rejected it). Retained first screenshot/receipt. Fixed fixture to sourceUUID.original without changing validator.+- Second pending-share run reached actual notice; screenshot/hierarchy showed parent receipt.compatibility identifier overwrote acknowledgement childID. Removed parent identifier; unchanged journey then passed38.5s (pdf-task16-ui-pdf-green-detail.log; xcresult21-34-38). Covers app-closed pending interval, explicit prerequisite, editable review, manual dish, draft/saved page1/2, save and relaunch. This is synthetic inbox publication plus actual app UI, not external share-host automation.+- Share rejection guidance explicitly asks for one unlocked PDF,1–20pages and<=32MiB. Final lint/config/boundary/startup checks pass after fixture changes (pdf-task16-static-final.log).+- Retained image UI first run found missing documented labelled synthetic Photos fixture; actual Photos picker opened with simulator stock images. No other image selected. Failure remains retained; documented tracked synthetic fixture seeding and affected rerun pending.++### Phase-final repeated header review+- Frozen438842a build/build-tests/full native gates passed again before review repair (32XCTest +406SwiftTesting; pdf-task16-full-before-header-fix-detail.log).+- Genuine regression:2 tests ran,2 failures in merchant-heading case (CHIN CHIN wrongly proposed as dish; true Noodles absent); legitimate top repeated items/wrapped names case passed. pdf-header-red-detail.log.+- Positioned-line grouping now considers document context before wrapping: repeated unknown top headings need matching text/source/geometry on distinct pages immediately above an independently named quantity-led item. Proven headings stay source evidence as metadata; item rows are never deduplicated by text. All bounded top evidence is considered, without an arbitrary first-line cutoff.+- Focused20 native extraction/completeness/retry/header cases passed, including real scanned20-page OCR with injected model; pdf-header-green-detail.log. Additional boundary/header suite3cases passed; pdf-header-boundary-green-detail.log. Final lint/config/boundary/startup checks outerexit0 pdf-header-static-final.log. Model prompt/budget/chunk algorithm and package code remain unchanged.+- Retained Photos review/resume/original31.415s and draft meal/dish photo save/reopen67.532s passed after documented synthetic PNG seed; pdf-task16-ui-retained-green-detail.log. Prior framing115.649s passed without source changes to that feature. Earlier missing-fixture failures remain preserved.++### Final closure on application source 495e526+- `make lint validate-config validate-boundaries validate-startup-isolation`: outer exit 0 (pdf-header-static-final.log).+- `make build build-tests test-storage XCODEBUILD='xcodebuild -collect-test-diagnostics never' DESTINATION='platform=iOS Simulator,id=FA48FDD9-588F-47C7-B261-0B7953E3BA23' STORAGE_TEST_SELECTION='-only-testing:FoodnotesTests -parallel-testing-enabled NO'`: outer exit 0; **32 XCTest + 409 SwiftTesting cases in 107 SwiftTesting suites**, no test skips/failures. pdf-header-native-final-detail.log; xcresult Test-Foodnotes-2026.10.27_21-52-14-+1100.+- `make test-ui` with same XCODEBUILD/DESTINATION and `UI_TEST_SELECTION='-only-testing:FoodnotesUITests/PDFReceiptJourneyTests -parallel-testing-enabled NO'`: outer exit 0;2cases passed (15.319 s Files picker,39.128 s pending-share/review/save/reopen/source pages). pdf-header-ui-final-detail.log; xcresult21-50-44.+- Six distinct selected UI cases pass across retained receipts. Final PDF-only row classification does not change the other four entry/image/photo/framing journeys; their existing passing receipts remain valid. Package code unchanged since its 102-case pass (78 domain / 16 archive / 8 handoff); actual model prompt/budget/chunk implementation unchanged since its 20-call measurement. No redundant package/model rerun claimed.+- Phase-final independent critic closure on 495e526 reports no remaining P1/P2; protected report .build-logs/reviews/pdf-final-critic.md. All 16 Rune tasks complete. Subsequent closure commit changes documentation/task tracking only.+- Reused outputs: DerivedData approximately 1.0 GiB; .build 352 MiB; .build-logs 23 MiB. All raw receipts, failed runs and unique tracked source remain preserved. Native/UI/build command sessions have ended successfully; no publication or physical-device action performed.++## Ordinary-receipt acceptance correction++After the authorised initial installation, exact-file local reproduction confirmed two ordinary pages needed two existing-size batches each (19/17 assembled rows), while the one-batch policy omitted evidence. The final allocator shares the unchanged maximum 20-call document budget across pages and carries unused capacity forward; it does not expand maximum work to 480 calls. Financial row classification, explicit verbatim refund-summary metadata and comma/Sept date parsing are corrected. See `specs/bugfixes/ordinary-pdf-receipt-budget/report.md`.++- Runtime red: one new budget case failed with four expected issues. An intermediate 37-case failed run and a helper-before-implementation compile failure are retained separately; neither is green evidence.+- Final focused extraction/image/date: 39 cases in 7 suites passed. Full native refresh: 32 XCTest + 414 Swift Testing cases passed, zero failures. Final focused six-case suite includes one subsequently added actual selectable-text synthetic PDF pipeline case, so five of those cases overlap the aggregate.+- Strict lint, configuration, boundaries, startup isolation and diff whitespace checks passed. Independent review has no remaining P1/P2.+- Exact supplied PDF through local production PDFKit/Vision/Foundation Models: both pages processed, explicit merchant/Delivery/order date/time recovered, zero dish proposals. Original is a refund summary without itemised dishes. This is a native Mac reproduction, not another physical-phone result. Private bytes and verbose output remain outside git; repository fixtures are synthetic. The unchanged model 20-call latency/cancellation receipt remains applicable to the maximum call count, not a timing measurement of this exact file.+- No new physical installation, push or merge for this correction. Existing UI layout, persistence and manual-edit/retry policies remain unchanged; no new UI journey pass is claimed.++## Itemised tax-invoice acceptance correction++The subsequently installed ordinary-receipt fix was 206f149. A second user-supplied itemised invoice exposed column semantics: the text reader retained three genuine item rows, but the model saw the header and rows in separate batches. The actual local baseline returned three dishes (the phone report was one), all with GST amounts as prices and no merchant. Verbatim grounding alone could not distinguish the wrong monetary column.++A bounded table adapter now carries an explicit Tax Point Date / Description / Qty / GST / GST Amount / Net amount schema across batches and continued pages. It emits source-validated names, quantities and printed net amounts for each row, protects those rows from model numeric overrides, and marks malformed associations incomplete. Explicit closing totals end the table; pagination/header exclusions do not. The invoice's declared on-behalf-of company/trading-name/locality block supplies a grounded merchant suggestion. No tax addition, unit-price division or price allocation is performed.++- Initial synthetic actual-PDF regression failed at runtime with three issues: missing items, wrong GST price and absent later item. Independent review then found a pagination reset; its two-case runtime red failed with two expected issues before closure.+- Final focused 31-case/six-suite PDF/retry aggregate passed. Full native refresh passed 32 XCTest + 420 Swift Testing cases, including the subsequently added complete synthetic PDF → review → merchant confirmation → save → reopen check for all three quantities/prices and unchanged original bytes.+- Final lint/configuration/boundaries/startup gates and diff whitespace checks passed. This also extracted an overlong pre-existing synthetic refund test body into an identical fixture helper; an earlier lint failure is retained, not counted as success.+- The complete private original was run twice locally through production PDFKit/Vision/FoundationModels and DraftExtractionReview, each with fresh row UUIDs. Exact private comparisons confirmed all three names/quantities/printed net amounts, merchant and invoice date, with no extra dishes/ordering/time. Public non-content evidence is `.build-logs/pdf-itemised-exact-receipt.json`; original/render/raw candidates/reviewed drafts remain outside git.+- Independent review closed the pagination P2; no remaining P1/P2. No updated phone installation, push, merge or real-library rewrite for this correction. Existing draft/manual-edit/deletion/retry protections are unchanged; a fresh import is the full corrected receipt acceptance path, since retry deliberately does not overwrite populated fields or reconstruct omitted/deleted items silently.+++## Approved GST-inclusive per-item correction++The owner clarified that Price AUD is per item including GST and explicitly authorised clearly evidenced row-total division. This supersedes the held 09d0cef net-row mapping, which was not installed. The reviewed implementation derives `(row net + row GST) / explicit quantity` using bounded integer cents and final half-up cent rounding; inclusive unit prices are never taxed or divided again. Detected ambiguous bases, missing quantities/row tax and contradictory printed unit values remain manual. No order-level fees/tax allocation or old-data rewrite.++- Updated prior synthetic expectations produced runtime red with six price mismatches on the net-row source.+- Final host 108 cases pass: 82 domain, 18 archive, 8 handoff. Final native 457 cases pass: 33 XCTest + 424 Swift Testing. Includes actual synthetic PDF → review → place confirmation → save → reopen for all three gross-unit prices and calculation metadata; manual quantity/price edits across resume/retry retain values and historical source-calculation provenance.+- Optional metadata preserves legacy decoding; validated ZIP round-trip carries source calculation/original bytes and strict unknown nested keys still reject. Older strict PDF test readers can reject new calculation metadata under the already-approved updated-build prerequisite.+- Two complete-original local actual-model/draft/provenance trials match all three quantities/gross unit prices plus restaurant/date. Independent private expected arithmetic predates implementation; no real receipt bytes/text are committed or externally model-uploaded. Non-content summary: `.build-logs/pdf-unit-price-exact-receipt.json`.+- All static gates pass. Actual native light/dark/AX3 calculation-disclosure pixels inspected. Critic/persistence/archive reviews have no remaining P1/P2. A synthetic test line-wrap is the only post-aggregate code-format change; no behavior changed after passing tests.+- Same authorised phone update proceeds only after exact-source signed artifact checks; installation receipts remain local and do not establish real-device PDF acceptance. Fresh import is needed to exercise corrected extraction without overwriting protected existing draft values. No push or merge.++## Proposal-limit page-status correction++The user confirmed every extracted field on installed 74ebe4b, but the parent-inspected screenshot reported Page 1 incomplete because the automatic proposal limit was reached. The code marked a page incomplete from candidate count before ignoring table-protected, already-declared, duplicate or invalid proposals. Its shared model decoder also lost raw-limit information when rejecting invalid generated entries. A separate in-memory manual-entry flag remained sticky across retry.++The PDF route now requests only fields the model can still contribute. Typed table item fields, declared merchant/order values and system date/time work are not regenerated. A capped response for actual remaining work still marks the page incomplete, including when no generated candidates survive decoding; duplicate accepted candidates are emitted once. Raw generation cap metadata is retained before kind/UUID conversion. Existing evidence/chunk/page/document bounds and all values/provenance are unchanged. Starting a guarded new retry resets its old notice; new fallback/failure/deletion/persistence conditions still warn.++- Controlled runtime red: two cases failed with three issues, reproducing complete correct data plus a capped irrelevant response/incomplete page and a sticky notice. The retained actual 74 native Mac run did not hit the phone's variable generation cap; phone-specific raw text was not retrieved.+- Final 33 XCTest + 429 Swift Testing cases pass (462 native). Genuine unresolved fifth-item omission, raw-capped/zero-decoded output, uncapped rejected/system/duplicate proposals, normal actual review and successful/failed retries are covered. All four static gates pass; critic/UI reviews clear. Core packages are unchanged; prior 108 host passes are retained, not rerun.+- Two complete-original production-pipeline runs using the real model adapter now report Page 1 processed, no fallback, identical three dish quantities/gross-unit prices/restaurant and calculation provenance. Actual inference calls are zero because all useful fields are already deterministically handled; these are not two new generation workloads. Non-content evidence: `.build-logs/pdf-proposal-status-exact-receipt.json`. Private material remains outside git.+- Existing draft statuses require explicit Retry or reimport; saved receipt metadata is not automatically rewritten. Same authorised phone update follows exact-source signature/install/launch checks. No push or merge.++## Debug information and editable restaurant prefill — 2026-10-27++User-accepted amendment is recorded in decision_log.md. Default-off AppStorage controls presentation only: shared receipt field/page components cover draft review and saved meal originals; actual incomplete states still show concise action-oriented copy with original access. Selected place/order identities and manual text/clears are guarded before automatic text assignment. Successful place proposals retain their PDF evidence. Existing records are not rewritten.++Evidence on simulator FA48FDD9-588F-47C7-B261-0B7953E3BA23:+- Red: new place-prefill tests failed with five assertions on the prior behavior; new Settings UI journey failed because the toggle was absent. The preliminary compile failure is not counted as red runtime evidence.+- Green: 20 focused Swift tests passed, then the complete native selection passed 34 XCTest + 432 Swift Testing declarations (466 total), zero failures. Package sources were unchanged; prior 108 host tests retained, not rerun for this UI amendment.+- Final test-only strengthening rerun passed one render XCTest + five invoice Swift tests. It explicitly checks the materialised restaurant name and PDF place evidence after save/reopen, with all three gross unit prices unchanged.+- Actual app journey passed default off, enable, relaunch persistence, disable, draft review off/on, save, saved detail on/off and relaunch; original receipt remains accessible. Synthetic fixture exercises a real unavailable-model failure, retaining the normal fallback/retry and saved incomplete notice.+- Component renders inspected with debug off/on in light/dark/AX3. Explicit UIKit appearance override corrected a test-harness mixed-appearance capture; no production styling hook. Full app review/saved screenshots also inspected. Large debug content scrolls naturally.+- Lint/config/boundary/startup-isolation checks passed. Initial sandbox Swift-cache access failures were rerun in the supported normal host context; no permission or trust configuration changed.+- Independent UI, persistence and final critic reviews found no P1/P2. Strengthened save/reopen coverage addresses the persistence review's optional suggestion.++The signed Debug phone build succeeded using the reusable DeviceDerivedData. App/extension strict signatures, existing team/group/CloudKit and target-inclusive unexpired profiles passed verification. Installation receipt will identify the committed source separately; no push or merge is part of this amendment.++Existing image review/resume and both PDF UI journeys passed. The broader run also exposed two stale manual-journey assumptions: an obsolete “default” word in the current full-date label and a single-scroll query for a lazily materialised ordering field. Retain the original save/reopen/edit assertions; check the exact displayed weekday/day/month and the current Personal library button, and dismiss the keyboard/scroll to the real ordering field. The failed run remains recorded locally, not counted as green.++The first test-correction rerun passed recovery/historical edit. The save journey then exposed that full-date formatting omits the year and Personal is now the library-action button; its test now checks the exact current weekday/day/month and the identified button label. These were test-only corrections; production source stayed unchanged.++Final manual-save journey passed under its distinct current selector, printing the exact expected/actual current date and verifying the Personal library button, save/relaunch and finishing without ratings. An intermediate run's failure pointed to an obsolete assertion/source line despite a rebuilt test binary; it is excluded rather than counted as a pass. Six distinct affected UI journeys now have actual passing receipts across the scoped runs: debug toggle, image resume/original, Files entry, PDF save/original pages, manual recovery/edit and manual save/relaunch. The broader failed runs are retained locally with their precise failures; this is not a claim of one all-UI-suite green run.++Final source changes after the 466-case aggregate were test/doc-only: stronger saved-place/provenance assertions and explicit render appearance passed their six-case rerun; current manual selectors/date assertion passed their bounded UI reruns. Production source remained unchanged. No real user library was inspected or rewritten.++## Accepted publication and deletion amendment — 2026-10-28++The owner accepted the installed import/debug/prefill build and authorised PR Pilot merge, then added meal deletion to that same scope. No further installation or real-meal deletion is included.++Deletion uses the existing presence tombstone, revision/session/current-document and frozen-write guards, transactional outbox and projection refresh. Originals and scoped profiles retain their lifetime rules. The native destructive alert has explicit Cancel/Delete; the initial system confirmation popover omitted Cancel on iOS27, so it was replaced by the alert before final UI verification. The actual simulator journey passed cancellation, confirmed deletion, return to journal and absence after relaunch; its synthetic screenshot was inspected.++Five native deletion declarations cover cancellation, stale/session/moving guards, mutation rollback, other visit/place/original retention and disk reopen, ordinary publication/peer fetch, and Shared publication without removing the Personal meal. A failing synthetic fetch test found that a committed same-epoch tombstone could be overwritten after its pending outbox disappeared; the narrow fetch guard now retains the deletion. The complete pre-provider-guard aggregate passed 34 XCTest +437 Swift Testing declarations (471), and all108 host package cases passed. A preliminary test incorrectly assumed byte-identical distinct asset IDs had the same owned path; that unsupported fixture assumption was removed, retaining explicit before/after bytes and cleanup checks for both owned paths. No physical deduplication claim is made.++Four pre-push reviews covered reuse, quality/security, efficiency and spec/docs/testing across the full diff. One major efficiency finding (unbounded PDF provider alias work) was fixed with a pre-load four-provider cap. The actual registered-loader red regression failed on the unguarded path; provider/intake green passed13 declarations, including four-alias acceptance and unchanged image handling. Minor current-stage and external-share evidence wording were corrected. Private originals, their contents and screenshots remain outside git. Final exact-head gates and merge receipts are reported through the PR workflow rather than inferred from these earlier snapshots.
diff --git a/specs/pdf-receipt-import/implementation.md b/specs/pdf-receipt-import/implementation.mdnew file mode 100644index 0000000..f093778--- /dev/null+++ b/specs/pdf-receipt-import/implementation.md@@ -0,0 +1,40 @@+# PDF receipt import and confirmed meal deletion++## Beginner level++### What changed+Share one PDF receipt to Foodnotes or choose Import PDF receipt from Files. Foodnotes keeps the original, reads its pages locally and fills an editable meal. Check the restaurant, dishes, quantities and prices before saving. Prices are GST-inclusive per item when the receipt supplies a clear basis. Unknown details remain editable rather than invented.++### Why it matters+Screenshots are unnecessary and the source stays available from review and saved meals. The normal screens show the meal instead of processing traces; Settings → Display → Debug information reveals those traces when needed. Delete meal asks for confirmation and removes only the chosen visit. Cancel keeps it.++### Key concepts+An original is the unchanged receipt, separate from food photos. Provenance records which receipt evidence supported a field. A deletion tombstone is a retained “removed” marker that keeps synchronised copies from making a deleted meal reappear.++## Intermediate level++### Changes overview+The share extension and Files route converge on durable original admission. PDFKit selectable text and bounded Vision OCR feed page/row evidence into the existing validated extraction/review engine. PDF provenance survives draft save, typed transport, strict versioned archives and readable export. Existing image flows remain supported.++### Implementation approach+Admission limits one receipt to 32 MiB and 20 pages, bounds alias verification to four PDF attachment providers before loading any, preserves bytes and rechecks identity. Geometry-aware row assembly separates table descriptions, quantities, GST and net amounts; declared merchant metadata remains separate from item rows. The deterministic table path derives gross unit cents from evidenced row net/GST and quantity, preserving calculation metadata. Model work is local and bounded; omission remains visible and manually recoverable. Draft edit versions, source/generation checks and canonical row identities protect user corrections and retries.++Deletion reuses Meal.isPresent and the ordinary revision-checked replaceDocument/outbox transaction. App session/document/write guards protect the selected visit; the native destructive alert supplies explicit Delete and Cancel. Snapshot refresh removes inaccessible detail routes. Original/file references and shared place/dish profiles are retained under existing lifetime rules, so deletion adds no ad hoc cleanup.++### Trade-offs+Bounded extraction can require manual completion. It does not guarantee every receipt layout is understood. Restaurant text is prefilled but does not guess a saved-place identity; explicit selections remain authoritative. Debug preference changes presentation, not stored provenance. Tombstones keep sync metadata and immutable originals rather than promising immediate disk-space reclamation.++## Expert level++### Technical detail+Input publication is atomic and owned before handoff. Account and destination identity remain explicit. Raster dimensions, page count, per-call evidence and document model work are bounded; synchronous validation/raster work runs away from the main actor, with cancellation checks between units. Evidence fields and optional integer-cent calculations use validated nested archive contracts. Rounding occurs at final per-item division; ambiguous bases, double-tax ambiguity and ungrounded order-fee allocation stay manual.++### Architecture impact+No new backend, currency model, cloud OCR, photo-repair path or live-library migration is introduced. PDF envelopes/archives use their approved versioned compatibility policy. Meal deletion introduces no persisted field or wire command: the existing false-wins presence merge is published through existing cloud control records. Fetch additionally preserves a committed same-epoch tombstone after its local outbox has been acknowledged, preventing a later whole-record projection from resurrecting it. Epoch/library/partition separation and frozen-transfer restrictions remain intact.++### Potential issues and limits+The owner accepted the installed PDF import; that acceptance does not identify every external share host or establish each CloudKit account combination. Simulator success alone cannot establish those results. Deletion is tested with synthetic repositories/transports and native simulator UI, without deleting anything on the phone. Old builds cannot fully read new PDF attachments under the approved updated-device prerequisite. Existing saved meals are not reparsed or rewritten automatically.++## Completeness assessment++The 15 PDF criteria are covered by admission, extraction/retry, review/original access, persistence/sync/archive/export and compatibility tests, with accepted amendments recorded in decision_log.md. Debug display and editable restaurant prefill are accepted on the installed build. The deletion amendment adds cancellation, write guards, rollback, unrelated-data preservation, reopen, shared routing, delete-wins fetch and list/detail UI coverage. Final publication receipts state actual current-head results and distinguish retained evidence from reruns. No unrelated price/quantity redesign, photo repair, deployment or real-meal deletion is included.
diff --git a/specs/pdf-receipt-import/parity-audit.md b/specs/pdf-receipt-import/parity-audit.mdnew file mode 100644index 0000000..79926a2--- /dev/null+++ b/specs/pdf-receipt-import/parity-audit.md@@ -0,0 +1,59 @@+# PDF pattern-extension call-site audit++Baseline `0128d2c`; source-only inventory for SourceImage, allImageSources, replaceImageLocators, ArchiveIO.image and imagePath. Every matched file is listed below; new implementation references require re-audit.++| File | Needs equivalent | Action |+| --- | --- | --- |+| `Foodnotes/Packages/FoodnotesCore/Sources/FoodnotesArchives/ArchiveZIPCodec.swift` | Yes | Media-dispatched validation and document paths; preserve originals/provenance and v1 images through mapping, export/restore. |+| `Foodnotes/Packages/FoodnotesCore/Sources/FoodnotesArchives/ArchiveValidation.swift` | Yes | Media-dispatched validation and document paths; preserve originals/provenance and v1 images through mapping, export/restore. |+| `Foodnotes/Foodnotes/Services/Sync/AppleCloudCodec.swift` | Yes | Preserve PDF media, bytes, source metadata and ownership through transfer; no image decoding. |+| `Foodnotes/Foodnotes/Services/Capture/DraftPhotoAdmission.swift` | No PDF photo equivalent | Keep image-only admission/UI; filter PDF out of membership, framing and candidate photo lists. |+| `Foodnotes/Foodnotes/Services/Sync/SyncContracts.swift` | Yes | Preserve PDF media, bytes, source metadata and ownership through transfer; no image decoding. |+| `Foodnotes/Foodnotes/Services/Capture/HandoffImportCoordinator.swift` | Yes | Add PDF dispatch/page provenance at this contract or UI/extraction hook; retain existing image behavior. |+| `Foodnotes/Foodnotes/Services/Capture/AssetStore.swift` | Yes | Include PDF in all-original publication/reference retention, locator rebasing, leases and cleanup protection; image-only checks must be explicit. Preserve optional source provenance in manifest copies. |+| `Foodnotes/Foodnotes/Services/Capture/CaptureReviewModel.swift` | Yes | Add PDF dispatch/page provenance at this contract or UI/extraction hook; retain existing image behavior. |+| `Foodnotes/Foodnotes/Services/Capture/Extraction/OnDeviceCaptureExtractor.swift` | Yes | Add PDF dispatch/page provenance at this contract or UI/extraction hook; retain existing image behavior. |+| `Foodnotes/Foodnotes/Services/Capture/Extraction/ExtractionTypes.swift` | Yes | Add PDF dispatch/page provenance at this contract or UI/extraction hook; retain existing image behavior. |+| `Foodnotes/Foodnotes/Services/Capture/Extraction/SourceEvidenceStore.swift` | Yes | Add PDF dispatch/page provenance at this contract or UI/extraction hook; retain existing image behavior. |+| `Foodnotes/Foodnotes/Persistence/RepositoryMutation.swift` | Yes | Include PDF in all-original publication/reference retention, locator rebasing, leases and cleanup protection; image-only checks must be explicit. Preserve optional source provenance in manifest copies. |+| `Foodnotes/Foodnotes/Services/Sync/CloudPublisher.swift` | Yes | Preserve PDF media, bytes, source metadata and ownership through transfer; no image decoding. |+| `Foodnotes/Foodnotes/Services/Capture/Extraction/OCR.swift` | Yes | Add PDF dispatch/page provenance at this contract or UI/extraction hook; retain existing image behavior. |+| `Foodnotes/Foodnotes/Services/Capture/Extraction/CaptureCorpusEvaluator.swift` | No replacement | Keep image fixture/corpus; add separate PDF tests. |+| `Foodnotes/Foodnotes/Services/Sync/CloudProofHarness.swift` | No replacement | Keep image fixture/corpus; add separate PDF tests. |+| `Foodnotes/Foodnotes/Persistence/LocalAssetPayload.swift` | Yes | Include PDF in all-original publication/reference retention, locator rebasing, leases and cleanup protection; image-only checks must be explicit. Preserve optional source provenance in manifest copies. |+| `Foodnotes/Foodnotes/Features/Capture/DraftPhotoFramingControl.swift` | No PDF photo equivalent | Keep image-only admission/UI; filter PDF out of membership, framing and candidate photo lists. |+| `Foodnotes/Foodnotes/Services/Sharing/SharingContracts.swift` | Yes | Preserve PDF media, bytes, source metadata and ownership through transfer; no image decoding. |+| `Foodnotes/Foodnotes/Persistence/AccountTransitionAuthority.swift` | Yes | Include PDF in all-original publication/reference retention, locator rebasing, leases and cleanup protection; image-only checks must be explicit. Preserve optional source provenance in manifest copies. |+| `Foodnotes/Foodnotes/Features/Meals/SavedMealContentEditor.swift` | Yes | Add PDF dispatch/page provenance at this contract or UI/extraction hook; retain existing image behavior. |+| `Foodnotes/Foodnotes/Services/Archives/ArchiveGraphMapper.swift` | Yes | Media-dispatched validation and document paths; preserve originals/provenance and v1 images through mapping, export/restore. |+| `Foodnotes/Foodnotes/Features/Meals/PhotoFramingControl.swift` | No PDF photo equivalent | Keep image-only admission/UI; filter PDF out of membership, framing and candidate photo lists. |+| `Foodnotes/Packages/FoodnotesCore/Sources/FoodnotesDomain/DraftPhotos.swift` | Yes | Add PDF dispatch/page provenance at this contract or UI/extraction hook; retain existing image behavior. |+| `Foodnotes/Foodnotes/Features/Meals/MealPhotoAdmission.swift` | No PDF photo equivalent | Keep image-only admission/UI; filter PDF out of membership, framing and candidate photo lists. |+| `Foodnotes/Foodnotes/Persistence/CoreDataMealRepository.swift` | Yes | Include PDF in all-original publication/reference retention, locator rebasing, leases and cleanup protection; image-only checks must be explicit. Preserve optional source provenance in manifest copies. |+| `Foodnotes/Foodnotes/Services/Archives/TransactionalArchiveService.swift` | Yes | Media-dispatched validation and document paths; preserve originals/provenance and v1 images through mapping, export/restore. |+| `Foodnotes/Foodnotes/Persistence/RepositoryHandoff.swift` | Yes | Include PDF in all-original publication/reference retention, locator rebasing, leases and cleanup protection; image-only checks must be explicit. Preserve optional source provenance in manifest copies. |+| `Foodnotes/Foodnotes/Persistence/DraftStorage.swift` | Yes | Include PDF in all-original publication/reference retention, locator rebasing, leases and cleanup protection; image-only checks must be explicit. Preserve optional source provenance in manifest copies. |+| `Foodnotes/Foodnotes/Persistence/DraftMaterializer.swift` | Yes | Add PDF dispatch/page provenance at this contract or UI/extraction hook; retain existing image behavior. |+| `Foodnotes/Foodnotes/Features/Meals/SavedPhotoFramingControl.swift` | No PDF photo equivalent | Keep image-only admission/UI; filter PDF out of membership, framing and candidate photo lists. |+| `Foodnotes/Foodnotes/Persistence/CoreDataHandoffStore.swift` | Yes | Include PDF in all-original publication/reference retention, locator rebasing, leases and cleanup protection; image-only checks must be explicit. Preserve optional source provenance in manifest copies. |+| `Foodnotes/Packages/FoodnotesCore/Sources/FoodnotesDomain/Validation.swift` | Yes | Add PDF dispatch/page provenance at this contract or UI/extraction hook; retain existing image behavior. |+| `Foodnotes/Foodnotes/Services/Sharing/AppleTransferAssets.swift` | Yes | Preserve PDF media, bytes, source metadata and ownership through transfer; no image decoding. |+| `Foodnotes/Foodnotes/Persistence/CoreDataAccountStore.swift` | Yes | Include PDF in all-original publication/reference retention, locator rebasing, leases and cleanup protection; image-only checks must be explicit. Preserve optional source provenance in manifest copies. |+| `Foodnotes/Foodnotes/Features/Capture/ManualReviewView.swift` | Yes | Add PDF dispatch/page provenance at this contract or UI/extraction hook; retain existing image behavior. |+| `Foodnotes/Foodnotes/Services/Sharing/TransferCapture.swift` | Yes | Preserve PDF media, bytes, source metadata and ownership through transfer; no image decoding. |+| `Foodnotes/Foodnotes/Persistence/RepositoryArchiveImport.swift` | Yes | Include PDF in all-original publication/reference retention, locator rebasing, leases and cleanup protection; image-only checks must be explicit. Preserve optional source provenance in manifest copies. |+| `Foodnotes/Packages/FoodnotesCore/Sources/FoodnotesDomain/RepositoryContracts.swift` | Yes | Include PDF in all-original publication/reference retention, locator rebasing, leases and cleanup protection; image-only checks must be explicit. Preserve optional source provenance in manifest copies. |+| `Foodnotes/Foodnotes/Services/Archives/ArchiveScratchContracts.swift` | Yes | Media-dispatched validation and document paths; preserve originals/provenance and v1 images through mapping, export/restore. |+| `Foodnotes/Packages/FoodnotesCore/Sources/FoodnotesDomain/CaptureContracts.swift` | Yes | Add PDF dispatch/page provenance at this contract or UI/extraction hook; retain existing image behavior. |+| `Foodnotes/Foodnotes/Features/Capture/DraftPhotoFields.swift` | No PDF photo equivalent | Keep image-only admission/UI; filter PDF out of membership, framing and candidate photo lists. |+| `Foodnotes/Foodnotes/Features/Meals/PhotoFramingSheet.swift` | No PDF photo equivalent | Keep image-only admission/UI; filter PDF out of membership, framing and candidate photo lists. |+| `Foodnotes/Foodnotes/Services/Archives/MarkdownExport/MarkdownText.swift` | Yes | Media-dispatched validation and document paths; preserve originals/provenance and v1 images through mapping, export/restore. |+| `Foodnotes/Foodnotes/Services/Archives/MarkdownExport/MarkdownExporter.swift` | Yes | Media-dispatched validation and document paths; preserve originals/provenance and v1 images through mapping, export/restore. |+| `Foodnotes/Foodnotes/Services/Archives/CoreDataArchiveScratchStore.swift` | Yes | Include PDF in all-original publication/reference retention, locator rebasing, leases and cleanup protection; image-only checks must be explicit. Preserve optional source provenance in manifest copies. |+| `Foodnotes/Foodnotes/App/ThumbnailFramingFixture.swift` | No PDF photo equivalent | Keep image-only admission/UI; filter PDF out of membership, framing and candidate photo lists. |++## Additional media/record sites++OriginalHandoffImageFile and share activation/provider selection need PDF-specific equivalents. ArchiveResources needs original-media validation. PlaceModels.AssetManifestEntry, Archives.ArchiveAssetRecord/ArchiveRecordsMapping and all manifest reconstruction sites preserve optional immutable receiptProvenance. MealCaptureOriginals dispatches the saved source viewer. AppCapture adds Files route. Domain DraftPhotos introduces `allOriginalSources` and `replaceOriginalLocators`; migrate every durable consumer listed above. Keep `allImageSources` strictly image-only for photo UI, and restrict photo-reference validation to image-eligible IDs. This explicit split prevents cleanup from losing PDF sources.++ArchiveJSON strict records/manifest schemas require explicit v1/v2 alternatives; reject mismatched envelope/record versions and unknown PDF fields rather than ignoring them.
diff --git a/specs/pdf-receipt-import/requirements-review.md b/specs/pdf-receipt-import/requirements-review.mdnew file mode 100644index 0000000..d1cddfb--- /dev/null+++ b/specs/pdf-receipt-import/requirements-review.md@@ -0,0 +1,17 @@+# Requirements review — T-2488++## Self-review++Five one-line user stories and 15 unique anchored EARS criteria; required Markdown hard breaks checked. Outcomes cover shared/in-app PDF intake, exact originals, text/scanned/mixed pages, all-page accounting, editable quantity/price reuse, manual-edit/account/generation protection, persistence and supported archive/export/recovery paths. No parser, OCR strategy, schema version, migration, page-rendering mechanism or implementation task is selected. No native tests or builds were run for this document stage.++## Sequential independent reviews++The design critic challenged three ambiguities: document rejection versus recoverable page failure, older-build support policy, and observable completion. The text now defines the admission boundary, explicitly proposes a communicated user-managed upgrade prerequisite with older-build PDF access unsupported, and accounts for every page as processed or incomplete. Minor clarifications add page provenance, retain legitimate repeated items, bound image regressions to established invariants, clarify supported durable artifacts, and make limits inclusive with distinct-document counting. Final critic closure found no remaining blockers.++The peer-review-validator completed its own assessment and consulted two independent Codex native peers with technical/edge-case and behavior/scope/compatibility lenses. PERSONAL_PROJECTS=1 requested external models, but neither prescribed external MCP reviewer was exposed; the role explicitly permits replacing unavailable perspectives with subagents. This is native-agent fallback validation, not distinct external-model validation. Both peers validated the critic resolutions and found no substantive writing blockers. Their two minor wording suggestions—displayable versus non-displayable original pages and explicit user-visible completion—were incorporated. Final sequential critic and peer addenda confirm faithful application of those recommendations; all review findings are closed.++## Synthesis and next gate++Technical writing gaps have been resolved without selecting an implementation. The reviewers do not approve owner policies. Four proposed choices remain: all pages as one receipt; one distinct PDF up to 32 MiB/20 pages; a communicated user-managed update prerequisite with older-build PDF access unsupported; and document-open rejection versus retaining an admitted original/editable draft for page/extraction failures or no evidence.++Do the requirements look good or do you want additional changes? Approval advances to design only. Full-spec route approval does not approve these requirements, design, tasks or implementation. No unreceived asynchronous answer is treated as approval.
diff --git a/specs/pdf-receipt-import/requirements.md b/specs/pdf-receipt-import/requirements.mdnew file mode 100644index 0000000..9ecd4dc--- /dev/null+++ b/specs/pdf-receipt-import/requirements.md@@ -0,0 +1,68 @@+# PDF receipt import — requirements (T-2488)++## Introduction++Foodnotes will accept PDF receipts as source documents for the existing meal-review flow. This lets a receipt shared from another app or selected from Files become an editable meal draft without requiring screenshots. Original PDF bytes remain available alongside the saved meal.++Status: approved by Arjen on 2026-10-27. All-pages/one-receipt, one distinct PDF, inclusive 32 MiB/20-page limits, admitted-failure drafts and the user-managed updated-build prerequisite are approved. Design and implementation remain separate approval gates.++## Non-Goals++- General image quantity/price redesign, currency expansion beyond the existing AUD behavior, or delivery-service API integration.+- PDF editing, combining separate files, multiple receipts per PDF, password entry or encrypted-document unlocking.+- Cloud OCR, automatic saving without review, PDF export generation, or unrelated photo-library repair.++### 1. PDF intake and original source++**User Story:** As a diner, I want to share or select a PDF receipt, so that I can review it without taking screenshots.++**Acceptance Criteria:**++1. <a name="1.1"></a>WHEN one PDF is shared to Foodnotes or selected through its receipt-import entry, Foodnotes SHALL admit it into one editable meal draft using the existing destination, account and review-confirmation patterns; unrelated thumbnail attachments SHALL not prevent an otherwise valid PDF share. +2. <a name="1.2"></a>WHEN PDF intake succeeds, Foodnotes SHALL retain the original PDF byte-for-byte and let the user open it from the draft and saved meal, view each displayable page, and identify pages that cannot be displayed; previews or extraction SHALL not replace or alter the original. +3. <a name="1.3"></a>WHEN a document cannot be opened as a PDF, requires a password to open, exceeds the inclusive 32 MiB/20-page limits, or the attempt contains more than one distinct PDF document, Foodnotes SHALL reject it before creating a new draft with an actionable explanation; alternate representations of one document SHALL not count as additional documents, and cancellation before admission SHALL leave existing meals and drafts unchanged. ++### 2. Text, scanned and multi-page extraction++**User Story:** As a diner, I want every page of my receipt considered, so that its items and meal details reach the same review.++**Acceptance Criteria:**++1. <a name="2.1"></a>WHERE a supported PDF contains selectable text, scanned pages or both, Foodnotes SHALL offer source-backed meal details and item names, quantities and prices using the same no-invention and confirmation semantics as image receipts; absent or ambiguous values SHALL remain blank or require the existing user-confirmation interaction, and each proposal SHALL remain traceable to its supporting original page(s). +2. <a name="2.2"></a>WHEN a supported PDF has multiple pages, Foodnotes SHALL consider all pages together as one receipt in document order, retain separate ordered items with their corresponding quantities/prices, and avoid creating dish items from repeated headers, carried totals or receipt totals; legitimate repeated items SHALL not be collapsed solely because their names repeat. +3. <a name="2.3"></a>WHEN PDF extraction ends, Foodnotes SHALL show the user whether each admitted page was processed or is explicitly incomplete, identify failed/unprocessed pages, and retain the original and editable draft for manual completion or retry; processed pages without usable evidence SHALL leave values blank, and complete processing SHALL not be presented as a guarantee that every field was recognised. ++### 3. Editable review and save++**User Story:** As a diner, I want to correct extracted values before saving, so that the meal reflects what I actually ordered.++**Acceptance Criteria:**++1. <a name="3.1"></a>WHEN PDF extraction proposes item quantities or prices, Foodnotes SHALL prefill the corresponding existing editable Quantity and Price AUD review fields, preserving the current validation and price interpretation rather than inventing unit prices or quantities from totals. +2. <a name="3.2"></a>WHEN the user corrects any review field, retries extraction, or leaves and resumes the draft, Foodnotes SHALL retain the user's corrections and prevent late proposals from overwriting them or updating a different draft/account generation. +3. <a name="3.3"></a>WHEN the user confirms a valid reviewed PDF meal, Foodnotes SHALL save the corrected item quantities, prices and meal details and show them unchanged after reopening; image receipt, camera and Photos SHALL retain their existing editable AUD quantity/price fields, blank/unknown handling, manual-correction protection, confirmation/save, destination/account fences and original-byte preservation. ++### 4. Durable source and compatibility++**User Story:** As a diner, I want my PDF source and corrected meal to survive normal data operations, so that I can refer to the receipt later.++**Acceptance Criteria:**++1. <a name="4.1"></a>WHEN a PDF-backed draft or meal is reopened after an app restart or supported in-place app upgrade/container relocation, Foodnotes SHALL retain its original-PDF association and reviewed values; an unavailable original SHALL be reported without deleting the meal or fabricating a replacement source. +2. <a name="4.2"></a>WHEN PDF-backed meals pass through existing supported sync, archive/restore or recovery, updated Foodnotes builds SHALL retain exact original PDF bytes, meal/source associations and corrected quantities/prices; readable export SHALL include the original PDF as a source file identifiable with its meal, without treating it as a food photo. +3. <a name="4.3"></a>WHEN the updated build reads existing image-only data or archives, Foodnotes SHALL preserve their values, source associations and image-review/save semantics. +4. <a name="4.4"></a>BEFORE creating the first PDF-backed draft, Foodnotes SHALL communicate that installations accessing the same library or restoring PDF-bearing archives must be updated; this SHALL be a user-managed prerequisite with older-build PDF access explicitly unsupported, and new content SHALL be represented as PDF rather than disguised as an image. ++### 5. Interruption and fallback++**User Story:** As a diner, I want interruptions to leave recoverable work, so that a failed import does not cost an existing meal or corrected draft.++**Acceptance Criteria:**++1. <a name="5.1"></a>WHEN the user cancels extraction or an extraction capability is unavailable, Foodnotes SHALL stop the active prefill attempt, retain any already admitted original and existing corrections, and offer the existing manual-review fallback without creating an automatic meal. +2. <a name="5.2"></a>WHEN sharing finishes while Foodnotes is closed or unable to admit the destination, Foodnotes SHALL follow the existing durable pending/unassigned-source behavior and present the PDF for review after supported admission; it SHALL not silently move the receipt to another account or library. +++## Owner-approved price clarification — 2026-10-27++The owner explicitly defined Price AUD as GST-inclusive per item, with quantity separate. This supersedes the earlier restriction against division for clearly evidenced row net/GST/quantity inputs. Derive per-item paid price only when those inputs or an explicit gross-row basis are known; prefer an explicit gross unit price. Round the final unit value half up to cents, preserve original inputs/provenance for review, and leave ambiguous cases manual rather than allocating order fees or guessing tax/quantity. Existing saved values and manual corrections remain unchanged.
diff --git a/specs/pdf-receipt-import/review-packet.md b/specs/pdf-receipt-import/review-packet.mdnew file mode 100644index 0000000..6a373d9--- /dev/null+++ b/specs/pdf-receipt-import/review-packet.md@@ -0,0 +1,90 @@+# Foodnotes PDF receipts — requirements approval packet++T-2488 · full-spec route approved · requirements approval pending++## What this adds++Share a PDF receipt to Foodnotes or select one in the app, process text/scanned/mixed pages, keep the exact original PDF, and prefill the existing editable meal, quantity and AUD price review. User corrections remain protected and are saved normally. Existing image quantity/price support is reused.++## Four proposed policies to approve or change++1. Process all pages together as one receipt, in document order; no page-selection step or multiple-receipt splitting.+2. One distinct PDF per import, at most 32 MiB and 20 pages (inclusive). Alternate representations and decorative thumbnails do not count as additional PDFs. The byte bound reuses the current intake limit; the 20-page bound is a proposal, not a measured performance claim.+3. Communicate a user-managed prerequisite to update installations accessing the library or restoring PDF-bearing archives before PDF use. Older-build PDF access is unsupported; cross-device version enforcement is not promised.+4. Reject documents that cannot open, require a password or exceed the limits before making a draft. Once a PDF is admitted, keep the original and editable draft if a page/extraction fails or yields no usable evidence, identify incomplete pages, and offer manual completion/retry.++## Review outcome++The critic and two independent peer perspectives resolved admission/fallback ambiguity, made page completion visible, clarified compatibility and preserved repeated legitimate items. No implementation architecture is chosen. Supporting review notes explain the native-agent fallback; no external-model review is claimed.++## Approval requested++Do the requirements look good or do you want additional changes? Approving the requirements and proposed policies permits the design stage only. No PDF implementation, installation or real-library changes are authorised by this packet.++The complete proposed requirements follow so this file is usable on its own. Companion files are delivered with the `pdf-receipt-import-` prefix.++---++# PDF receipt import — requirements (T-2488)++## Introduction++Foodnotes will accept PDF receipts as source documents for the existing meal-review flow. This lets a receipt shared from another app or selected from Files become an editable meal draft without requiring screenshots. Original PDF bytes remain available alongside the saved meal.++Status: proposed requirements, awaiting owner approval. Proposed policies: process all pages as one receipt; accept one distinct PDF of at most 32 MiB and 20 pages per import; communicate a user-managed update prerequisite, with older-build PDF access unsupported. These proposals are not approved by the route decision alone.++## Non-Goals++- General image quantity/price redesign, currency expansion beyond the existing AUD behavior, or delivery-service API integration.+- PDF editing, combining separate files, multiple receipts per PDF, password entry or encrypted-document unlocking.+- Cloud OCR, automatic saving without review, PDF export generation, or unrelated photo-library repair.++### 1. PDF intake and original source++**User Story:** As a diner, I want to share or select a PDF receipt, so that I can review it without taking screenshots.++**Acceptance Criteria:**++1. <a name="1.1"></a>WHEN one PDF is shared to Foodnotes or selected through its receipt-import entry, Foodnotes SHALL admit it into one editable meal draft using the existing destination, account and review-confirmation patterns; unrelated thumbnail attachments SHALL not prevent an otherwise valid PDF share. +2. <a name="1.2"></a>WHEN PDF intake succeeds, Foodnotes SHALL retain the original PDF byte-for-byte and let the user open it from the draft and saved meal, view each displayable page, and identify pages that cannot be displayed; previews or extraction SHALL not replace or alter the original. +3. <a name="1.3"></a>WHEN a document cannot be opened as a PDF, requires a password to open, exceeds the inclusive 32 MiB/20-page limits, or the attempt contains more than one distinct PDF document, Foodnotes SHALL reject it before creating a new draft with an actionable explanation; alternate representations of one document SHALL not count as additional documents, and cancellation before admission SHALL leave existing meals and drafts unchanged. ++### 2. Text, scanned and multi-page extraction++**User Story:** As a diner, I want every page of my receipt considered, so that its items and meal details reach the same review.++**Acceptance Criteria:**++1. <a name="2.1"></a>WHERE a supported PDF contains selectable text, scanned pages or both, Foodnotes SHALL offer source-backed meal details and item names, quantities and prices using the same no-invention and confirmation semantics as image receipts; absent or ambiguous values SHALL remain blank or require the existing user-confirmation interaction, and each proposal SHALL remain traceable to its supporting original page(s). +2. <a name="2.2"></a>WHEN a supported PDF has multiple pages, Foodnotes SHALL consider all pages together as one receipt in document order, retain separate ordered items with their corresponding quantities/prices, and avoid creating dish items from repeated headers, carried totals or receipt totals; legitimate repeated items SHALL not be collapsed solely because their names repeat. +3. <a name="2.3"></a>WHEN PDF extraction ends, Foodnotes SHALL show the user whether each admitted page was processed or is explicitly incomplete, identify failed/unprocessed pages, and retain the original and editable draft for manual completion or retry; processed pages without usable evidence SHALL leave values blank, and complete processing SHALL not be presented as a guarantee that every field was recognised. ++### 3. Editable review and save++**User Story:** As a diner, I want to correct extracted values before saving, so that the meal reflects what I actually ordered.++**Acceptance Criteria:**++1. <a name="3.1"></a>WHEN PDF extraction proposes item quantities or prices, Foodnotes SHALL prefill the corresponding existing editable Quantity and Price AUD review fields, preserving the current validation and price interpretation rather than inventing unit prices or quantities from totals. +2. <a name="3.2"></a>WHEN the user corrects any review field, retries extraction, or leaves and resumes the draft, Foodnotes SHALL retain the user's corrections and prevent late proposals from overwriting them or updating a different draft/account generation. +3. <a name="3.3"></a>WHEN the user confirms a valid reviewed PDF meal, Foodnotes SHALL save the corrected item quantities, prices and meal details and show them unchanged after reopening; image receipt, camera and Photos SHALL retain their existing editable AUD quantity/price fields, blank/unknown handling, manual-correction protection, confirmation/save, destination/account fences and original-byte preservation. ++### 4. Durable source and compatibility++**User Story:** As a diner, I want my PDF source and corrected meal to survive normal data operations, so that I can refer to the receipt later.++**Acceptance Criteria:**++1. <a name="4.1"></a>WHEN a PDF-backed draft or meal is reopened after an app restart or supported in-place app upgrade/container relocation, Foodnotes SHALL retain its original-PDF association and reviewed values; an unavailable original SHALL be reported without deleting the meal or fabricating a replacement source. +2. <a name="4.2"></a>WHEN PDF-backed meals pass through existing supported sync, archive/restore or recovery, updated Foodnotes builds SHALL retain exact original PDF bytes, meal/source associations and corrected quantities/prices; readable export SHALL include the original PDF as a source file identifiable with its meal, without treating it as a food photo. +3. <a name="4.3"></a>WHEN the updated build reads existing image-only data or archives, Foodnotes SHALL preserve their values, source associations and image-review/save semantics. +4. <a name="4.4"></a>BEFORE creating the first PDF-backed draft, Foodnotes SHALL communicate that installations accessing the same library or restoring PDF-bearing archives must be updated; this SHALL be a user-managed prerequisite with older-build PDF access explicitly unsupported, and new content SHALL be represented as PDF rather than disguised as an image. ++### 5. Interruption and fallback++**User Story:** As a diner, I want interruptions to leave recoverable work, so that a failed import does not cost an existing meal or corrected draft.++**Acceptance Criteria:**++1. <a name="5.1"></a>WHEN the user cancels extraction or an extraction capability is unavailable, Foodnotes SHALL stop the active prefill attempt, retain any already admitted original and existing corrections, and offer the existing manual-review fallback without creating an automatic meal. +2. <a name="5.2"></a>WHEN sharing finishes while Foodnotes is closed or unable to admit the destination, Foodnotes SHALL follow the existing durable pending/unassigned-source behavior and present the PDF for review after supported admission; it SHALL not silently move the receipt to another account or library.
diff --git a/specs/pdf-receipt-import/tasks.md b/specs/pdf-receipt-import/tasks.mdnew file mode 100644index 0000000..f206e38--- /dev/null+++ b/specs/pdf-receipt-import/tasks.md@@ -0,0 +1,139 @@+---+references:+ - requirements.md+ - design.md+ - decision_log.md+metadata:+ execution: 16 tasks completed in eight red/green pairs; stream 1+ scope: Synthetic data only; no physical-device install or real-library repair or publication+ status: Approved; implementation complete+---+# T-2488 PDF receipt import implementation tasks++- [x] 1. RED — Write failing original-media and source-contract regressions <!-- id:u7n50tx -->+ - RED receipt: .build-logs/pdf-task1-red.log native Swift compilation fails for missing allOriginalSources+ - replaceOriginalLocators+ - receiptPages and pageIndex (exit 1; no tests executed). Five domain regressions cover photo isolation+ - legacy defaults and 32 generated rebasing cases.+ - Stream: 1+ - Owner: pdf-implementation+ - Requirements: [4.1](requirements.md#4.1), [4.2](requirements.md#4.2), [4.3](requirements.md#4.3), [3.3](requirements.md#3.3)+ - References: Foodnotes/Packages/FoodnotesCore/Sources/FoodnotesDomain/CaptureContracts.swift, Foodnotes/Packages/FoodnotesCore/Sources/FoodnotesDomain/DraftPhotos.swift, Foodnotes/Foodnotes/Persistence/DraftStorage.swift++- [x] 2. GREEN — Extend original-media contracts and all-original storage integration <!-- id:u7n50ty -->+ - GREEN: five focused PDF domain tests; full make test-domain: 73 domain + 11 archives + 8 handoff = 92 passed.+ - Focused FA48 native storage: two tests passed. Four synthetic storage-only byte retention cases; valid PDF parsing is independently covered in tasks 3/4.+ - Blocked-by: u7n50tx (RED — Write failing original-media and source-contract regressions)+ - Stream: 1+ - Requirements: [4.1](requirements.md#4.1), [4.2](requirements.md#4.2), [4.3](requirements.md#4.3), [3.3](requirements.md#3.3)+ - References: Foodnotes/Packages/FoodnotesCore/Sources/FoodnotesDomain/CaptureContracts.swift, Foodnotes/Packages/FoodnotesCore/Sources/FoodnotesDomain/DraftPhotos.swift, Foodnotes/Foodnotes/Persistence/DraftStorage.swift++- [x] 3. RED — Write failing bounded PDF reader and renderer tests <!-- id:u7n50tz -->+ - RED: native build exits 65 for absent PDFReceiptAdmission and PDFReceiptEvidence; .build-logs/pdf-task3-red-build.log. No tests executed.+ - Blocked-by: u7n50ty (GREEN — Extend original-media contracts and all-original storage integration)+ - Stream: 1+ - Requirements: [1.2](requirements.md#1.2), [1.3](requirements.md#1.3), [2.1](requirements.md#2.1), [2.3](requirements.md#2.3), [5.1](requirements.md#5.1)+ - References: Foodnotes/Foodnotes/Services/Capture/PDFReceiptAdmission.swift, Foodnotes/Foodnotes/Services/Capture/Extraction/PDFReceiptEvidence.swift, Foodnotes/FoodnotesTests/CaptureExtraction++- [x] 4. GREEN — Implement the bounded PDF reader and serial renderer <!-- id:u7n50u0 -->+ - GREEN: six native PDFReceiptReaderTests passed on FA48. Inclusive 32 MiB and 20 pages; valid zero/21 page rejection; locked/corrupt/hash/symlink rejection; cancellation/allocation failure/rotation crop covered.+ - 20-page huge-page synthetic native simulator render elapsed 0.046283417 seconds. Weak CGImage lifetime observer reports priorRasterRetained=false; 2048 long edge and 4 MP asserted for every raster. Rendering only; no model performance claim.+ - Receipt .build-logs/pdf-task4-green-native.log; retained xcresult Test-Foodnotes-2026.10.27_19-00-52-+1100.xcresult.+ - Blocked-by: u7n50tz (RED — Write failing bounded PDF reader and renderer tests)+ - Stream: 1+ - Requirements: [1.2](requirements.md#1.2), [1.3](requirements.md#1.3), [2.1](requirements.md#2.1), [2.3](requirements.md#2.3), [5.1](requirements.md#5.1)+ - References: Foodnotes/Foodnotes/Services/Capture/PDFReceiptAdmission.swift, Foodnotes/Foodnotes/Services/Capture/Extraction/PDFReceiptEvidence.swift, Foodnotes/FoodnotesTests/CaptureExtraction++- [x] 5. RED — Write failing PDF provider and durable intake tests <!-- id:u7n50u1 -->+ - RED: .build-logs/pdf-task5-red-build.log native build exits65 for missing provider/Files/compatibility services; no executed tests.+ - Blocked-by: u7n50u0 (GREEN — Implement the bounded PDF reader and serial renderer)+ - Stream: 1+ - Requirements: [1.1](requirements.md#1.1), [1.2](requirements.md#1.2), [1.3](requirements.md#1.3), [4.4](requirements.md#4.4), [5.2](requirements.md#5.2)+ - References: Foodnotes/FoodnotesShare/ShareViewController.swift, Foodnotes/SharedCapture/OriginalHandoffImageFile.swift, Foodnotes/Packages/FoodnotesCore/Sources/CaptureHandoff/FileSourceHandoff.swift, Foodnotes/Foodnotes/Services/Capture/HandoffImportCoordinator.swift++- [x] 6. GREEN — Implement atomic PDF share and Files intake services <!-- id:u7n50u2 -->+ - GREEN: 18 native tests across intake and retained CaptureInput/HandoffCoordinator suites pass. Final expanded receipt: 16 tests (9 PDF intake + 6 reader + 1 extreme raster geometry) pass; detailed .build-logs/pdf-task6-final-native.log and retained xcresult.+ - Real NSItemProvider/NSExtensionItem tests cover PDF+thumbnail/representations/duplicate bytes/distinct PDFs; built extension activation predicate is evaluated against native providers. Files scope/cancellation/copy mutation/version retention/compatibility/account/shared destination are covered.+ - Reader review fix: dedicated missing rasterDimensions API red receipt .build-logs/pdf-geometry-red-build.log followed by finite normalized arithmetic guard and extreme-dimension native green. No original bytes rewritten.+ - Blocked-by: u7n50u1 (RED — Write failing PDF provider and durable intake tests)+ - Stream: 1+ - Requirements: [1.1](requirements.md#1.1), [1.2](requirements.md#1.2), [1.3](requirements.md#1.3), [4.4](requirements.md#4.4), [5.2](requirements.md#5.2)+ - References: Foodnotes/FoodnotesShare/ShareViewController.swift, Foodnotes/SharedCapture/OriginalHandoffImageFile.swift, Foodnotes/Packages/FoodnotesCore/Sources/CaptureHandoff/FileSourceHandoff.swift, Foodnotes/Foodnotes/Services/Capture/HandoffImportCoordinator.swift++- [x] 7. RED — Write failing page evidence, row identity and review-retry tests <!-- id:u7n50u3 -->+ - RED: native compile exits65 for missing PDFReceiptRows, PDFReceiptRowRegistry, PDFCaptureExtractor and page-event APIs; .build-logs/pdf-task7-red-build.log. No executed cases claimed.+ - Subsequent runtime regressions genuinely exposed recursive draft observer assignment, underscaled raster placement and GIF-first provider selection; retained failed native logs document each. Fixed scoped behavior, not expectations.+ - Blocked-by: u7n50u2 (GREEN — Implement atomic PDF share and Files intake services)+ - Stream: 1+ - Requirements: [2.1](requirements.md#2.1), [2.2](requirements.md#2.2), [2.3](requirements.md#2.3), [3.1](requirements.md#3.1), [3.2](requirements.md#3.2), [5.1](requirements.md#5.1)+ - References: Foodnotes/Foodnotes/Services/Capture/Extraction/OnDeviceCaptureExtractor.swift, Foodnotes/Foodnotes/Services/Capture/Extraction/ProposalValidation.swift, Foodnotes/Foodnotes/Services/Capture/Extraction/ExtractionReview.swift, Foodnotes/Foodnotes/Services/Capture/CaptureReviewModel.swift++- [x] 8. GREEN — Implement page extraction and safe document reconciliation <!-- id:u7n50u4 -->+ - Final assembly follow-up: genuine native red6cases/1failed because ambiguous overlapping columns incorrectly finished processed; explicit assembly-omission flag now propagates incomplete without admitting the ambiguous item. Final scoped13cases passed, including20-page scan/Vision/injected-model path; .build-logs/pdf-task8-assembly-{red,green}-native.log.+ - Task9 future-red files were temporarily parked for this dependency-order repair only; no scheme/exclusion/config changes. Both restored byte-exact to original paths before task10, hashes in .build-logs/pdf-task9-pending-sources.json. Scoped task8 green is not full acceptance.+ - Blocked-by: u7n50u3 (RED — Write failing page evidence, row identity and review-retry tests)+ - Stream: 1+ - Requirements: [2.1](requirements.md#2.1), [2.2](requirements.md#2.2), [2.3](requirements.md#2.3), [3.1](requirements.md#3.1), [3.2](requirements.md#3.2), [5.1](requirements.md#5.1)+ - References: Foodnotes/Foodnotes/Services/Capture/Extraction/OnDeviceCaptureExtractor.swift, Foodnotes/Foodnotes/Services/Capture/Extraction/ProposalValidation.swift, Foodnotes/Foodnotes/Services/Capture/Extraction/ExtractionReview.swift, Foodnotes/Foodnotes/Services/Capture/CaptureReviewModel.swift++- [x] 9. RED — Write failing PDF save, sync and lifecycle preservation tests <!-- id:u7n50u5 -->+ - Native red build exits65 for missing accepted-field provenance / dismissed occurrence / evidence-anchor contracts. Domain red Swift build exits1 for missing provenance validation/remapping/field APIs. .build-logs/pdf-task9-red-build.log and pdf-task9-domain-red.log; no tests executed or zero-test pass claimed.+ - Blocked-by: u7n50u4 (GREEN — Implement page extraction and safe document reconciliation)+ - Stream: 1+ - Requirements: [1.2](requirements.md#1.2), [3.2](requirements.md#3.2), [3.3](requirements.md#3.3), [4.1](requirements.md#4.1), [4.2](requirements.md#4.2), [4.3](requirements.md#4.3)+ - References: Foodnotes/Foodnotes/Persistence/DraftMaterializer.swift, Foodnotes/Foodnotes/Persistence/RepositoryStorage.swift, Foodnotes/Foodnotes/Services/Sync/AppleCloudCodec.swift, Foodnotes/Foodnotes/Services/Sharing/TransferCapture.swift, Foodnotes/Foodnotes/Services/Sharing/AppleTransferAssets.swift++- [x] 10. GREEN — Implement saved source provenance and typed PDF transport <!-- id:u7n50u6 -->+ - P1 review follow-up: genuine runtime red6tests/1failed with receipt row occurrence on empty-model/manual-save. Fixed saved projection: retain draft retry registry; persist only actual/tombstoned occurrence rows, with unmaterialized rows represented as source evidence rather than invented dishes. Four model modes (empty/throwing/partial/rejected) now manually complete/save/reopen successfully with exact bytes. Added absent-row retry confirmation protection. Native11/11 provenance+retry cases pass; .build-logs/pdf-task10-fallback-{red,green}-native.log. Strict lint passes.+ - A later automatic approval rejection was known not executed; the exact regression action was retried once and accepted after correctly enveloped trusted codex_delegation/input human approval evidence. Exact shell command/target/original denial and accepted-once outcome retained in .build-logs/pdf-task10-fallback-authorized-command.txt and pdf-task10-fallback-approval-receipt.json. Initial test missing-await compile error was corrected before genuine runtime red and is not behavioral proof.+ - Blocked-by: u7n50u5 (RED — Write failing PDF save, sync and lifecycle preservation tests)+ - Stream: 1+ - Requirements: [1.2](requirements.md#1.2), [3.2](requirements.md#3.2), [3.3](requirements.md#3.3), [4.1](requirements.md#4.1), [4.2](requirements.md#4.2), [4.3](requirements.md#4.3)+ - References: Foodnotes/Foodnotes/Persistence/DraftMaterializer.swift, Foodnotes/Foodnotes/Persistence/RepositoryStorage.swift, Foodnotes/Foodnotes/Services/Sync/AppleCloudCodec.swift, Foodnotes/Foodnotes/Services/Sharing/TransferCapture.swift, Foodnotes/Foodnotes/Services/Sharing/AppleTransferAssets.swift++- [x] 11. RED — Write failing PDF archive, restore and readable-export tests <!-- id:u7n50u7 -->+ - RED host compile exits1 for absent ArchiveAssetRecord.receiptProvenance / ArchiveIO.original; native red build exits65 for missing archive provenance plus corrected fixture initializer errors. No executed cases claimed; .build-logs/pdf-task11-domain-red.log and pdf-task11-native-red-build.log.+ - Initial host test-write/run was denied before execution under obsolete T2489 scope; one identical retry accepted after fuller trusted parent input linked the delivered16-task PDF plan to human Implement it. Exact action SHA2070a4b71a05e796468590bb7e65b613b3801c214a1f18133a910dc40fbd8a4f, .build-logs/pdf-task11-authorized-command.txt and approval-receipt.json.+ - Blocked-by: u7n50u6 (GREEN — Implement saved source provenance and typed PDF transport)+ - Stream: 1+ - Requirements: [1.2](requirements.md#1.2), [4.1](requirements.md#4.1), [4.2](requirements.md#4.2), [4.3](requirements.md#4.3), [4.4](requirements.md#4.4)+ - References: Foodnotes/Packages/FoodnotesCore/Sources/FoodnotesArchives/ArchiveJSON.swift, Foodnotes/Packages/FoodnotesCore/Sources/FoodnotesArchives/ArchiveZIPCodec.swift, Foodnotes/Packages/FoodnotesCore/Sources/FoodnotesDomain/Archives/ArchiveRecordsMapping.swift, Foodnotes/Foodnotes/Services/Archives/MarkdownExport/MarkdownExporter.swift++- [x] 12. GREEN — Implement versioned PDF archive and export parity <!-- id:u7n50u8 -->+ - GREEN:4 host PDF archive cases pass with8 seeded byte/provenance/tombstone variants. Full package101pass (78domain/15archives/8handoff). Native PDF save/fallback/readableZIP/restore collision aggregate8/8pass; affected legacy archive/fault/resource/collision/image aggregate12/12pass. Strict lint passes. .build-logs/pdf-task12-domain-final.log, pdf-task12-native-green-detail.log, pdf-task12-native-legacy-detail.log.+ - PDF-bearing records/manifests emit schema2 only, image-only writers retain1; version equality and strict nested provenance/unknown version/field checks precede extraction writes. CoreGraphics validates actual PDF open/unlocked/page/size without rendering. Canonical documents/UUID.pdf entries retain exact bytes; unreadable sources and typed paths reject.+ - Archive mappings preserve accepted origin and inactive occurrence tombstones; restore collisions remap source/occurrence/page links while source-local anchors remain stable. Combined image/PDF prospective plans normalize correct version, including identical replay with no new meals. ReadableZIP links exact PDF under its meal without image embedding.+ - Blocked-by: u7n50u7 (RED — Write failing PDF archive, restore and readable-export tests)+ - Stream: 1+ - Requirements: [1.2](requirements.md#1.2), [4.1](requirements.md#4.1), [4.2](requirements.md#4.2), [4.3](requirements.md#4.3), [4.4](requirements.md#4.4)+ - References: Foodnotes/Packages/FoodnotesCore/Sources/FoodnotesArchives/ArchiveJSON.swift, Foodnotes/Packages/FoodnotesCore/Sources/FoodnotesArchives/ArchiveZIPCodec.swift, Foodnotes/Packages/FoodnotesCore/Sources/FoodnotesDomain/Archives/ArchiveRecordsMapping.swift, Foodnotes/Foodnotes/Services/Archives/MarkdownExport/MarkdownExporter.swift++- [x] 13. RED — Write failing PDF review, page-status and source-viewer tests <!-- id:u7n50u9 -->+ - Native compile red exits65 for missing PDF viewer/model/status APIs; no executed cases. pdf-task13-red-build.log. Actual later stale-page representable regression failed before fix; pdf-viewer-stale-red-detail.log.+ - Blocked-by: u7n50u8 (GREEN — Implement versioned PDF archive and export parity)+ - Stream: 1+ - Requirements: [1.2](requirements.md#1.2), [2.3](requirements.md#2.3), [3.1](requirements.md#3.1), [3.2](requirements.md#3.2), [3.3](requirements.md#3.3), [4.1](requirements.md#4.1), [4.4](requirements.md#4.4), [5.1](requirements.md#5.1)+ - References: Foodnotes/Foodnotes/Features/Capture/ManualReviewView.swift, Foodnotes/Foodnotes/Features/Capture/DraftPhotoFields.swift, Foodnotes/Foodnotes/Features/Meals/MealCaptureOriginals.swift, Foodnotes/Foodnotes/Services/Capture/ReceiptSourceViewer.swift++- [x] 14. GREEN — Implement PDF review UI and read-only source presentation <!-- id:u7n50ua -->+ - Read-only verified-byte PDFKit viewer and draft/saved media dispatch, explicit page state/retry and first-install compatibility notice implemented. Actual light/dark/AX3 renders inspected; accessible navigation adjusted. Contextual field/item supporting-page links consume draft accepted/current/suggested origins and saved provenance. Actual unavailable-page representable regression clears stale content and restores valid navigation. Independent UI and final critic reviews close all P1/P2 findings.+ - Blocked-by: u7n50u9 (RED — Write failing PDF review, page-status and source-viewer tests)+ - Stream: 1+ - Requirements: [1.2](requirements.md#1.2), [2.3](requirements.md#2.3), [3.1](requirements.md#3.1), [3.2](requirements.md#3.2), [3.3](requirements.md#3.3), [4.1](requirements.md#4.1), [4.4](requirements.md#4.4), [5.1](requirements.md#5.1)+ - References: Foodnotes/Foodnotes/Features/Capture/ManualReviewView.swift, Foodnotes/Foodnotes/Features/Capture/DraftPhotoFields.swift, Foodnotes/Foodnotes/Features/Meals/MealCaptureOriginals.swift, Foodnotes/Foodnotes/Services/Capture/ReceiptSourceViewer.swift++- [x] 15. RED — Write failing automated PDF entry-to-save acceptance journeys <!-- id:u7n50ub -->+ - Actual3native acceptance cases failed4issues: Files request absent and valid/invalid picked selections deleted. pdf-task15-red-detail.log. Earlier scaffold enum error preserved separately, not behavior red. Native Files picker coexistence and pending-share notice/correction/save/reopen/page UI journeys added with isolated synthetic launch fixture.+ - Blocked-by: u7n50ua (GREEN — Implement PDF review UI and read-only source presentation)+ - Stream: 1+ - Requirements: [1.1](requirements.md#1.1), [1.2](requirements.md#1.2), [1.3](requirements.md#1.3), [2.1](requirements.md#2.1), [2.2](requirements.md#2.2), [2.3](requirements.md#2.3), [3.1](requirements.md#3.1), [3.2](requirements.md#3.2), [3.3](requirements.md#3.3), [4.1](requirements.md#4.1), [4.2](requirements.md#4.2), [4.3](requirements.md#4.3), [4.4](requirements.md#4.4), [5.1](requirements.md#5.1), [5.2](requirements.md#5.2)+ - References: Foodnotes/Foodnotes/App/AppCapture.swift, Foodnotes/Foodnotes/Features/Capture/NativeImagePicker.swift, Foodnotes/Config/FoodnotesShare-Info.plist, Foodnotes/FoodnotesUITests, Foodnotes/FoodnotesTests/CaptureExtraction++- [x] 16. GREEN — Wire app PDF entry points and pass the final regression gates <!-- id:u7n50uc -->+ - Completed Files action/native single-PDF picker and owned security-scoped copy without deleting selected files; synthetic pending-share UI fixture uses real durable inbox with production launch isolation. Final source 495e526 passes lint/config/boundary/startup, build/build-tests and complete native aggregate: 32 XCTest plus409 SwiftTesting in107 suites; no test skips/failures. Logs pdf-header-static-final.log and pdf-header-native-final-detail.log.+ - Host102 cases passed (78 domain/16 archive/8 handoff); package source unchanged by final app-only fixes. Six distinct selected UI journeys have passing receipts: two refreshed PDF journeys on495e526 plus capture-entry coexistence and retained Photos/original, draft photo and real framing journeys. Earlier genuine failures and fixture prerequisites retained. Actual Files UI opens/cancels; picked URL/save and extension provider payloads are native framework/composition coverage, not external host automation.+ - Actual production model20 calls completed357.599s; cancellation0.106s; wrapper peakRSS23855104 bytes excludes unambiguously unattributable OS inference services/accelerator memory. Prompt/budget/chunk implementation unchanged by final receipt-header classification. Phase-final independent review closes all P1/P2. No deployment, merge, push or live-data action.+ - Blocked-by: u7n50ub (RED — Write failing automated PDF entry-to-save acceptance journeys)+ - Stream: 1+ - Requirements: [1.1](requirements.md#1.1), [1.2](requirements.md#1.2), [1.3](requirements.md#1.3), [2.1](requirements.md#2.1), [2.2](requirements.md#2.2), [2.3](requirements.md#2.3), [3.1](requirements.md#3.1), [3.2](requirements.md#3.2), [3.3](requirements.md#3.3), [4.1](requirements.md#4.1), [4.2](requirements.md#4.2), [4.3](requirements.md#4.3), [4.4](requirements.md#4.4), [5.1](requirements.md#5.1), [5.2](requirements.md#5.2)+ - References: Foodnotes/Foodnotes/App/AppCapture.swift, Foodnotes/Foodnotes/Features/Capture/NativeImagePicker.swift, Foodnotes/Config/FoodnotesShare-Info.plist, Foodnotes/FoodnotesUITests, Foodnotes/FoodnotesTests/CaptureExtraction