# 🔧 UNIFIED DIRECTIVE: Alarm / Schedule / Notification Documentation & Implementation Stack

**Author:** Matthew Raymer  
**Status:** Active – Master Coordination Directive  
**Scope:** Android & iOS, Capacitor plugin, alarms/schedules/notifications  
**Version:** 1.1.0  
**Last Updated:** November 2025  
**Last Synced With Plugin Version:** v1.1.0

---

## 0. Purpose

Unify all existing alarm/notification documents into a **coherent, layered system** that:

1. **Eliminates duplication** (especially Android alarm behavior repeated across docs)
2. **Separates concerns** into:
   * Platform facts
   * Exploration/testing
   * Plugin requirements
   * Implementation directives (Phases 1–3)
3. **Provides iOS parity** to the existing Android-heavy material
4. **Maps OS-level capabilities → plugin guarantees → JS/TS API contract**
5. **Standardizes testing** into executable matrices for exploration and regression
6. **Connects exploration → design → implementation** and tracks status across that pipeline

**This directive is the top of the stack.** If any lower-level document conflicts with this one, **this directive wins** unless explicitly noted.

**Mission Statement**: This directive ensures that every alarm outcome on every platform is predictable, testable, and recoverable, with no undocumented behavior.

**⚠️ ENFORCEMENT RULE**: No new alarm-related documentation may be created outside Documents A, B, C, or P1–P3. All future changes must modify these documents, not create additional standalone files.

---

## 1. Inputs (Existing Documents)

### 1.1 Platform & Reference Layer

* `platform-capability-reference.md` – OS-level facts (Android & iOS)
* `android-alarm-persistence-directive.md` – Android abilities & limitations, engineering-grade

### 1.2 Exploration & Findings

* `plugin-behavior-exploration-template.md` – Structured template for exploring behavior
* `explore-alarm-behavior-directive.md` – Exploration directive for behavior & persistence
* `exploration-findings-initial.md` – Initial code-level discovery

### 1.3 Requirements & Implementation

* `plugin-requirements-implementation.md` – Plugin behavior rules & guarantees
* `android-implementation-directive.md` – Umbrella Android implementation overview (app launch recovery, missed alarms, force stop, boot)
* Phase directives (normative):
  * `../android-implementation-directive-phase1.md` – Cold start recovery (minimal viable)
  * `../android-implementation-directive-phase2.md` – Force stop detection & recovery
  * `../android-implementation-directive-phase3.md` – Boot receiver missed alarm handling

### 1.4 Improvement Directive

* `improve-alarm-directives.md` – Current plan for structural and content improvements across the stack

---

## 2. Target Structure (What We're Building)

We standardize around **three primary doc roles**, plus implementation phases:

### A. **Platform Reference (Document A)**

**Goal:** Single, stable, normative OS facts.

* Merge:
  * Android section from `android-alarm-persistence-directive.md`
  * Android & iOS matrices from `platform-capability-reference.md`
* Content rules:
  * NO plugin-specific rules
  * Just: "what Android/iOS can and cannot do"
  * Use matrices & short prose only
* Label each item as:
  * **OS-guaranteed**, **Plugin-required**, or **Forbidden** (where relevant)
* Output path (recommended):
  `docs/alarms/01-platform-capability-reference.md`

### B. **Plugin Behavior Exploration (Document B)**

**Goal:** Executable exploration & testing spec.

* Baseline: `plugin-behavior-exploration-template.md` + `explore-alarm-behavior-directive.md`
* Remove duplicated platform explanations (refer to Document A instead)
* For each scenario (swipe, reboot, force stop, etc.):
  * Link to source files & functions (line or section refs)
  * Provide **Expected (OS)** & **Expected (Plugin)** from Docs A + C
  * Add columns for **Actual Result** and **Notes** (checkbox matrix)
* Output path:
  `docs/alarms/02-plugin-behavior-exploration.md`

### C. **Plugin Requirements & Implementation Rules (Document C)**

**Goal:** What the plugin MUST guarantee & how.

