Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions packages/app/server/AGENTS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# Server Configuration Modules (packages/app/server)

## Purpose
This cluster manages configuration files for the server environment, including testing, build, and linting setups. It ensures consistent tooling behavior across development and CI environments.

## Boundaries
- **Belongs here:** `vitest.config.ts`, `tsup.config.ts`, `eslint.config.mjs`—all define environment-specific tooling configurations.
- **Does NOT belong here:** Application business logic, runtime server code, or deployment scripts. These configs are static and do not influence runtime behavior directly.

## Invariants
- All configuration files must export a default configuration object via `defineConfig`.
- Config files should avoid side effects; they are purely declarative.
- The `vitest.config.ts` and `tsup.config.ts` are frequently updated, so agents must handle potential breaking changes or schema updates.
- ESLint config (`eslint.config.mjs`) must adhere to ECMAScript Module syntax and be compatible with the project's linting standards.
- No circular dependencies should exist between configs; each should be self-contained.

## Patterns
- Use `defineConfig` to wrap configuration objects for type safety and consistency.
- Maintain naming conventions: `vitest.config.ts`, `tsup.config.ts`, `eslint.config.mjs`.
- For TypeScript configs, prefer explicit types where possible.
- Handle errors gracefully; configs should fail to load if invalid, but avoid silent failures.
- Keep configurations minimal; extend base configs only when necessary.
- Frequently modified files (5 versions each) suggest the need for careful review when editing to prevent breaking changes.

## Pitfalls
- Modifying `vitest.config.ts` or `tsup.config.ts` without updating related build/test scripts can cause environment failures.
- Changing ESLint config syntax or rules may silently break linting if not validated.
- Overriding default behaviors in configs may lead to inconsistent tooling behavior.
- Frequent churn indicates these configs are sensitive; avoid unnecessary modifications.
- Be cautious with dependencies imported into configs; ensure they are compatible and correctly versioned.

## Dependencies
- `defineConfig` from the relevant configuration libraries (e.g., Vite, Tsup, ESLint). Use it to ensure proper typing and structure.
- External plugins or presets used within configs must be compatible with the current versions.
- Do not introduce runtime dependencies into static configs unless explicitly supported; configs should be self-contained.
- When extending configs, verify that dependencies are correctly installed and compatible with the existing setup.

---

**Summary:**
This cluster encapsulates static tooling configurations critical for development consistency. Agents must handle frequent updates, avoid breaking invariants, and respect the separation from runtime code. Proper use of `defineConfig` and adherence to naming, syntax, and dependency standards are essential for stability.
47 changes: 47 additions & 0 deletions packages/app/server/src/AGENTS_defines_provider_typ_5e8780f9.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# ProviderType Module & createX402Transaction Method

## Purpose
Defines provider types used for transaction processing and implements `createX402Transaction`, an async method that generates a `TransactionCosts` object based on a given `Transaction`. This facilitates dynamic transaction cost calculation within the provider ecosystem.

## Boundaries
- **Belongs here:**
- Provider type definitions (`ProviderType.ts`) that categorize or configure different transaction providers.
- Implementation of `createX402Transaction`, which encapsulates logic for creating a specific transaction cost report.
- **Does NOT belong here:**
- Core transaction processing logic unrelated to provider types.
- External API integrations or database access—these should be abstracted or delegated elsewhere.
- Utility functions or shared helpers unrelated to provider type definitions or transaction cost creation.

## Invariants
- `createX402Transaction` must always return a `TransactionCosts` object, never null or undefined.
- The method should handle all `Transaction` inputs gracefully, including invalid or incomplete data, by throwing or returning error states as per the application's error handling pattern.
- The `Transaction` parameter must be validated before processing; invalid transactions should not produce a `TransactionCosts` object.
- The function must preserve data integrity: no mutation of input `Transaction`, and all outputs must accurately reflect the input's details plus calculated costs.
- The method must respect the contract that it is asynchronous; any synchronous operations should be wrapped or awaited appropriately.
- Provider types in `ProviderType.ts` should be immutable or controlled; avoid runtime modifications that could break type assumptions.

