# Tasks: MailioReceipt v1

**Input**: Design documents from `/specs/001-mailio-receipt-v1/`
**Prerequisites**: plan.md ✅, spec.md ✅, research.md ✅, data-model.md ✅, contracts/api.md ✅

**Tests**: Included per constitution requirements (crypto tests, public API tests, integration tests)

**Organization**: Tasks are grouped by user story to enable independent implementation and testing of each story.

## Format: `[ID] [P?] [Story] Description`

- **[P]**: Can run in parallel (different files, no dependencies)
- **[Story]**: Which user story this task belongs to (e.g., US1, US2, US3)
- Include exact file paths in descriptions

---

## Phase 1: Setup (Project Initialization)

**Purpose**: Project initialization and basic structure

- [x] T001 Create project structure with src/mailio_receipt/ and tests/ directories
- [x] T002 Initialize pyproject.toml with dependencies: cryptography>=41.0, httpx>=0.25, canonicaljson>=2.0
- [x] T003 [P] Configure ruff for linting in pyproject.toml
- [x] T004 [P] Configure mypy for type checking in pyproject.toml
- [x] T005 [P] Add pytest and dev dependencies: pytest, pytest-asyncio, respx

---

## Phase 2: Foundational (Blocking Prerequisites)

**Purpose**: Core infrastructure that MUST be complete before ANY user story can be implemented

**⚠️ CRITICAL**: No user story work can begin until this phase is complete

- [x] T006 [P] Implement error hierarchy in src/mailio_receipt/errors.py per api.md
- [x] T007 [P] Define type aliases and protocols in src/mailio_receipt/types.py
- [x] T008 Implement core data models (Actors, Intent, Chain, Binding, SignedMetadata) in src/mailio_receipt/models.py
- [x] T009 Implement MailioAuditEvent dataclass in src/mailio_receipt/models.py
- [x] T010 Implement MailioReceipt dataclass with to_dict/from_dict/to_json/from_json in src/mailio_receipt/models.py
- [x] T011 Implement Signature dataclass in src/mailio_receipt/models.py
- [x] T012 [P] Implement RFC8785 canonicalization in src/mailio_receipt/canonicalize.py using canonicaljson
- [x] T013 Create shared test fixtures (test keys, sample actors, sample intents) in tests/conftest.py
- [x] T014 Add IntentKind constants class in src/mailio_receipt/models.py per api.md

**Checkpoint**: Foundation ready - user story implementation can now begin

---

## Phase 3: User Story 1 - Create a Receipt for a Planned Action (Priority: P1) 🎯 MVP

**Goal**: Enable agents to create signed MailioReceipts for planned actions with event details, actor information, and optional artifact bindings

**Independent Test**: Create a receipt with sample event data, verify the structure contains all required fields (type, version, event, eventDigest, signatures) and the signature is valid

### Tests for User Story 1

> **NOTE: Write these tests FIRST, ensure they FAIL before implementation**

- [x] T015 [P] [US1] Test model validation in tests/test_models.py (required fields, UUIDs, timestamps)
- [x] T016 [P] [US1] Test RFC8785 canonicalization produces deterministic output in tests/test_canonicalize.py
- [x] T017 [P] [US1] Test JWS detached signature creation in tests/test_signing.py

### Implementation for User Story 1

- [x] T018 [US1] Implement SHA-256 digest computation for canonicalized events in src/mailio_receipt/canonicalize.py
- [x] T019 [US1] Implement create_jws_detached function using cryptography in src/mailio_receipt/signing.py
- [x] T020 [US1] Implement create_event factory function in src/mailio_receipt/models.py
- [x] T021 [US1] Implement create_receipt function in src/mailio_receipt/__init__.py
- [x] T022 [US1] Add receipt digest property (SHA-256 of full receipt) for identifier use; chaining uses event digest
- [x] T023 [US1] Export create_receipt, create_event, and models in src/mailio_receipt/__init__.py

**Checkpoint**: User Story 1 complete - agents can create and sign receipts for planned actions

---

