Update documentation to align terminology, clarify project stages, and improve consistency; add RECOMMENDATIONS.md for project-specific guidance.

This commit is contained in:
olekhondera
2025-12-12 01:50:38 +02:00
parent 8794e74934
commit 5053235e95
12 changed files with 102 additions and 43 deletions

View File

@@ -0,0 +1,59 @@
# Project-Specific Recommendations & Overrides
This file is the project-specific layer on top of the generic template.
Humans and AI agents should treat it as the **single place to record locked decisions, nonnegotiable constraints, and intentional deviations** from `docs/` guidance.
Update this file whenever you make a decision that changes the stack, scope, constraints, or any recommendation in `docs/`.
---
## 1. Project Context (fill in)
- **Domain / product type:** _[e.g., customer support AI, compliance assistant, content classifier]_
- **Primary users:** _[roles/personas]_
- **Key success metrics:** _[latency, accuracy, cost, adoption, etc.]_
- **Current phase:** _Phase 0 / 1 / 2 / 3 / 4_
- **Repos/services in scope:** _[monorepo, separate FE/BE, workers, etc.]_
## 2. Locked Stack Decisions (override template here)
If a choice is not listed here, the default recommendations in `docs/` apply.
**Frontend**
- **Framework:** _Next.js (App Router)_ / _other_
- **Language:** _TypeScript_ / _other_
- **Styling:** _Tailwind CSS_ / _other_
- **Server/Client data layer:** _React Query / SWR / other_
- **Forms & validation:** _React Hook Form + Zod_ / _other_
- **Auth client:** _Clerk / Auth.js / other_
**Backend**
- **Runtime/language:** _Node.js (LTS) + TypeScript_ / _other_
- **Framework:** _Express / Fastify / other_
- **Database:** _Postgres_ / _other_ (vector search: _pgvector_ / _other_)
- **Queues/workers:** _BullMQ (Redis)_ / _other_
- **LLM provider & helper:** _Single abstraction (e.g., `callLLM()`)_, provider _[fill in]_
- **File/storage:** _S3/Supabase Storage/local_ / _other_
**Infra / DevOps**
- **Hosting/deploy:** _[Vercel/Fly/K8s/etc.]_
- **CI/CD:** _[GitHub Actions/GitLab/etc.]_
- **Observability:** _[Sentry/OTel/Prometheus/etc.]_
- **Environments:** _dev/stage/prod_ (or specify)
## 3. NonNegotiable Constraints (add to RULES scope)
- **Compliance/regulation:** _[PII/PHI/PCI, SOC2, GDPR, etc.]_
- **Data residency/retention:** _[regions, retention window]_
- **Performance/SLOs:** _[e.g., p95 < X ms, batch window]_
- **Cost limits:** _[monthly LLM budget, infra cap]_
- **Target platforms:** _[browsers/devices, locales]_
- **Repository constraints:** _[additional forbidden commands, branching rules, etc.]_
## 4. Deviations From Template (explicit trade-offs)
List any intentional departures from `docs/` recommendations and why.
- _[Decision]_ → _[Why]__[Migration/rollback plan if relevant]_
## 5. Open Questions / To Confirm
- _[Unresolved item]_ → _[owner]__[ETA]_
## 6. Change Log (optional)
- _YYYYMMDD_: _[decision summary]_

View File

@@ -95,7 +95,7 @@ conflict.
### 6.1 Consult project docs first ### 6.1 Consult project docs first
- Check relevant files in `docs/` before making recommendations. - Check relevant files in `docs/` before making recommendations.
- If `recommendation.md` exists at the repo root, read it before starting work and incorporate its guidance where - If `RECOMMENDATIONS.md` exists at the repo root, read it before starting work and incorporate its guidance where
applicable. applicable.
- If project docs contradict general best practices, prefer project docs and flag potential staleness for user - If project docs contradict general best practices, prefer project docs and flag potential staleness for user
confirmation. confirmation.

View File