* Baseline: `plugin-requirements-implementation.md` + `improve-alarm-directives.md`
* Must include:
  1. **Plugin Behavior Guarantees & Limitations** by platform (table)
  2. **Persistence Requirements** (fields, storage, validation, failure modes)
  3. **Recovery Requirements**:
     * Boot (Android)
     * Cold start
     * Warm start
     * Force stop (Android)
     * User-tap recovery
  4. **Missed alarm handling contract** (definition, triggers, required actions)
  5. **JS/TS API Contract**:
     * What JS devs can rely on
     * Platform caveats (e.g., Force Stop, iOS background limits)
  6. **Unsupported features / limitations** clearly called out
* Output path:
  `docs/alarms/03-plugin-requirements.md`

### D. **Implementation Directives (Phase 1–3)**

Already exist; this directive standardizes their role:

* **Phase docs are normative for code.**
  If they conflict with Document C, update the phase docs and then C.

**⚠️ STRUCTURE FREEZE**: The structure defined in this directive is FINAL. No new document categories may be introduced without updating this master directive first.

---

## 3. Ownership, Versioning & Status

### 3.1 Ownership

**Assignable Ownership** (replace abstract roles with concrete owners):

| Layer                  | Owner               | Responsibility                                    |
| ---------------------- | ------------------- | ------------------------------------------------- |
| Doc A – Platform Facts | Engineering Lead    | Long-lived reference, rare changes                |
| Doc B – Exploration    | QA / Testing Lead   | Living document, updated with test results        |
| Doc C – Requirements   | Plugin Architect    | Versioned with plugin, defines guarantees        |
| Phases P1–P3           | Implementation Lead | Normative code specs, tied to Doc C requirements |

**Note**: If owners are not yet assigned, use role names above as placeholders until assignment.

### 3.2 Versioning Rules

* Any change that alters **JS/TS-visible behavior** → bump plugin **MINOR** at least
* Any change that breaks prior guarantees or adds new required migration → **MAJOR bump**
* Each doc should include:
  * `Version: x.y.z`
  * `Last Synced With Plugin Version: vX.Y.Z`

### 3.3 Status Matrix

**Status matrix is maintained in Section 11** (see below). This section is kept for historical reference only.

---

## 4. Work Plan – "Do All of the Above"

This is the **concrete to-do list** that satisfies:

* Consolidation
* Versioning & ownership
* Status tracking
* Single-source master structure
* Next-phase readiness
* Improvements from `improve-alarm-directives.md`

### Step 1 – Normalize Platform Reference (Doc A)

1. Start from `platform-capability-reference.md` + `android-alarm-persistence-directive.md`
2. Merge into a single doc:
   * Android matrix
   * iOS matrix
   * Core principles (no plugin rules)
3. Ensure each line is labeled:
   * **OS-guaranteed**, **Plugin-required**, or **Forbidden** (where relevant)
4. Mark the old Android alarm persistence doc as:
   * **Deprecated in favor of Doc A** (leave file but add a banner)

### Step 2 – Rewrite Exploration (Doc B)

1. Use `plugin-behavior-exploration-template.md` as the skeleton
2. Integrate concrete scenario descriptions and code paths from `explore-alarm-behavior-directive.md`
3. For **each scenario**:
   * App swipe, OS kill, reboot, force stop, cold start, warm start, notification tap:
   * Add row: Step-by-step actions + Expected (OS) + Expected (Plugin) + Actual + Notes
4. Remove any explanation that duplicates Doc A; replace with "See Doc A, section X"

### Step 3 – Rewrite Plugin Requirements (Doc C)

1. Start from `plugin-requirements-implementation.md` & improvement goals
2. Add / enforce sections:
   * **Plugin Behavior Guarantees & Limitations**
   * **Persistence Spec** (fields, mandatory vs optional)
   * **Recovery Points** (boot, cold, warm, force stop, user tap)
   * **Missed Alarm Contract**
   * **JS/TS API Contract**
   * **Unsupported / impossible guarantees** (Force Stop, iOS background, etc.)
