## 1. Expanded Compute Support (Sub-phase 1.1)

- [x] 1.1 P1-01: Python Lambda Subprocess Runner - Implement a Python Lambda handler executor using `asyncio.create_subprocess_exec` with a bootstrap script that reads event from stdin, imports and invokes the handler module, and writes the JSON response to stdout. Support configurable Python executable path (default `python3`). Create `ldk/runtime/python_runner.py` and `ldk/runtime/python_bootstrap.py`.
- [x] 1.2 P1-02: Python debugpy Integration - Extend the Python subprocess runner to optionally attach debugpy for remote debugging when `--inspect` is passed to `ldk dev`. Allocate per-function debug ports starting from a configurable base (default 5678). Display debugpy connection URL at startup. Produce clear error if debugpy is not installed.
- [x] 1.3 P1-03: Lambda Context Object - Implement a Lambda context object (`ldk/runtime/lambda_context.py`) providing `functionName`, `functionVersion`, `memoryLimitInMB`, `logGroupName`, `logStreamName`, `awsRequestId` (UUID per invocation), `invokedFunctionArn`, and `getRemainingTimeInMillis()` backed by a real countdown timer. JSON-serializable for subprocess runners.
- [x] 1.4 P1-04: Timeout Enforcement - Enforce CDK-configured timeout (default 3s) for Lambda invocations using `asyncio.wait_for`. For subprocess runners, send SIGTERM then SIGKILL after 1s grace period. Return `{"errorMessage": "Task timed out after X.XX seconds", "errorType": "TaskTimedOut"}`. Ensure subsequent invocations start cleanly.
- [x] 1.5 P1-05: Environment Variable Resolution - Implement `ldk/runtime/env_resolver.py` to resolve CloudFormation intrinsic functions (`Ref`, `Fn::GetAtt`, `Fn::Join`, `Fn::Sub`, `Fn::Select`) in Lambda environment variables using a `ResourceRegistry` that maps logical IDs to local resource identifiers. Set resolved env vars in both in-process and subprocess runners.

## 2. SQS Provider (Sub-phase 1.2)

- [x] 2.1 P1-06: In-Memory Queue Data Structure - Implement `ldk/providers/sqs/queue.py` with `LocalQueue` class supporting `send_message`, `receive_messages` (with visibility timeout), and `delete_message`. Use `asyncio.Lock` for concurrency safety. Track `ApproximateReceiveCount`, `SentTimestamp`, `MD5OfBody`. Use `time.monotonic()` for visibility timeout tracking.
- [x] 2.2 P1-07: SQS API Endpoints - Implement FastAPI routes (`ldk/providers/sqs/routes.py`) for SendMessage, ReceiveMessage, DeleteMessage actions at `POST /<account>/<queue-name>`. Support `VisibilityTimeout`, `MaxNumberOfMessages` (default 1, max 10), `WaitTimeSeconds` (long-polling with `asyncio.Event`). Return AWS SQS XML response format.
- [x] 2.3 P1-08: SQS Queue Auto-Discovery from CDK - Extend cloud assembly parser to discover `AWS::SQS::Queue` resources and extract `QueueName`, `VisibilityTimeout`, `FifoQueue`, `ContentBasedDeduplication`, `RedrivePolicy`. Create `LocalQueue` instances and register queue URLs in `ResourceRegistry`.
- [x] 2.4 P1-09: Lambda Event Source Mapping for SQS - Implement `ldk/providers/sqs/event_source.py` with `SqsEventSourcePoller` that polls queues and invokes Lambda handlers with SQS event batches. Respect `BatchSize`, delete messages on success, return to queue on failure. Use configurable polling interval (default 1s) with backoff.
- [x] 2.5 P1-10: Dead Letter Queue Support - Implement DLQ routing: parse `RedrivePolicy` from CDK, move messages to DLQ when `ApproximateReceiveCount >= maxReceiveCount`. Resolve DLQ ARN to local queue via `ResourceRegistry`.
- [x] 2.6 P1-11: FIFO Queue Support - Implement `ldk/providers/sqs/fifo_queue.py` with `MessageGroupId`-based ordering (no head-of-line blocking) and `MessageDeduplicationId` deduplication with 5-minute window. Support `ContentBasedDeduplication` via SHA-256 hash.

## 3. S3 Provider (Sub-phase 1.3)

