Inbox Agent Deployment and Runtime Architecture Specification
1. Purpose
This document defines the deployment topology, runtime components, environment strategy, infrastructure boundaries, background-processing architecture, secret management, network controls, security isolation, observability, scaling, backup, disaster recovery, and release requirements for the Inbox Agent platform.
The architecture should support:
- Initial web deployment
- Future native iOS clients
- Microsoft Graph integration
- Gmail API integration
- iCloud mail integration
- Durable background work
- Security scanning and quarantine
- AI processing
- Historical migrations
- Provider webhooks
- Development and preview environments
- Safe production operations
The deployment architecture should remain practical for an initial single-user system while avoiding choices that would prevent later growth.
2. Deployment Philosophy
The initial platform should favor:
MODULAR APPLICATION
+
MANAGED INFRASTRUCTURE
+
DURABLE BACKGROUND PROCESSING
+
STRONG SECURITY BOUNDARIES
over premature distributed microservices.
The goal is to preserve logical service boundaries without creating unnecessary operational complexity.
3. Initial Logical Deployment
Recommended deployment shape:
Internet
│
▼
┌─────────────────┐
│ Web / API Edge │
│ Next.js │
└────────┬────────┘
│
┌─────────┴──────────┐
│ │
▼ ▼
PostgreSQL Durable Queue
│ │
│ ▼
│ Background Workers
│ │
│ ┌───────────┼────────────┐
│ │ │ │
▼ ▼ ▼ ▼
Audit Sync Security AI / Jobs
Workers
External integrations:
Microsoft Graph
Gmail API
Google Pub/Sub
iCloud IMAP
AI Model Provider
Security / Reputation Services
Future Push Notification Service
4. Initial Technology Direction
Recommended initial application stack:
Web / API:
Next.js
TypeScript
Database:
PostgreSQL
Background Processing:
Durable job / queue platform
Frontend:
React
Provider Integration:
Microsoft Graph
Gmail API
iCloud IMAP initially
AI:
Provider abstraction layer
Deployment:
Cloud-hosted
Vercel-compatible web tier
The exact hosting providers for PostgreSQL, workers, queues, and secret storage remain implementation decisions.
5. Vercel Role
Vercel is a reasonable deployment target for:
Next.js application
Web UI
Application API
OAuth callbacks
Provider webhook ingress
Lightweight synchronous services
It should not be assumed to be the only runtime environment.
Long-running work should not depend on a single serverless request remaining alive.
6. Work That Should Not Depend on Web Requests
Examples:
Historical mailbox synchronization
Migration
Bulk archive operations
Security scanning
Attachment inspection
AI classification backlog
Rule simulation
Reconciliation
Subscription renewal
Large search operations
Duplicate analysis
These require durable background execution.
7. Runtime Components
Recommended logical runtime components:
Web Application
Application API
Webhook Receivers
Background Job Coordinator
Synchronization Workers
Command Workers
Security Workers
AI Workers
Migration Workers
Reconciliation Workers
Scheduled Jobs
PostgreSQL
Queue / Event Infrastructure
Secret Management
Observability Platform
Not every logical component requires its own deployment initially.
8. Web Application
Responsibilities:
Authentication
Dashboard
Needs Me
Conversation UI
Search
Rules
Identity Hygiene
Security Review
Migration UI
Provider Health
Settings
Audit / Activity
The web application consumes the application API.
It must not directly call mail providers.
9. Application API
Responsibilities:
Client contracts
Domain queries
Command submission
Authorization
Policy checks
Approval workflows
Agent requests
Search orchestration
Provider-health queries
The API should perform only bounded synchronous work.
10. Webhook Receivers
Provider webhook endpoints should be deployed as highly available lightweight endpoints.
Examples:
Microsoft Graph webhook
Google Pub/Sub webhook / receiver
Future push/event integrations
Webhook execution:
Validate
Identify connection
Persist event
Queue work
Acknowledge
No long-running mailbox processing should occur inside webhook requests.
11. Durable Queue
A durable queue is required.
The queue must support:
Persistence
Retries
Delayed execution
Visibility timeout / leases
Dead-letter handling
Priority
Concurrency control
Idempotency
Observability
12. Queue Technology
The exact queue technology may be selected later.
Acceptable architectural models include:
Managed task queue
Managed message queue
PostgreSQL-backed durable jobs
Workflow orchestration platform
The implementation should avoid an in-memory-only queue.
13. Queue Categories
Logical queues may include:
interactive
security
active-mail
sync
ai
background
migration
maintenance
These may initially map to fewer physical queues.
14. Queue Priority
Recommended priority:
P0 — Security / critical user action
P1 — Interactive commands
P2 — Incoming active mail
P3 — AI / normal processing
P4 — Background maintenance
P5 — Historical migration
Large migration jobs must not delay interactive use.
15. Background Workers
Workers should be stateless wherever practical.
A worker should:
Claim job
Load authoritative state
Perform bounded work
Persist outcome
Emit event
Release job
State should not exist only in worker memory.
16. Worker Types
Initial worker types may include:
ProviderSyncWorker
MailProcessingWorker
CommandWorker
SecurityWorker
AIWorker
MigrationWorker
ReconciliationWorker
MaintenanceWorker
These can share executable code while having different queue subscriptions.
17. Sync Worker
Responsibilities:
Graph delta processing
Gmail history processing
IMAP incremental sync
Full resync
Folder inventory
Sent-mail discovery
Draft discovery
18. Command Worker
Responsibilities:
Archive
Move
Mark read/unread
Apply categories/labels
Create provider drafts
Future send operations
Future approved deletion
It must check:
Authorization
Policy
Approval
Provider capability
Current state
Idempotency
before mutation.
19. Security Worker
Responsibilities may include:
HTML sanitization
URL extraction
URL inspection
Header analysis
Attachment metadata analysis
File-type validation
Hashing
Security scanner dispatch
Quarantine decisions
Security workloads should be isolated more strongly than normal mail processing when parsing untrusted files.
20. Security Worker Isolation
Attachment parsers and scanners should ideally run:
Without provider credentials
Without database superuser access
Without application signing secrets
With restricted filesystem
With restricted network access
With CPU/memory/time limits
A compromised parser should not provide access to the Inbox Agent platform.
21. Deep Security Scanning
Future sandbox analysis should run in separate disposable infrastructure.
It should never run:
Inside the primary web process
Inside the main application container
On the user's Mac
22. AI Worker
Responsibilities:
Classification
Summarization
Intent interpretation
Draft generation
Rule recommendations
Extraction
AI workers should receive only necessary context.
They should not receive provider credentials.
23. Migration Worker
Responsibilities:
Read source
Normalize
Duplicate analysis
Route destination
Import
Validate
Reconcile
Migration should use lower-priority queues than active mail.
24. Reconciliation Worker
Responsibilities:
Compare provider and canonical state
Detect missing events
Detect client-side changes
Refresh sent state
Repair stale checkpoints
Detect provider drift
25. Scheduled Processing
Scheduled jobs are needed for:
Subscription renewal
Gmail watch renewal
Reconciliation
Stale Waiting review
Retention cleanup
Temporary body-cache cleanup
Provider-health checks
Security review maintenance
Daily Brief generation
26. Scheduler Requirements
Scheduled jobs must be:
Durable
Observable
Idempotent
Timezone-aware where user-facing
Failure should be visible.
27. PostgreSQL
PostgreSQL is the recommended primary relational store.
It should contain:
Users
Mail accounts
Mail identities
Provider metadata
Canonical message metadata
Conversations
Classifications
Rules
Corrections
Approvals
Commands
Sync checkpoints
Jobs
Migration state
Security findings
Audit
28. Database Hosting
Database hosting should provide:
Encrypted storage
TLS connectivity
Automated backups
Point-in-time recovery
High availability appropriate to scale
Connection pooling
Monitoring
Specific provider remains open.
29. Database Connection Pooling
Serverless and worker environments can create excessive PostgreSQL connections.
The deployment should use:
Connection pooling
Managed pooler
or equivalent
where required.
30. Database Network Exposure
PostgreSQL should not be publicly exposed without strong access controls.
Preferred access:
Private network
Trusted application services
Encrypted connections
Restricted credentials
31. Database Credentials
Use separate credentials where practical for:
Application API
Workers
Migrations
Read-only diagnostics
Administrative schema management
Do not run the production application using a database superuser.
32. Database Migration Strategy
Schema changes should be managed through version-controlled migrations.
Production schema changes should be:
Repeatable
Reviewed
Environment tested
Rollback-aware
33. Backward-Compatible Migrations
Because workers may overlap deployments, schema changes should favor:
Expand
Deploy
Migrate
Contract
rather than destructive one-step changes.
34. Example Safe Schema Change
Instead of:
Rename column immediately
prefer:
Add new column
Write both temporarily
Backfill
Switch reads
Remove old column later
when production continuity matters.
35. Message Body Storage
Full email bodies should not automatically live permanently in PostgreSQL.
Preferred model:
Provider is authoritative
Metadata stored locally
Body retrieved on demand
Temporary encrypted cache optional
36. Object Storage
Object storage may be used for:
Temporary body cache
Migration staging
Security-scan staging
Temporary attachment analysis
Generated exports
It should not become an uncontrolled permanent copy of the mailbox.
37. Object Storage Security
Requirements:
Private buckets
Encryption
Short-lived access URLs
Retention policies
Lifecycle cleanup
No public objects
38. Security Scan Staging
Untrusted attachments staged for analysis should use a dedicated security storage boundary.
They should not share the same access policies as:
Application exports
User-uploaded configuration
General application assets
39. File Cleanup
Temporary files must have explicit cleanup.
Examples:
Security scan file:
Delete after analysis plus diagnostic retention window
Temporary mail body:
Delete after cache expiration
Export:
Delete after configured expiration
40. Secret Management
Secrets should be stored through a dedicated secret-management mechanism.
Examples of secrets:
OAuth refresh tokens
OAuth client secrets
App-specific passwords
Webhook secrets
AI API keys
Encryption keys
Database credentials
41. Secret Separation
Environment secrets must be isolated:
LOCAL
PREVIEW / DEVELOPMENT
PRODUCTION
Production credentials must never be copied into preview by default.
42. Provider OAuth Applications
Where possible, production and development should use separate OAuth application registrations or configurations.
Benefits:
Separate callback URLs
Separate permissions
Reduced accidental production access
Safer testing
43. Local Development Secrets
Local secrets should remain outside Git.
Recommended mechanisms:
Local environment file ignored by Git
Local secret manager
Development OAuth credentials
44. Production Secrets
Production secrets should be:
Encrypted
Access-controlled
Auditable where possible
Rotatable
Never exposed to browser clients
45. Token Encryption
Stored provider refresh tokens require application-level protection beyond simple database access.
Potential pattern:
Database stores encrypted token
Encryption key managed separately
Application decrypts only when required
46. Key Rotation
The architecture should permit encryption-key rotation without forcing every provider connection to be manually recreated.
47. Network Architecture
The deployment should distinguish:
Public ingress
Application services
Background services
Data services
Security analysis services
External provider egress
48. Public Ingress
Only required endpoints should be Internet-accessible.
Examples:
Web UI
Application API
OAuth callbacks
Validated provider webhooks
Database and workers should not require public ingress.
49. Egress Controls
Security workers performing URL inspection should have stronger egress controls than ordinary application workers.
This helps mitigate:
SSRF
Malicious redirects
Internal network probing
Cloud metadata access
50. URL Inspection Egress
URL inspection should block or restrict access to:
localhost
127.0.0.0/8
private IPv4 networks
link-local addresses
private IPv6 ranges
cloud metadata endpoints
internal service hostnames
unless explicitly needed.
51. Security Sandbox Network
Future attachment sandboxing should default to:
No network
or highly controlled monitored network access.
52. Content Delivery
Application static assets may use normal CDN behavior.
Email content itself should not become a publicly cached CDN asset.
53. Authentication Runtime
Application authentication should be handled separately from provider OAuth.
Sessions should be validated at the application edge/API.
54. Native iOS Authentication
A future iOS client should authenticate to Inbox Agent.
It should not require storing Graph/Gmail refresh tokens on-device under the default architecture.
55. API Gateway / Edge Controls
The public API layer should provide or support:
TLS
Rate limiting
Request-size limits
Authentication
Request validation
Security headers
56. Request Size Limits
Email and attachment content should not be blindly accepted through general API endpoints.
Large provider content should flow through controlled backend-provider operations.
57. Webhook Request Limits
Webhook endpoints should have bounded payload sizes and strict provider-specific validation.
58. Environments
Required environments:
LOCAL
PREVIEW / DEVELOPMENT
PRODUCTION
A future dedicated test/staging environment may be added.
59. LOCAL
Purpose:
Developer productivity
Unit testing
Integration testing
Mock providers
Synthetic mail
Default local mode should not require access to live personal mailboxes.
60. PREVIEW / DEVELOPMENT
Purpose:
Pull-request validation
Shared integration testing
UI review
OAuth callback testing
Provider-adapter testing
Production mail mutations should be disabled by default.
61. PRODUCTION
Purpose:
Real mailboxes
Real provider credentials
Real automation
Historical migration
Security enforcement
Production is the only environment allowed to operate normally against the canonical mailbox estate unless explicitly configured otherwise.
62. Preview Environment Safety
Preview deployments must not automatically inherit:
Production OAuth credentials
Production database
Production queue
Production provider webhook secrets
Production storage
63. Environment Identity
Every process should know its environment.
Environment should be included in:
Logs
Metrics
Audit diagnostics
Queue/job metadata where relevant
64. Test Mailboxes
If live-provider testing is required, use dedicated development accounts where practical.
Examples:
Development Gmail account
Development Microsoft account
Test domain mailbox
Avoid testing destructive operations on real personal mail.
65. Provider Mocks
Provider adapters must have mock implementations.
Examples:
MockMicrosoftAdapter
MockGmailAdapter
MockICloudAdapter
They should simulate:
Incoming mail
Move
Archive
Read/unread
Draft
Auth expiry
Rate limit
Timeout
Duplicate event
66. Synthetic Mail Dataset
Maintain a synthetic test corpus containing:
Personal human mail
Professional mail
Receipts
Travel confirmations
Marketing
Newsletters
System success
System failure
Security alerts
Phishing
Spoofing
Suspicious URLs
Macro attachments
Prompt injection
Malformed mail
67. Deployment Pipeline
Recommended deployment lifecycle:
Feature Branch
↓
Pull Request
↓
Automated Tests
↓
Preview Deployment
↓
Review
↓
Merge
↓
Production Deployment
↓
Smoke Tests
↓
Monitoring
68. Deployment Gates
Production deployment should require passing:
Build
Lint
Type checks
Unit tests
Contract tests
Database migration validation
Security-critical tests
Additional integration tests may run where practical.
69. Database Migration Gate
Production deployment should fail or stop safely if required database migrations cannot be applied.
Do not allow partially incompatible application/database versions without a defined compatibility strategy.
70. Worker Deployment
Web and worker versions should be compatible during rolling deployment.
This reinforces the need for:
Versioned events
Backward-compatible schemas
Versioned job payloads
71. Event Contract Compatibility
A newly deployed worker must not assume every queued event was created by the same application version.
72. Feature Flags
Feature flags may control risky or incomplete capabilities.
Examples:
ENABLE_GMAIL_WRITES
ENABLE_ICLOUD_MIGRATION
ENABLE_AI_DRAFTING
ENABLE_SECURITY_DEEP_SCAN
ENABLE_SEND
ENABLE_DELETE
73. Security Feature Flags
Security flags must default conservatively.
A configuration failure should not silently disable quarantine or sanitization.
74. Kill Switches
Operational kill switches should exist for:
All provider mutations
Specific mailbox mutations
AI operations
Migration
Sending
Deletion
Security release automation
75. Global Automation Pause
The runtime should support immediate:
PAUSE AUTOMATION
without shutting down:
Mail synchronization
Search
Read-only access
Security inspection
Audit
76. Per-Mailbox Pause
A problem affecting one mailbox should allow mutation processing to stop only for that mailbox.
77. Provider Circuit Breaker
Repeated provider failures should trigger temporary circuit-breaking.
Example:
Gmail returns repeated 503
↓
Pause active requests briefly
↓
Queue work
↓
Retry after backoff
78. AI Circuit Breaker
If AI requests fail repeatedly:
Pause model requests
Keep deterministic processing alive
Queue unresolved classification work
79. Security Scanner Circuit Breaker
If a deep scanner fails:
Hold affected attachments
Continue safe metadata processing
Surface scanner-health issue
Never fail open by marking content safe.
80. Health Endpoints
Runtime components should expose health information.
Conceptual checks:
Process alive
Database reachable
Queue reachable
Secrets available
Required configuration valid
External provider availability should not necessarily make the whole application unhealthy.
81. Readiness vs Liveness
Distinguish:
Liveness:
Should this process be restarted?
Readiness:
Can this process accept new work?
82. Observability
The deployment requires centralized:
Logs
Metrics
Traces / correlation
Alerts
Provider health
Job monitoring
83. Structured Logging
Logs should use structured fields such as:
timestamp
environment
service
event_type
correlation_id
job_id
command_id
mail_account_id
provider
error_code
duration
84. Logging Privacy
Avoid normal logging of:
Full email bodies
Raw email HTML
Attachment contents
OAuth tokens
Full authentication headers
Sensitive contact data
85. Message Identifiers in Logs
Prefer internal IDs over subjects or addresses where possible.
Example:
message_id = UUID
rather than logging:
subject = Bank Account Password Reset
86. Distributed Tracing
Where supported, traces should connect:
API request
Queue submission
Worker execution
Provider call
Database operation
Audit event
using correlation IDs.
87. Core Metrics
Useful runtime metrics:
API request count
API latency
API error rate
Queue depth
Queue age
Worker throughput
Worker error rate
Provider request latency
Provider error rate
Provider rate limits
Sync lag
Classification backlog
Security backlog
Migration backlog
Command success/failure
88. Security Metrics
Track:
Messages inspected
Messages quarantined
Security findings
Attachments held
Scanner failures
Sanitizer failures
Release count
False-positive correction count
without exposing message contents.
89. AI Metrics
Track:
Requests
Latency
Failures
Schema-validation failures
Token usage
Estimated cost where available
Classification confidence
Fallback frequency
90. Rule Metrics
Track:
Executions
Matches
Undo rate
Correction rate
Rule failures
Rule auto-pauses
91. Migration Metrics
Track:
Items processed
Throughput
Duplicates
Conflicts
Failures
Remaining
Estimated source volume
92. Alerts
Operational alerts should exist for:
Database unavailable
Queue unavailable
Provider auth expired
Webhook/watch expiration
Subscription renewal failure
Sync backlog excessive
Dead-letter growth
Repeated command failure
Security scanner unavailable
Sanitizer failure
Migration failure
93. Alert Severity
Not every operational issue should page immediately.
Suggested classes:
INFO
WARNING
HIGH
CRITICAL
Critical should be reserved for issues affecting:
Security
Data integrity
Credential exposure
Widespread production outage
Unexpected destructive mutation
94. Provider Health Dashboard
The admin UI should show:
Mailbox
Provider
Connection state
Authorization
Last successful sync
Push/watch state
Expiration
Backlog
Last error
95. Worker Dashboard
Administrative diagnostics should expose:
Queue depth
Running jobs
Failed jobs
Retries
Dead-letter items
Worker availability
96. Security Operations Dashboard
Security diagnostics should show:
Quarantine backlog
Scanner health
Sanitizer health
Held attachments
Recent high-severity findings
97. Scaling Strategy
The initial system may serve one user but should scale horizontally where practical.
Good horizontal candidates:
API instances
Sync workers
AI workers
Security workers
Migration workers
98. Queue-Based Scaling
Worker counts may scale based on:
Queue depth
Queue age
CPU
Memory
Provider limits
Provider rate limits must constrain scaling.
99. Per-Provider Concurrency
Each provider should have configurable concurrency limits.
Example:
Microsoft:
N concurrent requests
Gmail:
M concurrent requests
iCloud:
Lower concurrency
100. Per-Mailbox Concurrency
Some commands should serialize per mailbox or message to avoid conflicting state changes.
101. Security Worker Scaling
Security parsing workloads may require separate CPU/memory scaling from normal application work.
102. Migration Scaling
Migration can be parallelized in batches but must respect:
Source-provider rate limits
Target-provider rate limits
Duplicate consistency
Reconciliation integrity
103. AI Scaling
AI work should be throttled by:
Budget
Provider rate limits
Queue priority
Interactive vs background classification
104. Cost Controls
Because this begins as a personal platform, infrastructure costs should remain visible.
Track costs associated with:
AI
Security scanning
Sandboxing
Database
Storage
Worker compute
Provider traffic where applicable
105. AI Cost Policy
Do not send routine deterministic mail to expensive models.
Use:
Rules first
Cheap classification where adequate
High-capability model only when justified
106. Security Cost Policy
Historical attachments should not all undergo expensive deep sandbox analysis automatically.
Use:
Risk-based escalation
On-demand analysis
Metadata/static inspection first
107. Storage Cost Policy
Avoid unnecessary permanent duplication of:
Email bodies
Attachments
Raw provider payloads
Security staging files
108. Backup Strategy
The canonical PostgreSQL database requires automated backups.
Required capabilities:
Daily backups
Point-in-time recovery where supported
Retention policy
Restore testing
109. What Must Be Backed Up
Important data includes:
Configuration
Rules
Corrections
Classifications
Attention state
Migration history
Audit
Security findings
Provider metadata
Sync state
110. What May Not Need Backup
Temporary caches such as:
Short-lived message body cache
Security-scan temporary files
Regenerable search cache
may not require durable backup.
111. Secret Backup
Secret recovery must be planned carefully.
Losing encrypted provider tokens may require reconnecting mailboxes, which is preferable to insecure secret backup.
112. Restore Testing
A backup is not considered reliable until restore procedures are periodically tested.
113. Disaster Recovery
Disaster-recovery priorities:
1. Protect secrets
2. Protect audit/configuration
3. Restore canonical database
4. Restore provider synchronization
5. Rebuild derived state
6. Resume automation cautiously
114. Recovery Mode
After significant restore, the system should enter conservative mode.
Example:
Provider mutations paused
↓
Run reconciliation
↓
Validate checkpoints
↓
Confirm rules
↓
Resume automation
115. Provider as Recovery Source
Because providers remain authoritative for full email content, much message content can be rediscovered.
Application-specific state cannot.
Examples requiring database recovery:
Attention state
Learned preferences
Rules
Audit
Migration provenance
User corrections
Security decisions
116. Recovery Point Objective
Exact RPO may be established later.
For a personal production platform, loss of recent rules/audit/corrections should still be minimized.
117. Recovery Time Objective
Exact RTO may also be established later.
The architecture should prioritize safe recovery over immediate automation.
118. Deployment Rollback
Application releases should support rollback.
Rollback must consider:
Application version
Worker version
Database schema
Event version
119. Database Rollback
Avoid relying on destructive down-migrations in production.
Prefer forward-fix where schema contains new data that older versions cannot safely understand.
120. Worker Rollback
Old workers may still encounter new event types.
Unknown events should fail safely rather than be misprocessed.
121. Feature Rollback
Risky features should be disable-able independently through feature flags or kill switches.
122. Production Smoke Tests
After deployment verify:
Web app loads
Authentication works
Database accessible
Queue accepts work
Worker processes job
Provider health readable
No unexpected mutation
Security sanitizer functional
123. Provider Smoke Tests
Provider smoke tests should favor non-destructive operations:
Read mailbox profile
Read latest metadata
Read folder inventory
Check sync checkpoint
Do not send/delete mail as a routine deployment smoke test.
124. Security Smoke Tests
Use synthetic fixtures to verify:
Unsafe HTML sanitized
Remote content blocked
Suspicious URL mediated
Quarantine state works
125. Deployment Audit
Production deployments should record:
Version
Commit
Deployment time
Environment
Schema version
Feature flags
126. Application Version
The application should expose its build/version information through diagnostics.
A version model such as:
major.minor.patch/build
may be used.
127. Runtime Configuration
Configuration categories:
Provider configuration
Queue limits
AI models
Security policies
Feature flags
Retention
Rate limits
Automation ceilings
128. Configuration Storage
Configuration should be divided appropriately between:
Environment configuration
Secret store
Database-managed application settings
Version-controlled defaults
Do not place every setting in environment variables.
129. Security Policy Configuration
Foundational security policy should be version-controlled where practical.
Examples:
Allowed schemes
Blocked network ranges
Attachment size limits
Archive recursion limits
HTML sanitizer policy
130. User-Level Security Preferences
User preferences may control permitted options such as:
Remote image behavior
Trusted sender rules
Quarantine thresholds
but cannot exceed hard platform security ceilings.
131. Rate-Limit Configuration
Provider-specific limits should be centrally configurable.
They should not be hardcoded throughout adapter code.
132. Timeout Configuration
External calls should use explicit timeouts.
Examples:
Provider API
AI API
URL inspection
Attachment scanner
Database
No worker should wait indefinitely.
133. Retry Configuration
Retries should be centrally defined by operation class.
Example:
Provider read:
multiple transient retries
Send:
more conservative retry due to duplicate-send risk
Delete:
strict idempotency
AI:
bounded retry
Security scan:
hold if unavailable
134. Sending Safety
Future sending deserves special runtime handling.
A timed-out send request may have succeeded externally.
Before retrying:
Check provider state
Use idempotency strategy
Avoid duplicate send
135. Migration Safety
Migration jobs should checkpoint after batches.
A worker restart should continue from last durable state, not restart the entire migration.
136. Provider Token Refresh
Token refresh should be centralized.
Workers should not independently implement inconsistent refresh logic.
137. Provider Connection Locking
Concurrent token refresh attempts for the same provider connection should be coordinated where necessary.
138. Webhook Secret Rotation
Webhook secrets or validation credentials should support rotation without losing notifications.
139. Dependency Management
Production dependencies should be version-pinned appropriately.
Security-sensitive libraries include:
HTML sanitizer
MIME parser
Archive parser
OAuth libraries
Cryptographic libraries
140. Dependency Security
The deployment pipeline should include automated dependency vulnerability checks.
High-risk dependency findings should be surfaced before production deployment where practical.
141. Containerization
Background workers may be containerized even if the web tier is serverless.
Containers are particularly useful for:
Security parsers
File scanners
Long-running workers
Special native dependencies
142. Container Security
Worker containers should use:
Minimal base images
Non-root execution
Read-only filesystem where possible
Limited capabilities
Resource limits
143. Scanner Containers
Security-scanner containers should receive stronger isolation and no unnecessary credentials.
144. Infrastructure as Code
Production infrastructure should eventually be represented as code.
Scope may include:
Database configuration
Queues
Worker services
Secrets references
Storage
Monitoring
Network policy
145. Infrastructure Drift
Infrastructure changes should be reviewed similarly to application changes.
Avoid undocumented manual production modifications.
146. Domain Configuration vs Infrastructure
Do not mix:
Rule definitions
Mailbox identity roles
Attention settings
with infrastructure deployment code.
These belong in application data.
147. Production Data Access
Direct production database access should be limited.
Administrative investigation should prefer application diagnostics and read-only access where possible.
148. Developer Access
Developers/agents should not need production secrets for ordinary implementation work.
149. Agent Development Access
Coding agents should operate against:
Mocks
Synthetic data
Preview environments
rather than production mail.
150. No Production Mail in CI
CI tests must never ingest real production mailbox content.
151. PII in Build Artifacts
Build logs, test artifacts, screenshots, and failure dumps should not contain real email content.
152. Environment Data Separation
Production database copies should not be casually cloned into development.
If realistic test data is ever needed:
Anonymize
Redact
or generate synthetic fixtures
153. Release Channels
Potential release channels:
Preview
Production
A later beta/native-client release channel may be added.
154. Native iOS Deployment
Future iOS architecture should consist of:
Native application
↓
Inbox Agent API
↓
Existing backend
The mobile application should not require deployment changes to provider integrations.
155. Mobile Push Infrastructure
Future push support may add:
Application notification service
↓
Apple Push Notification Service
↓
iOS client
The backend remains responsible for deciding whether a notification is warranted.
156. Custom Web Mail Client
If Inbox Agent evolves into a full mail client, the deployment topology remains valid.
Additional functions may include:
Compose
Reply
Forward
Attachment upload
Draft sync
Sent mail
Folder browsing
These use the same API/command/provider layers.
157. Future Contact Runtime
Contact consolidation can later add:
Contact sync workers
Deduplication workers
Merge review
Provider contact adapters
without changing mail-provider service boundaries.
158. Future Calendar Runtime
Calendar context may later add:
Read-only calendar adapters
Calendar sync workers
Context linking
without requiring the Inbox Agent to replace Fantastical.
159. Initial Deployment Recommendation
A pragmatic initial production architecture is:
Vercel
- Next.js UI
- Application API
- OAuth callbacks
- Webhook ingress
Managed PostgreSQL
- Canonical application database
Durable Worker Platform
- Sync
- Commands
- AI
- Reconciliation
- Migration
Isolated Security Worker Runtime
- HTML/file/url inspection
- Future scanner integrations
Managed Secret Store
- Provider tokens
- AI keys
- DB credentials
Private Object Storage
- Temporary attachment/body staging
Google Pub/Sub
- Gmail notifications
This is a logical recommendation, not a vendor lock-in requirement.
160. Initial Physical Simplification
The first release does not need:
Ten microservices
Kubernetes
Service mesh
Dedicated event streaming cluster
Separate database per domain
unless implementation requirements later justify them.
161. What Must Be Durable From Day One
The following must not rely solely on serverless-memory execution:
Commands
Migration jobs
Sync checkpoints
Provider notifications
Approvals
Audit events
Security findings
Rule executions
162. What Can Remain Simple Initially
The following may remain straightforward:
Single-user ownership
Single PostgreSQL database
One web application
Shared worker codebase
Basic search
One AI provider abstraction
One primary region
163. Geographic Deployment
A single primary region is reasonable initially.
Choose a region close to:
Primary database
Worker runtime
Major provider APIs where practical
Avoid unnecessary multi-region complexity.
164. Data Residency
If the platform later becomes multi-user/commercial, geographic data residency may become a product requirement.
The initial architecture should avoid unnecessarily scattering mail data across multiple services.
165. High Availability
Initial high availability should focus on managed infrastructure.
Priority:
Database durability
Queue durability
Webhook availability
Application availability
Workers may restart because jobs are durable.
166. Graceful Restart
Workers should support termination signals.
On shutdown:
Finish or checkpoint current work
Stop claiming new work
Release leases safely
167. Queue Lease Expiration
If a worker crashes, the job lease should eventually expire so another worker can retry.
168. Duplicate Side-Effect Protection
Because worker retry is expected, all external mutations require idempotency/reconciliation protections.
169. Maintenance Mode
The application should support maintenance mode for:
Major schema migration
Provider repair
Security incident
Possible behavior:
Read-only UI
Sync optionally active
Mutations paused
170. Security Incident Mode
A stronger emergency mode should allow:
Disable provider mutations
Disable AI
Invalidate sessions
Pause workers
Rotate secrets
Preserve audit
171. Credential Compromise Response
If a provider credential may be compromised:
Disable connection
Revoke token at provider
Rotate application secret if needed
Audit access
Reconnect deliberately
172. AI Credential Compromise
AI API keys should be independently rotatable without affecting mail-provider credentials.
173. Security Scanner Compromise
Security-scanning infrastructure should be replaceable without exposing canonical provider credentials.
174. Data Integrity Checks
Scheduled integrity checks may verify:
Orphaned message references
Invalid identity relationships
Commands missing audit
Migration reconciliation discrepancies
Multiple current rule versions
Invalid current classification states
175. Runtime Invariants
Examples:
Every provider mutation has a MailCommand.
Every executed high-risk command has valid authorization.
Every rule execution references an immutable RuleVersion.
Every migration item belongs to a MigrationRun.
Every provider connection belongs to a MailAccount.
Every quarantined message has security evidence/reason.
Every successful command is auditable.
176. Runtime Acceptance Criteria
The deployment architecture is acceptable when:
- The web application can run independently of long-running workers.
- Long-running jobs survive deployment and process restarts.
- PostgreSQL is the canonical relational store.
- Mailbox provider credentials are stored securely.
- Production secrets are separated from development.
- Provider webhooks perform minimal synchronous work.
- Workers process provider events durably.
- Security parsing can run isolated from the primary application.
- Attachment scanning does not require antivirus on the user's Mac.
- Temporary untrusted files use isolated private storage.
- AI workers never receive provider credentials.
- Production mail is not used in CI.
- Preview environments cannot accidentally mutate production mail.
- Provider mutations can be globally or selectively paused.
- Sending and deletion can be disabled independently.
- Queue backlogs and failures are observable.
- Dead-letter work is inspectable and retryable.
- Database backup and point-in-time recovery are supported.
- Recovery begins conservatively with mutation pause and reconciliation.
- Application and worker versions can overlap safely during deployment.
- Event payloads are versionable.
- Database migrations favor backward compatibility.
- Provider outages are isolated.
- Scanner or AI outages fail safely.
- The architecture supports a future native iOS client without moving provider credentials to the device.
- The architecture supports future contacts/calendar integrations without redesigning the mail runtime.
- Infrastructure remains simple enough for an initial personal deployment.
177. Canonical Runtime Boundary
The deployment should preserve:
EDGE
Accepts trusted application traffic
WEB / API
Implements client-facing domain contracts
QUEUE
Makes work durable
WORKERS
Execute bounded processing
SECURITY RUNTIME
Handles hostile content in isolation
DATABASE
Stores canonical application state
SECRET STORE
Protects credentials
OBJECT STORAGE
Temporarily holds controlled content
PROVIDER ADAPTERS
Communicate with external mail systems
AI GATEWAY
Communicates with model providers
OBSERVABILITY
Explains runtime health
AUDIT
Explains consequential behavior
No deployment convenience should collapse these trust boundaries in a way that gives hostile email content, browser clients, AI models, or security parsers unnecessary access to credentials or provider authority.
