Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
db09b94
Record capture reliability work and verification plan
legitimate-apps Oct 2, 2026
f5a12fc
Preserve unsent notes across relaunch and isolate account sessions
legitimate-apps Oct 2, 2026
977c54e
Protect voice captures from stale asynchronous completions
legitimate-apps Oct 2, 2026
0d083a5
Record passing iOS recovery and voice verification
legitimate-apps Oct 2, 2026
ededd4b
Keep completion facts from hidden assignments private
legitimate-apps Oct 2, 2026
dc72efe
Complete individual recurring occurrences through assistant tools
legitimate-apps Oct 2, 2026
62e5405
Record verified workflow integration and Catalyst build
legitimate-apps Oct 2, 2026
124198d
Keep active note editors when another window resumes the same account
legitimate-apps Oct 2, 2026
69d13d8
Record observed relaunch recovery through UI HTTP and SQLite
legitimate-apps Oct 2, 2026
64a24af
Document capture recovery contract and preserve verification evidence
legitimate-apps Oct 2, 2026
672bbf8
Finalize reliability run handoff and resource cleanup
legitimate-apps Oct 2, 2026
5dc9105
Reproduce voice recovery gaps across hard process termination
legitimate-apps Oct 2, 2026
9d4d2c6
Define durable voice ownership and document process-death baseline
legitimate-apps Oct 2, 2026
ade857e
Persist adopted voice audio with account-scoped restoration
legitimate-apps Oct 2, 2026
282973f
Checkpoint and restore edited voice review state
legitimate-apps Oct 2, 2026
30cebbf
Persist voice retry identity before submitting an unchanged capture
legitimate-apps Oct 2, 2026
b669634
Keep voice submission checkpoints coherent after disk failures
legitimate-apps Oct 2, 2026
a05c73c
Recover intact voice recordings alongside damaged manifests
legitimate-apps Oct 2, 2026
e79fe90
Fence restored voice captures against superseded flow writes
legitimate-apps Oct 2, 2026
8ac488e
Reconcile recovered voice edits through the original note identity
legitimate-apps Oct 2, 2026
2b85907
Verify voice reconciliation across process death and prevent bypass
legitimate-apps Oct 2, 2026
32f7e8b
Restore current voice manifests and reject invalid first submissions
legitimate-apps Oct 2, 2026
13c2479
Checkpoint terminal voice cleanup before unlinking private audio
legitimate-apps Oct 2, 2026
fa210c3
Verify voice crash recovery against REST and SQLite
legitimate-apps Oct 2, 2026
a5265d7
Retain voice recovery when suspending presentation ownership
legitimate-apps Oct 2, 2026
62885ec
Fence retired voice recovery stores and delete account audio explicitly
legitimate-apps Oct 2, 2026
01dbba6
Record credit-limit stop and final voice recovery handoff
legitimate-apps Oct 2, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
135 changes: 135 additions & 0 deletions docs/decisions/2026-10-02-voice-recovery.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
# Voice capture ownership and process-death recovery

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.

## 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 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
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 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.
13 changes: 13 additions & 0 deletions docs/mcp/MCP-GUIDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
21 changes: 21 additions & 0 deletions docs/specs/2026-06-16-command-design.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
33 changes: 27 additions & 6 deletions ios/Command/App/AppState.swift
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,9 @@ 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
private var notesRecoveryScope: URL?
/// Shared delegatee roster (People list + assignee pickers).
let people = PeopleStore()
/// Shared goals + assignments.
Expand Down Expand Up @@ -183,7 +185,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
Expand All @@ -205,8 +208,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()
}
}
}

Expand Down Expand Up @@ -580,7 +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.
/// 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()
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
Expand Down Expand Up @@ -750,6 +769,7 @@ final class AppState {
/// no longer exists.
func forgetDeletedAccount() async {
lock.reset()
notes.deactivate(deleteRecovery: true)
tearDownSession()
lastError = nil
}
Expand Down Expand Up @@ -784,8 +804,9 @@ 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()
notesRecoveryScope = nil
people.delegatees = []
tasks.assignments = []
tasks.goals = []
Expand Down
25 changes: 14 additions & 11 deletions ios/Command/Features/Calendar/CalendarView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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
}
Expand Down Expand Up @@ -729,21 +730,23 @@ 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)
case .schedule:
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.
Expand Down
Loading
Loading