Operational MCP failure diagnostics are available to tenant owners/managers through system.error-diagnostic.get and system.error-diagnostic.list. Records are bounded and retained for 30 days; see the operations guide.
Borrower list cards mask Thai national IDs by default. The card's copy action intentionally copies the complete stored value for authorized owner workflows; use the borrower detail or edit flow when the full value must be viewed or updated. The list adapts its card columns to the available content width, so a narrow main panel keeps one full-width card rather than a cramped half-width column. Borrower detail headers use a compact profile avatar on small screens and expand modestly on larger layouts.
CreditSync is a mobile-first loan management system for lenders who need to track funding sources, borrower profiles, loan contracts, repayments, and closing balances in one place.
On narrow screens, authenticated users get a role-filtered five-destination bottom navigation; the existing drawer keeps the other permitted destinations available. The page, footer, drawer, and AI assistant account for device bottom safe areas. The chat fits short mobile viewports, and the footer leaves room beside the floating assistant. Navigation labels are available in Thai and English.
The authenticated UI release footer displays the application, MCP schema, and private plugin versions, with a changelog link to the active codex/mcp-tool-discovery release branch until integration.
MCP clients can use the read-only tool.catalog.search capability when unsure which tool fits a request. It searches tool guidance metadata only, shows executable candidates from the active profile, and reports when another profile is needed; it does not read borrower records or run a matched tool. Reconnect to the relevant profile explicitly when a search reports connection_required.
In the MCP loan workflow, loan.cancel.preview persists a preview record. It is not a read-only or idempotent lookup; inspect the loan and its preview history before retrying, and use the separate cancellation execution only after reviewing current state.
The stack is built around Bun + Elysia on the backend, React + Vite on the frontend, PostgreSQL for relational data, MinIO for file storage, and Dragonfly for Redis-compatible caching.
CreditSync is designed for workflows like:
- Creating borrower profiles and storing their history
- Uploading ID card images and extracting text with OCR
- Creating loan agreements with single-payment, daily, weekly, monthly, or floating interest logic
- Generating installment schedules before confirming a loan
- Supporting weekly or monthly schedules with a borrower-agreed installment count: the backend derives the rate-based amount when no amount is supplied, while an explicit count-plus-amount pair creates a fixed-total schedule whose amount above principal is scheduled interest
- Capturing data-only or image-first repayments, reviewing matches, posting allocations, and reversing corrections
- Paying selected daily interest accrual dates from a floating-loan Accrual table, recording the actual Bangkok receipt time independently, and reviewing per-date receipt, advance-deduction, and legacy provenance before confirmation. Apply the current backend migrations first; historical receipts that conflict with later live principal or paid-penalty history require reconciliation review. If a post response is uncertain, resume the saved command with its original key; an expired unposted preview can be reviewed again against the same intake.
- Importing verified ChatGPT attachments into an existing loan-payout draft without creating a payment intake or posting money; every required attachment is inspected before a separate payout transition, and real mobile-device transport acceptance remains pending
Evidence declarations and accepted payment/payout evidence attempts are sticky safety requirements. CreditSync records the requirement before signing, download, DNS, or storage work, retains it when an attempt fails or is cleaned up, and requires every declared attachment to have an exact tenant-scoped finalized association before preview, posting, or activation. The Web disbursement editor keeps the selected draft and fields available after an evidence-blocked post, shows a localized safe blocker, and reuses the same idempotency key only when the operator manually retries. ChatGPT imports bind the tenant, target, idempotency key, and source-file fingerprint before network access; a changed descriptor under the same key stops for review without adding an attempt, while an exact retry resumes safely. When a legacy finalized association is first encountered, only its provable SHA-256 or source-fingerprint identity is seeded into the durable floor; known ChatGPT source aliases and direct content-hash aliases for the same association are not counted twice, and ambiguous identities are never inferred. The profile-bound read-only workflow.resolve endpoint reads only bounded authoritative target state and emits typed visible-tool guidance; it never authorizes a financial transition or invents future IDs, and if a host never reports an attachment, the backend cannot infer that file exists.
Cancelled duplicate reviews retain the ordinary strict evidence rule by default. Only an explicit, audited selection may use the canonical intake's single complete ready evidence for a cancelled, unposted duplicate that has exactly one persisted requirement, no effective evidence, and no authoritative attempts; selection is immutable and revalidated before replacement authorization. Exact participant identity decisions are available through payment.identity-decision.preview → confirmed payment.identity-decision.execute and the authenticated /payment-intakes/:id/identity-decision/* routes; previews show bounded amount, payer, and Bangkok business-time snapshots plus discrepancy seconds, and execution requires complete evidence for every connected participant unless that exact group has an existing audited canonical-coverage rule. Distinct decisions apply only to the reviewed pair, while same-payment groups are revalidated against current snapshots, ownership, evidence, and active postings. Mutable duplicate blockers enter this identity workflow before ordinary payment preview.
Payment recovery decisions are also explicit and append-only. Identity decisions snapshot the exact tenant-scoped participants and require a fresh preview, confirmation, reason, and idempotency key; effective same-payment components are transitive across valid decision snapshots, validated historical duplicate-review memberships, and replacement lineages, while superseded corrections are excluded and every active financial effect is rechecked before a posting exemption or group union. Identity-decision authorization also covers every connected member visible through those immutable relationships, including collector role boundaries. They do not rewrite posted or cancelled history and do not exempt a later third intake. A cancelled intake with failed or incomplete evidence follows payment.evidence-recovery.preview → confirmed payment.evidence-recovery.execute (or the matching authenticated REST routes) to create one linked recovery successor with a preserved requirement floor; any lower interpretation requires a confirmed, reasoned before/after requirement decision, and the successor remains blocked until its required evidence and ordinary payment preview are complete. A cancelled recovery successor can itself be recovered; evidence coverage follows only executed recovery receipts at every step and requires a complete final successor. When recovered groups are joined, each incomplete historical member must have its own authorized coverage; one successor need not cover unrelated recovery histories. Requesting a new identity preview clears the previous UI confirmation. Recovery is bounded by tenant-first deterministic identity locks and retries only confirmed PostgreSQL deadlock/serialization failures.
Concurrent same-tenant/kind/import-key races resolve to one durable binding and a stable conflict before a second download.
MCP clients can use the bounded read-only composite tools borrower.resolve-and-portfolio, loan.inspect-context, and payment.match-context for summary-first context. Each collection reports hasMore and an opaque nextCursor; follow named child cursors before presenting a portfolio, schedule, or payment history as complete. Ambiguous borrower resolution remains a candidate set, and these tools do not write or calculate financial values.
The MCP catalog provides typed purpose, prerequisites, side effects, retry safety, confirmation guidance, and related workflows for all 147 currently registered tools. Legacy and modern transports use the same tool descriptions and server instructions. Tool guidance describes how to use an operation; the advertised schema, service authorization, and current application state remain authoritative.
Payment-slip batches support an upload-first, human-review-only OCR step after staging evidence is finalized. The local OCR boundary returns candidate amount, Bangkok transfer time, payer/receiver, fee, and a hashed reference; it verifies downloaded bytes against the finalized evidence checksum, serializes extraction receipts by tenant/key, and does not create an intake, choose a borrower/loan, calculate accounting, or post money. Missing or ambiguous fields stay unresolved for manual review, and the existing evidence checksum/revision gates require a fresh preview after any change.
Unposted payment intakes can be explicitly cancelled from the Web inbox or MCP after inspecting the server-derived capability and confirming a reason/state hash. Cancellation retains the original evidence and audit history, excludes the intake from processing, and is not a refund or debt waiver. A cancelled intake may be replaced only through payment.replacement.inspect → explicit confirmation → payment.replacement.create; the replacement is a new draft with immutable evidence lineage and follows the ordinary preview/post workflow. Posted records continue through the existing compensating reversal workflow.
- Calculating closing balances for early payoff
- Tracking source-of-funds profiles and traceability between bank funding and downstream loans
- Receiving images from LINE webhooks and storing them for later processing
Release v0.4.46 includes the independently reviewed workflow resolver and sticky evidence guards, deployed on 14 September 2026 after a verified PostgreSQL/MinIO backup and isolated restore rehearsal. Combined backend/cache, frontend, plugin, typecheck, protocol and production verification is recorded in the acceptance matrix. Existing ChatGPT connections must refresh/reconnect and verify tool visibility; server verification does not prove that a real mobile attachment reached the importer. Real-host/device and long-running canary acceptance remain explicit.
The repo already contains a working MVP foundation:
- Google sign-in and JWT-based session flow
- Multi-tenant backend model using
tenant_id - Borrower CRUD
- File upload to MinIO / S3-compatible storage
- OCR endpoint for uploaded ID-card-like images
- Loan calculation plus draft-review-activation flow
- Payment intake, evidence, review, grouped allocation, posting, and compensating reversal workflow
- Historical payment reconciliation for reviewed
needs_reviewintakes and fully compensated, finalized-evidence-backedreversedsources. Areadybackdated floating payment blocked by later immutable allocations first passes rollback-only preflight, then requires explicit confirmation for the auditedpayment.reconcile.mark-reviewtransition; a fresh reconciliation preview requires a second confirmation before execution. The preview exposes the backend chronological temporal-reflow impact, and execute returns its durable reflow-group identifier. Existing executed legacy reconciliations with complete interest-only provenance can usepayment.reconcile.reflow.preview→ explicit confirmation →payment.reconcile.reflow.execute; original transactions remain immutable and missing/unsupported provenance is held.payment.reconcile.*remains interest-only, whilepayment.restore.*creates one linked child with the exact original component split and retains source evidence unchanged - Same-loan scheduled-payment allocation correction through
payment.allocation-correction.preview→ exact before/after review and zero-variance conservation → explicit confirmation →payment.allocation-correction.execute. It preserves the posted intake and original transaction, appends one compensation and one replacement, and stops on floating, cross-loan, overpayment, duplicate, stale, or downstream-dependent states. Only an executed renewal's verifiedprincipal_transferandcash_payoutopening ancestors on the renewal-created loan are exempted from dependency warnings; all unknown or unrelated adjustments remain blockers and opening lineage participates in stale-state validation. Production repair remains a separately authorized post-deployment operation requiring a fresh preview. - Atomic payment batches use an upload-first staging/review boundary:
/payment-batches/stagecreates resumable tenant-scoped slip drafts without inventing amount or transfer time;GET /payment-batches/:id/workspaceresumes that workspace with public staging status, revision, evidence readiness, and review links; staging evidence is prepared/finalized before review records normalized fields and creates the intake. The authenticated REST workflow and direct MCP tools (payment.batch.stage, staging evidence prepare/finalize, workspace,payment.batch.candidates, review/edit, split, decision, cancel, preview, execute) use the same application services and strict public UUID/money/date contracts. Candidate discovery returns bounded tenant/portfolio-authorized named borrowers and backend-calculated scheduled/floating contract projections, with separate current due components and input-specific proposal components plus revision-bound fingerprints; fuzzy or multiple matches remain human decisions and are never auto-mapped. Draft staging edits are revision/reason/idempotency bound, mapping-aware, and invalidate previews; reviewed borrower mappings remain authoritative per item, including borrower-only mappings, and explicit multi-contract allocations must stay within that borrower. Automatic planning uses Bangkok business dates, holds a unique sum spanning multiple contracts until an explicit human selection, and sorts slips chronologically./payment-batches/:id/splitmoves selected unposted membership atomically into a provenance-linked batch without duplicating intakes or evidence; runtime holds are derived from the actual borrower/date chronology so a ready prefix is not blocked by a later held source member. The batch then requires chronology-aware preview, explicit confirmation, stable idempotency, and atomic execute. Calendar gaps, duplicate/ambiguity/mismatch, missing provenance, or changed semantics hold the whole batch; no capture or review path posts financial records. - Payment-batch cancellation is an explicit reasoned, revision-bound, idempotent operation; a stale or replay-conflicting cancel request does not alter the batch.
- The Web batch workspace now presents the bounded four-step capture → human review → chronology → confirmation flow: capture 1–50 files and evidence first, enter human-confirmed amount/time afterward, resume staged work after refresh or connection loss, reselect a file against its stable pending staging row without duplicating evidence, choose named borrower/contract candidates and explicit multi-contract amounts, then execute only the latest ready preview. Preview renders backend-confirmed chronological allocations and translated component breakdowns; split shows the destination batch, exact moved members, and dependency before navigation, while cancellation produces a terminal receipt and isolates a genuinely new draft's keys. It never auto-posts from OCR or accepts manually typed internal UUIDs; backend candidate/accounting services remain authoritative. Missing OCR remains an explicit manual-review state.
- If a receipt request loses its response, retry the same request before leaving. Evidence failures retain a link to the saved receipt; Cancel requires confirmation for saved or uncertain requests and supports keyboard navigation. Supporting-file selection follows the app language; locally duplicated files can be removed before any receipt is created. Per-contract allocation totals and slip differences retain exact decimal precision.
- Daily-loan renewal preview, confirmed execution, and compensating reversal workflow
- Single-payment settlement/restructure preview, explicit confirmation, component waivers, replacement contracts, and compensating reversal workflow
- Explicitly confirmed, idempotent unfunded-loan cancellation preview/execute workflow, guarded by zero actual disbursement, no effective posted payment, and no downstream financial activity
- Owner/manager scheduled-loan replacement preview, confirmed execution, public lineage, and compensating reversal workflow
- Scheduled-loan payment deferral with append-only source/replacement history, visible deferral counts, and inline request errors
- Legacy repayment-history reads remain available; repayment writes use the payment-intake workflow exclusively
- Closing summary calculation for loans
- LINE webhook ingestion for image uploads
Some screens are still mock/demo oriented and not fully wired to live backend data yet, especially:
- dashboard analytics
- fund detail dashboards
- graph-based portfolio visualization
- some deeper bank-funding traceability flows
- Google Sign-In for web login
- JWT auth between frontend and backend
- role model prepared for
owner,manager,collector, andviewer - multi-tenant data separation
- tenant admins (
owner,manager) can see all tenant data, whilecollectorandvieweraccounts are scoped to records they own - first Google login in a tenant becomes
owner; later auto-created users default toviewer
Account identity and tenant role are read-only values supplied by the authorized Google and tenant account. The protected /settings page provides immediate Thai/English language and Light/Dark/System appearance preferences for the current device; these preferences are not synchronized through the backend. Signing out removes the local CreditSync session while retaining display preferences.
- create and edit borrower profiles
- search canonical names and confirmed aliases without auto-selecting ambiguous matches
- manage borrower aliases and view borrower portfolio summaries
- confirm or deactivate aliases and review borrower/alias audit revisions with request and correlation identifiers
- store phone, address, tags, notes, and map links
- attach ID card image
- OCR text extraction to help fill borrower data
The MCP loans profile supports deferring one fully unpaid installment on an active scheduled loan. Inspect and select the exact schedule first, review the replacement date and component amounts, then obtain explicit confirmation; deferral adds a replacement schedule row and audit record without creating a payment.
- filter the Loan List between Active, Done, and All agreements while retaining search, status, funding, and sort controls
- group multiple Loan List cards under the canonical borrower name while retaining the same card layout and interactions
- view Loan Detail repayment and payment-history tables with row numbers, total-record counts, configurable page sizes, summary counts, and clear paid/due/overdue status indicators
- calculate repayment schedules before saving
- support
single_payment,daily,weekly,monthly, andfloatingrepayment types - preview and persist exact single-payment due dates, agreed fixed-interest floors, optional greater-of retroactive interest, and contracted late penalties before activation creates one immutable maturity row
- preserve legacy floating contracts as daily-accrual while allowing new floating terms to state an explicit
daily,weekly, or calendar-monthly accrual cycle; weekly preview exposesfullPeriodInterest,firstPeriodStartDate,advanceInterestAmount,netDisbursement, the inclusivecoveredStartDate/coveredEndDate, the excludedfirstPeriodDueDateand matchingnextAccrualDate, plusadvanceInterestRefundPolicy: "non_refundable"; for a 10 August anchor the covered dates are 10–16 August and the due/next-period boundary is 17 August - accrue a weekly rate proportionally into immutable daily snapshots, make it normally payable only at the seven-day boundary anchored to
interestStartDate, and charge it as one paid, non-refundable first period whendeductis selected; overdue floating penalties use an append-only dated due-group ledger, exact penalty/interest transaction allocations, compensating adjustments and reasoned reversals, and pure as-of closing/health projections that never rewrite financial history; migration creates an exact Bangkok cutover for every legacy floating loan, while backdated payments stop for reconciliation if they would overlap later immutable allocations - manage effective-dated floating-interest periods from Loan Detail, including exact current daily interest, future scheduled changes, previewed automatic range splitting, and audited confirmation
- pay one or more selected floating daily-interest accrual dates from Loan Detail, record the actual Bangkok receipt time independently, review exact target allocations and other unpaid obligations, and recover a posted receipt safely after refresh failures; historical previews allow safe disjoint interest receipts but stop for live later principal, penalty, overlap, or stale-ledger conflicts rather than waiving or redistributing them
- create editable loan drafts, then activate them to lock terms and generate schedules exactly once
- use separate preview, draft-save, and activation confirmations in the web wizard
- distinguish due-now and overdue scheduled or floating daily-interest obligations directly on the loan-agreement list before opening details
- present responsive Loan List cards as collection-first summaries with grouped arrears, overdue age, contract terms, localized dates/currency, profile metadata, and actionable unassigned-agent state
- show up to three borrower labels under each loan card name, using confirmed aliases first and borrower tags after, with a localized
+Noverflow when more labels exist - search loan lists by borrower name, loan ID, aliases, and tags, including hidden overflow labels
- show the current loan agent (or localized unassigned state) on Loan List cards and include confirmed agent aliases in search
- scan exact Loan List financial summaries: non-paid cards keep outstanding and original principal together with backend-owned interest-received and paid-to-date totals, while paid cards show a checked completion state with original principal and interest received
- show compact contract IDs on Loan List cards with a copy action that copies the full public ID
- preview installment breakdown
- calculate floating closing obligations from current outstanding principal, unpaid due and accruing interest, outstanding fees, and applicable penalties while reporting payment history separately
- record actual borrower cash, bank-transfer, or adjustment disbursements independently of approved loan terms
Single-payment contracts keep principal, agreed interest, fees, and late penalties as separate exact components. A contract can use the agreed fixed interest only, or the greater of that fixed amount and retroactive interest calculated from actual posted-disbursement exposure; those two interest candidates are alternatives and are never added together. When contracted, the daily late penalty accrues concurrently after the due date and grace period. The localized wizard shows the authoritative one-row maturity preview before a draft is saved and activated.
Loan Detail can settle and restructure an eligible contract into a new single_payment, daily, weekly, monthly, or floating contract. The backend preview shows gross, waived, externally paid, and carried balances independently. Waiving interest, fees, or penalties requires a component-specific reason and preserves the forgiven amount in the append-only ledger; an external payment is different because it is allocated as real settlement value in penalty -> fee -> interest -> principal order. Outstanding principal plus optional newly approved principal becomes the replacement principal—carried interest, fees, and penalties are opening components and are not capitalized. Additional approved principal is not itself proof of cash sent: execution creates a linked disbursement draft whose normal evidence/post lifecycle remains authoritative for the payout.
Loan Detail keeps the existing agreement route and back navigation while separating Information, Agents, Payment History, and Repayment Schedule into accessible, localized tabs. Agent agreements are effective-dated in the Asia/Bangkok business timezone and confirmation-gated; posted payment sources remain Unattributed until explicitly assigned as direct or split among agents, and displayed total and per-schedule commissions come from backend-authoritative previews rather than client-side accounting. Repayment and payment-history tables support localized pagination with 10, 20, 50, 100, or all rows per page.
Restructure is preview -> review exact totals and cash direction -> explicit confirmation -> execute. Preview expiry, a stale balance version/hash, an idempotency conflict, an unallocated external credit, or unexpected cash stops execution. A safely repeated request with the same key and payload returns the original result. Reversal writes compensating history and is blocked after downstream payments, posted payout events, later waivers/restructures/renewals, or other dependent records make reversal unsafe. Later eligible carried interest/fee/penalty can be waived through its own preview/confirmed execute/reverse workflow; principal cannot be waived.
Scheduled-loan replacement is available only to tenant owners and managers. It is preview -> review exact backend balances, corrections, dates, named funding source, structured warnings, and no-cash amount -> explicit confirmation -> execute; the client does not recalculate financial values. The Web renders Bangkok business dates and preview expiry as Gregorian DD/MM/YYYY in English and Thai and preserves the warning's exact amount and correction semantics. Preview expiry, stale balance/draft versions, or a nested backend reviewRequired blocker removes execution authority, displays any safe blocker public IDs, and requires a new preview. After execution, the original agreement is terminal replaced (shown in Done and All as Closed — Replaced, never Paid); durable query invalidation refreshes the Loan List plus both public loan details even across route navigation, and Loan Detail provides public source/replacement links. Reversal is a separate compensating command requiring its own non-blank reason, checkbox confirmation, and idempotency key; it remains subject to downstream safety checks. Once a safe reversal restores the old loan, its retained reversed lineage does not prevent a later fresh replacement preview.
The authenticated REST surface is mounted below /api/loans: list/inspect and preview use /:loanId/restructures, execution/reversal use /restructures/:restructureId, component waivers use /:loanId/waivers and /waivers/:waiverId, and durable early settlement uses /:loanId/early-settlement/preview followed by /early-settlement/:previewId/execute. Every financial execute/reverse request carries a non-blank reason and Idempotency-Key; execute also carries the exact confirmation/hash/version fields returned by preview. The Web workflow calls these adapters but renders only backend-calculated money and schedules.
Daily-loan renewals use the authenticated /loan-renewals API:
POST /loan-renewals/previewacceptsoldLoanPublicId,requestedPrincipal, an explicit settlement policy, and reasonedfee,penalty,other_charge, orwaiverlines. Scheduled daily renewals default tofull_contract_interest;accrued_to_datemust be selected explicitly.POST /loan-renewals/:id/executerequires the persistedpreviewHash,confirmed: true, a non-blankreason, and anIdempotency-Keyheader. A collection result also requires the explicitconfirmedCashDirection: "collection"acknowledgment.POST /loan-renewals/:id/reverserequires a non-blankreasonandIdempotency-Keyheader. The web client retains each execution or reversal key while the same intent is retried and replaces it only when the preview or operator reason changes.
Renewal previews derive principal from posted, non-reversed transaction components. The manual Web flow displays the backend's payment history, full and received old-contract interest, each reasoned adjustment, recovered amount before adjustments, exact payout or collection, and replacement schedule without recreating money arithmetic in React. Under the default policy, all remaining interest of the old contract is settled at renewal; this reduces the cash paid out and is not described as refundable principal. Any edit discards the approval snapshot and requires a fresh preview. Execution locks and recomputes balances, due-day charges, penalties, and funding at execution time; previews become stale when any hashed state changes. Funding mutations and renewals serialize on the borrower loan before reading allocation state, and funding carry uses deterministic integer-cent largest-remainder allocation with tenant-safe renewal/group provenance. The outstanding-principal transfer is non-cash; only the net payout or collection is recorded as borrower cash. Reversal keys are operation-scoped, exact pre-execution loan state is restored, and reversal is blocked only by net active downstream transactions, adjustments, or funding before append-only compensations are written. Invalid RENEWAL_PREVIEW_TTL_SECONDS values fall back to 900 seconds.
- record repayments manually through payment intakes
- capture repayments from a loan detail with borrower-first contract filtering, then review allocation in Payment Inbox before posting
- upload repayment slips
- link payment to a loan
- show repayment history
- create data-only payment intakes, preserve existing Web UI signed S3/MinIO evidence PUTs, or securely import official ChatGPT top-level file parameters through an exact HTTPS host allowlist
- detect tenant-scoped operation, bank-reference, QR-payload, and evidence-hash duplicates without treating semantic similarity as a duplicate
- preview deterministic matches, review ambiguous matches, and split one intake across borrowers, loans, and schedules
- post schedule, loan, and fund effects atomically, then correct posted payments with append-only compensating reversals
- reconcile approved historical
needs_reviewallocations or restore a fully reversed evidence-backed source throughpayment.restore.create→payment.restore.evidence.prepare→ signed PUT →payment.restore.evidence.finalize→payment.restore.preview→ exact review → explicit confirmation →payment.restore.execute; an unwanted unposted restore draft followsintake.get→ explicit confirmation →payment.restore.cancel→intake.getverification. Restore cancellation preserves the reversed source, restore evidence, and append-only history, creates no transaction/refund/balance change, and a cancelled child permits a later restore only with a new create key. Ordinary payment posting also requires the no-write preflight against the latest ready proposal. Restore returns source/child UUID lineage, copies the immutable original component split, and never copies bank-reference or evidence data - replace an authorized cancelled, never-posted payment through
payment.replacement.inspect→ explicit confirmation →payment.replacement.create; this creates an audited draft only, retains the original amount/payer/receivedAt and references immutable finalized evidence. Re-inspect the current loan schedules, then use ordinarypayment.preview→ fresh ready/zero-variance confirmation →payment.post. This is separate from reversed-payment restore, cannot fork a lineage, and a cancelled successor may be replaced again. - resolve an exact reviewed semantic duplicate through
payment.replacement.duplicate-review.preview→ explicit confirmation →payment.replacement.duplicate-review.execute. The tenant-scoped append-only review ledger authorizes only its exact cancelled candidates after rechecking cancellation provenance, amount, received timestamp, normalized payer, dependencies, hard identities, expiry, lineage, and ownership. It creates no payment or balance change; replacement and ordinary ready/zero-variance preview/post guards still run afterward. A reviewed duplicate may have no evidence only when the canonical cancelled source has complete finalized evidence; stale, ambiguous, conflicting, or newly introduced duplicates remain blocked. - reject reconciliation, restore, allocation-correction, and temporal-reflow execution when an actually consumed payment intake has a sticky required attachment that is pending or rejected; a data-only intake with no known attachment attempt remains valid, and an already successful idempotent replay returns its original receipt before the guard
- stop floating-payment allocation when legacy daily-interest rows have an invalid zero-principal basis, and repair those rows through an idempotent append-only correction with adjustment and audit history
The authenticated payment API is rooted at /payment-intakes. It exposes create/list/get and review-queue operations, /:id/evidence/upload-intents, /:id/evidence/:evidenceId/finalize, /:id/match-preview, /:id/post, /:id/review, and /:id/reverse. REST reversal requires a non-blank operator reason, which is preserved in the audit event. To preserve the frozen MCP schema-version 1.0 contract, payment.reverse continues to accept the legacy { paymentIntakePublicId } input and uses a stable compatibility audit reason when the optional reason is absent; new MCP callers should provide it. All command IDs are UUIDs and all public money values are two-decimal strings. GET /transactions remains available for legacy repayment history, but POST /transactions returns 405 LEGACY_REPAYMENT_WRITE_DISABLED; all repayment writes must use /payment-intakes so one Decimal allocator and one PostgreSQL lock order govern balances.
Loan detail repayment history is available from GET /loans/:loanPublicId/payment-intakes. A quick capture records an optional originLoanPublicId on the intake, then opens Payment Inbox for allocation preview and posting; it never posts a repayment directly. Older payment records remain discoverable through their existing transaction or latest allocation links.
Payment Inbox presents incoming payments as a responsive flat list and loads 25 newest-first records per page. Operators can search payer names and filter by status or an inclusive Asia/Bangkok received-date range; changing a filter returns to the first page while refresh and payment actions retain the active view.
The authenticated loan-disbursement API is rooted at /loans/:loanPublicId/disbursements. It provides list, draft create/update, /:disbursementId/evidence/upload-intents, /:disbursementId/evidence/:evidenceId/finalize, /:disbursementId/post, and /:disbursementId/reverse operations. Gross transfer and loan-attributed amounts are exact two-decimal strings; grouped transfers require a note. Draft commands deliberately reject evidenceFilePublicIds: create the draft first, then prepare a signed evidence upload and finalize that evidence against the draft. Post and reverse require an Idempotency-Key, and reversal also requires a non-blank reason. Restructure-created additional-principal payouts expose an immutable nullable restructurePublicId; note edits never change that linkage, and the relation is preserved on posting and compensating reversal. These ledger events do not change approved principal, schedules, or funding allocations.
Intermediary money is tracked as two linked ledgers. /intermediary-collections records the amount and time a borrower paid a collector without prematurely posting lender cash, while /intermediary-remittances records the gross transfer received from that collector. Operators explicitly select collections, preview an exact zero-balance proposal, optionally attach the remittance slip through evidence/prepare followed by direct signed PUT and evidence/:evidenceId/finalize, then post with confirmation and an idempotency key. Historical collections may reference an already-posted payment intake; CreditSync validates loan, timestamp, and exact amount and does not create a second repayment. The /intermediaries workspace provides canonical-name or confirmed-alias search, search-before-create review of both active and inactive exact candidates, localized profile-name and alias editing, exact managed-loan summaries linked to Loan Detail, assignment history, masked payment destinations, and unreconciled disbursement warnings. GET /intermediaries/:id/held-balance exposes the authenticated tenant-scoped exact funding, payout, advance-interest-return, disbursement-held, collection-held, and total-held projection used by that profile. Collection and remittance ledgers remain available at /intermediaries/remittances, including profile-scoped filtering.
Intermediary-routed loan payouts are a separate append-only ledger. After exact borrower/intermediary resolution and an active effective-dated disbursement assignment, CreditSync derives the contractual funding, borrower net payout, and advance-interest return targets from the immutable loan activation. Operators record each actual transfer and bind every supplied slip's evidence/file UUID plus immutable MIME, size, and SHA-256 across prepare, ready retry, finalize, and inspection. They may post only after inspected roles, references, amounts, payees, and evidence identities match, followed by a fresh explicitly confirmed proposal with ready evidence, no warnings, retained balance 0.00, and variance 0.00. Loan Detail and intermediary profiles show the three money-path roles, exact split transfers, safe transfer metadata, and one independently resolved View slip action per finalized evidence item; the confirmation remains disabled for expired or non-zero-variance proposals and any supplied evidence that is not ready. Confirmation and its idempotency key are bound to the exact proposal ID/hash; a stale or already-expired proposal is refreshed for review and must be explicitly confirmed again. After posting, the Web UI reloads authoritative group detail, actual loan disbursements, and intermediary held balance; a failed refresh is shown as a blocking warning so stale financial presentation is not treated as current. General MCP group/list inspection returns normalized reference displays and safe per-event evidence status/count/public IDs/MIME types; evidence viewing uses short-lived REST/Web UI access descriptors requested only when selected and discarded when the preview closes or unmounts, while MCP inspection excludes retrieval URLs, storage keys, and checksums.
The manual repayment form can record one receipt with exact allocations across multiple contracts and schedules. Supporting JPEG, PNG, or PDF files are optional and shared by that receipt; when files are attached, enter the amount shown on the slip and confirm the difference is zero. Without files, the receipt total is derived from the allocation rows. The form uses Bangkok time, retains a saved intake and file manifest for upload retries, and opens the same Payment Inbox review flow without posting automatically. Use Record separate transfers for a batch of independent receipts; that batch workflow is distinct from attaching multiple files to one receipt. Each participating contract's payment history shows its own allocated amount and links to the shared receipt review and evidence.
The web app exposes /payments as the human review inbox. It persists and shows semantic-duplicate warnings, requires an explicit warning acknowledgment, accepts optional signed evidence, edits any number of exact allocations across borrowers/loans/schedules, retains the previous proposal for a meaningful difference view, and requires a ready preview of the exact current editor revision before posting. Allocation edits are locked while previewing; every edit/add/remove/selection change invalidates the ready proposal, and stale responses are discarded. Reversal uses a separate reason-confirmation step. The manual repayment shortcut creates the intake and opens it in this review screen with the selected loan/schedule suggested; it never auto-posts or calls the disabled legacy write endpoint.
- define funding sources / bank profiles
- model upstream bank borrowing and downstream borrower lending separately
- prepare data structure for ROI and traceability analysis
- show each source's net borrower-loan allocations, including direct own-capital allocations and allocations routed through bank drawdowns
- upload files into MinIO
- store file metadata in PostgreSQL
- receive image uploads from LINE webhook
- keep incoming bot files separated from normal user uploads
| Area | Technology |
|---|---|
| Runtime | Bun |
| Backend API | ElysiaJS |
| Frontend | React + Vite |
| Styling | Tailwind CSS |
| UI Components | shadcn/ui style components |
| Database | PostgreSQL |
| ORM | Drizzle ORM |
| Object Storage | MinIO / S3-compatible storage |
| OCR | Tesseract.js |
| Auth | Google Sign-In |
| Infra | Docker Compose, Kubernetes manifests, Cloudflare Tunnel, Dragonfly |
.
├── backend/ # Bun + Elysia API
│ ├── src/db/ # schema and database connection
│ ├── src/lib/ # calculator, OCR, storage helpers
│ ├── src/middleware/ # auth middleware
│ ├── src/modules/ # auth, borrowers, loans, files, transactions, webhook
│ └── src/services/ # shared borrower and loan-application commands
├── frontend/ # React + Vite app
│ ├── src/components/ # reusable UI components
│ ├── src/layouts/ # dashboard shell
│ ├── src/lib/ # api client, auth helpers, i18n
│ └── src/pages/ # landing, login, dashboard screens
├── docs/ # ADRs and planning docs
├── plugins/creditsync/ # Private Codex plugin 9.1.0, skills, evals, and validation
├── k8s/ # Kubernetes manifests
├── docker-compose.yml # local development infra
├── docker-compose.infra.yml # production-style infra including dragonfly cache
├── docker-compose.app.yml # production-style app services
└── .env.production # production-style Docker config
The main entities in the current schema are:
userstenant_configsbank_profilesbank_loansborrowersloanstransactionsfilesbot_uploadsbank_transactions
This supports a traceability model where funding can originate from a bank profile / bank loan and then be linked to borrower loans and repayments.
For the production loan-schema reconciliation procedure, including the exact 16-column/9-constraint/1-index drift gate, backup/restore rehearsal, reviewed-artifact deployment, full catalog/fingerprint verification, rollback rules, and the inspect-first daily-loan/disbursement workflow, use the production reconciliation runbook. It is an operator procedure: do not run its production mutation steps without the required approvals and stop conditions.
- Bun 1.x
- Docker and Docker Compose
- PostgreSQL
- MinIO or another S3-compatible storage
- Google OAuth client ID
The simplest local path is:
docker compose up -d postgres minioThis uses docker-compose.yml, which is kept specifically for local development.
It is intentionally separate from the production-style Docker files.
This repo exposes:
- PostgreSQL on
localhost:5433 - MinIO API on
localhost:9000 - MinIO Console on
localhost:9001 - Dragonfly on
localhost:6381
Use these files as the starting point:
- root example:
.env.example - backend local env:
backend/.env - frontend local env:
frontend/.env
Important variables include:
DATABASE_URLGOOGLE_CLIENT_IDJWT_SECRETDEFAULT_TENANT_IDS3_ENDPOINTS3_PUBLIC_URLS3_BUCKETFILE_URL_TTL_SECONDSEVIDENCE_UPLOAD_TTL_SECONDSEVIDENCE_MAX_BYTESPAYMENT_PREVIEW_TTL_SECONDSRENEWAL_PREVIEW_TTL_SECONDSSTORAGE_PROVIDERCACHE_URLCACHE_TTL_SECONDSMCP_API_TOKEN_HASHESMCP_ALLOWED_HOSTSMCP_TENANT_IDMCP_ACTOR_EMAILDEPLOYED_AT(the explicit ISO 8601 deployment timestamp used by the frontend footer)MCP_RATE_LIMIT_MAXMCP_RATE_LIMIT_WINDOW_SECONDSLINE_CHANNEL_SECRETLINE_CHANNEL_ACCESS_TOKENLINE_TENANT_IDVITE_GOOGLE_CLIENT_ID
For file access, CreditSync stores an internal file reference and resolves it to a time-limited signed URL only when requested. Existing Web UI payment evidence continues to use direct signed S3-compatible PUTs with signed MIME, size, SHA-256 checksum, tenant, and intake metadata. ChatGPT attachment ingestion is a separate server-side path: configure CHATGPT_FILE_DOWNLOAD_HOSTS as an exact comma-separated HTTPS hostname allowlist, leaving it empty to disable imports. The backend rejects redirects, credentials, custom ports, unsafe DNS/IP results, unsupported MIME or magic bytes, and oversized responses; it stores verified JPEG, PNG, or PDF evidence in MinIO without returning attachment or storage URLs. EVIDENCE_UPLOAD_TTL_SECONDS defaults to 300, EVIDENCE_MAX_BYTES to 20971520 (20 MiB), and both PAYMENT_PREVIEW_TTL_SECONDS and RENEWAL_PREVIEW_TTL_SECONDS default to 900. Both evidence paths require STORAGE_PROVIDER=s3; existing Azure Blob reads/uploads remain available outside these workflows.
cd backend && bun install
cd ../frontend && bun installcd backend
bun run migratecd backend
bun run devBackend runs on:
http://localhost:3000
Swagger is enabled by the Elysia Swagger plugin.
cd frontend
bun run devFrontend runs on:
http://localhost:5173
The frontend uses /api as the API base path and expects Vite proxy configuration during development.
Protected app navigation now keeps the dashboard overview at /dashboard, while resource sections live at first-level routes such as /funds/:id, /borrowers/:id, and /loans/:id. URL-facing resource identifiers are moving to uuidv7-style public IDs, while internal numeric IDs remain in the database for joins and accounting logic.
In the authenticated layout, desktop users can collapse the sidebar to a 72px compact rail and expand it again. The sidebar header stays focused on the app mark and collapse control, while the account menu lives in the footer; theme and language preferences remain available on /settings. Icon navigation keeps localized tooltips and accessible names, and the preference is remembered in browser-local storage.
The tenant-admin dashboard is a Daily Command Center: it leads with exact cash due today, ranks only actionable exceptions by operational urgency, and shows compact borrower/fund repayment queues. Funding, reconciliation, and profitability remain available as secondary details. Each API-backed section loads and retries independently so one unavailable signal does not hide the rest of the operational picture.
Floating daily-interest arrears appear in the Dashboard as one borrower row per loan. The row aggregates exact interest payable, reports the number of overdue daily accruals and their maximum age, and opens repayment capture without inventing a fixed schedule.
Loan detail pages include an Accrual Table tab showing every accrued day through the current Bangkok business date for active floating loans, using the backend's read-only interest projection alongside persisted reversal and prepaid-period history. The table shows period dates and exact interest, paid and remaining amounts; opening it does not materialize ledger records. The floating interest summary uses the same current due-interest calculation, and daily advance-interest obligations are counted once. MCP accrual UUIDs continue to identify persisted ledger records.
Loan agreement creation is draft-first. POST /api/loans accepts a borrower and either an optional drawdown UUID (bankLoanPublicId) or an active own-capital profile UUID (bankProfilePublicId), never both, and returns a draft without schedules. Draft terms can be changed with PUT /api/loans/:id; POST /api/loans/:id/activate locks the terms, checks the selected source's signed remaining capacity, then creates schedules and exactly one initial funding allocation. Activation requires a stable idempotency key; an identical same-key retry returns the original result while a conflicting reuse stops. The web wizard groups own capital, bank drawdowns, and unallocated loans; an existing personal source can be explicitly converted to an own-capital pool at its detail page, with a default non-cash 2.00% annual opportunity-cost rate.
The funding matching workspace provides a searchable contract queue, exact live allocation and remaining-gap summaries, and a separate review step before any allocation is posted. The UI rejects amounts that exceed either the selected contract's remaining gap or the chosen funding source's remaining capacity; existing allocations remain append-only and corrections use the explicit reallocation workflow.
Funding-source detail pages expose GET /api/bank-profiles/:id/funding-usage. The page shows current net borrower-loan allocations for the source and can include settled loans for historical review. Own-capital pools use their credit limit less net allocations as available capital; they allocate directly to borrower loans and intentionally do not create bank-drawdown records. External-liability sources retain drawdown-based available credit while showing the borrower loans funded through their drawdowns.
Floating loans use an explicit one-day or one-week interest policy with a percentage or per-thousand rate and zero or one advance-interest period. The non-refundable advance treatment is explicit policy data. Daily accrual snapshots use Bangkok calendar dates and cumulative Decimal rounding, including daily projections within a weekly period; payments apply due accrued interest before principal, and an advance deduction is retained as immutable paid history.
Current floating obligations resolve the complete reversal lineage before applying the requested business-date cutoff. A voided receipt therefore cannot reappear as paid interest or penalty merely because its reversal was processed later; the original receipts, reversals, and audit timestamps remain available in the append-only ledger. Read-only projections include missing accrual dates without persisting them; successful payment posting materializes those accruals through the receipt date in the same transaction.
Floating-loan close-out is previewed for an exact Bangkok as-of date. The preview separately shows outstanding principal, due interest, accrued-not-due interest, fees, penalties, already-paid non-refundable advance interest, and the new settlement total. Execution requires the exact current preview hash, explicit confirmation, reason, and stable idempotency key. A changed balance or later accrual makes the preview stale and requires a fresh preview and confirmation; settlement never refunds the already-paid advance amount or edits prior financial records.
In the Web loan wizard, choose Floating, then select a daily or weekly interest period, a percentage or per-thousand rate, and whether to deduct one non-refundable period in advance. The review step displays the backend-produced full-period interest, advance deduction, net borrower payout, and first-period dates before the operator saves the draft and explicitly activates it. Loan Detail repeats those backend-owned contract values and compares the contract net payout with the effective posted gross disbursement; a difference is shown as an informational warning only and never changes principal, interest, schedules, or payout history. Draft and reversed disbursements do not trigger that warning. Loan Detail also labels due interest separately from still-accruing interest and provides the settlement workflow: choose the Bangkok settlement date, preview every exact component, enter a reason, check the confirmation for that preview, and execute. If balances make the preview stale, the page automatically loads a fresh preview and clears confirmation so the operator must review and confirm the new amounts.
Settlement and renewal previews and executions stop when the source loan has a known draft payout requirement that is pending or rejected. Restructure and temporal payment reflow likewise block a false-ready preview before creating replacement or reflow records, then recheck at execution. These alternate flows do not invent an attachment transport; unsupported evidence association remains human-review-only.
For a scheduled daily loan, the wizard can start from either the borrower’s proposed daily payment or a flat daily-interest term (% per day, baht per day, or baht per ฿1,000). Choose a duration in days or 30-day months; CreditSync derives the other value, displays flat daily/monthly/annual reference rates, and creates an exact schedule whose final row absorbs rounding differences.
Loan detail shows these fixed daily terms separately from the repayment schedule. It also identifies a direct own-capital allocation as a capital-pool allocation rather than an unmatched bank drawdown. The Disbursements card records actual borrower payouts independently from the approved principal and schedule: save an editable draft, optionally use the signed evidence-upload/finalize flow, then post it. Posted rows are immutable; corrections use a reasoned compensating reversal and a new draft. A grouped transfer must record the gross transfer and the amount attributed to this loan, with an explanation when they differ.
Active or paid daily-loan detail pages include the renewal control. The operator sees recovered principal, old outstanding principal, separate due interest/fee/penalty components, aggregate charges, waivers, settlement, net payout or collection, and the full replacement schedule before checking an explicit confirmation. Customer renewal summaries include a subtle finance watermark, a visually emphasized net-cash line, localized PNG download, and direct image copy when the browser supports the Clipboard API. Execution and reversal use separate stable retry keys and show explicit empty, unavailable, failed, or populated audit states with localized action labels.
Loan-facing REST payloads use public UUIDs for loans, schedules, funding profiles, drawdowns, and allocations. Public money inputs and outputs use two-decimal strings (for example, "500.00"). This includes schedule and closing reads, allocation/profitability summaries, and funding allocation/reallocation mutations. Generated schedules conserve the exact principal-plus-interest obligation: each row's principal, interest, and fee components equal its scheduled total and remaining due, with any cent residual carried by the final installment. Schedule money remains Decimal-safe internally and does not pass through JavaScript number, including for values above the safe-integer range.
For an own-capital pool, the profile profitability response also reports opportunityCostAccrued and economicSpread. Opportunity cost is calculated from each positive allocation date through the current Bangkok calendar date at the profile's annual rate; it is analytical only and never creates a borrower charge, cash movement, or financial transaction.
CreditSync serves a private stateless Streamable HTTP MCP endpoint at /mcp in the existing backend process. Each HTTP request gets a fresh MCP server and Web Standard transport; there are no server sessions or legacy SSE endpoints. The adapter invokes the same borrower, payment, loan, and renewal application services as the web API directly—it does not call CreditSync REST routes internally. The unauthenticated GET /mcp/health response contains only service status and schema version.
All MCP requests are bound to the server-side MCP_TENANT_ID and MCP_ACTOR_EMAIL. A client cannot submit or override tenant or actor identity. The configured actor must already exist in that tenant, and its normal CreditSync role/portfolio permissions still apply. Funding sources are list-only; the MCP surface has no generic SQL, arbitrary fetch, or funding mutation tool.
The backend schema-version 1.0 exposes the tools and count recorded in the generated contract at plugins/creditsync/references/mcp-tool-contract.json; the list below is an illustrative excerpt:
borrower.search borrower.portfolio borrower.create
borrower.update borrower.alias intake.get
intake.list intake.create evidence.prepare
evidence.finalize payment.preview payment.post
evidence.import-chatgpt-file
payment.evidence-supplement.import-chatgpt-file
payment.evidence-supplement.record
payment.reverse loan.preview loan.draft
loan.activate loan.interest-rate.list
loan.interest-rate.preview loan.interest-rate.execute
loan.settlement.preview loan.settlement.execute
loan.disbursement.list loan.disbursement.draft
loan.disbursement.update
loan.disbursement.evidence.prepare loan.disbursement.evidence.finalize
loan.disbursement.post loan.disbursement.reverse
loan.commission-participant.list loan.commission-participant.add
loan.commission-participant.update loan.commission-participant.end
loan.commission.preview loan.commission.list
loan.commission.calculate loan.commission.reverse
payment.intermediary-attribution.create
payment.intermediary-attribution.list
payment.intermediary-attribution.reverse
intermediary.search intermediary.create
intermediary.profile.get intermediary.bank-account.save
intermediary.managed-loan.list
intermediary.assignment.create intermediary.assignment.end
intermediary.disbursement.list intermediary.disbursement.get
intermediary.disbursement.create
intermediary.disbursement.event.create
intermediary.disbursement.evidence.prepare
intermediary.disbursement.evidence.finalize
intermediary.disbursement.preview
intermediary.disbursement.post intermediary.disbursement.reverse
intermediary.collection.list intermediary.collection.create
intermediary.remittance.get intermediary.remittance.create
intermediary.remittance.allocations.save
intermediary.remittance.preview
intermediary.remittance.evidence.prepare
intermediary.remittance.evidence.finalize
intermediary.remittance.post
renewal.preview renewal.execute
renewal.reverse funding-source.list
funding-allocation.preview funding-allocation.create funding-allocation.list
Tool inputs use public UUIDs and two-decimal money strings. Results include concise text plus structured content with schemaVersion: "1.0". Loan contracts expose independent startDate and scheduled-loan paymentStartDate; loan.contract.get and loan.payment-history.list provide authoritative read-only inspection, while loan.payment-start-date.update preserves posted payments, changes only unpaid due dates through an audit-linked database exception, and refreshes the derived next due date. Abandoned unactivated drafts can be removed with the explicitly confirmed, reasoned, idempotent loan.draft.delete command after dependency checks; active or posted contracts cannot use it. Active non-terminal loans may receive deferred funding through funding-allocation.preview, funding-allocation.create, and funding-allocation.list; allocations are append-only, idempotent, source-capacity checked, and do not rewrite loan terms. Loan commission participants are effective-dated immutable versions; updates append a successor, while payment-source attribution corrections append reasoned compensating entries. Commission outputs are derived by backend services from posted interest components and never by MCP arithmetic; loan.commission.reverse is a read-only preview for posted reversal payments and never returns write audit metadata. Actual commission-participant and payment-attribution writes require explicit confirmation and stable idempotency keys and return safe audit/correlation identifiers. Disbursement drafts support strict non-empty PATCH updates to editable metadata; each update retains finalized evidence and requires a re-list plus fresh confirmation before posting. Payment posting/reversal, idempotent loan activation, floating-interest execution and settlement/reversal, renewal execution/reversal, direct and intermediary-routed disbursement post/reverse, intermediary remittance posting, single-payment restructuring, and component waivers follow explicit confirmation and audit boundaries. Settlement and intermediated-disbursement previews persist short-lived versioned command artifacts; execution accepts only the exact current preview. Intermediary bank-account save, assignment create/end, and transfer-evidence prepare/finalize MCP results also return their audit public UUID and correlation UUID while their existing REST DTOs remain unchanged. Tool failures use the stable shape {code,message,retryable,reviewRequired,details} without internal stack traces.
Modern clients use the official @modelcontextprotocol/server/client 2.0.0 adapter with protocol revision 2026-07-28; the legacy adapter remains on @modelcontextprotocol/sdk 1.30.0. Modern discovery is paginated in deterministic 25-tool pages and returns opaque profile/catalog-bound cursors plus cache hints. Curated connections are available at /mcp/core-read, /mcp/payments, /mcp/loans, /mcp/disbursements, /mcp/admin, and the optional eight-tool read-only /mcp/discovery entry profile. Discovery provides metadata search and profile-filtered named help; connect to the required domain profile to use its tools, and avoid connecting to overlapping profiles simultaneously when one is sufficient. Profile membership is generated from explicit allowlists and does not replace tenant authorization. Provider-hosted deferred loading and native tool search depend on client/provider support; CreditSync metadata search does not automatically load hidden tools. After an authorized rollout, refresh or reconnect and check the catalog/workflow/guidance versions. See docs/operations/agent-mcp-plugin.md and the discovery verification report.
Generate a high-entropy client token and calculate its SHA-256 hash locally. Keep the raw token only in the MCP client secret store; CreditSync receives only its hash:
umask 077
CREDITSYNC_MCP_TOKEN_FILE=/secure/operator/location/creditsync-mcp-token
openssl rand -hex 32 | tr -d '\n' > "$CREDITSYNC_MCP_TOKEN_FILE"
test "$(wc -c < "$CREDITSYNC_MCP_TOKEN_FILE")" -eq 64
sha256sum "$CREDITSYNC_MCP_TOKEN_FILE"The no-newline write and 64-byte assertion ensure the digest covers the exact raw bearer bytes. Set the resulting 64-character digest in MCP_API_TOKEN_HASHES, set MCP_ALLOWED_HOSTS to the external request host (comma-separated, without a URL scheme), and configure the fixed tenant/actor. Load the raw file into the client secret without appending a newline, then connect to https://your-credit-sync-host.example/mcp.
For rotation, put the old and new hashes in MCP_API_TOKEN_HASHES separated by a comma, restart the backend, move clients to the new raw token, then remove the old hash and restart again. At most two unique hashes are accepted. Never commit the raw token, token hash, .env, or .env.production.
MCP_RATE_LIMIT_MAX defaults to 60 requests per MCP_RATE_LIMIT_WINDOW_SECONDS (also 60). Dragonfly is used when CACHE_URL is available; an in-process limiter remains active if the cache is unavailable. /mcp logs only sanitized event, tool, status, request/correlation ID, and timing fields—never authorization headers or tool arguments.
The repository includes CreditSync Plugin 12.0.0 under plugins/creditsync, synchronized with the current 147-tool catalog and seven profile snapshots. It retains 11 orchestration skills and adds generated tool guidance, bounded Thai/English metadata search, profile-filtered named help, and an optional read-only eight-tool discovery profile. Search and help return metadata only; they neither authorize nor execute operations. Financial workflows remain separate closed-schema tools and require their own current-state checks, applicable evidence gates, and explicit confirmation. The plugin does not bundle a local MCP process, bearer token, OAuth, hooks, or plugin UI. Host/client acceptance is separate from local validation and remains unverified until tested against an authorized deployment and supported client.
Before installation, register the deployed MCP endpoint as a private Codex app and replace the conspicuous plugin_asdk_app_REPLACE_AFTER_PRIVATE_REGISTRATION value in plugins/creditsync/.app.json with the returned plugin_asdk_app... technical ID. Then validate the package, add this Git repository as the marketplace that tracks main, and install the plugin:
bun test plugins/creditsync/tests/plugin-contract.test.ts
bun run plugins/creditsync/scripts/validate.ts
python3 /home/flintstone/.codex/skills/.system/plugin-creator/scripts/validate_plugin.py plugins/creditsync
codex plugin marketplace add FlintsLabs/CreditSync --ref main
codex plugin add creditsync@creditsync-marketplaceThe Git marketplace snapshot reads .agents/plugins/marketplace.json, which resolves the plugin at ./plugins/creditsync inside the same snapshot. After pushing a validated plugin change to main, refresh the snapshot and reinstall:
codex plugin marketplace upgrade creditsync-marketplace
codex plugin add creditsync@creditsync-marketplaceA push does not hot-reload the installed copy. After an authorized rollout, refresh/reconnect the MCP profile, compare the advertised catalog/workflow/guidance versions with the plugin references, and start a new Codex task so updated skills and the app are discovered. The committed app ID is intentionally a non-runnable registration placeholder, so static validation is not evidence of a live private-app connection.
See docs/operations/agent-mcp-plugin.md for Cloudflare, token rotation, MinIO evidence, private registration, and rollback; docs/operations/workflow-resolver-acceptance.md for the implementation/host/device acceptance split; and docs/operations/backup-recovery.md for database/object backup and isolated restore verification. Resetting backend tests always uses a separate synthetic disposable database, never a restored real-data database.
| Scenario | Infra | Backend | Frontend |
|---|---|---|---|
| Local development | docker compose up -d postgres minio |
cd backend && bun run dev |
cd frontend && bun run dev |
| Production-style Docker | docker compose --env-file .env.production -f docker-compose.infra.yml up -d |
docker compose --env-file .env.production -f docker-compose.app.yml up --build -d backend |
docker compose --env-file .env.production -f docker-compose.app.yml up --build -d frontend |
Use bun run dev when you are actively developing features locally.
Use the split Docker files when you want production-like containers, Nginx proxying, or selective rebuilds for frontend and backend.
docker-compose.yml: local development infra only. Use this when you want Docker forpostgresandminio, but still runbackendandfrontendwithbun run dev.docker-compose.infra.yml: production-style infra. Use this for long-livedpostgres,minio, anddragonfly.docker-compose.app.yml: production-style app services. Use this to build and redeploybackendandfrontendindependently from infra.
For a production-style Docker setup, this repo separates infrastructure from application services:
docker-compose.infra.ymlforpostgres,minio, anddragonflydocker-compose.app.ymlforbackendandfrontend.env.productionfor Docker production-style variables
Fill in the real values in:
At minimum, update:
GOOGLE_CLIENT_IDGOOGLE_CLIENT_SECRETVITE_GOOGLE_CLIENT_IDJWT_SECRETCORS_ORIGINSS3_PUBLIC_URLFILE_URL_TTL_SECONDSCACHE_URLCACHE_TTL_SECONDSMCP_API_TOKEN_HASHESMCP_ALLOWED_HOSTSMCP_TENANT_IDMCP_ACTOR_EMAIL
docker compose --env-file .env.production -f docker-compose.infra.yml up -dDEPLOYED_AT="$(date -u +%Y-%m-%dT%H:%M:%SZ)" \
docker compose --env-file .env.production -f docker-compose.app.yml up --build -dSupply the deployment timestamp once for the Compose invocation. The frontend displays the same value after refreshes and frontend container restarts. If the variable is omitted or invalid, the footer shows a localized unavailable message rather than using the browser or container clock.
The frontend writes /deployment.json from this runtime environment value on container startup. It preserves an existing value in the container and serves the exact route with Cache-Control: no-store; it is not a build timestamp or browser-generated time.
This exposes:
- frontend on
http://localhost:8088 - PostgreSQL on
localhost:5436 - MinIO API on
localhost:9012 - MinIO Console on
localhost:9013 - Dragonfly on
localhost:6381
The frontend container serves the React app through Nginx and proxies /api and /mcp to the backend container. The MCP proxy keeps authorization, protocol, request, and correlation headers, disables response/request buffering, and uses extended read/send timeouts.
When Cloudflare Tunnel is enabled in Docker, it should run on the shared creditsync_runtime network so hostnames like frontend, backend, and minio resolve directly inside the tunnel container.
The infrastructure Compose file also includes the optional OpenAI Secure MCP Tunnel client as tunnel-client. It joins creditsync_runtime and forwards ChatGPT Developer Mode traffic to http://backend:3000/mcp. Set TUNNEL_CLIENT_VERSION, CONTROL_PLANE_TUNNEL_ID, OPENAI_TUNNEL_API_KEY_FILE, and CREDITSYNC_MCP_AUTHORIZATION_FILE, then start it with --profile openai-mcp; the two credential files are mounted as Compose secrets and must not be committed. The service uses the official ghcr.io/openai/tunnel-client image. See docs/operations/handoff-openai-secure-mcp-tunnel.md for setup and verification.
Rebuild only backend:
docker compose --env-file .env.production -f docker-compose.app.yml up --build -d backendRebuild only frontend:
docker compose --env-file .env.production -f docker-compose.app.yml up --build -d frontendBackend tests can be run with:
cd backend
bun run test
bun run typecheckbun run test uses the disposable PostgreSQL runner, which supplies the database URL required by database-backed service, migration, and MCP diagnostic tests. For a focused run, append test file paths, for example bun run test src/services/mcp-diagnostic-service.test.ts.
Frontend verification uses both its Bun-native discovery gate and the configured Vitest suite:
cd frontend
bun test
bun run test
bun run lint
bun run buildThe scoped browser acceptance harness uses a synthetic local tenant and a locally signed test JWT. It mocks only the API/OCR boundary, never uses production credentials or financial data, and captures the batch upload → OCR review → chronology preview → confirmation → receipt screens:
cd frontend
bun run test:e2eThis browser harness is UI workflow evidence; backend financial invariants and real OCR runtime checks remain separate disposable/test-only gates.
MCP local acceptance uses the backend-scoped commands (the repository has no root package):
bun run --cwd backend test src/mcp/contract-snapshot.test.ts src/mcp/server.test.ts src/mcp/modern.test.ts src/mcp/profiles.test.ts
bun run --cwd backend typecheck
bun run --cwd backend mcp:discovery:benchmark
MCP_CONFORMANCE_ROOT=/tmp/verified-mcp-conformance bun run --cwd backend mcp:conformanceThe generated catalog and profile index are the source of truth for tool membership and counts. Legacy full discovery remains unpaginated, curated/modern discovery is paginated, and real iOS/Android payment and payout attachment transport plus canary rollout remain pending. The targeted test command above uses disposable PostgreSQL; do not treat this targeted acceptance set as the full backend suite.
The MCP verification handoff records the tested implementation commit, complete disposable backend results, separate cache coverage, conformance evidence and remaining runtime acceptance gates.
The initial 2026-09-13 recovery hold was traced to an overly broad checker: pending upload reservations and valid batch staging metadata must not be classified as lost finalized evidence. The backend was subsequently deployed after corrected recovery checks and a fresh backup; the frontend image was retained. Run bun run --cwd backend scripts/check-evidence-recovery.ts with explicit database/storage configuration for the read-only, lifecycle-aware gate, and bun test backend/scripts/evidence-recovery-policy.test.ts for its regressions. Pending warnings never authorize posting or imply attached evidence. See the handoff report for artifact, migration, deployment and backup evidence; mobile acceptance remains pending.
The resolver acceptance matrix separates local implementation evidence from host/profile adoption, real-device file transport, and supervisor-controlled deployment. A repository fixture or /mcp test never marks those external gates passed.
The cancellation browser suite uses a separate local port (5197) and mocked API data. It checks explicit batch navigation, confirmation, retained history, and Bangkok timestamps from a browser outside Thailand:
cd frontend
bun x playwright test --config playwright.cancellation.config.tsSet PLAYWRIGHT_CHROMIUM_EXECUTABLE to an existing Chromium executable when not using Playwright's bundled browser. For a resource-constrained machine, run the full Vitest suite with bun run test --maxWorkers=2.
frontend/bunfig.toml preloads the local Happy DOM and Testing Library matcher setup for Bun-native DOM tests; Vitest continues to use its separate jsdom configuration for the full frontend suite.
Vitest automatically disables Node's native webstorage in test workers when the runtime supports that option, so jsdom supplies browser storage on Node 26 without a manual NODE_OPTIONS override. Tests discovered by Vitest must import test APIs from vitest, not bun:test.
Database-backed service tests are opt-in and require TEST_DATABASE_URL to point to a disposable database. To create an isolated ephemeral PostgreSQL 18 container with a dynamically assigned host port, migrate it, run a focused test, and remove it automatically:
./backend/scripts/test-disposable-postgres.sh src/services/loan-disbursement-service.test.tsThe script deliberately does not use the local development database. To use a separately provisioned disposable database instead, set both DATABASE_URL and TEST_DATABASE_URL to that database before running bun test.
With no focused file argument, the disposable runner drops and recreates the disposable public/drizzle schemas, applies the current migrations, and executes every backend test file in a separate Bun process. Each test process receives an explicit runner-owned database URL, preventing stale migration journals or timed-out transactions from leaking across files; it does not change per-test timeouts, assertions, or skipped-test policy.
Current tests cover:
- OCR smoke test
- loan schedule calculation
- loan closing summary calculation
This repo also includes:
- Dockerfiles for frontend and backend
- Kubernetes manifests under
k8s/ - Cloudflare Tunnel support for exposing services securely
If you deploy publicly, do not commit real secrets. Keep OAuth credentials, JWT secrets, tunnel tokens, and bot credentials in env files or secret management only.
Additional planning and architecture notes:
- docs/implementation_plan.md
- docs/adr/001-tech-stack.md
- docs/adr/002-storage-strategy.md
- requirement.md
- Agent/MCP/plugin operations
- Backup and recovery
If the next goal is making this production-ready, the highest-value areas are:
- replace remaining mock dashboard data with live API data
- complete bank funding to borrower traceability screens
- add stronger RBAC enforcement per route
- add due-date reminders and notification workflows
- improve repayment matching for bulk transfers and slip verification
- harden secret handling and deployment configuration
MCP capability discovery is available through the read-only search and /mcp/discovery profile. Search metadata, then resolve current financial workflow state and use the named inspect/preview/confirmation flow; search and named help never authorize writes. Generated tool guide and per-profile snapshots live under plugins/creditsync/references/. Clients with host-native deferred tool search or dynamic tool allowlists may use those documented APIs where supported; CreditSync cannot dynamically load hidden commands in every ChatGPT/Codex host. Avoid overlapping profile connections. After a catalog rollout, check the catalog version and refresh/reconnect the connection, then start a new task. listChanged is not advertised. Host/model acceptance remains unverified by local synthetic tests.