## Phase 4: User Story 2 - Request and Grant Approval (Priority: P1)

**Goal**: Enable users to approve agent actions before execution via approval request/grant receipts with chain linking

**Independent Test**: Create an approval request receipt, then create a grant receipt that references it, verify the chain linkage and approval binding are correct

### Tests for User Story 2

- [x] T024 [P] [US2] Test approval request creation with correct intent kind in tests/test_signing.py
- [x] T025 [P] [US2] Test approval grant with chain reference in tests/test_integration.py
- [x] T026 [P] [US2] Test TTL validation for approvals in tests/test_models.py

### Implementation for User Story 2

- [x] T027 [US2] Document generic approval receipts using create_event/create_receipt and event-digest chaining
- [x] T028 [US2] Add chain linking validation (prevReceiptDigest format) in src/mailio_receipt/models.py
- [x] T029 [US2] Add TTL parsing and validation (ISO8601 duration) in src/mailio_receipt/models.py
- [x] T030 [US2] Export chain_from and compute_chain_digest helpers

**Checkpoint**: User Stories 1 AND 2 complete - approval workflow supported

---

## Phase 5: User Story 3 - Revoke an Approval (Priority: P2)

**Goal**: Enable users to revoke previously granted approvals before action execution

**Independent Test**: Create an approval, then revoke it, verify that the revocation receipt is correctly linked

### Tests for User Story 3

- [x] T031 [P] [US3] Test revocation receipt creation with correct intent kind in tests/test_signing.py
- [x] T032 [P] [US3] Test revocation chain reference to approval in tests/test_integration.py

### Implementation for User Story 3

- [x] T033 [US3] Document generic revocation receipts using create_event/create_receipt and event-digest chaining
- [x] T034 [US3] Export chain_from and compute_chain_digest helpers

**Checkpoint**: User Story 3 complete - revocation workflow supported

---

## Phase 6: User Story 6 - Resolve DID:web Identifiers (Priority: P3)

**Goal**: Resolve DID:web identifiers to obtain public keys for signature verification

**Note**: Implementing before US4 because verification depends on DID resolution

**Independent Test**: Resolve a known DID:web and verify the returned key matches expectations

### Tests for User Story 6

- [x] T035 [P] [US6] Test DID:web URL conversion algorithm in tests/test_did_resolver.py
- [x] T036 [P] [US6] Test DID document fetching with mock HTTP in tests/test_did_resolver.py
- [x] T037 [P] [US6] Test verification key extraction from DID document in tests/test_did_resolver.py
- [x] T038 [P] [US6] Test DID caching with TTL in tests/test_did_resolver.py
- [x] T039 [P] [US6] Test network error handling (retryable errors) in tests/test_did_resolver.py

### Implementation for User Story 6

- [x] T040 [US6] Implement DIDResolver protocol in src/mailio_receipt/types.py
- [x] T041 [US6] Implement did_to_https_url conversion in src/mailio_receipt/did_resolver.py
- [x] T042 [US6] Implement DIDWebResolver class with httpx in src/mailio_receipt/did_resolver.py
- [x] T043 [US6] Implement DID document caching with configurable TTL in src/mailio_receipt/did_resolver.py
- [x] T044 [US6] Implement get_verification_key to extract EC public keys in src/mailio_receipt/did_resolver.py
- [x] T045 [US6] Export DIDResolver and DIDWebResolver in src/mailio_receipt/__init__.py

**Checkpoint**: User Story 6 complete - DID:web resolution ready for verification

---

## Phase 7: User Story 4 - Verify a Receipt and Chain (Priority: P2)

**Goal**: Verify receipt authenticity and chain integrity via signature verification and DID resolution

**Dependencies**: Requires US6 (DID resolution)

**Independent Test**: Create a valid receipt chain, verify it succeeds. Tamper with a receipt and verify it fails

### Tests for User Story 4