- [x] 3.1 P1-12: Filesystem-Backed Object Storage - Implement `ldk/providers/s3/storage.py` with `LocalBucketStorage` class. Store objects at `<data_dir>/s3/<bucket>/<key>` and metadata at `<data_dir>/s3/.metadata/<bucket>/<key>.json`. Support PutObject, GetObject, DeleteObject, ListObjectsV2. Compute ETag as MD5 hex digest. Use `aiofiles` for async I/O.
- [x] 3.2 P1-13: S3 API Endpoints - Implement FastAPI routes (`ldk/providers/s3/routes.py`) for PUT/GET/DELETE/HEAD `/<bucket>/<key:path>` and GET `/<bucket>?list-type=2`. Return XML responses matching AWS S3 format. Use `StreamingResponse` for GetObject.
- [x] 3.3 P1-14: S3 Bucket Auto-Discovery from CDK - Extend cloud assembly parser to discover `AWS::S3::Bucket` resources, extract `BucketName` (or generate from logical ID), create storage directories, register in `ResourceRegistry`, and extract `NotificationConfiguration` for event wiring.
- [x] 3.4 P1-15: S3 Event Notifications - Implement `ldk/providers/s3/notifications.py` with `NotificationDispatcher`. Fire `ObjectCreated`/`ObjectRemoved` events to Lambda handlers. Evaluate `Filter.S3KeyFilter.FilterRules` (Prefix/Suffix). Dispatch asynchronously via `asyncio.create_task`.
- [x] 3.5 P1-16: Presigned URL Generation and Handling - Implement `ldk/providers/s3/presigned.py` for URL generation and validation. Use HMAC-SHA256 signatures with a local signing key. Support expiration. Add FastAPI routes for presigned URL paths.

## 4. SNS Provider (Sub-phase 1.4)

- [x] 4.1 P1-17: SNS Topic Registry and Publish - Implement `ldk/providers/sns/provider.py` and `ldk/providers/sns/topic.py`. Discover `AWS::SNS::Topic` from CDK, register in `ResourceRegistry`. Implement `publish` with fan-out to all subscribers via `asyncio.create_task`.
- [x] 4.2 P1-18: SNS API Endpoint - Implement `ldk/providers/sns/routes.py` with `POST /` for `Action=Publish`. Parse `TopicArn`, `Message`, `Subject`, `MessageAttributes`. Return AWS SNS XML response format.
- [x] 4.3 P1-19: SNS-to-Lambda Subscription Dispatch - Parse `AWS::SNS::Subscription` with `Protocol: lambda`. Wire to topics. Invoke Lambda handlers with SNS event format. Use `asyncio.gather(return_exceptions=True)` for fan-out.
- [x] 4.4 P1-20: SNS-to-SQS Subscription - Parse `AWS::SNS::Subscription` with `Protocol: sqs`. Deliver messages to subscribed SQS queues wrapped in SNS notification envelope JSON.
- [x] 4.5 P1-21: SNS Message Filtering - Implement `ldk/providers/sns/filter.py` with `matches_filter_policy()`. Support exact string matching, numeric comparison operators, and exists checks. Evaluate per-subscriber before dispatch.

## 5. Enhanced DynamoDB (Sub-phase 1.5)

- [x] 5.1 P1-22: Global Secondary Index Support - Parse `GlobalSecondaryIndexes` from CDK. Create SQLite indexes. Rewrite Query SQL for `IndexName` parameter. Support `ALL`, `KEYS_ONLY`, `INCLUDE` projection types.
- [x] 5.2 P1-23: FilterExpression Evaluation - Implement `ldk/providers/dynamodb/expressions.py` with recursive descent parser. Support comparison, logical (`AND`, `OR`, `NOT`), `BETWEEN`, `IN` operators. Support `attribute_exists()`, `attribute_not_exists()`, `begins_with()`, `contains()`, `size()` functions. Resolve `ExpressionAttributeNames` and `ExpressionAttributeValues`.
- [x] 5.3 P1-24: UpdateExpression Evaluation - Implement `ldk/providers/dynamodb/update_expression.py`. Parse SET (with `if_not_exists()`, `list_append()`, arithmetic), REMOVE, ADD, DELETE clauses. Support combined clauses. Return updated item per `ReturnValues`.
- [x] 5.4 P1-25: Batch Operations - Implement `batch_get_item` and `batch_write_item` methods. Validate 25-item limit. Delegate to existing CRUD methods. Return empty `UnprocessedKeys`/`UnprocessedItems`.
- [x] 5.5 P1-26: DynamoDB Streams - Implement `ldk/providers/dynamodb/streams.py` with `StreamDispatcher`. Emit INSERT/MODIFY/REMOVE events. Parse `StreamSpecification.StreamViewType`. Buffer events briefly (100ms) then batch-invoke Lambda handlers. Use `asyncio.Queue` for event buffer.
- [x] 5.6 P1-27: Eventual Consistency Simulation - Maintain write timestamp log. For eventually consistent reads (`ConsistentRead: false`), return stale data if within delay window (default 200ms). GSI queries always eventual. Store previous item version. Configurable via `dynamodb.eventual_consistency_delay_ms`.
- [x] 5.7 P1-28: DynamoDB State Persistence with aiosqlite - Harden persistence layer. Store databases at `<data_dir>/dynamodb/<table_name>.db`. Enable WAL mode. Handle schema migrations for new GSIs. Properly close connections on shutdown.

