Skip to content

refactor(macOS): centralize Rewind repository plumbing - #15376

Merged
Git-on-my-level merged 20 commits into
BasedHardware:mainfrom
aryanorastar:refactor/9519-rewind-storage-base
Oct 5, 2026
Merged

Git-on-my-level merged 20 commits into
BasedHardware:mainfrom
aryanorastar:refactor/9519-rewind-storage-base

Conversation

@aryanorastar

@aryanorastar aryanorastar commented Sep 21, 2026 •

Copy link
Copy Markdown
Collaborator

What changed and why

Closes #9519.

Rewind-backed macOS services independently cached DatabasePool references and repeated the same pool-generation/reopen logic. That made user switches and local-database recovery depend on every storage owner implementing an identical lifecycle correctly.

This PR introduces one RewindRepository actor that owns pool acquisition, generation revalidation, invalidation, and recovery. It migrates all 11 discovered consumers one storage at a time:

  • action items
  • transcriptions
  • memories
  • goals
  • staged tasks
  • proactive state
  • task chat
  • live notes
  • knowledge graph
  • AI user profile
  • file indexing

It also moves action-item FTS recovery out of RewindDatabase into a parameterized external-content FTS definition. Durable source rows remain authoritative, repair is performed against the exact failing pool, and the File Indexer test-injected pool behavior is preserved.

There is no schema or user-visible behavior change. The desktop changelog entry is intentionally {"kind":"none"}.

Product invariants affected

  • INV-AUTH-1
  • INV-CHAT-1
  • INV-MEM-1
  • INV-TASK-1

The refactor preserves these contracts while consolidating the local storage lifecycle behind one replaceable-pool owner.

How it was verified

  • Clean debug build passed.
  • Focused repository, FTS repair, and artifact-recovery suite: 7/7 passed.
  • Storage regression selection covering database lifecycle, transcription recovery, sign-out invalidation, file indexing/retention, user-profile row IDs, staged-task sync, action-item reconciliation, memory identities, and legacy task chat: 45/45 passed.
  • Cross-surface agent contract smoke passed.
  • Full desktop suite executed 885 tests: 884 passed. The sole failure is an unrelated, unchanged floating-bar AppKit sizing assertion (197.5 >= 198.0); it reproduces when run independently and no floating-bar source or test is changed by this PR.
  • Full SwiftLint passed with 0 violations; changed Swift files pass pinned swift-format lint; desktop test-quality and diff-hygiene checks pass.
  • The new repository-ownership check and its fail/pass self-test both pass through the shared checks manifest.

Named-bundle smoke was run from clean revision 237486e327 using bundle com.omi.omi-9519-rewind-repo; the committed rewind-artifact-recovery bridge flow passed in 398 ms with zero log errors. The non-production recovery gauntlet proved:

  • a protected synthetic frame was rejected before persistence (0 protected rows);
  • two admitted frames persisted and read back in red/green order;
  • the database closed and reopened, with both rows surviving;
  • repositories primed before the close successfully read action items and legacy task chat after the pool generation changed;
  • the two fixture rows and video artifact were removed afterward.

Tests

  • RewindRepositoryTests covers generation revalidation, explicit invalidation, failed reopen without stale-pool fallback, injected-pool isolation, and generic FTS repair.
  • RewindArtifactGauntletTests covers the real encoder → SQLite → video-readback → close/reopen path, including post-reopen action-item and task-chat reads.
  • ActionItemsFTSRepairTests now exercises the generic FTS definition and verifies durable action-item rows survive index reconstruction.
  • check-rewind-repository-ownership.py --self-test proves copied private pool/generation caches are rejected while repository-owned storage passes.

Failure class (fixes)

Failure-Class: none

New guards (only when adding a check or ratchet)

The duplicated ownership documented in #9519 is the incident this guard would have caught. The prevention is the shared RewindRepository primitive; the structural check only prevents future storage owners from bypassing it with private _dbQueue or generation caches.

Scoped cleanups

Removed the action-items-specific FTS classifier/install/repair/drop plumbing from RewindDatabase, leaving schema migration and pool ownership there while the reusable repair behavior lives with the repository abstraction.

Review in cubic

@Git-on-my-level

Copy link
Copy Markdown
Member

Verified end-to-end against #9519 — this is a clean, well-evidenced consolidation. Thank you for the per-storage commit split, the honest local-test report, and the changelog restraint.