- [x] T046 [P] [US4] Test single receipt signature verification in tests/test_verification.py
- [x] T047 [P] [US4] Test eventDigest recomputation and validation in tests/test_verification.py
- [x] T048 [P] [US4] Test tampered receipt detection in tests/test_verification.py
- [x] T049 [P] [US4] Test chain traversal via prevReceiptDigest in tests/test_verification.py
- [x] T050 [P] [US4] Test chain integrity failure detection in tests/test_verification.py

### Implementation for User Story 4

- [x] T051 [US4] Implement verify_jws_detached function in src/mailio_receipt/signing.py
- [x] T052 [US4] Implement verify_receipt async function in src/mailio_receipt/verification.py
- [x] T053 [US4] Implement VerificationResult dataclass in src/mailio_receipt/verification.py
- [x] T054 [US4] Implement verify_chain async function in src/mailio_receipt/verification.py
- [x] T055 [US4] Implement ChainVerificationResult dataclass in src/mailio_receipt/verification.py
- [x] T056 [US4] Export verify_receipt and verify_chain in src/mailio_receipt/__init__.py

**Checkpoint**: User Story 4 complete - receipt and chain verification functional

---

## Phase 8: User Story 5 - Check Execution Eligibility (Priority: P2)

**Goal**: Determine if an action can execute based on approvals, revocations, TTL, and bindings

**Dependencies**: Benefits from US4 for verified chains

**Independent Test**: Create a flow with approvals and optionally revocations, verify the execution check returns the correct allow/block decision

### Tests for User Story 5

- [x] T057 [P] [US5] Test execution allowed with valid approval in tests/test_execution.py
- [x] T058 [P] [US5] Test execution blocked without approval in tests/test_execution.py
- [x] T059 [P] [US5] Test execution blocked by revocation (ts <= decisionTs) in tests/test_execution.py
- [x] T060 [P] [US5] Test execution allowed when revocation after decision in tests/test_execution.py
- [x] T061 [P] [US5] Test execution blocked by expired approval in tests/test_execution.py
- [x] T062 [P] [US5] Test binding validation blocks on digest mismatch in tests/test_execution.py

### Implementation for User Story 5

- [x] T063 [US5] Implement BlockingReason enum in src/mailio_receipt/execution.py
- [x] T064 [US5] Implement ExecutionDecision dataclass in src/mailio_receipt/execution.py
- [x] T065 [US5] Implement check_execution function in src/mailio_receipt/execution.py
- [x] T066 [US5] Implement approval collection from receipt chain in src/mailio_receipt/execution.py
- [x] T067 [US5] Implement revocation detection with timestamp comparison in src/mailio_receipt/execution.py
- [x] T068 [US5] Implement TTL expiration check in src/mailio_receipt/execution.py
- [x] T069 [US5] Implement binding digest validation in src/mailio_receipt/execution.py
- [x] T070 [US5] Export check_execution and ExecutionDecision in src/mailio_receipt/__init__.py

**Checkpoint**: User Story 5 complete - execution eligibility checks functional

---

## Phase 9: User Story 7 - Record Execution Outcome (Priority: P3)

**Goal**: Record execution success or failure as receipts to complete the audit trail

**Independent Test**: Create a flow through planned → approved → executed, verify the chain is complete and all events are linked

### Tests for User Story 7

- [x] T071 [P] [US7] Test execution outcome receipt creation (success) in tests/test_integration.py
- [x] T072 [P] [US7] Test execution outcome receipt creation (failure) in tests/test_integration.py
- [x] T073 [P] [US7] Test complete workflow chain integrity in tests/test_integration.py

### Implementation for User Story 7

- [x] T074 [US7] Document generic execution outcome receipts using create_event/create_receipt
- [x] T075 [US7] Add failure details schema to scope for ACTION_FAILED in src/mailio_receipt/models.py
- [x] T076 [US7] Export chain_from and compute_chain_digest helpers

**Checkpoint**: All user stories complete - full workflow supported

---

## Phase 10: Polish & Cross-Cutting Concerns

**Purpose**: Improvements that affect multiple user stories

