@venlyfinance/settlement-mcp 0.6.0 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/AGENTS.md CHANGED
@@ -9,7 +9,7 @@ You are building a financial product UI on `@venlyfinance/react`. These rules ex
9
9
  3. **Never place `clientSecret` in browser code.** The provider throws if you try. For browser apps use `proxyClientOptions()` against your own backend route.
10
10
  4. **Money movement is stage-then-confirm.** Render a review step showing `state.staged` (the exact request) before calling `confirm()`. Never wire a form submit directly to execution.
11
11
  5. **Approval UIs render the rule, not the error.** Use `capability` from `useFourEyesApproval`: when `reason` is `"actor-is-creator"`, say that a second person must approve – do not show buttons that will be refused. On failure `"stale-version"`, refetch and let the operator re-decide; never auto-retry an approval.
12
- 6. **Gate every finished screen with the design audit, and wire it into CI.** `npx @venlyfinance/settlement-mcp review "src/**/*.tsx"` fails (exit 1) on any error-severity finding – raw colours, invented timing or custody copy, crypto codes inside `Intl.NumberFormat` currency formatting, a required field labelled optional, parity fixtures, and more. Add it as a CI step in the app you build. A deliberate, justified exception carries `venly-allow:<rule-id>` on the offending line or the line above.
12
+ 6. **Gate both the screen and its runtime contract, and wire both into CI.** Run `npx @venlyfinance/settlement-mcp review "src/**/*.tsx"` for the design contract and `npx @venlyfinance/settlement-mcp verify "src/**/*.{ts,tsx}"` for package/provider/hook/proxy composition. Each fails (exit 1) on any error-severity finding. A deliberate, justified exception carries `venly-allow:<rule-id>` on the offending line or the line above.
13
13
 
14
14
  ## Rendering money states
15
15
 
@@ -32,4 +32,4 @@ The UI kit's auth and team blocks therefore render against two adapter interface
32
32
  ## Demo choreography (mock mode)
33
33
 
34
34
  `useVenlyMock()` exposes the store controls. A credible end-to-end demo:
35
- create party → `advanceVerification(id)` → create account → virtual bank account (note its `referenceCode`) → stage + confirm a transfer → `advanceTransfer(id)` → show the ledger. Inject failures with `failNext("CONFLICT")` to show the stale-version approval path – error states are part of the product.
35
+ create party → `advanceVerification(id)` → create account → virtual bank account (note its `referenceCode`) → **fund it: `simulations.inbound.credit(vbaId, 500)`** (a new account holds nothing, as in production; an unfunded transfer is refused with `402 insufficient-funds`) → stage + confirm a transfer → `advanceTransfer(id)` → show the ledger, and `simulations.ledger.verify()` to prove it balances. Inject failures with `failNext("CONFLICT")` to show the stale-version approval path – error states are part of the product.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,34 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.7.1 – 2026-08-21
4
+
5
+ - Republish so the packaged blueprints carry the corrected npm ranges for
6
+ `@venlyfinance/react` (`^0.5.0`) and `@venlyfinance/sdk` (`^0.6.0`). The
7
+ 0.7.0 tarball was cut before that fix landed, so its blueprints told agents
8
+ to install ranges that never reach the versions the registry blocks import.
9
+ No behaviour change beyond the stamped ranges.
10
+
11
+ ## 0.7.0 – 2026-08-19
12
+
13
+ The MCP now pushes a machine-checkable runtime contract instead of relying on
14
+ agents to discover composition guidance through optional pull surfaces.
15
+
16
+ - The initialize response carries server instructions that establish
17
+ `@venlyfinance/react` hooks and flow machines as the browser data plane,
18
+ `@venlyfinance/sdk` as the server data plane, and the shadcn registry as the
19
+ UI installation path.
20
+ - Every `get_journey_blueprint` response keeps its prose blueprint and adds the
21
+ same `runtime_contract` as fenced JSON and `structuredContent`: exact registry
22
+ dependencies, qualified hook imports, provider configuration, forbidden
23
+ hand-rolled patterns, install commands, and completion gates.
24
+ - New deterministic `verify` CLI and `verify_runtime_contract` MCP tool with
25
+ auto-detected `direct-sdk` and `backend-proxy` profiles. Exit codes match the
26
+ `review` CLI (0 clean, 1 on errors, 2 on usage/no-match), and
27
+ `venly-allow:<rule-id>` suppressions work on verifier findings.
28
+ - Money-route-without-SDK, in-memory-money-store, and direct-profile missing
29
+ React checks remain warning-only pending a false-positive-boundary ruling.
30
+ - Requires `@venlyfinance/sdk` ^0.5.0.
31
+
3
32
  ## 0.3.0 – 2026-08-04
4
33
 
5
34
  Wording-is-the-safety-surface release. An outside integrator audit (2026-08-04) found the server's words disagreeing with its behavior in three
package/README.md CHANGED
@@ -13,9 +13,9 @@ Start in explicit mock mode with no credentials or network. Move the same SDK
13
13
  business logic to staging only after reviewing capabilities, compliance state and
14
14
  the normalized write requests. Staging and production writes fail closed.
15
15
 
16
- The Venly Finance builder surface documented here is the v0.2.0 release line.
16
+ The Venly Finance builder surface documented here is the v0.7.0 release line.
17
17
 
18
- Building with a coding agent? Start from [AGENTS.md](AGENTS.md) - the MCP also serves it as the \venly://frontend/agents resource.
18
+ Building with a coding agent? Start from [AGENTS.md](AGENTS.md) - the MCP also serves it as the `venly://frontend/agents` resource and pushes the core runtime doctrine in its initialize response.
19
19
 
20
20
  ## What it is
21
21
 
@@ -124,8 +124,12 @@ Delivery of UI source rides the shadcn registry standard – add
124
124
  to `components.json`, then `npx shadcn@latest add @venlyfinance/receive`. The MCP carries
125
125
  what a registry cannot:
126
126
 
127
- - `get_journey_blueprint` – screen inventory, required states, registry items and binding
128
- hooks for eight money-product journeys.
127
+ - `get_journey_blueprint` – screen inventory and required states for eleven
128
+ money-product journeys, plus a machine-readable `runtime_contract` containing
129
+ exact package versions, qualified hooks, provider setup, forbidden patterns,
130
+ install commands and completion checks.
131
+ - `verify_runtime_contract` – deterministic runtime-contract checks over supplied
132
+ source and package metadata, using the same profiles and rules as the CLI.
129
133
  - `review_screen` – deterministic design audit of a screen's source (raw colours,
130
134
  hyphen-minus amounts, success styling on cancelled steps, masked review values,
131
135
  invented timing/custody copy, crypto codes inside `Intl.NumberFormat` currency
@@ -157,6 +161,22 @@ Scope the glob to component source, never to token or theme files: the
157
161
  css file is the one legitimate home of raw colour values (theming stays a
158
162
  one-file edit). `"src/**/*.tsx"` is the right default.
159
163
 
164
+ ### Runtime-contract CLI
165
+
166
+ Gate the data-plane composition alongside the screen audit:
167
+
168
+ ```bash
169
+ npx @venlyfinance/settlement-mcp verify "src/**/*.{ts,tsx}"
170
+ ```
171
+
172
+ The verifier auto-detects `direct-sdk` (browser provider + hooks) or
173
+ `backend-proxy` (browser proxy options + SDK-backed server routes). Override
174
+ with `--profile direct-sdk` or `--profile backend-proxy`. Exit codes are `0`
175
+ when no error findings exist, `1` when any error exists, and `2` for usage or
176
+ no-match failures; warnings print but do not fail. The same
177
+ `venly-allow:<rule-id>` token suppresses a deliberate finding on its line or
178
+ the line above.
179
+
160
180
  ## Safety model (fail closed)
161
181
 
162
182
  Outside explicit mock mode, read-only/dry-run is the default posture. A staging
@@ -323,6 +343,7 @@ settlement-mcp/
323
343
  resources.ts capability, safety and workflow resources
324
344
  prompts.ts build_international_account prompt
325
345
  results.ts text + structured output and error redaction
346
+ verify-cli.ts runtime-contract profiles, checks and CLI
326
347
  staging-smoke.ts safe discovery/read/dry-run staging verification
327
348
  client/
328
349
  sdk-client.ts Adapter over @venlyfinance/sdk
@@ -1,7 +1,8 @@
1
1
  /** Shared constants. The default environment is MOCK so an unconfigured run
2
2
  * never touches real infrastructure; staging/production are explicit. */
3
3
  export declare const SERVER_NAME = "venly-finance-mcp-server";
4
- export declare const SERVER_VERSION = "0.6.0";
4
+ export declare const SERVER_VERSION = "0.7.1";
5
+ export declare const INSTRUCTIONS = "Venly Finance build advisor. This server is a build-time advisor, not your app's data plane. The data plane is the published packages: every read is a hook and every regulated lifecycle a flow machine from `@venlyfinance/react`, inside `<VenlyProvider environment=\"mock\">` \u2013 zero credentials, zero network; server-side code uses `@venlyfinance/sdk`. Hand-rolled fetch layers, in-memory money stores, or route handlers that re-implement transfers, balances, or approvals are off-contract and fail review. UI installs from the @venlyfinance shadcn registry: `npx shadcn@latest add @venlyfinance/balances @venlyfinance/send \u2026` (auto-installs the npm packages). Before scaffolding, read `venly://frontend/agents` \u2013 it is the composition doctrine (AGENTS.md). Consult `get_journey_blueprint` per screen; gate finished screens with `review_screen` and `npx @venlyfinance/settlement-mcp review \"src/**/*.tsx\"`.";
5
6
  export declare const ENVIRONMENT_FLAG = "VENLY_ENV";
6
7
  export type VenlyEnvironment = "mock" | "qa" | "staging" | "production";
7
8
  export declare function resolveVenlyEnvironment(env: Record<string, string | undefined>): VenlyEnvironment;
package/dist/constants.js CHANGED
@@ -1,7 +1,8 @@
1
1
  /** Shared constants. The default environment is MOCK so an unconfigured run
2
2
  * never touches real infrastructure; staging/production are explicit. */
3
3
  export const SERVER_NAME = "venly-finance-mcp-server";
4
- export const SERVER_VERSION = "0.6.0";
4
+ export const SERVER_VERSION = "0.7.1";
5
+ export const INSTRUCTIONS = `Venly Finance build advisor. This server is a build-time advisor, not your app's data plane. The data plane is the published packages: every read is a hook and every regulated lifecycle a flow machine from \`@venlyfinance/react\`, inside \`<VenlyProvider environment="mock">\` – zero credentials, zero network; server-side code uses \`@venlyfinance/sdk\`. Hand-rolled fetch layers, in-memory money stores, or route handlers that re-implement transfers, balances, or approvals are off-contract and fail review. UI installs from the @venlyfinance shadcn registry: \`npx shadcn@latest add @venlyfinance/balances @venlyfinance/send …\` (auto-installs the npm packages). Before scaffolding, read \`venly://frontend/agents\` – it is the composition doctrine (AGENTS.md). Consult \`get_journey_blueprint\` per screen; gate finished screens with \`review_screen\` and \`npx @venlyfinance/settlement-mcp review "src/**/*.tsx"\`.`;
5
6
  export const ENVIRONMENT_FLAG = "VENLY_ENV";