What I checked:

  • RewindRepository.swift — the new actor centralizes exactly the lifecycle the issue called out (pool acquisition, generation revalidation, invalidation, reopen). Injected-pool semantics (cachedGeneration == nil) preserve FileIndexerService's test-injection behavior, and clearing the cache before a reopen attempt means a failed reopen can never hand back a stale pool — a strict improvement over the old copies, proven by testGenerationChangeNeverFallsBackToStalePoolWhenReopenFails.
  • RewindDatabase.swift + RewindFTSDefinition — the removed isActionItemsFTSError/repairActionItemsFTS block is faithfully reproduced with the virtual table parameterized. I diffed the generated DDL for .actionItems against the deleted installActionItemsFTS: identical FTS5 external-content definition, triggers, and shadow-table fallback list. The precondition-gated identifier validation keeps the SQL interpolation safe; only code-owned constants reach it today.
  • All ten storage migrations (ActionItemStorage, TranscriptionStorage, MemoryStorage, GoalStorage, ProactiveStorage, StagedTaskStorage, TaskChatMessageStorage, NoteStorage, KnowledgeGraphStorage, AIUserProfileService) keep their per-domain error types and lazy-init semantics; invalidateCache() becoming async is source-compatible across the actor boundary. Code search confirms no private var _dbQueue/_dbGeneration copies remain under Desktop/Sources (RewindStorage itself never held a pool, so the "11 consumers" count is accurate).
  • RewindArtifactGauntlet.swift / RewindArtifactGauntletTests.swift / e2e/flows/rewind-artifact-recovery.yaml — the gauntlet now primes two repositories before the close/reopen and asserts reads succeed after, directly exercising the recovery path this refactor exists to protect.
  • RewindRepositoryTests.swift — good harness design (injectable RewindDatabasePoolSource); covers generation change, explicit invalidation, failed reopen, injected pools, and the parameterized FTS repair including the narrow error classifier.
  • desktop/macos/scripts/check-rewind-repository-ownership.py + .github/checks-manifest.yaml — I ran the self-test locally and confirmed it rejects a copied _dbQueue/_dbGeneration pair while accepting repository-owned storage; CI logs show both new manifest checks were selected and passed in the Hygiene job on this head.
  • desktop/macos/changelog/unreleased/20260921-rewind-repository-consolidation.json — kind: "none" is right for a no-user-visible-change refactor.

Two nits, neither blocking:

  1. AIUserProfileService uses the owner string "AIUserStorage" while every other owner matches its type name — worth aligning for log greppability.
  2. The ownership guard scans all of Desktop/Sources/**/*.swift for private var _dbQueue, so a future non-Rewind actor that legitimately owns a differently-scoped pool under that name will trip it. Fine as an intentional fence — just something to remember when it fires.

Leaving for human maintainer review rather than an automated verdict: this reshapes the local-storage lifecycle for 11 actors behind one shared owner and adds a repo-wide CI guard that will reject future PRs reintroducing private pool caches, so the consolidation and the new enforcement both deserve a maintainer's explicit sign-off before merge.

🤖 Automated review on behalf of the maintainers.


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

@Git-on-my-level Git-on-my-level added positive-signal Automation verified a genuine fix/quality contribution needs-maintainer-review Needs a human maintainer to sign off before merge macOS labels Sep 21, 2026
…storage-base

# Conflicts:
#	.github/checks-manifest.yaml
@aryanorastar

Copy link
Copy Markdown
Collaborator Author

Conflict resolved, and the owner-string nit from your review is fixed in its own commit.

The conflict, and why it keeps happening. .github/checks-manifest.yaml was the only file, and it was positional rather than a disagreement: main added openfoodfacts-robustness-and-coercion-tests at the very top of checks:, which is exactly where this branch's two rewind-repository-ownership entries sit. Resolved as the union — but I also moved our two entries out of the list head into the desktop-check region, beside desktop-e2e-flow-coverage. Order carries no meaning in this file (run_checks.py resolves by id and rejects duplicates), and sitting where main appends means conflicting with every new check for as long as the branch is open.

Verified by parsing rather than by eye, since a manifest that looks merged while having silently dropped an entry is the failure this file cannot afford: 279 entries against main's 277, the two added are this PR's, none dropped, no duplicate ids.

The guard still holds on the merged head: check-rewind-repository-ownership.py PASS, its --self-test PASS, and test_run_checks.py 53 passed — so both manifest entries still execute through the shared runner after the move.

Your first nit I tried to fix and then reverted — the rename is blocked by another guard. AIUserProfileService does construct RewindRepository(owner: "AIUserStorage") while every other owner string matches its type, and you are right that it costs log greppability. But legacy-memory-surface-ratchet counts the regex ai_user_profile|AIUserProfile|synthesize_ai_user_profile|formatAIProfileSection against that exact file, so spelling the owner "AIUserProfileService" adds a counted occurrence and the shrink-only ratchet rejects it:

growth:
  ...AIUserProfileService.swift: 47 -> 48

Any spelling that matches the type name matches that regex, so there is no version of this rename that passes while the Gate F baseline stands. Reverted; the file keeps "AIUserStorage". Worth recording on the issue rather than in this PR: the string is misleading today precisely because a retirement ratchet makes the accurate name more expensive than the inaccurate one.

Your second nit I deliberately left alone. The ownership guard scanning all of Desktop/Sources/**/*.swift for private var _dbQueue is the fence this PR exists to install, and narrowing it pre-emptively for a hypothetical non-Rewind pool owner would weaken it before anything has actually tripped. Your note is the right place for that to be recorded, and whoever hits it will have the context.

Scope is unchanged at 21 files, +608/−361, desktop/macOS and the manifest only — no behaviour change from the merge.

@aryanorastar

Copy link
Copy Markdown
Collaborator Author

Refreshed against current main on df2dc6c05d — 263 commits, merged clean with zero conflicts.

Same reasoning as the sibling desktop PRs: the checks on b0b26cabea were measured against a base 263 commits old.

Verified on the merged head:

check result
swift build Build complete (81.88s), no errors
check-rewind-repository-ownership.py PASS
check-rewind-repository-ownership.py --self-test PASS
.github/scripts/test_run_checks.py 56 passed, 10 subtests
legacy_memory_surface_inventory rc=0
.github/checks-manifest.yaml parsed 299 entries vs main's 297, 0 duplicates, exactly this PR's two added, none dropped

Diff scope unchanged at 21 files, desktop/ and .github/ only. No conflicts, so no resolution decisions were taken.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot review overview

🟡 Changes recommended

The recovery gauntlet needs stronger assertions proving action-item and task-chat continuity after reopening.

Review effort: Lite
Findings: 1 Medium severity

Open (1)
What changed in this PR

Refactors macOS Rewind storage to centralize database-pool lifecycle and FTS repair in RewindRepository.

Changes:

  • Migrates storage consumers to shared repository ownership.
  • Adds lifecycle, recovery, FTS, and ownership-check coverage.
  • Preserves injected-pool behavior and records no user-facing change.
File Reviewed change
desktop/​macos/​scripts/​check-rewind-repository-ownership.py Adds repository ownership guard.
desktop/​macos/​e2e/​flows/​rewind-artifact-recovery.yaml Extends recovery-flow coverage.
desktop/​macos/​Desktop/​Tests/​RewindRepositoryTests.swift Tests repository lifecycle and FTS repair.
desktop/​macos/​Desktop/​Tests/​RewindArtifactGauntletTests.swift Tests artifact recovery behavior.
desktop/​macos/​Desktop/​Tests/​ActionItemsFTSRepairTests.swift Tests generic FTS repair.
desktop/​macos/​Desktop/​Sources/​Rewind/​Core/​TranscriptionStorage.swift Migrates transcription storage ownership.
desktop/​macos/​Desktop/​Sources/​Rewind/​Core/​TaskChatMessageStorage.swift Migrates task-chat storage ownership.
desktop/​macos/​Desktop/​Sources/​Rewind/​Core/​StagedTaskStorage.swift Migrates staged-task storage ownership.
desktop/​macos/​Desktop/​Sources/​Rewind/​Core/​RewindRepository.swift Adds shared pool lifecycle and FTS repair.
desktop/​macos/​Desktop/​Sources/​Rewind/​Core/​RewindDatabase.swift Removes domain-specific FTS plumbing.
desktop/​macos/​Desktop/​Sources/​Rewind/​Core/​RewindArtifactGauntlet.swift Exercises post-reopen repository reads.
desktop/​macos/​Desktop/​Sources/​Rewind/​Core/​ProactiveStorage.swift Migrates proactive storage ownership.
desktop/​macos/​Desktop/​Sources/​Rewind/​Core/​MemoryStorage.swift Migrates memory storage ownership.
desktop/​macos/​Desktop/​Sources/​Rewind/​Core/​GoalStorage.swift Migrates goal storage ownership.
desktop/​macos/​Desktop/​Sources/​Rewind/​Core/​ActionItemStorage.swift Migrates action-item storage and FTS handling.
desktop/​macos/​Desktop/​Sources/​ProactiveAssistants/​Services/​AIUserProfileService.swift Migrates profile persistence ownership.
desktop/​macos/​Desktop/​Sources/​LiveNotes/​NoteStorage.swift Migrates note storage ownership.
desktop/​macos/​Desktop/​Sources/​FileIndexing/​KnowledgeGraphStorage.swift Migrates graph storage ownership.
desktop/​macos/​Desktop/​Sources/​FileIndexing/​FileIndexerService.swift Preserves injected-pool behavior.
desktop/​macos/​changelog/​unreleased/​20260921-rewind-repository-consolidation.json Records no user-facing change.
.github/​checks-manifest.yaml Registers ownership checks.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

