HealthProbe / AGENTS.md
Newer Older
236 lines | 8.694kb
Bogdan Timofte authored a month ago
1
# HealthProbe – Multi-Model Development Guide
2

            
3
## Overview
4

            
5
HealthProbe is built by multiple AI models, each owning a distinct domain.
6
This document defines boundaries, interfaces, and handoff contracts.
7

            
8
---
9

            
10
## Model Allocation
11

            
12
| Domain | Owner | Tools |
13
|--------|-------|-------|
14
| **UI / SwiftUI Views** | Claude Code | Xcode, SwiftUI, CLAUDE.md |
15
| **Data Models (SwiftData)** | Dedicated model session | Xcode, Swift |
16
| **HealthKit Integration** | Dedicated model session | Xcode, HealthKit docs |
17
| **Anomaly Detection Algorithms** | Dedicated model session | Swift, statistical references |
18
| **Sync Monitoring** | Dedicated model session | Xcode, CloudKit docs |
19
| **Documentation** | Claude Code + dedicated session | Markdown |
20
| **Tests** | Dedicated model session | XCTest, Swift Testing |
21

            
22
---
23

            
24
## Directory Ownership
25

            
26
```
27
HealthProbe/
28
├── Views/           ← Claude Code (UI)
29
├── ViewModels/      ← Claude Code (UI)
30
├── Utilities/       ← Claude Code (shared helpers, mocks)
31
├── Models/          ← Models agent (SwiftData schemas)
32
├── Services/        ← Services agent (HealthKit, anomaly, sync)
33
└── Tests/           ← Tests agent
34
```
35

            
36
**Rule:** Each agent writes only within its owned directories.
37
Cross-boundary changes require an explicit interface contract (protocol) first.
38

            
39
---
40

            
41
## Interface Contracts
42

            
43
All service boundaries are defined as Swift protocols.
44
Claude Code (UI) consumes protocols — never concrete implementations.
45

            
46
### HealthMonitorProtocol
47

            
48
```swift
49
/// Owned by: Services agent
50
/// Consumed by: UI (DashboardViewModel)
51
protocol HealthMonitorProtocol {
52
    var currentStatus: HealthStatus { get }
53
    var lastChecked: Date? { get }
54
    func runCheck() async throws
55
}
56
```
57

            
58
### AnomalyStoreProtocol
59

            
60
```swift
61
/// Owned by: Services agent
62
/// Consumed by: UI (AnomalyListViewModel)
63
protocol AnomalyStoreProtocol {
64
    var anomalies: [DetectedAnomaly] { get }
65
    func markResolved(_ anomaly: DetectedAnomaly) async throws
66
}
67
```
68

            
69
### AuditTrailProtocol
70

            
71
```swift
72
/// Owned by: Services agent
73
/// Consumed by: UI (AuditTrailView)
74
protocol AuditTrailProtocol {
75
    var entries: [AuditTrailEntry] { get }
76
    func export() async throws -> Data  // JSON
77
}
78
```
79

            
80
### SyncMonitorProtocol
81

            
82
```swift
83
/// Owned by: Services agent
84
/// Consumed by: UI (SyncViewModel)
85
protocol SyncMonitorProtocol {
86
    var iCloudEnabled: Bool { get }
87
    var lastSyncDate: Date? { get }
88
    var stateChanges: [SyncStateChange] { get }
89
}
90
```
91

            
92
---
93

            
94
## Shared Types (Models Agent)
95

            
96
These types are defined once in `Models/` and shared across all agents:
97

            
98
```swift
99
// Models/TypeDistributionBin.swift
100
@Model
101
final class TypeDistributionBin {
102
    var bucketStart: Date
103
    var bucketEnd: Date
104
    var count: Int
105
}
106

            
107
// Models/TypeCount.swift
Bogdan Timofte authored 3 weeks ago
108
// TypeCount owns zero or more TypeDistributionBin records.
109
// These bins store sample counts and import anchors, not raw health values.
110

            
111
// Interface updated 2026-05-12 — see AGENTS.md
112
// Models/HealthRecord.swift
113
// HealthRecord stores one anonymized HealthKit record fingerprint plus its start/end dates.
114
// It intentionally does not store raw health values, device identifiers, or source metadata.
115
// UI may compare HealthRecord fingerprints between adjacent snapshots to expose losses
116
// that are masked by newly-added records with the same total count.
117
// High-volume snapshots store these records in TypeCount.recordArchiveData instead of
118
// creating one SwiftData model per record, avoiding main-thread stalls after import.
119

            
120
// Interface updated 2026-05-13 — see AGENTS.md
121
// TypeDistributionBin also stores content hashes and HealthKit query anchors.
122
// Import uses a global anchored query per data type so follow-up snapshots fetch only
123
// HealthKit deltas instead of scanning calendar blocks with fixed per-query latency.
Bogdan Timofte authored a month ago
124

            
Bogdan Timofte authored 3 weeks ago
125
// Interface updated 2026-05-14 — see AGENTS.md
126
// TypeCount.recordArchiveData is stored with SwiftData external storage.
127
// The archive remains a complete per-record forensic snapshot, but large blobs should
128
// not be kept inline with the TypeCount row because high-volume HealthKit stores can
129
// exceed device memory during import or detail inspection.
130
// Initial high-volume imports stream records directly into a compact binary archive
131
// instead of building a full in-memory dictionary/array; plist archives remain readable
132
// for backwards compatibility.
133

            
Bogdan Timofte authored 3 weeks ago
134
// Interface updated 2026-05-17 — see AGENTS.md
135
// Models/TypeCount.detailCacheData stores precomputed detail data for the current
136
// TypeCount compared with the immediately previous snapshot on the same device.
137
// The cache contains aggregate added/disappeared counts, capped preview records for
138
// UI drill-down, and daily change bins for temporal charts. It must be computed when
139
// snapshots are saved and refreshed for neighboring snapshots when snapshot deletion
140
// changes chain links. Existing stores are backfilled incrementally with a strict
141
// per-launch TypeCount cap to avoid decoding many large archives in one run.
142

            
Bogdan Timofte authored a month ago
143
// Models/DetectedAnomaly.swift
144
enum AnomalyType: String, Codable {
145
    case historicalInsertion = "historical_insertion"
146
    case silentDeletion      = "silent_deletion"
147
    case duplicate           = "duplicate"
148
    case divergence          = "divergence"
149
}
150

            
151
enum Severity: String, Codable, Comparable {
152
    case info, warning, critical
153
}
154

            
155
enum HealthStatus: String {
156
    case healthy, warning, critical, unknown
157
}
158
```
159

            
160
Any model changes must be announced in this file before other agents consume them.
161

            
162
---
163

            
164
## Handoff Process
165

            
166
When a module is ready to be consumed by another agent:
167

            
168
1. **Define the protocol** in `Services/Protocols/` (services agent)
169
2. **Implement a mock** in `Utilities/Mocks.swift` (Claude Code)
170
3. **Build UI against the mock** (Claude Code)
171
4. **Replace mock with real implementation** (services agent)
172
5. **Integration test** (tests agent)
173

            
174
This allows UI development and service development to proceed in parallel.
175

            
176
---
177

            
178
## Algorithms & Detection Logic
179

            
180
The following modules involve non-trivial logic and should be reviewed carefully:
181

            
182
| Module | File | Description |
183
|--------|------|-------------|
184
| **Anomaly Detector** | `Services/AnomalyDetector.swift` | Statistical detection: insertions, deletions, duplicates, divergence |
185
| **Divergence Engine** | `Services/DivergenceEngine.swift` | Time-series trend analysis, σ comparison |
186
| **Fingerprinter** | `Services/SampleFingerprinter.swift` | Duplicate detection via sample hashing |
187
| **Snapshot Comparator** | `Services/SnapshotComparator.swift` | Diff between two HealthKit snapshots |
188
| **Distribution Comparator** | `Services/SnapshotDiffService.swift` | Daily per-type distribution diff to reveal old-data disappearance masked by new data |
189

            
190
**Guidelines for algorithm modules:**
191
- Document assumptions explicitly (e.g., "assumes continuous monitoring since install")
192
- All thresholds (e.g., `age > 7 days`) must be configurable constants, not magic numbers
193
- Include unit tests for edge cases (empty snapshots, partial data, clock skew)
194
- No UI code; return plain Swift types only
195

            
196
---
197

            
198
## Privacy Directives — All Agents
199

            
200
**Mandatory across all modules:**
201
- No credentials, API keys, tokens, or certificates in any file
202
- No personal data: names, emails, phone numbers, dates of birth
203
- No device identifiers: UDID, serial number, advertising ID, device name
204
- No account identifiers: Apple ID, iCloud account info, CloudKit record IDs
205
- No raw health values in code, tests, previews, logs, or comments
206
- No location data or patterns enabling re-identification
207
- Synthetic data only in tests and previews
208

            
209
---
210

            
211
## Communication Between Agents
212

            
213
When one agent needs to communicate a decision or change to another:
214

            
215
1. **Update this file** (`AGENTS.md`) with the protocol/interface change
216
2. **Update the relevant protocol** in `Services/Protocols/`
217
3. **Add a comment** in the affected file: `// Interface updated YYYY-MM-DD — see AGENTS.md`
218

            
219
---
220

            
221
## Current Status
222

            
223
| Module | Status | Owner |
224
|--------|--------|-------|
225
| SwiftData Models | ✅ Done | Models agent |
226
| HealthKit Integration | ✅ Done | Services agent |
227
| Snapshot Diff Service | ✅ Done | Services agent |
228
| Service Protocols | ⏳ Not started | Services agent |
229
| Anomaly Detection | ⏳ Not started | Services agent |
230
| Sync Monitor | ⏳ Not started | Services agent |
231
| UI – App entry + TabView | ✅ Done | Claude Code |
232
| UI – Dashboard | ✅ Done (functional, minimal) | Claude Code |
233
| UI – Snapshots + Detail | ✅ Done | Claude Code |
234
| UI – Data Types | ✅ Done | Claude Code |
235
| UI – Settings | ✅ Done | Claude Code |
236
| Unit Tests | ⏳ Not started | Tests agent |