@@ -443,7 +443,7 @@ export default defineConfig({
- ✅ Page Object Model for maintainability - ✅ Page Object Model for maintainability
- ✅ API setup for faster test execution - ✅ API setup for faster test execution
- ✅ Parallel execution with sharding - ✅ Parallel execution with sharding
- ⚠️ Requires test payment gateway (Stripe test mode) - ⚠️ Requires test payment gateway in provider test mode
- ⚠️ Database seeding needed for consistent state - ⚠️ Database seeding needed for consistent state
**CI Integration**: **CI Integration**:

View File

@@ -38,7 +38,7 @@
## 3. API Layers ## 3. API Layers
- HTTP API (REST) with versioning (`/api/v1`). - HTTP API (REST) with versioning (`/api/v1`).
- Service layer for business logic and transactions. - Service layer for business logic and database transactions.
- Repositories for data access; use migrations for schema evolution. - Repositories for data access; use migrations for schema evolution.
## 4. Infrastructure & Ops ## 4. Infrastructure & Ops
@@ -49,7 +49,7 @@
## 5. Data & Schema Notes ## 5. Data & Schema Notes
- Records: store raw payload + normalized fields + `reasoning_trace` JSONB (model, rationale, confidence, source). - Records: store raw payload + normalized fields + `reasoning_trace` JSONB (model, rationale, confidence, source).
- EventLog: include `source_agent` (default `balance`) and payload for auditability; ensure filters by tenant/time/type. - EventLog: include `source_agent` (default `balance`) and payload for auditability; ensure filters by tenant/time/type.
- Embeddings: table keyed by transaction/merchant strings to support similarity search; index with `pgvector`. - Embeddings: table keyed by record text fields (or other domain signals) to support similarity search; index with `pgvector`.
- Multi-tenant: all core tables carry `tenantId` and enforce scoped queries; `User` role per tenant. - Multi-tenant: all core tables carry `tenantId` and enforce scoped queries; `User` role per tenant.
## 6. Payment & Messaging (High-Level) ## 6. Payment & Messaging (High-Level)
@@ -59,5 +59,5 @@
## 7. Queues (BullMQ) ## 7. Queues (BullMQ)
- `records:ingest` — normalize webhook payloads, write `Record`, emit `INGESTED`. - `records:ingest` — normalize webhook payloads, write `Record`, emit `INGESTED`.
- `records:process` — rule engine → embeddings similarity → LLM fallback; emit `PROCESSED` with `reasoning_trace`. - `records:process` — rule engine → embeddings similarity → LLM fallback; emit `PROCESSED` with `reasoning_trace`.
- `reports:generate` — build P&L/exports, emit `REPORT_GENERATED`. - `reports:generate` — build domain reports/exports, emit `REPORT_GENERATED`.
- Dead-letter queues per stream; retries with backoff; idempotent handlers keyed by external event IDs. - Dead-letter queues per stream; retries with backoff; idempotent handlers keyed by external event IDs.

View File

@@ -3,7 +3,7 @@
--- ---
**Last Updated:** 2025-01-17 **Last Updated:** 2025-01-17
**Phase:** Phase 0 (Planning) **Phase:** Phase 0 (Planning)
**Status:** Approved **Status:** Draft
**Owner:** Backend Architect **Owner:** Backend Architect
**References:** **References:**
- `/docs/project-overview.md` - `/docs/project-overview.md`

View File

@@ -1,27 +1,27 @@
# Frontend Architecture Plan — Accounting AI Agent # Frontend Architecture Plan — AI Product Template
> **Status:** Phase 0 (Planning) — recommendations to finalize in Phase 1 > **Status:** Phase 0 (Planning) — recommendations to finalize in Phase 1
> **Scope:** Next.js (App Router, TS) + Tailwind + React Query/SWR for ingestion → categorization → approvals → reporting → billing > **Scope:** Next.js (App Router, TS) + Tailwind + React Query/SWR for ingestion → categorization → approvals → reporting → billing
> **Sources:** Next.js App Router best practices (per latest docs), product/domain docs in `/docs` > **Sources:** Next.js App Router best practices (per latest docs), product/domain docs in `/docs`
## 0. Goals & Non-Goals ## 0. Goals & Non-Goals
- Ship a clear, predictable frontend for finance users: fast tables, reliable status, explainability (rule hit, embedding score, LLM reasoning trace). - Ship a clear, predictable frontend for users in your target domain: fast tables, reliable status, explainability (rule hit, embedding score, LLM reasoning trace).
- Optimize for multi-tenant, webhook-driven states, and Stripe-hosted billing; no direct provider/LLM calls from the browser. - Optimize for multi-tenant, webhook-driven states, and paymentproviderhosted billing; no direct provider/LLM calls from the browser.
- Non-goal: custom card forms or direct provider SDKs in the browser. - Non-goal: custom card forms or direct provider SDKs in the browser.
## 1. Routing & Layout ## 1. Routing & Layout
- App Router with `app/`; root `layout.tsx` imports globals (per Next.js docs). - App Router with `app/`; root `layout.tsx` imports globals (per Next.js docs).
- Layout shells: public (marketing), app shell (auth/tenant-protected), auth screens. - Layout shells: public (marketing), app shell (auth/tenant-protected), auth screens.
- Minimal routes: `/`, `/transactions`, `/transactions/review`, `/rules`, `/reports`, `/settings/billing`, `/settings/accounts`, `/settings/team`. - Minimal routes: `/`, `/records`, `/records/review`, `/rules`, `/reports`, `/settings/billing`, `/settings/integrations`, `/settings/team`.
- Navigation state from `next/navigation`; avoid dynamic `href` objects in `<Link>` (App Router requirement). - Navigation state from `next/navigation`; avoid dynamic `href` objects in `<Link>` (App Router requirement).
## 2. Feature/Folder Structure ## 2. Feature/Folder Structure
``` ```
src/ src/
app/ # routes/layouts app/ # routes/layouts
features/ # onboarding, transactions, approvals, rules, reports, billing, settings features/ # onboarding, records, approvals, rules, reports, billing, settings
entities/ # tenant, user, transaction, rule, report, event, integration entities/ # tenant, user, record, rule, report, event, integration
shared/ # ui kit, hooks, api client, lib (formatting, currency), auth client shared/ # ui kit, hooks, api client, lib (formatting, domain utils), auth client
widgets/ # composed UI blocks (dashboards, charts, tables) widgets/ # composed UI blocks (dashboards, charts, tables)
``` ```
- Co-locate queries/mutations/types/tests per feature; keep shared minimal. - Co-locate queries/mutations/types/tests per feature; keep shared minimal.
@@ -29,7 +29,7 @@ src/
## 3. Data Layer & State ## 3. Data Layer & State
- HTTP client with typed fetchers; attach auth/tenant context; central 401/403 handling. - HTTP client with typed fetchers; attach auth/tenant context; central 401/403 handling.
- React Query/SWR for cache + background refresh; server-side data where possible (RSC) with client wrappers for interactivity. - React Query/SWR for cache + background refresh; server-side data where possible (RSC) with client wrappers for interactivity.
- Pagination/virtualization for large lists (`/transactions`, `/events`); filters persisted in URL search params. - Pagination/virtualization for large lists (`/records`, `/events`); filters persisted in URL search params.
- Optimistic updates only for low-risk actions (naming/rule toggles); approvals/overrides stay pessimistic with clear status. - Optimistic updates only for low-risk actions (naming/rule toggles); approvals/overrides stay pessimistic with clear status.
## 4. Auth, Tenant, Roles ## 4. Auth, Tenant, Roles
@@ -38,12 +38,12 @@ src/
- Role-based UI gating (owner/admin/viewer); hide/disable disallowed actions. - Role-based UI gating (owner/admin/viewer); hide/disable disallowed actions.
## 5. UX for Key Flows ## 5. UX for Key Flows
- **Transactions:** table with status chips (ingested/categorized/needs_approval/approved/error), drawer: raw payload, rule hit, embedding score, `reasoning_trace`, receipts, history. - **Records:** table with status chips (ingested/categorized/needs_approval/approved/error), drawer: raw payload, rule hit, embedding score, `reasoning_trace`, attachments, history.
- **Approvals:** queue view, approve/override with confirmation; optional rule creation inline; show impact preview. - **Approvals:** queue view, approve/override with confirmation; optional rule creation inline; show impact preview.
- **Rules:** list (priority, hit rate), editor with condition/action JSON preview, test on sample set. - **Rules:** list (priority, hit rate), editor with condition/action JSON preview, test on sample set.
- **Reports:** date range, currency/timezone indicators; async export with status chips and download links. - **Reports:** date range and domain indicators (e.g., timezone/currency if relevant); async export with status chips and download links.
- **Billing:** Stripe-hosted Checkout/Portal; post-return state from backend; recovery CTAs. - **Billing:** paymentproviderhosted Checkout/Portal; post-return state from backend; recovery CTAs.
- **Integrations:** QuickBooks/bank connection status, webhook health, rotate secrets; surface retry guidance. - **Integrations:** external provider connection status, webhook health, rotate secrets; surface retry guidance.
- **Errors/Support:** human-readable errors with traceId; recovery steps for webhook/LLM failures. - **Errors/Support:** human-readable errors with traceId; recovery steps for webhook/LLM failures.
## 6. Styling & UI Kit ## 6. Styling & UI Kit
@@ -71,12 +71,12 @@ src/
## 11. Testing ## 11. Testing
- Unit: helpers/formatters. - Unit: helpers/formatters.
- Component: transactions table/drawer, approvals flow, rule editor, billing/status banners. - Component: records table/drawer, approvals flow, rule editor, billing/status banners.
- E2E: onboarding + source connect, transaction ingest display, categorize → approve, rule create/apply, billing flow, report export. - E2E: onboarding + source connect, record ingest display, categorize → approve, rule create/apply, billing flow, report export.
## 12. Open Questions / To Finalize ## 12. Open Questions / To Finalize
- Exact table virtualization lib (if any) and charting choice. - Exact table virtualization lib (if any) and charting choice.
- How much data is loaded server-side vs client-side for `/transactions` (depends on API paging). - How much data is loaded server-side vs client-side for `/records` (depends on API paging).
- Error surface for LLM fallback (what to show vs hide). - Error surface for LLM fallback (what to show vs hide).
- i18n scope (English only vs multi-lingual). - i18n scope (English only vs multi-lingual).
- Whether to expose `rawSnippet` of LLM response in UI or keep to audit logs only. - Whether to expose `rawSnippet` of LLM response in UI or keep to audit logs only.

View File

@@ -25,8 +25,8 @@
``` ```
src/ src/
app/ # routes/layouts app/ # routes/layouts
features/ # flows: onboarding, transactions, approvals, reports, billing features/ # flows: onboarding, records, approvals, reports, billing
entities/ # domain: tenant, user, transaction, rule, report, event entities/ # domain: tenant, user, record, rule, report, event
shared/ # ui kit, hooks, api client, utils shared/ # ui kit, hooks, api client, utils
widgets/ # composed UI blocks widgets/ # composed UI blocks
i18n/ # translations (if added) i18n/ # translations (if added)
@@ -37,11 +37,11 @@ Principles: co-locate tests/types; avoid cross-feature coupling; keep shared min
- Single typed HTTP client; attach auth tokens; handle 401/403 centrally. - Single typed HTTP client; attach auth tokens; handle 401/403 centrally.
- Cache with React Query/SWR; use optimistic/paused states carefully for approvals and rule edits. - Cache with React Query/SWR; use optimistic/paused states carefully for approvals and rule edits.
- Prefer RSC for data loading; mark interactive leaf nodes with `"use client"`. - Prefer RSC for data loading; mark interactive leaf nodes with `"use client"`.
- Pagination/filtering for transaction-heavy views; background refetch for webhook-driven updates. - Pagination/filtering for record-heavy views; background refetch for webhook-driven updates.
## 4. Payments & Billing UI ## 4. Payments & Billing UI
- Backend initiates Stripe sessions/portal links; frontend renders statuses only. - Backend initiates payment-provider sessions/portal links; frontend renders statuses only.
- After return from Stripe, fetch status from backend (webhook-driven source of truth); show success/fail/pending and recovery options. - After return from payment provider, fetch status from backend (webhook-driven source of truth); show success/fail/pending and recovery options.
- Never collect raw card data; no custom card forms. - Never collect raw card data; no custom card forms.
## 5. LLM & Explainability Surfacing ## 5. LLM & Explainability Surfacing
@@ -54,5 +54,5 @@ Principles: co-locate tests/types; avoid cross-feature coupling; keep shared min
## 7. Testing ## 7. Testing
- Unit: utility/helpers. - Unit: utility/helpers.
- Component: critical UI (transactions list, approval drawer, rule editor, billing modal). - Component: critical UI (records list, approval drawer, rule editor, billing modal).
- E2E: onboarding, ingestion health check, categorize + approve, billing change, report export. - E2E: onboarding, ingestion health check, categorize + approve, billing change, report export.

View File

@@ -3,7 +3,7 @@
--- ---
**Last Updated:** 2025-01-17 **Last Updated:** 2025-01-17
**Phase:** Phase 0 (Planning) **Phase:** Phase 0 (Planning)
**Status:** Approved **Status:** Draft
**Owner:** Frontend Architect **Owner:** Frontend Architect
**References:** **References:**
- `/docs/project-overview.md` (product goals) - `/docs/project-overview.md` (product goals)
@@ -12,17 +12,17 @@
--- ---
## 1. Role of Frontend ## 1. Role of Frontend
- Deliver onboarding, data connection, categorization review, approval, reporting, and billing experiences for SMB finance users. - Deliver onboarding, data connection, categorization review, approval, reporting, and optional billing experiences for users in your target domain.
- Keep flows fast, explainable (surface reasoning trace, rule hit), and safe (reflect webhook/provider states, avoid double actions). - Keep flows fast, explainable (surface reasoning trace, rule hit), and safe (reflect webhook/provider states, avoid double actions).
## 2. Core Screens & Flows ## 2. Core Screens & Flows
- Marketing/landing with CTA to signup. - Marketing/landing with CTA to signup.
- Onboarding: signup/login, plan selection (Stripe Checkout/portal), source connection (QuickBooks OAuth2, bank webhooks health), team invites. - Onboarding: signup/login, plan selection (payment provider Checkout/Portal if applicable), source connection (external providers via OAuth2/webhooks), team invites.
- Transactions: lists/filters, detail drawer (raw fields, rule hit, embedding score, LLM reasoning trace), bulk actions. - Records: lists/filters, detail drawer (raw fields, rule hit, embedding score, LLM reasoning trace), bulk actions.
- Approvals & Rules: approval queue, override + optional rule creation, rule list/editor, history snippets. - Approvals & Rules: approval queue, override + optional rule creation, rule list/editor, history snippets.
- Reports: P&L/summary dashboards, exports with statuses. - Reports: dashboards/summaries, exports with statuses.
- Billing & Settings: subscription status, payment method, tenant/team management, integrations health, audit/event log view. - Billing & Settings: subscription status, payment method, tenant/team management, integrations health, audit/event log view.
- Routes (min set): `/`, `/transactions`, `/transactions/review`, `/rules`, `/reports`, `/settings/billing`, `/settings/accounts`. - Routes (min set): `/`, `/records`, `/records/review`, `/rules`, `/reports`, `/settings/billing`, `/settings/integrations`.
## 3. Technical Principles ## 3. Technical Principles
- Next.js (App Router) with TypeScript; Tailwind for styling; React Query/SWR for data fetching and cache orchestration. - Next.js (App Router) with TypeScript; Tailwind for styling; React Query/SWR for data fetching and cache orchestration.
@@ -31,10 +31,10 @@
- Strong loading/error/empty states for data-heavy lists; avoid blocking UX during long jobs (categorization replays, exports). - Strong loading/error/empty states for data-heavy lists; avoid blocking UX during long jobs (categorization replays, exports).
## 4. Backend Interaction ## 4. Backend Interaction
- All data via backend APIs; frontend never calls providers (Stripe/QuickBooks/banks/LLM) directly. - All data via backend APIs; frontend never calls external providers (data, payment, LLM) directly.
- Payments: initiate via backend (Stripe session/portal) and show statuses driven by webhooks. - Payments: initiate via backend (payment provider session/portal) and show statuses driven by webhooks.
- LLM: never called from the browser; surfaced reasoning traces come from backend responses. - LLM: never called from the browser; surfaced reasoning traces come from backend responses.
- Auth: Clerk/Auth.js; guard routes per tenant/role; handle token refresh gracefully. - Auth: Clerk/Auth.js; guard routes per tenant/role; handle token refresh gracefully.
## 5. I18n ## 5. I18n
- Primary UI in English; other locales optional. Keep copy concise and finance-friendly. - Primary UI in English; other locales optional. Keep copy concise and domain-appropriate.

View File

@@ -29,7 +29,7 @@
- Minimize global state; prefer streaming data in RSC where possible. - Minimize global state; prefer streaming data in RSC where possible.
## 5. Data-Heavy Views ## 5. Data-Heavy Views
- Virtualize large tables (transactions, events); paginate server-side. - Virtualize large tables (records, events); paginate server-side.
- Background refetch for webhook-driven updates; avoid full-page reloads. - Background refetch for webhook-driven updates; avoid full-page reloads.
- Show skeletons and incremental data rather than blank states. - Show skeletons and incremental data rather than blank states.

View File

@@ -12,7 +12,7 @@
--- ---
## 1. Tone & Clarity ## 1. Tone & Clarity
- Professional, concise, finance-friendly. Emphasize trust (audit log, reasoning traces, secure billing and webhooks). - Professional and concise. Emphasize trust (audit log, reasoning traces, secure billing and webhooks).
- Avoid jargon without tooltips; show why a decision was made (rule hit, similarity, LLM reasoning). - Avoid jargon without tooltips; show why a decision was made (rule hit, similarity, LLM reasoning).
## 2. Responsiveness ## 2. Responsiveness
@@ -34,14 +34,14 @@
- Require confirmation when enabling a high-priority rule; surface last editor and timestamp. - Require confirmation when enabling a high-priority rule; surface last editor and timestamp.
### Onboarding & Integrations ### Onboarding & Integrations
- Display connection status/health for QuickBooks/bank webhooks; guide recovery/retry. - Display connection status/health for external providers and their webhooks; guide recovery/retry.
- Stripe plan selection and post-checkout status must be clear and recoverable. - Payment plan selection and post-checkout status must be clear and recoverable.
### Reports & Exports ### Reports & Exports
- Show date range, currency, timezone; indicate processing state and download links when ready. - Show date range, currency, timezone; indicate processing state and download links when ready.
## 5. Payments & Billing UX ## 5. Payments & Billing UX
- Use provider trust markers (Stripe) and keep users on provider-hosted flows. - Use provider trust markers and keep users on provider-hosted flows.
- Post-return states: success, pending, failed; include retry/contact support options. - Post-return states: success, pending, failed; include retry/contact support options.
## 6. Support & Errors ## 6. Support & Errors

View File

@@ -3,7 +3,7 @@
--- ---
**Last Updated:** 2025-01-17 **Last Updated:** 2025-01-17
**Phase:** Phase 0 (Planning) **Phase:** Phase 0 (Planning)
**Status:** Approved — update as phases complete **Status:** Draft — update as phases complete
**Owner:** Product Team **Owner:** Product Team
**References:** **References:**
- `/docs/project-overview.md` (project goals and requirements) - `/docs/project-overview.md` (project goals and requirements)

View File

@@ -3,7 +3,7 @@
--- ---
**Last Updated:** 2025-01-17 **Last Updated:** 2025-01-17
**Phase:** Phase 0 (Planning) **Phase:** Phase 0 (Planning)
**Status:** Approved **Status:** Draft
**Owner:** Product Team **Owner:** Product Team
**References:** **References:**
- `/docs/phases-plan.md` (development roadmap) - `/docs/phases-plan.md` (development roadmap)