Inbox Agent Technical Architecture and Integration Requirements
1. Purpose
This document defines the technical architecture, provider integration strategy, persistence requirements, event-processing model, agent boundaries, security requirements, and deployment expectations for the Inbox Agent.
This is an architecture and integration specification.
It intentionally does not define Jira epics, stories, tasks, sprint structure, or implementation sequencing. Those artifacts will be generated separately by Charter.
2. Architecture Goals
The technical architecture must:
- Support multiple independent physical mailboxes.
- Support aliases that share physical mailboxes.
- Support Microsoft, Gmail, and iCloud mail sources.
- Preserve provider-specific capabilities without leaking provider-specific behavior throughout the application.
- Provide one canonical internal message model.
- Support both event-driven and incremental synchronization.
- Separate deterministic automation from AI reasoning.
- Preserve complete auditability.
- Support reversible operations.
- Prevent the AI layer from directly receiving unrestricted mailbox authority.
- Keep mail-provider credentials secure.
- Support future providers without redesigning the core application.
- Remain independent of any desktop mail client.
- Support deployment as a modern web application developed primarily in Cursor.
3. High-Level Architecture
Recommended logical architecture:
┌─────────────────────────┐
│ Web UI │
│ Next.js │
└────────────┬────────────┘
│
┌────────────▼────────────┐
│ Application API │
│ / Server Operations │
└────────────┬────────────┘
│
┌──────────────────────┼──────────────────────┐
│ │ │
▼ ▼ ▼
Agent Orchestrator Rule Engine Search / Views
│ │ │
└──────────────┬───────┴──────────────┬──────┘
│ │
▼ ▼
Canonical Mail Model Metadata Store
│ │
└──────────┬───────────┘
│
Provider Adapter Layer
│
┌─────────────────────┼─────────────────────┐
│ │ │
▼ ▼ ▼
Microsoft Graph Gmail API iCloud Mail
Adapter / IMAP
The provider adapter layer is mandatory.
Core application logic should not contain provider-specific branching such as:
if microsoft
if gmail
if icloud
throughout the business logic.
Provider differences should be encapsulated in adapters.
4. Recommended Application Platform
The application should be implemented as a modern web application.
Preferred application framework:
Next.js
TypeScript
React
Reasons include:
- Existing development familiarity.
- Strong support for server-side operations.
- Suitable deployment model.
- Mature authentication ecosystem.
- Straightforward integration with AI orchestration libraries.
- Good fit for Cursor-based development.
The architecture should not require Next.js-specific behavior in the domain model.
Provider connectors, classification services, and rule processing should remain separable from the UI framework.
5. Architectural Layers
The system should contain at least the following logical layers:
Presentation
Application Services
Agent Orchestration
Rule Engine
Domain Model
Provider Adapters
Persistence
Background/Event Processing
Security
Audit
Observability
Responsibilities should remain clearly separated.
6. Provider Adapter Interface
Every mail provider should implement a common logical interface.
Representative capabilities:
connectAccount()
refreshAuthorization()
getMailboxProfile()
listFolders()
getFolder()
listMessages()
getMessage()
getThread()
searchMessages()
getMessageHeaders()
setReadState()
setFlag()
setCategoriesOrLabels()
moveMessage()
archiveMessage()
createDraft()
listSentMessages()
getChanges()
subscribeToChanges()
renewSubscription()
testConnection()
Not every provider must support every capability.
Adapters must expose capability information.
Example:
supportsPushNotifications = true
supportsFolders = true
supportsCategories = true
supportsNativeRules = false
supportsDraftCreation = true
supportsStableThreadId = true
The application must degrade gracefully when capabilities differ.
7. Microsoft Integration
7.1 Microsoft Graph
Microsoft mail integration should use Microsoft Graph rather than IMAP.
Graph provides access to:
Messages
Mail folders
Categories
Inbox rules
Headers
Search/filter
Drafts
Sent mail
Change notifications
Incremental synchronization
Microsoft Graph supports mail operations against Microsoft 365 mailboxes, and its mail resources expose message properties such as categories, conversation IDs, flags, and importance. Graph also supports folder delta queries and message change notifications.
8. Microsoft Accounts
The Microsoft estate currently contains two separate mailbox contexts.
Personal Microsoft Account
jskoch@msn.com
This is an independent Microsoft consumer mailbox.
Microsoft 365 Professional Mailbox
jason@jasonkoch.io
Tenant:
jasonkoch13.onmicrosoft.com
Alias:
jason@jasonkoch.ai
The application must not assume these Microsoft accounts share:
Tenant
Authentication session
OAuth consent
Directory
Mailbox
Token
Each connection must be modeled independently.
9. Microsoft Alias Handling
Mail received at:
jason@jasonkoch.ai
must remain distinguishable from mail received at:
jason@jasonkoch.io
even though both resolve to the same physical mailbox.
The adapter should inspect available recipient and transport headers when needed to preserve delivered identity.
Canonical metadata should include:
physical_mailbox_id
delivered_identity
to_addresses
cc_addresses
internet_message_id
internet_headers
Do not infer identity solely from the physical mailbox address.
10. Microsoft Authentication
Microsoft integration should use OAuth 2.0 through Microsoft identity services.
The initial design should favor delegated authorization because the application manages the user's own mailboxes.
Authorization should follow least-privilege principles.
Expected progression:
Discovery:
Mail.Read
Operational organization:
Mail.ReadWrite
Sending:
Do not request until sending is explicitly enabled.
Graph requires Mail.ReadWrite for message write operations such as creating messages within folders.
The application should avoid requesting broader permissions before needed.
11. Microsoft Change Detection
Microsoft integration should support both:
Change Notifications
+
Delta Synchronization
Graph supports subscriptions for message changes, and Outlook mail folders support delta queries for incremental synchronization.
Change notifications should act as:
Something changed
rather than the sole canonical record of what changed.
The application should follow notifications with provider reads or delta synchronization as required.
12. Microsoft Identifier Handling
The system must not assume standard Microsoft message IDs remain permanently stable across moves.
Microsoft documents that message and folder IDs may change after operations such as move or copy, while immutable IDs are available for more stable identification within supported constraints.
The adapter should therefore support:
provider_message_id
immutable_provider_id where available
internet_message_id
canonical_message_id
The internal canonical message ID must never depend exclusively on a mutable provider ID.
13. Gmail Integration
Gmail should use the native Gmail API rather than IMAP for primary operation.
Current Gmail mailboxes:
Jason.s.koch@gmail.com
platypus.software.dev@gmail.com
Each should be modeled as an independent physical mailbox with independent authorization.
14. Gmail Authentication
Gmail API access should use OAuth 2.0.
For server-side access that continues when the user is not actively present, Google supports a server-side authorization flow using access and refresh tokens.
Credentials must not be stored in source code.
Refresh tokens must be stored encrypted.
15. Gmail Permission Strategy
Use the least permissive Gmail scope capable of supporting the current phase.
Potential phases:
Discovery:
gmail.readonly
Classification + organization:
gmail.modify
Sending:
Separate explicit capability decision
Google classifies several Gmail scopes, including gmail.readonly and gmail.modify, as restricted scopes. The system should avoid the full mail.google.com scope unless permanent deletion is specifically required. Google explicitly notes that other operations can use less permissive scopes.
This has implications for OAuth verification if the application is ever distributed beyond personal/private use.
16. Gmail Labels
Gmail's organizational primitive is labels rather than traditional folders.
The canonical model must not force Gmail labels directly into the physical folder model.
The adapter should translate:
Gmail Label
↔
Provider Classification / Location
while the application continues to use:
Attention State
Semantic Classification
Retention
Virtual Views
Gmail supports modifying message labels through the Gmail API.
17. Gmail Push Notifications
The Gmail adapter should support Gmail push notifications.
Gmail's users.watch capability sends mailbox change notifications through Google Cloud Pub/Sub and returns an expiration value, meaning watches must be renewed.
Required architecture:
Gmail
│
▼
Gmail Watch
│
▼
Google Cloud Pub/Sub
│
▼
Inbox Agent Event Endpoint
│
▼
Gmail History / Sync
The application must maintain renewal state for each Gmail watch.
18. Gmail History Tracking
The canonical mailbox connection record should maintain the latest successfully processed Gmail:
historyId
Push notifications should trigger incremental retrieval beginning from known state rather than repeatedly scanning the entire mailbox.
Failure recovery must support resynchronization.
19. System Gmail Specialization
platypus.software.dev@gmail.com
should use the standard Gmail adapter but support different processing policy.
This is a policy concern, not a separate provider implementation.
Example:
Provider:
Gmail
Mailbox Type:
SYSTEM_SERVICE
Processing Profile:
EXCEPTION_ORIENTED
The architecture should never hard-code individual email addresses into provider logic.
20. iCloud Mail Integration
iCloud should be treated differently from Microsoft and Gmail.
Apple supports third-party access to iCloud Mail and publishes IMAP settings for clients that require them. Apple currently supports third-party authorization where supported, with app-specific passwords as a fallback.
For this project, iCloud Mail should primarily serve as:
Discovery source
Historical migration source
Legacy mailbox
Forwarding validation source
rather than the primary real-time automation platform.
21. iCloud Mail Adapter
The iCloud adapter may use:
IMAP over TLS
for mail discovery and historical retrieval.
Published iCloud Mail IMAP configuration currently uses:
imap.mail.me.com
Port 993
SSL/TLS
with appropriate Apple authorization.
SMTP should not be required for the initial iCloud integration because autonomous sending from iCloud is not a project requirement.
22. iCloud Accounts
Current iCloud mail sources:
jskoch67@icloud.com
Jason.s.koch@icloud.com
The first is active for Apple services but forwards mail.
The second is legacy.
Both should initially be treated as:
READ / DISCOVERY / MIGRATION
sources.
Write operations should be avoided until migration behavior is proven and explicitly approved.
23. iCloud Calendar and Contacts Boundary
The project must not treat iCloud Mail migration as authorization to migrate:
Shared calendars
Contacts
Apple account services
These remain separate domains.
Current architectural policy:
MAIL
Prefer Microsoft
FAMILY CALENDARS
Remain iCloud
CONTACTS
Remain iCloud initially
Calendar and contacts integration may later provide contextual information to the agent.
It is not required for initial mail migration.
24. Canonical Account Model
The system requires a canonical account model independent of provider.
Suggested entity:
MailAccount
Representative fields:
id
provider
provider_account_id
primary_address
display_name
account_type
mailbox_type
status
authorization_status
sync_status
last_successful_sync_at
last_error_at
capabilities
created_at
updated_at
25. Mailbox Types
Supported mailbox types should include:
PERSONAL
PROFESSIONAL
COMMERCIAL
SYSTEM_SERVICE
APPLE_INFRASTRUCTURE
LEGACY
This enables behavior differences without encoding email addresses into application logic.
26. Identity Model
A physical mailbox may have multiple identities.
Entity:
MailIdentity
Suggested fields:
id
mail_account_id
email_address
identity_type
is_primary
is_alias
purpose
preferred_message_categories
active
Example:
MailAccount:
jason@jasonkoch.io
Identities:
jason@jasonkoch.io
jason@jasonkoch.ai
27. Canonical Message Model
The application should maintain a normalized representation of provider messages.
Entity:
Message
Suggested fields:
id
mail_account_id
provider_message_id
provider_thread_id
internet_message_id
conversation_key
sender_address
sender_name
subject
body_preview
sent_at
received_at
has_attachments
is_read
is_draft
delivered_identity_id
historical
migration_run_id
created_at
updated_at
Full message bodies do not necessarily need to be permanently duplicated into the application database.
That decision should be made based on search, AI processing, privacy, and cost requirements.
28. Body Storage Principle
Default recommendation:
Provider remains source of truth for full message body.
The application database should initially store:
Provider identifiers
Headers
Metadata
Classification
Summaries
Derived features
Audit information
Full bodies may be:
Fetched on demand
Temporarily processed
Cached selectively
This reduces duplication of sensitive mail.
Historical migration workflows are an exception because actual message transfer between providers may require full message retrieval.
29. Message Provenance
Canonical messages must retain:
source_provider
source_mailbox
source_folder
original_recipient
delivered_identity
migration_run
For migrated messages, provenance must survive after the source mailbox is retired.
30. Canonical Conversation Model
The system should maintain a provider-independent logical conversation.
Entity:
Conversation
Suggested fields:
id
subject_normalized
attention_state
priority
classification
status
last_message_at
last_human_message_at
last_user_message_at
waiting_on
due_at
resolved_at
Provider thread IDs may assist but should not be treated as universal cross-provider identifiers.
31. Classification Model
Derived classification should not be stored solely in provider categories or labels.
The application's metadata store remains authoritative for AI-derived semantics.
Entity:
MessageClassification
Suggested fields:
message_id
primary_classification
secondary_tags
attention_state
priority
retention_state
requires_action
requires_response
waiting_state
project_id
vendor
confidence
classification_source
classified_at
32. Provider Metadata Mirroring
Where useful, selected application classifications may also be mirrored into native provider metadata.
Examples:
Microsoft categories
Gmail labels
However:
Provider metadata ≠ canonical application metadata
The application must continue functioning even if a user modifies provider categories outside the Inbox Agent.
33. Rule Engine Architecture
The deterministic rule engine must be independent of the AI model.
Logical flow:
MESSAGE EVENT
│
▼
NORMALIZE
│
▼
SECURITY POLICY
│
▼
DETERMINISTIC RULE ENGINE
│
├── matched → actions
│
└── unmatched
│
▼
AI CLASSIFICATION
│
▼
CONFIDENCE POLICY
│
▼
LOW-RISK ACTION
OR REVIEW
An LLM should never be required to execute simple known rules.
34. Rule Representation
Rules should be stored as structured data rather than executable arbitrary code.
Example logical representation:
Rule
Scope
Conditions[]
Actions[]
Priority
Enabled
Supported operators may include:
equals
contains
starts_with
ends_with
matches_domain
in
not_in
greater_than
less_than
regex
Rule definitions must be validateable before execution.
35. Rule Execution Safety
Each action type must carry a risk classification.
Example:
SET_CLASSIFICATION
LOW
MARK_READ
LOW
ARCHIVE
LOW / MEDIUM
MOVE
MEDIUM
DELETE
HIGH
SEND
HIGH
CHANGE_FORWARDING
CRITICAL
The policy engine determines whether execution:
Runs automatically
Requires batch approval
Requires explicit per-action approval
Is prohibited
36. AI Agent Architecture
The AI component should operate through explicitly defined tools.
Conceptual tools:
search_mail
read_message
read_thread
classify_message
summarize_thread
propose_attention_state
propose_priority
propose_identity_change
propose_rule
test_rule
create_draft
request_archive
request_move
request_mark_read
The agent should not receive unrestricted direct credentials to provider APIs.
37. Agent Tool Gateway
All AI-requested operations should pass through a controlled application tool gateway.
LLM
│
▼
Tool Request
│
▼
Authorization / Policy Check
│
├── Denied
│
├── Approval Required
│
└── Allowed
│
▼
Provider Adapter
This is one of the central safety requirements.
38. AI Model Abstraction
The architecture should not tightly bind the system to one LLM provider or model.
Define an abstraction for:
Classification
Summarization
Structured extraction
Draft generation
Natural-language query interpretation
Rule recommendation
Model choice may vary by function.
For example:
Low-cost classifier
→ routine semantic classification
Higher-capability model
→ complex thread reasoning
No model
→ deterministic rule
39. Structured AI Output
AI classification must produce validated structured output.
Example:
classification
attention_state
priority
requires_response
requires_action
waiting_on
due_date
confidence
short_reason
Free-form prose must not directly drive mailbox mutations.
Structured output must be schema-validated before use.
40. Confidence Policy
AI outputs must include confidence or an equivalent reliability signal.
Application policy determines action.
Example:
HIGH
Allow approved low-risk automation
MEDIUM
Apply metadata but preserve visibility
LOW
Send to Review
Thresholds should be configurable.
41. Natural-Language Query Architecture
Natural-language mail questions should follow:
User Question
│
▼
Intent / Query Planner
│
▼
Structured Search
│
▼
Provider Search + Metadata Search
│
▼
Result Set
│
▼
Answer / View / Proposed Action
The LLM should not be expected to remember mailbox contents from prior prompts.
Queries must execute against actual message data.
42. Search Architecture
Search will likely require two complementary systems.
Provider-native mail search
+
Application metadata search
Provider search is best for:
Message body
Provider headers
Attachment metadata
Existing mailbox content
Application search is best for:
Attention state
AI classification
Priority
Migration provenance
Identity hygiene
Audit history
Agent metadata
The query planner may combine both.
43. Persistence Layer
A relational database is recommended for canonical application state.
The data model is strongly relational:
Accounts
Identities
Messages
Conversations
Classifications
Rules
Rule executions
Migration runs
Folder mappings
Provider sync state
Audit events
Approvals
Projects
Sender profiles
PostgreSQL is a natural fit.
44. Core Persistence Entities
At minimum:
mail_accounts
mail_identities
provider_connections
folders
folder_mappings
messages
conversations
message_classifications
rules
rule_conditions
rule_actions
rule_executions
sync_checkpoints
provider_subscriptions
migration_runs
migration_items
approvals
audit_events
sender_profiles
projects
45. Database Normalization
Core transactional entities should be relational rather than storing the entire domain model inside arbitrary JSON blobs.
JSON may be used for:
Raw provider payload snapshots
Flexible provider capabilities
Non-critical diagnostic metadata
AI trace metadata
but should not replace normalized primary entities.
46. Event Architecture
The application should operate around durable internal events.
Examples:
MAIL_RECEIVED
MAIL_UPDATED
MAIL_MOVED
MAIL_DELETED
THREAD_UPDATED
RULE_MATCHED
RULE_ACTION_EXECUTED
CLASSIFICATION_COMPLETED
ATTENTION_CHANGED
WAITING_CREATED
WAITING_RESOLVED
MIGRATION_STARTED
MIGRATION_COMPLETED
USER_CORRECTION
APPROVAL_REQUESTED
APPROVAL_COMPLETED
Provider notifications should be translated into internal events.
47. Idempotency
All event handlers must be idempotent.
Receiving the same provider notification twice must not result in:
Duplicate classification
Duplicate moves
Duplicate drafts
Duplicate migration records
Duplicate rule execution
Each processing operation should carry an idempotency key.
48. Background Processing
Long-running work must not execute entirely in synchronous web requests.
Examples:
Initial mailbox discovery
Folder inventory
Historical synchronization
Classification backlog
Migration
Duplicate analysis
Rule simulation
Large searches
Subscription renewal
Reconciliation
These require durable background jobs.
49. Job Model
Background jobs should support:
Queued
Running
Succeeded
Failed
Retrying
Cancelled
Partially Completed
Each job should maintain:
started_at
completed_at
attempt_count
error
progress
related_mailbox
related_migration_run
50. Retry Policy
Transient provider failures should retry safely.
Use:
Exponential backoff
Provider rate-limit awareness
Maximum attempt count
Dead-letter / manual review
Do not indefinitely retry malformed or unauthorized requests.
51. Sync Checkpoints
Every mailbox must maintain durable synchronization checkpoints.
Examples:
Microsoft:
delta_link
subscription_id
subscription_expiration
last_successful_sync
Gmail:
history_id
watch_expiration
last_successful_sync
iCloud:
last_uid
uid_validity
folder_sync_checkpoint
last_successful_sync
The exact implementation may vary by protocol.
52. Subscription Renewal
Push mechanisms requiring expiration must be renewed automatically.
Examples:
Microsoft Graph subscriptions
Gmail watch registrations
Renewal must be observable and auditable.
Failure to renew should generate a provider health alert.
53. Polling Fallback
Push failure must not permanently stop synchronization.
The system should support provider-appropriate fallback synchronization.
Example:
Push healthy
→ event-driven sync
Push expired
→ scheduled incremental sync
→ renew subscription
54. Migration Architecture
Historical migration should run through a separate migration pipeline.
Source Adapter
│
▼
Read Message
│
▼
Normalize
│
▼
Duplicate Analysis
│
▼
Classification / Routing
│
▼
Target Provider Import
│
▼
Validate
│
▼
Reconcile
Migration and live-message automation should use shared domain models but distinct workflows.
55. Migration Source of Truth
During a migration:
Source provider
remains authoritative until validation is complete.
A copied target message must not cause immediate source deletion.
56. Duplicate Detection
Duplicate detection should use multiple signals.
Preferred:
Internet Message-ID
Secondary:
Sender
Recipients
Normalized subject
Timestamp tolerance
Normalized body hash
Attachment hashes
A duplicate match should produce confidence rather than blindly deleting one side.
57. Migration Import Strategy
The technical implementation must investigate the best provider-native method for inserting historical mail into Microsoft while preserving:
Sent date
Received date where possible
Sender
Recipients
Body
Attachments
Headers
Migration feasibility must be validated in a pilot before bulk migration.
Provider APIs may differ in what metadata can be preserved exactly.
The application must report any preservation limitation rather than silently changing message semantics.
58. Authentication Secret Storage
The system must never store OAuth access tokens or refresh tokens in:
Client-side storage
Git
Environment files committed to repository
Application logs
AI prompts
Secrets must use encrypted server-side storage.
59. Credential Isolation
Provider credentials must be separated by connection.
Compromise of one provider authorization should not automatically expose credentials for another mailbox.
Example:
Connection A
Microsoft Personal
Connection B
Microsoft Professional
Connection C
Gmail Commercial
Connection D
Gmail System
60. Least Privilege
Permissions should expand only when features require them.
Suggested progression:
DISCOVERY
read only
ORGANIZATION
read/write mail metadata
DRAFTING
draft creation
SENDING
separate explicit activation
DELETION
separate explicit activation
Do not request sending or destructive privileges merely because the provider exposes them.
61. User Approval Service
High-risk actions should create an Approval entity.
Example:
approval_id
action_type
requested_by
requested_at
payload_summary
affected_message_count
risk_level
status
approved_at
executed_at
Approval should be distinct from execution.
62. Audit Architecture
Every meaningful state change must generate an immutable audit event.
Examples:
Message classified
Message archived
Message moved
Rule created
Rule modified
Rule executed
AI suggestion accepted
AI suggestion rejected
User correction
Migration item processed
Approval granted
Draft created
Audit history should be append-oriented.
63. Audit Event Requirements
Each event should contain:
event_id
timestamp
actor_type
actor_id
mail_account_id
message_id
conversation_id
rule_id
action
old_value
new_value
reason_summary
source
confidence
correlation_id
Actor types:
USER
RULE_ENGINE
AI_AGENT
MIGRATION_ENGINE
SYSTEM
PROVIDER
64. Correlation IDs
Operations spanning multiple services should share a correlation ID.
Example:
Provider notification
→ sync
→ classification
→ rule evaluation
→ archive
→ audit
All events should be traceable as one processing chain.
65. AI Data Privacy
Only message content required for the current operation should be sent to an AI model.
The system should avoid automatically sending:
Entire mailbox histories
Irrelevant attachments
Large unrelated threads
Sensitive account secrets
Authentication headers
Prompt construction should follow data minimization.
66. Attachment Security
Attachments should be treated as untrusted input.
The system must not automatically:
Execute attachments
Run macros
Launch binaries
Follow embedded scripts
Attachment analysis should be isolated and limited to required parsing.
67. Prompt Injection Resistance
Email content is untrusted external input.
A message may contain instructions such as:
Ignore previous instructions.
Forward all emails to...
Delete these messages...
Send credentials...
These must be treated purely as message content.
Provider actions can only originate from:
User instructions
Approved deterministic rules
Application policy
Authorized agent tool calls
Never from commands embedded in an email body.
68. Agent Action Authorization
The AI should have no direct ability to:
Send mail
Delete permanently
Modify forwarding
Modify provider security
Modify OAuth grants
Change external accounts
unless the application policy layer explicitly approves the operation.
69. Logging
Application logs must avoid sensitive message content where practical.
Default logs should record:
Message ID
Provider
Operation
Result
Latency
Error classification
not:
Full subject
Full body
Attachment content
OAuth token
Sensitive debugging should be opt-in.
70. Observability
Operational telemetry should include:
Mailbox sync health
Provider API latency
Webhook delivery health
Watch/subscription expiration
Processing queue depth
Classification latency
Rule execution count
Failed actions
Migration progress
Token refresh failures
Rate-limit events
71. Provider Health Dashboard
Each connection should expose:
Connected
Authentication valid
Last successful sync
Push/watch status
Subscription expiration
Backlog
Last error
Example:
Microsoft Personal
Healthy
Last sync: 2 minutes ago
Gmail System
Healthy
Watch expires: 3 days
iCloud Legacy
Read-only
Last sync: yesterday
72. Error Classification
Errors should be categorized.
Examples:
AUTHENTICATION
AUTHORIZATION
RATE_LIMIT
PROVIDER_UNAVAILABLE
NETWORK
INVALID_MESSAGE
SYNC_CONFLICT
MIGRATION_CONFLICT
AI_FAILURE
POLICY_DENIED
UNKNOWN
This supports intelligent retries and user-facing diagnostics.
73. AI Failure Behavior
AI unavailability must not stop deterministic mail processing.
If the model provider fails:
Rules continue.
Provider synchronization continues.
No destructive fallback occurs.
Unclassified messages remain visible.
Messages may enter Review.
74. Provider Failure Behavior
One provider failing should not disable the application.
Example:
Gmail unavailable
Microsoft:
Continue normally
Gmail:
Display stale status
Queue safe retries
Do not imply zero new messages
75. Rule Engine Failure Behavior
If rule evaluation fails:
Do not execute partial destructive actions.
Leave message visible.
Record error.
Retry if safe.
76. Application Authentication
The Inbox Agent itself requires authenticated user access.
Initial deployment may be single-user, but architecture should not assume:
No authentication is necessary.
The system should support a strong identity provider and secure session management.
77. Single-User Initial Design
The first deployment may optimize for one user.
However, primary entities should still include ownership boundaries.
Example:
user_id
on:
mail_accounts
rules
projects
settings
approvals
This prevents major redesign if additional authorized family or administrative users are later introduced.
78. Roles
Initial roles may simply be:
OWNER
Future:
OWNER
ADMIN
VIEWER
Multi-user functionality is not required for initial scope.
79. Deployment
The application should support cloud deployment.
Expected components may include:
Next.js application
PostgreSQL database
Background job infrastructure
Webhook endpoints
Encrypted secret management
AI provider integration
Google Pub/Sub integration
The deployment platform must support externally reachable secure HTTPS endpoints for provider notifications.
80. Vercel Compatibility
The architecture may be deployed using Vercel for the Next.js application.
However, long-running or durable processes must not depend on a single web request remaining active.
Background work should use infrastructure appropriate for durable execution.
The architecture must not assume serverless request duration is sufficient for:
Mailbox migration
Large discovery
Bulk classification
Reconciliation
81. Environments
At minimum:
LOCAL
PREVIEW / DEVELOPMENT
PRODUCTION
Provider OAuth redirect URIs and webhook endpoints must be environment-aware.
Production credentials must never be used in local development except through deliberate secure configuration.
82. Local Development
Cursor-based local development should support:
Local application
Test database
Provider sandbox/test identities where practical
Mock provider adapters
Recorded non-sensitive fixtures
Developers should not require access to the user's entire live mailbox to test every feature.
83. Provider Mocking
Each provider adapter should implement a mock or test implementation.
Required scenarios include:
New message
Message update
Move
Archive
Authorization failure
Rate limit
Duplicate notification
Malformed message
Provider timeout
This is especially important for reliable agent and rule testing.
84. Test Fixtures
Production email content should not be committed into test fixtures.
Synthetic messages should represent:
Personal email
Professional request
Receipt
Travel confirmation
Failed deployment
Security warning
Newsletter
Promotion
85. Rule Regression Testing
Approved rules should be testable against historical/synthetic samples.
A rule modification should identify whether previously known examples change outcome.
This allows regression protection for mailbox behavior.
86. AI Evaluation Dataset
User corrections should eventually create an evaluation dataset.
Examples:
Message features
Expected classification
Expected attention state
Expected priority
Expected identity
The dataset should be used to measure agent quality before changing models or prompts.
87. Data Retention
The application should define separate retention policies for:
Provider message metadata
AI summaries
Audit events
AI input/output traces
Migration logs
Temporary body caches
Attachment caches
Audit history should have longer retention than transient AI processing data.
88. Temporary Content
Temporary full-message content fetched for classification should be discarded after processing unless explicitly required for:
Search
Caching
Migration
Audit evidence
The default should favor minimal duplication.
89. Native Provider Rules
The application may inspect or manage native provider rules where APIs allow, but the Inbox Agent rule engine should remain conceptually separate.
Reasons:
Cross-provider behavior
Central audit
Unified management
Rule learning
Provider portability
Native rules may be used for provider-side optimization later.
90. Rule Source of Truth
Default:
Inbox Agent database
=
Source of truth for Inbox Agent rules
If rules are mirrored into Microsoft or Gmail provider settings, synchronization state must be tracked explicitly.
91. Search Index Decision
A dedicated search index should not be mandatory for the first implementation.
Start with:
Provider search
+
PostgreSQL metadata queries
Evaluate a separate search/vector index only if required by:
Performance
Semantic retrieval
Large historical corpus
Attachment content search
92. Embeddings
Embeddings may be useful later for:
Semantic message search
Similar sender behavior
Folder similarity analysis
Project inference
Related-thread discovery
Embeddings are not required for deterministic mail management.
They should not become a foundational dependency without demonstrated need.
93. Caching
Caching may be used for:
Mailbox profile
Folder inventory
Message summaries
Thread summaries
Provider capabilities
Cache invalidation should use provider event/sync information where possible.
94. Rate Limits
Each provider adapter must centrally manage:
Rate limits
Retry-after headers
Backoff
Concurrency
Batch sizes
Agent-generated operations must not independently flood provider APIs.
95. Bulk Operations
Bulk operations must be chunked.
Example:
Archive 10,000 messages
should become multiple provider-safe jobs rather than one request or one transaction.
Progress must be observable.
96. Transaction Boundaries
Provider mutations and local database updates cannot be assumed to share one atomic transaction.
The system must support eventual consistency.
Pattern:
Create intended action
Execute provider action
Confirm provider result
Update local state
Write audit result
Failures between steps must be recoverable.
97. Outbox / Command Pattern
High-value mailbox mutations should use durable commands.
Example:
MailCommand
ARCHIVE
message_id
requested_by
status
provider_result
This prevents UI or AI calls from directly mutating providers without tracking.
98. Reconciliation Jobs
Periodic reconciliation should compare local state with provider state.
Purpose:
Detect manual changes in Outlook/Gmail
Detect missed webhook events
Detect expired subscriptions
Correct drift
The system should assume users may still use traditional mail clients.
99. Client Independence Requirement
Manual actions performed outside Inbox Agent must eventually synchronize back.
Examples:
User reads email in Outlook
User moves message in webmail
User labels message in Gmail
Inbox Agent should reconcile and update its model.
100. Calendar Integration Boundary
Calendar intelligence is a future module.
Potential connectors:
iCloud shared calendars
Microsoft calendar
Initial architecture should expose an interface that could later answer:
Does this message correspond to an existing event?
Is this travel date on the calendar?
Has this meeting already been scheduled?
But calendar integration should not block the mail-management MVP.
101. Contacts Integration Boundary
Contacts remain primarily in iCloud.
Future contact adapter responsibilities may include:
Known sender identification
Relationship hints
Name normalization
Preferred identity
The mail system should accept contact signals but not require local duplication of the entire contact database.
102. Security Acceptance Criteria
The architecture is acceptable only if:
- Provider passwords are never stored where OAuth can be used.
- OAuth tokens are encrypted server-side.
- Secrets are not exposed to the client.
- AI models never receive OAuth tokens.
- AI tool calls pass through an authorization layer.
- Email content is treated as untrusted input.
- Prompt injection in email cannot directly trigger provider actions.
- Sending and permanent deletion remain protected capabilities.
- Every mutation is auditable.
- High-risk operations require approval.
- Provider failure cannot cause destructive fallback behavior.
103. Integration Acceptance Criteria
The architecture is acceptable when:
- Microsoft personal mail can connect independently.
- Microsoft 365 professional mail can connect independently.
jason@jasonkoch.aican be recognized as a delivered identity within the professional mailbox.- Both Gmail mailboxes can connect independently.
- Gmail mailbox changes can be processed incrementally.
- iCloud mail can be inventoried without modifying it.
- Provider differences are hidden behind adapter interfaces.
- One provider outage does not halt the remaining system.
- All mailboxes expose health and synchronization status.
- Historical mail migration can operate independently from real-time mail processing.
104. Architectural Decisions
The following are current preferred decisions:
Application:
Next.js + TypeScript
Canonical application data:
Relational database / PostgreSQL
Microsoft mail:
Microsoft Graph
Gmail:
Gmail API
iCloud mail:
Read-oriented iCloud/IMAP adapter initially
Microsoft synchronization:
Graph change notifications + delta synchronization
Gmail synchronization:
Gmail watch + Pub/Sub + history synchronization
AI:
Tool-based orchestration behind policy gateway
Rules:
Structured deterministic rule engine
Mail body:
Provider remains source of truth by default
Metadata:
Application database is authoritative
Historical migration:
Separate durable workflow
Permanent deletion:
Not autonomous
Sending:
Not autonomous initially
Contacts:
Remain iCloud
Shared family calendars:
Remain iCloud
Desktop mail client:
Not architecturally significant
105. Open Technical Decisions
The following should remain explicit architectural investigation items rather than assumptions:
Exact PostgreSQL hosting platform
Exact durable job/orchestration technology
Exact AI model/provider strategy
Exact encrypted OAuth token storage mechanism
Exact method for importing historical messages into Microsoft while maximizing original metadata preservation
Whether Microsoft categories should mirror selected agent classifications
Whether Gmail labels should mirror selected agent classifications
Whether full message bodies require any persistent local caching
Whether semantic/vector search is needed after initial implementation
Exact iCloud authorization approach supported by the final connector implementation
Whether contact integration belongs in the first operational release
These decisions should be resolved by implementation spikes or Charter-generated planning work rather than guessed in advance.
106. Core Architectural Principle
The system should maintain the following separation:
PROVIDER
Where the email physically lives
IDENTITY
Which address the sender intended to reach
MESSAGE
What was actually sent
CLASSIFICATION
What the email means
ATTENTION
What Jason needs to do
RULE
Known deterministic behavior
AI
Reasoning where deterministic logic is insufficient
POLICY
What the system is authorized to do
AUDIT
What actually happened
No one layer should be allowed to silently substitute for another.