3. Everywhere it relies on platform behavior:
   * Link back to Doc A using short cross-reference ("See A §2.1")
4. Add a **"Traceability"** mini-table:
   * Row per behavior → Platform fact in A → Tested scenario in B → Implemented in Phase N

### Step 4 – Align Implementation Directives with Doc C

1. Treat Phase docs as **canonical code spec**: P1, P2, P3
2. For each behavior required in Doc C:
   * Identify which Phase implements it (or will implement it)
3. Update:
   * `android-implementation-directive.md` to be explicitly **descriptive/integrative**, not normative, pointing to Phases 1–3 & Doc C
   * Ensure scenario model, alarm existence checks, and boot handling match the **corrected model** already defined in Phase 2 & 3
4. Add acceptance criteria per phase that directly reference:
   * Requirements in Doc C
   * Platform constraints in Doc A
5. **Phase 1–3 must REMOVE**:
   * Any scenario logic (moved to Doc C)
   * Any platform behavioral claims (moved to Doc A)
   * Any recovery responsibilities not assigned to that phase

### Step 5 – Versioning & Status

1. At the top of Docs A, B, C, and each Phase doc, add:
   * `Version`, `Last Updated`, `Sync'd with Plugin vX.Y.Z`
2. Maintain the status matrix (Section 11) as the **single source of truth** for doc maturity
3. When a Phase is fully implemented and deployed:
   * Mark "In Use?" = ✅
   * Add link to code tags/commit hash

### Step 6 – Readiness Check for Next Work Phase

Before starting any *new* implementation work on alarms / schedules:

1. **Confirm:**
   * Doc A exists and is stable enough (no "TODO" in core matrices)
   * Doc B has at least the base scenarios scaffolded
   * Doc C clearly defines:
     * What we guarantee on each platform
     * What we cannot do (e.g., Force Stop auto-resume)
2. Only then:
   * Modify or extend Phase 1–3
   * Or add new phases (e.g., warm-start optimizations, iOS parity work)

---

## 5. Acceptance Criteria for THIS Directive (Revised and Final)

This directive is complete **ONLY** when:

1. **Doc A exists, is referenced, and no other doc contains platform facts**
   * File exists: `docs/alarms/01-platform-capability-reference.md`
   * All old platform docs marked as deprecated with banner
   * No platform facts duplicated in other docs

2. **Doc B contains**:
   * At least 6 scenarios (swipe, reboot, force stop, cold start, warm start, notification tap)
   * Expected OS vs Plugin behavior columns
   * Space for Actual Result and Notes
   * Links to source files/functions

3. **Doc C contains**:
   * Guarantees by platform (table format)
   * Recovery matrix (boot, cold, warm, force stop, user tap)
   * JS/TS API contract
   * Unsupported behaviors clearly called out

4. **Phase docs**:
   * Contain NO duplication of Doc A (platform facts)
   * Reference Doc C explicitly (requirements)
   * Have acceptance criteria tied to Doc C requirements

5. **Deprecated files have**:
   * Banner: "⚠️ **DEPRECATED**: Superseded by [000-UNIFIED-ALARM-DIRECTIVE](./000-UNIFIED-ALARM-DIRECTIVE.md)"
   * Link to replacement document

6. **Status matrix fields are no longer empty** (Section 11)
   * All docs marked as Drafted at minimum

---

## 6. Document Relationships & Cross-References

### 6.1 Reference Flow

```
Unified Directive (this doc)
    ↓
    ├─→ Doc A (Platform Reference)
    │   └─→ Referenced by: B, C, P1-P3
    │
    ├─→ Doc B (Exploration)
    │   └─→ References: A (platform facts), C (expected behavior)
    │   └─→ Feeds into: P1-P3 (test results inform implementation)
    │
    ├─→ Doc C (Requirements)
    │   └─→ References: A (platform constraints)
    │   └─→ Referenced by: P1-P3 (implementation must satisfy)
    │
    └─→ P1-P3 (Implementation)
        └─→ References: A (platform facts), C (requirements)
        └─→ Validated by: B (exploration results)
```

### 6.2 Cross-Reference Format