- [ ] T077 [P] Verify all public API exports in src/mailio_receipt/__init__.py match api.md
- [ ] T078 [P] Add comprehensive docstrings to all public functions per api.md
- [ ] T079 Run all tests with pytest to ensure 100% pass rate
- [ ] T080 Performance test: verify 100-receipt chain in <2s (SC-002)
- [ ] T081 Run quickstart.md validation manually to verify examples work
- [ ] T082 [P] Run ruff check and fix any linting issues
- [ ] T083 [P] Run mypy and fix any type errors

---

## Dependencies & Execution Order

### Phase Dependencies

- **Setup (Phase 1)**: No dependencies - can start immediately
- **Foundational (Phase 2)**: Depends on Setup completion - BLOCKS all user stories
- **User Story 1 (Phase 3)**: Depends on Foundational - receipt creation
- **User Story 2 (Phase 4)**: Depends on US1 - approval workflow
- **User Story 3 (Phase 5)**: Depends on US2 - revocation workflow
- **User Story 6 (Phase 6)**: Depends on Foundational - DID resolution (implemented before US4)
- **User Story 4 (Phase 7)**: Depends on US6 - verification needs DID resolution
- **User Story 5 (Phase 8)**: Depends on Foundational - execution checks
- **User Story 7 (Phase 9)**: Depends on US1 - outcome recording
- **Polish (Phase 10)**: Depends on all user stories being complete

### User Story Dependencies

```
Foundational
     │
     ├──────────────────┬────────────────────┬─────────────────┐
     ▼                  ▼                    ▼                 ▼
   US1 (P1)          US6 (P3)            US5 (P2)          US7 (P3)
 Receipt Create    DID Resolution     Execution Check   Record Outcome
     │                  │
     ▼                  ▼
   US2 (P1)          US4 (P2)
 Approval Grant    Verification
     │
     ▼
   US3 (P2)
 Revocation
```

### Within Each User Story

- Tests MUST be written and FAIL before implementation
- Models before services
- Services before API functions
- Core implementation before integration
- Story complete before moving to next phase

### Parallel Opportunities

- **Phase 1**: T003, T004, T005 can run in parallel
- **Phase 2**: T006, T007, T012 can run in parallel; T008→T009→T010→T011 are sequential
- **Phase 3-9**: All tests within a story marked [P] can run in parallel
- **Phase 10**: T077, T078, T082, T083 can run in parallel

---

## Parallel Example: User Story 1 Tests

```bash
# Launch all tests for User Story 1 together:
Task: "T015 Test model validation in tests/test_models.py"
Task: "T016 Test RFC8785 canonicalization in tests/test_canonicalize.py"
Task: "T017 Test JWS detached signature creation in tests/test_signing.py"
```

---

## Implementation Strategy

### MVP First (User Stories 1 + 2)

1. Complete Phase 1: Setup
2. Complete Phase 2: Foundational (CRITICAL - blocks all stories)
3. Complete Phase 3: User Story 1 - Create Receipt
4. Complete Phase 4: User Story 2 - Approval Grant
5. **STOP and VALIDATE**: Test receipt creation and approval workflow
6. Deploy/demo if ready

### Incremental Delivery

1. Setup + Foundational → Foundation ready
2. Add User Story 1 → Receipt creation works → Demo
3. Add User Story 2 → Approval workflow works → Demo
4. Add User Story 3 → Revocation works → Demo
5. Add User Stories 6 + 4 → Verification works → Demo
6. Add User Story 5 → Execution checks work → Demo
7. Add User Story 7 → Full workflow complete → Release

### Suggested MVP Scope

**Minimum**: User Stories 1 + 2 (P1 features)
- Creates signed receipts
- Supports approval workflow
- No verification yet (verification is P2)

---

## Notes

- [P] tasks = different files, no dependencies
- [Story] label maps task to specific user story for traceability
- Each user story should be independently completable and testable
- Verify tests fail before implementing
- Commit after each task or logical group
- Stop at any checkpoint to validate story independently
- US6 (DID Resolution) is implemented before US4 (Verification) due to dependency