## Patterns
- Use explicit, descriptive naming for variables and functions; e.g., `createX402Transaction`.
- Implement comprehensive error handling: catch exceptions, validate inputs, and propagate errors in a consistent manner.
- Follow the project's coding style for async functions, including proper use of `await`.
- When modifying, ensure that any new provider types or transaction cost calculations adhere to existing data schemas and validation rules.
- Maintain separation of concerns: `ProviderType.ts` should only define types/constants; `createX402Transaction` should focus solely on transaction cost creation logic.

## Pitfalls
- **Churn risk:** Both the module and method are frequently modified; introducing incompatible changes can break assumptions.
- **Coupling:** Since the method depends on `Transaction` and returns `TransactionCosts`, ensure these types are stable; avoid tight coupling to external modules that may change.
- **Null safety:** Failing to validate `Transaction` inputs could lead to runtime errors or inconsistent `TransactionCosts`.
- **Type assumptions:** Misalignment between `Transaction` and `TransactionCosts` schemas can cause subtle bugs; enforce strict validation.
- **Asynchronous handling:** Forgetting to `await` the async method can cause unpredictable behavior downstream.
- **Provider type modifications:** Changes in `ProviderType.ts` should be reflected in all dependent logic to prevent mismatches.

## Dependencies
- **Transaction:** Must be validated and processed according to its schema; ensure any updates to `Transaction` are reflected here.
- **TransactionCosts:** The output schema; understand its fields and constraints to produce valid results.
- **TypeScript types:** Use the types from `ProviderType.ts` to enforce correct provider categorization.
- **Error handling conventions:** Follow existing patterns for propagating errors from `createX402Transaction`.
- **External configs or constants:** If any provider-specific parameters are used, ensure they are correctly imported and used consistently.

---

**Note:** Be vigilant about frequent modifications in both the module and method—test thoroughly after changes to prevent regressions.
70 changes: 70 additions & 0 deletions packages/app/server/src/AGENTS_encapsulates_logic_5da8044e.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
# Package: packages/app/server/src

## Purpose
Encapsulates server-side logic for user spend management and error handling, focusing on retrieving balances, updating user spend pools, and managing upstream response errors. It provides core transactional and error-resilient operations critical to financial workflows.

## Boundaries
- **Includes:**
- `getBalance()`: Fetches total user balance, likely from a database or cache.
- `upsertUserSpendPoolUsage()`: Atomically updates or inserts user spend pool records within a Prisma transaction, ensuring data consistency during concurrent operations.
- `handleUpstreamError()`: Processes upstream HTTP responses, throwing or handling errors based on response status or content.

- **Excludes:**
- User authentication/authorization logic (should be handled upstream).
- External payment gateways or external API integrations beyond response error handling.
- Business logic for spend pool creation, deletion, or complex validation (beyond basic upsert).
- UI rendering or client-side code.
- Non-transactional data retrieval or background jobs.

## Invariants
- `upsertUserSpendPoolUsage()` must be invoked within an active Prisma transaction (`tx`) to ensure atomicity.
- `getBalance()` must return a non-negative number; if negative, it indicates a data inconsistency.
- `handleUpstreamError()` must never swallow errors silently; it should throw or escalate after processing.
- All methods assume proper dependency injection; no internal state is maintained.
- Null or undefined `userId`, `spendPoolId`, or `amount` parameters are invalid; validation should be enforced externally or at call sites.
- `amount` must be a `Decimal` object, not a primitive number, to avoid precision errors.
- Response handling in `handleUpstreamError()` should consider HTTP status codes and response body content to determine error severity.

## Patterns
- Use explicit async/await syntax for all I/O operations.
- Consistent error handling: `handleUpstreamError()` processes `Response` objects, throwing on error status.
- Transactional integrity: `upsertUserSpendPoolUsage()` requires a Prisma `TransactionClient` passed explicitly, emphasizing explicit transaction boundaries.
- Naming conventions:
- Methods prefixed with `get` or `fetch` for retrieval.
- Methods prefixed with `upsert` for create/update logic.
- Error handling methods prefixed with `handle`.
- Decimal usage for monetary amounts to prevent floating-point inaccuracies.
- Frequent modifications suggest these methods are core to spend and balance logic, requiring careful change management.

