diff --git a/AGENTS.md b/AGENTS.md index 24d9af6b..30b06ee2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -59,7 +59,7 @@ Do not weaken these unless the user explicitly asks for a product change. - **INV-11:** Failure thresholds intentionally stop bad runs: 5 consecutive failures or 20 total failures. - **INV-12:** Deduplicate moves files to the macOS Trash only. Hard delete is not available in the production UI or executor commit path. - **INV-13:** The dedupe audit receipt directory (`.organize_logs/`) is preflighted before any deletion. An unwritable destination aborts the commit with `ReceiptPreflightError` and zero files touched. -- **INV-14:** Pair-as-unit conflict resolution is **Keep-wins**: when either half of a RAW+JPEG or Live Photo HEIC+MOV pair has an effective Keep — explicit, automatic (the cluster's auto-suggested keeper), or implicit (default-Keep in an unreviewed low/medium-confidence cluster) — neither half is deleted. Pair-fanout deletes a partner only when that partner is itself marked Delete, auto-selected for Delete by a high-confidence cluster, or is a singleton outside any cluster. When a plan is built from reviewed groups only, a partner that belongs to a group not yet reviewed is never added by fan-out; its own group decides once it is reviewed. Metadata sidecars (`.xmp`, and `.aae` edit instructions, including the iPhone form where `IMG_.` owns `IMG_E.aae` in the same folder with exactly the same digits) extend this rule: a sidecar travels with its parent photo as a unit and is trashed only when **every** photo that references it is also being deleted (and no surviving pair partner shares its basename). A sidecar shared across a basename unit — `photo.xmp` applies to both `photo.raw` and `photo.jpg` — survives if any owner is kept. +- **INV-14:** Pair-as-unit conflict resolution is **Keep-wins**: when either half of a RAW+JPEG or Live Photo HEIC+MOV pair has an effective Keep — explicit, automatic (the cluster's auto-suggested keeper), or implicit (default-Keep in an unreviewed low/medium-confidence cluster) — neither half is deleted. Pair-fanout deletes a partner only when that partner is itself a duplicate: marked Delete, or auto-selected for Delete by a high-confidence cluster. A partner outside every cluster stays, because it is the only copy of that content; the one exception is a Live Photo video (never clustered), which goes with its still only when a copy the plan keeps has its own video. Among otherwise identical copies, the one that has a RAW or Live Photo video partner is the suggested keeper, so the lone copy is the one removed. When a plan is built from reviewed groups only, a partner that belongs to a group not yet reviewed is never added by fan-out; its own group decides once it is reviewed. Metadata sidecars (`.xmp`, and `.aae` edit instructions, including the iPhone form where `IMG_.` owns `IMG_E.aae` in the same folder with exactly the same digits) extend this rule: a sidecar travels with its parent photo as a unit and is trashed only when **every** photo that references it is also being deleted (and no surviving pair partner shares its basename). A sidecar shared across a basename unit — `photo.xmp` applies to both `photo.raw` and `photo.jpg` — survives if any owner is kept. - **INV-15:** Organize and dedupe traversal must not follow symlinks or aliases by default. Skip symlink files/directories, app bundles, photo libraries, packages, hidden system-like containers, and any path that escapes the selected root. - **INV-16:** Fast destination scans are validating scans: cached records are trusted only when the file still exists and size/mtime still match; stale cache rows are refreshed or removed. - **INV-17:** Dedupe mutation plans are immutable content-verified snapshots. The planner never reads live filesystem identity; missing target hashes fail closed and exclude that path from deletion. diff --git a/DECISIONS.md b/DECISIONS.md index 60bb1fbe..844e1d1d 100644 --- a/DECISIONS.md +++ b/DECISIONS.md @@ -1,5 +1,14 @@ # Decisions +## Release 2.1 scope and press lens (2026-11-30) + +- Owner: 2.1 ships when ranks 1 to 11 of the next-half review and anything added since are done; there is no date. Press outreach follows 2.1. +- Owner, 2026-12-01: accepted the build order, the press scope additions and cards B12 (Shortcuts and Finder actions), B13 (reviewer sample library) and B14 (technical post and press page) in `docs/plan/next-half/README.md`, "Release 2.1 scope and press lens". NAS public is required for 2.1. +- Agent's judgment, not challenged by the owner: Guardian mirror and restore stay deferred and B9 (scrub-only) is the press headline; card ingest, a library timeline, metadata-complete Photos export and direct iPhone import are declined for 2.1. +- Owner, 2026-11-30: B12 gains a Finder Quick Action on folders that opens the Organize preview. Owner, 2026-12-01: B12 also gains a Quick Action on files that copies them into their dated place in the default destination. It completes from Finder only when every item has a certain date, no conflicting-date warning and no name collision; otherwise it opens the app's preview (full rules in the B12 card). +- Owner, 2026-12-01: B9 gains an explicit "start tracking this folder as it is today" baseline through `GuardianManifestUpdater.accept`, which INV-23 already permits. +- Owner, 2026-12-01: release state is tracked in `docs/plan/release-2.1/PROGRESS.md` (features, owner checks, release gates). Plan folders stay the source of truth; no GitHub Project or per-work-package issues. + ## Release 2.1 bug sweep (2026-11-29) - Pair fan-out and unreviewed groups (INV-14; decided by the agent during the sweep, approved by the owner 2026-11-29): the commit plan is built from reviewed groups only, so a RAW or Live Photo partner sitting in an unreviewed group had no decision and was added to the plan while its own group showed it as kept. The planner now takes `fanoutProtectedPaths`; the store passes the members of unreviewed groups for the reviewed plan, the free removal batch and the lane summaries. A held-back partner stays until its own group is reviewed, which can leave a RAW without its JPEG. Planning over all groups is unchanged. @@ -11,6 +20,25 @@ - A count of 1 on the dedupe unlock button reads "Unlock to Remove 1 Duplicate" (implementer's wording; approved by the owner 2026-11-29). - Not built, needs a design decision: skipping a companion whose owner failed verification (edit preservation B-2, item 3). Copy jobs carry no owner link and owner and companion can be prepared in the same concurrent batch. +## Release 2.1 second batch (2026-11-29) + +Owner decisions, given as answers to a question list on 2026-11-29: + +- Lone RAW (INV-14, approved): the copy that has a RAW or Live Photo video partner is the suggested keeper, and a partner is trashed only if it is itself a duplicate. Built as a keeper tie-break after RAW-first and before the path tie-break in `DuplicateClusterer`, and a guard in planner step 5: a partner outside every cluster stays. +- Fix before 2.1 (approved): the free-removal offer speed, Photos staging kept for an unfinished copy (D-PIR-130 in `docs/plan/photos-import-resume/DECISIONS.md`), the Shortcut using stored preferences, and saved-review loss. +- Version 2.1 and draft 2.1 store text in English and German (approved to draft; the text itself is not reviewed). + +Decided by the agent while building these; the owner has not reviewed them: + +- Live Photo videos are never hashed or clustered, so "outside every cluster" proves nothing for a MOV. A MOV outside every cluster goes with its still only when a copy the plan keeps has its own MOV; otherwise it stays as a standalone video. MOV content is not compared, as before. +- The free removal batch is found by searching over a prefix of the lane-ordered groups, starting from the prefix the full plan's per-group counts predict, instead of growing one group at a time. Every candidate is still a real planner result checked against the limit and the full plan. In rare pair cases the batch can differ from the old walk: it may take a later prefix that passes, and it does not probe one group past a passing first guess. +- A dedupe commit that moved 0 files keeps the saved review. +- Quick Review "Accept the Rest" accepts only the unreviewed groups from the current position on; groups skipped earlier stay unreviewed, and the button count is the same list. +- The Shortcut also takes the parallel-transfer preference, since worker count means nothing without it. It still does not take the event-suggestion preference. +- Photos staging is also kept by the post-run cleanup when a pending job reads from it, so a copy that stopped, failed or hit the free limit in the same session can be finished. + +Known items left for a later release (owner did not pick them for 2.1): companion owner link (edit preservation B-2 item 3 and `_collision_N`); a stopped free copy that may be resumable only from the menu (unverified); Shortcut result text and Core error messages in English only; setup edge cases (late overlap check after relaunch, profile saved from one dropped file); two iPhone `.aae` name forms ending "Not copied"; the keeper-reason text does not mention the partner tie-break; `reviewedDeletionPlan()` and `freeBatchOffer` each compute the full reviewed plan. + ## German translation import (2026-11-15) - Merge only German translations for existing keys from `/Users/nishithnand/Downloads/Translation DE`; preserve current keys, English, other languages and extraction metadata. The supplied catalogs predate newer app copy, which continues to fall back to English. Omit the unused incoming `%d duplicates found` key. diff --git a/docs/APP_STORE_METADATA.md b/docs/APP_STORE_METADATA.md index 92b5332b..f3dc2a12 100644 --- a/docs/APP_STORE_METADATA.md +++ b/docs/APP_STORE_METADATA.md @@ -13,7 +13,7 @@ Copy-paste-ready source for Chronoframe's current Mac App Store listing. Charact | Bundle ID | `com.nishith.chronoframe` | | Primary category | Photo & Video | | Secondary category | Utilities | -| Version | `2.0` | +| Version | `2.1` | | Copyright | `2026 Nishith Nand` | | Age rating | 4+ (no objectionable content) | @@ -72,22 +72,33 @@ The owner confirmed there are no existing users (2026-10-16), so the earlier pai > duplicate,dedupe,photos,organizer,EXIF,cleanup,media,folder,backup,video,sort,library,metadata -## What's New (release notes for version 2.0) +## What's New (release notes for version 2.1) -> Chronoframe 2.0 brings new ways to build and care for your photo library: +Version 2.0's text is kept in `marketing/release-2.0/metadata/whats_new.txt`. + +> Chronoframe 2.1 makes the first run clearer and keeps your edits safe. > -> • Import selected original photos and videos from Apple Photos without changing the Photos library. -> • Register watched source folders, see an estimate of new items, and review each import before copying. -> • Review similar videos with optional perceptual matching, alongside exact photo and video duplicates. -> • Preview your library with contact sheets and timelines, compare duplicates, and choose what moves to Trash. -> • Improved copy compatibility on external drives, visible duplicate names in Trash, interruption recovery, and clearer verification and history. -> • Refined layouts and accessibility throughout the organizing and duplicate-review workflows. +> • Chronoframe now speaks German and follows your Mac's language setting. +> • A short guided setup on first launch, and a preview that shows the free limit and how your library will be arranged before anything is copied. +> • Try it free: copy one month of new photos, or remove whole groups of duplicates, within the free allowance. The allowance and the one-time unlock are unchanged. +> • Edit files (.xmp and .aae) are copied with their photo, and Deduplicate never selects an edited version, such as IMG_0001-edited.jpg, on its own. +> • Undo This Copy on the completion screen, with a count showing that every file found is accounted for. +> • Fixes: conflicting capture dates are flagged in the preview, saved duplicate reviews survive a relaunch, a Photos import can be stopped and resumed, and the live Copied count counts only files that were copied. > -> Dates near midnight now use the capture date’s recorded time zone. For a previously organized library, use Health → Reorganize to correct affected destination folders; originals are unchanged. +> No subscription. Your source files and Photos library remain untouched. + +### Was ist neu (Deutsch, Version 2.1) + +> Chronoframe 2.1 macht den ersten Start übersichtlicher und schützt deine Bearbeitungen. > -> Now free to download: organize 500 files and move 100 duplicates to Trash before purchasing. These allowances are cumulative per Apple Account on each Mac. One $14.99 US lifetime unlock removes the limits, with Family Sharing. Scanning, preview, review, and history remain free; revert remains available without purchasing and returns the corresponding allowance. +> • Chronoframe gibt es jetzt auf Deutsch und folgt der Sprache deines Macs. +> • Eine kurze geführte Einrichtung beim ersten Start und eine Vorschau, die das kostenlose Limit und die Struktur deiner Mediathek zeigt, bevor etwas kopiert wird. +> • Kostenlos ausprobieren: Kopiere einen Monat neuer Fotos oder entferne ganze Duplikatgruppen im Rahmen des kostenlosen Kontingents. Kontingent und einmalige Freischaltung bleiben unverändert. +> • Bearbeitungsdateien (.xmp und .aae) werden zusammen mit ihrem Foto kopiert, und beim Bereinigen von Duplikaten wählt Chronoframe eine bearbeitete Version, etwa IMG_0001-edited.jpg, nie von selbst aus. +> • „Diesen Kopiervorgang rückgängig machen…“ auf dem Abschlussbildschirm, mit einer Zählung, die zeigt, dass alle gefundenen Dateien berücksichtigt sind. +> • Korrekturen: Widersprüchliche Aufnahmedaten werden in der Vorschau markiert, gespeicherte Duplikatprüfungen bleiben nach einem Neustart erhalten, ein Fotos-Import lässt sich anhalten und fortsetzen, und der laufende Zähler „Kopiert“ zählt nur tatsächlich kopierte Dateien. > -> No subscription. Your organizing source files and Photos library remain untouched. +> Kein Abo. Deine Originaldateien und deine Fotos-Mediathek bleiben unverändert. ## Review Notes @@ -103,6 +114,10 @@ The purchase path below leads the saved review notes; it requires a build with t > > LAUNCH: Version 2.0 launches directly as a free download with the $14.99 US lifetime unlock. There are no existing customers to migrate and no paid rollout or acquisition-date legacy unlock. New customers receive the allowance regardless of the app transaction's original purchase date. Submit the app and first non-consumable together. +### Version 2.1 addendum (draft) + +No new in-app purchase, product, price or allowance cap. Version 2.1 adds a guided first-run setup, a free copy of one month of new files and a free removal of whole duplicate groups, both inside the existing 500-file and 100-duplicate allowance, German localization, and protection for edit files. The free month lists its files and waits for confirmation before copying. The purchase path in the notes above is unchanged. Update the saved App Review notes in App Store Connect with this paragraph when 2.1 is submitted. + ## App Privacy (questionnaire answers) These mirror `docs/PRIVACY_POLICY.md` and `ui/Resources/PrivacyInfo.xcprivacy`. diff --git a/docs/APP_STORE_RELEASE.md b/docs/APP_STORE_RELEASE.md index 7d7587f0..8730c089 100644 --- a/docs/APP_STORE_RELEASE.md +++ b/docs/APP_STORE_RELEASE.md @@ -19,7 +19,7 @@ Chronoframe is ready to submit only when all items below are complete: - Internal TestFlight passes the manual matrix below, including the free trial and unlock rows, and the focused manual session in `remaining-work-plan.md`. - App Store metadata, screenshots, privacy policy URL, support URL, and pricing are complete in App Store Connect. - The in-app purchase exists in App Store Connect with Family Sharing ON, and is attached to this version for submission. -- `ChronoframeUnlock.defaultPolicy()` disables both live and cached legacy unlocks. A new customer receives the allowance regardless of acquisition date; the verified non-consumable unlock removes limits. `MARKETING_VERSION` is `2.0`. +- `ChronoframeUnlock.defaultPolicy()` disables both live and cached legacy unlocks. A new customer receives the allowance regardless of acquisition date; the verified non-consumable unlock removes limits. `MARKETING_VERSION` is `2.1`. ## App Store Connect Metadata diff --git a/docs/FAQ.md b/docs/FAQ.md index f600f1ed..2a554643 100644 --- a/docs/FAQ.md +++ b/docs/FAQ.md @@ -136,7 +136,7 @@ A: No, not for now. Deduplicate moves files to the macOS Trash, and Chronoframe **Q: Can I organize into a folder on my NAS?** -A: Only when the share supports a rename that refuses to replace an existing file. Chronoframe checks this before it plans anything and stops if the share can't guarantee it. Nothing is copied, and your originals are untouched. Many SMB shares, including the Synology share tested, do not support it. Copying from a share to a folder on this Mac is not affected. See [Troubleshooting](./TROUBLESHOOTING.md#nas-and-network-folder-issues). +A: Not over SMB, which is how a Mac normally connects to a NAS. Chronoframe copies into a network folder only when it can use a rename that refuses to replace an existing file, and macOS does not offer that on SMB connections. This comes from macOS, not from your NAS brand or its settings, so there is no NAS option to change. Chronoframe checks before it plans anything and stops; nothing is copied, and your originals are untouched. Copying from a share to a folder on this Mac is not affected, so you can organize the photos on a NAS onto this Mac or an attached drive. See [Troubleshooting](./TROUBLESHOOTING.md#nas-and-network-folder-issues). **Q: What if a file changes after a deduplicate scan?** diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.md index 9b5c89b5..e6697f94 100644 --- a/docs/TROUBLESHOOTING.md +++ b/docs/TROUBLESHOOTING.md @@ -256,12 +256,12 @@ The NAS Library workspace isn't available in release builds yet. The copy rules, **Message:** "This network folder can't guarantee that a copy never replaces an existing file, so Chronoframe won't organize into it. Choose a folder on this Mac or an attached drive. Nothing was copied, and your originals were untouched." -**Problem:** Before it plans a preview or a copy into a network folder, Chronoframe checks that the share supports a rename that refuses to replace an existing file. This share doesn't, so Chronoframe stops before scanning or copying instead of using a weaker method. Many SMB shares, including the Synology share tested, don't support it. +**Problem:** Before it plans a preview or a copy into a network folder, Chronoframe checks that the share supports a rename that refuses to replace an existing file. macOS does not offer that rename on SMB connections, so Chronoframe stops before scanning or copying instead of using a weaker method. This comes from macOS, not from your NAS brand or its settings; it was confirmed on a Synology share and applies to SMB shares in general. **Solution:** - Choose a destination folder on this Mac or an attached drive - Copying from the share to a folder on this Mac is not affected -- Choosing the same network folder again will stop the same way; Chronoframe checks again each time, so a different share or server setup is picked up +- Changing settings on the NAS will not help. Chronoframe checks again each time, so if a future macOS version adds support, the same folder will start working without an update ### "The network folder ... disconnected or changed" diff --git a/docs/next-half-product-review-2026-11-07.md b/docs/next-half-product-review-2026-11-07.md index e32096b1..0fa03166 100644 --- a/docs/next-half-product-review-2026-11-07.md +++ b/docs/next-half-product-review-2026-11-07.md @@ -10,10 +10,12 @@ > | 2 | Dedupe review survives relaunch | Done: #267 (UI-test isolation #276). | > | 3 | Visible, cancellable, resumable Photos import | Done in part: #268 "Stop and resume a Photos import", #270. Whether bounded staging and checkpoint-by-complete-asset are fully delivered is unverified; see `docs/plan/photos-import-resume/PROGRESS.md`. | > | 4 | Find and account (item-level reconciliation plus original-name lookup) | Not started on main (plan folder only). | -> | 5 | First ten minutes (preflight, free batch, proof) | Not delivered as scoped; only wording changes landed (#278). | +> | 5 | First ten minutes (preflight, free batch, proof) | Superseded 2026-11-28 by first-run experience, shipped in #307 to #311. | > | 6 (B11) | Already-archived view and date-range selection in Photos import | Not started. | > | 7 to 11 | Batch clock correction, protected folders then keeper preference, XMP companions, verify-my-archive (scrub-only Guardian), Takeout rescue | Not started. The conflicting-date review these build on shipped: #261, #272, #273. | > +> **Update 2026-11-30:** XMP companions (rank 9) shipped in #299 together with edited Photos versions, so "Edited-appearance import from Photos" under "Decided against" below no longer holds. The remaining ranks are ordered for release 2.1 in `docs/plan/next-half/README.md`, "Release 2.1 scope and press lens"; that order supersedes the ranking below. +> > Preconditions in the review are met or changed: build 508 is superseded; V2 is public and Free with a $14.99 unlock since 2026-10-22 (see `docs/APP_STORE_RELEASE.md`). Open PRs right now (#282 run-outcome accuracy, #283 marketing tooling, #284 German UI fit) are not part of this list. ## Product judgment diff --git a/docs/plan/nas-public/DECISIONS.md b/docs/plan/nas-public/DECISIONS.md index 3437e4e2..95421bef 100644 --- a/docs/plan/nas-public/DECISIONS.md +++ b/docs/plan/nas-public/DECISIONS.md @@ -48,3 +48,5 @@ Same as every next-half plan: keep every invariant and every `docs/NAS_REQUIREME - **D-NASP-127 H2 corpus built locally and copied (2026-11-08).** `make-corpus` straight onto the share failed on its 7th file: the Synology refuses to create `@eaDir` over SMB (the folder silently never appears), so the generator's `@eaDir` exclusion fixtures can't be written. The corpus was generated locally with the same seed (manifest SHA-256 `caf67e8d93c4b0c123701e76ed8f2cf4caf36c0f047a8405e1d8fc8d2c98008c`) and copied with `rsync -rt --exclude '@eaDir'` to `/Volumes/photo/chronoframe-h2-corpus-2` (9,998 of 10,000 files; the two missing are the `@eaDir` fixtures, which an SMB client can never see on this server). `assess-parity` compares against an exhaustive hash of what is actually on the share, so parity stays valid. Follow-up (not done): `make-corpus` could skip fixtures the server refuses. The first attempt left `/Volumes/photo/chronoframe-h2-corpus` (6 files) for the owner to delete. - **D-NASP-128 H6 reworded (2026-11-08).** Copying into this profile is refused (D-NASP-115), so "each way" becomes share → Mac verified copy plus refusal evidence (H-NASP-3) for Mac → share. The quota fault moves to a local 2 GiB disk image destination, because a DSM quota change is an account setting the agent does not make. - **D-NASP-129 Disk-space resume check looks wrong (observation, not fixed, 2026-11-09).** In H6's disk-full run the CLI paused three times ("71 MB free, 106 MB needed", then 61 MB), then printed "Disk space check passed. Resuming run." while still short, and the next copy hit ENOSPC. Safety held (no partial file under a final name, receipt ABORTED, originals untouched), but the resume condition should be reviewed. Not folded into NASP; flagged for the owner. +- **D-NASP-130 The H1 result is a macOS SMB client limit, not a Synology one (finding, 2026-12-01; no decision made).** Apple's published SMB client source (`apple-oss-distributions/SMBClient`, `main`, `kernel/smbfs/smbfs_vnops.c` and `smbfs_vfsops.c`, read 2026-12-01) contains no `RENAME_EXCL` handling, never sets `VOL_CAP_INT_RENAME_EXCL`, and `smbfs_vnop_link` returns `err_link`, so hard links are not available as a no-replace install either. That matches H1 on macOS 27 (P03 ENOTSUP on a free name). Limits: the published source may not match the macOS 27 kernel extension, and only one server was probed. If it holds, P03 cannot pass on any SMB share, so (a) D-NASP-115's "this profile" is every SMB destination, and (b) the FLAG row's condition "every row above is `pass-hardware`" cannot be met while H1 expects P03 to pass. Open for the owner: reword H1's expectation to "P03 result recorded and the app refuses copying into the share (H-NASP-3)", or reopen ADR-NAS-03. Exclusive create (`O_CREAT | O_EXCL`) is the only no-replace primitive left on SMB; it is the basis of options B and C that D-NASP-115 rejected. +- **D-NASP-131 H1 reworded; copying into an SMB share stays refused (owner, 2026-12-01).** Nishith chose option A after D-NASP-130: keep ADR-NAS-03 and INV-28 as written and do not reopen the exclusive-create install paths. H1 now expects the P03 result to be recorded, P04 and P05 to pass, and the refusal to be proven by H-NASP-3. NAS public therefore means assessment, review and verified copies from a share to this Mac. FAQ and TROUBLESHOOTING now say the limit comes from macOS on SMB connections, not from the NAS (replaces the D-NASP-123 wording, 2026-12-01). Still open: press and store copy must not claim organizing onto a NAS. diff --git a/docs/plan/nas-public/EVIDENCE_LEDGER.md b/docs/plan/nas-public/EVIDENCE_LEDGER.md index a8fc6dfb..4ddb9e9e 100644 --- a/docs/plan/nas-public/EVIDENCE_LEDGER.md +++ b/docs/plan/nas-public/EVIDENCE_LEDGER.md @@ -6,7 +6,7 @@ Only Nishith records results. Rows H1–H8 are the v1 hardware checks; run them | Row | What to run | Pass when | Status | Evidence | |---|---|---|---|---| -| H1 | `probe --test-dir` on the share (P01 to P07), including whether RENAME_EXCL is supported; save `probe.json` (full procedure: docs/plan/nas-v1/EVIDENCE_LEDGER.md H1) | P03, P04, P05 pass; P04 leaves the existing bytes' digest unchanged | fail-hardware (2026-11-08, Nishith) | `evidence/H1-probe.json`. Synology SMB, macOS 27, mount `smbfs` (server redacted). P03 `unsupported` (ENOTSUP); P04 pass (EEXIST, digest unchanged); P01, P02, P05, P06, P07 pass. Copying into this profile does not ship (ADR-NAS-03, D-NASP-115); WP-05 adds the preflight. Profile: DS416play, DSM 7.2.1-69057 Update 13; mount SMB 3.1.1, signed (`SMB_CURR_SIGN_ALGORITHM AES_128_GMAC`), encryption off, Apple extensions on (`OS_X_SERVER TRUE`), file IDs supported (`smbutil statshares -m`); DSM `enable_server_signing=0`, `smb_min_protocol=1`, `smb_max_protocol=3`. | +| H1 | `probe --test-dir` on the share (P01 to P07), including whether RENAME_EXCL is supported; save `probe.json` (full procedure: docs/plan/nas-v1/EVIDENCE_LEDGER.md H1) | Reworded 2026-12-01 (D-NASP-131): P03 result recorded; P04 leaves the existing bytes' digest unchanged; P05 passes. Where P03 is `unsupported`, the app refuses copying into the share (H-NASP-3). Original wording: P03, P04, P05 pass | meets the reworded expectation on the 2026-11-08 evidence; awaiting owner mark (was fail-hardware, 2026-11-08, Nishith) | `evidence/H1-probe.json`. Synology SMB, macOS 27, mount `smbfs` (server redacted). P03 `unsupported` (ENOTSUP); P04 pass (EEXIST, digest unchanged); P01, P02, P05, P06, P07 pass. Copying into this profile does not ship (ADR-NAS-03, D-NASP-115); WP-05 adds the preflight. Profile: DS416play, DSM 7.2.1-69057 Update 13; mount SMB 3.1.1, signed (`SMB_CURR_SIGN_ALGORITHM AES_128_GMAC`), encryption off, Apple extensions on (`OS_X_SERVER TRUE`), file IDs supported (`smbutil statshares -m`); DSM `enable_server_signing=0`, `smb_min_protocol=1`, `smb_max_protocol=3`. | | H2 | `make-corpus` (10,000 files, 20% duplicates, seed 42), then `assess-parity` three matched cold runs; save `parity.json` per run (full procedure: docs/plan/nas-v1/EVIDENCE_LEDGER.md H2) | `parity: true`, ledger within the NAS-NFR-09 budget in all three runs | result recorded, awaiting owner (agent-run 2026-11-08, D-NASP-125) | Commit `bfdf036`. Corpus seed 42, 10,000 files / 307,745,135 bytes, manifest SHA-256 `caf67e8d93c4b0c123701e76ed8f2cf4caf36c0f047a8405e1d8fc8d2c98008c`; on the share 9,998 files (D-NASP-127). `assess-parity --root /Volumes/photo/chronoframe-h2-corpus-2`, fresh `--state-dir` per run (D-NASP-126): run 1 `parity: true` 1783/1783 groups, bytesReadClean 134,306,952 = H, budget 142,695,560, unresolved 0, wallSeconds 352.2; run 2 same, 183.9 s; run 3 same, 178.8 s. Exit 0 each. `evidence/H2-parity-run{1,2,3}.json`, `evidence/H2-make-corpus.json`. Limitation: runs 2–3 may have a warm SMB client cache | | H3 | Choose share, assess, quit, relaunch, confirm review restored, remount under another path (full procedure: docs/plan/nas-v1/EVIDENCE_LEDGER.md H3) | Saved review restored; remount recognized as the same library | todo-hardware | | | H4 | Assess a share with no write access to the account; compare server-side change history before and after (full procedure: docs/plan/nas-v1/EVIDENCE_LEDGER.md H4) | No server-side changes | todo-hardware | | diff --git a/docs/plan/next-half/README.md b/docs/plan/next-half/README.md index ad5e2c9d..64512c48 100644 --- a/docs/plan/next-half/README.md +++ b/docs/plan/next-half/README.md @@ -1,6 +1,6 @@ # Next-half implementation plans (Nov 2026 – Apr 2027) -Status: plans 1 to 3a shipped (PRs #266 to #269, follow-up #274); plans 4 and 5 are not started; the backlog cards are unapproved proposals. Prepared 2026-11-07 from the Round 3 ranking in [`docs/next-half-product-review-2026-11-07.md`](../../next-half-product-review-2026-11-07.md). A plan changes product behavior only when its orchestrator runs and Nishith merges its branch. +Status (2026-11-30): plans 1 to 3a shipped (PRs #266 to #269, follow-up #274); plan 5 was superseded by plan 6, which shipped in #307 to #311; B8 shipped as edit preservation (#299); plan 4 is not started. The rest of the 2.1 queue is in [Release 2.1 scope and press lens](#release-21-scope-and-press-lens-2026-11-30); its scope and order were approved 2026-12-01, and each card still needs an implementation plan before code is written. Prepared 2026-11-07 from the Round 3 ranking in [`docs/next-half-product-review-2026-11-07.md`](../../next-half-product-review-2026-11-07.md). A plan changes product behavior only when its orchestrator runs and Nishith merges its branch. Owner decisions recorded 2026-11-07: ranks 1–5 at full depth, ranks 6–10 as backlog cards; finish NAS on `feature/nas-v1`, then one branch and one plan folder per feature; Opus orchestrates, Sonnet implements and reviews, Haiku does data entry; agents never touch App Review, StoreKit, hardware checks or release flag values. @@ -14,7 +14,8 @@ Owner decisions recorded 2026-11-07: ranks 1–5 at full depth, ranks 6–10 as | 3a | [`clear-path/`](../clear-path/) | `feature/clear-path` | `feature/photos-import-resume` (stacked, D-CLP-01) | `CLP` | UX review 2026-11-12 — plain-language Organize and Deduplicate flow, several folders at once | shipped in #269, follow-up #274 | | 4 | [`find-and-account/`](../find-and-account/) | `feature/find-and-account` | `main` after #3 merges | `FAA` | 4 — item-level reconciliation and original-name lookup | not started | | 5 | [`first-ten-minutes/`](../first-ten-minutes/) | `feature/first-ten-minutes` | `main` after #4 merges | `FTM` | 5 — preflight, free batch, proof | superseded 2026-11-28 by docs/plan/first-run-experience (D-FRX-08). Not built. | -| 6 | [`first-run-experience/`](../first-run-experience/) | `feature/first-run-trust`, `feature/first-run-duplicates`, `feature/first-run-guided` (stacked, D-FRX-01) | `main` after #299 | `FRX` | six onboarding recommendations approved 2026-11-28 | built, not merged | +| 6 | [`first-run-experience/`](../first-run-experience/) | `feature/first-run-trust`, `feature/first-run-duplicates`, `feature/first-run-guided` (stacked, D-FRX-01) | `main` after #299 | `FRX` | six onboarding recommendations approved 2026-11-28 | shipped in #307 to #309, follow-ups #310 and #311; owner rows H-FRX-1 to H-FRX-8 not run | +| 6a | [`edit-preservation/`](../edit-preservation/) | `feature/edit-preservation-impl` | `main` after #298 | `EPR` | 9 (B8) plus edited Photos versions | shipped in #299 (INV-31) | Each plan is self-contained: `CONTRACTS.md`, `DECISIONS.md`, `IMPLEMENTATION_PLAN.md`, `PROGRESS.md`, `ACCEPTANCE_MATRIX.md`, `BLOCKED.md`, `EVIDENCE_LEDGER.md`. Shared files live here: [`AGENT_RULES.md`](AGENT_RULES.md), [`bin/cf_swift.sh`](bin/cf_swift.sh), [`ORCHESTRATOR_KICKOFF.md`](ORCHESTRATOR_KICKOFF.md), [`claude-config/`](claude-config/) (install into the gitignored `.claude/`). @@ -28,11 +29,79 @@ Plans 2–5 may be reordered by the owner; each `DECISIONS.md` D-01 names its ba - **NAS hardware checks H1–H8.** Owner-only; procedures in `docs/plan/nas-v1/EVIDENCE_LEDGER.md`, results in `docs/plan/nas-public/EVIDENCE_LEDGER.md` (H1 failed on the Synology profile; several rows still open). - **Release flag flips** (`NASCapability.isEnabled` release value). Owner-only, after the ledger rows read `pass-hardware`. -## Backlog cards (ranks 6–11; not planned this pass) +## Release 2.1 scope and press lens (2026-11-30) + +Status: **approved 2026-12-01** (prepared 2026-11-30). Owner decisions: 2.1 ships when ranks 1 to 11 and everything added here are done, with no date; press outreach follows 2.1; the build order, the press scope additions and cards B12 to B14 are accepted; NAS public is required for 2.1. Each card still needs its own implementation plan and approval before code is written. Statuses below were checked against `git log origin/main` and each plan's `PROGRESS.md` on 2026-11-30; nothing was built or run. + +State for every item, the owner checks still owed and the release gates are tracked in [`../release-2.1/PROGRESS.md`](../release-2.1/PROGRESS.md). This section holds scope and order only. + +### The story 2.1 has to carry + +One sentence a writer can repeat: **Chronoframe organizes a photo archive and can show that every file is accounted for and unchanged.** Each remaining item is judged by whether a reviewer can see that for themselves in a few minutes. + +| Audience | Outlets on the outreach list | What they need to see | Carried by | +|---|---|---|---| +| Mac generalists | Six Colors, 9to5Mac, TidBITS | A plain job done safely; proof, not claims | Find and account, B9, B11 | +| Technical | Michael Tsai, TidBITS | How verification, receipts and undo work | B9, B14 post | +| Automation | MacStories, MacSparky | Shortcuts actions with usable output | B12 | +| Photographers | Thomas Fitzgerald | RAW and sidecar safety, clock repair | Edit preservation (shipped), B6 | + +### Build order + +One branch and one plan folder per item, each based on `main` after the previous one merges unless its plan's D-01 says otherwise. Items with no dependency between them may be reordered. + +| Order | Item | Plan folder (prefix) | Depends on | Press role | State | +|---|---|---|---|---|---| +| 1 | Find and account (rank 4) | `find-and-account/` (`FAA`) | none | The demo: "where did IMG_1234 go" | Plan written 2026-11-07, not started. Refresh before running (see below). | +| 2 | B9 Verify my archive | `guardian-verify/` (`GVF`) | none; reads FAA records when present | The headline for Mac and technical press | Card only | +| 3 | B6 Batch camera-clock correction | `batch-clock/` (`BCL`) | none | The photographer feature | Card only | +| 4 | B11 Already-archived view in Photos import | `photos-archived-view/` (`PAV`) | FAA index; plan 3 checkpoint | Leaving iCloud, the most common reader job | Card only | +| 5 | B10 Takeout rescue | `takeout-dates/` (`TKO`) | companion rule (shipped in #299) | Leaving Google Photos | Card only | +| 6 | B7 Protected folders, then keeper preference | `protected-folders/` (`PRF`) | none | None; built for users | Card only | +| 7 | B12 Shortcuts actions and Finder Quick Actions | `shortcuts-actions/` (`SCA`) | FAA, B9, B6 | Required for MacStories and MacSparky | New card | +| 8 | B13 Reviewer sample library | `press-kit/` (`PRK`) | every item above | Lets a writer see the value in five minutes | New card | +| 9 | B14 Technical post and press page | `press-kit/` (`PRK`) | B9, FAA | What Tsai and TidBITS link to | New card | +| owner | NAS public (rank 1) | `nas-public/` | hardware rows H1 to H8, flag flip | Second angle for NAS owners, stated as "organize the photos on your NAS onto a drive, and check a NAS library"; never "organize onto a NAS" | Merged, flag off. Required for 2.1 (owner, 2026-12-01). Copying into an SMB share is refused by design (D-NASP-130, D-NASP-131). | + +Changes from the Round 4 order: B9 moves from rank 10 to second, because it is the headline and nothing blocks it; B10 is no longer "first to drop", since 2.1 has no capacity limit and leaving Google Photos is a broad reader job; B7 moves last among features because it has no press role. B11 stays behind FAA because it needs the mapping index. + +### Before each implementation plan is written + +- **Find and account.** The plan predates clear-path, first-run experience and edit preservation. Refresh every line reference into `Views/Setup/`, `Views/Run/`, `SetupCoordinator.swift` and `RunSessionStore.swift`, and all UI copy. Decide how companions and edited variants appear in the outcome record. INV-30 is reserved for it (D-EPR-12); `AGENTS.md` has no INV-30 yet. +- **B9.** Read `GuardianScheduler`, `GuardianStore` and `SwiftGuardianEngine` to list what the scrub-only workspace reuses. Confirm `GuardianManifestUpdater.accept` covers a first baseline of a whole existing folder (press scope below). +- **B6.** Confirm `ReviewOverrides` can record which batch wrote an override, so undo removes exactly that batch. +- **B11.** Answer the card's open question: whether the Photos asset identifier is persisted with the destination mapping. +- **B12.** List what each intent returns and which intents may run without the app in front. No intent may purchase (existing CI guard) or mutate without the same lock and receipt path as the app. + +### Press scope added to existing cards + +These widen the cards below. Accepted 2026-12-01. + +- **B9, start from an existing archive.** The card baselines only from a verified Organize receipt, so a reviewer could verify nothing but what Chronoframe copied. Add an explicit "Start tracking this folder as it is today" action that records the current digests through `GuardianManifestUpdater.accept`. INV-23 already allows trust by explicit user acceptance. Copy must say it records today's state and proves nothing about earlier damage. +- **B9, results a writer can quote.** The report names each changed or missing file with its path, the date it was last verified and the date the change was found, and exports as CSV. +- **B6, the before and after is the screenshot.** The preview shows old date, new date and the destination folder each item moves to, for the whole batch. +- **B10 and B11, wording.** Neither may say or imply "safe to delete" from Google or iCloud. This is unchanged from Round 4 and matters more when a journalist is quoting the screen. +- **Find and account, a visible answer.** Typing an original file name returns where it is now, which run put it there and whether it is still present. + +### Considered for the press lens and declined + +- **Guardian mirror and restore.** The Round 4 reasons stand: largest expansion of responsibility, and a same-drive mirror is not a backup. B9 tells the same story for a fraction of the risk. +- **Card ingest with a "safe to format" verdict.** Conflicts with the "never imply safe to delete" rule and serves working professionals, who are not the primary customer. +- **Library timeline with gaps.** Overlaps the "reviewed through" calendar and space report removed in Round 3. +- **Metadata-complete export from Photos, direct iPhone import.** PhotoKit cannot deliver the first in full; the second carries a high support cost and no proof story. + +### Owner decisions (2026-12-01) + +1. Build order accepted as written. +2. B12, B13 and B14 are 2.1 scope, including the technical post and the press page. +3. B9 gets the "start from an existing archive" action. +4. NAS public is required for 2.1; the release waits for its hardware rows. + +## Backlog cards (ranks 6–11 and press additions B12–B14) Each card is the seed of a future plan folder. Scope lines are the Round 3 boundaries; nothing below is approved for implementation. -Order after Round 4 (2026-11-10): **B11** (rank 6), B6 (7), B7 (8), B8 (9), B9 (10), B10 (11). Card IDs are unchanged so existing references stay valid. +Order after Round 4 (2026-11-10): **B11** (rank 6), B6 (7), B7 (8), B8 (9), B9 (10), B10 (11). Card IDs are unchanged so existing references stay valid. The 2.1 build order in the section above supersedes this order (2026-11-30); B8 has shipped. ### B11 — Already-archived view and date-range selection in Photos import (`feature/photos-archived-view`) - **Job:** "I offload from iCloud every few months; show me what is already in my archive and import only the rest." @@ -57,7 +126,7 @@ Order after Round 4 (2026-11-10): **B11** (rank 6), B6 (7), B7 (8), B8 (9), B9 ( - **Out:** cross-root protection, Organize-source protection (sources are already read-only), near-duplicate auto decisions. - **Invariants to tag:** Trash-only; plan integrity/expected identity; Keep-wins pair/sidecar. -### B8 — Existing XMP companions travel with organized photos (`feature/xmp-companions`) +### B8 — Existing XMP companions travel with organized photos (shipped in #299 as `edit-preservation/`) - **Job:** a Lightroom user's `.xmp` ratings and edits are left behind by Organize today. - **Builds on:** dedupe's sidecar discovery; `MediaDiscovery` extension allowlist; collision renaming in `CopyPlanBuilder`. - **Scope:** discover `.xmp` whose basename matches exactly one supported media file in the same directory; copy unchanged beside the owner, renamed in lockstep on collision; verified, receipted and reverted with the owner; ambiguous or orphan companions listed as unresolved in the plan. @@ -77,3 +146,26 @@ Order after Round 4 (2026-11-10): **B11** (rank 6), B6 (7), B7 (8), B8 (9), B9 ( - **Scope:** for `name.ext` match exactly one of `name.ext.json`, `name.ext.supplemental-metadata.json` or the truncated-name variant Google documents, in the same directory; read `photoTakenTime.timestamp` as an alternative date shown in the existing conflicting-date review, never applied automatically; copy the JSON as a companion when B8 exists, otherwise leave it and say so. - **Out:** Google login, album JSON, edited-variant `-edited` files, any date rewrite without review. - **First to drop** if customer recruitment finds no demand. + +### B12 — Shortcuts actions and Finder Quick Actions for the 2.1 capabilities (`feature/shortcuts-actions`) +- **Status:** accepted as 2.1 scope 2026-12-01 (added 2026-11-30 from the press lens; promoted from the maintenance bucket in the product review). No implementation plan yet. +- **Job:** "run my archive chores from Shortcuts and use the result in the next step." +- **Builds on:** `OrganizeFolderIntent` (the only intent today), the FAA lookup index, the B9 scrub, B6 overrides. +- **Scope:** Verify Archive (returns counts and the list of changed or missing files), Find Photo (original name in, current location and presence out), Preview Organize (dry run, returns counts and the report file). Each returns typed output another action can consume, and result text is localized. +- **Finder Quick Action, folder (accepted 2026-11-30):** right-click a folder, "Preview Organize in Chronoframe" opens the app with that folder staged as the source and the preview running. It copies nothing from Finder. +- **Finder Quick Action, files (accepted 2026-12-01, owner idea):** right-click one or more photos or videos, "File in Chronoframe Archive" copies them into their dated place in the default destination. It is a verified copy through the same engine, lock, receipt and free limit as a run, so it appears in History and can be undone; the original stays where it is. It completes from Finder only when every item has a certain date, no conflicting-date warning and no name collision, and then posts a notification with Reveal and Undo. Otherwise it opens the app's preview with the items staged. Companions and RAW+JPEG partners in the same folder travel with the selected file. With no default destination set, it opens Setup. +- **Out:** any intent that deletes, deduplicates or purchases; any intent that copies without the app's lock, receipt and free-limit path; background scheduling. +- **Open questions:** whether a clock-correction intent is useful without the preview, or should be left out; how a sandboxed Finder extension receives access to the selected files and the bookmarked destination. +- **Invariants to tag:** Guardian scrub read-only (23); source read-only; App Intents never purchase (existing guard). + +### B13 — Reviewer sample library (`feature/press-kit`) +- **Status:** accepted as 2.1 scope 2026-12-01. No implementation plan yet. +- **Job:** a writer with no messy archive to hand sees every 2.1 capability in a few minutes. +- **Scope:** a script that generates a small folder from synthetic, license-free images: exact and near duplicates, a RAW+JPEG pair, an `.xmp` and an `.aae` companion, a batch with a wrong camera clock, a Takeout-style JSON pair, and a conflicting-date file. A second step changes one byte in one organized file so Verify has something to find. A one-page walkthrough lists the steps and what each shows. +- **Out:** real photographs, anything bundled in the app, any network download at run time. +- **Reuses:** existing test fixture builders where they already produce these shapes. + +### B14 — Technical post and press page (`feature/press-kit`) +- **Status:** accepted as 2.1 scope 2026-12-01. Documentation and site work; no app code. +- **Scope:** one post explaining receipts, verified copies, undo and the scrub, written from `docs/SAFETY_AND_RECOVERY.md` and `docs/TECHNICAL.md`; a press page with the one-sentence story, screenshots, pricing, the sample library link and contact. +- **Out:** claims not backed by a tagged invariant test; competitor comparisons beyond the hand-checked compare page. diff --git a/docs/plan/photos-import-resume/DECISIONS.md b/docs/plan/photos-import-resume/DECISIONS.md index 0f97c0ac..29df5d1a 100644 --- a/docs/plan/photos-import-resume/DECISIONS.md +++ b/docs/plan/photos-import-resume/DECISIONS.md @@ -55,3 +55,4 @@ When a gap appears that no contract or decision covers, choose the option that, - **D-PIR-127 (item 7) Resume validates the card's own directory.** Amends D-PIR-106 and D-PIR-112. `resumeImport` takes the `resumable` the card shows, re-validates only that directory (destination and files as they are now) and resumes it; it no longer runs the full refresh first, which could pick or delete another import. If that directory is gone or invalid it runs the refresh (so the card shows what really exists), sets "That interrupted import is no longer available. Your Photos library was not changed." and resumes nothing. With no `resumable` at all it still returns nil silently. The "couldn't prepare" text for this case in `testResumeRevalidatesDestinationAndFilesAtResumeTime` was updated to the new message. - **D-PIR-128 (item 6) Asset size joins the low-space threshold.** Amends D-PIR-05 and D-PIR-103. `PhotosExportableResource` gains `fileSize: Int64?` (default nil). After an asset's resources are listed the executor stops with `PhotosExportStop.lowStagingSpace` when free space is below floor + the asset's summed known sizes (`floorBytes` in the stop is that threshold). The first, size-less check before `.assetStarted` is unchanged, so D-PIR-103 holds for it; the size check runs after `.assetStarted`, and nothing of the asset is written. Unknown sizes and unknown free space never stop the export. `PhotosResourceExportService` passes nil: PhotoKit has no public resource size, and the undocumented `fileSize` KVC key was rejected as an App Review risk during review of #268. Production therefore behaves as before; the threshold logic is in place and tested for when a public size source exists (e.g. an exporter that knows the size up front). - **D-PIR-129 Filename collisions in the export executor fixed (renumbered from D-PIR-121 when merged with #268; owner, 2026-11-12: separate fix for D-PIR-104; PR #270).** On branch `fix/photos-export-name-collision`, stacked on `feature/clear-path`. Names are compared by a filesystem-style key: canonical decomposition plus case folding (`nameKey`), diacritics kept, so "Cafe" and "Caf\u00e9" stay distinct. Reserved names use the same key. `lowercased()` was not enough: small and final sigma fold together on APFS but lowercase apart (`testStemsThatFoldTogetherButDoNotLowercaseTogetherDoNotShareAFile`). Unicode normalization needed no code change, because Swift `String` equality already treats canonical equivalents as equal; the composed/decomposed tests are regression guards that passed before the fix. The name is claimed with an exclusive create (`O_CREAT|O_EXCL|O_NOFOLLOW`) before `writeResource` runs; EEXIST means a file the key did not foresee is already there, so the next candidate is tried and that file is never touched, and rollback removes only files this call created. The exporter then replaces the empty claimed file. Search is bounded (`maxNameAttempts`, 10,000); exhaustion fails only that asset. Failing-first: `testFallbackNameNeverLandsOnAnotherAssetsFile`, `testNamesDifferingOnlyByCaseDoNotShareAFile`, `testReservedFilenameIsMatchedIgnoringCase` (the third showed a reserved staged file being overwritten), then `testUnreservedStagedFileOfCaseVariantNameSurvivesByteForByte`, `testRollbackNeverRemovesAFileTheExecutorDidNotCreate`, `testExhaustedNameAttemptsFailOnlyThatAsset` and the sigma test (all tagged INV-22). Full case folding also merges ß and SS, which APFS keeps apart; accepted, an extra rename is harmless. Out of scope: case-sensitive volumes still rename stems that differ only by case. `cf_swift.sh suite` 0; `coverage` 0 (meaningful 96.04%); `guards feature/clear-path` 0 (14/14); `xcode` 0 (these four lanes ran before the fold and exclusive-create change and have not been re-run). Not verified in the running app. +- **D-PIR-130 A finished export survives cleanup while a pending copy still reads from it (owner, 2026-11-29: fix chosen from the 2.1 sweep). Amends C-04 and D-PIR-109.** Launch cleanup and the post-run `cleanupStaging` no longer remove a `.ready` staging folder when a PENDING job in the destination's `.organize_cache.db` has its source under that folder (`PendingCopyJobStagingReferenceChecker`, a read-only open with no lease, the same as the run preflight's pending count). The folder is removed once the queue is read and nothing pending is under it, or the destination has no queue. At launch, when the destination or its queue cannot be read, the folder is kept for 30 days from the checkpoint's `updatedAt` and then removed (agent's choice of 30 days, not reviewed by the owner). The post-run cleanup keeps the folder only on a proven reference. A `.ready` checkpoint is still not offered as an interrupted export. diff --git a/docs/plan/release-2.1/PROGRESS.md b/docs/plan/release-2.1/PROGRESS.md new file mode 100644 index 00000000..05c66904 --- /dev/null +++ b/docs/plan/release-2.1/PROGRESS.md @@ -0,0 +1,79 @@ +# Release 2.1 — tracker + +Status (2026-12-01): scope approved, no 2.1 feature plan started. 2.1 ships when every row in the three tables below is done; there is no date. Press outreach follows the release. + +This file holds state and links only. Scope and order live in [`../next-half/README.md`](../next-half/README.md), "Release 2.1 scope and press lens". Detail lives in each plan folder, which stays the source of truth: when this file and a plan's `PROGRESS.md` disagree, the plan is right and this file is stale. + +## How to update + +- An orchestrator updates its feature row at each gate and when its PR merges, through the data-entry agent. +- Only Nishith moves an owner-check row to `pass` or `fail`; he records the result in the plan's `EVIDENCE_LEDGER.md` first, then the count here. +- Feature states, in order: `card` → `plan written` → `plan approved` → `in progress` → `built` (final gate passed on the branch) → `merged` → `verified` (owner rows for that feature pass in the running app). "Merged" never implies "verified". + +## 1. Features + +| # | Item | Plan folder | State | PR | Owner checks | Notes | +|---|---|---|---|---|---|---| +| 1 | Find and account (rank 4) | [`find-and-account/`](../find-and-account/) | plan written | — | not defined yet | Plan dates from 2026-11-07 and must be refreshed against clear-path, first-run and edit preservation before approval. Reserves INV-30. | +| 2 | B9 Verify my archive | `guardian-verify/` (to create) | card | — | — | Includes "start tracking this folder as it is today". | +| 3 | B6 Batch camera-clock correction | `batch-clock/` (to create) | card | — | — | | +| 4 | B11 Already-archived view in Photos import | `photos-archived-view/` (to create) | card | — | — | Needs item 1's index. | +| 5 | B10 Takeout rescue | `takeout-dates/` (to create) | card | — | — | | +| 6 | B7 Protected folders, then keeper preference | `protected-folders/` (to create) | card | — | — | | +| 7 | B12 Shortcuts actions and Finder Quick Actions | `shortcuts-actions/` (to create) | card | — | — | Needs items 1, 2 and 3. | +| 8 | B13 Reviewer sample library | `press-kit/` (to create) | card | — | — | Needs every item above. | +| 9 | B14 Technical post and press page | `press-kit/` (to create) | card | — | — | No app code. | +| — | NAS public (rank 1) | [`nas-public/`](../nas-public/) | merged (#266), flag off | #266 | 2 pass, 0 fail, 10 open | Required for 2.1. Ships as read-from-NAS: assess, review and copy from a share to this Mac. Copying into an SMB share stays refused (D-NASP-130, D-NASP-131). | + +Already merged and counted in 2.1, awaiting owner checks only (section 2): dedupe persistence (#267), Photos import resume (#268, #270), clear path (#269, #274), edit preservation (#299), first-run experience (#307 to #311). + +In flight outside the feature list: branch `fix/release-2.1-second` (2.1 bug sweep, version bump and What's New draft), 15 commits ahead of `origin/main` on 2026-12-01, not merged. + +## 2. Owner checks + +Rows only Nishith can run: hardware, the running app, VoiceOver, a signed or MAS build. Counts were read from each ledger on 2026-12-01. Totals: 44 rows, 2 pass, 0 fail, 4 with a recorded result awaiting the owner's mark, 38 not run. + +| Plan | Ledger | Rows | Pass | Fail | Awaiting owner | Not run | What they cover | +|---|---|---|---|---|---|---|---| +| NAS public | [`nas-public/EVIDENCE_LEDGER.md`](../nas-public/EVIDENCE_LEDGER.md) | 12 | 2 (H-NASP-1, H-NASP-2) | 0 | 4 (H1, H2, H6, H8) | 6 (H3, H4, H5, H7, H-NASP-3, FLAG) | Real-share probe, parity, relaunch and remount, read-only share, disconnect and sleep, verified copy, accessibility, performance, the flag flip | +| Dedupe persistence | [`dedupe-persistence/EVIDENCE_LEDGER.md`](../dedupe-persistence/EVIDENCE_LEDGER.md) | 5 | 0 | 0 | 0 | 5 (H-DDP-1 to 5) | Review restored after relaunch, changed file re-enters review, commit, VoiceOver, app smoke | +| Photos import resume | [`photos-import-resume/EVIDENCE_LEDGER.md`](../photos-import-resume/EVIDENCE_LEDGER.md) | 6 | 0 | 0 | 0 | 6 (H-PIR-1 to 6) | Stop and resume with iCloud assets, low space, destination mismatch, VoiceOver, app smoke | +| Clear path | [`clear-path/EVIDENCE_LEDGER.md`](../clear-path/EVIDENCE_LEDGER.md) | 7 | 0 | 0 | 0 | 7 (H-CLP-1 to 7) | Sandboxed folder list, the real 65,000-file library, VoiceOver, UI-test lane, screenshot recapture, a first-time user session, store and site wording | +| Edit preservation | [`edit-preservation/EVIDENCE_LEDGER.md`](../edit-preservation/EVIDENCE_LEDGER.md) | 6 | 0 | 0 | 0 | 6 (H-EPR-1 to 6) | Companions in dedupe, organize and revert; edited Photos versions; resume; wording | +| First-run experience | [`first-run-experience/EVIDENCE_LEDGER.md`](../first-run-experience/EVIDENCE_LEDGER.md) | 8 | 0 | 0 | 0 | 8 (H-FRX-1 to 8) | MAS build on a clean account: accounted-for line and Undo, free limit, duplicate lanes, free removal, guided setup, a 20,000-file collection, existing-account layout, VoiceOver | + +Several rows overlap and can be run in one sitting: the VoiceOver rows (H7, H-DDP-4, H-PIR-5, H-CLP-3, H-FRX-8), the app-smoke rows (H-DDP-5, H-PIR-6), and the clean-account MAS rows (H-FRX-1 to 5). + +### Blocked items that name the owner + +Pointers only; read each file for its current state. + +| Plan | Item | Subject | +|---|---|---| +| First-run experience | [B-1](../first-run-experience/BLOCKED.md) | Planner fan-out fix (INV-32) is built and merged; only Nishith marks it resolved. | +| Clear path | [B-5](../clear-path/BLOCKED.md) | App smoke screenshots could not be taken by the agent. | +| Photos import resume | [B-1](../photos-import-resume/BLOCKED.md) | G2 app smoke not completed; screen access declined. | +| Edit preservation | [B-2](../edit-preservation/BLOCKED.md) | Companion follow-ups left for a later release (see root `DECISIONS.md`). | + +## 3. Release gates + +Run once, on the commit that will ship, after every feature row is `merged`. + +| Gate | State | Evidence | +|---|---|---| +| Full SwiftPM suite, coverage gate, invariant script, all `script/check_*.sh` | todo | command and exit code | +| Xcode build and UI-test lane | todo | command and exit code | +| German strings for every new key; `check_german_localization.py` | todo | command and exit code | +| What's New, English and German, rewritten for the final scope | draft exists for the current scope (ac29b36f); redo at the end | commit | +| `docs/screenshots/` recaptured (also H-CLP-5) | todo | commit | +| App Store metadata, site and compare page match the shipped labels (also H-CLP-7) | todo | note | +| FAQ, TROUBLESHOOTING, SAFETY_AND_RECOVERY and TECHNICAL cover every new feature | todo | commit | +| Reviewer sample library walkthrough run end to end on the release build | todo | notes | +| Technical post and press page published | todo | links | +| MAS archive built, uploaded and approved | todo | build number | + +## Log + +- 2026-12-01: tracker created. Owner-check counts read from the six ledgers; feature states read from each `PROGRESS.md` and `git log origin/main`. Nothing was built or run. +- 2026-12-01: H1 diagnosed (D-NASP-130): the missing exclusive rename is a macOS SMB client limit. No code or ledger status changed. +- 2026-12-01: owner chose option A (D-NASP-131). H1 reworded; it now awaits the owner's mark instead of reading fail. diff --git a/ui/Chronoframe.xcodeproj/project.pbxproj b/ui/Chronoframe.xcodeproj/project.pbxproj index 662505c7..f8bc5627 100644 --- a/ui/Chronoframe.xcodeproj/project.pbxproj +++ b/ui/Chronoframe.xcodeproj/project.pbxproj @@ -424,7 +424,7 @@ "@executable_path/../Frameworks", ); MACOSX_DEPLOYMENT_TARGET = 14.0; - MARKETING_VERSION = 2.0; + MARKETING_VERSION = 2.1; ONLY_ACTIVE_ARCH = YES; OTHER_LDFLAGS = ( "$(inherited)", @@ -455,7 +455,7 @@ "@executable_path/../Frameworks", ); MACOSX_DEPLOYMENT_TARGET = 14.0; - MARKETING_VERSION = 2.0; + MARKETING_VERSION = 2.1; OTHER_LDFLAGS = ( "$(inherited)", "-lsqlite3", diff --git a/ui/Sources/ChronoframeApp/AppIntents/OrganizeFolderIntent.swift b/ui/Sources/ChronoframeApp/AppIntents/OrganizeFolderIntent.swift index 6ad65258..09e6d756 100644 --- a/ui/Sources/ChronoframeApp/AppIntents/OrganizeFolderIntent.swift +++ b/ui/Sources/ChronoframeApp/AppIntents/OrganizeFolderIntent.swift @@ -100,8 +100,9 @@ public struct OrganizeFolderIntent: AppIntent { "Successfully organized folder. Transferred \(copiedCount == 1 ? "1 file" : "\(copiedCount) files")." } - /// The run this intent performs. The layout is the person's own, read through - /// `PreferencesStore`, so a Shortcut run lands in the same library layout as the app. + /// The run this intent performs. Layout, verify-copies, parallel transfer and worker count are + /// the person's own, read through `PreferencesStore` the way `SetupStore.makeConfiguration` + /// does, so a Shortcut run behaves like a run started in the app. @MainActor static func makeConfiguration( sourcePath: String, @@ -113,9 +114,9 @@ public struct OrganizeFolderIntent: AppIntent { sourcePath: sourcePath, destinationPath: destinationPath, profileName: nil, - verifyCopies: true, - parallelTransferEnabled: true, - workerCount: 8, + verifyCopies: preferences.verifyCopies, + parallelTransferEnabled: preferences.parallelTransferEnabled, + workerCount: max(1, preferences.workerCount), folderStructure: preferences.folderStructure ) } diff --git a/ui/Sources/ChronoframeApp/Views/Deduplicate/RapidTriageView.swift b/ui/Sources/ChronoframeApp/Views/Deduplicate/RapidTriageView.swift index 1d71176b..d881d7c0 100644 --- a/ui/Sources/ChronoframeApp/Views/Deduplicate/RapidTriageView.swift +++ b/ui/Sources/ChronoframeApp/Views/Deduplicate/RapidTriageView.swift @@ -16,6 +16,17 @@ enum QuickReviewScope { clusters.filter { !reviewedIDs.contains($0.id) && laneOf($0) == lane } } + /// What "Accept the Rest" accepts: the groups from the person's position on that are + /// still unreviewed. A group they skipped earlier is behind that position and stays whole. + static func restClusters( + from walk: [DuplicateCluster], + currentIndex: Int, + reviewedIDs: Set + ) -> [DuplicateCluster] { + guard currentIndex < walk.count else { return [] } + return walk[max(currentIndex, 0)...].filter { !reviewedIDs.contains($0.id) } + } + /// The number on "Accept the Rest": only for nearly identical groups, only once /// the person has passed at least one group, and only while groups remain. static func acceptTheRestCount(lane: DeduplicateReviewLane, currentIndex: Int, remainingInLane: Int) -> Int? { @@ -330,19 +341,29 @@ struct RapidTriageView: View { advance() } - /// Groups still unreviewed in this lane: exactly what "Accept the Rest" accepts. + /// The groups from the person's position on that are still unreviewed: exactly what + /// "Accept the Rest" accepts. Groups they skipped earlier are not among them. + private var restClusters: [DuplicateCluster] { + QuickReviewScope.restClusters( + from: clustersToReview, + currentIndex: currentIndex, + reviewedIDs: sessionStore.approvedClusterIDs + ) + } + private var acceptTheRestCount: Int? { QuickReviewScope.acceptTheRestCount( lane: lane, currentIndex: currentIndex, - remainingInLane: sessionStore.laneSummaries[lane]?.groups ?? 0 + remainingInLane: restClusters.count ) } - /// Accepts the suggestion for every group still unreviewed in the nearly identical - /// lane, then shows the completion screen. Nothing is moved to the Trash here. + /// Accepts the suggestion for every group from here on that is still unreviewed, + /// then shows the completion screen. Skipped groups stay unreviewed. Nothing is + /// moved to the Trash here. private func acceptTheRest() { - sessionStore.acceptSuggestions(in: .nearlyIdentical) + sessionStore.acceptSuggestions(forClusters: restClusters) dragOffset = .zero currentIndex = clustersToReview.count } diff --git a/ui/Sources/ChronoframeAppCore/Services/PhotosStagingReferenceChecker.swift b/ui/Sources/ChronoframeAppCore/Services/PhotosStagingReferenceChecker.swift new file mode 100644 index 00000000..418b4531 --- /dev/null +++ b/ui/Sources/ChronoframeAppCore/Services/PhotosStagingReferenceChecker.swift @@ -0,0 +1,79 @@ +#if canImport(ChronoframeCore) +import ChronoframeCore +#endif +import Foundation + +/// Whether a destination's copy queue still reads from a staging folder. +public enum PhotosStagingReference: Equatable, Sendable { + /// A pending copy job names a file inside the folder: the copy needs it. + case referenced + /// The queue was read (or provably does not exist) and no pending job names the folder. + case unreferenced + /// The destination or its queue could not be read, so nothing is proven. + case undetermined +} + +/// Answers "does an unfinished copy still read from this staging folder?" +/// for launch cleanup. Pending jobs in the destination's `.organize_cache.db` +/// carry their source path, and a Photos import's source is its staging +/// folder, so a pending job under the folder means a resume needs it. +public protocol PhotosStagingReferenceChecking: Sendable { + func reference(toStagingDirectory stagingDirectory: URL, destinationPath: String) -> PhotosStagingReference +} + +/// Reads the destination's copy queue without writing anything: the same +/// read-only open the run preflight uses to count pending jobs, which takes no +/// destination lease because it mutates nothing. Anything it cannot read is +/// `.undetermined`, never "nothing pending": an unmounted or unreachable +/// destination, a denied path, an unreadable database. +public struct PendingCopyJobStagingReferenceChecker: PhotosStagingReferenceChecking { + private let presenceChecker: any FilesystemPresenceChecking + + public init(presenceChecker: any FilesystemPresenceChecking = POSIXFilesystemPresenceChecker()) { + self.presenceChecker = presenceChecker + } + + private struct FoundReference: Error {} + + public func reference(toStagingDirectory stagingDirectory: URL, destinationPath: String) -> PhotosStagingReference { + guard !destinationPath.isEmpty else { return .undetermined } + let root = URL(fileURLWithPath: destinationPath, isDirectory: true) + // A destination root that is not there may be an unmounted volume. + guard presenceChecker.presence(at: root.path) == .exists else { return .undetermined } + + let databaseURL = root.appendingPathComponent(EngineArtifactLayout.chronoframeDefault.queueDatabaseFilename) + switch presenceChecker.presence(at: databaseURL.path) { + case .inaccessible: + return .undetermined + case .missing: + // The run preflight reads a missing queue as zero pending jobs, so + // there is no copy to resume from this destination. + return .unreferenced + case .exists: + break + } + + guard let database = try? OrganizerDatabase(url: databaseURL, readOnly: true) else { return .undetermined } + defer { database.close() } + + // Job paths are whatever string the run was given as its source, so + // match both the folder as named and with symlinks (/var) resolved. + let prefixes = Set([ + stagingDirectory.standardizedFileURL.path, + stagingDirectory.resolvingSymlinksInPath().standardizedFileURL.path + ]).map { $0.hasSuffix("/") ? $0 : $0 + "/" } + + do { + try database.enumerateQueuedJobBatches(status: .pending) { batch in + if batch.contains(where: { job in prefixes.contains(where: job.sourcePath.hasPrefix) }) { + throw FoundReference() + } + } + } catch is FoundReference { + return .referenced + } catch { + return .undetermined + } + return .unreferenced + } +} diff --git a/ui/Sources/ChronoframeAppCore/Stores/DeduplicateSessionStore.swift b/ui/Sources/ChronoframeAppCore/Stores/DeduplicateSessionStore.swift index 5f4948cb..67627a8f 100644 --- a/ui/Sources/ChronoframeAppCore/Stores/DeduplicateSessionStore.swift +++ b/ui/Sources/ChronoframeAppCore/Stores/DeduplicateSessionStore.swift @@ -610,6 +610,29 @@ public final class DeduplicateSessionStore: ObservableObject { scheduleSave() } + /// Accepts the suggestions for the listed groups that are still unreviewed and + /// automatically eligible. Any other group, including one the person skipped, is left alone. + public func acceptSuggestions(forClusters candidates: [DuplicateCluster]) { + let listed = candidates.filter { + DeduplicationPlanner.isAutomaticCommitEligible($0) && !approvedClusterIDs.contains($0.id) + } + guard !listed.isEmpty else { return } + let oldDecisions = decisions + let oldApproved = approvedClusterIDs + var byPath = decisions.byPath + for (path, decision) in suggestedDecisions(for: listed).byPath { + byPath[path] = decision + } + decisions = DedupeDecisions(byPath: byPath, pairKeepOverrides: decisions.pairKeepOverrides) + approvedClusterIDs.formUnion(listed.map(\.id)) + registerUndo( + oldDecisions: oldDecisions, + oldApproved: oldApproved, + actionName: String(localized: "Accept Nearly Identical", bundle: Bundle.module) + ) + scheduleSave() + } + /// Reviewed groups in which every member is marked Delete. public var fullyMarkedClusterIDs: Set { Set(reviewedClusters.filter { cluster in @@ -837,7 +860,8 @@ public final class DeduplicateSessionStore: ObservableObject { summary: summary, completedAt: Date() ) - if !preparedPlanIsFreeBatch { + // A commit that moved nothing has not used up the review, so it stays for the next scan. + if !preparedPlanIsFreeBatch && summary.deletedCount > 0 { reviewSnapshotStore.remove(folderPath: destinationPath) restoredReview = nil savedReviewForCurrentFolder = nil diff --git a/ui/Sources/ChronoframeAppCore/Stores/PhotosImportStore.swift b/ui/Sources/ChronoframeAppCore/Stores/PhotosImportStore.swift index a01116cf..b9551f96 100644 --- a/ui/Sources/ChronoframeAppCore/Stores/PhotosImportStore.swift +++ b/ui/Sources/ChronoframeAppCore/Stores/PhotosImportStore.swift @@ -94,6 +94,7 @@ public final class PhotosImportStore: ObservableObject { private let stagingParentURL: URL private let pageSize: Int private let checkpointStore: any PhotosImportCheckpointStoring + private let stagingReferenceChecker: any PhotosStagingReferenceChecking private let exportExecutorFactory: (any PhotosResourceExporting) -> PhotosExportExecutor private let now: @Sendable () -> Date private let cancellation = PhotosPreparationCancellation() @@ -129,6 +130,7 @@ public final class PhotosImportStore: ObservableObject { stagingParentURL: URL, pageSize: Int = 120, checkpointStore: any PhotosImportCheckpointStoring = PhotosImportFileCheckpointStore(), + stagingReferenceChecker: any PhotosStagingReferenceChecking = PendingCopyJobStagingReferenceChecker(), exportExecutorFactory: @escaping (any PhotosResourceExporting) -> PhotosExportExecutor = { PhotosExportExecutor(exporter: $0) }, now: @escaping @Sendable () -> Date = Date.init ) { @@ -138,6 +140,7 @@ public final class PhotosImportStore: ObservableObject { self.stagingParentURL = stagingParentURL self.pageSize = max(1, pageSize) self.checkpointStore = checkpointStore + self.stagingReferenceChecker = stagingReferenceChecker self.exportExecutorFactory = exportExecutorFactory self.now = now self.authorization = access.currentAuthorization() @@ -377,6 +380,10 @@ public final class PhotosImportStore: ObservableObject { guard Self.isChronoframeStagingDirectory(child) else { continue } guard let candidate = resumableCandidate(at: child, destination: destination) else { + // A finished export is the source of its copy. If the person + // quit mid-copy, the destination's pending jobs still read + // from this folder and a resume fails without it. + if isStillNeededByUnfinishedCopy(child) { continue } try? fileManager.removeItem(at: child) continue } @@ -395,6 +402,30 @@ public final class PhotosImportStore: ObservableObject { resumable = candidates.first } + /// How long a finished export is kept when its destination cannot be + /// checked (offline volume, denied path, unreadable queue) and so cannot + /// prove the folder unneeded. Past this it is removed: it can be many GB, + /// and losing it costs only a repeat export, never a user file. + private static let uncheckedStagingRetention: TimeInterval = 30 * 24 * 60 * 60 + + /// True when the finished (`.ready`) export in `directory` must survive + /// cleanup: a pending copy job still reads from it, or its destination + /// cannot be checked and the export is recent. Reads only. + private func isStillNeededByUnfinishedCopy(_ directory: URL) -> Bool { + guard let checkpoint = checkpointStore.load(in: directory), checkpoint.state == .ready else { return false } + switch stagingReferenceChecker.reference( + toStagingDirectory: directory, + destinationPath: checkpoint.destinationPath + ) { + case .referenced: + return true + case .unreferenced: + return false + case .undetermined: + return now().timeIntervalSince(checkpoint.updatedAt) < Self.uncheckedStagingRetention + } + } + /// The resumable import in `directory`, or nil when it has no usable /// checkpoint (missing, consumed, damaged or untrusted). Reads only. private func resumableCandidate(at directory: URL, destination: DestinationCapture?) -> PhotosResumableImport? { @@ -416,7 +447,16 @@ public final class PhotosImportStore: ObservableObject { /// once; a missing directory is not an error. public func cleanupStaging(for context: PhotosImportContext) { preparedStagingPaths.remove(context.stagingDirectoryURL.standardizedFileURL.path) - try? FileManager.default.removeItem(at: context.stagingDirectoryURL) + // A copy that stopped, failed or hit the free limit leaves pending + // jobs that still read from this folder; launch cleanup removes it + // once nothing does. + let reference = stagingReferenceChecker.reference( + toStagingDirectory: context.stagingDirectoryURL, + destinationPath: context.destinationPath + ) + if reference != .referenced { + try? FileManager.default.removeItem(at: context.stagingDirectoryURL) + } includeEditedVersions = false } diff --git a/ui/Sources/ChronoframeCore/DeduplicationPlanner.swift b/ui/Sources/ChronoframeCore/DeduplicationPlanner.swift index c7cd5ce3..106a60e3 100644 --- a/ui/Sources/ChronoframeCore/DeduplicationPlanner.swift +++ b/ui/Sources/ChronoframeCore/DeduplicationPlanner.swift @@ -24,6 +24,11 @@ import Foundation /// triggering member's cluster ownership so the receipt is complete. /// A partner listed in `fanoutProtectedPaths` (members of groups the /// caller did not pass because they are not reviewed) is never added. +/// A partner is trashed only when it is itself a duplicate (INV-14): a +/// partner outside every cluster stays, except a Live Photo MOV, which is +/// never clustered and so is added only when a member the plan keeps owns +/// a MOV of its own. The scanner also ranks the copy that has a partner +/// as the suggested keeper, so the lone copy is the one removed. public enum DeduplicationPlanner { public static func plan( decisions: DedupeDecisions, @@ -182,6 +187,18 @@ public enum DeduplicationPlanner { if decisions.pairKeepOverrides.contains(partner) { continue } + // INV-14: a partner is trashed only when it is itself a + // duplicate. A partner that is no cluster member is never a + // duplicate by exact content: RAW files are identity-hashed + // and exact-clustered, so a RAW outside every cluster has no + // identical copy and stays. Live Photo MOVs are never + // clustered, so a MOV outside every cluster goes only when a + // member this plan keeps owns a MOV of its own. + if effective[partner] == nil { + guard kind == .livePhoto, clusterKeepsAMemberWithItsOwnPartner( + of: kind, in: cluster, planItems: planItems, configuration: configuration + ) else { continue } + } if planItems[partner] != nil { continue } guard let expectedIdentity = snapshot.identitiesByPath[partner] else { continue @@ -307,6 +324,20 @@ public enum DeduplicationPlanner { // MARK: - Helpers + private static func clusterKeepsAMemberWithItsOwnPartner( + of kind: DeduplicatePairDetector.Pair.Kind, + in cluster: DuplicateCluster, + planItems: [String: DeduplicationPlan.Item], + configuration: DeduplicateConfiguration + ) -> Bool { + cluster.members.contains { member in + planItems[member.path] == nil + && member.pairedPath != nil + && pairKind(for: member) == kind + && pairKindEnabled(kind, in: configuration) + } + } + public static func isAutomaticCommitEligible(_ cluster: DuplicateCluster) -> Bool { // AGENTS-INVARIANT: 6 — Structural guard: a non-exact video cluster is // never eligible for automatic deletion, even if a future annotation diff --git a/ui/Sources/ChronoframeCore/DuplicateClusterer.swift b/ui/Sources/ChronoframeCore/DuplicateClusterer.swift index 2d40b67a..15d929d1 100644 --- a/ui/Sources/ChronoframeCore/DuplicateClusterer.swift +++ b/ui/Sources/ChronoframeCore/DuplicateClusterer.swift @@ -229,6 +229,10 @@ public enum DuplicateClusterer { let rhsSmile = rhs.smileScore ?? 0 if lhsSmile != rhsSmile { return lhsSmile > rhsSmile } if lhs.isRaw != rhs.isRaw { return lhs.isRaw } + // INV-14: among otherwise tied copies, the one with a RAW/MOV partner + // is kept, so the lone copy is the one removed and a partner is + // never trashed for lack of a keeper that owns one. + if (lhs.pairedPath != nil) != (rhs.pairedPath != nil) { return lhs.pairedPath != nil } return lhs.path < rhs.path } diff --git a/ui/Sources/ChronoframeCore/FreeDedupeBatchPlanner.swift b/ui/Sources/ChronoframeCore/FreeDedupeBatchPlanner.swift index d057891d..ade7c172 100644 --- a/ui/Sources/ChronoframeCore/FreeDedupeBatchPlanner.swift +++ b/ui/Sources/ChronoframeCore/FreeDedupeBatchPlanner.swift @@ -20,9 +20,11 @@ public enum FreeDedupeBatchPlanner { configuration: DeduplicateConfiguration, snapshot: DeduplicateScanSnapshot, fanoutProtectedPaths: Set, - limit: Int + limit: Int, + onPlannerRun: (() -> Void)? = nil ) -> FreeDedupeBatch? { // 1. The person's full reviewed plan. + onPlannerRun?() let full = DeduplicationPlanner.plan( decisions: decisions, clusters: reviewedClusters, @@ -46,28 +48,35 @@ public enum FreeDedupeBatchPlanner { } } - // 3 and 4. Grow the selection one group at a time. Forcing Keep is not - // monotone (pair Keep-wins can carry a Keep into another group and - // un-skip a group the all-Delete rail skipped), so a candidate is - // accepted only if it fits and deletes nothing the full plan does not. - var selected: Set = [] - var selectedOrder: [UUID] = [] - var accepted: DeduplicationPlan? + // 3 and 4. Search over how many groups of `ordered` to take. Forcing + // Keep is not monotone (pair Keep-wins can carry a Keep into another + // group and un-skip a group the all-Delete rail skipped), so a prefix + // is accepted only if it fits and deletes nothing the full plan does + // not. Each probe is one planner run, so the search starts from the + // prefix the full plan's own per-group counts predict and, only if that + // fails, gallops down then bisects: one run in the common case, about + // log2(N) at worst, instead of one per group. `lo` always passed both + // checks, `hi` always failed (the whole list is the full plan, which + // exceeds the limit). + var forced = ForcedKeepDecisions(decisions: decisions, groups: ordered.map { $0.members.map(\.path) }) + var deletesPerGroup: [UUID: Int] = [:] + for item in full.items { deletesPerGroup[item.owningClusterID, default: 0] += 1 } + var estimate = 0 + var running = 0 for cluster in ordered { - var trial = selected - trial.insert(cluster.id) - - var candidateDecisions = decisions - var byPath = decisions.byPath - for other in reviewedClusters where !trial.contains(other.id) { - for member in other.members { - byPath[member.path] = .keep - } - } - candidateDecisions.byPath = byPath + running += deletesPerGroup[cluster.id, default: 0] + guard running <= limit else { break } + estimate += 1 + } + var accepted: DeduplicationPlan? + var lo = 0 + var hi = ordered.count + func probe(_ prefixLength: Int) -> Bool { + forced.select(prefixLength) + onPlannerRun?() let candidate = DeduplicationPlanner.plan( - decisions: candidateDecisions, + decisions: forced.decisions, clusters: reviewedClusters, configuration: configuration, snapshot: snapshot, @@ -76,12 +85,33 @@ public enum FreeDedupeBatchPlanner { let withinFullPlan = candidate.items.allSatisfy { item in fullIdentities[item.path] == item.expectedIdentity } - guard candidate.count <= limit, withinFullPlan else { break } - + guard candidate.count <= limit, withinFullPlan else { return false } accepted = candidate - selected = trial - selectedOrder.append(cluster.id) + return true + } + + let first = min(max(estimate, 1), hi - 1) + if first >= 1 { + if probe(first) { + // The full plan's own count for the next group already + // overshoots the limit, so a larger prefix is not worth + // another full planner run to look for. + lo = first + hi = first + 1 + } else { + hi = first + var step = 1 + while hi > 1 { + let next = max(hi - step, 1) + if probe(next) { lo = next; break } else { hi = next; step *= 2 } + } + } + while hi - lo > 1 { + let mid = (lo + hi) / 2 + if probe(mid) { lo = mid } else { hi = mid } + } } + let selectedOrder = ordered.prefix(lo).map(\.id) // 5. guard let plan = accepted, !plan.items.isEmpty else { return nil } @@ -93,3 +123,43 @@ public enum FreeDedupeBatchPlanner { ) } } + +/// The decisions with every group after the first `selectedCount` forced to +/// Keep. Moving the prefix only touches the paths of the groups it crosses, +/// so a probe does not rebuild the whole dictionary. A path listed by several +/// groups stays Keep while any unselected group still lists it. +private struct ForcedKeepDecisions { + private let original: [String: DedupeDecision] + private let groups: [[String]] + private var unselectedGroupsListing: [String: Int] = [:] + private var selectedCount = 0 + private(set) var decisions: DedupeDecisions + + init(decisions: DedupeDecisions, groups: [[String]]) { + original = decisions.byPath + self.groups = groups + self.decisions = decisions + for path in groups.joined() { + unselectedGroupsListing[path, default: 0] += 1 + self.decisions.byPath[path] = .keep + } + } + + mutating func select(_ count: Int) { + while selectedCount < count { + for path in groups[selectedCount] { + let remaining = (unselectedGroupsListing[path] ?? 1) - 1 + unselectedGroupsListing[path] = remaining + if remaining == 0 { decisions.byPath[path] = original[path] } + } + selectedCount += 1 + } + while selectedCount > count { + selectedCount -= 1 + for path in groups[selectedCount] { + unselectedGroupsListing[path, default: 0] += 1 + decisions.byPath[path] = .keep + } + } + } +} diff --git a/ui/Tests/ChronoframeAppCoreTests/ChronoframeCoreFreeDedupeBatchPlannerTests.swift b/ui/Tests/ChronoframeAppCoreTests/ChronoframeCoreFreeDedupeBatchPlannerTests.swift index 5f6a6316..1c2328b5 100644 --- a/ui/Tests/ChronoframeAppCoreTests/ChronoframeCoreFreeDedupeBatchPlannerTests.swift +++ b/ui/Tests/ChronoframeAppCoreTests/ChronoframeCoreFreeDedupeBatchPlannerTests.swift @@ -97,6 +97,9 @@ final class ChronoframeCoreFreeDedupeBatchPlannerTests: XCTestCase { fixture.addGroup("a", deletes: 2, lane: .identical) fixture.addGroup("b", deletes: 2, lane: .nearlyIdentical) fixture.addGroup("c", deletes: 2, lane: .lookAtEach) { members in + // The kept still owns a movie of its own, so the dropped still's movie is a duplicate. + members[0].pairedPath = "/fx/c/keep.mov" + members[0].isLivePhotoStill = true members[1].pairedPath = "/fx/c/d1.mov" members[1].isLivePhotoStill = true } @@ -212,6 +215,9 @@ final class ChronoframeCoreFreeDedupeBatchPlannerTests: XCTestCase { var fixture = Fixture() // a/d1 is a Live Photo still whose MOV is not in any cluster; the person kept the MOV. fixture.addGroup("a", deletes: 1, lane: .lookAtEach) { members in + // The kept still owns a movie of its own, so the dropped still's movie is a duplicate. + members[0].pairedPath = "/fx/a/keep.mov" + members[0].isLivePhotoStill = true members[1].pairedPath = "/fx/a/d1.mov" members[1].isLivePhotoStill = true } @@ -251,14 +257,15 @@ final class ChronoframeCoreFreeDedupeBatchPlannerTests: XCTestCase { fixture.addGroup("other", deletes: 2, lane: .lookAtEach) fixture.fanoutProtectedPaths = ["/fx/a/X.dng", "/fx/b/X.dng"] - // Premise: unprotected, the keeper follows its pair partner into the plan. + // INV-14: a DNG outside the passed groups is unique content, so even an unprotected + // plan no longer carries it along with its JPEG. let unprotected = DeduplicationPlanner.plan( decisions: fixture.decisions, clusters: fixture.clusters, configuration: fixture.configuration, snapshot: fixture.snapshot ) - XCTAssertTrue(unprotected.items.contains { $0.path == "/fx/b/X.dng" }) + XCTAssertFalse(unprotected.items.contains { $0.path == "/fx/b/X.dng" }) let full = fixture.fullPlan() XCTAssertEqual(Set(full.items.map(\.path)), ["/fx/b/X.jpg", "/fx/other/d1.jpg", "/fx/other/d2.jpg"]) @@ -333,6 +340,106 @@ final class ChronoframeCoreFreeDedupeBatchPlannerTests: XCTestCase { XCTAssertEqual(Set(skipped.items.map(\.path)), ["/fx/z/z1.jpg"]) } + // MARK: Search + + /// Limit 1 on the Y/Z/W review above: the walk used to stop at Y, whose candidate + /// un-skips Y. The prefix search verifies Y+Z too, and that candidate passes both + /// checks, so the free batch is Z's single file. + func testPrefixSearchTakesALaterPrefixThatPassesBothChecks() throws { + var fixture = Fixture() + fixture.addGroup("y", deletes: 1, lane: .lookAtEach) { members in + members[0].path = "/fx/y/y1.jpg" + members[1].path = "/fx/y/y2.jpg" + members[0].pairedPath = "/fx/z/z1.jpg" + } + let z = fixture.addGroup("z", deletes: 1, lane: .lookAtEach) { members in + members[0].path = "/fx/z/z2.jpg" + members[1].path = "/fx/z/z1.jpg" + members[1].pairedPath = "/fx/y/y1.jpg" + } + fixture.addGroup("w", deletes: 1, lane: .lookAtEach) + fixture.decisions.byPath = [ + "/fx/y/y1.jpg": .delete, + "/fx/y/y2.jpg": .delete, + "/fx/z/z1.jpg": .delete, + "/fx/z/z2.jpg": .keep, + "/fx/w/keep.jpg": .keep, + "/fx/w/d1.jpg": .delete, + ] + XCTAssertEqual(fixture.fullPlan().count, 2) + + let batch = try XCTUnwrap(fixture.batch(limit: 1)) + XCTAssertEqual(batch.plan.items.map(\.path), ["/fx/z/z1.jpg"]) + XCTAssertEqual(batch.includedClusterIDs, [z.id]) + XCTAssertEqual(batch.deferredFileCount, 1) + } + + /// The predicted prefix fails (it un-skips Y); the search falls back to a smaller + /// prefix that passes, as the one-group-at-a-time walk did. + func testFailedPredictionFallsBackToASmallerPassingPrefix() throws { + var fixture = Fixture() + let p = fixture.addGroup("p", deletes: 1, lane: .lookAtEach) + fixture.addGroup("y", deletes: 1, lane: .lookAtEach) { members in + members[0].path = "/fx/y/y1.jpg" + members[1].path = "/fx/y/y2.jpg" + members[0].pairedPath = "/fx/z/z1.jpg" + } + fixture.addGroup("w", deletes: 1, lane: .lookAtEach) + fixture.addGroup("z", deletes: 1, lane: .lookAtEach) { members in + members[0].path = "/fx/z/z2.jpg" + members[1].path = "/fx/z/z1.jpg" + members[1].pairedPath = "/fx/y/y1.jpg" + } + fixture.decisions.byPath = [ + "/fx/p/keep.jpg": .keep, + "/fx/p/d1.jpg": .delete, + "/fx/y/y1.jpg": .delete, + "/fx/y/y2.jpg": .delete, + "/fx/z/z1.jpg": .delete, + "/fx/z/z2.jpg": .keep, + "/fx/w/keep.jpg": .keep, + "/fx/w/d1.jpg": .delete, + ] + XCTAssertEqual(Set(fixture.fullPlan().items.map(\.path)), ["/fx/p/d1.jpg", "/fx/z/z1.jpg", "/fx/w/d1.jpg"]) + + let batch = try XCTUnwrap(fixture.batch(limit: 2)) + XCTAssertEqual(batch.plan.items.map(\.path), ["/fx/p/d1.jpg"]) + XCTAssertEqual(batch.includedClusterIDs, [p.id]) + } + + /// The offer is recomputed on the main actor whenever a decision changes, so the + /// number of full planner runs must stay logarithmic in the reviewed group count, + /// not one per group taken. + func testTenThousandReviewedGroupsNeedOnlyAHandfulOfPlannerRuns() throws { + var fixture = Fixture() + let lanes = DeduplicateReviewLane.allCases + for index in 0..<10_000 { + fixture.addGroup("g\(index)", deletes: 1 + index % 3, lane: lanes[index % lanes.count]) + } + let full = fixture.fullPlan() + XCTAssertGreaterThan(full.count, 100) + let fullIdentities = Dictionary(uniqueKeysWithValues: full.items.map { ($0.path, $0.expectedIdentity) }) + + var runs = 0 + let batch = try XCTUnwrap(FreeDedupeBatchPlanner.batch( + decisions: fixture.decisions, + reviewedClusters: fixture.clusters, + configuration: fixture.configuration, + snapshot: fixture.snapshot, + fanoutProtectedPaths: fixture.fanoutProtectedPaths, + limit: 100, + onPlannerRun: { runs += 1 } + )) + + XCTAssertLessThanOrEqual(runs, 4, "the old walk ran the planner about 100 times") + XCTAssertLessThanOrEqual(batch.plan.count, 100) + XCTAssertGreaterThan(batch.plan.count, 90, "the prediction should fill the allowance") + for item in batch.plan.items { + XCTAssertEqual(fullIdentities[item.path], item.expectedIdentity) + } + XCTAssertEqual(batch.deferredFileCount, full.count - batch.plan.count) + } + // MARK: Property func testPropertyRandomReviewsNeverExceedLimitOrLeaveTheFullPlan() { diff --git a/ui/Tests/ChronoframeAppCoreTests/DeduplicateSessionStoreTests.swift b/ui/Tests/ChronoframeAppCoreTests/DeduplicateSessionStoreTests.swift index d99147fd..4bc8e72d 100644 --- a/ui/Tests/ChronoframeAppCoreTests/DeduplicateSessionStoreTests.swift +++ b/ui/Tests/ChronoframeAppCoreTests/DeduplicateSessionStoreTests.swift @@ -171,7 +171,9 @@ final class DeduplicateSessionStoreTests: XCTestCase { path: "/dest/OTHER.HEIC", size: 50, modificationTime: 0, - qualityScore: 0.9 + qualityScore: 0.9, + isLivePhotoStill: true, + pairedPath: "/dest/OTHER.MOV" ) let cluster = DuplicateCluster( id: clusterID, @@ -618,7 +620,9 @@ final class DeduplicateSessionStoreTests: XCTestCase { path: "/dest/OTHER.HEIC", size: 50, modificationTime: 0, - qualityScore: 0.9 + qualityScore: 0.9, + isLivePhotoStill: true, + pairedPath: "/dest/OTHER.MOV" ) let cluster = DuplicateCluster( kind: .burst, @@ -1407,14 +1411,15 @@ final class DeduplicateSessionStoreTests: XCTestCase { XCTAssertTrue(committed) XCTAssertEqual(Set(engine.lastCommitPlan?.items.map(\.path) ?? []), expected) - // Premise: unprotected, the DNG keeper rides along with its JPEG. + // INV-14: a DNG outside the passed groups is unique content, so even an unprotected + // plan no longer carries it along with its JPEG. let unprotected = DeduplicationPlanner.plan( decisions: store.decisions, clusters: [jpegs, other], configuration: DeduplicateConfiguration(destinationPath: "/dest"), snapshot: engine.summary.scanSnapshot ) - XCTAssertTrue(unprotected.items.contains { $0.path == "/dest/b/X.dng" }) + XCTAssertFalse(unprotected.items.contains { $0.path == "/dest/b/X.dng" }) } /// The count a lane card shows is what accepting the lane would plan, so it holds back @@ -1483,6 +1488,24 @@ final class DeduplicateSessionStoreTests: XCTestCase { XCTAssertEqual(store.laneSummaries[.nearlyIdentical]?.groups, 0) } + @MainActor + func testAcceptSuggestionsForClustersTakesOnlyTheGivenUnreviewedEligibleGroups() async throws { + let listed = laneCluster("listed", lane: .nearlyIdentical, deletes: 1) + let unlisted = laneCluster("unlisted", lane: .nearlyIdentical, deletes: 1) + let alreadyDone = laneCluster("alreadyDone", lane: .nearlyIdentical, deletes: 1) + let look = laneCluster("look", lane: .lookAtEach, deletes: 1) + let (store, _) = await scannedLaneStore([listed, unlisted, alreadyDone, look]) + store.acceptSuggestionsForCluster(alreadyDone) + let decisionsBefore = store.decisions + + store.acceptSuggestions(forClusters: [listed, alreadyDone, look]) + + XCTAssertEqual(store.approvedClusterIDs, [listed.id, alreadyDone.id], "Only listed, eligible, unreviewed groups") + XCTAssertFalse(store.approvedClusterIDs.contains(unlisted.id)) + XCTAssertFalse(store.approvedClusterIDs.contains(look.id), "A group to look at stays review-only") + XCTAssertEqual(store.decisions, decisionsBefore) + } + @MainActor func testAcceptLookAtEachDoesNothing() async throws { let look = laneCluster("look", lane: .lookAtEach, deletes: 1) @@ -1758,7 +1781,11 @@ final class DeduplicateSessionStoreTests: XCTestCase { var still = PhotoCandidate(path: "/dest/live/d1.heic", size: 100, modificationTime: 0) still.pairedPath = "/dest/live/d1.mov" still.isLivePhotoStill = true - let members = [PhotoCandidate(path: "/dest/live/keep.heic", size: 100, modificationTime: 0), still] + // The kept still owns a movie of its own, so the dropped still's movie is a duplicate. + var keeper = PhotoCandidate(path: "/dest/live/keep.heic", size: 100, modificationTime: 0) + keeper.pairedPath = "/dest/live/keep.mov" + keeper.isLivePhotoStill = true + let members = [keeper, still] let cluster = DuplicateCluster( kind: .exactDuplicate, members: members, @@ -1950,6 +1977,45 @@ final class DeduplicateSessionStoreTests: XCTestCase { XCTAssertEqual(store.decisions.byPath["/dest/live/d1.heic"], .keep) } + /// A commit that moved nothing (every item failed or was skipped) has not used + /// up the person's review, so the saved review stays for the next scan. + @MainActor + func testCommitThatMovedNothingKeepsSavedReview() async throws { + let snapshotStore = InMemoryDeduplicateReviewSnapshotStore() + let cluster = laneCluster("only", lane: .identical, deletes: 2) + let nothingMoved = DeduplicateCommitSummary(deletedCount: 0, failedCount: 2, bytesReclaimed: 0, receiptPath: nil, hardDelete: false) + let (store, _) = await scannedLaneStore([cluster], commitEvents: [.complete(nothingMoved)], snapshotStore: snapshotStore) + store.refreshSavedReview(folderPath: "/dest") + store.acceptSuggestions(in: .identical) + store.prepareReviewedCommitPlan() + store.commitReviewed(configuration: DeduplicateConfiguration(destinationPath: "/dest")) + let completed = await waitForCondition { store.status == .completed } + XCTAssertTrue(completed) + + XCTAssertEqual(store.commitSummary?.deletedCount, 0) + XCTAssertTrue(snapshotStore.removals.isEmpty, "Nothing moved, so the review work is not spent") + XCTAssertNotNil(snapshotStore.load(folderPath: "/dest")) + XCTAssertNotNil(store.savedReviewForCurrentFolder) + } + + /// One file moved and one failed: the review is spent, as before. + @MainActor + func testCommitThatMovedSomethingStillRemovesSavedReviewEvenWithFailures() async throws { + let snapshotStore = InMemoryDeduplicateReviewSnapshotStore() + let cluster = laneCluster("only", lane: .identical, deletes: 2) + let partial = DeduplicateCommitSummary(deletedCount: 1, failedCount: 1, bytesReclaimed: 100, receiptPath: nil, hardDelete: false) + let (store, _) = await scannedLaneStore([cluster], commitEvents: [.complete(partial)], snapshotStore: snapshotStore) + store.refreshSavedReview(folderPath: "/dest") + store.acceptSuggestions(in: .identical) + store.prepareReviewedCommitPlan() + store.commitReviewed(configuration: DeduplicateConfiguration(destinationPath: "/dest")) + let completed = await waitForCondition { store.status == .completed } + XCTAssertTrue(completed) + + XCTAssertEqual(snapshotStore.removals, ["/dest"]) + XCTAssertNil(store.savedReviewForCurrentFolder) + } + @MainActor func testOrdinaryCommitStillRemovesSavedReview() async throws { let snapshotStore = InMemoryDeduplicateReviewSnapshotStore() diff --git a/ui/Tests/ChronoframeAppCoreTests/DeduplicateTests.swift b/ui/Tests/ChronoframeAppCoreTests/DeduplicateTests.swift index c586cfd4..5dcef12d 100644 --- a/ui/Tests/ChronoframeAppCoreTests/DeduplicateTests.swift +++ b/ui/Tests/ChronoframeAppCoreTests/DeduplicateTests.swift @@ -805,13 +805,14 @@ final class DeduplicateTests: XCTestCase { // MARK: - DeduplicationPlanner - /// Verifies step 5 of the planner — paired singletons (typically the - /// RAW half of a RAW+JPEG pair sitting outside any duplicate cluster) - /// are fanned into the plan when their JPEG counterpart inside the - /// cluster is deleted and the RAW pairing toggle is on. Mirrors the - /// "partner outside cluster" pattern used by + /// Verifies step 5 of the planner — a RAW half of a RAW+JPEG pair + /// sitting outside any duplicate cluster has no identical copy in the + /// scan, so deleting its JPEG counterpart inside the cluster must NOT + /// fan it into the plan, even with the RAW pairing toggle on (INV-14). + /// Mirrors the "partner outside cluster" pattern used by /// `testPlannerHonorsPairTogglesIndependently`. - func testPlannerExpandsRawJpegPairWhenToggleEnabled() { + // AGENTS-INVARIANT: 14 + func testPlannerLeavesUniqueRawPartnerWhenToggleEnabled() { let jpeg = candidate(path: "/dest/IMG.JPG", pairedPath: "/dest/IMG.CR2") let other = candidate(path: "/dest/OTHER.JPG") @@ -830,7 +831,7 @@ final class DeduplicateTests: XCTestCase { let plan = DeduplicationPlanner.plan(decisions: decisions, clusters: [cluster], configuration: config, snapshot: testScanSnapshot(for: [cluster])) let paths = Set(plan.pathsToDelete) XCTAssertTrue(paths.contains("/dest/IMG.JPG")) - XCTAssertTrue(paths.contains("/dest/IMG.CR2"), "Singleton RAW partner must be fanned into the plan") + XCTAssertFalse(paths.contains("/dest/IMG.CR2"), "A RAW partner outside every cluster is unique content and must stay") XCTAssertFalse(paths.contains("/dest/OTHER.JPG")) } @@ -1242,7 +1243,9 @@ final class DeduplicateTests: XCTestCase { configuration: configRawOn, snapshot: testScanSnapshot(for: [cluster]) ) - XCTAssertTrue(Set(planRawOn.pathsToDelete).contains("/dest/IMG.CR2")) + // INV-14: the RAW sits outside every cluster, so it is unique and + // stays whichever way the toggle is set. + XCTAssertFalse(Set(planRawOn.pathsToDelete).contains("/dest/IMG.CR2")) } /// Live Photo pairing toggle is honored independently of the @@ -1295,7 +1298,12 @@ final class DeduplicateTests: XCTestCase { pairedPath: "/dest/IMG.MOV", isLivePhotoStill: true ) - let other = candidate(path: "/dest/OTHER.HEIC", qualityScore: 0.9) + let other = candidate( + path: "/dest/OTHER.HEIC", + qualityScore: 0.9, + pairedPath: "/dest/OTHER.MOV", + isLivePhotoStill: true + ) let cluster = DuplicateCluster( kind: .burst, members: [heic, other], @@ -1454,7 +1462,12 @@ final class DeduplicateTests: XCTestCase { pairedPath: "/dest/IMG.MOV", isLivePhotoStill: true ) - let other = candidate(path: "/dest/OTHER.HEIC", qualityScore: 0.9) + let other = candidate( + path: "/dest/OTHER.HEIC", + qualityScore: 0.9, + pairedPath: "/dest/OTHER.MOV", + isLivePhotoStill: true + ) let cluster = DuplicateCluster( kind: .burst, members: [heic, other], @@ -1499,7 +1512,9 @@ final class DeduplicateTests: XCTestCase { let other = candidate( path: temporaryDirectory.appendingPathComponent("OTHER.HEIC").path, qualityScore: 0.9, - size: 50 + size: 50, + pairedPath: temporaryDirectory.appendingPathComponent("OTHER.MOV").path, + isLivePhotoStill: true ) let cluster = DuplicateCluster( kind: .burst, diff --git a/ui/Tests/ChronoframeAppCoreTests/DeduplicationPlannerGroupRailTests.swift b/ui/Tests/ChronoframeAppCoreTests/DeduplicationPlannerGroupRailTests.swift index 3cb6d00f..034171fc 100644 --- a/ui/Tests/ChronoframeAppCoreTests/DeduplicationPlannerGroupRailTests.swift +++ b/ui/Tests/ChronoframeAppCoreTests/DeduplicationPlannerGroupRailTests.swift @@ -133,14 +133,15 @@ final class DeduplicationPlannerGroupRailTests: XCTestCase { XCTAssertEqual(plan.items.map(\.path), [jpegB.path], "b/X.dng is the unreviewed group's keeper and must stay") - // Premise: without the protected set the keeper follows its pair partner into the plan. + // INV-14: a DNG outside the passed groups is unique content, so even without the + // protected set it no longer follows its pair partner into the plan. let unprotected = DeduplicationPlanner.plan( decisions: decisions, clusters: [reviewed], configuration: configuration(), snapshot: testScanSnapshot(for: [reviewed]) ) - XCTAssertEqual(Set(unprotected.items.map(\.path)), [jpegB.path, dngB.path]) + XCTAssertEqual(Set(unprotected.items.map(\.path)), [jpegB.path]) } // AGENTS-INVARIANT: 14 @@ -173,8 +174,8 @@ final class DeduplicationPlannerGroupRailTests: XCTestCase { } // AGENTS-INVARIANT: 14 - func testPairPartnerInNoGroupStillFansOut() { - // Only the protected paths are shielded; a true singleton partner is unchanged behaviour. + func testPairPartnerInNoGroupIsNeverFannedOut() { + // A RAW in no group has no identical copy in the scan, so it stays (INV-14). let jpegA = candidate("/lib/a/X.jpg", pairedPath: "/lib/a/X.dng") let jpegB = candidate("/lib/b/X.jpg", pairedPath: "/lib/b/X.dng") let reviewed = cluster([jpegA, jpegB]) @@ -188,7 +189,7 @@ final class DeduplicationPlannerGroupRailTests: XCTestCase { fanoutProtectedPaths: ["/lib/c/unrelated.dng"] ) - XCTAssertEqual(Set(plan.items.map(\.path)), [jpegB.path, "/lib/b/X.dng"]) + XCTAssertEqual(Set(plan.items.map(\.path)), [jpegB.path]) } // AGENTS-INVARIANT: 14 diff --git a/ui/Tests/ChronoframeAppCoreTests/DeduplicationPlannerPartnerFanoutTests.swift b/ui/Tests/ChronoframeAppCoreTests/DeduplicationPlannerPartnerFanoutTests.swift new file mode 100644 index 00000000..774f28d8 --- /dev/null +++ b/ui/Tests/ChronoframeAppCoreTests/DeduplicationPlannerPartnerFanoutTests.swift @@ -0,0 +1,223 @@ +import Foundation +import XCTest +@testable import ChronoframeCore + +/// INV-14 partner rule: the copy that has a RAW/MOV partner is the suggested +/// keeper, and a partner is trashed only when it is itself a duplicate. A RAW +/// outside every cluster has no identical copy in the scan (RAW files are +/// identity-hashed and exact-clustered), so fan-out never adds it. A Live +/// Photo MOV is never clustered, so a singleton MOV is added only when a +/// member the plan keeps owns a MOV of its own. +final class DeduplicationPlannerPartnerFanoutTests: XCTestCase { + // MARK: Keeper suggestion + + // AGENTS-INVARIANT: 14 + func testPairedCopyOutranksLoneCopyWhenOtherwiseTied() throws { + // The lone copy sorts first by path, so only the partner tie-break can pick the paired one. + let lone = candidate("/lib/a/X.jpg") + let paired = candidate("/lib/z/X.jpg", pairedPath: "/lib/z/X.dng") + + let clusters = DuplicateClusterer.exactDuplicateClusters( + candidatesByIdentity: [FileIdentity(size: 1_000, digest: "same"): [lone, paired]] + ) + let cluster = try XCTUnwrap(clusters.first) + + XCTAssertEqual(cluster.suggestedKeeperIDs, [paired.id]) + } + + // AGENTS-INVARIANT: 14 + func testPartnerTieBreakDoesNotOverrideQualityEvidence() { + let sharper = candidate("/lib/a/X.jpg", qualityScore: 0.9) + let paired = candidate("/lib/z/X.jpg", pairedPath: "/lib/z/X.dng", qualityScore: 0.5) + + let keepers = DuplicateClusterer.suggestKeeperIDs(for: [paired, sharper]) + + XCTAssertEqual(keepers, [sharper.id]) + } + + // AGENTS-INVARIANT: 14 + func testAcceptingIdenticalCopiesTrashesOnlyTheLoneJpeg() throws { + let lone = candidate("/lib/a/X.jpg") + let paired = candidate("/lib/z/X.jpg", pairedPath: "/lib/z/X.dng") + let cluster = try XCTUnwrap(DuplicateClusterer.exactDuplicateClusters( + candidatesByIdentity: [FileIdentity(size: 1_000, digest: "same"): [lone, paired]] + ).first) + + let decisions = DeduplicationPlanner.automaticDecisions(for: [cluster], configuration: configuration()) + let plan = DeduplicationPlanner.plan( + decisions: decisions, + clusters: [cluster], + configuration: configuration(), + snapshot: testScanSnapshot(for: [cluster]) + ) + + XCTAssertEqual(plan.items.map(\.path), [lone.path]) + } + + // MARK: RAW fan-out + + // AGENTS-INVARIANT: 14 + func testExplicitDeleteOnPairedJpegLeavesUniqueRawOutOfThePlan() { + let paired = candidate("/lib/a/X.jpg", pairedPath: "/lib/a/X.dng") + let lone = candidate("/lib/b/X.jpg") + let cluster = exactCluster([paired, lone], keeper: lone) + let decisions = DedupeDecisions(byPath: [paired.path: .delete, lone.path: .keep]) + + let plan = DeduplicationPlanner.plan( + decisions: decisions, + clusters: [cluster], + configuration: configuration(), + snapshot: testScanSnapshot(for: [cluster]) + ) + + XCTAssertEqual(plan.items.map(\.path), [paired.path]) + } + + // AGENTS-INVARIANT: 14 + func testPartnerThatIsItselfADuplicateStillGoes() { + let jpegA = candidate("/lib/a/X.jpg", pairedPath: "/lib/a/X.dng") + let jpegB = candidate("/lib/b/X.jpg", pairedPath: "/lib/b/X.dng") + let rawA = candidate("/lib/a/X.dng", isRaw: true, pairedPath: "/lib/a/X.jpg") + let rawB = candidate("/lib/b/X.dng", isRaw: true, pairedPath: "/lib/b/X.jpg") + let jpegs = exactCluster([jpegA, jpegB], keeper: jpegB) + let raws = exactCluster([rawA, rawB], keeper: rawB) + + // Auto-selected: both high-confidence clusters mark the "a" copies Delete. + let auto = DeduplicationPlanner.plan( + decisions: DedupeDecisions(byPath: [:]), + clusters: [jpegs, raws], + configuration: configuration(), + snapshot: testScanSnapshot(for: [jpegs, raws]) + ) + XCTAssertEqual(Set(auto.items.map(\.path)), [jpegA.path, rawA.path]) + + // Explicit: the partner is marked Delete by the user. + let explicit = DeduplicationPlanner.plan( + decisions: DedupeDecisions(byPath: [ + jpegA.path: .delete, jpegB.path: .keep, rawA.path: .delete, rawB.path: .keep, + ]), + clusters: [jpegs, raws], + configuration: configuration(), + snapshot: testScanSnapshot(for: [jpegs, raws]) + ) + XCTAssertEqual(Set(explicit.items.map(\.path)), [jpegA.path, rawA.path]) + } + + // MARK: Live Photo fan-out (MOVs are never clustered) + + // AGENTS-INVARIANT: 14 + func testSingletonMovGoesWhenTheKeptStillHasItsOwnMov() { + let kept = candidate("/lib/a/IMG_1.HEIC", pairedPath: "/lib/a/IMG_1.MOV", isLivePhotoStill: true) + let dropped = candidate("/lib/b/IMG_1.HEIC", pairedPath: "/lib/b/IMG_1.MOV", isLivePhotoStill: true) + let cluster = exactCluster([kept, dropped], keeper: kept) + + let plan = DeduplicationPlanner.plan( + decisions: DedupeDecisions(byPath: [:]), + clusters: [cluster], + configuration: configuration(), + snapshot: testScanSnapshot(for: [cluster]) + ) + + XCTAssertEqual(Set(plan.items.map(\.path)), [dropped.path, "/lib/b/IMG_1.MOV"]) + XCTAssertEqual(plan.items.first { $0.path == "/lib/b/IMG_1.MOV" }?.pairOrigin, .livePhoto) + } + + // AGENTS-INVARIANT: 14 + func testSingletonMovStaysWhenTheKeptStillHasNoMov() { + let kept = candidate("/lib/a/IMG_1.HEIC") + let dropped = candidate("/lib/b/IMG_1.HEIC", pairedPath: "/lib/b/IMG_1.MOV", isLivePhotoStill: true) + let cluster = exactCluster([kept, dropped], keeper: kept) + + let plan = DeduplicationPlanner.plan( + decisions: DedupeDecisions(byPath: [:]), + clusters: [cluster], + configuration: configuration(), + snapshot: testScanSnapshot(for: [cluster]) + ) + + XCTAssertEqual(plan.items.map(\.path), [dropped.path]) + } + + // AGENTS-INVARIANT: 14 + func testSingletonMovStaysWhenTheKeptMemberHasARawPartnerInstead() { + // Same extension class: a kept RAW+JPEG partner does not justify trashing a MOV. + let kept = candidate("/lib/a/IMG_1.HEIC", pairedPath: "/lib/a/IMG_1.DNG") + let dropped = candidate("/lib/b/IMG_1.HEIC", pairedPath: "/lib/b/IMG_1.MOV", isLivePhotoStill: true) + let cluster = exactCluster([kept, dropped], keeper: kept) + + let plan = DeduplicationPlanner.plan( + decisions: DedupeDecisions(byPath: [:]), + clusters: [cluster], + configuration: configuration(), + snapshot: testScanSnapshot(for: [cluster]) + ) + + XCTAssertEqual(plan.items.map(\.path), [dropped.path]) + } + + // MARK: Sidecars + + // AGENTS-INVARIANT: 14 + func testSidecarSharedWithASurvivingRawPartnerSurvives() { + let paired = candidate("/lib/a/X.jpg", pairedPath: "/lib/a/X.dng", sidecarPaths: ["/lib/a/X.xmp"]) + let lone = candidate("/lib/b/X.jpg") + let cluster = exactCluster([paired, lone], keeper: lone) + let snapshot = testScanSnapshot( + for: [cluster], + sidecarOwners: ["/lib/a/X.xmp": ["/lib/a/X.jpg", "/lib/a/X.dng"]] + ) + + let plan = DeduplicationPlanner.plan( + decisions: DedupeDecisions(byPath: [paired.path: .delete, lone.path: .keep]), + clusters: [cluster], + configuration: configuration(), + snapshot: snapshot + ) + + XCTAssertEqual(plan.items.map(\.path), [paired.path], "the RAW stays, so the sidecar it shares stays") + } + + // MARK: Helpers + + private func candidate( + _ path: String, + isRaw: Bool = false, + pairedPath: String? = nil, + isLivePhotoStill: Bool = false, + qualityScore: Double = 0.5, + sidecarPaths: [String] = [] + ) -> PhotoCandidate { + PhotoCandidate( + path: path, + size: 1_000, + modificationTime: 0, + qualityScore: qualityScore, + isRaw: isRaw, + isLivePhotoStill: isLivePhotoStill, + pairedPath: pairedPath, + sidecarPaths: sidecarPaths + ) + } + + private func exactCluster(_ members: [PhotoCandidate], keeper: PhotoCandidate) -> DuplicateCluster { + DuplicateCluster( + kind: .exactDuplicate, + members: members, + suggestedKeeperIDs: [keeper.id], + bytesIfPruned: 0, + annotation: ClusterAnnotation( + confidence: .high, + matchReason: MatchReason(kind: .exactDuplicate), + warnings: [] + ) + ) + } + + private func configuration() -> DeduplicateConfiguration { + DeduplicateConfiguration( + destinationPath: "/tmp/destination", + treatRawJpegPairsAsUnit: true, + treatLivePhotoPairsAsUnit: true + ) + } +} diff --git a/ui/Tests/ChronoframeAppCoreTests/PhotosImportResumeTests.swift b/ui/Tests/ChronoframeAppCoreTests/PhotosImportResumeTests.swift index 944b8f89..5a0fc780 100644 --- a/ui/Tests/ChronoframeAppCoreTests/PhotosImportResumeTests.swift +++ b/ui/Tests/ChronoframeAppCoreTests/PhotosImportResumeTests.swift @@ -845,6 +845,230 @@ final class PhotosImportResumeTests: XCTestCase { XCTAssertNil(store.resumable) } + // MARK: Launch cleanup keeps staging an unfinished copy still needs + + /// A `.ready` staging folder (the state a copy reads from) next to a + /// destination whose copy queue names `jobs`, each a file in the staging + /// folder and the status its job reached: the disk a transfer that was + /// quit part-way through leaves behind. + private func seedReadyStagingWithQueue( + parent: URL, + name: String, + assetIDs: [String] = ["a", "b"], + updatedAt: Date, + jobs: [(file: String, status: CopyJobStatus)], + resolveJobPaths: Bool = false + ) throws -> (staging: URL, destination: URL) { + let staging = parent.appendingPathComponent(name, isDirectory: true) + let destination = makeTempParent() + try FileManager.default.createDirectory(at: destination, withIntermediateDirectories: true) + let database = try OrganizerDatabase(url: destination.appendingPathComponent(".organize_cache.db")) + defer { database.close() } + let base = resolveJobPaths ? staging.resolvingSymlinksInPath().standardizedFileURL.path : staging.path + try database.enqueueQueuedJobs(jobs.enumerated().map { index, job in + QueuedCopyJob( + sourcePath: base + "/" + job.file, + destinationPath: destination.appendingPathComponent("2024/photo-\(index).jpg").path, + hash: FileIdentity(size: 1, digest: "d\(index)").rawValue, + status: job.status + ) + }) + let seeded = try seedCheckpoint( + parent: parent, name: name, state: .ready, assetIDs: assetIDs, + updatedAt: updatedAt, destinationPath: destination.path + ) + return (seeded, destination) + } + + private func capture(_ destination: URL) -> PhotosImportStore.DestinationCapture { + PhotosImportStore.DestinationCapture(path: destination.path, bookmarkKeys: ["k"]) + } + + @MainActor + func testRelaunchKeepsReadyStagingWhilePendingCopyJobsStillReferenceIt() throws { + let parent = makeTempParent() + let (staging, destination) = try seedReadyStagingWithQueue( + parent: parent, name: "mid-copy", updatedAt: fixedDate(10), + jobs: [("a.jpg", .copied), ("b.jpg", .pending)] + ) + + // A new store over the same staging parent is a relaunch: nothing is + // remembered in memory, so only what is on disk can protect the folder. + let relaunched = makeStore(ids: ["a"], exporter: ScriptedExporter(), staging: parent) + relaunched.refreshResumableImport(destination: capture(destination)) + + XCTAssertTrue(exists(staging.path), "A staged export a pending copy job reads from must survive launch cleanup") + XCTAssertTrue(exists(staging.appendingPathComponent("b.jpg").path)) + XCTAssertNil(relaunched.resumable, "A copy-phase folder is kept for the copy, not offered as an interrupted export") + } + + @MainActor + func testReferenceIsFoundWhenTheJobPathIsTheSymlinkResolvedForm() throws { + let parent = makeTempParent() + let (staging, destination) = try seedReadyStagingWithQueue( + parent: parent, name: "mid-copy", assetIDs: ["a"], updatedAt: fixedDate(10), + jobs: [("a.jpg", .pending)], resolveJobPaths: true + ) + + makeStore(ids: ["a"], exporter: ScriptedExporter(), staging: parent) + .refreshResumableImport(destination: capture(destination)) + + XCTAssertTrue(exists(staging.path)) + } + + @MainActor + func testReferencedStagingSurvivesRegardlessOfAge() throws { + // Age never overrides proof: the queue still names the folder. + let parent = makeTempParent() + let (staging, _) = try seedReadyStagingWithQueue( + parent: parent, name: "old", assetIDs: ["a"], updatedAt: fixedDate(-86_400 * 400), + jobs: [("a.jpg", .pending)] + ) + + makeStore(ids: ["a"], exporter: ScriptedExporter(), staging: parent).refreshResumableImport(destination: nil) + + XCTAssertTrue(exists(staging.path)) + } + + private func context(staging: URL, destination: URL) -> PhotosImportContext { + PhotosImportContext( + importID: UUID(), stagingDirectoryURL: staging, destinationPath: destination.path, + destinationBookmarkKeys: ["k"], assetIDs: ["a", "b"], sourceDateHints: [:] + ) + } + + @MainActor + func testCleanupAfterAStoppedCopyKeepsStagingItsPendingJobsStillRead() throws { + let parent = makeTempParent() + let (staging, destination) = try seedReadyStagingWithQueue( + parent: parent, name: "stopped", updatedAt: fixedDate(10), + jobs: [("a.jpg", .copied), ("b.jpg", .pending)] + ) + + makeStore(ids: ["a"], exporter: ScriptedExporter(), staging: parent) + .cleanupStaging(for: context(staging: staging, destination: destination)) + + XCTAssertTrue(exists(staging.appendingPathComponent("b.jpg").path), "A stopped copy can only be finished from its staged export") + } + + @MainActor + func testCleanupAfterAFinishedCopyRemovesStaging() throws { + let parent = makeTempParent() + let (staging, destination) = try seedReadyStagingWithQueue( + parent: parent, name: "done", updatedAt: fixedDate(10), + jobs: [("a.jpg", .copied), ("b.jpg", .copied)] + ) + + makeStore(ids: ["a"], exporter: ScriptedExporter(), staging: parent) + .cleanupStaging(for: context(staging: staging, destination: destination)) + + XCTAssertFalse(exists(staging.path)) + } + + @MainActor + func testRelaunchRemovesReadyStagingOnceItsCopyJobsFinished() throws { + let parent = makeTempParent() + let (staging, destination) = try seedReadyStagingWithQueue( + parent: parent, name: "finished", updatedAt: fixedDate(10), + jobs: [("a.jpg", .copied), ("b.jpg", .skipped)] + ) + + makeStore(ids: ["a"], exporter: ScriptedExporter(), staging: parent) + .refreshResumableImport(destination: capture(destination)) + + XCTAssertFalse(exists(staging.path), "Staging nothing references any more is cleaned up") + } + + @MainActor + func testStagingIsRemovedOnceTheResumedCopyHasFinishedIt() throws { + let parent = makeTempParent() + let (staging, destination) = try seedReadyStagingWithQueue( + parent: parent, name: "mid-copy", assetIDs: ["a"], updatedAt: fixedDate(10), + jobs: [("a.jpg", .pending)] + ) + + makeStore(ids: ["a"], exporter: ScriptedExporter(), staging: parent) + .refreshResumableImport(destination: capture(destination)) + XCTAssertTrue(exists(staging.path)) + + let database = try OrganizerDatabase(url: destination.appendingPathComponent(".organize_cache.db")) + try database.updateJobStatus(sourcePath: staging.path + "/a.jpg", status: .copied) + database.close() + + makeStore(ids: ["a"], exporter: ScriptedExporter(), staging: parent) + .refreshResumableImport(destination: capture(destination)) + XCTAssertFalse(exists(staging.path), "Once the copy finished, the next launch frees the space") + } + + @MainActor + func testRelaunchRemovesReadyStagingTheQueueNeverReferenced() throws { + let parent = makeTempParent() + let unrelated = try seedReadyStagingWithQueue( + parent: parent, name: "unrelated", assetIDs: ["a"], updatedAt: fixedDate(10), + jobs: [] + ) + // A pending job for some other source does not protect this folder. + let database = try OrganizerDatabase(url: unrelated.destination.appendingPathComponent(".organize_cache.db")) + try database.enqueueQueuedJobs([QueuedCopyJob( + sourcePath: "/Volumes/Other/IMG_1.jpg", + destinationPath: unrelated.destination.appendingPathComponent("x.jpg").path, + hash: FileIdentity(size: 1, digest: "z").rawValue, + status: .pending + )]) + database.close() + // A reachable destination with no copy queue has nothing to resume. + let emptyDestination = makeTempParent() + try FileManager.default.createDirectory(at: emptyDestination, withIntermediateDirectories: true) + let noQueue = try seedCheckpoint( + parent: parent, name: "no-queue", state: .ready, assetIDs: ["a"], + updatedAt: fixedDate(20), destinationPath: emptyDestination.path + ) + + makeStore(ids: ["a"], exporter: ScriptedExporter(), staging: parent) + .refreshResumableImport(destination: capture(unrelated.destination)) + + XCTAssertFalse(exists(unrelated.staging.path)) + XCTAssertFalse(exists(noQueue.path)) + } + + @MainActor + func testStagingIsKeptWhileTheDestinationCannotBeChecked() throws { + let parent = makeTempParent() + let now = Date(timeIntervalSince1970: 1_700_000_000) + // The destination is an unmounted volume: its absence proves nothing. + let unmounted = try seedCheckpoint( + parent: parent, name: "unmounted", state: .ready, assetIDs: ["a"], + updatedAt: now.addingTimeInterval(-86_400), destinationPath: "/Volumes/PIR-not-mounted/Photos" + ) + // The destination is reachable but its queue cannot be read. + let unreadableDestination = makeTempParent() + try FileManager.default.createDirectory(at: unreadableDestination, withIntermediateDirectories: true) + try Data("this is not a database".utf8).write(to: unreadableDestination.appendingPathComponent(".organize_cache.db")) + let unreadable = try seedCheckpoint( + parent: parent, name: "unreadable", state: .ready, assetIDs: ["a"], + updatedAt: now.addingTimeInterval(-86_400), destinationPath: unreadableDestination.path + ) + + makeStore(ids: ["a"], exporter: ScriptedExporter(), staging: parent).refreshResumableImport(destination: nil) + + XCTAssertTrue(exists(unmounted.path), "Never infer that an unreachable destination has nothing pending") + XCTAssertTrue(exists(unreadable.path), "Never infer that an unreadable queue has nothing pending") + } + + @MainActor + func testUncheckableStagingIsEventuallyCleanedUp() throws { + let parent = makeTempParent() + let now = Date(timeIntervalSince1970: 1_700_000_000) + let abandoned = try seedCheckpoint( + parent: parent, name: "abandoned", state: .ready, assetIDs: ["a"], + updatedAt: now.addingTimeInterval(-86_400 * 31), destinationPath: "/Volumes/PIR-not-mounted/Photos" + ) + + makeStore(ids: ["a"], exporter: ScriptedExporter(), staging: parent).refreshResumableImport(destination: nil) + + XCTAssertFalse(exists(abandoned.path), "Staging nobody can prove is needed does not stay for ever") + } + // AGENTS-INVARIANT: 22 @MainActor func testCheckpointSaveFailureStopsTheExportInsteadOfContinuing() async throws { diff --git a/ui/Tests/ChronoframeAppTests/DeduplicateReviewViewsTests.swift b/ui/Tests/ChronoframeAppTests/DeduplicateReviewViewsTests.swift index 96dfe6fa..3cea3b84 100644 --- a/ui/Tests/ChronoframeAppTests/DeduplicateReviewViewsTests.swift +++ b/ui/Tests/ChronoframeAppTests/DeduplicateReviewViewsTests.swift @@ -308,6 +308,54 @@ final class DeduplicateReviewViewsTests: XCTestCase { XCTAssertEqual(AccessibilityIdentifiers.quickReviewAcceptRest, "quickReview.acceptRest") } + /// "Accept the Rest" is the groups from the person's position on. A group they skipped + /// earlier stays unreviewed, and the count on the button is exactly what it accepts. + func testAcceptTheRestLeavesSkippedGroupsAloneAndCountMatches() async throws { + let first = laneCluster("first", lane: .nearlyIdentical) + let skipped = laneCluster("skipped", lane: .nearlyIdentical) + let third = laneCluster("third", lane: .nearlyIdentical) + let fourth = laneCluster("fourth", lane: .nearlyIdentical) + let store = try await scannedStore([first, skipped, third, fourth]) + let walk = QuickReviewScope.clusters( + in: .nearlyIdentical, + from: store.clusters, + reviewedIDs: store.approvedClusterIDs, + laneOf: store.lane(for:) + ) + XCTAssertEqual(walk.map(\.id), [first.id, skipped.id, third.id, fourth.id]) + + // Accept the first group, skip the second, then stop on the third. + store.acceptSuggestionsForCluster(first) + let currentIndex = 2 + let rest = QuickReviewScope.restClusters(from: walk, currentIndex: currentIndex, reviewedIDs: store.approvedClusterIDs) + XCTAssertEqual(rest.map(\.id), [third.id, fourth.id]) + XCTAssertEqual( + QuickReviewScope.acceptTheRestCount(lane: .nearlyIdentical, currentIndex: currentIndex, remainingInLane: rest.count), + 2 + ) + + store.acceptSuggestions(forClusters: rest) + + XCTAssertEqual(store.approvedClusterIDs, [first.id, third.id, fourth.id], "The skipped group is not accepted") + XCTAssertFalse(store.approvedClusterIDs.contains(skipped.id)) + XCTAssertEqual(store.laneSummaries[.nearlyIdentical]?.groups, 1, "The skipped group is still waiting for review") + } + + func testAcceptTheRestLeavesOutGroupsReviewedSinceTheWalkStarted() async throws { + let one = laneCluster("one", lane: .nearlyIdentical) + let two = laneCluster("two", lane: .nearlyIdentical) + let three = laneCluster("three", lane: .nearlyIdentical) + let store = try await scannedStore([one, two, three]) + store.acceptSuggestionsForCluster(three) + let rest = QuickReviewScope.restClusters( + from: [one, two, three], + currentIndex: 1, + reviewedIDs: store.approvedClusterIDs + ) + XCTAssertEqual(rest.map(\.id), [two.id]) + XCTAssertTrue(QuickReviewScope.restClusters(from: [one, two, three], currentIndex: 3, reviewedIDs: []).isEmpty) + } + func testFullyMarkedNoticeText() { XCTAssertNil(DeduplicateFooterCopy.fullyMarkedNotice(groupCount: 0)) XCTAssertEqual( diff --git a/ui/Tests/ChronoframeAppTests/OrganizeFolderIntentConfigurationTests.swift b/ui/Tests/ChronoframeAppTests/OrganizeFolderIntentConfigurationTests.swift index ea4e54ac..d20232a5 100644 --- a/ui/Tests/ChronoframeAppTests/OrganizeFolderIntentConfigurationTests.swift +++ b/ui/Tests/ChronoframeAppTests/OrganizeFolderIntentConfigurationTests.swift @@ -61,8 +61,8 @@ final class OrganizeFolderIntentConfigurationTests: XCTestCase { XCTAssertEqual(configuration().folderStructure, .yyyyMMDD) } - /// Everything but the layout is what the intent shipped with. - func testTheRestOfTheConfigurationIsUnchanged() { + /// With nothing stored, the stored-preference defaults match what the intent shipped with. + func testDefaultsMatchWhatTheIntentShippedWith() { let config = configuration() XCTAssertEqual(config.mode, .transfer) @@ -73,4 +73,29 @@ final class OrganizeFolderIntentConfigurationTests: XCTestCase { XCTAssertTrue(config.parallelTransferEnabled) XCTAssertEqual(config.workerCount, 8) } + + func testStoredVerifyCopiesOffIsHonored() { + defaults.set(false, forKey: "verifyCopies") + + XCTAssertFalse(configuration().verifyCopies) + } + + func testStoredWorkerCountIsHonored() { + defaults.set(3, forKey: "workerCount") + + XCTAssertEqual(configuration().workerCount, 3) + } + + /// The app's own run path never hands the engine fewer than one worker. + func testStoredWorkerCountIsClampedToAtLeastOne() { + defaults.set(0, forKey: "workerCount") + + XCTAssertEqual(configuration().workerCount, 1) + } + + func testStoredParallelTransferOffIsHonored() { + defaults.set(false, forKey: "parallelTransferEnabled") + + XCTAssertFalse(configuration().parallelTransferEnabled) + } }