Reconcile starter seeds on connect and add restore + duplicate cleanup

Seeding now covers existing installs, not just empty containers: after the
same settle delay as auto-seed, connect() branches to reconcileSeeds(),
driven by a pure tested planner — upgrade an older seed revision in place
(safe: clone-on-edit guarantees no user content at seed ULIDs), skip
up-to-date/quarantined files, respect delete-veto stubs, and write missing
seeds unless a same-name legacy split exists. Settings gains Restore
Starter Splits (the one deliberate veto lift, writing current bundle
bytes) and a dev duplicate-cleanup tool backed by a fail-closed scanner.
The HealthKit estimate now follows the clone redirect when resolving a
workout's split.

Claude-Session: https://claude.ai/code/session_01LEoff8bXGBS83tK1c55Mf7
This commit is contained in:
2026-07-06 16:29:59 -04:00
parent 2c1e4759ae
commit 7586edd878
10 changed files with 1344 additions and 152 deletions
@@ -0,0 +1,198 @@
import Foundation
import Testing
@testable import Workouts
/// Locks the survivor rules of `DuplicateCleanupPlanner` the safety-critical
/// part of the developer duplicate-cleanup tool. Referenced-split and seed
/// protection must always beat "earliest ULID wins," an in-progress workout must
/// never be touched, and the HealthKit-link holder must always survive (deleting
/// it would cascade-delete the real Health sample). Fixed 26-char ULID-like ids
/// keep every assertion deterministic.
struct DuplicateCleanupPlannerTests {
// MARK: - Fixtures
private func id(_ n: Int) -> String {
"01TESTID" + String(repeating: "0", count: 16) + String(format: "%02d", n)
}
private func exercise(
name: String = "Bench Press", order: Int = 0, sets: Int = 3, reps: Int = 10,
weight: Int = 100, loadType: Int = LoadType.weight.rawValue, duration: Int = 0
) -> ExerciseDocument {
ExerciseDocument(
id: "EX-\(name)-\(order)", name: name, order: order, sets: sets, reps: reps, weight: weight,
loadType: loadType, durationSeconds: duration
)
}
private func split(
id splitID: String, name: String = "Push Day", exercises: [ExerciseDocument]? = nil,
createdAt: Date = Date(timeIntervalSince1970: 0)
) -> SplitDocument {
SplitDocument(
schemaVersion: SplitDocument.currentSchemaVersion, id: splitID, name: name, color: "indigo",
systemImage: "dumbbell.fill", order: 0, createdAt: createdAt, updatedAt: createdAt,
exercises: exercises ?? [exercise()], activityType: nil
)
}
private func log(name: String = "Bench Press", order: Int = 0, date: Date = Date(timeIntervalSince1970: 0)) -> WorkoutLogDocument {
WorkoutLogDocument(
id: "LOG-\(name)-\(order)", exerciseName: name, order: order, sets: 3, reps: 10, weight: 100,
loadType: LoadType.weight.rawValue, durationSeconds: 0, currentStateIndex: 0,
status: WorkoutStatus.completed.rawValue, notes: nil, date: date
)
}
private func workout(
id workoutID: String, splitID: String? = "SPLIT-1", splitName: String? = "Push Day",
start: Date, status: String = WorkoutStatus.completed.rawValue,
logs: [WorkoutLogDocument]? = nil, metrics: WorkoutMetrics? = nil
) -> WorkoutDocument {
WorkoutDocument(
schemaVersion: WorkoutDocument.currentSchemaVersion, id: workoutID, splitID: splitID,
splitName: splitName, start: start, end: nil, status: status, createdAt: start, updatedAt: start,
logs: logs ?? [log(date: start)], metrics: metrics
)
}
/// A fixed calendar day/time built via `Calendar.current`, so it agrees with
/// the planner's own `Calendar.current`-based day bucketing regardless of the
/// test runner's time zone.
private func fixedDate(day: Int = 15, hour: Int = 9) -> Date {
var comps = DateComponents()
comps.year = 2024
comps.month = 3
comps.day = day
comps.hour = hour
return Calendar.current.date(from: comps)!
}
private func metrics(healthKitWorkoutUUID: String? = nil, recordedAt: Date = Date(timeIntervalSince1970: 0)) -> WorkoutMetrics {
WorkoutMetrics(
activeEnergyKcal: nil, avgHeartRate: nil, maxHeartRate: nil, minHeartRate: nil,
totalVolume: nil, hrZoneSeconds: nil, healthKitWorkoutUUID: healthKitWorkoutUUID,
source: .watch, recordedAt: recordedAt
)
}
// MARK: - Split survivor rules
@Test func identicalUnreferencedSplitsKeepEarliestULID() {
let earlier = split(id: id(1))
let later = split(id: id(2))
let plan = DuplicateCleanupPlanner.plan(
splits: [later, earlier], workouts: [], referencedSplitIDs: [], isSeed: { _ in false }
)
#expect(plan.splitGroups.count == 1)
#expect(plan.splitGroups[0].keep.map(\.id) == [id(1)])
#expect(plan.splitGroups[0].delete.map(\.id) == [id(2)])
}
/// Referenced-protection must override "earliest ULID wins": a later,
/// referenced split survives and the earlier, unreferenced duplicate is the
/// one deleted the opposite of the no-protection tiebreak.
@Test func referencedProtectionOverridesEarliestWins() {
let earlier = split(id: id(1)) // unreferenced, would win the earliest-id tiebreak alone
let later = split(id: id(2)) // referenced by a workout
let plan = DuplicateCleanupPlanner.plan(
splits: [earlier, later], workouts: [], referencedSplitIDs: [id(2)], isSeed: { _ in false }
)
#expect(plan.splitGroups.count == 1)
#expect(plan.splitGroups[0].keep.map(\.id) == [id(2)])
#expect(plan.splitGroups[0].delete.map(\.id) == [id(1)])
}
@Test func seedMemberNeverDeleted() throws {
let seedSplit = split(id: id(1))
let duplicate = split(id: id(2))
let plan = DuplicateCleanupPlanner.plan(
splits: [seedSplit, duplicate], workouts: [], referencedSplitIDs: [],
isSeed: { $0 == id(1) }
)
let group = try #require(plan.splitGroups.first)
#expect(group.keep.map(\.id) == [id(1)])
#expect(group.delete.map(\.id) == [id(2)])
#expect(!group.delete.contains { $0.id == id(1) })
}
@Test func differingExerciseContentNotGrouped() {
let a = split(id: id(1), exercises: [exercise(weight: 100)])
let b = split(id: id(2), exercises: [exercise(weight: 105)])
let plan = DuplicateCleanupPlanner.plan(
splits: [a, b], workouts: [], referencedSplitIDs: [], isSeed: { _ in false }
)
#expect(plan.splitGroups.isEmpty)
}
/// Machine comfort settings are real content: splits identical except for a
/// setting value or for the nil (non-machine) vs. empty (machine, nothing
/// recorded) distinction must not be judged duplicates.
@Test func differingMachineSettingsNotGrouped() {
var lowSeat = exercise()
lowSeat.machineSettings = [MachineSetting(name: "Seat Height", value: "4")]
var highSeat = exercise()
highSeat.machineSettings = [MachineSetting(name: "Seat Height", value: "5")]
var machineNothingRecorded = exercise()
machineNothingRecorded.machineSettings = []
let a = split(id: id(1), exercises: [lowSeat])
let b = split(id: id(2), exercises: [highSeat])
let c = split(id: id(3), exercises: [machineNothingRecorded])
let d = split(id: id(4)) // machineSettings nil not a machine exercise
let plan = DuplicateCleanupPlanner.plan(
splits: [a, b, c, d], workouts: [], referencedSplitIDs: [], isSeed: { _ in false }
)
#expect(plan.splitGroups.isEmpty)
}
// MARK: - Workout grouping / survivor rules
@Test func sameDayWorkoutsDifferingOnlyInIDsAndTimestampsAreGrouped() {
let day = fixedDate(hour: 9)
let sameDayLater = fixedDate(hour: 20)
let w1 = workout(id: id(1), start: day)
let w2 = workout(id: id(2), start: sameDayLater)
let plan = DuplicateCleanupPlanner.plan(
splits: [], workouts: [w1, w2], referencedSplitIDs: [], isSeed: { _ in false }
)
#expect(plan.workoutGroups.count == 1)
#expect(plan.workoutGroups[0].keep.id == id(1))
#expect(plan.workoutGroups[0].delete.map(\.id) == [id(2)])
}
@Test func differentDaysNotGrouped() {
let w1 = workout(id: id(1), start: fixedDate(day: 15))
let w2 = workout(id: id(2), start: fixedDate(day: 16))
let plan = DuplicateCleanupPlanner.plan(
splits: [], workouts: [w1, w2], referencedSplitIDs: [], isSeed: { _ in false }
)
#expect(plan.workoutGroups.isEmpty)
}
@Test func inProgressMemberDropsEntireGroup() {
let start = fixedDate()
let w1 = workout(id: id(1), start: start, status: WorkoutStatus.inProgress.rawValue)
let w2 = workout(id: id(2), start: start, status: WorkoutStatus.inProgress.rawValue)
let plan = DuplicateCleanupPlanner.plan(
splits: [], workouts: [w1, w2], referencedSplitIDs: [], isSeed: { _ in false }
)
#expect(plan.workoutGroups.isEmpty)
}
/// The HealthKit-link holder must survive even though the other copy has the
/// lexicographically smaller (earlier) id deleting the link holder would
/// cascade-delete the real Health sample.
@Test func healthKitLinkHolderSurvivesOverEarlierULID() throws {
let start = fixedDate()
let earlierNoLink = workout(id: id(1), start: start, metrics: nil)
let laterWithLink = workout(id: id(2), start: start, metrics: metrics(healthKitWorkoutUUID: "HK-UUID"))
let plan = DuplicateCleanupPlanner.plan(
splits: [], workouts: [earlierNoLink, laterWithLink], referencedSplitIDs: [], isSeed: { _ in false }
)
let group = try #require(plan.workoutGroups.first)
#expect(group.keep.id == id(2))
#expect(group.delete.map(\.id) == [id(1)])
}
}
@@ -0,0 +1,137 @@
import Foundation
import Testing
import IndieSync
@testable import Workouts
/// Locks the decision table of `SeedReconcilePlanner` the safety-critical logic that
/// upgrades stale starter-seed revisions and adds newly-shipped seeds on an existing
/// install without ever duplicating a user's split, resurrecting a deleted seed, or
/// downgrade-rewriting a newer app version's file. All fixtures are plain structs so
/// every assertion is a pure, deterministic function of the inputs.
struct SeedReconcilePlannerTests {
// MARK: - Fixtures
private func exercise(
name: String, order: Int = 0, sets: Int = 3, reps: Int = 10, weight: Int = 100
) -> ExerciseDocument {
ExerciseDocument(
id: "EX-\(name)-\(order)", name: name, order: order, sets: sets, reps: reps,
weight: weight, loadType: LoadType.weight.rawValue, durationSeconds: 0
)
}
/// A seed-shaped split at the current schema version, with a fixed frozen date so
/// two builds of "the same" content compare equal.
private func seed(
id: String = "01DXF6DT0038BDC2WC3EVX8ZJ5",
name: String = "Upper Body",
schemaVersion: Int = SplitDocument.currentSchemaVersion,
exercises: [ExerciseDocument]? = nil
) -> SplitDocument {
SplitDocument(
schemaVersion: schemaVersion, id: id, name: name, color: "indigo",
systemImage: "dumbbell.fill", order: 0,
createdAt: Date(timeIntervalSince1970: 0), updatedAt: Date(timeIntervalSince1970: 0),
exercises: exercises ?? [exercise(name: "Bench Press")], activityType: nil
)
}
// MARK: - Live file present
/// An older app version wrote this seed at schemaVersion 1 (and, on disk, carried
/// extra now-removed keys which decode into the current struct as simply absent).
/// The content is otherwise identical, so normalizing the version stamp must make it
/// read as up to date: no churn, no rewrite.
@Test func semanticEqualitySkipsAcrossSchemaVersions() {
let bundle = seed() // current schemaVersion
var live = bundle
live.schemaVersion = 1 // older wrapper, same content
let input = SeedReconcileInput(seedID: bundle.id, seedDoc: bundle, liveDoc: live, hasStub: false)
#expect(SeedReconcilePlanner.decision(for: input, liveSplitNames: []) == .skip(.upToDate))
}
/// The bundle seed gained an exercise since this install wrote its file a real
/// content change must upgrade (overwrite with current bundle bytes), even though
/// the live file is a lower schema version.
@Test func contentChangeUpgrades() {
let bundle = seed(exercises: [exercise(name: "Bench Press"), exercise(name: "Overhead Press", order: 1)])
var live = seed(exercises: [exercise(name: "Bench Press")]) // one fewer exercise
live.schemaVersion = 1
let input = SeedReconcileInput(seedID: bundle.id, seedDoc: bundle, liveDoc: live, hasStub: false)
#expect(SeedReconcilePlanner.decision(for: input, liveSplitNames: []) == .upgrade)
}
/// A weight tweak alone is enough of a content change to upgrade.
@Test func exerciseWeightChangeUpgrades() {
let bundle = seed(exercises: [exercise(name: "Bench Press", weight: 135)])
let live = seed(exercises: [exercise(name: "Bench Press", weight: 115)])
let input = SeedReconcileInput(seedID: bundle.id, seedDoc: bundle, liveDoc: live, hasStub: false)
#expect(SeedReconcilePlanner.decision(for: input, liveSplitNames: []) == .upgrade)
}
/// A live file written by a NEWER app version (schemaVersion above current) is
/// quarantined never downgrade-rewrite it, even though it differs.
@Test func newerSchemaFileIsQuarantined() {
let bundle = seed()
var live = seed(exercises: [exercise(name: "Something New")])
live.schemaVersion = SplitDocument.currentSchemaVersion + 1
#expect(!live.isReadable) // guards the premise
let input = SeedReconcileInput(seedID: bundle.id, seedDoc: bundle, liveDoc: live, hasStub: false)
#expect(SeedReconcilePlanner.decision(for: input, liveSplitNames: []) == .skip(.quarantined))
}
// MARK: - No live file
/// No live file but a stub exists the user deleted this seed. The veto stands.
@Test func stubVetoesResurrection() {
let bundle = seed()
let input = SeedReconcileInput(seedID: bundle.id, seedDoc: bundle, liveDoc: nil, hasStub: true)
#expect(SeedReconcilePlanner.decision(for: input, liveSplitNames: []) == .skip(.vetoed))
}
/// No live file, no stub, but a live split (a legacy runtime-built or user-cloned
/// "Upper Body") already uses the seed's name writing it would duplicate by name.
@Test func nameCollisionSkips() {
let bundle = seed(name: "Upper Body")
let input = SeedReconcileInput(seedID: bundle.id, seedDoc: bundle, liveDoc: nil, hasStub: false)
#expect(SeedReconcilePlanner.decision(for: input, liveSplitNames: ["Upper Body", "Core"]) == .skip(.nameCollision))
}
/// No live file, no stub, no same-name split a genuinely missing seed (newly
/// shipped, or a pre-fixed-ULID install) gets written.
@Test func missingSeedIsWritten() {
let bundle = seed(name: "Bodyweight Core")
let input = SeedReconcileInput(seedID: bundle.id, seedDoc: bundle, liveDoc: nil, hasStub: false)
#expect(SeedReconcilePlanner.decision(for: input, liveSplitNames: ["Upper Body", "Core"]) == .write)
}
/// A stub present but the same name also live: the veto is checked first, so it
/// still skips (as vetoed) rather than as a name collision either way, no write.
@Test func stubTakesPrecedenceOverNameCollision() {
let bundle = seed(name: "Upper Body")
let input = SeedReconcileInput(seedID: bundle.id, seedDoc: bundle, liveDoc: nil, hasStub: true)
#expect(SeedReconcilePlanner.decision(for: input, liveSplitNames: ["Upper Body"]) == .skip(.vetoed))
}
// MARK: - Restore
/// Restore rewrites only a seed that is both absent and free of a name collision;
/// the presence of a veto stub is irrelevant (restore lifts it).
@Test func shouldRestoreOnlyWhenAbsentAndNameFree() {
// Absent, name free restore (whether or not a stub exists).
#expect(SeedReconcilePlanner.shouldRestore(hasLiveFile: false, seedName: "Upper Body", liveSplitNames: []))
// Live file already present reconcile handles any upgrade; restore leaves it.
#expect(!SeedReconcilePlanner.shouldRestore(hasLiveFile: true, seedName: "Upper Body", liveSplitNames: []))
// A live same-name split exists don't duplicate it.
#expect(!SeedReconcilePlanner.shouldRestore(hasLiveFile: false, seedName: "Upper Body", liveSplitNames: ["Upper Body"]))
}
}