@aryanorastar

Copy link
Copy Markdown
Collaborator Author

Refreshed against current main on 7e5be31e5c — merged clean, no conflicts, so no resolution decisions were taken and the diff is unchanged (21 files, desktop/ + .github/).

Verified on the merged head: swift build complete (99.99s); check-rewind-repository-ownership PASS; --self-test PASS.

…tlet reopen

The reopen step only proved the action-item and task-chat reads did not
throw, so a stale pool returning an empty result still reported both as
readable. Seed one action item and one task-chat row before the close,
read them back by ID and content on both sides of the reopen, and remove
them on success and failure. The action item is stored soft-deleted with
no backend ID so task lists and backend sync never pick it up.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@aryanorastar

Copy link
Copy Markdown
Collaborator Author

Pushed 6fa8cb6: the Rewind gauntlet now checks that real rows survive the database reopen, not just that the reads don't throw.

  • Before the close it seeds one action item and one task-chat row tagged with the run's nonce. Both are read back through ActionItemStorage (by ID and description) and TaskChatMessageStorage (by message ID) before the close and again after the reopen. actionItemsReadableAfterReopen / taskChatReadableAfterReopen now come from those reads instead of being hard-coded true.
  • The seeded rows are removed on both the success and failure paths. The action item is stored soft-deleted with no backend ID, so task lists and backend sync never pick it up during the run.
  • RewindArtifactGauntletTests passes locally. Changing the task-chat check to expect no rows makes it fail, so the new assertion is live.

…storage-base

# Conflicts:
#	desktop/macos/Desktop/Sources/Rewind/Core/MemoryStorage.swift
@aryanorastar

Copy link
Copy Markdown
Collaborator Author

Merged current main (6576c9d).

  • Conflict in MemoryStorage.swift: feat(siri): App Intents + Spotlight personal context for macOS and iOS #19133 made ensureInitialized() non-private so the Siri MemoryStorage extensions can call it, while this PR replaced the method body with the shared RewindRepository lookup. Kept main's visibility and this PR's body.
  • The package builds with those Siri callers. RewindArtifactGauntletTests, RewindRepositoryTests, and the Siri suites pass locally (48 tests).

@Git-on-my-level

Copy link
Copy Markdown
Member

Reviewed the full diff — this is a clean, well-tested consolidation. Specific observations:

  • RewindRepository.swift: the new actor preserves the exact cache contract it replaces. Generation revalidation happens on every hand-off, an explicitly injected pool (cachedGeneration == nil) passes through untouched — matching the old FileIndexerService test-injection behavior — and the stale pool is cleared before source.initialize(), so a failed reopen can never hand back the previous owner's pool. RewindRepositoryTests covers each of these paths, including the failed-reopen case.
  • RewindDatabase.swift → RewindFTSDefinition: matchesRepairableError(_:) is a faithful port of the old isActionItemsFTSError (same result-code and message classification), and migration 19 now goes through RewindFTSDefinition.actionItems.install with SQL identical to the removed hand-rolled version. The interpolated identifiers are code-owned constants guarded by precondition(isSafeIdentifier) plus the tokenizer quote check, so there is no injection surface. Durable action_items rows are still never dropped or rewritten; repair rebuilds only the projection.
  • The 11 migrated storage actors (ActionItemStorage, MemoryStorage, GoalStorage, ProactiveStorage, StagedTaskStorage, TaskChatMessageStorage, TranscriptionStorage, NoteStorage, KnowledgeGraphStorage, AIUserProfileService, FileIndexerService) are mechanical migrations; each keeps its domain-specific not-initialized error. The one API change external callers see is invalidateCache() becoming async.
  • check-rewind-repository-ownership.py + checks-manifest.yaml: the guard is a repo-local static scan with a real self-test (accepts repository-owned storage, rejects copied _dbQueue/_dbGeneration pairs), no network or secret access. Note the regex flags any private var _dbQueue/_dbGeneration in Sources, not just Rewind-backed actors — that breadth looks intentional as an ownership convention, just be aware it will also catch unrelated future code using those names.
  • RewindArtifactGauntlet.swift + rewind-artifact-recovery.yaml: seeding one soft-deleted action item and one task-chat row, then requiring both to read back through their repositories across the close/reopen, directly exercises the recovery path this refactor is about; e2e expectations and the gauntlet result fields are updated consistently, and the {"kind":"none"} changelog entry matches the no-user-visible-change claim.
  • Minor nit, non-blocking: AIUserProfileService.swift uses owner string "AIUserStorage" instead of the actor name, so log prefixes during initialization failures will say AIUserStorage.