When referencing between documents, use this format:

* **Doc A**: `[Platform Reference §2.1](../alarms/01-platform-capability-reference.md#21-android-alarm-persistence)`
* **Doc B**: `[Exploration §3.2](../alarms/02-plugin-behavior-exploration.md#32-cold-start-scenario)`
* **Doc C**: `[Requirements §4.3](../alarms/03-plugin-requirements.md#43-recovery-requirements)`
* **Phase docs**: `[Phase 1 §2.3](../android-implementation-directive-phase1.md#23-cold-start-recovery)`

---

## 7. Canonical Source of Truth Rules

### 7.1 Platform Facts

**Only Doc A** contains platform facts. All other docs reference Doc A, never duplicate platform behavior.

**Reference Format**: `[Doc A §X.Y]` - See [Platform Capability Reference](./01-platform-capability-reference.md)

### 7.2 Requirements

**Only Doc C** defines plugin requirements. Phase docs implement Doc C requirements.

**Reference Format**: `[Doc C §X.Y]` - See [Plugin Requirements](./03-plugin-requirements.md)

### 7.3 Implementation Details

**Only Phase docs (P1-P3)** contain implementation details. Unified Directive does not specify code structure or algorithms.

**Reference Format**: `[Phase N §X.Y]` - See Phase implementation directives

### 7.4 Test Results

**Only Doc B** contains actual test results and observed behavior. Doc B references Doc A for expected OS behavior and Doc C for expected plugin behavior.

---

## 8. Conflict Resolution

If conflicts arise between documents:

1. **This directive (000)** wins for structure and organization
2. **Doc A** wins for platform facts
3. **Doc C** wins for requirements
4. **Phase docs (P1-P3)** win for implementation details
5. **Doc B** is observational (actual test results) and may reveal conflicts

When a conflict is found:
1. Document it in this section
2. Resolve by updating the lower-priority document
3. Update the status matrix

---

## 9. Next Steps

### ⚠️ Time-Based Triggers (Enforcement)

**Doc A must be created BEFORE any further implementation work.**
- No Phase 2 or Phase 3 changes until Doc A exists
- No new platform behavior claims in any doc until Doc A is canonical

**Doc B must be baseline-complete BEFORE Phase 2 changes.**
- At least 6 core scenarios scaffolded
- Expected behavior columns populated from Doc A + Doc C

**Doc C must be finalized BEFORE any JS/TS API changes.**
- All guarantees documented
- API contract defined
- No breaking changes to JS/TS API without Doc C update first

### Immediate (Before New Implementation)

1. Create stub documents A, B, C with structure
2. Migrate content from existing docs into new structure
3. Update all cross-references
4. Mark old docs as deprecated (with pointers to new docs)

**Deliverables Required**:
- Doc A exists as a file in repo
- Doc B exists with scenario tables scaffolded
- Doc C exists with required sections
- Status matrix updated in this document
- Deprecated docs marked with header banner

### Short-term (During Implementation)

1. Keep Doc B updated with test results
2. Update Phase docs as implementation progresses
3. Maintain status matrix

### Long-term (Post-Implementation)

1. Add iOS parity documentation
2. Expand exploration scenarios
3. Create regression test suite based on Doc B

### ⚠️ iOS Parity Activation Milestone

**iOS parity work begins ONLY after**:

1. **Doc A contains iOS matrix** - All iOS platform facts documented with labels (see [Doc A](./01-platform-capability-reference.md#3-ios-notification-capability-matrix))
2. **Doc C defines iOS limitations and guarantees** - All iOS-specific requirements documented (see [Doc C](./03-plugin-requirements.md#1-plugin-behavior-guarantees--limitations))
3. **No references in Phase docs assume Android-only behavior** - All Phase docs are platform-agnostic or explicitly handle both platforms

**Blocking Rule**: No iOS implementation work may proceed until these conditions are met.

**Enforcement**: Phase docs MUST reference Doc A for platform facts and Doc C for requirements. No platform-specific assumptions allowed.

---

## 10. Change-Control Rules

Any change to Docs A–C requires:

1. **Update version header** in the document
2. **Update status matrix** (Section 11) in this directive
3. **Commit message tag**: `[ALARM-DOCS]` prefix
4. **Notification in CHANGELOG** if JS/TS-visible behavior changes

**Phase docs may not be modified unless Doc C changes first** (or explicit exception documented).

**Example commit message**:
```
[ALARM-DOCS] Update Doc C with force stop recovery guarantee

- Added force stop detection requirement
- Updated recovery matrix
- Version bumped to 1.1.0
```

---

## 11. Status Matrix

| Doc | Path                                  | Role              | Drafted? | Cleaned? | In Use? | Notes                                    |
| --- | ------------------------------------- | ----------------- | -------- | -------- | ------- | ---------------------------------------- |
| A   | `01-platform-capability-reference.md` | Platform facts    | ✅        | ✅        | ✅       | Created, merged from platform docs, canonical rule added |
| B   | `02-plugin-behavior-exploration.md`   | Exploration       | ✅        | ✅        | ✅       | Converted to executable test harness + emulator script              |
| C   | `03-plugin-requirements.md`           | Requirements      | ✅        | ✅        | ✅       | Enhanced with guarantees matrix, JS/TS contract, traceability - **complete and in compliance** |
| P1  | `../android-implementation-directive-phase1.md` | Impl – Cold start | ✅        | ✅        | ✅       | Emulator-verified via `test-phase1.sh` (Pixel 8 API 34, 2025-11-27) |
| P2  | `../android-implementation-directive-phase2.md`  | Impl – Force stop | ✅        | ✅        | ☐       | Implemented; to be emulator-verified via `test-phase2.sh` (Pixel 8 API 34, 2025-11-XX) |
| P3  | `../android-implementation-directive-phase3.md`  | Impl – Boot Recovery | ✅        | ✅        | ☐       | Implemented; verify via `test-phase3.sh` (API 34 baseline) |
| V1  | `PHASE1-VERIFICATION.md`                        | Verification – P1 | ✅        | ✅        | ✅       | Summarizes Phase 1 emulator tests and latest known good run         |
| V2  | `PHASE2-VERIFICATION.md`                         | Verification – P2 | ✅        | ✅        | ☐       | Summarizes Phase 2 emulator tests and latest known good run         |
| V3  | `PHASE3-VERIFICATION.md`                         | Verification – P3 | ✅        | ✅        | ☐       | To be completed after first clean emulator run          |

**Doc C Compliance Milestone**: Doc C is considered complete **ONLY** when:
- ✅ Cross-platform guarantees matrix present
- ✅ JS/TS API contract with returned fields and error states
- ✅ Explicit storage schema documented
- ✅ Recovery contract with all triggers and actions
- ✅ Unsupported behaviors explicitly listed
- ✅ Traceability matrix mapping A → B → C → Phase

**Legend:**
- ✅ = Complete
- ☐ = Not started / In progress
- ⚠️ = Needs attention

---

## Related Documentation

* [Android Implementation Directive](../android-implementation-directive.md) – Umbrella overview
* [Phase 1: Cold Start Recovery](../android-implementation-directive-phase1.md) – Minimal viable recovery
* [Phase 2: Force Stop Recovery](../android-implementation-directive-phase2.md) – Force stop detection
* [Phase 3: Boot Recovery](../android-implementation-directive-phase3.md) – Boot receiver enhancement
* [Exploration Findings](../exploration-findings-initial.md) – Initial code discovery

---

**Status**: Active master coordination directive  
**Last Updated**: November 2025  
**Next Review**: After implementation phases are complete

---

## 12. Single Instruction for Team

**⚠️ BLOCKING RULE**: No engineering or documentation work on alarms/schedules/notifications may continue until Steps 1–3 in §9 ("Immediate") are complete and committed.

**Specifically**:
- Doc A must exist as a file
- Doc B must have scenario tables scaffolded
- Doc C must have required sections
- Status matrix must be updated
- Deprecated files must be marked

**Exception**: Only emergency bug fixes may proceed, but must be documented retroactively in the appropriate Doc A/B/C structure.

---

## 13. Prohibited Content Rules

**The following content may NOT appear in any document except the specified one**:

| Content Type | Allowed Only In | Examples |
| ------------ | --------------- | -------- |
| **Platform rules** | Doc A only | "Android wipes alarms on reboot", "iOS persists notifications automatically" |
| **Guarantees or requirements** | Doc C only | "Plugin MUST detect missed alarms", "Plugin SHOULD reschedule on boot" |
| **Actual behavior findings** | Doc B only | "Test showed alarm fired 2 seconds late", "Missed alarm not detected in scenario X" |
| **Recovery logic** | Phase docs only | "ReactivationManager.performRecovery()", "BootReceiver sets flag" |
| **Implementation details** | Phase docs only | Code snippets, function signatures, database queries |

**Violation Response**: If prohibited content is found, move it to the correct document and replace with a cross-reference.

---

## 14. Glossary

**Shared terminology across all documents** (must be identical):

| Term | Definition |
| ---- | ---------- |
| **recovery** | Process of detecting and handling missed alarms, rescheduling future alarms, and restoring plugin state after app launch, boot, or force stop |
| **cold start** | App launched from terminated state (process killed, no memory state) |
| **warm start** | App returning from background (process may still exist, memory state may persist) |
| **missed alarm** | Alarm where `trigger_time < now`, alarm was not fired (or firing status unknown), alarm is still enabled, and alarm has not been manually cancelled |
| **delivered alarm** | Alarm that successfully fired and displayed notification to user |
| **persisted alarm** | Alarm definition stored in durable storage (database, files, etc.) |
| **cleared alarm** | Alarm removed from AlarmManager/UNUserNotificationCenter but may still exist in persistent storage |
| **first run** | First time app is launched after installation (no previous state) |
| **notification tap** | User interaction with notification that launches app |
| **rescheduled** | Alarm re-registered with AlarmManager/UNUserNotificationCenter after being cleared |
| **reactivated** | Plugin state restored and alarms rescheduled after app launch or boot |

**Usage**: All documents MUST use these exact definitions. No synonyms or variations allowed.

---

## 15. Lifecycle Flow Diagram

**Document relationship and information flow**:

```
┌─────────────────────────────────────────────────────────────┐
│         Unified Directive (000) - Master Coordination       │
│         Defines structure, ownership, change control        │
└─────────────────────────────────────────────────────────────┘
                            │
                            │ References & Coordinates
                            │
        ┌───────────────────┼───────────────────┐
        │                   │                   │
        ▼                   ▼                   ▼
┌───────────────┐   ┌───────────────┐   ┌───────────────┐
│   Doc A       │   │   Doc B       │   │   Doc C       │
│   Platform    │   │   Exploration │   │   Requirements│
│   Facts       │   │   & Testing   │   │   & Guarantees│
└───────────────┘   └───────────────┘   └───────────────┘
        │                   │                   │
        │                   │                   │
        │                   │                   │
        │                   │                   │
        └───────────────────┼───────────────────┘
                            │
                            │ Implements
                            │
        ┌───────────────────┼───────────────────┐
        │                   │                   │
        ▼                   ▼                   ▼
┌───────────────┐   ┌───────────────┐   ┌───────────────┐
│   Phase 1     │   │   Phase 2     │   │   Phase 3     │
│   Cold Start  │   │   Force Stop  │   │   Boot       │
│   Recovery    │   │   Recovery    │   │   Recovery   │
└───────────────┘   └───────────────┘   └───────────────┘
```

**Information Flow**:
1. **Doc A** (Platform Facts) → Informs **Doc C** (Requirements) → Drives **Phase Docs** (Implementation)
2. **Doc B** (Exploration) → Validates **Phase Docs** → Updates **Doc C** (Requirements)
3. **Phase Docs** → Implements **Doc C** → Tested by **Doc B**

**Key Principle**: Platform facts (A) constrain requirements (C), which drive implementation (Phases), which are validated by exploration (B).