6
7
  export function resolveVenlyEnvironment(env) {
7
8
  // Default is MOCK (since 0.3.0): the mock-first product must not point at
@@ -14,13 +14,18 @@ declare const JOURNEYS: {
14
14
  readonly team: "# Team\nShell: in-shell content column.\nRegistry items: venly-tokens, data-table, status-pill; block: team (TeamTable, InviteDialog).\nBinding: a TeamAdapter over your auth provider (createMockTeamAdapter for demos).\nStates that must exist: ACTIVE/INVITED/DISABLED members on first paint, invite\ncreated (display-only link in mock - never a fake sent-email claim), role\nchange persisting, self-actions blocked with the reason.\nRules that must hold: member status is word + glyph; role controls live in the\nrow; you cannot change your own role or disable yourself - the control is\ndisabled AND explains why.";
15
15
  readonly "home-balances": "# Home / balances\nShell: left nav rail + thin top bar; full-width content.\nRegistry items: venly-tokens, balance-card, data-table, status-pill; block: balances (BalancesBlock, BalanceMiniature).\nHooks: useAccounts, useWallets; balances rendered per asset across the account's wallets.\nStates that must exist: loading, zero balances (first-run guidance), reserved buckets, entirely reserved (available 0 rendered honestly - the acct-escrow seed exercises it), balance load error degrading locally with a retry.\nRules that must hold: available is the emphasised figure and the only one above the rule; reserved is demoted by position and scale, never colour, and carries the still-yours qualifier; unspendable buckets carry the padlock; masking covers every figure including the chrome miniature; arithmetic mismatches are surfaced, never corrected; never assume stablecoin parity - render the quoted rate.";
16
16
  readonly receive: "# Receive\nShell: content column - a warning callout, the field card, an advisory below.\nRegistry items: venly-tokens, field-list; block: receive.\nHooks: useVirtualBankAccounts (first active EUR account).\nStates that must exist: no virtual bank account yet (offer creation), details present, reference not yet assigned (\"Not assigned yet\" + Required pill - never \"(not required)\").\nRules that must hold: the payment reference is enforced as mandatory (amber Required pill, warning above the fields); per-field copy names the field it copied and only confirms on a successful write; rows never vanish - render the \"(not required)\" variant.";
17
- readonly send: "# Send\nShell: full page; form clamped ~600px; review step replaces the form.\nRegistry items: venly-tokens, arithmetic-ladder, timeline; block: send.\nHooks: useStagedTransfer (the machine IS the flow), useFeeQuote when fees apply.\nStates that must exist: draft (validation issues listed), staged review, submitting, pending (polling), completed, failed (reason shown, terminal).\nRules that must hold: money movement is stage-then-confirm - the review renders the exact staged request as an arithmetic ladder (working before the answer, uncertainty attached to the number); the commit button restates the amount and never carries a countdown; values are never masked on review; execution is single-shot on an idempotency key pinned at staging.";
17
+ readonly send: "# Send (one door)\nShell: full page; the door is the recipient picker; forms clamp ~600px; the\nreview and the step-up ceremony replace the form in place.\nRegistry items: venly-tokens, status-pill, field-list, data-table, list-error;\nblocks: send (SendDoor, RecipientPicker, DirectoryPick, PlatformTransferFlow,\nPayoutSendFlow, SendReview, StepUpConfirm, TransferDetail, PayoutDetail) and\nrecipients (RecipientsView, AddRecipientForm, BeneficiaryAccountForm,\nRouteCeremony) - the prerequisite surface saved recipients are managed on.\nHooks: useCreateFiatTransfer and useCreateCryptoTransfer (the staged-transfer\nmachine typed per rail), useRequestPayout, usePartyRoles, useAddPartyRole,\nuseCreateParty, useRegisterPayoutBankAccount, useCreatePayoutRoute,\nusePreparePayoutOwnershipProof, useCompletePayoutOwnershipProof, useParties,\nuseAccounts, useWallets, useAccountSupportedAssets, useTransfers, useTransfer,\nusePayouts, usePayout, usePayoutRoutes.\nBinding: ONE door - the first screen is the recipient picker and the fork is\nthe recipient's OBJECT TYPE, never a rail choice. A person or business on the\nplatform (a directory YOUR user table serves; render name + handle, never a\nUUID - ids stay request-side) starts an on-platform transfer. A saved\nrecipient - a party holding the payout-recipient role, owning reviewed bank\naccounts (details masked server-side) and an ACTIVE payout route - starts a\nthird-party payout referencing the ROUTE, never raw bank details. Your own\nbank account is a link row into the withdraw flow. Send-to-external-wallet\nhas NO surface: no teaser, no disabled row, no rendered trace.\nStates that must exist: recipient picker (three classes, populated and empty), disabled with the reason (unverified directory rows, non-active routes and non-active accounts), over-balance, review (known figures only), step-up (wrong code blocks, the deterministic demo code proceeds), pending, completed, failed (the record's own error verbatim, terminal), requested, sending, provider processing, rejected, returned (money came back - a neutral terminal), no active route (blocked start with the unblocking CTA), load failure (explicit error plus retry - never an empty detail).\nRules that must hold: every money confirm passes the step-up ceremony against\nYOUR auth adapter and the commit fires only after the code verifies - this is\napp-side ceremony and must never be presented as an API security guarantee;\nexecution is single-shot on an idempotency key minted ONCE per staged draft,\nso a retry replays the same record instead of moving money twice; reviews\nrender ONLY figures the API has produced, and the payout review states the\nabsence in words beside the two-sided units sentence. Forbidden to invent\n(render the labelled omission or nothing at all): a fee row - and equally a\n\"No fee\" claim, since no source confirms zero; an ETA or delivery date - no\ntiming field exists on transfers or payouts; a pre-create rate or\nrecipient-gets figure - exchangeRate and settledFiatAmount exist on CREATED\nand COMPLETED records only; named in-flight stages beyond the status enums -\nrender the app-side observation log instead. Beneficiary details come back\nmasked: render the mask, never re-ask. Route states render verbatim and a\nREJECTED route is terminal-negative with a way forward, never a dead end.";
18
18
  readonly activity: "# Activity\nShell: full-width table + side panel.\nRegistry items: venly-tokens, data-table, status-pill, side-panel, timeline; block: activity.\nHooks: useTransfers (and useRampRequests where ramps are in scope).\nStates that must exist: loading, empty ledger, rows with pending/failed pills, open detail panel that stays in sync with refetches.\nRules that must hold: a row click opens the panel, never navigates; no scrim - the source row stays tinted; settled rows stay quiet (colour is a budget; pills only where action or failure lives); the panel's hero is the amount; the failure reason rides the terminal timeline node.";
19
19
  readonly "onboarding-status": "# Onboarding / verification status\nShell: full page, form clamped ~600px; a status home once submitted.\nRegistry items: venly-tokens, timeline, status-pill, field-list; block: onboarding (CompanyForm, VerificationStatusHome, RestrictedBanner).\nHooks: useCreateParty, useCreateAccount, useParty, useAccount; verification status from the party/account records verbatim.\nStates that must exist: collecting (review before submit), submitted/waiting (say who acts next, on which channel, what still works meanwhile), approved, declined (humane copy, review-request as the primary action), re-verification on a live account (banner naming what pauses and what keeps working).\nRules that must hold: never render a fake progress percentage - use real status; a waiting state answers how long / who acts / what still works, and where no review window is published the copy says so instead of inventing one; a decline explains and offers a next step, not a dead end; creating a party is NOT completed verification - show the honest state.";
20
20
  readonly "withdraw-bank-accounts": "# Withdraw + bank accounts (off-ramp)\nShell: settings page for the whitelist; full page for the flow, form clamped ~600px.\nRegistry items: venly-tokens, data-table, status-pill, timeline, field-list, arithmetic-ladder; blocks: bank-accounts (BankAccountsBlock, AddBankAccountForm), withdraw (WithdrawFlow, WithdrawalsTable, ConnectedWithdrawDetail).\nHooks: useCompanyBankAccounts, useBankAccountConfig, useCreateCompanyBankAccount, useRampRequests, useRampRequest, useCreateRampRequest, useFeeQuote, useRampPairs, useReferenceData, useFourEyesApproval, useInitiateRamp, describeRampStatus.\nStates that must exist: empty whitelist (one CTA), account in review / verified / declined, no-verified-destination block, amount over balance (two-place signal), fee quote with its unit, awaiting approval (creator sees why they can't approve), stale decision (409 - refetch and re-decide, never auto-retry), awaiting funds (deposit instructions + mandatory reference + tx-hash report), processing, paid out, failed, rejected, cancelled, on hold.\nRules that must hold: destinations are the company's OWN verified accounts - unverified rows are disabled with the reason, never hidden; the pre-create review renders only known figures (no invented rate, no bank-receives placeholder - the created record carries the fiat arithmetic and the detail opens on it); a refusal never reads as a wait; the event timeline renders actor, role and absolute timestamps.";
21
21
  readonly reconciliation: "# Reconciliation\nShell: split pane (roughly one-third list, two-thirds evidence) - not a drawer.\nRegistry items: venly-tokens, data-table, side-panel, status-pill, field-list.\nHooks: reconcile_by_reference_code (MCP composite) or useVirtualBankAccounts + useTransfers joined on referenceCode.\nStates that must exist: matched, unmatched with candidate expectations, partial/many-to-one with a live shortfall figure, resolved.\nRules that must hold: show per-signal match rationale (which fields agree), never a bare score; keep zero-counts visible - an empty exception queue is information; keyboard row-stepping for review throughput.";
22
22
  readonly "proof-of-segregation": "# Proof of segregation\nShell: content column, single card.\nRegistry items: venly-tokens, field-list, balance-card.\nHooks: useWallets, useAccount; on-chain balance beside the ledger figure.\nStates that must exist: reconciled (figures agree, timestamped), reconciling, source unavailable (say so - never render a stale figure as current).\nRules that must hold: the wallet address renders monospace with copy; the on-chain figure and ledger figure sit side by side with their as-of times; discrepancies are stated, not smoothed.";
23
23
  readonly approvals: "# Approvals\nShell: full-width queue + side panel tailored to the approver.\nRegistry items: venly-tokens, data-table, status-pill, side-panel, timeline.\nHooks: useRampRequests, useFourEyesApproval (capability decides what renders), useRampLifecycle.\nStates that must exist: queue with awaiting-approval items, detail with the decision context beside the figures, applied, stale-version (someone acted first - refetch and re-decide), creator-view (cannot approve own request - render the rule, not a disabled mystery button).\nRules that must hold: the optimistic-locking version travels with every decision; a 409 means re-decide against fresh state, never auto-retry; reject requires a reason; the creator sees why they cannot approve.";
24
+ readonly "console-review-queue": "# Console review queue (the operator worklist)\nShell: left nav rail + thin top bar, full-width content, and a page-edge\nenvironment banner naming mock mode. Not a consumer surface - density rules\napply.\nRegistry items: venly-tokens, data-table, status-pill, money, list-error;\nblocks: console-queue (ConsoleQueue, WhoseMove, AgeCell, deriveKycActor,\nderivePayoutActor - the derivation functions are exported so a consumer can\nunit-test the join).\nHooks: useAccounts, useParties. The queue's own state is DERIVED on every\nrender - never stored, never cached as a status.\nBinding: sections are ACTORS, not statuses - your move, waiting on the customer,\nwaiting on a provider, then a collapsed closed section, so the reviewer's own\nworklist is the top band by construction.\nStates that must exist: loading, your move, waiting on the customer, waiting on a provider, closed, empty queue, filtered to nothing, list error.\nRules that must hold: the whose-move value is a pure function of enum values on\nthe row - no clock reading, no threshold, no configuration and no default, and a\ncombination the mapping does not cover renders NO value plus an explicit\nnot-recognised line, which is a bug report rather than a guess; never a target\ntime, a breach colour or an overdue state, because the API publishes no targets\nand an invented one is the same defect as an invented fee; an age column is\nlabelled for what it actually measures - a created-at delta is \"Age\", and only a\nduration the API itself computes may be called time in state; empty sections are\nstill drawn as a zero header row, because nothing-to-do is information; loading\nis a skeleton that preserves column geometry exactly, never prose; a row click\nopens a side panel and never navigates; one status pill per row - the whose-move\nvalue is plain text, since two pills read as two states.";
25
+ readonly "console-decision-detail": "# Console decision detail (evidence, ceremony, audit trail)\nShell: side panel about 30% wide over the queue - no scrim, the table stays\nvisible clipped at the panel edge and the source row stays tinted. Escalate to a\n35/65 split only when the evidence outgrows the panel. Evidence goes on the\nLEFT: this is a judging task, not an authoring one.\nRegistry items: venly-tokens, side-panel, timeline, field-list, status-pill,\nmoney, data-table; blocks: console-decision (ConsoleDecisionPanel,\nEvidenceStack, DecisionForm, DualTimeline).\nHooks: useAccount, useParty, useWallets, useTransfers,\nuseVirtualBankAccounts, useVenlyMock (the trail reads the mock's event log).\nTwo timeline columns, not one feed: the decision chain (who decided what, when,\nin which seat) beside money movement on the same subject. Different actors,\ndifferent audiences; merging them is what makes an audit trail unreadable.\nStates that must exist: loading, evidence present, evidence unavailable, decision owed, decision applied, stale decision, terminal decision, frozen, empty trail.\nRules that must hold: every evidence row is either a real field path or a\nlabelled omission, and an omission is a FIRST-CLASS type in the component's\nprops, so a placeholder cannot be rendered where a gap belongs;\nomission copy states only what is verified and never implies a result, a\npending state, or a clean one - and never mentions the API contract, which is\ndeveloper diagnostics rather than operator language; a field the API cannot\ncarry is captured anyway when the work needs it, and rendered with a visible\nbadge saying it is a console note rather than API state; every decision carries the\noptimistic-locking version, and a conflict means refetch and re-decide against\nfresh state, never auto-retry; every transition the console causes leaves a\ntimeline node with actor, role and a timezone-qualified absolute timestamp, so a\nstatus change with no node is a bug; a store resync is a system line, not a\ndecision node; the panel footer carries row-stepping key chips so the reviewer\nmoves row to row without closing.";
26
+ readonly "console-pricing-config": "# Console pricing configuration\nShell: in-shell content column. A config screen, not a queue: no whose-move\nvalue and no aging. The whole screen sits inside a platform-view section\nboundary - fee configuration is the platform's seat.\nRegistry items: venly-tokens, data-table, arithmetic-ladder, field-list,\nlist-error; blocks: console-pricing (ConsolePricingTable, FeeLadder, FeePanel\n- read-only, because the fees operation is GET-only; the panel renders\nfields, never an editable form).\nHooks: useCompanyFees.\nBinding: the fee data the packages actually serve is a VOLUME-TIER model - tier\nname, ramp direction, minimum and maximum volume, percentage, version - and it\nis the same model the shipped withdrawal quote consumes, so this screen shows\nwhere a real quote comes from. A second, richer per-rail configuration model\nexists on an internal plane and is NOT served here; it renders as a labelled\nomission, never as an empty form.\nStates that must exist: loading, tiers present, no tiers, configuration unavailable, worked example, save failed.\nRules that must hold: a worked arithmetic ladder is mandatory on the tier\nsection - a sample amount times the tier percentage, with the operator glyphs in\na left gutter - because a pricing screen that shows only stored numbers teaches\nnothing; the ladder renders ONLY over data that exists, never over the omitted\nsection; the tier\na sample amount falls into is highlighted in the table so the row and the ladder\nare visibly the same fact; a single-member enum renders as a disabled\nsingle-value field that says so, not a select pretending at choice; a date\nwindow that has not opened reads scheduled, never active; forms are single\ncolumn with the field width capped, label above input, helper text between them\nand the error below.";
27
+ readonly "console-simulator": "# Sandbox simulator (play the counterparty)\nShell: its own chrome - a scrimmed right-hand drawer on a distinct surface with\na persistent sandbox label, reachable from ONE fixed affordance in the top bar.\nIt is the only scrimmed drawer in the console, so the surface change alone\nsignals the register change.\nRegistry items: venly-tokens, field-list, status-pill, money; blocks:\nconsole-simulator (SimulatorDrawer, SimulatorControl, LedgerVerifyPanel,\nChannelFooter - SimulatorControl refuses an imperative operator-decision\nlabel with a thrown developer error).\nHooks: useVenlyMock. Every control maps to exactly one call on the mock's\nsimulations namespace - no control without a call, and no call renamed.\nBinding: inbound credits, provider progression and screening verdicts are things\nOTHER parties do, so they live here rather than in the operator's workflow.\nStates that must exist: drawer closed, drawer open, sharing, not sharing, credit landed, verdict returned, payout advanced, books balanced, books do not balance, reset.\nRules that must hold: controls are phrased as events that happen to you, in the\nthird person, while operator controls elsewhere are imperative decisions - a\ncontrol phrased in the wrong voice is in the wrong surface; a simulated\ntransition emits the SAME event the real path emits, and the trail attributes it\nto the simulator plainly rather than to an operator; the drawer is reachable\nonly from the top bar, never from a queue row or a decision panel, because those\npaths make another party's action look like the operator's; the ledger check gets\na visible surface: it is the one control here that asserts something true, namely\nthat the simulated books balance; the channel footer states the adapter, session\nand peer count, and says IN WORDS when the surface is not actually sharing - the\ndefault channel shares nothing and cross-context sharing is same-origin only, so\nwithout that line a two-context demo can prove nothing while looking correct.";
28
+ readonly "console-webhooks": "# Console webhooks (endpoint registration, honestly bounded)\nShell: in-shell content column - a table with a panel form beside it. This\none IS a form: the public plane carries the full lifecycle (list, create,\nread, replace, delete, ping).\nRegistry items: venly-tokens, data-table, status-pill, list-error; blocks:\nconsole-webhooks (WebhooksTable, WebhookForm, WebhookDeliveryLog - the\ndelivery log renders inside SIMULATOR chrome only, never on this screen).\nHooks: useWebhooks, useWebhook, useCreateWebhook, useUpdateWebhook,\nuseDeleteWebhook, usePingWebhook.\nBinding: webhook rows render the contract fields verbatim - url, name, and\na status enum that has exactly one member in this release, rendered as a\ndisabled single value that says so rather than a select pretending at\nchoice. The authentication method is a two-variant choice (API key or\nbasic); its secret fields are write-only on the contract, so the platform\nnever returns a stored secret and this screen never displays one - editing\nmeans re-entering the credential, and the form says why.\nStates that must exist: loading, webhooks listed, no webhooks yet, registration form, secret masked, ping result, delete confirmation, list error.\nRules that must hold: Ping is the promoted per-row affordance - it is the\none real signal the API offers about an endpoint - and its result renders\nverbatim; delivery history is NOT available from the API in this release\nand the screen says so on the screen itself, with the next step (use Ping),\nnever as a silent gap; the create operation carries no idempotency\nenvelope, so a replayed create registers a second webhook - any\nretry-safety a surface adds is a client-side convention badged as such,\nnever presented as contract behaviour; delete is confirm-and-explain: the\nconfirmation names the consequence before anything is removed; the\nsimulated delivery log is a sandbox surface phrased in the third person\nand badged as simulation, rendered only inside the simulator's own chrome.";
24
29
  };
25
30
  type JourneyKey = keyof typeof JOURNEYS;
26
31
  interface Finding {
package/dist/frontend.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { z } from "zod";
2
+ import { verifyRuntimeContract } from "./verify-cli.js";
2
3
  export const REGISTRY_URL_TEMPLATE = "https://raw.githubusercontent.com/Venly/venly-settlement-sdk/main/ui/r/{name}.json";
3
4
  const JOURNEYS = {
4
5
  auth: `# Auth (sign-in, 2FA, sign-up)
@@ -36,12 +37,45 @@ Registry items: venly-tokens, field-list; block: receive.
36
37
  Hooks: useVirtualBankAccounts (first active EUR account).
37
38
  States that must exist: no virtual bank account yet (offer creation), details present, reference not yet assigned ("Not assigned yet" + Required pill - never "(not required)").
38
39
  Rules that must hold: the payment reference is enforced as mandatory (amber Required pill, warning above the fields); per-field copy names the field it copied and only confirms on a successful write; rows never vanish - render the "(not required)" variant.`,
39
- send: `# Send
40
- Shell: full page; form clamped ~600px; review step replaces the form.
41
- Registry items: venly-tokens, arithmetic-ladder, timeline; block: send.
42
- Hooks: useStagedTransfer (the machine IS the flow), useFeeQuote when fees apply.
43
- States that must exist: draft (validation issues listed), staged review, submitting, pending (polling), completed, failed (reason shown, terminal).
44
- Rules that must hold: money movement is stage-then-confirm - the review renders the exact staged request as an arithmetic ladder (working before the answer, uncertainty attached to the number); the commit button restates the amount and never carries a countdown; values are never masked on review; execution is single-shot on an idempotency key pinned at staging.`,
40
+ send: `# Send (one door)
41
+ Shell: full page; the door is the recipient picker; forms clamp ~600px; the
42
+ review and the step-up ceremony replace the form in place.
43
+ Registry items: venly-tokens, status-pill, field-list, data-table, list-error;
44
+ blocks: send (SendDoor, RecipientPicker, DirectoryPick, PlatformTransferFlow,
45
+ PayoutSendFlow, SendReview, StepUpConfirm, TransferDetail, PayoutDetail) and
46
+ recipients (RecipientsView, AddRecipientForm, BeneficiaryAccountForm,
47
+ RouteCeremony) - the prerequisite surface saved recipients are managed on.
48
+ Hooks: useCreateFiatTransfer and useCreateCryptoTransfer (the staged-transfer
49
+ machine typed per rail), useRequestPayout, usePartyRoles, useAddPartyRole,
50
+ useCreateParty, useRegisterPayoutBankAccount, useCreatePayoutRoute,
51
+ usePreparePayoutOwnershipProof, useCompletePayoutOwnershipProof, useParties,
52
+ useAccounts, useWallets, useAccountSupportedAssets, useTransfers, useTransfer,
53
+ usePayouts, usePayout, usePayoutRoutes.
54
+ Binding: ONE door - the first screen is the recipient picker and the fork is
55
+ the recipient's OBJECT TYPE, never a rail choice. A person or business on the
56
+ platform (a directory YOUR user table serves; render name + handle, never a
57
+ UUID - ids stay request-side) starts an on-platform transfer. A saved
58
+ recipient - a party holding the payout-recipient role, owning reviewed bank
59
+ accounts (details masked server-side) and an ACTIVE payout route - starts a
60
+ third-party payout referencing the ROUTE, never raw bank details. Your own
61
+ bank account is a link row into the withdraw flow. Send-to-external-wallet
62
+ has NO surface: no teaser, no disabled row, no rendered trace.
63
+ States that must exist: recipient picker (three classes, populated and empty), disabled with the reason (unverified directory rows, non-active routes and non-active accounts), over-balance, review (known figures only), step-up (wrong code blocks, the deterministic demo code proceeds), pending, completed, failed (the record's own error verbatim, terminal), requested, sending, provider processing, rejected, returned (money came back - a neutral terminal), no active route (blocked start with the unblocking CTA), load failure (explicit error plus retry - never an empty detail).
64
+ Rules that must hold: every money confirm passes the step-up ceremony against
65
+ YOUR auth adapter and the commit fires only after the code verifies - this is
66
+ app-side ceremony and must never be presented as an API security guarantee;
67
+ execution is single-shot on an idempotency key minted ONCE per staged draft,
68
+ so a retry replays the same record instead of moving money twice; reviews
69
+ render ONLY figures the API has produced, and the payout review states the
70
+ absence in words beside the two-sided units sentence. Forbidden to invent
71
+ (render the labelled omission or nothing at all): a fee row - and equally a
72
+ "No fee" claim, since no source confirms zero; an ETA or delivery date - no
73
+ timing field exists on transfers or payouts; a pre-create rate or
74
+ recipient-gets figure - exchangeRate and settledFiatAmount exist on CREATED
75
+ and COMPLETED records only; named in-flight stages beyond the status enums -
76
+ render the app-side observation log instead. Beneficiary details come back
77
+ masked: render the mask, never re-ask. Route states render verbatim and a
78
+ REJECTED route is terminal-negative with a way forward, never a dead end.`,
45
79
  activity: `# Activity
46
80
  Shell: full-width table + side panel.
47
81
  Registry items: venly-tokens, data-table, status-pill, side-panel, timeline; block: activity.
@@ -78,8 +112,445 @@ Registry items: venly-tokens, data-table, status-pill, side-panel, timeline.
78
112
  Hooks: useRampRequests, useFourEyesApproval (capability decides what renders), useRampLifecycle.
79
113
  States that must exist: queue with awaiting-approval items, detail with the decision context beside the figures, applied, stale-version (someone acted first - refetch and re-decide), creator-view (cannot approve own request - render the rule, not a disabled mystery button).
80
114
  Rules that must hold: the optimistic-locking version travels with every decision; a 409 means re-decide against fresh state, never auto-retry; reject requires a reason; the creator sees why they cannot approve.`,
115
+ "console-review-queue": `# Console review queue (the operator worklist)
116
+ Shell: left nav rail + thin top bar, full-width content, and a page-edge
117
+ environment banner naming mock mode. Not a consumer surface - density rules
118
+ apply.
119
+ Registry items: venly-tokens, data-table, status-pill, money, list-error;
120
+ blocks: console-queue (ConsoleQueue, WhoseMove, AgeCell, deriveKycActor,
121
+ derivePayoutActor - the derivation functions are exported so a consumer can
122
+ unit-test the join).
123
+ Hooks: useAccounts, useParties. The queue's own state is DERIVED on every
124
+ render - never stored, never cached as a status.
125
+ Binding: sections are ACTORS, not statuses - your move, waiting on the customer,
126
+ waiting on a provider, then a collapsed closed section, so the reviewer's own
127
+ worklist is the top band by construction.
128
+ States that must exist: loading, your move, waiting on the customer, waiting on a provider, closed, empty queue, filtered to nothing, list error.
129
+ Rules that must hold: the whose-move value is a pure function of enum values on
130
+ the row - no clock reading, no threshold, no configuration and no default, and a
131
+ combination the mapping does not cover renders NO value plus an explicit
132
+ not-recognised line, which is a bug report rather than a guess; never a target
133
+ time, a breach colour or an overdue state, because the API publishes no targets
134
+ and an invented one is the same defect as an invented fee; an age column is
135
+ labelled for what it actually measures - a created-at delta is "Age", and only a
136
+ duration the API itself computes may be called time in state; empty sections are
137
+ still drawn as a zero header row, because nothing-to-do is information; loading
138
+ is a skeleton that preserves column geometry exactly, never prose; a row click
139
+ opens a side panel and never navigates; one status pill per row - the whose-move
140
+ value is plain text, since two pills read as two states.`,
141
+ "console-decision-detail": `# Console decision detail (evidence, ceremony, audit trail)
142
+ Shell: side panel about 30% wide over the queue - no scrim, the table stays
143
+ visible clipped at the panel edge and the source row stays tinted. Escalate to a
144
+ 35/65 split only when the evidence outgrows the panel. Evidence goes on the
145
+ LEFT: this is a judging task, not an authoring one.
146
+ Registry items: venly-tokens, side-panel, timeline, field-list, status-pill,
147
+ money, data-table; blocks: console-decision (ConsoleDecisionPanel,
148
+ EvidenceStack, DecisionForm, DualTimeline).
149
+ Hooks: useAccount, useParty, useWallets, useTransfers,
150
+ useVirtualBankAccounts, useVenlyMock (the trail reads the mock's event log).
151
+ Two timeline columns, not one feed: the decision chain (who decided what, when,
152
+ in which seat) beside money movement on the same subject. Different actors,
153
+ different audiences; merging them is what makes an audit trail unreadable.
154
+ States that must exist: loading, evidence present, evidence unavailable, decision owed, decision applied, stale decision, terminal decision, frozen, empty trail.
155
+ Rules that must hold: every evidence row is either a real field path or a
156
+ labelled omission, and an omission is a FIRST-CLASS type in the component's
157
+ props, so a placeholder cannot be rendered where a gap belongs;
158
+ omission copy states only what is verified and never implies a result, a
159
+ pending state, or a clean one - and never mentions the API contract, which is
160
+ developer diagnostics rather than operator language; a field the API cannot
161
+ carry is captured anyway when the work needs it, and rendered with a visible
162
+ badge saying it is a console note rather than API state; every decision carries the
163
+ optimistic-locking version, and a conflict means refetch and re-decide against
164
+ fresh state, never auto-retry; every transition the console causes leaves a
165
+ timeline node with actor, role and a timezone-qualified absolute timestamp, so a
166
+ status change with no node is a bug; a store resync is a system line, not a
167
+ decision node; the panel footer carries row-stepping key chips so the reviewer
168
+ moves row to row without closing.`,
169
+ "console-pricing-config": `# Console pricing configuration
170
+ Shell: in-shell content column. A config screen, not a queue: no whose-move
171
+ value and no aging. The whole screen sits inside a platform-view section
172
+ boundary - fee configuration is the platform's seat.
173
+ Registry items: venly-tokens, data-table, arithmetic-ladder, field-list,
174
+ list-error; blocks: console-pricing (ConsolePricingTable, FeeLadder, FeePanel
175
+ - read-only, because the fees operation is GET-only; the panel renders
176
+ fields, never an editable form).
177
+ Hooks: useCompanyFees.
178
+ Binding: the fee data the packages actually serve is a VOLUME-TIER model - tier
179
+ name, ramp direction, minimum and maximum volume, percentage, version - and it
180
+ is the same model the shipped withdrawal quote consumes, so this screen shows
181
+ where a real quote comes from. A second, richer per-rail configuration model
182
+ exists on an internal plane and is NOT served here; it renders as a labelled
183
+ omission, never as an empty form.
184
+ States that must exist: loading, tiers present, no tiers, configuration unavailable, worked example, save failed.
185
+ Rules that must hold: a worked arithmetic ladder is mandatory on the tier
186
+ section - a sample amount times the tier percentage, with the operator glyphs in
187
+ a left gutter - because a pricing screen that shows only stored numbers teaches
188
+ nothing; the ladder renders ONLY over data that exists, never over the omitted
189
+ section; the tier
190
+ a sample amount falls into is highlighted in the table so the row and the ladder
191
+ are visibly the same fact; a single-member enum renders as a disabled
192
+ single-value field that says so, not a select pretending at choice; a date
193
+ window that has not opened reads scheduled, never active; forms are single
194
+ column with the field width capped, label above input, helper text between them
195
+ and the error below.`,
196
+ "console-simulator": `# Sandbox simulator (play the counterparty)
197
+ Shell: its own chrome - a scrimmed right-hand drawer on a distinct surface with
198
+ a persistent sandbox label, reachable from ONE fixed affordance in the top bar.
199
+ It is the only scrimmed drawer in the console, so the surface change alone
200
+ signals the register change.
201
+ Registry items: venly-tokens, field-list, status-pill, money; blocks:
202
+ console-simulator (SimulatorDrawer, SimulatorControl, LedgerVerifyPanel,
203
+ ChannelFooter - SimulatorControl refuses an imperative operator-decision
204
+ label with a thrown developer error).
205
+ Hooks: useVenlyMock. Every control maps to exactly one call on the mock's
206
+ simulations namespace - no control without a call, and no call renamed.
207
+ Binding: inbound credits, provider progression and screening verdicts are things
208
+ OTHER parties do, so they live here rather than in the operator's workflow.
209
+ States that must exist: drawer closed, drawer open, sharing, not sharing, credit landed, verdict returned, payout advanced, books balanced, books do not balance, reset.
210
+ Rules that must hold: controls are phrased as events that happen to you, in the
211
+ third person, while operator controls elsewhere are imperative decisions - a
212
+ control phrased in the wrong voice is in the wrong surface; a simulated
213
+ transition emits the SAME event the real path emits, and the trail attributes it
214
+ to the simulator plainly rather than to an operator; the drawer is reachable
215
+ only from the top bar, never from a queue row or a decision panel, because those
216
+ paths make another party's action look like the operator's; the ledger check gets
217
+ a visible surface: it is the one control here that asserts something true, namely
218
+ that the simulated books balance; the channel footer states the adapter, session
219
+ and peer count, and says IN WORDS when the surface is not actually sharing - the
220
+ default channel shares nothing and cross-context sharing is same-origin only, so
221
+ without that line a two-context demo can prove nothing while looking correct.`,
222
+ "console-webhooks": `# Console webhooks (endpoint registration, honestly bounded)
223
+ Shell: in-shell content column - a table with a panel form beside it. This
224
+ one IS a form: the public plane carries the full lifecycle (list, create,
225
+ read, replace, delete, ping).
226
+ Registry items: venly-tokens, data-table, status-pill, list-error; blocks:
227
+ console-webhooks (WebhooksTable, WebhookForm, WebhookDeliveryLog - the
228
+ delivery log renders inside SIMULATOR chrome only, never on this screen).
229
+ Hooks: useWebhooks, useWebhook, useCreateWebhook, useUpdateWebhook,
230
+ useDeleteWebhook, usePingWebhook.
231
+ Binding: webhook rows render the contract fields verbatim - url, name, and
232
+ a status enum that has exactly one member in this release, rendered as a
233
+ disabled single value that says so rather than a select pretending at
234
+ choice. The authentication method is a two-variant choice (API key or
235
+ basic); its secret fields are write-only on the contract, so the platform
236
+ never returns a stored secret and this screen never displays one - editing
237
+ means re-entering the credential, and the form says why.
238
+ States that must exist: loading, webhooks listed, no webhooks yet, registration form, secret masked, ping result, delete confirmation, list error.
239
+ Rules that must hold: Ping is the promoted per-row affordance - it is the
240
+ one real signal the API offers about an endpoint - and its result renders
241
+ verbatim; delivery history is NOT available from the API in this release
242
+ and the screen says so on the screen itself, with the next step (use Ping),
243
+ never as a silent gap; the create operation carries no idempotency
244
+ envelope, so a replayed create registers a second webhook - any
245
+ retry-safety a surface adds is a client-side convention badged as such,
246
+ never presented as contract behaviour; delete is confirm-and-explain: the
247
+ confirmation names the consequence before anything is removed; the
248
+ simulated delivery log is a sandbox surface phrased in the third person
249
+ and badged as simulation, rendered only inside the simulator's own chrome.`,
81
250
  };
82
251
  const JOURNEY_KEYS = Object.keys(JOURNEYS);
252
+ const RUNTIME_PACKAGES_BY_BLOCK = {
253
+ activity: {
254
+ "@venlyfinance/react": "^0.6.0",
255
+ "@venlyfinance/sdk": "^0.7.0",
256
+ "@tanstack/react-query": "^5.0.0",
257
+ },
258
+ auth: { "@radix-ui/react-one-time-password-field": "^0.1.16" },
259
+ balances: {
260
+ "@venlyfinance/react": "^0.6.0",
261
+ "@venlyfinance/sdk": "^0.7.0",
262
+ "@tanstack/react-query": "^5.0.0",
263
+ },
264
+ "bank-accounts": {
265
+ "@venlyfinance/react": "^0.6.0",
266
+ "@venlyfinance/sdk": "^0.7.0",
267
+ "@tanstack/react-query": "^5.0.0",
268
+ },
269
+ "console-decision": {
270
+ "@venlyfinance/react": "^0.6.0",
271
+ "@venlyfinance/sdk": "^0.7.0",
272
+ "@tanstack/react-query": "^5.0.0",
273
+ },
274
+ "console-queue": {
275
+ "@venlyfinance/react": "^0.6.0",
276
+ "@venlyfinance/sdk": "^0.7.0",
277
+ "@tanstack/react-query": "^5.0.0",
278
+ },
279
+ "console-pricing": {
280
+ "@venlyfinance/react": "^0.6.0",
281
+ "@venlyfinance/sdk": "^0.7.0",
282
+ "@tanstack/react-query": "^5.0.0",
283
+ },
284
+ "console-simulator": {
285
+ "@venlyfinance/react": "^0.6.0",
286
+ "@venlyfinance/sdk": "^0.7.0",
287
+ "@tanstack/react-query": "^5.0.0",
288
+ },
289
+ "console-tenant": {
290
+ "@venlyfinance/react": "^0.6.0",
291
+ "@venlyfinance/sdk": "^0.7.0",
292
+ "@tanstack/react-query": "^5.0.0",
293
+ },
294
+ "console-webhooks": {
295
+ "@venlyfinance/react": "^0.6.0",
296
+ "@venlyfinance/sdk": "^0.7.0",
297
+ "@tanstack/react-query": "^5.0.0",
298
+ },
299
+ onboarding: {
300
+ "@venlyfinance/react": "^0.6.0",
301
+ "@venlyfinance/sdk": "^0.7.0",
302
+ "@tanstack/react-query": "^5.0.0",
303
+ },
304
+ receive: {
305
+ "@venlyfinance/react": "^0.6.0",
306
+ "@venlyfinance/sdk": "^0.7.0",
307
+ "@tanstack/react-query": "^5.0.0",
308
+ },
309
+ reconciliation: {
310
+ "@venlyfinance/react": "^0.6.0",
311
+ "@venlyfinance/sdk": "^0.7.0",
312
+ "@tanstack/react-query": "^5.0.0",
313
+ },
314
+ recipients: {
315
+ "@venlyfinance/react": "^0.6.0",
316
+ "@venlyfinance/sdk": "^0.7.0",
317
+ "@tanstack/react-query": "^5.0.0",
318
+ },
319
+ send: {
320
+ "@venlyfinance/react": "^0.6.0",
321
+ "@venlyfinance/sdk": "^0.7.0",
322
+ "@tanstack/react-query": "^5.0.0",
323
+ "@radix-ui/react-one-time-password-field": "^0.1.16",
324
+ },
325
+ team: { "@radix-ui/react-dialog": "^1.1.23" },
326
+ withdraw: {
327
+ "@venlyfinance/react": "^0.6.0",
328
+ "@venlyfinance/sdk": "^0.7.0",
329
+ "@tanstack/react-query": "^5.0.0",
330
+ },
331
+ };
332
+ /**
333
+ * Kept in step with the ranges the registry generator stamps into ui/r/*.json
334
+ * (`RUNTIME_DEPENDENCIES` in ui/scripts/build-registry.mjs): the runtime-contract
335
+ * test asserts the two agree, so a blueprint can never advertise a range the
336
+ * registry will not install.
337
+ *
338
+ * The package set any hook-using screen needs, for journeys the registry has no
339
+ * composite block for yet - those screens are built from primitives
340
+ * (data-table, side-panel, timeline …), and a primitive registry item declares
341
+ * no npm dependencies, so deriving `requiredPackages` from blocks alone would
342
+ * tell an agent that a surface living entirely on hooks needs no packages.
343
+ *
344
+ * The ranges name the versions the console surfaces actually consume: the
345
+ * party IV read and the payout hooks arrived in sdk 0.7.0 / react 0.6.0, on
346
+ * top of the 0.6.0 mock behaviours (channel state, balances that move).
347
+ */
348
+ const DATA_PLANE_PACKAGES = {
349
+ "@venlyfinance/react": "^0.6.0",
350
+ "@venlyfinance/sdk": "^0.7.0",
351
+ "@tanstack/react-query": "^5.0.0",
352
+ };
353
+ const JOURNEY_RUNTIME = {
354
+ auth: {
355
+ blocks: ["auth"],
356
+ hooks: [],
357
+ demoBindings: [{ import: "createMockAuthAdapter", from: "registry:block/auth" }],
358
+ },
359
+ team: {
360
+ blocks: ["team"],
361
+ hooks: [],
362
+ demoBindings: [{ import: "createMockTeamAdapter", from: "registry:block/team" }],
363
+ },
364
+ "home-balances": { blocks: ["balances"], hooks: ["useAccounts", "useWallets"] },
365
+ receive: { blocks: ["receive"], hooks: ["useVirtualBankAccounts"] },
366
+ send: {
367
+ blocks: ["send", "recipients"],
368
+ hooks: [
369
+ "useCreateFiatTransfer",
370
+ "useCreateCryptoTransfer",
371
+ "useRequestPayout",
372
+ "usePartyRoles",
373
+ "useAddPartyRole",
374
+ "useCreateParty",
375
+ "useRegisterPayoutBankAccount",
376
+ "useCreatePayoutRoute",
377
+ "usePreparePayoutOwnershipProof",
378
+ "useCompletePayoutOwnershipProof",
379
+ "useParties",
380
+ "useAccounts",
381
+ "useWallets",
382
+ "useAccountSupportedAssets",
383
+ "useTransfers",
384
+ "useTransfer",
385
+ "usePayouts",
386
+ "usePayout",
387
+ "usePayoutRoutes",
388
+ ],
389
+ extraForbidden: [
390
+ "a fee row or a \"No fee\" claim (no source confirms zero)",
391
+ "an ETA or delivery-date row (no timing field exists on transfers or payouts)",
392
+ "a pre-create rate or recipient-gets figure (exchangeRate/settledFiatAmount are post-create fields)",
393
+ "named in-flight stages beyond the status enums (render the observation log instead)",
394
+ "a send-to-external-wallet surface (no teaser, no disabled row, no rendered trace)",
395
+ ],
396
+ },
397
+ activity: { blocks: ["activity"], hooks: ["useTransfers", "useRampRequests"] },
398
+ "onboarding-status": {
399
+ blocks: ["onboarding"],
400
+ hooks: ["useCreateParty", "useCreateAccount", "useParty", "useAccount"],
401
+ },
402
+ "withdraw-bank-accounts": {
403
+ blocks: ["bank-accounts", "withdraw"],
404
+ hooks: [
405
+ "useCompanyBankAccounts",
406
+ "useBankAccountConfig",
407
+ "useCreateCompanyBankAccount",
408
+ "useRampRequests",
409
+ "useRampRequest",
410
+ "useCreateRampRequest",
411
+ "useFeeQuote",
412
+ "useRampPairs",
413
+ "useReferenceData",
414
+ "useFourEyesApproval",
415
+ "useInitiateRamp",
416
+ "describeRampStatus",
417
+ ],
418
+ },
419
+ reconciliation: {
420
+ blocks: ["reconciliation"],
421
+ hooks: ["useVirtualBankAccounts", "useTransfers"],
422
+ },
423
+ "proof-of-segregation": { blocks: ["balances"], hooks: ["useWallets", "useAccount"] },
424
+ approvals: {
425
+ blocks: ["withdraw"],
426
+ hooks: ["useRampRequests", "useFourEyesApproval", "useRampLifecycle"],
427
+ },
428
+ "console-review-queue": {
429
+ blocks: ["console-queue"],
430
+ dataPlane: true,
431
+ hooks: ["useAccounts", "useParties"],
432
+ extraForbidden: [
433
+ "a whose-move or needs-attention value computed from anything other than enum values on the row",
434
+ "a target time, breach threshold or overdue state (the API publishes no targets)",
435
+ "labelling a created-at delta \"time in state\" rather than \"Age\" (only an API-computed duration may use that phrase)",
436
+ ],
437
+ },
438
+ "console-decision-detail": {
439
+ blocks: ["console-decision"],
440
+ dataPlane: true,
441
+ hooks: [
442
+ "useAccount",
443
+ "useParty",
444
+ "useWallets",
445
+ "useTransfers",
446
+ "useVirtualBankAccounts",
447
+ "useVenlyMock",
448
+ ],
449
+ extraForbidden: [
450
+ "a rendered placeholder where an unavailable field belongs (omission is a prop type, not a string)",
451
+ "a captured field the API cannot carry, rendered without the console-note badge",
452
+ "a status change that leaves no timeline node with actor, role and timezone-qualified stamp",
453
+ "auto-retry on a version conflict (refetch and let the operator re-decide)",
454
+ ],
455
+ },
456
+ "console-pricing-config": {
457
+ blocks: ["console-pricing"],
458
+ dataPlane: true,
459
+ hooks: ["useCompanyFees"],
460
+ extraForbidden: [
461
+ "an arithmetic ladder over figures the API does not serve",
462
+ "a single-member enum rendered as a select",
463
+ "an editable control on the tier section (the fees operation is GET-only)",
464
+ ],
465
+ },
466
+ "console-simulator": {
467
+ blocks: ["console-simulator"],
468
+ dataPlane: true,
469
+ hooks: ["useVenlyMock"],
470
+ extraForbidden: [
471
+ "counterparty or provider simulation rendered inside operator chrome",
472
+ "a simulator control reachable from a queue row or a decision panel",
473
+ "a simulator control phrased as an imperative operator decision",
474
+ "a cross-context demo that does not state its channel adapter and peer count",
475
+ ],
476
+ },
477
+ "console-webhooks": {
478
+ blocks: ["console-webhooks"],
479
+ dataPlane: true,
480
+ hooks: [
481
+ "useWebhooks",
482
+ "useWebhook",
483
+ "useCreateWebhook",
484
+ "useUpdateWebhook",
485
+ "useDeleteWebhook",
486
+ "usePingWebhook",
487
+ ],
488
+ extraForbidden: [
489
+ "a delivery-history surface presented as API-served (no delivery-log operation exists on any plane)",
490
+ "a stored secret displayed anywhere (the authentication secret fields are write-only)",
491
+ "retry-safety presented as contract behaviour (a replayed create registers a second webhook)",
492
+ "the single-member status enum rendered as a select",
493
+ ],
494
+ },
495
+ };
496
+ const RUNTIME_CONTRACT_SCHEMA = z.object({
497
+ runtimeMode: z.enum(["mock", "staging", "production"]),
498
+ requiredPackages: z.record(z.string()),
499
+ requiredHooks: z.array(z.object({ import: z.string(), from: z.string() })),
500
+ demoBindings: z.array(z.object({ import: z.string(), from: z.string() })).optional(),
501
+ provider: z.object({
502
+ import: z.string(),
503
+ from: z.string(),
504
+ props: z.object({ environment: z.literal("mock") }),
505
+ }),
506
+ forbiddenPatterns: z.array(z.string()),
507
+ install: z.array(z.string()),
508
+ completionChecks: z.array(z.string()),
509
+ });
510
+ function runtimeContractForJourney(journey) {
511
+ const definition = JOURNEY_RUNTIME[journey];
512
+ // Base first, blocks last: a composite block's own stamped dependencies are
513
+ // what the registry will actually install, so they win where the two differ.
514
+ const requiredPackages = definition.dataPlane
515
+ ? { ...DATA_PLANE_PACKAGES }
516
+ : {};
517
+ for (const block of definition.blocks) {
518
+ Object.assign(requiredPackages, RUNTIME_PACKAGES_BY_BLOCK[block]);
519
+ }
520
+ const installItems = definition.blocks.length
521
+ ? definition.blocks.map((block) => `@venlyfinance/${block}`)
522
+ : (definition.registryItems ?? []).map((item) => `@venlyfinance/${item}`);
523
+ return {
524
+ runtimeMode: "mock",
525
+ requiredPackages,
526
+ requiredHooks: definition.hooks.map((name) => ({
527
+ import: name,
528
+ from: "@venlyfinance/react",
529
+ })),
530
+ ...(definition.demoBindings ? { demoBindings: definition.demoBindings } : {}),
531
+ provider: {
532
+ import: "VenlyProvider",
533
+ from: "@venlyfinance/react",
534
+ props: { environment: "mock" },
535
+ },
536
+ forbiddenPatterns: [
537
+ "in-memory store of transfer/balance/approval state",
538
+ "fetch()/axios to self-owned money routes that do not wrap @venlyfinance/sdk",
539
+ "useEffect polling loops for transfer status (useStagedTransfer/useRampLifecycle exist)",
540
+ "clientSecret in browser code (provider throws; use proxyClientOptions())",
541
+ ...(definition.extraForbidden ?? []),
542
+ ],
543
+ install: [
544
+ "npx shadcn@latest init -y -b radix -p nova",
545
+ 'add { "registries": { "@venlyfinance": "https://raw.githubusercontent.com/Venly/venly-settlement-sdk/main/ui/r/{name}.json" } } to components.json',
546
+ `npx shadcn@latest add ${installItems.join(" ")} -y -o`,
547
+ ],
548
+ completionChecks: [
549
+ 'npx @venlyfinance/settlement-mcp review "src/**/*.tsx" exits 0',
550
+ 'npx @venlyfinance/settlement-mcp verify "src/**/*.{ts,tsx}" exits 0',
551
+ ],
552
+ };
553
+ }
83
554
  // ---------------------------------------------------------------------------
84
555
  // Shared mechanics. Three cross-cutting behaviours every rule participates in:
85
556
  //
@@ -442,9 +913,58 @@ export function registerFrontendTools(server) {
442
913
  inputSchema: {
443
914
  journey: z.enum(JOURNEY_KEYS).describe("Which journey to blueprint"),
444
915
  },
445
- }, async ({ journey }) => ({
446
- content: [{ type: "text", text: JOURNEYS[journey] }],
447
- }));
916
+ outputSchema: {
917
+ runtime_contract: RUNTIME_CONTRACT_SCHEMA,
918
+ },
919
+ }, async ({ journey }) => {
920
+ const structuredContent = {
921
+ runtime_contract: runtimeContractForJourney(journey),
922
+ };
923
+ return {
924
+ content: [
925
+ { type: "text", text: JOURNEYS[journey] },
926
+ {
927
+ type: "text",
928
+ text: `\`\`\`json\n${JSON.stringify(structuredContent, null, 2)}\n\`\`\``,
929
+ },
930
+ ],
931
+ structuredContent,
932
+ };
933
+ });
934
+ server.registerTool("verify_runtime_contract", {
935
+ title: "Verify an app's Venly runtime contract",
936
+ description: "Deterministically checks supplied app source and package.json against the direct-sdk or backend-proxy runtime contract. The same rules power the verify CLI.",
937
+ inputSchema: {
938
+ files: z
939
+ .array(z.object({ path: z.string().min(1), source: z.string() }))
940
+ .min(1),
941
+ packageJson: z.string().describe("The app's package.json contents"),
942
+ profile: z.enum(["direct-sdk", "backend-proxy"]).optional(),
943
+ },
944
+ }, async ({ files, packageJson, profile }) => {
945
+ let parsedPackageJson;
946
+ try {
947
+ parsedPackageJson = JSON.parse(packageJson);
948
+ }
949
+ catch (error) {
950
+ const message = `Invalid packageJson: ${error.message}`;
951
+ return {
952
+ content: [{ type: "text", text: message }],
953
+ structuredContent: { error: message },
954
+ isError: true,
955
+ };
956
+ }
957
+ const result = verifyRuntimeContract({ files, packageJson: parsedPackageJson, profile });
958
+ const structuredContent = {
959
+ profile: result.profile,
960
+ findings: result.findings,
961
+ summary: result.summary,
962
+ };
963
+ return {
964
+ content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
965
+ structuredContent,
966
+ };
967
+ });
448
968
  server.registerTool("review_screen", {
449
969
  title: "Design-audit a screen",
450
970
  description: "Deterministic audit of component/markup source against the kit's design contract: raw colours, hyphen-minus amounts, success styling on cancelled steps, masked review values, invented timing/custody copy, crypto codes inside Intl currency formatting, required fields rendered optional, parity and round-number fixtures, zebra striping, off-token shadows, gradients, colour-only state. Pass the journey key to also check the source against that journey's required blueprint states. Suppress a deliberate exception with venly-allow:<rule-id> on the offending line or the line above. Returns findings, not a score.",
package/dist/index.js CHANGED
@@ -42,6 +42,17 @@ if (argv[0] === "review") {
42
42
  process.exit(2);
43
43
  });
44
44
  }
