| name | treasury-domain-architect |
| description | Build AFENDA Treasury as an AP-grade full-stack ERP sub-domain (contracts, db, core, api, worker, web, tests, gates). Use when: treasury module, cash management, bank account, bank statement, reconciliation, liquidity forecast, cash position, payment factory, bank transfer, treasury controls, treasury architecture review, AP-style enterprise workflow. |
| argument-hint | Describe treasury scope: compact checklist or full end-to-end implementation, and which entities/flows to include first. |
Treasury Domain Architect
Builds the Treasury sub-domain using the same enterprise architecture and quality bar as AP.
Use this skill when
- You need a new Treasury module following AFENDA schema-is-truth workflow
- You want AP-style Result-typed services, audit, outbox, and org isolation
- You need to review a Treasury implementation and pinpoint architectural mistakes
- You want a repeatable full-stack rollout sequence with completion gates
Target outcome
Produce an end-to-end Treasury implementation across:
packages/contracts/src/erp/finance/treasury/
packages/db/src/schema/erp/finance/treasury/
packages/core/src/erp/finance/treasury/
apps/api/src/routes/erp/finance/treasury.ts
apps/worker/src/jobs/erp/finance/treasury/
apps/web/src/app/(erp)/finance/treasury/
__vitest_test__/ coverage + gate verification
Treasury baseline scope (default)
If the user does not provide entity scope, start with this compact essential pack:
bank-account (master data, active/inactive)
bank-statement (header)
bank-statement-line (append-only ingestion lines)
cash-transfer (inter-account movement lifecycle)
cash-position-snapshot (as-of balance view materialization event)
reconciliation-session (open/matched/closed process)
Mandatory architecture constraints
- Import Direction Law must be preserved
- Money in minor units as
bigint only
- DB timestamps are
timestamptz
- Every mutation command includes
idempotencyKey
- Every mutation uses
withAudit(...) and emits outbox event in same transaction
- All reads and writes are org-scoped (
orgId)
- No
console.*; use platform logger patterns
- Tests only under
__vitest_test__/
Workflow
- Define Treasury module boundary and first entity slice
- Write contracts first (entities, commands, status enums)
- Register shared artifacts (errors, audit actions, permissions, outbox event types)
- Create Drizzle schema + migration + contract-db sync mapping
- Implement core services (Result-typed, guard-first, withAudit)
- Implement query layer (cursor list + detail + org filters)
- Wire API routes (thin handlers, zod schemas, AP response style)
- Wire worker handlers for outbox-driven side effects
- Build web UI screens (list/detail/create/action flows + loading/error states)
- Add test matrix (guards, success, outbox payload assertions)
- Update barrels and OWNERS files
- Run verification (
pnpm typecheck, targeted tests, pnpm check:all)
Decision points and branching
Branch A: New Treasury from skeleton
Use when treasury folders are placeholders only.
- Keep module path as
erp/finance/treasury
- Scaffold one vertical slice (
bank-account) end-to-end
- Only after tests pass, add remaining entities incrementally
Branch B: Existing Treasury partial implementation
Use when some tables or services already exist.
- Audit for AP-pattern parity before adding features
- Fix architectural gaps first (idempotency, audit, outbox, org filtering)
- Then add new entities or transitions
Branch C: Review-only request
Use when user asks to pinpoint mistakes instead of building features.
- Perform architecture conformance review
- Rank issues by severity and regression risk
- Provide exact file-level remediation plan
Mistake radar (pinpoint and avoid)
Common wrong patterns to reject immediately:
- Commands without
idempotencyKey
- Mutation service writes without
withAudit(...)
- Outbox event emitted outside mutation transaction
- Missing
orgId filter in queries or updates
- Using float/number for money instead of
bigint minor units
- Missing status transition guards
- API route importing DB directly instead of core
- Tests missing outbox payload assertions
- Truth-table style data updated/deleted instead of append-only behavior
- Barrel growth beyond readability with no split strategy
Treasury-specific invariants
- Reconciliation integrity: matched amount sum cannot exceed statement line amount
- Transfer integrity: debit and credit legs must be same amount/currency or explicitly FX-linked
- Cash position reproducibility: snapshots must be derivable from prior balances + posted events
- Bank account lifecycle: inactive account cannot accept new transfer or statement ingestion
- Multi-tenant control: cross-org bank account references are always rejected
Service pattern (required)
Every public service follows:
- Guard checks first (existence, ownership, status, permission)
- Execute mutation inside
withAudit(...)
- Append status/history rows (no destructive mutation for truth records)
- Insert outbox event with serialized bigint fields as strings in payload
- Return Result type:
{ ok: true, data: ... }
{ ok: false, error: { code, message, meta? } }
API pattern (required)
For each Treasury entity:
POST /v1/commands/create-<entity>
POST /v1/commands/<action>-<entity> for lifecycle transitions
GET /v1/<entities> cursor list (stable sort)
GET /v1/<entities>/{id} detail
Use AP-style schemas and response helpers; handlers remain thin delegates.
Test completion criteria
For each service function, include:
- Guard tests (
not found, invalid state, forbidden, cross-org rejection)
- Success test with expected return payload
- Outbox assertion including event
type and payload field checks
- Side-effect assertion for status/history updates
- Query tests for org filter and pagination behavior
Done definition
Treasury slice is complete only when all are true:
- Contracts, DB, core, API, worker, web are wired for the selected scope
- Error codes/audit actions/permissions/outbox types are registered
- Tests pass for all new services and routes
pnpm typecheck passes
pnpm check:all passes
Suggested prompts
/treasury-domain-architect Build bank-account + bank-statement + reconciliation-session end-to-end using AP architecture.
/treasury-domain-architect Review current treasury implementation and list AP-pattern violations by severity.
/treasury-domain-architect Add cash-transfer workflow with audit, outbox, API routes, UI actions, and full tests.
First follow-up questions to finalize scope
- Start with review-only, or implement first vertical slice now?
- Which first slice:
bank-account, bank-statement, or cash-transfer?
- Do you want compact checklist output or full file-by-file implementation output?