## 6. Developer Experience Polish (Sub-phase 1.6)

- [x] 6.1 P1-29: Structured Logging Framework - Implement `ldk/logging/logger.py` with `LdkLogger` class. Format HTTP requests as `POST /orders -> createOrder (234ms) -> 201`. Format SQS as `SQS OrderQueue -> processOrder (1 msg, 156ms) -> OK`. Support log levels (debug, info, warn, error) via config and `--log-level` flag. Color coding with Rich.
- [x] 6.2 P1-30: SDK Call Instrumentation - Add logging hooks at provider API route entry points. Use `contextvars.ContextVar` for parent invocation tracking. Log operation summaries at INFO, full payloads at DEBUG. Visually indent SDK calls under parent request.
- [x] 6.3 P1-31: Request Flow Tracing - Implement `ldk/logging/tracer.py` with `Tracer` class using `contextvars.ContextVar` for `TraceContext` propagation. Build span tree. Link downstream triggers to originating trace. Display hierarchical trace with timing after root request completes.
- [x] 6.4 P1-32: Error Logging with Context - Wrap handler invocations in try/except. Display handler name, event source, truncated event payload (max 1KB), and full stack trace. Capture Python subprocess stderr for traceback. Red coloring for errors.
- [x] 6.5 P1-33: Hot Reload Logging - Log file change detection (`Changed: src/handlers/createOrder.py`) and reload completion with duration (`Reloaded createOrder in 120ms`). Batch rapid successive changes (within 100ms). Log reload errors.
- [x] 6.6 P1-34: CDK Change Detection and Incremental Apply - Watch CDK source files. On change, re-run `cdk synth`, diff cloud assembly against current state. Add/remove/update resources incrementally. Display diff in terminal. Debounce rapid changes (500ms). Handle synth failures gracefully.
- [x] 6.7 P1-35: State Persistence for SQS - Persist queue messages to SQLite at `<data_dir>/sqs/<queue_name>.db`. Load on startup, flush on shutdown. Reset visibility timeout for in-flight messages on restart. Support `ldk reset` clearing SQS state.
- [x] 6.8 P1-36: `ldk invoke` Command - Add `invoke` command to Typer CLI. Support `--event` (inline JSON) and `--event-file` (file path). Connect to running `ldk dev` via management API or perform one-shot invocation. Pretty-print response JSON.
- [x] 6.9 P1-37: `ldk reset` Command - Add `reset` command to Typer CLI. Delete all files under `<data_dir>/`. Show confirmation prompt (skippable with `--yes`). Notify running `ldk dev` to reinitialize. Report what was deleted.
- [x] 6.10 P1-38: Management API for CLI Commands - Implement `ldk/api/management.py` with FastAPI `APIRouter` at `/_ldk/` prefix. Endpoints: `POST /_ldk/invoke`, `POST /_ldk/reset`, `POST /_ldk/send`, `GET /_ldk/status`. JSON responses.
- [x] 6.11 P1-39: Graceful Shutdown and State Flush - Register signal handlers for SIGINT/SIGTERM via `asyncio`. Implement `ldk/lifecycle/shutdown.py` with `ShutdownManager`. Stop pollers, flush DynamoDB connections, flush SQS state. Display "Shutting down..." and "Goodbye". Second Ctrl+C forces immediate exit.
- [x] 6.12 P1-40: Configuration File Support - Implement `ldk/config.py` with `LdkConfig` dataclass and `load_config()`. Parse `ldk.yaml` with pyyaml. Keys: `log_level`, `port`, `data_dir`, `dynamodb.eventual_consistency_delay_ms`, `watch.include`, `watch.exclude`. Priority: CLI args > env vars > config > defaults.