45
+ else if (argv[0] === "verify") {
46
+ import("./verify-cli.js")
47
+ .then(({ runVerifyCli }) => runVerifyCli(argv.slice(1)))
48
+ .then((code) => {
49
+ process.exitCode = code;
50
+ })
51
+ .catch((err) => {
52
+ process.stderr.write(`Fatal: ${err.message}\n`);
53
+ process.exit(2);
54
+ });
55
+ }
45
56
  else {
46
57
  main().catch((err) => {
47
58
  process.stderr.write(`Fatal: ${err.message}\n`);
package/dist/server.js CHANGED
@@ -4,7 +4,7 @@
4
4
  * mock client and no network.
5
5
  */
6
6
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
7
- import { ENVIRONMENT_FLAG, SERVER_NAME, SERVER_VERSION, resolveVenlyEnvironment, } from "./constants.js";
7
+ import { ENVIRONMENT_FLAG, INSTRUCTIONS, SERVER_NAME, SERVER_VERSION, resolveVenlyEnvironment, } from "./constants.js";
8
8
  import { registerReadTools } from "./tools/read-tools.js";
9
9
  import { registerWriteTools } from "./tools/write-tools.js";
10
10
  import { registerX402Tools } from "./tools/x402-tools.js";
@@ -26,6 +26,8 @@ export function createServer(options) {
26
26
  const server = new McpServer({
27
27
  name: SERVER_NAME,
28
28
  version: SERVER_VERSION,
29
+ }, {
30
+ instructions: INSTRUCTIONS,
29
31
  });
30
32
  registerReadTools(server, options.client);
31
33
  registerWriteTools(server, options.client, env);
@@ -1,4 +1,4 @@
1
- export declare const EXPECTED_TOOLS: readonly ["list_ramp_requests", "get_ramp_request", "list_accounts", "get_account", "list_wallets", "list_virtual_bank_accounts", "get_virtual_bank_account", "reconcile_by_reference_code", "list_transfers", "get_transfer", "list_parties", "get_party", "get_reference_data", "create_party", "create_account", "create_virtual_bank_account", "create_fiat_transfer", "create_crypto_transfer", "approve_ramp_request", "reject_ramp_request", "create_payment_session", "list_payouts", "get_payout", "list_payout_routes", "list_payout_bank_accounts", "register_payout_bank_account", "create_payout_route", "prepare_payout_ownership_proof", "complete_payout_ownership_proof", "request_payout", "quote_x402_payment", "get_journey_blueprint", "review_screen"];
1
+ export declare const EXPECTED_TOOLS: readonly ["list_ramp_requests", "get_ramp_request", "list_accounts", "get_account", "list_wallets", "list_virtual_bank_accounts", "get_virtual_bank_account", "reconcile_by_reference_code", "list_transfers", "get_transfer", "list_parties", "get_party", "get_reference_data", "create_party", "create_account", "create_virtual_bank_account", "create_fiat_transfer", "create_crypto_transfer", "approve_ramp_request", "reject_ramp_request", "create_payment_session", "list_payouts", "get_payout", "list_payout_routes", "list_payout_bank_accounts", "register_payout_bank_account", "create_payout_route", "prepare_payout_ownership_proof", "complete_payout_ownership_proof", "request_payout", "quote_x402_payment", "get_journey_blueprint", "verify_runtime_contract", "review_screen"];
2
2
  export declare const EXPECTED_RESOURCE_URIS: readonly ["venly://capabilities", "venly://safety", "venly://workflows/international-account", "venly://workflows/mock-to-staging", "venly://frontend/agents"];
3
3
  export declare const EXPECTED_PROMPTS: readonly ["build_international_account"];
4
4
  export interface DiscoveryNames {
@@ -36,6 +36,7 @@ export const EXPECTED_TOOLS = [
36
36
  "request_payout",
37
37
  "quote_x402_payment",
38
38
  "get_journey_blueprint",
39
+ "verify_runtime_contract",
39
40
  "review_screen",
40
41
  ];
41
42
  export const EXPECTED_RESOURCE_URIS = [
@@ -0,0 +1,24 @@
1
+ export type VerifyProfile = "direct-sdk" | "backend-proxy";
2
+ export interface VerifySourceFile {
3
+ path: string;
4
+ source: string;
5
+ }
6
+ export interface VerifyFinding {
7
+ rule: string;
8
+ severity: "error" | "warn";
9
+ path: string;
10
+ evidence: string;
11
+ fix: string;
12
+ line?: number;
13
+ }
14
+ export interface VerifyResult {
15
+ profile: VerifyProfile;
16
+ findings: VerifyFinding[];
17
+ summary: string;
18
+ }
19
+ export declare function verifyRuntimeContract(options: {
20
+ files: VerifySourceFile[];
21
+ packageJson: Record<string, unknown>;
22
+ profile?: VerifyProfile;
23
+ }): VerifyResult;
24
+ export declare function runVerifyCli(args: string[], out?: NodeJS.WritableStream, err?: NodeJS.WritableStream): Promise<0 | 1 | 2>;
@@ -0,0 +1,371 @@
1
+ // `verify` subcommand: deterministic runtime-contract checks for generated apps.
2
+ //
3
+ // Exit codes: 0 clean (warnings allowed) · 1 at least one error · 2 usage or
4
+ // no-match. The three unresolved false-positive boundaries intentionally warn:
5
+ // missing React in direct-sdk, app-owned money routes, and in-memory stores.
6
+ import { existsSync, readFileSync, readdirSync, statSync, } from "node:fs";
7
+ import { dirname, join, relative, resolve } from "node:path";
8
+ const BLUEPRINT_HOOKS = new Set([
9
+ "useAccount",
10
+ "useAccounts",
11
+ "useBankAccountConfig",
12
+ "useCompanyBankAccounts",
13
+ "useCreateAccount",
14
+ "useCreateCompanyBankAccount",
15
+ "useCreateParty",
16
+ "useCreateRampRequest",
17
+ "useFeeQuote",
18
+ "useFourEyesApproval",
19
+ "useInitiateRamp",
20
+ "useParty",
21
+ "useRampLifecycle",
22
+ "useRampPairs",
23
+ "useRampRequest",
24
+ "useRampRequests",
25
+ "useReferenceData",
26
+ "useStagedTransfer",
27
+ "useTransfers",
28
+ "useVirtualBankAccounts",
29
+ "useWallets",
30
+ ]);
31
+ function lineFor(source, index) {
32
+ return source.slice(0, index).split("\n").length;
33
+ }
34
+ function suppressed(source, rule, line) {
35
+ const token = `venly-allow:${rule}`;
36
+ if (line === undefined)
37
+ return source.includes(token);
38
+ const lines = source.split("\n");
39
+ return Boolean(lines[line - 1]?.includes(token) || lines[line - 2]?.includes(token));
40
+ }
41
+ function dependencies(packageJson) {
42
+ return Object.assign({}, packageJson.dependencies ?? {}, packageJson.devDependencies ?? {}, packageJson.peerDependencies ?? {});
43
+ }
44
+ function importsFrom(source, packageName) {
45
+ const names = [];
46
+ const expression = new RegExp(`import\\s*\\{([^}]*)\\}\\s*from\\s*["']${packageName.replaceAll("/", "\\/")}["']`, "g");
47
+ for (const match of source.matchAll(expression)) {
48
+ for (const item of (match[1] ?? "").split(",")) {
49
+ const name = item.trim().split(/\s+as\s+/)[0]?.trim();
50
+ if (name)
51
+ names.push(name);
52
+ }
53
+ }
54
+ return names;
55
+ }
56
+ function isServerFile(file) {
57
+ return (/(?:^|\/)(?:server|backend|api)(?:\/|\.)/i.test(file.path) ||
58
+ /(?:^|\/)route\.[cm]?[jt]sx?$/i.test(file.path) ||
59
+ /[.]server\.[cm]?[jt]sx?$/i.test(file.path) ||
60
+ /^\s*["']use server["'];?/m.test(file.source));
61
+ }
62
+ function isMoneyRoute(file) {
63
+ const routeHandler = /(?:^|\/)route\.[cm]?[jt]sx?$/i.test(file.path) ||
64
+ /export\s+(?:async\s+)?function\s+(?:GET|POST|PUT|PATCH|DELETE)\b/.test(file.source);
65
+ const moneySignal = /(?:transfers?|payouts?|balances?|ramps?|rampRequests|virtual[-_/ ]bank)/i.test(`${file.path}\n${file.source}`);
66
+ return routeHandler && moneySignal;
67
+ }
68
+ function autoDetectProfile(files) {
69
+ return files.some((file) => file.source.includes("proxyClientOptions") || isMoneyRoute(file))
70
+ ? "backend-proxy"
71
+ : "direct-sdk";
72
+ }
73
+ export function verifyRuntimeContract(options) {
74
+ const { files, packageJson } = options;
75
+ const profile = options.profile ?? autoDetectProfile(files);
76
+ const deps = dependencies(packageJson);
77
+ const findings = [];
78
+ function addProjectFinding(finding) {
79
+ const source = files.map((file) => file.source).join("\n");
80
+ if (!suppressed(source, finding.rule)) {
81
+ findings.push({ ...finding, path: "package.json" });
82
+ }
83
+ }
84
+ function addSourceFinding(file, finding) {
85
+ if (!suppressed(file.source, finding.rule, finding.line)) {
86
+ findings.push({ ...finding, path: file.path });
87
+ }
88
+ }
89
+ if (!("@venlyfinance/react" in deps) && !("@venlyfinance/sdk" in deps)) {
90
+ addProjectFinding({
91
+ rule: "venly-package-missing",
92
+ severity: "error",
93
+ evidence: "package.json declares zero @venlyfinance runtime packages",
94
+ fix: "Install the registry block for the journey or add the required @venlyfinance package.",
95
+ });
96
+ }
97
+ if (profile === "direct-sdk") {
98
+ if (!("@venlyfinance/react" in deps)) {
99
+ addProjectFinding({
100
+ rule: "react-package-missing",
101
+ severity: "warn",
102
+ evidence: "direct-sdk profile has no @venlyfinance/react dependency",
103
+ fix: "Install the journey's registry block, or suppress this warning for an intentionally headless integration.",
104
+ });
105
+ }
106
+ const providerImported = files.some((file) => importsFrom(file.source, "@venlyfinance/react").includes("VenlyProvider"));
107
+ const mockProviderRendered = files.some((file) => /<VenlyProvider\b[^>]*\benvironment\s*=\s*(?:["']mock["']|\{[^}]+\})/s.test(file.source));
108
+ if (!providerImported || !mockProviderRendered) {
109
+ addProjectFinding({
110
+ rule: "provider-missing",
111
+ severity: "error",
112
+ evidence: "no VenlyProvider import and mock/environment expression wrapper were found",
113
+ fix: 'Import VenlyProvider from @venlyfinance/react and wrap the tree with environment="mock".',
114
+ });
115
+ }
116
+ const importedHooks = files.flatMap((file) => importsFrom(file.source, "@venlyfinance/react").filter((name) => BLUEPRINT_HOOKS.has(name)));
117
+ if (importedHooks.length === 0) {
118
+ addProjectFinding({
119
+ rule: "blueprint-hook-missing",
120
+ severity: "error",
121
+ evidence: "no journey-blueprint hook is imported from @venlyfinance/react",
122
+ fix: "Use the qualified hooks named by get_journey_blueprint instead of rebuilding the data layer.",
123
+ });
124
+ }
125
+ for (const file of files) {
126
+ if (!/(?:@venlyfinance\/react|["']react["']|["']use client["'])/.test(file.source))
127
+ continue;
128
+ for (const match of file.source.matchAll(/\bclientSecret\b/g)) {
129
+ addSourceFinding(file, {
130
+ rule: "browser-client-secret",
131
+ severity: "error",
132
+ line: lineFor(file.source, match.index ?? 0),
133
+ evidence: "clientSecret appears in browser/React source",
134
+ fix: "Keep secrets server-side; use proxyClientOptions() for browser traffic.",
135
+ });
136
+ }
137
+ }
138
+ }
139
+ else {
140
+ if (!("@venlyfinance/sdk" in deps)) {
141
+ addProjectFinding({
142
+ rule: "sdk-package-missing",
143
+ severity: "error",
144
+ evidence: "backend-proxy profile has no @venlyfinance/sdk dependency",
145
+ fix: "Add @venlyfinance/sdk and make money routes wrap the official client.",
146
+ });
147
+ }
148
+ for (const file of files) {
149
+ if (isMoneyRoute(file) && !/from\s*["']@venlyfinance\/sdk["']/.test(file.source)) {
150
+ addSourceFinding(file, {
151
+ rule: "money-route-without-sdk",
152
+ severity: "warn",
153
+ line: 1,
154
+ evidence: "money-route heuristic matched but no @venlyfinance/sdk import was found",
155
+ fix: "Wrap this route with @venlyfinance/sdk, or suppress if it is an unrelated consumer-owned ledger.",
156
+ });
157
+ }
158
+ if (!isServerFile(file)) {
159
+ for (const match of file.source.matchAll(/\bclientSecret\b/g)) {
160
+ addSourceFinding(file, {
161
+ rule: "client-secret-outside-server",
162
+ severity: "error",
163
+ line: lineFor(file.source, match.index ?? 0),
164
+ evidence: "clientSecret appears outside a server-only file",
165
+ fix: "Move the secret into a server route or server-only module.",
166
+ });
167
+ }
168
+ }
169
+ }
170
+ const proxyImported = files.some((file) => importsFrom(file.source, "@venlyfinance/react").includes("proxyClientOptions"));
171
+ if (!proxyImported) {
172
+ addProjectFinding({
173
+ rule: "proxy-client-options-missing",
174
+ severity: "warn",
175
+ evidence: "backend-proxy profile has no browser-side proxyClientOptions import",
176
+ fix: "Use proxyClientOptions() in the browser provider, or suppress for a server-only consumer.",
177
+ });
178
+ }
179
+ }
180
+ for (const file of files) {
181
+ if (/\buseEffect\b/.test(file.source) &&
182
+ /\bset(?:Interval|Timeout)\b/.test(file.source) &&
183
+ /(?:status|state)/i.test(file.source) &&
184
+ /\b(?:transfer|ramp)/i.test(file.source)) {
185
+ const match = /\buseEffect\b/.exec(file.source);
186
+ addSourceFinding(file, {
187
+ rule: "status-polling",
188
+ severity: "warn",
189
+ line: lineFor(file.source, match?.index ?? 0),
190
+ evidence: "useEffect timer polling appears beside transfer/ramp state",
191
+ fix: "Use useStagedTransfer or useRampLifecycle for lifecycle polling.",
192
+ });
193
+ }
194
+ const store = /(?:^|\n)\s*export\s+(?:const|let)\s+(transfers|balances|payouts|rampRequests)\s*=\s*(?:\[|new\s+(?:Map|Set)\b)/g;
195
+ for (const match of file.source.matchAll(store)) {
196
+ addSourceFinding(file, {
197
+ rule: "in-memory-money-store",
198
+ severity: "warn",
199
+ line: lineFor(file.source, match.index ?? 0),
200
+ evidence: `module exports mutable in-memory money state named ${match[1]}`,
201
+ fix: "Use @venlyfinance/react hooks/flows or the SDK; suppress only for a deliberate fixture.",
202
+ });
203
+ }
204
+ }
205
+ findings.sort((a, b) => a.path.localeCompare(b.path) ||
206
+ (a.line ?? 0) - (b.line ?? 0) ||
207
+ a.rule.localeCompare(b.rule));
208
+ const errors = findings.filter((finding) => finding.severity === "error").length;
209
+ const warnings = findings.length - errors;
210
+ return {
211
+ profile,
212
+ findings,
213
+ summary: `${errors} error(s), ${warnings} warning(s) across ${files.length} file(s)`,
214
+ };
215
+ }
216
+ const SKIP_DIRS = new Set(["node_modules", ".git", "dist"]);
217
+ function braceExpand(pattern) {
218
+ const match = /\{([^{}]*)\}/.exec(pattern);
219
+ if (!match)
220
+ return [pattern];
221
+ const before = pattern.slice(0, match.index);
222
+ const after = pattern.slice(match.index + match[0].length);
223
+ return (match[1] ?? "").split(",").flatMap((option) => braceExpand(before + option + after));
224
+ }
225
+ function patternToRegExp(pattern) {
226
+ const escaped = pattern.replace(/[.+^$()|[\]\\?]/g, "\\$&");
227
+ const translated = escaped
228
+ .replace(/\*\*\//g, "\u0000")
229
+ .replace(/\*\*/g, "\u0001")
230
+ .replace(/\*/g, "[^/]*")
231
+ .replace(/\u0000/g, "(?:.*/)?")
232
+ .replace(/\u0001/g, ".*");
233
+ return new RegExp(`^${translated}$`);
234
+ }
235
+ function walk(dir, into) {
236
+ let entries;
237
+ try {
238
+ entries = readdirSync(dir, { withFileTypes: true });
239
+ }
240
+ catch {
241
+ return;
242
+ }
243
+ for (const entry of entries) {
244
+ if (entry.isDirectory()) {
245
+ if (!SKIP_DIRS.has(entry.name))
246
+ walk(join(dir, entry.name), into);
247
+ }
248
+ else if (entry.isFile()) {
249
+ into.push(join(dir, entry.name));
250
+ }
251
+ }
252
+ }
253
+ function expandPattern(pattern, cwd) {
254
+ const results = [];
255
+ for (const variant of braceExpand(pattern)) {
256
+ const segments = variant.split("/");
257
+ const firstWild = segments.findIndex((segment) => segment.includes("*"));
258
+ if (firstWild === -1) {
259
+ if (existsSync(join(cwd, variant)) && statSync(join(cwd, variant)).isFile())
260
+ results.push(variant);
261
+ continue;
262
+ }
263
+ const staticPrefix = segments.slice(0, firstWild).join("/");
264
+ const root = staticPrefix ? join(cwd, staticPrefix) : cwd;
265
+ const files = [];
266
+ walk(root, files);
267
+ const matcher = patternToRegExp(variant);
268
+ for (const file of files) {
269
+ const rel = relative(cwd, file).split("\\").join("/");
270
+ if (matcher.test(rel))
271
+ results.push(rel);
272
+ }
273
+ }
274
+ return [...new Set(results)].sort();
275
+ }
276
+ function expandPatterns(patterns, cwd) {
277
+ return [...new Set(patterns.flatMap((pattern) => expandPattern(pattern, cwd)))];
278
+ }
279
+ function findPackageJson(file, cwd) {
280
+ let dir = dirname(resolve(cwd, file));
281
+ while (true) {
282
+ const candidate = join(dir, "package.json");
283
+ if (existsSync(candidate))
284
+ return candidate;
285
+ const parent = dirname(dir);
286
+ if (parent === dir)
287
+ return undefined;
288
+ dir = parent;
289
+ }
290
+ }
291
+ function parseArgs(args) {
292
+ const patterns = [];
293
+ let profile;
294
+ for (let index = 0; index < args.length; index++) {
295
+ const arg = args[index] ?? "";
296
+ if (arg === "--profile") {
297
+ const value = args[++index];
298
+ if (value !== "direct-sdk" && value !== "backend-proxy") {
299
+ return { patterns, error: "--profile must be direct-sdk or backend-proxy" };
300
+ }
301
+ profile = value;
302
+ }
303
+ else if (arg.startsWith("--profile=")) {
304
+ const value = arg.slice("--profile=".length);
305
+ if (value !== "direct-sdk" && value !== "backend-proxy") {
306
+ return { patterns, error: "--profile must be direct-sdk or backend-proxy" };
307
+ }
308
+ profile = value;
309
+ }
310
+ else if (arg.startsWith("-")) {
311
+ return { patterns, error: `Unknown option: ${arg}` };
312
+ }
313
+ else {
314
+ patterns.push(arg);
315
+ }
316
+ }
317
+ return { patterns, profile };
318
+ }
319
+ export async function runVerifyCli(args, out = process.stdout, err = process.stderr) {
320
+ const parsed = parseArgs(args);
321
+ if (parsed.error || parsed.patterns.length === 0) {
322
+ if (parsed.error)
323
+ err.write(`${parsed.error}\n`);
324
+ err.write('Usage: verify [--profile direct-sdk|backend-proxy] "<glob>" [more globs or files]\n' +
325
+ ' e.g. verify "src/**/*.{ts,tsx}"\n' +
326
+ "Exits 1 on any error-severity finding, 2 when nothing matched.\n");
327
+ return 2;
328
+ }
329
+ const cwd = process.cwd();
330
+ const files = expandPatterns(parsed.patterns, cwd);
331
+ if (files.length === 0) {
332
+ err.write(`Nothing matched: ${parsed.patterns.join(" ")}\n`);
333
+ return 2;
334
+ }
335
+ const groups = new Map();
336
+ for (const file of files) {
337
+ const packagePath = findPackageJson(file, cwd) ?? join(cwd, "package.json");
338
+ groups.set(packagePath, [...(groups.get(packagePath) ?? []), file]);
339
+ }
340
+ let errors = 0;
341
+ let warnings = 0;
342
+ for (const [packagePath, groupFiles] of [...groups.entries()].sort()) {
343
+ let packageJson = {};
344
+ if (existsSync(packagePath)) {
345
+ try {
346
+ packageJson = JSON.parse(readFileSync(packagePath, "utf8"));
347
+ }
348
+ catch (error) {
349
+ err.write(`Invalid package.json at ${relative(cwd, packagePath)}: ${error.message}\n`);
350
+ return 2;
351
+ }
352
+ }
353
+ const result = verifyRuntimeContract({
354
+ files: groupFiles.map((path) => ({ path, source: readFileSync(path, "utf8") })),
355
+ packageJson,
356
+ profile: parsed.profile,
357
+ });
358
+ out.write(`profile: ${result.profile}\n`);
359
+ for (const finding of result.findings) {
360
+ if (finding.severity === "error")
361
+ errors++;
362
+ else
363
+ warnings++;
364
+ const line = finding.line === undefined ? "" : `:${finding.line}`;
365
+ out.write(`${finding.path}${line} ${finding.severity} ${finding.rule} ${finding.evidence}\n`);
366
+ out.write(` fix: ${finding.fix}\n`);
367
+ }
368
+ }
369
+ out.write(`${errors} error(s), ${warnings} warning(s) across ${files.length} file(s)\n`);
370
+ return errors > 0 ? 1 : 0;
371
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@venlyfinance/settlement-mcp",
3
- "version": "0.6.0",
3
+ "version": "0.7.1",
4
4
  "description": "Venly Finance MCP: SDK-backed tools, resources and prompts for building international money products safely.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -29,7 +29,7 @@
29
29
  "node": ">=20"
30
30
  },
31
31
  "dependencies": {
32
- "@venlyfinance/sdk": "^0.4.0",
32
+ "@venlyfinance/sdk": "^0.5.0",
33
33
  "@modelcontextprotocol/sdk": "^1.30.0",
34
34
  "zod": "^3.23.8"
35
35
  },