From db09b94033d720f33a7fac3db4f0bbdc07566f5d Mon Sep 17 00:00:00 2001 From: legitimate-apps <309192374+legitimate-apps@users.noreply.github.com> Date: Fri, 2 Oct 2026 11:06:55 -0400 Subject: [PATCH 01/27] Record capture reliability work and verification plan --- state/ASTRA-1002.md | 53 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 state/ASTRA-1002.md diff --git a/state/ASTRA-1002.md b/state/ASTRA-1002.md new file mode 100644 index 0000000..7451c76 --- /dev/null +++ b/state/ASTRA-1002.md @@ -0,0 +1,53 @@ +# Command reliability push — 2026-10-02 + +## Scope and authority +- Worktree branch: `astra/capture-reliability-1002`, based on `47170c2` (build 70). +- Own this worktree only. The main checkout belongs to a separate session. +- Capture reliability first, then valuable gaps between the shipped app/server/MCP and the product promise. +- No spending, third-party messages, publication, deployment, or store submissions in this run. +- Commit with the project identity and no attribution trailers. Keep all evidence and text public-safe. +- The operator explicitly selected Astra for this run; this supersedes historical model restrictions. + +## Hydration (observed) +Read START-HERE, CLAUDE/AGENTS, maintainer override, shared operating contract, original design, +MCP guide, local roadmap/TODO/mission and duplicate-note closure, and indexed project memory. +No CORPUS.md is present in the checkout or maintainer ops tree. Several backlog entries are stale; +validate them against current code and tests before choosing work. Current repository guidance says +public: do not use a self-hosted CI runner. Duplicate-note work is complete in the baseline and is +not this run's assignment. + +## Current priority +**Durable unsent note recovery.** Observed: editor savers/parked edits and the calendar's quick +capture draft exist only in memory. A process termination loses unsent work even though same-process +save/retry behavior is now solid. Implement account-and-server-scoped recovery, retain the original +create key/payload across a relaunch, and remove recovery records only after success or explicit +discard. Reauthentication must restore only the matching account's work. Check stale network +callbacks at sign-out so they cannot mutate another account's capture state. + +## Verification plan +- Discriminating tests for relaunch recovery, uncertain creates, partial saves, explicit discard, + account/server isolation, and stale completions. +- Simulator tests and Catalyst compilation using leased simulator/DerivedData; observe UI where changed. +- Record actual commands/results below; do not claim production behavior from local tests. + +## Done / evidence +- Isolated worktree created from the shipped baseline. No edits to main. + +## Next +Trace lifecycle and account activation, implement durable recovery, run regression controls, then +select the next customer-visible reliability/workflow gap. + +## In progress — local recovery +- Added per-account/server atomic recovery files for editor snapshots and quick-capture text. + Identity includes account creation time to separate a recreated account with a reused ID. +- Retirement of a note store blocks new requests from disappearing editors after sign-out; + successful in-flight requests may still finalize their original recovery record. +- Hidden editor snapshots retain their veil; unreadable files are preserved and reported. +- Calendar's visible input now binds directly to the account store instead of a separate + view-local string (otherwise persistence tests alone would miss the actual input surface). +- Simulator lease: `7F4A84D8-DCF7-4520-BD2F-8B9E54242624`; DD lease project/purpose + `command-astra-1002/tests`. Evidence scratch: `/tmp/command-astra-1002/`. +- First build invocation stopped before compilation because the test target lacked a generated + Info.plist under ad-hoc signing. The local build invocation now supplies + `CODE_SIGNING_ALLOWED=YES CODE_SIGN_IDENTITY=- GENERATE_INFOPLIST_FILE=YES`. +- No feature verification claimed yet; compiling and exercising persistence regressions next. From f5a12fcd3d3dca37085dfa550afbaaea971678dc Mon Sep 17 00:00:00 2001 From: legitimate-apps <309192374+legitimate-apps@users.noreply.github.com> Date: Fri, 2 Oct 2026 11:54:14 -0400 Subject: [PATCH 02/27] Preserve unsent notes across relaunch and isolate account sessions --- ios/Command/App/AppState.swift | 24 ++- .../Features/Calendar/CalendarView.swift | 25 ++- .../Features/Notes/NoteDetailView.swift | 21 +- .../Features/Notes/NoteRecoveryStore.swift | 86 ++++++++ ios/Command/Features/Notes/NoteSaver.swift | 49 ++++- ios/Command/Features/Notes/NotesStore.swift | 105 ++++++++- ios/Command/Features/Notes/NotesView.swift | 8 +- ios/Command/Networking/APIClient.swift | 80 +++++-- ios/Command/Networking/CreateAttempt.swift | 2 +- ios/CommandTests/KeyedCreateTests.swift | 21 ++ .../NoteRecoveryPersistenceTests.swift | 203 ++++++++++++++++++ .../ParkedNoteRecoveryTests.swift | 24 ++- ios/CommandTests/SessionIsolationTests.swift | 143 ++++++++++++ state/ASTRA-1002.md | 34 ++- 14 files changed, 766 insertions(+), 59 deletions(-) create mode 100644 ios/Command/Features/Notes/NoteRecoveryStore.swift create mode 100644 ios/CommandTests/NoteRecoveryPersistenceTests.swift create mode 100644 ios/CommandTests/SessionIsolationTests.swift diff --git a/ios/Command/App/AppState.swift b/ios/Command/App/AppState.swift index fa35179..49b3e7c 100644 --- a/ios/Command/App/AppState.swift +++ b/ios/Command/App/AppState.swift @@ -115,7 +115,8 @@ final class AppState { var lastError: String? /// Shared notes state (capture bar + Notes list stay in sync). - let notes = NotesStore() + private(set) var notes = NotesStore() + private let noteRecoveryRoot: URL /// Shared delegatee roster (People list + assignee pickers). let people = PeopleStore() /// Shared goals + assignments. @@ -183,7 +184,8 @@ final class AppState { /// Whether a server has been chosen yet. Drives `.needsServer`. var hasServer: Bool { !serverURLString.trimmingCharacters(in: .whitespaces).isEmpty } - init(client: APIClient? = nil) { + init(client: APIClient? = nil, noteRecoveryRoot: URL = NoteRecoveryStore.defaultRoot) { + self.noteRecoveryRoot = noteRecoveryRoot Self.migrateLegacyServerURL(UserDefaults.standard) let saved = client?.baseURL.absoluteString ?? UserDefaults.standard.string(forKey: Self.urlKey) ?? Self.defaultServerURL serverURLString = saved @@ -205,8 +207,13 @@ final class AppState { /// Wire the client's session-expiry callback back to us. Reinstalled whenever the /// client is rebuilt (a server-URL change), so the hook never points at a stale client. private func installClientHooks() { - client.onUnauthorized = { [weak self] in - Task { @MainActor in self?.handleSessionExpired() } + let installedClient = client + client.onUnauthorized = { [weak self, weak installedClient] identity in + Task { @MainActor in + guard let self, let installedClient, self.client === installedClient, + installedClient.isCurrentSession(identity) else { return } + self.handleSessionExpired() + } } } @@ -581,6 +588,10 @@ final class AppState { /// Post-sign-in fan-out: load the entitlement (consent + subscription state) and /// bind RevenueCat's identity to this account so its purchase webhook maps back. private func onSignedIn() async { + notes.deactivate() + if let account { + notes = NotesStore(recovery: NoteRecoveryStore(root: noteRecoveryRoot, server: client.baseURL, account: account)) + } await refreshEntitlement() // RevenueCat identity + offering load run OFF the critical path. A slow or // stalled StoreKit product fetch — e.g. a freshly-created sandbox product still @@ -750,6 +761,7 @@ final class AppState { /// no longer exists. func forgetDeletedAccount() async { lock.reset() + notes.deactivate(deleteRecovery: true) tearDownSession() lastError = nil } @@ -784,8 +796,8 @@ final class AppState { UserDefaults.standard.removeObject(forKey: Self.manualTimezoneKey) // it was that account's choice entitlement = nil Task { [subscription] in await subscription.signOut() } - notes.notes = [] - notes.draft = "" + notes.deactivate() + notes = NotesStore() people.delegatees = [] tasks.assignments = [] tasks.goals = [] diff --git a/ios/Command/Features/Calendar/CalendarView.swift b/ios/Command/Features/Calendar/CalendarView.swift index d7b1287..0da7f05 100644 --- a/ios/Command/Features/Calendar/CalendarView.swift +++ b/ios/Command/Features/Calendar/CalendarView.swift @@ -22,7 +22,13 @@ struct CalendarView: View { @State private var savedHidden = false @State private var showRecording = false @State private var captureMode: CaptureMode = .note - @State private var captureText = "" // shared across modes — switching mode keeps the text + // The account-scoped store owns the text, including after a tab remount or app relaunch. + private var captureText: String { + get { app.notes.draft } + nonmutating set { + app.notes.draft = newValue; app.log.draft = newValue; app.schedule.draft = newValue + } + } @State private var showDatePicker = false @State private var showTimePicker = false @State private var showLogDatePicker = false @@ -268,11 +274,6 @@ struct CalendarView: View { .toolbarBackground(.hidden, for: .navigationBar) // transparent bar; paper shows through .toolbar { todayToolbar } .overlay(alignment: .top) { if showSaved { savedToast } } - .onChange(of: captureText) { _, text in - // These stores share this field. Observe edits, including a change back to the - // original text, so a failed submission's key never follows a new draft. - app.notes.draft = text; app.log.draft = text; app.schedule.draft = text - } .onChange(of: captureMode) { _, mode in dateOverridden = false // a mode switch re-syncs the date to the big calendar if mode == .schedule { @@ -479,7 +480,7 @@ struct CalendarView: View { } private var inputField: some View { - TextField(composePlaceholder, text: $captureText, axis: .vertical) + TextField(composePlaceholder, text: Binding(get: { captureText }, set: { captureText = $0 }), axis: .vertical) .focused($fieldFocused) .font(Typeface.body(16)) .foregroundStyle(Palette.ink) @@ -683,7 +684,7 @@ struct CalendarView: View { private var activeError: String? { switch captureMode { - case .note: return app.notes.errorMessage + case .note: return app.notes.recoveryError ?? app.notes.errorMessage case .log: return app.log.errorMessage case .schedule: return app.schedule.errorMessage } @@ -729,13 +730,15 @@ struct CalendarView: View { private func send(hidden: Bool = false) { let sentText = captureText, sentMode = captureMode + let notes = app.notes, client = app.client Task { + guard app.notes === notes else { return } // Push the shared entry text into the active store, then save. let ok: Bool switch sentMode { case .note: - app.notes.draft = sentText - ok = await app.notes.saveDraft(hidden: hidden, client: app.client) + notes.draft = sentText + ok = await notes.saveDraft(hidden: hidden, client: client) case .log: app.log.draft = sentText ok = await app.log.logDraft(hidden: hidden, client: app.client) @@ -743,7 +746,7 @@ struct CalendarView: View { app.schedule.draft = sentText ok = await app.schedule.addToQueue(hidden: hidden, client: app.client) } - guard ok else { return } + guard ok, app.notes === notes else { return } Haptics.success() // A response to the submitted text must not erase typing or switch the mode's // date after the user has moved on to another capture. diff --git a/ios/Command/Features/Notes/NoteDetailView.swift b/ios/Command/Features/Notes/NoteDetailView.swift index c7f93b2..f762a83 100644 --- a/ios/Command/Features/Notes/NoteDetailView.swift +++ b/ios/Command/Features/Notes/NoteDetailView.swift @@ -57,7 +57,7 @@ struct NoteDetailView: View { init(note: Note? = nil, inDetailColumn: Bool = false, session: NoteSaver? = nil) { self.initialNote = note self.inDetailColumn = inDetailColumn - _saver = State(initialValue: session ?? NoteSaver(noteId: note?.id, text: Self.combined(note))) + _saver = State(initialValue: session ?? NoteSaver(noteId: note?.id, text: Self.combined(note), hidden: note?.hidden ?? false)) } /// Reconstruct the single-field text from a note losslessly. Body holds the full content; a @@ -70,8 +70,10 @@ struct NoteDetailView: View { return note.body.isEmpty ? title : title + "\n" + note.body } - private var client: APIClient { app.client } - private var store: NotesStore { app.notes } + @State private var editorClient: APIClient? + private var client: APIClient { editorClient ?? app.client } + @State private var editorStore: NotesStore? + private var store: NotesStore { editorStore ?? app.notes } private var noteId: Int? { saver.noteId } private var text: String { saver.text } private var isNew: Bool { noteId == nil } @@ -97,7 +99,7 @@ struct NoteDetailView: View { /// A hidden note opens censored: shown but covered, so it never reveals plaintext on /// tap. In "Rub to reveal" the reader can rub it to peek; "Reveal all" lifts the cover /// and restores normal editing. - private var isHidden: Bool { !revealedOverride && (initialNote?.hidden ?? false) && app.hiddenRevealMode != .revealAll } + private var isHidden: Bool { !revealedOverride && saver.hidden && app.hiddenRevealMode != .revealAll } var body: some View { NavigationStack { @@ -183,8 +185,7 @@ struct NoteDetailView: View { if phase != .active { saveTask?.cancel(); Task { _ = await saver.flush(using: saveOps) } } } // A sheet can't be swiped away while its last save failed — the Retry / Discard banner - // is the way out. Parked edits live only in memory, so a swipe followed by the app - // being killed would lose the text. + // is the way out. Local recovery also survives an unexpected process termination. .interactiveDismissDisabled(saver.isFailed) .confirmationDialog("Discard unsaved changes?", isPresented: $showDiscard, titleVisibility: .visible) { Button("Discard", role: .destructive) { discardAndClose() } @@ -195,6 +196,8 @@ struct NoteDetailView: View { .onAppear { lifetime.appear() guard !registeredEditor else { return } + editorStore = app.notes + editorClient = app.client saver = store.resumeEditor(saver: saver, owner: lifetime.owner) registeredEditor = true } @@ -279,7 +282,7 @@ struct NoteDetailView: View { /// never exposes plaintext. The reader rubs to peek (in "Rub to reveal" mode). private var hiddenReader: some View { ScrollView { - Text(Self.combined(initialNote).isEmpty ? "Hidden note" : Self.combined(initialNote)) + Text(text.isEmpty ? "Hidden note" : text) .font(Typeface.body(17)) .foregroundStyle(Palette.ink) .frame(maxWidth: .infinity, alignment: .leading) @@ -384,7 +387,7 @@ struct NoteDetailView: View { guard let id = noteId else { return } focused = false Task { - await app.notes.setHidden(id: id, hidden: true, client: client) + await store.setHidden(id: id, hidden: true, client: client) finish() } } label: { Label("Hide", systemImage: "eye.slash") } @@ -396,7 +399,7 @@ struct NoteDetailView: View { guard let id = noteId else { return } Task { if await app.privacy.authenticate(reason: "Reveal this note"), - await app.notes.setHidden(id: id, hidden: false, client: client) { + await store.setHidden(id: id, hidden: false, client: client) { revealedOverride = true } } diff --git a/ios/Command/Features/Notes/NoteRecoveryStore.swift b/ios/Command/Features/Notes/NoteRecoveryStore.swift new file mode 100644 index 0000000..b6613de --- /dev/null +++ b/ios/Command/Features/Notes/NoteRecoveryStore.swift @@ -0,0 +1,86 @@ +import CryptoKit +import Foundation + +/// Device-local recovery, not a second notes database. Each unsent editor has its own atomic +/// file so a damaged record cannot prevent the other drafts from being recovered. +@MainActor +final class NoteRecoveryStore { + let directory: URL + private let files = FileManager.default + private let owner = UUID() + private static var owners: [URL: UUID] = [:] + + /// A reauthenticated store takes over this scope. Late completions from its predecessor + /// must not overwrite or remove recovery files that the new editor now owns. + func claimOwnership() { Self.owners[directory] = owner } + private var ownsFiles: Bool { Self.owners[directory] == owner } + + init(root: URL, server: URL, account: Account) { + // IDs are only unique within a server, and can be reused after an account is deleted. + let identity = [server.absoluteString.trimmingCharacters(in: CharacterSet(charactersIn: "/")), + String(account.id), account.username, account.createdAt].joined(separator: "\n") + let scope = SHA256.hash(data: Data(identity.utf8)).map { String(format: "%02x", $0) }.joined() + directory = root.appendingPathComponent(scope, isDirectory: true) + } + + nonisolated static var defaultRoot: URL { + FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0] + .appendingPathComponent("NoteRecovery", isDirectory: true) + } + + struct Draft: Codable { + var text: String + var attempt: CreateAttempt + } + + func loadDraft() throws -> Draft? { + let url = directory.appendingPathComponent("draft.json") + guard files.fileExists(atPath: url.path) else { return nil } + return try JSONDecoder().decode(Draft.self, from: Data(contentsOf: url)) + } + + func saveDraft(_ draft: Draft) throws { + guard ownsFiles else { return } + if draft.text.isEmpty { try remove("draft.json") } + else { try write(draft, name: "draft.json") } + } + + /// Return intact records even if one cannot be read. The unreadable file is never removed. + func loadEdits() throws -> (edits: [NoteSaver.Snapshot], unreadable: Bool) { + guard files.fileExists(atPath: directory.path) else { return ([], false) } + let urls = try files.contentsOfDirectory(at: directory, includingPropertiesForKeys: nil) + .filter { $0.lastPathComponent.hasPrefix("edit-") && $0.pathExtension == "json" } + var edits: [NoteSaver.Snapshot] = [] + var unreadable = false + for url in urls.sorted(by: { $0.lastPathComponent < $1.lastPathComponent }) { + do { edits.append(try JSONDecoder().decode(NoteSaver.Snapshot.self, from: Data(contentsOf: url))) } + catch { unreadable = true } + } + return (edits, unreadable) + } + + func save(_ snapshot: NoteSaver.Snapshot) throws { try write(snapshot, name: name(snapshot.id)) } + func removeEdit(_ id: UUID) throws { try remove(name(id)) } + func removeAll() throws { + guard ownsFiles else { return } + if files.fileExists(atPath: directory.path) { try files.removeItem(at: directory) } + } + + private func name(_ id: UUID) -> String { "edit-\(id.uuidString).json" } + private func remove(_ name: String) throws { + guard ownsFiles else { return } + let url = directory.appendingPathComponent(name) + if files.fileExists(atPath: url.path) { try files.removeItem(at: url) } + } + private func write(_ value: some Encodable, name: String) throws { + guard ownsFiles else { return } + try files.createDirectory(at: directory, withIntermediateDirectories: true, + attributes: [.posixPermissions: 0o700]) + var folder = directory + var values = URLResourceValues(); values.isExcludedFromBackup = true + try folder.setResourceValues(values) + let url = directory.appendingPathComponent(name) + try JSONEncoder().encode(value).write(to: url, options: [.atomic, .completeFileProtectionUntilFirstUserAuthentication]) + try files.setAttributes([.posixPermissions: 0o600], ofItemAtPath: url.path) + } +} diff --git a/ios/Command/Features/Notes/NoteSaver.swift b/ios/Command/Features/Notes/NoteSaver.swift index c883fec..3e69587 100644 --- a/ios/Command/Features/Notes/NoteSaver.swift +++ b/ios/Command/Features/Notes/NoteSaver.swift @@ -23,7 +23,7 @@ import Observation @Observable final class NoteSaver: Identifiable { /// Identity of this editing session, retained across presentations and create retries. - let id = UUID() + let id: UUID enum State: Equatable { case idle, saving, saved, failed(String) } /// The two server operations a save needs, supplied per call (the view builds them from its @@ -37,7 +37,8 @@ final class NoteSaver: Identifiable { /// The editor's current text. The view writes every keystroke here; a save always sends the /// latest value when an update STARTS; an uncertain create first replays its original payload. - var text: String + var text: String { didSet { recoveryDidChange?() } } + private(set) var hidden: Bool private(set) var noteId: Int? private(set) var state: State = .idle /// Trimmed text of the last successful save (or of the note as loaded). @@ -46,9 +47,37 @@ final class NoteSaver: Identifiable { private var inFlight: Task? /// A lost response may follow a committed POST. Retry its exact payload and key, then PATCH /// any newer text. This also supports servers that require identical replay payloads. - private var createPayload: (title: String?, body: String)? + struct CreatePayload: Codable { let title: String?; let body: String } + private var createPayload: CreatePayload? + @ObservationIgnored var recoveryDidChange: (() -> Void)? - init(noteId: Int?, text: String) { + struct Snapshot: Codable { + let id: UUID + let noteId: Int? + let text: String + let lastSavedText: String + let hidden: Bool + let createPayload: CreatePayload? + } + + var recoverySnapshot: Snapshot? { + guard hasUnsavedChanges || createPayload != nil else { return nil } + return Snapshot(id: id, noteId: noteId, text: text, lastSavedText: lastSavedText, hidden: hidden, + createPayload: createPayload) + } + + init(recovering snapshot: Snapshot) { + id = snapshot.id + hidden = snapshot.hidden + noteId = snapshot.noteId + text = snapshot.text + lastSavedText = snapshot.lastSavedText + createPayload = snapshot.createPayload + } + + init(noteId: Int?, text: String, hidden: Bool = false) { + self.hidden = hidden + self.id = UUID() self.noteId = noteId self.text = text self.lastSavedText = text.trimmingCharacters(in: .whitespacesAndNewlines) @@ -59,7 +88,7 @@ final class NoteSaver: Identifiable { /// erase (Delete is the explicit way to remove a note), so it is never persisted over content. var hasUnsavedChanges: Bool { let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines) - return !trimmed.isEmpty && trimmed != lastSavedText + return createPayload != nil || (!trimmed.isEmpty && trimmed != lastSavedText) } var isFailed: Bool { if case .failed = state { return true } else { return false } } @@ -81,7 +110,8 @@ final class NoteSaver: Identifiable { let id = noteId if id == nil, createPayload == nil { let title = Note.firstLine(of: text) - createPayload = (title.isEmpty ? nil : title, text) + createPayload = CreatePayload(title: title.isEmpty ? nil : title, body: text) + recoveryDidChange?() } let full = id == nil ? createPayload!.body : text let trimmed = full.trimmingCharacters(in: .whitespacesAndNewlines) @@ -97,6 +127,7 @@ final class NoteSaver: Identifiable { } self.lastSavedText = trimmed self.state = .saved + self.recoveryDidChange?() return true } catch { self.state = .failed(Self.describe(error)) @@ -128,11 +159,17 @@ final class NoteSaver: Identifiable { return true } + func setHidden(_ hidden: Bool) { + self.hidden = hidden + recoveryDidChange?() + } + /// Mark `text` as what the server now holds (e.g. after restoring a revision). func markSaved(_ text: String) { self.text = text lastSavedText = text.trimmingCharacters(in: .whitespacesAndNewlines) state = .saved + recoveryDidChange?() } /// Typing after a save resets the indicator (a failure stays visible until a save succeeds). diff --git a/ios/Command/Features/Notes/NotesStore.swift b/ios/Command/Features/Notes/NotesStore.swift index 0bf3185..8db4643 100644 --- a/ios/Command/Features/Notes/NotesStore.swift +++ b/ios/Command/Features/Notes/NotesStore.swift @@ -14,9 +14,79 @@ import SwiftUI @Observable final class NotesStore { var notes: [Note] = [] - var draft = "" { didSet { if draft != oldValue { draftCreate.reset() } } } + var draft = "" { + didSet { + if draft != oldValue { draftCreate.reset(); persistDraft() } + } + } private var draftCreate = CreateAttempt() private struct DraftPayload: Encodable { let body: String; let hidden: Bool } + private let recovery: NoteRecoveryStore? + private var acceptsRequests = true + private var recoveryDeleted = false + private var draftReadable = true + /// Separate from transport errors: a successful fetch cannot hide a disk recovery failure. + private(set) var recoveryError: String? + + init(recovery: NoteRecoveryStore? = nil) { + self.recovery = recovery + guard let recovery else { return } + recovery.claimOwnership() + do { + if let saved = try recovery.loadDraft() { + draft = saved.text + draftCreate = saved.attempt + } + } catch { + draftReadable = false + recoveryError = "A local draft couldn't be read. Its recovery file has been kept." + } + do { + let result = try recovery.loadEdits() + unsavedEdits = result.edits.map { UnsavedNoteEdit(saver: NoteSaver(recovering: $0)) } + unsavedEdits.forEach { observeRecovery($0.saver) } + if result.unreadable { recoveryError = "Some local edits couldn't be read. Their recovery files have been kept." } + } catch { + recoveryError = "Local edits couldn't be read. Their recovery files have been kept." + } + } + + /// Old views can finish an already-started request, but can never start another one after + /// sign-out (the shared cookie jar may now belong to a different account). + func deactivate(deleteRecovery: Bool = false) { + acceptsRequests = false + if deleteRecovery { + recoveryDeleted = true + do { try recovery?.removeAll() } + catch { recoveryError = "Couldn't remove this account's local recovery files." } + } + } + + private func persistDraft() { + guard !recoveryDeleted, draftReadable else { return } + do { try recovery?.saveDraft(.init(text: draft, attempt: draftCreate)) } + catch { recoveryError = "Couldn't keep a recovery copy on this device. Keep Command open until your note saves." } + } + + private func observeRecovery(_ saver: NoteSaver) { + saver.recoveryDidChange = { [weak self, weak saver] in + guard let self, let saver, !self.recoveryDeleted else { return } + do { + if let snapshot = saver.recoverySnapshot { try self.recovery?.save(snapshot) } + else { try self.recovery?.removeEdit(saver.id) } + } catch { + self.recoveryError = "Couldn't keep a recovery copy on this device. Keep Command open until your note saves." + } + } + saver.recoveryDidChange?() + } + + private func removeRecovery(_ saver: NoteSaver) { + saver.recoveryDidChange = nil + do { try recovery?.removeEdit(saver.id) } + catch { recoveryError = "Couldn't remove a local recovery copy. It may appear again when you reopen Command." } + } + var isLoading = false var isSaving = false var errorMessage: String? @@ -48,6 +118,7 @@ final class NotesStore { var owners = editors[saver.id]?.owners ?? [] owners.insert(owner) editors[saver.id] = (saver, owners) + observeRecovery(saver) return saver } @@ -56,6 +127,13 @@ final class NotesStore { if !editor.owners.isEmpty { editors[saver.id] = editor; return } editors.removeValue(forKey: saver.id) if shouldPark { park(saver: saver) } + else { removeRecovery(saver) } + } + + private func syncHidden(_ note: Note) { + for saver in editors.values.map(\.saver) + unsavedEdits.map(\.saver) where saver.noteId == note.id { + saver.setHidden(note.hidden ?? false) + } } private var mutationVersion = 0 @@ -69,6 +147,7 @@ final class NotesStore { } func load(client: APIClient) async { + guard acceptsRequests else { return } let token = UUID(), startedAt = mutationVersion latestLoad = token; activeLoads[token] = startedAt isLoading = true @@ -92,6 +171,7 @@ final class NotesStore { else { fresh.insert(note, at: 0) } } else { fresh.removeAll { $0.id == id } } } + fresh.forEach { syncHidden($0) } withAnimation(.snappy) { notes = fresh } errorMessage = nil } catch { @@ -102,6 +182,7 @@ final class NotesStore { /// Save the current draft as a typed note. Returns true on success. @discardableResult func saveDraft(hidden: Bool = false, client: APIClient) async -> Bool { + guard acceptsRequests else { return false } guard !isSaving else { return false } let sentDraft = draft let body = sentDraft.trimmingCharacters(in: .whitespacesAndNewlines) @@ -111,6 +192,7 @@ final class NotesStore { do { let payload = DraftPayload(body: body, hidden: hidden) let key = try draftCreate.key(for: payload) + persistDraft() let note = try await client.createNote(body: body, source: "typed", hidden: hidden, idempotencyKey: key) draftCreate.succeeded(key: key) insertCreated(note) @@ -128,6 +210,7 @@ final class NotesStore { /// top of the list. A nil title lets the server generate one (AI titling). @discardableResult func create(title: String?, body: String, idempotencyKey: UUID = UUID(), client: APIClient) async -> Note? { + guard acceptsRequests else { return nil } let b = body.trimmingCharacters(in: .whitespacesAndNewlines) guard !b.isEmpty else { return nil } do { @@ -146,6 +229,7 @@ final class NotesStore { /// `errorMessage` set) otherwise, so the recording sheet can keep the transcript for a retry. @discardableResult func saveVoiceNote(_ text: String, engine: String, locale: String?, idempotencyKey: String = UUID().uuidString, client: APIClient) async -> Bool { + guard acceptsRequests else { return false } let body = text.trimmingCharacters(in: .whitespacesAndNewlines) guard !body.isEmpty else { return false } do { @@ -170,6 +254,7 @@ final class NotesStore { /// Replace a note in the list in place (keeps the list reactive after an edit). private func replace(_ note: Note) { + syncHidden(note) if let i = notes.firstIndex(where: { $0.id == note.id }) { notes[i] = note recordMutation(id: note.id, note: note) @@ -179,6 +264,7 @@ final class NotesStore { /// Patch title and/or body, syncing the row. @discardableResult func update(id: Int, title: String? = nil, body: String? = nil, client: APIClient) async -> Note? { + guard acceptsRequests else { return nil } do { let note = try await client.updateNote(id: id, title: title, body: body) replace(note); errorMessage = nil; return note @@ -190,6 +276,7 @@ final class NotesStore { /// Redact (hide) or unredact (reveal) a note, syncing the row so the veil updates live. @discardableResult func setHidden(id: Int, hidden: Bool, client: APIClient) async -> Bool { + guard acceptsRequests else { return false } do { let note = try await client.setNoteHidden(id: id, hidden: hidden) replace(note); errorMessage = nil; return true @@ -200,6 +287,7 @@ final class NotesStore { /// Delete = archive: hide from the list but keep it (and its backups) recoverable. func archive(id: Int, client: APIClient) async { + guard acceptsRequests else { return } do { _ = try await client.archiveNote(id: id, archived: true) recordMutation(id: id, note: nil) @@ -213,6 +301,7 @@ final class NotesStore { /// The user closed the note: snapshot a backup + (maybe) start an AI title, then /// poll briefly so the row updates with the generated title. func close(id: Int, client: APIClient) async { + guard acceptsRequests else { return } do { let note = try await client.closeNote(id: id) replace(note) @@ -230,8 +319,10 @@ final class NotesStore { } private func pollTitle(id: Int, client: APIClient) async { + guard acceptsRequests else { return } for _ in 0..<8 { try? await Task.sleep(for: .milliseconds(1200)) + guard acceptsRequests, !Task.isCancelled else { return } guard let note = try? await client.getNote(id: id) else { continue } replace(note) if note.titleStatus != "generating" { return } @@ -239,12 +330,14 @@ final class NotesStore { } func revisions(id: Int, client: APIClient) async -> [NoteRevision] { + guard acceptsRequests else { return [] } do { return try await client.noteRevisions(id: id) } catch { errorMessage = describe(error); return [] } } @discardableResult func restore(noteId: Int, revisionId: Int, client: APIClient) async -> Note? { + guard acceptsRequests else { return nil } do { let note = try await client.restoreNoteRevision(noteId: noteId, revisionId: revisionId) replace(note); errorMessage = nil; return note @@ -256,6 +349,7 @@ final class NotesStore { /// Duplicate a note's body into a brand-new note with the given name (title). @discardableResult func duplicate(title: String, body: String, client: APIClient) async -> Note? { + guard acceptsRequests else { return nil } do { let note = try await client.createNote(body: body, source: "typed", title: title) insertCreated(note); errorMessage = nil; return note @@ -267,6 +361,7 @@ final class NotesStore { /// Retain the original saver, including a successful create followed by a failed PATCH, /// and its stable session identity. Retrying must never manufacture a fresh create owner. func park(saver: NoteSaver) { + observeRecovery(saver) unsavedEdits.removeAll { $0.id == saver.id || (saver.noteId != nil && $0.noteId == saver.noteId) } unsavedEdits.append(UnsavedNoteEdit(saver: saver)) } @@ -274,6 +369,7 @@ final class NotesStore { /// Only one retry pass runs at a time. Edits parked during a /// retry remain in the queue. Only the exact session successfully flushed is removed. func retryUnsavedEdits(client: APIClient) async { + guard acceptsRequests else { return } guard !isRetrying else { return } isRetrying = true defer { isRetrying = false } @@ -291,12 +387,17 @@ final class NotesStore { throw NoteSaveError(message: self.errorMessage) } }) - if await edit.saver.flush(using: ops) { unsavedEdits.removeAll { $0.id == edit.id } } + if await edit.saver.flush(using: ops) { + unsavedEdits.removeAll { $0.id == edit.id } + // Reopening the editor during the retry transfers ownership to the editor. + if editors[edit.id] == nil { removeRecovery(edit.saver) } + } } } func discardUnsavedEdits() { guard !isRetrying else { return } + unsavedEdits.forEach { removeRecovery($0.saver) } unsavedEdits.removeAll() } diff --git a/ios/Command/Features/Notes/NotesView.swift b/ios/Command/Features/Notes/NotesView.swift index b82a443..2cde1de 100644 --- a/ios/Command/Features/Notes/NotesView.swift +++ b/ios/Command/Features/Notes/NotesView.swift @@ -44,6 +44,10 @@ struct NotesView: View { } .transition(.move(edge: .top).combined(with: .opacity)) } + if let error = app.notes.recoveryError { + Label(error, systemImage: "exclamationmark.triangle") + .font(.footnote).foregroundStyle(Palette.danger).padding(12) + } if !app.notes.unsavedEdits.isEmpty { unsavedEditsBanner } content } @@ -133,7 +137,7 @@ struct NotesView: View { .font(.system(size: 14)) .foregroundStyle(Palette.danger) .accessibilityHidden(true) - Text(count == 1 ? "1 note edit couldn't be saved." : "\(count) note edits couldn't be saved.") + Text(count == 1 ? "1 note has unsaved edits on this device." : "\(count) notes have unsaved edits on this device.") .font(Typeface.body(13)) .foregroundStyle(Palette.ink) Spacer(minLength: 8) @@ -161,7 +165,7 @@ struct NotesView: View { .disabled(app.notes.isRetrying) Button("Cancel", role: .cancel) {} } message: { - Text("These edits never reached the server and will be lost.") + Text("This removes the local recovery copies. Any changes already saved on the server will remain.") } } diff --git a/ios/Command/Networking/APIClient.swift b/ios/Command/Networking/APIClient.swift index e46d0b3..160cd45 100644 --- a/ios/Command/Networking/APIClient.swift +++ b/ios/Command/Networking/APIClient.swift @@ -32,13 +32,50 @@ final class APIClient { let baseURL: URL private let session: URLSession private let cookieStorage: HTTPCookieStorage? + // All clients share the app's cookie jar. Serialize snapshot/check/store so a response + // from an old login cannot restore its cookie over a newer account's session. + private static let cookieLock = NSLock() + private var sessionGeneration = UUID() + + struct SessionIdentity: Equatable, Sendable { + fileprivate let generation: UUID + fileprivate let cookieHeader: String? + } + + private func identityLocked() -> SessionIdentity { + let cookies = (cookieStorage?.cookies(for: baseURL) ?? []).sorted { $0.name < $1.name } + return SessionIdentity(generation: sessionGeneration, + cookieHeader: cookies.isEmpty ? nil : HTTPCookie.requestHeaderFields(with: cookies)["Cookie"]) + } + + private func sessionIdentity() -> SessionIdentity { + Self.cookieLock.withLock { identityLocked() } + } + + func isCurrentSession(_ identity: SessionIdentity) -> Bool { + Self.cookieLock.withLock { identityLocked() == identity } + } + + private func authorize(_ request: inout URLRequest, identity: SessionIdentity) throws { + guard isCurrentSession(identity) else { throw URLError(.cancelled) } + request.httpShouldHandleCookies = false + request.setValue(identity.cookieHeader, forHTTPHeaderField: "Cookie") + } + + private func accept(_ response: HTTPURLResponse, url: URL, identity: SessionIdentity) throws -> SessionIdentity { + try Self.cookieLock.withLock { + guard identityLocked() == identity else { throw URLError(.cancelled) } + storeCookies(from: response, for: url) + return identityLocked() + } + } /// Fired (off the main actor) when the server rejects our session with 401 on an /// *authenticated* request — the session cookie expired or was revoked mid-use. /// NOT fired for login/register/invite credential checks, whose 401 is an auth error /// the auth screen surfaces locally. AppState installs this to drop cleanly back /// to the sign-in screen instead of leaving every action failing with a generic error. - var onUnauthorized: (@Sendable () -> Void)? + var onUnauthorized: (@Sendable (SessionIdentity) -> Void)? /// Decide whether a failed response means "this session is dead" — the one signal that /// throws the operator back to the sign-in screen. @@ -57,9 +94,10 @@ final class APIClient { && !path.hasSuffix("/auth/invite") } - private func flagUnauthorized(status: Int, code: String?, url: URL?) { + private func flagUnauthorized(status: Int, code: String?, url: URL?, identity: SessionIdentity) { guard Self.isSessionExpiry(status: status, code: code, path: url?.path ?? "") else { return } - onUnauthorized?() + guard isCurrentSession(identity) else { return } + onUnauthorized?(identity) } /// Drain every page of a cursor-paginated list into one array. The list endpoints are cursor- @@ -98,7 +136,7 @@ final class APIClient { init(baseURL: URL, configuration: URLSessionConfiguration = .default) { self.baseURL = baseURL - configuration.httpShouldSetCookies = true + configuration.httpShouldSetCookies = false configuration.httpCookieAcceptPolicy = .always self.cookieStorage = configuration.httpCookieStorage self.session = URLSession(configuration: configuration) @@ -657,7 +695,8 @@ final class APIClient { /// request. `threadId == nil` starts a new thread (the first `thread` event /// reports its id). func streamAgentChat(message: String, threadId: Int?, model: String? = nil, allowHidden: Bool = false, images: [ChatImage] = []) -> AsyncThrowingStream { - AsyncThrowingStream { continuation in + let identity = sessionIdentity() + return AsyncThrowingStream { continuation in let task = Task { do { var req = URLRequest(url: makeURL("/api/agent/chat", query: [])) @@ -670,10 +709,10 @@ final class APIClient { // every ~15s during a run; this allows for a few missed ones on a bad link. req.timeoutInterval = 180 req.httpBody = try Self.encoder.encode(AgentChatBody(message: message, threadId: threadId, model: model, allowHidden: allowHidden, images: images)) - attachCookies(to: &req) + try authorize(&req, identity: identity) let (bytes, response) = try await session.bytes(for: req) guard let http = response as? HTTPURLResponse else { throw APIError.notHTTP } - storeCookies(from: http, for: req.url!) + let acceptedIdentity = try accept(http, url: req.url!, identity: identity) guard (200..<300).contains(http.statusCode) else { // Drain the (small) error envelope rather than discarding it: the code is // what distinguishes a dead session from an edge 401, and the message is @@ -681,11 +720,12 @@ final class APIClient { let parsed = try? Self.decoder.decode( ServerError.self, from: await Self.errorBody(from: bytes) ) - flagUnauthorized(status: http.statusCode, code: parsed?.error.code, url: req.url) + flagUnauthorized(status: http.statusCode, code: parsed?.error.code, url: req.url, identity: acceptedIdentity) throw APIError.http(status: http.statusCode, code: parsed?.error.code, message: parsed?.error.message) } for try await line in bytes.lines { + guard isCurrentSession(acceptedIdentity) else { throw URLError(.cancelled) } guard line.hasPrefix("data:") else { continue } // SSE: ignore comments/blank lines let payload = line.dropFirst(5).trimmingCharacters(in: .whitespaces) guard !payload.isEmpty, let data = payload.data(using: .utf8), @@ -867,9 +907,10 @@ final class APIClient { if let idempotencyKey { req.setValue(idempotencyKey, forHTTPHeaderField: "Idempotency-Key") } // Only keyed creates are replayable. HTTP errors and permanent URL errors go straight // to the caller; a transient transport failure gets at most two bounded retries. + let identity = sessionIdentity() var retries = 0 while true { - do { return try await send(req) } + do { return try await send(req, identity: identity) } catch { guard idempotencyKey != nil, retries < 2, let transport = error as? URLError, Self.isTransient(transport) else { throw error } @@ -903,15 +944,16 @@ final class APIClient { return try await send(req) } - private func send(_ request: URLRequest) async throws -> Data { + private func send(_ request: URLRequest, identity: SessionIdentity? = nil) async throws -> Data { + let identity = identity ?? sessionIdentity() var request = request - attachCookies(to: &request) + try authorize(&request, identity: identity) let (data, response) = try await session.data(for: request) guard let http = response as? HTTPURLResponse else { throw APIError.notHTTP } - storeCookies(from: http, for: request.url!) + let acceptedIdentity = try accept(http, url: request.url!, identity: identity) guard (200..<300).contains(http.statusCode) else { let parsed = try? Self.decoder.decode(ServerError.self, from: data) - flagUnauthorized(status: http.statusCode, code: parsed?.error.code, url: request.url) + flagUnauthorized(status: http.statusCode, code: parsed?.error.code, url: request.url, identity: acceptedIdentity) throw APIError.http(status: http.statusCode, code: parsed?.error.code, message: parsed?.error.message) } return data @@ -949,8 +991,11 @@ final class APIClient { } func clearSessionCookies() { - guard let storage = cookieStorage, let cookies = storage.cookies(for: baseURL) else { return } - for cookie in cookies { storage.deleteCookie(cookie) } + Self.cookieLock.withLock { + sessionGeneration = UUID() + guard let storage = cookieStorage, let cookies = storage.cookies(for: baseURL) else { return } + for cookie in cookies { storage.deleteCookie(cookie) } + } } private func storeCookies(from http: HTTPURLResponse, for url: URL) { @@ -960,10 +1005,7 @@ final class APIClient { storage.setCookies(cookies, for: url, mainDocumentURL: url) } - private func attachCookies(to request: inout URLRequest) { - guard let storage = cookieStorage, let url = request.url, let cookies = storage.cookies(for: url), !cookies.isEmpty else { return } - for (key, value) in HTTPCookie.requestHeaderFields(with: cookies) { request.setValue(value, forHTTPHeaderField: key) } - } + } /// Assignment create body — its own type because callers build it field-by-field. diff --git a/ios/Command/Networking/CreateAttempt.swift b/ios/Command/Networking/CreateAttempt.swift index c2a93be..c25f247 100644 --- a/ios/Command/Networking/CreateAttempt.swift +++ b/ios/Command/Networking/CreateAttempt.swift @@ -2,7 +2,7 @@ import Foundation /// One intended create, retained after ambiguous failures. A changed payload or an explicit /// reset starts a new intent; success clears only the attempt that actually finished. -struct CreateAttempt { +struct CreateAttempt: Codable { private var payload: Data? private var currentKey: String? diff --git a/ios/CommandTests/KeyedCreateTests.swift b/ios/CommandTests/KeyedCreateTests.swift index 1f43130..43554c9 100644 --- a/ios/CommandTests/KeyedCreateTests.swift +++ b/ios/CommandTests/KeyedCreateTests.swift @@ -56,6 +56,27 @@ final class KeyedCreateTests: XCTestCase { } private var keys: [String?] { CreateWireProtocol.creates.map { $0.value(forHTTPHeaderField: "Idempotency-Key") } } + func testQuickNoteRetryAfterRelaunchRetainsTheOriginalKey() async throws { + let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + defer { try? FileManager.default.removeItem(at: root) } + let account = Account(id: 1, username: "tester", displayName: nil, createdAt: "2026-01-01T00:00:00Z") + func disk() -> NoteRecoveryStore { + NoteRecoveryStore(root: root, server: URL(string: "https://example.com")!, account: account) + } + CreateWireProtocol.reset(statuses: [500, 201]) + let original = NotesStore(recovery: disk()) + original.draft = "Idea" + let first = await original.saveDraft(client: client()) + XCTAssertFalse(first) + let relaunched = NotesStore(recovery: disk()) + XCTAssertEqual(relaunched.draft, "Idea") + let retry = await relaunched.saveDraft(client: client()) + XCTAssertTrue(retry) + XCTAssertEqual(keys.count, 2) + XCTAssertEqual(keys.first, keys.last) + XCTAssertNil(try disk().loadDraft()) + } + func testEveryEntityCreateHasFreshKeyPerAction() async throws { CreateWireProtocol.reset() let client = client() diff --git a/ios/CommandTests/NoteRecoveryPersistenceTests.swift b/ios/CommandTests/NoteRecoveryPersistenceTests.swift new file mode 100644 index 0000000..8752baa --- /dev/null +++ b/ios/CommandTests/NoteRecoveryPersistenceTests.swift @@ -0,0 +1,203 @@ +import XCTest +@testable import Command + +@MainActor +final class NoteRecoveryPersistenceTests: XCTestCase { + private var root: URL! + override func setUp() async throws { + root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + } + override func tearDown() async throws { try? FileManager.default.removeItem(at: root) } + private func recovery(server: String = "https://example.com", id: Int = 1, + created: String = "2026-01-01T00:00:00Z") -> NoteRecoveryStore { + NoteRecoveryStore(root: root, server: URL(string: server)!, + account: Account(id: id, username: "tester", displayName: nil, createdAt: created)) + } + private func editing(_ store: NotesStore, noteId: Int? = 42, hidden: Bool = false) -> (NoteSaver, UUID) { + let owner = UUID() + let saver = store.resumeEditor(saver: NoteSaver(noteId: noteId, text: noteId == nil ? "" : "Saved", hidden: hidden), owner: owner) + return (saver, owner) + } + + func testEveryKeystrokeSurvivesRelaunchWithoutDisappearOrFailedSave() throws { + let disk = recovery(), store = NotesStore(recovery: recovery()) + let (saver, _) = editing(store) + saver.text = "Saved and an unsent sentence" + let relaunched = NotesStore(recovery: disk) + XCTAssertEqual(relaunched.unsavedEdits.first?.text, saver.text) + XCTAssertEqual(relaunched.unsavedEdits.first?.saver.id, saver.id) + XCTAssertEqual(relaunched.unsavedEdits.first?.noteId, 42) + XCTAssertEqual(try disk.loadEdits().edits.count, 1) + } + + func testParkedAndActiveEditorsRecoverTogetherAndDiscardIsDurable() throws { + let disk = recovery(), store = NotesStore(recovery: disk) + let (first, owner) = editing(store, noteId: nil) + first.text = "New offline note" + store.releaseEditor(saver: first, owner: owner, park: true) + let (second, _) = editing(store) + second.text = "Existing offline edit" + let relaunched = NotesStore(recovery: recovery()) + XCTAssertEqual(Set(relaunched.unsavedEdits.map(\.text)), [first.text, second.text]) + relaunched.discardUnsavedEdits() + XCTAssertTrue(try disk.loadEdits().edits.isEmpty) + XCTAssertTrue(NotesStore(recovery: recovery()).unsavedEdits.isEmpty) + } + + func testCloseAndExplicitDiscardRemoveOnlyTheirOwnFile() throws { + let disk = recovery(), store = NotesStore(recovery: disk) + let (saver, owner) = editing(store) + saver.text = "Discarded" + let (other, _) = editing(store, noteId: 43) + other.text = "Still pending" + store.releaseEditor(saver: saver, owner: owner, park: false) + saver.text = "Late callback cannot restore a discarded draft" + XCTAssertEqual(try disk.loadEdits().edits.map(\.text), [other.text]) + } + + func testSuccessfulSaveRemovesRecoveryButLaterTypingPersistsAgain() async throws { + let disk = recovery(), store = NotesStore(recovery: disk) + let (saver, _) = editing(store) + saver.text = "First edit" + let ops = NoteSaver.Ops(create: { _, _, _ in 1 }, update: { _, _, _ in }) + let saved = await saver.flush(using: ops) + XCTAssertTrue(saved) + XCTAssertTrue(try disk.loadEdits().edits.isEmpty) + saver.text = "Second edit" + XCTAssertEqual(try disk.loadEdits().edits.first?.text, "Second edit") + } + + func testUncertainCreateRecoversOriginalPayloadAndKeyThenPatchesLatestText() async throws { + let disk = recovery(), store = NotesStore(recovery: disk) + let (saver, _) = editing(store, noteId: nil) + saver.text = "Original create" + let lost = NoteSaver.Ops(create: { _, _, _ in throw URLError(.networkConnectionLost) }, update: { _, _, _ in }) + let saved = await saver.save(using: lost) + XCTAssertFalse(saved) + saver.text = "Original create plus offline edits" + let relaunched = NotesStore(recovery: recovery()) + let resumed = try XCTUnwrap(relaunched.unsavedEdits.first?.saver) + var calls: [String] = [] + let ops = NoteSaver.Ops(create: { _, body, key in + XCTAssertEqual(key, saver.id) + calls.append("create: " + body) + return 73 + }, update: { id, _, body in + XCTAssertEqual(id, 73) + calls.append("update: " + body) + }) + let ok = await resumed.flush(using: ops) + XCTAssertTrue(ok) + XCTAssertEqual(calls, ["create: Original create", "update: Original create plus offline edits"]) + XCTAssertTrue(try disk.loadEdits().edits.isEmpty) + } + + func testPartialSaveRecoversCreatedIDAndDoesNotCreateAgain() async throws { + let store = NotesStore(recovery: recovery()) + let (saver, _) = editing(store, noteId: nil) + saver.text = "Original" + let ops = NoteSaver.Ops(create: { _, _, _ in + saver.text = "Newer text during create" + return 73 + }, update: { _, _, _ in throw URLError(.notConnectedToInternet) }) + let ok = await saver.flush(using: ops) + XCTAssertFalse(ok) + let relaunched = NotesStore(recovery: recovery()) + let resumed = try XCTUnwrap(relaunched.unsavedEdits.first?.saver) + XCTAssertEqual(resumed.noteId, 73) + XCTAssertEqual(resumed.lastSavedText, "Original") + let retry = NoteSaver.Ops(create: { _, _, _ in XCTFail("must not recreate"); return 99 }, update: { id, _, body in + XCTAssertEqual(id, 73); XCTAssertEqual(body, "Newer text during create") + }) + let saved = await resumed.flush(using: retry) + XCTAssertTrue(saved) + } + + func testDraftRecoversAndClearingItRemovesTheRecoveryCopy() throws { + let disk = recovery(), store = NotesStore(recovery: disk) + store.draft = "A quick thought" + let relaunched = NotesStore(recovery: recovery()) + XCTAssertEqual(relaunched.draft, store.draft) + relaunched.draft = "" + XCTAssertNil(try disk.loadDraft()) + } + + func testAccountServerAndRecreatedAccountAreIsolated() { + let original = NotesStore(recovery: recovery()) + original.draft = "Private capture" + let (saver, _) = editing(original); saver.text = "Private edit" + for disk in [recovery(id: 2), recovery(server: "https://other.example.com"), + recovery(server: "https://example.com/another"), recovery(created: "2026-02-01T00:00:00Z")] { + let other = NotesStore(recovery: disk) + XCTAssertEqual(other.draft, "") + XCTAssertTrue(other.unsavedEdits.isEmpty) + } + original.deactivate() + XCTAssertEqual(NotesStore(recovery: recovery()).draft, "Private capture") + } + + func testOldSessionCompletionCannotEraseReauthenticatedEditorsRecovery() async throws { + let disk = recovery(), original = NotesStore(recovery: disk) + let (oldSaver, _) = editing(original) + oldSaver.text = "Before sign-out" + original.deactivate() + let replacement = NotesStore(recovery: recovery()) + let resumed = try XCTUnwrap(replacement.unsavedEdits.first?.saver) + resumed.text = "New edits after reauthentication" + oldSaver.markSaved("Before sign-out") + original.draft = "A stale quick capture" + XCTAssertEqual(try disk.loadEdits().edits.first?.text, resumed.text) + XCTAssertNil(try disk.loadDraft()) + } + + func testAccountDeletionRemovesRecoveryAndLateChangesCannotRecreateIt() throws { + let disk = recovery(), store = NotesStore(recovery: disk) + store.draft = "Private capture" + let (saver, _) = editing(store); saver.text = "Private edit" + store.deactivate(deleteRecovery: true) + saver.text = "Late editor change"; store.draft = "Late capture change" + XCTAssertFalse(FileManager.default.fileExists(atPath: disk.directory.path)) + } + + func testHiddenEditKeepsItsVeilAcrossRelaunch() throws { + let store = NotesStore(recovery: recovery()) + let (saver, _) = editing(store, hidden: true); saver.text = "Private edit" + let resumed = try XCTUnwrap(NotesStore(recovery: recovery()).unsavedEdits.first?.saver) + XCTAssertTrue(resumed.hidden) + } + + func testCorruptEditDoesNotHideOtherRecoveryFilesOrGetDeleted() throws { + let disk = recovery(), store = NotesStore(recovery: disk) + let (saver, _) = editing(store); saver.text = "Intact" + let corrupt = disk.directory.appendingPathComponent("edit-damaged.json") + try Data("bad json".utf8).write(to: corrupt) + let relaunched = NotesStore(recovery: recovery()) + XCTAssertEqual(relaunched.unsavedEdits.first?.text, "Intact") + XCTAssertNotNil(relaunched.recoveryError) + relaunched.discardUnsavedEdits() + XCTAssertTrue(FileManager.default.fileExists(atPath: corrupt.path)) + } + + func testDiskFailureIsVisibleAndDoesNotPretendRecoverySucceeded() throws { + try FileManager.default.createDirectory(at: root.deletingLastPathComponent(), withIntermediateDirectories: true) + try Data("not a directory".utf8).write(to: root) + let store = NotesStore(recovery: recovery()) + let (saver, _) = editing(store); saver.text = "Keep this in memory" + XCTAssertEqual(saver.text, "Keep this in memory") + XCTAssertNotNil(store.recoveryError) + } + + func testSessionTeardownRetiresStoreAndDropsParkedEditsFromNextAccount() async { + let client = APIClient(baseURL: URL(string: "https://example.invalid")!) + let app = AppState(client: client, noteRecoveryRoot: root) + let previous = app.notes + let saver = NoteSaver(noteId: nil, text: ""); saver.text = "Previous account" + previous.park(saver: saver) + await app.forgetDeletedAccount() + XCTAssertFalse(app.notes === previous) + XCTAssertTrue(app.notes.unsavedEdits.isEmpty) + let created = await previous.create(title: nil, body: "Must not send", client: client) + XCTAssertNil(created) + XCTAssertNil(previous.errorMessage, "retired store must not even try the transport") + } +} diff --git a/ios/CommandTests/ParkedNoteRecoveryTests.swift b/ios/CommandTests/ParkedNoteRecoveryTests.swift index 981c5ee..02bc866 100644 --- a/ios/CommandTests/ParkedNoteRecoveryTests.swift +++ b/ios/CommandTests/ParkedNoteRecoveryTests.swift @@ -8,13 +8,14 @@ private final class RecoveryWireProtocol: URLProtocol { nonisolated(unsafe) static var onGet: (() -> Void)? nonisolated(unsafe) static var onPost: (() -> Void)? nonisolated(unsafe) static var holdPost = false + nonisolated(unsafe) static var returnedHidden = false static let noteJSON = Data(""" {"id":42,"account_id":1,"body":"Server copy","title":"Server copy","title_status":"user", "source":"typed","created_at":"2026-10-01T00:00:00Z","updated_at":"2026-10-01T00:00:00Z"} """.utf8) static func reset() { lock.lock(); defer { lock.unlock() } - gets = []; posts = []; onGet = nil; onPost = nil; holdPost = false + gets = []; posts = []; onGet = nil; onPost = nil; holdPost = false; returnedHidden = false } static func releaseGets(includesNote: Bool) { lock.lock(); let pending = gets; gets = []; lock.unlock() @@ -41,6 +42,8 @@ private final class RecoveryWireProtocol: URLProtocol { } else { respond(Self.noteJSON) } } func respond(_ data: Data) { + let data = Self.returnedHidden + ? Data(String(decoding: data, as: UTF8.self).replacingOccurrences(of: "\"source\":", with: "\"hidden\":true,\"source\":").utf8) : data client?.urlProtocol(self, didReceive: HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: ["Content-Type":"application/json"])!, cacheStoragePolicy: .notAllowed) client?.urlProtocol(self, didLoad: data); client?.urlProtocolDidFinishLoading(self) @@ -59,6 +62,25 @@ final class ParkedNoteRecoveryTests: XCTestCase { let decoder = JSONDecoder(); decoder.keyDecodingStrategy = .convertFromSnakeCase return try decoder.decode(Note.self, from: RecoveryWireProtocol.noteJSON) } + func testHidingAnOfflineEditPersistsItsVeilForRecovery() async throws { + RecoveryWireProtocol.reset(); RecoveryWireProtocol.returnedHidden = true + let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + defer { try? FileManager.default.removeItem(at: root) } + let account = Account(id: 1, username: "tester", displayName: nil, createdAt: "2026-01-01T00:00:00Z") + func disk() -> NoteRecoveryStore { + NoteRecoveryStore(root: root, server: URL(string: "https://example.com")!, account: account) + } + let store = NotesStore(recovery: disk()) + let owner = UUID() + let saver = store.resumeEditor(saver: NoteSaver(noteId: 42, text: "Saved"), owner: owner) + saver.text = "Offline private changes" + let hidden = await store.setHidden(id: 42, hidden: true, client: client()) + XCTAssertTrue(hidden) + store.releaseEditor(saver: saver, owner: owner, park: true) + let restored = try XCTUnwrap(NotesStore(recovery: disk()).unsavedEdits.first?.saver) + XCTAssertTrue(restored.hidden, "review without a server row must not expose a newly hidden note") + } + func testReopeningResumesParkedTextAndIdentityAndReparksSameSaver() { let store = NotesStore(), original = NoteSaver(noteId: 42, text: "Server copy") original.text = "Server copy with offline edits" diff --git a/ios/CommandTests/SessionIsolationTests.swift b/ios/CommandTests/SessionIsolationTests.swift new file mode 100644 index 0000000..7542034 --- /dev/null +++ b/ios/CommandTests/SessionIsolationTests.swift @@ -0,0 +1,143 @@ +import XCTest +@testable import Command + +private final class SessionWireProtocol: URLProtocol { + static let lock = NSLock() + nonisolated(unsafe) static var held: SessionWireProtocol? + nonisolated(unsafe) static var requests: [URLRequest] = [] + nonisolated(unsafe) static var onRequest: (() -> Void)? + static func reset() { lock.withLock { held = nil; requests = []; onRequest = nil } } + override class func canInit(with request: URLRequest) -> Bool { true } + override class func canonicalRequest(for request: URLRequest) -> URLRequest { request } + override func startLoading() { + let callback = Self.lock.withLock { + Self.held = self; Self.requests.append(request); return Self.onRequest + } + callback?() + } + override func stopLoading() {} + static func fail() { + let pending = lock.withLock { held } + pending?.client?.urlProtocol(pending!, didFailWithError: URLError(.networkConnectionLost)) + } + static func respond(status: Int, cookie: String? = nil) { + guard let pending = lock.withLock({ held }) else { return } + var headers = ["Content-Type": "application/json"] + if let cookie { headers["Set-Cookie"] = "command_session=\(cookie); Path=/; HttpOnly" } + let body = status == 401 ? "{\"error\":{\"code\":\"auth_failed\",\"message\":\"Expired\"}}" : """ + {"id":42,"account_id":1,"body":"Idea","title":"Idea","title_status":"user", + "source":"typed","created_at":"2026-10-01T00:00:00Z","updated_at":"2026-10-01T00:00:00Z"} + """ + pending.client?.urlProtocol(pending, didReceive: HTTPURLResponse(url: pending.request.url!, statusCode: status, + httpVersion: nil, headerFields: headers)!, cacheStoragePolicy: .notAllowed) + pending.client?.urlProtocol(pending, didLoad: Data(body.utf8)) + pending.client?.urlProtocolDidFinishLoading(pending) + } +} + +@MainActor +final class SessionIsolationTests: XCTestCase { + private func setup() throws -> (APIClient, HTTPCookieStorage) { + SessionWireProtocol.reset() + let config = URLSessionConfiguration.ephemeral + config.protocolClasses = [SessionWireProtocol.self] + let jar = try XCTUnwrap(config.httpCookieStorage) + let client = APIClient(baseURL: URL(string: "https://session-test.invalid")!, configuration: config) + setCookie("account-a", jar: jar) + return (client, jar) + } + private func setCookie(_ value: String, jar: HTTPCookieStorage) { + jar.setCookie(HTTPCookie(properties: [.domain: "session-test.invalid", .path: "/", + .name: "command_session", .value: value])!) + } + private func held() -> XCTestExpectation { + let started = expectation(description: "request suspended") + SessionWireProtocol.onRequest = { started.fulfill() } + return started + } + private func result(_ client: APIClient) async -> Error? { + do { _ = try await client.createNote(body: "Private account A capture"); return nil } + catch { return error } + } + + func testKeyedRetryNeverSwitchesToNewAccountsCookie() async throws { + let (client, jar) = try setup(), started = held() + let operation = Task { await result(client) } + await fulfillment(of: [started], timeout: 2) + XCTAssertEqual(SessionWireProtocol.requests.first?.value(forHTTPHeaderField: "Cookie"), "command_session=account-a") + SessionWireProtocol.fail() + client.clearSessionCookies() + setCookie("account-b", jar: jar) + let error = await operation.value + XCTAssertEqual((error as? URLError)?.code, .cancelled) + XCTAssertEqual(SessionWireProtocol.requests.count, 1, "no request may be retried under account B") + } + + func testLateResponseCannotReplaceNewAccountsCookieOrReturnOldData() async throws { + let (client, jar) = try setup(), started = held() + let operation = Task { await result(client) } + await fulfillment(of: [started], timeout: 2) + client.clearSessionCookies(); setCookie("account-b", jar: jar) + SessionWireProtocol.respond(status: 201, cookie: "account-a-renewed") + let error = await operation.value + XCTAssertEqual((error as? URLError)?.code, .cancelled) + XCTAssertEqual(jar.cookies?.first(where: { $0.name == "command_session" })?.value, "account-b") + } + + func testCookieChangeFromAnotherClientAlsoInvalidatesOldResponse() async throws { + let (client, jar) = try setup(), started = held() + let operation = Task { await result(client) } + await fulfillment(of: [started], timeout: 2) + // Separate APIClient instances (for example App Intents) share the cookie jar. + setCookie("account-b", jar: jar) + SessionWireProtocol.respond(status: 201, cookie: "account-a-renewed") + let error = await operation.value + XCTAssertEqual((error as? URLError)?.code, .cancelled) + XCTAssertEqual(jar.cookies?.first(where: { $0.name == "command_session" })?.value, "account-b") + } + + func testLateUnauthorizedCannotExpireNewSession() async throws { + let (client, jar) = try setup(), started = held() + let unauthorized = expectation(description: "stale rejection ignored"); unauthorized.isInverted = true + client.onUnauthorized = { _ in unauthorized.fulfill() } + let operation = Task { await result(client) } + await fulfillment(of: [started], timeout: 2) + client.clearSessionCookies(); setCookie("account-b", jar: jar) + SessionWireProtocol.respond(status: 401) + _ = await operation.value + await fulfillment(of: [unauthorized], timeout: 0.1) + } + + func testCurrentSessionStillAcceptsSuccessAndCookieRenewal() async throws { + let (client, jar) = try setup(), started = held() + let operation = Task { await result(client) } + await fulfillment(of: [started], timeout: 2) + SessionWireProtocol.respond(status: 201, cookie: "account-a-renewed") + let error = await operation.value + XCTAssertNil(error) + XCTAssertEqual(jar.cookies?.first(where: { $0.name == "command_session" })?.value, "account-a-renewed") + } + + func testCurrentRejectionCarriesIdentityThatExpiresBeforeQueuedUIHandler() async throws { + let (client, jar) = try setup(), started = held() + let rejected = expectation(description: "current rejection") + let identityBox = IdentityBox() + client.onUnauthorized = { identity in identityBox.set(identity); rejected.fulfill() } + let operation = Task { await result(client) } + await fulfillment(of: [started], timeout: 2) + SessionWireProtocol.respond(status: 401) + _ = await operation.value + await fulfillment(of: [rejected], timeout: 2) + let identity = try XCTUnwrap(identityBox.get()) + XCTAssertTrue(client.isCurrentSession(identity)) + client.clearSessionCookies(); setCookie("account-b", jar: jar) + XCTAssertFalse(client.isCurrentSession(identity), "the queued main-actor handler must ignore the old rejection") + } +} + +private final class IdentityBox: @unchecked Sendable { + private let lock = NSLock() + private var value: APIClient.SessionIdentity? + func set(_ identity: APIClient.SessionIdentity) { lock.withLock { value = identity } } + func get() -> APIClient.SessionIdentity? { lock.withLock { value } } +} diff --git a/state/ASTRA-1002.md b/state/ASTRA-1002.md index 7451c76..1135754 100644 --- a/state/ASTRA-1002.md +++ b/state/ASTRA-1002.md @@ -34,8 +34,8 @@ callbacks at sign-out so they cannot mutate another account's capture state. - Isolated worktree created from the shipped baseline. No edits to main. ## Next -Trace lifecycle and account activation, implement durable recovery, run regression controls, then -select the next customer-visible reliability/workflow gap. +Integrate verified voice and MCP helper commits, verify rendered recovery/relaunch behavior, +compile Catalyst, then push this branch and open a PR. No new item after 12:10; wrap at 12:20. ## In progress — local recovery - Added per-account/server atomic recovery files for editor snapshots and quick-capture text. @@ -51,3 +51,33 @@ select the next customer-visible reliability/workflow gap. Info.plist under ad-hoc signing. The local build invocation now supplies `CODE_SIGNING_ALLOWED=YES CODE_SIGN_IDENTITY=- GENERATE_INFOPLIST_FILE=YES`. - No feature verification claimed yet; compiling and exercising persistence regressions next. + +## Crash recovery — 11:44 EDT +- Recovered own and both helper worktrees after the terminal crash. All source changes survived; + no feature commit had yet been created. Main remains untouched. +- Resumed two helpers only: finish the existing voice race fixes and MCP occurrence-completion fix. + No extra backlog items started. Helpers run no simulators; the unused voice simulator is released. +- Renewed own simulator and DerivedData leases. The simulator registry's adopt command preserves + the dead owner PID; transferred only this run's owned lease to the resumed process after checking + the old owner was gone. Other sessions' leases are untouched. +- OBSERVED: native macOS XCTest harness compiles actual recovery/transport/store sources and runs + 54 tests with 0 failures (3.880 seconds). This is logic/transport evidence, not iOS UI evidence. +- OBSERVED: helper server full suite before crash had 771 passes and 2 failures. Resumed helper + is correcting the production serializer and test fixture, then revalidating. +- Full iOS suite is now running on the single owned simulator, capped at two build jobs. +- Latest operator timing: useful work until 12:25 EDT, then wrap up; absolute stop 13:00/refill. + +## Verified step — 11:54 EDT +- OBSERVED: full iOS simulator suite **300 tests, 0 failures**; xcodebuild TEST SUCCEEDED. + Evidence: `/tmp/command-astra-1002/ios-tests.log`; xcresult under the leased DD + `Logs/Test/Test-Command-2026.10.02_11-47-40--0400.xcresult`. +- OBSERVED: native recovery/transport suite **54 tests, 0 failures**. Discrimination controls + disabled persistence and stale-response protection only in copied harness sources: two tests + then produced six failed assertions. Restored implementations: both passed. Logs in + `/tmp/command-astra-1002/{macos-recovery-tests,recovery-controls,recovery-controls-restored}.log`. +- Implemented durable unsent editor/draft recovery, stable uncertain-create retries across restart, + hidden-state preservation, account-scoped retirement, and transport session identities that + prevent stale retries/responses/401 callbacks from crossing a sign-in boundary. +- UI behavior and Catalyst build remain pending. This evidence does not claim production deployment. +- Latest timing checkpoint: commit each verified step immediately; start nothing new at 12:10, + wrap at 12:20. Absolute stop remains 13:00/reset. From 977c54e4f63ca3f5e8a6f845f5a1046146ab1bb6 Mon Sep 17 00:00:00 2001 From: legitimate-apps <309192374+legitimate-apps@users.noreply.github.com> Date: Fri, 2 Oct 2026 11:50:38 -0400 Subject: [PATCH 03/27] Protect voice captures from stale asynchronous completions --- .../Transcription/RecordingSheet.swift | 15 +- .../Transcription/VoiceCaptureFlow.swift | 57 ++- ios/CommandTests/VoiceCaptureFlowTests.swift | 326 +++++++++++++++++- state/ASTRA-VOICE-1002.md | 51 +++ 4 files changed, 434 insertions(+), 15 deletions(-) create mode 100644 state/ASTRA-VOICE-1002.md diff --git a/ios/Command/Transcription/RecordingSheet.swift b/ios/Command/Transcription/RecordingSheet.swift index 8a956a4..e5b5469 100644 --- a/ios/Command/Transcription/RecordingSheet.swift +++ b/ios/Command/Transcription/RecordingSheet.swift @@ -213,6 +213,8 @@ struct RecordingSheet: View { } private func begin() async { + // A queued Record again task must not revive a sheet that has already been cancelled. + guard !flow.isCancelled, !Task.isCancelled else { return } flow.reset() if requiresPreparedPermission { switch VoiceLaunchPolicy.decision(for: permissionState) { @@ -225,16 +227,19 @@ struct RecordingSheet: View { } return } - guard await recorder.requestPermission() else { phase = .denied; return } + guard let granted = await flow.requestPermission(using: { await recorder.requestPermission() }) else { return } + guard granted else { phase = .denied; return } await startRecording() } private func requestPreparedPermission() async { - guard await recorder.requestPermission() else { phase = .denied; return } + guard let granted = await flow.requestPermission(using: { await recorder.requestPermission() }) else { return } + guard granted else { phase = .denied; return } await startRecording() } private func startRecording() async { + guard !flow.isCancelled, !Task.isCancelled else { return } do { flow.reset() try recorder.start() @@ -255,6 +260,8 @@ struct RecordingSheet: View { } private func stopAndTranscribe() async { + // Stop and the interruption observer can both enqueue this before either task runs. + guard phase == .recording, !flow.isCancelled else { return } guard let url = recorder.stop() else { dismiss(); return } flow.adopt(url) await transcribeKeptRecording() @@ -263,13 +270,15 @@ struct RecordingSheet: View { /// Transcribe the kept recording. The file is NOT deleted here — only once its words are /// committed (saved / used) or the user cancels — so a failure can be retried. private func transcribeKeptRecording() async { + guard phase != .transcribing, !flow.isCancelled else { return } phase = .transcribing + let capture = flow.captureID let transcription = app.transcription let used = await flow.transcribe(immediateUse: useImmediatelyAfterTranscription && onUse != nil) { url in try await transcription.transcribe(fileURL: url, locale: Locale.current.identifier) } // Cancelled mid-transcription: the sheet is already closing; hand nothing on. - guard !flow.isCancelled else { return } + guard !flow.isCancelled, !Task.isCancelled, flow.captureID == capture else { return } if let used, let onUse { onUse(used) dismiss() diff --git a/ios/Command/Transcription/VoiceCaptureFlow.swift b/ios/Command/Transcription/VoiceCaptureFlow.swift index dec2bd1..9297754 100644 --- a/ios/Command/Transcription/VoiceCaptureFlow.swift +++ b/ios/Command/Transcription/VoiceCaptureFlow.swift @@ -19,7 +19,18 @@ import Observation final class VoiceCaptureFlow { /// The finished recording, kept until it's committed or discarded. private(set) var audioURL: URL? - var transcript = "" { didSet { if transcript != oldValue { noteCreate.reset() } } } + var transcript = "" { + didSet { + if transcript != oldValue { + reviewRevision = UUID() + noteCreate.reset() + } + } + } + /// Changes whenever another capture replaces this one, even if it reuses a file URL. + private(set) var captureID = UUID() + private var reviewRevision = UUID() + private var transcriptionAttempt = UUID() private var noteCreate = CreateAttempt() private struct NotePayload: Encodable { let text: String; let engine: String } private(set) var engineUsed = "" @@ -37,6 +48,7 @@ final class VoiceCaptureFlow { /// A new recording is starting: drop the previous one and any leftover review state. func reset() { + captureID = UUID() discardAudio() noteCreate.reset() transcript = "" @@ -46,10 +58,23 @@ final class VoiceCaptureFlow { isCancelled = false } + /// A permission prompt can outlive the sheet. Nil means the caller must not start recording + /// or change its UI because this capture was cancelled or replaced while the prompt was up. + func requestPermission(using request: () async -> Bool) async -> Bool? { + guard !isCancelled, !Task.isCancelled else { return nil } + let capture = captureID + let granted = await request() + guard !isCancelled, !Task.isCancelled, captureID == capture else { return nil } + return granted + } + /// The recorder finished; keep its file for transcription (and any retry of it). func adopt(_ url: URL) { if let old = audioURL, old != url { removeFile(old) } - if audioURL != url { noteCreate.reset() } + if audioURL != url { + captureID = UUID() + noteCreate.reset() + } audioURL = url } @@ -59,10 +84,14 @@ final class VoiceCaptureFlow { /// while transcribing (the result is dropped; nothing is handed on). func transcribe(immediateUse: Bool, using transcribe: (URL) async throws -> (text: String, engine: String)) async -> String? { - guard let url = audioURL, !isCancelled else { return nil } + guard let url = audioURL, !isCancelled, !Task.isCancelled else { return nil } + let capture = captureID, revision = reviewRevision + let attempt = UUID() + transcriptionAttempt = attempt do { let result = try await transcribe(url) - guard !isCancelled else { return nil } + guard !isCancelled, !Task.isCancelled, captureID == capture, + reviewRevision == revision, transcriptionAttempt == attempt else { return nil } transcript = result.text engineUsed = result.engine errorMessage = nil @@ -72,23 +101,30 @@ final class VoiceCaptureFlow { return cleaned } } catch { - guard !isCancelled else { return nil } + guard !isCancelled, !Task.isCancelled, captureID == capture, + reviewRevision == revision, transcriptionAttempt == attempt else { return nil } errorMessage = (error as? LocalizedError)?.errorDescription ?? error.localizedDescription transcriptionFailed = true } return nil } - /// Save the reviewed transcript as a note via `save` (true on success). The recording is - /// released only once the note is committed; on failure it's kept and the error shown. + /// Save the reviewed transcript. Returns true only when the current review was committed and + /// may close. Completion of an older save must not discard newer edits or another recording. + /// A failed current save keeps the recording and shows the error for retry. func saveNote(using save: (_ text: String, _ engine: String, _ key: String) async -> String?) async -> Bool { - guard !saving else { return false } + guard !saving, !isCancelled, !Task.isCancelled else { return false } + let capture = captureID, revision = reviewRevision + let text = transcript saving = true defer { saving = false } do { let engine = engineUsed.isEmpty ? "sfspeech" : engineUsed - let key = try noteCreate.key(for: NotePayload(text: transcript, engine: engine)) - if let failure = await save(transcript, engine, key) { + let key = try noteCreate.key(for: NotePayload(text: text, engine: engine)) + let failure = await save(text, engine, key) + guard !isCancelled, !Task.isCancelled, captureID == capture, + reviewRevision == revision else { return false } + if let failure { errorMessage = failure return false } @@ -108,6 +144,7 @@ final class VoiceCaptureFlow { /// The user cancelled (or the sheet went away): drop the recording and suppress any in-flight /// transcription's result. func cancel() { + captureID = UUID() isCancelled = true discardAudio() } diff --git a/ios/CommandTests/VoiceCaptureFlowTests.swift b/ios/CommandTests/VoiceCaptureFlowTests.swift index 4989d62..da53e90 100644 --- a/ios/CommandTests/VoiceCaptureFlowTests.swift +++ b/ios/CommandTests/VoiceCaptureFlowTests.swift @@ -11,7 +11,16 @@ import XCTest @testable import Command @MainActor -private final class Gate { var held: CheckedContinuation? } +private final class Gate { + var held: CheckedContinuation? { + didSet { ready?.resume(); ready = nil } + } + private var ready: CheckedContinuation? + + func waitUntilHeld() async { + if held == nil { await withCheckedContinuation { ready = $0 } } + } +} @MainActor final class VoiceCaptureFlowTests: XCTestCase { @@ -88,7 +97,7 @@ final class VoiceCaptureFlowTests: XCTestCase { return ("send this to the assistant", "sfspeech") } } - for _ in 0..<200 where gate.held == nil { await Task.yield() } + await gate.waitUntilHeld() flow.cancel() // the user hit Cancel while "Transcribing…" gate.held?.resume() @@ -99,6 +108,319 @@ final class VoiceCaptureFlowTests: XCTestCase { XCTAssertEqual(removed, [audio]) } + func test_saveCompletionAfterTranscriptEdit_keepsEditedReviewAndAudio() async { + let flow = makeFlow() + flow.adopt(audio) + flow.transcript = "Original words" + let gate = Gate() + let pending = Task { + await flow.saveNote { text, _, _ in + XCTAssertEqual(text, "Original words") + await withCheckedContinuation { gate.held = $0 } + return nil + } + } + await gate.waitUntilHeld() + XCTAssertNotNil(gate.held) + flow.transcript = "Original words plus a new thought" + gate.held?.resume() + + let dismiss = await pending.value + XCTAssertFalse(dismiss, "saving older words must not dismiss newer edits") + XCTAssertEqual(flow.transcript, "Original words plus a new thought") + XCTAssertEqual(flow.audioURL, audio) + XCTAssertTrue(removed.isEmpty) + XCTAssertFalse(flow.saving) + } + + func test_saveCompletionAfterNewRecording_doesNotReleaseNewAudio() async { + let flow = makeFlow() + flow.adopt(audio) + flow.transcript = "First recording" + let gate = Gate() + let pending = Task { + await flow.saveNote { _, _, _ in + await withCheckedContinuation { gate.held = $0 } + return nil + } + } + await gate.waitUntilHeld() + XCTAssertNotNil(gate.held) + flow.reset() + let nextAudio = URL(fileURLWithPath: "/tmp/new-command-recording.m4a") + flow.adopt(nextAudio) + flow.transcript = "Second recording" + gate.held?.resume() + + let dismiss = await pending.value + XCTAssertFalse(dismiss) + XCTAssertEqual(flow.audioURL, nextAudio) + XCTAssertEqual(flow.transcript, "Second recording") + XCTAssertEqual(removed, [audio]) + } + + func test_saveFailureAfterNewRecording_doesNotShowOldError() async { + let flow = makeFlow() + flow.adopt(audio) + flow.transcript = "First recording" + let gate = Gate() + let pending = Task { + await flow.saveNote { _, _, _ in + await withCheckedContinuation { gate.held = $0 } + return "Old request failed" + } + } + await gate.waitUntilHeld() + XCTAssertNotNil(gate.held) + flow.reset() + flow.adopt(URL(fileURLWithPath: "/tmp/new-command-recording.m4a")) + gate.held?.resume() + + let dismiss = await pending.value + XCTAssertFalse(dismiss) + XCTAssertNil(flow.errorMessage) + } + + func test_transcriptionAfterCancelAndReset_neverHandsOnOldWords() async { + let flow = makeFlow() + flow.adopt(audio) + let gate = Gate() + let pending = Task { + await flow.transcribe(immediateUse: true) { _ in + await withCheckedContinuation { gate.held = $0 } + return ("Old assistant request", "sfspeech") + } + } + await gate.waitUntilHeld() + XCTAssertNotNil(gate.held) + flow.cancel() + flow.reset() + let nextAudio = URL(fileURLWithPath: "/tmp/new-command-recording.m4a") + flow.adopt(nextAudio) + flow.transcript = "Current review" + gate.held?.resume() + + let used = await pending.value + XCTAssertNil(used) + XCTAssertEqual(flow.transcript, "Current review") + XCTAssertEqual(flow.audioURL, nextAudio) + XCTAssertEqual(removed, [audio]) + } + + func test_transcriptionAfterResetWithReusedURL_cannotCommitOldCapture() async { + let flow = makeFlow() + flow.adopt(audio) + let gate = Gate() + let pending = Task { + await flow.transcribe(immediateUse: true) { _ in + await withCheckedContinuation { gate.held = $0 } + return ("Old recording at the same path", "sfspeech") + } + } + await gate.waitUntilHeld() + flow.reset() + flow.adopt(audio) + gate.held?.resume() + let used = await pending.value + + XCTAssertNil(used) + XCTAssertEqual(flow.transcript, "") + XCTAssertEqual(flow.audioURL, audio) + XCTAssertEqual(removed, [audio], "only the discarded old capture may be removed") + } + + func test_transcriptionFailureAfterReset_doesNotCorruptCurrentReview() async { + let flow = makeFlow() + flow.adopt(audio) + let gate = Gate() + let pending = Task { + await flow.transcribe(immediateUse: false) { _ in + await withCheckedContinuation { gate.held = $0 } + throw URLError(.cannotDecodeContentData) + } + } + await gate.waitUntilHeld() + XCTAssertNotNil(gate.held) + flow.reset() + flow.adopt(URL(fileURLWithPath: "/tmp/new-command-recording.m4a")) + _ = await flow.transcribe(immediateUse: false) { _ in ("Current review", "parakeet-v3") } + gate.held?.resume() + _ = await pending.value + + XCTAssertNil(flow.errorMessage) + XCTAssertFalse(flow.transcriptionFailed) + XCTAssertEqual(flow.transcript, "Current review") + XCTAssertEqual(flow.engineUsed, "parakeet-v3") + } + + func test_cancelDuringSave_doesNotRequestDismissalOrAcceptAnotherSave() async { + let flow = makeFlow() + flow.adopt(audio) + flow.transcript = "Words" + let gate = Gate() + let pending = Task { + await flow.saveNote { _, _, _ in + await withCheckedContinuation { gate.held = $0 } + return nil + } + } + await gate.waitUntilHeld() + XCTAssertNotNil(gate.held) + flow.cancel() + gate.held?.resume() + let dismiss = await pending.value + XCTAssertFalse(dismiss) + var saveCalled = false + _ = await flow.saveNote { _, _, _ in saveCalled = true; return nil } + XCTAssertFalse(saveCalled) + } + + func test_supersededTranscriptionForSameAudio_doesNotReplaceNewResult() async { + let flow = makeFlow() + flow.adopt(audio) + // Keep the review revision unchanged when the newer attempt completes. This verifies + // attempt identity, independently of protection against changed transcript text. + flow.transcript = "Latest attempt" + let gate = Gate() + let pending = Task { + await flow.transcribe(immediateUse: true) { _ in + await withCheckedContinuation { gate.held = $0 } + return ("Older attempt", "sfspeech") + } + } + await gate.waitUntilHeld() + _ = await flow.transcribe(immediateUse: false) { _ in ("Latest attempt", "parakeet-v3") } + gate.held?.resume() + let used = await pending.value + + XCTAssertNil(used) + XCTAssertEqual(flow.transcript, "Latest attempt") + XCTAssertEqual(flow.engineUsed, "parakeet-v3") + XCTAssertEqual(flow.audioURL, audio) + XCTAssertTrue(removed.isEmpty) + } + + func test_cancelledTranscriptionTask_keepsAudioAndDoesNotHandOnWords() async { + let flow = makeFlow() + flow.adopt(audio) + let gate = Gate() + let pending = Task { + await flow.transcribe(immediateUse: true) { _ in + await withCheckedContinuation { gate.held = $0 } + return ("Cancelled request", "sfspeech") + } + } + await gate.waitUntilHeld() + pending.cancel() + gate.held?.resume() + let used = await pending.value + + XCTAssertNil(used) + XCTAssertEqual(flow.transcript, "") + XCTAssertEqual(flow.audioURL, audio) + XCTAssertTrue(removed.isEmpty) + } + + func test_permissionPromptAfterCancellation_doesNotAuthorizeRecording() async { + let flow = makeFlow() + let gate = Gate() + let pending = Task { + await flow.requestPermission { + await withCheckedContinuation { gate.held = $0 } + return true + } + } + await gate.waitUntilHeld() + flow.cancel() + gate.held?.resume() + let granted = await pending.value + XCTAssertNil(granted) + XCTAssertTrue(flow.isCancelled) + } + + func test_permissionPromptAfterNewCapture_doesNotChangeNewCapture() async { + let flow = makeFlow() + let gate = Gate() + let pending = Task { + await flow.requestPermission { + await withCheckedContinuation { gate.held = $0 } + return false + } + } + await gate.waitUntilHeld() + flow.reset() + gate.held?.resume() + let granted = await pending.value + XCTAssertNil(granted, "an old permission result must not change a new sheet phase") + } + + func test_currentPermissionDecision_isReturnedToTheSheet() async { + let flow = makeFlow() + let denied = await flow.requestPermission { false } + XCTAssertEqual(denied, false) + let granted = await flow.requestPermission { true } + XCTAssertEqual(granted, true) + } + + func test_transcriptionCompletionAfterReviewEdit_preservesTypedWords() async { + let flow = makeFlow() + flow.adopt(audio) + let gate = Gate() + let pending = Task { + await flow.transcribe(immediateUse: true) { _ in + await withCheckedContinuation { gate.held = $0 } + return ("Recognized words", "sfspeech") + } + } + await gate.waitUntilHeld() + flow.transcript = "My corrected words" + gate.held?.resume() + let used = await pending.value + + XCTAssertNil(used) + XCTAssertEqual(flow.transcript, "My corrected words") + XCTAssertEqual(flow.audioURL, audio) + XCTAssertTrue(removed.isEmpty) + } + + func test_saveCompletionAfterEditAndRevert_preservesNewReview() async { + let flow = makeFlow() + flow.adopt(audio) + flow.transcript = "Original words" + let gate = Gate() + let pending = Task { + await flow.saveNote { _, _, _ in + await withCheckedContinuation { gate.held = $0 } + return nil + } + } + await gate.waitUntilHeld() + flow.transcript = "Changed words" + flow.transcript = "Original words" + gate.held?.resume() + let dismiss = await pending.value + + XCTAssertFalse(dismiss) + XCTAssertEqual(flow.audioURL, audio) + XCTAssertTrue(removed.isEmpty) + } + + func test_cancelledPermissionTask_doesNotAuthorizeRecording() async { + let flow = makeFlow() + let gate = Gate() + let pending = Task { + await flow.requestPermission { + await withCheckedContinuation { gate.held = $0 } + return true + } + } + await gate.waitUntilHeld() + pending.cancel() + gate.held?.resume() + let granted = await pending.value + XCTAssertNil(granted) + } + func test_immediateUse_returnsCleanedTextAndReleasesAudio() async { let flow = makeFlow() flow.adopt(audio) diff --git a/state/ASTRA-VOICE-1002.md b/state/ASTRA-VOICE-1002.md new file mode 100644 index 0000000..66ae9aa --- /dev/null +++ b/state/ASTRA-VOICE-1002.md @@ -0,0 +1,51 @@ +# Voice capture reliability — 2026-10-02 + +Owned branch: `astra/voice-reliability-1002`, baseline `47170c2`. +Scope: `VoiceCaptureFlow`, `RecordingSheet`, and `VoiceCaptureFlowTests`. +No release, deployment, push, simulator, or emulator was performed by this helper. + +## Finished + +A suspended save previously dismissed newer transcript edits and deleted whichever recording +was current when its response arrived. A suspended transcription checked only cancellation, +which a new recording clears. A microphone permission callback could start recording after Cancel. +These were selected because lost capture and unintended assistant submissions violate the app's +fast, reliable capture promise. + +- Bind save completion to capture identity and review revision. Older completions retain current + audio/edits, do not dismiss, and do not replace the current error state. +- Bind transcription completion to capture, review revision, and attempt identity; cancellation, + replacement, and newer attempts suppress stale text, errors, and immediate-use callbacks. +- Gate permission results and recording starts against cancellation and capture replacement. + A queued Record again task cannot reset a cancelled sheet. Duplicate Stop/interruption tasks + and transcription retries are guarded by sheet phase. +- Added deterministic suspended-operation tests. Gates await the continuation being held rather + than relying on sleeps. Preserve existing failed-save/retry and idempotency controls. + +## Observed evidence + +Native macOS XCTest compiles the actual production `VoiceCaptureFlow.swift`, `CreateAttempt.swift`, +and `AssistantSurfaceLogic.swift`, with the actual `VoiceCaptureFlowTests.swift`, in a temporary +no-dependency SwiftPM harness. It uses Swift 5.10, matching `ios/project.yml`, macOS 14 minimum, +and one build job. Artifacts are in a leased external DerivedData directory: +`/Volumes/Crucial X8/DerivedData/command-astra-voice-1002-voice-tests-3/VoiceFlowHarness`. + +Command: `swift test --package-path --jobs 1`. + +Fixed source: **20 tests, 0 failures**. Log: `/tmp/command-voice-native-fixed-1002.log`. + +Discriminating control: replace only the flow source with `git show 47170c2:ios/Command/Transcription/VoiceCaptureFlow.swift` +and omit the four tests calling the newly introduced permission API. **16 tests, 35 assertion +failures across 11 methods; all five preexisting controls pass**. Log: +`/tmp/command-voice-native-baseline-1002.log`. Restored the fixed source and all 20 tests and reran +successfully afterward. `git diff --check` passes. All three voice helper DerivedData leases +(including the two inherited from the interrupted helper) were released after testing. + +## Limits and exact next step + +OBSERVED: state-machine callbacks, retained audio ownership, idempotency, and cancellation under +native XCTest. ASSUMED / not device-tested by this helper: actual microphone permission sheets, +AVAudioSession timing, rendered sheet behavior, real transcription engines, and server requests. +The integrating session owns the single permitted simulator and the full iOS build/test gate. +Cherry-pick this branch's commit, run that integration gate, then record its actual result in +`state/ASTRA-1002.md`; do not imply that host XCTest proves a device microphone flow. From 0d083a5bd38b8018eb7f02881b9e11dc974bff7e Mon Sep 17 00:00:00 2001 From: legitimate-apps <309192374+legitimate-apps@users.noreply.github.com> Date: Fri, 2 Oct 2026 11:56:39 -0400 Subject: [PATCH 04/27] Record passing iOS recovery and voice verification --- state/ASTRA-1002.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/state/ASTRA-1002.md b/state/ASTRA-1002.md index 1135754..9e24a92 100644 --- a/state/ASTRA-1002.md +++ b/state/ASTRA-1002.md @@ -81,3 +81,15 @@ compile Catalyst, then push this branch and open a PR. No new item after 12:10; - UI behavior and Catalyst build remain pending. This evidence does not claim production deployment. - Latest timing checkpoint: commit each verified step immediately; start nothing new at 12:10, wrap at 12:20. Absolute stop remains 13:00/reset. + +## Verified voice integration — 11:57 EDT +- Integrated `977c54e` (helper source commit `2ade749`): stale permission, transcription and save + completions cannot revive cancelled capture or discard newer review/audio. +- OBSERVED: full iOS app compiled and all **20 voice XCTest cases passed**, no failures. + Evidence: `/tmp/command-astra-1002/ios-voice-tests.log`, xcresult + `Logs/Test/Test-Command-2026.10.02_11-54-55--0400.xcresult` in the leased DD. +- Helper native controls: original implementation failed 35 assertions across 11 methods; + restored fixed source passed all 20 cases. Details in `state/ASTRA-VOICE-1002.md`. +- Actual microphone prompts/audio hardware remain outside this verification claim. +- Recovery and voice commits are pushed to the remote branch. MCP integration and rendered + relaunch check are next; no new feature scope is being opened. From ededd4b8b457886919beb95f0abeac305256c5f2 Mon Sep 17 00:00:00 2001 From: legitimate-apps <309192374+legitimate-apps@users.noreply.github.com> Date: Fri, 2 Oct 2026 11:54:50 -0400 Subject: [PATCH 05/27] Keep completion facts from hidden assignments private --- server/src/command/core/activities.py | 9 +++++++++ server/tests/test_activities.py | 16 ++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/server/src/command/core/activities.py b/server/src/command/core/activities.py index 395996f..45a26b5 100644 --- a/server/src/command/core/activities.py +++ b/server/src/command/core/activities.py @@ -424,6 +424,14 @@ def log_completion( ).fetchone() if existing is not None: return get(conn, account_id, int(existing["id"])) + # A generated completion copies private assignment content, so inherit its veil. + # Keep this at the shared completion boundary for whole-series and per-day writes. + parent = conn.execute( + "SELECT hidden FROM assignments WHERE id = ? AND account_id = ?", + (assignment_id, account_id), + ).fetchone() + if parent is None: + raise NotFound(f"No assignment with id {assignment_id}.") return create( conn, account_id, @@ -433,4 +441,5 @@ def log_completion( assignment_id=assignment_id, occurrence_date=occurrence_date, source="assignment_completion", + hidden=bool(parent["hidden"]), ) diff --git a/server/tests/test_activities.py b/server/tests/test_activities.py index 42cfbe7..fafc949 100644 --- a/server/tests/test_activities.py +++ b/server/tests/test_activities.py @@ -223,3 +223,19 @@ def test_activities_permission_gate(conn: sqlite3.Connection) -> None: with pytest.raises(PermissionDenied): P.require(conn, aid, "activities", "delete") + + +@pytest.mark.parametrize("occurrence_date", [None, "2026-10-02"]) +def test_hidden_assignment_completion_inherits_visibility(conn: sqlite3.Connection, occurrence_date) -> None: + aid = _acct(conn) + a = A.create(conn, aid, title="Private routine", hidden=True, schedule_kind="routine", + rrule="FREQ=DAILY", scheduled_start="2026-10-01T09:00:00Z") + if occurrence_date is None: + A.set_status(conn, aid, a.id, "done") + else: + A.set_occurrence_status(conn, aid, a.id, occurrence_date, "done") + assert ACT.search(conn, aid, assignment_id=a.id)[0] == [] + facts = ACT.search(conn, aid, assignment_id=a.id, include_hidden=True)[0] + assert len(facts) == 1 and facts[0].hidden + with pytest.raises(NotFound): + ACT.get_for_agent(conn, aid, facts[0].id, include_hidden=False) From dc72efe67e5d9e398a325f99e7571d72dd3a5617 Mon Sep 17 00:00:00 2001 From: legitimate-apps <309192374+legitimate-apps@users.noreply.github.com> Date: Fri, 2 Oct 2026 11:59:25 -0400 Subject: [PATCH 06/27] Complete individual recurring occurrences through assistant tools --- docs/mcp/MCP-GUIDE.md | 13 ++++ server/src/command/core/agent/tools.py | 16 +++- server/src/command/core/assignments.py | 20 ++++- server/src/command/mcp/tools/assignments.py | 13 +++- server/tests/test_agent_workflow_tools.py | 13 ++++ server/tests/test_assignments.py | 45 +++++++++++ server/tests/test_mcp_tools_end_to_end.py | 83 +++++++++++++++++++++ server/tests/test_occurrence_overrides.py | 20 +++++ state/ASTRA-MCP-1002.md | 77 +++++++++++++++++++ 9 files changed, 294 insertions(+), 6 deletions(-) create mode 100644 state/ASTRA-MCP-1002.md diff --git a/docs/mcp/MCP-GUIDE.md b/docs/mcp/MCP-GUIDE.md index d51d91c..f4ce785 100644 --- a/docs/mcp/MCP-GUIDE.md +++ b/docs/mcp/MCP-GUIDE.md @@ -240,6 +240,19 @@ get logged: (assignment, occurrence), so re-completing never double-logs. Don't *also* `activities_log` a completion — it's already recorded. +For "I did today's walk", call `assignments_calendar` and pass that occurrence's +`occurrence_date` to `assignments_set_status` along with `assignment_id` and +`status: "done"`. This changes only that occurrence; tomorrow's walk stays pending. +The date is the **original schedule key** (`YYYY-MM-DD`), even when a reschedule +moves the occurrence onto another day. Copy `occurrence_date`, never derive it +from `occurs_at`. Invalid or nonexistent schedule dates are rejected without +recording a completion. Use `status: "skipped"` for a single missed occurrence. +Omitting `occurrence_date` retains whole-assignment/whole-series behavior, so do +that only when the operator means the entire series. Per-occurrence calls return +`assignment_id`, `occurrence_date` and the applied `status`; whole-series calls +return the assignment. Reopening an occurrence changes the plan but preserves +the existing completion fact; completing it again does not duplicate that fact. + So the log is *complete*: planned-and-done **and** out-of-the-blue both land in it. "Didn't do it" is the **absence** of an activity — record it on the plan with the `skipped` status, not as an activity. diff --git a/server/src/command/core/agent/tools.py b/server/src/command/core/agent/tools.py index 7333500..22487d1 100644 --- a/server/src/command/core/agent/tools.py +++ b/server/src/command/core/agent/tools.py @@ -208,12 +208,24 @@ def update_assignment( @_guard -def set_assignment_status(ctx: RunContext[AgentDeps], assignment_id: int, status: str) -> str: - """Set an assignment's status (todo|scheduled|in_progress|done|blocked|cancelled).""" +def set_assignment_status( + ctx: RunContext[AgentDeps], assignment_id: int, status: str, occurrence_date: str | None = None, +) -> str: + """Set status (todo|scheduled|in_progress|done|blocked|cancelled|skipped). For one recurring + occurrence, pass occurrence_date (YYYY-MM-DD) from get_calendar: the ORIGINAL key, even + after rescheduling, not the date of occurs_at. Omitting it changes the entire assignment + or recurring series. 'done' logs a deduplicated completion; 'skipped' logs no activity.""" with _conn(ctx) as conn: assignments_core.get_for_agent( conn, ctx.deps.account_id, assignment_id, include_hidden=ctx.deps.allow_hidden ) + if occurrence_date is not None: + assignments_core.set_occurrence_status( + conn, ctx.deps.account_id, assignment_id, occurrence_date, status + ) + return json.dumps({ + "assignment_id": assignment_id, "occurrence_date": occurrence_date, "status": status, + }) return _dump(assignments_core.set_status(conn, ctx.deps.account_id, assignment_id, status)) diff --git a/server/src/command/core/assignments.py b/server/src/command/core/assignments.py index 152eb86..9936dc0 100644 --- a/server/src/command/core/assignments.py +++ b/server/src/command/core/assignments.py @@ -936,12 +936,18 @@ def _is_occurrence_date(a: Assignment, occurrence_date: str) -> bool: d = datetime.fromisoformat(occurrence_date).date() except (ValueError, TypeError): return False - zone = _zone(a.timezone) + if d.isoformat() != occurrence_date: + return False + # Legacy schedules can retain a fixed UTC offset without an IANA zone. Match the + # calendar's actual date key in that same zone, and avoid date arithmetic overflowing + # for otherwise valid boundary dates such as 0001-01-01 or 9999-12-31. + zone = _zone(a.timezone) or (_parse_dt(a.scheduled_start).tzinfo if a.scheduled_start else UTC) day_anchor = datetime(d.year, d.month, d.day, tzinfo=zone or UTC) - margin = timedelta(hours=36) return any( t[0].date().isoformat() == occurrence_date - for t in _original_instants(a, day_anchor - margin, day_anchor + timedelta(days=1) + margin) + for t in _original_instants( + a, day_anchor, day_anchor.replace(hour=23, minute=59, second=59, microsecond=999999) + ) ) @@ -956,6 +962,14 @@ def set_occurrence_status( current = get(conn, account_id, assignment_id) # ownership if status not in VALID_STATUS: raise ValidationError(f"status must be one of {sorted(VALID_STATUS)}.") + # The key identifies a real ORIGINAL schedule date, even after a reschedule moves its + # display time to a different day. Reject typos before writing a status or a completion + # fact: an arbitrary date must not invent work that never appeared in the plan. + if not _is_occurrence_date(current, occurrence_date): + raise NotFound( + f"No occurrence of this assignment on {occurrence_date}.", + hint="Use occurrence_date from the calendar, including for rescheduled occurrences.", + ) prior = conn.execute( "SELECT status FROM occurrence_status WHERE assignment_id = ? AND occurrence_date = ?", (assignment_id, occurrence_date), diff --git a/server/src/command/mcp/tools/assignments.py b/server/src/command/mcp/tools/assignments.py index ad3e81e..54dc648 100644 --- a/server/src/command/mcp/tools/assignments.py +++ b/server/src/command/mcp/tools/assignments.py @@ -236,6 +236,9 @@ def work(conn: sqlite3.Connection, account_id: int) -> dict[str, Any]: name="assignments_set_status", description=( "Set an assignment's status (todo|scheduled|in_progress|done|blocked|cancelled|skipped). " + "For one occurrence, pass occurrence_date (YYYY-MM-DD) from assignments_calendar; " + "use its original key even when rescheduled, never the date of occurs_at. " + "Omit occurrence_date only to change the entire assignment/recurring series. " "Setting 'done' auto-logs a completion activity (deduped); 'skipped' marks it not-done." ), annotations=ToolAnnotations( @@ -247,13 +250,21 @@ def work(conn: sqlite3.Connection, account_id: int) -> dict[str, Any]: ), ) async def assignments_set_status( - assignment_id: int, status: str, include_hidden: bool = False + assignment_id: int, status: str, include_hidden: bool = False, + occurrence_date: str | None = None, ) -> dict[str, Any]: def work(conn: sqlite3.Connection, account_id: int) -> dict[str, Any]: permissions.require(conn, account_id, "assignments", "update") assignments_core.get_for_agent( conn, account_id, assignment_id, include_hidden=include_hidden ) + if occurrence_date is not None: + assignments_core.set_occurrence_status( + conn, account_id, assignment_id, occurrence_date, status + ) + return { + "assignment_id": assignment_id, "occurrence_date": occurrence_date, "status": status, + } return assignments_core.set_status(conn, account_id, assignment_id, status).model_dump() return await run_for_account(settings.db_path, work) diff --git a/server/tests/test_agent_workflow_tools.py b/server/tests/test_agent_workflow_tools.py index f6a0423..b4c4f2b 100644 --- a/server/tests/test_agent_workflow_tools.py +++ b/server/tests/test_agent_workflow_tools.py @@ -191,3 +191,16 @@ def test_read_attachment_truncates_long_text(wired) -> None: conn.commit() out = json.loads(T.read_attachment(ctx, att.id, max_chars=100)) assert out["truncated"] is True and len(out["content"]) == 100 + + +def test_complete_one_occurrence_without_finishing_the_routine(wired) -> None: + ctx, conn, aid = wired + a = A.create(conn, aid, title="Daily walk", schedule_kind="routine", rrule="FREQ=DAILY", + scheduled_start="2026-10-01T09:00:00Z") + conn.commit() + result = json.loads(T.set_assignment_status(ctx, a.id, "done", occurrence_date="2026-10-02")) + assert result == {"assignment_id": a.id, "occurrence_date": "2026-10-02", "status": "done"} + assert A.get(conn, aid, a.id).status == "todo" + cal = A.calendar(conn, aid, "2026-10-01T00:00:00Z", "2026-10-04T00:00:00Z") + assert [o.status for o in cal] == ["todo", "done", "todo"] + assert json.loads(T.set_assignment_status(ctx, a.id, "cancelled"))["status"] == "cancelled" diff --git a/server/tests/test_assignments.py b/server/tests/test_assignments.py index 6ff14b3..ca26abe 100644 --- a/server/tests/test_assignments.py +++ b/server/tests/test_assignments.py @@ -359,3 +359,48 @@ def test_archived_assignment_hidden_from_delegatee(conn: sqlite3.Connection) -> assert [x.id for x in delegatee_access.my_assignments(conn, aid, helper.id)] == [a.id] A.set_archived(conn, aid, a.id, True) assert delegatee_access.my_assignments(conn, aid, helper.id) == [] + + +@pytest.mark.parametrize("occurrence_date", [ + "not-a-date", "2026-06-14", "2026-06-16", "2026-06-22", "2026-06-15T09:00:00Z", + "0001-01-01", "9999-12-31", +]) +def test_occurrence_status_rejects_nonexistent_dates_without_logging( + conn: sqlite3.Connection, occurrence_date: str, +) -> None: + aid = _acct(conn) + a = A.create( + conn, aid, title="Monday check-in", schedule_kind="routine", + rrule="FREQ=WEEKLY;BYDAY=MO;COUNT=1", scheduled_start="2026-06-15T09:00:00Z", + ) + with pytest.raises(NotFound, match="No occurrence"): + A.set_occurrence_status(conn, aid, a.id, occurrence_date, "done") + assert conn.execute("SELECT COUNT(*) FROM occurrence_status").fetchone()[0] == 0 + assert conn.execute("SELECT COUNT(*) FROM activities").fetchone()[0] == 0 + assert A.get(conn, aid, a.id).status == "todo" + + +def test_occurrence_status_allows_each_day_of_a_multiday_one_off(conn: sqlite3.Connection) -> None: + aid = _acct(conn) + a = A.create( + conn, aid, title="Conference", + scheduled_start="2026-06-15T09:00:00Z", scheduled_end="2026-06-17T17:00:00Z", + ) + A.set_occurrence_status(conn, aid, a.id, "2026-06-16", "skipped") + cal = A.calendar(conn, aid, "2026-06-15T00:00:00Z", "2026-06-18T00:00:00Z") + assert [o.status for o in cal] == ["todo", "skipped", "todo"] + + +@pytest.mark.parametrize(("start", "timezone", "key"), [ + ("2026-10-02T00:15:00+14:00", None, "2026-10-02"), + ("2026-10-02T23:45:00-12:00", None, "2026-10-02"), + ("2026-10-31T09:00:00-04:00", "America/New_York", "2026-11-02"), +]) +def test_occurrence_status_uses_calendar_local_key(conn, start, timezone, key) -> None: + aid = _acct(conn) + a = A.create(conn, aid, title="Local routine", schedule_kind="routine", rrule="FREQ=DAILY", + scheduled_start=start, timezone=timezone) + A.set_occurrence_status(conn, aid, a.id, key, "done") + cal = A.calendar(conn, aid, "2026-10-01T00:00:00Z", "2026-11-04T00:00:00Z") + done = [o.occurrence_date for o in cal if o.status == "done"] + assert done == [key] diff --git a/server/tests/test_mcp_tools_end_to_end.py b/server/tests/test_mcp_tools_end_to_end.py index eecb0ee..139d2d3 100644 --- a/server/tests/test_mcp_tools_end_to_end.py +++ b/server/tests/test_mcp_tools_end_to_end.py @@ -426,3 +426,86 @@ async def test_notes_create_replay_requires_read_permission_and_visibility( } assert conn.execute("SELECT COUNT(*) FROM notes").fetchone()[0] == 1 assert conn.execute("SELECT COUNT(*) FROM audit_log WHERE tool = 'notes_create'").fetchone()[0] == 1 + + +@pytest.mark.anyio +async def test_occurrence_completion_changes_one_day_and_deduplicates_activity(live) -> None: + mcp, conn, account_id = live + a = assignments_core.create( + conn, account_id, title="Daily walk", schedule_kind="routine", rrule="FREQ=DAILY", + scheduled_start="2026-10-01T09:00:00-04:00", timezone="America/New_York", + ) + # Move Oct 2 across midnight: the original calendar key still identifies the occurrence. + assignments_core.reschedule_occurrence(conn, account_id, a.id, "2026-10-02", "2026-10-03T12:00:00Z") + conn.commit() + for _ in range(2): + result = await _call( + mcp, "assignments_set_status", assignment_id=a.id, status="done", occurrence_date="2026-10-02", + ) + assert result == {"assignment_id": a.id, "occurrence_date": "2026-10-02", "status": "done"} + assert assignments_core.get(conn, account_id, a.id).status == "todo" + calendar = await _call( + mcp, "assignments_calendar", start="2026-10-01T00:00:00Z", end="2026-10-04T00:00:00Z", + ) + assert [(o["occurrence_date"], o["status"]) for o in calendar["occurrences"]] == [ + ("2026-10-01", "todo"), ("2026-10-02", "done"), ("2026-10-03", "todo"), + ] + facts = conn.execute("SELECT occurrence_date FROM activities WHERE assignment_id = ?", (a.id,)).fetchall() + assert [row[0] for row in facts] == ["2026-10-02"] + # A skip is a plan decision, not a completion fact; undoing a status doesn't erase history. + await _call(mcp, "assignments_set_status", assignment_id=a.id, + status="skipped", occurrence_date="2026-10-03") + await _call(mcp, "assignments_set_status", assignment_id=a.id, + status="todo", occurrence_date="2026-10-02") + await _call(mcp, "assignments_set_status", assignment_id=a.id, + status="done", occurrence_date="2026-10-02") + assert conn.execute("SELECT COUNT(*) FROM activities WHERE assignment_id = ?", (a.id,)).fetchone()[0] == 1 + + +@pytest.mark.anyio +async def test_occurrence_completion_enforces_permissions_visibility_and_ownership(live) -> None: + from command.core import settings as settings_core + + mcp, conn, account_id = live + a = assignments_core.create( + conn, account_id, title="Private daily walk", schedule_kind="routine", rrule="FREQ=DAILY", + scheduled_start="2026-10-01T09:00:00Z", + ) + assignments_core.update(conn, account_id, a.id, hidden=True) + other = accounts_core.register(conn, "other-owner", "password1") + foreign = assignments_core.create( + conn, other.id, title="Other task", scheduled_start="2026-10-01T09:00:00Z", + ) + conn.commit() + for target, include_hidden in ((a.id, False), (foreign.id, True)): + with pytest.raises(ToolError, match="No assignment with id"): + await _call(mcp, "assignments_set_status", assignment_id=target, status="done", + occurrence_date="2026-10-01", include_hidden=include_hidden) + settings_core.set_value(conn, account_id, "mcp_permissions", {"assignments": {"update": False}}) + conn.commit() + with pytest.raises(ToolError, match="disabled"): + await _call(mcp, "assignments_set_status", assignment_id=a.id, status="done", + occurrence_date="2026-10-01", include_hidden=True) + assert conn.execute("SELECT COUNT(*) FROM occurrence_status").fetchone()[0] == 0 + assert conn.execute("SELECT COUNT(*) FROM activities").fetchone()[0] == 0 + settings_core.set_value(conn, account_id, "mcp_permissions", {"assignments": {"update": True}}) + conn.commit() + await _call(mcp, "assignments_set_status", assignment_id=a.id, status="done", + occurrence_date="2026-10-01", include_hidden=True) + assert conn.execute("SELECT hidden FROM activities WHERE assignment_id = ?", (a.id,)).fetchone()[0] == 1 + + +@pytest.mark.anyio +async def test_occurrence_completion_rejects_invalid_key_and_preserves_series_mode(live) -> None: + mcp, conn, account_id = live + a = assignments_core.create( + conn, account_id, title="Weekly walk", schedule_kind="routine", rrule="FREQ=WEEKLY;BYDAY=MO", + scheduled_start="2026-10-05T09:00:00Z", + ) + conn.commit() + with pytest.raises(ToolError, match="No occurrence"): + await _call(mcp, "assignments_set_status", assignment_id=a.id, + status="done", occurrence_date="2026-10-06") + assert conn.execute("SELECT COUNT(*) FROM activities").fetchone()[0] == 0 + result = await _call(mcp, "assignments_set_status", assignment_id=a.id, status="cancelled") + assert result["id"] == a.id and result["status"] == "cancelled" diff --git a/server/tests/test_occurrence_overrides.py b/server/tests/test_occurrence_overrides.py index 845218a..198a3c4 100644 --- a/server/tests/test_occurrence_overrides.py +++ b/server/tests/test_occurrence_overrides.py @@ -179,3 +179,23 @@ def test_rest_reschedule_roundtrip(client: TestClient) -> None: target2 = next(o for o in cal2 if o["occurrence_date"] == "2026-08-05") assert target2["occurs_at"].startswith("2026-08-05T09:00") assert target2["rescheduled"] is False + + +def test_rest_occurrence_status_rejects_nonexistent_schedule_date(client: TestClient) -> None: + client.post("/api/auth/register", json={"username": "owner", "password": "password1"}) + a = client.post( + "/api/assignments", + json={"title": "Monday review", "schedule_kind": "routine", "rrule": "FREQ=WEEKLY;BYDAY=MO", + "scheduled_start": "2026-10-05T09:00:00Z"}, + ).json() + result = client.post( + f"/api/assignments/{a['id']}/occurrences/2026-10-06/status", json={"status": "done"}, + ) + assert result.status_code == 404 + assert result.json()["error"]["code"] == "not_found" + assert "occurrence_date" in result.json()["error"]["hint"] + valid = client.post( + f"/api/assignments/{a['id']}/occurrences/2026-10-05/status", json={"status": "done"}, + ) + assert valid.status_code == 200 and valid.json() == {"updated": True} + assert client.get(f"/api/assignments/{a['id']}").json()["status"] == "todo" diff --git a/state/ASTRA-MCP-1002.md b/state/ASTRA-MCP-1002.md new file mode 100644 index 0000000..14658fc --- /dev/null +++ b/state/ASTRA-MCP-1002.md @@ -0,0 +1,77 @@ +# MCP workflow run — 2026-10-02 + +Base: 47170c2. Branch: astra/mcp-workflow-1002. Isolated worktree. + +Chosen work: make a single recurring occurrence completable through MCP and the in-app +assistant. Both current status tools only update the entire assignment; this can mark all +future routine occurrences done. The guide already promises per-occurrence completion facts. +Also validate occurrence keys in shared core: the current REST/core path accepts nonexistent +dates and writes false completion facts. Preserve original keys after rescheduling. + +Plan: discriminating regression tests, extend existing tool signatures, shared validation, +full server pytest/ruff/mypy, disposable localhost MCP/REST wire verification, small commit. +No production mutation, publication, deployment or release. No Apple changes/builds needed. + +Hydrated: public START-HERE/CLAUDE/AGENTS, private maintainer override/roadmap/backlog and project +memory index. No CORPUS.md exists in the checkout or maintainer ops tree. Old audit/backlog +entries are treated as hypotheses; many already have code and tests. + +Status: DONE — verified and committed; ready for integrator cherry-pick. + +## Recovery and completed implementation + +Recovered after the interrupted run; preserved its source edits and regression cases. +The interrupted full run had 771 passes and two failures. Fixed the real in-app serializer +failure (dict passed to model-only serializer) and the test's nonexistent hidden-setting API. +The visibility test then revealed a real shared-core omission: generated completion activity +was public even when its assignment was hidden. New completion facts now inherit the parent +assignment's hidden flag for whole-assignment and occurrence completions. + +Implemented: +- Optional `occurrence_date` on external MCP and in-app assistant status tools. Omission + keeps the existing whole-assignment behavior; supplying the calendar key updates one day. +- Shared-core validation rejects nonexistent/noncanonical occurrence keys before any write. + Rescheduled items retain their original key; legacy fixed-offset dates and DST stay aligned + with the calendar. Multi-day one-offs still accept each calendar day. +- MCP guide explains original keys, whole-series omission, skips and completion deduplication. +- Tests cover tool calls, permission denial, ownership, hidden visibility, repeated completion, + invalid keys, whole-series compatibility, REST errors, date boundaries and timezone cases. + +OBSERVED discriminating controls: +- Before implementation, the new core/MCP/in-app regressions failed: arbitrary dates were + accepted, MCP completed the whole series, and in-app status rejected the new argument. + Preserved output: `/tmp/command-mcp-occurrence-red.log` (one failure there was a fixture API + mistake, subsequently fixed; it is not claimed as a behavioral regression). +- Executing the original activity module with the two new privacy regressions gives exactly + `2 failed, 17 deselected`: visible activities leak from hidden assignments for both status + modes. Output: `/tmp/command-mcp-hidden-red.log`. No source files changed for that control. + +OBSERVED actual localhost wire verification (disposable server/database, no live data): +- Authenticated MCP repeated completion result: + `{"assignment_id":1,"occurrence_date":"2026-10-02","status":"done"}`. +- REST calendar: Oct 1 todo; original Oct 2 done (moved to Oct 3 08:00Z); Oct 3 todo. + Parent assignment remains todo. +- MCP invalid key returns `isError=true`; REST nonexistent date returns HTTP 404 `not_found` + with a hint to use the calendar's occurrence_date. +- SQLite has exactly one completion row: `[1,"2026-10-02","assignment_completion"]`. +- Script `/tmp/command-mcp-wire.py`; output `/tmp/command-mcp-wire.log`; server logs + `/tmp/command-mcp-wire-server.log`. Server terminated and temporary database removed. + +Final checks (OBSERVED): +- `cd server && uv run pytest -q`: **778 passed in 266.09s (0:04:26)**. + Full terminal output: `/tmp/command-mcp-final-green-suite.log`. +- `uv run ruff check .`: **All checks passed!** +- `uv run mypy src`: **Success: no issues found in 102 source files**. +- `git diff --check`: clean. +- Additional timezone/core run: `35 passed in 10.09s`. + +The intermediate recovered run reached 774 passes with one incorrect expected error string +in a new test. Corrected it to the actual existing not-found wording; the final suite above +includes that corrected test and all timezone cases. + +Done in two logical commits: hidden completion inheritance, then occurrence tool support. +Next: integrator cherry-picks both commits, reviews combined branch and handles branch push/PR. +No unfinished implementation or owned long-running server remains. Production and UI behavior +were not exercised; this item changes server/tool behavior only. Existing historical activity +visibility is not rewritten; newly generated completion facts inherit current parent visibility. +No simulator, Apple build, production mutation, deploy, release, spending or publication. From 62e540578dc705b4e999ba16feaf69b6b3a0197b Mon Sep 17 00:00:00 2001 From: legitimate-apps <309192374+legitimate-apps@users.noreply.github.com> Date: Fri, 2 Oct 2026 12:00:20 -0400 Subject: [PATCH 07/27] Record verified workflow integration and Catalyst build --- state/ASTRA-1002.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/state/ASTRA-1002.md b/state/ASTRA-1002.md index 9e24a92..6b2c7be 100644 --- a/state/ASTRA-1002.md +++ b/state/ASTRA-1002.md @@ -93,3 +93,13 @@ compile Catalyst, then push this branch and open a PR. No new item after 12:10; - Actual microphone prompts/audio hardware remain outside this verification claim. - Recovery and voice commits are pushed to the remote branch. MCP integration and rendered relaunch check are next; no new feature scope is being opened. + +## Verified MCP integration and Catalyst — 12:00 EDT +- Integrated helper commits `1bc8935` and `1f947ab`: agents can complete one original recurring + occurrence without completing the series; invalid dates fail before writes; newly generated + completion facts inherit hidden assignment privacy. Shared core covers REST/MCP/in-app paths. +- OBSERVED in helper worktree on exactly these server sources: **778 pytest tests passed**, + Ruff clean, mypy clean across 102 files. Native timezone/DST/boundary regression cases pass. + Detailed commands, controls and MCP/REST/SQLite observations: `state/ASTRA-MCP-1002.md`. +- OBSERVED: integrated app **Mac Catalyst BUILD SUCCEEDED**. Log: + `/tmp/command-astra-1002/catalyst-build.log`. This is compilation evidence, not Mac UI evidence. From 124198d3bf6952dc52bd59d6d082884d6bb91047 Mon Sep 17 00:00:00 2001 From: legitimate-apps <309192374+legitimate-apps@users.noreply.github.com> Date: Fri, 2 Oct 2026 12:08:31 -0400 Subject: [PATCH 08/27] Keep active note editors when another window resumes the same account --- ios/Command/App/AppState.swift | 17 +++++++++++++---- .../NoteRecoveryPersistenceTests.swift | 17 +++++++++++++++++ state/ASTRA-1002.md | 13 +++++++++++++ 3 files changed, 43 insertions(+), 4 deletions(-) diff --git a/ios/Command/App/AppState.swift b/ios/Command/App/AppState.swift index 49b3e7c..10578c8 100644 --- a/ios/Command/App/AppState.swift +++ b/ios/Command/App/AppState.swift @@ -117,6 +117,7 @@ final class AppState { /// Shared notes state (capture bar + Notes list stay in sync). private(set) var notes = NotesStore() private let noteRecoveryRoot: URL + private var notesRecoveryScope: URL? /// Shared delegatee roster (People list + assignee pickers). let people = PeopleStore() /// Shared goals + assignments. @@ -587,11 +588,18 @@ final class AppState { /// Post-sign-in fan-out: load the entitlement (consent + subscription state) and /// bind RevenueCat's identity to this account so its purchase webhook maps back. - private func onSignedIn() async { + /// A second window bootstraps the same account. Preserve its active editor owners; + /// only a changed account/server scope needs a new recovery store. + func activateNotes(for account: Account) { + let recovery = NoteRecoveryStore(root: noteRecoveryRoot, server: client.baseURL, account: account) + guard notesRecoveryScope != recovery.directory else { return } notes.deactivate() - if let account { - notes = NotesStore(recovery: NoteRecoveryStore(root: noteRecoveryRoot, server: client.baseURL, account: account)) - } + notes = NotesStore(recovery: recovery) + notesRecoveryScope = recovery.directory + } + + private func onSignedIn() async { + if let account { activateNotes(for: account) } await refreshEntitlement() // RevenueCat identity + offering load run OFF the critical path. A slow or // stalled StoreKit product fetch — e.g. a freshly-created sandbox product still @@ -798,6 +806,7 @@ final class AppState { Task { [subscription] in await subscription.signOut() } notes.deactivate() notes = NotesStore() + notesRecoveryScope = nil people.delegatees = [] tasks.assignments = [] tasks.goals = [] diff --git a/ios/CommandTests/NoteRecoveryPersistenceTests.swift b/ios/CommandTests/NoteRecoveryPersistenceTests.swift index 8752baa..0dc9582 100644 --- a/ios/CommandTests/NoteRecoveryPersistenceTests.swift +++ b/ios/CommandTests/NoteRecoveryPersistenceTests.swift @@ -187,6 +187,23 @@ final class NoteRecoveryPersistenceTests: XCTestCase { XCTAssertNotNil(store.recoveryError) } + func testRepeatedAccountActivationKeepsActiveEditorAndRecoveryOwnership() throws { + let client = APIClient(baseURL: URL(string: "https://example.com")!) + let app = AppState(client: client, noteRecoveryRoot: root) + let account = Account(id: 1, username: "tester", displayName: nil, createdAt: "2026-01-01T00:00:00Z") + app.activateNotes(for: account) + let original = app.notes + let (saver, _) = editing(original) + saver.text = "Before another window" + app.activateNotes(for: account) + XCTAssertTrue(app.notes === original, "same-account bootstrap must not retire open editors") + saver.text = "Typed after another window opens" + XCTAssertEqual(try recovery().loadEdits().edits.first?.text, saver.text) + app.activateNotes(for: Account(id: 2, username: "second", displayName: nil, createdAt: account.createdAt)) + XCTAssertFalse(app.notes === original) + XCTAssertTrue(app.notes.unsavedEdits.isEmpty) + } + func testSessionTeardownRetiresStoreAndDropsParkedEditsFromNextAccount() async { let client = APIClient(baseURL: URL(string: "https://example.invalid")!) let app = AppState(client: client, noteRecoveryRoot: root) diff --git a/state/ASTRA-1002.md b/state/ASTRA-1002.md index 6b2c7be..5d6cd88 100644 --- a/state/ASTRA-1002.md +++ b/state/ASTRA-1002.md @@ -103,3 +103,16 @@ compile Catalyst, then push this branch and open a PR. No new item after 12:10; Detailed commands, controls and MCP/REST/SQLite observations: `state/ASTRA-MCP-1002.md`. - OBSERVED: integrated app **Mac Catalyst BUILD SUCCEEDED**. Log: `/tmp/command-astra-1002/catalyst-build.log`. This is compilation evidence, not Mac UI evidence. + +## Verified multiwindow correction — 12:08 EDT +- Independent review found repeated same-account bootstrap (another iPad/Mac window) retired + existing editors and transferred their recovery-file ownership. Account activation now preserves + the store for the same server/account scope and replaces it only for a changed scope or teardown. +- OBSERVED: full app recompilation plus **15 recovery persistence iOS tests passed**, including + retaining editor/store identity and persisting edits typed after repeated activation. + Evidence: `/tmp/command-astra-1002/ios-window-tests.log`. +- OBSERVED: quick draft survived termination with exact text. Offline editor recovery JSON retained + both the original uncertain-create payload/key and later body edits; relaunch displayed the + unsaved banner and Review showed exact text. Final save/DB check remains next. +- PR opened: https://github.com/legitimate-apps/command/pull/1 . Both initial CI checks passed: + PII scan (5s) and server lock/type/test (5m17s). Latest correction is iOS-only. From 69d13d8232e8de58beb3b5a8a9ac8d79364c6fc9 Mon Sep 17 00:00:00 2001 From: legitimate-apps <309192374+legitimate-apps@users.noreply.github.com> Date: Fri, 2 Oct 2026 12:10:20 -0400 Subject: [PATCH 09/27] Record observed relaunch recovery through UI HTTP and SQLite --- state/ASTRA-1002.md | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/state/ASTRA-1002.md b/state/ASTRA-1002.md index 5d6cd88..0d0dcd3 100644 --- a/state/ASTRA-1002.md +++ b/state/ASTRA-1002.md @@ -116,3 +116,20 @@ compile Catalyst, then push this branch and open a PR. No new item after 12:10; unsaved banner and Review showed exact text. Final save/DB check remains next. - PR opened: https://github.com/legitimate-apps/command/pull/1 . Both initial CI checks passed: PII scan (5s) and server lock/type/test (5m17s). Latest correction is iOS-only. + +## Verified actual capture recovery — 12:10 EDT +- OBSERVED simulator UI: typed quick draft, terminated the app, relaunched and read the exact same + text from the accessibility tree and screen. Evidence: `draft-before.json`, `draft-after.json`, + `draft-recovered.jpg` under `/tmp/command-astra-1002/`. +- OBSERVED offline editor: stopped only the disposable server, typed a title/body, confirmed + “Not saved — Could not connect to the server.” Disk JSON contained the original create payload + and UUID plus all later edits. Terminated the app, restarted server, relaunched Notes: the recovery + banner appeared and Review showed exact title/body. `recovery-banner.jpg`, `review-tree.json`. +- OBSERVED Retry: HTTP POST `/api/notes` **201**, PATCH `/api/notes/1` **200**; SQLite contains + exactly **one note** with title “Offline recovery title” and complete body. UI shows the saved row; + recovery banner gone, editor recovery file removed, separate unsent quick draft retained. + Evidence: server log, `retry-tree.json`, `recovery-saved.jpg` in the same scratch directory. +- OBSERVED final Catalyst build after multiwindow correction: **BUILD SUCCEEDED** in + `/tmp/command-astra-1002/catalyst-final-build.log`. +- Latest timing: start nothing new after 12:15; wrap at 12:25. Full combined iOS verification and + durable evidence/PR update are the remaining steps, then stop owned resources. From 64a24afb6b182d68d18e6c433df7fac37a91d335 Mon Sep 17 00:00:00 2001 From: legitimate-apps <309192374+legitimate-apps@users.noreply.github.com> Date: Fri, 2 Oct 2026 12:12:32 -0400 Subject: [PATCH 10/27] Document capture recovery contract and preserve verification evidence --- docs/specs/2026-06-16-command-design.md | 21 +++++ state/ASTRA-1002.md | 9 +++ state/evidence/astra-1002/draft-recovered.jpg | Bin 0 -> 12717 bytes state/evidence/astra-1002/recovery-banner.jpg | Bin 0 -> 11623 bytes state/evidence/astra-1002/recovery-saved.jpg | Bin 0 -> 9018 bytes state/evidence/astra-1002/verification.md | 74 ++++++++++++++++++ 6 files changed, 104 insertions(+) create mode 100644 state/evidence/astra-1002/draft-recovered.jpg create mode 100644 state/evidence/astra-1002/recovery-banner.jpg create mode 100644 state/evidence/astra-1002/recovery-saved.jpg create mode 100644 state/evidence/astra-1002/verification.md diff --git a/docs/specs/2026-06-16-command-design.md b/docs/specs/2026-06-16-command-design.md index 4286700..36e16b0 100644 --- a/docs/specs/2026-06-16-command-design.md +++ b/docs/specs/2026-06-16-command-design.md @@ -204,6 +204,27 @@ and streaming endpoints use their own connections. This was tested at the ASGI response-send boundary with FastAPI 0.141.1 / Starlette 1.6.0; ordinary TestClient calls alone wait for cleanup and cannot prove that timing guarantee. + +### Device-local unsent note recovery (updated 2026-10-02) + +The app keeps atomic recovery files for the calendar's note draft and unsent +note editors. Recovery belongs to a server and account identity (including +account creation time); signing out retains it for that account, while account +deletion removes it. Another account cannot see or retry those edits. Reopening +a second window for the same account preserves active editor ownership. + +An uncertain create retains its original key and payload across relaunch. +Later edits are applied by PATCH after that create is acknowledged. Saved or +explicitly discarded edits remove their recovery record. Unreadable records are +kept and reported; disk-write failure warns the user to keep the app open until +saving succeeds. Hidden notes retain their veil in recovered editors. Recovery +files are excluded from backup and use device file protection. + +This is unsent-work recovery, not an offline copy of the server database. Voice +audio/review state and log/schedule drafts are not covered by these recovery +files. Transport retries keep their original session identity; stale responses +cannot replace a newer account's cookies or sign that account out. + --- ## 5. Auth & the memorable access token diff --git a/state/ASTRA-1002.md b/state/ASTRA-1002.md index 0d0dcd3..abf4d5b 100644 --- a/state/ASTRA-1002.md +++ b/state/ASTRA-1002.md @@ -133,3 +133,12 @@ compile Catalyst, then push this branch and open a PR. No new item after 12:10; `/tmp/command-astra-1002/catalyst-final-build.log`. - Latest timing: start nothing new after 12:15; wrap at 12:25. Full combined iOS verification and durable evidence/PR update are the remaining steps, then stop owned resources. + +## Final combined verification — 12:12 EDT +- OBSERVED **316 iOS tests passed, zero failures**, including all recovery, account isolation, + existing capture/idempotency tests and expanded voice suite. Full log: + `/tmp/command-astra-1002/ios-final-tests.log`; xcresult + `Logs/Test/Test-Command-2026.10.02_12-10-22--0400.xcresult` in leased DD. +- Durable public-safe test output excerpts, exact invocation shape, screenshot evidence and + verification limits are committed in `state/evidence/astra-1002/verification.md`. +- Design spec now states actual recovery coverage and limits; MCP guide already updated. diff --git a/state/evidence/astra-1002/draft-recovered.jpg b/state/evidence/astra-1002/draft-recovered.jpg new file mode 100644 index 0000000000000000000000000000000000000000..26bc0efd84a3fd4976747115fba68329533cb2d0 GIT binary patch literal 12717 zcmc(F1yo$ivi2SZcNqvW5CQ~;;4T9RFhFnyC%6Ycc2zs30pZ3xGfX07w1-SD%1~ zGM+Y;0HCA78VqxPT3F-*}6c8AUf(k}M zLq&EC@Ilp?{G_@lc7{ErN!7={GVq$Z1Yu#5-6E%;yvxYM z%)-jYFCZu+EOP&WjI117UO__>p{1>(t7m3zVQFP;W9#~do4bdnmv`{fkkDsg;SmXm zNy#bCQ`6G(@(T)!ic3n%YG2jWH#9aiw{&&)yzTAl9~hjNoSL4QoqIq3>GR6!+WN-k z*7m{S(ecUY*|+oW*K#38<(F8<@?XkDgp>;f6%~w%aV-}J#p7CVB2=_H+~~woY8WQY zBy>E1m=Njs+?q}-dS3Ofq^2(8*klZRpY9%9i*_T~-xDn8|4Ood2=n0Im zVG)uM5)zWpkRcNdBh7VUs=Db(T%y|*Of6LYP4m^6S>-1A5`ATMdo_>~dYk7!8yaJvuT>&I=7wq@Q{YSU1fY&5fKzLr~e?ax&n~vW< z^U@b_e5>R)5923|*_OBhm}M`p56&alZ%Ksb)gIfM4jE2Ps=c%ye}hU>)?F6A&8A*p zA_Gwc{fmroHTKuI49x8F;~4VTMf1t6%T}xoWuhS%GVzO}KyOXuD(vvQ^3Q{a9Q}g* zK%DvmJj9~R7y-h=ZrWUTr|TMO&Dl%(=XOHLh04Hk^|y^X{l7hTzD1v%ICS2$5nIgH z(KGF4=&)2t_u!BQk+ydD*{q-s>PL8}7dMup}&+ZS5 zeDo5Qw#8@apHl-Nv9Fk6B$%)ed(01%LSp zz3*X5yGlFmJ=*VO2}mkuR1bkeeZ@hA5UR~?^Z*Gi4==-lxD-o<1n&gzbbH$!Z}H`j zQpMs&EV$3s9Nx93`cMv5Vq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NEcQtAj@ zGq}0F$DwLhs>DSr8j0$*?D=LfRXan^cL{F&?2ppa4_k#fVnety-fyC9E`3T2-Vu^H zXalLR23#ADrh_E>2N(P6Sxfq8>x!a^< zrSR>wbce#2K3-%C7ZyR<7&p+GgbO}1t`)s(< zNIKnKcdu#|mOW3^UV9b4em?yDp}?VstnXcPSuj^)H{;=--7l9*Mz-QBkn z7+$mDA;j7MhAbiW<|aSd+V6r6z#{l!Q6U3kRRT4ZQL?C&=c58Ie6C|=wpA9v z$#6F7rIYdDp5b0s_F&0|)DJ@y>E*7_aYmr}`Y|^5@GZ|%uf88JD|$`=W4PVCrdh1_ z^yn0ce;tCRy-)n5E~$*+1Sxp9q3C8uyu443#DtjtL1c?KR%XL@5vRg#ubbZ)@TPt$ zv9rlWqBRc1ktz}QhV*`6sFeh!%kii?5MYX6?AE;I z^R*&TVRP$Y!P8`Ix#(2WBnqYXI@Dvtpwip=ne6H1`3CIzM;jh{x4;hS`sqp8;(XW649$ABDqmtIONwcb(q)sJ)&Vcr<2l zu$mw_O1-JJs_q@Mm>oKv$V*ib@jsx{a*HS)VRm zwyuf5dNuBkkrZY&Qm>=2_A10v1VW7Xkp9cZi$gH-AHqu&beC2}ksea2IFkVs#8q8%Qa|N9WxcJ5(K zj{enY Date: Fri, 2 Oct 2026 12:14:10 -0400 Subject: [PATCH 11/27] Finalize reliability run handoff and resource cleanup --- state/ASTRA-1002.md | 43 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/state/ASTRA-1002.md b/state/ASTRA-1002.md index abf4d5b..cccc7d9 100644 --- a/state/ASTRA-1002.md +++ b/state/ASTRA-1002.md @@ -1,5 +1,9 @@ # Command reliability push — 2026-10-02 +**FINAL — selected work finished, verified, committed and pushed; PR #1 open.** + +See the final handoff below; earlier sections preserve the run history. + ## Scope and authority - Worktree branch: `astra/capture-reliability-1002`, based on `47170c2` (build 70). - Own this worktree only. The main checkout belongs to a separate session. @@ -142,3 +146,42 @@ compile Catalyst, then push this branch and open a PR. No new item after 12:10; - Durable public-safe test output excerpts, exact invocation shape, screenshot evidence and verification limits are committed in `state/evidence/astra-1002/verification.md`. - Design spec now states actual recovery coverage and limits; MCP guide already updated. + +## Final handoff — 12:14 EDT + +### Done +- `f5a12fc`: durable unsent editor/calendar note recovery plus account/session isolation. +- `977c54e`: voice permission/transcription/save race protection. +- `ededd4b`: newly generated completion activities inherit hidden assignment visibility. +- `dc72efe`: MCP and in-app assistant per-occurrence status with shared date validation. +- `124198d`: repeated same-account window bootstrap preserves active editors and disk ownership. +- `64a24af`: durable verification screenshots/excerpts and recovery design documentation. +- Final combined evidence: **316 iOS tests passed**, **778 server tests passed**, final Catalyst + build succeeded, Ruff/mypy/lockfile clean, real UI + HTTP + SQLite recovery verified. +- PR: https://github.com/legitimate-apps/command/pull/1 . Initial server and PII CI passed; + final documentation/state pushes can retrigger the same CI. Consult PR checks for latest run. +- Main checkout untouched. All code is on `astra/capture-reliability-1002`; no merge, release, + server deployment, store submission, external messages, or new spend. + +### Cleanup +- Both helpers finished; all their implementation commits are integrated. No unfinished helper work. +- Own simulator shutdown confirmed and lease/device disposed; no booted simulators remain. +- Own simulator companion stopped; all voice/helper and integrator DerivedData leases released. +- Disposable verification servers stopped. No owned build/test/server/emulator remains running. +- Worktrees retained for review. Raw local logs remain under `/tmp/command-astra-1002/` and + `/tmp/command-mcp-*`; committed evidence survives scratch cleanup in + `state/evidence/astra-1002/verification.md` and the helper state files. + +### Remaining and exact next step +1. Review PR #1 and its final CI checks. It is ready for review; this run does not merge or deploy it. +2. Next capture-reliability item: **durable voice recording/review recovery across process death**. + Start by reproducing process termination after recorder stop and during transcription; define + account-scoped ownership/retention of audio and transcript, then add crash/relaunch tests before + implementation. Current voice changes guard asynchronous races only; they do not claim this. +3. Log/schedule drafts still lack equivalent durable recovery. Note edits retain the existing + last-write-wins behavior for genuinely simultaneous edits on different devices. +4. Physical microphone/AVAudioSession behavior and rendered Mac/iPad multiwindow interaction remain + unverified. Multiwindow preservation has automated iOS coverage and Catalyst compilation. +5. Existing historical completion activities are not migrated; new facts inherit current visibility. + +No unfinished source change is being handed off. No task has been started merely to spend usage. From 5dc9105efb27c3fa750f2cebb4530798409928fd Mon Sep 17 00:00:00 2001 From: legitimate-apps <309192374+legitimate-apps@users.noreply.github.com> Date: Fri, 2 Oct 2026 12:36:00 -0400 Subject: [PATCH 12/27] Reproduce voice recovery gaps across hard process termination --- ios/recovery-repro/VoiceRecoveryProbe.swift | 75 +++++++++ .../test_voice_process_recovery.py | 145 ++++++++++++++++++ state/ASTRA-1002.md | 14 ++ 3 files changed, 234 insertions(+) create mode 100644 ios/recovery-repro/VoiceRecoveryProbe.swift create mode 100644 ios/recovery-repro/test_voice_process_recovery.py diff --git a/ios/recovery-repro/VoiceRecoveryProbe.swift b/ios/recovery-repro/VoiceRecoveryProbe.swift new file mode 100644 index 0000000..d2f9ccf --- /dev/null +++ b/ios/recovery-repro/VoiceRecoveryProbe.swift @@ -0,0 +1,75 @@ +import Foundation + +/// Test process only. Checkpoints are an external observer, never read to restore app state. +@main +struct VoiceRecoveryProbe { + @MainActor + static func main() async throws { + let args = CommandLine.arguments + let mode = args[1], directory = URL(fileURLWithPath: args[2], isDirectory: true) + let audio = directory.appendingPathComponent("recording.wav") + let flow = VoiceCaptureFlow() + func snapshot(_ extra: [String: String] = [:]) throws { + var value = extra + value["audio"] = flow.audioURL?.path ?? "" + value["transcript"] = flow.transcript + value["engine"] = flow.engineUsed + value["pid"] = String(ProcessInfo.processInfo.processIdentifier) + try JSONSerialization.data(withJSONObject: value, options: [.sortedKeys]) + .write(to: directory.appendingPathComponent("observation.json"), options: .atomic) + } + func hold() async { + while true { try? await Task.sleep(for: .seconds(3600)) } + } + if mode == "relaunch" { + try snapshot() + return + } + if mode == "retry" { + // Re-enter the SAME payload to isolate the loss of retry identity from transcript loss. + flow.transcript = "Reviewed capture" + _ = await flow.saveNote { _, _, key in + try! snapshot(["key": key]) + return "Response lost" + } + return + } + flow.adopt(audio) + switch mode { + case "stopped": + try snapshot(); await hold() + case "transcribing": + _ = await flow.transcribe(immediateUse: false) { _ in + try snapshot(["checkpoint": "inside-transcriber"]) + await hold() + throw CancellationError() + } + case "review": + _ = await flow.transcribe(immediateUse: false) { _ in ("Spoken capture", "sfspeech") } + flow.transcript = "Latest edited review" + try snapshot(); await hold() + case "uncertain": + flow.transcript = "Reviewed capture" + _ = await flow.saveNote { _, _, key in + try! snapshot(["key": key, "checkpoint": "request-awaiting-response"]) + await hold() + return "Response lost" + } + case "cancel": + flow.cancel(); try snapshot() + case "success": + flow.transcript = "Reviewed capture" + _ = await flow.saveNote { _, _, _ in nil } + try snapshot() + case "same-process-retry": + flow.transcript = "Reviewed capture" + var keys: [String] = [] + for _ in 0..<2 { + _ = await flow.saveNote { _, _, key in keys.append(key); return "Response lost" } + } + try snapshot(["firstKey": keys[0], "secondKey": keys[1]]) + default: + fatalError("Unknown test mode") + } + } +} diff --git a/ios/recovery-repro/test_voice_process_recovery.py b/ios/recovery-repro/test_voice_process_recovery.py new file mode 100644 index 0000000..613d428 --- /dev/null +++ b/ios/recovery-repro/test_voice_process_recovery.py @@ -0,0 +1,145 @@ +#!/usr/bin/env python3 +"""Real process-death characterization against copied, unmodified production Swift sources. + +Default: 3 controls + 4 explicitly expected failures. --require-recovery turns those +known gaps into ordinary failing acceptance tests. No simulator, microphone or server. +""" +import argparse +import json +from pathlib import Path +import shutil +import signal +import subprocess +import tempfile +import time +import unittest +import wave + +ROOT = Path(__file__).resolve().parents[2] +PROBE = None + + +def build_probe(build_dir): + package = build_dir / "VoiceRecoveryProcessRepro" + sources = package / "Sources" / "Probe" + sources.mkdir(parents=True, exist_ok=True) + (package / "Package.swift").write_text('''// swift-tools-version: 5.10 +import PackageDescription +let package = Package(name: "VoiceRecoveryProcessRepro", platforms: [.macOS(.v14)], + targets: [.executableTarget(name: "Probe")]) +''') + for relative in ( + "Transcription/VoiceCaptureFlow.swift", "Networking/CreateAttempt.swift", + "Widgets/AssistantSurfaceLogic.swift", + ): + source = ROOT / "ios/Command" / relative + shutil.copyfile(source, sources / source.name) + shutil.copyfile(Path(__file__).with_name("VoiceRecoveryProbe.swift"), sources / "VoiceRecoveryProbe.swift") + subprocess.run(["swift", "build", "--package-path", str(package), "--jobs", "2"], check=True, timeout=120) + result = subprocess.run(["swift", "build", "--package-path", str(package), "--show-bin-path"], + check=True, capture_output=True, text=True, timeout=30) + return Path(result.stdout.strip()) / "Probe" + + +class VoiceProcessRecoveryTests(unittest.TestCase): + def setUp(self): + self.directory = Path(tempfile.mkdtemp(prefix="command-voice-repro-")) + self.addCleanup(shutil.rmtree, self.directory) + self.audio = self.directory / "recording.wav" + # A valid 16 kHz mono WAV fixture; these tests do not invoke a codec or microphone. + with wave.open(str(self.audio), "wb") as audio: + audio.setnchannels(1) + audio.setsampwidth(2) + audio.setframerate(16000) + audio.writeframes(b"\0\0" * 1600) + self.observation = self.directory / "observation.json" + scenarios = { + "test_stopped_recording_is_discoverable_after_process_death": "stopped", + "test_transcribing_recording_is_discoverable_after_process_death": "transcribing", + "test_review_text_and_engine_survive_process_death": "review", + "test_uncertain_create_reuses_key_after_process_death": "uncertain", + } + scenario = scenarios.get(self._testMethodName) + if scenario: + # Preconditions live in setUp so harness faults CANNOT count as expected failures. + child = subprocess.Popen([str(PROBE), scenario, str(self.directory)], + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) + self.addCleanup(self.stop_child, child) + deadline = time.monotonic() + 10 + while not self.observation.exists() and child.poll() is None and time.monotonic() < deadline: + time.sleep(0.01) + self.assertTrue(self.observation.exists(), "child failed to reach the requested checkpoint") + self.before = json.loads(self.observation.read_text()) + self.assertEqual(child.pid, int(self.before["pid"])) + self.assertEqual(self.before["audio"], str(self.audio)) + if scenario == "transcribing": + self.assertEqual(self.before["checkpoint"], "inside-transcriber") + if scenario == "uncertain": + self.assertEqual(self.before["checkpoint"], "request-awaiting-response") + self.assertTrue(self.before["key"]) + if scenario == "review": + self.assertEqual(self.before["transcript"], "Latest edited review") + child.kill() + child.communicate(timeout=5) + self.assertEqual(child.returncode, -signal.SIGKILL) + self.assertTrue(self.audio.exists(), "SIGKILL must bypass all app cleanup callbacks") + self.after = self.run_probe("retry" if scenario == "uncertain" else "relaunch") + self.assertNotEqual(self.before["pid"], self.after["pid"]) + + @staticmethod + def stop_child(child): + if child.poll() is None: + child.kill() + child.communicate(timeout=5) + + def run_probe(self, mode): + self.observation.unlink(missing_ok=True) + subprocess.run([str(PROBE), mode, str(self.directory)], check=True, + capture_output=True, text=True, timeout=10) + return json.loads(self.observation.read_text()) + + @unittest.expectedFailure + def test_stopped_recording_is_discoverable_after_process_death(self): + self.assertEqual(self.after["audio"], str(self.audio)) + + @unittest.expectedFailure + def test_transcribing_recording_is_discoverable_after_process_death(self): + self.assertEqual(self.after["audio"], str(self.audio)) + + @unittest.expectedFailure + def test_review_text_and_engine_survive_process_death(self): + self.assertEqual((self.after["transcript"], self.after["engine"]), + ("Latest edited review", "sfspeech")) + + @unittest.expectedFailure + def test_uncertain_create_reuses_key_after_process_death(self): + self.assertEqual(self.after["key"], self.before["key"]) + + def test_failed_save_reuses_key_without_process_death(self): + result = self.run_probe("same-process-retry") + self.assertEqual(result["firstKey"], result["secondKey"]) + self.assertTrue(self.audio.exists()) + + def test_explicit_cancel_removes_recording(self): + result = self.run_probe("cancel") + self.assertEqual(result["audio"], "") + self.assertFalse(self.audio.exists()) + + def test_acknowledged_save_removes_recording(self): + result = self.run_probe("success") + self.assertEqual(result["audio"], "") + self.assertFalse(self.audio.exists()) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--build-dir", type=Path, required=True, help="Owned dd-lease directory") + parser.add_argument("--require-recovery", action="store_true", help="Fail for known missing durability") + args = parser.parse_args() + PROBE = build_probe(args.build_dir) + if args.require_recovery: + for name in unittest.defaultTestLoader.getTestCaseNames(VoiceProcessRecoveryTests): + method = getattr(VoiceProcessRecoveryTests, name) + if hasattr(method, "__unittest_expecting_failure__"): + method.__unittest_expecting_failure__ = False + unittest.main(argv=[__file__], verbosity=2) diff --git a/state/ASTRA-1002.md b/state/ASTRA-1002.md index cccc7d9..67ef16e 100644 --- a/state/ASTRA-1002.md +++ b/state/ASTRA-1002.md @@ -185,3 +185,17 @@ compile Catalyst, then push this branch and open a PR. No new item after 12:10; 5. Existing historical completion activities are not migrated; new facts inherit current visibility. No unfinished source change is being handed off. No task has been started merely to spend usage. + +## Bounded follow-on — 12:36 EDT (operator reopened scope) +- New deadline: commit/push this item by 12:50, then stop; no merges or deployments. +- Test-first scope: crash/relaunch voice reproduction plus ownership/retention design. Production + recovery will only be implemented if it can be fully verified safely within the deadline. +- Added an opt-in native subprocess harness compiling unmodified production VoiceCaptureFlow, + CreateAttempt and validation source. It SIGKILLs at stopped, in-flight transcription, edited + review and uncertain-create checkpoints, then launches a fresh process. It never restores + from its observer JSON. No simulator/microphone/server was started. +- OBSERVED: **7 cases: 3 controls pass, 4 explicitly expected durability failures**. Strict + `--require-recovery` mode produces **4 ordinary failures**. Thus voice process-death recovery + remains missing; this is a reproducer, not a claim that the feature is implemented. +- Logs: `/tmp/command-astra-1002/voice-process-{characterization,required}.log`. +- One leased native DerivedData directory is in use for the harness and will be released. From 9d4d2c6951bc86b00cc5ec25d0141ff1291affee Mon Sep 17 00:00:00 2001 From: legitimate-apps <309192374+legitimate-apps@users.noreply.github.com> Date: Fri, 2 Oct 2026 12:38:57 -0400 Subject: [PATCH 13/27] Define durable voice ownership and document process-death baseline --- docs/decisions/2026-10-02-voice-recovery.md | 129 ++++++++++++++++++ ios/recovery-repro/README.md | 43 ++++++ .../test_voice_process_recovery.py | 11 +- state/ASTRA-1002.md | 30 ++++ .../astra-1002/voice-process-reproduction.md | 43 ++++++ 5 files changed, 255 insertions(+), 1 deletion(-) create mode 100644 docs/decisions/2026-10-02-voice-recovery.md create mode 100644 ios/recovery-repro/README.md create mode 100644 state/evidence/astra-1002/voice-process-reproduction.md diff --git a/docs/decisions/2026-10-02-voice-recovery.md b/docs/decisions/2026-10-02-voice-recovery.md new file mode 100644 index 0000000..e47b427 --- /dev/null +++ b/docs/decisions/2026-10-02-voice-recovery.md @@ -0,0 +1,129 @@ +# Voice capture ownership and process-death recovery + +Status: **proposed implementation contract; not implemented**. The first reproductions are +committed in `ios/recovery-repro/`. This note records the work needed to turn the existing +within-process voice safety into durable recovery, without changing the capture product flow. + +## Observed problem and evidence + +`AudioRecorder.start()` writes M4A into temporary storage. `VoiceCaptureFlow` holds the audio +URL, transcript, engine, revision, and create attempt only in memory. Its default initializer +(the one used by `RecordingSheet`) has no restore path. Killing a process after recording stops, +during transcription, during edited review, or while awaiting a create response leaves a new +process unable to discover the capture or reuse the pending request key. + +The native subprocess reproducer compiles actual production source, reaches those boundaries, +uses SIGKILL, checks the exit signal, and launches a different process. Three existing-behavior +controls pass; four recovery assertions are expected failures. Strict mode fails those four +assertions. The raw fixture file survives the kill, which separates lost discovery/metadata +from deletion. Observer JSON is test evidence only; the app never reads it for restoration. + +This is **not** an AVAudioRecorder or app-bootstrap test. The fixture is finalized PCM WAV; +actual recording is M4A. Whether an unfinished M4A remains decodable after process death is +unproven and requires a device/simulator recording test before claiming recovery during recording. +The harness also does not exercise account scope or rendered recovery UI. + +Source review identifies two additional ownership problems to resolve with persistence: + +- `RecordingSheet.onDisappear` calls both recorder and flow cancellation. Ordinary navigation, + window closure, and a swipe from successful review currently mean deletion. +- Immediate-use transcription deletes source audio before its `Void` callback runs. In + `AgentChatView.acceptTranscription`, a full assistant queue can reject `AgentStore.send`, and + its Boolean result is ignored. Manual Use writes an in-memory view draft. Neither action is + evidence of durable acceptance. This handoff gap is source-observed, not reproduced on device. + +## Owner, scope, and storage + +A shared capture coordinator owns durable records independently of sheet/window lifetimes. +Each capture has a stable UUID and the same scope convention as note recovery: normalized +server URL, account ID, username, and account creation identity. A second window for the same +scope reuses the coordinator. One microphone lease is exclusive across windows; different +stopped captures may remain separately reviewable. + +Store each capture beneath protected Application Support storage, excluded from backup, with +restrictive directory/file permissions. Raw audio stays local. A versioned manifest contains: + +- Stable capture ID, scope identity, intended destination, creation time, lifecycle phase. +- Relative audio filename constrained to that capture directory; interrupted/finalized status. +- Latest transcript, revision, engine, locale, and any hidden-content requirement. +- Pending original note request (all submitted fields), its idempotency key, and acknowledged + note ID or durable recipient receipt where applicable. + +No transcript/audio content belongs in diagnostics. App lock and hidden-content rules apply to +recovery previews, manifests, audio, and temporary transcription copies. Signing out hides and +retains the original account's unfinished captures; a different account cannot enumerate or +submit them. Account deletion removes that scope. Transport work stays bound to its session. + +## Lifecycle and retention + +| Boundary | Durable action | Restore behavior | +|---|---|---| +| Before recorder starts | Create manifest and owned audio path | Never automatically activate microphone | +| Recording stops/interruption | Finalize audio; record interruption and stopped phase | Validate audio; offer transcription/review | +| Transcription starts | Retain stopped audio and checkpoint phase | Offer retry; never auto-send a turn | +| Result or review edit | Atomically persist transcript/revision/engine | Restore latest committed text | +| Note request begins | Persist exact original payload and key before network call | Reconcile/replay original request | +| Note acknowledged | Persist note ID/receipt, then settle pending edits | Resume PATCH if needed; avoid another create | +| Recipient accepts handoff | Persist recipient's durable receipt for exact revision | Do not redeliver accepted revision | +| Explicit discard / completed capture | Persist terminal state before unlinking files | Finish cleanup; never resurrect/replay | + +A record found in `recording` after a crash becomes an interrupted capture. Do not promise that +it contains the final spoken words. Validate decoding and explain truncation. Keep damaged audio +and manifest evidence with a recoverable error instead of deleting it or fabricating success. + +Stopping asynchronous work and discarding content are separate operations. Disappearance, +account changes, window closure, and suspension retain unfinished records. Explicit **Discard +recording** authorizes deletion. Record again must explicitly replace the current capture or +park it before starting another; an incidental lifecycle callback cannot make that choice. + +Atomic manifest writes must preserve the previous readable record on failure. Do not advance a +network submission or destructive handoff when its prerequisite checkpoint failed. Surface the +failure. Audio must be durably owned before transcription; copying/moving a temporary recording +must handle the crash window without deleting the only readable copy. Recording directly into +its owned directory avoids a later adoption gap, but requires verification of recorder behavior. + +No age-based expiry of unfinished captures. Disk pressure is a visible error and explicit user +choice. Cleanup may delete known terminal leftovers; unknown/unreadable records are retained +for reconciliation. A failed unlink does not make a completed capture pending again. + +## Note retry identity and downstream acceptance + +After an uncertain POST, replay its **original key and complete payload**. Keep newer transcript +edits separately, recover the note ID, and PATCH those edits to that same note. Editing after an +uncertain request must not silently generate another create. Include source, body, engine, +locale, and all other submitted fields in the persisted request contract. Save the returned +identity before clearing pending state; use existing server idempotency to close that crash window. + +Replace `Void` transcript handoff with an acknowledgment naming the durable recipient, scope, +capture ID, and accepted revision. A refused/full queue keeps the source recoverable. An +in-memory draft, scheduled Task, or callback invocation is insufficient acknowledgment. Source +cleanup requires durable acceptance, and stale acknowledgments cannot delete a newer revision. + +An assistant turn may spend money or execute tools. Do **not** automatically replay an uncertain +assistant submission after relaunch without server-supported idempotency/reconciliation. Restore +it for explicit review. A local persisted draft can accept ownership without sending a turn; +that is a separate boundary from successful remote submission. + +## Verification gates and implementation order + +1. Keep the committed process reproductions as a baseline. When introducing the coordinator, + adapt the probe to the real production account-scoped restore entry point; never restore from + observer output or duplicate recovery logic inside tests. Remove expected-failure markers only + when the corresponding guarantees pass. Strict mode must then pass all acceptance cases. +2. Add durable-store tests before implementation: account/server/recreated-account isolation, + ownership transfers, atomic-write failure, corrupt/missing audio, and terminal cleanup replay. +3. Implement owned recording storage and manifest transitions, then wire the shared coordinator + into account activation and sheet lifecycle. Verify real app terminate/relaunch, including + two-window ownership and account changes. Do not claim app integration from the native probe. +4. Test process death during actual M4A recording, after stop before transcription, during + transcription, during edited review, and after a failed disk checkpoint. Assert retained + recoverable material and no automatic microphone/assistant activity. +5. Exercise an actual local REST create with a lost response, crash, relaunch, and later edits. + Assert one note, the original create key, complete final body, and eventual cleanup. +6. Test create acknowledgment before cleanup, explicit discard before unlink, refused assistant + queue, accepted durable draft transfer, and uncertain assistant send. Assert no duplicated, + cross-account, or unintended submissions. Run iOS tests, Catalyst build, and UI verification. + +The bounded 2026-10-02 follow-on delivers the baseline and this contract only. Production +persistence is deliberately not partially wired into the app: unfinished recording durability, +destructive lifecycle callbacks, and unacknowledged handoff must be solved and verified together. diff --git a/ios/recovery-repro/README.md b/ios/recovery-repro/README.md new file mode 100644 index 0000000..0f1971b --- /dev/null +++ b/ios/recovery-repro/README.md @@ -0,0 +1,43 @@ +# Voice process-death reproduction + +An opt-in native macOS harness for the current voice recovery gap. It copies unmodified +production `VoiceCaptureFlow`, `CreateAttempt`, and shared validation source into a tiny SwiftPM +executable, then Python tests kill and relaunch that executable. No third-party dependency, +microphone, simulator, server, or app account is used. + +Run from the repo root with an owned DerivedData lease: + +```sh +VOICE_REPRO_DD=$(dd-lease path --project command-voice-repro --purpose tests) +trap 'dd-lease release "$VOICE_REPRO_DD"' EXIT +python3 ios/recovery-repro/test_voice_process_recovery.py --build-dir "$VOICE_REPRO_DD" +python3 ios/recovery-repro/test_voice_process_recovery.py --build-dir "$VOICE_REPRO_DD" --require-recovery +``` + +Current result: + +- Default characterization: **7 cases, 3 controls passed, 4 expected failures**. +- `--require-recovery`: **4 ordinary failures**, exit 1. This is the test-first acceptance baseline, + not a passing recovery feature. It intentionally stays outside the normal green iOS test suite. +- An unexpected success in default mode fails the suite, forcing the expected-failure marker + to be revisited when production behavior changes. + +Each crash setup waits for an atomic observation at its exact boundary, confirms the expected +state, sends SIGKILL, confirms signal termination and surviving audio, then launches a new PID. +Harness/precondition failures occur in `setUp` and cannot count as expected recovery failures. +Every child has a bounded wait and cleanup. Temporary fixtures are deleted at test end. + +The observation file is an **external oracle** only: the worker never reads it. A fresh launch +constructs the same default flow as the current recording sheet. The uncertain-create case +re-enters the exact original payload after relaunch to isolate retry-key loss from transcript +loss. It captures the request callback before a response; it does not contact a real server. + +The WAV fixture is valid finalized 16 kHz mono audio, but no decoding is invoked. These tests +prove loss of flow discovery, metadata and retry identity across actual process death. They do +not prove recovery of unfinished M4A, AVAudioSession behavior, actual app bootstrap, account +isolation, or UI integration. The stop checkpoint begins at `flow.adopt`, not an actual recorder. + +Implementation plan and ownership/retention contract: +[Voice recovery design](../../docs/decisions/2026-10-02-voice-recovery.md). +A future coordinator must be exercised through its production restore entry point. Merely teaching +this test worker to reload its observations would conceal the defect and is not an implementation. diff --git a/ios/recovery-repro/test_voice_process_recovery.py b/ios/recovery-repro/test_voice_process_recovery.py index 613d428..c59204c 100644 --- a/ios/recovery-repro/test_voice_process_recovery.py +++ b/ios/recovery-repro/test_voice_process_recovery.py @@ -79,12 +79,16 @@ def setUp(self): self.assertTrue(self.before["key"]) if scenario == "review": self.assertEqual(self.before["transcript"], "Latest edited review") + self.assertEqual(self.before["engine"], "sfspeech") child.kill() child.communicate(timeout=5) self.assertEqual(child.returncode, -signal.SIGKILL) self.assertTrue(self.audio.exists(), "SIGKILL must bypass all app cleanup callbacks") self.after = self.run_probe("retry" if scenario == "uncertain" else "relaunch") self.assertNotEqual(self.before["pid"], self.after["pid"]) + if scenario == "uncertain": + self.assertIsInstance(self.after.get("key"), str) + self.assertTrue(self.after["key"], "retry must reach the request boundary") @staticmethod def stop_child(child): @@ -96,7 +100,11 @@ def run_probe(self, mode): self.observation.unlink(missing_ok=True) subprocess.run([str(PROBE), mode, str(self.directory)], check=True, capture_output=True, text=True, timeout=10) - return json.loads(self.observation.read_text()) + value = json.loads(self.observation.read_text()) + for key in ("audio", "transcript", "engine", "pid"): + self.assertIn(key, value, f"probe observation missing {key}") + self.assertIsInstance(value[key], str) + return value @unittest.expectedFailure def test_stopped_recording_is_discoverable_after_process_death(self): @@ -117,6 +125,7 @@ def test_uncertain_create_reuses_key_after_process_death(self): def test_failed_save_reuses_key_without_process_death(self): result = self.run_probe("same-process-retry") + self.assertTrue(result["firstKey"]) self.assertEqual(result["firstKey"], result["secondKey"]) self.assertTrue(self.audio.exists()) diff --git a/state/ASTRA-1002.md b/state/ASTRA-1002.md index 67ef16e..e332882 100644 --- a/state/ASTRA-1002.md +++ b/state/ASTRA-1002.md @@ -199,3 +199,33 @@ No unfinished source change is being handed off. No task has been started merely remains missing; this is a reproducer, not a claim that the feature is implemented. - Logs: `/tmp/command-astra-1002/voice-process-{characterization,required}.log`. - One leased native DerivedData directory is in use for the harness and will be released. + +## Bounded follow-on FINAL — 12:39 EDT + +Done: +- `5dc9105`: real SIGKILL/fresh-process voice recovery reproductions using production flow code. +- Independent review hardened observation shape and pre-kill engine checks so harness failures + cannot be counted as expected durability failures. +- `ios/recovery-repro/README.md` documents lease/run commands, expected-failure semantics, + strict acceptance mode, and the exact production/integration limits. +- `docs/decisions/2026-10-02-voice-recovery.md` defines ownership, storage, lifecycle, retention, + privacy, original payload/key replay, acknowledged assistant handoff, and implementation gates. +- Durable evidence: `state/evidence/astra-1002/voice-process-reproduction.md`. +- OBSERVED final rerun: **7 cases, 3 passing controls, 4 expected failures** (0.137s); strict + `--require-recovery` mode: **4 failures** (0.143s, exit 1), confirming current missing durability. + Swift executable compiled successfully from actual production sources. `git diff --check` clean. + +In progress: **none**. Production voice persistence was not started. A partially wired store +would not safely resolve unfinished M4A finalization, view-lifecycle deletion, account ownership, +and downstream acknowledgment in this deadline. The requested reproduction/design deliverable +is complete; the missing feature is explicitly represented by failing acceptance requirements. + +Exact next step: read the design and run both reproducer modes from `ios/recovery-repro/README.md`. +Then add account-scoped durable-store tests (scope/recreated accounts, interrupted writes, ownership, +terminal cleanup) and verify actual AVAudioRecorder M4A behavior under process kill before wiring +persistence into the recorder/sheet. Adapt the probe to the real coordinator restoration entry +point; never restore from observer JSON. Do not remove expected-failure markers until implemented. + +Cleanup: read-only review helper finished; no helper implementation pending. The one native +DerivedData lease was released. No simulator/emulator was created, and no probe/build/server +process remains. Changes are on the same review branch/PR; no merge or deployment. diff --git a/state/evidence/astra-1002/voice-process-reproduction.md b/state/evidence/astra-1002/voice-process-reproduction.md new file mode 100644 index 0000000..23bbc65 --- /dev/null +++ b/state/evidence/astra-1002/voice-process-reproduction.md @@ -0,0 +1,43 @@ +# Voice process-death reproduction — 2026-10-02 + +Scope: native test-only subprocesses compile unmodified production voice flow, create-attempt, +and validation source. No production code changed. No app UI, simulator, microphone, or server +was started. The owned native DerivedData lease was released after verification. + +Observed after independent review and harness hardening: + +```text +$ python3 ios/recovery-repro/test_voice_process_recovery.py --build-dir "$LEASED_DD" +Ran 7 tests in 0.137s +OK (expected failures=4) + +$ python3 ios/recovery-repro/test_voice_process_recovery.py --build-dir "$LEASED_DD" --require-recovery +Ran 7 tests in 0.143s +FAILED (failures=4) +``` + +| Scenario | Before termination | Fresh process observation | Result | +|---|---|---|---| +| Stopped recording | Flow owns existing WAV | No audio URL discovered | Known missing recovery | +| Transcription in flight | Entered held transcriber callback | No audio URL discovered | Known missing recovery | +| Edited review | Latest edited text and sfspeech engine | Empty transcript and engine | Known missing recovery | +| Uncertain create | Request callback has original key | Same re-entered payload obtains a different key | Known missing recovery | +| Same-process failed-save retry | Two failed request callbacks | Same nonempty key; audio retained | Control passes | +| Explicit Cancel | Flow owns audio | Audio deleted | Control passes | +| Acknowledged note save | Flow owns reviewed audio | Audio deleted | Control passes | + +All crash cases check the exact SIGKILL exit signal, audio existence after death, and a different +PID on relaunch. JSON shape, engine preconditions, and process/checkpoint errors are validated +outside expected-failure assertions. An unexpected recovery success fails characterization mode. +The worker never reads the observer JSON; Python removes it before launching the next process. + +Limits: finalized fixture audio does not prove unfinalized M4A decodability. The request callback +is a simulated unresolved network boundary, not proof of server duplication. Fresh initialization +exercises the current production flow constructor, not real app/bootstrap/account restoration. +The probe must call the future production coordinator when it exists. See +[design contract](../../../docs/decisions/2026-10-02-voice-recovery.md) and +[harness instructions](../../../ios/recovery-repro/README.md). + +Raw local logs remain at `/tmp/command-astra-1002/voice-process-characterization.log` and +`/tmp/command-astra-1002/voice-process-required.log`. The above outcome is a confirmed test-first +baseline, **not an implemented or passing crash-recovery feature**. From ade857ecbf953dda5af401cc2f8914eba897c8db Mon Sep 17 00:00:00 2001 From: legitimate-apps <309192374+legitimate-apps@users.noreply.github.com> Date: Fri, 2 Oct 2026 12:57:38 -0400 Subject: [PATCH 14/27] Persist adopted voice audio with account-scoped restoration --- .../Transcription/VoiceCaptureFlow.swift | 47 +++++++++-- .../VoiceRecordingRecoveryStore.swift | 78 +++++++++++++++++++ .../VoiceRecordingRecoveryStoreTests.swift | 61 +++++++++++++++ ios/recovery-repro/README.md | 7 ++ ios/recovery-repro/VoiceRecoveryProbe.swift | 6 +- .../test_voice_process_recovery.py | 15 ++-- state/ASTRA-1002.md | 17 ++++ 7 files changed, 216 insertions(+), 15 deletions(-) create mode 100644 ios/Command/Transcription/VoiceRecordingRecoveryStore.swift create mode 100644 ios/CommandTests/VoiceRecordingRecoveryStoreTests.swift diff --git a/ios/Command/Transcription/VoiceCaptureFlow.swift b/ios/Command/Transcription/VoiceCaptureFlow.swift index 9297754..dc8c2dd 100644 --- a/ios/Command/Transcription/VoiceCaptureFlow.swift +++ b/ios/Command/Transcription/VoiceCaptureFlow.swift @@ -41,15 +41,27 @@ final class VoiceCaptureFlow { private(set) var isCancelled = false private let removeFile: (URL) -> Void + private let recovery: VoiceRecordingRecoveryStore? + private var recoveredRecordingID: UUID? - init(removeFile: @escaping (URL) -> Void = { try? FileManager.default.removeItem(at: $0) }) { + init(recovery: VoiceRecordingRecoveryStore? = nil, + restoring recording: VoiceRecordingRecoveryStore.Recording? = nil, + removeFile: @escaping (URL) -> Void = { try? FileManager.default.removeItem(at: $0) }) { self.removeFile = removeFile + self.recovery = recovery + if let recovery, let recording { + do { + audioURL = try recovery.audioURL(for: recording) + captureID = recording.id + recoveredRecordingID = recording.id + } catch { errorMessage = "Couldn't reopen the saved recording. Its files have been kept." } + } } /// A new recording is starting: drop the previous one and any leftover review state. func reset() { + guard discardAudio() else { return } captureID = UUID() - discardAudio() noteCreate.reset() transcript = "" engineUsed = "" @@ -70,12 +82,21 @@ final class VoiceCaptureFlow { /// The recorder finished; keep its file for transcription (and any retry of it). func adopt(_ url: URL) { - if let old = audioURL, old != url { removeFile(old) } - if audioURL != url { - captureID = UUID() - noteCreate.reset() - } + guard audioURL != url else { return } + guard discardAudio() else { return } + captureID = UUID() + noteCreate.reset() audioURL = url + if let recovery { + do { + let record = try recovery.keep(url, id: captureID) + audioURL = try recovery.audioURL(for: record) + recoveredRecordingID = record.id + removeFile(url) // ownership transferred only after durable metadata publication + } catch { + errorMessage = "Couldn't keep a recovery copy of this recording. Keep Command open." + } + } } /// Transcribe the kept recording. Returns the cleaned transcript when `immediateUse` applies @@ -149,8 +170,18 @@ final class VoiceCaptureFlow { discardAudio() } - private func discardAudio() { + @discardableResult + private func discardAudio() -> Bool { + if let recoveredRecordingID, let recovery { + do { try recovery.discard(recoveredRecordingID) } + catch { + errorMessage = "Couldn't remove the saved recording. Its cleanup can be retried." + return false + } + } if let url = audioURL { removeFile(url) } audioURL = nil + recoveredRecordingID = nil + return true } } diff --git a/ios/Command/Transcription/VoiceRecordingRecoveryStore.swift b/ios/Command/Transcription/VoiceRecordingRecoveryStore.swift new file mode 100644 index 0000000..3ceef66 --- /dev/null +++ b/ios/Command/Transcription/VoiceRecordingRecoveryStore.swift @@ -0,0 +1,78 @@ +import CryptoKit +import Foundation + +/// Owns stopped audio independently of a recorder's temporary file. App-level recovery UI and +/// account lifecycle wiring are separate: callers must explicitly opt into this durable owner. +@MainActor +final class VoiceRecordingRecoveryStore { + struct Recording: Codable { + let version: Int + let id: UUID + let filename: String + } + enum RecoveryError: Error { case invalidRecord } + let directory: URL + private let files = FileManager.default + + init(root: URL, server: URL, accountID: Int, username: String, accountCreatedAt: String) { + let identity = [server.absoluteString.trimmingCharacters(in: CharacterSet(charactersIn: "/")), + String(accountID), username, accountCreatedAt].joined(separator: "\n") + let scope = SHA256.hash(data: Data(identity.utf8)).map { String(format: "%02x", $0) }.joined() + directory = root.appendingPathComponent(scope, isDirectory: true) + } + + /// Publish metadata only after the copied audio exists. A crash during copy leaves the source + /// untouched and an undiscoverable partial directory; no successful capture is claimed. + func keep(_ source: URL, id: UUID) throws -> Recording { + let suffix = source.pathExtension.lowercased() + guard ["m4a", "wav", "caf"].contains(suffix) else { throw RecoveryError.invalidRecord } + let record = Recording(version: 1, id: id, filename: "recording.\(suffix)") + let folder = directory.appendingPathComponent(id.uuidString, isDirectory: true) + try files.createDirectory(at: folder, withIntermediateDirectories: true, + attributes: [.posixPermissions: 0o700]) + var protectedFolder = folder + var values = URLResourceValues(); values.isExcludedFromBackup = true + try protectedFolder.setResourceValues(values) + let destination = folder.appendingPathComponent(record.filename) + try files.copyItem(at: source, to: destination) + try files.setAttributes([.posixPermissions: 0o600, + .protectionKey: FileProtectionType.completeUntilFirstUserAuthentication], + ofItemAtPath: destination.path) + try JSONEncoder().encode(record).write(to: folder.appendingPathComponent("manifest.json"), + options: [.atomic, .completeFileProtectionUntilFirstUserAuthentication]) + try files.setAttributes([.posixPermissions: 0o600], + ofItemAtPath: folder.appendingPathComponent("manifest.json").path) + return record + } + + func recordings() throws -> [Recording] { + guard files.fileExists(atPath: directory.path) else { return [] } + return try files.contentsOfDirectory(at: directory, includingPropertiesForKeys: nil) + .sorted(by: { $0.lastPathComponent < $1.lastPathComponent }) + .compactMap { folder in + let manifest = folder.appendingPathComponent("manifest.json") + guard files.fileExists(atPath: manifest.path) else { return nil } + let record = try JSONDecoder().decode(Recording.self, from: Data(contentsOf: manifest)) + guard record.id.uuidString == folder.lastPathComponent else { throw RecoveryError.invalidRecord } + _ = try audioURL(for: record) + return record + } + } + + func audioURL(for record: Recording) throws -> URL { + guard record.version == 1, ["recording.m4a", "recording.wav", "recording.caf"].contains(record.filename) + else { throw RecoveryError.invalidRecord } + let url = directory.appendingPathComponent(record.id.uuidString).appendingPathComponent(record.filename) + guard files.fileExists(atPath: url.path) else { throw RecoveryError.invalidRecord } + return url + } + + /// Removing the manifest first makes a crash during cleanup non-replayable. Leftover audio + /// remains private; it is never mistaken for another pending recording. + func discard(_ id: UUID) throws { + let folder = directory.appendingPathComponent(id.uuidString, isDirectory: true) + let manifest = folder.appendingPathComponent("manifest.json") + if files.fileExists(atPath: manifest.path) { try files.removeItem(at: manifest) } + if files.fileExists(atPath: folder.path) { try files.removeItem(at: folder) } + } +} diff --git a/ios/CommandTests/VoiceRecordingRecoveryStoreTests.swift b/ios/CommandTests/VoiceRecordingRecoveryStoreTests.swift new file mode 100644 index 0000000..914cf0e --- /dev/null +++ b/ios/CommandTests/VoiceRecordingRecoveryStoreTests.swift @@ -0,0 +1,61 @@ +import XCTest +@testable import Command + +@MainActor +final class VoiceRecordingRecoveryStoreTests: XCTestCase { + private var root: URL! + override func setUp() async throws { root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) } + override func tearDown() async throws { try? FileManager.default.removeItem(at: root) } + private func store(server: String = "https://example.com", id: Int = 1, created: String = "first") -> VoiceRecordingRecoveryStore { + VoiceRecordingRecoveryStore(root: root.appendingPathComponent("recovery"), server: URL(string: server)!, + accountID: id, username: "tester", accountCreatedAt: created) + } + private func source() throws -> URL { + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + let url = root.appendingPathComponent("source.m4a") + try Data("opaque audio fixture".utf8).write(to: url) + return url + } + func testStoredCopySurvivesSourceRemovalAndFreshStore() throws { + let original = try source(), owner = store() + let record = try owner.keep(original, id: UUID()) + try FileManager.default.removeItem(at: original) + let restarted = store(), recovered = try XCTUnwrap(restarted.recordings().first) + XCTAssertEqual(record.id, recovered.id) + XCTAssertEqual(try Data(contentsOf: restarted.audioURL(for: recovered)), Data("opaque audio fixture".utf8)) + } + func testAccountServerAndRecreatedAccountCannotDiscoverAudio() throws { + _ = try store().keep(source(), id: UUID()) + XCTAssertTrue(try store(id: 2).recordings().isEmpty) + XCTAssertTrue(try store(server: "https://other.example.com").recordings().isEmpty) + XCTAssertTrue(try store(created: "recreated").recordings().isEmpty) + XCTAssertEqual(try store().recordings().count, 1) + } + func testDiscardDoesNotResurrectAndRemovesOwnedAudio() throws { + let owner = store(), record = try owner.keep(source(), id: UUID()) + let audio = try owner.audioURL(for: record) + try owner.discard(record.id) + XCTAssertFalse(FileManager.default.fileExists(atPath: audio.path)) + XCTAssertTrue(try store().recordings().isEmpty) + try owner.discard(record.id) + } + func testCorruptManifestIsReportedAndKept() throws { + let owner = store(), record = try owner.keep(source(), id: UUID()) + let manifest = owner.directory.appendingPathComponent(record.id.uuidString).appendingPathComponent("manifest.json") + try Data("broken".utf8).write(to: manifest) + XCTAssertThrowsError(try owner.recordings()) + XCTAssertTrue(FileManager.default.fileExists(atPath: manifest.path)) + XCTAssertNoThrow(try owner.audioURL(for: record)) + } + func testFailedCopyDoesNotPublishRecoveryAndKeepsSource() throws { + let owner = store(), original = try source(), id = UUID() + _ = try owner.keep(original, id: id) + XCTAssertThrowsError(try owner.keep(original, id: id)) + XCTAssertTrue(FileManager.default.fileExists(atPath: original.path)) + XCTAssertEqual(try owner.recordings().count, 1) + } + func testManifestCannotReferenceAnOutsideFile() throws { + let owner = store() + XCTAssertThrowsError(try owner.audioURL(for: .init(version: 1, id: UUID(), filename: "../../outside.m4a"))) + } +} diff --git a/ios/recovery-repro/README.md b/ios/recovery-repro/README.md index 0f1971b..9d60829 100644 --- a/ios/recovery-repro/README.md +++ b/ios/recovery-repro/README.md @@ -41,3 +41,10 @@ Implementation plan and ownership/retention contract: [Voice recovery design](../../docs/decisions/2026-10-02-voice-recovery.md). A future coordinator must be exercised through its production restore entry point. Merely teaching this test worker to reload its observations would conceal the defect and is not an implementation. + +## Implementation step 1 (12:57 EDT) + +The probe now uses the production account-scoped audio store and explicit flow restoration. +Stopped/transcribing audio passes SIGKILL/relaunch checks: **5 cases pass, 2 remain expected +failures** (review state and retry identity). The recording sheet is not wired to this store yet. +The four-failure output above is the historical baseline. See the run state for current progress. diff --git a/ios/recovery-repro/VoiceRecoveryProbe.swift b/ios/recovery-repro/VoiceRecoveryProbe.swift index d2f9ccf..a9ddca5 100644 --- a/ios/recovery-repro/VoiceRecoveryProbe.swift +++ b/ios/recovery-repro/VoiceRecoveryProbe.swift @@ -8,7 +8,11 @@ struct VoiceRecoveryProbe { let args = CommandLine.arguments let mode = args[1], directory = URL(fileURLWithPath: args[2], isDirectory: true) let audio = directory.appendingPathComponent("recording.wav") - let flow = VoiceCaptureFlow() + let recovery = VoiceRecordingRecoveryStore(root: directory.appendingPathComponent("recovery"), + server: URL(string: "https://example.invalid")!, accountID: 1, + username: "recovery-test", accountCreatedAt: "2026-10-02") + let restored = (mode == "relaunch" || mode == "retry") ? try recovery.recordings().first : nil + let flow = VoiceCaptureFlow(recovery: recovery, restoring: restored) func snapshot(_ extra: [String: String] = [:]) throws { var value = extra value["audio"] = flow.audioURL?.path ?? "" diff --git a/ios/recovery-repro/test_voice_process_recovery.py b/ios/recovery-repro/test_voice_process_recovery.py index c59204c..61e99ed 100644 --- a/ios/recovery-repro/test_voice_process_recovery.py +++ b/ios/recovery-repro/test_voice_process_recovery.py @@ -1,7 +1,7 @@ #!/usr/bin/env python3 """Real process-death characterization against copied, unmodified production Swift sources. -Default: 3 controls + 4 explicitly expected failures. --require-recovery turns those +Default: 5 passing cases + 2 explicitly expected failures. --require-recovery turns those known gaps into ordinary failing acceptance tests. No simulator, microphone or server. """ import argparse @@ -29,7 +29,8 @@ def build_probe(build_dir): targets: [.executableTarget(name: "Probe")]) ''') for relative in ( - "Transcription/VoiceCaptureFlow.swift", "Networking/CreateAttempt.swift", + "Transcription/VoiceCaptureFlow.swift", "Transcription/VoiceRecordingRecoveryStore.swift", + "Networking/CreateAttempt.swift", "Widgets/AssistantSurfaceLogic.swift", ): source = ROOT / "ios/Command" / relative @@ -71,7 +72,11 @@ def setUp(self): self.assertTrue(self.observation.exists(), "child failed to reach the requested checkpoint") self.before = json.loads(self.observation.read_text()) self.assertEqual(child.pid, int(self.before["pid"])) - self.assertEqual(self.before["audio"], str(self.audio)) + self.audio = Path(self.before["audio"]) + self.assertTrue(self.audio.is_relative_to(self.directory / "recovery")) + self.assertTrue(self.audio.exists()) + with wave.open(str(self.audio), "rb") as recovered_audio: + self.assertEqual(recovered_audio.getnframes(), 1600) if scenario == "transcribing": self.assertEqual(self.before["checkpoint"], "inside-transcriber") if scenario == "uncertain": @@ -106,11 +111,9 @@ def run_probe(self, mode): self.assertIsInstance(value[key], str) return value - @unittest.expectedFailure def test_stopped_recording_is_discoverable_after_process_death(self): self.assertEqual(self.after["audio"], str(self.audio)) - @unittest.expectedFailure def test_transcribing_recording_is_discoverable_after_process_death(self): self.assertEqual(self.after["audio"], str(self.audio)) @@ -127,7 +130,7 @@ def test_failed_save_reuses_key_without_process_death(self): result = self.run_probe("same-process-retry") self.assertTrue(result["firstKey"]) self.assertEqual(result["firstKey"], result["secondKey"]) - self.assertTrue(self.audio.exists()) + self.assertTrue(Path(result["audio"]).exists()) def test_explicit_cancel_removes_recording(self): result = self.run_probe("cancel") diff --git a/state/ASTRA-1002.md b/state/ASTRA-1002.md index e332882..8959b0b 100644 --- a/state/ASTRA-1002.md +++ b/state/ASTRA-1002.md @@ -229,3 +229,20 @@ point; never restore from observer JSON. Do not remove expected-failure markers Cleanup: read-only review helper finished; no helper implementation pending. The one native DerivedData lease was released. No simulator/emulator was created, and no probe/build/server process remains. Changes are on the same review branch/PR; no merge or deployment. + +## Reset-window implementation step 1 — 12:57 EDT +- Operator reopened implementation until reset/stop instruction. Implemented an opt-in production + VoiceRecordingRecoveryStore and VoiceCaptureFlow restoration path for **stopped audio only**. +- Atomic manifest publication follows successful protected audio copy; account/server/recreated + account scopes are isolated. Original temporary audio is released only after transfer succeeds. + Explicit terminal cleanup removes the manifest before audio so leftover files cannot replay. +- Process probe now uses this actual production restore API, never its observer file. OBSERVED: + stopped and transcribing SIGKILL/relaunch assertions now PASS; review text and uncertain create + key remain expected failures (**5 passing cases, 2 expected failures**). +- OBSERVED **26 native XCTest cases passed**, including all 20 existing voice-flow cases and six + new storage tests (source removal, scope isolation, discard, corruption, failed copy, path safety). + Logs: `/tmp/command-astra-1002/voice-audio-{step,xctest}.log`. +- IMPORTANT: RecordingSheet still uses the nonpersistent default; account/UI lifecycle integration + is not yet wired. This is a verified production primitive, NOT a shipped end-to-end voice fix. +- Next: persist review text/engine atomically and turn the corresponding process assertion green; + then pending original request/key, account coordinator, sheet dismissal semantics and app tests. From 282973f4bdca793cf328b3977086f9fa6c5f4d67 Mon Sep 17 00:00:00 2001 From: legitimate-apps <309192374+legitimate-apps@users.noreply.github.com> Date: Fri, 2 Oct 2026 12:59:25 -0400 Subject: [PATCH 15/27] Checkpoint and restore edited voice review state --- .../Transcription/VoiceCaptureFlow.swift | 13 +++++++++++ .../VoiceRecordingRecoveryStore.swift | 14 ++++++++++++ .../VoiceRecordingRecoveryStoreTests.swift | 22 +++++++++++++++++++ ios/recovery-repro/README.md | 6 +++++ .../test_voice_process_recovery.py | 3 +-- state/ASTRA-1002.md | 15 +++++++++++++ 6 files changed, 71 insertions(+), 2 deletions(-) diff --git a/ios/Command/Transcription/VoiceCaptureFlow.swift b/ios/Command/Transcription/VoiceCaptureFlow.swift index dc8c2dd..1e8b341 100644 --- a/ios/Command/Transcription/VoiceCaptureFlow.swift +++ b/ios/Command/Transcription/VoiceCaptureFlow.swift @@ -24,9 +24,11 @@ final class VoiceCaptureFlow { if transcript != oldValue { reviewRevision = UUID() noteCreate.reset() + if !applyingTranscription { persistReview() } } } } + private var applyingTranscription = false /// Changes whenever another capture replaces this one, even if it reuses a file URL. private(set) var captureID = UUID() private var reviewRevision = UUID() @@ -54,6 +56,8 @@ final class VoiceCaptureFlow { audioURL = try recovery.audioURL(for: recording) captureID = recording.id recoveredRecordingID = recording.id + transcript = recording.transcript ?? "" + engineUsed = recording.engine ?? "" } catch { errorMessage = "Couldn't reopen the saved recording. Its files have been kept." } } } @@ -113,10 +117,13 @@ final class VoiceCaptureFlow { let result = try await transcribe(url) guard !isCancelled, !Task.isCancelled, captureID == capture, reviewRevision == revision, transcriptionAttempt == attempt else { return nil } + applyingTranscription = true transcript = result.text engineUsed = result.engine + applyingTranscription = false errorMessage = nil transcriptionFailed = false + persistReview() if immediateUse, let cleaned = try? VoiceInputValidator.cleaned(result.text) { discardAudio() return cleaned @@ -170,6 +177,12 @@ final class VoiceCaptureFlow { discardAudio() } + private func persistReview() { + guard let recovery, let recoveredRecordingID else { return } + do { try recovery.saveReview(id: recoveredRecordingID, transcript: transcript, engine: engineUsed) } + catch { errorMessage = "Couldn't keep your latest review edits. Keep Command open until they save." } + } + @discardableResult private func discardAudio() -> Bool { if let recoveredRecordingID, let recovery { diff --git a/ios/Command/Transcription/VoiceRecordingRecoveryStore.swift b/ios/Command/Transcription/VoiceRecordingRecoveryStore.swift index 3ceef66..58855d0 100644 --- a/ios/Command/Transcription/VoiceRecordingRecoveryStore.swift +++ b/ios/Command/Transcription/VoiceRecordingRecoveryStore.swift @@ -9,6 +9,8 @@ final class VoiceRecordingRecoveryStore { let version: Int let id: UUID let filename: String + var transcript: String? = nil + var engine: String? = nil } enum RecoveryError: Error { case invalidRecord } let directory: URL @@ -45,6 +47,18 @@ final class VoiceRecordingRecoveryStore { return record } + func saveReview(id: UUID, transcript: String, engine: String) throws { + let manifest = directory.appendingPathComponent(id.uuidString).appendingPathComponent("manifest.json") + var record = try JSONDecoder().decode(Recording.self, from: Data(contentsOf: manifest)) + guard record.id == id else { throw RecoveryError.invalidRecord } + _ = try audioURL(for: record) + record.transcript = transcript + record.engine = engine + try JSONEncoder().encode(record).write(to: manifest, + options: [.atomic, .completeFileProtectionUntilFirstUserAuthentication]) + try files.setAttributes([.posixPermissions: 0o600], ofItemAtPath: manifest.path) + } + func recordings() throws -> [Recording] { guard files.fileExists(atPath: directory.path) else { return [] } return try files.contentsOfDirectory(at: directory, includingPropertiesForKeys: nil) diff --git a/ios/CommandTests/VoiceRecordingRecoveryStoreTests.swift b/ios/CommandTests/VoiceRecordingRecoveryStoreTests.swift index 914cf0e..835e214 100644 --- a/ios/CommandTests/VoiceRecordingRecoveryStoreTests.swift +++ b/ios/CommandTests/VoiceRecordingRecoveryStoreTests.swift @@ -54,6 +54,28 @@ final class VoiceRecordingRecoveryStoreTests: XCTestCase { XCTAssertTrue(FileManager.default.fileExists(atPath: original.path)) XCTAssertEqual(try owner.recordings().count, 1) } + func testReviewRestoresLatestEditsAndEngineWithAudio() async throws { + let owner = store(), flow = VoiceCaptureFlow(recovery: owner) + flow.adopt(try source()) + _ = await flow.transcribe(immediateUse: false) { _ in ("spoken", "parakeet-v3") } + flow.transcript = "edited after transcription" + let record = try XCTUnwrap(store().recordings().first) + let restored = VoiceCaptureFlow(recovery: store(), restoring: record) + XCTAssertEqual(restored.transcript, "edited after transcription") + XCTAssertEqual(restored.engineUsed, "parakeet-v3") + XCTAssertEqual(restored.captureID, flow.captureID) + XCTAssertNotNil(restored.audioURL) + } + func testReviewWriteFailureKeepsExistingAudioAndSurfacesError() throws { + let owner = store(), flow = VoiceCaptureFlow(recovery: owner) + flow.adopt(try source()) + let manifest = owner.directory.appendingPathComponent(flow.captureID.uuidString).appendingPathComponent("manifest.json") + try Data("damaged manifest".utf8).write(to: manifest) + flow.transcript = "keep these edits in memory" + XCTAssertNotNil(flow.errorMessage) + XCTAssertEqual(try Data(contentsOf: manifest), Data("damaged manifest".utf8)) + XCTAssertTrue(FileManager.default.fileExists(atPath: try XCTUnwrap(flow.audioURL).path)) + } func testManifestCannotReferenceAnOutsideFile() throws { let owner = store() XCTAssertThrowsError(try owner.audioURL(for: .init(version: 1, id: UUID(), filename: "../../outside.m4a"))) diff --git a/ios/recovery-repro/README.md b/ios/recovery-repro/README.md index 9d60829..a0e1613 100644 --- a/ios/recovery-repro/README.md +++ b/ios/recovery-repro/README.md @@ -48,3 +48,9 @@ The probe now uses the production account-scoped audio store and explicit flow r Stopped/transcribing audio passes SIGKILL/relaunch checks: **5 cases pass, 2 remain expected failures** (review state and retry identity). The recording sheet is not wired to this store yet. The four-failure output above is the historical baseline. See the run state for current progress. + +## Implementation step 2 (12:59 EDT) + +Production restoration now reloads atomic review text and engine checkpoints as well as audio. +Current result: **6 passing cases, 1 expected failure** (uncertain-create identity). The sheet +still uses its nonpersistent default. Native source tests cover review restore and write failure. diff --git a/ios/recovery-repro/test_voice_process_recovery.py b/ios/recovery-repro/test_voice_process_recovery.py index 61e99ed..a187cc1 100644 --- a/ios/recovery-repro/test_voice_process_recovery.py +++ b/ios/recovery-repro/test_voice_process_recovery.py @@ -1,7 +1,7 @@ #!/usr/bin/env python3 """Real process-death characterization against copied, unmodified production Swift sources. -Default: 5 passing cases + 2 explicitly expected failures. --require-recovery turns those +Default: 6 passing cases + 1 explicitly expected failure. --require-recovery turns those known gaps into ordinary failing acceptance tests. No simulator, microphone or server. """ import argparse @@ -117,7 +117,6 @@ def test_stopped_recording_is_discoverable_after_process_death(self): def test_transcribing_recording_is_discoverable_after_process_death(self): self.assertEqual(self.after["audio"], str(self.audio)) - @unittest.expectedFailure def test_review_text_and_engine_survive_process_death(self): self.assertEqual((self.after["transcript"], self.after["engine"]), ("Latest edited review", "sfspeech")) diff --git a/state/ASTRA-1002.md b/state/ASTRA-1002.md index 8959b0b..fc82de0 100644 --- a/state/ASTRA-1002.md +++ b/state/ASTRA-1002.md @@ -246,3 +246,18 @@ process remains. Changes are on the same review branch/PR; no merge or deploymen is not yet wired. This is a verified production primitive, NOT a shipped end-to-end voice fix. - Next: persist review text/engine atomically and turn the corresponding process assertion green; then pending original request/key, account coordinator, sheet dismissal semantics and app tests. + +## Reset-window implementation step 2 — 12:59 EDT +- Added atomic review text/engine checkpoints to the same recording manifest and production flow + restoration. Transcription results checkpoint text+engine together; later editor changes persist. + Corrupt/write failures retain audio and surface an error rather than silently deleting evidence. +- OBSERVED hard-kill suite now **6 passing cases, 1 expected failure**: stopped audio, in-flight + transcription audio and edited review all restore through the production API. Uncertain-create + identity is still missing and intentionally red. Log: `voice-review-step.log` in run scratch. +- OBSERVED **28 native XCTest cases passed**, including existing voice behavior plus review restore + and failed-write preservation. Log: `/tmp/command-astra-1002/voice-review-xctest.log`. +- App/account/sheet integration is STILL NOT wired; microphone-in-progress recovery, durable + assistant handoff, original pending create reconciliation, and full app verification remain. +- Next immediate action: compile the integrated iOS target (no simulator boot) to verify the new + production source on its actual platform. Then tackle original request reconciliation before + enabling this store in RecordingSheet. Do not describe these primitives as complete app recovery. From 30cebbf9ede7dc8ac956473324c33590bbad8d60 Mon Sep 17 00:00:00 2001 From: legitimate-apps <309192374+legitimate-apps@users.noreply.github.com> Date: Fri, 2 Oct 2026 13:02:47 -0400 Subject: [PATCH 16/27] Persist voice retry identity before submitting an unchanged capture --- .../Transcription/VoiceCaptureFlow.swift | 4 ++++ .../VoiceRecordingRecoveryStore.swift | 14 +++++++++++ .../VoiceRecordingRecoveryStoreTests.swift | 24 +++++++++++++++++++ ios/recovery-repro/README.md | 12 ++++++++++ .../test_voice_process_recovery.py | 5 ++-- state/ASTRA-1002.md | 15 ++++++++++++ 6 files changed, 71 insertions(+), 3 deletions(-) diff --git a/ios/Command/Transcription/VoiceCaptureFlow.swift b/ios/Command/Transcription/VoiceCaptureFlow.swift index 1e8b341..fbbe985 100644 --- a/ios/Command/Transcription/VoiceCaptureFlow.swift +++ b/ios/Command/Transcription/VoiceCaptureFlow.swift @@ -58,6 +58,7 @@ final class VoiceCaptureFlow { recoveredRecordingID = recording.id transcript = recording.transcript ?? "" engineUsed = recording.engine ?? "" + noteCreate = recording.createAttempt ?? CreateAttempt() } catch { errorMessage = "Couldn't reopen the saved recording. Its files have been kept." } } } @@ -149,6 +150,9 @@ final class VoiceCaptureFlow { do { let engine = engineUsed.isEmpty ? "sfspeech" : engineUsed let key = try noteCreate.key(for: NotePayload(text: text, engine: engine)) + if let recovery, let recoveredRecordingID { + try recovery.saveCreateAttempt(id: recoveredRecordingID, attempt: noteCreate) + } let failure = await save(text, engine, key) guard !isCancelled, !Task.isCancelled, captureID == capture, reviewRevision == revision else { return false } diff --git a/ios/Command/Transcription/VoiceRecordingRecoveryStore.swift b/ios/Command/Transcription/VoiceRecordingRecoveryStore.swift index 58855d0..e80f493 100644 --- a/ios/Command/Transcription/VoiceRecordingRecoveryStore.swift +++ b/ios/Command/Transcription/VoiceRecordingRecoveryStore.swift @@ -11,6 +11,7 @@ final class VoiceRecordingRecoveryStore { let filename: String var transcript: String? = nil var engine: String? = nil + var createAttempt: CreateAttempt? = nil } enum RecoveryError: Error { case invalidRecord } let directory: URL @@ -59,6 +60,19 @@ final class VoiceRecordingRecoveryStore { try files.setAttributes([.posixPermissions: 0o600], ofItemAtPath: manifest.path) } + /// A failed checkpoint must prevent the request: otherwise relaunch could manufacture a + /// new key for a create whose outcome is unknown. The encoded attempt includes its payload. + func saveCreateAttempt(id: UUID, attempt: CreateAttempt) throws { + let manifest = directory.appendingPathComponent(id.uuidString).appendingPathComponent("manifest.json") + var record = try JSONDecoder().decode(Recording.self, from: Data(contentsOf: manifest)) + guard record.id == id else { throw RecoveryError.invalidRecord } + _ = try audioURL(for: record) + record.createAttempt = attempt + try JSONEncoder().encode(record).write(to: manifest, + options: [.atomic, .completeFileProtectionUntilFirstUserAuthentication]) + try files.setAttributes([.posixPermissions: 0o600], ofItemAtPath: manifest.path) + } + func recordings() throws -> [Recording] { guard files.fileExists(atPath: directory.path) else { return [] } return try files.contentsOfDirectory(at: directory, includingPropertiesForKeys: nil) diff --git a/ios/CommandTests/VoiceRecordingRecoveryStoreTests.swift b/ios/CommandTests/VoiceRecordingRecoveryStoreTests.swift index 835e214..63de4ab 100644 --- a/ios/CommandTests/VoiceRecordingRecoveryStoreTests.swift +++ b/ios/CommandTests/VoiceRecordingRecoveryStoreTests.swift @@ -76,6 +76,30 @@ final class VoiceRecordingRecoveryStoreTests: XCTestCase { XCTAssertEqual(try Data(contentsOf: manifest), Data("damaged manifest".utf8)) XCTAssertTrue(FileManager.default.fileExists(atPath: try XCTUnwrap(flow.audioURL).path)) } + func testUncertainRequestIdentitySurvivesFreshFlowForSamePayload() async throws { + let owner = store(), flow = VoiceCaptureFlow(recovery: owner) + flow.adopt(try source()); flow.transcript = "same payload" + var originalKey = "" + _ = await flow.saveNote { _, _, key in originalKey = key; return "response lost" } + let restored = VoiceCaptureFlow(recovery: store(), restoring: try XCTUnwrap(store().recordings().first)) + var replayKey = "" + _ = await restored.saveNote { text, _, key in + XCTAssertEqual(text, "same payload"); replayKey = key; return "still unavailable" + } + XCTAssertFalse(originalKey.isEmpty) + XCTAssertEqual(originalKey, replayKey) + } + func testFailedRequestCheckpointPreventsNetworkSubmission() async throws { + let owner = store(), flow = VoiceCaptureFlow(recovery: owner) + flow.adopt(try source()); flow.transcript = "not safe to send" + let manifest = owner.directory.appendingPathComponent(flow.captureID.uuidString).appendingPathComponent("manifest.json") + try Data("damaged manifest".utf8).write(to: manifest) + var sent = false + let saved = await flow.saveNote { _, _, _ in sent = true; return nil } + XCTAssertFalse(saved); XCTAssertFalse(sent) + XCTAssertNotNil(flow.errorMessage) + XCTAssertNotNil(flow.audioURL) + } func testManifestCannotReferenceAnOutsideFile() throws { let owner = store() XCTAssertThrowsError(try owner.audioURL(for: .init(version: 1, id: UUID(), filename: "../../outside.m4a"))) diff --git a/ios/recovery-repro/README.md b/ios/recovery-repro/README.md index a0e1613..7d8d1a5 100644 --- a/ios/recovery-repro/README.md +++ b/ios/recovery-repro/README.md @@ -1,5 +1,10 @@ # Voice process-death reproduction +**Current implementation checkpoint:** all seven original cases pass in strict mode through the +opt-in production audio/review/attempt restore API. RecordingSheet is not yet wired to it; this +is not end-to-end app recovery. Later edits after an uncertain create still need note-ID/PATCH +reconciliation. The historical baseline and intermediate results below document progression. + An opt-in native macOS harness for the current voice recovery gap. It copies unmodified production `VoiceCaptureFlow`, `CreateAttempt`, and shared validation source into a tiny SwiftPM executable, then Python tests kill and relaunch that executable. No third-party dependency, @@ -54,3 +59,10 @@ The four-failure output above is the historical baseline. See the run state for Production restoration now reloads atomic review text and engine checkpoints as well as audio. Current result: **6 passing cases, 1 expected failure** (uncertain-create identity). The sheet still uses its nonpersistent default. Native source tests cover review restore and write failure. + +## Implementation step 3 (13:02 EDT) + +The unchanged reviewed capture now restores its persisted create key and payload. A failed +request checkpoint blocks submission. Strict mode: **7 passed, no expected failures**. Native +source suite: **30 passed**. Production app/account/UI integration and later-edit reconciliation +remain required; passing this initial matrix alone does not establish complete voice recovery. diff --git a/ios/recovery-repro/test_voice_process_recovery.py b/ios/recovery-repro/test_voice_process_recovery.py index a187cc1..bbbfee2 100644 --- a/ios/recovery-repro/test_voice_process_recovery.py +++ b/ios/recovery-repro/test_voice_process_recovery.py @@ -1,8 +1,8 @@ #!/usr/bin/env python3 """Real process-death characterization against copied, unmodified production Swift sources. -Default: 6 passing cases + 1 explicitly expected failure. --require-recovery turns those -known gaps into ordinary failing acceptance tests. No simulator, microphone or server. +All seven baseline cases now pass through the opt-in production restore API. +--require-recovery remains compatible with the original failing-baseline invocation. No simulator, microphone or server. """ import argparse import json @@ -121,7 +121,6 @@ def test_review_text_and_engine_survive_process_death(self): self.assertEqual((self.after["transcript"], self.after["engine"]), ("Latest edited review", "sfspeech")) - @unittest.expectedFailure def test_uncertain_create_reuses_key_after_process_death(self): self.assertEqual(self.after["key"], self.before["key"]) diff --git a/state/ASTRA-1002.md b/state/ASTRA-1002.md index fc82de0..252c366 100644 --- a/state/ASTRA-1002.md +++ b/state/ASTRA-1002.md @@ -261,3 +261,18 @@ process remains. Changes are on the same review branch/PR; no merge or deploymen - Next immediate action: compile the integrated iOS target (no simulator boot) to verify the new production source on its actual platform. Then tackle original request reconciliation before enabling this store in RecordingSheet. Do not describe these primitives as complete app recovery. + +## Reset-window implementation step 3 — 13:02 EDT +- Persist and restore CreateAttempt (key plus encoded original text/engine payload) before a + request may begin. A failed metadata checkpoint now prevents the network submission. +- OBSERVED original process-death baseline in strict mode: **all 7 cases pass, no expected + failures**. The unchanged reviewed capture reuses its key after hard kill and fresh process. +- OBSERVED **30 native XCTest cases pass**, including same-payload restoration and proof that a + failed request checkpoint does not invoke the transport. Logs: `voice-key-{step,xctest}.log`. +- OBSERVED step-2 integrated iOS build succeeded (`voice-recovery-ios-build.log`); checking the + latest step-3 target is next. No simulator has been booted in this implementation window. +- IMPORTANT REMAINING: these guarantees use opt-in production restore APIs in the process probe. + RecordingSheet/account coordinator still do not opt in. Editing text after an uncertain create + still follows existing changed-payload/new-intent behavior; preserving one note while applying + later edits requires recording the returned note ID and PATCH reconciliation, not just a key. + Assistant durable handoff, same-capture multiwindow ownership and actual M4A kill behavior remain. From b66963478ea6022880733effe84721d43f417cee Mon Sep 17 00:00:00 2001 From: legitimate-apps <309192374+legitimate-apps@users.noreply.github.com> Date: Fri, 2 Oct 2026 13:07:14 -0400 Subject: [PATCH 17/27] Keep voice submission checkpoints coherent after disk failures --- .../Transcription/VoiceCaptureFlow.swift | 12 ++++++-- .../VoiceRecordingRecoveryStore.swift | 4 ++- .../VoiceRecordingRecoveryStoreTests.swift | 30 +++++++++++++++++++ state/ASTRA-1002.md | 14 +++++++++ 4 files changed, 57 insertions(+), 3 deletions(-) diff --git a/ios/Command/Transcription/VoiceCaptureFlow.swift b/ios/Command/Transcription/VoiceCaptureFlow.swift index fbbe985..988699e 100644 --- a/ios/Command/Transcription/VoiceCaptureFlow.swift +++ b/ios/Command/Transcription/VoiceCaptureFlow.swift @@ -143,6 +143,10 @@ final class VoiceCaptureFlow { /// A failed current save keeps the recording and shows the error for retry. func saveNote(using save: (_ text: String, _ engine: String, _ key: String) async -> String?) async -> Bool { guard !saving, !isCancelled, !Task.isCancelled else { return false } + if recovery != nil && recoveredRecordingID == nil { + errorMessage = "This recording has no recovery copy yet. Keep Command open; it has not been sent." + return false + } let capture = captureID, revision = reviewRevision let text = transcript saving = true @@ -151,7 +155,7 @@ final class VoiceCaptureFlow { let engine = engineUsed.isEmpty ? "sfspeech" : engineUsed let key = try noteCreate.key(for: NotePayload(text: text, engine: engine)) if let recovery, let recoveredRecordingID { - try recovery.saveCreateAttempt(id: recoveredRecordingID, attempt: noteCreate) + try recovery.saveCreateAttempt(id: recoveredRecordingID, attempt: noteCreate, transcript: text, engine: engine) } let failure = await save(text, engine, key) guard !isCancelled, !Task.isCancelled, captureID == capture, @@ -182,7 +186,11 @@ final class VoiceCaptureFlow { } private func persistReview() { - guard let recovery, let recoveredRecordingID else { return } + guard let recovery else { return } + guard let recoveredRecordingID else { + if audioURL != nil { errorMessage = "Couldn't keep a recovery copy of this recording. Keep Command open." } + return + } do { try recovery.saveReview(id: recoveredRecordingID, transcript: transcript, engine: engineUsed) } catch { errorMessage = "Couldn't keep your latest review edits. Keep Command open until they save." } } diff --git a/ios/Command/Transcription/VoiceRecordingRecoveryStore.swift b/ios/Command/Transcription/VoiceRecordingRecoveryStore.swift index e80f493..10807a3 100644 --- a/ios/Command/Transcription/VoiceRecordingRecoveryStore.swift +++ b/ios/Command/Transcription/VoiceRecordingRecoveryStore.swift @@ -62,12 +62,14 @@ final class VoiceRecordingRecoveryStore { /// A failed checkpoint must prevent the request: otherwise relaunch could manufacture a /// new key for a create whose outcome is unknown. The encoded attempt includes its payload. - func saveCreateAttempt(id: UUID, attempt: CreateAttempt) throws { + func saveCreateAttempt(id: UUID, attempt: CreateAttempt, transcript: String, engine: String) throws { let manifest = directory.appendingPathComponent(id.uuidString).appendingPathComponent("manifest.json") var record = try JSONDecoder().decode(Recording.self, from: Data(contentsOf: manifest)) guard record.id == id else { throw RecoveryError.invalidRecord } _ = try audioURL(for: record) record.createAttempt = attempt + record.transcript = transcript + record.engine = engine try JSONEncoder().encode(record).write(to: manifest, options: [.atomic, .completeFileProtectionUntilFirstUserAuthentication]) try files.setAttributes([.posixPermissions: 0o600], ofItemAtPath: manifest.path) diff --git a/ios/CommandTests/VoiceRecordingRecoveryStoreTests.swift b/ios/CommandTests/VoiceRecordingRecoveryStoreTests.swift index 63de4ab..d7b662b 100644 --- a/ios/CommandTests/VoiceRecordingRecoveryStoreTests.swift +++ b/ios/CommandTests/VoiceRecordingRecoveryStoreTests.swift @@ -100,6 +100,36 @@ final class VoiceRecordingRecoveryStoreTests: XCTestCase { XCTAssertNotNil(flow.errorMessage) XCTAssertNotNil(flow.audioURL) } + func testRecoveredDiskCheckpointsSubmittedReviewAndKeyTogether() async throws { + let owner = store(), flow = VoiceCaptureFlow(recovery: owner) + flow.adopt(try source()); flow.transcript = "old review" + let manifest = owner.directory.appendingPathComponent(flow.captureID.uuidString).appendingPathComponent("manifest.json") + let old = try Data(contentsOf: manifest) + try Data("unreadable".utf8).write(to: manifest) + flow.transcript = "submitted review" + XCTAssertNotNil(flow.errorMessage) + try old.write(to: manifest) + var submittedKey = "" + _ = await flow.saveNote { _, _, key in submittedKey = key; return "response lost" } + let restored = VoiceCaptureFlow(recovery: store(), restoring: try XCTUnwrap(store().recordings().first)) + XCTAssertEqual(restored.transcript, "submitted review") + _ = await restored.saveNote { text, _, key in + XCTAssertEqual(text, "submitted review"); XCTAssertEqual(key, submittedKey); return "response lost" + } + } + func testFailedAdoptionStaysVisibleAndCannotSubmitWithoutCheckpoint() async throws { + let original = try source() + try Data("not a directory".utf8).write(to: root.appendingPathComponent("recovery")) + let flow = VoiceCaptureFlow(recovery: store()) + flow.adopt(original) + XCTAssertNotNil(flow.errorMessage) + _ = await flow.transcribe(immediateUse: false) { _ in ("recovered in memory", "sfspeech") } + XCTAssertNotNil(flow.errorMessage) + var sent = false + let saved = await flow.saveNote { _, _, _ in sent = true; return nil } + XCTAssertFalse(sent); XCTAssertFalse(saved) + XCTAssertTrue(FileManager.default.fileExists(atPath: original.path)) + } func testManifestCannotReferenceAnOutsideFile() throws { let owner = store() XCTAssertThrowsError(try owner.audioURL(for: .init(version: 1, id: UUID(), filename: "../../outside.m4a"))) diff --git a/state/ASTRA-1002.md b/state/ASTRA-1002.md index 252c366..9b6e147 100644 --- a/state/ASTRA-1002.md +++ b/state/ASTRA-1002.md @@ -276,3 +276,17 @@ process remains. Changes are on the same review branch/PR; no merge or deploymen still follows existing changed-payload/new-intent behavior; preserving one note while applying later edits requires recording the returned note ID and PATCH reconciliation, not just a key. Assistant durable handoff, same-capture multiwindow ownership and actual M4A kill behavior remain. + +## Reset-window disk-failure hardening — 13:07 EDT +- Independent review found two real failure paths. Added regressions first: both failed against + the prior source (**2 tests, 7 assertion failures**, `voice-disk-controls-red.log`). +- A request checkpoint now atomically stores its submitted review/engine AND attempt, preventing + a recovered disk from pairing an old review with a newer pending key. A failed durable adoption + remains visible after transcription and blocks note submission without a checkpoint. +- OBSERVED fixed source: **32 native tests passed** and **7 strict process-death cases passed**. + Logs: `/tmp/command-astra-1002/voice-disk-{green,process}.log`. +- OBSERVED step-3 integrated iOS build succeeded (`voice-key-ios-build.log`). Latest hardening is + native-verified; subsequent app build remains to do. +- Remaining review finding: one corrupt manifest currently blocks discovery of intact siblings. + Fix discovery to report unreadable records separately before wiring recovery UI. Capture owner + fencing, original-request/later-edit reconciliation and durable assistant transfer remain too. From a05c73c373592cc485a6b160cd1683d947b8df6b Mon Sep 17 00:00:00 2001 From: legitimate-apps <309192374+legitimate-apps@users.noreply.github.com> Date: Fri, 2 Oct 2026 13:08:46 -0400 Subject: [PATCH 18/27] Recover intact voice recordings alongside damaged manifests --- .../VoiceRecordingRecoveryStore.swift | 23 ++++++++----- .../VoiceRecordingRecoveryStoreTests.swift | 33 ++++++++++++------- ios/recovery-repro/VoiceRecoveryProbe.swift | 2 +- state/ASTRA-1002.md | 10 ++++++ 4 files changed, 48 insertions(+), 20 deletions(-) diff --git a/ios/Command/Transcription/VoiceRecordingRecoveryStore.swift b/ios/Command/Transcription/VoiceRecordingRecoveryStore.swift index 10807a3..9062cd6 100644 --- a/ios/Command/Transcription/VoiceRecordingRecoveryStore.swift +++ b/ios/Command/Transcription/VoiceRecordingRecoveryStore.swift @@ -75,18 +75,25 @@ final class VoiceRecordingRecoveryStore { try files.setAttributes([.posixPermissions: 0o600], ofItemAtPath: manifest.path) } - func recordings() throws -> [Recording] { - guard files.fileExists(atPath: directory.path) else { return [] } - return try files.contentsOfDirectory(at: directory, includingPropertiesForKeys: nil) + /// A damaged manifest must not hide intact siblings. Keep every unreadable file and make + /// the warning explicit so recovery UI can report incomplete discovery. + func load() throws -> (recordings: [Recording], unreadable: Bool) { + guard files.fileExists(atPath: directory.path) else { return ([], false) } + let folders = try files.contentsOfDirectory(at: directory, includingPropertiesForKeys: nil) .sorted(by: { $0.lastPathComponent < $1.lastPathComponent }) - .compactMap { folder in - let manifest = folder.appendingPathComponent("manifest.json") - guard files.fileExists(atPath: manifest.path) else { return nil } + var recordings: [Recording] = [] + var unreadable = false + for folder in folders { + let manifest = folder.appendingPathComponent("manifest.json") + guard files.fileExists(atPath: manifest.path) else { continue } + do { let record = try JSONDecoder().decode(Recording.self, from: Data(contentsOf: manifest)) guard record.id.uuidString == folder.lastPathComponent else { throw RecoveryError.invalidRecord } _ = try audioURL(for: record) - return record - } + recordings.append(record) + } catch { unreadable = true } + } + return (recordings, unreadable) } func audioURL(for record: Recording) throws -> URL { diff --git a/ios/CommandTests/VoiceRecordingRecoveryStoreTests.swift b/ios/CommandTests/VoiceRecordingRecoveryStoreTests.swift index d7b662b..ea07b82 100644 --- a/ios/CommandTests/VoiceRecordingRecoveryStoreTests.swift +++ b/ios/CommandTests/VoiceRecordingRecoveryStoreTests.swift @@ -20,30 +20,30 @@ final class VoiceRecordingRecoveryStoreTests: XCTestCase { let original = try source(), owner = store() let record = try owner.keep(original, id: UUID()) try FileManager.default.removeItem(at: original) - let restarted = store(), recovered = try XCTUnwrap(restarted.recordings().first) + let restarted = store(), recovered = try XCTUnwrap(restarted.load().recordings.first) XCTAssertEqual(record.id, recovered.id) XCTAssertEqual(try Data(contentsOf: restarted.audioURL(for: recovered)), Data("opaque audio fixture".utf8)) } func testAccountServerAndRecreatedAccountCannotDiscoverAudio() throws { _ = try store().keep(source(), id: UUID()) - XCTAssertTrue(try store(id: 2).recordings().isEmpty) - XCTAssertTrue(try store(server: "https://other.example.com").recordings().isEmpty) - XCTAssertTrue(try store(created: "recreated").recordings().isEmpty) - XCTAssertEqual(try store().recordings().count, 1) + XCTAssertTrue(try store(id: 2).load().recordings.isEmpty) + XCTAssertTrue(try store(server: "https://other.example.com").load().recordings.isEmpty) + XCTAssertTrue(try store(created: "recreated").load().recordings.isEmpty) + XCTAssertEqual(try store().load().recordings.count, 1) } func testDiscardDoesNotResurrectAndRemovesOwnedAudio() throws { let owner = store(), record = try owner.keep(source(), id: UUID()) let audio = try owner.audioURL(for: record) try owner.discard(record.id) XCTAssertFalse(FileManager.default.fileExists(atPath: audio.path)) - XCTAssertTrue(try store().recordings().isEmpty) + XCTAssertTrue(try store().load().recordings.isEmpty) try owner.discard(record.id) } func testCorruptManifestIsReportedAndKept() throws { let owner = store(), record = try owner.keep(source(), id: UUID()) let manifest = owner.directory.appendingPathComponent(record.id.uuidString).appendingPathComponent("manifest.json") try Data("broken".utf8).write(to: manifest) - XCTAssertThrowsError(try owner.recordings()) + XCTAssertTrue(try owner.load().unreadable) XCTAssertTrue(FileManager.default.fileExists(atPath: manifest.path)) XCTAssertNoThrow(try owner.audioURL(for: record)) } @@ -52,14 +52,14 @@ final class VoiceRecordingRecoveryStoreTests: XCTestCase { _ = try owner.keep(original, id: id) XCTAssertThrowsError(try owner.keep(original, id: id)) XCTAssertTrue(FileManager.default.fileExists(atPath: original.path)) - XCTAssertEqual(try owner.recordings().count, 1) + XCTAssertEqual(try owner.load().recordings.count, 1) } func testReviewRestoresLatestEditsAndEngineWithAudio() async throws { let owner = store(), flow = VoiceCaptureFlow(recovery: owner) flow.adopt(try source()) _ = await flow.transcribe(immediateUse: false) { _ in ("spoken", "parakeet-v3") } flow.transcript = "edited after transcription" - let record = try XCTUnwrap(store().recordings().first) + let record = try XCTUnwrap(store().load().recordings.first) let restored = VoiceCaptureFlow(recovery: store(), restoring: record) XCTAssertEqual(restored.transcript, "edited after transcription") XCTAssertEqual(restored.engineUsed, "parakeet-v3") @@ -81,7 +81,7 @@ final class VoiceRecordingRecoveryStoreTests: XCTestCase { flow.adopt(try source()); flow.transcript = "same payload" var originalKey = "" _ = await flow.saveNote { _, _, key in originalKey = key; return "response lost" } - let restored = VoiceCaptureFlow(recovery: store(), restoring: try XCTUnwrap(store().recordings().first)) + let restored = VoiceCaptureFlow(recovery: store(), restoring: try XCTUnwrap(store().load().recordings.first)) var replayKey = "" _ = await restored.saveNote { text, _, key in XCTAssertEqual(text, "same payload"); replayKey = key; return "still unavailable" @@ -111,7 +111,7 @@ final class VoiceRecordingRecoveryStoreTests: XCTestCase { try old.write(to: manifest) var submittedKey = "" _ = await flow.saveNote { _, _, key in submittedKey = key; return "response lost" } - let restored = VoiceCaptureFlow(recovery: store(), restoring: try XCTUnwrap(store().recordings().first)) + let restored = VoiceCaptureFlow(recovery: store(), restoring: try XCTUnwrap(store().load().recordings.first)) XCTAssertEqual(restored.transcript, "submitted review") _ = await restored.saveNote { text, _, key in XCTAssertEqual(text, "submitted review"); XCTAssertEqual(key, submittedKey); return "response lost" @@ -130,6 +130,17 @@ final class VoiceRecordingRecoveryStoreTests: XCTestCase { XCTAssertFalse(sent); XCTAssertFalse(saved) XCTAssertTrue(FileManager.default.fileExists(atPath: original.path)) } + func testDamagedRecordingDoesNotHideIntactSibling() throws { + let owner = store() + let damaged = try owner.keep(source(), id: UUID()) + let intact = try owner.keep(source(), id: UUID()) + let manifest = owner.directory.appendingPathComponent(damaged.id.uuidString).appendingPathComponent("manifest.json") + try Data("damaged".utf8).write(to: manifest) + let recovered = try owner.load() + XCTAssertEqual(recovered.recordings.map(\.id), [intact.id]) + XCTAssertTrue(recovered.unreadable) + XCTAssertTrue(FileManager.default.fileExists(atPath: manifest.path)) + } func testManifestCannotReferenceAnOutsideFile() throws { let owner = store() XCTAssertThrowsError(try owner.audioURL(for: .init(version: 1, id: UUID(), filename: "../../outside.m4a"))) diff --git a/ios/recovery-repro/VoiceRecoveryProbe.swift b/ios/recovery-repro/VoiceRecoveryProbe.swift index a9ddca5..73b7aa1 100644 --- a/ios/recovery-repro/VoiceRecoveryProbe.swift +++ b/ios/recovery-repro/VoiceRecoveryProbe.swift @@ -11,7 +11,7 @@ struct VoiceRecoveryProbe { let recovery = VoiceRecordingRecoveryStore(root: directory.appendingPathComponent("recovery"), server: URL(string: "https://example.invalid")!, accountID: 1, username: "recovery-test", accountCreatedAt: "2026-10-02") - let restored = (mode == "relaunch" || mode == "retry") ? try recovery.recordings().first : nil + let restored = (mode == "relaunch" || mode == "retry") ? try recovery.load().recordings.first : nil let flow = VoiceCaptureFlow(recovery: recovery, restoring: restored) func snapshot(_ extra: [String: String] = [:]) throws { var value = extra diff --git a/state/ASTRA-1002.md b/state/ASTRA-1002.md index 9b6e147..710b2de 100644 --- a/state/ASTRA-1002.md +++ b/state/ASTRA-1002.md @@ -290,3 +290,13 @@ process remains. Changes are on the same review branch/PR; no merge or deploymen - Remaining review finding: one corrupt manifest currently blocks discovery of intact siblings. Fix discovery to report unreadable records separately before wiring recovery UI. Capture owner fencing, original-request/later-edit reconciliation and durable assistant transfer remain too. + +## Reset-window discovery hardening — 13:09 EDT +- Added a failing sibling-recovery regression, then changed discovery to return intact recordings + plus an explicit unreadable flag. Damaged metadata/audio no longer hides other pending captures; + unreadable files are preserved. The process probe uses this production discovery API. +- OBSERVED baseline control failed; fixed **33 native tests passed** and **7 strict process-death + cases passed**. Logs: `voice-discovery-{red,green,process}.log` under the run scratch directory. +- Remaining next guarantee: capture owner fencing so a superseded flow cannot overwrite or delete + files restored by another flow/window. App/UI wiring and full reconciliation remain deferred + until these ownership and submission boundaries are complete. From e79fe90c40b130eab347564cb0ed2c67edeb4fab Mon Sep 17 00:00:00 2001 From: legitimate-apps <309192374+legitimate-apps@users.noreply.github.com> Date: Fri, 2 Oct 2026 13:10:59 -0400 Subject: [PATCH 19/27] Fence restored voice captures against superseded flow writes --- .../Transcription/VoiceCaptureFlow.swift | 24 +++++++++++++----- .../VoiceRecordingRecoveryStore.swift | 12 +++++++++ .../VoiceRecordingRecoveryStoreTests.swift | 25 +++++++++++++++++++ state/ASTRA-1002.md | 11 ++++++++ 4 files changed, 66 insertions(+), 6 deletions(-) diff --git a/ios/Command/Transcription/VoiceCaptureFlow.swift b/ios/Command/Transcription/VoiceCaptureFlow.swift index 988699e..837d398 100644 --- a/ios/Command/Transcription/VoiceCaptureFlow.swift +++ b/ios/Command/Transcription/VoiceCaptureFlow.swift @@ -45,6 +45,11 @@ final class VoiceCaptureFlow { private let removeFile: (URL) -> Void private let recovery: VoiceRecordingRecoveryStore? private var recoveredRecordingID: UUID? + private let recordingOwner = UUID() + private var ownsRecording: Bool { + guard let recovery, let recoveredRecordingID else { return true } + return recovery.isOwner(recoveredRecordingID, owner: recordingOwner) + } init(recovery: VoiceRecordingRecoveryStore? = nil, restoring recording: VoiceRecordingRecoveryStore.Recording? = nil, @@ -56,6 +61,7 @@ final class VoiceCaptureFlow { audioURL = try recovery.audioURL(for: recording) captureID = recording.id recoveredRecordingID = recording.id + recovery.claim(recording.id, owner: recordingOwner) transcript = recording.transcript ?? "" engineUsed = recording.engine ?? "" noteCreate = recording.createAttempt ?? CreateAttempt() @@ -97,6 +103,7 @@ final class VoiceCaptureFlow { let record = try recovery.keep(url, id: captureID) audioURL = try recovery.audioURL(for: record) recoveredRecordingID = record.id + recovery.claim(record.id, owner: recordingOwner) removeFile(url) // ownership transferred only after durable metadata publication } catch { errorMessage = "Couldn't keep a recovery copy of this recording. Keep Command open." @@ -110,13 +117,13 @@ final class VoiceCaptureFlow { /// while transcribing (the result is dropped; nothing is handed on). func transcribe(immediateUse: Bool, using transcribe: (URL) async throws -> (text: String, engine: String)) async -> String? { - guard let url = audioURL, !isCancelled, !Task.isCancelled else { return nil } + guard let url = audioURL, !isCancelled, !Task.isCancelled, ownsRecording else { return nil } let capture = captureID, revision = reviewRevision let attempt = UUID() transcriptionAttempt = attempt do { let result = try await transcribe(url) - guard !isCancelled, !Task.isCancelled, captureID == capture, + guard !isCancelled, !Task.isCancelled, ownsRecording, captureID == capture, reviewRevision == revision, transcriptionAttempt == attempt else { return nil } applyingTranscription = true transcript = result.text @@ -130,7 +137,7 @@ final class VoiceCaptureFlow { return cleaned } } catch { - guard !isCancelled, !Task.isCancelled, captureID == capture, + guard !isCancelled, !Task.isCancelled, ownsRecording, captureID == capture, reviewRevision == revision, transcriptionAttempt == attempt else { return nil } errorMessage = (error as? LocalizedError)?.errorDescription ?? error.localizedDescription transcriptionFailed = true @@ -142,7 +149,7 @@ final class VoiceCaptureFlow { /// may close. Completion of an older save must not discard newer edits or another recording. /// A failed current save keeps the recording and shows the error for retry. func saveNote(using save: (_ text: String, _ engine: String, _ key: String) async -> String?) async -> Bool { - guard !saving, !isCancelled, !Task.isCancelled else { return false } + guard !saving, !isCancelled, !Task.isCancelled, ownsRecording else { return false } if recovery != nil && recoveredRecordingID == nil { errorMessage = "This recording has no recovery copy yet. Keep Command open; it has not been sent." return false @@ -158,7 +165,7 @@ final class VoiceCaptureFlow { try recovery.saveCreateAttempt(id: recoveredRecordingID, attempt: noteCreate, transcript: text, engine: engine) } let failure = await save(text, engine, key) - guard !isCancelled, !Task.isCancelled, captureID == capture, + guard !isCancelled, !Task.isCancelled, ownsRecording, captureID == capture, reviewRevision == revision else { return false } if let failure { errorMessage = failure @@ -186,6 +193,7 @@ final class VoiceCaptureFlow { } private func persistReview() { + guard ownsRecording else { return } guard let recovery else { return } guard let recoveredRecordingID else { if audioURL != nil { errorMessage = "Couldn't keep a recovery copy of this recording. Keep Command open." } @@ -197,8 +205,12 @@ final class VoiceCaptureFlow { @discardableResult private func discardAudio() -> Bool { + guard ownsRecording else { return false } if let recoveredRecordingID, let recovery { - do { try recovery.discard(recoveredRecordingID) } + do { + try recovery.discard(recoveredRecordingID) + recovery.release(recoveredRecordingID, owner: recordingOwner) + } catch { errorMessage = "Couldn't remove the saved recording. Its cleanup can be retried." return false diff --git a/ios/Command/Transcription/VoiceRecordingRecoveryStore.swift b/ios/Command/Transcription/VoiceRecordingRecoveryStore.swift index 9062cd6..fd7d5b6 100644 --- a/ios/Command/Transcription/VoiceRecordingRecoveryStore.swift +++ b/ios/Command/Transcription/VoiceRecordingRecoveryStore.swift @@ -16,6 +16,18 @@ final class VoiceRecordingRecoveryStore { enum RecoveryError: Error { case invalidRecord } let directory: URL private let files = FileManager.default + private static var owners: [URL: UUID] = [:] + + func claim(_ id: UUID, owner: UUID) { + Self.owners[directory.appendingPathComponent(id.uuidString)] = owner + } + func isOwner(_ id: UUID, owner: UUID) -> Bool { + Self.owners[directory.appendingPathComponent(id.uuidString)] == owner + } + func release(_ id: UUID, owner: UUID) { + let key = directory.appendingPathComponent(id.uuidString) + if Self.owners[key] == owner { Self.owners.removeValue(forKey: key) } + } init(root: URL, server: URL, accountID: Int, username: String, accountCreatedAt: String) { let identity = [server.absoluteString.trimmingCharacters(in: CharacterSet(charactersIn: "/")), diff --git a/ios/CommandTests/VoiceRecordingRecoveryStoreTests.swift b/ios/CommandTests/VoiceRecordingRecoveryStoreTests.swift index ea07b82..2a8af4f 100644 --- a/ios/CommandTests/VoiceRecordingRecoveryStoreTests.swift +++ b/ios/CommandTests/VoiceRecordingRecoveryStoreTests.swift @@ -141,6 +141,31 @@ final class VoiceRecordingRecoveryStoreTests: XCTestCase { XCTAssertTrue(recovered.unreadable) XCTAssertTrue(FileManager.default.fileExists(atPath: manifest.path)) } + func testSupersededFlowCannotDiscardRestoredRecording() throws { + let owner = store(), original = VoiceCaptureFlow(recovery: owner) + original.adopt(try source()); original.transcript = "original" + let restored = VoiceCaptureFlow(recovery: owner, restoring: try XCTUnwrap(owner.load().recordings.first)) + original.cancel() + XCTAssertTrue(FileManager.default.fileExists(atPath: try XCTUnwrap(restored.audioURL).path)) + XCTAssertEqual(try owner.load().recordings.count, 1) + } + func testSupersededFlowCannotOverwriteNewerReview() throws { + let owner = store(), original = VoiceCaptureFlow(recovery: owner) + original.adopt(try source()); original.transcript = "original" + let restored = VoiceCaptureFlow(recovery: owner, restoring: try XCTUnwrap(owner.load().recordings.first)) + restored.transcript = "current owner" + original.transcript = "late stale edit" + XCTAssertEqual(try owner.load().recordings.first?.transcript, "current owner") + } + func testSupersededFlowCannotStartRequest() async throws { + let owner = store(), original = VoiceCaptureFlow(recovery: owner) + original.adopt(try source()); original.transcript = "original" + let restored = VoiceCaptureFlow(recovery: owner, restoring: try XCTUnwrap(owner.load().recordings.first)) + var sent = false + let saved = await original.saveNote { _, _, _ in sent = true; return nil } + XCTAssertFalse(saved); XCTAssertFalse(sent) + XCTAssertNotNil(restored.audioURL) + } func testManifestCannotReferenceAnOutsideFile() throws { let owner = store() XCTAssertThrowsError(try owner.audioURL(for: .init(version: 1, id: UUID(), filename: "../../outside.m4a"))) diff --git a/state/ASTRA-1002.md b/state/ASTRA-1002.md index 710b2de..3c99dfd 100644 --- a/state/ASTRA-1002.md +++ b/state/ASTRA-1002.md @@ -300,3 +300,14 @@ process remains. Changes are on the same review branch/PR; no merge or deploymen - Remaining next guarantee: capture owner fencing so a superseded flow cannot overwrite or delete files restored by another flow/window. App/UI wiring and full reconciliation remain deferred until these ownership and submission boundaries are complete. + +## Reset-window ownership fencing — 13:11 EDT +- Added three failing regressions first: superseded flow deletion, review overwrite and network + submission (**3 tests, 5 failed assertions** on prior code; `voice-owner-red.log`). +- Explicit restore claims a per-capture owner token. Superseded flows cannot persist reviews, + start note requests/transcription, accept stale async results, or delete the current audio. + Tokens are scoped by the account recovery directory and capture ID, and released on cleanup. +- OBSERVED fixed source: **36 native XCTest cases passed**, **7 strict process-death cases passed**. + Logs: `/tmp/command-astra-1002/voice-owner-{green,process}.log`. +- Scope is file/flow ownership, not the future app-wide microphone coordinator. Sheet/account + integration, complete pending-create reconciliation and acknowledged assistant handoff remain. From 8ac488edf069698e8ea43194c723e6a0f0574185 Mon Sep 17 00:00:00 2001 From: legitimate-apps <309192374+legitimate-apps@users.noreply.github.com> Date: Fri, 2 Oct 2026 13:17:15 -0400 Subject: [PATCH 20/27] Reconcile recovered voice edits through the original note identity --- .../Transcription/VoiceCaptureFlow.swift | 66 +++++++++++++++++++ .../VoiceRecordingRecoveryStore.swift | 25 +++++++ .../VoiceRecordingRecoveryStoreTests.swift | 50 ++++++++++++++ state/ASTRA-1002.md | 13 ++++ 4 files changed, 154 insertions(+) diff --git a/ios/Command/Transcription/VoiceCaptureFlow.swift b/ios/Command/Transcription/VoiceCaptureFlow.swift index 837d398..8299f87 100644 --- a/ios/Command/Transcription/VoiceCaptureFlow.swift +++ b/ios/Command/Transcription/VoiceCaptureFlow.swift @@ -46,6 +46,9 @@ final class VoiceCaptureFlow { private let recovery: VoiceRecordingRecoveryStore? private var recoveredRecordingID: UUID? private let recordingOwner = UUID() + private var noteSubmission: VoiceRecordingRecoveryStore.NoteSubmission? + private var savedNoteID: Int? + private var savedText: String? private var ownsRecording: Bool { guard let recovery, let recoveredRecordingID else { return true } return recovery.isOwner(recoveredRecordingID, owner: recordingOwner) @@ -65,6 +68,9 @@ final class VoiceCaptureFlow { transcript = recording.transcript ?? "" engineUsed = recording.engine ?? "" noteCreate = recording.createAttempt ?? CreateAttempt() + noteSubmission = recording.noteSubmission + savedNoteID = recording.savedNoteID + savedText = recording.savedText } catch { errorMessage = "Couldn't reopen the saved recording. Its files have been kept." } } } @@ -74,6 +80,7 @@ final class VoiceCaptureFlow { guard discardAudio() else { return } captureID = UUID() noteCreate.reset() + noteSubmission = nil; savedNoteID = nil; savedText = nil transcript = "" engineUsed = "" errorMessage = nil @@ -97,6 +104,7 @@ final class VoiceCaptureFlow { guard discardAudio() else { return } captureID = UUID() noteCreate.reset() + noteSubmission = nil; savedNoteID = nil; savedText = nil audioURL = url if let recovery { do { @@ -181,6 +189,64 @@ final class VoiceCaptureFlow { } } + struct NoteOperations { + var create: (VoiceRecordingRecoveryStore.NoteSubmission) async throws -> Int + var update: (Int, String) async throws -> Void + } + + /// Durable note path: replay the original create, checkpoint its identity, then PATCH later + /// edits to that same note. A lost PATCH response is safe to repeat. The caller's operations + /// must use the capture's account/session and the exact request fields supplied here. + func saveRecoveredNote(locale: String?, using operations: NoteOperations) async -> Bool { + guard !saving, !isCancelled, !Task.isCancelled, ownsRecording, + recovery != nil, recoveredRecordingID != nil else { return false } + let capture = captureID + saving = true + defer { saving = false } + do { + if noteSubmission == nil { + let engine = engineUsed.isEmpty ? "sfspeech" : engineUsed + let key = try noteCreate.key(for: NotePayload(text: transcript, engine: engine)) + noteSubmission = .init(body: transcript, engine: engine, locale: locale, key: key) + } + // Always write before transport, including retry after a previous checkpoint failed. + try checkpointSubmission() + guard let submission = noteSubmission else { return false } + if savedNoteID == nil { + let id = try await operations.create(submission) + guard !isCancelled, !Task.isCancelled, ownsRecording, captureID == capture else { return false } + savedNoteID = id + savedText = submission.body + try checkpointSubmission() + } + guard let id = savedNoteID else { return false } + let sent = transcript + if savedText != sent { + try await operations.update(id, sent) + guard !isCancelled, !Task.isCancelled, ownsRecording, captureID == capture else { return false } + savedText = sent + try checkpointSubmission() + } + // New edits during PATCH remain recoverable and keep the review open for another pass. + guard transcript == savedText else { return false } + errorMessage = nil + return discardAudio() + } catch { + guard !isCancelled, ownsRecording, captureID == capture else { return false } + errorMessage = error.localizedDescription + return false + } + } + + private func checkpointSubmission() throws { + guard ownsRecording, let recovery, let recoveredRecordingID, let noteSubmission else { + throw VoiceRecordingRecoveryStore.RecoveryError.invalidRecord + } + try recovery.saveSubmission(id: recoveredRecordingID, submission: noteSubmission, + noteID: savedNoteID, savedText: savedText, + review: transcript, engine: engineUsed) + } + /// The transcript was handed to the caller from review: the words are committed. func committedToCaller() { discardAudio() } diff --git a/ios/Command/Transcription/VoiceRecordingRecoveryStore.swift b/ios/Command/Transcription/VoiceRecordingRecoveryStore.swift index fd7d5b6..d32dd11 100644 --- a/ios/Command/Transcription/VoiceRecordingRecoveryStore.swift +++ b/ios/Command/Transcription/VoiceRecordingRecoveryStore.swift @@ -5,6 +5,12 @@ import Foundation /// account lifecycle wiring are separate: callers must explicitly opt into this durable owner. @MainActor final class VoiceRecordingRecoveryStore { + struct NoteSubmission: Codable { + let body: String + let engine: String + let locale: String? + let key: String + } struct Recording: Codable { let version: Int let id: UUID @@ -12,6 +18,9 @@ final class VoiceRecordingRecoveryStore { var transcript: String? = nil var engine: String? = nil var createAttempt: CreateAttempt? = nil + var noteSubmission: NoteSubmission? = nil + var savedNoteID: Int? = nil + var savedText: String? = nil } enum RecoveryError: Error { case invalidRecord } let directory: URL @@ -87,6 +96,22 @@ final class VoiceRecordingRecoveryStore { try files.setAttributes([.posixPermissions: 0o600], ofItemAtPath: manifest.path) } + func saveSubmission(id: UUID, submission: NoteSubmission, noteID: Int?, savedText: String?, + review: String, engine: String) throws { + let manifest = directory.appendingPathComponent(id.uuidString).appendingPathComponent("manifest.json") + var record = try JSONDecoder().decode(Recording.self, from: Data(contentsOf: manifest)) + guard record.id == id else { throw RecoveryError.invalidRecord } + _ = try audioURL(for: record) + record.noteSubmission = submission + record.savedNoteID = noteID + record.savedText = savedText + record.transcript = review + record.engine = engine + try JSONEncoder().encode(record).write(to: manifest, + options: [.atomic, .completeFileProtectionUntilFirstUserAuthentication]) + try files.setAttributes([.posixPermissions: 0o600], ofItemAtPath: manifest.path) + } + /// A damaged manifest must not hide intact siblings. Keep every unreadable file and make /// the warning explicit so recovery UI can report incomplete discovery. func load() throws -> (recordings: [Recording], unreadable: Bool) { diff --git a/ios/CommandTests/VoiceRecordingRecoveryStoreTests.swift b/ios/CommandTests/VoiceRecordingRecoveryStoreTests.swift index 2a8af4f..07c13eb 100644 --- a/ios/CommandTests/VoiceRecordingRecoveryStoreTests.swift +++ b/ios/CommandTests/VoiceRecordingRecoveryStoreTests.swift @@ -166,6 +166,56 @@ final class VoiceRecordingRecoveryStoreTests: XCTestCase { XCTAssertFalse(saved); XCTAssertFalse(sent) XCTAssertNotNil(restored.audioURL) } + func testLaterEditsAfterUncertainCreateMustNotCreateAnotherNote() async throws { + let owner = store(), original = VoiceCaptureFlow(recovery: owner) + original.adopt(try source()); original.transcript = "first submitted text" + var notes: [Int: String] = [:], keys: [String: Int] = [:] + var loseResponse = true + let operations = VoiceCaptureFlow.NoteOperations(create: { request in + XCTAssertEqual(request.body, "first submitted text") + XCTAssertEqual(request.locale, "en-US") + let id = keys[request.key] ?? keys.count + 1 + keys[request.key] = id; notes[id] = notes[id] ?? request.body + if loseResponse { throw URLError(.networkConnectionLost) } + return id + }, update: { id, body in notes[id] = body }) + _ = await original.saveRecoveredNote(locale: "en-US", using: operations) + original.transcript = "later edited text" + let restored = VoiceCaptureFlow(recovery: owner, restoring: try XCTUnwrap(owner.load().recordings.first)) + loseResponse = false + let saved = await restored.saveRecoveredNote(locale: "fr-FR", using: operations) + XCTAssertTrue(saved) + XCTAssertEqual(notes.count, 1) + XCTAssertEqual(notes[1], "later edited text") + XCTAssertTrue(try owner.load().recordings.isEmpty) + } + func testAcknowledgedCreateThenFailedPatchResumesWithoutAnotherCreate() async throws { + let owner = store(), original = VoiceCaptureFlow(recovery: owner) + original.adopt(try source()); original.transcript = "original request" + var creates = 0 + let first = VoiceCaptureFlow.NoteOperations(create: { _ in + creates += 1; original.transcript = "edited during create"; return 42 + }, update: { _, _ in throw URLError(.notConnectedToInternet) }) + let initial = await original.saveRecoveredNote(locale: nil, using: first) + XCTAssertFalse(initial) + let restored = VoiceCaptureFlow(recovery: owner, restoring: try XCTUnwrap(owner.load().recordings.first)) + let second = VoiceCaptureFlow.NoteOperations(create: { _ in creates += 1; return 99 }, update: { id, text in + XCTAssertEqual(id, 42); XCTAssertEqual(text, "edited during create") + }) + let saved = await restored.saveRecoveredNote(locale: nil, using: second) + XCTAssertTrue(saved); XCTAssertEqual(creates, 1) + } + func testEditsDuringPatchStayPendingAgainstSameNoteID() async throws { + let owner = store(), flow = VoiceCaptureFlow(recovery: owner) + flow.adopt(try source()); flow.transcript = "first" + let first = VoiceCaptureFlow.NoteOperations(create: { _ in flow.transcript = "second"; return 7 }, + update: { _, _ in flow.transcript = "third" }) + let saved = await flow.saveRecoveredNote(locale: nil, using: first) + XCTAssertFalse(saved) + let record = try XCTUnwrap(owner.load().recordings.first) + XCTAssertEqual(record.savedNoteID, 7); XCTAssertEqual(record.savedText, "second") + XCTAssertEqual(record.transcript, "third") + } func testManifestCannotReferenceAnOutsideFile() throws { let owner = store() XCTAssertThrowsError(try owner.audioURL(for: .init(version: 1, id: UUID(), filename: "../../outside.m4a"))) diff --git a/state/ASTRA-1002.md b/state/ASTRA-1002.md index 3c99dfd..d1fd2b7 100644 --- a/state/ASTRA-1002.md +++ b/state/ASTRA-1002.md @@ -311,3 +311,16 @@ process remains. Changes are on the same review branch/PR; no merge or deploymen Logs: `/tmp/command-astra-1002/voice-owner-{green,process}.log`. - Scope is file/flow ownership, not the future app-wide microphone coordinator. Sheet/account integration, complete pending-create reconciliation and acknowledged assistant handoff remain. + +## Reset-window note reconciliation primitive — 13:17 EDT +- Added a failing later-edit regression first: uncertain create followed by changed review created + two notes on the legacy path (1 test, 2 failures; `voice-reconcile-red.log`). +- Added saveRecoveredNote operations with a durable original body/engine/locale/key, acknowledged + note ID and saved text. It replays the original create, checkpoints the returned ID before PATCH, + and applies later review edits to that same note. Edits during PATCH remain pending against its ID. +- OBSERVED **39 native XCTest cases passed**, including lost-create response + later edits, + create acknowledgment + failed PATCH + restart (no second create), and edits arriving during + PATCH. Existing **7 strict process-death cases still pass**. Logs: `voice-reconcile-{green,process}.log`. +- This NEW durable save entry point is not yet called by RecordingSheet. Legacy saveNote retains + its old changed-payload semantics; wire the durable entry point when enabling account recovery. + Need an extended hard-kill test for later-edit reconciliation, then app integration/verification. From 2b859077cdea930ddc51ca8c1b51509f814bbf79 Mon Sep 17 00:00:00 2001 From: legitimate-apps <309192374+legitimate-apps@users.noreply.github.com> Date: Fri, 2 Oct 2026 13:20:35 -0400 Subject: [PATCH 21/27] Verify voice reconciliation across process death and prevent bypass --- .../Transcription/VoiceCaptureFlow.swift | 4 +++ .../VoiceRecordingRecoveryStoreTests.swift | 12 +++++++ ios/recovery-repro/VoiceRecoveryProbe.swift | 34 ++++++++++++------- .../test_voice_process_recovery.py | 19 ++++++++--- state/ASTRA-1002.md | 11 ++++++ 5 files changed, 64 insertions(+), 16 deletions(-) diff --git a/ios/Command/Transcription/VoiceCaptureFlow.swift b/ios/Command/Transcription/VoiceCaptureFlow.swift index 8299f87..17447b1 100644 --- a/ios/Command/Transcription/VoiceCaptureFlow.swift +++ b/ios/Command/Transcription/VoiceCaptureFlow.swift @@ -158,6 +158,10 @@ final class VoiceCaptureFlow { /// A failed current save keeps the recording and shows the error for retry. func saveNote(using save: (_ text: String, _ engine: String, _ key: String) async -> String?) async -> Bool { guard !saving, !isCancelled, !Task.isCancelled, ownsRecording else { return false } + if noteSubmission != nil { + errorMessage = "Finish this recording's pending save before starting another submission." + return false + } if recovery != nil && recoveredRecordingID == nil { errorMessage = "This recording has no recovery copy yet. Keep Command open; it has not been sent." return false diff --git a/ios/CommandTests/VoiceRecordingRecoveryStoreTests.swift b/ios/CommandTests/VoiceRecordingRecoveryStoreTests.swift index 07c13eb..e3b9754 100644 --- a/ios/CommandTests/VoiceRecordingRecoveryStoreTests.swift +++ b/ios/CommandTests/VoiceRecordingRecoveryStoreTests.swift @@ -216,6 +216,18 @@ final class VoiceRecordingRecoveryStoreTests: XCTestCase { XCTAssertEqual(record.savedNoteID, 7); XCTAssertEqual(record.savedText, "second") XCTAssertEqual(record.transcript, "third") } + func testLegacySaveCannotBypassPendingReconciliation() async throws { + let owner = store(), original = VoiceCaptureFlow(recovery: owner) + original.adopt(try source()); original.transcript = "pending create" + _ = await original.saveRecoveredNote(locale: nil, using: .init(create: { _ in + throw URLError(.networkConnectionLost) + }, update: { _, _ in })) + let restored = VoiceCaptureFlow(recovery: owner, restoring: try XCTUnwrap(owner.load().recordings.first)) + var sent = false + let saved = await restored.saveNote { _, _, _ in sent = true; return nil } + XCTAssertFalse(sent); XCTAssertFalse(saved) + XCTAssertEqual(try owner.load().recordings.count, 1) + } func testManifestCannotReferenceAnOutsideFile() throws { let owner = store() XCTAssertThrowsError(try owner.audioURL(for: .init(version: 1, id: UUID(), filename: "../../outside.m4a"))) diff --git a/ios/recovery-repro/VoiceRecoveryProbe.swift b/ios/recovery-repro/VoiceRecoveryProbe.swift index 73b7aa1..502d856 100644 --- a/ios/recovery-repro/VoiceRecoveryProbe.swift +++ b/ios/recovery-repro/VoiceRecoveryProbe.swift @@ -11,7 +11,7 @@ struct VoiceRecoveryProbe { let recovery = VoiceRecordingRecoveryStore(root: directory.appendingPathComponent("recovery"), server: URL(string: "https://example.invalid")!, accountID: 1, username: "recovery-test", accountCreatedAt: "2026-10-02") - let restored = (mode == "relaunch" || mode == "retry") ? try recovery.load().recordings.first : nil + let restored = ["relaunch", "retry", "reconcile"].contains(mode) ? try recovery.load().recordings.first : nil let flow = VoiceCaptureFlow(recovery: recovery, restoring: restored) func snapshot(_ extra: [String: String] = [:]) throws { var value = extra @@ -30,12 +30,21 @@ struct VoiceRecoveryProbe { return } if mode == "retry" { - // Re-enter the SAME payload to isolate the loss of retry identity from transcript loss. - flow.transcript = "Reviewed capture" - _ = await flow.saveNote { _, _, key in - try! snapshot(["key": key]) - return "Response lost" - } + _ = await flow.saveRecoveredNote(locale: "fr-FR", using: .init(create: { request in + try snapshot(["key": request.key]) + throw URLError(.networkConnectionLost) + }, update: { _, _ in })) + return + } + if mode == "reconcile" { + var key = "", body = "", locale = "", patchedBody = "", patchedID = "" + let saved = await flow.saveRecoveredNote(locale: "fr-FR", using: .init(create: { request in + key = request.key; body = request.body; locale = request.locale ?? "" + return 7 + }, update: { id, text in patchedID = String(id); patchedBody = text })) + try snapshot(["key": key, "createBody": body, "createLocale": locale, + "patchedID": patchedID, "patchedBody": patchedBody, + "saved": String(saved), "remaining": String(try recovery.load().recordings.count)]) return } flow.adopt(audio) @@ -52,13 +61,14 @@ struct VoiceRecoveryProbe { _ = await flow.transcribe(immediateUse: false) { _ in ("Spoken capture", "sfspeech") } flow.transcript = "Latest edited review" try snapshot(); await hold() - case "uncertain": + case "uncertain", "uncertain-edited": flow.transcript = "Reviewed capture" - _ = await flow.saveNote { _, _, key in - try! snapshot(["key": key, "checkpoint": "request-awaiting-response"]) + _ = await flow.saveRecoveredNote(locale: "en-US", using: .init(create: { request in + if mode == "uncertain-edited" { flow.transcript = "Later review edits" } + try snapshot(["key": request.key, "checkpoint": "request-awaiting-response"]) await hold() - return "Response lost" - } + throw URLError(.networkConnectionLost) + }, update: { _, _ in })) case "cancel": flow.cancel(); try snapshot() case "success": diff --git a/ios/recovery-repro/test_voice_process_recovery.py b/ios/recovery-repro/test_voice_process_recovery.py index bbbfee2..0d3f95c 100644 --- a/ios/recovery-repro/test_voice_process_recovery.py +++ b/ios/recovery-repro/test_voice_process_recovery.py @@ -1,7 +1,7 @@ #!/usr/bin/env python3 """Real process-death characterization against copied, unmodified production Swift sources. -All seven baseline cases now pass through the opt-in production restore API. +Eight crash/relaunch and control cases exercise the opt-in production restore API. --require-recovery remains compatible with the original failing-baseline invocation. No simulator, microphone or server. """ import argparse @@ -59,6 +59,7 @@ def setUp(self): "test_transcribing_recording_is_discoverable_after_process_death": "transcribing", "test_review_text_and_engine_survive_process_death": "review", "test_uncertain_create_reuses_key_after_process_death": "uncertain", + "test_later_edits_reconcile_original_request_after_process_death": "uncertain-edited", } scenario = scenarios.get(self._testMethodName) if scenario: @@ -79,7 +80,7 @@ def setUp(self): self.assertEqual(recovered_audio.getnframes(), 1600) if scenario == "transcribing": self.assertEqual(self.before["checkpoint"], "inside-transcriber") - if scenario == "uncertain": + if scenario in ("uncertain", "uncertain-edited"): self.assertEqual(self.before["checkpoint"], "request-awaiting-response") self.assertTrue(self.before["key"]) if scenario == "review": @@ -89,9 +90,9 @@ def setUp(self): child.communicate(timeout=5) self.assertEqual(child.returncode, -signal.SIGKILL) self.assertTrue(self.audio.exists(), "SIGKILL must bypass all app cleanup callbacks") - self.after = self.run_probe("retry" if scenario == "uncertain" else "relaunch") + self.after = self.run_probe({"uncertain": "retry", "uncertain-edited": "reconcile"}.get(scenario, "relaunch")) self.assertNotEqual(self.before["pid"], self.after["pid"]) - if scenario == "uncertain": + if scenario in ("uncertain", "uncertain-edited"): self.assertIsInstance(self.after.get("key"), str) self.assertTrue(self.after["key"], "retry must reach the request boundary") @@ -124,6 +125,16 @@ def test_review_text_and_engine_survive_process_death(self): def test_uncertain_create_reuses_key_after_process_death(self): self.assertEqual(self.after["key"], self.before["key"]) + def test_later_edits_reconcile_original_request_after_process_death(self): + self.assertEqual(self.after["key"], self.before["key"]) + self.assertEqual(self.after["createBody"], "Reviewed capture") + self.assertEqual(self.after["createLocale"], "en-US") + self.assertEqual(self.after["patchedID"], "7") + self.assertEqual(self.after["patchedBody"], "Later review edits") + self.assertEqual(self.after["saved"], "true") + self.assertEqual(self.after["remaining"], "0") + self.assertFalse(self.audio.exists()) + def test_failed_save_reuses_key_without_process_death(self): result = self.run_probe("same-process-retry") self.assertTrue(result["firstKey"]) diff --git a/state/ASTRA-1002.md b/state/ASTRA-1002.md index d1fd2b7..e4f4d26 100644 --- a/state/ASTRA-1002.md +++ b/state/ASTRA-1002.md @@ -324,3 +324,14 @@ process remains. Changes are on the same review branch/PR; no merge or deploymen - This NEW durable save entry point is not yet called by RecordingSheet. Legacy saveNote retains its old changed-payload semantics; wire the durable entry point when enabling account recovery. Need an extended hard-kill test for later-edit reconciliation, then app integration/verification. + +## Reset-window reconciliation across SIGKILL — 13:20 EDT +- Extended actual process-kill probe: persist an original create, edit review while awaiting its + response, SIGKILL, restore, replay original body/key/locale, then PATCH the returned ID with later + text and remove recovery after acknowledgment. No observer-file restoration or real server used. +- Guarded the legacy save entry point from bypassing an existing durable reconciliation. Its + regression failed on prior source (1 test, 3 failures); fixed source has **40 native tests passing**. +- OBSERVED **8 strict process-death cases pass** (`voice-reconcile-hardkill.log`), including the new + edited-pending-request case. Native output: `voice-reconcile-final-native.log`. +- Review identified next corrections before UI wiring: restore must reread current manifest by ID + instead of trusting a cached listing; reject blank initial submission before freezing its payload. From 32f7e8b4d1590be096cc9a7131646784b106b870 Mon Sep 17 00:00:00 2001 From: legitimate-apps <309192374+legitimate-apps@users.noreply.github.com> Date: Fri, 2 Oct 2026 13:23:16 -0400 Subject: [PATCH 22/27] Restore current voice manifests and reject invalid first submissions --- .../Transcription/VoiceCaptureFlow.swift | 5 ++++ .../VoiceRecordingRecoveryStore.swift | 10 +++++++ .../VoiceRecordingRecoveryStoreTests.swift | 29 +++++++++++++++++++ state/ASTRA-1002.md | 10 +++++++ 4 files changed, 54 insertions(+) diff --git a/ios/Command/Transcription/VoiceCaptureFlow.swift b/ios/Command/Transcription/VoiceCaptureFlow.swift index 17447b1..899dcb5 100644 --- a/ios/Command/Transcription/VoiceCaptureFlow.swift +++ b/ios/Command/Transcription/VoiceCaptureFlow.swift @@ -61,6 +61,7 @@ final class VoiceCaptureFlow { self.recovery = recovery if let recovery, let recording { do { + let recording = try recovery.recording(id: recording.id) audioURL = try recovery.audioURL(for: recording) captureID = recording.id recoveredRecordingID = recording.id @@ -209,6 +210,10 @@ final class VoiceCaptureFlow { defer { saving = false } do { if noteSubmission == nil { + guard !transcript.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { + errorMessage = "Add some text before saving this recording." + return false + } let engine = engineUsed.isEmpty ? "sfspeech" : engineUsed let key = try noteCreate.key(for: NotePayload(text: transcript, engine: engine)) noteSubmission = .init(body: transcript, engine: engine, locale: locale, key: key) diff --git a/ios/Command/Transcription/VoiceRecordingRecoveryStore.swift b/ios/Command/Transcription/VoiceRecordingRecoveryStore.swift index d32dd11..85a8242 100644 --- a/ios/Command/Transcription/VoiceRecordingRecoveryStore.swift +++ b/ios/Command/Transcription/VoiceRecordingRecoveryStore.swift @@ -133,6 +133,16 @@ final class VoiceRecordingRecoveryStore { return (recordings, unreadable) } + /// Listing entries are display snapshots. Restoration rereads the current manifest before + /// claiming ownership so a stale picker cannot erase a newer submission or note identity. + func recording(id: UUID) throws -> Recording { + let manifest = directory.appendingPathComponent(id.uuidString).appendingPathComponent("manifest.json") + let record = try JSONDecoder().decode(Recording.self, from: Data(contentsOf: manifest)) + guard record.id == id else { throw RecoveryError.invalidRecord } + _ = try audioURL(for: record) + return record + } + func audioURL(for record: Recording) throws -> URL { guard record.version == 1, ["recording.m4a", "recording.wav", "recording.caf"].contains(record.filename) else { throw RecoveryError.invalidRecord } diff --git a/ios/CommandTests/VoiceRecordingRecoveryStoreTests.swift b/ios/CommandTests/VoiceRecordingRecoveryStoreTests.swift index e3b9754..5273e36 100644 --- a/ios/CommandTests/VoiceRecordingRecoveryStoreTests.swift +++ b/ios/CommandTests/VoiceRecordingRecoveryStoreTests.swift @@ -228,6 +228,35 @@ final class VoiceRecordingRecoveryStoreTests: XCTestCase { XCTAssertFalse(sent); XCTAssertFalse(saved) XCTAssertEqual(try owner.load().recordings.count, 1) } + func testCachedListingCannotEraseNewerAcknowledgedNoteIdentity() async throws { + let owner = store(), original = VoiceCaptureFlow(recovery: owner) + original.adopt(try source()); original.transcript = "original" + let cached = try XCTUnwrap(owner.load().recordings.first) + _ = await original.saveRecoveredNote(locale: nil, using: .init(create: { _ in + original.transcript = "newer edits"; return 42 + }, update: { _, _ in throw URLError(.notConnectedToInternet) })) + let restored = VoiceCaptureFlow(recovery: owner, restoring: cached) + var created = false, updatedID = 0 + let saved = await restored.saveRecoveredNote(locale: nil, using: .init(create: { _ in + created = true; return 99 + }, update: { id, text in updatedID = id; XCTAssertEqual(text, "newer edits") })) + XCTAssertTrue(saved); XCTAssertFalse(created); XCTAssertEqual(updatedID, 42) + } + func testBlankInitialSubmissionDoesNotPoisonCorrectedCapture() async throws { + let owner = store(), flow = VoiceCaptureFlow(recovery: owner) + flow.adopt(try source()); flow.transcript = " \n " + var creates = 0 + let operations = VoiceCaptureFlow.NoteOperations(create: { request in + creates += 1 + if request.body.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { throw URLError(.badURL) } + return 42 + }, update: { _, _ in }) + let empty = await flow.saveRecoveredNote(locale: nil, using: operations) + XCTAssertFalse(empty); XCTAssertEqual(creates, 0) + flow.transcript = "corrected text" + let saved = await flow.saveRecoveredNote(locale: nil, using: operations) + XCTAssertTrue(saved); XCTAssertEqual(creates, 1) + } func testManifestCannotReferenceAnOutsideFile() throws { let owner = store() XCTAssertThrowsError(try owner.audioURL(for: .init(version: 1, id: UUID(), filename: "../../outside.m4a"))) diff --git a/state/ASTRA-1002.md b/state/ASTRA-1002.md index e4f4d26..376ac10 100644 --- a/state/ASTRA-1002.md +++ b/state/ASTRA-1002.md @@ -335,3 +335,13 @@ process remains. Changes are on the same review branch/PR; no merge or deploymen edited-pending-request case. Native output: `voice-reconcile-final-native.log`. - Review identified next corrections before UI wiring: restore must reread current manifest by ID instead of trusting a cached listing; reject blank initial submission before freezing its payload. + +## Reset-window restoration correctness — 13:23 EDT +- Added independent-review regressions first: stale listing could erase acknowledged note identity, + and a blank first request permanently froze an invalid payload (**2 tests, 5 failures** before fix). +- Restoration now rereads the current manifest by capture ID synchronously before claiming ownership. + Blank initial review is rejected before a pending request is created; corrected text remains savable. +- OBSERVED **42 native XCTest cases passed**, **8 strict process-death cases passed**. Logs: + `voice-restore-validation-{red,green,process}.log` under `/tmp/command-astra-1002/`. +- Next: integrated target compilation, then shared app lifecycle/microphone ownership and note-only + recovery UI integration with proper account deletion/teardown. No partial UI activation is present. From 13c2479b3f5c0d10b9562291df53677f3f1e230e Mon Sep 17 00:00:00 2001 From: legitimate-apps <309192374+legitimate-apps@users.noreply.github.com> Date: Fri, 2 Oct 2026 13:28:35 -0400 Subject: [PATCH 23/27] Checkpoint terminal voice cleanup before unlinking private audio --- docs/decisions/2026-10-02-voice-recovery.md | 14 +++++++--- .../Transcription/VoiceCaptureFlow.swift | 4 ++- .../VoiceRecordingRecoveryStore.swift | 27 ++++++++++++++----- .../VoiceRecordingRecoveryStoreTests.swift | 23 ++++++++++++++++ ios/recovery-repro/README.md | 20 +++++++------- state/ASTRA-1002.md | 16 +++++++++++ 6 files changed, 82 insertions(+), 22 deletions(-) diff --git a/docs/decisions/2026-10-02-voice-recovery.md b/docs/decisions/2026-10-02-voice-recovery.md index e47b427..9052b1c 100644 --- a/docs/decisions/2026-10-02-voice-recovery.md +++ b/docs/decisions/2026-10-02-voice-recovery.md @@ -1,6 +1,6 @@ # Voice capture ownership and process-death recovery -Status: **proposed implementation contract; not implemented**. The first reproductions are +Status: **partially implemented in opt-in production primitives; app integration pending**. The first reproductions are committed in `ios/recovery-repro/`. This note records the work needed to turn the existing within-process voice safety into durable recovery, without changing the capture product flow. @@ -12,7 +12,10 @@ URL, transcript, engine, revision, and create attempt only in memory. Its defaul during transcription, during edited review, or while awaiting a create response leaves a new process unable to discover the capture or reuse the pending request key. -The native subprocess reproducer compiles actual production source, reaches those boundaries, +The initial native subprocess reproducer compiled actual production source and reached those boundaries. +Its historical baseline below predates the opt-in durable store. The current eight cases pass +through production discovery/restoration, including later-edit reconciliation; RecordingSheet +still uses its nonpersistent default. The reproducer uses SIGKILL, checks the exit signal, and launches a different process. Three existing-behavior controls pass; four recovery assertions are expected failures. Strict mode fails those four assertions. The raw fixture file survives the kill, which separates lost discovery/metadata @@ -124,6 +127,9 @@ that is a separate boundary from successful remote submission. queue, accepted durable draft transfer, and uncertain assistant send. Assert no duplicated, cross-account, or unintended submissions. Run iOS tests, Catalyst build, and UI verification. -The bounded 2026-10-02 follow-on delivers the baseline and this contract only. Production -persistence is deliberately not partially wired into the app: unfinished recording durability, +The first bounded 2026-10-02 follow-on delivered the baseline and this contract. The later +operator-authorized reset window added account-scoped audio, review and complete note-request +checkpoints, ownership fencing, note-ID/PATCH reconciliation and terminal cleanup. These +primitives pass native and process-death checks. Production persistence remains opt-in and +is not wired into the app: unfinished recording durability, destructive lifecycle callbacks, and unacknowledged handoff must be solved and verified together. diff --git a/ios/Command/Transcription/VoiceCaptureFlow.swift b/ios/Command/Transcription/VoiceCaptureFlow.swift index 899dcb5..d86f5c2 100644 --- a/ios/Command/Transcription/VoiceCaptureFlow.swift +++ b/ios/Command/Transcription/VoiceCaptureFlow.swift @@ -283,7 +283,9 @@ final class VoiceCaptureFlow { guard ownsRecording else { return false } if let recoveredRecordingID, let recovery { do { - try recovery.discard(recoveredRecordingID) + if try !recovery.discard(recoveredRecordingID) { + errorMessage = "This recording is finished. Its private audio cleanup will be retried." + } recovery.release(recoveredRecordingID, owner: recordingOwner) } catch { diff --git a/ios/Command/Transcription/VoiceRecordingRecoveryStore.swift b/ios/Command/Transcription/VoiceRecordingRecoveryStore.swift index 85a8242..c31d245 100644 --- a/ios/Command/Transcription/VoiceRecordingRecoveryStore.swift +++ b/ios/Command/Transcription/VoiceRecordingRecoveryStore.swift @@ -25,6 +25,7 @@ final class VoiceRecordingRecoveryStore { enum RecoveryError: Error { case invalidRecord } let directory: URL private let files = FileManager.default + private let removeItem: (URL) throws -> Void private static var owners: [URL: UUID] = [:] func claim(_ id: UUID, owner: UUID) { @@ -38,7 +39,9 @@ final class VoiceRecordingRecoveryStore { if Self.owners[key] == owner { Self.owners.removeValue(forKey: key) } } - init(root: URL, server: URL, accountID: Int, username: String, accountCreatedAt: String) { + init(root: URL, server: URL, accountID: Int, username: String, accountCreatedAt: String, + removeItem: @escaping (URL) throws -> Void = { try FileManager.default.removeItem(at: $0) }) { + self.removeItem = removeItem let identity = [server.absoluteString.trimmingCharacters(in: CharacterSet(charactersIn: "/")), String(accountID), username, accountCreatedAt].joined(separator: "\n") let scope = SHA256.hash(data: Data(identity.utf8)).map { String(format: "%02x", $0) }.joined() @@ -121,6 +124,12 @@ final class VoiceRecordingRecoveryStore { var recordings: [Recording] = [] var unreadable = false for folder in folders { + let name = folder.lastPathComponent + if name.hasPrefix(".discarded-"), UUID(uuidString: String(name.dropFirst(11))) != nil { + // Only an explicit terminal rename authorizes cleanup; unknown files are retained. + try? removeItem(folder) + continue + } let manifest = folder.appendingPathComponent("manifest.json") guard files.fileExists(atPath: manifest.path) else { continue } do { @@ -151,12 +160,16 @@ final class VoiceRecordingRecoveryStore { return url } - /// Removing the manifest first makes a crash during cleanup non-replayable. Leftover audio - /// remains private; it is never mistaken for another pending recording. - func discard(_ id: UUID) throws { + /// The same-volume rename is the terminal checkpoint. If it fails, the intact capture + /// remains pending. Once it succeeds, failed unlink is cleanup work, never a pending note. + /// Returns whether cleanup finished; false still means the capture is durably terminal. + @discardableResult + func discard(_ id: UUID) throws -> Bool { let folder = directory.appendingPathComponent(id.uuidString, isDirectory: true) - let manifest = folder.appendingPathComponent("manifest.json") - if files.fileExists(atPath: manifest.path) { try files.removeItem(at: manifest) } - if files.fileExists(atPath: folder.path) { try files.removeItem(at: folder) } + let retired = directory.appendingPathComponent(".discarded-" + id.uuidString, isDirectory: true) + if files.fileExists(atPath: folder.path) { try files.moveItem(at: folder, to: retired) } + guard files.fileExists(atPath: retired.path) else { return true } + do { try removeItem(retired); return true } + catch { return false } } } diff --git a/ios/CommandTests/VoiceRecordingRecoveryStoreTests.swift b/ios/CommandTests/VoiceRecordingRecoveryStoreTests.swift index 5273e36..0a1cf73 100644 --- a/ios/CommandTests/VoiceRecordingRecoveryStoreTests.swift +++ b/ios/CommandTests/VoiceRecordingRecoveryStoreTests.swift @@ -257,6 +257,29 @@ final class VoiceRecordingRecoveryStoreTests: XCTestCase { let saved = await flow.saveRecoveredNote(locale: nil, using: operations) XCTAssertTrue(saved); XCTAssertEqual(creates, 1) } + func testCleanupFailureCannotResurrectOrStrandAcknowledgedCapture() async throws { + var blockCleanup = true + let owner = VoiceRecordingRecoveryStore(root: root.appendingPathComponent("recovery"), + server: URL(string: "https://example.com")!, accountID: 1, username: "tester", + accountCreatedAt: "first", removeItem: { url in + if blockCleanup && url.lastPathComponent != "manifest.json" { throw URLError(.cannotRemoveFile) } + try FileManager.default.removeItem(at: url) + }) + let flow = VoiceCaptureFlow(recovery: owner) + flow.adopt(try source()); flow.transcript = "acknowledged note" + let id = flow.captureID + let saved = await flow.saveRecoveredNote(locale: nil, using: .init(create: { _ in 42 }, update: { _, _ in })) + XCTAssertTrue(saved, "A completed capture must be terminal even if unlink fails") + XCTAssertNil(flow.audioURL) + XCTAssertNotNil(flow.errorMessage, "Private audio cleanup remains visible") + XCTAssertTrue(try owner.load().recordings.isEmpty) + XCTAssertThrowsError(try owner.recording(id: id)) + XCTAssertFalse(FileManager.default.fileExists(atPath: owner.directory.appendingPathComponent(id.uuidString).path)) + blockCleanup = false + _ = try owner.load() + XCTAssertTrue(try FileManager.default.contentsOfDirectory(atPath: owner.directory.path).isEmpty, + "Known terminal leftovers should be cleaned on the next discovery") + } func testManifestCannotReferenceAnOutsideFile() throws { let owner = store() XCTAssertThrowsError(try owner.audioURL(for: .init(version: 1, id: UUID(), filename: "../../outside.m4a"))) diff --git a/ios/recovery-repro/README.md b/ios/recovery-repro/README.md index 7d8d1a5..d7734c8 100644 --- a/ios/recovery-repro/README.md +++ b/ios/recovery-repro/README.md @@ -1,12 +1,12 @@ # Voice process-death reproduction -**Current implementation checkpoint:** all seven original cases pass in strict mode through the -opt-in production audio/review/attempt restore API. RecordingSheet is not yet wired to it; this -is not end-to-end app recovery. Later edits after an uncertain create still need note-ID/PATCH -reconciliation. The historical baseline and intermediate results below document progression. +**Current implementation checkpoint:** all eight cases pass through the opt-in production +account-scoped audio/review/request restore API. The eighth case reconciles later edits after +an uncertain create using the original request identity and a PATCH to its returned note ID. +RecordingSheet is not yet wired to recovery; this is not end-to-end app recovery. An opt-in native macOS harness for the current voice recovery gap. It copies unmodified -production `VoiceCaptureFlow`, `CreateAttempt`, and shared validation source into a tiny SwiftPM +production `VoiceCaptureFlow`, `VoiceRecordingRecoveryStore`, `CreateAttempt`, and shared validation source into a tiny SwiftPM executable, then Python tests kill and relaunch that executable. No third-party dependency, microphone, simulator, server, or app account is used. @@ -19,7 +19,7 @@ python3 ios/recovery-repro/test_voice_process_recovery.py --build-dir "$VOICE_RE python3 ios/recovery-repro/test_voice_process_recovery.py --build-dir "$VOICE_REPRO_DD" --require-recovery ``` -Current result: +Historical test-first baseline (before the production store was implemented): - Default characterization: **7 cases, 3 controls passed, 4 expected failures**. - `--require-recovery`: **4 ordinary failures**, exit 1. This is the test-first acceptance baseline, @@ -33,12 +33,12 @@ Harness/precondition failures occur in `setUp` and cannot count as expected reco Every child has a bounded wait and cleanup. Temporary fixtures are deleted at test end. The observation file is an **external oracle** only: the worker never reads it. A fresh launch -constructs the same default flow as the current recording sheet. The uncertain-create case -re-enters the exact original payload after relaunch to isolate retry-key loss from transcript -loss. It captures the request callback before a response; it does not contact a real server. +constructs a flow through production store discovery and restoration. The uncertain-create +cases restore the original body, engine, locale and key, including separately retained later +edits. They capture the request callback before a response; they do not contact a real server. The WAV fixture is valid finalized 16 kHz mono audio, but no decoding is invoked. These tests -prove loss of flow discovery, metadata and retry identity across actual process death. They do +exercise flow discovery, metadata and retry identity across actual process death. They do not prove recovery of unfinished M4A, AVAudioSession behavior, actual app bootstrap, account isolation, or UI integration. The stop checkpoint begins at `flow.adopt`, not an actual recorder. diff --git a/state/ASTRA-1002.md b/state/ASTRA-1002.md index 376ac10..50e28e3 100644 --- a/state/ASTRA-1002.md +++ b/state/ASTRA-1002.md @@ -345,3 +345,19 @@ process remains. Changes are on the same review branch/PR; no merge or deploymen `voice-restore-validation-{red,green,process}.log` under `/tmp/command-astra-1002/`. - Next: integrated target compilation, then shared app lifecycle/microphone ownership and note-only recovery UI integration with proper account deletion/teardown. No partial UI activation is present. + +## Reset-window terminal cleanup — 13:30 EDT +- OBSERVED integrated iOS Simulator and Mac Catalyst builds passed at commit 32f7e8b + (`voice-current-{ios,catalyst}-build.log`). No simulator was booted. +- Added a failing filesystem-cleanup regression: after note acknowledgment, deleting the manifest + before a failed audio unlink stranded the editable flow (1 test, 4 failed assertions). +- Terminal cleanup now atomically renames the capture directory before unlinking. A failed rename + retains the pending capture; a failed unlink leaves a terminal private directory, visibly reports + cleanup pending, and discovery retries only these explicitly retired directories. +- OBSERVED fixed source: **43 native XCTest cases passed**, **8 strict process-death cases passed**. + Evidence: `/tmp/command-astra-1002/voice-terminal-{red,green,process}.log`. +- Updated the reproduction README and ownership design status to distinguish the implemented + opt-in primitives from the historical failing baseline and still-unwired RecordingSheet. +- Still unfinished: shared microphone/account lifecycle coordinator, retained sheet disappearance, + real recorder crash behavior, acknowledged assistant handoff and actual app recovery UI. Next: + wire-test durable note reconciliation against the local REST server before activating app recovery. From fa210c3d84102e315d7eb2e96cc4c5603a43876e Mon Sep 17 00:00:00 2001 From: legitimate-apps <309192374+legitimate-apps@users.noreply.github.com> Date: Fri, 2 Oct 2026 13:31:32 -0400 Subject: [PATCH 24/27] Verify voice crash recovery against REST and SQLite --- ios/recovery-repro/README.md | 18 +++ ios/recovery-repro/VoiceRecoveryProbe.swift | 56 ++++++++ .../test_voice_process_recovery.py | 11 +- .../test_voice_wire_recovery.py | 122 ++++++++++++++++++ state/ASTRA-1002.md | 14 ++ 5 files changed, 219 insertions(+), 2 deletions(-) create mode 100644 ios/recovery-repro/test_voice_wire_recovery.py diff --git a/ios/recovery-repro/README.md b/ios/recovery-repro/README.md index d7734c8..3a70775 100644 --- a/ios/recovery-repro/README.md +++ b/ios/recovery-repro/README.md @@ -66,3 +66,21 @@ The unchanged reviewed capture now restores its persisted create key and payload request checkpoint blocks submission. Strict mode: **7 passed, no expected failures**. Native source suite: **30 passed**. Production app/account/UI integration and later-edit reconciliation remain required; passing this initial matrix alone does not establish complete voice recovery. + +## Local REST and SQLite acceptance + +`test_voice_wire_recovery.py` builds the same production-source probe, starts the actual server +on a reserved loopback socket with a fresh temporary SQLite database and no inherited model +credentials, and uses the actual Swift APIClient with ephemeral cookies. It kills the client +AFTER a real POST commits but BEFORE the flow receives the note ID. A new process restores the +original request and later edits, repeats POST, then PATCHes the same note. Assertions inspect +SQLite before and after, original key/locale, separate process IDs, terminal recovery and audio +cleanup. The observation file is removed before relaunch. All child processes stop in `finally`. + +```sh +python3 ios/recovery-repro/test_voice_wire_recovery.py --build-dir "$VOICE_REPRO_DD" +``` + +Requires the existing `server/.venv` (or `--server-python PATH`). Current result: **1 passed**; +HTTP **POST 201, POST 201, PATCH 200**, SQLite **one note** with the later review body. This proves +the wire/persistence boundary, not the still-unwired app screen or unfinished M4A decoding. diff --git a/ios/recovery-repro/VoiceRecoveryProbe.swift b/ios/recovery-repro/VoiceRecoveryProbe.swift index 502d856..ae30f4d 100644 --- a/ios/recovery-repro/VoiceRecoveryProbe.swift +++ b/ios/recovery-repro/VoiceRecoveryProbe.swift @@ -7,6 +7,10 @@ struct VoiceRecoveryProbe { static func main() async throws { let args = CommandLine.arguments let mode = args[1], directory = URL(fileURLWithPath: args[2], isDirectory: true) + if mode.hasPrefix("wire-") { + try await wire(mode: mode, directory: directory, server: URL(string: args[3])!) + return + } let audio = directory.appendingPathComponent("recording.wav") let recovery = VoiceRecordingRecoveryStore(root: directory.appendingPathComponent("recovery"), server: URL(string: "https://example.invalid")!, accountID: 1, @@ -87,3 +91,55 @@ struct VoiceRecoveryProbe { } } } + +private extension VoiceRecoveryProbe { + @MainActor + static func wire(mode: String, directory: URL, server: URL) async throws { + precondition(server.host == "127.0.0.1" && server.scheme == "http") + let client = APIClient(baseURL: server, configuration: .ephemeral) + let username = "voice-recovery-test", password = "local-fixture-password-only" + if mode == "wire-seed" { try await client.register(username: username, password: password, displayName: nil) } + let account = try await client.login(username: username, password: password) + let recovery = VoiceRecordingRecoveryStore(root: directory.appendingPathComponent("recovery"), + server: server, accountID: account.id, username: account.username, accountCreatedAt: account.createdAt) + let record = mode == "wire-reconcile" ? try recovery.load().recordings.first : nil + let flow = VoiceCaptureFlow(recovery: recovery, restoring: record) + if mode == "wire-seed" { + flow.adopt(directory.appendingPathComponent("recording.wav")) + flow.transcript = "Original voice capture" + } + var observations: [String: String] = [:] + func snapshot() throws { + observations["pid"] = String(ProcessInfo.processInfo.processIdentifier) + observations["audio"] = flow.audioURL?.path ?? "" + observations["review"] = flow.transcript + try JSONSerialization.data(withJSONObject: observations, options: [.sortedKeys]) + .write(to: directory.appendingPathComponent("observation.json"), options: .atomic) + } + let saved = await flow.saveRecoveredNote(locale: mode == "wire-seed" ? "en-US" : "fr-FR", + using: .init(create: { request in + let note = try await client.createNote(body: request.body, source: "voice", engine: request.engine, + locale: request.locale, idempotencyKey: request.key) + observations["key"] = request.key + observations["noteID"] = String(note.id) + observations["createBody"] = request.body + observations["createLocale"] = request.locale ?? "" + if mode == "wire-seed" { + // The server committed; withhold that acknowledgment from the production flow. + flow.transcript = "Later voice review edits" + observations["checkpoint"] = "server-committed-before-flow-ack" + try snapshot() + while true { try await Task.sleep(for: .seconds(3600)) } + } + return note.id + }, update: { id, text in + let note = try await client.updateNote(id: id, body: text) + observations["patchedID"] = String(note.id) + observations["patchedBody"] = note.body + })) + observations["saved"] = String(saved) + observations["remaining"] = String(try recovery.load().recordings.count) + observations["error"] = flow.errorMessage ?? "" + try snapshot() + } +} diff --git a/ios/recovery-repro/test_voice_process_recovery.py b/ios/recovery-repro/test_voice_process_recovery.py index 0d3f95c..90bea35 100644 --- a/ios/recovery-repro/test_voice_process_recovery.py +++ b/ios/recovery-repro/test_voice_process_recovery.py @@ -30,11 +30,18 @@ def build_probe(build_dir): ''') for relative in ( "Transcription/VoiceCaptureFlow.swift", "Transcription/VoiceRecordingRecoveryStore.swift", - "Networking/CreateAttempt.swift", - "Widgets/AssistantSurfaceLogic.swift", + "Networking/CreateAttempt.swift", "Networking/APIClient.swift", + "Networking/Models.swift", "Networking/ServerInfo.swift", + "Widgets/AssistantSurfaceLogic.swift", "Features/Notes/MarkdownSyntax.swift", ): source = ROOT / "ios/Command" / relative shutil.copyfile(source, sources / source.name) + # APIClient's unused model-list endpoint needs this shape from the UI store. Copy its + # declaration verbatim without pulling in the unrelated assistant streaming subsystem. + agent_source = (ROOT / "ios/Command/Features/Agent/AgentStore.swift").read_text() + start = agent_source.index("struct AgentModelTier:") + end = agent_source.index("\n}", start) + 2 + (sources / "AgentModelTier.swift").write_text(agent_source[start:end] + "\n") shutil.copyfile(Path(__file__).with_name("VoiceRecoveryProbe.swift"), sources / "VoiceRecoveryProbe.swift") subprocess.run(["swift", "build", "--package-path", str(package), "--jobs", "2"], check=True, timeout=120) result = subprocess.run(["swift", "build", "--package-path", str(package), "--show-bin-path"], diff --git a/ios/recovery-repro/test_voice_wire_recovery.py b/ios/recovery-repro/test_voice_wire_recovery.py new file mode 100644 index 0000000..67c2787 --- /dev/null +++ b/ios/recovery-repro/test_voice_wire_recovery.py @@ -0,0 +1,122 @@ +#!/usr/bin/env python3 +"""SIGKILL a voice client after real local REST create, then reconcile against SQLite. + +Uses production Swift persistence/flow/APIClient and the real server with a disposable database. +No model credentials, simulator or remote server; the owned server always stops at test exit. +""" +import argparse +import json +import os +from pathlib import Path +import signal +import socket +import sqlite3 +import subprocess +import tempfile +import time +import unittest +import urllib.error +import urllib.request +import wave + +from test_voice_process_recovery import ROOT, build_probe + +PROBE = None +SERVER_PYTHON = None + + +class VoiceWireRecoveryTests(unittest.TestCase): + @staticmethod + def stop(child): + if child.poll() is None: + child.terminate() + try: + child.wait(timeout=5) + except subprocess.TimeoutExpired: + child.kill() + child.wait(timeout=5) + + def test_lost_create_response_and_process_death_patch_one_note(self): + with tempfile.TemporaryDirectory(prefix="command-voice-wire-") as temporary: + directory = Path(temporary) + db = directory / "command.db" + log = directory / "server.log" + # Inherit no application/model credentials and load no worktree .env file. + env = {name: os.environ[name] for name in ("PATH", "HOME", "TMPDIR", "LANG") if name in os.environ} + env.update(COMMAND_DB_PATH=str(db), COMMAND_COOKIE_SECURE="false", + COMMAND_ENVIRONMENT="dev", COMMAND_MAX_LLM_SENDS_BEFORE_OPEN="0") + with socket.socket() as listener, log.open("w") as output: + listener.bind(("127.0.0.1", 0)) + listener.listen() + server_url = f"http://127.0.0.1:{listener.getsockname()[1]}" + server = subprocess.Popen([str(SERVER_PYTHON), "-m", "uvicorn", "command.app:app", + "--fd", str(listener.fileno()), "--workers", "1"], cwd=directory, env=env, + pass_fds=(listener.fileno(),), stdout=output, stderr=subprocess.STDOUT) + try: + deadline = time.monotonic() + 20 + while True: + try: + with urllib.request.urlopen(server_url + "/api/health", timeout=0.3) as response: + self.assertEqual(response.status, 200) + break + except (urllib.error.URLError, TimeoutError): + if server.poll() is not None or time.monotonic() > deadline: + self.fail("Disposable server failed readiness: " + log.read_text()[-2000:]) + time.sleep(0.05) + with wave.open(str(directory / "recording.wav"), "wb") as audio: + audio.setnchannels(1); audio.setsampwidth(2); audio.setframerate(16000) + audio.writeframes(b"\0\0" * 1600) + observation = directory / "observation.json" + with (directory / "client.log").open("w") as client_output: + child = subprocess.Popen([str(PROBE), "wire-seed", str(directory), server_url], + stdout=client_output, stderr=subprocess.STDOUT) + try: + deadline = time.monotonic() + 15 + while not observation.exists() and child.poll() is None and time.monotonic() < deadline: + time.sleep(0.01) + self.assertTrue(observation.exists(), "Client failed checkpoint: " + + (directory / "client.log").read_text()[-2000:]) + before = json.loads(observation.read_text()) + self.assertEqual(before.get("checkpoint"), "server-committed-before-flow-ack", before) + with sqlite3.connect(db) as connection: + initial = connection.execute("SELECT id, body, source, engine, locale, idempotency_key FROM notes").fetchall() + self.assertEqual(initial, [(int(before["noteID"]), "Original voice capture", "voice", + "sfspeech", "en-US", before["key"])]) + manifests = list((directory / "recovery").glob("*/*/manifest.json")) + self.assertEqual(len(manifests), 1) + self.assertIsNone(json.loads(manifests[0].read_text()).get("savedNoteID")) + child.kill(); child.wait(timeout=5) + self.assertEqual(child.returncode, -signal.SIGKILL) + finally: + self.stop(child) + observation.unlink() # Relaunch cannot use the external observer as persistence. + subprocess.run([str(PROBE), "wire-reconcile", str(directory), server_url], + check=True, capture_output=True, text=True, timeout=15) + after = json.loads(observation.read_text()) + self.assertNotEqual(before["pid"], after["pid"]) + self.assertEqual(after["key"], before["key"]) + self.assertEqual(after["createBody"], "Original voice capture") + self.assertEqual(after["createLocale"], "en-US") + self.assertEqual(after["patchedID"], before["noteID"]) + self.assertEqual(after["saved"], "true", after) + self.assertEqual(after["remaining"], "0") + self.assertFalse(Path(before["audio"]).exists()) + with sqlite3.connect(db) as connection: + final = connection.execute("SELECT id, body, source, engine, locale, idempotency_key FROM notes").fetchall() + self.assertEqual(final, [(int(before["noteID"]), "Later voice review edits", "voice", + "sfspeech", "en-US", before["key"])]) + print("OBSERVED SQLite: one voice note, original key/locale, later review body, audio removed") + print("OBSERVED HTTP:\n" + "\n".join(line for line in log.read_text().splitlines() + if ' /api/notes' in line)) + finally: + self.stop(server) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--build-dir", type=Path, required=True, help="Owned dd-lease directory") + parser.add_argument("--server-python", type=Path, default=ROOT / "server/.venv/bin/python") + args = parser.parse_args() + PROBE = build_probe(args.build_dir) + SERVER_PYTHON = args.server_python.absolute() + unittest.main(argv=[__file__], verbosity=2) diff --git a/state/ASTRA-1002.md b/state/ASTRA-1002.md index 50e28e3..e9ccbb5 100644 --- a/state/ASTRA-1002.md +++ b/state/ASTRA-1002.md @@ -361,3 +361,17 @@ process remains. Changes are on the same review branch/PR; no merge or deploymen - Still unfinished: shared microphone/account lifecycle coordinator, retained sheet disappearance, real recorder crash behavior, acknowledged assistant handoff and actual app recovery UI. Next: wire-test durable note reconciliation against the local REST server before activating app recovery. + +## Reset-window real REST reconciliation — 13:31 EDT +- Added a repeatable local-wire acceptance test using production VoiceCaptureFlow/store/APIClient, + a credential-free disposable server on a reserved loopback socket and a fresh SQLite database. +- Client receives real POST success, withholds acknowledgment from the flow, persists later review + edits, then is SIGKILLed. Relaunch restores without its observer file and reconciles the original + request. SQLite assertions prove exactly one note with the original key/engine/locale and later + review body; acknowledged completion removes recovery/audio. +- OBSERVED **1 wire test passed**, HTTP **POST 201 + POST 201 + PATCH 200**; original **8 process + cases passed** with the expanded actual-APIClient build. Logs: `voice-wire-result.log` and + `voice-wire-compile.log`. The disposable server/client stopped and fixtures were removed. +- Next: implement explicit retain-on-disappearance/async suspension behavior in the flow before + coordinator/UI integration. No app recovery UI is enabled yet; actual M4A crash behavior and + durable assistant handoff remain unverified/unimplemented. From a5265d73390beb0c7f3b284e43a5c517bd75d7da Mon Sep 17 00:00:00 2001 From: legitimate-apps <309192374+legitimate-apps@users.noreply.github.com> Date: Fri, 2 Oct 2026 13:33:54 -0400 Subject: [PATCH 25/27] Retain voice recovery when suspending presentation ownership --- .../Transcription/VoiceCaptureFlow.swift | 27 +++++++++++ .../VoiceRecordingRecoveryStoreTests.swift | 47 +++++++++++++++++++ state/ASTRA-1002.md | 12 +++++ 3 files changed, 86 insertions(+) diff --git a/ios/Command/Transcription/VoiceCaptureFlow.swift b/ios/Command/Transcription/VoiceCaptureFlow.swift index d86f5c2..b227a15 100644 --- a/ios/Command/Transcription/VoiceCaptureFlow.swift +++ b/ios/Command/Transcription/VoiceCaptureFlow.swift @@ -259,6 +259,33 @@ final class VoiceCaptureFlow { /// The transcript was handed to the caller from review: the words are committed. func committedToCaller() { discardAudio() } + /// End this presentation's ownership without discarding its capture. The coordinator must + /// finalize/adopt active recorder audio first. Failure leaves this owner usable so the caller + /// can retain it and surface the checkpoint error instead of claiming recovery is safe. + @discardableResult + func suspendKeepingRecovery() -> Bool { + guard ownsRecording else { return false } + if audioURL != nil { + guard let recovery, let recoveredRecordingID else { + errorMessage = "This recording has no recovery copy yet. Keep Command open." + return false + } + do { + if noteSubmission != nil { try checkpointSubmission() } + else { + try recovery.saveReview(id: recoveredRecordingID, transcript: transcript, engine: engineUsed) + } + recovery.release(recoveredRecordingID, owner: recordingOwner) + } catch { + errorMessage = "Couldn't keep your latest review edits. Keep Command open until they save." + return false + } + } + captureID = UUID() + isCancelled = true + return true + } + /// The user cancelled (or the sheet went away): drop the recording and suppress any in-flight /// transcription's result. func cancel() { diff --git a/ios/CommandTests/VoiceRecordingRecoveryStoreTests.swift b/ios/CommandTests/VoiceRecordingRecoveryStoreTests.swift index 0a1cf73..6d92268 100644 --- a/ios/CommandTests/VoiceRecordingRecoveryStoreTests.swift +++ b/ios/CommandTests/VoiceRecordingRecoveryStoreTests.swift @@ -280,6 +280,53 @@ final class VoiceRecordingRecoveryStoreTests: XCTestCase { XCTAssertTrue(try FileManager.default.contentsOfDirectory(atPath: owner.directory.path).isEmpty, "Known terminal leftovers should be cleaned on the next discovery") } + func testSuspensionRetainsReviewAndRejectsLateTranscription() async throws { + let owner = store(), flow = VoiceCaptureFlow(recovery: owner) + flow.adopt(try source()); flow.transcript = "review before disappearance" + let result = await flow.transcribe(immediateUse: true) { _ in + XCTAssertTrue(flow.suspendKeepingRecovery()) + return ("late transcript must not be sent", "sfspeech") + } + XCTAssertNil(result); XCTAssertTrue(flow.isCancelled) + flow.cancel() // a stale disappearance callback cannot discard the retained capture + flow.transcript = "stale view edit" + let restored = VoiceCaptureFlow(recovery: owner, restoring: try XCTUnwrap(owner.load().recordings.first)) + XCTAssertEqual(restored.transcript, "review before disappearance") + XCTAssertNotNil(restored.audioURL) + } + func testSuspensionWhileCreatingRetainsOriginalRequestForReconciliation() async throws { + let owner = store(), flow = VoiceCaptureFlow(recovery: owner) + flow.adopt(try source()); flow.transcript = "original" + var key = "" + let saved = await flow.saveRecoveredNote(locale: "en-US", using: .init(create: { request in + key = request.key; flow.transcript = "later edits" + XCTAssertTrue(flow.suspendKeepingRecovery()) + return 42 + }, update: { _, _ in XCTFail("Suspended flow must not send a PATCH") })) + XCTAssertFalse(saved) + let record = try XCTUnwrap(owner.load().recordings.first) + XCTAssertEqual(record.noteSubmission?.key, key); XCTAssertNil(record.savedNoteID) + XCTAssertEqual(record.transcript, "later edits") + let restored = VoiceCaptureFlow(recovery: owner, restoring: record) + let reconciled = await restored.saveRecoveredNote(locale: nil, using: .init(create: { request in + XCTAssertEqual(request.key, key); XCTAssertEqual(request.body, "original"); return 42 + }, update: { id, body in XCTAssertEqual(id, 42); XCTAssertEqual(body, "later edits") })) + XCTAssertTrue(reconciled) + } + func testSuspensionRefusesToClaimUnsavedEditsAreDurable() throws { + let owner = store(), flow = VoiceCaptureFlow(recovery: owner) + flow.adopt(try source()); flow.transcript = "keep me" + let manifest = owner.directory.appendingPathComponent(flow.captureID.uuidString).appendingPathComponent("manifest.json") + let original = try Data(contentsOf: manifest) + try Data("damaged".utf8).write(to: manifest) + XCTAssertFalse(flow.suspendKeepingRecovery()) + XCTAssertFalse(flow.isCancelled); XCTAssertNotNil(flow.errorMessage) + XCTAssertNotNil(flow.audioURL) + try original.write(to: manifest) + flow.transcript = "still writable" + XCTAssertEqual(try owner.recording(id: flow.captureID).transcript, "still writable") + XCTAssertTrue(flow.suspendKeepingRecovery()) + } func testManifestCannotReferenceAnOutsideFile() throws { let owner = store() XCTAssertThrowsError(try owner.audioURL(for: .init(version: 1, id: UUID(), filename: "../../outside.m4a"))) diff --git a/state/ASTRA-1002.md b/state/ASTRA-1002.md index e9ccbb5..3d6881c 100644 --- a/state/ASTRA-1002.md +++ b/state/ASTRA-1002.md @@ -375,3 +375,15 @@ process remains. Changes are on the same review branch/PR; no merge or deploymen - Next: implement explicit retain-on-disappearance/async suspension behavior in the flow before coordinator/UI integration. No app recovery UI is enabled yet; actual M4A crash behavior and durable assistant handoff remain unverified/unimplemented. + +## Reset-window explicit retention boundary — 13:34 EDT +- Added test-first suspension contracts (initial compile correctly failed for the absent API), then + implemented suspendKeepingRecovery: checkpoint current review/request, release ownership, and + invalidate callbacks without deleting audio. Failed checkpoints retain a usable owner and error. +- OBSERVED **46 native XCTest cases passed**. New cases cover late transcription after suspension, + stale cancellation/edit callbacks, suspension during create followed by original-request replay, + and checkpoint failure/recovery. Logs: `voice-suspend-{red,green}.log`. +- This API still requires a coordinator to finalize active recorder audio before suspension and + retain the flow on checkpoint failure; RecordingSheet has not been changed or activated. +- Next: integrated builds/process regression checks, consume independent review, then shared + account/microphone coordinator with explicit restore selection and real app verification. From 62885ec26e55a1aa71431c92c854c3b4b9c40e83 Mon Sep 17 00:00:00 2001 From: legitimate-apps <309192374+legitimate-apps@users.noreply.github.com> Date: Fri, 2 Oct 2026 13:39:20 -0400 Subject: [PATCH 26/27] Fence retired voice recovery stores and delete account audio explicitly --- .../VoiceRecordingRecoveryStore.swift | 36 +++++++++++- .../VoiceRecordingRecoveryStoreTests.swift | 57 +++++++++++++++++++ state/ASTRA-1002.md | 15 +++++ 3 files changed, 105 insertions(+), 3 deletions(-) diff --git a/ios/Command/Transcription/VoiceRecordingRecoveryStore.swift b/ios/Command/Transcription/VoiceRecordingRecoveryStore.swift index c31d245..fe4e00d 100644 --- a/ios/Command/Transcription/VoiceRecordingRecoveryStore.swift +++ b/ios/Command/Transcription/VoiceRecordingRecoveryStore.swift @@ -22,21 +22,43 @@ final class VoiceRecordingRecoveryStore { var savedNoteID: Int? = nil var savedText: String? = nil } - enum RecoveryError: Error { case invalidRecord } + enum RecoveryError: Error { case invalidRecord, inactiveAccount } let directory: URL private let files = FileManager.default private let removeItem: (URL) throws -> Void private static var owners: [URL: UUID] = [:] + private var claimedOwners: [URL: UUID] = [:] + private var active = true + + private func requireActive() throws { + guard active else { throw RecoveryError.inactiveAccount } + } + + /// The account coordinator shares this store across its flows. Retirement is permanent: + /// signing in again uses a fresh store. Failed deletion still retires callbacks and may be + /// retried explicitly; never silently claim private files were removed. + func deactivate(deleteRecordings: Bool) throws { + active = false + for (key, owner) in claimedOwners where Self.owners[key] == owner { + Self.owners.removeValue(forKey: key) + } + claimedOwners.removeAll() + if deleteRecordings, files.fileExists(atPath: directory.path) { try removeItem(directory) } + } func claim(_ id: UUID, owner: UUID) { - Self.owners[directory.appendingPathComponent(id.uuidString)] = owner + guard active else { return } + let key = directory.appendingPathComponent(id.uuidString) + Self.owners[key] = owner + claimedOwners[key] = owner } func isOwner(_ id: UUID, owner: UUID) -> Bool { - Self.owners[directory.appendingPathComponent(id.uuidString)] == owner + active && Self.owners[directory.appendingPathComponent(id.uuidString)] == owner } func release(_ id: UUID, owner: UUID) { let key = directory.appendingPathComponent(id.uuidString) if Self.owners[key] == owner { Self.owners.removeValue(forKey: key) } + if claimedOwners[key] == owner { claimedOwners.removeValue(forKey: key) } } init(root: URL, server: URL, accountID: Int, username: String, accountCreatedAt: String, @@ -51,6 +73,7 @@ final class VoiceRecordingRecoveryStore { /// Publish metadata only after the copied audio exists. A crash during copy leaves the source /// untouched and an undiscoverable partial directory; no successful capture is claimed. func keep(_ source: URL, id: UUID) throws -> Recording { + try requireActive() let suffix = source.pathExtension.lowercased() guard ["m4a", "wav", "caf"].contains(suffix) else { throw RecoveryError.invalidRecord } let record = Recording(version: 1, id: id, filename: "recording.\(suffix)") @@ -73,6 +96,7 @@ final class VoiceRecordingRecoveryStore { } func saveReview(id: UUID, transcript: String, engine: String) throws { + try requireActive() let manifest = directory.appendingPathComponent(id.uuidString).appendingPathComponent("manifest.json") var record = try JSONDecoder().decode(Recording.self, from: Data(contentsOf: manifest)) guard record.id == id else { throw RecoveryError.invalidRecord } @@ -87,6 +111,7 @@ final class VoiceRecordingRecoveryStore { /// A failed checkpoint must prevent the request: otherwise relaunch could manufacture a /// new key for a create whose outcome is unknown. The encoded attempt includes its payload. func saveCreateAttempt(id: UUID, attempt: CreateAttempt, transcript: String, engine: String) throws { + try requireActive() let manifest = directory.appendingPathComponent(id.uuidString).appendingPathComponent("manifest.json") var record = try JSONDecoder().decode(Recording.self, from: Data(contentsOf: manifest)) guard record.id == id else { throw RecoveryError.invalidRecord } @@ -101,6 +126,7 @@ final class VoiceRecordingRecoveryStore { func saveSubmission(id: UUID, submission: NoteSubmission, noteID: Int?, savedText: String?, review: String, engine: String) throws { + try requireActive() let manifest = directory.appendingPathComponent(id.uuidString).appendingPathComponent("manifest.json") var record = try JSONDecoder().decode(Recording.self, from: Data(contentsOf: manifest)) guard record.id == id else { throw RecoveryError.invalidRecord } @@ -118,6 +144,7 @@ final class VoiceRecordingRecoveryStore { /// A damaged manifest must not hide intact siblings. Keep every unreadable file and make /// the warning explicit so recovery UI can report incomplete discovery. func load() throws -> (recordings: [Recording], unreadable: Bool) { + guard active else { return ([], false) } guard files.fileExists(atPath: directory.path) else { return ([], false) } let folders = try files.contentsOfDirectory(at: directory, includingPropertiesForKeys: nil) .sorted(by: { $0.lastPathComponent < $1.lastPathComponent }) @@ -145,6 +172,7 @@ final class VoiceRecordingRecoveryStore { /// Listing entries are display snapshots. Restoration rereads the current manifest before /// claiming ownership so a stale picker cannot erase a newer submission or note identity. func recording(id: UUID) throws -> Recording { + try requireActive() let manifest = directory.appendingPathComponent(id.uuidString).appendingPathComponent("manifest.json") let record = try JSONDecoder().decode(Recording.self, from: Data(contentsOf: manifest)) guard record.id == id else { throw RecoveryError.invalidRecord } @@ -153,6 +181,7 @@ final class VoiceRecordingRecoveryStore { } func audioURL(for record: Recording) throws -> URL { + try requireActive() guard record.version == 1, ["recording.m4a", "recording.wav", "recording.caf"].contains(record.filename) else { throw RecoveryError.invalidRecord } let url = directory.appendingPathComponent(record.id.uuidString).appendingPathComponent(record.filename) @@ -165,6 +194,7 @@ final class VoiceRecordingRecoveryStore { /// Returns whether cleanup finished; false still means the capture is durably terminal. @discardableResult func discard(_ id: UUID) throws -> Bool { + try requireActive() let folder = directory.appendingPathComponent(id.uuidString, isDirectory: true) let retired = directory.appendingPathComponent(".discarded-" + id.uuidString, isDirectory: true) if files.fileExists(atPath: folder.path) { try files.moveItem(at: folder, to: retired) } diff --git a/ios/CommandTests/VoiceRecordingRecoveryStoreTests.swift b/ios/CommandTests/VoiceRecordingRecoveryStoreTests.swift index 6d92268..d1100d7 100644 --- a/ios/CommandTests/VoiceRecordingRecoveryStoreTests.swift +++ b/ios/CommandTests/VoiceRecordingRecoveryStoreTests.swift @@ -327,6 +327,63 @@ final class VoiceRecordingRecoveryStoreTests: XCTestCase { XCTAssertEqual(try owner.recording(id: flow.captureID).transcript, "still writable") XCTAssertTrue(flow.suspendKeepingRecovery()) } + func testDeactivatedAccountKeepsFilesButFencesOldCallbacks() async throws { + let owner = store(), flow = VoiceCaptureFlow(recovery: owner) + flow.adopt(try source()); flow.transcript = "account one review" + let id = flow.captureID + let result = await flow.transcribe(immediateUse: true) { _ in + try owner.deactivate(deleteRecordings: false) + return ("late result", "sfspeech") + } + XCTAssertNil(result) + flow.transcript = "stale edits"; flow.cancel() + XCTAssertThrowsError(try owner.keep(source(), id: UUID())) + XCTAssertThrowsError(try owner.saveReview(id: id, transcript: "stale direct write", engine: "sfspeech")) + XCTAssertTrue(try owner.load().recordings.isEmpty) + let fresh = store() + XCTAssertEqual(try fresh.recording(id: id).transcript, "account one review") + XCTAssertTrue(try store(id: 2).load().recordings.isEmpty) + } + func testDeletedScopeCannotBeRecreatedByOldFlow() throws { + let owner = store(), flow = VoiceCaptureFlow(recovery: owner) + flow.adopt(try source()); flow.transcript = "delete with account" + let id = flow.captureID + try owner.deactivate(deleteRecordings: true) + XCTAssertFalse(FileManager.default.fileExists(atPath: owner.directory.path)) + flow.transcript = "late edit"; flow.cancel() + XCTAssertThrowsError(try owner.keep(source(), id: UUID())) + owner.claim(id, owner: UUID()) + XCTAssertTrue(try store().load().recordings.isEmpty) + XCTAssertFalse(FileManager.default.fileExists(atPath: owner.directory.path)) + } + func testFailedAccountDeletionStillFencesOldWritesAndCanRetryCleanup() throws { + var blockDeletion = true + let owner = VoiceRecordingRecoveryStore(root: root.appendingPathComponent("recovery"), + server: URL(string: "https://example.com")!, accountID: 1, username: "tester", + accountCreatedAt: "first", removeItem: { url in + if blockDeletion { throw URLError(.cannotRemoveFile) } + try FileManager.default.removeItem(at: url) + }) + let flow = VoiceCaptureFlow(recovery: owner) + flow.adopt(try source()); flow.transcript = "old account" + XCTAssertThrowsError(try owner.deactivate(deleteRecordings: true)) + flow.transcript = "late edit" + XCTAssertFalse(owner.isOwner(flow.captureID, owner: UUID())) + XCTAssertThrowsError(try owner.saveReview(id: flow.captureID, transcript: "late direct write", engine: "sfspeech")) + blockDeletion = false + XCTAssertNoThrow(try owner.deactivate(deleteRecordings: true)) + XCTAssertFalse(FileManager.default.fileExists(atPath: owner.directory.path)) + } + func testRetiringSupersededStoreDoesNotRevokeFreshOwner() throws { + let old = store(), original = VoiceCaptureFlow(recovery: old) + original.adopt(try source()); original.transcript = "original" + let current = store() + let flow = VoiceCaptureFlow(recovery: current, restoring: try XCTUnwrap(current.load().recordings.first)) + try old.deactivate(deleteRecordings: false) + flow.transcript = "current owner edit" + XCTAssertEqual(try current.recording(id: flow.captureID).transcript, "current owner edit") + XCTAssertTrue(flow.suspendKeepingRecovery()) + } func testManifestCannotReferenceAnOutsideFile() throws { let owner = store() XCTAssertThrowsError(try owner.audioURL(for: .init(version: 1, id: UUID(), filename: "../../outside.m4a"))) diff --git a/state/ASTRA-1002.md b/state/ASTRA-1002.md index 3d6881c..8c655f7 100644 --- a/state/ASTRA-1002.md +++ b/state/ASTRA-1002.md @@ -387,3 +387,18 @@ process remains. Changes are on the same review branch/PR; no merge or deploymen retain the flow on checkpoint failure; RecordingSheet has not been changed or activated. - Next: integrated builds/process regression checks, consume independent review, then shared account/microphone coordinator with explicit restore selection and real app verification. + +## Reset-window account retirement — 13:39 EDT +- Added tests before the new account-retirement API, then implemented permanent store deactivation. + Logout retains files while hiding discovery and rejecting old writes/claims; account deletion + removes that directory, surfaces removal failure, and permits explicit cleanup retry. Only tokens + issued by this store are released, preserving a newer store's already-restored owner. +- OBSERVED **50 native XCTest cases passed** (`voice-account-green.log`). Initial test compilation + failed on the absent API (`voice-account-red.log`). Covers late transcription/edit callbacks, + deletion without resurrection, failed deletion with writes still fenced, and newer-owner survival. +- OBSERVED prior suspension commit also passed **8 process cases**, **1 real wire/SQLite case**, and + both iOS/Catalyst builds (`voice-suspend-{process,wire,ios-build,catalyst-build}.log`). Independent + read-only review found no concrete issues in terminal cleanup, wire discrimination or suspension. +- App lifecycle callers have not been wired yet. Next: a shared note-capture coordinator must own + recorder finalization BEFORE store retirement; account deactivation alone cannot retain a live + recorder's temporary file. Continue with coordinator tests and explicit restore selection. From 01dbba67dca7f02d4c9925691c9594f0e128fa5c Mon Sep 17 00:00:00 2001 From: legitimate-apps <309192374+legitimate-apps@users.noreply.github.com> Date: Fri, 2 Oct 2026 13:40:12 -0400 Subject: [PATCH 27/27] Record credit-limit stop and final voice recovery handoff --- state/ASTRA-1002.md | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/state/ASTRA-1002.md b/state/ASTRA-1002.md index 8c655f7..4ed7ffe 100644 --- a/state/ASTRA-1002.md +++ b/state/ASTRA-1002.md @@ -1,3 +1,8 @@ +> **STOPPED at operator credit-limit instruction, 2026-10-02.** Latest production commit: +> `62885ec`, pushed to `astra/capture-reliability-1002`; PR #1 remains open. No merge/deploy. +> Voice recovery primitives are implemented and verified incrementally, but RecordingSheet +> remains nonpersistent: app-level voice recovery is NOT finished. Final handoff is at the end. + # Command reliability push — 2026-10-02 **FINAL — selected work finished, verified, committed and pushed; PR #1 open.** @@ -402,3 +407,32 @@ process remains. Changes are on the same review branch/PR; no merge or deploymen - App lifecycle callers have not been wired yet. Next: a shared note-capture coordinator must own recorder finalization BEFORE store retirement; account deactivation alone cannot retain a live recorder's temporary file. Continue with coordinator tests and explicit restore selection. + +## FINAL — operator credit-limit stop + +- Stopped immediately after the explicit instruction; started no further implementation or tests. +- All sound code is committed and pushed through **62885ec**. Worktree was clean before this final + state update. PR: https://github.com/legitimate-apps/command/pull/1 (open, no merge/deployment). +- Latest verification: **50 native voice XCTest cases passed** on 62885ec. **8 process-kill cases, + 1 actual REST/SQLite reconciliation case, and iOS + Catalyst builds passed** on a5265d7, before + the final account-retirement change. That final change has native coverage; broader recheck + remains for the next authorized session. Initial typed/MCP integration evidence remains above. +- Finished voice guarantees: account-scoped protected stopped audio; atomic review and original + request checkpoints; current-manifest restoration; stale-owner fencing; original POST replay + plus note-ID/PATCH reconciliation; terminal rename before cleanup; explicit retained suspension; + store retirement with stale-write fencing and explicit account-audio deletion/retry. +- **Unfinished:** no shared recorder/account coordinator or recovery picker/sheet wiring. The app + still uses the nonpersistent default. Active M4A process-death decoding, acknowledged assistant + handoff, rendered recovery UI, and full account/multiwindow app verification remain incomplete. + There are no half-written coordinator/UI files to recover. +- **Exact next step:** read the voice design and current source/tests, acquire a fresh DerivedData + lease, then test-first implement the shared NOTE capture coordinator. It must own recorder + finalization before account retirement, retain on sheet disappearance, preserve same-account + multiwindow ownership, and offer explicit restore selection. Wire the durable note operations + to the capture's original client/session only after those lifecycle tests pass. Keep assistant + handoff outside this activation until its durable acknowledgment contract is implemented. +- Cleanup OBSERVED: active helper finish_voice interrupted; finish_mcp already completed. Last + build session completed. DerivedData lease command-astra-1002-tests released. No owned probe, + local server, simulator, emulator or browser remains running/leased. Earlier simulator lease + was released before the reset-window work; no simulator was booted in this follow-on. +- The pending read-only helper design review was stopped; no result was integrated or relied on.