The one local suite failure noted in the PR description (floating-bar AppKit sizing assertion) touches no files in this diff and the GitHub Desktop Swift Build & Tests check is green, so it does not gate here.

Leaving for human maintainer sign-off before merge: this consolidates the storage-pool lifecycle for user data (sign-out/user-switch invalidation and recovery) across every Rewind-backed macOS actor, which is an architecture call worth a maintainer's eyes even though the migration itself looks correct.


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

…storage-base

# Conflicts:
#	desktop/macos/e2e/flows/rewind-artifact-recovery.yaml
@Git-on-my-level

Copy link
Copy Markdown
Member

Reviewed the full diff on top of the earlier feedback in this thread — the consolidation holds up. File-by-file notes:

  • RewindRepository.swift — databasePool() preserves the exact per-storage contracts being replaced: an injected pool (cachedGeneration == nil) is returned as-is until invalidated (FileIndexerService's test-injection path), a shared-source pool is revalidated against the current generation on every hand-off, and on a generation change the stale pool is dropped before initialize() is attempted, so a failed reopen can never hand back the old pool. testGenerationChangeNeverFallsBackToStalePoolWhenReopenFails pins that last property with a real GRDB pool, which is the right way to lock it in.
  • RewindFTSDefinition — the generated CREATE VIRTUAL TABLE / trigger SQL is byte-equivalent to the literals removed from RewindDatabase.swift (migration 19 parity holds), matchesRepairableError is a faithful port of isActionItemsFTSError, and the identifier interpolation is fenced by the isSafeIdentifier / non-empty-columns / tokenizer-quote preconditions with code-owned constants only. The ActionItemStorage repair retry now targets the exact failing pool via repairFTS(.actionItems, in: db, …), which keeps the stale-queue-race fix intact.
  • check-rewind-repository-ownership.py + checks-manifest entries — nice touch making the architectural rule deterministic; the self-test lane entry that proves the guard rejects copied _dbQueue/_dbGeneration caches is exactly how a guard like this should be pinned. The manifest diff only registers the script in existing lanes.
  • RewindArtifactGauntlet.swift — seeding one soft-deleted action item and one task-chat row and requiring them to read back through their repositories on both sides of the database reopen (with cleanup on both success and error paths) upgrades the gauntlet from "reads don't throw" to "repositories actually follow the replacement pool".
  • The 11 consumer migrations (ActionItemStorage, MemoryStorage, TranscriptionStorage, GoalStorage, StagedTaskStorage, ProactiveStorage, TaskChatMessageStorage, NoteStorage, KnowledgeGraphStorage, AIUserProfileService, FileIndexerService) — mechanical and consistent; I compared each against the removed code and the error types / throwing paths are unchanged. The changelog kind: none matches the no-user-visible-change claim.

The one full-suite failure called out in the PR body (floating-bar AppKit sizing, 197.5 >= 198.0) is pre-existing and untouched by this diff, and the relevant desktop CI lanes are green.

No security concerns found: no new dependencies, no secrets handling, and the FTS SQL construction is identifier-guarded with no user input reaching the type. Leaving formal sign-off to the maintainer review already requested — this is a storage-lifecycle consolidation across every Rewind consumer plus a new CI guard, so it deserves that final human pass before merge.


by AI on behalf of David — if you need David’s attention urgently, please @Git-on-my-level and escalate with need human response.

@aryanorastar

Copy link
Copy Markdown
Collaborator Author

@Git-on-my-level this is green and ready for a maintainer review when you have a moment.

@Git-on-my-level
Git-on-my-level merged commit e9c45bd into BasedHardware:main Oct 5, 2026
37 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

macOS needs-maintainer-review Needs a human maintainer to sign off before merge positive-signal Automation verified a genuine fix/quality contribution

Projects

None yet

Development

Successfully merging this pull request may close these issues.

refactor(macOS): shared repository base for Rewind local storage classes (collapse duplicated DB plumbing)

3 participants