## Pitfalls
- **Churn Hotspots:**
- `getBalance()`, `upsertUserSpendPoolUsage()`, `handleUpstreamError()` have high churn; modifications risk introducing regressions or inconsistencies.
- Changes to `getBalance()` must consider caching or external data sources; frequent updates may affect performance or correctness.
- `upsertUserSpendPoolUsage()` must handle concurrent updates; improper transaction handling can cause race conditions or data corruption.
- `handleUpstreamError()` must correctly interpret varied response formats; misinterpretation can lead to unhandled errors or silent failures.

- **Common mistakes:**
- Omitting transaction context in `upsertUserSpendPoolUsage()`.
- Not validating input parameters before calling these methods.
- Ignoring the need for consistent error propagation in `handleUpstreamError()`.
- Assuming `getBalance()` is always accurate without considering cache invalidation or external data refresh.

## Dependencies
- **Prisma.TransactionClient:**
- Must be a valid Prisma transaction context; ensure caller manages transaction lifecycle.
- Do not reuse transaction clients outside their scope.

- **Decimal:**
- Use the `Decimal` class for `amount` to maintain precision; avoid primitive number types.

- **Response (globalThis.Response):**
- Handle HTTP status codes (e.g., 4xx, 5xx) explicitly; consider response body content for detailed error info.
- Do not assume all responses are successful; always check status before processing.

- **External APIs:**
- No external dependencies are directly imported; assume all external interactions are via `Response` objects passed to `handleUpstreamError()`.

---

**Note:**
Agents modifying this code should prioritize maintaining transactional integrity, input validation, and error handling consistency. Frequent churn areas require thorough testing to prevent regressions.
47 changes: 47 additions & 0 deletions packages/app/server/src/AGENTS_implements_an_expres_f061fb01.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# Trace Logging Middleware (packages/app/server/src)

## Purpose
Implements an Express middleware function `traceLoggingMiddleware` that logs request details for tracing and debugging purposes. It ensures consistent logging for incoming requests and their lifecycle within the server.

## Boundaries
- **Belongs here:** Request lifecycle logging, middleware setup, request context enrichment.
- **Does NOT belong here:** Business logic, route handling, response formatting, error handling beyond logging, schema definitions (handled in `descriptionForRoute.ts`), or external request processing.

## Invariants
- `traceLoggingMiddleware` must always call `next()` exactly once, regardless of errors.
- It must log at the start of request processing and after response is sent, capturing request method, URL, headers, and response status.
- Null-safety: `req`, `res`, and `next` are guaranteed to be non-null; no null checks needed.
- Response status should be captured after response finishes, not before.
- Logging should not block or delay response; perform asynchronously if needed.
- Middleware must not modify `req` or `res` objects unless explicitly intended for tracing.
- Churn: Frequently modified (5 versions); ensure backward compatibility with previous logging formats.

## Patterns
- Use consistent naming: `traceLoggingMiddleware`.
- Log request details at the start (`req.method`, `req.url`, headers) and after response (`res.statusCode`).
- Attach event listeners to `res` (`finish` event) for capturing response completion.
- Handle errors gracefully; ensure `next()` is called even if logging fails.
- Use external dependencies (`bodies`, `response`, `status`) for structured logging and response handling.
- Maintain idempotency: middleware should be safe to call multiple times without side effects.
- Follow existing code style: arrow functions, explicit types, minimal side effects.

## Pitfalls
- Forgetting to call `next()`, causing request hang or deadlock.
- Logging after response has already been sent, missing status code.
- Not handling errors in logging, leading to unhandled exceptions.
- Modifying request or response objects unintentionally.
- Churn: frequent modifications increase risk of breaking invariants; test thoroughly.
- Over-logging: avoid sensitive data exposure in logs.
- Churn hotspots imply the middleware may evolve; monitor for breaking changes.

## Dependencies
- **request:** Used to access request data; must be used carefully to avoid blocking.
- **bodies:** For parsing request bodies if needed for logging (not shown explicitly here).
- **response:** For structured response data, if applicable.
- **status:** For standardized status code handling.
- **External logging library (implied):** Ensure logs are asynchronous and non-blocking.
- Use these dependencies according to their API contracts; avoid side effects or assumptions about their internal state.

---

**Note:** Given the frequent modifications, always review recent changes for compatibility, especially around response lifecycle handling and logging formats.
Loading
Loading