@capxul/sdk 1.2.2 → 1.2.3
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/README.md +18 -20
- package/dist/{create-capxul-client-DVzm78RU.mjs → create-capxul-client-BTnlLLag.mjs} +462 -66
- package/dist/create-capxul-client-BTnlLLag.mjs.map +1 -0
- package/dist/{create-capxul-client-C7H5b68l.d.mts → create-capxul-client-BxTtXho7.d.mts} +287 -285
- package/dist/create-capxul-client-BxTtXho7.d.mts.map +1 -0
- package/dist/index.d.mts +29 -78
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +131 -405
- package/dist/index.mjs.map +1 -1
- package/dist/node/index.d.mts +1 -1
- package/dist/{signer-CJT0pPiO.d.mts → signer-DgWAmtmi.d.mts} +2 -3
- package/dist/{signer-CJT0pPiO.d.mts.map → signer-DgWAmtmi.d.mts.map} +1 -1
- package/dist/testing/index.d.mts +1 -1
- package/dist/testing/index.mjs +1 -1
- package/package.json +4 -4
- package/dist/create-capxul-client-C7H5b68l.d.mts.map +0 -1
- package/dist/create-capxul-client-DVzm78RU.mjs.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"create-capxul-client-BTnlLLag.mjs","names":["_exhaustive","processLike","AppIdSchema","ChainIdSchema","CurrencyCodeSchema","DocumentHashSchema","EpochMsSchema","DurationMsSchema","AppIdSchema","ChainIdSchema","EpochMsSchema","DurationMsSchema","ChainIdSchema","CurrencyCodeSchema","DocumentHashSchema","EpochMsSchema","mapOk","normalizeRefForBackend","normalizePaymentTiming","missingConvexCall","handleRefValue","nonEmptyRefValue","errorKind","EVM_ADDRESS_RE","cloneProps","cloneTelemetryValue","#capture","#identify","#group","#reset","#run","processLike","mapOk","normalizePaymentTiming","emailDomain","processLike","normalizeRefForBackend","sdkPackageJson.version"],"sources":["../src/domain/identity/model.ts","../../config/src/tokens.ts","../../config/src/org-payments.ts","../../config/src/safe.ts","../../config/src/binding.ts","../../config/src/route.ts","../../config/src/role-dsl.ts","../../config/src/org-zodiac.ts","../../config/src/org-bootstrap.ts","../src/telemetry/stack-frame-parser.ts","../src/telemetry/get-failure-mode.ts","../src/telemetry/capture-exception.ts","../src/surface/_shared/provisioning-telemetry.ts","../src/internal/invocation-observation.ts","../src/domain/machine/telemetry.ts","../src/domain/machine/shell.ts","../src/surface/to-capxul-result.ts","../src/surface/_shared/effect-actor-bridge.ts","../src/surface/account-deps.ts","../src/surface/account-lifecycle.ts","../../wire/src/brands.ts","../../wire/src/bootstrap.ts","../../wire/src/functions.ts","../../wire/src/status.ts","../../wire/src/financial-ops.ts","../../wire/src/document-render.ts","../../wire/src/secret-material.ts","../../wire/src/observation-context.ts","../src/contract/actor-scope.ts","../src/surface/contacts.ts","../src/surface/account.ts","../package.json","../src/ports/auth-client.ts","../src/adapters/auth-client/effect-port.ts","../src/ports/bootstrap.ts","../src/ports/clock.ts","../src/ports/convex-call.ts","../src/ports/identity.ts","../src/adapters/_shared/wire.ts","../src/domain/money/to-wei.ts","../src/ports/account-read.ts","../src/domain/money/from-wei.ts","../src/ports/sub-account.ts","../src/ports/smart-account.ts","../../observability/src/index.ts","../src/ports/telemetry.ts","../src/adapters/telemetry/PostHogTelemetryAdapter.ts","../src/flows/identity.ts","../src/contract/org-lifecycle.ts","../src/surface/capxul-deps.ts","../src/surface/auth.ts","../src/surface/smart-account-deps.ts","../src/surface/smart-account.ts","../src/contract/identity.ts","../src/surface/identity-deps.ts","../src/surface/identity.ts","../src/surface/_shared/money-telemetry.ts","../src/surface/accounts-deps.ts","../src/surface/accounts.ts","../src/surface/current-user.ts","../src/contract/financial-ops.ts","../src/surface/money.ts","../src/contract/media.ts","../src/surface/media.ts","../src/contract/system.ts","../src/surface/system.ts","../src/surface/sub-accounts-deps.ts","../src/surface/sub-accounts.ts","../src/contract/payroll.ts","../src/surface/_shared/org-telemetry.ts","../src/domain/org/spend-gate.ts","../src/surface/org-deps.ts","../src/surface/org-lifecycle.ts","../src/surface/org.ts","../src/surface/factory.ts","../src/observation.ts","../src/telemetry/from-posthog.ts","../src/telemetry/identity-product.ts","../src/surface/create-capxul-client.ts"],"sourcesContent":["/**\n * T3 CANDIDATE 1 — \"one nested machine\".\n *\n * ONE identity machine. The session phases are the outer states; the readiness\n * lanes NEST inside `authenticated`; the org lane NESTS inside the claimed\n * account. Session-read stays in-machine as an event on its own slot (the\n * incumbent seam, redesigned states).\n *\n * Replaces the former split auth and provisioning machines plus the separate\n * account-lane phase reducer as one union. Organization lifecycle vocabulary\n * remains shared with the consumer surface while ordering becomes structural.\n *\n * The load-bearing structural claim (wayfinder map #1049): `org` is a FIELD OF\n * THE CLAIMED ACCOUNT. There is nowhere to put an organization lane unless the\n * personal Safe is deployed and claimed — the ordering is a type, not a guard.\n */\n\nimport type { Outcome } from \"../machine/shell.ts\";\nimport type { Failure } from \"@capxul/errors\";\n\n// ---------------------------------------------------------------------------\n// Refusals — a per-machine string-literal union, every member a real\n// CapxulErrorCode (packages/errors/src/errors.ts:6-27).\n// ---------------------------------------------------------------------------\n\nexport type RefusalReason = \"WRONG_STATE\" | \"INVALID_INPUT\" | \"OTP_EXPIRED\" | \"SIGNER_REJECTED\";\n\nexport type Refusal = { readonly refused: RefusalReason };\nconst WRONG: Refusal = { refused: \"WRONG_STATE\" };\n\n/** org-lifecycle.ts:173-184, lifted verbatim. */\nexport const isRetryable = (failure: Failure): boolean => {\n if (failure.code === \"CANCELLED\" || failure.code === \"SIGNER_REJECTED\") return true;\n if (failure.code === \"PROVIDER_ERROR\") {\n const mode = failure.mode;\n return (\n mode !== \"auth-origin-mismatch\" &&\n mode !== \"app-env-allowlist\" &&\n mode !== \"no-secure-context\"\n );\n }\n return failure.code === \"NETWORK_ERROR\" || failure.code === \"UNKNOWN\";\n};\n\n// ---------------------------------------------------------------------------\n// The state\n// ---------------------------------------------------------------------------\n\nexport interface Session {\n readonly email: string;\n readonly authUserId: string;\n}\n\n/** the pre-S1 account lane — PRD #462: wallet→identity→provision is counterfactual\n * and signerless; `deploy` is the separate claim step that needs a signer. */\nexport type AccountStep = \"wallet\" | \"identity\" | \"provision\" | \"deploy\";\n\n/** org-lifecycle.ts:7-11, verbatim. */\nexport type OrgStep =\n | \"preparingFounderAccount\"\n | \"awaitingFounderAuthorization\"\n | \"submittingBootstrap\"\n | \"confirmingBootstrap\";\n\nexport interface OrgDraft {\n readonly name: string;\n readonly handle: string;\n readonly country: string;\n}\n\n/** Full one-shot coordinator input. Only {@link OrgDraft} is retained in IdentityState. */\nexport interface OrgSubmissionDraft extends OrgDraft {\n readonly bio?: string;\n readonly size?: string;\n}\n\n/** The org lane, keyed by the active orgId — which does not exist yet while the\n * FIRST DURABLE ORG WRITE is in flight, hence `creating` carrying only a draft. */\nexport type OrgLane =\n | { readonly at: \"creating\"; readonly draft: OrgDraft }\n | { readonly at: \"loading\"; readonly orgId: string }\n | { readonly at: \"settingUp\"; readonly orgId: string; readonly step: OrgStep }\n | { readonly at: \"ready\"; readonly orgId: string }\n | {\n readonly at: \"failed\";\n readonly orgId: string | null;\n readonly step: OrgStep;\n readonly failure: Failure;\n readonly retryable: boolean;\n };\n\n/**\n * Personal-account readiness — the ONLY pre-org readiness truth (#1049 #1051).\n * `claimed` is the single variant with an `org` field: the map's ordering\n * `Account deployed+claimed → first durable Organization write` is expressed by\n * the absence of that field everywhere else, not by a guard someone can forget.\n */\nexport type Readiness =\n | { readonly at: \"unknown\" }\n | { readonly at: \"deriving\"; readonly step: AccountStep }\n | { readonly at: \"counterfactual\"; readonly address: string }\n | { readonly at: \"claiming\"; readonly address: string }\n | { readonly at: \"claimed\"; readonly address: string; readonly org: OrgLane | null }\n | {\n readonly at: \"failed\";\n readonly step: AccountStep;\n readonly failure: Failure;\n readonly retryable: boolean;\n };\n\nexport type IdentityState =\n | { readonly phase: \"signed_out\" }\n | { readonly phase: \"otp_sending\"; readonly email: string }\n | { readonly phase: \"otp_pending\"; readonly email: string; readonly requestedAt: number }\n | { readonly phase: \"otp_verifying\"; readonly email: string; readonly requestedAt: number }\n | {\n readonly phase: \"authenticated\";\n readonly session: Session;\n readonly profileComplete: boolean;\n readonly account: Readiness;\n }\n // the pre-S1 auth machine allows SignOut mid-OTP-entry, where no session exists yet.\n | { readonly phase: \"signing_out\"; readonly session: Session | null }\n | {\n readonly phase: \"faulted\";\n readonly failure: Failure;\n /** Non-null exactly when an OTP entry is resumable — the incumbent's\n * `email !== null && otpRequestedAt !== null` pair (the pre-S1 auth machine),\n * made structural. */\n readonly resume: { readonly email: string; readonly requestedAt: number } | null;\n };\n\nexport const SIGNED_OUT: IdentityState = { phase: \"signed_out\" };\n\n// ---------------------------------------------------------------------------\n// Labels — one per distinguishable position in the nest. The P3 record's\n// `from`/`to`/`state` fields, and the row key of the transition table.\n// ---------------------------------------------------------------------------\n\nexport const STATE_LABELS = [\n \"signed_out\",\n \"otp_sending\",\n \"otp_pending\",\n \"otp_verifying\",\n \"authenticated:unknown\",\n \"authenticated:deriving\",\n \"authenticated:counterfactual\",\n \"authenticated:claiming\",\n \"authenticated:failed\",\n \"authenticated:claimed\",\n \"authenticated:claimed:creating\",\n \"authenticated:claimed:loading\",\n \"authenticated:claimed:settingUp\",\n \"authenticated:claimed:ready\",\n \"authenticated:claimed:failed\",\n \"signing_out\",\n \"faulted\",\n] as const;\n\nexport type StateLabel = (typeof STATE_LABELS)[number];\n\nexport const label = (state: IdentityState): StateLabel => {\n if (state.phase !== \"authenticated\") return state.phase;\n if (state.account.at !== \"claimed\") return `authenticated:${state.account.at}`;\n const org = state.account.org;\n return org === null ? \"authenticated:claimed\" : `authenticated:claimed:${org.at}`;\n};\n\n// ---------------------------------------------------------------------------\n// Events\n// ---------------------------------------------------------------------------\n\nexport type IdentityEvent =\n // session (auth.ts, lifted 1:1 — GetSession→ReadSession, RestoreCachedSession\n // →RestoreSession, ResetAuthFlow→Reset)\n | { readonly _tag: \"RequestOtp\"; readonly email: string }\n | {\n readonly _tag: \"VerifyOtp\";\n readonly email: string;\n readonly otp: string;\n readonly now: number;\n }\n | { readonly _tag: \"ReadSession\" }\n | { readonly _tag: \"SignOut\" }\n | {\n readonly _tag: \"RestoreSession\";\n readonly session: Session;\n readonly profileComplete: boolean;\n }\n | { readonly _tag: \"ResumeOtpEntry\"; readonly now: number }\n | { readonly _tag: \"Reset\" }\n // account lane (account-lane.ts kickProvisioning / retryProvisioning + the\n // separate signer-bearing claim)\n | { readonly _tag: \"EnsureAccount\" }\n | { readonly _tag: \"ClaimAccount\" }\n | { readonly _tag: \"RetryAccount\" }\n // org lane (org-lifecycle.ts startOrResume / loadLifecycle / retry)\n | { readonly _tag: \"CreateOrganization\"; readonly draft: OrgSubmissionDraft }\n | { readonly _tag: \"AttachOrganization\"; readonly orgId: string }\n | { readonly _tag: \"RetryOrganization\" }\n | { readonly _tag: \"LeaveOrganization\" };\n\nexport type IdentityPrivateEvent =\n | { readonly _tag: \"OtpSent\"; readonly at: number }\n | { readonly _tag: \"OtpFailed\"; readonly failure: Failure }\n | {\n readonly _tag: \"Verified\";\n readonly session: Session;\n readonly profileComplete: boolean;\n }\n | { readonly _tag: \"VerifyFailed\"; readonly failure: Failure }\n | {\n readonly _tag: \"SessionRead\";\n readonly session: Session | null;\n readonly profileComplete: boolean;\n }\n | { readonly _tag: \"SessionReadFailed\"; readonly failure: Failure }\n | { readonly _tag: \"SignedOut\" }\n | { readonly _tag: \"SignOutFailed\"; readonly failure: Failure }\n | { readonly _tag: \"AccountAt\"; readonly step: AccountStep }\n | { readonly _tag: \"AccountDerived\"; readonly address: string }\n | { readonly _tag: \"AccountClaiming\" }\n | { readonly _tag: \"AccountClaimed\"; readonly address: string }\n | { readonly _tag: \"AccountFailed\"; readonly step: AccountStep; readonly failure: Failure }\n | { readonly _tag: \"OrgAt\"; readonly orgId: string; readonly step: OrgStep }\n | { readonly _tag: \"OrgReady\"; readonly orgId: string }\n | {\n readonly _tag: \"OrgFailed\";\n readonly orgId: string | null;\n readonly step: OrgStep;\n readonly failure: Failure;\n readonly retryable?: boolean;\n };\n\nexport type EventTag = IdentityEvent[\"_tag\"];\n\nexport const EVENT_TAGS = [\n \"RequestOtp\",\n \"VerifyOtp\",\n \"ReadSession\",\n \"SignOut\",\n \"RestoreSession\",\n \"ResumeOtpEntry\",\n \"Reset\",\n \"EnsureAccount\",\n \"ClaimAccount\",\n \"RetryAccount\",\n \"CreateOrganization\",\n \"AttachOrganization\",\n \"RetryOrganization\",\n \"LeaveOrganization\",\n] as const satisfies readonly EventTag[];\n\nexport type PrivateEventTag = IdentityPrivateEvent[\"_tag\"];\n\nexport const PRIVATE_EVENT_TAGS = [\n \"OtpSent\",\n \"OtpFailed\",\n \"Verified\",\n \"VerifyFailed\",\n \"SessionRead\",\n \"SessionReadFailed\",\n \"SignedOut\",\n \"SignOutFailed\",\n \"AccountAt\",\n \"AccountDerived\",\n \"AccountClaiming\",\n \"AccountClaimed\",\n \"AccountFailed\",\n \"OrgAt\",\n \"OrgReady\",\n \"OrgFailed\",\n] as const satisfies readonly PrivateEventTag[];\n\nexport type IdentityEventTag = EventTag | PrivateEventTag;\n\nexport const IDENTITY_EVENT_TAGS = [\n ...EVENT_TAGS,\n ...PRIVATE_EVENT_TAGS,\n] as const satisfies readonly IdentityEventTag[];\n\n// ---------------------------------------------------------------------------\n// The transition table, AS DATA (the pre-S1 auth machine's form, extended over the nest).\n// Only the VALID set is listed; everything absent refuses WRONG_STATE. The test\n// derives the invalid set as the complement, so the table is provably total.\n// ---------------------------------------------------------------------------\n\n/** Valid in every `authenticated:*` position — the pre-S1 auth machine's row. */\nconst SESSION_EVENTS = [\"ReadSession\", \"SignOut\", \"Reset\"] as const satisfies readonly EventTag[];\n\nexport const TRANSITION_TABLE: Record<StateLabel, readonly EventTag[]> = {\n // ---- session phases: the pre-S1 auth machine, lifted verbatim -------------------\n signed_out: [\"RequestOtp\", \"ReadSession\", \"RestoreSession\", \"Reset\"],\n otp_sending: [\"Reset\", \"SignOut\"],\n otp_pending: [\"RequestOtp\", \"VerifyOtp\", \"ReadSession\", \"SignOut\", \"Reset\"],\n otp_verifying: [\"Reset\", \"SignOut\"],\n signing_out: [\"Reset\"],\n faulted: [\"Reset\", \"RequestOtp\", \"ReadSession\", \"ResumeOtpEntry\"],\n\n // ---- the account lane, nested under `authenticated` ---------------------\n \"authenticated:unknown\": [...SESSION_EVENTS, \"EnsureAccount\"],\n \"authenticated:deriving\": [...SESSION_EVENTS],\n \"authenticated:counterfactual\": [...SESSION_EVENTS, \"ClaimAccount\"],\n \"authenticated:claiming\": [...SESSION_EVENTS],\n \"authenticated:failed\": [...SESSION_EVENTS, \"RetryAccount\"],\n\n // ---- #1049: the org lane opens HERE and nowhere else --------------------\n \"authenticated:claimed\": [...SESSION_EVENTS, \"CreateOrganization\", \"AttachOrganization\"],\n \"authenticated:claimed:creating\": [...SESSION_EVENTS],\n \"authenticated:claimed:loading\": [...SESSION_EVENTS],\n \"authenticated:claimed:settingUp\": [...SESSION_EVENTS],\n \"authenticated:claimed:ready\": [...SESSION_EVENTS, \"AttachOrganization\", \"LeaveOrganization\"],\n \"authenticated:claimed:failed\": [...SESSION_EVENTS, \"RetryOrganization\", \"LeaveOrganization\"],\n};\n\n// ---------------------------------------------------------------------------\n// Config closed over at boot (account-lane.ts's `requirement` / `hasSigner`).\n// ---------------------------------------------------------------------------\n\nexport type AccountRequirement = \"none\" | \"counterfactual\" | \"deployed\";\n\nexport interface IdentityConfig {\n readonly otpTtlMs: number;\n readonly requirement: AccountRequirement;\n /** the pre-S1 account lane — whether THIS client holds a CapxulSigner. */\n readonly hasSigner: boolean;\n}\n\nexport const DEFAULT_CONFIG: IdentityConfig = {\n otpTtlMs: 300_000, // the pre-S1 auth machine\n requirement: \"deployed\",\n hasSigner: true,\n};\n\n// ---------------------------------------------------------------------------\n// transition() — total, pure\n// ---------------------------------------------------------------------------\n\nconst authenticated = (\n session: Session,\n profileComplete: boolean,\n account: Readiness,\n): IdentityState => ({ phase: \"authenticated\", session, profileComplete, account });\n\n/** Replace the readiness lane, keeping the session. Only callable where the\n * state is already authenticated. */\nconst withAccount = (\n state: Extract<IdentityState, { phase: \"authenticated\" }>,\n account: Readiness,\n): IdentityState => authenticated(state.session, state.profileComplete, account);\n\n/** Replace the org lane. The signature is the #1049 invariant: you cannot ask\n * for an org lane without handing over a CLAIMED account. */\nconst withOrg = (\n state: Extract<IdentityState, { phase: \"authenticated\" }>,\n claimed: Extract<Readiness, { at: \"claimed\" }>,\n org: OrgLane | null,\n): IdentityState => withAccount(state, { at: \"claimed\", address: claimed.address, org });\n\n/** the pre-S1 auth machine's `failed()` — the session is dropped, the OTP entry is kept\n * only when it was actually resumable. */\nconst fault = (state: IdentityState, failure: Failure): IdentityState => ({\n phase: \"faulted\",\n failure,\n resume:\n state.phase === \"otp_pending\" || state.phase === \"otp_verifying\"\n ? { email: state.email, requestedAt: state.requestedAt }\n : null,\n});\n\nconst claimedOrg = (\n state: IdentityState,\n): {\n readonly state: Extract<IdentityState, { phase: \"authenticated\" }>;\n readonly claimed: Extract<Readiness, { at: \"claimed\" }>;\n} | null =>\n state.phase === \"authenticated\" && state.account.at === \"claimed\"\n ? { state, claimed: state.account }\n : null;\n\n// The private closed set is intentionally centralized so every completion is\n// checked against the same state authority.\n// oxlint-disable-next-line eslint/complexity\nconst privateTransition = (\n state: IdentityState,\n event: IdentityPrivateEvent,\n): Outcome<IdentityState, RefusalReason> | Refusal => {\n switch (event._tag) {\n case \"OtpSent\":\n return state.phase === \"otp_sending\"\n ? { next: { phase: \"otp_pending\", email: state.email, requestedAt: event.at } }\n : WRONG;\n case \"OtpFailed\":\n return state.phase === \"otp_sending\" ? { next: fault(state, event.failure) } : WRONG;\n case \"Verified\":\n return state.phase === \"otp_verifying\"\n ? { next: authenticated(event.session, event.profileComplete, { at: \"unknown\" }) }\n : WRONG;\n case \"VerifyFailed\":\n return state.phase === \"otp_verifying\" ? { next: fault(state, event.failure) } : WRONG;\n\n case \"SessionRead\": {\n const session = event.session;\n if (session === null) {\n // the pre-S1 auth machine — an absent wire session during OTP entry is normal.\n const midOtp =\n state.phase === \"otp_sending\" ||\n state.phase === \"otp_pending\" ||\n state.phase === \"otp_verifying\";\n return { next: midOtp ? state : SIGNED_OUT };\n }\n if (state.phase === \"authenticated\" && state.session.authUserId === session.authUserId) {\n // Identical read → return the SAME object so the shell's epoch does not\n // advance and an in-flight lane is not invalidated (auth.ts's\n // commit-policy problem, solved by identity instead of a WeakMap).\n return {\n next:\n state.profileComplete === event.profileComplete\n ? state\n : authenticated(session, event.profileComplete, state.account),\n };\n }\n return { next: authenticated(session, event.profileComplete, { at: \"unknown\" }) };\n }\n case \"SessionReadFailed\":\n return { next: fault(state, event.failure) };\n\n case \"SignedOut\":\n return state.phase === \"signing_out\" ? { next: SIGNED_OUT } : WRONG;\n case \"SignOutFailed\":\n return state.phase === \"signing_out\" ? { next: fault(state, event.failure) } : WRONG;\n\n // ---- account lane ----------------------------------------------------\n case \"AccountAt\":\n return state.phase === \"authenticated\" && state.account.at === \"deriving\"\n ? { next: withAccount(state, { at: \"deriving\", step: event.step }) }\n : WRONG;\n case \"AccountDerived\":\n return state.phase === \"authenticated\" && state.account.at === \"deriving\"\n ? { next: withAccount(state, { at: \"counterfactual\", address: event.address }) }\n : WRONG;\n case \"AccountClaiming\":\n return state.phase === \"authenticated\" && state.account.at === \"counterfactual\"\n ? { next: withAccount(state, { at: \"claiming\", address: state.account.address }) }\n : WRONG;\n case \"AccountClaimed\":\n // Valid from `claiming` (the claim landed) and from `counterfactual` (the\n // probe found it already deployed — the pre-S1 account lane's re-read).\n return state.phase === \"authenticated\" &&\n (state.account.at === \"claiming\" || state.account.at === \"counterfactual\")\n ? { next: withAccount(state, { at: \"claimed\", address: event.address, org: null }) }\n : WRONG;\n case \"AccountFailed\":\n return state.phase === \"authenticated\" &&\n (state.account.at === \"deriving\" || state.account.at === \"claiming\")\n ? {\n next: withAccount(state, {\n at: \"failed\",\n step: event.step,\n failure: event.failure,\n retryable: isRetryable(event.failure),\n }),\n }\n : WRONG;\n\n // ---- org lane (only reachable under a claimed account) ----------------\n case \"OrgAt\": {\n const held = claimedOrg(state);\n if (held === null || held.claimed.org === null) return WRONG;\n const org = held.claimed.org;\n return org.at === \"creating\" || org.at === \"loading\" || org.at === \"settingUp\"\n ? {\n next: withOrg(held.state, held.claimed, {\n at: \"settingUp\",\n orgId: event.orgId,\n step: event.step,\n }),\n }\n : WRONG;\n }\n case \"OrgReady\": {\n const held = claimedOrg(state);\n if (held === null || held.claimed.org === null) return WRONG;\n const org = held.claimed.org;\n return org.at === \"creating\" || org.at === \"settingUp\" || org.at === \"loading\"\n ? { next: withOrg(held.state, held.claimed, { at: \"ready\", orgId: event.orgId }) }\n : WRONG;\n }\n case \"OrgFailed\": {\n const held = claimedOrg(state);\n if (held === null || held.claimed.org === null) return WRONG;\n const org = held.claimed.org;\n return org.at === \"creating\" || org.at === \"loading\" || org.at === \"settingUp\"\n ? {\n next: withOrg(held.state, held.claimed, {\n at: \"failed\",\n orgId: event.orgId,\n step: event.step,\n failure: event.failure,\n retryable: event.retryable ?? isRetryable(event.failure),\n }),\n }\n : WRONG;\n }\n }\n};\n\n// The public closed set is the executable scenario table; a single reducer is\n// what makes the 17-state/14-event complement mechanically testable.\n// oxlint-disable-next-line eslint/complexity\nexport const transition = (\n state: IdentityState,\n event: IdentityEvent | IdentityPrivateEvent,\n config: IdentityConfig = DEFAULT_CONFIG,\n): Outcome<IdentityState, RefusalReason> | Refusal => {\n if (isPrivate(event)) return privateTransition(state, event);\n\n // the pre-S1 auth machine — shape validation precedes the state guard.\n if (event._tag === \"VerifyOtp\" && !/^\\d{6}$/.test(event.otp)) {\n return { refused: \"INVALID_INPUT\" };\n }\n if (event._tag === \"CreateOrganization\" && event.draft.handle.trim() === \"\") {\n return { refused: \"INVALID_INPUT\" };\n }\n if (!TRANSITION_TABLE[label(state)].includes(event._tag)) return WRONG;\n\n switch (event._tag) {\n case \"RequestOtp\":\n return { next: { phase: \"otp_sending\", email: event.email } };\n case \"VerifyOtp\": {\n if (state.phase !== \"otp_pending\" || event.email !== state.email) {\n return { refused: \"INVALID_INPUT\" };\n }\n const requestedAt = state.phase === \"otp_pending\" ? state.requestedAt : 0;\n if (event.now - requestedAt > config.otpTtlMs) return { refused: \"OTP_EXPIRED\" };\n return { next: { phase: \"otp_verifying\", email: event.email, requestedAt } };\n }\n case \"ReadSession\":\n // The SAME object on purpose (the pre-S1 auth machine's read-only session slot): a\n // refresh must not advance the epoch and kill an in-flight lane.\n return { next: state };\n case \"SignOut\":\n return {\n next: {\n phase: \"signing_out\",\n session: state.phase === \"authenticated\" ? state.session : null,\n },\n };\n case \"RestoreSession\":\n return {\n next: authenticated(event.session, event.profileComplete, { at: \"unknown\" }),\n };\n case \"ResumeOtpEntry\": {\n if (state.phase !== \"faulted\" || state.resume === null) return WRONG;\n if (event.now - state.resume.requestedAt > config.otpTtlMs) return { refused: \"OTP_EXPIRED\" };\n return {\n next: {\n phase: \"otp_pending\",\n email: state.resume.email,\n requestedAt: state.resume.requestedAt,\n },\n };\n }\n case \"Reset\":\n return { next: SIGNED_OUT };\n\n // ---- account lane ----------------------------------------------------\n case \"EnsureAccount\":\n if (config.requirement === \"none\") return WRONG; // loud, where the pre-S1 account lane was silent\n return state.phase === \"authenticated\"\n ? { next: withAccount(state, { at: \"deriving\", step: \"wallet\" }) }\n : WRONG;\n case \"ClaimAccount\": {\n if (state.phase !== \"authenticated\" || state.account.at !== \"counterfactual\") return WRONG;\n // the pre-S1 account lane — a signerless client PARKS at counterfactual;\n // the dedicated approval surface owns the claim. Refuse, do not park\n // silently.\n if (!config.hasSigner) return { refused: \"SIGNER_REJECTED\" };\n return { next: withAccount(state, { at: \"claiming\", address: state.account.address }) };\n }\n case \"RetryAccount\":\n return state.phase === \"authenticated\" &&\n state.account.at === \"failed\" &&\n state.account.retryable\n ? { next: withAccount(state, { at: \"deriving\", step: \"wallet\" }) }\n : WRONG;\n\n // ---- org lane --------------------------------------------------------\n case \"CreateOrganization\": {\n const held = claimedOrg(state);\n if (held === null || held.claimed.org !== null) return WRONG;\n const draft: OrgDraft = {\n name: event.draft.name,\n handle: event.draft.handle,\n country: event.draft.country,\n };\n return { next: withOrg(held.state, held.claimed, { at: \"creating\", draft }) };\n }\n case \"AttachOrganization\": {\n const held = claimedOrg(state);\n if (held === null) return WRONG;\n if (held.claimed.org?.at === \"ready\" && held.claimed.org.orgId === event.orgId) {\n return { next: state };\n }\n if (held.claimed.org !== null && held.claimed.org.at !== \"ready\") return WRONG;\n return { next: withOrg(held.state, held.claimed, { at: \"loading\", orgId: event.orgId }) };\n }\n case \"RetryOrganization\": {\n const held = claimedOrg(state);\n if (held === null || held.claimed.org === null) return WRONG;\n const org = held.claimed.org;\n if (org.at !== \"failed\" || !org.retryable || org.orgId === null) return WRONG;\n // org-lifecycle.ts:71-72 — retry clears durable failure and RESUMES the\n // recorded step; it never restarts the lane.\n return {\n next: withOrg(held.state, held.claimed, {\n at: \"settingUp\",\n orgId: org.orgId,\n step: org.step,\n }),\n };\n }\n case \"LeaveOrganization\": {\n const held = claimedOrg(state);\n if (held === null) return WRONG;\n return { next: withOrg(held.state, held.claimed, null) };\n }\n }\n};\n\nconst PRIVATE_TAGS: ReadonlySet<string> = new Set(PRIVATE_EVENT_TAGS);\n\nconst isPrivate = (event: IdentityEvent | IdentityPrivateEvent): event is IdentityPrivateEvent =>\n PRIVATE_TAGS.has(event._tag);\n\n// ---------------------------------------------------------------------------\n// The ONE read the UI needs — what use-wallet-provisioning.ts (235 L) becomes.\n// ---------------------------------------------------------------------------\n\nexport type Destination =\n | { readonly to: \"home\" }\n | { readonly to: \"selectUserType\" }\n | { readonly to: \"provisioning\"; readonly scope: \"personal\" }\n | { readonly to: \"provisioning\"; readonly scope: \"organization\"; readonly orgId: string | null }\n | { readonly to: \"dashboardPersonal\" }\n | { readonly to: \"dashboardOrganization\"; readonly orgId: string };\n\n/**\n * The post-auth destination and provisioning lane merge as one total switch\n * over the nest. \"An active journey outranks default\n * routing; org-list contents never choose a destination\" holds by construction:\n * there is no org list in the state, only the ONE active lane.\n */\nexport const destination = (state: IdentityState): Destination | null => {\n if (state.phase !== \"authenticated\") return { to: \"home\" };\n if (!state.profileComplete) return { to: \"selectUserType\" };\n if (state.account.at === \"unknown\") return null;\n if (state.account.at !== \"claimed\") return { to: \"provisioning\", scope: \"personal\" };\n const org = state.account.org;\n if (org === null) return { to: \"dashboardPersonal\" };\n if (org.at === \"ready\") return { to: \"dashboardOrganization\", orgId: org.orgId };\n return {\n to: \"provisioning\",\n scope: \"organization\",\n orgId: org.at === \"creating\" ? null : org.orgId,\n };\n};\n\n/** True only for the edge into `target`; no-op transitions never re-enter. */\nexport const entered = (\n previous: IdentityState,\n next: IdentityState,\n target: StateLabel,\n): boolean => label(previous) !== target && label(next) === target;\n","// Deployed test-token config for the Account/Balance domain (see\n// `packages/config/CONTEXT.md`). This domain is\n// TypeScript-only: it reuses the already-deployed `TestUSDC` (\"USDX\") token on\n// Base Sepolia rather than authoring or deploying a contract. Addresses live\n// here as plain string constants; the backend RPC helper encodes `balanceOf`\n// calldata from them.\n\n/** `TestUSDC` (\"USDX\") — Base Sepolia, 6 decimals, open `mint`. (Canon §1.) */\nexport const USDX_ADDRESS_BASE_SEPOLIA = \"0xf09fcbb6df9f8f918e58f9c8ab15a76ade862b77\";\n\n/** USDX on-chain precision. Drives the SDK-boundary `fromWei`/`toWei`. */\nexport const USDX_DECIMALS = 6;\n\n/**\n * The consumer-facing currency USDX represents. The Money surface is currency\n * USD/USDX only in v1 (canon §10); components stay currency-aware so a second\n * token (NGN) slots in later.\n */\nexport const USDX_CURRENCY = \"USD\";\n\n/**\n * ERC-20 `balanceOf(address)` 4-byte function selector\n * (`keccak256(\"balanceOf(address)\")[:4]`). Used to encode `eth_call` calldata\n * for the balance RPC pull (canon §2 — no indexer).\n */\nexport const ERC20_BALANCE_OF_SELECTOR = \"0x70a08231\";\n\n/**\n * Exact-transfer token allowlist (#536 / G2 HITL gate): the only ERC-20s the\n * `CapxulPayments` adapter may move via `send(token, …)`. v1 permits USDX on\n * Base Sepolia only. Enforced BEFORE any execute so a tainted or fuzzy token\n * address can never be transferred — the allowlist is the policy boundary, not\n * the caller's input. Lowercased for case-insensitive comparison.\n */\nexport const EXACT_TRANSFER_TOKEN_ALLOWLIST: readonly string[] = [\n USDX_ADDRESS_BASE_SEPOLIA.toLowerCase(),\n];\n\n/** True iff `tokenAddress` is on the exact-transfer allowlist (case-insensitive). */\nexport function isExactTransferTokenAllowed(tokenAddress: string): boolean {\n return EXACT_TRANSFER_TOKEN_ALLOWLIST.includes(tokenAddress.toLowerCase());\n}\n","import { concat, encodeFunctionData, encodePacked, isAddress, type Address, type Hex } from \"viem\";\n\n/** Zodiac MultiSendCallOnly module on Base Sepolia. */\nexport const MULTI_SEND_CALL_ONLY: Address = \"0x9641d764fc13c8b624c04430c7356c1c7c8102e2\";\n\n/** Zodiac Roles v2 mastercopy on Base Sepolia. */\nexport const ROLES_MASTERCOPY: Address = \"0x9646fdad06d3e24444381f44362a3b0eb343d337\";\n\n/** Zodiac ModuleProxyFactory on Base Sepolia. */\nexport const ZODIAC_MODULE_PROXY_FACTORY: Address = \"0x000000000000addb49795b0f9ba5bc298cdda236\";\n\n/** Zodiac MultiSend unwrapper on Base Sepolia. */\nexport const ZODIAC_MULTI_SEND_UNWRAPPER: Address = \"0x93b7fcbc63ed8a3a24b59e1c3e6649d50b7427c0\";\n\n/** CapxulPayments proxy on Base Sepolia. */\nexport const CAPXUL_PAYMENTS_ADDRESS: Address = \"0xe740ea65521edc9bef0ea75d30b5334711db99f4\";\n\nexport const CAPXUL_PAYMENTS_SEND_ABI = [\n {\n type: \"function\",\n name: \"send\",\n stateMutability: \"nonpayable\",\n inputs: [\n { name: \"token\", type: \"address\" },\n { name: \"recipient\", type: \"address\" },\n { name: \"amount\", type: \"uint256\" },\n { name: \"documentHash\", type: \"bytes32\" },\n { name: \"paymentType\", type: \"uint8\" },\n ],\n outputs: [],\n },\n] as const;\n\nexport const ERC20_APPROVE_ABI = [\n {\n type: \"function\",\n name: \"approve\",\n stateMutability: \"nonpayable\",\n inputs: [\n { name: \"spender\", type: \"address\" },\n { name: \"amount\", type: \"uint256\" },\n ],\n outputs: [{ name: \"\", type: \"bool\" }],\n },\n] as const;\n\nexport interface CapxulPaymentsSendCallInput {\n readonly tokenAddress: Address;\n readonly recipientAddress: Address;\n readonly amount: bigint;\n readonly documentHash?: Hex;\n readonly paymentType?: number;\n}\n\nexport interface CapxulCreateCommitmentInput {\n readonly tokenAddress: Address;\n readonly recipientAddress: Address;\n readonly totalAmount: bigint;\n readonly startTime: number;\n readonly cliffTime: number;\n readonly endTime: number;\n readonly documentHash?: Hex;\n readonly paymentType?: number;\n}\n\nexport interface CapxulPaymentsRoleSpendCallInput extends CapxulPaymentsSendCallInput {\n readonly rolesModuleAddress: Address;\n readonly roleKey: Hex;\n}\n\nexport interface EncodedOrgPaymentCall {\n readonly to: Address;\n readonly data: Hex;\n readonly value: bigint;\n}\n\nconst MULTI_SEND_CALL_ONLY_ABI = [\n {\n type: \"function\",\n name: \"multiSend\",\n stateMutability: \"payable\",\n inputs: [{ name: \"transactions\", type: \"bytes\" }],\n outputs: [],\n },\n] as const;\n\nconst ROLES_EXEC_TRANSACTION_WITH_ROLE_ABI = [\n {\n type: \"function\",\n name: \"execTransactionWithRole\",\n stateMutability: \"nonpayable\",\n inputs: [\n { name: \"to\", type: \"address\" },\n { name: \"value\", type: \"uint256\" },\n { name: \"data\", type: \"bytes\" },\n { name: \"operation\", type: \"uint8\" },\n { name: \"roleKey\", type: \"bytes32\" },\n { name: \"shouldRevert\", type: \"bool\" },\n ],\n outputs: [{ name: \"success\", type: \"bool\" }],\n },\n] as const;\n\n// Safe4337Module `executeUserOpWithErrorString(to, value, data, operation)` —\n// the single entry the module calls back into the Safe with. A personal Safe\n// batches approve+send by delegatecalling MultiSendCallOnly (operation=1).\nconst SAFE4337_EXECUTE_USEROP_ABI = [\n {\n type: \"function\",\n name: \"executeUserOpWithErrorString\",\n stateMutability: \"nonpayable\",\n inputs: [\n { name: \"to\", type: \"address\" },\n { name: \"value\", type: \"uint256\" },\n { name: \"data\", type: \"bytes\" },\n { name: \"operation\", type: \"uint8\" },\n ],\n outputs: [],\n },\n] as const;\n\nconst OPERATION_CALL = 0;\nconst OPERATION_DELEGATECALL = 1;\nconst BYTES32_RE = /^0x[0-9a-fA-F]{64}$/;\n\nfunction normalizeAddress(address: Address, field: string): Address {\n if (!isAddress(address)) {\n throw new RangeError(`${field} must be a valid EVM address`);\n }\n return address.toLowerCase() as Address;\n}\n\nfunction normalizeBytes32(value: Hex, field: string): Hex {\n if (!BYTES32_RE.test(value)) {\n throw new RangeError(`${field} must be a 32-byte 0x-prefixed hex string`);\n }\n return value.toLowerCase() as Hex;\n}\n\nfunction normalizeUint8(value: number, field: string): number {\n if (!Number.isInteger(value) || value < 0 || value > 255) {\n throw new RangeError(`${field} must be an integer between 0 and 255`);\n }\n return value;\n}\n\nfunction normalizePositiveAmount(value: bigint, field: string): bigint {\n if (value <= 0n) {\n throw new RangeError(`${field} must be positive`);\n }\n return value;\n}\n\nexport function buildCapxulPaymentsSendCalls(\n input: CapxulPaymentsSendCallInput,\n): readonly [EncodedOrgPaymentCall, EncodedOrgPaymentCall] {\n const tokenAddress = normalizeAddress(input.tokenAddress, \"tokenAddress\");\n const recipientAddress = normalizeAddress(input.recipientAddress, \"recipientAddress\");\n const amount = normalizePositiveAmount(input.amount, \"amount\");\n const documentHash = normalizeBytes32(\n input.documentHash ?? (`0x${\"0\".repeat(64)}` as Hex),\n \"documentHash\",\n );\n const paymentType = normalizeUint8(input.paymentType ?? 0, \"paymentType\");\n\n return [\n {\n to: tokenAddress,\n data: encodeFunctionData({\n abi: ERC20_APPROVE_ABI,\n functionName: \"approve\",\n args: [CAPXUL_PAYMENTS_ADDRESS, amount],\n }),\n value: 0n,\n },\n {\n to: CAPXUL_PAYMENTS_ADDRESS,\n data: encodeFunctionData({\n abi: CAPXUL_PAYMENTS_SEND_ABI,\n functionName: \"send\",\n args: [tokenAddress, recipientAddress, amount, documentHash, paymentType],\n }),\n value: 0n,\n },\n ];\n}\n\nfunction buildCapxulCreateCommitmentCalls(\n input: CapxulCreateCommitmentInput,\n): readonly [EncodedOrgPaymentCall, EncodedOrgPaymentCall] {\n const tokenAddress = normalizeAddress(input.tokenAddress, \"tokenAddress\");\n const recipientAddress = normalizeAddress(input.recipientAddress, \"recipientAddress\");\n const totalAmount = normalizePositiveAmount(input.totalAmount, \"totalAmount\");\n const startTime = normalizeUint48(input.startTime, \"startTime\");\n const cliffTime = normalizeUint48(input.cliffTime, \"cliffTime\");\n const endTime = normalizeUint48(input.endTime, \"endTime\");\n if (startTime > endTime || cliffTime < startTime || cliffTime > endTime) {\n throw new RangeError(\"commitment times must satisfy start <= cliff <= end\");\n }\n const documentHash = normalizeBytes32(\n input.documentHash ?? (`0x${\"0\".repeat(64)}` as Hex),\n \"documentHash\",\n );\n const paymentType = normalizeUint8(input.paymentType ?? 0, \"paymentType\");\n\n return [\n {\n to: tokenAddress,\n data: encodeFunctionData({\n abi: ERC20_APPROVE_ABI,\n functionName: \"approve\",\n args: [CAPXUL_PAYMENTS_ADDRESS, totalAmount],\n }),\n value: 0n,\n },\n {\n to: CAPXUL_PAYMENTS_ADDRESS,\n data: encodeFunctionData({\n abi: CAPXUL_PAYMENTS_COMMITMENT_ABI,\n functionName: \"createCommitment\",\n args: [\n tokenAddress,\n recipientAddress,\n totalAmount,\n startTime,\n cliffTime,\n endTime,\n documentHash,\n paymentType,\n ],\n }),\n value: 0n,\n },\n ];\n}\n\nexport function buildCapxulPaymentsRoleSpendCall(\n input: CapxulPaymentsRoleSpendCallInput,\n): EncodedOrgPaymentCall {\n const paymentCalls = buildCapxulPaymentsSendCalls(input);\n const roleKey = normalizeBytes32(input.roleKey, \"roleKey\");\n const multiSendData = encodeFunctionData({\n abi: MULTI_SEND_CALL_ONLY_ABI,\n functionName: \"multiSend\",\n args: [concat(paymentCalls.map(encodeMultiSendCallTransaction))],\n });\n\n return {\n to: normalizeAddress(input.rolesModuleAddress, \"rolesModuleAddress\"),\n data: encodeFunctionData({\n abi: ROLES_EXEC_TRANSACTION_WITH_ROLE_ABI,\n functionName: \"execTransactionWithRole\",\n args: [MULTI_SEND_CALL_ONLY, 0n, multiSendData, OPERATION_DELEGATECALL, roleKey, true],\n }),\n value: 0n,\n };\n}\n\n/**\n * Wrap an org Roles `execTransactionWithRole` call (from `*RoleSpendCall` /\n * `*RoleBatchSpendCall`) into the member Safe's `executeUserOpWithErrorString`\n * (operation = CALL into the Roles module) — the full Safe callData a sponsored\n * UserOp from the member's personal Safe carries (G4 · #547).\n */\nexport function buildOrgRoleSpendPersonalCallData(roleSpendCall: EncodedOrgPaymentCall): Hex {\n return encodeFunctionData({\n abi: SAFE4337_EXECUTE_USEROP_ABI,\n functionName: \"executeUserOpWithErrorString\",\n args: [\n normalizeAddress(roleSpendCall.to, \"rolesModuleAddress\"),\n 0n,\n roleSpendCall.data,\n OPERATION_CALL,\n ],\n });\n}\n\n/**\n * Wrap an ARBITRARY batch of calls into a member Safe's\n * `executeUserOpWithErrorString` via a delegatecall into MultiSendCallOnly\n * (G4 · #547 dev seam). Used by the dev MCP proof to drive the org's Zodiac\n * Roles DEPLOY (deployModule + enableModule + setUpRoles) and role GRANT\n * (assignRoles) as ONE sponsored UserOp from the founder's personal Safe —\n * the same `buildSponsoredSafeUserOp` mechanism the spend path uses. A single\n * call is still wrapped (MultiSend of length 1) so the caller need not branch.\n */\nexport function buildOrgPersonalMultiCallData(calls: readonly EncodedOrgPaymentCall[]): Hex {\n if (calls.length === 0) {\n throw new RangeError(\"multi-call batch must include at least one call\");\n }\n const multiSendData = encodeFunctionData({\n abi: MULTI_SEND_CALL_ONLY_ABI,\n functionName: \"multiSend\",\n args: [concat(calls.map(encodeMultiSendCallTransaction))],\n });\n return encodeFunctionData({\n abi: SAFE4337_EXECUTE_USEROP_ABI,\n functionName: \"executeUserOpWithErrorString\",\n args: [MULTI_SEND_CALL_ONLY, 0n, multiSendData, OPERATION_DELEGATECALL],\n });\n}\n\nexport interface CapxulPaymentsRoleBatchRun {\n readonly recipientAddress: Address;\n readonly amount: bigint;\n readonly documentHash?: Hex;\n readonly timing?: {\n readonly startTime: number;\n readonly cliffTime: number;\n readonly endTime: number;\n };\n}\n\nexport interface CapxulPaymentsRoleBatchSpendCallInput {\n readonly rolesModuleAddress: Address;\n readonly roleKey: Hex;\n readonly tokenAddress: Address;\n readonly runs: readonly CapxulPaymentsRoleBatchRun[];\n readonly paymentType?: number;\n}\n\n/**\n * Encode an org PAYROLL BATCH (G4 · #547): one `execTransactionWithRole`\n * (the member's role key) → MultiSendCallOnly → N × (approve + CapxulPayments\n * settlement call), one call per employee. Instant lines use `send`; scheduled\n * and stream salary lines use `createCommitment`. Each line keeps its own\n * recipient + amount, so each is bounded independently by the role's on-chain\n * Zodiac conditions (per-tx cap, per-day allowance, allowed recipient). One\n * sponsored UserOp settles the batch.\n */\nexport function buildCapxulPaymentsRoleBatchSpendCall(\n input: CapxulPaymentsRoleBatchSpendCallInput,\n): EncodedOrgPaymentCall {\n if (input.runs.length === 0) {\n throw new RangeError(\"payroll batch must include at least one run\");\n }\n const roleKey = normalizeBytes32(input.roleKey, \"roleKey\");\n const paymentType = input.paymentType ?? 0;\n const subCalls: EncodedOrgPaymentCall[] = input.runs.flatMap((run) => {\n if (run.timing !== undefined) {\n return [\n ...buildCapxulCreateCommitmentCalls({\n tokenAddress: input.tokenAddress,\n recipientAddress: run.recipientAddress,\n totalAmount: run.amount,\n startTime: run.timing.startTime,\n cliffTime: run.timing.cliffTime,\n endTime: run.timing.endTime,\n paymentType,\n ...(run.documentHash === undefined ? {} : { documentHash: run.documentHash }),\n }),\n ];\n }\n return [\n ...buildCapxulPaymentsSendCalls({\n tokenAddress: input.tokenAddress,\n recipientAddress: run.recipientAddress,\n amount: run.amount,\n paymentType,\n ...(run.documentHash === undefined ? {} : { documentHash: run.documentHash }),\n }),\n ];\n });\n const multiSendData = encodeFunctionData({\n abi: MULTI_SEND_CALL_ONLY_ABI,\n functionName: \"multiSend\",\n args: [concat(subCalls.map(encodeMultiSendCallTransaction))],\n });\n return {\n to: normalizeAddress(input.rolesModuleAddress, \"rolesModuleAddress\"),\n data: encodeFunctionData({\n abi: ROLES_EXEC_TRANSACTION_WITH_ROLE_ABI,\n functionName: \"execTransactionWithRole\",\n args: [MULTI_SEND_CALL_ONLY, 0n, multiSendData, OPERATION_DELEGATECALL, roleKey, true],\n }),\n value: 0n,\n };\n}\n\nfunction encodeMultiSendCallTransaction(call: EncodedOrgPaymentCall): Hex {\n return encodePacked(\n [\"uint8\", \"address\", \"uint256\", \"uint256\", \"bytes\"],\n [OPERATION_CALL, call.to, call.value, BigInt((call.data.length - 2) / 2), call.data],\n );\n}\n\n/**\n * Encode a personal Safe's `executeUserOpWithErrorString` callData that pays via\n * CapxulPayments in one UserOp: approve + send batched through a delegatecall\n * into MultiSendCallOnly. The Safe4337Module invokes this on the Safe; the\n * MultiSend then CALLs each sub-transaction from the Safe's own context.\n */\nexport function buildCapxulPaymentsPersonalSendCallData(input: CapxulPaymentsSendCallInput): Hex {\n const calls = buildCapxulPaymentsSendCalls(input);\n const multiSendData = encodeFunctionData({\n abi: MULTI_SEND_CALL_ONLY_ABI,\n functionName: \"multiSend\",\n args: [concat(calls.map(encodeMultiSendCallTransaction))],\n });\n return encodeFunctionData({\n abi: SAFE4337_EXECUTE_USEROP_ABI,\n functionName: \"executeUserOpWithErrorString\",\n args: [MULTI_SEND_CALL_ONLY, 0n, multiSendData, OPERATION_DELEGATECALL],\n });\n}\n\n// ── Commitments (G3 · #546) — CapxulPayments escrow-vest-claim ───────────────\n// The alpha Commitment engine is the deployed CapxulPayments contract\n// (commitment-engine-source.md). Times are uint48 epoch SECONDS. release maps:\n// scheduled → startTime == cliffTime == endTime == at\n// stream → linear [startTime, endTime], optional cliffTime\n\nexport const CAPXUL_PAYMENTS_COMMITMENT_ABI = [\n {\n type: \"function\",\n name: \"createCommitment\",\n stateMutability: \"nonpayable\",\n inputs: [\n { name: \"token\", type: \"address\" },\n { name: \"recipient\", type: \"address\" },\n { name: \"totalAmount\", type: \"uint256\" },\n { name: \"startTime\", type: \"uint48\" },\n { name: \"cliffTime\", type: \"uint48\" },\n { name: \"endTime\", type: \"uint48\" },\n { name: \"documentHash\", type: \"bytes32\" },\n { name: \"paymentType\", type: \"uint8\" },\n ],\n outputs: [{ name: \"commitmentId\", type: \"uint256\" }],\n },\n {\n type: \"function\",\n name: \"claim\",\n stateMutability: \"nonpayable\",\n inputs: [{ name: \"commitmentId\", type: \"uint256\" }],\n outputs: [],\n },\n {\n type: \"function\",\n name: \"cancel\",\n stateMutability: \"nonpayable\",\n inputs: [\n { name: \"commitmentId\", type: \"uint256\" },\n { name: \"documentHash\", type: \"bytes32\" },\n ],\n outputs: [],\n },\n {\n type: \"function\",\n name: \"redirect\",\n stateMutability: \"nonpayable\",\n inputs: [\n { name: \"commitmentId\", type: \"uint256\" },\n { name: \"newRecipient\", type: \"address\" },\n { name: \"newDocumentHash\", type: \"bytes32\" },\n ],\n outputs: [],\n },\n {\n type: \"function\",\n name: \"claimableAmount\",\n stateMutability: \"view\",\n inputs: [{ name: \"commitmentId\", type: \"uint256\" }],\n outputs: [{ name: \"\", type: \"uint256\" }],\n },\n // Public `commitments(uint256)` mapping getter — returns the full Commitment\n // struct. Used to bind lifecycle evidence to the on-chain STATE after a\n // claim/cancel/redirect op (G3 #546 — actions must not trust sender+success\n // alone). Mirrors the `Commitment` struct field order in CapxulPayments.sol.\n {\n type: \"function\",\n name: \"commitments\",\n stateMutability: \"view\",\n inputs: [{ name: \"\", type: \"uint256\" }],\n outputs: [\n { name: \"creator\", type: \"address\" },\n { name: \"token\", type: \"address\" },\n { name: \"recipient\", type: \"address\" },\n { name: \"totalAmount\", type: \"uint256\" },\n { name: \"claimed\", type: \"uint256\" },\n { name: \"startTime\", type: \"uint48\" },\n { name: \"cliffTime\", type: \"uint48\" },\n { name: \"endTime\", type: \"uint48\" },\n { name: \"documentHash\", type: \"bytes32\" },\n { name: \"paymentType\", type: \"uint8\" },\n { name: \"cancelled\", type: \"bool\" },\n ],\n },\n] as const;\n\nfunction normalizeUint48(value: number, field: string): number {\n if (!Number.isInteger(value) || value < 0 || value > 0xffff_ffff_ffff) {\n throw new RangeError(`${field} must be a uint48 (epoch seconds)`);\n }\n return value;\n}\n\n/**\n * Encode a personal Safe's `createCommitment` UserOp: approve + createCommitment\n * batched through a delegatecall into MultiSendCallOnly (one sponsored UserOp).\n * The creator (payer Safe) escrows `totalAmount` into CapxulPayments.\n */\nexport function buildCapxulCreateCommitmentPersonalCallData(\n input: CapxulCreateCommitmentInput,\n): Hex {\n const tokenAddress = normalizeAddress(input.tokenAddress, \"tokenAddress\");\n const recipientAddress = normalizeAddress(input.recipientAddress, \"recipientAddress\");\n const totalAmount = normalizePositiveAmount(input.totalAmount, \"totalAmount\");\n const startTime = normalizeUint48(input.startTime, \"startTime\");\n const cliffTime = normalizeUint48(input.cliffTime, \"cliffTime\");\n const endTime = normalizeUint48(input.endTime, \"endTime\");\n if (startTime > endTime || cliffTime < startTime || cliffTime > endTime) {\n throw new RangeError(\"commitment times must satisfy start <= cliff <= end\");\n }\n const documentHash = normalizeBytes32(\n input.documentHash ?? (`0x${\"0\".repeat(64)}` as Hex),\n \"documentHash\",\n );\n const paymentType = normalizeUint8(input.paymentType ?? 0, \"paymentType\");\n\n const approveCall: EncodedOrgPaymentCall = {\n to: tokenAddress,\n data: encodeFunctionData({\n abi: ERC20_APPROVE_ABI,\n functionName: \"approve\",\n args: [CAPXUL_PAYMENTS_ADDRESS, totalAmount],\n }),\n value: 0n,\n };\n const createCall: EncodedOrgPaymentCall = {\n to: CAPXUL_PAYMENTS_ADDRESS,\n data: encodeFunctionData({\n abi: CAPXUL_PAYMENTS_COMMITMENT_ABI,\n functionName: \"createCommitment\",\n args: [\n tokenAddress,\n recipientAddress,\n totalAmount,\n startTime,\n cliffTime,\n endTime,\n documentHash,\n paymentType,\n ],\n }),\n value: 0n,\n };\n const multiSendData = encodeFunctionData({\n abi: MULTI_SEND_CALL_ONLY_ABI,\n functionName: \"multiSend\",\n args: [concat([approveCall, createCall].map(encodeMultiSendCallTransaction))],\n });\n return encodeFunctionData({\n abi: SAFE4337_EXECUTE_USEROP_ABI,\n functionName: \"executeUserOpWithErrorString\",\n args: [MULTI_SEND_CALL_ONLY, 0n, multiSendData, OPERATION_DELEGATECALL],\n });\n}\n\nfunction buildSingleCapxulPaymentsCallData(data: Hex): Hex {\n return encodeFunctionData({\n abi: SAFE4337_EXECUTE_USEROP_ABI,\n functionName: \"executeUserOpWithErrorString\",\n args: [CAPXUL_PAYMENTS_ADDRESS, 0n, data, OPERATION_CALL],\n });\n}\n\n/** Encode a recipient Safe's `claim(commitmentId)` UserOp callData. */\nexport function buildCapxulCommitmentClaimCallData(commitmentId: bigint): Hex {\n return buildSingleCapxulPaymentsCallData(\n encodeFunctionData({\n abi: CAPXUL_PAYMENTS_COMMITMENT_ABI,\n functionName: \"claim\",\n args: [commitmentId],\n }),\n );\n}\n\n/** Encode a creator Safe's `cancel(commitmentId, documentHash)` UserOp callData. */\nexport function buildCapxulCommitmentCancelCallData(commitmentId: bigint, documentHash?: Hex): Hex {\n return buildSingleCapxulPaymentsCallData(\n encodeFunctionData({\n abi: CAPXUL_PAYMENTS_COMMITMENT_ABI,\n functionName: \"cancel\",\n args: [\n commitmentId,\n normalizeBytes32(documentHash ?? (`0x${\"0\".repeat(64)}` as Hex), \"documentHash\"),\n ],\n }),\n );\n}\n\n/** Encode a creator Safe's `redirect(commitmentId, newRecipient, newDocumentHash)` UserOp callData. */\nexport function buildCapxulCommitmentRedirectCallData(\n commitmentId: bigint,\n newRecipient: Address,\n newDocumentHash?: Hex,\n): Hex {\n return buildSingleCapxulPaymentsCallData(\n encodeFunctionData({\n abi: CAPXUL_PAYMENTS_COMMITMENT_ABI,\n functionName: \"redirect\",\n args: [\n commitmentId,\n normalizeAddress(newRecipient, \"newRecipient\"),\n normalizeBytes32(newDocumentHash ?? (`0x${\"0\".repeat(64)}` as Hex), \"newDocumentHash\"),\n ],\n }),\n );\n}\n","import {\n concat,\n encodeAbiParameters,\n encodeFunctionData,\n encodePacked,\n getContractAddress,\n hashTypedData,\n keccak256,\n pad,\n toBytes,\n toHex,\n type Hex,\n} from \"viem\";\n\nimport { Errors } from \"@capxul/errors\";\nimport { MULTI_SEND_CALL_ONLY } from \"./org-payments.ts\";\n\nexport const BASE_SEPOLIA_CHAIN_ID = 84532;\n\nexport const SAFE_PROXY_FACTORY = \"0x4e1DCf7AD4e460CfD30791CCC4F9c8a4f820ec67\";\nexport const SAFE_L2_SINGLETON = \"0x29fcB43b46531BcA003ddC8FCB67FFE91900C762\";\nexport const SAFE_MODULE_SETUP = \"0x2dd68b007B46fBe91B9A7c3EDa5A7a1063cB5b47\";\nexport const SAFE_4337_MODULE = \"0x75cf11467937ce3F2f357CE24ffc3DBF8fD5c226\";\nexport const MULTI_SEND = \"0x38869bf66a61cF6bDB996A6aE40D5853Fd43B526\";\n\n/**\n * Canonical personal-Safe salt namespace — **v2** (PRD #462). v2 derives the\n * address from the email ONLY: the initializer's sole owner is the fixed\n * `CAPXUL_BOOTSTRAP_OWNER`, so the address exists before any user signer does\n * and can never rotate with one. The user's signer is installed at claim time\n * via `swapOwner` (see `capxulClaimOwnerCallData`).\n */\nexport const CAPXUL_SAFE_SALT_NAMESPACE = \"capxul:safe:email:v2\";\n\n/**\n * Retired v1 personal-Safe namespace (signer-in-derivation). Kept ONLY as the\n * pin for pre-v2 on-chain artifacts that must not move — today that is the\n * backend faucet Safe (`testUsdcMint.ts`), which stays owner=deployer,\n * namespace=v1 so its deployed address is unchanged. Never use for new lanes.\n */\nexport const CAPXUL_SAFE_SALT_NAMESPACE_V1 = \"capxul:safe:email:v1\";\n\n/**\n * The Capxul bootstrap owner — the sole `setup()` owner of every unclaimed\n * personal Safe under derivation v2. This address is part of the CREATE2\n * preimage of EVERY personal Safe address: treat it exactly like\n * `SAFE_PROXY_FACTORY` (changing it is a derivation-version event → v3).\n * The private key lives backend-only (`CAPXUL_BOOTSTRAP_OWNER_PRIVATE_KEY`)\n * and signs exactly one kind of operation: the claim userOp that deploys the\n * Safe and swaps this owner out for the user's signer (PRD #462). The earlier\n * ClaimGuard derivation-v3 placeholder (#461) is closed; future mainnet-scale\n * hardening should be filed against the current payments/claim architecture.\n */\nexport const CAPXUL_BOOTSTRAP_OWNER = \"0x425fca96f4a3e18fb80974e38096b5da460f2704\";\n\n/** Safe `OwnerManager` sentinel — `prevOwner` for the single-owner swap. */\nexport const SAFE_SENTINEL_OWNERS = \"0x0000000000000000000000000000000000000001\";\n\nconst UINT48_MAX = 281_474_976_710_655;\n\n// Captured 2026-05-17 via `eth_call SafeProxyFactory.proxyCreationCode()`\n// against Base mainnet (chainId 8453). Identical bytecode across every chain\n// the factory is deployed to because the factory is itself deterministically\n// deployed via CREATE2. 486 bytes / 972 hex chars after the `0x` prefix.\n//\n// Used by `deriveCapxulSafeAddress` below; previously duplicated in\n// `packages/backend/convex/_shared/counterfactual.ts:PROXY_CREATION_CODE`.\n// Both sites pin the same hex literal — keep them in sync if Safe ever\n// migrates the factory bytecode (no such migration through v1.4.1).\nexport const SAFE_PROXY_CREATION_CODE: Hex =\n \"0x608060405234801561001057600080fd5b506040516101e63803806101e68339818101604052602081101561003357600080fd5b8101908080519060200190929190505050600073ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff1614156100ca576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004018080602001828103825260228152602001806101c46022913960400191505060405180910390fd5b806000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055505060ab806101196000396000f3fe608060405273ffffffffffffffffffffffffffffffffffffffff600054167fa619486e0000000000000000000000000000000000000000000000000000000060003514156050578060005260206000f35b3660008037600080366000845af43d6000803e60008114156070573d6000fd5b3d6000f3fea264697066735822122003d1488ee65e08fa41e58e888a9865554c535f2c77126a82cb4c0f917f31441364736f6c63430007060033496e76616c69642073696e676c65746f6e20616464726573732070726f7669646564\";\n\n/**\n * Normalize an email for use as a Capxul Safe salt input.\n *\n * Trims surrounding whitespace and lowercases the address so that\n * `\" User+Demo@Example.COM \"` and `\"user+demo@example.com\"` derive\n * the same `safeAddress`. This is the canonical normalization rule —\n * any future change here would shift every existing user's Safe\n * address, so the rule is pinned by the fixture matrix in\n * `packages/config/tests/safe-address-conformance.test.ts`.\n *\n * @param email - The raw email address to normalize\n * @returns The trimmed, lowercased email\n */\nexport function normalizeSafeSaltEmail(email: string): string {\n return email.trim().toLowerCase();\n}\n\n/**\n * Compute the deterministic Safe salt nonce for a `(namespace, email)`\n * pair. The salt nonce is the `bigint` reading of\n * `keccak256(namespace + \":\" + normalizeSafeSaltEmail(email))`.\n *\n * Namespace defaults to `CAPXUL_SAFE_SALT_NAMESPACE`\n * (`\"capxul:safe:email:v2\"`) — the per-version Capxul scheme. Pass a\n * different namespace only for pinned pre-v2 artifacts\n * (`CAPXUL_SAFE_SALT_NAMESPACE_V1`, faucet Safe) or when bumping the scheme.\n *\n * @param input.email - The email to derive the salt nonce from\n * @param input.namespace - Optional namespace override (defaults to `CAPXUL_SAFE_SALT_NAMESPACE`)\n * @returns The Capxul-namespaced salt nonce as a `bigint`\n */\nexport function computeCapxulSafeSaltNonce(input: {\n readonly email: string;\n readonly namespace?: string;\n}): bigint {\n const namespace = input.namespace ?? CAPXUL_SAFE_SALT_NAMESPACE;\n const normalizedEmail = normalizeSafeSaltEmail(input.email);\n return BigInt(keccak256(toBytes(`${namespace}:${normalizedEmail}`)));\n}\n\n// --- Safe v1.4.1 + 4337 module address derivation -----------------------------\n\nconst ZERO_ADDRESS: Hex = \"0x0000000000000000000000000000000000000000\";\n\nconst safeSetupAbi = [\n {\n type: \"function\",\n name: \"setup\",\n stateMutability: \"nonpayable\",\n inputs: [\n { name: \"_owners\", type: \"address[]\" },\n { name: \"_threshold\", type: \"uint256\" },\n { name: \"to\", type: \"address\" },\n { name: \"data\", type: \"bytes\" },\n { name: \"fallbackHandler\", type: \"address\" },\n { name: \"paymentToken\", type: \"address\" },\n { name: \"payment\", type: \"uint256\" },\n { name: \"paymentReceiver\", type: \"address\" },\n ],\n outputs: [],\n },\n] as const;\n\nconst enableModulesAbi = [\n {\n type: \"function\",\n name: \"enableModules\",\n stateMutability: \"nonpayable\",\n inputs: [{ name: \"modules\", type: \"address[]\" }],\n outputs: [],\n },\n] as const;\n\nconst multiSendAbi = [\n {\n type: \"function\",\n name: \"multiSend\",\n stateMutability: \"payable\",\n inputs: [{ name: \"transactions\", type: \"bytes\" }],\n outputs: [],\n },\n] as const;\n\nconst safeProxyFactoryAbi = [\n {\n type: \"function\",\n name: \"createProxyWithNonce\",\n stateMutability: \"nonpayable\",\n inputs: [\n { name: \"_singleton\", type: \"address\" },\n { name: \"initializer\", type: \"bytes\" },\n { name: \"saltNonce\", type: \"uint256\" },\n ],\n outputs: [{ name: \"proxy\", type: \"address\" }],\n },\n] as const;\n\nconst safeExecTransactionAbi = [\n {\n type: \"function\",\n name: \"execTransaction\",\n stateMutability: \"payable\",\n inputs: [\n { name: \"to\", type: \"address\" },\n { name: \"value\", type: \"uint256\" },\n { name: \"data\", type: \"bytes\" },\n { name: \"operation\", type: \"uint8\" },\n { name: \"safeTxGas\", type: \"uint256\" },\n { name: \"baseGas\", type: \"uint256\" },\n { name: \"gasPrice\", type: \"uint256\" },\n { name: \"gasToken\", type: \"address\" },\n { name: \"refundReceiver\", type: \"address\" },\n { name: \"signatures\", type: \"bytes\" },\n ],\n outputs: [{ name: \"success\", type: \"bool\" }],\n },\n] as const;\n\nexport interface SafeTransactionCall {\n readonly to: Hex;\n readonly value: bigint;\n readonly data: Hex;\n}\n\n/**\n * Encode ordered calls as one Safe `execTransaction` through MultiSend.\n *\n * The owner must approve the surrounding transaction, so this builder uses\n * Safe's prevalidated-signature format and delegates the ordered calls through\n * the canonical MultiSend contract.\n */\nexport function buildSafeMultiSendExecTransactionCall(input: {\n readonly safeAddress: Hex;\n readonly ownerAddress: Hex;\n readonly calls: readonly SafeTransactionCall[];\n}): SafeTransactionCall {\n const transactions = concat(input.calls.map(encodeSafeMultiSendCallTransaction));\n const multiSendData = encodeFunctionData({\n abi: multiSendAbi,\n functionName: \"multiSend\",\n args: [transactions],\n });\n\n return {\n to: input.safeAddress,\n value: 0n,\n data: encodeFunctionData({\n abi: safeExecTransactionAbi,\n functionName: \"execTransaction\",\n args: [\n MULTI_SEND,\n 0n,\n multiSendData,\n 1,\n 0n,\n 0n,\n 0n,\n ZERO_ADDRESS,\n ZERO_ADDRESS,\n `${pad(input.ownerAddress, { size: 32 })}${\"0\".repeat(64)}01`,\n ],\n }),\n };\n}\n\nfunction encodeSafeMultiSendCallTransaction(call: SafeTransactionCall): Hex {\n return encodePacked(\n [\"uint8\", \"address\", \"uint256\", \"uint256\", \"bytes\"],\n [0, call.to, call.value, BigInt((call.data.length - 2) / 2), call.data],\n );\n}\n\n// Shared Safe `setup` initializer used by both `deriveCapxulSafeAddressForOwner`\n// (the CREATE2 address) and `safeDeploymentFactoryArgsForOwner` (the\n// `createProxyWithNonce` factory calldata). A single builder guarantees the\n// derived address and the factory data can never drift apart. Under\n// derivation v2 the sole owner is `CAPXUL_BOOTSTRAP_OWNER` for every personal\n// Safe; the faucet lane passes the deployer EOA (v1 pin).\nfunction buildCapxulSafeInitializer(owner: Hex): Hex {\n const enableModulesCall = encodeFunctionData({\n abi: enableModulesAbi,\n functionName: \"enableModules\",\n args: [[SAFE_4337_MODULE]],\n });\n\n // MultiSend payload per `permissionless/accounts/safe/encodeInternalTransaction`:\n // uint8 operation || address to || uint256 value || uint256 dataLen || bytes data\n // operation=1 (delegatecall) into SafeModuleSetup with the enableModules call.\n const enableModulesByteLen = BigInt((enableModulesCall.length - 2) / 2);\n const multiSendPayload: Hex = encodePacked(\n [\"uint8\", \"address\", \"uint256\", \"uint256\", \"bytes\"],\n [1, SAFE_MODULE_SETUP, 0n, enableModulesByteLen, enableModulesCall],\n );\n\n const setupData = encodeFunctionData({\n abi: multiSendAbi,\n functionName: \"multiSend\",\n args: [multiSendPayload],\n });\n\n return encodeFunctionData({\n abi: safeSetupAbi,\n functionName: \"setup\",\n args: [[owner], 1n, MULTI_SEND, setupData, SAFE_4337_MODULE, ZERO_ADDRESS, 0n, ZERO_ADDRESS],\n });\n}\n\nconst ADDRESS_REGEX = /^0x[0-9a-fA-F]{40}$/;\n\nfunction validateAndNormalizeAddress(field: string, value: string): Hex {\n const address = value.toLowerCase();\n if (!ADDRESS_REGEX.test(address)) {\n throw Errors.invalidInput(field, `must be 0x + 40 hex chars, got ${value}`);\n }\n return address as Hex;\n}\n\n/**\n * Pure derivation of the Capxul personal Safe address — **v2: email only**\n * (PRD #462). The Safe v1.4.1 (SafeL2) + 4337-module initializer's sole owner\n * is the fixed `CAPXUL_BOOTSTRAP_OWNER`, so the address is a pure function of\n * the (normalized) email and exists before any user signer does. The user's\n * signer is installed at claim time via `swapOwner` — signer rotation can\n * never move the address (org-domain rule D7, now system-wide).\n *\n * Returns the lowercased `0x` + 40 hex string (raw — no brand applied so this\n * function is callable from both `@capxul/config` consumers that don't have\n * `@capxul/types` available, and from packages that re-brand at their own\n * boundary).\n *\n * Algorithm: exactly mirrors `permissionless.toSafeSmartAccount({ version:\n * \"1.4.1\", safeSingletonAddress: SAFE_L2_SINGLETON, owners: [BOOTSTRAP] })`\n * + the Capxul-canonical module setup (delegatecall into\n * `SafeModuleSetup.enableModules([SAFE_4337_MODULE])` via the MultiSend lane\n * during proxy setup). The proxy creation code is pinned at\n * `SAFE_PROXY_CREATION_CODE`; the salt is Capxul-namespaced (v2) via\n * `computeCapxulSafeSaltNonce({ email })`.\n *\n * Canonical: SDK deployment adapters and\n * `packages/backend/convex/smartAccount/mutations.ts:provision` import this\n * function; the conformance test at\n * `packages/config/tests/safe-address-conformance.test.ts` pins the matrix.\n */\nexport function deriveCapxulSafeAddress(input: { readonly email: string }): string {\n return deriveCapxulSafeAddressForOwner({\n ownerAddress: CAPXUL_BOOTSTRAP_OWNER,\n email: input.email,\n });\n}\n\n/**\n * Owner-parametrized derivation core. Two callers only:\n * 1. `deriveCapxulSafeAddress` (canonical v2: owner = bootstrap, namespace v2);\n * 2. the backend faucet Safe (`testUsdcMint.ts`: owner = deployer EOA,\n * namespace pinned to `CAPXUL_SAFE_SALT_NAMESPACE_V1` so its deployed\n * address never moves).\n * Do NOT introduce new owner-parametrized lanes — per-user owners in the\n * derivation is exactly the v1 mistake v2 removes.\n */\nexport function deriveCapxulSafeAddressForOwner(input: {\n readonly ownerAddress: string;\n readonly email: string;\n readonly namespace?: string;\n}): string {\n const owner = validateAndNormalizeAddress(\"ownerAddress\", input.ownerAddress);\n const initializer = buildCapxulSafeInitializer(owner);\n\n const saltNonce = computeCapxulSafeSaltNonce(\n input.namespace === undefined\n ? { email: input.email }\n : { email: input.email, namespace: input.namespace },\n );\n const salt = keccak256(encodePacked([\"bytes32\", \"uint256\"], [keccak256(initializer), saltNonce]));\n\n const deploymentCode = concat([\n SAFE_PROXY_CREATION_CODE,\n encodeAbiParameters([{ type: \"uint256\" }], [BigInt(SAFE_L2_SINGLETON)]),\n ]);\n\n const address = getContractAddress({\n opcode: \"CREATE2\",\n from: SAFE_PROXY_FACTORY as Hex,\n salt,\n bytecodeHash: keccak256(deploymentCode),\n });\n\n return address.toLowerCase();\n}\n\n/** Factory address + `createProxyWithNonce` calldata for the deployment UserOp. */\nexport interface SafeDeploymentFactoryArgs {\n readonly factory: Hex;\n readonly factoryData: Hex;\n readonly safeAddress: string;\n}\n\n/**\n * Build the EntryPoint v0.7 `factory` + `factoryData` for deploying the Capxul\n * personal Safe for an email (derivation v2: owner = `CAPXUL_BOOTSTRAP_OWNER`).\n * `factoryData` is the\n * `SafeProxyFactory.createProxyWithNonce(singleton, initializer, saltNonce)`\n * calldata; the backend claim lane packs these into the UserOp `initCode`.\n * Byte-for-byte equal to permissionless's\n * `toSafeSmartAccount(...).getFactoryArgs()` — pinned in\n * `packages/sdk/src/__tests__/safe4337-split-sign.test.ts`.\n */\nexport function safeDeploymentFactoryArgs(input: {\n readonly email: string;\n}): SafeDeploymentFactoryArgs {\n return safeDeploymentFactoryArgsForOwner({\n ownerAddress: CAPXUL_BOOTSTRAP_OWNER,\n email: input.email,\n });\n}\n\n/** Owner-parametrized factory args — same two-caller rule as `deriveCapxulSafeAddressForOwner`. */\nexport function safeDeploymentFactoryArgsForOwner(input: {\n readonly ownerAddress: string;\n readonly email: string;\n readonly namespace?: string;\n}): SafeDeploymentFactoryArgs {\n const owner = validateAndNormalizeAddress(\"ownerAddress\", input.ownerAddress);\n const initializer = buildCapxulSafeInitializer(owner);\n const saltNonce = computeCapxulSafeSaltNonce(\n input.namespace === undefined\n ? { email: input.email }\n : { email: input.email, namespace: input.namespace },\n );\n const factoryData = encodeFunctionData({\n abi: safeProxyFactoryAbi,\n functionName: \"createProxyWithNonce\",\n args: [SAFE_L2_SINGLETON as Hex, initializer, saltNonce],\n });\n return {\n factory: SAFE_PROXY_FACTORY as Hex,\n factoryData,\n safeAddress: deriveCapxulSafeAddressForOwner(input),\n };\n}\n\n// --- Claim (PRD #462) ---------------------------------------------------------\n//\n// Claiming a personal Safe = the ONE sponsored userOp that (a) deploys the\n// proxy via `safeDeploymentFactoryArgs` initCode when undeployed and (b) swaps\n// the bootstrap owner for the user's signer. The swap executes FROM the Safe\n// on itself through the Safe4337Module's `executeUserOpWithErrorString`\n// (wrap this calldata with `safe4337ExecuteUserOpCallData({ to: safeAddress,\n// data })`). The SafeOp digest is signed server-side by the bootstrap key —\n// the user signs nothing at claim.\n\nconst ownerManagerSwapOwnerAbi = [\n {\n type: \"function\",\n name: \"swapOwner\",\n stateMutability: \"nonpayable\",\n inputs: [\n { name: \"prevOwner\", type: \"address\" },\n { name: \"oldOwner\", type: \"address\" },\n { name: \"newOwner\", type: \"address\" },\n ],\n outputs: [],\n },\n] as const;\n\n/**\n * Encode the `OwnerManager.swapOwner` calldata that installs the user's signer\n * as the Safe's sole owner at claim. Single-owner Safe ⇒ `prevOwner` is the\n * `SAFE_SENTINEL_OWNERS` sentinel and `oldOwner` is `CAPXUL_BOOTSTRAP_OWNER`.\n */\nexport function capxulClaimOwnerCallData(input: { readonly newOwner: string }): Hex {\n const newOwner = validateAndNormalizeAddress(\"newOwner\", input.newOwner);\n if (newOwner === CAPXUL_BOOTSTRAP_OWNER) {\n throw Errors.invalidInput(\"newOwner\", \"must not be the bootstrap owner\");\n }\n if (newOwner === SAFE_SENTINEL_OWNERS || BigInt(newOwner) === 0n) {\n throw Errors.invalidInput(\"newOwner\", \"must not be the sentinel or zero address\");\n }\n return encodeFunctionData({\n abi: ownerManagerSwapOwnerAbi,\n functionName: \"swapOwner\",\n args: [SAFE_SENTINEL_OWNERS as Hex, CAPXUL_BOOTSTRAP_OWNER as Hex, newOwner],\n });\n}\n\n// --- Safe 4337 split-signing (backend builds + sponsors; client signs) --------\n//\n// The Safe4337Module validates the owner's signature over an EIP-712 `SafeOp`\n// typed-data digest — NOT the EntryPoint userOpHash. In the backend-orchestrated\n// deploy (backend-orchestrated-deploy.md) the backend builds + gas-fills +\n// paymaster-sponsors the deployment UserOperation and computes this digest; the\n// consumer's `CapxulSigner` signs it; the backend packs\n// `validAfter|validUntil|signature` and submits. These helpers MUST mirror\n// permissionless's `signUserOperation` byte-for-byte — verified hermetically in\n// `packages/sdk/src/__tests__/safe4337-split-sign.test.ts`.\n\n/** Canonical ERC-4337 EntryPoint v0.7 address (same on every chain). */\nexport const ENTRY_POINT_07_ADDRESS = \"0x0000000071727De22E5E9d8BAf0edAc6f37da032\";\n\n/** EIP-712 `SafeOp` typed-data fields for EntryPoint v0.7 (Safe4337Module). */\nexport const EIP712_SAFE_OPERATION_TYPE_V07 = {\n SafeOp: [\n { type: \"address\", name: \"safe\" },\n { type: \"uint256\", name: \"nonce\" },\n { type: \"bytes\", name: \"initCode\" },\n { type: \"bytes\", name: \"callData\" },\n { type: \"uint128\", name: \"verificationGasLimit\" },\n { type: \"uint128\", name: \"callGasLimit\" },\n { type: \"uint256\", name: \"preVerificationGas\" },\n { type: \"uint128\", name: \"maxPriorityFeePerGas\" },\n { type: \"uint128\", name: \"maxFeePerGas\" },\n { type: \"bytes\", name: \"paymasterAndData\" },\n { type: \"uint48\", name: \"validAfter\" },\n { type: \"uint48\", name: \"validUntil\" },\n { type: \"address\", name: \"entryPoint\" },\n ],\n} as const;\n\n/** Prepared (gas + paymaster filled, unsigned) EntryPoint v0.7 UserOperation. */\nexport interface Safe4337PreparedUserOp {\n readonly sender: Hex;\n readonly nonce: bigint;\n readonly factory?: Hex | undefined;\n readonly factoryData?: Hex | undefined;\n readonly callData: Hex;\n readonly callGasLimit: bigint;\n readonly verificationGasLimit: bigint;\n readonly preVerificationGas: bigint;\n readonly maxFeePerGas: bigint;\n readonly maxPriorityFeePerGas: bigint;\n readonly paymaster?: Hex | undefined;\n readonly paymasterVerificationGasLimit?: bigint | undefined;\n readonly paymasterPostOpGasLimit?: bigint | undefined;\n readonly paymasterData?: Hex | undefined;\n}\n\n/** Pack EntryPoint v0.7 `factory` + `factoryData` into the SafeOp `initCode`. */\nexport function safe4337InitCode(userOp: Safe4337PreparedUserOp): Hex {\n if (userOp.factory === undefined || userOp.factory === \"0x\") return \"0x\";\n return concat([userOp.factory, userOp.factoryData ?? \"0x\"]);\n}\n\n/** Pack EntryPoint v0.7 unpacked paymaster fields into SafeOp `paymasterAndData`. */\nexport function safe4337PaymasterAndData(userOp: Safe4337PreparedUserOp): Hex {\n if (userOp.paymaster === undefined || userOp.paymaster === \"0x\") return \"0x\";\n return concat([\n userOp.paymaster,\n pad(toHex(userOp.paymasterVerificationGasLimit ?? 0n), { size: 16 }),\n pad(toHex(userOp.paymasterPostOpGasLimit ?? 0n), { size: 16 }),\n userOp.paymasterData ?? \"0x\",\n ]);\n}\n\n/**\n * Compute the EIP-712 `SafeOp` digest the Safe4337Module owner must sign for a\n * prepared deployment UserOperation. The `CapxulSigner` signs THIS digest.\n */\nexport function safe4337SafeOpDigest(input: {\n readonly userOp: Safe4337PreparedUserOp;\n readonly chainId: number;\n readonly validAfter?: number;\n readonly validUntil?: number;\n readonly safe4337ModuleAddress?: Hex;\n readonly entryPointAddress?: Hex;\n}): Hex {\n return hashTypedData({\n domain: {\n chainId: input.chainId,\n verifyingContract: input.safe4337ModuleAddress ?? (SAFE_4337_MODULE as Hex),\n },\n types: EIP712_SAFE_OPERATION_TYPE_V07,\n primaryType: \"SafeOp\",\n message: {\n safe: input.userOp.sender,\n nonce: input.userOp.nonce,\n initCode: safe4337InitCode(input.userOp),\n callData: input.userOp.callData,\n verificationGasLimit: input.userOp.verificationGasLimit,\n callGasLimit: input.userOp.callGasLimit,\n preVerificationGas: input.userOp.preVerificationGas,\n maxPriorityFeePerGas: input.userOp.maxPriorityFeePerGas,\n maxFeePerGas: input.userOp.maxFeePerGas,\n paymasterAndData: safe4337PaymasterAndData(input.userOp),\n validAfter: input.validAfter ?? 0,\n validUntil: input.validUntil ?? 0,\n entryPoint: input.entryPointAddress ?? ENTRY_POINT_07_ADDRESS,\n },\n });\n}\n\n/** Pack a single-owner ECDSA signature into the Safe4337 UserOp signature. */\nexport function packSafe4337OwnerSignature(input: {\n readonly signature: Hex;\n readonly validAfter?: number;\n readonly validUntil?: number;\n}): Hex {\n assertUint48(input.validAfter ?? 0, \"validAfter\");\n assertUint48(input.validUntil ?? 0, \"validUntil\");\n return encodePacked(\n [\"uint48\", \"uint48\", \"bytes\"],\n [input.validAfter ?? 0, input.validUntil ?? 0, input.signature],\n );\n}\n\nfunction assertUint48(value: number, field: string): void {\n if (!Number.isSafeInteger(value) || value < 0 || value > UINT48_MAX) {\n throw Errors.invalidInput(field, `must fit uint48 (0..${UINT48_MAX})`);\n }\n}\n\nconst executeUserOpWithErrorStringAbi = [\n {\n type: \"function\",\n name: \"executeUserOpWithErrorString\",\n stateMutability: \"nonpayable\",\n inputs: [\n { name: \"to\", type: \"address\" },\n { name: \"value\", type: \"uint256\" },\n { name: \"data\", type: \"bytes\" },\n { name: \"operation\", type: \"uint8\" },\n ],\n outputs: [],\n },\n] as const;\n\n/**\n * Encode the deployment UserOp `callData` — a single Safe4337Module\n * `executeUserOpWithErrorString(to, value, data, operation=0)` call. Byte-for-byte\n * equal to permissionless's `toSafeSmartAccount(...).encodeCalls([{ to, value, data }])`\n * for the single-call path (no ERC-7579 launchpad, no on-chain identifier) — the\n * same path the proven live deploy adapter uses.\n */\nexport function safe4337ExecuteUserOpCallData(input: {\n readonly to: Hex;\n readonly value?: bigint;\n readonly data?: Hex;\n}): Hex {\n return encodeFunctionData({\n abi: executeUserOpWithErrorStringAbi,\n functionName: \"executeUserOpWithErrorString\",\n args: [input.to, input.value ?? 0n, input.data ?? \"0x\", 0],\n });\n}\n\n/**\n * Encode more than one ordered call through Safe's canonical\n * MultiSendCallOnly delegatecall path, byte-for-byte matching\n * permissionless `SafeSmartAccount.encodeCalls` for a non-7579 Safe.\n */\nexport function safe4337MultiSendUserOpCallData(input: {\n readonly calls: readonly SafeTransactionCall[];\n}): Hex {\n if (input.calls.length < 2) {\n throw Errors.invalidInput(\"calls\", \"Safe4337 multi-send requires at least two calls\");\n }\n const transactions = concat(input.calls.map(encodeSafeMultiSendCallTransaction));\n const multiSendData = encodeFunctionData({\n abi: multiSendAbi,\n functionName: \"multiSend\",\n args: [transactions],\n });\n return encodeFunctionData({\n abi: executeUserOpWithErrorStringAbi,\n functionName: \"executeUserOpWithErrorString\",\n args: [MULTI_SEND_CALL_ONLY, 0n, multiSendData, 1],\n });\n}\n\n// DO NOT USE IN PRODUCTION. SAFE4337_STUB_OWNER_ECDSA is an intentionally\n// insecure, deterministic, forgeable, and replayable gas-estimation stub.\n// safe4337StubSignature() must be replaced by a real owner signature before\n// submitting any transaction or deployment UserOp.\nconst SAFE4337_STUB_OWNER_ECDSA: Hex =\n \"0xfffffffffffffffffffffffffffffff0000000000000000000000000000000007aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa1c\";\n\n/**\n * Packed Safe4337 stub signature (single static owner) for gas estimation —\n * byte-for-byte equal to permissionless's `getStubSignature()`.\n */\nexport function safe4337StubSignature(): Hex {\n return packSafe4337OwnerSignature({ signature: SAFE4337_STUB_OWNER_ECDSA });\n}\n","import { Errors } from \"@capxul/errors\";\nimport { normalizeSafeSaltEmail } from \"./safe.ts\";\n\n/** Openfort `thirdPartyUserId` namespace for email bindings (epic #331 / #332). */\nexport const CAPXUL_BINDING_EMAIL_NAMESPACE = \"capxul:binding:email:v1\";\n\nconst BINDING_EMAIL_PREFIX = `${CAPXUL_BINDING_EMAIL_NAMESPACE}:`;\n\n/**\n * Normalize a raw email for binding id + Safe salt derivation.\n * Delegates to {@link normalizeSafeSaltEmail} so binding resolution and\n * `deriveCapxulSafeAddress` never drift apart.\n */\nexport function normalizeBindingEmail(email: string): string {\n return normalizeSafeSaltEmail(email);\n}\n\n/**\n * Production Openfort player key for authenticated flows (#338).\n * Matches the BetterAuth ↔ Openfort browser bridge (`user._id`).\n * Hermetic smoke scripts may still pregen by normalized email directly.\n */\nexport function openfortThirdPartyUserIdForAuth(authUserId: string): string {\n return authUserId;\n}\n\n/**\n * Format the canonical Capxul email binding id (Convex + wire lookup key).\n *\n * `capxul:binding:email:v1:{normalizedEmail}` — pinned by the #332 conformance\n * matrix in `tests/binding.test.ts`. Openfort `thirdPartyUserId` for live SDK\n * flows uses {@link openfortThirdPartyUserIdForAuth}; unauthenticated smoke\n * scripts may still pass normalized email.\n */\nexport function formatEmailBindingId(email: string): string {\n return `${BINDING_EMAIL_PREFIX}${normalizeBindingEmail(email)}`;\n}\n\n/**\n * Parse a binding id back to the normalized email. Throws\n * {@link CapxulError} `INVALID_INPUT` when the id is not an email-binding\n * id for the v1 namespace.\n */\nexport function parseEmailBindingId(bindingId: string): string {\n if (!bindingId.startsWith(BINDING_EMAIL_PREFIX)) {\n throw Errors.invalidInput(\"bindingId\", `must start with \"${BINDING_EMAIL_PREFIX}\"`);\n }\n const suffix = bindingId.slice(BINDING_EMAIL_PREFIX.length);\n if (suffix.length === 0) {\n throw Errors.invalidInput(\"bindingId\", \"must include a normalized email suffix\");\n }\n if (normalizeBindingEmail(suffix) !== suffix) {\n throw Errors.invalidInput(\"bindingId\", \"email suffix must be canonical (normalized)\");\n }\n return suffix;\n}\n\n/** True when `bindingId` is a v1 email binding id with a canonical suffix. */\nexport function isEmailBindingId(bindingId: string): boolean {\n if (!bindingId.startsWith(BINDING_EMAIL_PREFIX)) {\n return false;\n }\n const suffix = bindingId.slice(BINDING_EMAIL_PREFIX.length);\n return suffix.length > 0 && normalizeBindingEmail(suffix) === suffix;\n}\n","// Settlement Route + Token value types (D1 · #563). The deepening move: chain /\n// token / decimals / verifying-contract knowledge was AMBIENT across the domain\n// — chainId re-defaulted in 7 executors, the token address known in 5 places,\n// the bare literal `84_532` hardcoded inside the chain-agnostic resolver, and\n// NO type binding `{chainId, token, decimals, verifyingContract}` so they could\n// drift apart. This module is the single binding.\n//\n// A `Token` is a settlement asset bound to its chain: `{chainId, address,\n// decimals}` travel together so a caller can never pair USDX's address with the\n// wrong chain or the wrong decimals. A `Route` is the settlement path: which\n// `Token` settles where, plus the `verifyingContract` (the CapxulPayments\n// contract the EIP-712 document hash + every send/commitment commit against).\n//\n// Only the `direct-base` route exists today (USDX on Base Sepolia through\n// CapxulPayments). `provider:blockradar` / `fiat-offramp` slot in later as new\n// `Route` values behind the UNCHANGED `SettlementPort` interface — the seam the\n// multi-route future requires.\n\nimport type { Address } from \"viem\";\n\nimport { BASE_SEPOLIA_CHAIN_ID } from \"./safe.ts\";\nimport { CAPXUL_PAYMENTS_ADDRESS } from \"./org-payments.ts\";\nimport { USDX_ADDRESS_BASE_SEPOLIA, USDX_DECIMALS } from \"./tokens.ts\";\n\n/**\n * The settlement-route identifiers. `direct-base` is the real USDX-on-Base\n * route; `provider:sandbox` (B3) is a HERMETIC mock route — a second route\n * behind the unchanged `SettlementPort` interface that returns deterministic\n * stub evidence with no chain access, so the withdraw lane can be proven\n * without a real provider. `provider:blockradar` / `fiat-offramp` remain\n * NOT_IMPLEMENTED until the real cash-out provider (Lightspark/UMA, BlockRadar)\n * lands in the R&D pass.\n */\nexport type SettlementRouteKind =\n | \"direct-base\"\n | \"provider:sandbox\"\n | \"provider:blockradar\"\n | \"fiat-offramp\";\n\n/**\n * A settlement asset bound to its chain. `{chainId, address, decimals}` travel\n * together — the binding that stops USDX's address being paired with the wrong\n * chain or the wrong decimals.\n */\nexport interface Token {\n readonly chainId: number;\n readonly address: Address;\n readonly decimals: number;\n}\n\n/**\n * A settlement path: which `Token` settles where, and the `verifyingContract`\n * (the CapxulPayments contract the EIP-712 document hash and every send /\n * commitment commits against). The deep `SettlementPort` owns one `Route`.\n */\nexport interface Route {\n readonly kind: SettlementRouteKind;\n readonly token: Token;\n /** Convenience mirror of `token.chainId` — the chain this route settles on. */\n readonly chainId: number;\n /** The CapxulPayments contract address (EIP-712 verifying contract). */\n readonly verifyingContract: Address;\n}\n\n/** USDX on Base Sepolia — the only settlement token in v1. */\nexport const USDX_BASE_SEPOLIA_TOKEN: Token = {\n chainId: BASE_SEPOLIA_CHAIN_ID,\n address: USDX_ADDRESS_BASE_SEPOLIA as Address,\n decimals: USDX_DECIMALS,\n};\n\n/**\n * The `direct-base` settlement route: USDX on Base Sepolia, settled directly\n * through the `CapxulPayments` contract. This is the ONLY route implemented in\n * D1; the `Route` shape is the seam future provider routes slot into.\n */\nexport const DIRECT_BASE_ROUTE: Route = {\n kind: \"direct-base\",\n token: USDX_BASE_SEPOLIA_TOKEN,\n chainId: USDX_BASE_SEPOLIA_TOKEN.chainId,\n verifyingContract: CAPXUL_PAYMENTS_ADDRESS,\n};\n\n/**\n * The `provider:sandbox` settlement route (B3): a HERMETIC mock cash-out route.\n * It binds the SAME token / chain / verifying contract as `direct-base` so the\n * value helpers (`moneyToRawUnits`, `normalizeRecipient`, …) behave identically;\n * only `submitAndConfirm` differs — the sandbox port returns deterministic stub\n * settlement evidence with no network access (see `sandboxSettlementPort`). The\n * real provider route (Lightspark/UMA, BlockRadar) replaces this behind the\n * unchanged `SettlementPort` interface in the R&D pass.\n */\nexport const SANDBOX_ROUTE: Route = {\n kind: \"provider:sandbox\",\n token: USDX_BASE_SEPOLIA_TOKEN,\n chainId: USDX_BASE_SEPOLIA_TOKEN.chainId,\n verifyingContract: CAPXUL_PAYMENTS_ADDRESS,\n};\n","import { keccak256, toBytes } from \"viem\";\n\nimport { Errors } from \"@capxul/errors\";\n\nexport type OrgRoleMoney = {\n readonly currency: \"USD\";\n /** Integer base units for USD with 6 decimals, e.g. $25,000 => \"25000000000\". */\n readonly value: string;\n readonly decimals: 6;\n};\n\nexport type OrgRoleSpendCap = {\n readonly perTx?: OrgRoleMoney;\n readonly perDay?: OrgRoleMoney;\n readonly toRecipients?: \"anyone\" | readonly string[];\n};\n\nexport type OrgRoleDefinition = {\n readonly label: string;\n readonly spend?: OrgRoleSpendCap;\n readonly subAccounts?: { readonly scope: \"all\" | readonly string[] };\n readonly canManageMembers?: boolean;\n readonly canManageRoles?: boolean;\n};\n\nexport type CompiledOrgRole = {\n readonly label: string;\n readonly roleKey: string;\n readonly definition: OrgRoleDefinition;\n readonly permissions: readonly string[];\n readonly allowance: OrgRoleSpendCap | null;\n};\n\nexport type CompiledOrgRoles = {\n readonly roles: readonly CompiledOrgRole[];\n readonly memberManagementRole: {\n readonly roleKey: string;\n readonly permission: \"zodiac.roles.assignRoles\";\n };\n};\n\nconst USD_DECIMALS = 6;\nconst USD_SCALE = 10n ** BigInt(USD_DECIMALS);\nconst USD_DISPLAY_RE = /^\\d+(?:\\.\\d{1,6})?$/;\nconst USD_BASE_UNIT_RE = /^\\d+$/;\nconst EXEC_TRANSACTION_WITH_ROLE = \"zodiac.roles.execTransactionWithRole\" as const;\nconst ASSIGN_ROLES = \"zodiac.roles.assignRoles\" as const;\nconst SCOPE_TARGET = \"zodiac.roles.scopeTarget\" as const;\nconst OWNER_ROLE_LABEL = \"Owner\";\nconst MARKETING_SUB_ACCOUNT_ID = \"subaccount_marketing\";\nconst PAYROLL_SUB_ACCOUNT_ID = \"subaccount_payroll\";\n\nfunction usd(value: string): OrgRoleMoney {\n return { currency: \"USD\", value: usdDisplayToBaseUnits(value), decimals: USD_DECIMALS };\n}\n\nfunction usdDisplayToBaseUnits(value: string): string {\n const trimmed = value.trim();\n if (trimmed !== value || !USD_DISPLAY_RE.test(value)) {\n throw Errors.invalidInput(\n \"role.spend\",\n \"USD caps must be unsigned decimal strings with at most 6 fractional digits\",\n );\n }\n const parts = value.split(\".\");\n const whole = parts[0] ?? \"0\";\n const fraction = parts[1] ?? \"\";\n return (BigInt(whole) * USD_SCALE + BigInt(fraction.padEnd(USD_DECIMALS, \"0\"))).toString();\n}\n\nfunction normalizeOrgRoleMoney(money: OrgRoleMoney, field: string): OrgRoleMoney {\n if (\n money.currency !== \"USD\" ||\n money.decimals !== USD_DECIMALS ||\n !USD_BASE_UNIT_RE.test(money.value)\n ) {\n throw Errors.invalidInput(field, `must be USD base units with ${USD_DECIMALS} decimals`);\n }\n return money;\n}\n\nfunction normalizeOrgRoleSpendCap(spend: OrgRoleSpendCap | undefined): OrgRoleSpendCap | undefined {\n if (spend === undefined) return undefined;\n return {\n ...(spend.perTx === undefined\n ? {}\n : { perTx: normalizeOrgRoleMoney(spend.perTx, \"roles.spend.perTx\") }),\n ...(spend.perDay === undefined\n ? {}\n : { perDay: normalizeOrgRoleMoney(spend.perDay, \"roles.spend.perDay\") }),\n ...(spend.toRecipients === undefined ? {} : { toRecipients: spend.toRecipients }),\n };\n}\n\nexport function normalizeOrgRoleLabel(label: string): string {\n const normalized = label.trim().replace(/\\s+/g, \" \");\n if (normalized.length === 0) {\n throw Errors.invalidInput(\"role.label\", \"must be a non-empty role label\");\n }\n return normalized;\n}\n\nexport function orgRoleKeyForLabel(label: string): string {\n return keccak256(toBytes(normalizeOrgRoleLabel(label).toLowerCase()));\n}\n\nexport function soloOrgRoleTemplate(): readonly OrgRoleDefinition[] {\n return [\n {\n label: \"Owner\",\n subAccounts: { scope: \"all\" },\n canManageMembers: true,\n canManageRoles: true,\n },\n ];\n}\n\nexport function startupOrgRoleTemplate(): readonly OrgRoleDefinition[] {\n return [\n ...soloOrgRoleTemplate(),\n {\n label: \"Finance Manager\",\n spend: {\n perTx: usd(\"25000\"),\n perDay: usd(\"100000\"),\n toRecipients: \"anyone\",\n },\n subAccounts: { scope: [MARKETING_SUB_ACCOUNT_ID] },\n },\n {\n label: \"Team Lead\",\n spend: {\n perTx: usd(\"5000\"),\n perDay: usd(\"15000\"),\n toRecipients: \"anyone\",\n },\n subAccounts: { scope: [PAYROLL_SUB_ACCOUNT_ID] },\n },\n ];\n}\n\nexport function orgRoleTemplateDefinitions(\n template: \"Solo\" | \"Startup\" | \"Custom\",\n customRoles: readonly OrgRoleDefinition[] = [],\n): readonly OrgRoleDefinition[] {\n switch (template) {\n case \"Solo\":\n return soloOrgRoleTemplate();\n case \"Startup\":\n return startupOrgRoleTemplate();\n case \"Custom\":\n return customRoles.length === 0 ? soloOrgRoleTemplate() : customRoles;\n default: {\n const _exhaustive: never = template;\n return _exhaustive;\n }\n }\n}\n\nexport function compileOrgRoleDefinitions(\n definitions: readonly OrgRoleDefinition[],\n): CompiledOrgRoles {\n if (definitions.length === 0) {\n throw Errors.invalidInput(\"roles\", \"must include at least one role\");\n }\n\n const seen = new Set<string>();\n const roles = definitions.map((definition): CompiledOrgRole => {\n const label = normalizeOrgRoleLabel(definition.label);\n const roleKey = orgRoleKeyForLabel(label);\n if (seen.has(roleKey)) {\n throw Errors.invalidInput(\"roles\", `duplicate role label: ${label}`);\n }\n seen.add(roleKey);\n const spend = normalizeOrgRoleSpendCap(definition.spend);\n\n const permissions: string[] = [];\n if (spend !== undefined || label === OWNER_ROLE_LABEL) {\n permissions.push(EXEC_TRANSACTION_WITH_ROLE);\n }\n if (definition.canManageMembers === true) {\n permissions.push(ASSIGN_ROLES);\n }\n if (definition.canManageRoles === true) {\n permissions.push(SCOPE_TARGET);\n }\n\n return {\n label,\n roleKey,\n definition: { ...definition, label, ...(spend === undefined ? {} : { spend }) },\n permissions,\n allowance: spend ?? null,\n };\n });\n\n const manager = roles.find((role) => role.definition.canManageMembers === true);\n if (manager === undefined) {\n throw Errors.invalidInput(\n \"roles.canManageMembers\",\n \"at least one role must compile to the on-chain member-management permission\",\n );\n }\n\n return {\n roles,\n memberManagementRole: {\n roleKey: manager.roleKey,\n permission: ASSIGN_ROLES,\n },\n };\n}\n","import {\n concat,\n encodeAbiParameters,\n encodeFunctionData,\n getContractAddress,\n keccak256,\n padHex,\n parseAbiParameters,\n stringToHex,\n type Hex,\n} from \"viem\";\n\nimport {\n CAPXUL_PAYMENTS_ADDRESS,\n MULTI_SEND_CALL_ONLY,\n ROLES_MASTERCOPY,\n ZODIAC_MODULE_PROXY_FACTORY,\n ZODIAC_MULTI_SEND_UNWRAPPER,\n} from \"./org-payments.ts\";\nimport {\n compileOrgRoleDefinitions,\n normalizeOrgRoleLabel,\n startupOrgRoleTemplate,\n type CompiledOrgRole,\n type OrgRoleDefinition,\n type OrgRoleSpendCap,\n} from \"./role-dsl.ts\";\nimport { USDX_ADDRESS_BASE_SEPOLIA } from \"./tokens.ts\";\n\nexport interface EncodedOrgZodiacCall {\n readonly to: Hex;\n readonly data: Hex;\n readonly value: bigint;\n}\n\nexport interface BuildOrgRolesDeployCallsInput {\n readonly safeAddress: Hex;\n readonly ownerAddress: Hex;\n readonly roleDefinitions?: readonly OrgRoleDefinition[];\n readonly saltNonce?: bigint;\n}\n\nexport interface OrgRolesDeployCalls {\n readonly rolesModuleAddress: Hex;\n readonly calls: readonly EncodedOrgZodiacCall[];\n}\n\nexport interface BuildOrgRoleAssignmentCallInput {\n readonly rolesModuleAddress: Hex;\n readonly managerRoleKey: Hex;\n readonly memberAddress: Hex;\n readonly roleKey: Hex;\n readonly memberOf: boolean;\n}\n\ntype ZodiacCondition = {\n readonly paramType: number;\n readonly operator: number;\n readonly compValue?: Hex;\n readonly children?: readonly ZodiacCondition[];\n};\n\ntype ZodiacPermission = {\n readonly targetAddress: Hex;\n readonly signature: string;\n readonly condition?: ZodiacCondition;\n};\n\ntype ZodiacRoleConfig = {\n readonly key: Hex;\n readonly members: readonly Hex[];\n readonly permissions: readonly ZodiacPermission[];\n};\n\ntype ZodiacSdkCall = {\n readonly to: string;\n readonly data: string;\n readonly value: string | number | bigint;\n};\n\ntype ZodiacSdk = {\n readonly setUpRoles: (input: {\n readonly address: Hex;\n readonly roles: readonly ZodiacRoleConfig[];\n }) => readonly ZodiacSdkCall[];\n};\n\nconst MODULE_PROXY_FACTORY_ABI = [\n {\n type: \"function\",\n name: \"deployModule\",\n stateMutability: \"nonpayable\",\n inputs: [\n { name: \"masterCopy\", type: \"address\" },\n { name: \"initializer\", type: \"bytes\" },\n { name: \"saltNonce\", type: \"uint256\" },\n ],\n outputs: [{ name: \"proxy\", type: \"address\" }],\n },\n] as const;\n\nconst SAFE_ENABLE_MODULE_ABI = [\n {\n type: \"function\",\n name: \"enableModule\",\n stateMutability: \"nonpayable\",\n inputs: [{ name: \"module\", type: \"address\" }],\n outputs: [],\n },\n] as const;\n\nconst ROLES_SET_UP_ABI = [\n {\n type: \"function\",\n name: \"setUp\",\n stateMutability: \"nonpayable\",\n inputs: [{ name: \"initParams\", type: \"bytes\" }],\n outputs: [],\n },\n] as const;\n\nconst ROLES_SET_ALLOWANCE_ABI = [\n {\n type: \"function\",\n name: \"setAllowance\",\n stateMutability: \"nonpayable\",\n inputs: [\n { name: \"key\", type: \"bytes32\" },\n { name: \"balance\", type: \"uint128\" },\n { name: \"maxRefill\", type: \"uint128\" },\n { name: \"refill\", type: \"uint128\" },\n { name: \"period\", type: \"uint64\" },\n { name: \"timestamp\", type: \"uint64\" },\n ],\n outputs: [],\n },\n] as const;\n\nconst ROLES_SET_TRANSACTION_UNWRAPPER_ABI = [\n {\n type: \"function\",\n name: \"setTransactionUnwrapper\",\n stateMutability: \"nonpayable\",\n inputs: [\n { name: \"target\", type: \"address\" },\n { name: \"selector\", type: \"bytes4\" },\n { name: \"adapter\", type: \"address\" },\n ],\n outputs: [],\n },\n] as const;\n\nconst ROLES_ASSIGN_ROLES_ABI = [\n {\n type: \"function\",\n name: \"assignRoles\",\n stateMutability: \"nonpayable\",\n inputs: [\n { name: \"module\", type: \"address\" },\n { name: \"roleKeys\", type: \"bytes32[]\" },\n { name: \"memberOf\", type: \"bool[]\" },\n ],\n outputs: [],\n },\n] as const;\n\nconst ROLES_EXEC_TRANSACTION_WITH_ROLE_ABI = [\n {\n type: \"function\",\n name: \"execTransactionWithRole\",\n stateMutability: \"nonpayable\",\n inputs: [\n { name: \"to\", type: \"address\" },\n { name: \"value\", type: \"uint256\" },\n { name: \"data\", type: \"bytes\" },\n { name: \"operation\", type: \"uint8\" },\n { name: \"roleKey\", type: \"bytes32\" },\n { name: \"shouldRevert\", type: \"bool\" },\n ],\n outputs: [{ name: \"success\", type: \"bool\" }],\n },\n] as const;\n\nexport const ORG_ROLE_ALLOWANCE_KEYS = {\n financeManagerDaily: padHex(stringToHex(\"FM_DAILY\"), { size: 32, dir: \"right\" }),\n teamLeadDaily: padHex(stringToHex(\"TL_DAILY\"), { size: 32, dir: \"right\" }),\n} as const;\n\nexport const MULTI_SEND_SELECTOR = \"0x8d80ff0a\" as const;\n/** Storage key used by Roles.unwrappers(bytes32) for the canonical MultiSend binding. */\nexport const MULTI_SEND_UNWRAPPER_KEY = padHex(\n concat([MULTI_SEND_CALL_ONLY, MULTI_SEND_SELECTOR]),\n { dir: \"right\", size: 32 },\n);\nconst ONE_DAY_SECONDS = 86_400n;\nconst ZODIAC_OPERATION_CALL = 0;\nconst EXEC_TRANSACTION_WITH_ROLE = \"zodiac.roles.execTransactionWithRole\";\nconst ROLE_MANAGEMENT_SIGNATURES = [\n \"allowTarget(bytes32,address,uint8)\",\n \"scopeTarget(bytes32,address)\",\n \"revokeTarget(bytes32,address)\",\n \"allowFunction(bytes32,address,bytes4,uint8)\",\n \"scopeFunction(bytes32,address,bytes4,(uint8,uint8,uint8,bytes)[],uint8)\",\n \"revokeFunction(bytes32,address,bytes4)\",\n \"setAllowance(bytes32,uint128,uint128,uint128,uint64,uint64)\",\n] as const;\n\nconst PARAMETER_TYPE = {\n none: 0,\n static: 1,\n calldata: 5,\n} as const;\n\nconst OPERATOR = {\n pass: 0,\n and: 1,\n or: 2,\n matches: 5,\n equalTo: 16,\n lessThan: 18,\n withinAllowance: 28,\n} as const;\n\nfunction normalizeHexAddress(address: Hex): Hex {\n return address.toLowerCase() as Hex;\n}\n\nexport function orgRoleAllowanceKeyForLabel(label: string): Hex {\n const normalized = normalizeOrgRoleLabel(label);\n switch (normalized) {\n case \"Finance Manager\":\n return ORG_ROLE_ALLOWANCE_KEYS.financeManagerDaily;\n case \"Team Lead\":\n return ORG_ROLE_ALLOWANCE_KEYS.teamLeadDaily;\n default:\n return keccak256(stringToHex(`CAPXUL_ORG_DAILY_ALLOWANCE:${normalized.toLowerCase()}`));\n }\n}\n\nfunction passStatic(): ZodiacCondition {\n return { paramType: PARAMETER_TYPE.static, operator: OPERATOR.pass };\n}\n\nfunction equalAddress(address: Hex): ZodiacCondition {\n return {\n paramType: PARAMETER_TYPE.static,\n operator: OPERATOR.equalTo,\n compValue: encodeAbiParameters([{ type: \"address\" }], [address]),\n };\n}\n\nfunction lteUint256(value: string): ZodiacCondition {\n return {\n paramType: PARAMETER_TYPE.static,\n operator: OPERATOR.lessThan,\n compValue: encodeAbiParameters([{ type: \"uint256\" }], [BigInt(value) + 1n]),\n };\n}\n\nfunction withinAllowance(allowanceKey: Hex): ZodiacCondition {\n return {\n paramType: PARAMETER_TYPE.static,\n operator: OPERATOR.withinAllowance,\n compValue: encodeAbiParameters([{ type: \"bytes32\" }], [allowanceKey]),\n };\n}\n\nfunction and(...children: readonly ZodiacCondition[]): ZodiacCondition {\n return { paramType: PARAMETER_TYPE.none, operator: OPERATOR.and, children };\n}\n\nfunction calldataMatches(children: readonly ZodiacCondition[]): ZodiacCondition {\n return { paramType: PARAMETER_TYPE.calldata, operator: OPERATOR.matches, children };\n}\n\n/**\n * The on-chain recipient condition for a role's `toRecipients` scope. `\"anyone\"`\n * (or an empty/undefined set) leaves the recipient param unconstrained on-chain\n * (`passStatic` — recipient validation is the Level-2 off-chain guard). A FIXED\n * recipient set compiles to an `Or` over per-address equality so the on-chain\n * Roles modifier itself refuses any recipient outside the set — this is the\n * treasury-drain boundary for createCommitment / redirect, not just `send`.\n */\nfunction recipientCondition(toRecipients: OrgRoleSpendCap[\"toRecipients\"]): ZodiacCondition {\n if (toRecipients === undefined || toRecipients === \"anyone\" || toRecipients.length === 0) {\n return passStatic();\n }\n const equals = toRecipients.map((address) => equalAddress(normalizeHexAddress(address as Hex)));\n // A single allowed recipient is a bare equality; multiple are OR-combined.\n return equals.length === 1 ? (equals[0] as ZodiacCondition) : orMatch(equals);\n}\n\nfunction orMatch(children: readonly ZodiacCondition[]): ZodiacCondition {\n // A logical `Or` node addresses no concrete parameter slot of its own — it\n // combines child conditions that each address the SAME value. Zodiac's\n // on-chain `Integrity.sol` enforces `Operator.Or ⇒ ParameterType.None`; a\n // `Static` paramType makes `scopeFunction` REVERT on deploy, bricking any role\n // with a 2+ recipient set. The children keep their own (`Static`) param types.\n return { paramType: PARAMETER_TYPE.none, operator: OPERATOR.or, children };\n}\n\nfunction encodeRolesSetUpCall(input: {\n readonly owner: Hex;\n readonly avatar: Hex;\n readonly target: Hex;\n}): Hex {\n const innerInitParams = encodeAbiParameters(parseAbiParameters(\"address, address, address\"), [\n input.owner,\n input.avatar,\n input.target,\n ]);\n return encodeFunctionData({\n abi: ROLES_SET_UP_ABI,\n functionName: \"setUp\",\n args: [innerInitParams],\n });\n}\n\nexport function computeOrgRolesModuleAddress(input: {\n readonly owner: Hex;\n readonly avatar: Hex;\n readonly target: Hex;\n readonly saltNonce?: bigint;\n}): Hex {\n const saltNonce = input.saltNonce ?? 0n;\n const proxyInitCode = (\"0x602d8060093d393df3363d3d373d3d3d363d73\" +\n ROLES_MASTERCOPY.slice(2).toLowerCase() +\n \"5af43d82803e903d91602b57fd5bf3\") as Hex;\n const initializer = encodeRolesSetUpCall(input);\n const initializerHash = keccak256(initializer);\n const saltNonceEncoded = encodeAbiParameters(parseAbiParameters(\"uint256\"), [saltNonce]);\n const salt = keccak256((initializerHash + saltNonceEncoded.slice(2)) as Hex);\n\n return normalizeHexAddress(\n getContractAddress({\n opcode: \"CREATE2\",\n from: ZODIAC_MODULE_PROXY_FACTORY,\n salt,\n bytecodeHash: keccak256(proxyInitCode),\n }),\n );\n}\n\nfunction buildDeployModuleCall(input: {\n readonly safeAddress: Hex;\n readonly saltNonce: bigint;\n}): EncodedOrgZodiacCall {\n return {\n to: ZODIAC_MODULE_PROXY_FACTORY,\n data: encodeFunctionData({\n abi: MODULE_PROXY_FACTORY_ABI,\n functionName: \"deployModule\",\n args: [\n ROLES_MASTERCOPY,\n encodeRolesSetUpCall({\n owner: input.safeAddress,\n avatar: input.safeAddress,\n target: input.safeAddress,\n }),\n input.saltNonce,\n ],\n }),\n value: 0n,\n };\n}\n\nfunction buildEnableModuleCall(input: {\n readonly safeAddress: Hex;\n readonly rolesModuleAddress: Hex;\n}): EncodedOrgZodiacCall {\n return {\n to: input.safeAddress,\n data: encodeFunctionData({\n abi: SAFE_ENABLE_MODULE_ABI,\n functionName: \"enableModule\",\n args: [input.rolesModuleAddress],\n }),\n value: 0n,\n };\n}\n\nfunction buildSetUnwrapperCall(rolesModuleAddress: Hex): EncodedOrgZodiacCall {\n return {\n to: rolesModuleAddress,\n data: encodeFunctionData({\n abi: ROLES_SET_TRANSACTION_UNWRAPPER_ABI,\n functionName: \"setTransactionUnwrapper\",\n args: [MULTI_SEND_CALL_ONLY, MULTI_SEND_SELECTOR, ZODIAC_MULTI_SEND_UNWRAPPER],\n }),\n value: 0n,\n };\n}\n\nfunction buildSetAllowanceCall(input: {\n readonly rolesModuleAddress: Hex;\n readonly allowanceKey: Hex;\n readonly dailyCap: string;\n}): EncodedOrgZodiacCall {\n const dailyCap = BigInt(input.dailyCap);\n return {\n to: input.rolesModuleAddress,\n data: encodeFunctionData({\n abi: ROLES_SET_ALLOWANCE_ABI,\n functionName: \"setAllowance\",\n args: [input.allowanceKey, dailyCap, dailyCap, dailyCap, ONE_DAY_SECONDS, 0n],\n }),\n value: 0n,\n };\n}\n\nfunction buildTemplateAllowanceCalls(input: {\n readonly rolesModuleAddress: Hex;\n readonly roles: readonly CompiledOrgRole[];\n}): readonly EncodedOrgZodiacCall[] {\n return input.roles.flatMap((role) => {\n const dailyCap = role?.allowance?.perDay?.value;\n return dailyCap === undefined\n ? []\n : [\n buildSetAllowanceCall({\n rolesModuleAddress: input.rolesModuleAddress,\n allowanceKey: orgRoleAllowanceKeyForLabel(role.label),\n dailyCap,\n }),\n ];\n });\n}\n\n// Selector signatures the role compiler scopes on CapxulPayments. `claim` is\n// DELIBERATELY ABSENT: claim is recipient-side (a recipient pulling vested\n// funds), never org treasury authority — granting it would let a role drain\n// commitments addressed to others (#488, D10).\nconst CREATE_COMMITMENT_SIGNATURE =\n \"createCommitment(address,address,uint256,uint48,uint48,uint48,bytes32,uint8)\";\nconst CANCEL_SIGNATURE = \"cancel(uint256,bytes32)\";\nconst REDIRECT_SIGNATURE = \"redirect(uint256,address,bytes32)\";\n\nfunction approvePermission(): ZodiacPermission {\n return {\n targetAddress: USDX_ADDRESS_BASE_SEPOLIA,\n signature: \"approve(address,uint256)\",\n condition: calldataMatches([equalAddress(CAPXUL_PAYMENTS_ADDRESS), passStatic()]),\n };\n}\n\nfunction paymentPermissions(input: {\n readonly allowanceKey: Hex;\n readonly perTxCap: string;\n readonly recipient: ZodiacCondition;\n}): readonly [ZodiacPermission, ZodiacPermission] {\n return [\n approvePermission(),\n {\n targetAddress: CAPXUL_PAYMENTS_ADDRESS,\n signature: \"send(address,address,uint256,bytes32,uint8)\",\n condition: calldataMatches([\n equalAddress(USDX_ADDRESS_BASE_SEPOLIA),\n input.recipient,\n and(lteUint256(input.perTxCap), withinAllowance(input.allowanceKey)),\n passStatic(),\n passStatic(),\n ]),\n },\n ];\n}\n\nfunction uncappedPaymentPermissions(): readonly [ZodiacPermission, ZodiacPermission] {\n return [\n approvePermission(),\n {\n targetAddress: CAPXUL_PAYMENTS_ADDRESS,\n signature: \"send(address,address,uint256,bytes32,uint8)\",\n condition: calldataMatches([\n equalAddress(USDX_ADDRESS_BASE_SEPOLIA),\n passStatic(),\n passStatic(),\n passStatic(),\n passStatic(),\n ]),\n },\n ];\n}\n\n/**\n * Commitment-verb permissions for a CAPPED role (#488 / G4 #547). `createCommitment`\n * carries the SAME on-chain conditions as `send`: token == USDX, the recipient\n * is in the role's allowed set, and the escrowed `totalAmount` is `<= perTx cap`\n * AND `withinAllowance(perDay key)`. `redirect` re-pins `newRecipient` to the\n * same allowed set (it changes who receives, so it is a recipient-boundary op).\n * `cancel` only reclaims unvested funds from a commitment the role created and\n * carries no recipient/amount, so it is allow-listed by selector with no comp\n * value. `claim` is NEVER emitted — it is recipient-side, not treasury authority.\n */\nfunction commitmentPermissions(input: {\n readonly allowanceKey: Hex;\n readonly perTxCap: string;\n readonly recipient: ZodiacCondition;\n}): readonly ZodiacPermission[] {\n return [\n {\n targetAddress: CAPXUL_PAYMENTS_ADDRESS,\n signature: CREATE_COMMITMENT_SIGNATURE,\n condition: calldataMatches([\n equalAddress(USDX_ADDRESS_BASE_SEPOLIA),\n input.recipient,\n and(lteUint256(input.perTxCap), withinAllowance(input.allowanceKey)),\n passStatic(), // startTime\n passStatic(), // cliffTime\n passStatic(), // endTime\n passStatic(), // documentHash\n passStatic(), // paymentType\n ]),\n },\n {\n targetAddress: CAPXUL_PAYMENTS_ADDRESS,\n signature: REDIRECT_SIGNATURE,\n condition: calldataMatches([\n passStatic(), // commitmentId\n input.recipient, // newRecipient — re-pinned to the role's allowed set\n passStatic(), // newDocumentHash\n ]),\n },\n {\n targetAddress: CAPXUL_PAYMENTS_ADDRESS,\n signature: CANCEL_SIGNATURE,\n condition: calldataMatches([passStatic(), passStatic()]),\n },\n ];\n}\n\n/** Uncapped commitment permissions for the Owner role (no per-tx/recipient cap). */\nfunction uncappedCommitmentPermissions(): readonly ZodiacPermission[] {\n return [\n {\n targetAddress: CAPXUL_PAYMENTS_ADDRESS,\n signature: CREATE_COMMITMENT_SIGNATURE,\n condition: calldataMatches([\n equalAddress(USDX_ADDRESS_BASE_SEPOLIA),\n passStatic(),\n passStatic(),\n passStatic(),\n passStatic(),\n passStatic(),\n passStatic(),\n passStatic(),\n ]),\n },\n {\n targetAddress: CAPXUL_PAYMENTS_ADDRESS,\n signature: REDIRECT_SIGNATURE,\n condition: calldataMatches([passStatic(), passStatic(), passStatic()]),\n },\n {\n targetAddress: CAPXUL_PAYMENTS_ADDRESS,\n signature: CANCEL_SIGNATURE,\n condition: calldataMatches([passStatic(), passStatic()]),\n },\n ];\n}\n\nfunction rolePermissions(input: {\n readonly role: CompiledOrgRole;\n readonly rolesModuleAddress: Hex;\n}): readonly ZodiacPermission[] {\n const permissions: ZodiacPermission[] = [];\n if (input.role.definition.canManageMembers === true) {\n permissions.push({\n targetAddress: input.rolesModuleAddress,\n signature: \"assignRoles(address,bytes32[],bool[])\",\n });\n }\n if (input.role.definition.canManageRoles === true) {\n permissions.push(\n ...ROLE_MANAGEMENT_SIGNATURES.map((signature) => ({\n targetAddress: input.rolesModuleAddress,\n signature,\n })),\n );\n }\n if (\n input.role.allowance === null &&\n input.role.permissions.includes(EXEC_TRANSACTION_WITH_ROLE)\n ) {\n permissions.push(...uncappedPaymentPermissions(), ...uncappedCommitmentPermissions());\n }\n if (input.role.allowance?.perTx !== undefined && input.role.allowance.perDay !== undefined) {\n const allowanceKey = orgRoleAllowanceKeyForLabel(input.role.label);\n const perTxCap = input.role.allowance.perTx.value;\n const recipient = recipientCondition(input.role.allowance.toRecipients);\n permissions.push(\n ...paymentPermissions({ allowanceKey, perTxCap, recipient }),\n ...commitmentPermissions({ allowanceKey, perTxCap, recipient }),\n );\n }\n return permissions;\n}\n\nasync function getZodiacSdk(): Promise<ZodiacSdk> {\n return (await import(\"zodiac-roles-sdk\")) as unknown as ZodiacSdk;\n}\n\nasync function buildRoleSetupCalls(input: {\n readonly rolesModuleAddress: Hex;\n readonly ownerAddress: Hex;\n readonly roles: readonly CompiledOrgRole[];\n readonly managerRoleKey: string;\n}): Promise<readonly EncodedOrgZodiacCall[]> {\n const managerRoleKey = input.managerRoleKey.toLowerCase();\n const roles = input.roles.map(\n (role): ZodiacRoleConfig => ({\n key: role.roleKey as Hex,\n members: role.roleKey.toLowerCase() === managerRoleKey ? [input.ownerAddress] : [],\n permissions: rolePermissions({ role, rolesModuleAddress: input.rolesModuleAddress }),\n }),\n );\n const zodiacSdk = await getZodiacSdk();\n return zodiacSdk.setUpRoles({ address: input.rolesModuleAddress, roles }).map((call) => ({\n to: normalizeHexAddress(call.to as Hex),\n data: call.data as Hex,\n value: BigInt(call.value),\n }));\n}\n\nexport async function buildOrgRolesDeployCalls(\n input: BuildOrgRolesDeployCallsInput,\n): Promise<OrgRolesDeployCalls> {\n const safeAddress = normalizeHexAddress(input.safeAddress);\n const ownerAddress = normalizeHexAddress(input.ownerAddress);\n const saltNonce = input.saltNonce ?? 0n;\n const roleDefinitions = input.roleDefinitions ?? startupOrgRoleTemplate();\n const compiled = compileOrgRoleDefinitions(roleDefinitions);\n const rolesModuleAddress = computeOrgRolesModuleAddress({\n owner: safeAddress,\n avatar: safeAddress,\n target: safeAddress,\n saltNonce,\n });\n\n return {\n rolesModuleAddress,\n calls: [\n buildDeployModuleCall({ safeAddress, saltNonce }),\n buildEnableModuleCall({ safeAddress, rolesModuleAddress }),\n buildSetUnwrapperCall(rolesModuleAddress),\n ...buildTemplateAllowanceCalls({ rolesModuleAddress, roles: compiled.roles }),\n ...(await buildRoleSetupCalls({\n rolesModuleAddress,\n ownerAddress,\n roles: compiled.roles,\n managerRoleKey: compiled.memberManagementRole.roleKey,\n })),\n ],\n };\n}\n\nexport function buildOrgRoleAssignmentCall(\n input: BuildOrgRoleAssignmentCallInput,\n): EncodedOrgZodiacCall {\n const rolesModuleAddress = normalizeHexAddress(input.rolesModuleAddress);\n const memberAddress = normalizeHexAddress(input.memberAddress);\n const roleKey = input.roleKey.toLowerCase() as Hex;\n const managerRoleKey = input.managerRoleKey.toLowerCase() as Hex;\n const assignRolesData = encodeFunctionData({\n abi: ROLES_ASSIGN_ROLES_ABI,\n functionName: \"assignRoles\",\n args: [memberAddress, [roleKey], [input.memberOf]],\n });\n\n return {\n to: rolesModuleAddress,\n data: encodeFunctionData({\n abi: ROLES_EXEC_TRANSACTION_WITH_ROLE_ABI,\n functionName: \"execTransactionWithRole\",\n args: [rolesModuleAddress, 0n, assignRolesData, ZODIAC_OPERATION_CALL, managerRoleKey, true],\n }),\n value: 0n,\n };\n}\n","import { encodeFunctionData, toEventSelector, toFunctionSelector, type Hex } from \"viem\";\n\nimport {\n buildCapxulOrgInitializer,\n computeCapxulOrgSaltNonce,\n deriveCapxulOrgAddress,\n} from \"./org-safe.ts\";\nimport {\n buildSafeMultiSendExecTransactionCall,\n SAFE_L2_SINGLETON,\n SAFE_PROXY_FACTORY,\n} from \"./safe.ts\";\nimport { soloOrgRoleTemplate } from \"./role-dsl.ts\";\nimport { buildOrgRolesDeployCalls, type EncodedOrgZodiacCall } from \"./org-zodiac.ts\";\n\nexport interface BuildSoloOrgBootstrapCallsInput {\n readonly founderPersonalAccount: Hex;\n readonly founderEmail: string;\n readonly organizationHandle: string;\n}\n\nexport interface SoloOrgBootstrapCalls {\n readonly organizationAccountAddress: Hex;\n readonly rolesModuleAddress: Hex;\n readonly calls: readonly EncodedOrgZodiacCall[];\n readonly authorityEvents: readonly SoloOrgBootstrapAuthorityEvent[];\n}\n\nexport interface SoloOrgBootstrapAuthorityEvent {\n readonly emitter: Hex;\n readonly topic0: Hex;\n readonly data: Hex;\n}\n\nconst ROLE_AUTHORITY_EVENT_BY_FUNCTION_SELECTOR = new Map<string, Hex>(\n (\n [\n [\"assignRoles(address,bytes32[],bool[])\", \"AssignRoles(address,bytes32[],bool[])\"],\n [\"allowTarget(bytes32,address,uint8)\", \"AllowTarget(bytes32,address,uint8)\"],\n [\"scopeTarget(bytes32,address)\", \"ScopeTarget(bytes32,address)\"],\n [\"revokeTarget(bytes32,address)\", \"RevokeTarget(bytes32,address)\"],\n [\n \"allowFunction(bytes32,address,bytes4,uint8)\",\n \"AllowFunction(bytes32,address,bytes4,uint8)\",\n ],\n [\n \"scopeFunction(bytes32,address,bytes4,(uint8,uint8,uint8,bytes)[],uint8)\",\n \"ScopeFunction(bytes32,address,bytes4,(uint8,uint8,uint8,bytes)[],uint8)\",\n ],\n [\"revokeFunction(bytes32,address,bytes4)\", \"RevokeFunction(bytes32,address,bytes4)\"],\n [\n \"setAllowance(bytes32,uint128,uint128,uint128,uint64,uint64)\",\n \"SetAllowance(bytes32,uint128,uint128,uint128,uint64,uint64)\",\n ],\n ] as const\n ).map(([functionSignature, eventSignature]) => [\n toFunctionSelector(functionSignature),\n toEventSelector(eventSignature) as Hex,\n ]),\n);\n\nfunction projectAuthorityEvents(\n calls: readonly EncodedOrgZodiacCall[],\n rolesModuleAddress: Hex,\n): readonly SoloOrgBootstrapAuthorityEvent[] {\n return calls.flatMap((call) => {\n if (call.to.toLowerCase() !== rolesModuleAddress.toLowerCase()) return [];\n const topic0 = ROLE_AUTHORITY_EVENT_BY_FUNCTION_SELECTOR.get(call.data.slice(0, 10));\n if (topic0 === undefined) return [];\n return [\n {\n emitter: rolesModuleAddress,\n topic0,\n data: `0x${call.data.slice(10)}` as Hex,\n },\n ];\n });\n}\n\nconst SAFE_PROXY_FACTORY_ABI = [\n {\n type: \"function\",\n name: \"createProxyWithNonce\",\n stateMutability: \"nonpayable\",\n inputs: [\n { name: \"singleton\", type: \"address\" },\n { name: \"initializer\", type: \"bytes\" },\n { name: \"saltNonce\", type: \"uint256\" },\n ],\n outputs: [{ name: \"proxy\", type: \"address\" }],\n },\n] as const;\n\nexport async function buildSoloOrgBootstrapCalls(\n input: BuildSoloOrgBootstrapCallsInput,\n): Promise<SoloOrgBootstrapCalls> {\n const initializer = buildCapxulOrgInitializer({\n founderPersonalSafe: input.founderPersonalAccount,\n });\n const organizationSaltNonce = computeCapxulOrgSaltNonce({\n email: input.founderEmail,\n orgHandle: input.organizationHandle,\n });\n const organizationAccountAddress = deriveCapxulOrgAddress({\n email: input.founderEmail,\n orgHandle: input.organizationHandle,\n founderPersonalSafe: input.founderPersonalAccount,\n }) as Hex;\n const roleDeployment = await buildOrgRolesDeployCalls({\n safeAddress: organizationAccountAddress,\n ownerAddress: input.founderPersonalAccount,\n roleDefinitions: soloOrgRoleTemplate(),\n });\n const [deployRolesModule, ...configureOrganizationCalls] = roleDeployment.calls;\n if (deployRolesModule === undefined || configureOrganizationCalls.length === 0) {\n throw new Error(\"Solo role deployment must include deployment and configuration calls\");\n }\n\n return {\n organizationAccountAddress,\n rolesModuleAddress: roleDeployment.rolesModuleAddress,\n authorityEvents: projectAuthorityEvents(\n configureOrganizationCalls,\n roleDeployment.rolesModuleAddress,\n ),\n calls: [\n {\n to: SAFE_PROXY_FACTORY,\n value: 0n,\n data: encodeFunctionData({\n abi: SAFE_PROXY_FACTORY_ABI,\n functionName: \"createProxyWithNonce\",\n args: [SAFE_L2_SINGLETON, initializer, organizationSaltNonce],\n }),\n },\n deployRolesModule,\n buildSafeMultiSendExecTransactionCall({\n safeAddress: organizationAccountAddress,\n ownerAddress: input.founderPersonalAccount,\n calls: configureOrganizationCalls,\n }),\n ],\n };\n}\n","/**\n * A single frame in PostHog's `$exception_list` format.\n * Matches `[{ frames: [{ filename, function, lineno, colno }] }]`.\n */\nexport interface ExceptionFrame {\n readonly filename: string;\n readonly function: string;\n readonly lineno: number | null;\n readonly colno: number | null;\n}\n\n/**\n * Regex for V8/Chrome stack trace frame lines.\n * Matches:\n * `at functionName (url:line:col)`\n * `at url:line:col`\n * `at async functionName (url:line:col)`\n * `at new ClassName (url:line:col)`\n */\nconst V8_FRAME_RE = /^\\s*at\\s+(?:(.+?)\\s+\\()?(?:(.+?)(?::(\\d+):(\\d+))?|(.+?))\\)?\\s*$/;\n\nfunction isNonUrlName(name: string): boolean {\n return (\n name === \"<anonymous>\" ||\n name.startsWith(\"eval\") ||\n name.startsWith(\"new \") ||\n name.startsWith(\"async \")\n );\n}\n\n/**\n * Parse a V8/Chrome-style stack trace string into PostHog `ExceptionFrame` objects.\n * Returns an empty array when `error.stack` is absent or empty.\n *\n * Handles:\n * - Standard `at functionName (url:line:col)`\n * - Bare `at url:line:col` (no function name)\n * - `at async functionName (url:line:col)`\n * - `at new ClassName (url:line:col)`\n * - Native frames: `at Array.forEach (<anonymous>)`\n */\nexport function parseV8StackFrames(error: { readonly stack?: string }): readonly ExceptionFrame[] {\n const stack = error.stack;\n if (stack === undefined || stack === null || stack === \"\") {\n return [];\n }\n\n const lines = stack.split(\"\\n\");\n const frames: ExceptionFrame[] = [];\n\n for (const line of lines) {\n const trimmed = line.trim();\n if (!trimmed.startsWith(\"at \")) continue;\n\n const match = V8_FRAME_RE.exec(trimmed);\n if (match === null) continue;\n\n if (match[1] !== undefined) {\n // Has function name: `at functionName (url:line:col)`\n frames.push({\n function: match[1],\n filename: match[2]!,\n lineno: match[3] !== undefined ? Number(match[3]) : null,\n colno: match[4] !== undefined ? Number(match[4]) : null,\n });\n } else if (match[2] !== undefined && !isNonUrlName(match[2])) {\n // Bare URL: `at url:line:col`\n frames.push({\n function: \"<anonymous>\",\n filename: match[2],\n lineno: match[3] !== undefined ? Number(match[3]) : null,\n colno: match[4] !== undefined ? Number(match[4]) : null,\n });\n } else {\n // Native or non-URL frame like `<anonymous>`\n frames.push({\n function: match[1] ?? match[2] ?? match[5] ?? \"<anonymous>\",\n filename: match[2] ?? match[5] ?? \"<anonymous>\",\n lineno: match[3] !== undefined ? Number(match[3]) : null,\n colno: match[4] !== undefined ? Number(match[4]) : null,\n });\n }\n }\n\n return frames;\n}\n\n/** One entry in PostHog's `$exception_list` — the shape Error Tracking groups on. */\nexport interface SdkBoundaryException {\n readonly type: string;\n readonly value: string;\n readonly mechanism: { readonly handled: true; readonly type: \"capxul_sdk_boundary\" };\n readonly stacktrace: { readonly frames: readonly ExceptionFrame[] };\n}\n\n/** Fixed, leak-safe frame used when the error carries no parseable stack. */\nconst SDK_BOUNDARY_FILENAME = \"capxul-sdk-observation://boundary\";\n\n/**\n * Build PostHog's `$exception_list` (always a single entry). Error Tracking\n * groups on `type`, so it is ALWAYS present (the CapxulError code) — the\n * previous `[{ frames }]` shape omitted it and PostHog dropped the event as\n * \"missing field `type`\". When the error has no parseable stack, a synthetic\n * boundary frame stands in so the event still ingests as a real Issue (#1031).\n */\nexport function buildExceptionList(input: {\n readonly type: string;\n readonly value: string;\n readonly operation?: string;\n readonly frames: readonly ExceptionFrame[];\n}): readonly [SdkBoundaryException] {\n const frames =\n input.frames.length > 0\n ? input.frames\n : [\n {\n filename: SDK_BOUNDARY_FILENAME,\n function: input.operation ?? \"unknown\",\n lineno: 1,\n colno: 1,\n },\n ];\n return [\n {\n type: input.type,\n value: input.value,\n mechanism: { handled: true, type: \"capxul_sdk_boundary\" },\n stacktrace: { frames },\n },\n ];\n}\n","import { isCapxulError, type FailureMode } from \"@capxul/config\";\n\n/**\n * The five canonical {@link FailureMode} members, for runtime membership checks.\n * Single source of truth — tests assert against this exact set so the taxonomy\n * and its guard can never drift apart.\n */\nexport const FAILURE_MODES: ReadonlySet<string> = new Set<FailureMode>([\n \"auth-origin-mismatch\",\n \"stale-openfort-cache\",\n \"app-env-allowlist\",\n \"no-secure-context\",\n \"unknown\",\n]);\n\nfunction isFailureMode(value: unknown): value is FailureMode {\n return typeof value === \"string\" && FAILURE_MODES.has(value);\n}\n\n/**\n * Extract the structured {@link FailureMode} from a CapxulError.\n *\n * Reads `details.failure_mode` and returns it only when it is one of the five\n * canonical members; any other value (a legacy free string, a typo, a\n * non-string) yields `undefined` so downstream telemetry never reports an\n * unrecognised cause.\n */\nexport function getFailureMode(error: unknown): FailureMode | undefined {\n if (!isCapxulError(error)) return undefined;\n const details = error.details;\n if (details === undefined) return undefined;\n return isFailureMode(details.failure_mode) ? details.failure_mode : undefined;\n}\n\n/**\n * Resolve the canonical {@link FailureMode} for a `$exception`, guaranteeing a\n * taxonomy member is always returned — never `undefined`, never a free string.\n *\n * Resolution order:\n * 1. the structured mode on the error's `details.failure_mode` (already guarded);\n * 2. a caller-supplied `contextFailureMode`, but ONLY when it passes the same\n * runtime membership check — the static `FailureMode` type is erased at\n * runtime, so an operation string (e.g. `\"signer-get-address\"`) injected via\n * a JS caller or `as` cast is rejected here rather than leaking to telemetry;\n * 3. `\"unknown\"` otherwise, so an unclassifiable error is still tagged with a\n * canonical value instead of being emitted with no `failure_mode` at all.\n */\nexport function resolveFailureMode(error: unknown, contextFailureMode?: unknown): FailureMode {\n return (\n getFailureMode(error) ?? (isFailureMode(contextFailureMode) ? contextFailureMode : \"unknown\")\n );\n}\n","import { Effect } from \"effect\";\n\nimport { isCapxulError, type FailureMode } from \"@capxul/config\";\n\nimport type { TelemetryPort } from \"../ports/telemetry\";\nimport { parseV8StackFrames, buildExceptionList } from \"./stack-frame-parser\";\nimport { resolveFailureMode } from \"./get-failure-mode\";\n\nexport interface HandledErrorReportContext {\n readonly layer?: string;\n readonly operation?: string;\n readonly provider?: string;\n readonly capxul_error_code?: string;\n readonly failure_mode?: FailureMode;\n}\n\n/** Fixed, leak-safe message — the raw error message may carry PII and never ships. */\nexport const EXCEPTION_MESSAGE = \"Capxul SDK operation failed\";\n\n/**\n * Capture an error as a `$exception` event through the telemetry port,\n * formatted for PostHog Error Tracking.\n *\n * Parses stack traces into `$exception_list` format, extracts structured\n * metadata from CapxulError objects, and supplements with context props.\n * Fire-and-forget: telemetry defects are silently swallowed.\n * Returns `Effect<void, never>` for use in Effect pipelines; the underlying\n * adapter work is synchronous, so callers outside Effect contexts can\n * use `Effect.runSync`.\n */\nexport function captureException(\n telemetry: TelemetryPort,\n error: unknown,\n context?: HandledErrorReportContext,\n): Effect.Effect<void, never> {\n return Effect.catchDefect(\n Effect.sync(() => {\n const frames = error instanceof Error ? parseV8StackFrames(error) : [];\n\n const capxulError = isCapxulError(error) ? error : null;\n const errorCode = capxulError?.code ?? context?.capxul_error_code ?? \"UNKNOWN\";\n\n const props: Record<string, unknown> = {\n capxul_error_code: errorCode,\n // PostHog Error Tracking groups on `type`. Carry it on both the top-level\n // and every `$exception_list` entry (from the CapxulError code) so the\n // event lands as a real Issue instead of being dropped as \"missing field\n // `type`\". The message is fixed and leak-safe, matching the backend relay\n // and observation boundary — never the raw (possibly PII) error message.\n $exception_type: errorCode,\n $exception_message: EXCEPTION_MESSAGE,\n $exception_list: buildExceptionList({\n type: errorCode,\n value: EXCEPTION_MESSAGE,\n ...(context?.operation === undefined ? {} : { operation: context.operation }),\n frames,\n }),\n layer: capxulError?.layer ?? context?.layer,\n operation: context?.operation,\n provider: context?.provider,\n // Always a canonical FailureMode member (defaults to \"unknown\"); the\n // resolver rejects non-taxonomy context values so an operation string\n // can never reach PostHog, and the key is never pruned as undefined.\n failure_mode: resolveFailureMode(error, context?.failure_mode),\n };\n\n if (capxulError?.details !== undefined) {\n props.details = JSON.stringify(capxulError.details);\n }\n\n // Remove undefined values\n for (const key of Object.keys(props)) {\n if (props[key] === undefined) {\n // oxlint-disable-next-line no-dynamic-delete -- prune absent props before emit\n delete props[key];\n }\n }\n\n return telemetry.emit({ name: \"$exception\" as never, props });\n }).pipe(Effect.flatten),\n () => Effect.void,\n );\n}\n\n/**\n * Synchronous fire-and-forget capture. Runs the Effect inline with\n * `Effect.runSync` so callers outside an Effect context (e.g. React\n * hooks before throwing) can report errors without awaiting.\n */\nexport function captureExceptionSync(\n telemetry: TelemetryPort,\n error: unknown,\n context?: HandledErrorReportContext,\n): void {\n try {\n Effect.runSync(captureException(telemetry, error, context));\n } catch {\n // Fire-and-forget: telemetry failures never propagate\n }\n}\n","import { Effect } from \"effect\";\n\nimport type { SmartAccount } from \"@capxul/types\";\n\nimport type { TelemetryPort } from \"../../ports/telemetry\";\n\nexport async function emitProvisioningTelemetry(\n telemetry: TelemetryPort | undefined,\n smartAccount: SmartAccount,\n): Promise<void> {\n if (telemetry === undefined) return;\n await Effect.runPromise(\n telemetry\n .emit({\n name: \"provisioning_safe_created\",\n props: { safe_address: smartAccount.smartAccountAddress },\n })\n .pipe(\n Effect.catch((cause) =>\n Effect.sync(() => reportProvisioningTelemetryFailure(\"error\", smartAccount, cause)),\n ),\n Effect.catchDefect((cause) =>\n Effect.sync(() => reportProvisioningTelemetryFailure(\"defect\", smartAccount, cause)),\n ),\n ),\n );\n}\n\nfunction reportProvisioningTelemetryFailure(\n kind: \"error\" | \"defect\",\n smartAccount: SmartAccount,\n cause: unknown,\n): void {\n if (!isProvisioningTelemetryDebugEnabled()) return;\n globalThis.console?.warn?.(\"[capxul] provisioning telemetry dropped\", {\n kind,\n safeAddress: smartAccount.smartAccountAddress,\n cause,\n });\n}\n\nfunction isProvisioningTelemetryDebugEnabled(): boolean {\n const processLike = globalThis as {\n readonly process?: { readonly env?: Record<string, string | undefined> };\n };\n return processLike.process?.env?.CAPXUL_DEBUG_TELEMETRY === \"1\";\n}\n","import type { WireObservationContext } from \"@capxul/wire/observation-context\";\n\nconst INVOCATION_OBSERVATION = Symbol(\"capxul.invocation-observation\");\nconst FAILURE_INVOCATION_SNAPSHOT = Symbol(\"capxul.failure-invocation-snapshot\");\n\nexport interface InvocationObservationSnapshot {\n readonly active: boolean;\n /** `undefined` is meaningful: the resolver returned no context at call start. */\n readonly context?: WireObservationContext;\n}\n\ntype InvocationObservationCarrier = {\n readonly [INVOCATION_OBSERVATION]?: InvocationObservationSnapshot;\n};\n\n/** @internal Attach one immutable, non-wire invocation snapshot to an SDK-owned object. */\nexport function attachInvocationObservation<T extends object>(\n target: T,\n source: InvocationObservationSnapshot,\n): T {\n const snapshot = Object.freeze(\n source.context === undefined\n ? { active: source.active }\n : { active: source.active, context: Object.freeze({ ...source.context }) },\n );\n Object.defineProperty(target, INVOCATION_OBSERVATION, {\n configurable: false,\n enumerable: false,\n value: snapshot,\n writable: false,\n });\n return target;\n}\n\n/** @internal Read the snapshot without exposing its symbol or adding a wire field. */\nexport function readInvocationObservation(\n source: unknown,\n): InvocationObservationSnapshot | undefined {\n if (typeof source !== \"object\" || source === null) return undefined;\n return (source as InvocationObservationCarrier)[INVOCATION_OBSERVATION];\n}\n\n/** @internal Carry a snapshot across an SDK adapter projection without resolving again. */\nexport function copyInvocationObservation<T extends object>(source: unknown, target: T): T {\n const snapshot = readInvocationObservation(source);\n return snapshot === undefined ? target : attachInvocationObservation(target, snapshot);\n}\n\n/** @internal Carry the public call-start delivery decision with its failure envelope. */\nexport function markFailureInvocationSnapshot<T extends object>(\n failure: T,\n snapshot: InvocationObservationSnapshot,\n): T {\n Object.defineProperty(failure, FAILURE_INVOCATION_SNAPSHOT, {\n configurable: false,\n enumerable: false,\n value: Object.freeze(snapshot),\n writable: false,\n });\n return failure;\n}\n\n/** @internal Read the call-start delivery decision; undefined means a direct adapter call. */\nexport function readFailureInvocationSnapshot(\n failure: unknown,\n): InvocationObservationSnapshot | undefined {\n if (typeof failure !== \"object\" || failure === null) return undefined;\n const snapshot = (failure as { readonly [FAILURE_INVOCATION_SNAPSHOT]?: unknown })[\n FAILURE_INVOCATION_SNAPSHOT\n ];\n return typeof snapshot === \"object\" && snapshot !== null && \"active\" in snapshot\n ? (snapshot as InvocationObservationSnapshot)\n : undefined;\n}\n","import { Effect, type Tracer } from \"effect\";\n\nimport type { CapxulErrorCode } from \"@capxul/errors\";\n\nimport type { IdentityTransition } from \"./shell.ts\";\n\nconst definedEntries = (\n values: Readonly<Record<string, unknown>>,\n): Readonly<Record<string, unknown>> =>\n Object.fromEntries(Object.entries(values).filter((entry) => entry[1] !== undefined));\n\nconst SAFE_ENGINEERING_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u;\n\nexport const safeEngineeringIdentifier = (value: string | undefined): string | undefined =>\n value !== undefined && SAFE_ENGINEERING_ID.test(value) ? value : undefined;\n\nexport const portFailureOutcome = (code: CapxulErrorCode): \"failed\" | \"cancelled\" =>\n code === \"CANCELLED\" ? \"cancelled\" : \"failed\";\n\nexport function formatTraceparent(span: Tracer.AnySpan): string | undefined {\n const traceId = span.traceId.toLowerCase();\n const spanId = span.spanId.toLowerCase();\n if (!/^[0-9a-f]{32}$/u.test(traceId) || !/^[0-9a-f]{16}$/u.test(spanId)) return undefined;\n if (/^0+$/u.test(traceId) || /^0+$/u.test(spanId)) return undefined;\n return `00-${traceId}-${spanId}-${span.sampled ? \"01\" : \"00\"}`;\n}\n\n/** Canonical, bounded fields for the one wide engineering log owned by P3. */\nexport const transitionLogFields = (\n record: IdentityTransition,\n): Readonly<Record<string, unknown>> => {\n const { correlation_id, journey_id, ...canonical } = record;\n const safeCorrelation = safeEngineeringIdentifier(correlation_id);\n const safeJourney = safeEngineeringIdentifier(journey_id);\n return definedEntries({\n ...canonical,\n ...(safeCorrelation === undefined ? {} : { correlation_id: safeCorrelation }),\n ...(safeJourney === undefined ? {} : { journey_id: safeJourney }),\n });\n};\n\n/** The shell span owns transition/refusal classification and no other seam's fields. */\nexport const transitionSpanFields = (\n record: IdentityTransition,\n): Readonly<Record<string, unknown>> => {\n if (record.outcome === \"applied\") {\n return {\n machine: record.machine,\n from: record.from,\n event: record.event,\n to: record.to,\n };\n }\n return {\n machine: record.machine,\n state: record.state,\n event: record.event,\n ...(record.outcome === \"refused\" ? { refused: record.refusal_code } : {}),\n };\n};\n\n/**\n * Emit engineering telemetry as an isolated side effect. Exporter/logger defects\n * can never change the actor's transition, reply, or P3 observer cardinality.\n */\nexport const logIdentityTransition = (record: IdentityTransition): Effect.Effect<void> =>\n (record.outcome === \"applied\"\n ? Effect.logInfo(\"identity.transition\")\n : record.outcome === \"failed\"\n ? Effect.logError(\"identity.transition\")\n : Effect.logWarning(\"identity.transition\")\n ).pipe(\n Effect.annotateLogs(transitionLogFields(record)),\n Effect.andThen(\n record.outcome === \"applied\"\n ? Effect.void\n : Effect.fail({\n code: record.outcome === \"refused\" ? record.refusal_code : record.error_code,\n }),\n ),\n Effect.withSpan(\"identity.transition\"),\n Effect.annotateSpans(transitionSpanFields(record)),\n Effect.catchCause(() => Effect.void),\n );\n","/* oxlint-disable eslint/complexity -- the actor loop is the closed public/private/lane-exit envelope matrix. */\nimport { Deferred, Effect, Fiber, Queue, Ref, Scope, Tracer } from \"effect\";\nimport type { CapxulErrorCode, Failure } from \"@capxul/errors\";\n\nimport { copyInvocationObservation } from \"../../internal/invocation-observation.ts\";\nimport { logIdentityTransition } from \"./telemetry.ts\";\n\nexport type Outcome<S, Reason extends CapxulErrorCode = CapxulErrorCode> =\n | { readonly next: S }\n | { readonly refused: Reason };\n\nconst INVOCATION_PARENT_SPAN = Symbol(\"@capxul/sdk/identity-invocation-parent-span\");\n\nexport interface InvocationControls {\n readonly signal?: AbortSignal;\n readonly timeoutMs?: number;\n readonly deadlineMs?: number;\n readonly correlation_id?: string;\n readonly journey_id?: string;\n /** @internal Opaque in-process trace parent; symbols never enter wire or P3 records. */\n readonly [INVOCATION_PARENT_SPAN]?: Tracer.AnySpan;\n}\n\nexport function carryInvocationParentSpan(\n controls: InvocationControls | undefined,\n parent: Tracer.AnySpan,\n): InvocationControls {\n return { ...controls, [INVOCATION_PARENT_SPAN]: parent };\n}\n\nexport function withInvocationParentSpan<A, E, R>(\n effect: Effect.Effect<A, E, R>,\n controls: InvocationControls | undefined,\n): Effect.Effect<A, E, R> {\n const parent = controls?.[INVOCATION_PARENT_SPAN];\n return parent === undefined ? effect : effect.pipe(Effect.withParentSpan(parent));\n}\n\ntype RecordBase = {\n readonly machine: string;\n readonly event: string;\n readonly slot: string;\n readonly epoch: number;\n readonly duration_ms: number;\n readonly correlation_id?: string;\n readonly journey_id?: string;\n};\n\nexport type IdentityTransition =\n | (RecordBase & {\n readonly outcome: \"applied\";\n readonly from: string;\n readonly to: string;\n readonly refusal_code?: never;\n readonly error_code?: never;\n })\n | (RecordBase & {\n readonly outcome: \"refused\";\n readonly state: string;\n readonly refusal_code: CapxulErrorCode;\n readonly error_code?: never;\n })\n | (RecordBase & {\n readonly outcome: \"failed\" | \"cancelled\";\n readonly state: string;\n readonly error_code: CapxulErrorCode;\n readonly refusal_code?: never;\n });\n\nexport class ActorFailure<Reason extends CapxulErrorCode> extends Error {\n readonly _tag = \"ActorFailure\";\n\n constructor(\n readonly reason: Reason,\n readonly machine: string,\n readonly state: string,\n readonly event: string,\n readonly details?: Readonly<Record<string, unknown>>,\n ) {\n super(`${machine}:${state}:${event} ${reason}`);\n this.name = \"ActorFailure\";\n }\n}\n\ninterface Tagged {\n readonly _tag: string;\n}\n\ninterface Cursor {\n readonly slot: string;\n readonly epoch: number;\n readonly event: string;\n readonly startedAt: number;\n readonly invocation: InvocationControls;\n}\n\ninterface LaneExit {\n readonly _tag: \"~lane/exit\";\n readonly failure?: Failure | undefined;\n readonly defect?: unknown;\n}\n\nexport interface Work<Priv extends Tagged, R> {\n readonly slot: string;\n /** Closed engineering-telemetry owner name; never a request argument or identity value. */\n readonly port: string;\n readonly run: (\n send: (event: Priv) => Effect.Effect<void>,\n controls: InvocationControls,\n ) => Effect.Effect<void, Failure, R>;\n}\n\nexport interface Spec<\n S,\n Pub extends Tagged,\n Priv extends Tagged,\n Reason extends CapxulErrorCode,\n R,\n> {\n readonly machine: string;\n readonly initial: S;\n readonly label: (state: S) => string;\n readonly slot: (event: Pub | Priv) => string;\n readonly transition: (state: S, event: Pub | Priv) => Outcome<S, Reason>;\n readonly work?: (args: { readonly state: S; readonly event: Pub }) => Work<Priv, R> | undefined;\n /** Public events such as Reset invalidate named running slots without making unrelated slots stale. */\n readonly invalidates?: (event: Pub) => readonly string[];\n /** Map shell-owned timeout/cancel/defect exits back into domain state. */\n readonly recoverFailure?: (state: S, event: string, failure: Failure) => Priv | undefined;\n}\n\nexport interface Actor<S, Pub, Reason extends CapxulErrorCode> {\n readonly ask: (\n event: Pub,\n controls?: InvocationControls,\n ) => Effect.Effect<S, ActorFailure<Reason | CapxulErrorCode>>;\n readonly tell: (\n event: Pub,\n controls?: InvocationControls,\n ) => Effect.Effect<void, ActorFailure<Reason | CapxulErrorCode>>;\n readonly snapshot: () => S;\n readonly subscribe: (observer: (state: S) => void) => () => void;\n readonly subscribeTransitions: (observer: (record: IdentityTransition) => void) => () => void;\n}\n\ninterface Envelope<S, Pub extends Tagged, Priv extends Tagged, Reason extends CapxulErrorCode> {\n readonly event: Pub | Priv | LaneExit;\n readonly reply: Deferred.Deferred<S, ActorFailure<Reason | CapxulErrorCode>> | null;\n readonly origin: Cursor | null;\n readonly invocation: InvocationControls;\n readonly startedAt: number;\n}\n\nexport interface BootOptions {\n readonly onTransition?: (record: IdentityTransition) => void;\n readonly onDefect?: (defect: unknown) => void;\n}\n\nconst duration = (startedAt: number): number => Math.max(0, Date.now() - startedAt);\n\nconst failReply = <S, Reason extends CapxulErrorCode>(\n reply: Deferred.Deferred<S, ActorFailure<Reason>> | null,\n failure: ActorFailure<Reason>,\n) => (reply === null ? Effect.void : Effect.asVoid(Deferred.fail(reply, failure)));\n\nconst withCarriage = (\n controls: InvocationControls,\n): Pick<IdentityTransition, \"correlation_id\" | \"journey_id\"> => ({\n ...(controls.correlation_id === undefined ? {} : { correlation_id: controls.correlation_id }),\n ...(controls.journey_id === undefined ? {} : { journey_id: controls.journey_id }),\n});\n\nconst timeoutFailure: Failure = { code: \"PROVIDER_ERROR\", message: \"Identity work timed out\" };\nconst cancelledFailure: Failure = { code: \"CANCELLED\", message: \"Identity work cancelled\" };\n\nconst abort = (signal: AbortSignal): Effect.Effect<never, Failure> =>\n signal.aborted\n ? Effect.fail(cancelledFailure)\n : Effect.callback<never, Failure>((resume) => {\n const onAbort = () => resume(Effect.fail(cancelledFailure));\n signal.addEventListener(\"abort\", onAbort, { once: true });\n return Effect.sync(() => signal.removeEventListener(\"abort\", onAbort));\n });\n\nconst control = <A, R>(\n effect: Effect.Effect<A, Failure, R>,\n controls: InvocationControls,\n): Effect.Effect<A, Failure, R> => {\n let controlled = effect;\n const deadlineDelay =\n controls.deadlineMs === undefined ? undefined : Math.max(0, controls.deadlineMs - Date.now());\n const timeoutMs =\n controls.timeoutMs === undefined\n ? deadlineDelay\n : deadlineDelay === undefined\n ? controls.timeoutMs\n : Math.min(controls.timeoutMs, deadlineDelay);\n if (timeoutMs !== undefined) {\n controlled = controlled.pipe(\n Effect.timeoutOrElse({\n duration: `${timeoutMs} millis`,\n orElse: () => Effect.fail(timeoutFailure),\n }),\n );\n }\n if (controls.signal !== undefined)\n controlled = Effect.raceFirst(controlled, abort(controls.signal));\n return controlled;\n};\n\nexport const boot = <S, Pub extends Tagged, Priv extends Tagged, Reason extends CapxulErrorCode, R>(\n spec: Spec<S, Pub, Priv, Reason, R>,\n options: BootOptions = {},\n): Effect.Effect<Actor<S, Pub, Reason>, never, R | Scope.Scope> =>\n Effect.gen(function* () {\n type FailureReason = Reason | CapxulErrorCode;\n type Env = Envelope<S, Pub, Priv, Reason>;\n type Slot = {\n readonly fiber: Fiber.Fiber<void>;\n readonly reply: Deferred.Deferred<S, ActorFailure<FailureReason>>;\n readonly cursor: Cursor;\n };\n\n const mailbox = yield* Queue.unbounded<Env>();\n const cell = yield* Ref.make(spec.initial);\n const slotEpochs = new Map<string, number>();\n const slots = new Map<string, Slot>();\n const stateObservers = new Set<(state: S) => void>();\n const transitionObservers = new Set<(record: IdentityTransition) => void>();\n let bootTransitionObserver = options.onTransition;\n let stopped = false;\n\n const defect = (cause: unknown) => {\n try {\n options.onDefect?.(cause);\n } catch {\n // A defect reporter is the last isolation boundary and cannot own actor truth.\n }\n };\n\n const emit = (record: IdentityTransition): Effect.Effect<void> =>\n Effect.sync(() => {\n if (bootTransitionObserver !== undefined) {\n try {\n bootTransitionObserver(record);\n } catch (cause) {\n bootTransitionObserver = undefined;\n defect(cause);\n }\n }\n for (const observer of transitionObservers) {\n try {\n observer(record);\n } catch (cause) {\n transitionObservers.delete(observer);\n defect(cause);\n }\n }\n }).pipe(Effect.andThen(logIdentityTransition(record)));\n\n const notify = (state: S) => {\n for (const observer of stateObservers) {\n try {\n observer(state);\n } catch (cause) {\n stateObservers.delete(observer);\n defect(cause);\n }\n }\n };\n\n const makeFailure = (\n state: S,\n event: Tagged,\n reason: FailureReason,\n details?: Readonly<Record<string, unknown>>,\n ) => new ActorFailure(reason, spec.machine, spec.label(state), event._tag, details);\n\n const nonApplied = (\n state: S,\n event: Tagged,\n reason: CapxulErrorCode,\n outcome: \"refused\" | \"failed\" | \"cancelled\",\n env: Pick<Env, \"origin\" | \"invocation\" | \"startedAt\">,\n ): IdentityTransition => {\n const slot = env.origin?.slot ?? spec.slot(event as Pub | Priv);\n return copyInvocationObservation(env.invocation, {\n machine: spec.machine,\n state: spec.label(state),\n event: event._tag,\n slot,\n epoch: env.origin?.epoch ?? slotEpochs.get(slot) ?? 0,\n outcome,\n duration_ms: duration(env.startedAt),\n ...withCarriage(env.invocation),\n ...(outcome === \"refused\" ? { refusal_code: reason } : { error_code: reason }),\n } as IdentityTransition);\n };\n\n const applied = (\n from: S,\n to: S,\n event: Tagged,\n slot: string,\n epoch: number,\n env: Pick<Env, \"invocation\" | \"startedAt\">,\n ): IdentityTransition =>\n copyInvocationObservation(env.invocation, {\n machine: spec.machine,\n from: spec.label(from),\n event: event._tag,\n to: spec.label(to),\n slot,\n epoch,\n outcome: \"applied\",\n duration_ms: duration(env.startedAt),\n ...withCarriage(env.invocation),\n });\n\n const finish = (cursor: Cursor, state: S) => {\n const held = slots.get(cursor.slot);\n if (held === undefined || held.cursor !== cursor) return Effect.void;\n slots.delete(cursor.slot);\n return Effect.asVoid(Deferred.succeed(held.reply, state));\n };\n\n const recoverFailure = (state: S, cursor: Cursor, failure: Failure) => {\n const event = spec.recoverFailure?.(state, cursor.event, failure);\n if (event === undefined) return Effect.succeed(state);\n const outcome = spec.transition(state, event);\n if (\"refused\" in outcome) return Effect.succeed(state);\n return Ref.set(cell, outcome.next).pipe(\n Effect.tap(() => {\n const record = applied(state, outcome.next, event, cursor.slot, cursor.epoch, {\n invocation: cursor.invocation,\n startedAt: cursor.startedAt,\n });\n return emit(record).pipe(\n Effect.andThen(\n Effect.sync(() => {\n notify(outcome.next);\n }),\n ),\n );\n }),\n Effect.as(outcome.next),\n );\n };\n\n // The shell owns the closed envelope matrix (public/private/lane-exit,\n // refusal/failure/cancellation, work start/finish); splitting it would hide\n // the atomic epoch and reply invariants across helpers.\n const step = (env: Env): Effect.Effect<void, never, R> =>\n Effect.gen(function* () {\n const state = yield* Ref.get(cell);\n\n if (env.origin !== null && (slotEpochs.get(env.origin.slot) ?? 0) !== env.origin.epoch) {\n const held = slots.get(env.origin.slot);\n if (held === undefined || held.cursor !== env.origin) return;\n slots.delete(env.origin.slot);\n const event = { _tag: env.origin.event };\n yield* emit(nonApplied(state, event, \"STALE_EPOCH\", \"refused\", env));\n yield* failReply(held.reply, makeFailure(state, event, \"STALE_EPOCH\"));\n return;\n }\n\n if (env.origin !== null && env.event._tag === \"~lane/exit\") {\n const exit = env.event as LaneExit;\n const held = slots.get(env.origin.slot);\n if (held === undefined || held.cursor !== env.origin) return;\n if (exit.defect !== undefined) {\n slots.delete(env.origin.slot);\n defect(exit.defect);\n const event = { _tag: env.origin.event };\n const failedState = yield* recoverFailure(state, env.origin, {\n code: \"WORK_DIED\",\n message: \"Identity work died\",\n });\n yield* emit(nonApplied(failedState, event, \"WORK_DIED\", \"failed\", env));\n yield* failReply(held.reply, makeFailure(failedState, event, \"WORK_DIED\"));\n return;\n }\n if (exit.failure !== undefined) {\n slots.delete(env.origin.slot);\n const outcome = exit.failure.code === \"CANCELLED\" ? \"cancelled\" : \"failed\";\n const event = { _tag: env.origin.event };\n const failedState =\n exit.failure === timeoutFailure || exit.failure === cancelledFailure\n ? yield* recoverFailure(state, env.origin, exit.failure)\n : state;\n yield* emit(nonApplied(failedState, event, exit.failure.code, outcome, env));\n const details = exit.failure === timeoutFailure ? { reason: \"timeout\" } : undefined;\n yield* failReply(\n held.reply,\n makeFailure(failedState, event, exit.failure.code, details),\n );\n return;\n }\n yield* finish(env.origin, state);\n return;\n }\n\n const outcome = spec.transition(state, env.event as Pub | Priv);\n if (\"refused\" in outcome) {\n yield* emit(nonApplied(state, env.event, outcome.refused, \"refused\", env));\n yield* failReply(env.reply, makeFailure(state, env.event, outcome.refused));\n return;\n }\n\n const next = outcome.next;\n yield* Ref.set(cell, next);\n const emitApplied = (slot: string, epoch: number) =>\n emit(applied(state, next, env.event, slot, epoch, env));\n\n if (env.origin !== null) {\n yield* emitApplied(env.origin.slot, env.origin.epoch);\n notify(next);\n return;\n }\n\n for (const slot of spec.invalidates?.(env.event as Pub) ?? []) {\n if (!slots.has(slot)) continue;\n slotEpochs.set(slot, (slotEpochs.get(slot) ?? 0) + 1);\n }\n\n const work =\n env.reply === null ? undefined : spec.work?.({ state: next, event: env.event as Pub });\n if (work === undefined || env.reply === null) {\n const slot = spec.slot(env.event as Pub);\n yield* emitApplied(slot, slotEpochs.get(slot) ?? 0);\n notify(next);\n if (env.reply !== null) yield* Deferred.succeed(env.reply, next).pipe(Effect.asVoid);\n return;\n }\n\n const previous = slots.get(work.slot);\n if (previous !== undefined) {\n slots.delete(work.slot);\n yield* Fiber.interrupt(previous.fiber);\n const previousEvent = { _tag: previous.cursor.event };\n const reason =\n previous.cursor.epoch === (slotEpochs.get(work.slot) ?? 0)\n ? \"SUPERSEDED\"\n : \"STALE_EPOCH\";\n yield* emit(\n nonApplied(next, previousEvent, reason, \"refused\", {\n origin: previous.cursor,\n invocation: previous.cursor.invocation,\n startedAt: previous.cursor.startedAt,\n }),\n );\n yield* failReply(previous.reply, makeFailure(next, previousEvent, reason));\n }\n\n const epoch = (slotEpochs.get(work.slot) ?? 0) + 1;\n slotEpochs.set(work.slot, epoch);\n const cursor: Cursor = {\n slot: work.slot,\n epoch,\n event: env.event._tag,\n startedAt: env.startedAt,\n invocation: env.invocation,\n };\n yield* emitApplied(work.slot, epoch);\n notify(next);\n const send = (event: Priv) =>\n Queue.offer(mailbox, {\n event,\n reply: null,\n origin: cursor,\n invocation: env.invocation,\n startedAt: env.startedAt,\n }).pipe(Effect.asVoid);\n\n const complete = (event: LaneExit) =>\n Queue.offer(mailbox, {\n event,\n reply: null,\n origin: cursor,\n invocation: env.invocation,\n startedAt: env.startedAt,\n }).pipe(Effect.asVoid);\n\n const observedWork = Effect.gen(function* () {\n yield* Effect.annotateCurrentSpan({ slot: work.slot, epoch, port: work.port });\n return yield* control(work.run(send, env.invocation), env.invocation);\n }).pipe(Effect.withSpan(`identity.work.${work.slot}`));\n // Recovery belongs outside the owner span so its Exit preserves the\n // real success, typed failure, cancellation, or defect outcome.\n const guarded = observedWork.pipe(\n Effect.matchEffect({\n onFailure: (failure) => complete({ _tag: \"~lane/exit\", failure }),\n onSuccess: () => complete({ _tag: \"~lane/exit\" }),\n }),\n Effect.catchDefect((cause) => complete({ _tag: \"~lane/exit\", defect: cause })),\n );\n const fiber = yield* Effect.forkChild(guarded, { startImmediately: true });\n slots.set(work.slot, { fiber, reply: env.reply, cursor });\n });\n\n const loop = yield* Effect.forkScoped(\n Effect.forever(\n Queue.take(mailbox).pipe(\n Effect.flatMap((env) => withInvocationParentSpan(step(env), env.invocation)),\n ),\n ),\n );\n\n yield* Effect.addFinalizer(() =>\n Effect.gen(function* () {\n stopped = true;\n yield* Fiber.interrupt(loop);\n const state = yield* Ref.get(cell);\n const outstanding = [...slots.values()];\n slots.clear();\n for (const held of outstanding) {\n yield* Fiber.interrupt(held.fiber);\n const env = {\n origin: held.cursor,\n invocation: held.cursor.invocation,\n startedAt: held.cursor.startedAt,\n };\n const event = { _tag: held.cursor.event };\n yield* emit(nonApplied(state, event, \"ACTOR_STOPPED\", \"refused\", env));\n yield* failReply(held.reply, makeFailure(state, event, \"ACTOR_STOPPED\"));\n }\n stateObservers.clear();\n transitionObservers.clear();\n yield* Queue.shutdown(mailbox);\n }),\n );\n\n const offer = (\n event: Pub,\n reply: Deferred.Deferred<S, ActorFailure<FailureReason>> | null,\n invocation: InvocationControls,\n ) => {\n const state = Ref.getUnsafe(cell);\n if (stopped) {\n const env = { origin: null, invocation, startedAt: Date.now() };\n return withInvocationParentSpan(\n emit(nonApplied(state, event, \"ACTOR_STOPPED\", \"refused\", env)).pipe(\n Effect.andThen(Effect.fail(makeFailure(state, event, \"ACTOR_STOPPED\"))),\n ),\n invocation,\n );\n }\n const startedAt = Date.now();\n return Queue.offer(mailbox, {\n event,\n reply,\n origin: null,\n invocation,\n startedAt,\n }).pipe(Effect.asVoid);\n };\n\n return {\n ask: (event, invocation = {}) =>\n Effect.gen(function* () {\n const reply = yield* Deferred.make<S, ActorFailure<FailureReason>>();\n yield* offer(event, reply, invocation);\n return yield* Deferred.await(reply);\n }),\n tell: (event, invocation = {}) => offer(event, null, invocation),\n snapshot: () => Ref.getUnsafe(cell),\n subscribe: (observer) => {\n stateObservers.add(observer);\n return () => {\n stateObservers.delete(observer);\n };\n },\n subscribeTransitions: (observer) => {\n transitionObservers.add(observer);\n return () => {\n transitionObservers.delete(observer);\n };\n },\n };\n });\n","// THE Effect→`CapxulResult` bridge (PRD #209; A2-Q1A \"ONE Promise bridge at\n// the public surface\", blueprint §2).\n//\n// Exactly one `Effect.runPromise` serves the whole public surface. Everything\n// public funnels through `runProgram`:\n//\n// 1. catch any non-`CapxulError` DEFECT and convert it to `Errors.unknown(…)`\n// so the error channel stays typed `CapxulError` end to end, and\n// 2. `Effect.result` to split success/failure into the `CapxulResult` shape\n// consumers expect.\n//\n// Two entry points sit on top of it, because the surface has two shapes of\n// caller — a program that needs a `Layer` (the auth hourglass) and a\n// signal-aware Convex call (the money/contacts/org/media/system bundles):\n//\n// toCapxulResult(program, layer) — provide, then run\n// runIfActive(signal, operation, effect) — abort-check, unwrap `publicError`,\n// then run\n//\n// #1148 note: `runIfActive` and a byte-identical twin named `runConvexIfActive`\n// used to live in `client/financial-ops.ts` and `client/actor-scope.ts` — two\n// more `Effect.runPromise` sites, each exported and imported cross-module\n// (system + media took one, org took the other). One bridge means one place\n// where a defect can escape untyped, and one place to change when the runtime\n// does.\n\nimport { Effect, Result, type Layer } from \"effect\";\n\nimport { Errors, type CapxulError } from \"@capxul/config\";\n\nimport type { CapxulResult } from \"./types\";\n\nexport type EffectPromiseRunner = <A, E>(program: Effect.Effect<A, E>) => Promise<A>;\n\n/** The one place an Effect becomes a Promise on the public surface. */\nasync function runProgram<T>(\n program: Effect.Effect<T, CapxulError, never>,\n runPromise: EffectPromiseRunner = Effect.runPromise,\n): Promise<CapxulResult<T>> {\n const result = await runPromise(\n program.pipe(\n Effect.catchDefect((defect) => Effect.fail(Errors.unknown(defect))),\n Effect.result,\n ),\n );\n if (Result.isFailure(result)) return { ok: false, error: result.failure };\n return { ok: true, value: result.success };\n}\n\nexport async function toCapxulResult<T, R>(\n program: Effect.Effect<T, CapxulError, R>,\n layer: Layer.Layer<R>,\n): Promise<CapxulResult<T>> {\n return runProgram(program.pipe(Effect.provide(layer)));\n}\n\n/**\n * Signal-aware bridge for the Convex-backed method bundles. The adapters fail\n * with `{ publicError }` rather than a bare `CapxulError`, so the wrapper is\n * unwrapped here — once — instead of at every call site.\n */\nexport async function runIfActive<T>(\n signal: AbortSignal | undefined,\n operation: string,\n effect: () => Effect.Effect<T, { readonly publicError: CapxulError }>,\n runPromise: EffectPromiseRunner = Effect.runPromise,\n): Promise<CapxulResult<T>> {\n if (signal?.aborted === true) {\n return { ok: false, error: Errors.cancelled({ operation }) };\n }\n const program = effect().pipe(Effect.mapError((error) => error.publicError));\n const controlled =\n signal === undefined\n ? program\n : Effect.raceFirst(\n program,\n Effect.callback<never, CapxulError>((resume) => {\n if (signal.aborted) {\n resume(Effect.fail(Errors.cancelled({ operation })));\n return Effect.void;\n }\n const onAbort = () => resume(Effect.fail(Errors.cancelled({ operation })));\n signal.addEventListener(\"abort\", onAbort, { once: true });\n return Effect.sync(() => signal.removeEventListener(\"abort\", onAbort));\n }),\n );\n return runProgram(controlled, runPromise);\n}\n","// Reading the live identity actor snapshot, for the consumer-facing method\n// bundles in `packages/sdk/src/surface/*`.\n//\n// #1148 (A2-Q1A): this module also carried `runPortEffect`, a THIRD\n// Effect→`CapxulResult` bridge. It did the same job as `runIfActive` minus the\n// abort check — and, unlike the other two, it had no `catchAllDefect`, so a\n// defect from a port escaped as an unhandled rejection instead of a typed\n// `CapxulError`. It now delegates to the one bridge, which closes that gap.\n\nimport { CapxulError, Errors } from \"@capxul/config\";\nimport { EXPECTED_OPERATION_OUTCOMES, type CapxulErrorCode, type Failure } from \"@capxul/errors\";\nimport type { AuthSession } from \"@capxul/types\";\nimport { Effect } from \"effect\";\n\nimport type { IdentityActor } from \"../../flows/identity\";\nimport {\n carryInvocationParentSpan,\n withInvocationParentSpan,\n type InvocationControls,\n} from \"../../domain/machine/shell\";\nimport { portFailureOutcome, safeEngineeringIdentifier } from \"../../domain/machine/telemetry.ts\";\nimport { runIfActive, type EffectPromiseRunner } from \"../to-capxul-result\";\nimport type { CapxulResult } from \"../types\";\n\nexport type IdentityFacadeVerb =\n | \"requestCode\"\n | \"verifyCode\"\n | \"signOut\"\n | \"createOrganization\"\n | \"completePersonal\"\n | \"retry\";\n\nconst facadeOutcome = (value: unknown): \"succeeded\" | \"refused\" | \"failed\" | \"cancelled\" => {\n if (\n typeof value !== \"object\" ||\n value === null ||\n !(\"ok\" in value) ||\n (value as { readonly ok?: unknown }).ok !== false\n ) {\n return \"succeeded\";\n }\n const reason = (value as { readonly reason?: unknown }).reason;\n if (reason === \"CANCELLED\") return \"cancelled\";\n return typeof reason === \"string\" && EXPECTED_OPERATION_OUTCOMES.has(reason as CapxulErrorCode)\n ? \"refused\"\n : \"failed\";\n};\n\nconst rejectedFacadeOutcome = (cause: unknown): \"cancelled\" | \"failed\" => {\n if (cause instanceof CapxulError) return cause.code === \"CANCELLED\" ? \"cancelled\" : \"failed\";\n if (typeof cause !== \"object\" || cause === null) return \"failed\";\n const candidate = cause as {\n readonly code?: unknown;\n readonly reason?: unknown;\n readonly error?: { readonly code?: unknown };\n readonly publicError?: { readonly code?: unknown };\n };\n return candidate.code === \"CANCELLED\" ||\n candidate.reason === \"CANCELLED\" ||\n candidate.error?.code === \"CANCELLED\" ||\n candidate.publicError?.code === \"CANCELLED\"\n ? \"cancelled\"\n : \"failed\";\n};\n\nconst RESOLVED_FACADE_SPAN_FAILURE = Symbol(\"resolved facade span failure\");\n\n/** The single facade-span bridge consumed by the renderer-neutral React facade. */\nexport async function runIdentityFacade<T>(\n verb: IdentityFacadeVerb,\n controls: InvocationControls | undefined,\n run: (controls: InvocationControls) => Promise<T>,\n runPromise: <A, E>(effect: Effect.Effect<A, E>) => Promise<A> = Effect.runPromise,\n): Promise<T> {\n const correlationId = safeEngineeringIdentifier(controls?.correlation_id);\n let resolvedFailure: T | undefined;\n const operation = Effect.gen(function* () {\n const parent = yield* Effect.currentSpan;\n return yield* Effect.tryPromise({\n try: () => run(carryInvocationParentSpan(controls, parent)),\n catch: (cause) => cause,\n });\n });\n const program = operation.pipe(\n Effect.tapError((cause) =>\n Effect.annotateCurrentSpan({ outcome: rejectedFacadeOutcome(cause) }),\n ),\n Effect.flatMap((value) => {\n const outcome = facadeOutcome(value);\n return Effect.annotateCurrentSpan({ outcome }).pipe(\n Effect.andThen(\n outcome === \"failed\" || outcome === \"cancelled\"\n ? Effect.sync(() => {\n resolvedFailure = value;\n }).pipe(Effect.andThen(Effect.fail(RESOLVED_FACADE_SPAN_FAILURE)))\n : Effect.succeed(value),\n ),\n );\n }),\n Effect.withSpan(`identity.${verb}`),\n Effect.annotateSpans({\n verb,\n ...(correlationId === undefined ? {} : { correlation_id: correlationId }),\n }),\n Effect.catch((cause) =>\n cause === RESOLVED_FACADE_SPAN_FAILURE\n ? Effect.succeed(resolvedFailure as T)\n : Effect.fail(cause),\n ),\n );\n return runPromise(program);\n}\n\n/**\n * Bridge an Effect whose typed failure carries `{ publicError: CapxulError }`\n * into the `Promise<CapxulResult<T>>` shape the consumer-facing method bundles\n * return. Applies to every port that surfaces a `publicError` (smart-account,\n * identity, auth-cache, account provision/deploy).\n */\nexport async function runPortEffect<T>(\n effect: Effect.Effect<T, { readonly publicError: CapxulError }>,\n controls?: InvocationControls,\n operation = \"port\",\n runPromise: EffectPromiseRunner = Effect.runPromise,\n): Promise<CapxulResult<T>> {\n const deadlineDelay =\n controls?.deadlineMs === undefined ? undefined : Math.max(0, controls.deadlineMs - Date.now());\n const timeoutMs =\n controls?.timeoutMs === undefined\n ? deadlineDelay\n : deadlineDelay === undefined\n ? controls.timeoutMs\n : Math.min(controls.timeoutMs, deadlineDelay);\n const controlled =\n timeoutMs === undefined\n ? effect\n : effect.pipe(\n Effect.timeoutOrElse({\n duration: `${timeoutMs} millis`,\n orElse: () =>\n Effect.fail({ publicError: Errors.providerTimeout(\"sdk\", operation, timeoutMs) }),\n }),\n );\n const observed = controlled.pipe(\n Effect.tap(() => Effect.annotateCurrentSpan({ outcome: \"succeeded\" })),\n Effect.tapError((failure) => {\n const mode = failure.publicError.details?.failure_mode;\n return Effect.annotateCurrentSpan({\n outcome: portFailureOutcome(failure.publicError.code),\n failure_code: failure.publicError.code,\n ...(typeof mode === \"string\" ? { mode } : {}),\n });\n }),\n Effect.tapDefect(() =>\n Effect.annotateCurrentSpan({ outcome: \"failed\", failure_code: \"UNKNOWN\" }),\n ),\n Effect.withSpan(`identity.port.${operation}`),\n );\n return runIfActive(\n controls?.signal,\n operation,\n () => withInvocationParentSpan(observed, controls),\n runPromise,\n );\n}\n\n/** Map machine-internal failure state onto the public SDK error vocabulary. */\nexport function publicIdentityFailure(failure: Failure): CapxulError {\n return new CapxulError(failure.code === \"WORK_DIED\" ? \"UNKNOWN\" : failure.code, failure.message, {\n ...(failure.mode === undefined ? {} : { details: { failure_mode: failure.mode } }),\n layer: \"identity\",\n });\n}\n\n/** The session carried by the actor's current snapshot, or `null`. */\nexport function sessionFromActor(actor: IdentityActor): AuthSession | null {\n return actor.authSession();\n}\n","// Account-readiness substrate — the `client.account.getStatus` readiness\n// ladder expressed as an Effect program that resolves a single Context tag\n// (PRD #209 hourglass collapse, slice 5).\n//\n// Mirrors the slice-2 `capxul-deps.ts` shape:\n//\n// 1. `AccountDeps` — the dependency bundle one Context tag carries.\n// A structural subset of `MakeAccountMethodsDeps`\n// (`account.ts`) — exactly the deps the\n// `getStatus` ladder reads.\n// 2. `AccountDepsTag` — the single tag the account atom + the public\n// `getStatus` method (via `toCapxulResult`)\n// resolve.\n// 3. `accountDepsLayer` — wraps a bundle as `Layer<AccountDepsTag>`.\n// 4. `accountStatusProgram` — `account.getStatus` as a single\n// `Effect<AccountStatus, CapxulError,\n// AccountDepsTag>`.\n//\n// `statusFromAccount` + `currentSession` live here (the `getStatus` helpers);\n// `account.ts` imports them back so `account-deps.ts` depends on `account.ts`\n// for the `AccountStatus` TYPE only (erased at runtime → no value cycle).\n//\n// NOT re-exported from the `@capxul/sdk` main barrel — this module is\n// workspace-internal (imported by sibling `src/client/*` modules only) and\n// has NO published export subpath. #1145: the `@capxul/sdk/react-substrate`\n// subpath these comments used to cite never existed.\n\nimport { Context, Effect, Result, Layer } from \"effect\";\n\nimport { Errors, isCapxulError, type CapxulError } from \"@capxul/config\";\nimport type { AuthSession, SmartAccount } from \"@capxul/types\";\n\nimport type { IdentityActor } from \"../flows/identity\";\nimport type { AuthCachePort } from \"../ports/auth-cache\";\nimport type { IdentityPort } from \"../ports/identity\";\nimport { sessionFromActor } from \"./_shared/effect-actor-bridge\";\nimport type { SmartAccountPort } from \"../ports/smart-account\";\nimport type { AccountRequirement } from \"./account-providers\";\nimport type { CapxulSigner } from \"../signer\";\nimport type { AccountStatus } from \"./account\";\n\n/**\n * The dependency bundle a single `Context.Service` carries (PRD #209). A\n * structural subset of `MakeAccountMethodsDeps` — exactly the deps the\n * `getStatus` ladder reads — so a `MakeAccountMethodsDeps` value is assignable\n * wherever an `AccountDeps` is expected.\n */\nexport interface AccountDeps {\n readonly actor: IdentityActor;\n readonly authCache?: AuthCachePort;\n readonly identityPort: IdentityPort;\n readonly smartAccountPort: SmartAccountPort;\n readonly chainId: number;\n readonly requirement: AccountRequirement;\n readonly signer?: CapxulSigner;\n}\n\n/** The single Context tag the account atom + `account.getStatus` resolve. */\nexport class AccountDepsTag extends Context.Service<AccountDepsTag, AccountDeps>()(\n \"@capxul/sdk/AccountDeps\",\n) {}\n\n/** Wrap a bundle as the `Layer<AccountDepsTag>` the React provider consumes. */\nexport function accountDepsLayer(deps: AccountDeps): Layer.Layer<AccountDepsTag> {\n return Layer.succeed(AccountDepsTag, deps);\n}\n\n/**\n * `account.getStatus` as a single Effect requiring ONLY `AccountDepsTag`.\n * Faithful transcription of the current public method body (`account.ts`):\n * resolve the session (actor first, then the resume-path `authCache`), then\n * walk the readiness ladder. The `SmartAccountPort` failure narrows to its\n * `publicError`; a consumer `AccountProvider.getAddress` rejection becomes a\n * `providerError` (defending the public `CapxulResult` contract).\n */\nexport const accountStatusProgram: Effect.Effect<AccountStatus, CapxulError, AccountDepsTag> =\n Effect.gen(function* () {\n const deps = yield* AccountDepsTag;\n const session = yield* Effect.promise(() => currentSession(deps.actor, deps.authCache));\n if (session === null) {\n return { status: \"notAuthenticated\" };\n }\n\n const current = yield* deps.smartAccountPort\n .loadByAuthUserId(session.authUserId)\n .pipe(Effect.mapError((failure) => failure.publicError));\n if (current !== null) {\n return statusFromAccount(current, deps.requirement);\n }\n\n if (deps.requirement === \"none\") {\n return {\n status: \"accountReady\",\n requirement: deps.requirement,\n account: null,\n deployment: { status: \"counterfactual\" },\n };\n }\n\n const signer = deps.signer;\n if (signer === undefined) {\n return { status: \"accountRequired\", requirement: deps.requirement, chainId: deps.chainId };\n }\n // Defend the public `CapxulResult` contract — a consumer-supplied signer\n // could throw. A rejection here would otherwise propagate up through\n // `client.account.getStatus()` and break it. Preserve an already-classified\n // CapxulError (e.g. the signer's `no-secure-context` probe) so its\n // `failure_mode` survives instead of being flattened into a bare\n // `getAddress` provider error.\n const signerAddress = yield* Effect.tryPromise({\n try: () => signer.getAddress(),\n catch: (cause) =>\n isCapxulError(cause) ? cause : Errors.providerError(\"signer\", \"getAddress\", cause),\n });\n return {\n status: \"accountProviderReady\",\n requirement: deps.requirement,\n chainId: deps.chainId,\n source: signer.source,\n signerAddress,\n };\n });\n\n/**\n * Resume-path session resolution. Consults the actor first; if the actor has\n * no session (e.g. page refresh before any sign-in event), reads\n * `authCache.getSession`. `AuthCacheError` is non-fatal at this read point —\n * treat as \"no session\" and let the consumer's `auth.signIn` path resolve.\n */\nexport async function currentSession(\n actor: IdentityActor,\n authCache: AuthCachePort | undefined,\n): Promise<AuthSession | null> {\n const fromActor = sessionFromActor(actor);\n if (fromActor !== null) return fromActor;\n if (authCache === undefined) return null;\n const cached = await Effect.runPromise(Effect.result(authCache.getSession));\n if (Result.isSuccess(cached)) {\n if (cached.success !== null && typeof actor.restoreAuthSession === \"function\") {\n const restored = await Effect.runPromise(\n Effect.result(actor.restoreAuthSession(cached.success)),\n );\n if (Result.isFailure(restored)) return null;\n }\n return cached.success;\n }\n return null;\n}\n\n/** Map a backend `SmartAccount` row onto the readiness `AccountStatus`. */\nfunction statusFromAccount(account: SmartAccount, requirement: AccountRequirement): AccountStatus {\n if (requirement === \"deployed\") {\n if (account.deployedAt === null) {\n return {\n status: \"accountPrepared\",\n requirement,\n account,\n deployment: { status: \"counterfactual\" },\n };\n }\n return {\n status: \"accountReady\",\n requirement,\n account,\n deployment: { status: \"deployed\", deployedAt: account.deployedAt },\n };\n }\n return {\n status: \"accountReady\",\n requirement,\n account,\n deployment:\n account.deployedAt === null\n ? { status: \"counterfactual\" }\n : { status: \"deployed\", deployedAt: account.deployedAt },\n };\n}\n","import type { CapxulError } from \"@capxul/config\";\n\nimport type { AccountStatus } from \"./account\";\nimport type { AccountRequirement } from \"./account-providers\";\n\nexport type ProvisioningFailureStep = \"wallet\" | \"identity\" | \"provision\" | \"deploy\";\n\nexport type ProvisioningPhase =\n | { readonly status: \"idle\" }\n | { readonly status: \"wallet\" }\n | { readonly status: \"identity\" }\n | { readonly status: \"provision\" }\n | { readonly status: \"deploy\" }\n | { readonly status: \"ready\" }\n | {\n readonly status: \"failed\";\n readonly at: ProvisioningFailureStep;\n readonly error: CapxulError;\n };\n\nexport function isActiveProvisioningPhase(phase: ProvisioningPhase): boolean {\n return (\n phase.status === \"wallet\" ||\n phase.status === \"identity\" ||\n phase.status === \"provision\" ||\n phase.status === \"deploy\"\n );\n}\n\nexport function isRequirementMet(status: AccountStatus, requirement: AccountRequirement): boolean {\n if (requirement === \"none\") return status.status !== \"notAuthenticated\";\n if (status.status !== \"accountReady\") return false;\n return requirement !== \"deployed\" || status.deployment.status === \"deployed\";\n}\n\nexport type AccountSetupStep = \"connecting\" | \"confirmingIdentity\" | \"registering\" | \"activating\";\n\nexport type AccountLifecycle =\n | { readonly status: \"loading\" }\n | { readonly status: \"settingUp\"; readonly step: AccountSetupStep }\n | { readonly status: \"ready\"; readonly accountId: string; readonly canTransact: boolean }\n | { readonly status: \"failed\"; readonly at: AccountSetupStep; readonly error: CapxulError };\n\nexport interface MapAccountLifecycleInput {\n readonly status: AccountStatus;\n readonly phase: ProvisioningPhase;\n readonly requirement: AccountRequirement;\n readonly accountId?: string;\n}\n\n// PRD #462: the \"binding\" provisioning step no longer exists — the address\n// derives from the email alone. \"confirmingIdentity\" stays in the public\n// `AccountSetupStep` vocabulary (contract-stable) but is no longer produced.\nexport function mapProvisioningFailureStep(step: ProvisioningFailureStep): AccountSetupStep {\n switch (step) {\n case \"wallet\":\n return \"connecting\";\n case \"identity\":\n return \"registering\";\n case \"provision\":\n case \"deploy\":\n return \"activating\";\n }\n}\n\nexport function mapProvisioningPhaseToSetupStep(phase: ProvisioningPhase): AccountSetupStep {\n switch (phase.status) {\n case \"idle\":\n case \"wallet\":\n return \"connecting\";\n case \"identity\":\n return \"registering\";\n case \"provision\":\n case \"deploy\":\n return \"activating\";\n case \"ready\":\n case \"failed\":\n return \"connecting\";\n }\n}\n\nexport function isSettingUpLifecycle(lifecycle: AccountLifecycle): boolean {\n return lifecycle.status === \"settingUp\";\n}\n\nfunction readyLifecycle(status: AccountStatus, accountId: string): AccountLifecycle {\n const canTransact = status.status === \"accountReady\" && status.deployment.status === \"deployed\";\n return { status: \"ready\", accountId, canTransact };\n}\n\nexport function mapAccountLifecycle(input: MapAccountLifecycleInput): AccountLifecycle {\n const { status, phase, requirement, accountId } = input;\n\n if (status.status === \"notAuthenticated\") {\n return { status: \"loading\" };\n }\n\n if (phase.status === \"failed\") {\n return {\n status: \"failed\",\n at: mapProvisioningFailureStep(phase.at),\n error: phase.error,\n };\n }\n\n if (isRequirementMet(status, requirement) || phase.status === \"ready\") {\n if (accountId === undefined) {\n return { status: \"loading\" };\n }\n return readyLifecycle(status, accountId);\n }\n\n if (isActiveProvisioningPhase(phase) || phase.status === \"idle\") {\n return {\n status: \"settingUp\",\n step: mapProvisioningPhaseToSetupStep(phase),\n };\n }\n\n return { status: \"loading\" };\n}\n","// Brand schemas for `@capxul/wire` envelopes. Per Decision 2 of issue #119\n// (2b parity required), each schema MUST validate as strictly as its `to*`\n// counterpart in `@capxul/types`. We achieve mechanical parity by importing\n// the regex/range constants from `@capxul/types` and reusing them inside\n// `Schema.filter(...)` refinements that narrow to the local `Brand<T, B>`\n// types — so decoded values are typed as `AppId` / `ChainId` / etc. directly,\n// no cast at the consumer site.\n\nimport { Schema, SchemaGetter } from \"effect\";\n\nimport {\n APP_ID_RE,\n type AppId,\n type ChainId,\n type CurrencyCode,\n BYTES32_RE,\n SUPPORTED_CURRENCY_CODES,\n type DocumentHash,\n type DurationMs,\n type EpochMs,\n type SessionToken,\n} from \"@capxul/types\";\n\n/**\n * `AppId` schema. Mirrors `toAppId` from `@capxul/types`:\n * `app_` + Crockford-base32 ULID (26 chars, first char in `[0-7]`).\n */\nexport const AppIdSchema: Schema.Codec<AppId, string> = Schema.String.pipe(\n Schema.refine((s): s is AppId => APP_ID_RE.test(s), {\n message: \"must be app_ plus a ULID\",\n }),\n);\n\n/**\n * `ChainId` schema. Mirrors `toChainId`: positive safe integer.\n */\nexport const ChainIdSchema: Schema.Codec<ChainId, number> = Schema.Number.pipe(\n Schema.refine((n): n is ChainId => Number.isSafeInteger(n) && n > 0, {\n message: \"must be a positive safe integer\",\n }),\n);\n\n/**\n * `CurrencyCode` schema. Mirrors `toCurrencyCode`: currently supported\n * consumer-facing ISO-ish currency code set.\n */\nexport const CurrencyCodeSchema: Schema.Codec<CurrencyCode, string> = Schema.String.pipe(\n Schema.refine(\n (s): s is CurrencyCode =>\n SUPPORTED_CURRENCY_CODES.includes(s as (typeof SUPPORTED_CURRENCY_CODES)[number]),\n {\n message: \"must be a supported currency code\",\n },\n ),\n);\n\nconst DOCUMENT_HASH_HEX_RE = /^[0-9a-fA-F]{64}$/;\n\n/**\n * `DocumentHash` schema. Mirrors `toDocumentHash`: bare or 0x-prefixed bytes32,\n * normalized to lowercase 0x-prefixed form.\n */\nexport const DocumentHashSchema: Schema.Codec<DocumentHash, string> = Schema.String.pipe(\n Schema.decodeTo(Schema.String, {\n decode: SchemaGetter.transform((s) => {\n const stripped = s.startsWith(\"0x\") || s.startsWith(\"0X\") ? s.slice(2) : s;\n return DOCUMENT_HASH_HEX_RE.test(stripped) ? `0x${stripped.toLowerCase()}` : s;\n }),\n encode: SchemaGetter.transform((s) => s),\n }),\n Schema.refine((s): s is DocumentHash => BYTES32_RE.test(s), {\n message: \"must be 32 bytes of hex\",\n }),\n);\n\n/**\n * `SessionToken` schema. Mirrors `toSessionToken`: non-empty string.\n * Issuance source distinguishes SDK-handshake tokens from auth-session\n * tokens; the brand itself is opaque.\n */\nexport const SessionTokenSchema: Schema.Codec<SessionToken, string> = Schema.String.pipe(\n Schema.refine((s): s is SessionToken => s.length > 0, {\n message: \"must be a non-empty string\",\n }),\n);\n\n/**\n * `EpochMs` schema. Mirrors `toEpochMs`: non-negative safe integer.\n */\nexport const EpochMsSchema: Schema.Codec<EpochMs, number> = Schema.Number.pipe(\n Schema.refine((n): n is EpochMs => Number.isSafeInteger(n) && n >= 0, {\n message: \"must be a non-negative safe integer\",\n }),\n);\n\n/**\n * `DurationMs` schema. Mirrors `toDurationMs`: non-negative safe integer.\n */\nexport const DurationMsSchema: Schema.Codec<DurationMs, number> = Schema.Number.pipe(\n Schema.refine((n): n is DurationMs => Number.isSafeInteger(n) && n >= 0, {\n message: \"must be a non-negative safe integer\",\n }),\n);\n","// `BootstrapEnvelope` — the JSON body returned by\n// `POST /v1/client/bootstrap`. Producer: `@capxul/backend`\n// (`packages/backend/convex/credentials/http.ts`). Consumer:\n// `@capxul/sdk` (`packages/sdk/src/adapters/bootstrap/HttpBootstrapAdapter.ts`).\n//\n// Per Decision 1 of issue #119, the envelope wraps the existing\n// `BootstrapResolution`-shaped payload in `{ protocol, version, state }`\n// so version negotiation is explicit on the wire. `state` matches the\n// `BootstrapResolution` port shape at\n// `packages/sdk/src/ports/bootstrap.ts:18-31` field-for-field — no new\n// fields. Forward-compatible additions (e.g. `deployment`) belong to\n// later slices that change the port surface.\n//\n// Per Decision 2 (2b parity required), every branded field uses the\n// matching schema from `./brands.ts`, which reuses the regex/range\n// constants exported from `@capxul/types`.\n\nimport { Schema } from \"effect\";\n\nimport {\n AppIdSchema,\n ChainIdSchema,\n DurationMsSchema,\n EpochMsSchema,\n SessionTokenSchema,\n} from \"./brands\";\n\nconst PUBLIC_POSTHOG_PROJECT_TOKEN = /^phc_[A-Za-z0-9_-]{1,191}$/u;\n\nconst PostHogIngestOrigin = Schema.String.pipe(\n Schema.refine(\n (value): value is string => {\n try {\n const url = new URL(value);\n return (\n url.protocol === \"https:\" &&\n url.username.length === 0 &&\n url.password.length === 0 &&\n url.pathname === \"/\" &&\n url.search.length === 0 &&\n url.hash.length === 0 &&\n (url.hostname === \"posthog.com\" || url.hostname.endsWith(\".posthog.com\"))\n );\n } catch {\n return false;\n }\n },\n { message: \"must be a credential-free PostHog HTTPS ingest origin\" },\n ),\n);\n\nexport const EngineeringTelemetryBootstrapPolicy = Schema.Struct({\n host: PostHogIngestOrigin,\n projectToken: Schema.String.pipe(\n Schema.refine((value): value is string => PUBLIC_POSTHOG_PROJECT_TOKEN.test(value), {\n message: \"must be a public PostHog project token\",\n }),\n ),\n capxulEnv: Schema.Union([\n Schema.Literal(\"development\"),\n Schema.Literal(\"e2e\"),\n Schema.Literal(\"staging\"),\n Schema.Literal(\"production\"),\n ]),\n});\n\nexport type EngineeringTelemetryBootstrapPolicyV1 = Schema.Schema.Type<\n typeof EngineeringTelemetryBootstrapPolicy\n>;\n\n/**\n * `BootstrapEnvelope` v1.\n *\n * - `protocol`: discriminator that lets future protocols coexist on the\n * same endpoint without a wire-shape conflict.\n * - `version`: numeric version inside the protocol. Unknown versions MUST\n * fail decode with an INVALID_INPUT-class `CapxulError` at the SDK seam.\n * - `state`: the resolved bootstrap payload. Field shape matches the\n * `BootstrapResolution` port; the SDK consumer can pass `state`\n * directly (after `normalizeRuntimeUrl` on the two URL fields) into\n * the port without re-branding.\n */\nexport const BootstrapEnvelope = Schema.Struct({\n protocol: Schema.Literal(\"capxul.bootstrap\"),\n version: Schema.Literal(1),\n state: Schema.Struct({\n applicationId: AppIdSchema,\n chainId: ChainIdSchema,\n sessionToken: SessionTokenSchema,\n issuedAt: EpochMsSchema,\n expiresIn: DurationMsSchema,\n authBaseUrl: Schema.String,\n convexUrl: Schema.String,\n siteBaseUrl: Schema.String,\n openfortPublishableKey: Schema.String,\n shieldPublishableKey: Schema.String,\n engineeringTelemetry: Schema.optional(EngineeringTelemetryBootstrapPolicy),\n }),\n});\n\nexport type BootstrapEnvelopeV1 = Schema.Schema.Type<typeof BootstrapEnvelope>;\nexport type BootstrapEnvelopeEncoded = Schema.Codec.Encoded<typeof BootstrapEnvelope>;\n","// The Capxul backend function registry — the SINGLE source of truth for every\n// Convex function path the SDK (or any other client) calls (A2-Q3A, ratified\n// architecture-arc PLAN.md §\"ARTIFACT-2 R1 DECISIONS\").\n//\n// Before the re-cut these strings were scattered across 12 SDK modules — 42 of\n// them inside `client/financial-ops.ts` and `client/actor-scope.ts`, which were\n// Convex adapters hiding inside the public surface. A typo produced a runtime\n// \"function not found\" from Convex, never a build error.\n//\n// Now: this file names them once, `@capxul/sdk/src/contract/**` turns each name\n// into a typed `FunctionReference`, and `scripts/lint-wire-contract.mjs`\n// (on `verify:static` → `check:fast`) proves three things statically:\n//\n// 1. every path here resolves to a real exported function in\n// `packages/backend/convex/<module>.ts`;\n// 2. every value equals `<module key>:<export key>` — a path cannot drift\n// from where it is filed;\n// 3. no `makeFunctionReference(\"…\")` string literal survives outside this\n// registry (test doubles excepted), so nobody re-introduces a private\n// copy of the contract.\n//\n// Adding a backend function: add the export in `packages/backend/convex`, add\n// one line here under its module key, then build the typed reference in\n// `packages/sdk/src/contract/`. Skipping step two fails the gate.\n\n/**\n * Backend function paths, keyed by Convex module path then export name.\n *\n * Invariant (gate-enforced): `CAPXUL_FUNCTIONS[m][e] === \\`${m}:${e}\\``.\n */\nexport const CAPXUL_FUNCTIONS = {\n \"account/actions\": {\n faucetMint: \"account/actions:faucetMint\",\n readBalance: \"account/actions:readBalance\",\n },\n \"financialOps/actions\": {\n cancelCommitment: \"financialOps/actions:cancelCommitment\",\n claimCommitment: \"financialOps/actions:claimCommitment\",\n markCommitmentCreated: \"financialOps/actions:markCommitmentCreated\",\n markPaymentSettled: \"financialOps/actions:markPaymentSettled\",\n markWithdrawalSettled: \"financialOps/actions:markWithdrawalSettled\",\n recordOrgPayment: \"financialOps/actions:recordOrgPayment\",\n redirectCommitment: \"financialOps/actions:redirectCommitment\",\n },\n \"financialOps/addressBook\": {\n add: \"financialOps/addressBook:add\",\n get: \"financialOps/addressBook:get\",\n hide: \"financialOps/addressBook:hide\",\n label: \"financialOps/addressBook:label\",\n list: \"financialOps/addressBook:list\",\n unhide: \"financialOps/addressBook:unhide\",\n },\n \"financialOps/destinations\": {\n add: \"financialOps/destinations:add\",\n list: \"financialOps/destinations:list\",\n payout: \"financialOps/destinations:payout\",\n remove: \"financialOps/destinations:remove\",\n },\n \"financialOps/insights\": {\n history: \"financialOps/insights:history\",\n summary: \"financialOps/insights:summary\",\n },\n \"financialOps/mutations\": {\n createPayee: \"financialOps/mutations:createPayee\",\n pay: \"financialOps/mutations:pay\",\n withdraw: \"financialOps/mutations:withdraw\",\n },\n \"financialOps/payrollRoster\": {\n add: \"financialOps/payrollRoster:add\",\n list: \"financialOps/payrollRoster:list\",\n remove: \"financialOps/payrollRoster:remove\",\n run: \"financialOps/payrollRoster:run\",\n update: \"financialOps/payrollRoster:update\",\n },\n \"financialOps/queries\": {\n depositInstructions: \"financialOps/queries:depositInstructions\",\n getCommitmentRef: \"financialOps/queries:getCommitmentRef\",\n getPayee: \"financialOps/queries:getPayee\",\n getPayment: \"financialOps/queries:getPayment\",\n listPayments: \"financialOps/queries:listPayments\",\n me: \"financialOps/queries:me\",\n renderStoredDocument: \"financialOps/queries:renderStoredDocument\",\n resolveHandle: \"financialOps/queries:resolveHandle\",\n resolvePayee: \"financialOps/queries:resolvePayee\",\n verifyPaymentDocument: \"financialOps/queries:verifyPaymentDocument\",\n },\n \"financialOps/requestsInbox\": {\n approve: \"financialOps/requestsInbox:approve\",\n cancel: \"financialOps/requestsInbox:cancel\",\n decline: \"financialOps/requestsInbox:decline\",\n get: \"financialOps/requestsInbox:get\",\n inboxList: \"financialOps/requestsInbox:inboxList\",\n issue: \"financialOps/requestsInbox:issue\",\n list: \"financialOps/requestsInbox:list\",\n reconcile: \"financialOps/requestsInbox:reconcile\",\n },\n \"identity/mutations\": {\n completeOnboarding: \"identity/mutations:completeOnboarding\",\n create: \"identity/mutations:create\",\n update: \"identity/mutations:update\",\n },\n \"identity/queries\": {\n loadByAuthUserId: \"identity/queries:loadByAuthUserId\",\n usernameAvailable: \"identity/queries:usernameAvailable\",\n },\n media: {\n generateUploadUrl: \"media:generateUploadUrl\",\n setOrgLogo: \"media:setOrgLogo\",\n setProfileImage: \"media:setProfileImage\",\n },\n \"org/actions\": {\n assignRole: \"org/actions:assignRole\",\n confirmBootstrap: \"org/actions:confirmBootstrap\",\n deployOrgRoles: \"org/actions:deployOrgRoles\",\n detectAndAcceptPendingInvitations: \"org/actions:detectAndAcceptPendingInvitations\",\n inviteMember: \"org/actions:inviteMember\",\n prepareBootstrap: \"org/actions:prepareBootstrap\",\n prepareFounderAccount: \"org/actions:prepareFounderAccount\",\n readTreasury: \"org/actions:readTreasury\",\n removeMember: \"org/actions:removeMember\",\n resumeBootstrapSubmission: \"org/actions:resumeBootstrapSubmission\",\n submitBootstrap: \"org/actions:submitBootstrap\",\n },\n \"org/lifecycle\": {\n getProofReceipt: \"org/lifecycle:getProofReceipt\",\n load: \"org/lifecycle:load\",\n recordFailure: \"org/lifecycle:recordFailure\",\n retry: \"org/lifecycle:retry\",\n startOrResume: \"org/lifecycle:startOrResume\",\n },\n \"org/mutations\": {\n createOrg: \"org/mutations:createOrg\",\n resendInviteToken: \"org/mutations:resendInviteToken\",\n },\n \"org/queries\": {\n listAll: \"org/queries:listAll\",\n listMembersByOrgId: \"org/queries:listMembersByOrgId\",\n listMine: \"org/queries:listMine\",\n listRolesByOrgId: \"org/queries:listRolesByOrgId\",\n loadByOrgId: \"org/queries:loadByOrgId\",\n },\n \"smartAccount/actions\": {\n claim: \"smartAccount/actions:claim\",\n confirmDeployment: \"smartAccount/actions:confirmDeployment\",\n },\n \"smartAccount/mutations\": {\n provision: \"smartAccount/mutations:provision\",\n },\n \"smartAccount/queries\": {\n loadByAuthUserId: \"smartAccount/queries:loadByAuthUserId\",\n loadBySmartAccountAddress: \"smartAccount/queries:loadBySmartAccountAddress\",\n },\n \"subAccount/actions\": {\n transfer: \"subAccount/actions:transfer\",\n },\n \"subAccount/mutations\": {\n create: \"subAccount/mutations:create\",\n remove: \"subAccount/mutations:remove\",\n rename: \"subAccount/mutations:rename\",\n },\n \"subAccount/queries\": {\n get: \"subAccount/queries:get\",\n list: \"subAccount/queries:list\",\n },\n system: {\n health: \"system:health\",\n },\n} as const;\n\n/** Every Convex module the registry names. */\nexport type CapxulFunctionModule = keyof typeof CAPXUL_FUNCTIONS;\n\n/** Every backend function path the registry names, as a literal union. */\nexport type CapxulFunctionPath = {\n [M in CapxulFunctionModule]: (typeof CAPXUL_FUNCTIONS)[M][keyof (typeof CAPXUL_FUNCTIONS)[M]];\n}[CapxulFunctionModule];\n","// Status vocabularies — the third leg of A2-Q3A (\"@capxul/wire = the single\n// backend contract: all function refs + wire types + STATUS VOCABULARIES\").\n//\n// Each vocabulary was previously hand-copied into three or four places that had\n// no way to disagree loudly: the runtime `Schema.Literal(...)` in\n// `financial-ops.ts`, the backend's TypeScript union + its hand-written\n// `value === \"…\" || …` type guard, and the SDK's public `type PaymentStatus`.\n// Drift between them is a silent wire break — a new status decodes on one side\n// and falls off the other.\n//\n// The tuples below are the vocabulary. Everything else derives:\n// - runtime decoding → `Schema.Literals(PAYMENT_STATUSES)`\n// - the TS union → `PaymentStatus`\n// - the guard → `isPaymentStatus`\n//\n// The Convex table validator in `packages/backend/convex/schema.ts` is a\n// STORAGE validator, deliberately not derived here (its literals also gate\n// historical rows); `packages/backend/convex/financialOps/__tests__` locks it\n// against these tuples instead, so a divergence fails a test rather than a\n// production decode.\n\n/** Payment lifecycle states carried on the wire (ADR-0018 P1). */\nexport const PAYMENT_STATUSES = [\n \"pending\",\n \"submitted\",\n \"pending_claim\",\n \"scheduled\",\n \"streaming\",\n \"settled\",\n \"cancelled\",\n \"redirected\",\n \"expired\",\n \"failed\",\n] as const;\nexport type PaymentStatus = (typeof PAYMENT_STATUSES)[number];\n\n/** What a payment is FOR. Pairs with `PAYMENT_DOCUMENT_KINDS`. */\nexport const PAYMENT_TYPES = [\"unspecified\", \"invoice\", \"payroll\", \"reimbursement\"] as const;\nexport type PaymentType = (typeof PAYMENT_TYPES)[number];\n\n/** Attachable document kinds; each maps to exactly one `PaymentType`. */\nexport const PAYMENT_DOCUMENT_KINDS = [\n \"memo\",\n \"invoice\",\n \"payslip\",\n \"receipt\",\n \"withdrawal\",\n] as const;\nexport type PaymentDocumentKind = (typeof PAYMENT_DOCUMENT_KINDS)[number];\n\n/** Lifecycle of a payment REQUEST as its issuer sees it. */\nexport const REQUEST_STATUSES = [\n \"draft\",\n \"sent\",\n \"viewed\",\n \"pending_settlement\",\n \"paid\",\n \"declined\",\n \"cancelled\",\n \"expired\",\n] as const;\nexport type RequestStatus = (typeof REQUEST_STATUSES)[number];\n\n/** The same request as its RECIPIENT sees it, in the approval inbox. */\nexport const INBOX_STATUSES = [\n \"open\",\n \"approved\",\n \"declined\",\n \"paid\",\n \"cancelled\",\n \"expired\",\n] as const;\nexport type InboxStatus = (typeof INBOX_STATUSES)[number];\n\n/** Narrow an untrusted string to a `PaymentStatus`. */\nexport function isPaymentStatus(value: unknown): value is PaymentStatus {\n return typeof value === \"string\" && (PAYMENT_STATUSES as readonly string[]).includes(value);\n}\n\n/** Narrow an untrusted string to a `PaymentType`. */\nexport function isPaymentType(value: unknown): value is PaymentType {\n return typeof value === \"string\" && (PAYMENT_TYPES as readonly string[]).includes(value);\n}\n","import { Schema, SchemaParser } from \"effect\";\n\nimport { ChainIdSchema, CurrencyCodeSchema, DocumentHashSchema, EpochMsSchema } from \"./brands\";\nimport { PAYMENT_DOCUMENT_KINDS, PAYMENT_STATUSES, PAYMENT_TYPES } from \"./status\";\n\nconst MINOR_UNIT_STRING_RE = /^[0-9]+$/;\nconst DECIMAL_STRING_RE = /^[0-9]+(?:\\.[0-9]+)?$/;\nconst EVM_ADDRESS_RE = /^0x[a-fA-F0-9]{40}$/;\n/**\n * The canonical on-chain domain anchor for the v1 payment-document EIP-712\n * `domain` (payment-document-spec.md v1). The `PaymentDocumentDomain` schema\n * validates against this exact literal, and the backend's receipt builder mints\n * envelopes carrying it — so it MUST stay byte-identical across both. Exported\n * once here to remove the drift risk of a mirrored declaration.\n */\nexport const PAYMENT_DOCUMENT_VERIFYING_CONTRACT = \"0xe740ea65521edc9bef0ea75d30b5334711db99f4\";\nconst PAYMENT_ID_RE = /^payment_[0-9A-Za-z]+$/;\nconst PAYEE_ID_RE = /^payee_[0-9A-Za-z]+$/;\nconst ORG_ID_RE = /^org_[0-9A-Za-z]+$/;\nconst USER_ID_RE = /^user_[0-9A-Za-z]+$/;\nconst HANDLE_RE = /^@?[a-z0-9][a-z0-9-]{2,31}$/;\nconst ORG_HANDLE_RE = /^[a-z0-9][a-z0-9-]{2,31}$/;\nconst EMAIL_RE = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\n\nconst MinorUnitStringSchema = Schema.String.pipe(\n Schema.check(\n Schema.makeFilter((value): value is string => MINOR_UNIT_STRING_RE.test(value), {\n message: \"must be a non-negative integer minor-unit string\",\n }),\n ),\n);\nconst PaymentIdSchema = Schema.String.pipe(\n Schema.check(\n Schema.makeFilter((value): value is string => PAYMENT_ID_RE.test(value), {\n message: \"must be payment_ plus an alphanumeric id\",\n }),\n ),\n);\nconst PayeeIdSchema = Schema.String.pipe(\n Schema.check(\n Schema.makeFilter((value): value is string => PAYEE_ID_RE.test(value), {\n message: \"must be payee_ plus an alphanumeric id\",\n }),\n ),\n);\nconst OrgIdSchema = Schema.String.pipe(\n Schema.check(\n Schema.makeFilter((value): value is string => ORG_ID_RE.test(value), {\n message: \"must be org_ plus an alphanumeric id\",\n }),\n ),\n);\nconst UserIdSchema = Schema.String.pipe(\n Schema.check(\n Schema.makeFilter((value): value is string => USER_ID_RE.test(value), {\n message: \"must be user_ plus an alphanumeric id\",\n }),\n ),\n);\nconst DecimalStringSchema = Schema.String.pipe(\n Schema.check(\n Schema.makeFilter((value): value is string => DECIMAL_STRING_RE.test(value), {\n message: \"must be a non-negative decimal string\",\n }),\n ),\n);\nconst HandleValueSchema = Schema.String.pipe(\n Schema.check(\n Schema.makeFilter(\n (value): value is string => !EVM_ADDRESS_RE.test(value) && HANDLE_RE.test(value),\n {\n message: \"must be a handle; raw addresses are not accepted\",\n },\n ),\n ),\n);\nconst OrgHandleValueSchema = Schema.String.pipe(\n Schema.check(\n Schema.makeFilter(\n (value): value is string => !EVM_ADDRESS_RE.test(value) && ORG_HANDLE_RE.test(value),\n {\n message: \"must be an org handle; raw addresses are not accepted\",\n },\n ),\n ),\n);\nconst EmailValueSchema = Schema.String.pipe(\n Schema.check(\n Schema.makeFilter(\n (value): value is string => !EVM_ADDRESS_RE.test(value) && EMAIL_RE.test(value),\n {\n message: \"must be an email; raw addresses are not accepted\",\n },\n ),\n ),\n);\nconst Uint8Schema = Schema.Number.pipe(\n Schema.check(\n Schema.makeFilter(\n (value): value is number => Number.isSafeInteger(value) && value >= 0 && value <= 255,\n {\n message: \"must be a uint8\",\n },\n ),\n ),\n);\nconst Uint64Schema = Schema.Number.pipe(\n Schema.check(\n Schema.makeFilter((value): value is number => Number.isSafeInteger(value) && value >= 0, {\n message: \"must be a non-negative safe integer\",\n }),\n ),\n);\nconst PaymentDocumentDomain = Schema.Struct({\n name: Schema.Literal(\"CapxulPayments\"),\n version: Schema.Literal(\"1\"),\n chainId: ChainIdSchema,\n verifyingContract: Schema.Literal(PAYMENT_DOCUMENT_VERIFYING_CONTRACT),\n});\nconst MemoDocument = Schema.Struct({\n kind: Schema.Literal(0),\n reference: Schema.String,\n note: Schema.String,\n issuedAt: Uint64Schema,\n});\nconst InvoiceDocument = Schema.Struct({\n kind: Schema.Literal(1),\n invoiceNumber: Schema.String,\n payerRef: Schema.String,\n payeeRef: Schema.String,\n amount: MinorUnitStringSchema,\n currency: CurrencyCodeSchema,\n decimals: Uint8Schema,\n issuedAt: Uint64Schema,\n dueAt: Uint64Schema,\n lineItemsHash: DocumentHashSchema,\n});\nconst PayslipDocument = Schema.Struct({\n kind: Schema.Literal(2),\n employerRef: Schema.String,\n employeeRef: Schema.String,\n period: Schema.String,\n gross: MinorUnitStringSchema,\n net: MinorUnitStringSchema,\n currency: CurrencyCodeSchema,\n decimals: Uint8Schema,\n issuedAt: Uint64Schema,\n});\nconst ReceiptDocument = Schema.Struct({\n kind: Schema.Literal(3),\n reference: Schema.String,\n amount: MinorUnitStringSchema,\n currency: CurrencyCodeSchema,\n decimals: Uint8Schema,\n paidAt: Uint64Schema,\n note: Schema.String,\n});\nconst WithdrawalDestAddressSchema = Schema.String.pipe(\n Schema.check(\n Schema.makeFilter((value): value is string => EVM_ADDRESS_RE.test(value), {\n message: \"must be a 0x EVM address\",\n }),\n ),\n);\n// Withdrawal / cash-out document (kind 4, payment-document-spec.md). Minted by\n// the B3 withdraw lane when value leaves the custody Safe to an external wallet.\n// `destAddress` lives ON the document (user-visible / consent-gated, audit-only)\n// — it is NEVER model-visible; only the documentHash crosses the model wire.\n// `provider`/`note` are required strings (\"\" when absent) so the EIP-712 hash is\n// deterministic (an absent field cannot be hashed) — mirrors Receipt.note.\nconst WithdrawalDocument = Schema.Struct({\n kind: Schema.Literal(4),\n reference: Schema.String,\n amount: MinorUnitStringSchema,\n currency: CurrencyCodeSchema,\n decimals: Uint8Schema,\n destChain: ChainIdSchema,\n destAddress: WithdrawalDestAddressSchema,\n settledAt: Uint64Schema,\n provider: Schema.String,\n note: Schema.String,\n});\n\nexport const FinancialOpsMoney = Schema.Struct({\n currency: CurrencyCodeSchema,\n value: DecimalStringSchema,\n decimals: Schema.Number.pipe(\n Schema.check(\n Schema.makeFilter((value): value is number => Number.isSafeInteger(value) && value >= 0, {\n message: \"must be a non-negative safe integer\",\n }),\n ),\n ),\n});\n\nexport const PaymentDocument = Schema.Struct({\n documentHash: DocumentHashSchema,\n // `withdrawal` (B3): the kind:4 cash-out document attached to a withdraw\n // Payment. It maps to paymentType \"unspecified\" (see paymentTypeForDocumentKind).\n kind: Schema.Literals(PAYMENT_DOCUMENT_KINDS),\n title: Schema.optional(Schema.String),\n uri: Schema.optional(Schema.String),\n issuedAt: Schema.optional(EpochMsSchema),\n});\ntype PaymentDocumentKind = Schema.Schema.Type<typeof PaymentDocument>[\"kind\"];\n\nconst PaymentType = Schema.Literals(PAYMENT_TYPES);\ntype PaymentTypeV1 = Schema.Schema.Type<typeof PaymentType>;\n\nfunction paymentTypeForDocumentKind(kind: PaymentDocumentKind): PaymentTypeV1 {\n switch (kind) {\n case \"memo\":\n return \"unspecified\";\n case \"invoice\":\n return \"invoice\";\n case \"payslip\":\n return \"payroll\";\n case \"receipt\":\n return \"reimbursement\";\n // B3: a withdrawal/cash-out document maps to the unspecified payment type.\n case \"withdrawal\":\n return \"unspecified\";\n }\n}\n\nexport const AttachablePaymentDocumentEnvelope = Schema.Union([\n Schema.Struct({\n protocol: Schema.Literal(\"capxul.payment-document\"),\n version: Schema.Literal(1),\n domain: PaymentDocumentDomain,\n primaryType: Schema.Literal(\"Memo\"),\n message: MemoDocument,\n }),\n Schema.Struct({\n protocol: Schema.Literal(\"capxul.payment-document\"),\n version: Schema.Literal(1),\n domain: PaymentDocumentDomain,\n primaryType: Schema.Literal(\"Invoice\"),\n message: InvoiceDocument,\n }),\n Schema.Struct({\n protocol: Schema.Literal(\"capxul.payment-document\"),\n version: Schema.Literal(1),\n domain: PaymentDocumentDomain,\n primaryType: Schema.Literal(\"Payslip\"),\n message: PayslipDocument,\n }),\n Schema.Struct({\n protocol: Schema.Literal(\"capxul.payment-document\"),\n version: Schema.Literal(1),\n domain: PaymentDocumentDomain,\n primaryType: Schema.Literal(\"Receipt\"),\n message: ReceiptDocument,\n }),\n]);\n\nexport const WithdrawalDocumentEnvelope = Schema.Struct({\n protocol: Schema.Literal(\"capxul.payment-document\"),\n version: Schema.Literal(1),\n domain: PaymentDocumentDomain,\n primaryType: Schema.Literal(\"Withdrawal\"),\n message: WithdrawalDocument,\n});\n\nexport const PaymentDocumentEnvelope = Schema.Union([\n AttachablePaymentDocumentEnvelope,\n WithdrawalDocumentEnvelope,\n]);\n\nconst ENVELOPE_PRIMARY_TYPE_TO_KIND: Record<\n Schema.Schema.Type<typeof PaymentDocumentEnvelope>[\"primaryType\"],\n PaymentDocumentKind\n> = {\n Memo: \"memo\",\n Invoice: \"invoice\",\n Payslip: \"payslip\",\n Receipt: \"receipt\",\n Withdrawal: \"withdrawal\",\n};\n\n/**\n * Derive the wire `paymentType` an UNKNOWN document envelope classifies to\n * (payment-document-spec.md D11: memo/withdrawal → unspecified, invoice →\n * invoice, payslip → payroll, receipt → reimbursement), or `undefined` if the\n * envelope is absent / malformed — the same tolerance as\n * `tryHashPaymentDocument`. Callers holding an untyped envelope (e.g. the MCP\n * org spend port, #712) use this so the type they record agrees with the type\n * the backend re-derives from the same document.\n */\nexport function paymentTypeForDocumentEnvelope(envelope: unknown): PaymentTypeV1 | undefined {\n if (envelope === undefined || envelope === null) return undefined;\n const decoded = SchemaParser.decodeUnknownResult(PaymentDocumentEnvelope)(envelope);\n if (decoded._tag === \"Failure\") return undefined;\n return paymentTypeForDocumentKind(ENVELOPE_PRIMARY_TYPE_TO_KIND[decoded.success.primaryType]);\n}\n\nexport const PayeeSummary = Schema.Struct({\n payeeId: PayeeIdSchema,\n label: Schema.String,\n trustState: Schema.Literals([\"unverified\", \"trusted\", \"blocked\"]),\n destinationKind: Schema.Literals([\"handle\", \"email\", \"saved-payee\", \"org\"]),\n});\n\nexport const PaymentRecipient = Schema.Struct({\n // `external_address` (B3 withdraw/cash-out): the recipient is an EXTERNAL 0x\n // wallet outside Capxul custody. The full address lives ONLY on the kind:4\n // Withdrawal document (user-visible / audit); here the `label` is a REDACTED\n // form (\"0x1234…abcd\") so a withdraw Payment renders leak-safe on the model\n // wire (assertWireSafe still bans `destAddress`). NOT added to the pay\n // resolver / PaymentRecipientRefSchema — withdraw takes the raw 0x on its own\n // path, the pay lane keeps rejecting bare addresses.\n kind: Schema.Literals([\n \"handle\",\n \"email\",\n \"payee\",\n \"capxulUserId\",\n \"me\",\n \"org\",\n \"external_address\",\n ]),\n label: Schema.String,\n payeeId: Schema.optional(PayeeIdSchema),\n});\n\n/**\n * A raw external EVM address for the B3 withdraw lane — the cash-out\n * destination. This is the ONE schema that ACCEPTS a bare 0x (the withdraw\n * mutation args use it), as opposed to `PaymentRecipientRefSchema` which\n * REJECTS bare addresses to protect the pay lane. The full address never\n * crosses the model wire; it lives on the kind:4 Withdrawal document only.\n */\nexport const ExternalAddressSchema = Schema.String.pipe(\n Schema.check(\n Schema.makeFilter((value): value is string => EVM_ADDRESS_RE.test(value), {\n message: \"must be a 0x EVM address (40 hex chars)\",\n }),\n ),\n);\n\n/**\n * Redact a full external 0x address to a short, model-safe label\n * (\"0x1234…abcd\"): first 6 + last 4 chars. The withdraw lane stores this as\n * the wire recipient `label` so the model can reference the destination\n * without the full address ever crossing the wire.\n */\nexport function redactExternalAddress(address: string): string {\n const lower = address.toLowerCase();\n if (!EVM_ADDRESS_RE.test(lower)) {\n throw new Error(\"redactExternalAddress requires a 0x EVM address\");\n }\n return `${lower.slice(0, 6)}…${lower.slice(-4)}`;\n}\n\nexport const PaymentTiming = Schema.Union([\n Schema.Struct({\n kind: Schema.Literal(\"instant\"),\n }),\n Schema.Struct({\n kind: Schema.Literal(\"scheduled\"),\n at: EpochMsSchema,\n }),\n Schema.Struct({\n kind: Schema.Literal(\"stream\"),\n startsAt: EpochMsSchema,\n endsAt: EpochMsSchema,\n cliffAt: Schema.optional(EpochMsSchema),\n }),\n]);\nexport const PaymentRelease = PaymentTiming;\n\nexport const PaymentRef = Schema.Union([\n Schema.Struct({\n kind: Schema.Literal(\"handle\"),\n handle: HandleValueSchema,\n }),\n Schema.Struct({\n kind: Schema.Literal(\"email\"),\n email: EmailValueSchema,\n }),\n Schema.Struct({\n kind: Schema.Literal(\"orgHandle\"),\n orgHandle: OrgHandleValueSchema,\n }),\n Schema.Struct({\n kind: Schema.Literal(\"capxulUserId\"),\n capxulUserId: UserIdSchema,\n }),\n Schema.Struct({\n kind: Schema.Literal(\"payeeId\"),\n payeeId: PayeeIdSchema,\n }),\n]);\n\nexport const Payment = Schema.Struct({\n id: PaymentIdSchema,\n status: Schema.Literals(PAYMENT_STATUSES),\n amount: FinancialOpsMoney,\n paymentType: PaymentType,\n recipient: PaymentRecipient,\n documents: Schema.Array(PaymentDocument),\n timing: PaymentTiming,\n released: FinancialOpsMoney,\n availableToClaim: FinancialOpsMoney,\n createdAt: EpochMsSchema,\n updatedAt: EpochMsSchema,\n}).pipe(\n Schema.check(\n Schema.makeFilter(\n (payment) =>\n payment.documents.every(\n (document) => paymentTypeForDocumentKind(document.kind) === payment.paymentType,\n ),\n {\n message: \"document kind must map to paymentType\",\n },\n ),\n ),\n);\n\nconst PaymentSource = Schema.Union([\n Schema.Struct({\n kind: Schema.Literal(\"me\"),\n orgId: Schema.optional(Schema.Undefined),\n }),\n Schema.Struct({\n kind: Schema.Literal(\"org\"),\n orgId: OrgIdSchema,\n }),\n]);\n\n/**\n * #592 invoice line item. `quantity` is a positive integer; `unitMinor` is the\n * per-unit price in integer minor units. The list is canonically hashed by\n * `hashLineItems` (payment-document-hash.ts) into the Invoice `lineItemsHash`,\n * and Σ(quantity × unitMinor) MUST equal the invoice `amount`. The hash binds\n * the documentHash to the exact items; the sum-check makes the items add up to\n * the amount due. See the financial-operations contract in `packages/wire/CONTEXT.md`.\n */\nexport const LineItem = Schema.Struct({\n description: Schema.String,\n quantity: Schema.Number.pipe(\n Schema.check(\n Schema.makeFilter((value): value is number => Number.isSafeInteger(value) && value > 0, {\n message: \"quantity must be a positive integer\",\n }),\n ),\n ),\n unitMinor: MinorUnitStringSchema,\n});\n\nexport const PaymentsPayInput = Schema.Struct({\n from: Schema.optional(PaymentSource),\n to: PaymentRef,\n amount: FinancialOpsMoney,\n timing: Schema.optional(PaymentTiming),\n document: Schema.optional(AttachablePaymentDocumentEnvelope),\n // #592: the itemized line-item list backing an Invoice document. When present\n // the backend asserts hashLineItems(lineItems) === document.lineItemsHash AND\n // Σ(quantity × unitMinor) === document.amount, then persists the list so the\n // render path can re-verify + itemize.\n lineItems: Schema.optional(Schema.Array(LineItem)),\n});\n\n// B3 (withdraw / cash-out): send USDX from the user's custody Safe to an\n// EXTERNAL 0x wallet. `to` is the raw external address (validated by\n// `ExternalAddressSchema` — the ONE schema that accepts a bare 0x), `document`\n// is the REQUIRED kind:4 Withdrawal envelope (the only doc kind allowed; it\n// carries the audit-visible destAddress). Stripe-shaped: no chain / Safe /\n// token / hash custody substrate on the input.\nexport const PaymentsWithdrawInput = Schema.Struct({\n to: ExternalAddressSchema,\n amount: FinancialOpsMoney,\n document: WithdrawalDocumentEnvelope,\n});\n\nexport const MeEnvelope = Schema.Struct({\n protocol: Schema.Literal(\"capxul.me\"),\n version: Schema.Literal(1),\n me: Schema.Struct({\n displayName: Schema.NullOr(Schema.String),\n handle: Schema.NullOr(Schema.String),\n defaultCurrency: CurrencyCodeSchema,\n depositInstructions: Schema.Array(\n Schema.Struct({\n network: Schema.String,\n asset: CurrencyCodeSchema,\n depositTarget: Schema.String,\n memo: Schema.optional(Schema.String),\n }),\n ),\n }),\n});\n\nexport const PaymentListEnvelope = Schema.Struct({\n protocol: Schema.Literal(\"capxul.payments\"),\n version: Schema.Literal(1),\n payments: Schema.Array(Payment),\n});\n\nexport type FinancialOpsMoneyV1 = Schema.Schema.Type<typeof FinancialOpsMoney>;\nexport type AttachablePaymentDocumentEnvelopeV1 = Schema.Schema.Type<\n typeof AttachablePaymentDocumentEnvelope\n>;\nexport type PaymentDocumentV1 = Schema.Schema.Type<typeof PaymentDocument>;\nexport type PaymentDocumentEnvelopeV1 = Schema.Schema.Type<typeof PaymentDocumentEnvelope>;\nexport type WithdrawalDocumentEnvelopeV1 = Schema.Schema.Type<typeof WithdrawalDocumentEnvelope>;\nexport type PayeeSummaryV1 = Schema.Schema.Type<typeof PayeeSummary>;\nexport type PaymentRecipientV1 = Schema.Schema.Type<typeof PaymentRecipient>;\nexport type PaymentTimingV1 = Schema.Schema.Type<typeof PaymentTiming>;\nexport type PaymentReleaseV1 = PaymentTimingV1;\nexport type PaymentRefV1 = Schema.Schema.Type<typeof PaymentRef>;\nexport type PaymentV1 = Schema.Schema.Type<typeof Payment>;\nexport type LineItemV1 = Schema.Schema.Type<typeof LineItem>;\nexport type PaymentsPayInputV1 = Schema.Schema.Type<typeof PaymentsPayInput>;\nexport type PaymentsWithdrawInputV1 = Schema.Schema.Type<typeof PaymentsWithdrawInput>;\nexport type MeEnvelopeV1 = Schema.Schema.Type<typeof MeEnvelope>;\nexport type PaymentListEnvelopeV1 = Schema.Schema.Type<typeof PaymentListEnvelope>;\n","// Payment-document HTML rendering (ADR-4, payment-document-spec.md).\n//\n// Each template is a function of the verified EIP-712 envelope PLUS optional\n// verified product CONTEXT the rendering surface holds — the `from`/`to` party\n// labels (sourced from the Payment, not the hashed struct) and the invoice\n// line-item list (the one the committed `lineItemsHash` commits to). The hash\n// still anchors the envelope; the context is never invented — a caller passes\n// only data it has verified. Money is always integer minor units + currency +\n// decimals (BigInt-safe string math, never a float). Free-text is HTML-escaped.\n// Output is framework-free semantic HTML with stable class hooks.\n\nimport type { PaymentDocumentEnvelopeV1 } from \"./financial-ops\";\nimport { hashLineItems } from \"./payment-document-hash\";\n\n/** A single invoice line item — committed (as an ordered list) by the envelope's `lineItemsHash`. */\nexport interface DocumentLineItem {\n readonly description: string;\n readonly quantity: number;\n /** Unit price in integer minor units (same currency/decimals as the document). */\n readonly unitMinor: string;\n}\n\n/**\n * Verified product context the rendering surface supplies alongside the envelope.\n * NONE of it is invented by the renderer: `from`/`to` are the Payment's party\n * labels; `lineItems` are the list the `lineItemsHash` commits to.\n */\nexport interface DocumentRenderContext {\n readonly from?: string;\n readonly to?: string;\n readonly lineItems?: readonly DocumentLineItem[];\n}\n\nconst HTML_ESCAPES: Record<string, string> = {\n \"&\": \"&\",\n \"<\": \"<\",\n \">\": \">\",\n '\"': \""\",\n \"'\": \"'\",\n};\n\nfunction esc(value: string): string {\n return value.replace(/[&<>\"']/g, (char) => HTML_ESCAPES[char] ?? char);\n}\n\nconst CURRENCY_SYMBOLS: Record<string, string> = {\n USD: \"$\",\n NGN: \"₦\",\n GHS: \"₵\",\n KES: \"KSh \",\n UGX: \"USh \",\n};\n\n/** Group the integer part with thousands separators (BigInt-safe, no float). */\nfunction groupThousands(digits: string): string {\n return digits.replace(/\\B(?=(\\d{3})+(?!\\d))/g, \",\");\n}\n\n/** Format integer minor units as a fixed-decimal display string (no float). */\nfunction formatMinorUnits(amount: string, decimals: number): string {\n const digits = amount.replace(/^0+(?=\\d)/, \"\");\n if (decimals === 0) return groupThousands(digits);\n const padded = digits.padStart(decimals + 1, \"0\");\n const whole = padded.slice(0, padded.length - decimals);\n const fraction = padded.slice(padded.length - decimals);\n return `${groupThousands(whole)}.${fraction}`;\n}\n\n/** A money amount with its currency symbol, e.g. `$1,250.00`. */\nfunction money(amount: string, currency: string, decimals: number): string {\n const symbol = CURRENCY_SYMBOLS[currency] ?? \"\";\n const formatted = `${symbol}${formatMinorUnits(amount, decimals)}`;\n const suffix = symbol === \"\" ? ` ${currency}` : \"\";\n return `${formatted}${suffix}`;\n}\n\nfunction moneyEl(amount: string, currency: string, decimals: number): string {\n return `<span class=\"doc-amount\"><span class=\"doc-amount-value\">${esc(\n money(amount, currency, decimals),\n )}</span></span>`;\n}\n\nconst MONTHS = [\n \"January\",\n \"February\",\n \"March\",\n \"April\",\n \"May\",\n \"June\",\n \"July\",\n \"August\",\n \"September\",\n \"October\",\n \"November\",\n \"December\",\n];\n\n/** Deterministic UTC date, e.g. `28 June 2026` (stable golden output, no locale). */\nfunction formatDate(epochMs: number): string {\n const d = new Date(epochMs);\n return `${d.getUTCDate()} ${MONTHS[d.getUTCMonth()]} ${d.getUTCFullYear()}`;\n}\n\nfunction isoDate(epochMs: number): string {\n return new Date(epochMs).toISOString();\n}\n\nfunction truncateAddress(address: string): string {\n return address.length <= 14 ? address : `${address.slice(0, 8)}…${address.slice(-6)}`;\n}\n\n/** A party block (label + name). Omitted entirely when no name is available. */\nfunction party(role: string, name: string | undefined): string {\n if (name === undefined || name === \"\") return \"\";\n return `<div class=\"doc-party\"><span class=\"doc-party-label\">${esc(\n role,\n )}</span><span class=\"doc-party-name\">${esc(name)}</span></div>`;\n}\n\nfunction brand(): string {\n return `<div class=\"doc-brand\"><span class=\"doc-brand-mark\">◆</span><span class=\"doc-brand-name\">Capxul</span></div>`;\n}\n\nfunction shell(kind: number, modifier: string, title: string, badge: string, body: string): string {\n return [\n `<article class=\"capxul-doc capxul-doc--${modifier}\" data-kind=\"${kind}\">`,\n `<header class=\"doc-header\">${brand()}`,\n `<div class=\"doc-headline\"><h1 class=\"doc-title\">${esc(title)}</h1>`,\n badge === \"\" ? \"\" : `<span class=\"doc-badge\">${esc(badge)}</span>`,\n `</div></header>`,\n body,\n `</article>`,\n ].join(\"\");\n}\n\nfunction metaRow(label: string, value: string): string {\n return `<div class=\"doc-meta-row\"><span class=\"doc-meta-label\">${esc(\n label,\n )}</span><span class=\"doc-meta-value\">${value}</span></div>`;\n}\n\nfunction dateEl(label: string, cls: string, epochMs: number): string {\n return `<div class=\"doc-meta-row\"><span class=\"doc-meta-label\">${esc(\n label,\n )}</span><time class=\"${cls}\" datetime=\"${esc(isoDate(epochMs))}\">${esc(\n formatDate(epochMs),\n )}</time></div>`;\n}\n\nfunction renderMemo(\n m: Extract<PaymentDocumentEnvelopeV1[\"message\"], { kind: 0 }>,\n ctx: DocumentRenderContext,\n): string {\n return shell(\n 0,\n \"memo\",\n \"Memo\",\n m.reference,\n [\n `<section class=\"doc-parties\">${party(\"From\", ctx.from)}${party(\"To\", ctx.to)}</section>`,\n `<section class=\"doc-body\"><p class=\"doc-note\">${esc(m.note)}</p></section>`,\n `<footer class=\"doc-footer\">${dateEl(\"Issued\", \"doc-issued\", m.issuedAt)}</footer>`,\n ].join(\"\"),\n );\n}\n\nfunction lineItemsTable(\n items: readonly DocumentLineItem[],\n currency: string,\n decimals: number,\n): { rows: string; computedTotalMinor: bigint } {\n let total = 0n;\n const rows = items\n .map((item) => {\n const lineTotal = BigInt(item.unitMinor) * BigInt(item.quantity);\n total += lineTotal;\n return [\n `<tr><td class=\"doc-li-desc\">${esc(item.description)}</td>`,\n `<td class=\"doc-li-qty\">${esc(String(item.quantity))}</td>`,\n `<td class=\"doc-li-unit\">${esc(money(item.unitMinor, currency, decimals))}</td>`,\n `<td class=\"doc-li-total\">${esc(\n money(lineTotal.toString(), currency, decimals),\n )}</td></tr>`,\n ].join(\"\");\n })\n .join(\"\");\n return { rows, computedTotalMinor: total };\n}\n\nfunction renderInvoice(\n m: Extract<PaymentDocumentEnvelopeV1[\"message\"], { kind: 1 }>,\n ctx: DocumentRenderContext,\n): string {\n const fromName = ctx.from ?? m.payeeRef; // the issuer/biller of an invoice is the payee\n const toName = ctx.to ?? m.payerRef;\n // #592: the line-item LIST is committed by `lineItemsHash`. Before itemizing,\n // RE-VERIFY that the supplied list actually hashes to the committed hash —\n // otherwise a tampered/mismatched list could be rendered as if authentic.\n // On mismatch (or no list), fall back to honestly showing the committed hash.\n const suppliedItems = ctx.lineItems;\n const itemsVerified =\n suppliedItems !== undefined &&\n suppliedItems.length > 0 &&\n hashLineItems(suppliedItems).toLowerCase() === m.lineItemsHash.toLowerCase();\n const itemsBlock = itemsVerified\n ? (() => {\n const { rows } = lineItemsTable(suppliedItems, m.currency, m.decimals);\n return `<table class=\"doc-line-items\"><thead><tr><th>Description</th><th class=\"doc-li-qty\">Qty</th><th class=\"doc-li-unit\">Unit</th><th class=\"doc-li-total\">Amount</th></tr></thead><tbody>${rows}</tbody></table>`;\n })()\n : `<p class=\"doc-line-items-hash\" data-line-items-hash=\"${esc(\n m.lineItemsHash,\n )}\">Line items committed by <code>${esc(m.lineItemsHash)}</code></p>`;\n return shell(\n 1,\n \"invoice\",\n \"Invoice\",\n m.invoiceNumber,\n [\n `<section class=\"doc-parties\">${party(\"From\", fromName)}${party(\"Bill to\", toName)}</section>`,\n `<section class=\"doc-meta\">${dateEl(\"Issued\", \"doc-issued\", m.issuedAt)}${dateEl(\n \"Due\",\n \"doc-due\",\n m.dueAt,\n )}</section>`,\n `<section class=\"doc-items\">${itemsBlock}</section>`,\n `<section class=\"doc-totals\"><div class=\"doc-total-line doc-total-grand\"><span class=\"doc-total-label\">Amount due</span>${moneyEl(\n m.amount,\n m.currency,\n m.decimals,\n )}</div></section>`,\n ].join(\"\"),\n );\n}\n\nfunction renderPayslip(\n m: Extract<PaymentDocumentEnvelopeV1[\"message\"], { kind: 2 }>,\n ctx: DocumentRenderContext,\n): string {\n const deductions = (BigInt(m.gross) - BigInt(m.net)).toString();\n return shell(\n 2,\n \"payslip\",\n \"Payslip\",\n m.period,\n [\n `<section class=\"doc-parties\">${party(\"Employer\", ctx.from ?? m.employerRef)}${party(\n \"Employee\",\n ctx.to ?? m.employeeRef,\n )}</section>`,\n `<section class=\"doc-totals\">`,\n `<div class=\"doc-total-line\"><span class=\"doc-total-label\">Gross</span>${moneyEl(\n m.gross,\n m.currency,\n m.decimals,\n )}</div>`,\n `<div class=\"doc-total-line doc-total-deduction\"><span class=\"doc-total-label\">Deductions</span><span class=\"doc-amount\"><span class=\"doc-amount-value\">−${esc(\n money(deductions, m.currency, m.decimals),\n )}</span></span></div>`,\n `<div class=\"doc-total-line doc-total-grand\"><span class=\"doc-total-label\">Net pay</span>${moneyEl(\n m.net,\n m.currency,\n m.decimals,\n )}</div></section>`,\n `<footer class=\"doc-footer\">${dateEl(\"Issued\", \"doc-issued\", m.issuedAt)}</footer>`,\n ].join(\"\"),\n );\n}\n\nfunction renderReceipt(\n m: Extract<PaymentDocumentEnvelopeV1[\"message\"], { kind: 3 }>,\n ctx: DocumentRenderContext,\n): string {\n return shell(\n 3,\n \"receipt\",\n \"Receipt\",\n \"Paid\",\n [\n `<section class=\"doc-hero\"><span class=\"doc-hero-label\">Amount paid</span><div class=\"doc-hero-amount\">${moneyEl(\n m.amount,\n m.currency,\n m.decimals,\n )}</div></section>`,\n `<section class=\"doc-parties\">${party(\"From\", ctx.from)}${party(\"To\", ctx.to)}</section>`,\n `<section class=\"doc-meta\">${metaRow(\"Reference\", esc(m.reference))}${dateEl(\n \"Paid\",\n \"doc-paid\",\n m.paidAt,\n )}</section>`,\n m.note === \"\"\n ? \"\"\n : `<footer class=\"doc-footer\"><p class=\"doc-note\">${esc(m.note)}</p></footer>`,\n ].join(\"\"),\n );\n}\n\nfunction renderWithdrawal(\n m: Extract<PaymentDocumentEnvelopeV1[\"message\"], { kind: 4 }>,\n _ctx: DocumentRenderContext,\n): string {\n const providerRow =\n m.provider === \"\"\n ? \"\"\n : metaRow(\"Provider\", `<span class=\"doc-provider\">${esc(m.provider)}</span>`);\n return shell(\n 4,\n \"withdrawal\",\n \"Withdrawal\",\n m.reference,\n [\n `<section class=\"doc-hero\"><span class=\"doc-hero-label\">Amount sent</span><div class=\"doc-hero-amount\">${moneyEl(\n m.amount,\n m.currency,\n m.decimals,\n )}</div></section>`,\n `<section class=\"doc-meta\">`,\n metaRow(\n \"To wallet\",\n `<span class=\"doc-dest-address\" data-chain=\"${esc(String(m.destChain))}\" data-address=\"${esc(\n m.destAddress,\n )}\" title=\"${esc(m.destAddress)}\">${esc(truncateAddress(m.destAddress))}</span>`,\n ),\n metaRow(\"Chain\", `chain ${esc(String(m.destChain))}`),\n providerRow,\n dateEl(\"Settled\", \"doc-settled\", m.settledAt),\n `</section>`,\n m.note === \"\"\n ? \"\"\n : `<footer class=\"doc-footer\"><p class=\"doc-note\">${esc(m.note)}</p></footer>`,\n ].join(\"\"),\n );\n}\n\n/**\n * Render a verified Payment-document envelope to framework-free semantic HTML.\n * Output depends on the envelope's own fields plus the optional verified\n * `context` (party labels from the Payment; the committed line-item list).\n * The template is selected by `primaryType` (equivalently the `kind`).\n */\nexport function renderPaymentDocument(\n envelope: PaymentDocumentEnvelopeV1,\n context: DocumentRenderContext = {},\n): string {\n switch (envelope.primaryType) {\n case \"Memo\":\n return renderMemo(envelope.message, context);\n case \"Invoice\":\n return renderInvoice(envelope.message, context);\n case \"Payslip\":\n return renderPayslip(envelope.message, context);\n case \"Receipt\":\n return renderReceipt(envelope.message, context);\n case \"Withdrawal\":\n return renderWithdrawal(envelope.message, context);\n }\n}\n\n/** A professional, swappable default stylesheet for the `.capxul-doc` class hooks. */\nexport const DOCUMENT_STYLESHEET = `\n.capxul-doc{--ink:#1d1d1f;--muted:#6e6e73;--line:#e7e7ea;--accent:#0a7d4b;--bg:#fff;\n font-family:-apple-system,BlinkMacSystemFont,\"Segoe UI\",Inter,system-ui,sans-serif;\n color:var(--ink);background:var(--bg);max-width:44rem;margin:0 auto;padding:2.75rem 3rem;\n border:1px solid var(--line);border-radius:16px;box-shadow:0 1px 2px rgba(0,0,0,.04),0 12px 32px rgba(0,0,0,.06);\n line-height:1.5;font-size:15px;overflow-wrap:anywhere;word-break:break-word}\n.capxul-doc *{box-sizing:border-box;min-width:0}\n.capxul-doc .doc-header{display:flex;flex-direction:column;gap:1.25rem;padding-bottom:1.5rem;border-bottom:1px solid var(--line);margin-bottom:1.75rem}\n.capxul-doc .doc-brand{display:flex;align-items:center;gap:.5rem;color:var(--accent);font-weight:600}\n.capxul-doc .doc-brand-mark{font-size:1.1rem}\n.capxul-doc .doc-brand-name{letter-spacing:.02em}\n.capxul-doc .doc-headline{display:flex;align-items:baseline;justify-content:space-between;gap:1rem;flex-wrap:wrap}\n.capxul-doc .doc-title{font-size:1.9rem;font-weight:700;letter-spacing:-.02em;margin:0}\n.capxul-doc .doc-badge{font-size:.7rem;font-weight:700;text-transform:uppercase;letter-spacing:.08em;\n color:var(--accent);background:rgba(10,125,75,.1);padding:.3rem .6rem;border-radius:999px;max-width:100%;text-align:right}\n.capxul-doc .doc-parties{display:grid;grid-template-columns:1fr 1fr;gap:1.25rem;margin-bottom:1.75rem}\n.capxul-doc .doc-party{display:flex;flex-direction:column;gap:.15rem}\n.capxul-doc .doc-party-label{font-size:.72rem;text-transform:uppercase;letter-spacing:.06em;color:var(--muted)}\n.capxul-doc .doc-party-name{font-weight:600}\n.capxul-doc .doc-meta{display:flex;flex-direction:column;gap:.4rem;margin-bottom:1.75rem}\n.capxul-doc .doc-meta-row{display:flex;justify-content:space-between;gap:1rem;font-size:.92rem}\n.capxul-doc .doc-meta-label{color:var(--muted);flex-shrink:0}\n.capxul-doc .doc-meta-value{font-weight:500;text-align:right}\n.capxul-doc time{color:var(--ink);font-variant-numeric:tabular-nums}\n.capxul-doc .doc-line-items{width:100%;border-collapse:collapse;margin:.5rem 0 1.5rem;font-size:.92rem}\n.capxul-doc .doc-line-items th{text-align:left;font-size:.7rem;text-transform:uppercase;letter-spacing:.05em;\n color:var(--muted);font-weight:600;padding:.5rem .25rem;border-bottom:1px solid var(--line)}\n.capxul-doc .doc-line-items td{padding:.7rem .25rem;border-bottom:1px solid var(--line)}\n.capxul-doc .doc-li-qty,.capxul-doc .doc-li-unit,.capxul-doc .doc-li-total{text-align:right;font-variant-numeric:tabular-nums;white-space:nowrap}\n.capxul-doc .doc-li-desc{width:100%}\n.capxul-doc .doc-totals{display:flex;flex-direction:column;gap:.5rem;margin-top:.5rem}\n.capxul-doc .doc-total-line{display:flex;justify-content:space-between;align-items:baseline;gap:1rem}\n.capxul-doc .doc-total-label{color:var(--muted)}\n.capxul-doc .doc-total-deduction .doc-amount-value{color:var(--muted)}\n.capxul-doc .doc-total-grand{border-top:2px solid var(--ink);margin-top:.5rem;padding-top:.75rem;font-size:1.15rem}\n.capxul-doc .doc-total-grand .doc-amount-value{font-weight:700}\n.capxul-doc .doc-amount-value{font-variant-numeric:tabular-nums;font-weight:600}\n.capxul-doc .doc-hero{text-align:center;padding:1.5rem 0 2rem}\n.capxul-doc .doc-hero-label{font-size:.72rem;text-transform:uppercase;letter-spacing:.06em;color:var(--muted)}\n.capxul-doc .doc-hero-amount{font-size:2.6rem;font-weight:700;letter-spacing:-.02em;margin-top:.35rem}\n.capxul-doc .doc-note{color:var(--ink);background:#f7f7f8;border-radius:10px;padding:.9rem 1.1rem;margin:0}\n.capxul-doc .doc-dest-address{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:.9rem}\n.capxul-doc .doc-footer{margin-top:1.75rem;padding-top:1.25rem;border-top:1px solid var(--line);color:var(--muted);font-size:.9rem}\n.capxul-doc code{font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:.82rem;color:var(--muted);word-break:break-all}\n@media (max-width:540px){.capxul-doc{padding:1.75rem 1.25rem}.capxul-doc .doc-parties{grid-template-columns:1fr}}\n`.trim();\n","// The single home for the observation / PostHog-reporting secret-material\n// pattern family (credential / JWT / private-key / wallet).\n//\n// The same patterns were once copied, with divergent literals, into two other\n// places — the backend PostHog automation and the scripts reporter — where\n// drift was a leak risk: a secret slipping past one copy and landing in a\n// PostHog issue body or an observation field. Both copies (and the custom\n// PostHog→GitHub automation they served) were removed in #873 once native\n// PostHog error tracking replaced them. This module is that family's single\n// source of truth; the wire sanitizer below is repointed here, which is why\n// `redactSecrets` (the mask half) currently has no consumer beyond this\n// package's own tests.\n//\n// Two faces of the one family:\n// - `containsSensitiveMaterial` (reject) tests for presence and is used to\n// drop a whole value that carries any secret. Its patterns are anchored on\n// consumed boundaries and are non-global so `.test()` stays stateless.\n// - `redactSecrets` (mask) rewrites a value in place, replacing each hit with\n// `[REDACTED]`. Its patterns are global so `String.replace` sweeps every\n// occurrence. Update both together when the credential families change.\n\n// Reject-side pattern set: any match means the whole value is unsafe to emit.\nconst SENSITIVE_MATERIAL_PATTERNS: readonly RegExp[] = [\n // 0x-prefixed hex long enough to be an address or embedded wallet payload.\n /0x[a-fA-F0-9]{40,}/u,\n // A bare 32-byte hex private key, bounded so it is not a hash substring.\n /(?:^|[^a-fA-F0-9])[a-fA-F0-9]{64}(?:$|[^a-fA-F0-9])/u,\n // A compact three-segment JWT.\n /eyJ[A-Za-z0-9_-]*\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+/u,\n // Known provider credential prefixes (Stripe/PostHog/GitHub/Slack/AWS/GCP…).\n /(?:(?:sk|pk|rk)_(?:live|test)|(?:phc|phx|ghp|gho|ghu|ghs|ghr|whsec)_|github_pat_|xox[baprs]-|AKIA[0-9A-Z]{16}|AIza)[A-Za-z0-9_-]*/iu,\n];\n\n// Mask-side patterns: global so every occurrence in a value is rewritten.\nconst RAW_PRIVATE_KEY_MASK = /(^|[^a-fA-F0-9])[a-fA-F0-9]{64}(?=$|[^a-fA-F0-9])/gu;\nconst KNOWN_CREDENTIAL_MASK =\n /(?:(?:sk|pk|rk)_(?:live|test)|(?:phc|phx|ghp|gho|ghu|ghs|ghr|whsec)_|github_pat_|xox[baprs]-|AKIA[0-9A-Z]{16}|AIza)[A-Za-z0-9_-]*/giu;\nconst LABELLED_SECRET_MASK =\n /\\b(api[ _-]?key|access[ _-]?token|token|secret|password|passphrase|private[ _-]?key|authorization|cookie|signature|request[ _-]?body|credential|otp|one[ _-]?time[ _-]?(?:password|code)|verification[ _-]?code)\\b\\s*[:=]\\s*(?:\"[^\"]*\"|'[^']*'|[^\\s,;]+)/giu;\n\n/**\n * Reject: does the value carry any known secret material? Best effort — callers\n * drop the whole value on a match; a false negative is a leak, a false positive\n * merely omits an observation field.\n */\nexport function containsSensitiveMaterial(value: string): boolean {\n return SENSITIVE_MATERIAL_PATTERNS.some((pattern) => pattern.test(value));\n}\n\n/**\n * Mask: return the value with every known secret rewritten to `[REDACTED]`,\n * preserving surrounding text. Used where a value must still be shown (log\n * lines, issue bodies) but must not carry live credentials.\n */\nexport function redactSecrets(value: string): string {\n return value\n .replace(/\\bBearer\\s+[^\\s,;]+/giu, \"Bearer [REDACTED]\")\n .replace(/\\beyJ[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\.[A-Za-z0-9_-]+\\b/gu, \"[REDACTED]\")\n .replace(/\\b0x[a-fA-F0-9]{40,}\\b/gu, \"[REDACTED]\")\n .replace(RAW_PRIVATE_KEY_MASK, \"$1[REDACTED]\")\n .replace(KNOWN_CREDENTIAL_MASK, \"[REDACTED]\")\n .replace(LABELLED_SECRET_MASK, (_match, label: string) => `${label}=[REDACTED]`);\n}\n","import { APP_ID_RE } from \"@capxul/types\";\n\nimport { containsSensitiveMaterial } from \"./secret-material\";\n\n/**\n * Bounded, non-authoritative observation metadata carried by selected SDK\n * calls. Actor identity is deliberately absent: the backend derives it from\n * the authenticated session and verifies organization/application hints.\n */\nexport interface WireObservationContext {\n readonly application?: string;\n readonly applicationId?: string;\n readonly release?: string;\n readonly sessionId?: string;\n readonly organizationId?: string;\n readonly journeyId?: string;\n readonly correlationId?: string;\n readonly anonymousId?: string;\n /** W3C trace carrier for the explicit Convex action hop; never product identity. */\n readonly traceparent?: string;\n}\n\n/** Single bounded HTTP carrier used before a Convex action envelope exists. */\nexport const OBSERVATION_CONTEXT_HEADER = \"x-capxul-observation-context\";\nconst MAX_OBSERVATION_HEADER_LENGTH = 1_024;\n\ntype ObservationContextField = keyof WireObservationContext;\n\nconst FIELD_RULES: Readonly<\n Record<ObservationContextField, { readonly maxLength: number; readonly pattern: RegExp }>\n> = {\n application: { maxLength: 64, pattern: /^[A-Za-z0-9][A-Za-z0-9._-]*$/u },\n applicationId: { maxLength: 30, pattern: APP_ID_RE },\n release: { maxLength: 128, pattern: /^[A-Za-z0-9][A-Za-z0-9._+@:/-]*$/u },\n sessionId: { maxLength: 128, pattern: /^[A-Za-z0-9][A-Za-z0-9._:-]*$/u },\n organizationId: { maxLength: 128, pattern: /^[A-Za-z0-9][A-Za-z0-9._:-]*$/u },\n journeyId: { maxLength: 128, pattern: /^[A-Za-z0-9][A-Za-z0-9._:-]*$/u },\n correlationId: { maxLength: 128, pattern: /^[A-Za-z0-9][A-Za-z0-9._:-]*$/u },\n anonymousId: { maxLength: 128, pattern: /^anon_[A-Za-z0-9-]+$/u },\n traceparent: {\n maxLength: 55,\n pattern: /^00-[0-9a-f]{32}-[0-9a-f]{16}-0[01]$/u,\n },\n};\n\n/**\n * Copy only the canonical allowlist and silently omit malformed/sensitive\n * values. Observation metadata is best effort and may never reject a domain\n * operation.\n */\nexport function sanitizeObservationContext(input: unknown): WireObservationContext | undefined {\n if (typeof input !== \"object\" || input === null || Array.isArray(input)) return undefined;\n\n const source = input as Readonly<Record<string, unknown>>;\n const sanitized: Partial<Record<ObservationContextField, string>> = {};\n for (const field of Object.keys(FIELD_RULES) as ObservationContextField[]) {\n const value = source[field];\n if (!isSafeField(field, value)) continue;\n sanitized[field] = value;\n }\n\n return Object.keys(sanitized).length === 0 ? undefined : sanitized;\n}\n\n/** Encode only the sanitized allowlist; absence stays absence. */\nexport function encodeObservationContextHeader(input: unknown): string | undefined {\n const sanitized = sanitizeObservationContext(input);\n return sanitized === undefined ? undefined : JSON.stringify(sanitized);\n}\n\n/** Decode an untrusted HTTP header without ever throwing into request handling. */\nexport function decodeObservationContextHeader(\n value: string | null | undefined,\n): WireObservationContext | undefined {\n if (\n typeof value !== \"string\" ||\n value.length === 0 ||\n value.length > MAX_OBSERVATION_HEADER_LENGTH\n ) {\n return undefined;\n }\n try {\n return sanitizeObservationContext(JSON.parse(value));\n } catch {\n return undefined;\n }\n}\n\nfunction isSafeField(field: ObservationContextField, value: unknown): value is string {\n if (typeof value !== \"string\") return false;\n const rule = FIELD_RULES[field];\n return (\n value.length > 0 &&\n value.length <= rule.maxLength &&\n value === value.trim() &&\n !value.includes(\"://\") &&\n !containsSensitiveMaterial(value) &&\n rule.pattern.test(value)\n );\n}\n","// The actor-scope backend contract (A2-Q3A · blueprint §2 moves ledger).\n//\n// The 17 typed function references and the five hand-rolled `Wire*` types that\n// used to sit inside `client/actor-scope.ts` live here. `actor-scope.ts` was\n// the second undeclared Convex adapter on the public surface; this module is\n// the declared one. Every function PATH comes from `@capxul/wire`'s\n// `CAPXUL_FUNCTIONS` registry and is proven against the backend by\n// `scripts/lint-wire-contract.mjs` on `check:fast`.\n//\n// The response types are still parameterised by the public money types in\n// `surface/money.ts` (type-only import, no runtime cycle) — L2 moves those\n// shapes into `@capxul/wire` when it rebuilds the ledger.\n\nimport { makeFunctionReference, type FunctionReference } from \"convex/server\";\n\nimport { CAPXUL_FUNCTIONS } from \"@capxul/wire\";\n\nimport type { ActorScopeRef, InsightsSummary } from \"../surface/contacts\";\nimport type { Payment, PaymentMoney, PaymentTiming, Ref } from \"../surface/money\";\n\nexport type BackendRef = Ref;\n\nexport type ActorArgs = { readonly actor: ActorScopeRef };\n\nexport type WireAddressBookEntry = {\n readonly id: string;\n readonly identity?: { readonly label?: string };\n readonly ref: Ref;\n readonly edges: readonly string[];\n readonly label: string | null;\n readonly hidden: boolean;\n};\n\nexport type WireRequestView = {\n readonly id: string;\n readonly payer?: Ref;\n readonly issuer: Ref;\n readonly amount: PaymentMoney;\n readonly reference: string;\n readonly status: string;\n readonly settledPaymentId?: string | null;\n readonly settledPayment?: PaymentPayload;\n readonly settledPaymentStatus?: Payment[\"status\"];\n readonly settledPaymentTiming?: PaymentTiming;\n readonly expiresAt?: number | null;\n readonly createdAt?: number;\n readonly updatedAt?: number;\n};\n\nexport type WireInsightsHistory = {\n readonly transactions: readonly PaymentPayload[];\n};\n\nexport type PaymentPayload = Omit<Payment, \"timing\"> & {\n readonly timing?: PaymentTiming;\n readonly release?: PaymentTiming;\n};\n\nexport type WireReconciliationEntry = {\n readonly paymentRequestId: string;\n readonly reference: string;\n readonly status: \"paid\" | \"exception\";\n readonly settledPaymentId: string | null;\n readonly receiptDocumentHash: string | null;\n};\n\nexport type ActorRelationshipFunctions = {\n readonly addressBookList: FunctionReference<\n \"query\",\n \"public\",\n ActorArgs,\n readonly WireAddressBookEntry[]\n >;\n readonly addressBookGet: FunctionReference<\n \"query\",\n \"public\",\n ActorArgs & { readonly ref: BackendRef },\n WireAddressBookEntry | null\n >;\n readonly addressBookAdd: FunctionReference<\n \"mutation\",\n \"public\",\n ActorArgs & { readonly ref: BackendRef; readonly label?: string },\n WireAddressBookEntry\n >;\n readonly addressBookHide: FunctionReference<\n \"mutation\",\n \"public\",\n ActorArgs & { readonly ref: BackendRef },\n WireAddressBookEntry\n >;\n readonly addressBookUnhide: FunctionReference<\n \"mutation\",\n \"public\",\n ActorArgs & { readonly ref: BackendRef },\n WireAddressBookEntry\n >;\n readonly addressBookLabel: FunctionReference<\n \"mutation\",\n \"public\",\n ActorArgs & { readonly ref: BackendRef; readonly label: string },\n WireAddressBookEntry\n >;\n readonly requestsIssue: FunctionReference<\n \"mutation\",\n \"public\",\n ActorArgs & {\n readonly payer: BackendRef;\n readonly amount: PaymentMoney;\n readonly reference: string;\n readonly memo?: string;\n readonly expiresAt?: number;\n },\n WireRequestView\n >;\n readonly requestsList: FunctionReference<\n \"query\",\n \"public\",\n ActorArgs,\n readonly WireRequestView[]\n >;\n readonly requestsGet: FunctionReference<\n \"query\",\n \"public\",\n ActorArgs & { readonly paymentRequestId: string },\n WireRequestView | null\n >;\n readonly requestsCancel: FunctionReference<\n \"mutation\",\n \"public\",\n ActorArgs & { readonly paymentRequestId: string },\n WireRequestView\n >;\n readonly requestsReconcile: FunctionReference<\n \"query\",\n \"public\",\n ActorArgs,\n readonly WireReconciliationEntry[]\n >;\n readonly inboxList: FunctionReference<\"query\", \"public\", ActorArgs, readonly WireRequestView[]>;\n readonly inboxApprove: FunctionReference<\n \"mutation\",\n \"public\",\n ActorArgs & { readonly paymentRequestId: string; readonly timing?: PaymentTiming },\n WireRequestView\n >;\n readonly inboxDecline: FunctionReference<\n \"mutation\",\n \"public\",\n ActorArgs & { readonly paymentRequestId: string },\n WireRequestView\n >;\n readonly insightsSummary: FunctionReference<\"query\", \"public\", ActorArgs, InsightsSummary>;\n readonly insightsHistory: FunctionReference<\"query\", \"public\", ActorArgs, WireInsightsHistory>;\n};\n\nexport const actorScopeContract: ActorRelationshipFunctions = {\n addressBookList: makeFunctionReference<\"query\", ActorArgs, readonly WireAddressBookEntry[]>(\n CAPXUL_FUNCTIONS[\"financialOps/addressBook\"].list,\n ),\n addressBookGet: makeFunctionReference<\n \"query\",\n ActorArgs & { readonly ref: BackendRef },\n WireAddressBookEntry | null\n >(CAPXUL_FUNCTIONS[\"financialOps/addressBook\"].get),\n addressBookAdd: makeFunctionReference<\n \"mutation\",\n ActorArgs & { readonly ref: BackendRef; readonly label?: string },\n WireAddressBookEntry\n >(CAPXUL_FUNCTIONS[\"financialOps/addressBook\"].add),\n addressBookHide: makeFunctionReference<\n \"mutation\",\n ActorArgs & { readonly ref: BackendRef },\n WireAddressBookEntry\n >(CAPXUL_FUNCTIONS[\"financialOps/addressBook\"].hide),\n addressBookUnhide: makeFunctionReference<\n \"mutation\",\n ActorArgs & { readonly ref: BackendRef },\n WireAddressBookEntry\n >(CAPXUL_FUNCTIONS[\"financialOps/addressBook\"].unhide),\n addressBookLabel: makeFunctionReference<\n \"mutation\",\n ActorArgs & { readonly ref: BackendRef; readonly label: string },\n WireAddressBookEntry\n >(CAPXUL_FUNCTIONS[\"financialOps/addressBook\"].label),\n requestsIssue: makeFunctionReference<\n \"mutation\",\n ActorArgs & {\n readonly payer: BackendRef;\n readonly amount: PaymentMoney;\n readonly reference: string;\n readonly memo?: string;\n readonly expiresAt?: number;\n },\n WireRequestView\n >(CAPXUL_FUNCTIONS[\"financialOps/requestsInbox\"].issue),\n requestsList: makeFunctionReference<\"query\", ActorArgs, readonly WireRequestView[]>(\n CAPXUL_FUNCTIONS[\"financialOps/requestsInbox\"].list,\n ),\n requestsGet: makeFunctionReference<\n \"query\",\n ActorArgs & { readonly paymentRequestId: string },\n WireRequestView | null\n >(CAPXUL_FUNCTIONS[\"financialOps/requestsInbox\"].get),\n requestsCancel: makeFunctionReference<\n \"mutation\",\n ActorArgs & { readonly paymentRequestId: string },\n WireRequestView\n >(CAPXUL_FUNCTIONS[\"financialOps/requestsInbox\"].cancel),\n requestsReconcile: makeFunctionReference<\"query\", ActorArgs, readonly WireReconciliationEntry[]>(\n CAPXUL_FUNCTIONS[\"financialOps/requestsInbox\"].reconcile,\n ),\n inboxList: makeFunctionReference<\"query\", ActorArgs, readonly WireRequestView[]>(\n CAPXUL_FUNCTIONS[\"financialOps/requestsInbox\"].inboxList,\n ),\n inboxApprove: makeFunctionReference<\n \"mutation\",\n ActorArgs & { readonly paymentRequestId: string; readonly timing?: PaymentTiming },\n WireRequestView\n >(CAPXUL_FUNCTIONS[\"financialOps/requestsInbox\"].approve),\n inboxDecline: makeFunctionReference<\n \"mutation\",\n ActorArgs & { readonly paymentRequestId: string },\n WireRequestView\n >(CAPXUL_FUNCTIONS[\"financialOps/requestsInbox\"].decline),\n insightsSummary: makeFunctionReference<\"query\", ActorArgs, InsightsSummary>(\n CAPXUL_FUNCTIONS[\"financialOps/insights\"].summary,\n ),\n insightsHistory: makeFunctionReference<\"query\", ActorArgs, WireInsightsHistory>(\n CAPXUL_FUNCTIONS[\"financialOps/insights\"].history,\n ),\n};\n","import { Errors, type CapxulError } from \"@capxul/errors\";\nimport type { InboxStatus, RequestStatus } from \"@capxul/wire\";\n\nimport type {\n DepositInstructions,\n MeMethods,\n Payment,\n PaymentMoney,\n PaymentTiming,\n ReconciliationEntry,\n Ref,\n} from \"./money\";\nimport {\n actorScopeContract,\n type BackendRef,\n type PaymentPayload,\n type WireAddressBookEntry,\n type WireReconciliationEntry,\n type WireRequestView,\n} from \"../contract/actor-scope\";\nimport type { ConvexCallPort } from \"../ports/convex-call\";\nimport { runIfActive } from \"./to-capxul-result\";\nimport type { CapxulResult } from \"./types\";\n\nexport type ActorScopeRef =\n | { readonly kind: \"account\" }\n | { readonly kind: \"org\"; readonly orgId: string };\n\nexport interface ActorProfile {\n readonly actor: ActorScopeRef;\n readonly displayName: string | null;\n readonly email?: string;\n readonly handle?: string;\n}\n\nexport interface AddressBookEntry {\n readonly id: string;\n readonly ref: Ref;\n readonly label: string;\n readonly relationship: readonly (\"paid\" | \"paidBy\" | \"requested\" | \"member\" | \"employee\")[];\n readonly hidden: boolean;\n}\n\nexport interface AddressBookAddInput {\n readonly ref: Ref;\n readonly label?: string;\n}\n\nexport interface AddressBookLabelInput {\n readonly entryId: string;\n readonly label: string;\n}\n\nexport interface AddressBookMethods {\n list(options?: {\n readonly signal?: AbortSignal;\n }): Promise<CapxulResult<readonly AddressBookEntry[]>>;\n get(\n entryId: string,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<AddressBookEntry | null>>;\n add(\n input: AddressBookAddInput,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<AddressBookEntry>>;\n hide(\n entryId: string,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<AddressBookEntry>>;\n unhide(\n entryId: string,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<AddressBookEntry>>;\n label(\n input: AddressBookLabelInput,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<AddressBookEntry>>;\n}\n\nexport interface ActorRequest {\n readonly id: string;\n readonly payer?: Ref;\n readonly amount: PaymentMoney;\n readonly reference: string;\n readonly status: RequestStatus;\n readonly expiresAt: number | null;\n}\n\nexport interface ActorRequestIssueInput {\n readonly payer: Ref;\n readonly amount: PaymentMoney;\n readonly reference: string;\n readonly memo?: string;\n readonly expiresAt?: number;\n}\n\nexport interface ActorRequestsMethods {\n issue(\n input: ActorRequestIssueInput,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<ActorRequest>>;\n list(options?: { readonly signal?: AbortSignal }): Promise<CapxulResult<readonly ActorRequest[]>>;\n get(\n requestId: string,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<ActorRequest | null>>;\n cancel(\n requestId: string,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<ActorRequest>>;\n reconcile(options?: {\n readonly signal?: AbortSignal;\n }): Promise<CapxulResult<readonly ReconciliationEntry[]>>;\n}\n\nexport interface InboxItem {\n readonly id: string;\n readonly issuer: Ref;\n readonly amount: PaymentMoney;\n readonly reference: string;\n readonly status: InboxStatus;\n}\n\nexport interface InboxApproveInput {\n readonly requestId: string;\n readonly timing?: PaymentTiming;\n}\n\nexport interface InboxMethods {\n list(options?: { readonly signal?: AbortSignal }): Promise<CapxulResult<readonly InboxItem[]>>;\n approve(\n input: InboxApproveInput,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<Payment>>;\n decline(\n requestId: string,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<InboxItem>>;\n}\n\nexport interface InsightsSummary {\n readonly pending: { readonly count: number; readonly total: PaymentMoney };\n readonly paidThisMonth: { readonly count: number; readonly total: PaymentMoney };\n readonly drafts: { readonly count: number };\n readonly reconciliation: { readonly open: number; readonly exceptions: number };\n}\n\nexport interface InsightsMethods {\n summary(options?: { readonly signal?: AbortSignal }): Promise<CapxulResult<InsightsSummary>>;\n history(options?: { readonly signal?: AbortSignal }): Promise<CapxulResult<readonly Payment[]>>;\n}\n\nexport interface ActorProfileMethods {\n get(options?: { readonly signal?: AbortSignal }): Promise<CapxulResult<ActorProfile>>;\n depositInstructions(options?: {\n readonly signal?: AbortSignal;\n }): Promise<CapxulResult<DepositInstructions>>;\n}\n\nexport interface ActorRelationshipMethods {\n readonly addressBook: AddressBookMethods;\n readonly requests: ActorRequestsMethods;\n readonly inbox: InboxMethods;\n readonly insights: InsightsMethods;\n readonly profile: ActorProfileMethods;\n}\n\nexport function makeActorRelationshipMethods(deps: {\n readonly actor: ActorScopeRef;\n readonly accountProfileMethods?: MeMethods;\n readonly convexCall?: ConvexCallPort;\n}): ActorRelationshipMethods {\n const domain = deps.actor.kind === \"account\" ? \"account\" : \"org\";\n const actor = deps.actor;\n const convexCall = deps.convexCall;\n if (convexCall === undefined) {\n return makeNotImplementedActorRelationshipMethods(deps, domain);\n }\n const fns = actorScopeContract;\n return {\n addressBook: {\n list: (options) =>\n mapOk(\n awaitableConvex(options?.signal, \"addressBook.list\", () =>\n convexCall.query(fns.addressBookList, { actor }),\n ),\n (entries) => entries.map(mapAddressBookEntry),\n ),\n get: async (entryId, options) => {\n const ref = refFromEntryId(entryId);\n if (!ref.ok) return ref;\n return mapOk(\n await awaitableConvex(options?.signal, \"addressBook.get\", () =>\n convexCall.query(fns.addressBookGet, { actor, ref: ref.value }),\n ),\n (entry) => (entry === null ? null : mapAddressBookEntry(entry)),\n );\n },\n add: async (input, options) => {\n const ref = normalizeRefForBackend(input.ref, \"ref\");\n if (!ref.ok) return ref;\n return mapOk(\n await awaitableConvex(options?.signal, \"addressBook.add\", () =>\n convexCall.mutation(fns.addressBookAdd, {\n actor,\n ref: ref.value,\n ...(input.label === undefined ? {} : { label: input.label }),\n }),\n ),\n mapAddressBookEntry,\n );\n },\n hide: async (entryId, options) => {\n const ref = refFromEntryId(entryId);\n if (!ref.ok) return ref;\n return mapOk(\n await awaitableConvex(options?.signal, \"addressBook.hide\", () =>\n convexCall.mutation(fns.addressBookHide, { actor, ref: ref.value }),\n ),\n mapAddressBookEntry,\n );\n },\n unhide: async (entryId, options) => {\n const ref = refFromEntryId(entryId);\n if (!ref.ok) return ref;\n return mapOk(\n await awaitableConvex(options?.signal, \"addressBook.unhide\", () =>\n convexCall.mutation(fns.addressBookUnhide, { actor, ref: ref.value }),\n ),\n mapAddressBookEntry,\n );\n },\n label: async (input, options) => {\n const ref = refFromEntryId(input.entryId);\n if (!ref.ok) return ref;\n return mapOk(\n await awaitableConvex(options?.signal, \"addressBook.label\", () =>\n convexCall.mutation(fns.addressBookLabel, {\n actor,\n ref: ref.value,\n label: input.label,\n }),\n ),\n mapAddressBookEntry,\n );\n },\n },\n requests: {\n issue: async (input, options) => {\n const payer = normalizeRefForBackend(input.payer, \"payer\");\n if (!payer.ok) return payer;\n return mapOk(\n await awaitableConvex(options?.signal, \"requests.issue\", () =>\n convexCall.mutation(fns.requestsIssue, {\n actor,\n payer: payer.value,\n amount: input.amount,\n reference: input.reference,\n ...(input.memo === undefined ? {} : { memo: input.memo }),\n ...(input.expiresAt === undefined ? {} : { expiresAt: input.expiresAt }),\n }),\n ),\n (request) => mapActorRequest(request, input.payer),\n );\n },\n list: (options) =>\n mapOk(\n awaitableConvex(options?.signal, \"requests.list\", () =>\n convexCall.query(fns.requestsList, { actor }),\n ),\n (requests) => requests.map((request) => mapActorRequest(request)),\n ),\n get: (requestId, options) =>\n mapOk(\n awaitableConvex(options?.signal, \"requests.get\", () =>\n convexCall.query(fns.requestsGet, { actor, paymentRequestId: requestId }),\n ),\n (request) => (request === null ? null : mapActorRequest(request)),\n ),\n cancel: (requestId, options) =>\n mapOk(\n awaitableConvex(options?.signal, \"requests.cancel\", () =>\n convexCall.mutation(fns.requestsCancel, { actor, paymentRequestId: requestId }),\n ),\n (request) => mapActorRequest(request),\n ),\n reconcile: async (options) => {\n return mapOk(\n awaitableConvex(options?.signal, \"requests.reconcile\", () =>\n convexCall.query(fns.requestsReconcile, { actor }),\n ),\n (entries) => entries.map(mapReconciliationEntry),\n );\n },\n },\n inbox: {\n list: (options) =>\n mapOk(\n awaitableConvex(options?.signal, \"inbox.list\", () =>\n convexCall.query(fns.inboxList, { actor }),\n ),\n (items) => items.map(mapInboxItem),\n ),\n approve: (input, options) =>\n mapOk(\n awaitableConvex(options?.signal, \"inbox.approve\", () =>\n convexCall.mutation(fns.inboxApprove, {\n actor,\n paymentRequestId: input.requestId,\n ...(input.timing === undefined ? {} : { timing: input.timing }),\n }),\n ),\n mapApprovedInboxPayment,\n ),\n decline: (requestId, options) =>\n mapOk(\n awaitableConvex(options?.signal, \"inbox.decline\", () =>\n convexCall.mutation(fns.inboxDecline, { actor, paymentRequestId: requestId }),\n ),\n mapInboxItem,\n ),\n },\n insights: {\n summary: (options) =>\n awaitableConvex(options?.signal, \"insights.summary\", () =>\n convexCall.query(fns.insightsSummary, { actor }),\n ),\n history: (options) =>\n mapOk(\n awaitableConvex(options?.signal, \"insights.history\", () =>\n convexCall.query(fns.insightsHistory, { actor }),\n ),\n (history) => history.transactions.map(normalizePaymentTiming),\n ),\n },\n profile: {\n get: (options) => {\n if (deps.actor.kind === \"account\" && deps.accountProfileMethods !== undefined) {\n return mapAccountProfile(deps.accountProfileMethods.get(options));\n }\n return missingConvexCall(`${domain}.profile.get`);\n },\n depositInstructions: (options) => {\n if (deps.actor.kind === \"account\" && deps.accountProfileMethods !== undefined) {\n return deps.accountProfileMethods.depositInstructions(options);\n }\n return missingConvexCall(`${domain}.profile.depositInstructions`);\n },\n },\n };\n}\n\nfunction makeNotImplementedActorRelationshipMethods(\n deps: {\n readonly actor: ActorScopeRef;\n readonly accountProfileMethods?: MeMethods;\n },\n domain: string,\n): ActorRelationshipMethods {\n return {\n addressBook: {\n list: () => missingConvexCall(\"addressBook.list\"),\n get: () => missingConvexCall(\"addressBook.get\"),\n add: () => missingConvexCall(\"addressBook.add\"),\n hide: () => missingConvexCall(\"addressBook.hide\"),\n unhide: () => missingConvexCall(\"addressBook.unhide\"),\n label: () => missingConvexCall(\"addressBook.label\"),\n },\n requests: {\n issue: () => missingConvexCall(\"requests.issue\"),\n list: () => missingConvexCall(\"requests.list\"),\n get: () => missingConvexCall(\"requests.get\"),\n cancel: () => missingConvexCall(\"requests.cancel\"),\n reconcile: () => missingConvexCall(\"requests.reconcile\"),\n },\n inbox: {\n list: () => missingConvexCall(\"inbox.list\"),\n approve: () => missingConvexCall(\"inbox.approve\"),\n decline: () => missingConvexCall(\"inbox.decline\"),\n },\n insights: {\n summary: () => missingConvexCall(\"insights.summary\"),\n history: () => missingConvexCall(\"insights.history\"),\n },\n profile: {\n get: (options) => {\n if (deps.actor.kind === \"account\" && deps.accountProfileMethods !== undefined) {\n return mapAccountProfile(deps.accountProfileMethods.get(options));\n }\n return missingConvexCall(`${domain}.profile.get`);\n },\n depositInstructions: (options) => {\n if (deps.actor.kind === \"account\" && deps.accountProfileMethods !== undefined) {\n return deps.accountProfileMethods.depositInstructions(options);\n }\n return missingConvexCall(`${domain}.profile.depositInstructions`);\n },\n },\n };\n}\n\nasync function mapAccountProfile(\n resultPromise: Promise<\n CapxulResult<{\n readonly authUserId: string;\n readonly email: string;\n readonly displayName: string | null;\n }>\n >,\n): Promise<CapxulResult<ActorProfile>> {\n const result = await resultPromise;\n if (!result.ok) return result;\n return {\n ok: true,\n value: {\n actor: { kind: \"account\" },\n displayName: result.value.displayName,\n email: result.value.email,\n },\n };\n}\n\nfunction missingConvexCall<T>(operation: string): Promise<CapxulResult<T>> {\n return Promise.resolve({\n ok: false,\n error: Errors.providerError(\"convex\", operation, \"ConvexCallPort is required\"),\n });\n}\n\nasync function mapOk<T, U>(\n resultOrPromise: CapxulResult<T> | Promise<CapxulResult<T>>,\n f: (value: T) => U,\n): Promise<CapxulResult<U>> {\n const result = await resultOrPromise;\n if (!result.ok) return result;\n return { ok: true, value: f(result.value) };\n}\n\nconst awaitableConvex = runIfActive;\n\nfunction mapAddressBookEntry(entry: WireAddressBookEntry): AddressBookEntry {\n const relationship = new Set<AddressBookEntry[\"relationship\"][number]>();\n for (const edge of entry.edges) {\n if (edge === \"paid\") relationship.add(\"paid\");\n if (edge === \"paidBy\") relationship.add(\"paidBy\");\n if (edge === \"requested\" || edge === \"requestedBy\") relationship.add(\"requested\");\n if (edge === \"member\") relationship.add(\"member\");\n if (edge === \"employee\") relationship.add(\"employee\");\n }\n return {\n id: entry.id,\n ref: entry.ref,\n label: entry.label ?? entry.identity?.label ?? refLabel(entry.ref),\n relationship: [...relationship],\n hidden: entry.hidden,\n };\n}\n\nfunction mapActorRequest(request: WireRequestView, payer?: Ref): ActorRequest {\n const resolvedPayer = request.payer ?? payer;\n return {\n id: request.id,\n ...(resolvedPayer === undefined ? {} : { payer: resolvedPayer }),\n amount: request.amount,\n reference: request.reference,\n status: mapActorRequestStatus(request.status),\n expiresAt: request.expiresAt ?? null,\n };\n}\n\nfunction mapInboxItem(item: WireRequestView): InboxItem {\n return {\n id: item.id,\n issuer: item.issuer,\n amount: item.amount,\n reference: item.reference,\n status: mapInboxStatus(item.status),\n };\n}\n\nfunction mapReconciliationEntry(entry: WireReconciliationEntry): ReconciliationEntry {\n return {\n paymentRequestId: entry.paymentRequestId,\n reference: entry.reference,\n status: entry.status,\n settledPaymentId: entry.settledPaymentId ?? null,\n receiptDocumentHash: entry.receiptDocumentHash ?? null,\n };\n}\n\nfunction mapApprovedInboxPayment(item: WireRequestView): Payment {\n if (item.settledPayment !== undefined) return normalizePaymentTiming(item.settledPayment);\n const zero = { ...item.amount, value: \"0\" };\n const status = item.settledPaymentStatus ?? (item.status === \"paid\" ? \"settled\" : \"pending\");\n const timing = item.settledPaymentTiming ?? { kind: \"instant\" };\n return {\n id: item.settledPaymentId ?? `payment_${item.id}`,\n status,\n amount: item.amount,\n paymentType: \"invoice\",\n recipient: paymentRecipientFromRef(item.issuer),\n documents: [],\n timing,\n released: status === \"settled\" ? item.amount : zero,\n availableToClaim: zero,\n createdAt: item.createdAt ?? 0,\n updatedAt: item.updatedAt ?? item.createdAt ?? 0,\n };\n}\n\nfunction paymentRecipientFromRef(ref: Ref): Payment[\"recipient\"] {\n switch (ref.kind) {\n case \"handle\":\n return { kind: \"handle\", label: ref.handle };\n case \"email\":\n return { kind: \"email\", label: ref.email };\n case \"orgHandle\":\n return { kind: \"org\", label: ref.orgHandle };\n case \"capxulUserId\":\n return { kind: \"capxulUserId\", label: ref.capxulUserId };\n case \"payeeId\":\n return { kind: \"payee\", label: ref.payeeId, payeeId: ref.payeeId };\n }\n}\n\nfunction mapActorRequestStatus(status: string): ActorRequest[\"status\"] {\n switch (status) {\n case \"draft\":\n case \"sent\":\n case \"viewed\":\n case \"paid\":\n case \"pending_settlement\":\n case \"declined\":\n case \"cancelled\":\n case \"expired\":\n return status;\n default:\n return \"sent\";\n }\n}\n\nfunction mapInboxStatus(status: string): InboxItem[\"status\"] {\n switch (status) {\n case \"approved\":\n case \"declined\":\n case \"paid\":\n case \"cancelled\":\n case \"expired\":\n return status;\n case \"pending_settlement\":\n return \"approved\";\n default:\n return \"open\";\n }\n}\n\nfunction normalizePaymentTiming(payment: PaymentPayload): Payment {\n const { release: _release, ...rest } = payment;\n return {\n ...rest,\n timing: payment.timing ?? payment.release ?? { kind: \"instant\" },\n };\n}\n\nexport function normalizeRefForBackend(ref: Ref, field: string): CapxulResult<BackendRef> {\n try {\n if (typeof (ref as unknown) === \"string\") {\n throw Errors.invalidInput(field, \"recipient must be a typed Ref variant\");\n }\n if (typeof ref !== \"object\" || ref === null || !(\"kind\" in ref)) {\n throw Errors.invalidInput(field, \"recipient must be a typed Ref variant\");\n }\n switch (ref.kind) {\n case \"handle\":\n return {\n ok: true,\n value: { kind: \"handle\", handle: handleRefValue(ref.handle, \"handle\") },\n };\n case \"email\":\n return { ok: true, value: { kind: \"email\", email: nonEmptyRefValue(ref.email, \"email\") } };\n case \"orgHandle\":\n return {\n ok: true,\n value: { kind: \"orgHandle\", orgHandle: nonEmptyRefValue(ref.orgHandle, \"orgHandle\") },\n };\n case \"capxulUserId\":\n return {\n ok: true,\n value: {\n kind: \"capxulUserId\",\n capxulUserId: nonEmptyRefValue(ref.capxulUserId, \"capxulUserId\"),\n },\n };\n case \"payeeId\":\n return {\n ok: true,\n value: { kind: \"payeeId\", payeeId: nonEmptyRefValue(ref.payeeId, \"payeeId\") },\n };\n default:\n throw Errors.invalidInput(field, \"recipient must be a known Ref variant\");\n }\n } catch (cause) {\n if (cause instanceof Error && \"code\" in cause) {\n return { ok: false, error: cause as CapxulError };\n }\n return {\n ok: false,\n error: Errors.invalidInput(field, \"recipient must be a typed Ref variant\"),\n };\n }\n}\n\nfunction refFromEntryId(entryId: string): CapxulResult<BackendRef> {\n try {\n const parsed = JSON.parse(entryId) as unknown;\n if (typeof parsed === \"object\" && parsed !== null && \"kind\" in parsed) {\n return normalizeRefForBackend(parsed as Ref, \"entryId\");\n }\n } catch {\n // Not JSON, continue with the canonical backend entry id prefixes.\n }\n const separator = entryId.indexOf(\":\");\n if (separator === -1) {\n return { ok: false, error: Errors.invalidInput(\"entryId\", \"must be an address-book entry id\") };\n }\n const prefix = entryId.slice(0, separator);\n const value = entryId.slice(separator + 1);\n switch (prefix) {\n case \"email\":\n return normalizeRefForBackend({ kind: \"email\", email: value }, \"entryId\");\n case \"user\":\n return normalizeRefForBackend({ kind: \"capxulUserId\", capxulUserId: value }, \"entryId\");\n case \"org\":\n return normalizeRefForBackend({ kind: \"orgHandle\", orgHandle: value }, \"entryId\");\n case \"payee\":\n return normalizeRefForBackend({ kind: \"payeeId\", payeeId: value }, \"entryId\");\n case \"handle\":\n return normalizeRefForBackend({ kind: \"handle\", handle: value }, \"entryId\");\n default:\n return {\n ok: false,\n error: Errors.invalidInput(\"entryId\", \"must be an address-book entry id\"),\n };\n }\n}\n\nfunction nonEmptyRefValue(value: string, field: string): string {\n const trimmed = value.trim();\n if (trimmed.length === 0) {\n throw Errors.invalidInput(field, \"Ref value must be non-empty\");\n }\n if (/^0x[0-9a-fA-F]{40}$/.test(trimmed)) {\n throw Errors.invalidInput(field, \"raw 0x addresses are not valid Ref values\");\n }\n return trimmed;\n}\n\nfunction handleRefValue(value: string, field: string): string {\n const trimmed = nonEmptyRefValue(value, field);\n return trimmed.startsWith(\"@\") ? trimmed.slice(1) : trimmed;\n}\n\nfunction refLabel(ref: Ref): string {\n switch (ref.kind) {\n case \"handle\":\n return ref.handle;\n case \"email\":\n return ref.email;\n case \"orgHandle\":\n return ref.orgHandle;\n case \"capxulUserId\":\n return ref.capxulUserId;\n case \"payeeId\":\n return ref.payeeId;\n }\n}\n","// Public consumer-facing `client.account` surface for the Effect-native\n// rebuild trunk. Ports the public-surface narrowing + readiness-ladder\n// shape from master (`packages/sdk/src/client/account.ts:42-77`) for\n// issue #159, sub-epic child 003b of #120.\n//\n// Diverges from master in two intentional ways for this slice:\n//\n// 1. `SmartAccountPort` is Effect-based on this trunk\n// (`Effect.Effect<SmartAccount | null, SmartAccountError, never>`),\n// so the public methods bridge via the shared `runPortEffect`\n// helper rather than awaiting a `Promise<CapxulResult<...>>`.\n// Mirrors the pattern already used by `makeSmartAccountMethods`.\n//\n// 2. The provision-action path (driving `accountProviderReady →\n// accountReady`) and the deploy path (`SafeDeploymentPort`,\n// `(authUserId, safeAddress)` deploy mutex, `accountPrepared`\n// upgrade) are deferred to sibling issue #161. `ensureReady` is a\n// fixed point relative to `getStatus` in this slice — every\n// readiness state returns the same value `getStatus` would.\n//\n// The `AccountStatus` discriminated union is the SHAPE the future\n// provision + deploy slices will fill; the `accountPrepared` variant is\n// reachable through `getStatus` (deployed-requirement + not-yet-deployed\n// backend record) but the upward `ensureReady → deploySafe` transition\n// lands in #161 with the deploy port.\n\nimport { CapxulError, Errors } from \"@capxul/config\";\nimport { toChainId, type Address, type SmartAccount } from \"@capxul/types\";\nimport { Effect } from \"effect\";\n\nimport type { IdentityActor } from \"../flows/identity\";\nimport type { IdentityEvent } from \"../domain/identity/model\";\nimport type { AuthCachePort } from \"../ports/auth-cache\";\nimport type { SmartAccountPort } from \"../ports/smart-account\";\nimport type { IdentityPort } from \"../ports/identity\";\nimport type { TelemetryPort } from \"../ports/telemetry\";\nimport { captureExceptionSync } from \"../telemetry/capture-exception\";\nimport { emitProvisioningTelemetry } from \"./_shared/provisioning-telemetry\";\nimport type { CapxulSigner } from \"../signer\";\n\nimport type { AccountReadPort } from \"../ports/account-read\";\nimport type { ConvexCallPort } from \"../ports/convex-call\";\nimport { publicIdentityFailure, runPortEffect } from \"./_shared/effect-actor-bridge\";\nimport { accountDepsLayer, accountStatusProgram, currentSession } from \"./account-deps\";\nimport { isRequirementMet, type ProvisioningPhase } from \"./account-lifecycle\";\nimport { mapAccountLifecycle, type AccountLifecycle } from \"./account-lifecycle\";\nimport type { AccountProviderSource, AccountRequirement } from \"./account-providers\";\nimport { makeActorRelationshipMethods, type ActorRelationshipMethods } from \"./contacts\";\nimport type { MeMethods } from \"./money\";\nimport { toCapxulResult } from \"./to-capxul-result\";\nimport type { CapxulResult } from \"./types\";\n\nexport type { AccountLifecycle, AccountSetupStep } from \"./account-lifecycle\";\nexport {\n isSettingUpLifecycle,\n mapAccountLifecycle,\n mapProvisioningFailureStep,\n mapProvisioningPhaseToSetupStep,\n} from \"./account-lifecycle\";\nexport type { ProvisioningFailureStep, ProvisioningPhase } from \"./account-lifecycle\";\nexport { isActiveProvisioningPhase, isRequirementMet } from \"./account-lifecycle\";\n\nexport type AccountStatus =\n | { readonly status: \"notAuthenticated\" }\n | {\n readonly status: \"accountRequired\";\n readonly requirement: AccountRequirement;\n readonly chainId: number;\n }\n | {\n readonly status: \"accountProviderReady\";\n readonly requirement: AccountRequirement;\n readonly chainId: number;\n readonly source: AccountProviderSource;\n readonly signerAddress: Address;\n }\n | {\n readonly status: \"accountPrepared\";\n readonly requirement: AccountRequirement;\n readonly account: SmartAccount;\n readonly deployment: { readonly status: \"counterfactual\" };\n }\n | {\n readonly status: \"accountReady\";\n readonly requirement: AccountRequirement;\n readonly account: SmartAccount | null;\n readonly deployment:\n | { readonly status: \"counterfactual\" }\n | {\n readonly status: \"deployed\";\n readonly deployedAt: SmartAccount[\"deployedAt\"];\n };\n };\n\n/**\n * Public consumer-facing surface (issue #159 · AC1+AC3). Exactly two\n * methods. `provision` and `deploySafe` are intentionally NOT here —\n * they are advanced/testing-only and will live on\n * `client._internal.account` when sibling issue #161 lands. Per\n * `packages/sdk/CONTEXT.md`, the narrowing is enforced at\n * both the type level (the `keyof AccountMethods` extract is exactly\n * `\"getStatus\" | \"ensureReady\"`) and at runtime (the bundle returned\n * here has those two own-keys and nothing else).\n *\n * Per `packages/sdk/docs/architecture.md`, the\n * `AccountStatus` discriminant — including the variants this slice can\n * only reach via `getStatus` (e.g. `accountPrepared`) — is the durable\n * shape consumers depend on. Sibling #161 will extend `ensureReady` to\n * advance the ladder past `accountProviderReady` and from\n * `accountPrepared` to `accountReady(deployed)`; until then, the type\n * surface is stable and the runtime fixed-point is documented.\n */\nexport interface AccountMethods extends ActorRelationshipMethods {\n /**\n * Post-auth account setup lifecycle — domain vocabulary over the internal\n * readiness ladder + provisioning lane (#356).\n */\n getLifecycle(): Promise<CapxulResult<AccountLifecycle>>;\n /** Resume setup after `failed` and return the updated lifecycle snapshot. */\n retrySetup(): Promise<CapxulResult<AccountLifecycle>>;\n /**\n * Internal advanced surface (#161 · AC1). Reserved for the rebuild's\n * own `ensureReady` upward transitions and for testing harnesses;\n * consumers MUST NOT depend on this in production. Tagged\n * `@internal-use` per `.claude/rules/flow-internal-substrate.md`.\n *\n * @internal-use\n */\n readonly _internal: AccountInternalSurface;\n}\n\n/**\n * Internal `provision` + `deploySafe` arms exposed at\n * `client._internal.account` (#161). Each returns `Promise<CapxulResult<T>>`\n * with the same error catalog the public methods use.\n *\n * @internal-use\n */\nexport interface AccountInternalSurface {\n provision(): Promise<CapxulResult<SmartAccount>>;\n deploySafe(observationSource?: unknown): Promise<CapxulResult<SmartAccount>>;\n /** @internal-use Substrate readiness ladder — tests and e2e only. */\n getStatus(): Promise<CapxulResult<AccountStatus>>;\n /** @internal-use Lane runner — tests and e2e only. */\n ensureReady(): Promise<CapxulResult<AccountStatus>>;\n /** @internal-use Provisioning lane phase — tests and e2e only. */\n getProvisioningPhase(): Promise<CapxulResult<ProvisioningPhase>>;\n /** @internal-use Lane retry — tests and e2e only. */\n retryProvisioning(): Promise<CapxulResult<ProvisioningPhase>>;\n}\n\nexport interface MakeAccountMethodsDeps {\n readonly actor: IdentityActor;\n /**\n * Resume-path fallback. `currentSession` consults the actor first; if\n * the actor has no session (e.g. page refresh before any sign-in\n * event), it then reads `authCache.getSession`. Without this,\n * `getStatus` returns `notAuthenticated` on resume even when the cache\n * holds a valid session.\n */\n readonly authCache?: AuthCachePort;\n readonly identityPort: IdentityPort;\n readonly smartAccountPort: SmartAccountPort;\n readonly telemetry?: TelemetryPort;\n readonly chainId: number;\n /**\n * Init-time readiness target. The factory closes over this so the\n * public methods don't need to take a per-call requirement arg.\n * REQUIRED at every boundary — `assembleCapxulClient` always sets it\n * (see `CreateCapxulClientInput`), and hermetic tests that exercise\n * `makeAccountMethods` directly must pass an explicit value (no hidden\n * default; issue #159 · AC4 \"no backwards-compat shims\").\n */\n readonly requirement: AccountRequirement;\n /**\n * Consumer-held signer (PRD #462). The claim path reads `getAddress()` —\n * the ONLY signer interaction at claim time: the backend builds and\n * bootstrap-signs the claim userOp; the user's key signs nothing until\n * their first real transaction. The client never holds an RPC URL, a gas\n * policy, or a bundler.\n */\n readonly signer?: CapxulSigner;\n /** Resolves logical `Account.id` when mapping lifecycle to `ready`. */\n readonly accountReadPort?: AccountReadPort;\n /** Optional account profile delegate for the actor-scope profile surface. */\n readonly profileMethods?: MeMethods;\n /** Convex function-call seam for actor relationship projections. */\n readonly convexCall?: ConvexCallPort;\n}\n\nexport interface MakeAccountMethodsResult {\n readonly methods: AccountMethods;\n readonly kickProvisioning: () => void;\n}\n\nconst provisioningPhase = (\n state: import(\"../domain/identity/model\").IdentityState,\n): ProvisioningPhase => {\n if (state.phase !== \"authenticated\") return { status: \"idle\" };\n switch (state.account.at) {\n case \"unknown\":\n return { status: \"idle\" };\n case \"deriving\":\n return { status: state.account.step };\n case \"counterfactual\":\n return { status: \"ready\" };\n case \"claiming\":\n return { status: \"deploy\" };\n case \"claimed\":\n return { status: \"ready\" };\n case \"failed\":\n return {\n status: \"failed\",\n at: state.account.step,\n error: publicIdentityFailure(state.account.failure),\n };\n }\n};\n\nconst actorFailure = (\n failure: import(\"../domain/machine/shell\").ActorFailure<import(\"@capxul/errors\").CapxulErrorCode>,\n) =>\n new CapxulError(failure.reason === \"WORK_DIED\" ? \"UNKNOWN\" : failure.reason, failure.message, {\n cause: failure,\n ...(failure.details === undefined ? {} : { details: failure.details }),\n layer: \"identity\",\n });\n\nexport function makeAccountMethods(deps: MakeAccountMethodsDeps): MakeAccountMethodsResult {\n // Brand the chain id eagerly at construction so hermetic tests surface\n // bad values now rather than on the first call. The branded value is\n // unused in this slice; sibling #161 (provision + deploy) reads it from\n // `deps` directly.\n toChainId(deps.chainId);\n const requirement: AccountRequirement = deps.requirement;\n\n // Hourglass seam (PRD #209, slice 5): the readiness ladder now lives in\n // `accountStatusProgram` (resolving `AccountDepsTag`), run through the\n // shared `toCapxulResult` bridge. `ensureReady` + the `_internal` arms below\n // still call `getStatus()` and the ports directly.\n const getStatus: AccountInternalSurface[\"getStatus\"] = () =>\n toCapxulResult(accountStatusProgram, accountDepsLayer(deps));\n\n const drive = async (event: IdentityEvent): Promise<CapxulResult<void>> => {\n const result = await Effect.runPromise(Effect.result(deps.actor.ask(event)));\n const state = result._tag === \"Failure\" ? deps.actor.snapshot() : result.success;\n if (\n result._tag === \"Failure\" &&\n state.phase === \"authenticated\" &&\n state.account.at === \"failed\" &&\n state.account.failure.code === result.failure.reason\n ) {\n return {\n ok: false,\n error:\n state.account.step === \"deploy\" && state.account.failure.code === \"PROVIDER_ERROR\"\n ? Errors.providerError(\"signer\", \"getAddress\", state.account.failure.message)\n : publicIdentityFailure(state.account.failure),\n };\n }\n if (result._tag === \"Failure\") return { ok: false, error: actorFailure(result.failure) };\n if (state.phase === \"faulted\") {\n return { ok: false, error: publicIdentityFailure(state.failure) };\n }\n if (state.phase === \"authenticated\" && state.account.at === \"failed\") {\n return {\n ok: false,\n error:\n state.account.step === \"deploy\" && state.account.failure.code === \"PROVIDER_ERROR\"\n ? Errors.providerError(\"signer\", \"getAddress\", state.account.failure.message)\n : publicIdentityFailure(state.account.failure),\n };\n }\n return { ok: true, value: undefined };\n };\n\n const loadAccount = async (): Promise<CapxulResult<SmartAccount>> => {\n const session = await currentSession(deps.actor, deps.authCache);\n if (session === null) return { ok: false, error: Errors.notAuthenticated() };\n const loaded = await runPortEffect(deps.smartAccountPort.loadByAuthUserId(session.authUserId));\n if (!loaded.ok) return loaded;\n return loaded.value === null\n ? { ok: false, error: Errors.smartAccountMissing(String(session.authUserId)) }\n : { ok: true, value: loaded.value };\n };\n\n // --- _internal.account.provision (#161 · AC1) ---\n const runProvision = async (): Promise<CapxulResult<SmartAccount>> => {\n const session = await currentSession(deps.actor, deps.authCache);\n if (session === null) return { ok: false, error: Errors.notAuthenticated() };\n const state = deps.actor.snapshot();\n if (state.phase !== \"authenticated\") {\n return { ok: false, error: Errors.notAuthenticated() };\n }\n if (state.account.at === \"unknown\") {\n const ran = await drive({ _tag: \"EnsureAccount\" });\n if (!ran.ok) return ran;\n } else if (state.account.at === \"failed\") {\n const ran = await drive({ _tag: \"RetryAccount\" });\n if (!ran.ok) return ran;\n }\n const loaded = await loadAccount();\n if (loaded.ok && state.account.at === \"unknown\") {\n await emitProvisioningTelemetry(deps.telemetry, loaded.value);\n }\n return loaded;\n };\n\n let provisionInFlight: Promise<CapxulResult<SmartAccount>> | null = null;\n const provisionImpl: AccountInternalSurface[\"provision\"] = () => {\n if (provisionInFlight !== null) return provisionInFlight;\n const pending = runProvision();\n provisionInFlight = pending;\n void pending.finally(() => {\n if (provisionInFlight === pending) provisionInFlight = null;\n });\n return pending;\n };\n\n // --- _internal.account.deploySafe → CLAIM (PRD #462) ---\n //\n // The \"deploy\" step is now the claim: ONE backend-built, bootstrap-signed\n // sponsored userOp (deploy + swapOwner). The signer contributes ONLY its\n // address. AC3 mutex: shared in-process Map<key, in-flight promise>;\n // the backend claim mutex is the authoritative dedup.\n const runDeploySafe = async (\n _observationSource?: unknown,\n ): Promise<CapxulResult<SmartAccount>> => {\n if (provisionInFlight !== null) {\n const provisioned = await provisionInFlight;\n if (!provisioned.ok) return provisioned;\n }\n const session = await currentSession(deps.actor, deps.authCache);\n if (session === null) return { ok: false, error: Errors.notAuthenticated() };\n const state = deps.actor.snapshot();\n if (state.phase !== \"authenticated\") return { ok: false, error: Errors.notAuthenticated() };\n if (state.account.at === \"unknown\" || state.account.at === \"failed\") {\n const provisioned = await provisionImpl();\n if (!provisioned.ok) return provisioned;\n }\n const current = deps.actor.snapshot();\n if (current.phase === \"authenticated\" && current.account.at === \"counterfactual\") {\n const claimed = await drive({ _tag: \"ClaimAccount\" });\n if (!claimed.ok) return claimed;\n }\n return loadAccount();\n };\n\n let deployInFlight: Promise<CapxulResult<SmartAccount>> | null = null;\n const deploySafeImpl: AccountInternalSurface[\"deploySafe\"] = (observationSource) => {\n if (deployInFlight !== null) return deployInFlight;\n const pending = runDeploySafe(observationSource);\n deployInFlight = pending;\n void pending.finally(() => {\n if (deployInFlight === pending) deployInFlight = null;\n });\n return pending;\n };\n\n // ensureReady advances the ladder by delegating to the lane runner.\n const ensureReady: AccountInternalSurface[\"ensureReady\"] = async () => {\n const status = await getStatus();\n if (!status.ok || isRequirementMet(status.value, requirement)) return status;\n const state = deps.actor.snapshot();\n if (state.phase !== \"authenticated\") {\n return { ok: false, error: Errors.notAuthenticated() };\n }\n const event: IdentityEvent | null =\n state.account.at === \"failed\"\n ? { _tag: \"RetryAccount\" }\n : state.account.at === \"unknown\"\n ? { _tag: \"EnsureAccount\" }\n : state.account.at === \"counterfactual\" && requirement === \"deployed\"\n ? { _tag: \"ClaimAccount\" }\n : null;\n if (event === null) return getStatus();\n const ran = await drive(event);\n if (!ran.ok) return ran;\n if (event._tag === \"EnsureAccount\") {\n const loaded = await loadAccount();\n if (loaded.ok) await emitProvisioningTelemetry(deps.telemetry, loaded.value);\n }\n return getStatus();\n };\n\n const getProvisioningPhase: AccountInternalSurface[\"getProvisioningPhase\"] = async () => {\n return { ok: true, value: provisioningPhase(deps.actor.snapshot()) };\n };\n\n const retryProvisioning: AccountInternalSurface[\"retryProvisioning\"] = async () => {\n const result = await drive({ _tag: \"RetryAccount\" });\n if (!result.ok) return result;\n return { ok: true, value: provisioningPhase(deps.actor.snapshot()) };\n };\n\n const reportAndReturn = (\n error: CapxulError,\n operation = \"getLifecycle\",\n ): { ok: false; error: CapxulError } => {\n if (deps.telemetry) {\n captureExceptionSync(deps.telemetry, error, {\n layer: \"account\",\n operation,\n });\n }\n return { ok: false, error };\n };\n\n const resolveLifecycle = async (): Promise<CapxulResult<AccountLifecycle>> => {\n const phase = provisioningPhase(deps.actor.snapshot());\n const status = await getStatus();\n if (!status.ok) {\n return reportAndReturn(status.error);\n }\n let accountId: string | undefined;\n if (\n status.value.status !== \"notAuthenticated\" &&\n (phase.status === \"ready\" || isRequirementMet(status.value, requirement))\n ) {\n const accountReadPort = deps.accountReadPort;\n if (accountReadPort === undefined) {\n return reportAndReturn(\n Errors.invalidInput(\"account\", \"accountReadPort is required to resolve ready lifecycle\"),\n );\n }\n const account = await runPortEffect(\n accountReadPort.readBalance({ chainId: toChainId(deps.chainId) }),\n );\n if (!account.ok) {\n return reportAndReturn(account.error);\n }\n accountId = String(account.value.id);\n }\n\n return {\n ok: true,\n value: mapAccountLifecycle({\n status: status.value,\n phase,\n requirement,\n ...(accountId === undefined ? {} : { accountId }),\n }),\n };\n };\n\n const getLifecycle: AccountMethods[\"getLifecycle\"] = () => resolveLifecycle();\n\n const retrySetup: AccountMethods[\"retrySetup\"] = async () => {\n const resetSession = (\n deps.signer as (CapxulSigner & { readonly resetSession?: unknown }) | undefined\n )?.resetSession;\n if (typeof resetSession === \"function\") {\n try {\n resetSession.call(deps.signer);\n } catch (cause) {\n return reportAndReturn(\n cause instanceof CapxulError\n ? cause\n : Errors.providerError(\"openfort\", \"resetSession\", cause, {\n failure_mode: \"unknown\",\n }),\n \"retrySetup\",\n );\n }\n }\n const retried = await drive({ _tag: \"RetryAccount\" });\n if (!retried.ok) return reportAndReturn(retried.error, \"retrySetup\");\n return resolveLifecycle();\n };\n\n return {\n methods: {\n ...makeActorRelationshipMethods({\n actor: { kind: \"account\" },\n ...(deps.convexCall === undefined ? {} : { convexCall: deps.convexCall }),\n ...(deps.profileMethods === undefined\n ? {}\n : { accountProfileMethods: deps.profileMethods }),\n }),\n getLifecycle,\n retrySetup,\n _internal: {\n provision: provisionImpl,\n deploySafe: deploySafeImpl,\n getStatus,\n ensureReady,\n getProvisioningPhase,\n retryProvisioning,\n },\n },\n kickProvisioning: () => {\n const state = deps.actor.snapshot();\n if (\n requirement !== \"none\" &&\n state.phase === \"authenticated\" &&\n state.profileComplete &&\n state.account.at === \"unknown\"\n ) {\n void provisionImpl();\n }\n },\n };\n}\n// Re-export the AccountProvider lane types so consumers depending on\n// `import { AccountProvider } from \"./account\"` (mirroring master)\n// continue to work. The runtime factories stay in\n// `./account-providers` (the canonical home; #158 landed them there).\nexport type {\n AccountProvider,\n AccountProviderSource,\n AccountRequirement,\n} from \"./account-providers\";\n","","import { Context, Data, Effect } from \"effect\";\nimport type { CapxulError } from \"@capxul/config\";\nimport type { AuthSession, DurationMs, Email } from \"@capxul/types\";\n\nimport type { CachedJwt } from \"./auth-cache\";\n\nexport type AuthClientResult<A> =\n | { readonly ok: true; readonly value: A }\n | { readonly ok: false; readonly error: CapxulError };\n\nexport type AuthClientOperationOptions = {\n readonly signal?: AbortSignal;\n};\n\nexport type SendOtpInput = {\n readonly email: Email;\n};\n\nexport type CanSendOtpInput = {\n readonly email: Email;\n};\n\nexport type CanSendOtpStatus = {\n readonly allowed: boolean;\n readonly cooldownMs: DurationMs;\n};\n\nexport type VerifyOtpInput = {\n readonly email: Email;\n readonly otp: string;\n};\n\nexport type GetConvexJwtOptions = AuthClientOperationOptions & {\n readonly forceRefresh?: boolean;\n};\n\nexport class AuthClientError extends Data.TaggedError(\"AuthClientError\")<{\n readonly operation: string;\n readonly kind: string;\n readonly cause: unknown;\n}> {}\n\n// Platform port for authentication operations. Cancellation lives only on the\n// options bag; input objects do not carry `signal`.\nexport interface AuthClientPort {\n canSendOtp(\n input: CanSendOtpInput,\n options?: AuthClientOperationOptions,\n ): Effect.Effect<CanSendOtpStatus, AuthClientError>;\n sendOtp(\n input: SendOtpInput,\n options?: AuthClientOperationOptions,\n ): Effect.Effect<void, AuthClientError>;\n verifyOtp(\n input: VerifyOtpInput,\n options?: AuthClientOperationOptions,\n ): Effect.Effect<AuthSession, AuthClientError>;\n getSession(\n options?: AuthClientOperationOptions,\n ): Effect.Effect<AuthSession | null, AuthClientError>;\n signOut(options?: AuthClientOperationOptions): Effect.Effect<void, AuthClientError>;\n /**\n * Fetches a Convex-aud JWT from `/api/auth/convex/token` (W7). Server mints\n * a fresh JWT on every call per Probe A's 2026-05-19 finding (RS256, 900 s\n * lifetime, `iss = <site-url>`, `aud = convex`). The caller (the SDK's\n * `tokenProvider` wired into ConvexCallPort) is responsible for the\n * `exp - 30s` proactive cache + `forceRefresh` callback handshake.\n */\n getConvexJwt(options?: GetConvexJwtOptions): Effect.Effect<CachedJwt, AuthClientError>;\n}\n\nexport class AuthClientPortTag extends Context.Service<AuthClientPortTag, AuthClientPort>()(\n \"@capxul/sdk/ports/AuthClientPort\",\n) {}\n","import type { CapxulError } from \"@capxul/config\";\nimport { Effect } from \"effect\";\n\nimport type { CachedJwt } from \"../../ports/auth-cache\";\nimport {\n AuthClientError,\n type CanSendOtpInput,\n type CanSendOtpStatus,\n type AuthClientOperationOptions,\n type AuthClientPort,\n type AuthClientResult,\n type GetConvexJwtOptions,\n type SendOtpInput,\n type VerifyOtpInput,\n} from \"../../ports/auth-client\";\nimport type { AuthSession } from \"@capxul/types\";\n\nexport interface PromiseAuthClientAdapter {\n readonly canSendOtp: (\n input: CanSendOtpInput,\n options?: AuthClientOperationOptions,\n ) => Promise<AuthClientResult<CanSendOtpStatus>>;\n readonly sendOtp: (\n input: SendOtpInput,\n options?: AuthClientOperationOptions,\n ) => Promise<AuthClientResult<void>>;\n readonly verifyOtp: (\n input: VerifyOtpInput,\n options?: AuthClientOperationOptions,\n ) => Promise<AuthClientResult<AuthSession>>;\n readonly getSession: (\n options?: AuthClientOperationOptions,\n ) => Promise<AuthClientResult<AuthSession | null>>;\n readonly signOut: (options?: AuthClientOperationOptions) => Promise<AuthClientResult<void>>;\n readonly getConvexJwt: (options?: GetConvexJwtOptions) => Promise<AuthClientResult<CachedJwt>>;\n}\n\nexport function authClientPortFromPromiseAdapter(\n adapter: PromiseAuthClientAdapter,\n): AuthClientPort {\n return {\n canSendOtp: (input, options) =>\n fromResult(\"canSendOtp\", () => adapter.canSendOtp(input, options)),\n sendOtp: (input, options) => fromResult(\"sendOtp\", () => adapter.sendOtp(input, options)),\n verifyOtp: (input, options) => fromResult(\"verifyOtp\", () => adapter.verifyOtp(input, options)),\n getSession: (options) => fromResult(\"getSession\", () => adapter.getSession(options)),\n signOut: (options) => fromResult(\"signOut\", () => adapter.signOut(options)),\n getConvexJwt: (options) => fromResult(\"getConvexJwt\", () => adapter.getConvexJwt(options)),\n };\n}\n\nfunction fromResult<A>(\n operation: string,\n run: () => Promise<AuthClientResult<A>>,\n): Effect.Effect<A, AuthClientError> {\n return Effect.tryPromise({\n try: run,\n catch: (cause) => new AuthClientError({ operation, kind: \"thrown\", cause }),\n }).pipe(\n Effect.flatMap((result) =>\n result.ok\n ? Effect.succeed(result.value)\n : Effect.fail(\n new AuthClientError({\n operation,\n kind: errorKind(result.error),\n cause: result.error,\n }),\n ),\n ),\n );\n}\n\nfunction errorKind(error: CapxulError): string {\n if (error.code === \"CANCELLED\") return \"cancelled\";\n if (error.code === \"NETWORK_ERROR\") return \"network\";\n if (error.code === \"INVALID_INPUT\" || error.code === \"OTP_EXPIRED\") return \"validation\";\n return \"provider\";\n}\n","import { Context, Data, Effect } from \"effect\";\nimport type { CapxulError, CapxulErrorCode, CapxulErrorDetails } from \"@capxul/config\";\nimport type {\n AllowedOrigin,\n AppId,\n ChainId,\n DurationMs,\n EpochMs,\n PublishableKey,\n SessionToken,\n} from \"@capxul/types\";\nimport type { EngineeringTelemetryBootstrapPolicyV1 } from \"@capxul/wire\";\n\nexport type BootstrapInput = {\n readonly publishableKey: PublishableKey;\n /**\n * Browser callers send the App origin so bootstrap can enforce the\n * publishable-key allowlist. Node/server callers may omit it; the backend\n * only applies the origin allowlist when an origin is present.\n */\n readonly origin?: AllowedOrigin;\n};\n\nexport type BootstrapResolution = {\n readonly applicationId: AppId;\n readonly chainId: ChainId;\n /**\n * SDK-handshake session token — distinct from the user-auth `AuthSession`\n * token issued by `AuthClientPort`. Both use the `SessionToken` brand for\n * opaque-string discipline; the issuance source distinguishes them.\n */\n readonly sessionToken: SessionToken;\n readonly issuedAt: EpochMs;\n readonly expiresIn: DurationMs;\n readonly authBaseUrl: string;\n readonly convexUrl: string;\n readonly siteBaseUrl: string;\n readonly openfortPublishableKey: string;\n readonly shieldPublishableKey: string;\n readonly engineeringTelemetry?: EngineeringTelemetryBootstrapPolicyV1;\n};\n\nexport type BootstrapErrorKind =\n | \"notAuthenticated\"\n | \"network\"\n | \"provider\"\n | \"malformedBody\"\n | \"invalidInput\"\n | \"rateLimited\";\n\nexport class BootstrapError extends Data.TaggedError(\"BootstrapError\")<{\n readonly operation: \"resolve\";\n readonly kind: BootstrapErrorKind;\n readonly publicCode: CapxulErrorCode;\n readonly cause: unknown;\n readonly details?: CapxulErrorDetails;\n}> {}\n\nexport function bootstrapErrorFromCapxul(\n kind: BootstrapErrorKind,\n error: CapxulError,\n): BootstrapError {\n return new BootstrapError({\n operation: \"resolve\",\n kind,\n publicCode: error.code,\n cause: error,\n ...(kind === \"notAuthenticated\" || error.details === undefined\n ? {}\n : { details: error.details }),\n });\n}\n\nexport interface BootstrapPort {\n readonly resolve: (input: BootstrapInput) => Effect.Effect<BootstrapResolution, BootstrapError>;\n}\n\nexport class BootstrapPortTag extends Context.Service<BootstrapPortTag, BootstrapPort>()(\n \"@capxul/sdk/ports/BootstrapPort\",\n) {}\n","import { Context, Data, Effect } from \"effect\";\n\nimport type { DurationMs, EpochMs } from \"@capxul/types\";\n\nexport interface ClockPort {\n readonly now: Effect.Effect<EpochMs, ClockError>;\n readonly sleep: (duration: DurationMs) => Effect.Effect<void, ClockError>;\n}\n\nexport class ClockError extends Data.TaggedError(\"ClockError\")<{\n readonly operation: \"now\" | \"sleep\" | \"initialize\";\n readonly cause: unknown;\n}> {}\n\nexport class ClockPortTag extends Context.Service<ClockPortTag, ClockPort>()(\n \"@capxul/sdk/ports/ClockPort\",\n) {}\n","import { Context, Data, Effect } from \"effect\";\nimport type { FunctionReference } from \"convex/server\";\n\nimport type { CapxulError, CapxulErrorCode, CapxulErrorDetails } from \"@capxul/config\";\n\n/**\n * Canonical teardown handle for substrate-level reactive callbacks.\n *\n * Calling it stops the subscription; no further snapshots will be delivered\n * to the callback after the first invocation. Calling more than once is a\n * no-op (idempotent).\n *\n * @internal-use\n */\nexport type Unsubscribe = () => void;\n\n/**\n * Snapshot is the substrate discriminated union for reactive callbacks over\n * `ConvexCallPort.subscribe`. The public SDK surface is imperative\n * (`Promise<CapxulResult>`).\n *\n * - `loading` · initial state before any value arrives from the substrate\n * - `ok` · a successful snapshot carrying `value`\n * - `error` · a failed snapshot carrying a typed error (defaults to\n * `CapxulError`)\n *\n * The substrate guarantees the first snapshot is `loading` (CC8 in the\n * `ConvexCallPort` contract); subsequent snapshots carry `ok` or `error`\n * per the underlying transport.\n *\n * Per ARCH-LOCK-1 (`docs/decisions/stage-4-reactivity-pivot.html`), domain\n * ports do not expose reactive callback methods — this pair lives on the\n * substrate port that owns `subscribe` (#1145 re-homed it from the former\n * `ports/subscription.ts`, which was never a port).\n *\n * @internal-use\n */\nexport type Snapshot<T, E = CapxulError> =\n | { readonly status: \"loading\" }\n | { readonly status: \"ok\"; readonly value: T }\n | { readonly status: \"error\"; readonly error: E };\n\nexport class ConvexCallError extends Data.TaggedError(\"ConvexCallError\")<{\n readonly operation: string;\n readonly publicCode: CapxulErrorCode;\n readonly publicError: CapxulError;\n readonly cause: unknown;\n readonly details?: CapxulErrorDetails;\n}> {}\n\nexport function convexCallErrorFromCapxul(operation: string, error: CapxulError): ConvexCallError {\n return new ConvexCallError({\n operation,\n publicCode: error.code,\n publicError: error,\n cause: error,\n ...(error.details === undefined ? {} : { details: error.details }),\n });\n}\n\nexport interface ConvexCallPort {\n query<TArgs extends Record<string, unknown>, TOutput>(\n fn: FunctionReference<\"query\", \"public\", TArgs, TOutput>,\n args: TArgs,\n ): Effect.Effect<TOutput, ConvexCallError>;\n\n mutation<TArgs extends Record<string, unknown>, TOutput>(\n fn: FunctionReference<\"mutation\", \"public\", TArgs, TOutput>,\n args: TArgs,\n ): Effect.Effect<TOutput, ConvexCallError>;\n\n action<TArgs extends Record<string, unknown>, TOutput>(\n fn: FunctionReference<\"action\", \"public\", TArgs, TOutput>,\n args: TArgs,\n ): Effect.Effect<TOutput, ConvexCallError>;\n\n /**\n * Substrate-level reactive transport over Convex's `onUpdate`.\n *\n * @internal-use — substrate only; see `ports/subscription.ts`. Domain\n * ports do not expose reactive callback methods to consumers (ARCH-LOCK-1).\n */\n subscribe<TArgs extends Record<string, unknown>, TOutput>(\n fn: FunctionReference<\"query\", \"public\", TArgs, TOutput>,\n args: TArgs,\n callback: (snapshot: Snapshot<TOutput>) => void,\n ): Effect.Effect<Unsubscribe, ConvexCallError>;\n}\n\nexport class ConvexCallPortTag extends Context.Service<ConvexCallPortTag, ConvexCallPort>()(\n \"@capxul/sdk/ports/ConvexCallPort\",\n) {}\n","import { Context, Data, Effect } from \"effect\";\nimport type { CapxulError, CapxulErrorCode, CapxulErrorDetails } from \"@capxul/config\";\nimport type { Address, AuthUserId, CountryCode, Email, Profile } from \"@capxul/types\";\n\nexport type CreateIdentityInput = {\n readonly authUserId: AuthUserId;\n readonly email: Email;\n readonly displayName?: string;\n readonly country?: CountryCode;\n};\n\nexport type UpdateIdentityInput = {\n readonly authUserId: AuthUserId;\n readonly displayName?: string;\n readonly country?: CountryCode;\n};\n\n/**\n * D-ONBOARD (#669) — the onboarding-complete identity write. Composes the\n * existing create/update write into one idempotent upsert that ALSO sets the\n * `onboarded` flag and persists the optional `withdrawalAddress` (the one\n * allowed raw-0x class). `displayName` + `country` are required at onboarding\n * time. The returned `Profile` is the existing branded shape — the onboarding\n * flags live on the wire row and are not projected onto the read surface.\n */\nexport type CompleteOnboardingIdentityInput = {\n readonly authUserId: AuthUserId;\n readonly email: Email;\n readonly displayName: string;\n readonly country: CountryCode;\n readonly withdrawalAddress?: Address;\n /** #1062: optional globally-unique handle — store-when-present, backend-normalized. */\n readonly username?: string;\n};\n\nexport class IdentityError extends Data.TaggedError(\"IdentityError\")<{\n readonly operation: string;\n readonly publicCode: CapxulErrorCode;\n readonly publicError: CapxulError;\n readonly cause: unknown;\n readonly details?: CapxulErrorDetails;\n}> {}\n\nexport function identityErrorFromCapxul(\n operation: string,\n error: CapxulError,\n cause: unknown = error,\n): IdentityError {\n return new IdentityError({\n operation,\n publicCode: error.code,\n publicError: error,\n cause,\n ...(error.details === undefined ? {} : { details: error.details }),\n });\n}\n\n// First domain port. Sibling to the platform-ports bundle; deliberately NOT a\n// member of `PlatformPorts` — domain ports are composed by consumers per the\n// hexagonal composition contract. See `packages/sdk/docs/architecture.md`.\nexport interface IdentityPort {\n loadByAuthUserId(authUserId: AuthUserId): Effect.Effect<Profile | null, IdentityError, never>;\n create(input: CreateIdentityInput): Effect.Effect<Profile, IdentityError, never>;\n update(input: UpdateIdentityInput): Effect.Effect<Profile, IdentityError, never>;\n /** D-ONBOARD (#669): idempotent upsert that marks the identity onboarded. */\n completeOnboarding(\n input: CompleteOnboardingIdentityInput,\n ): Effect.Effect<Profile, IdentityError, never>;\n}\n\nexport class IdentityPortTag extends Context.Service<IdentityPortTag, IdentityPort>()(\n \"@capxul/sdk/ports/IdentityPort\",\n) {}\n","import type { Address, ChainId, DurationMs } from \"@capxul/types\";\n\n/**\n * Documented brand-erasure helpers for the wire boundary.\n *\n * Branded primitives (`Address`, `ChainId`) carry compile-time tags that\n * vanish at runtime. When sending values across a wire — Convex function\n * args, viem's template-literal-typed parameters, raw JSON — we have to\n * remove the brand at the type level so the wire-side type system accepts\n * the value.\n *\n * Using these helpers (rather than ad-hoc `as number` / `as \\`0x${string}\\``\n * casts) localizes every de-branding site. If we ever need to centralize\n * validation (e.g. \"must not de-brand a placeholder address\"), the change\n * lands here once instead of grep-and-replace across every adapter.\n */\n\n/**\n * De-brand a `ChainId` for the wire. The runtime representation is already\n * `number` — the cast removes the compile-time brand only.\n */\nexport function wireChainId(chainId: ChainId): number {\n return chainId;\n}\n\n/**\n * De-brand a `DurationMs` for the wire. The runtime representation is\n * already `number` — the cast removes the compile-time brand only.\n *\n * Used at Convex mutation call sites where the backend's schema expects\n * a plain `number` for `graceMs` (and similar duration fields). The\n * branded `DurationMs` type is the SDK's discipline; the wire format is\n * agnostic.\n */\nexport function wireDurationMs(duration: DurationMs): number {\n return duration;\n}\n\n/**\n * De-brand an `Address` for viem's `\\`0x${string}\\`` template-literal type.\n * Our `Address` brand is structurally `\\`0x${string}\\`` (lowercased hex)\n * but TypeScript needs an explicit cast to satisfy viem's type signature.\n */\nexport function addressForViem(address: Address): `0x${string}` {\n return address as `0x${string}`;\n}\n","import { parseUnits } from \"viem\";\n\n/**\n * Lower consumer `Money` into an on-chain integer string for guarded writes.\n * Canon `account-balance-model.md` §10 — internal at the SDK boundary only.\n */\nexport function toWei(money: { readonly value: string; readonly decimals: number }): string {\n return parseUnits(money.value, money.decimals).toString();\n}\n","import { Context, Data, Effect } from \"effect\";\nimport type { CapxulError, CapxulErrorCode, CapxulErrorDetails } from \"@capxul/config\";\nimport type { Account, ChainId, Money } from \"@capxul/types\";\n\nexport type ReadAccountBalanceInput = {\n readonly chainId: ChainId;\n};\n\nexport type FundFromFaucetInput = {\n readonly chainId: ChainId;\n readonly amount: Money;\n};\n\nexport type FundFromFaucetResult = {\n readonly txHash: string;\n};\n\nexport class AccountReadError extends Data.TaggedError(\"AccountReadError\")<{\n readonly operation: string;\n readonly publicCode: CapxulErrorCode;\n readonly publicError: CapxulError;\n readonly cause: unknown;\n readonly details?: CapxulErrorDetails;\n}> {}\n\nexport function accountReadErrorFromCapxul(\n operation: string,\n error: CapxulError,\n cause: unknown = error,\n): AccountReadError {\n return new AccountReadError({\n operation,\n publicCode: error.code,\n publicError: error,\n cause,\n ...(error.details === undefined ? {} : { details: error.details }),\n });\n}\n\n/**\n * Logical Account money read (M2 Slice S1a). Joins the `accounts` row with a\n * live RPC `balanceOf` pull; the adapter lifts wire integers to `Money`.\n */\nexport interface AccountReadPort {\n readBalance(input: ReadAccountBalanceInput): Effect.Effect<Account, AccountReadError, never>;\n fundFromFaucet(\n input: FundFromFaucetInput,\n ): Effect.Effect<FundFromFaucetResult, AccountReadError, never>;\n}\n\nexport class AccountReadPortTag extends Context.Service<AccountReadPortTag, AccountReadPort>()(\n \"@capxul/sdk/ports/AccountReadPort\",\n) {}\n","import { formatUnits } from \"viem\";\n\nimport { toCurrencyCode, type Money } from \"@capxul/types\";\n\n/**\n * Lift an on-chain integer (e.g. USDX 6-decimal) into consumer `Money`.\n * Canon `account-balance-model.md` §10 — internal at the SDK boundary only.\n */\nexport function fromWei(rawBalance: string, decimals: number, currency: string): Money {\n if (!Number.isInteger(decimals) || decimals < 0) {\n throw new Error(`fromWei: decimals must be a non-negative integer, got ${String(decimals)}`);\n }\n const normalized = rawBalance.trim();\n if (!/^\\d+$/.test(normalized)) {\n // Show the exact (trimmed) value that failed the regex, truncated to keep\n // logs bounded for a pathologically long input.\n const truncated = normalized.length > 80 ? `${normalized.slice(0, 80)}…` : normalized;\n throw new Error(`fromWei: rawBalance must be a base-10 integer string, got ${truncated}`);\n }\n return {\n currency: toCurrencyCode(currency),\n value: formatUnits(BigInt(normalized), decimals),\n decimals,\n };\n}\n","import { Context, Data, Effect } from \"effect\";\nimport type { CapxulError, CapxulErrorCode, CapxulErrorDetails } from \"@capxul/config\";\nimport type { AccountId, Money, SubAccount, SubAccountId } from \"@capxul/types\";\n\nexport class SubAccountError extends Data.TaggedError(\"SubAccountError\")<{\n readonly operation: string;\n readonly publicCode: CapxulErrorCode;\n readonly publicError: CapxulError;\n readonly cause: unknown;\n readonly details?: CapxulErrorDetails;\n}> {}\n\nexport function subAccountErrorFromCapxul(\n operation: string,\n error: CapxulError,\n cause: unknown = error,\n): SubAccountError {\n return new SubAccountError({\n operation,\n publicCode: error.code,\n publicError: error,\n cause,\n ...(error.details === undefined ? {} : { details: error.details }),\n });\n}\n\nexport type CreateSubAccountInput = {\n readonly accountId: AccountId;\n readonly name: string;\n};\n\nexport type SubAccountIdInput = {\n readonly subAccountId: SubAccountId;\n};\n\nexport type RenameSubAccountInput = {\n readonly subAccountId: SubAccountId;\n readonly name: string;\n};\n\n/**\n * A `transfer` endpoint is either the Account's MAIN balance (the remainder\n * left over after every sub-account is funded — never a stored row) or a\n * specific sub-account, addressed by its `SubAccountId` (canon\n * `account-balance-model.md` §5, §12).\n */\nexport type TransferEndpoint = \"main\" | SubAccountId;\n\n/**\n * Move money between two of the SAME Account's balances (canon §12). The\n * backend resolves the Account from auth (v1 = one Account per user), so the\n * input carries no `accountId` — only the from/to endpoints and the `Money`\n * amount. One verb covers money in (`main → sub`), money out (`sub → main`),\n * and `sub → sub`.\n */\nexport type TransferInput = {\n readonly from: TransferEndpoint;\n readonly to: TransferEndpoint;\n readonly amount: Money;\n};\n\n/**\n * Result of a `transfer`: the recomputed `available` (`balanceOf − Σ`), plus\n * the updated source/destination sub-account rows. An endpoint that is `\"main\"`\n * has no stored row, so its slot is `null`.\n */\nexport type TransferResult = {\n readonly available: Money;\n readonly from: SubAccount | null;\n readonly to: SubAccount | null;\n};\n\nexport interface SubAccountPort {\n create(input: CreateSubAccountInput): Effect.Effect<SubAccount, SubAccountError, never>;\n get(input: SubAccountIdInput): Effect.Effect<SubAccount | null, SubAccountError, never>;\n list(input: {\n readonly accountId: AccountId;\n }): Effect.Effect<readonly SubAccount[], SubAccountError, never>;\n rename(input: RenameSubAccountInput): Effect.Effect<SubAccount, SubAccountError, never>;\n delete(input: SubAccountIdInput): Effect.Effect<void, SubAccountError, never>;\n transfer(input: TransferInput): Effect.Effect<TransferResult, SubAccountError, never>;\n}\n\nexport class SubAccountPortTag extends Context.Service<SubAccountPortTag, SubAccountPort>()(\n \"@capxul/sdk/ports/SubAccountPort\",\n) {}\n","import { Context, Data, Effect } from \"effect\";\nimport type { CapxulError, CapxulErrorCode, CapxulErrorDetails } from \"@capxul/config\";\nimport type {\n Address,\n AuthUserId,\n BlockNumber,\n ChainId,\n DurationMs,\n SmartAccount,\n TxHash,\n} from \"@capxul/types\";\n\n/**\n * Configuration for a Safe deployment: the chain + RPC endpoint +\n * gas-sponsorship policy. `receiptTimeoutMs` is optional; the deploying\n * adapter applies a default when omitted.\n *\n * #1145 (DEMOLITION §D4): re-homed here from the deleted\n * `ports/safe-deployment.ts`. The SafeDeploymentPort itself was fakes-only\n * plus one e2e adapter; the real Safe lifecycle is backend-orchestrated\n * through this port. Only the two data shapes below survive on the SDK\n * surface — `SafeDeploymentConfig` parameterises the org-deploy seam\n * (`orgDeploymentConfig`), `SafeDeploymentEvidence` is the payload of\n * `confirmDeployment`.\n */\nexport type SafeDeploymentConfig = {\n readonly chainId: ChainId;\n readonly rpcUrl: string;\n readonly gasPolicyId: string;\n readonly receiptTimeoutMs?: DurationMs;\n};\n\n/**\n * Evidence of a successful Safe deployment.\n *\n * Every field except `chainId` / `signerAddress` / `safeAddress` is\n * optional because the AC8 precheck short-circuit path (Safe already\n * on-chain at this address; off-chain receipt evidence unavailable)\n * calls the persistence step WITHOUT a `userOpHash`, `txHash`, or\n * `blockNumber` — there is no recoverable transaction. Aaron's rule:\n * \"If there is no TX and it hasn't been deployed then there shouldn't\n * be a hash.\" End-to-end nullable: `v.optional(v.string())` in the\n * backend schema.\n *\n * **`deployedAt` is NOT a field on this type.** The SDK is never the\n * oracle for `deployedAt`. The backend (`confirmDeployment` action —\n * Convex mutations cannot `fetch`, so the chain re-verification lives\n * in an action) derives it from on-chain data — `eth_getUserOperationReceipt`\n * for the real-userOp path or `eth_getLogs` for the precheck path —\n * then resolves the receipt block's timestamp via `eth_getBlockByNumber`.\n * See `packages/sdk/docs/architecture.md` for the deployment trust boundary.\n */\nexport type SafeDeploymentEvidence = {\n readonly chainId: ChainId;\n readonly signerAddress: Address;\n readonly safeAddress: Address;\n readonly txHash?: TxHash;\n readonly userOpHash?: TxHash;\n readonly blockNumber?: BlockNumber;\n};\n\nexport type ProvisionInput = {\n readonly authUserId: AuthUserId;\n readonly chainId: ChainId;\n};\n\n/**\n * Input to `SmartAccountPort.confirmDeployment` (#161 · γ-B).\n *\n * The SDK provides evidence pointers; the backend is the oracle for\n * `deployedAt`. `evidence.deployedAt` does NOT exist by schema (see\n * `SafeDeploymentEvidence`) — the backend derives `deployedAt` from\n * the on-chain receipt block via `eth_getBlockByNumber`.\n *\n * Precheck path: `evidence.userOpHash` omitted; backend scans\n * `SafeProxyFactory.ProxyCreation(safeAddress, _)` via `eth_getLogs`.\n *\n * Real-userOp path: `evidence.userOpHash` populated; backend calls\n * `eth_getUserOperationReceipt(userOpHash)` to re-verify and derive.\n */\nexport type ConfirmDeploymentInput = {\n readonly authUserId: AuthUserId;\n readonly chainId: ChainId;\n readonly safeAddress: Address;\n readonly evidence: SafeDeploymentEvidence;\n};\n\n/**\n * Input to `SmartAccountPort.claim` (PRD #462). The authenticated session\n * reports the browser-created signer address; the BACKEND builds and\n * bootstrap-signs the claim userOp (deploy + swapOwner) — the consumer signs\n * nothing at claim.\n */\nexport type ClaimInput = {\n readonly authUserId: AuthUserId;\n readonly chainId: ChainId;\n readonly signerAddress: Address;\n};\n\nexport class SmartAccountError extends Data.TaggedError(\"SmartAccountError\")<{\n readonly operation: string;\n readonly publicCode: CapxulErrorCode;\n readonly publicError: CapxulError;\n readonly cause: unknown;\n readonly details?: CapxulErrorDetails;\n}> {}\n\nexport function smartAccountErrorFromCapxul(\n operation: string,\n error: CapxulError,\n cause: unknown = error,\n): SmartAccountError {\n return new SmartAccountError({\n operation,\n publicCode: error.code,\n publicError: error,\n cause,\n ...(error.details === undefined ? {} : { details: error.details }),\n });\n}\n\n// Domain port. Sibling to the platform-ports bundle; deliberately NOT a\n// member of `PlatformPorts` — domain ports are composed by consumers per the\n// hexagonal composition contract. See `packages/sdk/docs/architecture.md`.\nexport interface SmartAccountPort {\n loadByAuthUserId(\n authUserId: AuthUserId,\n ): Effect.Effect<SmartAccount | null, SmartAccountError, never>;\n loadBySmartAccountAddress(\n address: Address,\n ): Effect.Effect<SmartAccount | null, SmartAccountError, never>;\n provision(input: ProvisionInput): Effect.Effect<SmartAccount, SmartAccountError, never>;\n /**\n * Persist on-chain Safe-deployment evidence. The backend re-verifies\n * the evidence against chain state and derives `deployedAt` from the\n * receipt block's timestamp. Returns the updated `SmartAccount` row.\n *\n * γ-B trust model: the SDK supplies evidence pointers only. The\n * backend is the SOLE oracle for `deployedAt` — see\n * `packages/sdk/docs/architecture.md`.\n */\n confirmDeployment(\n input: ConfirmDeploymentInput,\n ): Effect.Effect<SmartAccount, SmartAccountError, never>;\n /**\n * Claim the account (PRD #462): the backend builds, bootstrap-signs, and\n * submits ONE sponsored userOp — deploy (when undeployed) + swapOwner\n * (bootstrap → `signerAddress`). Idempotent; returns the updated row. When\n * another claim is in flight the row comes back with `claimedAt: null` —\n * callers poll lifecycle until the claim lands.\n */\n claim(input: ClaimInput): Effect.Effect<SmartAccount, SmartAccountError, never>;\n}\n\nexport class SmartAccountPortTag extends Context.Service<SmartAccountPortTag, SmartAccountPort>()(\n \"@capxul/sdk/ports/SmartAccountPort\",\n) {}\n","import { Effect } from \"effect\";\n\nimport { Schema, SchemaGetter } from \"effect\";\nimport type { CapxulError } from \"@capxul/errors\";\nimport {\n APP_ID_RE,\n BYTES32_RE,\n EVM_ADDRESS_RE,\n type AccountId,\n type Address,\n type AnonymousDistinctId,\n type AppId,\n type BlockNumber,\n type ChainId,\n type CurrencyCode,\n type DurationMs,\n type EpochMs,\n type PublishableKeyId,\n type SubAccountId,\n type TxHash,\n type WeiAmount,\n} from \"@capxul/types\";\n\nexport const TELEMETRY_EVENT_NAMES = [\n \"auth_otp_requested\",\n \"auth_otp_delivered\",\n \"auth_otp_expired\",\n \"auth_verified\",\n \"auth_failed\",\n \"auth_signed_out\",\n \"onboarding_intent_selected\",\n \"onboarding_profile_submitted\",\n \"onboarding_organization_submitted\",\n \"onboarding_dashboard_reached\",\n \"provisioning_safe_created\",\n \"provisioning_safe_confirmed\",\n \"bootstrap_resolved\",\n \"bootstrap_failed\",\n \"member_activation_started\",\n \"member_activation_ready\",\n \"member_activation_failed\",\n \"organization_creation_started\",\n \"organization_creation_ready\",\n \"organization_creation_failed\",\n // Money domain (M2). Producer split documented in\n // packages/observability/CONTEXT.md \"Money domain\".\n \"account_balance_read\",\n \"account_balance_failed\",\n \"faucet_requested\",\n \"faucet_confirmed\",\n \"faucet_failed\",\n \"subaccount_created\",\n \"subaccount_renamed\",\n \"subaccount_deleted\",\n \"subaccount_op_failed\",\n \"transfer_requested\",\n \"transfer_backend_received\",\n \"transfer_confirmed\",\n \"transfer_failed\",\n // Organization domain — creation funnel (canon org-domain-model.md §C5, J1).\n // Producer split documented in packages/observability/CONTEXT.md\n // \"Organization domain\". Grouped by the PostHog `organization` group type.\n \"org_create_started\",\n \"org_safe_created\",\n \"org_safe_confirmed\",\n \"org_roles_seeded\",\n \"org_created\",\n \"org_create_failed\",\n \"org_invite_sent\",\n \"org_invite_accepted\",\n \"org_role_granted\",\n \"org_member_active\",\n \"org_member_removed\",\n \"org_invite_expired\",\n \"org_role_grant_failed\",\n // Financial-ops target surface (G0 RED scaffold, #543). These names are\n // cataloged before behavior lands; `FINANCIAL_OPS_TARGET_TELEMETRY_PRODUCERS`\n // below is the single producer registry until follow-up issues wire emits.\n \"payment_requested\",\n \"payment_resolved\",\n \"payment_document_attached\",\n \"payment_submitted\",\n \"payment_settled\",\n \"payment_claimed\",\n \"payment_cancelled\",\n \"payment_redirected\",\n \"payment_failed\",\n \"stream_created\",\n \"stream_claimed\",\n \"stream_cancelled\",\n \"stream_completed\",\n \"stream_failed\",\n // Withdrawal / cash-out lane (B3). Value leaves the custody Safe to an\n // EXTERNAL 0x wallet. Props are leak-safe: payment_id + document_hash + amount\n // + currency + status + reason — NEVER the external destAddress (it lives on\n // the kind:4 Withdrawal document only). `withdrawal_settled` is WIRED (emitted\n // from the withdraw settlement action via emitServerAwaited); the other three\n // are planned RED targets in FINANCIAL_OPS_TARGET_TELEMETRY_PRODUCERS.\n \"withdrawal_requested\",\n \"withdrawal_submitted\",\n \"withdrawal_settled\",\n \"withdrawal_failed\",\n] as const;\n\nexport type TelemetryEventName = (typeof TELEMETRY_EVENT_NAMES)[number];\n\nexport type NonEmptyTelemetryEventNames = readonly [TelemetryEventName, ...TelemetryEventName[]];\nexport type FunnelStepPropertyFilter = {\n readonly key: string;\n readonly value: readonly string[];\n readonly operator: \"exact\";\n readonly type: \"event\";\n};\nexport type FunnelJourney = {\n readonly type: \"funnel\";\n readonly steps: NonEmptyTelemetryEventNames;\n readonly drops_on?: NonEmptyTelemetryEventNames;\n readonly step_filters?: Readonly<\n Partial<Record<TelemetryEventName, readonly FunnelStepPropertyFilter[]>>\n >;\n};\nexport type PointEventJourney = {\n readonly type: \"point_event\";\n readonly point_event: TelemetryEventName;\n};\nexport type Journey = FunnelJourney | PointEventJourney;\n\nexport const TELEMETRY_JOURNEYS = {\n returning_user_login: {\n type: \"funnel\",\n steps: [\"auth_otp_requested\", \"auth_otp_delivered\", \"auth_verified\"],\n drops_on: [\"auth_otp_expired\", \"auth_failed\"],\n },\n new_user_first_signin: {\n type: \"funnel\",\n steps: [\n \"auth_otp_requested\",\n \"auth_otp_delivered\",\n \"auth_verified\",\n \"provisioning_safe_created\",\n \"provisioning_safe_confirmed\",\n ],\n drops_on: [\"auth_otp_expired\", \"auth_failed\"],\n },\n sign_out_session_close: {\n type: \"point_event\",\n point_event: \"auth_signed_out\",\n },\n member_activation: {\n type: \"funnel\",\n steps: [\"member_activation_started\", \"member_activation_ready\"],\n drops_on: [\"member_activation_failed\"],\n },\n organization_creation_lifecycle: {\n type: \"funnel\",\n steps: [\"organization_creation_started\", \"organization_creation_ready\"],\n drops_on: [\"organization_creation_failed\"],\n },\n new_member_personal_dashboard: {\n type: \"funnel\",\n steps: [\n \"auth_verified\",\n \"onboarding_intent_selected\",\n \"onboarding_profile_submitted\",\n \"member_activation_ready\",\n \"onboarding_dashboard_reached\",\n ],\n step_filters: {\n onboarding_intent_selected: [\n { key: \"intent\", value: [\"personal\"], operator: \"exact\", type: \"event\" },\n { key: \"entry_point\", value: [\"signup\"], operator: \"exact\", type: \"event\" },\n ],\n onboarding_profile_submitted: [\n { key: \"intent\", value: [\"personal\"], operator: \"exact\", type: \"event\" },\n ],\n onboarding_dashboard_reached: [\n { key: \"intent\", value: [\"personal\"], operator: \"exact\", type: \"event\" },\n ],\n },\n },\n new_member_organization_dashboard: {\n type: \"funnel\",\n steps: [\n \"auth_verified\",\n \"onboarding_intent_selected\",\n \"onboarding_profile_submitted\",\n \"onboarding_organization_submitted\",\n \"member_activation_started\",\n \"member_activation_ready\",\n \"organization_creation_started\",\n \"organization_creation_ready\",\n \"onboarding_dashboard_reached\",\n ],\n step_filters: {\n onboarding_intent_selected: [\n { key: \"intent\", value: [\"organization\"], operator: \"exact\", type: \"event\" },\n { key: \"entry_point\", value: [\"signup\"], operator: \"exact\", type: \"event\" },\n ],\n onboarding_profile_submitted: [\n { key: \"intent\", value: [\"organization\"], operator: \"exact\", type: \"event\" },\n ],\n onboarding_dashboard_reached: [\n { key: \"intent\", value: [\"organization\"], operator: \"exact\", type: \"event\" },\n ],\n },\n },\n existing_member_organization_dashboard: {\n type: \"funnel\",\n steps: [\n \"onboarding_intent_selected\",\n \"onboarding_organization_submitted\",\n \"organization_creation_started\",\n \"organization_creation_ready\",\n \"onboarding_dashboard_reached\",\n ],\n step_filters: {\n onboarding_intent_selected: [\n { key: \"intent\", value: [\"organization\"], operator: \"exact\", type: \"event\" },\n { key: \"entry_point\", value: [\"dashboard\"], operator: \"exact\", type: \"event\" },\n ],\n onboarding_dashboard_reached: [\n { key: \"intent\", value: [\"organization\"], operator: \"exact\", type: \"event\" },\n ],\n },\n },\n // Money domain (M2).\n money_on_screen: {\n type: \"point_event\",\n point_event: \"account_balance_read\",\n },\n fund_account: {\n type: \"funnel\",\n steps: [\"faucet_requested\", \"faucet_confirmed\"],\n drops_on: [\"faucet_failed\"],\n },\n first_value_movement: {\n type: \"funnel\",\n steps: [\"account_balance_read\", \"transfer_requested\", \"transfer_confirmed\"],\n drops_on: [\"transfer_failed\"],\n },\n subaccount_lifecycle: {\n type: \"point_event\",\n point_event: \"subaccount_created\",\n },\n // Organization domain (canon org-domain-model.md §C5). J1 create-org funnel.\n org_creation: {\n type: \"funnel\",\n steps: [\n \"org_create_started\",\n \"org_safe_created\",\n \"org_safe_confirmed\",\n \"org_roles_seeded\",\n \"org_created\",\n ],\n drops_on: [\"org_create_failed\"],\n },\n org_member_onboarding: {\n type: \"funnel\",\n steps: [\"org_invite_sent\", \"org_invite_accepted\", \"org_role_granted\", \"org_member_active\"],\n drops_on: [\"org_invite_expired\", \"org_role_grant_failed\"],\n },\n // Financial-ops domain (ADR-1 money journey + funnel catalog,\n // docs/adr/0006-money-journey-funnel-catalog.md). These reconcile the\n // alpha-scope FE journeys, the J1–J4 telemetry funnels, and the G0–G6 capstone\n // goals into one canonical set. Producers are wired per lane in B1; until then\n // every step/drop is a planned RED target in\n // FINANCIAL_OPS_TARGET_TELEMETRY_PRODUCERS (ADR-2 seam: planned XOR wired).\n // Org-spend, payroll, and receivable-collect lanes ride the same payment_*\n // events with a source/context prop discriminator — no new event names.\n direct_payment: {\n type: \"funnel\",\n steps: [\n \"payment_requested\",\n \"payment_resolved\",\n \"payment_document_attached\",\n \"payment_submitted\",\n \"payment_settled\",\n ],\n drops_on: [\"payment_failed\"],\n },\n commitment_claim: {\n type: \"funnel\",\n steps: [\"payment_submitted\", \"payment_claimed\"],\n drops_on: [\"payment_cancelled\"],\n },\n commitment_redirect: {\n type: \"point_event\",\n point_event: \"payment_redirected\",\n },\n salary_stream: {\n type: \"funnel\",\n steps: [\"stream_created\", \"stream_claimed\", \"stream_completed\"],\n drops_on: [\"stream_cancelled\", \"stream_failed\"],\n },\n // Cash-out / withdraw lane (B3). USDX leaves the custody Safe to an external\n // 0x wallet; `withdrawal_settled` is the server-confirmed evidence-bound step.\n cash_out: {\n type: \"funnel\",\n steps: [\"withdrawal_requested\", \"withdrawal_submitted\", \"withdrawal_settled\"],\n drops_on: [\"withdrawal_failed\"],\n },\n} as const satisfies Record<string, Journey>;\n\nexport type TelemetryProps = Record<string, unknown>;\n\nexport type TelemetryEvent = {\n readonly name: TelemetryEventName;\n readonly props?: TelemetryProps | undefined;\n};\n\nexport const PII = Schema.String.pipe(Schema.brand(\"PII\"));\nexport type PII = Schema.Schema.Type<typeof PII>;\n\nconst OptionalString = Schema.optional(Schema.String);\nconst AddressSchema: Schema.Codec<Address, string> = Schema.String.pipe(\n Schema.decodeTo(Schema.String, {\n decode: SchemaGetter.transform((value) => value.toLowerCase()),\n encode: SchemaGetter.transform((value) => value),\n }),\n Schema.refine((value): value is Address => EVM_ADDRESS_RE.test(value), {\n message: \"must be 0x + 40 hex chars\",\n }),\n);\nconst AppIdSchema: Schema.Codec<AppId, string> = Schema.String.pipe(\n Schema.refine((value): value is AppId => APP_ID_RE.test(value), {\n message: \"must be app_ plus a ULID\",\n }),\n);\nconst BlockNumberSchema: Schema.Codec<BlockNumber, number> = Schema.Number.pipe(\n Schema.refine((value): value is BlockNumber => Number.isSafeInteger(value) && value >= 0, {\n message: \"must be a non-negative safe integer\",\n }),\n);\nconst ChainIdSchema: Schema.Codec<ChainId, number> = Schema.Number.pipe(\n Schema.refine((value): value is ChainId => Number.isSafeInteger(value) && value > 0, {\n message: \"must be a positive safe integer\",\n }),\n);\nconst DurationMsSchema: Schema.Codec<DurationMs, number> = Schema.Number.pipe(\n Schema.refine((value): value is DurationMs => Number.isSafeInteger(value) && value >= 0, {\n message: \"must be a non-negative safe integer\",\n }),\n);\nconst EpochMsSchema: Schema.Codec<EpochMs, number> = Schema.Number.pipe(\n Schema.refine((value): value is EpochMs => Number.isSafeInteger(value) && value >= 0, {\n message: \"must be a non-negative safe integer\",\n }),\n);\nconst PublishableKeyIdSchema: Schema.Codec<PublishableKeyId, string> = Schema.String.pipe(\n Schema.refine((value): value is PublishableKeyId => value.length > 0, {\n message: \"must be a non-empty string\",\n }),\n);\nconst TxHashSchema: Schema.Codec<TxHash, string> = Schema.String.pipe(\n Schema.refine((value): value is TxHash => BYTES32_RE.test(value), {\n message: \"must be 0x + 64 hex chars\",\n }),\n);\n// Money-domain brands. `account_`/`subaccount_` prefixes mirror the `@capxul/types`\n// brand constructors (`toAccountId`/`toSubAccountId`); WeiAmount is a non-negative\n// integer STRING per `.claude/rules/numeric-parsing.md` (never a float, never a number).\nconst ACCOUNT_ID_TELEMETRY_RE = /^account_[0-9A-Za-z]+$/;\nconst SUBACCOUNT_ID_TELEMETRY_RE = /^subaccount_[0-9A-Za-z]+$/;\nconst WEI_AMOUNT_TELEMETRY_RE = /^[0-9]+$/;\nconst AccountIdSchema: Schema.Codec<AccountId, string> = Schema.String.pipe(\n Schema.refine((value): value is AccountId => ACCOUNT_ID_TELEMETRY_RE.test(value), {\n message: \"must be account_ plus an alphanumeric id\",\n }),\n);\nconst SubAccountIdSchema: Schema.Codec<SubAccountId, string> = Schema.String.pipe(\n Schema.refine((value): value is SubAccountId => SUBACCOUNT_ID_TELEMETRY_RE.test(value), {\n message: \"must be subaccount_ plus an alphanumeric id\",\n }),\n);\nconst WeiAmountSchema: Schema.Codec<WeiAmount, string> = Schema.String.pipe(\n Schema.refine((value): value is WeiAmount => WEI_AMOUNT_TELEMETRY_RE.test(value), {\n message: \"must be a non-negative integer string\",\n }),\n);\nconst CurrencyCodeSchema: Schema.Codec<CurrencyCode, string> = Schema.String.pipe(\n Schema.refine((value): value is CurrencyCode => value.length > 0, {\n message: \"must be a non-empty currency code\",\n }),\n);\nconst BalanceBucketSchema = Schema.Literals([\"zero\", \"nonzero\"]);\nconst TransferDirectionSchema = Schema.Literals([\"add\", \"out\", \"between\"]);\nconst SubAccountOpSchema = Schema.Literals([\"create\", \"rename\", \"delete\"]);\nconst OptionalAccountId = Schema.optional(AccountIdSchema);\nconst OptionalSubAccountId = Schema.optional(SubAccountIdSchema);\nconst OptionalWeiAmount = Schema.optional(WeiAmountSchema);\nconst OptionalCurrencyCode = Schema.optional(CurrencyCodeSchema);\nconst OptionalBalanceBucket = Schema.optional(BalanceBucketSchema);\nconst OptionalTransferDirection = Schema.optional(TransferDirectionSchema);\nconst OptionalSubAccountOp = Schema.optional(SubAccountOpSchema);\nconst OptionalTrue = Schema.optional(Schema.Literal(true));\nconst OptionalAddress = Schema.optional(AddressSchema);\nconst OptionalAppId = Schema.optional(AppIdSchema);\nconst OptionalBlockNumber = Schema.optional(BlockNumberSchema);\nconst OptionalChainId = Schema.optional(ChainIdSchema);\nconst OptionalDurationMs = Schema.optional(DurationMsSchema);\nconst OptionalEpochMs = Schema.optional(EpochMsSchema);\nconst OptionalPublishableKeyId = Schema.optional(PublishableKeyIdSchema);\nconst OptionalTxHash = Schema.optional(TxHashSchema);\nconst PAYMENT_ID_TELEMETRY_RE = /^payment_[0-9A-Za-z]+$/;\nconst PAYEE_ID_TELEMETRY_RE = /^payee_[0-9A-Za-z]+$/;\nconst PaymentIdTelemetrySchema = Schema.String.pipe(\n Schema.refine((value): value is string => PAYMENT_ID_TELEMETRY_RE.test(value), {\n message: \"must be payment_ plus an alphanumeric id\",\n }),\n);\nconst PayeeIdTelemetrySchema = Schema.String.pipe(\n Schema.refine((value): value is string => PAYEE_ID_TELEMETRY_RE.test(value), {\n message: \"must be payee_ plus an alphanumeric id\",\n }),\n);\nconst DocumentHashSchema = Schema.String.pipe(\n Schema.refine((value): value is string => BYTES32_RE.test(value), {\n message: \"must be 0x + 64 hex chars\",\n }),\n);\n/**\n * Environment discriminator (ADR-0020 A1 amendment, 2026-08-07). PostHog\n * project 368736 is the SINGLE sink for every environment, so `capxul_env` —\n * not project isolation — is what keeps a production surface from reading dev\n * traffic. It is REQUIRED on every catalog event and every synced artifact\n * filters on it.\n *\n * `unknown` is a defect marker, not an environment: it means a producer\n * reached the transport without declaring where it runs. It is in the union so\n * the property is never ABSENT (an absent property is invisible to a filter,\n * a present `unknown` is loud), and sync v2 never synthesizes an artifact for\n * it.\n */\nexport const CAPXUL_ENVS = [\"development\", \"e2e\", \"staging\", \"production\", \"unknown\"] as const;\nexport type CapxulEnv = (typeof CAPXUL_ENVS)[number];\n\n/** Environments a synced product surface may be built for (`unknown` cannot). */\nexport const SYNCABLE_CAPXUL_ENVS = [\"development\", \"e2e\", \"staging\", \"production\"] as const;\n\n/**\n * Which half of the system emitted the event. REQUIRED alongside `capxul_env`\n * so a name that two halves can produce (settlement, auth) stays attributable.\n */\nexport const TELEMETRY_PRODUCERS = [\"server\", \"browser\", \"sdk\", \"mcp\", \"e2e\"] as const;\nexport type TelemetryProducer = (typeof TELEMETRY_PRODUCERS)[number];\n\nconst CapxulEnvSchema = Schema.Literals(CAPXUL_ENVS);\nconst TelemetryProducerSchema = Schema.Literals(TELEMETRY_PRODUCERS);\n\n/**\n * The canonical envelope (ADR-0020 A4): snake_case ONLY. `capxul_env` and\n * `producer` are REQUIRED — a boundary that forgets to stamp them fails schema\n * decode instead of silently shipping an unattributable event. Call sites do\n * not pass them: `stampTelemetryEnvelope` injects them at the emit boundary,\n * which is the only place that knows where the process runs.\n */\nconst TelemetryEnvelopeProps = {\n capxul_env: CapxulEnvSchema,\n producer: TelemetryProducerSchema,\n journey_id: OptionalString,\n correlation_id: OptionalString,\n sdk_version: OptionalString,\n};\n\nexport interface TelemetryEnvelopeDefaults {\n readonly capxul_env: CapxulEnv;\n readonly producer: TelemetryProducer;\n}\n\n/**\n * Stamp the required envelope onto an event at its emit boundary. Call-site\n * props win on conflict: a relay that already knows the true producer (the\n * browser-failure relay stamps `browser` while running on the server) must not\n * be overwritten by the transport's own default.\n */\nexport function stampTelemetryEnvelope(\n event: TelemetryEvent,\n defaults: TelemetryEnvelopeDefaults,\n): TelemetryEvent {\n return { name: event.name, props: { ...defaults, ...event.props } };\n}\n\nconst AuthOtpRequestedProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n email: Schema.optional(PII),\n email_domain: OptionalString,\n});\nconst AuthOtpDeliveredProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n durationMs: OptionalDurationMs,\n email: Schema.optional(PII),\n email_domain: OptionalString,\n resendMessageId: OptionalString,\n});\nconst AuthOtpExpiredProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n email: Schema.optional(PII),\n email_domain: OptionalString,\n});\nconst AuthVerifiedProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n auth_type: OptionalString,\n});\nconst AuthFailedProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n email: Schema.optional(PII),\n auth_type: OptionalString,\n reason: OptionalString,\n});\nconst AuthSignedOutProps = Schema.Struct(TelemetryEnvelopeProps);\nconst ProvisioningSafeCreatedProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n safe_address: OptionalAddress,\n});\nconst ProvisioningSafeConfirmedProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n chainId: OptionalChainId,\n deployedAt: OptionalEpochMs,\n deployedAtBlock: OptionalBlockNumber,\n deployTxHash: OptionalTxHash,\n durationMs: OptionalDurationMs,\n safe_address: OptionalAddress,\n userOpHash: OptionalTxHash,\n});\nconst BootstrapResolvedProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n applicationId: OptionalAppId,\n durationMs: OptionalDurationMs,\n env: OptionalString,\n keyId: OptionalPublishableKeyId,\n origin: OptionalString,\n});\nconst BootstrapFailedProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n applicationId: OptionalAppId,\n durationMs: OptionalDurationMs,\n origin: OptionalString,\n reason: OptionalString,\n});\n\n// Money domain (M2). No sub-account NAMES, no raw emails, no raw addresses —\n// only branded ids, WeiAmount strings, buckets, and durations. See\n// packages/observability/CONTEXT.md \"Money domain\".\nconst AccountBalanceReadProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n account_id: OptionalAccountId,\n currency: OptionalCurrencyCode,\n balance_bucket: OptionalBalanceBucket,\n durationMs: OptionalDurationMs,\n});\nconst AccountBalanceFailedProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n reason: OptionalString,\n});\nconst FaucetRequestedProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n amount: OptionalWeiAmount,\n chainId: OptionalChainId,\n});\nconst FaucetConfirmedProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n amount: OptionalWeiAmount,\n chainId: OptionalChainId,\n txHash: OptionalTxHash,\n durationMs: OptionalDurationMs,\n});\nconst FaucetFailedProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n reason: OptionalString,\n});\nconst SubaccountCreatedProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n sub_account_id: OptionalSubAccountId,\n durationMs: OptionalDurationMs,\n});\nconst SubaccountRenamedProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n sub_account_id: OptionalSubAccountId,\n});\nconst SubaccountDeletedProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n sub_account_id: OptionalSubAccountId,\n});\nconst SubaccountOpFailedProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n op: OptionalSubAccountOp,\n reason: OptionalString,\n});\nconst TransferRequestedProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n amount: OptionalWeiAmount,\n direction: OptionalTransferDirection,\n});\nconst TransferBackendReceivedProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n direction: OptionalTransferDirection,\n});\nconst TransferConfirmedProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n amount: OptionalWeiAmount,\n direction: OptionalTransferDirection,\n available_bucket: OptionalBalanceBucket,\n txless: OptionalTrue,\n durationMs: OptionalDurationMs,\n});\nconst TransferFailedProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n reason: OptionalString,\n});\n\n// Organization domain (canon org-domain-model.md §C5). No raw emails (PII):\n// `email_domain` only; `org_id` is the public `org_`-shaped brand (also the\n// PostHog `organization` group key); `safe_address` is the Org Safe; `role` is\n// the seeded role label; `reason` is the failure cause. See\n// packages/observability/CONTEXT.md \"Organization domain\".\nconst ORG_ID_TELEMETRY_RE = /^org_[0-9A-Za-z]+$/;\nconst OrgIdTelemetrySchema: Schema.Codec<string, string> = Schema.String.pipe(\n Schema.refine((value): value is string => ORG_ID_TELEMETRY_RE.test(value), {\n message: \"must be org_ plus an alphanumeric id\",\n }),\n);\nconst OptionalOrgId = Schema.optional(OrgIdTelemetrySchema);\nconst AttemptNumberSchema = Schema.Number.pipe(\n Schema.refine((value): value is number => Number.isSafeInteger(value) && value > 0, {\n message: \"must be a positive safe integer\",\n }),\n);\nconst OnboardingStageSchema = Schema.Literals([\n \"profile\",\n \"accountProvisioning\",\n \"accountClaim\",\n \"preparingFounderAccount\",\n \"awaitingFounderAuthorization\",\n \"submittingBootstrap\",\n \"confirmingBootstrap\",\n]);\n// The #816 lifecycle family: strict (non-optional) props plus the shared\n// envelope. `producer` comes from the envelope now — the literal \"server\"\n// constraint moved to the emit boundary, which is the only place that knows.\nconst MemberActivationStartedProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n $insert_id: Schema.String,\n});\nconst MemberActivationReadyProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n $insert_id: Schema.String,\n duration_ms: DurationMsSchema,\n});\nconst MemberActivationFailedProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n $insert_id: Schema.String,\n stage: OnboardingStageSchema,\n error_code: Schema.String,\n retryable: Schema.Boolean,\n});\nconst OrganizationCreationStartedProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n $insert_id: Schema.String,\n organization_id: OrgIdTelemetrySchema,\n attempt_number: AttemptNumberSchema,\n});\nconst OrganizationCreationReadyProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n $insert_id: Schema.String,\n organization_id: OrgIdTelemetrySchema,\n attempt_number: AttemptNumberSchema,\n duration_ms: DurationMsSchema,\n});\nconst OrganizationCreationFailedProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n $insert_id: Schema.String,\n organization_id: OrgIdTelemetrySchema,\n attempt_number: AttemptNumberSchema,\n stage: OnboardingStageSchema,\n error_code: Schema.String,\n retryable: Schema.Boolean,\n});\nconst OnboardingIntentSchema = Schema.Literals([\"personal\", \"organization\"]);\nconst OnboardingIntentSelectedProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n journey_id: Schema.String,\n intent: OnboardingIntentSchema,\n entry_point: Schema.String,\n});\nconst OnboardingProfileSubmittedProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n journey_id: Schema.String,\n intent: OnboardingIntentSchema,\n});\nconst OnboardingOrganizationSubmittedProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n journey_id: Schema.String,\n});\nconst OnboardingDashboardReachedProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n journey_id: Schema.String,\n intent: OnboardingIntentSchema,\n organization_id: Schema.optional(OrgIdTelemetrySchema),\n});\nconst OrgCreateStartedProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n org_id: OptionalOrgId,\n email_domain: OptionalString,\n template: OptionalString,\n});\nconst OrgSafeCreatedProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n org_id: OptionalOrgId,\n chainId: OptionalChainId,\n safe_address: OptionalAddress,\n});\nconst OrgSafeConfirmedProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n org_id: OptionalOrgId,\n chainId: OptionalChainId,\n safe_address: OptionalAddress,\n durationMs: OptionalDurationMs,\n});\nconst OrgRolesSeededProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n org_id: OptionalOrgId,\n chainId: OptionalChainId,\n role: OptionalString,\n txHash: OptionalTxHash,\n});\nconst OrgCreatedProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n org_id: OptionalOrgId,\n chainId: OptionalChainId,\n safe_address: OptionalAddress,\n durationMs: OptionalDurationMs,\n});\nconst OrgCreateFailedProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n org_id: OptionalOrgId,\n reason: OptionalString,\n});\nconst OrgInviteSentProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n org_id: OptionalOrgId,\n email_domain: OptionalString,\n role: OptionalString,\n status: OptionalString,\n});\nconst OrgInviteAcceptedProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n org_id: OptionalOrgId,\n role: OptionalString,\n status: OptionalString,\n});\nconst OrgRoleGrantedProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n org_id: OptionalOrgId,\n role: OptionalString,\n status: OptionalString,\n txHash: OptionalTxHash,\n});\nconst OrgMemberActiveProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n org_id: OptionalOrgId,\n role: OptionalString,\n status: OptionalString,\n durationMs: OptionalDurationMs,\n});\nconst OrgMemberRemovedProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n org_id: OptionalOrgId,\n role: OptionalString,\n status: OptionalString,\n txHash: OptionalTxHash,\n});\nconst OrgInviteExpiredProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n org_id: OptionalOrgId,\n email_domain: OptionalString,\n reason: OptionalString,\n role: OptionalString,\n status: OptionalString,\n});\nconst OrgRoleGrantFailedProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n org_id: OptionalOrgId,\n reason: OptionalString,\n role: OptionalString,\n});\n\n// Financial-ops target telemetry (G0 RED scaffold). Props intentionally carry\n// product ids, document hashes, buckets, and reasons. No raw emails, no raw\n// addresses, no userOp hashes, and no chain custody vocabulary.\nconst OptionalPaymentId = Schema.optional(PaymentIdTelemetrySchema);\nconst OptionalPayeeId = Schema.optional(PayeeIdTelemetrySchema);\nconst OptionalDocumentHash = Schema.optional(DocumentHashSchema);\nconst PaymentTargetTelemetryProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n payment_id: OptionalPaymentId,\n payee_id: OptionalPayeeId,\n document_hash: OptionalDocumentHash,\n amount: OptionalWeiAmount,\n currency: OptionalCurrencyCode,\n status: OptionalString,\n reason: OptionalString,\n durationMs: OptionalDurationMs,\n});\nconst StreamTargetTelemetryProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n payment_id: OptionalPaymentId,\n document_hash: OptionalDocumentHash,\n amount: OptionalWeiAmount,\n currency: OptionalCurrencyCode,\n status: OptionalString,\n available_bucket: OptionalBalanceBucket,\n reason: OptionalString,\n durationMs: OptionalDurationMs,\n});\n// Withdrawal / cash-out lane (B3). Leak-safe: product id + document hash +\n// amount + currency + status + reason + duration. NO destAddress (the external\n// 0x lives on the kind:4 Withdrawal document only), no txHash/userOpHash, no\n// chain custody vocabulary.\nconst WithdrawalTargetTelemetryProps = Schema.Struct({\n ...TelemetryEnvelopeProps,\n payment_id: OptionalPaymentId,\n document_hash: OptionalDocumentHash,\n amount: OptionalWeiAmount,\n currency: OptionalCurrencyCode,\n status: OptionalString,\n reason: OptionalString,\n durationMs: OptionalDurationMs,\n});\n\nexport const AuthOtpRequestedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"auth_otp_requested\"),\n props: AuthOtpRequestedProps,\n});\nexport const AuthOtpDeliveredTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"auth_otp_delivered\"),\n props: AuthOtpDeliveredProps,\n});\nexport const AuthOtpExpiredTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"auth_otp_expired\"),\n props: AuthOtpExpiredProps,\n});\nexport const AuthVerifiedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"auth_verified\"),\n props: AuthVerifiedProps,\n});\nexport const AuthFailedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"auth_failed\"),\n props: AuthFailedProps,\n});\nexport const AuthSignedOutTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"auth_signed_out\"),\n props: AuthSignedOutProps,\n});\nexport const OnboardingIntentSelectedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"onboarding_intent_selected\"),\n props: OnboardingIntentSelectedProps,\n});\nexport const OnboardingProfileSubmittedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"onboarding_profile_submitted\"),\n props: OnboardingProfileSubmittedProps,\n});\nexport const OnboardingOrganizationSubmittedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"onboarding_organization_submitted\"),\n props: OnboardingOrganizationSubmittedProps,\n});\nexport const OnboardingDashboardReachedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"onboarding_dashboard_reached\"),\n props: OnboardingDashboardReachedProps,\n});\nexport const ProvisioningSafeCreatedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"provisioning_safe_created\"),\n props: ProvisioningSafeCreatedProps,\n});\nexport const ProvisioningSafeConfirmedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"provisioning_safe_confirmed\"),\n props: ProvisioningSafeConfirmedProps,\n});\nexport const BootstrapResolvedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"bootstrap_resolved\"),\n props: BootstrapResolvedProps,\n});\nexport const BootstrapFailedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"bootstrap_failed\"),\n props: BootstrapFailedProps,\n});\nexport const MemberActivationStartedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"member_activation_started\"),\n props: MemberActivationStartedProps,\n});\nexport const MemberActivationReadyTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"member_activation_ready\"),\n props: MemberActivationReadyProps,\n});\nexport const MemberActivationFailedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"member_activation_failed\"),\n props: MemberActivationFailedProps,\n});\nexport const OrganizationCreationStartedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"organization_creation_started\"),\n props: OrganizationCreationStartedProps,\n});\nexport const OrganizationCreationReadyTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"organization_creation_ready\"),\n props: OrganizationCreationReadyProps,\n});\nexport const OrganizationCreationFailedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"organization_creation_failed\"),\n props: OrganizationCreationFailedProps,\n});\nexport const AccountBalanceReadTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"account_balance_read\"),\n props: AccountBalanceReadProps,\n});\nexport const AccountBalanceFailedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"account_balance_failed\"),\n props: AccountBalanceFailedProps,\n});\nexport const FaucetRequestedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"faucet_requested\"),\n props: FaucetRequestedProps,\n});\nexport const FaucetConfirmedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"faucet_confirmed\"),\n props: FaucetConfirmedProps,\n});\nexport const FaucetFailedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"faucet_failed\"),\n props: FaucetFailedProps,\n});\nexport const SubaccountCreatedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"subaccount_created\"),\n props: SubaccountCreatedProps,\n});\nexport const SubaccountRenamedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"subaccount_renamed\"),\n props: SubaccountRenamedProps,\n});\nexport const SubaccountDeletedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"subaccount_deleted\"),\n props: SubaccountDeletedProps,\n});\nexport const SubaccountOpFailedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"subaccount_op_failed\"),\n props: SubaccountOpFailedProps,\n});\nexport const TransferRequestedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"transfer_requested\"),\n props: TransferRequestedProps,\n});\nexport const TransferBackendReceivedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"transfer_backend_received\"),\n props: TransferBackendReceivedProps,\n});\nexport const TransferConfirmedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"transfer_confirmed\"),\n props: TransferConfirmedProps,\n});\nexport const TransferFailedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"transfer_failed\"),\n props: TransferFailedProps,\n});\nexport const OrgCreateStartedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"org_create_started\"),\n props: OrgCreateStartedProps,\n});\nexport const OrgSafeCreatedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"org_safe_created\"),\n props: OrgSafeCreatedProps,\n});\nexport const OrgSafeConfirmedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"org_safe_confirmed\"),\n props: OrgSafeConfirmedProps,\n});\nexport const OrgRolesSeededTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"org_roles_seeded\"),\n props: OrgRolesSeededProps,\n});\nexport const OrgCreatedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"org_created\"),\n props: OrgCreatedProps,\n});\nexport const OrgCreateFailedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"org_create_failed\"),\n props: OrgCreateFailedProps,\n});\nexport const OrgInviteSentTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"org_invite_sent\"),\n props: OrgInviteSentProps,\n});\nexport const OrgInviteAcceptedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"org_invite_accepted\"),\n props: OrgInviteAcceptedProps,\n});\nexport const OrgRoleGrantedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"org_role_granted\"),\n props: OrgRoleGrantedProps,\n});\nexport const OrgMemberActiveTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"org_member_active\"),\n props: OrgMemberActiveProps,\n});\nexport const OrgMemberRemovedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"org_member_removed\"),\n props: OrgMemberRemovedProps,\n});\nexport const OrgInviteExpiredTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"org_invite_expired\"),\n props: OrgInviteExpiredProps,\n});\nexport const OrgRoleGrantFailedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"org_role_grant_failed\"),\n props: OrgRoleGrantFailedProps,\n});\nexport const PaymentRequestedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"payment_requested\"),\n props: PaymentTargetTelemetryProps,\n});\nexport const PaymentResolvedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"payment_resolved\"),\n props: PaymentTargetTelemetryProps,\n});\nexport const PaymentDocumentAttachedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"payment_document_attached\"),\n props: PaymentTargetTelemetryProps,\n});\nexport const PaymentSubmittedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"payment_submitted\"),\n props: PaymentTargetTelemetryProps,\n});\nexport const PaymentSettledTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"payment_settled\"),\n props: PaymentTargetTelemetryProps,\n});\nexport const PaymentClaimedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"payment_claimed\"),\n props: PaymentTargetTelemetryProps,\n});\nexport const PaymentCancelledTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"payment_cancelled\"),\n props: PaymentTargetTelemetryProps,\n});\nexport const PaymentRedirectedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"payment_redirected\"),\n props: PaymentTargetTelemetryProps,\n});\nexport const PaymentFailedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"payment_failed\"),\n props: PaymentTargetTelemetryProps,\n});\nexport const StreamCreatedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"stream_created\"),\n props: StreamTargetTelemetryProps,\n});\nexport const StreamClaimedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"stream_claimed\"),\n props: StreamTargetTelemetryProps,\n});\nexport const StreamCancelledTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"stream_cancelled\"),\n props: StreamTargetTelemetryProps,\n});\nexport const StreamCompletedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"stream_completed\"),\n props: StreamTargetTelemetryProps,\n});\nexport const StreamFailedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"stream_failed\"),\n props: StreamTargetTelemetryProps,\n});\nexport const WithdrawalRequestedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"withdrawal_requested\"),\n props: WithdrawalTargetTelemetryProps,\n});\nexport const WithdrawalSubmittedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"withdrawal_submitted\"),\n props: WithdrawalTargetTelemetryProps,\n});\nexport const WithdrawalSettledTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"withdrawal_settled\"),\n props: WithdrawalTargetTelemetryProps,\n});\nexport const WithdrawalFailedTelemetryEventSchema = Schema.Struct({\n name: Schema.Literal(\"withdrawal_failed\"),\n props: WithdrawalTargetTelemetryProps,\n});\n\nexport const TELEMETRY_EVENT_SCHEMAS = {\n auth_otp_requested: AuthOtpRequestedTelemetryEventSchema,\n auth_otp_delivered: AuthOtpDeliveredTelemetryEventSchema,\n auth_otp_expired: AuthOtpExpiredTelemetryEventSchema,\n auth_verified: AuthVerifiedTelemetryEventSchema,\n auth_failed: AuthFailedTelemetryEventSchema,\n auth_signed_out: AuthSignedOutTelemetryEventSchema,\n onboarding_intent_selected: OnboardingIntentSelectedTelemetryEventSchema,\n onboarding_profile_submitted: OnboardingProfileSubmittedTelemetryEventSchema,\n onboarding_organization_submitted: OnboardingOrganizationSubmittedTelemetryEventSchema,\n onboarding_dashboard_reached: OnboardingDashboardReachedTelemetryEventSchema,\n provisioning_safe_created: ProvisioningSafeCreatedTelemetryEventSchema,\n provisioning_safe_confirmed: ProvisioningSafeConfirmedTelemetryEventSchema,\n bootstrap_resolved: BootstrapResolvedTelemetryEventSchema,\n bootstrap_failed: BootstrapFailedTelemetryEventSchema,\n member_activation_started: MemberActivationStartedTelemetryEventSchema,\n member_activation_ready: MemberActivationReadyTelemetryEventSchema,\n member_activation_failed: MemberActivationFailedTelemetryEventSchema,\n organization_creation_started: OrganizationCreationStartedTelemetryEventSchema,\n organization_creation_ready: OrganizationCreationReadyTelemetryEventSchema,\n organization_creation_failed: OrganizationCreationFailedTelemetryEventSchema,\n account_balance_read: AccountBalanceReadTelemetryEventSchema,\n account_balance_failed: AccountBalanceFailedTelemetryEventSchema,\n faucet_requested: FaucetRequestedTelemetryEventSchema,\n faucet_confirmed: FaucetConfirmedTelemetryEventSchema,\n faucet_failed: FaucetFailedTelemetryEventSchema,\n subaccount_created: SubaccountCreatedTelemetryEventSchema,\n subaccount_renamed: SubaccountRenamedTelemetryEventSchema,\n subaccount_deleted: SubaccountDeletedTelemetryEventSchema,\n subaccount_op_failed: SubaccountOpFailedTelemetryEventSchema,\n transfer_requested: TransferRequestedTelemetryEventSchema,\n transfer_backend_received: TransferBackendReceivedTelemetryEventSchema,\n transfer_confirmed: TransferConfirmedTelemetryEventSchema,\n transfer_failed: TransferFailedTelemetryEventSchema,\n org_create_started: OrgCreateStartedTelemetryEventSchema,\n org_safe_created: OrgSafeCreatedTelemetryEventSchema,\n org_safe_confirmed: OrgSafeConfirmedTelemetryEventSchema,\n org_roles_seeded: OrgRolesSeededTelemetryEventSchema,\n org_created: OrgCreatedTelemetryEventSchema,\n org_create_failed: OrgCreateFailedTelemetryEventSchema,\n org_invite_sent: OrgInviteSentTelemetryEventSchema,\n org_invite_accepted: OrgInviteAcceptedTelemetryEventSchema,\n org_role_granted: OrgRoleGrantedTelemetryEventSchema,\n org_member_active: OrgMemberActiveTelemetryEventSchema,\n org_member_removed: OrgMemberRemovedTelemetryEventSchema,\n org_invite_expired: OrgInviteExpiredTelemetryEventSchema,\n org_role_grant_failed: OrgRoleGrantFailedTelemetryEventSchema,\n payment_requested: PaymentRequestedTelemetryEventSchema,\n payment_resolved: PaymentResolvedTelemetryEventSchema,\n payment_document_attached: PaymentDocumentAttachedTelemetryEventSchema,\n payment_submitted: PaymentSubmittedTelemetryEventSchema,\n payment_settled: PaymentSettledTelemetryEventSchema,\n payment_claimed: PaymentClaimedTelemetryEventSchema,\n payment_cancelled: PaymentCancelledTelemetryEventSchema,\n payment_redirected: PaymentRedirectedTelemetryEventSchema,\n payment_failed: PaymentFailedTelemetryEventSchema,\n stream_created: StreamCreatedTelemetryEventSchema,\n stream_claimed: StreamClaimedTelemetryEventSchema,\n stream_cancelled: StreamCancelledTelemetryEventSchema,\n stream_completed: StreamCompletedTelemetryEventSchema,\n stream_failed: StreamFailedTelemetryEventSchema,\n withdrawal_requested: WithdrawalRequestedTelemetryEventSchema,\n withdrawal_submitted: WithdrawalSubmittedTelemetryEventSchema,\n withdrawal_settled: WithdrawalSettledTelemetryEventSchema,\n withdrawal_failed: WithdrawalFailedTelemetryEventSchema,\n} as const;\n\nexport const FINANCIAL_OPS_TARGET_TELEMETRY_PRODUCERS = [\n { eventName: \"payment_requested\", ownerIssue: 410, producer: \"sdk-target\" },\n { eventName: \"payment_resolved\", ownerIssue: 410, producer: \"sdk-target\" },\n { eventName: \"payment_document_attached\", ownerIssue: 486, producer: \"sdk-target\" },\n { eventName: \"payment_submitted\", ownerIssue: 410, producer: \"sdk-target\" },\n // payment_settled WIRED in B1 → emitted from financialOps/actions.ts. #575 wired\n // the settle lanes: direct pay (markPaymentSettled) via the awaited\n // emitSettledTelemetry, and org spend/payroll (applyOrgPaymentRecord) via the\n // scheduled emitScheduledSettledTelemetry. (#1144 demolished the workbench\n // execute and receivable collect lanes; the two literal producers stay.) The\n // ADR-0007 rule was relaxed from exactly-one to ≥1 for this reason. Absent\n // here per planned-XOR-wired.\n //\n // #575 WIRED the commitment-resolution backend producers (financialOps/actions.ts:\n // claimCommitment → payment_claimed | stream_claimed | stream_completed;\n // cancelCommitment → payment_cancelled | stream_cancelled; redirectCommitment →\n // payment_redirected). All absent here per planned-XOR-wired.\n { eventName: \"payment_failed\", ownerIssue: 410, producer: \"sdk-target\" },\n { eventName: \"stream_created\", ownerIssue: 411, producer: \"sdk-target\" },\n { eventName: \"stream_failed\", ownerIssue: 411, producer: \"sdk-target\" },\n // Withdrawal / cash-out lane (B3). `withdrawal_settled` is WIRED (emitted from\n // financialOps/actions.ts markWithdrawalSettled via emitServerAwaited) — per\n // planned-XOR-wired it is ABSENT here. The other three stay RED targets until\n // their producers land.\n { eventName: \"withdrawal_requested\", ownerIssue: 410, producer: \"sdk-target\" },\n { eventName: \"withdrawal_submitted\", ownerIssue: 410, producer: \"sdk-target\" },\n { eventName: \"withdrawal_failed\", ownerIssue: 410, producer: \"sdk-target\" },\n] as const;\n\n/**\n * Catalog events whose product mapper remains gated on the #1150 frontend\n * adoption. L1 S1 removes their retired SDK-flow producers without inventing\n * replacements inside the identity actor. The telemetry-spine gate enforces\n * planned-XOR-wired: a name must leave this list in the same change that adds\n * its real product-boundary producer.\n */\nexport const PRODUCT_MAPPER_GATED_TELEMETRY_EVENTS = [\"auth_otp_expired\"] as const;\n\n/** Catalogued browser observations whose only legal producer lands in L1 S6. */\nexport const BROWSER_GATED_TELEMETRY_EVENTS = [\n \"onboarding_intent_selected\",\n \"onboarding_profile_submitted\",\n \"onboarding_organization_submitted\",\n \"onboarding_dashboard_reached\",\n] as const;\n\nexport interface TelemetryIdentifyInput {\n readonly distinctId: string;\n readonly anonDistinctId?: AnonymousDistinctId;\n readonly traits?: TelemetryProps;\n readonly properties?: TelemetryProps;\n}\n\nexport interface TelemetryGroupInput {\n readonly groupType: string;\n readonly groupKey: string;\n readonly properties?: TelemetryProps;\n}\n\nimport type { TelemetryPort, HandledErrorReportContext } from \"./telemetry-port\";\nexport type { TelemetryPort, HandledErrorReportContext } from \"./telemetry-port\";\n\nexport type TrackHandler = (name: TelemetryEventName, props?: TelemetryProps) => void;\n\nlet trackHandler: TrackHandler = () => {};\n\nexport function setTrackHandler(handler: TrackHandler): TrackHandler {\n const previous = trackHandler;\n trackHandler = handler;\n return previous;\n}\n\nexport function getTrackHandler(): TrackHandler {\n return trackHandler;\n}\n\nexport function track(name: TelemetryEventName, props?: TelemetryProps): void {\n trackHandler(name, props);\n}\n\nexport interface TelemetryRedactionOptions {\n readonly rawMode?: boolean;\n}\n\nexport function redactTelemetryEvent(\n event: TelemetryEvent,\n options: TelemetryRedactionOptions = {},\n): TelemetryEvent {\n const props = redactTelemetryProps(event.name, event.props, options);\n return props === undefined ? { name: event.name } : { name: event.name, props };\n}\n\nexport function redactTelemetryProps(\n name: TelemetryEventName,\n props: TelemetryProps | undefined,\n options: TelemetryRedactionOptions = {},\n): TelemetryProps | undefined {\n if (props === undefined) return undefined;\n\n const clone = cloneProps(props);\n if (options.rawMode === true) return clone;\n\n for (const key of PII_PROP_KEYS_BY_EVENT[name] ?? []) {\n redactProperty(clone, key);\n }\n return clone;\n}\n\n/**\n * The vendor-neutral shape needed by a PostHog `before_send` callback.\n * Keeping this structural avoids making the observability contract depend on\n * posthog-js while still giving browser hosts one shared URL-scrubbing policy.\n */\nexport interface PostHogBrowserCapture {\n readonly event: string;\n properties: Record<string, unknown>;\n $set?: Record<string, unknown>;\n $set_once?: Record<string, unknown>;\n}\n\n/**\n * Remove query strings and fragments from every PostHog URL/referrer/path\n * property before transport. Browser applications may carry emails, draft ids,\n * or other capabilities in the URL; those values must never leave the origin.\n *\n * The callback mutates and returns the supplied event, matching PostHog's\n * `before_send` contract while preserving the event's full structural type.\n */\nexport function sanitizePostHogBrowserEvent<T extends PostHogBrowserCapture | null>(event: T): T {\n if (event === null) return event;\n\n const seen = new WeakSet<object>();\n sanitizePostHogBrowserValue(event.properties, seen);\n if (event.$set !== undefined) sanitizePostHogBrowserValue(event.$set, seen);\n if (event.$set_once !== undefined) sanitizePostHogBrowserValue(event.$set_once, seen);\n return event;\n}\n\n/**\n * Sanitize AND stamp. Every browser event leaves with `capxul_env` and\n * `producer: \"browser\"` on it, because the browser half has no transport of\n * its own to stamp at — `before_send` is the one funnel every capture,\n * pageview, exception and replay-meta event passes through. Forgetting to\n * register a super-property is therefore not a failure mode.\n */\nexport function createCapxulBeforeSend(\n capxulEnv: CapxulEnv,\n): <T extends PostHogBrowserCapture | null>(event: T) => T {\n return (event) => {\n const sanitized = sanitizePostHogBrowserEvent(event);\n if (sanitized === null) return sanitized;\n sanitized.properties.capxul_env = capxulEnv;\n sanitized.properties.producer ??= \"browser\" satisfies TelemetryProducer;\n return sanitized;\n };\n}\n\nexport type PostHogBeforeSend = ReturnType<typeof createCapxulBeforeSend>;\n\n/**\n * ADR-0016 posture, unchanged: capability-URL utility apps (approval links,\n * docs). No persistence, no autocapture, no replay, no flags, pathname-only\n * pageviews. Survives the app demolition as a library.\n */\nexport interface PostHogUtilityAppOptions {\n readonly api_host: string;\n readonly defaults: \"2026-01-30\";\n readonly autocapture: false;\n readonly capture_pageview: false;\n readonly capture_pageleave: true;\n readonly disable_session_recording: true;\n readonly disable_persistence: true;\n readonly capture_heatmaps: false;\n readonly capture_exceptions: false;\n readonly capture_performance: false;\n readonly disable_surveys: true;\n readonly disable_web_experiments: true;\n readonly disable_product_tours: true;\n readonly disable_conversations: true;\n readonly disable_external_dependency_loading: true;\n readonly person_profiles: \"identified_only\";\n readonly advanced_disable_flags: true;\n readonly save_campaign_params: false;\n readonly save_referrer: false;\n readonly before_send: PostHogBeforeSend;\n}\n\n/** Back-compat alias for the pre-ADR-0020 name. */\nexport type PostHogBrowserOptions = PostHogUtilityAppOptions;\n\n/**\n * ADR-0020 A6 product posture: same sanitizer / slim-bundle / token-guard core\n * as the utility profile, but the three toggles a PRODUCT needs and a\n * capability-URL utility must not have —\n *\n * - `disable_persistence: false` — J1 spans an OTP reload; without persistence\n * step 1 and step 3 are different anonymous \"users\" and every multi-page\n * funnel lies.\n * - identify-driven person profiles (ADR-0020 A2 wires the calls at L1).\n * - session replay, PRODUCTION only, fully masked (inputs, all text, no\n * canvas, no header/body capture). Below production it stays off, which is\n * also why external dependency loading (the recorder script) stays blocked\n * there.\n *\n * Autocapture stays OFF: funnels run on catalog events, not on DOM guesses.\n */\nexport interface PostHogProductAppOptions {\n readonly api_host: string;\n readonly defaults: \"2026-01-30\";\n readonly autocapture: false;\n readonly capture_pageview: false;\n readonly capture_pageleave: true;\n readonly disable_session_recording: boolean;\n readonly disable_persistence: false;\n readonly capture_heatmaps: false;\n readonly capture_exceptions: true;\n readonly capture_performance: false;\n readonly disable_surveys: true;\n readonly disable_web_experiments: true;\n readonly disable_product_tours: true;\n readonly disable_conversations: true;\n readonly disable_external_dependency_loading: boolean;\n readonly person_profiles: \"identified_only\";\n readonly advanced_disable_flags: true;\n readonly save_campaign_params: false;\n readonly save_referrer: false;\n readonly session_recording: {\n readonly maskAllInputs: true;\n readonly maskTextSelector: \"*\";\n readonly captureCanvas: { readonly recordCanvas: false };\n readonly recordHeaders: false;\n readonly recordBody: false;\n };\n readonly before_send: PostHogBeforeSend;\n}\n\nexport interface CapxulBrowserAnalyticsInput {\n readonly key: string | undefined;\n readonly host: string;\n /** Where this browser build runs. Stamped on every event it sends. */\n readonly capxulEnv: CapxulEnv;\n}\n\n/** Back-compat alias for the pre-ADR-0020 name. */\nexport type InitializePostHogBrowserAnalyticsInput = CapxulBrowserAnalyticsInput;\n\nexport function utilityAppAnalytics(input: CapxulBrowserAnalyticsInput): PostHogUtilityAppOptions {\n return {\n api_host: input.host,\n defaults: \"2026-01-30\",\n autocapture: false,\n capture_pageview: false,\n capture_pageleave: true,\n disable_session_recording: true,\n disable_persistence: true,\n capture_heatmaps: false,\n capture_exceptions: false,\n capture_performance: false,\n disable_surveys: true,\n disable_web_experiments: true,\n disable_product_tours: true,\n disable_conversations: true,\n disable_external_dependency_loading: true,\n person_profiles: \"identified_only\",\n advanced_disable_flags: true,\n save_campaign_params: false,\n save_referrer: false,\n before_send: createCapxulBeforeSend(input.capxulEnv),\n };\n}\n\nexport function productAppAnalytics(input: CapxulBrowserAnalyticsInput): PostHogProductAppOptions {\n const replay = input.capxulEnv === \"production\";\n return {\n api_host: input.host,\n defaults: \"2026-01-30\",\n autocapture: false,\n capture_pageview: false,\n capture_pageleave: true,\n disable_session_recording: !replay,\n disable_persistence: false,\n capture_heatmaps: false,\n capture_exceptions: true,\n capture_performance: false,\n disable_surveys: true,\n disable_web_experiments: true,\n disable_product_tours: true,\n disable_conversations: true,\n disable_external_dependency_loading: !replay,\n person_profiles: \"identified_only\",\n advanced_disable_flags: true,\n save_campaign_params: false,\n save_referrer: false,\n session_recording: {\n maskAllInputs: true,\n maskTextSelector: \"*\",\n captureCanvas: { recordCanvas: false },\n recordHeaders: false,\n recordBody: false,\n },\n before_send: createCapxulBeforeSend(input.capxulEnv),\n };\n}\n\nexport type PostHogBrowserInitialize<Options, T> = (key: string, options: Options) => T;\n\nexport interface PostHogBrowserPageviewClient {\n capture(event: \"$pageview\", properties: Readonly<Record<string, unknown>>): unknown;\n}\n\n/**\n * Apply a named privacy profile before an application-owned PostHog client\n * initializes. Hosts still own the vendor client and lifecycle; this helper\n * centralizes the security-relevant options and the missing-key opt-out (no\n * key ⇒ no client ⇒ no network call).\n */\nexport function initializeCapxulBrowserAnalytics<Options, T>(\n profile: (input: CapxulBrowserAnalyticsInput) => Options,\n input: CapxulBrowserAnalyticsInput,\n initialize: PostHogBrowserInitialize<Options, T>,\n): T | undefined {\n const key = input.key?.trim();\n if (key === undefined || key.length === 0) return undefined;\n\n try {\n return initialize(key, profile(input));\n } catch {\n return undefined;\n }\n}\n\n/** The utility profile, pre-bound — the shape ADR-0016's consumers already use. */\nexport function initializePostHogBrowserAnalytics<T>(\n input: CapxulBrowserAnalyticsInput,\n initialize: PostHogBrowserInitialize<PostHogUtilityAppOptions, T>,\n): T | undefined {\n return initializeCapxulBrowserAnalytics(utilityAppAnalytics, input, initialize);\n}\n\n/**\n * Build an explicit SPA pageview sink for toolbar-free PostHog clients. The\n * pathname-only input avoids query capabilities, repeated pathnames are\n * deduplicated, and vendor failures remain best-effort.\n */\nexport function createPostHogBrowserPageviewTracker(\n client: PostHogBrowserPageviewClient | null | undefined,\n): (pathname: string) => void {\n let previousPathname: string | undefined;\n return (pathname) => {\n if (client === null || client === undefined) return;\n const safePathname = stripUrlQueryAndFragment(pathname);\n if (safePathname === previousPathname) return;\n try {\n void Promise.resolve(client.capture(\"$pageview\", { $pathname: safePathname })).catch(\n () => {},\n );\n previousPathname = safePathname;\n } catch {\n // Analytics is best effort and cannot interrupt application navigation.\n }\n };\n}\n\nfunction sanitizePostHogBrowserValue(value: unknown, seen: WeakSet<object>): void {\n if (typeof value !== \"object\" || value === null || seen.has(value)) return;\n seen.add(value);\n\n if (Array.isArray(value)) {\n for (const item of value) sanitizePostHogBrowserValue(item, seen);\n return;\n }\n\n const properties = value as Record<string, unknown>;\n for (const [key, nestedValue] of Object.entries(properties)) {\n if (isPostHogQueryDerivedProperty(key)) {\n delete properties[key];\n continue;\n }\n if (typeof nestedValue === \"string\" && isPostHogUrlProperty(key)) {\n properties[key] = stripUrlQueryAndFragment(nestedValue);\n continue;\n }\n sanitizePostHogBrowserValue(nestedValue, seen);\n }\n}\n\nconst POSTHOG_QUERY_DERIVED_PROPERTY_NAMES = [\n \"utm_source\",\n \"utm_medium\",\n \"utm_campaign\",\n \"utm_content\",\n \"utm_term\",\n \"gad_source\",\n \"mc_cid\",\n \"gclid\",\n \"gclsrc\",\n \"dclid\",\n \"gbraid\",\n \"wbraid\",\n \"fbclid\",\n \"msclkid\",\n \"twclid\",\n \"li_fat_id\",\n \"igshid\",\n \"ttclid\",\n \"rdt_cid\",\n \"epik\",\n \"qclid\",\n \"sccid\",\n \"irclid\",\n \"_kx\",\n \"ph_keyword\",\n] as const;\n\nfunction isPostHogQueryDerivedProperty(key: string): boolean {\n const normalized = key.toLowerCase();\n return POSTHOG_QUERY_DERIVED_PROPERTY_NAMES.some(\n (propertyName) =>\n normalized === propertyName ||\n normalized.endsWith(`_${propertyName}`) ||\n normalized.endsWith(`$${propertyName}`),\n );\n}\n\nfunction isPostHogUrlProperty(key: string): boolean {\n const normalized = key.toLowerCase();\n return (\n normalized.includes(\"url\") ||\n normalized.includes(\"referrer\") ||\n normalized.includes(\"path\") ||\n normalized.includes(\"filename\")\n );\n}\n\nfunction stripUrlQueryAndFragment(value: string): string {\n const queryIndex = value.indexOf(\"?\");\n const fragmentIndex = value.indexOf(\"#\");\n if (queryIndex === -1 && fragmentIndex === -1) return value;\n if (queryIndex === -1) return value.slice(0, fragmentIndex);\n if (fragmentIndex === -1) return value.slice(0, queryIndex);\n return value.slice(0, Math.min(queryIndex, fragmentIndex));\n}\n\nexport class RecordingTelemetryAdapter implements TelemetryPort {\n readonly #events: TelemetryEvent[] = [];\n readonly #rawMode: boolean;\n\n constructor(options: TelemetryRedactionOptions = {}) {\n this.#rawMode = options.rawMode === true;\n }\n\n get events(): readonly TelemetryEvent[] {\n return this.#events.map((event) => cloneEvent(event));\n }\n\n emit(event: TelemetryEvent): Effect.Effect<void, never> {\n return Effect.sync(() => {\n this.#events.push(redactTelemetryEvent(event, { rawMode: this.#rawMode }));\n });\n }\n\n identify(_input: TelemetryIdentifyInput): Effect.Effect<void, never> {\n return Effect.void;\n }\n\n group(_input: TelemetryGroupInput): Effect.Effect<void, never> {\n return Effect.void;\n }\n\n reset(): Effect.Effect<void, never> {\n return Effect.void;\n }\n\n reportHandledError(\n _error: CapxulError,\n _context?: HandledErrorReportContext,\n ): Effect.Effect<void, never> {\n return Effect.void;\n }\n\n clear(): void {\n this.#events.length = 0;\n }\n}\n\nexport class PostHogTelemetryAdapter implements TelemetryPort {\n readonly #capture: (name: string, props?: TelemetryProps) => void | Promise<void>;\n\n constructor(deps: {\n readonly capture: (name: string, props?: TelemetryProps) => void | Promise<void>;\n }) {\n this.#capture = deps.capture;\n }\n\n emit(event: TelemetryEvent): Effect.Effect<void, never> {\n return Effect.sync(() => {\n try {\n void Promise.resolve(\n this.#capture(event.name, redactTelemetryProps(event.name, event.props)),\n ).catch(() => {});\n } catch {}\n });\n }\n\n identify(_input: TelemetryIdentifyInput): Effect.Effect<void, never> {\n return Effect.void;\n }\n\n group(_input: TelemetryGroupInput): Effect.Effect<void, never> {\n return Effect.void;\n }\n\n reset(): Effect.Effect<void, never> {\n return Effect.void;\n }\n\n reportHandledError(\n _error: CapxulError,\n _context?: HandledErrorReportContext,\n ): Effect.Effect<void, never> {\n return Effect.void;\n }\n}\n\nexport class InMemoryTelemetryBusAdapter implements TelemetryPort {\n readonly #subscribers = new Set<(event: TelemetryEvent) => void>();\n readonly #rawMode: boolean;\n\n constructor(options: TelemetryRedactionOptions = {}) {\n this.#rawMode = options.rawMode === true;\n }\n\n subscribe(handler: (event: TelemetryEvent) => void): () => void {\n this.#subscribers.add(handler);\n return () => {\n this.#subscribers.delete(handler);\n };\n }\n\n emit(event: TelemetryEvent): Effect.Effect<void, never> {\n return Effect.sync(() => {\n const delivered = redactTelemetryEvent(event, { rawMode: this.#rawMode });\n for (const handler of this.#subscribers) {\n try {\n handler(cloneEvent(delivered));\n } catch {\n /* fire-and-forget */\n }\n }\n });\n }\n\n identify(_input: TelemetryIdentifyInput): Effect.Effect<void, never> {\n return Effect.void;\n }\n\n group(_input: TelemetryGroupInput): Effect.Effect<void, never> {\n return Effect.void;\n }\n\n reset(): Effect.Effect<void, never> {\n return Effect.void;\n }\n\n reportHandledError(\n _error: CapxulError,\n _context?: HandledErrorReportContext,\n ): Effect.Effect<void, never> {\n return Effect.void;\n }\n}\n\nconst PII_PROP_KEYS_BY_EVENT: Partial<Record<TelemetryEventName, readonly string[]>> = {\n auth_otp_requested: [\"email\"],\n auth_otp_delivered: [\"email\"],\n auth_otp_expired: [\"email\"],\n auth_failed: [\"email\"],\n};\n\nfunction redactProperty(props: TelemetryProps, key: string): void {\n const value = props[key];\n if (typeof value === \"string\") {\n props[key] = sha256Hex(value).slice(0, 12);\n }\n}\n\nfunction cloneEvent(event: TelemetryEvent): TelemetryEvent {\n if (event.props === undefined) {\n return { name: event.name };\n }\n\n return {\n name: event.name,\n props: cloneProps(event.props),\n };\n}\n\nfunction cloneProps(props: TelemetryProps): TelemetryProps {\n const cloned: TelemetryProps = {};\n for (const [key, value] of Object.entries(props)) {\n cloned[key] = cloneTelemetryValue(value);\n }\n return cloned;\n}\n\nfunction cloneTelemetryValue(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(cloneTelemetryValue);\n if (value === null || typeof value !== \"object\") return value;\n if (Object.getPrototypeOf(value) !== Object.prototype) return value;\n const cloned: Record<string, unknown> = {};\n for (const [key, nested] of Object.entries(value)) {\n cloned[key] = cloneTelemetryValue(nested);\n }\n return cloned;\n}\n\nconst SHA256_INITIAL_HASH: readonly number[] = [\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,\n] as const;\n\nconst SHA256_K: readonly number[] = [\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,\n] as const;\n\nfunction sha256Hex(input: string): string {\n const bytes = new TextEncoder().encode(input);\n const padded = padSha256Message(bytes);\n const view = new DataView(padded.buffer, padded.byteOffset, padded.byteLength);\n const words = new Uint32Array(64);\n let h0 = SHA256_INITIAL_HASH[0]!;\n let h1 = SHA256_INITIAL_HASH[1]!;\n let h2 = SHA256_INITIAL_HASH[2]!;\n let h3 = SHA256_INITIAL_HASH[3]!;\n let h4 = SHA256_INITIAL_HASH[4]!;\n let h5 = SHA256_INITIAL_HASH[5]!;\n let h6 = SHA256_INITIAL_HASH[6]!;\n let h7 = SHA256_INITIAL_HASH[7]!;\n\n for (let offset = 0; offset < padded.byteLength; offset += 64) {\n for (let i = 0; i < 16; i++) {\n words[i] = view.getUint32(offset + i * 4);\n }\n for (let i = 16; i < 64; i++) {\n const s0 = rotr(words[i - 15]!, 7) ^ rotr(words[i - 15]!, 18) ^ (words[i - 15]! >>> 3);\n const s1 = rotr(words[i - 2]!, 17) ^ rotr(words[i - 2]!, 19) ^ (words[i - 2]! >>> 10);\n words[i] = (words[i - 16]! + s0 + words[i - 7]! + s1) >>> 0;\n }\n\n let a = h0;\n let b = h1;\n let c = h2;\n let d = h3;\n let e = h4;\n let f = h5;\n let g = h6;\n let h = h7;\n\n for (let i = 0; i < 64; i++) {\n const s1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25);\n const ch = (e & f) ^ (~e & g);\n const temp1 = (h + s1 + ch + SHA256_K[i]! + words[i]!) >>> 0;\n const s0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22);\n const maj = (a & b) ^ (a & c) ^ (b & c);\n const temp2 = (s0 + maj) >>> 0;\n\n h = g;\n g = f;\n f = e;\n e = (d + temp1) >>> 0;\n d = c;\n c = b;\n b = a;\n a = (temp1 + temp2) >>> 0;\n }\n\n h0 = (h0 + a) >>> 0;\n h1 = (h1 + b) >>> 0;\n h2 = (h2 + c) >>> 0;\n h3 = (h3 + d) >>> 0;\n h4 = (h4 + e) >>> 0;\n h5 = (h5 + f) >>> 0;\n h6 = (h6 + g) >>> 0;\n h7 = (h7 + h) >>> 0;\n }\n\n return [h0, h1, h2, h3, h4, h5, h6, h7]\n .map((word) => word.toString(16).padStart(8, \"0\"))\n .join(\"\");\n}\n\nfunction padSha256Message(bytes: Uint8Array): Uint8Array {\n const bitLength = bytes.byteLength * 8;\n const zeroPadLength = (64 - ((bytes.byteLength + 1 + 8) % 64)) % 64;\n const output = new Uint8Array(bytes.byteLength + 1 + zeroPadLength + 8);\n output.set(bytes);\n output[bytes.byteLength] = 0x80;\n\n const view = new DataView(output.buffer);\n view.setUint32(output.byteLength - 8, Math.floor(bitLength / 0x100000000));\n view.setUint32(output.byteLength - 4, bitLength >>> 0);\n return output;\n}\n\nfunction rotr(value: number, bits: number): number {\n return (value >>> bits) | (value << (32 - bits));\n}\n","import { Context } from \"effect\";\nexport {\n TELEMETRY_EVENT_NAMES,\n redactTelemetryEvent,\n redactTelemetryProps,\n type TelemetryGroupInput,\n type TelemetryIdentifyInput,\n type TelemetryEvent,\n type TelemetryEventName,\n type TelemetryProps,\n type TelemetryRedactionOptions,\n} from \"@capxul/observability\";\nexport type { TelemetryPort, HandledErrorReportContext } from \"@capxul/observability\";\nimport type { TelemetryPort } from \"@capxul/observability\";\n\nexport class TelemetryPortTag extends Context.Service<TelemetryPortTag, TelemetryPort>()(\n \"@capxul/sdk/ports/TelemetryPort\",\n) {}\n","import { Effect, Layer } from \"effect\";\n\nimport {\n redactTelemetryProps,\n TelemetryPortTag,\n type TelemetryEvent,\n type TelemetryGroupInput,\n type TelemetryIdentifyInput,\n type TelemetryEventName,\n type TelemetryPort,\n type TelemetryProps,\n} from \"../../ports/telemetry\";\n\nexport type PostHogCapture = (\n name: TelemetryEventName,\n props: TelemetryProps | undefined,\n source?: TelemetryEvent,\n) => void | Promise<void>;\nexport type PostHogIdentify = (input: TelemetryIdentifyInput) => void | Promise<void>;\nexport type PostHogGroup = (input: TelemetryGroupInput) => void | Promise<void>;\nexport type PostHogReset = () => void | Promise<void>;\n\nexport type PostHogTelemetryLayerDeps = {\n readonly capture: PostHogCapture;\n readonly identify?: PostHogIdentify;\n readonly group?: PostHogGroup;\n readonly reset?: PostHogReset;\n};\n\nexport class PostHogTelemetryAdapter implements TelemetryPort {\n readonly #capture: PostHogCapture;\n readonly #identify: PostHogIdentify;\n readonly #group: PostHogGroup;\n readonly #reset: PostHogReset;\n\n constructor(deps: PostHogTelemetryLayerDeps) {\n this.#capture = deps.capture;\n this.#identify = deps.identify ?? (() => undefined);\n this.#group = deps.group ?? (() => undefined);\n this.#reset = deps.reset ?? (() => undefined);\n }\n\n emit(event: TelemetryEvent): Effect.Effect<void, never, never> {\n return this.#run(\n () =>\n this.#capture(event.name, redactTelemetryProps(event.name, cloneProps(event.props)), event),\n \"emit\",\n event.name,\n );\n }\n\n identify(input: TelemetryIdentifyInput): Effect.Effect<void, never, never> {\n return this.#run(() => this.#identify(cloneIdentifyInput(input)), \"identify\");\n }\n\n group(input: TelemetryGroupInput): Effect.Effect<void, never, never> {\n return this.#run(() => this.#group(cloneGroupInput(input)), \"group\");\n }\n\n reset(): Effect.Effect<void, never, never> {\n return this.#run(() => this.#reset(), \"reset\");\n }\n\n #run(\n operation: () => void | Promise<void>,\n operationName: \"emit\" | \"identify\" | \"group\" | \"reset\",\n eventName?: TelemetryEventName,\n ): Effect.Effect<void, never> {\n const diagnose = Effect.logWarning(\"product.telemetry.transport.dropped\").pipe(\n Effect.annotateLogs({\n operation: operationName,\n ...(eventName === undefined ? {} : { product_event: eventName }),\n }),\n Effect.catchCause(() => Effect.void),\n );\n return Effect.suspend(() => {\n let pending: void | Promise<void>;\n try {\n pending = operation();\n } catch {\n return diagnose;\n }\n if (pending === undefined) return Effect.void;\n const transport = Effect.tryPromise({\n try: () => pending,\n catch: () => undefined,\n }).pipe(Effect.catch(() => diagnose));\n return Effect.forkDetach(transport, { startImmediately: true }).pipe(Effect.asVoid);\n });\n }\n}\n\nexport function PostHogTelemetryLayer(\n deps: PostHogTelemetryLayerDeps,\n): Layer.Layer<TelemetryPortTag, never, never> {\n return Layer.succeed(TelemetryPortTag, new PostHogTelemetryAdapter(deps));\n}\n\nfunction cloneIdentifyInput(input: TelemetryIdentifyInput): TelemetryIdentifyInput {\n const traits = input.traits === undefined ? undefined : cloneProps(input.traits);\n const properties = input.properties === undefined ? undefined : cloneProps(input.properties);\n return {\n distinctId: input.distinctId,\n ...(input.anonDistinctId === undefined ? {} : { anonDistinctId: input.anonDistinctId }),\n ...(traits === undefined ? {} : { traits }),\n ...(properties === undefined ? {} : { properties }),\n };\n}\n\nfunction cloneGroupInput(input: TelemetryGroupInput): TelemetryGroupInput {\n const properties = input.properties === undefined ? undefined : cloneProps(input.properties);\n return properties === undefined\n ? { groupType: input.groupType, groupKey: input.groupKey }\n : {\n groupType: input.groupType,\n groupKey: input.groupKey,\n properties,\n };\n}\n\nfunction cloneProps(props: TelemetryProps | undefined): TelemetryProps | undefined {\n if (props === undefined) return undefined;\n const cloned: TelemetryProps = {};\n for (const [key, value] of Object.entries(props)) {\n cloned[key] = cloneTelemetryValue(value);\n }\n return cloned;\n}\n\nfunction cloneTelemetryValue(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(cloneTelemetryValue);\n if (value === null || typeof value !== \"object\") return value;\n if (Object.getPrototypeOf(value) !== Object.prototype) return value;\n const cloned: Record<string, unknown> = {};\n for (const [key, nested] of Object.entries(value)) {\n cloned[key] = cloneTelemetryValue(nested);\n }\n return cloned;\n}\n","import { Effect, Result, Scope, type Tracer } from \"effect\";\nimport { CapxulError, type Failure } from \"@capxul/errors\";\nimport { toAuthUserId, toChainId, toEmail, type AuthSession, type OrgId } from \"@capxul/types\";\nimport type { WireObservationContext } from \"@capxul/wire/observation-context\";\n\nimport type { FlowPorts } from \"./types.ts\";\nimport type { CapxulSigner } from \"../signer.ts\";\nimport type { OrganizationSetupOps, OrgLifecycle } from \"../surface/org-lifecycle.ts\";\nimport {\n DEFAULT_CONFIG,\n SIGNED_OUT,\n label,\n transition,\n type AccountStep,\n type IdentityConfig,\n type IdentityEvent,\n type IdentityPrivateEvent,\n type IdentityState,\n type OrgSubmissionDraft,\n type OrgStep,\n type Session,\n} from \"../domain/identity/model.ts\";\nimport { boot, type Actor, type BootOptions, type Spec } from \"../domain/machine/shell.ts\";\nimport {\n formatTraceparent,\n portFailureOutcome,\n safeEngineeringIdentifier,\n} from \"../domain/machine/telemetry.ts\";\nimport { copyInvocationObservation } from \"../internal/invocation-observation.ts\";\n\nexport const IDENTITY_SLOT = {\n session: \"identity:session\",\n auth: \"identity:auth\",\n account: \"identity:account\",\n org: \"identity:org\",\n} as const;\n\ntype IdentityEventTag = IdentityEvent[\"_tag\"] | IdentityPrivateEvent[\"_tag\"];\ntype IdentitySlot = (typeof IDENTITY_SLOT)[keyof typeof IDENTITY_SLOT];\n\nconst IDENTITY_SLOT_BY_EVENT = {\n ReadSession: IDENTITY_SLOT.session,\n RestoreSession: IDENTITY_SLOT.session,\n SessionRead: IDENTITY_SLOT.session,\n SessionReadFailed: IDENTITY_SLOT.session,\n RequestOtp: IDENTITY_SLOT.auth,\n VerifyOtp: IDENTITY_SLOT.auth,\n SignOut: IDENTITY_SLOT.auth,\n ResumeOtpEntry: IDENTITY_SLOT.auth,\n Reset: IDENTITY_SLOT.auth,\n OtpSent: IDENTITY_SLOT.auth,\n OtpFailed: IDENTITY_SLOT.auth,\n Verified: IDENTITY_SLOT.auth,\n VerifyFailed: IDENTITY_SLOT.auth,\n SignedOut: IDENTITY_SLOT.auth,\n SignOutFailed: IDENTITY_SLOT.auth,\n EnsureAccount: IDENTITY_SLOT.account,\n ClaimAccount: IDENTITY_SLOT.account,\n RetryAccount: IDENTITY_SLOT.account,\n AccountAt: IDENTITY_SLOT.account,\n AccountDerived: IDENTITY_SLOT.account,\n AccountClaiming: IDENTITY_SLOT.account,\n AccountClaimed: IDENTITY_SLOT.account,\n AccountFailed: IDENTITY_SLOT.account,\n CreateOrganization: IDENTITY_SLOT.org,\n AttachOrganization: IDENTITY_SLOT.org,\n RetryOrganization: IDENTITY_SLOT.org,\n LeaveOrganization: IDENTITY_SLOT.org,\n OrgAt: IDENTITY_SLOT.org,\n OrgReady: IDENTITY_SLOT.org,\n OrgFailed: IDENTITY_SLOT.org,\n} satisfies Record<IdentityEventTag, IdentitySlot>;\n\nconst identitySlot = (event: IdentityEvent | IdentityPrivateEvent): IdentitySlot =>\n IDENTITY_SLOT_BY_EVENT[event._tag];\n\nexport interface IdentityActor extends Actor<\n IdentityState,\n IdentityEvent,\n import(\"../domain/identity/model.ts\").RefusalReason\n> {\n /** Full provider session retained beside the deliberately minimal model session. */\n readonly authSession: () => AuthSession | null;\n /** Trust a cache-resumed provider session before a later ReadSession verifies it. */\n readonly restoreAuthSession: (\n session: AuthSession,\n controls?: import(\"../domain/machine/shell.ts\").InvocationControls,\n ) => Effect.Effect<\n IdentityState,\n import(\"../domain/machine/shell.ts\").ActorFailure<\n import(\"../domain/identity/model.ts\").RefusalReason | import(\"@capxul/errors\").CapxulErrorCode\n >\n >;\n}\n\nexport interface BootIdentityFlowInput {\n readonly ports: Pick<FlowPorts, \"authClient\" | \"identity\" | \"smartAccount\" | \"clock\">;\n readonly chainId: number;\n readonly requirement: IdentityConfig[\"requirement\"];\n readonly signer?: CapxulSigner;\n readonly organizationSetup?: OrganizationSetupOps;\n readonly otpTtlMs?: number;\n}\n\nconst failureOf = (error: unknown): Failure => {\n if (error instanceof CapxulError) {\n const mode = error.details?.failure_mode;\n return {\n code: error.code,\n message: error.message,\n ...(typeof mode === \"string\" ? { mode: mode as Exclude<Failure[\"mode\"], undefined> } : {}),\n };\n }\n if (typeof error === \"object\" && error !== null && \"publicError\" in error) {\n return failureOf((error as { readonly publicError: unknown }).publicError);\n }\n if (typeof error === \"object\" && error !== null && \"cause\" in error) {\n const cause = (error as { readonly cause: unknown }).cause;\n if (cause !== error) return failureOf(cause);\n }\n return {\n code: \"UNKNOWN\",\n message: error instanceof Error ? error.message : \"Unexpected identity work failure\",\n };\n};\n\nconst resultEffect = <A>(\n name: string,\n promise: (\n parent: Tracer.AnySpan,\n ) => Promise<\n { readonly ok: true; readonly value: A } | { readonly ok: false; readonly error: CapxulError }\n >,\n) =>\n call(\n name,\n Effect.currentSpan.pipe(\n Effect.flatMap((parent) => Effect.promise(() => promise(parent))),\n Effect.flatMap((result) =>\n result.ok ? Effect.succeed(result.value) : Effect.fail(result.error),\n ),\n ),\n );\n\nconst call = <A, E, R>(\n name: string,\n effect: Effect.Effect<A, E, R>,\n): Effect.Effect<A, Failure, R> =>\n effect.pipe(\n Effect.mapError(failureOf),\n Effect.tap(() => Effect.annotateCurrentSpan({ outcome: \"succeeded\" })),\n Effect.tapError((failure) =>\n Effect.annotateCurrentSpan({\n outcome: portFailureOutcome(failure.code),\n failure_code: failure.code,\n ...(failure.mode === undefined ? {} : { mode: failure.mode }),\n }),\n ),\n Effect.tapDefect(() =>\n Effect.annotateCurrentSpan({ outcome: \"failed\", failure_code: \"UNKNOWN\" }),\n ),\n Effect.withSpan(`identity.port.${name}`),\n );\n\nconst modelSession = (session: AuthSession): Session => ({\n authUserId: String(session.authUserId),\n email: String(session.email),\n});\n\nconst claimAccount = (input: BootIdentityFlowInput, authUserId: string, signer: CapxulSigner) =>\n call(\n \"smart-account.claim\",\n Effect.tryPromise({\n try: () => signer.getAddress(),\n catch: () => new CapxulError(\"PROVIDER_ERROR\", \"Provider error: signer getAddress\"),\n }).pipe(\n Effect.flatMap((signerAddress) =>\n input.ports.smartAccount.claim({\n authUserId: toAuthUserId(authUserId),\n chainId: toChainId(input.chainId),\n signerAddress,\n }),\n ),\n ),\n );\n\nconst profileComplete = (profile: { readonly onboarded: boolean } | null): boolean =>\n profile?.onboarded === true;\n\nconst sessionProfile = (\n input: BootIdentityFlowInput,\n session: AuthSession | null,\n): Effect.Effect<\n { readonly session: Session | null; readonly profileComplete: boolean },\n Failure\n> => {\n if (session === null) return Effect.succeed({ session: null, profileComplete: false });\n return call(\n \"identity.load-by-auth-user-id\",\n input.ports.identity.loadByAuthUserId(session.authUserId),\n ).pipe(\n Effect.map((profile) => ({\n session: modelSession(session),\n profileComplete: profileComplete(profile),\n })),\n );\n};\n\ntype Send = (event: IdentityPrivateEvent) => Effect.Effect<void>;\n\nconst accountLane = (\n input: BootIdentityFlowInput,\n config: IdentityConfig,\n session: Session,\n send: Send,\n): Effect.Effect<void, Failure> =>\n Effect.gen(function* () {\n const failAt = (step: AccountStep, failure: Failure) =>\n send({ _tag: \"AccountFailed\", step, failure }).pipe(Effect.andThen(Effect.fail(failure)));\n\n // Wallet derivation is signerless: the verified email is the derivation\n // input. The signer is consulted only by the separate claim step.\n\n // The address is a pure function of the verified email. Identity profile\n // writes remain owned by the onboarding facade; this lane publishes the\n // ruled identity progress edge without duplicating that write.\n yield* send({ _tag: \"AccountAt\", step: \"identity\" });\n\n yield* send({ _tag: \"AccountAt\", step: \"provision\" });\n const existing = yield* Effect.result(\n call(\n \"smart-account.load-by-auth-user-id\",\n input.ports.smartAccount.loadByAuthUserId(toAuthUserId(session.authUserId)),\n ),\n );\n if (Result.isFailure(existing)) return yield* failAt(\"provision\", existing.failure);\n const provisioned = yield* Effect.result(\n existing.success === null\n ? call(\n \"smart-account.provision\",\n input.ports.smartAccount.provision({\n authUserId: toAuthUserId(session.authUserId),\n chainId: toChainId(input.chainId),\n }),\n )\n : Effect.succeed(existing.success),\n );\n if (Result.isFailure(provisioned)) return yield* failAt(\"provision\", provisioned.failure);\n const account = provisioned.success;\n const address = String(account.smartAccountAddress);\n yield* send({ _tag: \"AccountDerived\", address });\n\n if (account.claimedAt !== null) {\n return yield* send({ _tag: \"AccountClaimed\", address });\n }\n if (config.requirement !== \"deployed\" || input.signer === undefined) return;\n\n yield* send({ _tag: \"AccountClaiming\" });\n const claimed = yield* Effect.result(claimAccount(input, session.authUserId, input.signer));\n return yield* Result.isFailure(claimed)\n ? failAt(\"deploy\", claimed.failure)\n : send({ _tag: \"AccountClaimed\", address: String(claimed.success.smartAccountAddress) });\n });\n\nconst orgStep = (lifecycle: OrgLifecycle): OrgStep | \"ready\" => {\n if (lifecycle.status === \"ready\") return \"ready\";\n if (lifecycle.status === \"settingUp\") return lifecycle.step;\n if (lifecycle.status === \"failed\") return lifecycle.at;\n return \"preparingFounderAccount\";\n};\n\nconst orgEngineeringContext = (\n controls: import(\"../domain/machine/shell.ts\").InvocationControls,\n parent: Tracer.AnySpan,\n): WireObservationContext => {\n const correlationId = safeEngineeringIdentifier(controls.correlation_id);\n const journeyId = safeEngineeringIdentifier(controls.journey_id);\n const traceparent = formatTraceparent(parent);\n return {\n ...(correlationId === undefined ? {} : { correlationId }),\n ...(journeyId === undefined ? {} : { journeyId }),\n ...(traceparent === undefined ? {} : { traceparent }),\n };\n};\n\nconst runOrgStep = (\n setup: OrganizationSetupOps,\n orgId: OrgId,\n step: OrgStep,\n controls: import(\"../domain/machine/shell.ts\").InvocationControls,\n): Effect.Effect<OrgLifecycle, Failure> => {\n const [name, invoke] =\n step === \"preparingFounderAccount\"\n ? ([\n \"organization-setup.prepare-founder-account\",\n (parent: Tracer.AnySpan) =>\n setup.prepareFounderAccount({\n orgId,\n observationContext: orgEngineeringContext(controls, parent),\n }),\n ] as const)\n : step === \"awaitingFounderAuthorization\"\n ? ([\n \"organization-setup.authorize-and-submit-bootstrap\",\n (parent: Tracer.AnySpan) =>\n setup.authorizeAndSubmitBootstrap({\n orgId,\n observationContext: orgEngineeringContext(controls, parent),\n }),\n ] as const)\n : step === \"submittingBootstrap\"\n ? ([\n \"organization-setup.resume-submitted-bootstrap\",\n (parent: Tracer.AnySpan) =>\n setup.resumeSubmittedBootstrap({\n orgId,\n observationContext: orgEngineeringContext(controls, parent),\n }),\n ] as const)\n : ([\n \"organization-setup.confirm-submitted-bootstrap\",\n (parent: Tracer.AnySpan) =>\n setup.confirmSubmittedBootstrap({\n orgId,\n observationContext: orgEngineeringContext(controls, parent),\n }),\n ] as const);\n return resultEffect(name, invoke);\n};\n\nconst orgLane = (\n setup: OrganizationSetupOps,\n start:\n | { readonly kind: \"create\"; readonly draft: OrgSubmissionDraft }\n | { readonly kind: \"attach\" | \"retry\"; readonly orgId: string },\n send: Send,\n controls: import(\"../domain/machine/shell.ts\").InvocationControls,\n): Effect.Effect<void, Failure> =>\n Effect.gen(function* () {\n let orgId: string;\n let lifecycle: OrgLifecycle;\n if (start.kind === \"create\") {\n const opened = yield* Effect.result(\n resultEffect(\"organization-setup.start-or-resume\", (parent) =>\n setup.startOrResume({\n ...start.draft,\n observationContext: orgEngineeringContext(controls, parent),\n }),\n ),\n );\n if (Result.isFailure(opened)) {\n yield* send({\n _tag: \"OrgFailed\",\n orgId: null,\n step: \"preparingFounderAccount\",\n failure: opened.failure,\n });\n return yield* Effect.fail(opened.failure);\n }\n orgId = String(opened.success.orgId);\n lifecycle = opened.success.lifecycle;\n } else {\n const opened = yield* Effect.result(\n start.kind === \"retry\"\n ? resultEffect(\"organization-setup.retry\", (parent) =>\n setup.retry({\n orgId: start.orgId as OrgId,\n observationContext: orgEngineeringContext(controls, parent),\n }),\n )\n : resultEffect(\"organization-setup.load-lifecycle\", (parent) =>\n setup.loadLifecycle({\n orgId: start.orgId as OrgId,\n observationContext: orgEngineeringContext(controls, parent),\n }),\n ),\n );\n if (Result.isFailure(opened)) {\n yield* send({\n _tag: \"OrgFailed\",\n orgId: start.orgId,\n step: \"preparingFounderAccount\",\n failure: opened.failure,\n });\n return yield* Effect.fail(opened.failure);\n }\n orgId = start.orgId;\n lifecycle = opened.success;\n }\n if (lifecycle.status === \"failed\") {\n const failure = failureOf(lifecycle.error);\n yield* send({\n _tag: \"OrgFailed\",\n orgId,\n step: lifecycle.at,\n failure,\n retryable: lifecycle.retryable,\n });\n return yield* Effect.fail(failure);\n }\n let step = orgStep(lifecycle);\n if (step === \"ready\") {\n yield* send({ _tag: \"OrgReady\", orgId });\n return;\n }\n yield* send({ _tag: \"OrgAt\", orgId, step });\n\n while (step !== \"ready\") {\n const current: OrgStep = step;\n const advanced = yield* Effect.result(runOrgStep(setup, orgId as OrgId, current, controls));\n if (Result.isFailure(advanced)) {\n yield* send({ _tag: \"OrgFailed\", orgId, step: current, failure: advanced.failure });\n return yield* Effect.fail(advanced.failure);\n }\n lifecycle = advanced.success;\n if (lifecycle.status === \"failed\") {\n const failure = failureOf(lifecycle.error);\n yield* send({\n _tag: \"OrgFailed\",\n orgId,\n step: lifecycle.at,\n failure,\n retryable: lifecycle.retryable,\n });\n return yield* Effect.fail(failure);\n }\n step = orgStep(lifecycle);\n yield* step === \"ready\"\n ? send({ _tag: \"OrgReady\", orgId })\n : send({ _tag: \"OrgAt\", orgId, step });\n if (step === current) yield* Effect.sleep(\"1 second\");\n }\n });\n\nconst recoverIdentityFailure = (\n state: IdentityState,\n event: string,\n failure: Failure,\n): IdentityPrivateEvent | undefined => {\n if (event === \"ReadSession\") return { _tag: \"SessionReadFailed\", failure };\n if (event === \"RequestOtp\" && state.phase === \"otp_sending\") {\n return { _tag: \"OtpFailed\", failure };\n }\n if (event === \"VerifyOtp\" && state.phase === \"otp_verifying\") {\n return { _tag: \"VerifyFailed\", failure };\n }\n if (event === \"SignOut\" && state.phase === \"signing_out\") {\n return { _tag: \"SignOutFailed\", failure };\n }\n if (state.phase !== \"authenticated\") return undefined;\n if (state.account.at === \"deriving\") {\n return { _tag: \"AccountFailed\", step: state.account.step, failure };\n }\n if (state.account.at === \"claiming\") {\n return { _tag: \"AccountFailed\", step: \"deploy\", failure };\n }\n if (state.account.at !== \"claimed\" || state.account.org === null) return undefined;\n const org = state.account.org;\n if (org.at === \"creating\") {\n return {\n _tag: \"OrgFailed\",\n orgId: null,\n step: \"preparingFounderAccount\",\n failure,\n };\n }\n if (org.at === \"loading\") {\n return {\n _tag: \"OrgFailed\",\n orgId: org.orgId,\n step: \"preparingFounderAccount\",\n failure,\n };\n }\n return org.at === \"settingUp\"\n ? { _tag: \"OrgFailed\", orgId: org.orgId, step: org.step, failure }\n : undefined;\n};\n\nexport const identitySpec = (\n input: BootIdentityFlowInput,\n sessionStore: { current: AuthSession | null } = { current: null },\n): Spec<\n IdentityState,\n IdentityEvent,\n IdentityPrivateEvent,\n import(\"../domain/identity/model.ts\").RefusalReason,\n never\n> => {\n const config: IdentityConfig = {\n ...DEFAULT_CONFIG,\n requirement: input.requirement,\n hasSigner: input.signer !== undefined,\n ...(input.otpTtlMs === undefined ? {} : { otpTtlMs: input.otpTtlMs }),\n };\n\n return {\n machine: \"identity\",\n initial: SIGNED_OUT,\n label,\n slot: identitySlot,\n transition: (state, event) => transition(state, event, config),\n recoverFailure: recoverIdentityFailure,\n invalidates: (event) =>\n event._tag === \"Reset\"\n ? [IDENTITY_SLOT.auth, IDENTITY_SLOT.session, IDENTITY_SLOT.account, IDENTITY_SLOT.org]\n : event._tag === \"SignOut\"\n ? [IDENTITY_SLOT.session, IDENTITY_SLOT.account, IDENTITY_SLOT.org]\n : [],\n // This is the exhaustive work-fiber dispatcher for the closed identity\n // event set. The state transition itself remains pure in model.ts.\n // oxlint-disable-next-line eslint/complexity\n work: ({ state, event }) => {\n const activeSession = state.phase === \"authenticated\" ? state.session : null;\n const org =\n state.phase === \"authenticated\" && state.account.at === \"claimed\"\n ? state.account.org\n : null;\n switch (event._tag) {\n case \"RequestOtp\":\n return {\n slot: IDENTITY_SLOT.auth,\n port: \"auth-client\",\n run: (send, controls) =>\n call(\n \"auth-client.send-otp\",\n input.ports.authClient.sendOtp(\n copyInvocationObservation(controls, { email: toEmail(event.email) }),\n ),\n ).pipe(\n Effect.andThen(call(\"clock.now\", input.ports.clock.now)),\n Effect.flatMap((at) => send({ _tag: \"OtpSent\", at })),\n Effect.catch((failure) =>\n send({ _tag: \"OtpFailed\", failure }).pipe(Effect.andThen(Effect.fail(failure))),\n ),\n ),\n };\n case \"VerifyOtp\":\n return {\n slot: IDENTITY_SLOT.auth,\n port: \"auth-client\",\n run: (send, controls) =>\n call(\n \"auth-client.verify-otp\",\n input.ports.authClient.verifyOtp(\n copyInvocationObservation(controls, {\n email: toEmail(event.email),\n otp: event.otp,\n }),\n ),\n ).pipe(\n Effect.tap((session) =>\n Effect.sync(() => {\n sessionStore.current = session;\n }),\n ),\n Effect.flatMap((session) =>\n sessionProfile(input, session).pipe(\n Effect.flatMap((loaded) =>\n send({\n _tag: \"Verified\",\n session: loaded.session ?? modelSession(session),\n profileComplete: loaded.profileComplete,\n }),\n ),\n ),\n ),\n Effect.catch((failure) =>\n send({ _tag: \"VerifyFailed\", failure }).pipe(\n Effect.andThen(Effect.fail(failure)),\n ),\n ),\n ),\n };\n case \"ReadSession\":\n return {\n slot: IDENTITY_SLOT.session,\n port: \"auth-client\",\n run: (send, controls) =>\n call(\n \"auth-client.get-session\",\n input.ports.authClient.getSession(copyInvocationObservation(controls, {})),\n ).pipe(\n Effect.tap((session) =>\n Effect.sync(() => {\n sessionStore.current = session;\n }),\n ),\n Effect.flatMap((session) => sessionProfile(input, session)),\n Effect.flatMap((loaded) => send({ _tag: \"SessionRead\", ...loaded })),\n Effect.catch((failure) =>\n Effect.sync(() => {\n sessionStore.current = null;\n }).pipe(\n Effect.andThen(\n activeSession !== null && failure.code === \"NOT_AUTHENTICATED\"\n ? Effect.fail(failure)\n : send({ _tag: \"SessionReadFailed\", failure }).pipe(\n Effect.andThen(Effect.fail(failure)),\n ),\n ),\n ),\n ),\n ),\n };\n case \"SignOut\":\n return {\n slot: IDENTITY_SLOT.auth,\n port: \"auth-client\",\n run: (send, controls) =>\n call(\n \"auth-client.sign-out\",\n input.ports.authClient.signOut(copyInvocationObservation(controls, {})),\n ).pipe(\n Effect.andThen(send({ _tag: \"SignedOut\" })),\n Effect.catch((failure) =>\n send({ _tag: \"SignOutFailed\", failure }).pipe(\n Effect.andThen(Effect.fail(failure)),\n ),\n ),\n Effect.ensuring(\n Effect.sync(() => {\n sessionStore.current = null;\n }),\n ),\n ),\n };\n case \"EnsureAccount\":\n case \"RetryAccount\":\n return activeSession === null\n ? undefined\n : {\n slot: IDENTITY_SLOT.account,\n port: \"smart-account\",\n run: (send) => accountLane(input, config, activeSession, send),\n };\n case \"ClaimAccount\": {\n const signer = input.signer;\n const address =\n state.phase === \"authenticated\" && state.account.at === \"claiming\"\n ? state.account.address\n : null;\n return address === null || activeSession === null || signer === undefined\n ? undefined\n : {\n slot: IDENTITY_SLOT.account,\n port: \"smart-account\",\n run: (send) =>\n Effect.gen(function* () {\n const claimed = yield* Effect.result(\n claimAccount(input, activeSession.authUserId, signer),\n );\n yield* Result.isFailure(claimed)\n ? send({\n _tag: \"AccountFailed\",\n step: \"deploy\",\n failure: claimed.failure,\n }).pipe(Effect.andThen(Effect.fail(claimed.failure)))\n : send({ _tag: \"AccountClaimed\", address });\n }),\n };\n }\n case \"CreateOrganization\":\n return input.organizationSetup === undefined || org?.at !== \"creating\"\n ? undefined\n : {\n slot: IDENTITY_SLOT.org,\n port: \"organization-setup\",\n run: (send, controls) =>\n orgLane(\n input.organizationSetup!,\n { kind: \"create\", draft: event.draft },\n send,\n controls,\n ),\n };\n case \"AttachOrganization\":\n return input.organizationSetup === undefined || org?.at !== \"loading\"\n ? undefined\n : {\n slot: IDENTITY_SLOT.org,\n port: \"organization-setup\",\n run: (send, controls) =>\n orgLane(\n input.organizationSetup!,\n { kind: \"attach\", orgId: org.orgId },\n send,\n controls,\n ),\n };\n case \"RetryOrganization\":\n return input.organizationSetup === undefined || org?.at !== \"settingUp\"\n ? undefined\n : {\n slot: IDENTITY_SLOT.org,\n port: \"organization-setup\",\n run: (send, controls) =>\n orgLane(\n input.organizationSetup!,\n { kind: \"retry\", orgId: org.orgId },\n send,\n controls,\n ),\n };\n default:\n return undefined;\n }\n },\n };\n};\n\nexport const bootIdentityFlow = (\n input: BootIdentityFlowInput,\n options: BootOptions = {},\n): Effect.Effect<IdentityActor, never, Scope.Scope> =>\n Effect.gen(function* () {\n const sessionStore: { current: AuthSession | null } = { current: null };\n const actor = yield* boot(identitySpec(input, sessionStore), options);\n return {\n ...actor,\n authSession: () => sessionStore.current,\n ask: (event, controls) =>\n actor.ask(event, controls).pipe(\n Effect.tap(() =>\n event._tag === \"Reset\"\n ? Effect.sync(() => {\n sessionStore.current = null;\n })\n : Effect.void,\n ),\n ),\n restoreAuthSession: (session, controls) =>\n actor\n .ask(\n {\n _tag: \"RestoreSession\",\n session: modelSession(session),\n profileComplete: false,\n },\n controls,\n )\n .pipe(\n Effect.tap(() =>\n Effect.sync(() => {\n sessionStore.current = session;\n }),\n ),\n ),\n };\n });\n","// The org-lifecycle proof-receipt contract (A2-Q3A · blueprint §2 moves ledger).\n//\n// The one `org/lifecycle` reference the SURFACE holds — the composition root\n// reads it to answer `client.organizations.proofReceipt(orgId)`. The other four\n// `org/lifecycle` functions belong to `adapters/org`, which builds them from\n// the same `CAPXUL_FUNCTIONS` registry.\n\nimport { makeFunctionReference, type FunctionReference } from \"convex/server\";\n\nimport { CAPXUL_FUNCTIONS } from \"@capxul/wire\";\n\nimport type { OrganizationSetupProofReceipt } from \"../surface/create-capxul-client\";\n\nexport const organizationSetupProofReceiptQuery: FunctionReference<\n \"query\",\n \"public\",\n { readonly orgId: string },\n OrganizationSetupProofReceipt | null\n> = makeFunctionReference(CAPXUL_FUNCTIONS[\"org/lifecycle\"].getProofReceipt);\n","// CapxulDeps is the single dependency bundle resolved by the public-method\n// Effect seam. The identity actor is the canonical auth/account state\n// authority; these programs adapt its asks to the retained public SDK methods.\n//\n// NOT re-exported from the `@capxul/sdk` main barrel — this module is\n// workspace-internal (imported by sibling `src/client/*` modules only) and\n// has NO published export subpath. #1145: the `@capxul/sdk/react-substrate`\n// subpath these comments used to cite never existed.\n\nimport { Context, Effect, Result, Layer } from \"effect\";\n\nimport { CapxulError, Errors } from \"@capxul/config\";\nimport { toEmail } from \"@capxul/types\";\n\nimport { type IdentityActor } from \"../flows/identity\";\nimport type { IdentityEvent, IdentityState } from \"../domain/identity/model\";\nimport type { InvocationControls } from \"../domain/machine/shell\";\nimport type { ExternalSigner } from \"../flows/types\";\nimport type { AuthClientPort, CanSendOtpStatus } from \"../ports/auth-client\";\nimport type { AuthCachePort } from \"../ports/auth-cache\";\nimport type { ClockPort } from \"../ports/clock\";\nimport type { TelemetryPort } from \"../ports/telemetry\";\n\nimport type { Session } from \"./types\";\nimport { publicIdentityFailure } from \"./_shared/effect-actor-bridge\";\n\n/**\n * The dependency bundle carried by the single public-method `Context.Service`.\n * Optional OTP and invocation controls remain bundle-owned.\n */\nexport interface CapxulDeps {\n readonly actor: IdentityActor;\n readonly authClient: AuthClientPort;\n readonly authCache: AuthCachePort;\n readonly clock: ClockPort;\n readonly telemetry?: TelemetryPort;\n readonly otpTtlMs?: number;\n readonly invokeTimeoutMs?: number;\n readonly afterVerifyOtp?: () => Promise<void>;\n}\n\n/** The single Context tag the atoms + public methods both resolve. */\nexport class CapxulDepsTag extends Context.Service<CapxulDepsTag, CapxulDeps>()(\n \"@capxul/sdk/CapxulDeps\",\n) {}\n\n/** Wrap a bundle as the `Layer<CapxulDepsTag>` the React provider consumes. */\nexport function capxulDepsLayer(deps: CapxulDeps): Layer.Layer<CapxulDepsTag> {\n return Layer.succeed(CapxulDepsTag, deps);\n}\n\ntype IdentityActorFailure = import(\"../domain/machine/shell\").ActorFailure<\n import(\"@capxul/errors\").CapxulErrorCode\n>;\n\ntype WrongStateContext = {\n readonly method: string;\n readonly validStates: readonly string[];\n};\n\nconst actorError = (failure: IdentityActorFailure, wrongState?: WrongStateContext) => {\n if (failure.reason === \"WRONG_STATE\" && wrongState !== undefined) {\n return Errors.wrongState({\n ...wrongState,\n currentState: failure.state.startsWith(\"authenticated\") ? \"authenticated\" : failure.state,\n });\n }\n return new CapxulError(\n failure.reason === \"WORK_DIED\" ? \"UNKNOWN\" : failure.reason,\n failure.message,\n {\n cause: failure,\n ...(failure.details === undefined ? {} : { details: failure.details }),\n layer: \"identity\",\n },\n );\n};\n\nconst ask = (\n actor: IdentityActor,\n event: IdentityEvent,\n controls?: InvocationControls,\n wrongState?: WrongStateContext,\n): Effect.Effect<IdentityState, CapxulError> =>\n actor.ask(event, controls).pipe(\n Effect.mapError((failure) => actorError(failure, wrongState)),\n Effect.flatMap((state) =>\n state.phase === \"faulted\"\n ? Effect.fail(publicIdentityFailure(state.failure))\n : Effect.succeed(state),\n ),\n );\n\n/**\n * getSession as one Effect requiring only `CapxulDepsTag`. The thin public\n * wrapper owns the leading abort pre-check; non-aborted signals reach the\n * identity actor through invocation controls.\n */\nexport const getSessionProgramWithOptions = (\n options?: AuthProgramOptions,\n): Effect.Effect<Session | null, CapxulError, CapxulDepsTag> =>\n Effect.gen(function* () {\n const deps = yield* CapxulDepsTag;\n\n // Cache-first.\n const cached = yield* deps.authCache.getSession.pipe(\n Effect.mapError((e) => Errors.providerError(\"auth-cache\", \"getSession\", e)),\n );\n const observed = deps.actor.snapshot();\n const actorState = observed.phase;\n if (observed.phase === \"faulted\") {\n return yield* Effect.fail(publicIdentityFailure(observed.failure));\n }\n if (\n cached === null &&\n (actorState === \"otp_pending\" ||\n actorState === \"otp_sending\" ||\n actorState === \"otp_verifying\")\n ) {\n return null;\n }\n if (cached !== null && actorState !== \"signed_out\") return cached;\n if (cached !== null && actorState === \"signed_out\") {\n yield* deps.actor\n .restoreAuthSession(cached, depsRequestOptions(deps, options))\n .pipe(Effect.mapError(actorError));\n return cached;\n }\n\n // Drive the identity actor's session read.\n const invocation = depsRequestOptions(deps, options);\n yield* ask(deps.actor, { _tag: \"ReadSession\" }, invocation).pipe(\n Effect.catch((failure) =>\n actorState === \"authenticated\" && failure.code === \"NOT_AUTHENTICATED\"\n ? Effect.result(ask(deps.actor, { _tag: \"SignOut\" }, invocation)).pipe(\n Effect.andThen(Effect.fail(failure)),\n )\n : Effect.fail(failure),\n ),\n );\n const refreshed = deps.actor.authSession();\n if (refreshed !== null) return refreshed;\n\n // Cache miss: snapshot canonical identity state.\n const session = deps.actor.authSession();\n if (session !== null) return session;\n\n // Cache may hold a session while the actor is still signed out (browser reload).\n if (cached !== null) return cached;\n\n // No session known locally.\n return null;\n });\n\nexport const getSessionProgram: Effect.Effect<Session | null, CapxulError, CapxulDepsTag> =\n getSessionProgramWithOptions();\n\n/** Consumer input for {@link verifyOtpProgram}. Mirrors the public method arg. */\nexport interface VerifyOtpProgramInput {\n readonly email: string;\n readonly code: string;\n readonly signer?: ExternalSigner;\n}\n\n/**\n * verifyOtp as one Effect requiring only `CapxulDepsTag`. Per-request signals\n * and the bundle invocation timeout are forwarded to the identity actor.\n */\nexport function verifyOtpProgram(\n input: VerifyOtpProgramInput,\n options?: AuthProgramOptions,\n): Effect.Effect<Session, CapxulError, CapxulDepsTag> {\n return Effect.gen(function* () {\n const deps = yield* CapxulDepsTag;\n\n // 1. Validate code shape — 6 digits.\n if (!/^\\d{6}$/.test(input.code)) {\n return yield* Effect.fail(Errors.invalidInput(\"otp\", \"must be 6 digits\"));\n }\n\n // 2. Brand only when this snapshot can legally verify. Invalid states are\n // sent to the actor unchanged so its atomic transition owns WRONG_STATE\n // and the single P3 refusal record.\n const observed = deps.actor.snapshot();\n const phase = observed.phase;\n let email = input.email;\n if (\n observed.phase === \"otp_pending\" ||\n (observed.phase === \"faulted\" && observed.resume !== null)\n ) {\n try {\n email = toEmail(input.email);\n } catch (err) {\n return yield* Effect.fail(\n err instanceof CapxulError ? err : Errors.invalidInput(\"email\", \"invalid email\"),\n );\n }\n }\n\n // 3. Resume a recoverable failed verify before retrying.\n if (phase === \"faulted\") {\n const now = yield* deps.clock.now.pipe(\n Effect.mapError((cause) => Errors.providerError(\"clock\", \"now\", cause)),\n );\n yield* ask(deps.actor, { _tag: \"ResumeOtpEntry\", now }, depsRequestOptions(deps, options));\n }\n\n // 4. Drive VERIFY. The `signer` arg is retained for public parity but is\n // not forwarded into the VerifyOtp event.\n const now = yield* deps.clock.now.pipe(\n Effect.mapError((cause) => Errors.providerError(\"clock\", \"now\", cause)),\n );\n yield* ask(\n deps.actor,\n { _tag: \"VerifyOtp\", email, otp: input.code, now },\n depsRequestOptions(deps, options),\n { method: \"verifyOtp\", validStates: [\"otp_pending\"] },\n );\n const session = deps.actor.authSession();\n if (session === null) return yield* Effect.fail(Errors.notAuthenticated());\n\n // 5. Persist the verified session.\n yield* deps.authCache\n .setSession(session)\n .pipe(Effect.mapError((e) => Errors.providerError(\"auth-cache\", \"setSession\", e)));\n\n return session;\n });\n}\n\n/** The `signIn` Result payload (mirrors the `AuthMethods[\"signIn\"]` value). */\nexport interface SignInSuccess {\n readonly sessionId: string;\n readonly expiresAt: number;\n}\n\n/**\n * Deps-only request-option builder. The bundle timeout and per-request signal\n * are forwarded into identity-actor invocation controls when present.\n */\nfunction depsRequestOptions(deps: CapxulDeps, options?: AuthProgramOptions): InvocationControls {\n return {\n ...(deps.invokeTimeoutMs === undefined || options?.timeoutMs !== undefined\n ? {}\n : { timeoutMs: deps.invokeTimeoutMs }),\n ...options,\n };\n}\n\n/**\n * Clear the local auth cache (session then JWT), mapping each failure into a\n * typed `CapxulError`. `clearSession` runs first and short-circuits the JWT\n * clear on failure.\n */\nfunction clearAuthCacheEffect(authCache: AuthCachePort): Effect.Effect<void, CapxulError> {\n return authCache.clearSession.pipe(\n Effect.mapError((cause) => Errors.providerError(\"auth-cache\", \"clearSession\", cause)),\n Effect.andThen(\n authCache.clearJwt.pipe(\n Effect.mapError((cause) => Errors.providerError(\"auth-cache\", \"clearJwt\", cause)),\n ),\n ),\n );\n}\n\nfunction cryptoRandomId(): string {\n // Best-effort 16-char hex id. Used only as a tracking value for the\n // `signIn` Result; not auth-critical.\n const bytes = new Uint8Array(8);\n if (\n typeof globalThis.crypto !== \"undefined\" &&\n typeof globalThis.crypto.getRandomValues === \"function\"\n ) {\n globalThis.crypto.getRandomValues(bytes);\n } else {\n for (let i = 0; i < bytes.length; i++) {\n bytes[i] = Math.floor(Math.random() * 256);\n }\n }\n return Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\")).join(\"\");\n}\n\n/**\n * `canSendOtp` as a single Effect requiring ONLY `CapxulDepsTag`. Faithful\n * transcription of the former public method body minus the leading\n * `signal.aborted` pre-check (stays in the thin method wrapper). The auth-port\n * failure mapping mirrors the former `runAuthClientEffect`: a `CapxulError`\n * cause passes through verbatim, anything else becomes a typed `providerError`.\n */\ntype AuthProgramOptions = InvocationControls;\n\nexport const canSendOtpProgram = (\n input: {\n readonly email: string;\n },\n options?: AuthProgramOptions,\n): Effect.Effect<CanSendOtpStatus, CapxulError, CapxulDepsTag> =>\n Effect.gen(function* () {\n const deps = yield* CapxulDepsTag;\n const email = yield* Effect.try({\n try: () => toEmail(input.email),\n catch: (err) =>\n err instanceof CapxulError ? err : Errors.invalidInput(\"email\", \"invalid email\"),\n });\n return yield* deps.authClient\n .canSendOtp({ email }, options?.signal === undefined ? undefined : { signal: options.signal })\n .pipe(\n Effect.mapError((failure) =>\n failure.cause instanceof CapxulError\n ? failure.cause\n : Errors.providerError(\"auth-client\", \"canSendOtp\", failure.cause),\n ),\n );\n });\n\n/**\n * `signIn` as one Effect requiring only `CapxulDepsTag`: brand the email,\n * enforce the public precondition, Reset a recoverable fault, drive\n * `RequestOtp`, then mint the tracking Result from the clock.\n */\nexport const signInProgram = (\n input: {\n readonly email: string;\n },\n options?: AuthProgramOptions,\n): Effect.Effect<SignInSuccess, CapxulError, CapxulDepsTag> =>\n Effect.gen(function* () {\n const deps = yield* CapxulDepsTag;\n\n // 1. Brand at entry — consumer passes raw string.\n const email = yield* Effect.try({\n try: () => toEmail(input.email),\n catch: (err) =>\n err instanceof CapxulError ? err : Errors.invalidInput(\"email\", \"invalid email\"),\n });\n\n // 2. A fault auto-resets first; every other state decision belongs to the\n // actor so a refusal and its P3 record are one atomic operation.\n const phase = deps.actor.snapshot().phase;\n if (phase === \"faulted\") {\n yield* ask(deps.actor, { _tag: \"Reset\" }, depsRequestOptions(deps, options));\n }\n yield* ask(deps.actor, { _tag: \"RequestOtp\", email }, depsRequestOptions(deps, options), {\n method: \"signIn\",\n validStates: [\"signed_out\", \"otp_pending\", \"faulted\"],\n });\n const now = yield* deps.clock.now.pipe(\n Effect.mapError((cause) => Errors.providerError(\"clock\", \"now\", cause)),\n );\n return {\n sessionId: cryptoRandomId(),\n expiresAt: now + (deps.otpTtlMs ?? 300_000),\n };\n });\n\n/**\n * `signOut` as a single Effect requiring ONLY `CapxulDepsTag`. Faithful\n * transcription of the former public method body: WRONG_STATE from signed_out,\n * reset-and-clear from faulted, otherwise drive `SignOut` and clear the local\n * cache REGARDLESS of the wire outcome. `Effect.result` captures the `SignOut`\n * result without short-circuiting so the cache clear always runs — a cache\n * clear failure then takes precedence over the wire error, matching the former\n * `if (!cacheClear.ok) return cacheClear; return result`.\n */\nexport const signOutProgramWithOptions = (\n options?: AuthProgramOptions,\n): Effect.Effect<void, CapxulError, CapxulDepsTag> =>\n Effect.gen(function* () {\n const deps = yield* CapxulDepsTag;\n let phase = deps.actor.snapshot().phase;\n\n if (phase === \"signed_out\") {\n const cached = yield* deps.authCache.getSession.pipe(\n Effect.mapError((e) => Errors.providerError(\"auth-cache\", \"getSession\", e)),\n );\n if (cached !== null) {\n yield* deps.actor\n .restoreAuthSession(cached, depsRequestOptions(deps, options))\n .pipe(Effect.mapError(actorError));\n phase = deps.actor.snapshot().phase;\n }\n }\n\n if (phase === \"faulted\") {\n yield* ask(deps.actor, { _tag: \"Reset\" }, depsRequestOptions(deps, options));\n yield* clearAuthCacheEffect(deps.authCache);\n return;\n }\n\n const signOutResult = yield* ask(\n deps.actor,\n { _tag: \"SignOut\" },\n depsRequestOptions(deps, options),\n {\n method: \"signOut\",\n validStates: [\"authenticated\", \"otp_pending\", \"otp_verifying\", \"otp_sending\", \"faulted\"],\n },\n ).pipe(Effect.result);\n if (Result.isFailure(signOutResult) && signOutResult.failure.code === \"WRONG_STATE\") {\n return yield* Effect.fail(signOutResult.failure);\n }\n // Clear local cache regardless of server outcome.\n yield* clearAuthCacheEffect(deps.authCache);\n if (Result.isFailure(signOutResult)) {\n return yield* Effect.fail(signOutResult.failure);\n }\n });\n\nexport const signOutProgram: Effect.Effect<void, CapxulError, CapxulDepsTag> =\n signOutProgramWithOptions();\n","// makeAuthMethods — TA12 imperative methods. Returns the `auth` bundle of\n// the CapxulClient surface.\n//\n// All five operations now collapse onto the hourglass `CapxulDeps` seam\n// (PRD #209): each method is a thin wrapper that runs its program\n// (`canSendOtpProgram` / `signInProgram` / `verifyOtpProgram` /\n// `signOutProgram` / `getSessionProgram`) through the shared `toCapxulResult`\n// bridge. The wrapper keeps the leading `signal.aborted` pre-check and threads\n// non-aborted signals into the programs; validate → precondition → actor-drive\n// → cache logic lives in the programs, which require ONLY `CapxulDepsTag`.\n\nimport { CapxulError, Errors } from \"@capxul/config\";\n\nimport type { IdentityActor } from \"../flows/identity\";\nimport type { ExternalSigner } from \"../flows/types\";\nimport type { AuthClientPort, CanSendOtpStatus } from \"../ports/auth-client\";\nimport type { AuthCachePort } from \"../ports/auth-cache\";\nimport type { ClockPort } from \"../ports/clock\";\nimport type { TelemetryPort } from \"../ports/telemetry\";\nimport type { InvocationControls } from \"../domain/machine/shell\";\n\nimport {\n canSendOtpProgram,\n capxulDepsLayer,\n getSessionProgramWithOptions,\n signInProgram,\n signOutProgramWithOptions,\n verifyOtpProgram,\n} from \"./capxul-deps\";\nimport { toCapxulResult } from \"./to-capxul-result\";\nimport type { CapxulResult, Session } from \"./types\";\n\nexport type AuthMethodOptions = InvocationControls;\nexport type SignInOptions = AuthMethodOptions;\n\nexport interface AuthMethods {\n canSendOtp(\n input: { readonly email: string },\n options?: AuthMethodOptions,\n ): Promise<CapxulResult<CanSendOtpStatus>>;\n signIn(\n input: { readonly email: string },\n options?: SignInOptions,\n ): Promise<CapxulResult<{ readonly sessionId: string; readonly expiresAt: number }>>;\n verifyOtp(\n input: {\n readonly email: string;\n readonly code: string;\n readonly signer?: ExternalSigner;\n },\n options?: AuthMethodOptions,\n ): Promise<CapxulResult<Session>>;\n signOut(options?: AuthMethodOptions): Promise<CapxulResult<void>>;\n getSession(options?: AuthMethodOptions): Promise<CapxulResult<Session | null>>;\n}\n\nexport interface MakeAuthMethodsDeps {\n readonly actor: IdentityActor;\n readonly authClient: AuthClientPort;\n readonly authCache: AuthCachePort;\n readonly clock: ClockPort;\n readonly telemetry?: TelemetryPort;\n readonly otpTtlMs?: number;\n readonly invokeTimeoutMs?: number;\n readonly afterVerifyOtp?: () => Promise<void>;\n}\n\nexport function makeAuthMethods(deps: MakeAuthMethodsDeps): AuthMethods {\n return {\n async canSendOtp(input, options) {\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"canSendOtp\" }) };\n }\n // Hourglass seam (PRD #209): brand + auth-port call now live in\n // `canSendOtpProgram`, run through the shared bridge.\n return toCapxulResult(canSendOtpProgram(input, options), capxulDepsLayer(deps));\n },\n\n async signIn(input, options) {\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"signIn\" }) };\n }\n // Hourglass seam (PRD #209): brand → precondition → RequestOtp → clock\n // logic now lives in `signInProgram`, run through the shared bridge.\n return toCapxulResult(signInProgram(input, options), capxulDepsLayer(deps));\n },\n\n async verifyOtp(input, options) {\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"verifyOtp\" }) };\n }\n // Hourglass seam (PRD #209, slice 3): the validate → precondition →\n // actor-drive → cache-write logic now lives in `verifyOtpProgram`, run\n // through the shared bridge.\n const result = await toCapxulResult(verifyOtpProgram(input, options), capxulDepsLayer(deps));\n if (!result.ok) {\n return result;\n }\n const afterVerifyOtp = deps.afterVerifyOtp;\n if (afterVerifyOtp === undefined) {\n return result;\n }\n try {\n await afterVerifyOtp();\n } catch (cause) {\n if (cause instanceof CapxulError) {\n return { ok: false, error: cause };\n }\n return {\n ok: false,\n error: Errors.providerError(\"sdk\", \"afterVerifyOtp\", cause),\n };\n }\n return result;\n },\n\n async signOut(options) {\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"signOut\" }) };\n }\n // Hourglass seam (PRD #209): the WRONG_STATE guard, error-reset, SignOut\n // drive, and cache-clear-regardless logic now live in `signOutProgram`,\n // run through the shared bridge.\n return toCapxulResult(signOutProgramWithOptions(options), capxulDepsLayer(deps));\n },\n\n async getSession(options) {\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"getSession\" }) };\n }\n // Hourglass seam (PRD #209): the cache-first → actor-drive → snapshot\n // logic now lives in `getSessionProgram`, run through the shared bridge.\n return toCapxulResult(getSessionProgramWithOptions(options), capxulDepsLayer(deps));\n },\n };\n}\n","// Smart-account substrate — the `SmartAccountMethods` operations expressed as\n// Effect programs that resolve a single Context tag (PRD #209 hourglass\n// collapse, slice 5).\n//\n// Mirrors the slice-2 `capxul-deps.ts` shape:\n//\n// 1. `SmartAccountDeps` — the dependency bundle one Context tag\n// carries. Verbatim mirror of\n// `MakeSmartAccountMethodsDeps`\n// (`smart-account.ts`).\n// 2. `SmartAccountDepsTag` — the single tag the public methods\n// resolve via `toCapxulResult`.\n// 3. `smartAccountDepsLayer` — wraps a bundle as\n// `Layer<SmartAccountDepsTag>`.\n// 4. `loadSmartAccountProgram` — `smartAccount.loadCurrent` as a single\n// `Effect<SmartAccount | null,\n// CapxulError, SmartAccountDepsTag>`.\n// 5. `provisionSmartAccountProgram`— `smartAccount.provision` as an\n// input-parameterised program returning\n// `Effect<SmartAccount, CapxulError,\n// SmartAccountDepsTag>`.\n//\n// NOT re-exported from the `@capxul/sdk` main barrel — this module is\n// workspace-internal (imported by sibling `src/client/*` modules only) and\n// has NO published export subpath. #1145: the `@capxul/sdk/react-substrate`\n// subpath these comments used to cite never existed.\n\nimport { Context, Effect, Layer } from \"effect\";\n\nimport { CapxulError, Errors } from \"@capxul/config\";\nimport type { AuthUserId, ChainId } from \"@capxul/types\";\n\nimport type { IdentityActor } from \"../flows/identity\";\nimport type { SmartAccount } from \"@capxul/types\";\nimport type { SmartAccountPort } from \"../ports/smart-account\";\nimport type { TelemetryPort } from \"../ports/telemetry\";\nimport { emitProvisioningTelemetry } from \"./_shared/provisioning-telemetry\";\nimport { sessionFromActor } from \"./_shared/effect-actor-bridge\";\n\n/**\n * The dependency bundle a single `Context.Service` carries (PRD #209). Verbatim\n * mirror of `MakeSmartAccountMethodsDeps` — kept structurally identical so a\n * `MakeSmartAccountMethodsDeps` value is assignable wherever a\n * `SmartAccountDeps` is expected.\n */\nexport interface SmartAccountDeps {\n readonly actor: IdentityActor;\n readonly smartAccountPort: SmartAccountPort;\n readonly chainId: ChainId;\n readonly sessionAuthUserIdFallback?: AuthUserId | null;\n readonly telemetry?: TelemetryPort;\n}\n\n/** The single Context tag the `smartAccount.*` methods resolve. */\nexport class SmartAccountDepsTag extends Context.Service<SmartAccountDepsTag, SmartAccountDeps>()(\n \"@capxul/sdk/SmartAccountDeps\",\n) {}\n\n/** Wrap a bundle as the `Layer<SmartAccountDepsTag>` the React provider consumes. */\nexport function smartAccountDepsLayer(deps: SmartAccountDeps): Layer.Layer<SmartAccountDepsTag> {\n return Layer.succeed(SmartAccountDepsTag, deps);\n}\n\n/**\n * `smartAccount.loadCurrent` as a single Effect requiring ONLY\n * `SmartAccountDepsTag`. Faithful transcription of the current public method\n * body (`smart-account.ts`): snapshot the actor for the session authUserId,\n * append the optional sentinel fallback, and return the first non-null\n * `SmartAccountPort` row. The leading `signal.aborted` pre-check stays in the\n * thin method wrapper. Port failures narrow to their `publicError`.\n */\nexport const loadSmartAccountProgram: Effect.Effect<\n SmartAccount | null,\n CapxulError,\n SmartAccountDepsTag\n> = Effect.gen(function* () {\n const deps = yield* SmartAccountDepsTag;\n const session = sessionFromActor(deps.actor);\n const fallback = deps.sessionAuthUserIdFallback ?? null;\n const candidates: AuthUserId[] = [];\n if (session !== null) {\n candidates.push(session.authUserId);\n }\n if (fallback !== null) candidates.push(fallback);\n for (const candidate of candidates) {\n const row = yield* deps.smartAccountPort\n .loadByAuthUserId(candidate)\n .pipe(Effect.mapError((failure) => failure.publicError));\n if (row !== null) return row;\n }\n return null;\n});\n\n/**\n * `smartAccount.provision` as an input-parameterised program requiring ONLY\n * `SmartAccountDepsTag`. Faithful transcription of the current public method\n * body (`smart-account.ts`): precondition the actor on `authenticated`, brand\n * the external signer at entry, then drive the `SmartAccountPort.provision`\n * port. The leading `signal.aborted` pre-check stays in the thin method\n * wrapper (provision currently takes no signal, so there is none).\n */\nexport function provisionSmartAccountProgram(): Effect.Effect<\n SmartAccount,\n CapxulError,\n SmartAccountDepsTag\n> {\n return Effect.gen(function* () {\n const deps = yield* SmartAccountDepsTag;\n const phase = deps.actor.snapshot().phase;\n if (phase !== \"authenticated\") {\n return yield* Effect.fail(\n Errors.wrongState({\n method: \"smartAccount.provision\",\n currentState: phase,\n validStates: [\"authenticated\"],\n }),\n );\n }\n const session = sessionFromActor(deps.actor);\n if (session === null) {\n return yield* Effect.fail(Errors.notAuthenticated());\n }\n const provisioned = yield* deps.smartAccountPort\n .provision({ authUserId: session.authUserId, chainId: deps.chainId })\n .pipe(Effect.mapError((failure) => failure.publicError));\n yield* Effect.promise(() => emitProvisioningTelemetry(deps.telemetry, provisioned));\n return provisioned;\n });\n}\n","// makeSmartAccountMethods — TA12 imperative bundle. Read paths snapshot\n// from SmartAccountPort; provision drives the identity actor's account slot\n// via the actor's chainId closure (TA8 — chainId never crosses the consumer\n// boundary).\n//\n// Hourglass seam (PRD #209, slice 5): the snapshot/precondition/port logic now\n// lives in `loadSmartAccountProgram` + `provisionSmartAccountProgram`\n// (resolving `SmartAccountDepsTag`), run through the shared `toCapxulResult`\n// bridge. The `signal.aborted` pre-check stays here in the thin method wrapper.\n\nimport { Errors } from \"@capxul/config\";\nimport type { AuthUserId, ChainId } from \"@capxul/types\";\n\nimport type { IdentityActor } from \"../flows/identity\";\nimport type { ExternalSigner } from \"../flows/types\";\nimport type { SmartAccountPort } from \"../ports/smart-account\";\nimport type { TelemetryPort } from \"../ports/telemetry\";\n\nimport {\n loadSmartAccountProgram,\n provisionSmartAccountProgram,\n smartAccountDepsLayer,\n} from \"./smart-account-deps\";\nimport { toCapxulResult } from \"./to-capxul-result\";\nimport type { CapxulResult, SmartAccount } from \"./types\";\n\nexport interface SmartAccountMethods {\n loadCurrent(options?: {\n readonly signal?: AbortSignal;\n }): Promise<CapxulResult<SmartAccount | null>>;\n provision(input?: {\n readonly externalSigner?: ExternalSigner;\n }): Promise<CapxulResult<SmartAccount>>;\n}\n\nexport interface MakeSmartAccountMethodsDeps {\n readonly actor: IdentityActor;\n readonly smartAccountPort: SmartAccountPort;\n readonly chainId: ChainId;\n readonly sessionAuthUserIdFallback?: AuthUserId | null;\n readonly telemetry?: TelemetryPort;\n}\n\nexport function makeSmartAccountMethods(deps: MakeSmartAccountMethodsDeps): SmartAccountMethods {\n return {\n async loadCurrent(options) {\n if (options?.signal?.aborted) {\n return {\n ok: false,\n error: Errors.cancelled({ operation: \"smartAccount.loadCurrent\" }),\n };\n }\n return toCapxulResult(loadSmartAccountProgram, smartAccountDepsLayer(deps));\n },\n\n async provision(_input) {\n return toCapxulResult(provisionSmartAccountProgram(), smartAccountDepsLayer(deps));\n },\n };\n}\n","// The identity backend contract (A2-Q3A · blueprint §2 moves ledger).\n//\n// `usernameAvailable` is the one identity function the SURFACE calls directly;\n// the rest of `identity/*` is reached through `adapters/identity`, which builds\n// its references from the same `CAPXUL_FUNCTIONS` registry.\n\nimport { makeFunctionReference, type FunctionReference } from \"convex/server\";\n\nimport { CAPXUL_FUNCTIONS } from \"@capxul/wire\";\n\nexport const usernameAvailableQuery: FunctionReference<\n \"query\",\n \"public\",\n { readonly username: string },\n { readonly available: boolean; readonly normalized: string }\n> = makeFunctionReference<\n \"query\",\n { readonly username: string },\n { readonly available: boolean; readonly normalized: string }\n>(CAPXUL_FUNCTIONS[\"identity/queries\"].usernameAvailable);\n","// Identity substrate — the `IdentityMethods` operations expressed as Effect\n// programs that resolve a single Context tag (PRD #209 hourglass collapse,\n// slice 5).\n//\n// Mirrors the slice-2 `capxul-deps.ts` shape for the auth surface:\n//\n// 1. `IdentityDeps` — the dependency bundle one Context tag\n// carries. Verbatim mirror of\n// `MakeIdentityMethodsDeps`\n// (`identity.ts`) so a method-deps value is\n// assignable wherever an `IdentityDeps` is\n// expected (and vice versa).\n// 2. `IdentityDepsTag` — the single tag both the public method (via\n// `toCapxulResult`) and the\n// profile resolution in reactive consumers.\n// 3. `identityDepsLayer` — wraps a bundle as `Layer<IdentityDepsTag>`.\n// 4. `loadIdentityProgram` — `identity.loadCurrent` as a single\n// `Effect<Profile | null, CapxulError,\n// IdentityDepsTag>`.\n//\n// NOT re-exported from the `@capxul/sdk` main barrel — this module is\n// workspace-internal (imported by sibling `src/client/*` modules only) and\n// has NO published export subpath. #1145: the `@capxul/sdk/react-substrate`\n// subpath these comments used to cite never existed.\n\nimport { Context, Effect, Layer } from \"effect\";\n\nimport { CapxulError, Errors } from \"@capxul/config\";\nimport type { Profile } from \"@capxul/types\";\n\nimport type { IdentityActor } from \"../flows/identity\";\nimport { identityErrorFromCapxul, type IdentityPort } from \"../ports/identity\";\nimport { publicIdentityFailure, sessionFromActor } from \"./_shared/effect-actor-bridge\";\n\n/**\n * The dependency bundle a single `Context.Service` carries (PRD #209). Verbatim\n * mirror of `MakeIdentityMethodsDeps` — kept structurally identical so a\n * `MakeIdentityMethodsDeps` value is assignable wherever an `IdentityDeps` is\n * expected.\n */\nexport interface IdentityDeps {\n readonly identityPort: IdentityPort;\n readonly actor?: IdentityActor;\n}\n\n/** The single Context tag the profile atom + `identity.loadCurrent` resolve. */\nexport class IdentityDepsTag extends Context.Service<IdentityDepsTag, IdentityDeps>()(\n \"@capxul/sdk/IdentityDeps\",\n) {}\n\n/** Wrap a bundle as the `Layer<IdentityDepsTag>` the React provider consumes. */\nexport function identityDepsLayer(deps: IdentityDeps): Layer.Layer<IdentityDepsTag> {\n return Layer.succeed(IdentityDepsTag, deps);\n}\n\n/**\n * `identity.loadCurrent` as a single Effect requiring ONLY `IdentityDepsTag`.\n * Faithful transcription of the current public method body (`identity.ts`):\n * the leading `signal.aborted` pre-check stays in the thin method wrapper;\n * the program snapshots the actor session, then narrows the `IdentityPort`\n * failure to its `publicError`. Defects/sync-throws surface as `UNKNOWN`\n * through `toCapxulResult`'s `catchAllDefect` (and the atom's runtime), which\n * replaces the old outer `try/catch`.\n */\nexport const loadIdentityProgram: Effect.Effect<Profile | null, CapxulError, IdentityDepsTag> =\n Effect.gen(function* () {\n const deps = yield* IdentityDepsTag;\n\n if (deps.actor === undefined) {\n return yield* Effect.fail(Errors.notAuthenticated());\n }\n const state = deps.actor.snapshot();\n if (state.phase === \"faulted\") {\n return yield* Effect.fail(publicIdentityFailure(state.failure));\n }\n const authUserId = sessionFromActor(deps.actor)?.authUserId;\n if (authUserId === undefined) {\n return null;\n }\n return yield* deps.identityPort.loadByAuthUserId(authUserId).pipe(\n Effect.catchDefect((cause) =>\n Effect.fail(\n identityErrorFromCapxul(\n \"loadByAuthUserId\",\n cause instanceof CapxulError ? cause : Errors.unknown(cause),\n cause,\n ),\n ),\n ),\n Effect.mapError((failure) => failure.publicError),\n );\n });\n","// makeIdentityMethods — TA12 imperative bundle. `loadCurrent` snapshots\n// from IdentityPort.\n//\n// Hourglass seam (PRD #209, slice 5): the snapshot-then-port logic now lives\n// in `loadIdentityProgram` (resolving `IdentityDepsTag`), run through the\n// shared `toCapxulResult` bridge. The `signal.aborted` pre-check stays here in\n// the thin method wrapper.\n\nimport { Errors } from \"@capxul/config\";\n\nimport type { IdentityActor } from \"../flows/identity\";\nimport { usernameAvailableQuery } from \"../contract/identity\";\nimport type { ConvexCallPort } from \"../ports/convex-call\";\nimport type { IdentityPort } from \"../ports/identity\";\n\nimport { runPortEffect } from \"./_shared/effect-actor-bridge\";\nimport { identityDepsLayer, loadIdentityProgram } from \"./identity-deps\";\nimport { toCapxulResult } from \"./to-capxul-result\";\nimport type { CapxulResult, Profile } from \"./types\";\n\nexport interface IdentityMethods {\n loadCurrent(options?: { readonly signal?: AbortSignal }): Promise<CapxulResult<Profile | null>>;\n /**\n * #1062: availability probe for the username the user is typing. Returns the\n * canonical stored form so the UI can echo it.\n */\n usernameAvailable(\n username: string,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<{ readonly available: boolean; readonly normalized: string }>>;\n}\n\nexport interface MakeIdentityMethodsDeps {\n readonly identityPort: IdentityPort;\n readonly actor?: IdentityActor;\n /** Substrate for `usernameAvailable`; omitted ⇒ the probe fails NOT_IMPLEMENTED. */\n readonly convexCall?: ConvexCallPort;\n}\n\nexport function makeIdentityMethods(deps: MakeIdentityMethodsDeps): IdentityMethods {\n const convexCall = deps.convexCall;\n return {\n async loadCurrent(options) {\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"identity.loadCurrent\" }) };\n }\n return toCapxulResult(loadIdentityProgram, identityDepsLayer(deps));\n },\n async usernameAvailable(\n username: string,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<{ readonly available: boolean; readonly normalized: string }>> {\n if (options?.signal?.aborted) {\n return {\n ok: false,\n error: Errors.cancelled({ operation: \"identity.usernameAvailable\" }),\n };\n }\n if (convexCall === undefined) {\n return { ok: false, error: Errors.notImplemented(\"identity\", \"usernameAvailable\") };\n }\n return runPortEffect(convexCall.query(usernameAvailableQuery, { username }));\n },\n };\n}\n","// Money-domain telemetry helpers for the SDK method bundles (M2).\n//\n// Mirrors `provisioning-telemetry.ts`: a thin, fire-and-forget bridge that\n// emits a catalogued `TelemetryEvent` through an optional `TelemetryPort`,\n// swallowing all failures (telemetry must never fail a money flow). The\n// producer split (which names the SDK emits vs which the backend emits) is\n// owned by `packages/observability/CONTEXT.md` and its producer tests.\n//\n// PII discipline (Aaron's locked decisions): sub-account NAMES never enter\n// telemetry. Props carry only branded ids (`sub_account_id`), WeiAmount\n// strings (never floats — `.claude/rules/numeric-parsing.md`), buckets, and\n// directions. Helpers here construct exactly those shapes.\n\nimport { Effect } from \"effect\";\n\nimport type { Money, SubAccountId } from \"@capxul/types\";\n\nimport { toWei } from \"../../domain/money/to-wei\";\nimport type { TelemetryEvent, TelemetryPort } from \"../../ports/telemetry\";\n\n/**\n * Lower a consumer `Money` into a non-negative integer WeiAmount string for\n * telemetry props. Reuses the SDK boundary `toWei` (viem `parseUnits`, string\n * math only — never a float multiply per `.claude/rules/numeric-parsing.md`).\n */\nfunction moneyToWeiAmount(money: Money): string {\n return toWei(money);\n}\n\n/** \"out\" = sub → main, \"add\" = main → sub, \"between\" = sub → sub. */\ntype TransferDirection = \"add\" | \"out\" | \"between\";\n\nfunction transferDirection(from: string, to: string): TransferDirection {\n if (from === \"main\") return \"add\";\n if (to === \"main\") return \"out\";\n return \"between\";\n}\n\nexport type SubAccountOp = \"create\" | \"rename\" | \"delete\";\n\n/** Fire-and-forget emit through an optional port; never throws. */\nasync function emitMoneyTelemetry(\n telemetry: TelemetryPort | undefined,\n event: TelemetryEvent,\n): Promise<void> {\n if (telemetry === undefined) return;\n await Effect.runPromise(\n telemetry.emit(event).pipe(\n Effect.catch((cause) =>\n Effect.sync(() => reportMoneyTelemetryFailure(\"error\", event.name, cause)),\n ),\n Effect.catchDefect((cause) =>\n Effect.sync(() => reportMoneyTelemetryFailure(\"defect\", event.name, cause)),\n ),\n ),\n );\n}\n\nexport function emitFaucetRequested(\n telemetry: TelemetryPort | undefined,\n input: { readonly amount: Money; readonly chainId: number },\n): Promise<void> {\n // Convert BEFORE the fire-and-forget emit, but guard it: a malformed amount\n // (parseUnits throw) must never escape into the money flow. Report + drop.\n let amount: string;\n try {\n amount = moneyToWeiAmount(input.amount);\n } catch (cause) {\n reportMoneyTelemetryFailure(\"defect\", \"faucet_requested\", cause);\n return Promise.resolve();\n }\n return emitMoneyTelemetry(telemetry, {\n name: \"faucet_requested\",\n props: { amount, chainId: input.chainId },\n });\n}\n\nexport function emitFaucetFailed(\n telemetry: TelemetryPort | undefined,\n reason: string,\n): Promise<void> {\n return emitMoneyTelemetry(telemetry, { name: \"faucet_failed\", props: { reason } });\n}\n\nexport function emitAccountBalanceFailed(\n telemetry: TelemetryPort | undefined,\n reason: string,\n): Promise<void> {\n return emitMoneyTelemetry(telemetry, { name: \"account_balance_failed\", props: { reason } });\n}\n\nexport function emitTransferRequested(\n telemetry: TelemetryPort | undefined,\n input: { readonly amount: Money; readonly from: string; readonly to: string },\n): Promise<void> {\n let amount: string;\n try {\n amount = moneyToWeiAmount(input.amount);\n } catch (cause) {\n reportMoneyTelemetryFailure(\"defect\", \"transfer_requested\", cause);\n return Promise.resolve();\n }\n return emitMoneyTelemetry(telemetry, {\n name: \"transfer_requested\",\n props: { amount, direction: transferDirection(input.from, input.to) },\n });\n}\n\nexport function emitTransferFailed(\n telemetry: TelemetryPort | undefined,\n reason: string,\n): Promise<void> {\n return emitMoneyTelemetry(telemetry, { name: \"transfer_failed\", props: { reason } });\n}\n\nexport function emitSubAccountCreated(\n telemetry: TelemetryPort | undefined,\n subAccountId: SubAccountId,\n): Promise<void> {\n return emitMoneyTelemetry(telemetry, {\n name: \"subaccount_created\",\n props: { sub_account_id: subAccountId },\n });\n}\n\nexport function emitSubAccountRenamed(\n telemetry: TelemetryPort | undefined,\n subAccountId: SubAccountId,\n): Promise<void> {\n return emitMoneyTelemetry(telemetry, {\n name: \"subaccount_renamed\",\n props: { sub_account_id: subAccountId },\n });\n}\n\nexport function emitSubAccountDeleted(\n telemetry: TelemetryPort | undefined,\n subAccountId: SubAccountId,\n): Promise<void> {\n return emitMoneyTelemetry(telemetry, {\n name: \"subaccount_deleted\",\n props: { sub_account_id: subAccountId },\n });\n}\n\nexport function emitSubAccountOpFailed(\n telemetry: TelemetryPort | undefined,\n op: SubAccountOp,\n reason: string,\n): Promise<void> {\n return emitMoneyTelemetry(telemetry, {\n name: \"subaccount_op_failed\",\n props: { op, reason },\n });\n}\n\nfunction reportMoneyTelemetryFailure(kind: \"error\" | \"defect\", name: string, cause: unknown): void {\n if (!isMoneyTelemetryDebugEnabled()) return;\n globalThis.console?.warn?.(\"[capxul] money telemetry dropped\", { kind, name, cause });\n}\n\nfunction isMoneyTelemetryDebugEnabled(): boolean {\n const processLike = globalThis as {\n readonly process?: { readonly env?: Record<string, string | undefined> };\n };\n return processLike.process?.env?.CAPXUL_DEBUG_TELEMETRY === \"1\";\n}\n","import { Context, Effect, Layer } from \"effect\";\n\nimport { CapxulError } from \"@capxul/config\";\nimport type { Account, ChainId, Money } from \"@capxul/types\";\n\nimport type { AccountReadPort } from \"../ports/account-read\";\nimport type { TelemetryPort } from \"../ports/telemetry\";\nimport {\n emitAccountBalanceFailed,\n emitFaucetFailed,\n emitFaucetRequested,\n} from \"./_shared/money-telemetry\";\n\nexport interface AccountsDeps {\n readonly accountReadPort: AccountReadPort;\n readonly chainId: ChainId;\n readonly telemetry?: TelemetryPort;\n}\n\nexport class AccountsDepsTag extends Context.Service<AccountsDepsTag, AccountsDeps>()(\n \"@capxul/sdk/AccountsDeps\",\n) {}\n\nexport function accountsDepsLayer(deps: AccountsDeps): Layer.Layer<AccountsDepsTag> {\n return Layer.succeed(AccountsDepsTag, deps);\n}\n\nexport const readAccountProgram: Effect.Effect<Account, CapxulError, AccountsDepsTag> = Effect.gen(\n function* () {\n const deps = yield* AccountsDepsTag;\n // The server-confirmed `account_balance_read` is emitted backend-side\n // (`account/actions:readBalance`) — the balance is a server fact. The SDK\n // owns only the client-side `account_balance_failed` on a rejected read.\n const account = yield* deps.accountReadPort.readBalance({ chainId: deps.chainId }).pipe(\n Effect.tapError((error) =>\n Effect.promise(() => emitAccountBalanceFailed(deps.telemetry, error.publicCode)),\n ),\n Effect.mapError((error) => error.publicError),\n );\n return account;\n },\n);\n\nexport function fundFromFaucetProgram(\n amount: Money,\n): Effect.Effect<{ readonly txHash: string }, CapxulError, AccountsDepsTag> {\n return Effect.gen(function* () {\n const deps = yield* AccountsDepsTag;\n // SDK producer for `faucet_requested` (before the backend mint). The\n // server-confirmed `faucet_confirmed` is emitted backend-side\n // (`account/actions:faucetMint`) after the mint receipt. Awaited (not\n // forked) on purpose: the SDK pins client-side telemetry causal ordering\n // (`faucet_requested` strictly before `faucet_failed`), asserted in\n // `money-telemetry-wiring.test.ts`, and mirrors the transfer flow's awaited\n // `emitTransferRequested`. \"Fire-and-forget\" here means the emit can never\n // THROW into the money flow (`emitMoneyTelemetry` swallows all failures),\n // not that it is detached.\n yield* Effect.promise(() =>\n emitFaucetRequested(deps.telemetry, { amount, chainId: deps.chainId }),\n );\n return yield* deps.accountReadPort.fundFromFaucet({ chainId: deps.chainId, amount }).pipe(\n Effect.tapError((error) =>\n Effect.promise(() => emitFaucetFailed(deps.telemetry, error.publicCode)),\n ),\n Effect.mapError((error) => error.publicError),\n );\n });\n}\n","import { Errors } from \"@capxul/config\";\nimport type { ChainId } from \"@capxul/types\";\n\nimport type { AccountReadPort } from \"../ports/account-read\";\nimport type { TelemetryPort } from \"../ports/telemetry\";\n\nimport { accountsDepsLayer, fundFromFaucetProgram, readAccountProgram } from \"./accounts-deps\";\nimport { toCapxulResult } from \"./to-capxul-result\";\nimport type { CapxulResult } from \"./types\";\nimport type { Account, Money } from \"@capxul/types\";\n\nexport interface AccountsMethods {\n read(options?: { readonly signal?: AbortSignal }): Promise<CapxulResult<Account>>;\n}\n\n/**\n * Faucet surface (dev-only). Deliberately OFF the public `AccountsMethods`;\n * reachable only via `client._internal.accounts` (production-surface-policy.md).\n * The reference CLI uses it behind a test-env gate — consumers never see `fund`.\n */\nexport interface AccountsFaucetMethods {\n fund(\n amount: Money,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<{ readonly txHash: string }>>;\n}\n\nexport type AccountsBundle = AccountsMethods & AccountsFaucetMethods;\n\nexport interface MakeAccountsMethodsDeps {\n readonly accountReadPort: AccountReadPort;\n readonly chainId: ChainId;\n readonly telemetry?: TelemetryPort;\n}\n\n/**\n * Build the accounts bundle. `assembleCapxulClient` exposes the public `read`\n * half at `client.accounts` (typed `AccountsMethods`) and the dev-only `fund`\n * half at `client._internal.accounts` (typed `AccountsFaucetMethods`), so the\n * faucet never appears on the public client surface.\n */\nexport function makeAccountsMethods(deps: MakeAccountsMethodsDeps): AccountsBundle {\n return {\n async read(options) {\n if (options?.signal?.aborted) {\n return {\n ok: false,\n error: Errors.cancelled({ operation: \"accounts.read\" }),\n };\n }\n return toCapxulResult(readAccountProgram, accountsDepsLayer(deps));\n },\n async fund(amount, options) {\n if (options?.signal?.aborted) {\n return {\n ok: false,\n error: Errors.cancelled({ operation: \"accounts.fund\" }),\n };\n }\n return toCapxulResult(fundFromFaucetProgram(amount), accountsDepsLayer(deps));\n },\n };\n}\n","import { Errors } from \"@capxul/errors\";\n\nimport type { AccountsMethods } from \"./accounts\";\nimport type { MeMethods } from \"./money\";\nimport type { OrgsMethod } from \"./org\";\nimport type { SmartAccountMethods } from \"./smart-account\";\nimport type { CapxulResult } from \"./types\";\n\nexport interface CurrentUserContext {\n readonly user: {\n readonly id: string;\n readonly email: string;\n readonly displayName: string | null;\n readonly handle: string | null;\n readonly paymentLink: { readonly handle: string; readonly url: string } | null;\n };\n readonly personalAccount: { readonly id: string; readonly address: string | null } | null;\n readonly organizations: readonly {\n readonly id: string;\n readonly name: string;\n readonly handle: string;\n readonly role: string;\n readonly account: { readonly id: string; readonly address: string | null } | null;\n }[];\n}\n\nexport interface CurrentUserMethods {\n get(options?: { readonly signal?: AbortSignal }): Promise<CapxulResult<CurrentUserContext>>;\n}\n\nexport function makeCurrentUserMethods(deps: {\n readonly me: MeMethods;\n readonly accounts: AccountsMethods;\n readonly smartAccount: SmartAccountMethods;\n readonly orgs: OrgsMethod;\n}): CurrentUserMethods {\n return {\n async get(options) {\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"currentUser.get\" }) };\n }\n\n const user = await deps.me.get(options);\n if (!user.ok) return { ok: false, error: user.error };\n\n const [account, smartAccount, organizations] = await Promise.all([\n deps.accounts.read(options),\n deps.smartAccount.loadCurrent(options),\n deps.orgs(options),\n ]);\n\n if (!smartAccount.ok) return { ok: false, error: smartAccount.error };\n if (!organizations.ok) return { ok: false, error: organizations.error };\n // The personal account may not exist yet: in the post-OTP / pre-provision\n // window the backend read fails with SMART_ACCOUNT_MISSING for a user with\n // no Safe (#1030). The return contract already declares `personalAccount`\n // nullable, so tolerate ONLY that expected outcome here and surface it as\n // `null`. Every other account error still fails loudly — nulling e.g. an\n // auth or network failure would mask a real error as \"unprovisioned\".\n if (!account.ok && account.error.code !== \"SMART_ACCOUNT_MISSING\") {\n return { ok: false, error: account.error };\n }\n\n return {\n ok: true,\n value: {\n user: {\n id: user.value.authUserId,\n email: user.value.email,\n displayName: user.value.displayName,\n handle: null,\n paymentLink: null,\n },\n personalAccount: account.ok\n ? {\n id: account.value.id,\n address: smartAccount.value?.smartAccountAddress ?? null,\n }\n : null,\n organizations: organizations.value.map((organization) => ({\n id: organization.id,\n name: organization.name,\n handle: organization.handle,\n role: organization.role,\n account: {\n id: organization.treasury.id,\n address: organization.safeAddress,\n },\n })),\n },\n };\n },\n };\n}\n","// The financialOps backend contract (A2-Q3A · blueprint §2 moves ledger).\n//\n// Before the re-cut these 25 typed function references and the four hand-rolled\n// `Backend*` wire types lived inside `client/financial-ops.ts` — a 1,724-line\n// module that was, in fact, an undeclared Convex adapter sitting on the public\n// surface. They live here now, and every function PATH comes from\n// `@capxul/wire`'s `CAPXUL_FUNCTIONS` registry, which\n// `scripts/lint-wire-contract.mjs` proves against the real backend on\n// `check:fast`.\n//\n// Direction of the remaining coupling: the reference table is parameterised by\n// the public response types, which still live in `surface/money.ts`. That\n// import is TYPE-ONLY (no runtime cycle) and is temporary — L2 rebuilds the\n// ledger and moves those shapes into `@capxul/wire` proper, at which point\n// this module imports nothing from `surface/`.\n\nimport { makeFunctionReference, type FunctionReference } from \"convex/server\";\n\nimport { CAPXUL_FUNCTIONS } from \"@capxul/wire\";\nimport type {\n AttachablePaymentDocumentEnvelopeV1,\n LineItemV1,\n PaymentDocumentEnvelopeV1,\n WithdrawalDocumentEnvelopeV1,\n} from \"@capxul/wire\";\n\nimport type {\n DepositInstructions,\n DestinationPayload,\n MeProfile,\n Payee,\n Payment,\n PaymentCommitmentRef,\n PaymentDocumentRender,\n PaymentDocumentVerification,\n PaymentMoney,\n PaymentTiming,\n PaymentType,\n RecipientResolution,\n Ref,\n} from \"../surface/money\";\n\n/** A payer/payee scope as the BACKEND names it (the surface says personal/organization). */\nexport type BackendRef = Ref;\n\nexport type BackendActorReference =\n | { readonly kind: \"account\" }\n | { readonly kind: \"org\"; readonly orgId: string };\n\nexport type BackendDestinationKind = \"bank\" | \"mobile-money\" | \"wallet\";\n\nexport type BackendDestination = {\n readonly id: string;\n readonly counterpartyId: string;\n // #1063: null exactly when ownerScope === \"self\" (the actor's own payout\n // destination has no counterparty ref behind it).\n readonly ref: BackendRef | null;\n readonly kind: BackendDestinationKind;\n // Optional on the wire type so pre-#1063 recorded rows stay loadable;\n // absence maps to \"counterparty\".\n readonly ownerScope?: \"self\" | \"counterparty\";\n readonly label: string | null;\n readonly payload: DestinationPayload;\n readonly createdAt: number;\n readonly updatedAt: number;\n};\n\nexport type FinancialOpsFunctions = {\n readonly me: FunctionReference<\"query\", \"public\", Record<string, never>, MeProfile>;\n readonly depositInstructions: FunctionReference<\n \"query\",\n \"public\",\n Record<string, never>,\n DepositInstructions\n >;\n readonly resolveHandle: FunctionReference<\n \"query\",\n \"public\",\n { readonly handle: string },\n RecipientResolution\n >;\n readonly createPayee: FunctionReference<\n \"mutation\",\n \"public\",\n { readonly label: string; readonly recipient: string; readonly handle?: string },\n Payee\n >;\n readonly getPayee: FunctionReference<\n \"query\",\n \"public\",\n { readonly payeeId: string },\n Payee | null\n >;\n readonly resolvePayee: FunctionReference<\n \"query\",\n \"public\",\n { readonly recipient: string },\n RecipientResolution\n >;\n readonly addDestination: FunctionReference<\n \"mutation\",\n \"public\",\n {\n readonly actor?: BackendActorReference;\n readonly ref?: BackendRef;\n readonly self?: boolean;\n readonly kind: BackendDestinationKind;\n readonly label?: string;\n readonly payload: DestinationPayload;\n },\n BackendDestination\n >;\n readonly listDestinations: FunctionReference<\n \"query\",\n \"public\",\n {\n readonly actor?: BackendActorReference;\n readonly ref?: BackendRef;\n readonly self?: boolean;\n },\n readonly BackendDestination[]\n >;\n readonly removeDestination: FunctionReference<\n \"mutation\",\n \"public\",\n {\n readonly actor?: BackendActorReference;\n readonly destinationId: string;\n },\n { readonly id: string }\n >;\n readonly pay: FunctionReference<\n \"mutation\",\n \"public\",\n {\n readonly to: BackendRef;\n readonly amount: PaymentMoney;\n readonly paymentType?: PaymentType;\n readonly document?: AttachablePaymentDocumentEnvelopeV1;\n readonly timing?: PaymentTiming;\n readonly lineItems?: readonly LineItemV1[];\n },\n Payment\n >;\n readonly payout: FunctionReference<\n \"mutation\",\n \"public\",\n {\n readonly actor?:\n | { readonly kind: \"account\" }\n | { readonly kind: \"org\"; readonly orgId: string };\n readonly destinationId: string;\n readonly amount: PaymentMoney;\n },\n Payment\n >;\n readonly withdraw: FunctionReference<\n \"mutation\",\n \"public\",\n {\n readonly to: string;\n readonly amount: PaymentMoney;\n readonly document: WithdrawalDocumentEnvelopeV1;\n },\n Payment\n >;\n readonly markPaymentSettled: FunctionReference<\n \"action\",\n \"public\",\n { readonly paymentId: string; readonly userOpHash: string; readonly txHash: string },\n Payment\n >;\n readonly markWithdrawalSettled: FunctionReference<\n \"action\",\n \"public\",\n { readonly paymentId: string; readonly userOpHash: string; readonly txHash: string },\n Payment\n >;\n readonly recordOrgPayment: FunctionReference<\n \"action\",\n \"public\",\n {\n readonly orgId: string;\n readonly recipientLabel: string;\n readonly recipientKind?: \"handle\" | \"email\" | \"payee\" | \"capxulUserId\" | \"me\" | \"org\";\n readonly recipientRef?: string;\n readonly recipientPayeeId?: string;\n readonly recipientSafeAddress: string;\n readonly amount: PaymentMoney;\n readonly paymentType: PaymentType;\n readonly document?: PaymentDocumentEnvelopeV1;\n readonly orgSafeAddress: string;\n readonly occurrenceIndex: number;\n readonly userOpHash: string;\n readonly txHash: string;\n },\n Payment\n >;\n readonly markCommitmentCreated: FunctionReference<\n \"action\",\n \"public\",\n {\n readonly paymentId: string;\n readonly onchainCommitmentId: string;\n readonly userOpHash: string;\n readonly txHash: string;\n },\n Payment\n >;\n readonly claimCommitment: FunctionReference<\n \"action\",\n \"public\",\n { readonly paymentId: string; readonly userOpHash: string; readonly txHash: string },\n Payment\n >;\n readonly cancelCommitment: FunctionReference<\n \"action\",\n \"public\",\n {\n readonly paymentId: string;\n readonly userOpHash: string;\n readonly txHash: string;\n readonly document?: PaymentDocumentEnvelopeV1;\n },\n Payment\n >;\n readonly redirectCommitment: FunctionReference<\n \"action\",\n \"public\",\n {\n readonly paymentId: string;\n readonly to: BackendRef;\n readonly userOpHash: string;\n readonly txHash: string;\n readonly document?: PaymentDocumentEnvelopeV1;\n },\n Payment\n >;\n readonly listPayments: FunctionReference<\"query\", \"public\", Record<string, never>, Payment[]>;\n readonly getPayment: FunctionReference<\n \"query\",\n \"public\",\n { readonly paymentId: string },\n Payment | null\n >;\n readonly verifyPaymentDocument: FunctionReference<\n \"query\",\n \"public\",\n { readonly documentHash: string },\n PaymentDocumentVerification\n >;\n readonly renderStoredDocument: FunctionReference<\n \"query\",\n \"public\",\n { readonly documentHash: string },\n PaymentDocumentRender\n >;\n readonly getCommitmentRef: FunctionReference<\n \"query\",\n \"public\",\n { readonly paymentId: string },\n PaymentCommitmentRef | null\n >;\n};\n\nexport const financialOpsContract: FinancialOpsFunctions = {\n me: makeFunctionReference<\"query\", Record<string, never>, MeProfile>(\n CAPXUL_FUNCTIONS[\"financialOps/queries\"].me,\n ),\n depositInstructions: makeFunctionReference<\"query\", Record<string, never>, DepositInstructions>(\n CAPXUL_FUNCTIONS[\"financialOps/queries\"].depositInstructions,\n ),\n resolveHandle: makeFunctionReference<\"query\", { handle: string }, RecipientResolution>(\n CAPXUL_FUNCTIONS[\"financialOps/queries\"].resolveHandle,\n ),\n createPayee: makeFunctionReference<\n \"mutation\",\n { label: string; recipient: string; handle?: string },\n Payee\n >(CAPXUL_FUNCTIONS[\"financialOps/mutations\"].createPayee),\n getPayee: makeFunctionReference<\"query\", { payeeId: string }, Payee | null>(\n CAPXUL_FUNCTIONS[\"financialOps/queries\"].getPayee,\n ),\n resolvePayee: makeFunctionReference<\"query\", { recipient: string }, RecipientResolution>(\n CAPXUL_FUNCTIONS[\"financialOps/queries\"].resolvePayee,\n ),\n addDestination: makeFunctionReference<\n \"mutation\",\n {\n actor?: BackendActorReference;\n ref?: BackendRef;\n self?: boolean;\n kind: BackendDestinationKind;\n label?: string;\n payload: DestinationPayload;\n },\n BackendDestination\n >(CAPXUL_FUNCTIONS[\"financialOps/destinations\"].add),\n listDestinations: makeFunctionReference<\n \"query\",\n {\n actor?: BackendActorReference;\n ref?: BackendRef;\n self?: boolean;\n },\n readonly BackendDestination[]\n >(CAPXUL_FUNCTIONS[\"financialOps/destinations\"].list),\n removeDestination: makeFunctionReference<\n \"mutation\",\n {\n actor?: BackendActorReference;\n destinationId: string;\n },\n { readonly id: string }\n >(CAPXUL_FUNCTIONS[\"financialOps/destinations\"].remove),\n pay: makeFunctionReference<\n \"mutation\",\n {\n to: BackendRef;\n amount: PaymentMoney;\n paymentType?: PaymentType;\n document?: AttachablePaymentDocumentEnvelopeV1;\n timing?: PaymentTiming;\n lineItems?: readonly LineItemV1[];\n },\n Payment\n >(CAPXUL_FUNCTIONS[\"financialOps/mutations\"].pay),\n payout: makeFunctionReference<\n \"mutation\",\n {\n actor?: { readonly kind: \"account\" } | { readonly kind: \"org\"; readonly orgId: string };\n destinationId: string;\n amount: PaymentMoney;\n },\n Payment\n >(CAPXUL_FUNCTIONS[\"financialOps/destinations\"].payout),\n withdraw: makeFunctionReference<\n \"mutation\",\n { to: string; amount: PaymentMoney; document: WithdrawalDocumentEnvelopeV1 },\n Payment\n >(CAPXUL_FUNCTIONS[\"financialOps/mutations\"].withdraw),\n markPaymentSettled: makeFunctionReference<\n \"action\",\n { paymentId: string; userOpHash: string; txHash: string },\n Payment\n >(CAPXUL_FUNCTIONS[\"financialOps/actions\"].markPaymentSettled),\n markWithdrawalSettled: makeFunctionReference<\n \"action\",\n { paymentId: string; userOpHash: string; txHash: string },\n Payment\n >(CAPXUL_FUNCTIONS[\"financialOps/actions\"].markWithdrawalSettled),\n recordOrgPayment: makeFunctionReference<\n \"action\",\n {\n orgId: string;\n recipientLabel: string;\n recipientSafeAddress: string;\n amount: PaymentMoney;\n paymentType: PaymentType;\n document?: PaymentDocumentEnvelopeV1;\n orgSafeAddress: string;\n occurrenceIndex: number;\n userOpHash: string;\n txHash: string;\n },\n Payment\n >(CAPXUL_FUNCTIONS[\"financialOps/actions\"].recordOrgPayment),\n markCommitmentCreated: makeFunctionReference<\n \"action\",\n { paymentId: string; onchainCommitmentId: string; userOpHash: string; txHash: string },\n Payment\n >(CAPXUL_FUNCTIONS[\"financialOps/actions\"].markCommitmentCreated),\n claimCommitment: makeFunctionReference<\n \"action\",\n { paymentId: string; userOpHash: string; txHash: string },\n Payment\n >(CAPXUL_FUNCTIONS[\"financialOps/actions\"].claimCommitment),\n cancelCommitment: makeFunctionReference<\n \"action\",\n { paymentId: string; userOpHash: string; txHash: string; document?: PaymentDocumentEnvelopeV1 },\n Payment\n >(CAPXUL_FUNCTIONS[\"financialOps/actions\"].cancelCommitment),\n redirectCommitment: makeFunctionReference<\n \"action\",\n {\n paymentId: string;\n to: BackendRef;\n userOpHash: string;\n txHash: string;\n document?: PaymentDocumentEnvelopeV1;\n },\n Payment\n >(CAPXUL_FUNCTIONS[\"financialOps/actions\"].redirectCommitment),\n listPayments: makeFunctionReference<\"query\", Record<string, never>, Payment[]>(\n CAPXUL_FUNCTIONS[\"financialOps/queries\"].listPayments,\n ),\n getPayment: makeFunctionReference<\"query\", { paymentId: string }, Payment | null>(\n CAPXUL_FUNCTIONS[\"financialOps/queries\"].getPayment,\n ),\n verifyPaymentDocument: makeFunctionReference<\n \"query\",\n { documentHash: string },\n PaymentDocumentVerification\n >(CAPXUL_FUNCTIONS[\"financialOps/queries\"].verifyPaymentDocument),\n renderStoredDocument: makeFunctionReference<\n \"query\",\n { documentHash: string },\n PaymentDocumentRender\n >(CAPXUL_FUNCTIONS[\"financialOps/queries\"].renderStoredDocument),\n getCommitmentRef: makeFunctionReference<\n \"query\",\n { paymentId: string },\n PaymentCommitmentRef | null\n >(CAPXUL_FUNCTIONS[\"financialOps/queries\"].getCommitmentRef),\n};\n","import { Errors, type CapxulError } from \"@capxul/errors\";\nimport type {\n AttachablePaymentDocumentEnvelopeV1,\n LineItemV1,\n OnchainEvidence,\n PaymentDocumentEnvelopeV1,\n PaymentDocumentKind as WirePaymentDocumentKind,\n PaymentStatus as WirePaymentStatus,\n PaymentTypeName as WirePaymentTypeName,\n WithdrawalDocumentEnvelopeV1,\n} from \"@capxul/wire\";\n\nimport {\n financialOpsContract,\n type BackendActorReference,\n type BackendDestination,\n type BackendDestinationKind,\n type BackendRef,\n type FinancialOpsFunctions,\n} from \"../contract/financial-ops\";\nimport type { ConvexCallPort } from \"../ports/convex-call\";\nimport { runIfActive } from \"./to-capxul-result\";\nimport type { CapxulResult } from \"./types\";\n\nexport type ActorReference =\n | { readonly kind: \"personal\" }\n | { readonly kind: \"organization\"; readonly organizationId: string };\n\ntype ActorReferenceInput = ActorReference | BackendActorReference;\n\nexport function actorReferenceToBackend(\n actor: ActorReferenceInput | undefined,\n): BackendActorReference | undefined {\n if (actor === undefined) return undefined;\n switch (actor.kind) {\n case \"personal\":\n return { kind: \"account\" };\n case \"organization\":\n return { kind: \"org\", orgId: actor.organizationId };\n case \"account\":\n case \"org\":\n return actor;\n }\n}\n\nexport type TargetReference =\n | { readonly kind: \"handle\"; readonly handle: string }\n | { readonly kind: \"email\"; readonly email: string }\n | { readonly kind: \"organization\"; readonly handle: string }\n | { readonly kind: \"payee\"; readonly id: string }\n | { readonly kind: \"destination\"; readonly id: string };\n\nexport interface ResolvedTarget {\n readonly reference: TargetReference;\n readonly label: string;\n readonly kind: \"person\" | \"organization\" | \"payee\" | \"destination\";\n readonly capabilities: {\n readonly canPay: boolean;\n readonly canRequest: boolean;\n readonly canPayout: boolean;\n };\n}\n\nexport interface TargetsMethods {\n resolve(\n reference: TargetReference,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<ResolvedTarget>>;\n}\n\nexport type RecipientResolutionKind = \"email\" | \"org\" | \"payee\";\n\nexport type Ref =\n | { readonly kind: \"handle\"; readonly handle: string }\n | { readonly kind: \"email\"; readonly email: string }\n | { readonly kind: \"orgHandle\"; readonly orgHandle: string }\n | { readonly kind: \"capxulUserId\"; readonly capxulUserId: string }\n | { readonly kind: \"payeeId\"; readonly payeeId: string };\n\nexport interface MeProfile {\n readonly authUserId: string;\n readonly email: string;\n readonly displayName: string | null;\n // D2 (#564) + SDK restart #646/#644: a profile names WHO you are, not WHERE\n // money settles. Custody substrate stays off the profile; the deposit TARGET\n // data lives only on `DepositInstructions`.\n}\n\nexport interface DepositInstructions {\n readonly accountKind: \"personalSafe\" | \"orgTreasury\";\n readonly chainId: number;\n readonly network: \"base-sepolia\";\n readonly currency: \"USD\";\n readonly address: string;\n readonly label: string;\n}\n\nexport interface RecipientResolution {\n readonly kind: RecipientResolutionKind;\n readonly recipient: string;\n readonly label: string;\n readonly safeAddress: string;\n // Recipient identity is chain-agnostic (D1 · #563): a resolution names WHO is\n // paid, not WHERE it settles. The chain is the SettlementPort's concern,\n // supplied at settlement — so no `chainId` here.\n readonly payeeId?: string;\n readonly orgId?: string;\n readonly handle?: string;\n readonly email?: string;\n}\n\nexport interface Payee {\n readonly payeeId: string;\n readonly label: string;\n readonly recipientRef: string;\n readonly handle: string | null;\n readonly destinationKind: \"email\" | \"org\" | \"payeeHandle\";\n readonly safeAddress: string;\n readonly createdAt: number;\n readonly updatedAt: number;\n}\n\nexport interface MeMethods {\n get(options?: { readonly signal?: AbortSignal }): Promise<CapxulResult<MeProfile>>;\n depositInstructions(options?: {\n readonly signal?: AbortSignal;\n }): Promise<CapxulResult<DepositInstructions>>;\n}\n\nexport interface HandlesMethods {\n resolve(\n handle: string,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<RecipientResolution>>;\n}\n\nexport interface PayeesMethods {\n create(\n input: { readonly label: string; readonly recipient: string; readonly handle?: string },\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<Payee>>;\n get(\n payeeId: string,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<Payee | null>>;\n resolve(\n recipient: string,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<RecipientResolution>>;\n}\n\nexport interface PaymentMoney {\n readonly currency: string;\n readonly value: string;\n readonly decimals: number;\n}\n\n// A2-Q3A: these three public unions are re-exports of @capxul/wire's status\n// vocabularies, not copies of them. The literals used to be spelled out here,\n// in wire's Schema.Literal, and in the backend's own union — three lists that\n// could disagree without anything failing until a live decode.\nexport type PaymentStatus = WirePaymentStatus;\nexport type PaymentType = WirePaymentTypeName;\nexport type PaymentDocumentKind = WirePaymentDocumentKind;\n\nexport interface PaymentDocumentRef {\n readonly documentHash: string;\n readonly kind: PaymentDocumentKind;\n readonly title?: string;\n readonly uri?: string;\n readonly issuedAt?: number;\n}\n\nexport type PaymentTiming =\n | { readonly kind: \"instant\" }\n | { readonly kind: \"scheduled\"; readonly at: number }\n | {\n readonly kind: \"stream\";\n readonly startsAt: number;\n readonly endsAt: number;\n readonly cliffAt?: number;\n };\n\nexport interface Payment {\n readonly id: string;\n readonly status: PaymentStatus;\n readonly amount: PaymentMoney;\n readonly paymentType: PaymentType;\n readonly recipient: {\n readonly kind:\n | \"handle\"\n | \"email\"\n | \"payee\"\n | \"capxulUserId\"\n | \"me\"\n | \"org\"\n | \"external_address\";\n readonly label: string;\n readonly payeeId?: string;\n };\n readonly documents: readonly PaymentDocumentRef[];\n readonly timing: PaymentTiming;\n readonly released: PaymentMoney;\n readonly availableToClaim: PaymentMoney;\n readonly createdAt: number;\n readonly updatedAt: number;\n}\n\nexport interface PaymentsPayInput {\n readonly actor?: ActorReference;\n readonly to: TargetReference;\n readonly amount: PaymentMoney;\n /**\n * How the payment is classified on the ledger. When a `document` is\n * attached, the type derived from the document kind is AUTHORITATIVE\n * (memo → unspecified, invoice → invoice, payslip → payroll, receipt →\n * reimbursement) — an explicit conflicting value is rejected with\n * INVALID_INPUT (\"must match the attached document kind\"). With no\n * document the explicit value is honored, defaulting to \"unspecified\".\n */\n readonly paymentType?: PaymentType;\n /** Full EIP-712 document envelope; hashed + stored, committed on-chain. */\n readonly document?: AttachablePaymentDocumentEnvelopeV1;\n /**\n * Timing clause (D-SHAPE · #646). Omitted ⇒ `instant` (the G2 direct-send path).\n * A `scheduled`/`stream` clause turns the payment into a Commitment\n * (escrow-vest-claim) backed by `CapxulPayments.createCommitment`.\n */\n readonly timing?: PaymentTiming;\n /**\n * #592: itemized line items backing an Invoice `document`. The backend asserts\n * `hashLineItems(lineItems) === document.lineItemsHash` AND `Σ(quantity ×\n * unitMinor) === document.amount`, then persists the list for itemized render.\n */\n readonly lineItems?: readonly LineItemV1[];\n}\n\n/**\n * B3 withdraw / cash-out input. Stripe-shaped: `to` is the EXTERNAL 0x wallet\n * (the ONE place the SDK accepts a raw address — the pay lane never does),\n * `amount` is a Money, `document` is the REQUIRED kind:4 Withdrawal envelope\n * (carries the audit-visible destAddress). No chain / Safe / token / hash\n * custody substrate on the input. Returns a leak-safe `Payment` whose recipient\n * label is the redacted address — never the full 0x.\n */\nexport interface PaymentsWithdrawInput {\n readonly to: string;\n readonly amount: PaymentMoney;\n readonly document: WithdrawalDocumentEnvelopeV1;\n}\n\n/**\n * Payout via a saved destination. The caller selects the destination by opaque\n * id and never re-enters a raw wallet address on this path.\n */\nexport interface PaymentsPayoutInput {\n readonly actor?: ActorReference;\n readonly destinationId: string;\n readonly amount: PaymentMoney;\n}\n\nexport type DestinationKind = \"bank_account\" | \"mobile_money\" | \"external_account\";\n\nexport type DestinationRail =\n | { readonly kind: \"bank\"; readonly country: string; readonly currency: string }\n | {\n readonly kind: \"mobile_money\";\n readonly country: string;\n readonly currency: string;\n readonly provider: string;\n }\n | { readonly kind: \"chain\"; readonly network: string; readonly asset?: string };\n\nexport type DestinationPayload =\n | {\n readonly accountHolderName: string;\n readonly bankName: string;\n readonly country: string;\n readonly currency: string;\n readonly accountNumberLast4: string;\n }\n | {\n readonly provider: string;\n readonly country: string;\n readonly currency: string;\n readonly phoneNumberLast4: string;\n }\n | {\n // #1063: wallet-network allowlist — widened beyond base-sepolia.\n readonly network: \"base-sepolia\" | \"solana-devnet\" | \"starknet-sepolia\";\n readonly address: string;\n };\n\nexport interface Destination {\n readonly id: string;\n readonly counterpartyId: string;\n /** #1063: null exactly when `ownerScope === \"self\"`. */\n readonly ref: Ref | null;\n /** Derived from `ref`; null for self-owned rows. */\n readonly target: TargetReference | null;\n readonly kind: DestinationKind;\n readonly rail: DestinationRail;\n /**\n * #1063: \"self\" = the actor's own payout destination; \"counterparty\" = the\n * address-book shape. The mapping always sets it (wire absence ⇒ \"counterparty\").\n */\n readonly ownerScope: \"self\" | \"counterparty\";\n readonly label: string | null;\n readonly payload: DestinationPayload;\n readonly createdAt: number;\n readonly updatedAt: number;\n}\n\n/** #1063 ratified shape: your own payout destination is `target: { self: true }`. */\nexport type SelfTarget = { readonly self: true };\n\n/** #1063: exactly one of `target` (counterparty or `{ self: true }`) or `ref`. */\nexport interface DestinationAddInput {\n readonly actor?: ActorReference;\n readonly target?: TargetReference | SelfTarget;\n readonly ref?: Ref;\n readonly kind: DestinationKind;\n readonly label?: string;\n readonly payload: DestinationPayload;\n}\n\nexport interface DestinationListInput {\n readonly actor?: ActorReference;\n /** #1063: `{ self: true }` narrows to the actor's own payout destinations. */\n readonly target?: TargetReference | SelfTarget;\n readonly ref?: Ref;\n readonly kind?: DestinationKind;\n}\n\nexport interface DestinationRemoveInput {\n readonly actor?: ActorReference;\n readonly destinationId: string;\n}\n\nexport interface DestinationsMethods {\n add(\n input: DestinationAddInput,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<Destination>>;\n list(\n input: DestinationListInput,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<readonly Destination[]>>;\n remove(\n input: DestinationRemoveInput,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<{ readonly id: string }>>;\n}\n\nexport interface ActivityListParams {\n readonly actor?: ActorReference;\n readonly cursor?: string;\n readonly limit?: number;\n readonly paymentType?: PaymentType;\n readonly timing?: PaymentTiming[\"kind\"];\n}\n\nexport interface ActivityItem {\n readonly id: string;\n readonly actor: ActorReference;\n readonly kind: \"payment\" | \"payout\" | \"withdrawal\" | \"deposit\" | \"claim\";\n readonly direction: \"in\" | \"out\" | \"internal\";\n readonly status: PaymentStatus;\n readonly amount: PaymentMoney;\n readonly title: string;\n readonly subtitle: string | null;\n readonly target: TargetReference | null;\n readonly paymentId: string | null;\n readonly createdAt: number;\n readonly updatedAt: number;\n}\n\nexport interface ActivityPage {\n readonly items: readonly ActivityItem[];\n readonly nextCursor: string | null;\n}\n\nexport interface ActivityMethods {\n list(\n params?: ActivityListParams,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<ActivityPage>>;\n}\n\nexport interface OfframpQuoteInput {\n readonly actor?: ActorReference;\n readonly destinationId: string;\n readonly amount: PaymentMoney;\n}\n\nexport interface OfframpQuote {\n readonly id: string;\n readonly input: OfframpQuoteInput;\n readonly expiresAt: number;\n readonly receivedAmount: PaymentMoney;\n readonly fee: PaymentMoney;\n}\n\nexport interface OfframpStatus {\n readonly id: string;\n readonly status: \"pending\" | \"processing\" | \"completed\" | \"failed\" | \"cancelled\";\n readonly paymentId: string | null;\n readonly destinationId: string;\n readonly updatedAt: number;\n}\n\nexport interface OfframpMethods {\n quote(\n input: OfframpQuoteInput,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<OfframpQuote>>;\n status(\n offrampId: string,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<OfframpStatus>>;\n}\n\n// D2 (#564): on-chain settlement evidence (userOpHash + txHash) is the\n// `OnchainEvidence` brand — internal-channel only, never the public surface.\nexport interface PaymentSettlementInput {\n readonly paymentId: string;\n readonly evidence: OnchainEvidence;\n}\n\n/**\n * Host-execution callback recording the on-chain escrow of a commitment\n * (G3 · #546): `createCommitment` returned `onchainCommitmentId`, escrowing\n * the total. `onchainCommitmentId` + the userOp/tx hashes are internal evidence,\n * never on the wire (internal channel only).\n */\nexport interface CommitmentCreatedInput {\n readonly paymentId: string;\n readonly onchainCommitmentId: string;\n readonly evidence: OnchainEvidence;\n}\n\n/** Host-execution callback recording a recipient-side `claim` (G3 · #546). */\nexport interface CommitmentClaimInput {\n readonly paymentId: string;\n readonly evidence: OnchainEvidence;\n}\n\n/**\n * Host-execution callback recording a creator-side `cancel` (G3 · #546):\n * on-chain the unvested remainder returns to the creator; vested-unclaimed\n * stays the recipient's. An optional credit-note document is appended.\n */\nexport interface CommitmentCancelInput {\n readonly paymentId: string;\n readonly evidence: OnchainEvidence;\n readonly document?: PaymentDocumentEnvelopeV1;\n}\n\n/**\n * Host-execution callback recording a pre-claim `redirect` to a new validated\n * recipient (G3 · #546). `to` is a validated recipient (handle/email/payee id),\n * never a raw address.\n */\nexport interface CommitmentRedirectInput {\n readonly paymentId: string;\n readonly to: Ref;\n readonly evidence: OnchainEvidence;\n readonly document?: PaymentDocumentEnvelopeV1;\n}\n\n/**\n * Host-execution callback recording a settled ORG spend/payroll on the ONE\n * `payments` ledger (D3 · #565). An org spend is a KIND of Payment — it lands a\n * real `payments` row with `source:\"org\"` + `orgId` (no parallel `orgSpends`\n * table, no synthetic client-side fabrication). The signer-side host calls this\n * AFTER the on-chain Roles-modifier spend settles; `evidence` carries the\n * internal userOp/tx hashes (never wire fields). `recipient` is the validated\n * recipient ref label; `recipientSafeAddress` is internal evidence on the row.\n */\nexport interface OrgPaymentRecordInput {\n readonly orgId: string;\n readonly recipientLabel: string;\n readonly recipientKind?: \"handle\" | \"email\" | \"payee\" | \"capxulUserId\" | \"me\" | \"org\";\n readonly recipientRef?: string;\n readonly recipientPayeeId?: string;\n readonly recipientSafeAddress: string;\n readonly amount: PaymentMoney;\n readonly paymentType: PaymentType;\n readonly document?: PaymentDocumentEnvelopeV1;\n /** The org Safe the spend debited — bound as the `from` of the settlement transfer. */\n readonly orgSafeAddress: string;\n /**\n * 0-based occurrence among batch runs with the same (recipient, amount), so\n * each run binds to + de-dupes on its own on-chain `Transfer` (D3 · #565).\n */\n readonly occurrenceIndex: number;\n readonly evidence: OnchainEvidence;\n}\n\nexport interface PaymentDocumentVerification {\n readonly documentHash: string;\n readonly ok: boolean;\n readonly derivedHash: string;\n readonly kind: PaymentDocumentKind;\n}\n\n/**\n * #577 render-on-demand result. `html` is self-contained user-visible document\n * HTML (stylesheet + rendered document). The MCP `paymentDocuments.render` tool\n * exposes only `{documentHash, kind, ok}` to the model and returns `html` in an\n * audience:[\"user\"] content block (#506 redaction matrix).\n */\nexport interface PaymentDocumentRender {\n readonly documentHash: string;\n readonly ok: boolean;\n readonly kind: PaymentDocumentKind;\n readonly html: string;\n}\n\n/**\n * Internal commitment execution reference (G3 · #546). The on-chain\n * `onchainCommitmentId` is internal evidence (like userOp/tx hashes) — it never\n * appears on the wire `Payment` or any MCP tool output, but the signer-side host\n * needs it to build a claim/cancel/redirect UserOp. This is the server-internal\n * channel that carries it (and the recipient Safe address for an auto-claim\n * relayer), never a consumer-facing surface.\n */\nexport interface PaymentCommitmentRef {\n readonly paymentId: string;\n readonly onchainCommitmentId: string | null;\n readonly status: PaymentStatus;\n}\n\n/**\n * The host-execution + on-chain-evidence channel for Payments (D2 · #564).\n * SPLIT OFF the public `PaymentsMethods` so an external builder consuming\n * `@capxul/sdk` directly never sees the custody substrate. Reached only via\n * `client.payments._internal` (mirrors `client._internal.*`); the signer-side\n * host (the dev MCP edge / a self-custody integrator) drives it AFTER executing\n * a UserOp. Every input carries the `OnchainEvidence` brand — never a wire field.\n */\nexport interface PaymentsInternalMethods {\n /** Report on-chain settlement evidence for an instant payment. */\n markSettled(\n input: PaymentSettlementInput,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<Payment>>;\n /**\n * B3: report on-chain settlement evidence for a withdraw/cash-out. The\n * backend binds the userOp to a matching external `Transfer` before settling.\n */\n markWithdrawalSettled(\n input: PaymentSettlementInput,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<Payment>>;\n /**\n * Record the on-chain escrow of a commitment after `createCommitment` returns\n * its `onchainCommitmentId` (G3 · #546).\n */\n markCommitmentCreated(\n input: CommitmentCreatedInput,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<Payment>>;\n /**\n * Record a settled ORG spend/payroll on the one `payments` ledger\n * (D3 · #565) — `source:\"org\"` + `orgId`, read back as a leak-safe Payment.\n */\n recordOrgPayment(\n input: OrgPaymentRecordInput,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<Payment>>;\n /** Record a recipient-side `claim` after the on-chain claim UserOp settles. */\n claim(\n input: CommitmentClaimInput,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<Payment>>;\n /** Record a creator-side `cancel` reclaiming only the unvested remainder. */\n cancel(\n input: CommitmentCancelInput,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<Payment>>;\n /** Record a pre-claim `redirect` to a new validated recipient. */\n redirect(\n input: CommitmentRedirectInput,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<Payment>>;\n /**\n * The on-chain commitment reference the signer-side host needs to build a\n * claim/cancel/redirect UserOp. `onchainCommitmentId` is internal evidence.\n */\n commitmentRef(\n paymentId: string,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<PaymentCommitmentRef | null>>;\n}\n\n/**\n * The PUBLIC, Stripe-shaped Payments surface (D2 · #564). Genus verbs only —\n * `pay` / `list` / `get`. No `userOpHash` / `txHash` / `onchainCommitmentId` /\n * `chainId` / `safeAddress`. Host-execution + on-chain evidence live on the\n * `_internal` channel below; an external builder never touches custody substrate.\n */\nexport interface PaymentsMethods {\n pay(\n input: PaymentsPayInput,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<Payment>>;\n payout(\n input: PaymentsPayoutInput,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<Payment>>;\n /**\n * B3 withdraw / cash-out: send USDX from the user's custody Safe to an\n * external 0x wallet, minting a kind:4 Withdrawal document. Returns a\n * leak-safe `Payment` (recipient label is the redacted address).\n */\n withdraw(\n input: PaymentsWithdrawInput,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<Payment>>;\n list(options?: { readonly signal?: AbortSignal }): Promise<CapxulResult<readonly Payment[]>>;\n get(\n paymentId: string,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<Payment | null>>;\n cancel(\n paymentId: string,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<Payment>>;\n /**\n * Host-execution + on-chain-evidence channel — off the public surface\n * (production-surface-policy.md pattern). Self-custody integrators drive this;\n * a Stripe-shaped consumer never does.\n *\n * @internal-use\n */\n readonly _internal: PaymentsInternalMethods;\n}\n\nexport interface PaymentDocumentsMethods {\n verify(\n documentHash: string,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<PaymentDocumentVerification>>;\n /**\n * #577: render-on-demand. Loads the owner's stored document by `documentHash`,\n * re-verifies its EIP-712 hash, and renders it to self-contained HTML using the\n * verified stored line items. Returns `{documentHash, kind, ok, html}`.\n */\n render(\n documentHash: string,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<PaymentDocumentRender>>;\n}\n\n// ── Request reconciliation (retained: the actor-scoped requestsInbox front\n// door in `actor-scope.ts` returns these entries). The `receivables` parallel\n// front door (`paymentRequests.*`) was demolished with its backend in #1144.\n\nexport interface ReconciliationEntry {\n readonly paymentRequestId: string;\n readonly reference: string;\n readonly status: \"paid\" | \"exception\";\n readonly settledPaymentId: string | null;\n readonly receiptDocumentHash: string | null;\n}\n\nexport interface FinancialOpsMethods {\n readonly me: MeMethods;\n readonly handles: HandlesMethods;\n readonly payees: PayeesMethods;\n readonly targets: TargetsMethods;\n readonly destinations: DestinationsMethods;\n readonly payments: PaymentsMethods;\n readonly activity: ActivityMethods;\n readonly offramp: OfframpMethods;\n readonly paymentDocuments: PaymentDocumentsMethods;\n}\n\nexport function makeFinancialOpsMethods(deps: {\n readonly convexCall: ConvexCallPort;\n readonly functions?: FinancialOpsFunctions;\n}): FinancialOpsMethods {\n const fns = deps.functions ?? financialOpsContract;\n return {\n me: {\n get: (options) =>\n runIfActive(options?.signal, \"me.get\", () => deps.convexCall.query(fns.me, {})),\n depositInstructions: (options) =>\n runIfActive(options?.signal, \"me.depositInstructions\", () =>\n deps.convexCall.query(fns.depositInstructions, {}),\n ),\n },\n handles: {\n resolve: (handle, options) =>\n runIfActive(options?.signal, \"handles.resolve\", () =>\n deps.convexCall.query(fns.resolveHandle, { handle }),\n ),\n },\n payees: {\n create: (input, options) =>\n runIfActive(options?.signal, \"payees.create\", () =>\n deps.convexCall.mutation(fns.createPayee, {\n label: input.label,\n recipient: input.recipient,\n ...(input.handle === undefined ? {} : { handle: input.handle }),\n }),\n ),\n get: (payeeId, options) =>\n runIfActive(options?.signal, \"payees.get\", () =>\n deps.convexCall.query(fns.getPayee, { payeeId }),\n ),\n resolve: (recipient, options) =>\n runIfActive(options?.signal, \"payees.resolve\", () =>\n deps.convexCall.query(fns.resolvePayee, { recipient }),\n ),\n },\n targets: {\n resolve: async (reference, options) => {\n switch (reference.kind) {\n case \"handle\": {\n const resolved = await runIfActive(options?.signal, \"targets.resolve.handle\", () =>\n deps.convexCall.query(fns.resolveHandle, { handle: reference.handle }),\n );\n return mapOk(resolved, (target) => resolvedTargetFromResolution(reference, target));\n }\n case \"email\": {\n const resolved = await runIfActive(options?.signal, \"targets.resolve.email\", () =>\n deps.convexCall.query(fns.resolvePayee, { recipient: reference.email }),\n );\n return mapOk(resolved, (target) => resolvedTargetFromResolution(reference, target));\n }\n case \"organization\": {\n const resolved = await runIfActive(\n options?.signal,\n \"targets.resolve.organization\",\n () => deps.convexCall.query(fns.resolveHandle, { handle: reference.handle }),\n );\n if (!resolved.ok) return { ok: false, error: resolved.error };\n if (resolved.value.kind !== \"org\") {\n return {\n ok: false,\n error: Errors.invalidInput(\n \"reference\",\n \"organization handle could not be resolved\",\n ),\n };\n }\n return { ok: true, value: resolvedTargetFromResolution(reference, resolved.value) };\n }\n case \"payee\": {\n const payee = await runIfActive(options?.signal, \"targets.resolve.payee\", () =>\n deps.convexCall.query(fns.getPayee, { payeeId: reference.id }),\n );\n if (!payee.ok) return { ok: false, error: payee.error };\n if (payee.value === null) {\n return { ok: false, error: Errors.invalidInput(\"reference\", \"payee not found\") };\n }\n return { ok: true, value: resolvedTargetFromPayee(reference, payee.value) };\n }\n case \"destination\":\n return Promise.resolve({\n ok: false,\n error: Errors.notImplemented(\"targets\", \"resolve.destination\"),\n });\n }\n },\n },\n destinations: {\n add: async (input, options) => {\n const scope = normalizeDestinationInputScope(input, \"target\");\n if (!scope.ok) return { ok: false, error: scope.error };\n const scopeValue = scope.value;\n // #1063: exactly one of target (counterparty or `{ self: true }`) or\n // ref — mirrors the backend guard.\n if (scopeValue === undefined) {\n return {\n ok: false,\n error: Errors.invalidInput(\"target\", DESTINATION_SCOPE_MESSAGE),\n };\n }\n const backendActor = actorReferenceToBackend(input.actor);\n return mapOk(\n await runIfActive(options?.signal, \"destinations.add\", () =>\n deps.convexCall.mutation(fns.addDestination, {\n ...(backendActor === undefined ? {} : { actor: backendActor }),\n ...(isSelfTarget(scopeValue) ? { self: true } : { ref: scopeValue }),\n kind: destinationKindToBackend(input.kind),\n ...(input.label === undefined ? {} : { label: input.label }),\n payload: input.payload,\n }),\n ),\n destinationFromBackend,\n );\n },\n list: async (input, options) => {\n const scope = normalizeDestinationInputScope(input, \"target\");\n if (!scope.ok) return { ok: false, error: scope.error };\n const scopeValue = scope.value;\n return mapOk(\n await runIfActive(options?.signal, \"destinations.list\", () =>\n deps.convexCall.query(fns.listDestinations, {\n ...(input.actor === undefined ? {} : { actor: actorReferenceToBackend(input.actor) }),\n ...(scopeValue !== undefined && isSelfTarget(scopeValue) ? { self: true } : {}),\n ...(scopeValue !== undefined && !isSelfTarget(scopeValue) ? { ref: scopeValue } : {}),\n }),\n ),\n (destinations) =>\n destinations\n .map(destinationFromBackend)\n .filter((destination) => input.kind === undefined || destination.kind === input.kind),\n );\n },\n remove: (input, options) =>\n runIfActive(options?.signal, \"destinations.remove\", () =>\n deps.convexCall.mutation(fns.removeDestination, {\n ...(input.actor === undefined ? {} : { actor: actorReferenceToBackend(input.actor) }),\n destinationId: input.destinationId,\n }),\n ),\n },\n payments: {\n pay: async (input, options) => {\n const actor = actorReferenceToBackend(input.actor);\n if (actor?.kind === \"org\") {\n return { ok: false, error: Errors.notImplemented(\"payments\", \"pay.organizationActor\") };\n }\n const to = normalizeTargetForBackend(input.to, \"to\");\n if (!to.ok) return { ok: false, error: to.error };\n return mapOk(\n await runIfActive(options?.signal, \"payments.pay\", () =>\n deps.convexCall.mutation(fns.pay, {\n to: to.value,\n amount: input.amount,\n ...(input.paymentType === undefined ? {} : { paymentType: input.paymentType }),\n ...(input.document === undefined ? {} : { document: input.document }),\n ...(input.timing === undefined ? {} : { timing: input.timing }),\n ...(input.lineItems === undefined ? {} : { lineItems: input.lineItems }),\n }),\n ),\n normalizePaymentTiming,\n );\n },\n payout: async (input, options) =>\n mapOk(\n await runIfActive(options?.signal, \"payments.payout\", () =>\n deps.convexCall.mutation(fns.payout, {\n ...(input.actor === undefined ? {} : { actor: actorReferenceToBackend(input.actor) }),\n destinationId: input.destinationId,\n amount: input.amount,\n }),\n ),\n normalizePaymentTiming,\n ),\n withdraw: (input, options) =>\n runIfActive(options?.signal, \"payments.withdraw\", () =>\n deps.convexCall.mutation(fns.withdraw, {\n to: input.to,\n amount: input.amount,\n document: input.document,\n }),\n ),\n list: async (options) =>\n mapOk(\n await runIfActive(options?.signal, \"payments.list\", () =>\n deps.convexCall.query(fns.listPayments, {}),\n ),\n (payments) => payments.map(normalizePaymentTiming),\n ),\n get: async (paymentId, options) =>\n mapOk(\n await runIfActive(options?.signal, \"payments.get\", () =>\n deps.convexCall.query(fns.getPayment, { paymentId }),\n ),\n (payment) => (payment === null ? null : normalizePaymentTiming(payment)),\n ),\n cancel: (paymentId, options) => {\n if (options?.signal?.aborted) {\n return Promise.resolve({\n ok: false,\n error: Errors.cancelled({ operation: \"payments.cancel\" }),\n });\n }\n void paymentId;\n return Promise.resolve({\n ok: false,\n error: Errors.notImplemented(\"payments\", \"cancel\"),\n });\n },\n // D2 (#564): the host-execution + on-chain-evidence channel. Off the\n // public surface; the backend actions still receive the raw userOp/tx\n // hashes (behavior-preserving) — they are unwrapped from the brand here.\n _internal: {\n markSettled: (input, options) =>\n runIfActive(options?.signal, \"payments.markSettled\", () =>\n deps.convexCall.action(fns.markPaymentSettled, {\n paymentId: input.paymentId,\n userOpHash: input.evidence.userOpHash,\n txHash: input.evidence.txHash,\n }),\n ),\n // B3: report withdraw/cash-out settlement evidence (external transfer).\n markWithdrawalSettled: (input, options) =>\n runIfActive(options?.signal, \"payments.markWithdrawalSettled\", () =>\n deps.convexCall.action(fns.markWithdrawalSettled, {\n paymentId: input.paymentId,\n userOpHash: input.evidence.userOpHash,\n txHash: input.evidence.txHash,\n }),\n ),\n // D3 (#565): record a settled org spend on the one ledger (source:\"org\").\n recordOrgPayment: (input, options) =>\n runIfActive(options?.signal, \"payments.recordOrgPayment\", () =>\n deps.convexCall.action(fns.recordOrgPayment, {\n orgId: input.orgId,\n recipientLabel: input.recipientLabel,\n ...(input.recipientKind === undefined ? {} : { recipientKind: input.recipientKind }),\n ...(input.recipientRef === undefined ? {} : { recipientRef: input.recipientRef }),\n ...(input.recipientPayeeId === undefined\n ? {}\n : { recipientPayeeId: input.recipientPayeeId }),\n recipientSafeAddress: input.recipientSafeAddress,\n amount: input.amount,\n paymentType: input.paymentType,\n ...(input.document === undefined ? {} : { document: input.document }),\n orgSafeAddress: input.orgSafeAddress,\n occurrenceIndex: input.occurrenceIndex,\n userOpHash: input.evidence.userOpHash,\n txHash: input.evidence.txHash,\n }),\n ),\n markCommitmentCreated: (input, options) =>\n runIfActive(options?.signal, \"payments.markCommitmentCreated\", () =>\n deps.convexCall.action(fns.markCommitmentCreated, {\n paymentId: input.paymentId,\n onchainCommitmentId: input.onchainCommitmentId,\n userOpHash: input.evidence.userOpHash,\n txHash: input.evidence.txHash,\n }),\n ),\n claim: (input, options) =>\n runIfActive(options?.signal, \"payments.claim\", () =>\n deps.convexCall.action(fns.claimCommitment, {\n paymentId: input.paymentId,\n userOpHash: input.evidence.userOpHash,\n txHash: input.evidence.txHash,\n }),\n ),\n cancel: (input, options) =>\n runIfActive(options?.signal, \"payments.cancel\", () =>\n deps.convexCall.action(fns.cancelCommitment, {\n paymentId: input.paymentId,\n userOpHash: input.evidence.userOpHash,\n txHash: input.evidence.txHash,\n ...(input.document === undefined ? {} : { document: input.document }),\n }),\n ),\n redirect: async (input, options) => {\n const to = normalizeRefForBackend(input.to, \"to\");\n if (!to.ok) return { ok: false, error: to.error };\n return mapOk(\n await runIfActive(options?.signal, \"payments.redirect\", () =>\n deps.convexCall.action(fns.redirectCommitment, {\n paymentId: input.paymentId,\n to: to.value,\n userOpHash: input.evidence.userOpHash,\n txHash: input.evidence.txHash,\n ...(input.document === undefined ? {} : { document: input.document }),\n }),\n ),\n normalizePaymentTiming,\n );\n },\n commitmentRef: (paymentId, options) =>\n runIfActive(options?.signal, \"payments.commitmentRef\", () =>\n deps.convexCall.query(fns.getCommitmentRef, { paymentId }),\n ),\n },\n },\n activity: {\n list: (params, options) => {\n if (options?.signal?.aborted) {\n return Promise.resolve({\n ok: false,\n error: Errors.cancelled({ operation: \"activity.list\" }),\n });\n }\n void params;\n return Promise.resolve({\n ok: false,\n error: Errors.notImplemented(\"activity\", \"list\"),\n });\n },\n },\n offramp: {\n quote: (input, options) => {\n if (options?.signal?.aborted) {\n return Promise.resolve({\n ok: false,\n error: Errors.cancelled({ operation: \"offramp.quote\" }),\n });\n }\n void input;\n return Promise.resolve({\n ok: false,\n error: Errors.notImplemented(\"offramp\", \"quote\"),\n });\n },\n status: (offrampId, options) => {\n if (options?.signal?.aborted) {\n return Promise.resolve({\n ok: false,\n error: Errors.cancelled({ operation: \"offramp.status\" }),\n });\n }\n void offrampId;\n return Promise.resolve({\n ok: false,\n error: Errors.notImplemented(\"offramp\", \"status\"),\n });\n },\n },\n paymentDocuments: {\n verify: (documentHash, options) =>\n runIfActive(options?.signal, \"paymentDocuments.verify\", () =>\n deps.convexCall.query(fns.verifyPaymentDocument, { documentHash }),\n ),\n render: (documentHash, options) =>\n runIfActive(options?.signal, \"paymentDocuments.render\", () =>\n deps.convexCall.query(fns.renderStoredDocument, { documentHash }),\n ),\n },\n };\n}\n\ntype PaymentPayload = Omit<Payment, \"timing\"> & {\n readonly timing?: PaymentTiming;\n readonly release?: PaymentTiming;\n};\n\nexport function refToRecipientString(ref: Ref): string {\n if (typeof (ref as unknown) === \"string\") {\n throw Errors.invalidInput(\"to\", \"recipient must be a typed Ref variant\");\n }\n if (typeof ref !== \"object\" || ref === null || !(\"kind\" in ref)) {\n throw Errors.invalidInput(\"to\", \"recipient must be a typed Ref variant\");\n }\n switch (ref.kind) {\n case \"handle\":\n return handleRefValue(ref.handle, \"handle\");\n case \"email\":\n return nonEmptyRefValue(ref.email, \"email\");\n case \"orgHandle\":\n return nonEmptyRefValue(ref.orgHandle, \"orgHandle\");\n case \"capxulUserId\":\n return nonEmptyRefValue(ref.capxulUserId, \"capxulUserId\");\n case \"payeeId\":\n return nonEmptyRefValue(ref.payeeId, \"payeeId\");\n default:\n throw Errors.invalidInput(\"to\", \"recipient must be a known Ref variant\");\n }\n}\n\nfunction nonEmptyRefValue(value: string, field: string): string {\n const trimmed = value.trim();\n if (trimmed.length === 0) {\n throw Errors.invalidInput(field, \"Ref value must be non-empty\");\n }\n if (/^0x[0-9a-fA-F]{40}$/.test(trimmed)) {\n throw Errors.invalidInput(field, \"raw 0x addresses are not valid Ref values\");\n }\n return trimmed;\n}\n\nfunction handleRefValue(value: string, field: string): string {\n const trimmed = nonEmptyRefValue(value, field);\n return trimmed.startsWith(\"@\") ? trimmed.slice(1) : trimmed;\n}\n\nfunction refFromTargetReference(reference: TargetReference, field: string): CapxulResult<Ref> {\n try {\n if (typeof (reference as unknown) === \"string\") {\n throw Errors.invalidInput(field, \"target must be a typed TargetReference variant\");\n }\n if (typeof reference !== \"object\" || reference === null || !(\"kind\" in reference)) {\n throw Errors.invalidInput(field, \"target must be a typed TargetReference variant\");\n }\n switch (reference.kind) {\n case \"handle\":\n return { ok: true, value: { kind: \"handle\", handle: reference.handle } };\n case \"email\":\n return { ok: true, value: { kind: \"email\", email: reference.email } };\n case \"organization\":\n return { ok: true, value: { kind: \"orgHandle\", orgHandle: reference.handle } };\n case \"payee\":\n return { ok: true, value: { kind: \"payeeId\", payeeId: reference.id } };\n case \"destination\":\n return {\n ok: false,\n error: Errors.notImplemented(\"targets\", \"reference.destination\"),\n };\n default:\n throw Errors.invalidInput(field, \"target must be a known TargetReference variant\");\n }\n } catch (cause) {\n if (cause instanceof Error && \"code\" in cause) {\n return { ok: false, error: cause as CapxulError };\n }\n return {\n ok: false,\n error: Errors.invalidInput(field, \"target must be a typed TargetReference variant\"),\n };\n }\n}\n\nfunction normalizeTargetForBackend(\n reference: TargetReference,\n field: string,\n): CapxulResult<BackendRef> {\n const ref = refFromTargetReference(reference, field);\n return ref.ok ? normalizeRefForBackend(ref.value, field) : ref;\n}\n\nconst DESTINATION_SCOPE_MESSAGE =\n \"provide exactly one of target or ref; use target: { self: true } for your own destination\";\n\n/** #1063: detect the `{ self: true }` variant of a destination target. */\nfunction isSelfTarget(value: TargetReference | SelfTarget | BackendRef): value is SelfTarget {\n return \"self\" in value;\n}\n\n/**\n * #1063: resolve the public `target`/`ref` pair — `SelfTarget` for the actor's\n * own destination, a `BackendRef` for a counterparty, `undefined` when unscoped.\n */\nfunction normalizeDestinationInputScope(\n input: { readonly target?: TargetReference | SelfTarget; readonly ref?: Ref },\n field: string,\n): CapxulResult<BackendRef | SelfTarget | undefined> {\n const target = input.target;\n if (target !== undefined && isSelfTarget(target)) {\n if (input.ref !== undefined) {\n return { ok: false, error: Errors.invalidInput(field, DESTINATION_SCOPE_MESSAGE) };\n }\n return { ok: true, value: target };\n }\n if (target !== undefined) return normalizeTargetForBackend(target, field);\n if (input.ref !== undefined) return normalizeDestinationRefForBackend(input.ref, \"ref\");\n return { ok: true, value: undefined };\n}\n\nfunction targetReferenceFromBackendRef(ref: Ref): TargetReference {\n switch (ref.kind) {\n case \"handle\":\n return { kind: \"handle\", handle: ref.handle };\n case \"email\":\n return { kind: \"email\", email: ref.email };\n case \"orgHandle\":\n return { kind: \"organization\", handle: ref.orgHandle };\n case \"payeeId\":\n return { kind: \"payee\", id: ref.payeeId };\n case \"capxulUserId\":\n throw Errors.notImplemented(\"targets\", \"reference.capxulUserId\");\n }\n}\n\nfunction resolvedTargetFromResolution(\n reference: TargetReference,\n resolution: RecipientResolution,\n): ResolvedTarget {\n const kind =\n resolution.kind === \"org\" ? \"organization\" : resolution.kind === \"payee\" ? \"payee\" : \"person\";\n return {\n reference,\n label: resolution.label,\n kind,\n capabilities: {\n canPay: true,\n canRequest: true,\n canPayout: false,\n },\n };\n}\n\nfunction resolvedTargetFromPayee(reference: TargetReference, payee: Payee): ResolvedTarget {\n return {\n reference,\n label: payee.label,\n kind: \"payee\",\n capabilities: {\n canPay: true,\n canRequest: true,\n canPayout: false,\n },\n };\n}\n\nfunction destinationKindToBackend(kind: DestinationKind): BackendDestinationKind {\n switch (kind) {\n case \"bank_account\":\n return \"bank\";\n case \"mobile_money\":\n return \"mobile-money\";\n case \"external_account\":\n return \"wallet\";\n }\n}\n\nfunction destinationKindFromBackend(kind: BackendDestinationKind): DestinationKind {\n switch (kind) {\n case \"bank\":\n return \"bank_account\";\n case \"mobile-money\":\n return \"mobile_money\";\n case \"wallet\":\n return \"external_account\";\n }\n}\n\nfunction destinationRailFromBackend(destination: BackendDestination): DestinationRail {\n switch (destination.kind) {\n case \"bank\": {\n const payload = destination.payload as Extract<\n DestinationPayload,\n { readonly bankName: string }\n >;\n return { kind: \"bank\", country: payload.country, currency: payload.currency };\n }\n case \"mobile-money\": {\n const payload = destination.payload as Extract<\n DestinationPayload,\n { readonly provider: string }\n >;\n return {\n kind: \"mobile_money\",\n country: payload.country,\n currency: payload.currency,\n provider: payload.provider,\n };\n }\n case \"wallet\": {\n const payload = destination.payload as Extract<\n DestinationPayload,\n { readonly network: string }\n >;\n return { kind: \"chain\", network: payload.network, asset: \"USD\" };\n }\n }\n}\n\nfunction destinationFromBackend(destination: BackendDestination): Destination {\n return {\n ...destination,\n // #1063: self rows carry no counterparty ref — surface null instead of\n // crashing the target derivation.\n target: destination.ref === null ? null : targetReferenceFromBackendRef(destination.ref),\n ownerScope: destination.ownerScope ?? \"counterparty\",\n kind: destinationKindFromBackend(destination.kind),\n rail: destinationRailFromBackend(destination),\n };\n}\n\nfunction normalizeDestinationRefForBackend(ref: Ref, field: string): CapxulResult<BackendRef> {\n if (typeof ref === \"object\" && ref !== null && \"kind\" in ref && ref.kind === \"capxulUserId\") {\n return { ok: false, error: Errors.notImplemented(\"targets\", \"reference.capxulUserId\") };\n }\n return normalizeRefForBackend(ref, field);\n}\n\nfunction normalizeRefForBackend(ref: Ref, field: string): CapxulResult<BackendRef> {\n try {\n if (typeof (ref as unknown) === \"string\") {\n throw Errors.invalidInput(field, \"recipient must be a typed Ref variant\");\n }\n if (typeof ref !== \"object\" || ref === null || !(\"kind\" in ref)) {\n throw Errors.invalidInput(field, \"recipient must be a typed Ref variant\");\n }\n switch (ref.kind) {\n case \"handle\":\n return {\n ok: true,\n value: { kind: \"handle\", handle: handleRefValue(ref.handle, \"handle\") },\n };\n case \"email\":\n return { ok: true, value: { kind: \"email\", email: nonEmptyRefValue(ref.email, \"email\") } };\n case \"orgHandle\":\n return {\n ok: true,\n value: { kind: \"orgHandle\", orgHandle: nonEmptyRefValue(ref.orgHandle, \"orgHandle\") },\n };\n case \"capxulUserId\":\n return {\n ok: true,\n value: {\n kind: \"capxulUserId\",\n capxulUserId: nonEmptyRefValue(ref.capxulUserId, \"capxulUserId\"),\n },\n };\n case \"payeeId\":\n return {\n ok: true,\n value: { kind: \"payeeId\", payeeId: nonEmptyRefValue(ref.payeeId, \"payeeId\") },\n };\n default:\n throw Errors.invalidInput(field, \"recipient must be a known Ref variant\");\n }\n } catch (cause) {\n if (cause instanceof Error && \"code\" in cause) {\n return { ok: false, error: cause as CapxulError };\n }\n return {\n ok: false,\n error: Errors.invalidInput(field, \"recipient must be a typed Ref variant\"),\n };\n }\n}\n\nfunction normalizePaymentTiming(payment: PaymentPayload): Payment {\n const { release: _release, ...rest } = payment;\n return {\n ...rest,\n timing: payment.timing ?? payment.release ?? { kind: \"instant\" },\n };\n}\n\nfunction mapOk<T, U>(result: CapxulResult<T>, f: (value: T) => U): CapxulResult<U> {\n if (!result.ok) return result;\n try {\n return { ok: true, value: f(result.value) };\n } catch (cause) {\n if (cause instanceof Error && \"code\" in cause) {\n return { ok: false, error: cause as CapxulError };\n }\n throw cause;\n }\n}\n","// The media backend contract (A2-Q3A · blueprint §2 moves ledger).\n//\n// Three typed references over `packages/backend/convex/media.ts`. Paths come\n// from `@capxul/wire`'s `CAPXUL_FUNCTIONS`; `lint-wire-contract` proves them\n// against the backend on `check:fast`.\n\nimport { makeFunctionReference, type FunctionReference } from \"convex/server\";\n\nimport { CAPXUL_FUNCTIONS } from \"@capxul/wire\";\n\nexport const mediaContract = {\n generateUploadUrl: makeFunctionReference<\n \"mutation\",\n Record<string, never>,\n { readonly uploadUrl: string }\n >(CAPXUL_FUNCTIONS.media.generateUploadUrl),\n setProfileImage: makeFunctionReference<\n \"mutation\",\n { readonly storageId: string },\n { readonly imageUrl: string | null }\n >(CAPXUL_FUNCTIONS.media.setProfileImage),\n setOrgLogo: makeFunctionReference<\n \"mutation\",\n { readonly orgId: string; readonly storageId: string },\n { readonly logoUrl: string | null }\n >(CAPXUL_FUNCTIONS.media.setOrgLogo),\n} satisfies {\n readonly generateUploadUrl: FunctionReference<\n \"mutation\",\n \"public\",\n Record<string, never>,\n { readonly uploadUrl: string }\n >;\n readonly setProfileImage: FunctionReference<\n \"mutation\",\n \"public\",\n { readonly storageId: string },\n { readonly imageUrl: string | null }\n >;\n readonly setOrgLogo: FunctionReference<\n \"mutation\",\n \"public\",\n { readonly orgId: string; readonly storageId: string },\n { readonly logoUrl: string | null }\n >;\n};\n","// Media surface (#1061 / ADR-0014), exposed at `client.media`.\n//\n// Upload flow: `generateUploadUrl` → POST the blob bytes to the returned URL\n// (Content-Type = the blob's MIME type; the response JSON carries the\n// `storageId`) → record it via `setProfileImage` / `setOrgLogo`. The backend\n// recording mutation is the validation boundary (ownership, content type,\n// size); serving URLs are resolved at read time and are not stable\n// long-lived links.\n\nimport { Errors } from \"@capxul/errors\";\n\nimport { mediaContract } from \"../contract/media\";\nimport type { ConvexCallPort } from \"../ports/convex-call\";\nimport { runIfActive } from \"./to-capxul-result\";\nimport type { CapxulResult } from \"./types\";\n\nexport interface MediaMethods {\n uploadImage(\n blob: Blob,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<{ readonly storageId: string }>>;\n setProfileImage(\n input: { readonly storageId: string },\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<{ readonly imageUrl: string | null }>>;\n setOrgLogo(\n input: { readonly orgId: string; readonly storageId: string },\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<{ readonly logoUrl: string | null }>>;\n}\n\nexport interface MakeMediaMethodsDeps {\n readonly convexCall: ConvexCallPort;\n /** Injectable for hermetic tests; defaults to the platform `fetch`. */\n readonly fetch?: typeof globalThis.fetch;\n}\n\nexport function makeMediaMethods(deps: MakeMediaMethodsDeps): MediaMethods {\n const fetchImpl = deps.fetch ?? ((input, init) => globalThis.fetch(input, init));\n return {\n async uploadImage(blob, options) {\n const url = await runIfActive(options?.signal, \"media.uploadImage\", () =>\n deps.convexCall.mutation(mediaContract.generateUploadUrl, {}),\n );\n if (!url.ok) return url;\n try {\n const response = await fetchImpl(url.value.uploadUrl, {\n method: \"POST\",\n headers: { \"Content-Type\": blob.type },\n body: blob,\n ...(options?.signal === undefined ? {} : { signal: options.signal }),\n });\n if (!response.ok) {\n return {\n ok: false,\n error: Errors.providerError(\n \"convex-storage\",\n \"uploadImage\",\n `upload failed with status ${response.status}`,\n ),\n };\n }\n const parsed = (await response.json()) as { readonly storageId?: unknown };\n if (typeof parsed.storageId !== \"string\" || parsed.storageId.length === 0) {\n return {\n ok: false,\n error: Errors.providerError(\n \"convex-storage\",\n \"uploadImage\",\n \"upload response carried no storageId\",\n ),\n };\n }\n return { ok: true, value: { storageId: parsed.storageId } };\n } catch (cause) {\n return { ok: false, error: Errors.providerError(\"convex-storage\", \"uploadImage\", cause) };\n }\n },\n setProfileImage: (input, options) =>\n runIfActive(options?.signal, \"media.setProfileImage\", () =>\n deps.convexCall.mutation(mediaContract.setProfileImage, { storageId: input.storageId }),\n ),\n setOrgLogo: (input, options) =>\n runIfActive(options?.signal, \"media.setOrgLogo\", () =>\n deps.convexCall.mutation(mediaContract.setOrgLogo, {\n orgId: input.orgId,\n storageId: input.storageId,\n }),\n ),\n };\n}\n","// The system backend contract (A2-Q3A · blueprint §2 moves ledger).\n//\n// `system:health` is the proof lane's liveness round-trip (#1149): the only\n// call whose whole point is that the answer came from the deployment rather\n// than from this process. Its path comes from `@capxul/wire`, so the proof\n// lane and the backend cannot drift apart silently.\n\nimport { makeFunctionReference, type FunctionReference } from \"convex/server\";\n\nimport { CAPXUL_FUNCTIONS } from \"@capxul/wire\";\n\n/** What `system:health` answers. */\nexport interface SystemHealth {\n /** The nonce the caller sent, as the backend saw it. */\n readonly nonce: string;\n /** Deployment that answered, e.g. `little-sandpiper-974`. */\n readonly deployment: string;\n /** Backend clock at execution (epoch ms). */\n readonly at: number;\n}\n\nexport const healthQuery: FunctionReference<\n \"query\",\n \"public\",\n { readonly nonce: string },\n SystemHealth\n> = makeFunctionReference<\"query\", { readonly nonce: string }, SystemHealth>(\n CAPXUL_FUNCTIONS.system.health,\n);\n","// System surface (#1149 proof lane), exposed at `client.system`.\n//\n// One method, one job: send a nonce to the configured backend and read it\n// back. It is the smallest honest liveness journey — MCP/host → SDK →\n// deployment → back — and it exists because a local echo (the MCP's\n// `system.ping`) can claim liveness without a single byte leaving the\n// process. `deployment` is reported by the backend from its own\n// `CONVEX_CLOUD_URL`, so the answer names the deployment that produced it.\n\nimport { healthQuery, type SystemHealth } from \"../contract/system\";\nimport type { ConvexCallPort } from \"../ports/convex-call\";\nimport { runIfActive } from \"./to-capxul-result\";\nimport type { CapxulResult } from \"./types\";\n\nexport type { SystemHealth };\n\nexport interface SystemMethods {\n health(\n nonce: string,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<SystemHealth>>;\n}\n\nexport interface MakeSystemMethodsDeps {\n readonly convexCall: ConvexCallPort;\n}\n\nexport function makeSystemMethods(deps: MakeSystemMethodsDeps): SystemMethods {\n return {\n health: (nonce, options) =>\n runIfActive(options?.signal, \"system.health\", () =>\n deps.convexCall.query(healthQuery, { nonce }),\n ),\n };\n}\n","import { Context, Effect, Layer } from \"effect\";\n\nimport { CapxulError } from \"@capxul/config\";\nimport type { AccountId, SubAccount, SubAccountId } from \"@capxul/types\";\n\nimport type { SubAccountPort, TransferInput, TransferResult } from \"../ports/sub-account\";\nimport type { TelemetryPort } from \"../ports/telemetry\";\nimport {\n emitSubAccountCreated,\n emitSubAccountDeleted,\n emitSubAccountOpFailed,\n emitSubAccountRenamed,\n emitTransferFailed,\n emitTransferRequested,\n} from \"./_shared/money-telemetry\";\n\nexport interface SubAccountsDeps {\n readonly subAccountPort: SubAccountPort;\n readonly telemetry?: TelemetryPort;\n}\n\nexport class SubAccountsDepsTag extends Context.Service<SubAccountsDepsTag, SubAccountsDeps>()(\n \"@capxul/sdk/SubAccountsDeps\",\n) {}\n\nexport function subAccountsDepsLayer(deps: SubAccountsDeps): Layer.Layer<SubAccountsDepsTag> {\n return Layer.succeed(SubAccountsDepsTag, deps);\n}\n\nexport function createSubAccountProgram(\n accountId: AccountId,\n name: string,\n): Effect.Effect<SubAccount, CapxulError, SubAccountsDepsTag> {\n return Effect.gen(function* () {\n const deps = yield* SubAccountsDepsTag;\n // `subaccount_created` is SDK-emitted on the server-confirmed row: the\n // backend write site is a Convex MUTATION, which cannot `fetch` PostHog\n // (V8 transactional runtime). Per the truth-source principle the returned\n // row IS the confirmed fact, so the SDK emits it the instant it lands. The\n // NAME never enters telemetry — only the branded `sub_account_id`. See\n // packages/observability/CONTEXT.md \"Money domain\".\n const created = yield* deps.subAccountPort.create({ accountId, name }).pipe(\n Effect.tapError((error) =>\n Effect.promise(() => emitSubAccountOpFailed(deps.telemetry, \"create\", error.publicCode)),\n ),\n Effect.mapError((error) => error.publicError),\n );\n yield* Effect.promise(() => emitSubAccountCreated(deps.telemetry, created.id));\n return created;\n });\n}\n\nexport function getSubAccountProgram(\n subAccountId: SubAccountId,\n): Effect.Effect<SubAccount | null, CapxulError, SubAccountsDepsTag> {\n return Effect.gen(function* () {\n const deps = yield* SubAccountsDepsTag;\n return yield* deps.subAccountPort\n .get({ subAccountId })\n .pipe(Effect.mapError((error) => error.publicError));\n });\n}\n\nexport function listSubAccountsProgram(\n accountId: AccountId,\n): Effect.Effect<readonly SubAccount[], CapxulError, SubAccountsDepsTag> {\n return Effect.gen(function* () {\n const deps = yield* SubAccountsDepsTag;\n return yield* deps.subAccountPort\n .list({ accountId })\n .pipe(Effect.mapError((error) => error.publicError));\n });\n}\n\nexport function renameSubAccountProgram(\n subAccountId: SubAccountId,\n name: string,\n): Effect.Effect<SubAccount, CapxulError, SubAccountsDepsTag> {\n return Effect.gen(function* () {\n const deps = yield* SubAccountsDepsTag;\n // SDK-emitted server-confirmed `subaccount_renamed` (rename is a Convex\n // mutation — same fetch constraint as create). NAME excluded; only the\n // branded `sub_account_id`.\n const renamed = yield* deps.subAccountPort.rename({ subAccountId, name }).pipe(\n Effect.tapError((error) =>\n Effect.promise(() => emitSubAccountOpFailed(deps.telemetry, \"rename\", error.publicCode)),\n ),\n Effect.mapError((error) => error.publicError),\n );\n yield* Effect.promise(() => emitSubAccountRenamed(deps.telemetry, renamed.id));\n return renamed;\n });\n}\n\nexport function deleteSubAccountProgram(\n subAccountId: SubAccountId,\n): Effect.Effect<void, CapxulError, SubAccountsDepsTag> {\n return Effect.gen(function* () {\n const deps = yield* SubAccountsDepsTag;\n // SDK-emitted server-confirmed `subaccount_deleted` (remove is a Convex\n // mutation — same fetch constraint). The deleted id is known client-side.\n yield* deps.subAccountPort.delete({ subAccountId }).pipe(\n Effect.tapError((error) =>\n Effect.promise(() => emitSubAccountOpFailed(deps.telemetry, \"delete\", error.publicCode)),\n ),\n Effect.mapError((error) => error.publicError),\n );\n yield* Effect.promise(() => emitSubAccountDeleted(deps.telemetry, subAccountId));\n });\n}\n\nexport function transferSubAccountProgram(\n input: TransferInput,\n): Effect.Effect<TransferResult, CapxulError, SubAccountsDepsTag> {\n return Effect.gen(function* () {\n const deps = yield* SubAccountsDepsTag;\n // SDK producer for `transfer_requested` (before the backend transfer). The\n // server-confirmed `transfer_confirmed` is emitted backend-side\n // (`subAccount/actions:transfer`) after `applyTransfer` returns.\n yield* Effect.promise(() =>\n emitTransferRequested(deps.telemetry, {\n amount: input.amount,\n from: input.from,\n to: input.to,\n }),\n );\n return yield* deps.subAccountPort.transfer(input).pipe(\n Effect.tapError((error) =>\n Effect.promise(() => emitTransferFailed(deps.telemetry, error.publicCode)),\n ),\n Effect.mapError((error) => error.publicError),\n );\n });\n}\n","import { Errors } from \"@capxul/config\";\nimport type { AccountId, SubAccount, SubAccountId } from \"@capxul/types\";\n\nimport type { SubAccountPort, TransferInput, TransferResult } from \"../ports/sub-account\";\nimport type { TelemetryPort } from \"../ports/telemetry\";\nimport {\n subAccountsDepsLayer,\n createSubAccountProgram,\n deleteSubAccountProgram,\n getSubAccountProgram,\n listSubAccountsProgram,\n renameSubAccountProgram,\n transferSubAccountProgram,\n} from \"./sub-accounts-deps\";\nimport { toCapxulResult } from \"./to-capxul-result\";\nimport type { CapxulResult } from \"./types\";\n\nexport interface SubAccountsMethods {\n create(\n accountId: AccountId,\n input: { readonly name: string },\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<SubAccount>>;\n get(\n subAccountId: SubAccountId,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<SubAccount | null>>;\n list(\n accountId: AccountId,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<readonly SubAccount[]>>;\n rename(\n subAccountId: SubAccountId,\n name: string,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<SubAccount>>;\n delete(\n subAccountId: SubAccountId,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<void>>;\n transfer(\n input: TransferInput,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<TransferResult>>;\n}\n\nexport interface MakeSubAccountsMethodsDeps {\n readonly subAccountPort: SubAccountPort;\n readonly telemetry?: TelemetryPort;\n}\n\nexport function makeSubAccountsMethods(deps: MakeSubAccountsMethodsDeps): SubAccountsMethods {\n const layer = subAccountsDepsLayer(deps);\n return {\n async create(accountId, input, options) {\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"subAccounts.create\" }) };\n }\n return toCapxulResult(createSubAccountProgram(accountId, input.name), layer);\n },\n async get(subAccountId, options) {\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"subAccounts.get\" }) };\n }\n return toCapxulResult(getSubAccountProgram(subAccountId), layer);\n },\n async list(accountId, options) {\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"subAccounts.list\" }) };\n }\n return toCapxulResult(listSubAccountsProgram(accountId), layer);\n },\n async rename(subAccountId, name, options) {\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"subAccounts.rename\" }) };\n }\n return toCapxulResult(renameSubAccountProgram(subAccountId, name), layer);\n },\n async delete(subAccountId, options) {\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"subAccounts.delete\" }) };\n }\n return toCapxulResult(deleteSubAccountProgram(subAccountId), layer);\n },\n async transfer(input, options) {\n if (options?.signal?.aborted) {\n return { ok: false, error: Errors.cancelled({ operation: \"subAccounts.transfer\" }) };\n }\n return toCapxulResult(transferSubAccountProgram(input), layer);\n },\n };\n}\n","// The payroll-roster backend contract (A2-Q3A · blueprint §2 moves ledger).\n//\n// Five typed function references over `financialOps/payrollRoster`, plus the\n// backend row shapes they carry. They used to be private declarations inside\n// `client/org.ts`; every PATH now comes from `@capxul/wire`'s\n// `CAPXUL_FUNCTIONS` registry, proven against the backend on `check:fast`.\n\nimport { makeFunctionReference, type FunctionReference } from \"convex/server\";\n\nimport type { Money } from \"@capxul/types\";\nimport { CAPXUL_FUNCTIONS } from \"@capxul/wire\";\n\nimport type { Payment, PaymentTiming, Ref } from \"../surface/money\";\n\nexport type PayrollFunctions = {\n readonly add: FunctionReference<\n \"mutation\",\n \"public\",\n {\n readonly orgId: string;\n readonly employee: Ref;\n readonly amount: Money;\n readonly timing: PaymentTiming;\n readonly payslipTemplate: PayrollBackendPayslipTemplate;\n readonly status?: \"active\" | \"paused\";\n },\n PayrollBackendRosterLine\n >;\n readonly list: FunctionReference<\n \"query\",\n \"public\",\n { readonly orgId: string; readonly includeRemoved?: boolean },\n readonly PayrollBackendRosterLine[]\n >;\n readonly update: FunctionReference<\n \"mutation\",\n \"public\",\n {\n readonly orgId: string;\n readonly rosterLineId: string;\n readonly employee?: Ref;\n readonly amount?: Money;\n readonly timing?: PaymentTiming;\n readonly payslipTemplate?: PayrollBackendPayslipTemplate;\n readonly status?: \"active\" | \"paused\";\n },\n PayrollBackendRosterLine\n >;\n readonly remove: FunctionReference<\n \"mutation\",\n \"public\",\n { readonly orgId: string; readonly rosterLineId: string },\n PayrollBackendRosterLine\n >;\n readonly run: FunctionReference<\n \"mutation\",\n \"public\",\n { readonly orgId: string; readonly period: string; readonly from: string },\n PayrollBackendRun\n >;\n};\n\nexport type PayrollBackendPayslipTemplate = {\n readonly title: string;\n readonly memo?: string;\n};\n\nexport type PayrollBackendRosterLine = {\n readonly id: string;\n readonly employee: Ref;\n readonly amount: Money;\n readonly timing: PaymentTiming;\n readonly status: \"active\" | \"paused\" | \"removed\";\n};\n\nexport type PayrollBackendRun = {\n readonly payments: readonly PaymentPayload[];\n};\n\nexport type PaymentPayload = Omit<Payment, \"timing\"> & {\n readonly timing?: PaymentTiming;\n readonly release?: PaymentTiming;\n};\n\nexport const payrollContract: PayrollFunctions = {\n add: makeFunctionReference<\n \"mutation\",\n {\n readonly orgId: string;\n readonly employee: Ref;\n readonly amount: Money;\n readonly timing: PaymentTiming;\n readonly payslipTemplate: PayrollBackendPayslipTemplate;\n readonly status?: \"active\" | \"paused\";\n },\n PayrollBackendRosterLine\n >(CAPXUL_FUNCTIONS[\"financialOps/payrollRoster\"].add),\n list: makeFunctionReference<\n \"query\",\n { readonly orgId: string; readonly includeRemoved?: boolean },\n readonly PayrollBackendRosterLine[]\n >(CAPXUL_FUNCTIONS[\"financialOps/payrollRoster\"].list),\n update: makeFunctionReference<\n \"mutation\",\n {\n readonly orgId: string;\n readonly rosterLineId: string;\n readonly employee?: Ref;\n readonly amount?: Money;\n readonly timing?: PaymentTiming;\n readonly payslipTemplate?: PayrollBackendPayslipTemplate;\n readonly status?: \"active\" | \"paused\";\n },\n PayrollBackendRosterLine\n >(CAPXUL_FUNCTIONS[\"financialOps/payrollRoster\"].update),\n remove: makeFunctionReference<\n \"mutation\",\n { readonly orgId: string; readonly rosterLineId: string },\n PayrollBackendRosterLine\n >(CAPXUL_FUNCTIONS[\"financialOps/payrollRoster\"].remove),\n run: makeFunctionReference<\n \"mutation\",\n { readonly orgId: string; readonly period: string; readonly from: string },\n PayrollBackendRun\n >(CAPXUL_FUNCTIONS[\"financialOps/payrollRoster\"].run),\n};\n","// Organization-domain telemetry helpers for the SDK method bundles (see\n// `packages/observability/CONTEXT.md`, J1 `org_creation` funnel).\n//\n// Mirrors `money-telemetry.ts`: a thin, fire-and-forget bridge that emits a\n// catalogued `TelemetryEvent` through an optional `TelemetryPort`, swallowing\n// all failures (telemetry must never fail an org flow). The producer split\n// (which names the SDK emits vs which the backend emits) is documented in\n// `packages/observability/CONTEXT.md` and its producer tests.\n//\n// PII discipline (canon §C5): raw emails NEVER enter telemetry — only\n// `email_domain`. `org_id` is the public `org_`-shaped brand (also the PostHog\n// `organization` group key); never an OTP, never a key.\n\nimport { Effect } from \"effect\";\n\nimport type { OrgId } from \"@capxul/types\";\n\nimport type { TelemetryEvent, TelemetryPort } from \"../../ports/telemetry\";\n\n/** Extract the domain from an email for telemetry (never the local part / PII). */\nfunction emailDomain(email: string): string | undefined {\n const at = email.lastIndexOf(\"@\");\n if (at < 0 || at === email.length - 1) return undefined;\n return email.slice(at + 1).toLowerCase();\n}\n\n/** Fire-and-forget emit through an optional port; never throws. */\nasync function emitOrgTelemetry(\n telemetry: TelemetryPort | undefined,\n event: TelemetryEvent,\n): Promise<void> {\n if (telemetry === undefined) return;\n await Effect.runPromise(\n telemetry.emit(event).pipe(\n Effect.catch((cause) =>\n Effect.sync(() => reportOrgTelemetryFailure(\"error\", event.name, cause)),\n ),\n Effect.catchDefect((cause) =>\n Effect.sync(() => reportOrgTelemetryFailure(\"defect\", event.name, cause)),\n ),\n ),\n );\n}\n\nexport function emitOrgCreateStarted(\n telemetry: TelemetryPort | undefined,\n input: { readonly template: string; readonly email?: string },\n): Promise<void> {\n const domain = input.email === undefined ? undefined : emailDomain(input.email);\n return emitOrgTelemetry(telemetry, {\n name: \"org_create_started\",\n props: {\n template: input.template,\n ...(domain === undefined ? {} : { email_domain: domain }),\n },\n });\n}\n\n/** Spread the `chainId` prop only when known — never emit a misleading `0`. */\nfunction chainIdProp(chainId: number | undefined): { chainId?: number } {\n return chainId === undefined ? {} : { chainId };\n}\n\nexport function emitOrgSafeCreated(\n telemetry: TelemetryPort | undefined,\n input: { readonly orgId: OrgId; readonly safeAddress: string; readonly chainId?: number },\n): Promise<void> {\n return emitOrgTelemetry(telemetry, {\n name: \"org_safe_created\",\n props: { org_id: input.orgId, safe_address: input.safeAddress, ...chainIdProp(input.chainId) },\n });\n}\n\nexport function emitOrgSafeConfirmed(\n telemetry: TelemetryPort | undefined,\n input: { readonly orgId: OrgId; readonly safeAddress: string; readonly chainId?: number },\n): Promise<void> {\n return emitOrgTelemetry(telemetry, {\n name: \"org_safe_confirmed\",\n props: { org_id: input.orgId, safe_address: input.safeAddress, ...chainIdProp(input.chainId) },\n });\n}\n\nexport function emitOrgRolesSeeded(\n telemetry: TelemetryPort | undefined,\n input: { readonly orgId: OrgId; readonly role: string },\n): Promise<void> {\n return emitOrgTelemetry(telemetry, {\n name: \"org_roles_seeded\",\n props: { org_id: input.orgId, role: input.role },\n });\n}\n\nexport function emitOrgCreated(\n telemetry: TelemetryPort | undefined,\n input: { readonly orgId: OrgId; readonly safeAddress: string; readonly chainId?: number },\n): Promise<void> {\n return emitOrgTelemetry(telemetry, {\n name: \"org_created\",\n props: { org_id: input.orgId, safe_address: input.safeAddress, ...chainIdProp(input.chainId) },\n });\n}\n\nexport function emitOrgCreateFailed(\n telemetry: TelemetryPort | undefined,\n reason: string,\n): Promise<void> {\n return emitOrgTelemetry(telemetry, { name: \"org_create_failed\", props: { reason } });\n}\n\nexport function emitOrgInviteSent(\n telemetry: TelemetryPort | undefined,\n input: {\n readonly orgId: OrgId;\n readonly email: string;\n readonly role: string;\n readonly status: string;\n },\n): Promise<void> {\n const domain = emailDomain(input.email);\n return emitOrgTelemetry(telemetry, {\n name: \"org_invite_sent\",\n props: {\n org_id: input.orgId,\n ...(domain === undefined ? {} : { email_domain: domain }),\n role: input.role,\n status: input.status,\n },\n });\n}\n\n// D3 (#565): the `org_spend_*` telemetry family was retired. An org spend is now\n// a KIND of Payment on the one ledger; its lifecycle is observed through the\n// `payment_*` / financial-ops telemetry, not a parallel org_spend dialect.\n\nfunction reportOrgTelemetryFailure(kind: \"error\" | \"defect\", name: string, cause: unknown): void {\n if (!isOrgTelemetryDebugEnabled()) return;\n globalThis.console?.warn?.(\"[capxul] org telemetry dropped\", { kind, name, cause });\n}\n\nfunction isOrgTelemetryDebugEnabled(): boolean {\n const processLike = globalThis as {\n readonly process?: { readonly env?: Record<string, string | undefined> };\n };\n return processLike.process?.env?.CAPXUL_DEBUG_TELEMETRY === \"1\";\n}\n","import { Errors, type CapxulError } from \"@capxul/config\";\nimport type { Address, SubAccountId } from \"@capxul/types\";\n\n/**\n * The role's allowed recipients. The address form backs the S4 `spend` path\n * (recipient is a resolved `Address`); the string form backs the G4\n * `spendViaPayments` / `batchPayroll` path, whose recipient is a VALIDATED REF\n * (handle/email/payee/org) compared in the same ref space as the role's set.\n * Comparison is case-insensitive over the raw string value either way.\n */\nexport type SpendGateRecipients = \"anyone\" | readonly (Address | string)[];\n\nexport type SpendGateSubAccountScope =\n | { readonly scope: \"all\" }\n | { readonly scope: \"only\"; readonly subAccountIds: readonly SubAccountId[] };\n\nexport interface EvaluateSpendGateInput {\n readonly activeMember: boolean;\n readonly subAccountId: SubAccountId;\n readonly subAccountBalanceRaw: string;\n readonly amountRaw: string;\n readonly currency: string;\n /** Resolved `Address` (S4 spend) or VALIDATED REF (G4 spendViaPayments). */\n readonly recipient: Address | string;\n readonly recipients: SpendGateRecipients;\n readonly subAccounts: SpendGateSubAccountScope;\n readonly perTxCapRaw?: string | null;\n readonly perDayCapRaw?: string | null;\n readonly spentTodayRaw?: string | null;\n}\n\nexport type SpendGateRejectReason =\n | \"not_member\"\n | \"over_cap\"\n | \"daily_cap_exhausted\"\n | \"wrong_envelope\"\n | \"invalid_recipient\"\n | \"insufficient_subaccount_balance\";\n\nexport type SpendGateDecision =\n | { readonly ok: true }\n | {\n readonly ok: false;\n readonly reason: SpendGateRejectReason;\n readonly error: CapxulError;\n };\n\nexport function evaluateSpendGate(input: EvaluateSpendGateInput): SpendGateDecision {\n if (!input.activeMember) {\n return reject(\"not_member\", Errors.invalidInput(\"member\", \"you are not an active member\"));\n }\n\n if (!recipientAllowed(input.recipients, input.recipient)) {\n return reject(\n \"invalid_recipient\",\n Errors.invalidRecipient(\"recipient is not allowed by this role\"),\n );\n }\n\n if (!subAccountAllowed(input.subAccounts, input.subAccountId)) {\n return reject(\n \"wrong_envelope\",\n Errors.invalidInput(\"subAccountId\", \"sub-account not in scope for this role\"),\n );\n }\n\n const amount = parseRaw(input.amountRaw, \"amountRaw\");\n const balance = parseRaw(input.subAccountBalanceRaw, \"subAccountBalanceRaw\");\n if (amount > balance) {\n return reject(\n \"insufficient_subaccount_balance\",\n Errors.insufficientBalance(input.currency, balance.toString(10), amount.toString(10)),\n );\n }\n\n const perTxCap = parseOptionalRaw(input.perTxCapRaw, \"perTxCapRaw\");\n if (perTxCap !== null && amount > perTxCap) {\n return reject(\n \"over_cap\",\n Errors.insufficientBalance(\n \"role per-transaction cap\",\n perTxCap.toString(10),\n amount.toString(10),\n ),\n );\n }\n\n const perDayCap = parseOptionalRaw(input.perDayCapRaw, \"perDayCapRaw\");\n if (perDayCap !== null) {\n const spentToday = parseOptionalRaw(input.spentTodayRaw, \"spentTodayRaw\") ?? 0n;\n const remaining = perDayCap - spentToday;\n if (remaining < amount) {\n return reject(\n \"daily_cap_exhausted\",\n Errors.insufficientBalance(\"role daily cap\", remaining.toString(10), amount.toString(10)),\n );\n }\n }\n\n return { ok: true };\n}\n\nfunction reject(reason: SpendGateRejectReason, error: CapxulError): SpendGateDecision {\n return { ok: false, reason, error } as const;\n}\n\nfunction recipientAllowed(recipients: SpendGateRecipients, recipient: Address | string): boolean {\n if (recipients === \"anyone\") return true;\n const normalized = String(recipient).toLowerCase();\n return recipients.some((allowed) => String(allowed).toLowerCase() === normalized);\n}\n\nfunction subAccountAllowed(scope: SpendGateSubAccountScope, subAccountId: SubAccountId): boolean {\n if (scope.scope === \"all\") return true;\n return scope.subAccountIds.includes(subAccountId);\n}\n\nfunction parseOptionalRaw(value: string | null | undefined, field: string): bigint | null {\n if (value === null || value === undefined) return null;\n return parseRaw(value, field);\n}\n\nfunction parseRaw(value: string, field: string): bigint {\n if (!/^[0-9]+$/.test(value)) {\n throw Errors.invalidInput(field, \"must be a non-negative integer string\");\n }\n return BigInt(value);\n}\n","// Effect program substrate for the Org method bundle (canon\n// `org-domain-model.md` §C2/§C3, D3/D10/D13). Mirrors `accounts-deps.ts`: a\n// `Context.Service` + `Layer` carrying the deps, and per-operation `*Program`\n// functions the public methods compose through `toCapxulResult`.\n//\n// Two enforcement modes:\n// - LIVE: an `OrgPort` performs the SDK-orchestrated deploy (D10) + RPC\n// `balanceOf` treasury read (D3). Supplied by the CLI/live-proof slice.\n// - HERMETIC (L1): NO port — `createOrg` builds an `OrgView` with a\n// deterministic counterfactual-shaped placeholder and a `$0` treasury, and\n// `treasury` returns `$0`. A fresh Org has no on-chain funds, so `$0` is\n// the correct deterministic answer and what the L1 hermetic proof pins.\n//\n// The org-creation telemetry funnel (canon §C5, J1) is woven in here as the\n// non-test producer for every `org_creation` catalog event.\n\nimport { Context, Effect, Layer } from \"effect\";\n\nimport {\n compileOrgRoleDefinitions,\n orgRoleKeyForLabel,\n orgRoleTemplateDefinitions,\n USDX_CURRENCY,\n USDX_DECIMALS,\n} from \"@capxul/config\";\nimport type { Account, Address, ChainId, Money, OrgId, SubAccountId } from \"@capxul/types\";\nimport {\n toAccountId,\n toAddress,\n toCurrencyCode,\n toEmail,\n toOrgId,\n toRoleKey,\n toSubAccountId,\n} from \"@capxul/types\";\n\nimport { fromWei } from \"../domain/money/from-wei\";\nimport { toWei } from \"../domain/money/to-wei\";\nimport type {\n OrgPort,\n OrgRolesDeploymentPort,\n OrgSpendAuthority,\n OrgSpendPort,\n} from \"../ports/org\";\nimport type { TelemetryPort } from \"../ports/telemetry\";\nimport { Errors, isCapxulError, type CapxulError } from \"@capxul/errors\";\n\nimport {\n emitOrgCreated,\n emitOrgCreateFailed,\n emitOrgCreateStarted,\n emitOrgInviteSent,\n emitOrgRolesSeeded,\n emitOrgSafeConfirmed,\n emitOrgSafeCreated,\n} from \"./_shared/org-telemetry\";\nimport type {\n AssignRoleInput,\n CreateOrgInput,\n DetectPendingOrgInvitationsResult,\n InviteMemberInput,\n MemberView,\n OrgView,\n OrgSpendViaPaymentsInput,\n OrgBatchPayrollInput,\n RemoveMemberInput,\n RoleDefinition,\n RoleView,\n} from \"./org\";\nimport {\n refToRecipientString,\n type DepositInstructions,\n type Payment,\n type PaymentMoney,\n type PaymentType,\n} from \"./money\";\nimport { evaluateSpendGate, type EvaluateSpendGateInput } from \"../domain/org/spend-gate\";\nimport type { OrgRoleDefinition } from \"@capxul/config\";\nimport type { ActorProfile } from \"./contacts\";\n\nexport interface OrgDeps {\n /** Live org seam (deploy + RPC treasury). Absent in the hermetic L1 path. */\n readonly orgPort?: OrgPort;\n readonly orgRolesDeploymentPort?: OrgRolesDeploymentPort;\n readonly orgSpendPort?: OrgSpendPort;\n /** Chain the org's treasury Account is read on (defaults to Base Sepolia). */\n readonly chainId?: ChainId;\n readonly telemetry?: TelemetryPort;\n}\n\nexport class OrgDepsTag extends Context.Service<OrgDepsTag, OrgDeps>()(\"@capxul/sdk/OrgDeps\") {}\n\nexport function orgDepsLayer(deps: OrgDeps): Layer.Layer<OrgDepsTag> {\n return Layer.succeed(OrgDepsTag, deps);\n}\n\nfunction isHermeticOrgDeps(deps: OrgDeps): boolean {\n return (\n deps.orgPort === undefined &&\n deps.orgRolesDeploymentPort === undefined &&\n deps.orgSpendPort === undefined\n );\n}\n\nfunction missingLiveOrgDep(portName: string): CapxulError {\n return Errors.invalidInput(\"orgDeps\", `${portName} is required in live org mode`);\n}\n\n/** Zero `Money` in the USDX-backed display currency (a fresh Org's treasury). */\nfunction zeroMoney(): Money {\n return fromWei(\"0\", USDX_DECIMALS, USDX_CURRENCY);\n}\n\n/** A fresh Org's treasury Account: `$0` balance, `available === balance`. */\nfunction zeroTreasury(orgId: OrgId): Account {\n const balance = zeroMoney();\n return {\n // Account ids are `account_`-shaped (NOT the Safe address, NOT the OrgId).\n // Hermetically derive a stable, valid id from the org handle/id seed.\n id: toAccountId(`account_${stripPrefix(orgId)}`),\n balance,\n available: balance,\n };\n}\n\n/** Drop a known `<prefix>_` so the remainder is reusable as another brand seed. */\nfunction stripPrefix(value: string): string {\n const underscore = value.indexOf(\"_\");\n const tail = underscore < 0 ? value : value.slice(underscore + 1);\n // Keep only the alphanumeric body so the `account_`/`org_` regexes accept it.\n const cleaned = tail.replace(/[^0-9A-Za-z]/g, \"\");\n return cleaned.length > 0 ? cleaned : \"0\";\n}\n\n/** Map an arbitrary string deterministically into lowercase hex chars. */\nfunction toHexSeed(value: string): string {\n let out = \"\";\n for (const ch of value) {\n out += (ch.codePointAt(0) ?? 0).toString(16).padStart(2, \"0\");\n }\n return out.length > 0 ? out : \"0\";\n}\n\n/**\n * Build the hermetic `OrgView` for the no-port L1 path: a deterministic\n * counterfactual-shaped placeholder Org Safe + a `$0` treasury (D3). The live\n * path replaces this with the real deployed address + RPC balance.\n */\nfunction hermeticOrgView(input: CreateOrgInput): OrgView {\n const orgId = toOrgId(`org_${stripPrefix(`x_${input.handle}`)}`);\n // A deterministic, well-formed lowercase 0x + 40 hex placeholder for the\n // hermetic path (the live path supplies the real `deriveCapxulOrgAddress`\n // counterfactual). Map the handle bytes into the hex alphabet so any handle\n // yields a valid `Address` shape.\n const placeholder = `0x${toHexSeed(input.handle).padEnd(40, \"0\").slice(0, 40)}`;\n return {\n id: orgId,\n name: input.name,\n handle: input.handle,\n safeAddress: toAddress(placeholder),\n // The founder is the creator → Owner role within their new org (D6/D7).\n role: \"Owner\",\n treasury: zeroTreasury(orgId),\n // #1064/#1061: hermetic path has no onboarding-collected extras.\n bio: null,\n size: null,\n logoUrl: null,\n };\n}\n\nfunction moneyFromConfig(input: {\n readonly currency: \"USD\";\n readonly value: string;\n readonly decimals: 6;\n}): Money {\n return {\n currency: toCurrencyCode(input.currency),\n value: input.value,\n decimals: input.decimals,\n };\n}\n\nfunction recipientsFromConfig(\n toRecipients: \"anyone\" | readonly string[] | undefined,\n): \"anyone\" | readonly Address[] | undefined {\n if (toRecipients === undefined || toRecipients === \"anyone\") return toRecipients;\n return toRecipients.map((recipient) => toAddress(recipient));\n}\n\nfunction subAccountsFromConfig(\n subAccounts: OrgRoleDefinition[\"subAccounts\"],\n): { readonly scope: \"all\" | readonly SubAccountId[] } | undefined {\n if (subAccounts === undefined) return undefined;\n if (subAccounts.scope === \"all\") return { scope: \"all\" };\n return { scope: subAccounts.scope.map((subAccountId) => toSubAccountId(subAccountId)) };\n}\n\nfunction roleDefinitionFromConfig(definition: OrgRoleDefinition): RoleDefinition {\n const toRecipients = recipientsFromConfig(definition.spend?.toRecipients);\n const subAccounts = subAccountsFromConfig(definition.subAccounts);\n return {\n label: definition.label,\n ...(definition.spend === undefined\n ? {}\n : {\n spend: {\n ...(definition.spend.perTx === undefined\n ? {}\n : { perTx: moneyFromConfig(definition.spend.perTx) }),\n ...(definition.spend.perDay === undefined\n ? {}\n : { perDay: moneyFromConfig(definition.spend.perDay) }),\n ...(toRecipients === undefined ? {} : { toRecipients }),\n },\n }),\n ...(subAccounts === undefined ? {} : { subAccounts }),\n ...(definition.canManageMembers === undefined\n ? {}\n : { canManageMembers: definition.canManageMembers }),\n ...(definition.canManageRoles === undefined\n ? {}\n : { canManageRoles: definition.canManageRoles }),\n };\n}\n\nfunction startupRoleViews(orgId: OrgId): readonly RoleView[] {\n const compiled = compileOrgRoleDefinitions(orgRoleTemplateDefinitions(\"Startup\"));\n return compiled.roles.map((role) => ({\n orgId,\n label: role.label,\n roleKey: toRoleKey(role.roleKey),\n definition: roleDefinitionFromConfig(role.definition),\n }));\n}\n\nfunction hermeticMember(input: {\n readonly orgId: OrgId;\n readonly email: string;\n readonly role: string;\n readonly status: \"pending\" | \"active\" | \"revoked\";\n readonly personalSafeAddress?: Address;\n readonly grantTxHash?: string | null;\n readonly revokeTxHash?: string | null;\n}): MemberView {\n return {\n orgId: input.orgId,\n email: toEmail(input.email),\n name: null,\n personalSafeAddress: input.personalSafeAddress ?? null,\n role: input.role,\n roleKey: toRoleKey(orgRoleKeyForLabel(input.role)),\n status: input.status,\n grantTxHash: input.grantTxHash ?? null,\n revokeTxHash: input.revokeTxHash ?? null,\n };\n}\n\n/**\n * The minimal `{from, to}` spend shape the gate + hermetic authority read off.\n * D3 (#565) removed the legacy `OrgSpendInput` (the address-keyed `org.spend`\n * lane); the leak-safe ref-based lane (`spendViaPayments`/`batchPayroll`)\n * constructs this shape internally with a placeholder `to` and enforces the real\n * validated recipient ref on the gate below.\n */\ntype SpendShape = {\n readonly from: SubAccountId;\n readonly to: Address;\n readonly amount: Money;\n};\n\nfunction hermeticSpendAuthority(input: SpendShape): OrgSpendAuthority {\n return {\n activeMember: true,\n subAccountBalanceRaw: \"100000000000\",\n recipients: \"anyone\",\n subAccounts: { scope: \"only\", subAccountIds: [input.from] },\n perTxCapRaw: \"25000000000\",\n perDayCapRaw: \"100000000000\",\n spentTodayRaw: \"0\",\n role: \"Finance Manager\",\n };\n}\n\nfunction spendGateInput(input: {\n readonly authority: OrgSpendAuthority;\n readonly spend: SpendShape;\n readonly amountRaw: string;\n readonly currency: string;\n}): EvaluateSpendGateInput {\n return {\n activeMember: input.authority.activeMember,\n subAccountId: input.spend.from,\n subAccountBalanceRaw: input.authority.subAccountBalanceRaw,\n amountRaw: input.amountRaw,\n currency: input.currency,\n recipient: input.spend.to,\n recipients: input.authority.recipients,\n subAccounts: input.authority.subAccounts,\n ...(input.authority.perTxCapRaw === undefined\n ? {}\n : { perTxCapRaw: input.authority.perTxCapRaw }),\n ...(input.authority.perDayCapRaw === undefined\n ? {}\n : { perDayCapRaw: input.authority.perDayCapRaw }),\n ...(input.authority.spentTodayRaw === undefined\n ? {}\n : { spentTodayRaw: input.authority.spentTodayRaw }),\n };\n}\n\nexport function createOrgProgram(\n input: CreateOrgInput,\n): Effect.Effect<OrgView, CapxulError, OrgDepsTag> {\n return Effect.gen(function* () {\n const deps = yield* OrgDepsTag;\n const chainId = deps.chainId;\n\n // SDK producer for the `org_creation` funnel (canon §C5, J1). Awaited (not\n // forked) on purpose — pins client-side causal ordering (`org_create_started`\n // strictly before the later steps), mirroring the money flow.\n yield* Effect.promise(() => emitOrgCreateStarted(deps.telemetry, { template: input.template }));\n\n const body = Effect.gen(function* () {\n // LIVE path — the port performs the SDK-orchestrated deploy (D10).\n if (deps.orgPort !== undefined) {\n const org = yield* deps.orgPort\n .createOrg({ input })\n .pipe(Effect.mapError((error) => error.publicError));\n yield* emitCreationFunnelTail(deps.telemetry, org, chainId);\n return org;\n }\n\n // HERMETIC path (L1) — deterministic `$0` org, no network.\n const org = hermeticOrgView(input);\n yield* emitCreationFunnelTail(deps.telemetry, org, chainId);\n return org;\n });\n\n // `org_create_failed` is the funnel's `drops_on` event (canon §C5, J1):\n // emit it (carrying the `CapxulErrorCode` as `reason`) before the failure\n // propagates, so a dropped creation is attributable. Fire-and-forget — the\n // telemetry emit never alters the original error.\n return yield* body.pipe(\n Effect.tapError((error) =>\n Effect.promise(() => emitOrgCreateFailed(deps.telemetry, error.code)),\n ),\n );\n });\n}\n\n/** Emit the remaining `org_creation` funnel steps once the org is built. */\nfunction emitCreationFunnelTail(\n telemetry: TelemetryPort | undefined,\n org: OrgView,\n chainId: ChainId | undefined,\n): Effect.Effect<void, never, never> {\n return Effect.promise(async () => {\n // Omit `chainId` when unknown (hermetic L1 has no chain) rather than\n // emitting a misleading `0` — the schema's `chainId` is optional.\n const chain = chainId === undefined ? {} : { chainId };\n await emitOrgSafeCreated(telemetry, {\n orgId: org.id,\n safeAddress: org.safeAddress,\n ...chain,\n });\n await emitOrgSafeConfirmed(telemetry, {\n orgId: org.id,\n safeAddress: org.safeAddress,\n ...chain,\n });\n await emitOrgRolesSeeded(telemetry, { orgId: org.id, role: org.role });\n await emitOrgCreated(telemetry, {\n orgId: org.id,\n safeAddress: org.safeAddress,\n ...chain,\n });\n });\n}\n\nexport function readTreasuryProgram(orgId: OrgId): Effect.Effect<Account, CapxulError, OrgDepsTag> {\n return Effect.gen(function* () {\n const deps = yield* OrgDepsTag;\n // LIVE path — RPC `balanceOf` over the Org Safe (D3).\n if (deps.orgPort !== undefined) {\n return yield* deps.orgPort\n .readTreasury({ orgId })\n .pipe(Effect.mapError((error) => error.publicError));\n }\n // HERMETIC path (L1) — a fresh org reads back at `$0` (D3).\n return zeroTreasury(orgId);\n });\n}\n\nfunction findOrgById(orgs: readonly OrgView[], orgId: OrgId): OrgView | undefined {\n return orgs.find((org) => String(org.id) === String(orgId));\n}\n\nfunction orgNotFound(orgId: OrgId): CapxulError {\n return Errors.invalidInput(\"orgId\", `org ${String(orgId)} was not found for this session`);\n}\n\nexport function readOrgProfileProgram(\n orgId: OrgId,\n): Effect.Effect<ActorProfile, CapxulError, OrgDepsTag> {\n return Effect.gen(function* () {\n const org = findOrgById(yield* listOrgsProgram(), orgId);\n if (org === undefined) return yield* Effect.fail(orgNotFound(orgId));\n return {\n actor: { kind: \"org\", orgId: String(orgId) },\n displayName: org.name,\n handle: org.handle,\n };\n });\n}\n\nexport function readOrgDepositInstructionsProgram(\n orgId: OrgId,\n): Effect.Effect<DepositInstructions, CapxulError, OrgDepsTag> {\n return Effect.gen(function* () {\n const deps = yield* OrgDepsTag;\n const org = findOrgById(yield* listOrgsProgram(), orgId);\n if (org === undefined) return yield* Effect.fail(orgNotFound(orgId));\n return {\n accountKind: \"orgTreasury\",\n chainId: Number(deps.chainId ?? 84_532),\n network: \"base-sepolia\",\n currency: \"USD\",\n address: String(org.safeAddress).toLowerCase(),\n label: \"Capxul org treasury\",\n };\n });\n}\n\nexport function listRolesProgram(\n orgId: OrgId,\n): Effect.Effect<readonly RoleView[], CapxulError, OrgDepsTag> {\n return Effect.gen(function* () {\n const deps = yield* OrgDepsTag;\n if (deps.orgPort !== undefined) {\n return yield* deps.orgPort\n .listRoles({ orgId })\n .pipe(Effect.mapError((error) => error.publicError));\n }\n return startupRoleViews(orgId);\n });\n}\n\nexport function deployRolesProgram(\n orgId: OrgId,\n): Effect.Effect<readonly RoleView[], CapxulError, OrgDepsTag> {\n return Effect.gen(function* () {\n const deps = yield* OrgDepsTag;\n if (deps.orgRolesDeploymentPort !== undefined) {\n const deployed = yield* deps.orgRolesDeploymentPort\n .deployRoles({ orgId })\n .pipe(Effect.mapError((error) => error.publicError));\n return deployed.roles;\n }\n if (!isHermeticOrgDeps(deps)) {\n return yield* Effect.fail(missingLiveOrgDep(\"orgRolesDeploymentPort\"));\n }\n return startupRoleViews(orgId);\n });\n}\n\nexport function listMembersProgram(\n orgId: OrgId,\n): Effect.Effect<readonly MemberView[], CapxulError, OrgDepsTag> {\n return Effect.gen(function* () {\n const deps = yield* OrgDepsTag;\n if (deps.orgPort !== undefined) {\n return yield* deps.orgPort\n .listMembers({ orgId })\n .pipe(Effect.mapError((error) => error.publicError));\n }\n return [];\n });\n}\n\nexport function inviteMemberProgram(\n orgId: OrgId,\n input: InviteMemberInput,\n): Effect.Effect<MemberView, CapxulError, OrgDepsTag> {\n return Effect.gen(function* () {\n const deps = yield* OrgDepsTag;\n const member =\n deps.orgPort !== undefined\n ? yield* deps.orgPort\n .inviteMember({ orgId, input })\n .pipe(Effect.mapError((error) => error.publicError))\n : hermeticMember({ orgId, email: input.email, role: input.role, status: \"pending\" });\n yield* Effect.promise(() =>\n emitOrgInviteSent(deps.telemetry, {\n orgId,\n email: input.email,\n role: member.role,\n status: member.status,\n }),\n );\n return member;\n });\n}\n\nexport function pendingMembersProgram(\n orgId: OrgId,\n): Effect.Effect<readonly MemberView[], CapxulError, OrgDepsTag> {\n return Effect.gen(function* () {\n const deps = yield* OrgDepsTag;\n if (deps.orgPort?.pendingMembers !== undefined) {\n return yield* deps.orgPort\n .pendingMembers({ orgId })\n .pipe(Effect.mapError((error) => error.publicError));\n }\n if (deps.orgPort !== undefined) {\n const members = yield* deps.orgPort\n .listMembers({ orgId })\n .pipe(Effect.mapError((error) => error.publicError));\n return members.filter(\n (member) =>\n member.status === \"pending\" ||\n member.status === \"pending_safe\" ||\n member.status === \"pending_grant\",\n );\n }\n return [];\n });\n}\n\nexport function resendInviteTokenProgram(\n orgId: OrgId,\n email: string,\n): Effect.Effect<MemberView, CapxulError, OrgDepsTag> {\n return Effect.gen(function* () {\n const deps = yield* OrgDepsTag;\n if (deps.orgPort?.resendInviteToken !== undefined) {\n return yield* deps.orgPort\n .resendInviteToken({ orgId, email })\n .pipe(Effect.mapError((error) => error.publicError));\n }\n if (!isHermeticOrgDeps(deps)) {\n return yield* Effect.fail(missingLiveOrgDep(\"orgPort.resendInviteToken\"));\n }\n return hermeticMember({ orgId, email, role: \"Member\", status: \"pending\" });\n });\n}\n\nexport function detectAndAcceptPendingInvitationsProgram(): Effect.Effect<\n DetectPendingOrgInvitationsResult,\n CapxulError,\n OrgDepsTag\n> {\n return Effect.gen(function* () {\n const deps = yield* OrgDepsTag;\n if (deps.orgPort !== undefined) {\n return yield* deps.orgPort\n .detectAndAcceptPendingInvitations({})\n .pipe(Effect.mapError((error) => error.publicError));\n }\n return { matched: [] };\n });\n}\n\nexport function assignRoleProgram(\n orgId: OrgId,\n input: AssignRoleInput,\n): Effect.Effect<MemberView, CapxulError, OrgDepsTag> {\n return Effect.gen(function* () {\n const deps = yield* OrgDepsTag;\n if (deps.orgRolesDeploymentPort !== undefined) {\n return yield* deps.orgRolesDeploymentPort\n .grantRole({ orgId, input })\n .pipe(Effect.mapError((error) => error.publicError));\n }\n if (!isHermeticOrgDeps(deps)) {\n return yield* Effect.fail(missingLiveOrgDep(\"orgRolesDeploymentPort\"));\n }\n return hermeticMember({\n orgId,\n email: \"member@example.com\",\n role: input.role,\n status: \"active\",\n personalSafeAddress: input.memberSafeAddress,\n grantTxHash: `0x${\"0\".repeat(64)}`,\n });\n });\n}\n\nexport function removeMemberProgram(\n orgId: OrgId,\n input: RemoveMemberInput,\n): Effect.Effect<void, CapxulError, OrgDepsTag> {\n return Effect.gen(function* () {\n const deps = yield* OrgDepsTag;\n if (deps.orgRolesDeploymentPort !== undefined) {\n return yield* deps.orgRolesDeploymentPort\n .revokeRole({ orgId, input })\n .pipe(Effect.mapError((error) => error.publicError));\n }\n if (!isHermeticOrgDeps(deps)) {\n return yield* Effect.fail(missingLiveOrgDep(\"orgRolesDeploymentPort\"));\n }\n });\n}\n\n// ── G4 (#547) — leak-safe org spend via the payments engine ──────────────────\n\n/**\n * Build a leak-safe settled `Payment` for an org spend (G4 · #547). NO `txHash`\n * / userOp / Safe internals and NO raw recipient address ever reach this record\n * — only the validated recipient ref label + the committed `documentHash`.\n */\nfunction leakSafeOrgPayment(input: {\n readonly orgId: OrgId;\n readonly to: string;\n readonly amount: Money;\n readonly paymentType: PaymentType;\n readonly documentHash?: string;\n readonly index: number;\n}): Payment {\n const now = Date.now();\n const id = `payment_${toHexSeed(`${input.orgId}:${input.to}:${input.amount.value}:${input.index}`)}`;\n const money: PaymentMoney = {\n currency: String(input.amount.currency),\n value: input.amount.value,\n decimals: input.amount.decimals,\n };\n return {\n id,\n status: \"settled\",\n amount: money,\n paymentType: input.paymentType,\n recipient: { kind: \"email\", label: input.to },\n documents:\n input.documentHash === undefined\n ? []\n : [\n {\n documentHash: input.documentHash,\n kind: input.paymentType === \"payroll\" ? \"payslip\" : \"memo\",\n },\n ],\n timing: { kind: \"instant\" },\n released: money,\n availableToClaim: { ...money, value: \"0\" },\n createdAt: now,\n updatedAt: now,\n };\n}\n\n/** Resolve authority + run the spend gate for one org spend run (G4 · #547). */\nfunction gateOneRun(input: {\n readonly deps: OrgDeps;\n readonly orgId: OrgId;\n readonly from: SubAccountId;\n readonly to: string;\n readonly amount: Money;\n /**\n * Raw USDX units already committed by EARLIER runs in the same batch (G4 #547).\n * Charged against BOTH the per-day cap (added to `spentToday`) and the\n * sub-account balance (subtracted) so a batch of in-per-tx runs that SUMS over\n * the day cap or the balance is rejected as a whole — no partial drain.\n */\n readonly accumulatedRaw?: string;\n}): Effect.Effect<\n { readonly authority: OrgSpendAuthority; readonly amountRaw: string },\n CapxulError,\n never\n> {\n return Effect.gen(function* () {\n const amountRaw = yield* Effect.try({\n try: () => toWei(input.amount),\n catch: (cause) =>\n Errors.invalidInput(\"amount\", cause instanceof Error ? cause.message : \"invalid money\"),\n });\n const currency = String(input.amount.currency);\n // The authority read derives the role's caps/recipient set from the org +\n // member; it does NOT key off the recipient, so the `from`/amount shape is\n // sufficient. The recipient axis is enforced by the gate below against the\n // REAL validated ref (NOT a fabricated zero address) — `recipients` for this\n // ref-based path is the role's allowed-ref set (or \"anyone\").\n const spendShaped: SpendShape = {\n from: input.from,\n to: toAddress(`0x${\"0\".repeat(40)}`),\n amount: input.amount,\n };\n const authority =\n input.deps.orgSpendPort === undefined\n ? hermeticSpendAuthority(spendShaped)\n : yield* input.deps.orgSpendPort\n .readSpendAuthority({ orgId: input.orgId, input: spendShaped, amountRaw })\n .pipe(Effect.mapError((error) => error.publicError));\n const accumulated = BigInt(input.accumulatedRaw ?? \"0\");\n const baseGateInput = spendGateInput({ authority, spend: spendShaped, amountRaw, currency });\n const decision = yield* Effect.try({\n try: () =>\n evaluateSpendGate({\n ...baseGateInput,\n // Enforce the recipient axis on the REAL validated ref — fixes the\n // zero-address substitution that silently disabled it (G4 #547).\n recipient: input.to,\n // Cross-run accumulation: charge prior runs against the day cap and the\n // balance so the batch's running total is bounded, not each run alone.\n subAccountBalanceRaw: subtractNonNegative(\n baseGateInput.subAccountBalanceRaw,\n accumulated,\n ),\n spentTodayRaw: (BigInt(authority.spentTodayRaw ?? \"0\") + accumulated).toString(10),\n }),\n catch: (cause) => (isCapxulError(cause) ? cause : Errors.unknown(cause)),\n });\n if (!decision.ok) return yield* Effect.fail(decision.error);\n return { authority, amountRaw };\n });\n}\n\n/** Subtract `delta` from a raw amount, flooring at zero (never negative). */\nfunction subtractNonNegative(raw: string, delta: bigint): string {\n const remaining = BigInt(raw) - delta;\n return (remaining < 0n ? 0n : remaining).toString(10);\n}\n\nexport function spendViaPaymentsProgram(\n orgId: OrgId,\n input: OrgSpendViaPaymentsInput,\n): Effect.Effect<Payment, CapxulError, OrgDepsTag> {\n return Effect.gen(function* () {\n const deps = yield* OrgDepsTag;\n if (deps.orgSpendPort === undefined && !isHermeticOrgDeps(deps)) {\n return yield* Effect.fail(missingLiveOrgDep(\"orgSpendPort\"));\n }\n const to = yield* Effect.try({\n try: () => refToRecipientString(input.to),\n catch: (cause) => (isCapxulError(cause) ? cause : Errors.invalidInput(\"to\", \"invalid Ref\")),\n });\n const gated = yield* gateOneRun({\n deps,\n orgId,\n from: input.from,\n to,\n amount: input.amount,\n });\n const paymentType = input.paymentType ?? \"unspecified\";\n\n if (deps.orgSpendPort?.submitSpendViaPayments !== undefined) {\n return yield* deps.orgSpendPort\n .submitSpendViaPayments({\n orgId,\n input,\n amountRaw: gated.amountRaw,\n authority: gated.authority,\n })\n .pipe(Effect.mapError((error) => error.publicError));\n }\n // Hermetic / adapter-without-payments-submit: build the leak-safe Payment\n // from the gated decision (the live adapter executes the on-chain spend).\n return leakSafeOrgPayment({ orgId, to, amount: input.amount, paymentType, index: 0 });\n });\n}\n\nexport function batchPayrollProgram(\n orgId: OrgId,\n input: OrgBatchPayrollInput,\n): Effect.Effect<readonly Payment[], CapxulError, OrgDepsTag> {\n return Effect.gen(function* () {\n const deps = yield* OrgDepsTag;\n if (deps.orgSpendPort === undefined && !isHermeticOrgDeps(deps)) {\n return yield* Effect.fail(missingLiveOrgDep(\"orgSpendPort\"));\n }\n if (input.runs.length === 0) {\n return yield* Effect.fail(\n Errors.invalidInput(\"runs\", \"payroll batch must include at least one run\"),\n );\n }\n // Gate EVERY run first — an over-cap run rejects the whole batch before any\n // submit, so a single bad row can never partially drain the treasury. Each\n // run is gated against the RUNNING TOTAL of the runs before it (G4 #547), so\n // a batch of in-per-tx runs that sums over the day cap / balance is rejected\n // as a whole rather than slipping through on independent per-run checks.\n const gated: { readonly authority: OrgSpendAuthority; readonly amountRaw: string }[] = [];\n const recipients = yield* Effect.try({\n try: () => input.runs.map((run) => refToRecipientString(run.to)),\n catch: (cause) => (isCapxulError(cause) ? cause : Errors.invalidInput(\"to\", \"invalid Ref\")),\n });\n let accumulatedRaw = 0n;\n for (const [index, run] of input.runs.entries()) {\n const result = yield* gateOneRun({\n deps,\n orgId,\n from: input.from,\n to: recipients[index]!,\n amount: run.amount,\n accumulatedRaw: accumulatedRaw.toString(10),\n });\n accumulatedRaw += BigInt(result.amountRaw);\n gated.push(result);\n }\n\n if (deps.orgSpendPort?.submitBatchPayroll !== undefined) {\n return yield* deps.orgSpendPort\n .submitBatchPayroll({\n orgId,\n from: input.from,\n runs: input.runs.map((run, index) => ({ run, amountRaw: gated[index]!.amountRaw })),\n authorities: gated.map((g) => g.authority),\n })\n .pipe(Effect.mapError((error) => error.publicError));\n }\n return input.runs.map((run, index) =>\n leakSafeOrgPayment({\n orgId,\n to: recipients[index]!,\n amount: run.amount,\n paymentType: \"payroll\",\n index,\n }),\n );\n });\n}\n\nexport function listOrgsProgram(): Effect.Effect<readonly OrgView[], CapxulError, OrgDepsTag> {\n return Effect.gen(function* () {\n const deps = yield* OrgDepsTag;\n if (deps.orgPort !== undefined) {\n return yield* deps.orgPort.listOrgs({}).pipe(Effect.mapError((error) => error.publicError));\n }\n // HERMETIC path (L1) — no orgs without a backend.\n return [];\n });\n}\n","import { Errors, type CapxulError } from \"@capxul/errors\";\nimport type { OrgId } from \"@capxul/types\";\nimport type { WireObservationContext } from \"@capxul/wire/observation-context\";\n\nimport type { CapxulResult } from \"./types\";\nimport { copyInvocationObservation } from \"../internal/invocation-observation\";\n\nexport type OrgSetupStep =\n | \"preparingFounderAccount\"\n | \"awaitingFounderAuthorization\"\n | \"submittingBootstrap\"\n | \"confirmingBootstrap\";\n\n/** Leak-safe readiness for exactly one Organization. */\nexport type OrgLifecycle =\n | { readonly status: \"loading\"; readonly orgId: OrgId }\n | {\n readonly status: \"settingUp\";\n readonly orgId: OrgId;\n readonly step: OrgSetupStep;\n }\n | { readonly status: \"ready\"; readonly orgId: OrgId; readonly canTransact: true }\n | {\n readonly status: \"failed\";\n readonly orgId: OrgId;\n readonly at: OrgSetupStep;\n readonly error: CapxulError;\n readonly retryable: boolean;\n };\n\nexport type StartOrResumeOrganizationInput = {\n readonly name: string;\n readonly handle: string;\n readonly country: string;\n /** #1064: optional onboarding-collected description + size bucket. */\n readonly bio?: string;\n readonly size?: string;\n /** @internal Safe trace/correlation carriage owned by the identity flow. */\n readonly observationContext?: WireObservationContext;\n};\n\nexport type OrganizationSetupStepInput = {\n readonly orgId: OrgId;\n readonly signal?: AbortSignal;\n /** @internal Safe trace/correlation carriage owned by the identity flow. */\n readonly observationContext?: WireObservationContext;\n};\n\nexport type RecordOrganizationSetupFailureInput = {\n readonly orgId: OrgId;\n readonly error: CapxulError;\n readonly retryable: boolean;\n /** @internal Safe trace/correlation carriage owned by the identity flow. */\n readonly observationContext?: WireObservationContext;\n};\n\n/**\n * Internal capability set used by the Core SDK's deep Organization boundary.\n * Consumers never coordinate these steps directly. Production composition\n * supplies them; hermetic contract tests provide a stateful implementation.\n */\nexport interface OrganizationSetupOps {\n startOrResume(\n input: StartOrResumeOrganizationInput,\n ): Promise<CapxulResult<{ readonly orgId: OrgId; readonly lifecycle: OrgLifecycle }>>;\n /** Completes and verifies the founder Account ownership handoff. */\n prepareFounderAccount(input: OrganizationSetupStepInput): Promise<CapxulResult<OrgLifecycle>>;\n /** Obtains configured signer authorization and submits the bootstrap once. */\n authorizeAndSubmitBootstrap(\n input: OrganizationSetupStepInput,\n ): Promise<CapxulResult<OrgLifecycle>>;\n /** Resumes a recorded provider-known submission without invoking the signer. */\n resumeSubmittedBootstrap(input: OrganizationSetupStepInput): Promise<CapxulResult<OrgLifecycle>>;\n /** Confirms a previously recorded submission without requesting authorization again. */\n confirmSubmittedBootstrap(input: OrganizationSetupStepInput): Promise<CapxulResult<OrgLifecycle>>;\n recordFailure(input: RecordOrganizationSetupFailureInput): Promise<CapxulResult<OrgLifecycle>>;\n loadLifecycle(input: {\n readonly orgId: OrgId;\n readonly observationContext?: WireObservationContext;\n }): Promise<CapxulResult<OrgLifecycle>>;\n /** Resets durable failure state only; the Core SDK resumes the correct step. */\n retry(input: OrganizationSetupStepInput): Promise<CapxulResult<OrgLifecycle>>;\n}\n\nfunction fail(error: CapxulError): CapxulResult<never> {\n return { ok: false, error };\n}\n\nexport function validateOrganizationLifecycleScope(\n orgId: OrgId,\n lifecycle: OrgLifecycle,\n): CapxulResult<OrgLifecycle> {\n if (String(lifecycle.orgId) !== String(orgId)) {\n return fail(Errors.invalidInput(\"orgId\", \"Organization lifecycle scope does not match\"));\n }\n return { ok: true, value: lifecycle };\n}\n\n/** Advance only the steps still required by one durable Organization lane. */\nexport async function advanceOrganizationSetup(\n setup: OrganizationSetupOps,\n orgId: OrgId,\n initial: OrgLifecycle,\n context?: { readonly signal?: AbortSignal | undefined; readonly observationSource?: unknown },\n): Promise<CapxulResult<OrgLifecycle>> {\n const { signal, observationSource } = context ?? {};\n const scopedInitial = validateOrganizationLifecycleScope(orgId, initial);\n if (!scopedInitial.ok) return scopedInitial;\n let lifecycle = scopedInitial.value;\n for (let transition = 0; transition < 3; transition += 1) {\n if (lifecycle.status !== \"settingUp\") {\n return { ok: true, value: lifecycle };\n }\n const currentStep = lifecycle.step;\n if (signal?.aborted) {\n const cancelled = Errors.cancelled({ operation: \"organization.setup\" });\n return recordSetupFailure(setup, orgId, cancelled, true, observationSource);\n }\n const stepInput = copyInvocationObservation(observationSource, {\n orgId,\n ...(signal === undefined ? {} : { signal }),\n });\n const next =\n lifecycle.step === \"preparingFounderAccount\"\n ? await setup.prepareFounderAccount(stepInput)\n : lifecycle.step === \"awaitingFounderAuthorization\"\n ? await setup.authorizeAndSubmitBootstrap(stepInput)\n : lifecycle.step === \"submittingBootstrap\"\n ? await setup.resumeSubmittedBootstrap(stepInput)\n : await setup.confirmSubmittedBootstrap(stepInput);\n if (!next.ok) {\n return recordSetupFailure(\n setup,\n orgId,\n next.error,\n isRetryableOrganizationSetupFailure(next.error),\n observationSource,\n );\n }\n const scopedNext = validateOrganizationLifecycleScope(orgId, next.value);\n if (!scopedNext.ok) {\n return recordSetupFailure(setup, orgId, scopedNext.error, false, observationSource);\n }\n lifecycle = scopedNext.value;\n // Confirmation is observational and may legitimately remain pending. Attempt\n // it once per public call; never spin or resubmit the recorded operation.\n if (currentStep === \"confirmingBootstrap\") {\n return { ok: true, value: lifecycle };\n }\n }\n if (lifecycle.status !== \"settingUp\" || lifecycle.step === \"confirmingBootstrap\") {\n return { ok: true, value: lifecycle };\n }\n return recordSetupFailure(\n setup,\n orgId,\n Errors.wrongState({\n method: \"organization.setup\",\n currentState: lifecycle.step,\n validStates: [\"confirmingBootstrap\", \"ready\", \"failed\"],\n }),\n false,\n observationSource,\n );\n}\n\nasync function recordSetupFailure(\n setup: OrganizationSetupOps,\n orgId: OrgId,\n error: CapxulError,\n retryable: boolean,\n observationSource?: unknown,\n): Promise<CapxulResult<OrgLifecycle>> {\n const recorded = await setup.recordFailure(\n copyInvocationObservation(observationSource, { orgId, error, retryable }),\n );\n if (!recorded.ok) return recorded;\n const scopedRecorded = validateOrganizationLifecycleScope(orgId, recorded.value);\n if (!scopedRecorded.ok) return scopedRecorded;\n return scopedRecorded;\n}\n\nfunction isRetryableProviderFailure(error: CapxulError): boolean {\n const mode = error.details?.failure_mode;\n return (\n mode !== \"auth-origin-mismatch\" && mode !== \"app-env-allowlist\" && mode !== \"no-secure-context\"\n );\n}\n\nfunction isRetryableOrganizationSetupFailure(error: CapxulError): boolean {\n if (error.code === \"CANCELLED\" || error.code === \"SIGNER_REJECTED\") return true;\n if (error.code === \"PROVIDER_ERROR\") return isRetryableProviderFailure(error);\n return error.code === \"NETWORK_ERROR\" || error.code === \"UNKNOWN\";\n}\n","// Public consumer-facing Org method surface for the Organization domain\n// (owned by `packages/sdk/CONTEXT.md` and `packages/backend/CONTEXT.md`).\n//\n// This is the LOCKED public surface the §C3 hooks call and the S1→S4 slices\n// fill. Planned UP FRONT per the capstone-first DoD — not discovered per slice.\n//\n// Shape (canon §C2/§C3, D13 explicit entity scoping — NO stateful active\n// context):\n//\n// - `capxul.createOrg(input)` — create an Org (S1)\n// - `capxul.orgs()` — list Orgs you belong to\n// - `capxul.org(orgId)` — entity-scoped bundle:\n// .treasury() → the real M2 `Account` over the Org Safe (D3)\n// .members() → MemberView[] (D8/D9)\n// .roles() → RoleView[] (D4/D6)\n// .invite(input) → invite-by-email (D8 virality loop)\n// .removeMember() → on-chain REVOKE + Convex mirror (D8)\n// .assignRole() → on-chain GRANT + Convex mirror (D7/D9)\n// .spendViaPayments(input) → leak-safe org spend on the one ledger (D5; D3 #565)\n//\n// Every method returns `Promise<CapxulResult<T>>`. RED behavior: each impl\n// resolves `Errors.notImplemented(\"org\", \"<verb>\")`; the slices replace each\n// one. Treasury reuses the M2 `Account` type verbatim (D3) — never\n// `AccountStatus` (that is the deploy-readiness ladder, no balance).\n//\n// Per `packages/sdk/CONTEXT.md` + `.claude/rules/flow-internal-substrate.md`:\n// named exports only, no Effect/flow-actor/program leak on the surface, every\n// return type is a real plain record. Per D13 the entity is always named\n// explicitly (`orgId` flows in via the scope factory) — there is NO global\n// \"acting as\" state.\n\nimport { Errors } from \"@capxul/errors\";\n\nimport {\n payrollContract,\n type PaymentPayload,\n type PayrollBackendPayslipTemplate,\n type PayrollBackendRosterLine,\n} from \"../contract/payroll\";\nimport type { PaymentDocumentEnvelopeV1 } from \"@capxul/wire\";\nimport type {\n Account,\n Address,\n ChainId,\n Email,\n Money,\n OrgId,\n RoleKey,\n SubAccountId,\n} from \"@capxul/types\";\n\nimport type { Payment, PaymentTiming, PaymentType, Ref } from \"./money\";\nimport { copyInvocationObservation } from \"../internal/invocation-observation\";\n\nimport type { OrgPort, OrgRolesDeploymentPort, OrgSpendPort } from \"../ports/org\";\nimport type { ConvexCallPort } from \"../ports/convex-call\";\nimport type { TelemetryPort } from \"../ports/telemetry\";\nimport {\n assignRoleProgram,\n batchPayrollProgram,\n createOrgProgram,\n detectAndAcceptPendingInvitationsProgram,\n deployRolesProgram,\n inviteMemberProgram,\n listMembersProgram,\n listRolesProgram,\n listOrgsProgram,\n orgDepsLayer,\n readOrgDepositInstructionsProgram,\n readOrgProfileProgram,\n readTreasuryProgram,\n removeMemberProgram,\n spendViaPaymentsProgram,\n} from \"./org-deps\";\nimport { toCapxulResult } from \"./to-capxul-result\";\nimport type { CapxulResult } from \"./types\";\nimport {\n advanceOrganizationSetup,\n validateOrganizationLifecycleScope,\n type OrganizationSetupOps,\n type OrgLifecycle,\n} from \"./org-lifecycle\";\nimport {\n makeActorRelationshipMethods,\n normalizeRefForBackend,\n type ActorRelationshipMethods,\n} from \"./contacts\";\nimport { runIfActive } from \"./to-capxul-result\";\n\n/**\n * A member's lifecycle status (D9 — unified `Member` with status\n * `pending | active | revoked | expired`). `pending` = invited (incl. a\n * non-user emailed into existence) but not yet a provisioned member with an\n * on-chain grant; `active` = on-chain role granted; `revoked` = offboarded\n * (on-chain REVOKE fired); `expired` = pending invitation timed out.\n */\nexport type MemberStatus =\n | \"pending\"\n | \"pending_safe\"\n | \"pending_grant\"\n | \"active\"\n | \"revoked\"\n | \"expired\";\n\n/**\n * One Org you belong to (canon §C1 \"Org list\" — name, role, balance).\n * `role` is the member's role label within THIS org. `treasury` is the M2\n * `Account` over the Org Safe (D3). `handle` is the globally-unique,\n * normalized org handle (D10a). Pure record of brand-typed fields — not a\n * brand.\n */\nexport type OrgView = {\n readonly id: OrgId;\n readonly name: string;\n readonly handle: string;\n readonly safeAddress: Address;\n /** The viewing member's own role label within this org. */\n readonly role: string;\n /** The Org treasury — the real M2 Account over the Org Safe (D3). */\n readonly treasury: Account;\n /** #1064: onboarding-collected description + size bucket; null when unset. */\n readonly bio: string | null;\n readonly size: string | null;\n /** #1061 / ADR-0014: logo serving URL resolved at read time; null when unset. */\n readonly logoUrl: string | null;\n};\n\nexport interface OrganizationAccount {\n readonly id: string;\n readonly address: string | null;\n readonly balance: Money;\n readonly available: Money;\n}\n\nexport interface OrganizationAuditLogItem {\n readonly id: string;\n readonly organizationId: string;\n readonly action: string;\n readonly actor: string | null;\n readonly summary: string;\n readonly createdAt: number;\n readonly metadata?: Record<string, unknown>;\n}\n\n/**\n * One member of an Org (canon §C1 \"Members\" — name/email, role, status; D7/D8).\n * `personalSafeAddress` is the member-identity key (D7 — Safe-as-identity); it\n * is `null` while the member is still `pending` (emailed into existence but not\n * yet provisioned a personal Safe). `email` is the universal entry point (D8).\n */\nexport type MemberView = {\n readonly orgId: OrgId;\n readonly email: Email;\n readonly name: string | null;\n /** Member-identity key (D7). `null` until the invitee provisions a Safe. */\n readonly personalSafeAddress: Address | null;\n /** The member's role label (maps deterministically to the on-chain `roleKey`, D9). */\n readonly role: string;\n readonly roleKey: RoleKey | null;\n readonly status: MemberStatus;\n readonly grantTxHash: string | null;\n readonly revokeTxHash: string | null;\n};\n\n/**\n * A role's on-chain Level-1 spend cap (D4/D5 — physically enforced via Zodiac\n * Roles + Allowance). `perTx` / `perDay` are `Money`; `toRecipients` scopes the\n * allowed recipient set. Omitting a field means \"unbounded on that axis\"\n * (the Owner role).\n */\nexport type RoleSpendCap = {\n readonly perTx?: Money;\n readonly perDay?: Money;\n readonly toRecipients?: \"anyone\" | readonly Address[];\n};\n\n/**\n * The Capxul-owned Role DSL definition (D4). `label` becomes the sticky\n * bytes32 `roleKey` on-chain. `spend` compiles to Level-1 on-chain Zodiac\n * conditions; `subAccounts` + `canManage*` compile to Level-2 off-chain Convex\n * guards (D5).\n */\nexport type RoleDefinition = {\n readonly label: string;\n // Level 1 — on-chain (Zodiac Roles + Allowance), physically enforced:\n readonly spend?: RoleSpendCap;\n // Level 2 — off-chain (Convex), business logic:\n readonly subAccounts?: { readonly scope: \"all\" | readonly SubAccountId[] };\n readonly canManageMembers?: boolean;\n readonly canManageRoles?: boolean;\n};\n\n/**\n * One role seeded on an Org (canon §C1 \"Roles\" — label + caps; D4/D6).\n * `roleKey` is the on-chain bytes32 role key derived from the label. `definition`\n * is the full Role DSL entry.\n */\nexport type RoleView = {\n readonly orgId: OrgId;\n readonly label: string;\n readonly roleKey: RoleKey;\n readonly definition: RoleDefinition;\n};\n\n/** Built-in role templates that seed a new Org at creation (D6). */\nexport type OrgTemplate = \"Solo\" | \"Startup\" | \"Custom\";\n\n/**\n * Input to `capxul.createOrg` (S1, D10a, D14). `name` is the display name;\n * `handle` is the globally-unique normalized handle (`^[a-z0-9-]{3,32}$`, D10a);\n * `template` seeds the initial role set (D6); `country` is stored unvalidated\n * (D14 — KYB deferred). For `template: \"Custom\"`, `roles` carries the authored\n * `RoleDefinition[]`.\n */\nexport type CreateOrgInput = {\n readonly name: string;\n readonly handle: string;\n readonly template: OrgTemplate;\n readonly country?: string;\n readonly roles?: readonly RoleDefinition[];\n};\n\n/**\n * Input to `org(orgId).invite` (S3, D8). Email is the universal entry point —\n * inviting an address that is not yet a Capxul user auto-creates a `pending`\n * membership that resolves on sign-in (the virality loop). `role` names the\n * role label the invitee is granted on accept.\n */\nexport type InviteMemberInput = {\n readonly email: string;\n readonly role: string;\n};\n\nexport type ResendInviteTokenInput = {\n readonly email: string;\n};\n\n/**\n * Input to `org(orgId).removeMember` (S3, D8). Keyed on the member's personal\n * Safe address (D7 — Safe-as-identity). Drives the on-chain REVOKE + Convex\n * mirror.\n */\nexport type RemoveMemberInput = {\n readonly memberSafeAddress: Address;\n};\n\n/**\n * Input to `org(orgId).assignRole` (S3, D7/D9). Keyed on the member's personal\n * Safe address (D7). Drives the on-chain GRANT + Convex mirror; the `role`\n * label maps deterministically to the on-chain `roleKey`.\n */\nexport type AssignRoleInput = {\n readonly memberSafeAddress: Address;\n readonly role: string;\n};\n\n/**\n * Input to `org(orgId).spendViaPayments` (G4 · #547). The LEAK-SAFE org spend:\n * delegates `org.spend` to the payments engine WITH the member's org role\n * authority and returns a `Payment`, not a `txHash`. `to` is a VALIDATED\n * recipient ref (handle / email / payee id / org handle) — never a raw\n * `Address` (the legacy address-keyed `org.spend` lane was hard-removed in D3\n * #565 when `orgSpends` was folded into the one `payments` ledger).\n * `from` is the Level-2 sub-account envelope the spend draws from (D5).\n */\nexport type OrgSpendViaPaymentsInput = {\n readonly from: SubAccountId;\n /** Validated recipient ref (handle/email/payee/org) — never a raw address. */\n readonly to: Ref;\n readonly amount: Money;\n /** Full EIP-712 payment document; hashed + stored, committed on-chain. */\n readonly document?: PaymentDocumentEnvelopeV1;\n readonly timing?: PaymentTiming;\n readonly paymentType?: PaymentType;\n};\n\n/**\n * One run in an `org(orgId).batchPayroll` batch (G4 · #547): a validated\n * recipient, an amount, and an optional payslip document. Each run is gated\n * independently against the role's per-tx / per-day / recipient conditions.\n */\nexport type OrgPayrollRun = {\n /** Validated recipient ref (handle/email/payee/org) — never a raw address. */\n readonly to: Ref;\n readonly amount: Money;\n readonly timing?: PaymentTiming;\n /** The payslip — an EIP-712 payment document, committed by `documentHash`. */\n readonly payslip?: PaymentDocumentEnvelopeV1;\n};\n\n/**\n * Input to `org(orgId).batchPayroll` (G4 · #547). Pays N employees in one\n * MultiSend through the Roles modifier; each carries a payslip and settles as\n * `paymentType = payroll`. Every run is gated; an over-cap run REJECTS the\n * whole batch (no partial treasury drain). Returns one leak-safe `Payment` per\n * run.\n */\nexport type OrgBatchPayrollInput = {\n readonly from: SubAccountId;\n readonly runs: readonly OrgPayrollRun[];\n};\n\nexport type DetectPendingOrgInvitationsResult = {\n readonly matched: readonly OrgId[];\n};\n\n/**\n * Entity-scoped Org method bundle, returned by `capxul.org(orgId)`. Every\n * method names the entity implicitly via the closed-over `orgId` (D13 — no\n * stateful active context). `treasury()` returns the real M2 `Account` over\n * the Org Safe (D3).\n */\nexport interface PayrollRosterLine {\n readonly id: string;\n readonly employee: Ref;\n readonly amount: Money;\n readonly timing: PaymentTiming;\n readonly status: \"active\" | \"paused\" | \"ended\";\n}\n\nexport interface PayrollPayslipTemplate {\n readonly title: string;\n readonly memo?: string;\n}\n\nexport interface PayrollRosterAddInput {\n readonly employee: Ref;\n readonly amount: Money;\n readonly timing: PaymentTiming;\n readonly payslipTemplate?: PaymentDocumentEnvelopeV1 | PayrollPayslipTemplate;\n}\n\nexport interface PayrollRunInput {\n readonly from: SubAccountId;\n readonly period: string;\n}\n\nexport interface PayrollMethods {\n readonly roster: {\n add(\n input: PayrollRosterAddInput,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<PayrollRosterLine>>;\n list(options?: {\n readonly signal?: AbortSignal;\n }): Promise<CapxulResult<readonly PayrollRosterLine[]>>;\n update(\n rosterLineId: string,\n input: Partial<PayrollRosterAddInput>,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<PayrollRosterLine>>;\n remove(\n rosterLineId: string,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<PayrollRosterLine>>;\n };\n run(\n input: PayrollRunInput,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<readonly Payment[]>>;\n}\n\nexport interface OrgScopedMethods extends ActorRelationshipMethods {\n /** Observe the durable, leak-safe lifecycle for this Organization only. */\n getLifecycle(options?: { readonly signal?: AbortSignal }): Promise<CapxulResult<OrgLifecycle>>;\n /** Explicitly resume this Organization's durable setup lane. */\n retrySetup(options?: { readonly signal?: AbortSignal }): Promise<CapxulResult<OrgLifecycle>>;\n /** The Org treasury — the real M2 Account over the Org Safe (D3). */\n treasury(options?: { readonly signal?: AbortSignal }): Promise<CapxulResult<Account>>;\n readonly account: {\n get(options?: { readonly signal?: AbortSignal }): Promise<CapxulResult<OrganizationAccount>>;\n };\n members(options?: {\n readonly signal?: AbortSignal;\n }): Promise<CapxulResult<readonly MemberView[]>>;\n roles(options?: { readonly signal?: AbortSignal }): Promise<CapxulResult<readonly RoleView[]>>;\n deployRoles(options?: {\n readonly signal?: AbortSignal;\n }): Promise<CapxulResult<readonly RoleView[]>>;\n invite(\n input: InviteMemberInput,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<MemberView>>;\n removeMember(\n input: RemoveMemberInput,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<void>>;\n assignRole(\n input: AssignRoleInput,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<MemberView>>;\n /**\n * Leak-safe org spend (G4 · #547; D3 #565 — the one ledger of record): execute\n * the spend through the payments engine with the member's org role authority\n * and return a `Payment` (no `to: Address`, no `txHash`, no Safe / userOp\n * internals). Writes a real `payments` row (`source:\"org\"`).\n */\n spendViaPayments(\n input: OrgSpendViaPaymentsInput,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<Payment>>;\n /**\n * Org payroll batch (G4 · #547): pay N employees in one MultiSend through the\n * Roles modifier, each with a payslip. Every run is gated; an over-cap run\n * rejects the whole batch. Returns one leak-safe `Payment` per run.\n */\n batchPayroll(\n input: OrgBatchPayrollInput,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<readonly Payment[]>>;\n readonly payroll: PayrollMethods;\n auditLog(options?: {\n readonly signal?: AbortSignal;\n }): Promise<CapxulResult<readonly OrganizationAuditLogItem[]>>;\n}\n\nexport type OrgsMethod = {\n (options?: { readonly signal?: AbortSignal }): Promise<CapxulResult<readonly OrgView[]>>;\n detectAndAcceptPendingInvitations(options?: {\n readonly signal?: AbortSignal;\n }): Promise<CapxulResult<DetectPendingOrgInvitationsResult>>;\n};\n\n/**\n * Top-level Org method bundle, exposed at `client.org` / `client.orgs` /\n * `client.createOrg`. `org(orgId)` resolves the entity-scoped bundle (D13).\n */\nexport interface OrgMethods {\n createOrg(\n input: CreateOrgInput,\n options?: { readonly signal?: AbortSignal },\n ): Promise<CapxulResult<OrgView>>;\n readonly orgs: OrgsMethod;\n /** Resolve the entity-scoped bundle for a specific Org (D13). */\n org(orgId: OrgId): OrgScopedMethods;\n}\n\nexport interface MakeOrgMethodsDeps {\n readonly organizationSetup?: OrganizationSetupOps;\n /**\n * Live org seam (canon D10 SDK-orchestrated deploy + D3 RPC treasury read).\n * Absent in the hermetic L1 path — `createOrg` then builds a deterministic\n * `$0` org and `treasury` returns `$0` (a fresh Org has no on-chain funds).\n */\n readonly orgPort?: OrgPort;\n readonly orgRolesDeploymentPort?: OrgRolesDeploymentPort;\n readonly orgSpendPort?: OrgSpendPort;\n /** Chain the org treasury Account is read on (defaults to Base Sepolia). */\n readonly chainId?: ChainId;\n readonly telemetry?: TelemetryPort;\n /** Convex function-call seam for org relationship and payroll projections. */\n readonly convexCall?: ConvexCallPort;\n}\n\n/**\n * Org method surface (canon §C2/§C3, D13). S1 (#274) wires `createOrg` /\n * `orgs` / `treasury` to their Effect programs (`org-deps.ts`); the S2→S4\n * member/role/spend verbs stay `Errors.notImplemented(\"org\", \"<verb>\")` until\n * their slices land. The entity-scoped bundle is constructed per `org(orgId)`\n * call (D13 — explicit scoping, no shared mutable \"active org\" state); the\n * closed-over `orgId` is the only entity reference.\n */\nexport function makeOrgMethods(deps: MakeOrgMethodsDeps): OrgMethods {\n const layer = orgDepsLayer({\n ...(deps.orgPort === undefined ? {} : { orgPort: deps.orgPort }),\n ...(deps.orgRolesDeploymentPort === undefined\n ? {}\n : { orgRolesDeploymentPort: deps.orgRolesDeploymentPort }),\n ...(deps.orgSpendPort === undefined ? {} : { orgSpendPort: deps.orgSpendPort }),\n ...(deps.chainId === undefined ? {} : { chainId: deps.chainId }),\n ...(deps.telemetry === undefined ? {} : { telemetry: deps.telemetry }),\n });\n\n const orgs: OrgsMethod = Object.assign(\n (options?: { readonly signal?: AbortSignal }): Promise<CapxulResult<readonly OrgView[]>> => {\n if (options?.signal?.aborted) {\n return Promise.resolve({ ok: false, error: Errors.cancelled({ operation: \"org.orgs\" }) });\n }\n return toCapxulResult(listOrgsProgram(), layer);\n },\n {\n detectAndAcceptPendingInvitations(options?: {\n readonly signal?: AbortSignal;\n }): Promise<CapxulResult<DetectPendingOrgInvitationsResult>> {\n if (options?.signal?.aborted) {\n return Promise.resolve({\n ok: false,\n error: Errors.cancelled({ operation: \"orgs.detectAndAcceptPendingInvitations\" }),\n });\n }\n return toCapxulResult(detectAndAcceptPendingInvitationsProgram(), layer);\n },\n },\n );\n\n return {\n createOrg(input, options) {\n if (options?.signal?.aborted) {\n return Promise.resolve({\n ok: false,\n error: Errors.cancelled({ operation: \"org.createOrg\" }),\n });\n }\n return toCapxulResult(createOrgProgram(input), layer);\n },\n orgs,\n org(orgId: OrgId): OrgScopedMethods {\n const convexCall = deps.convexCall;\n return {\n ...makeActorRelationshipMethods({\n actor: { kind: \"org\", orgId: String(orgId) },\n ...(convexCall === undefined ? {} : { convexCall }),\n }),\n async getLifecycle(options) {\n if (options?.signal?.aborted) {\n return {\n ok: false,\n error: Errors.cancelled({ operation: \"org.getLifecycle\" }),\n };\n }\n if (deps.organizationSetup === undefined) {\n return {\n ok: false,\n error: Errors.notImplemented(\"organizationSetup\", \"getLifecycle\"),\n };\n }\n const loaded = await deps.organizationSetup.loadLifecycle({ orgId });\n if (!loaded.ok) return loaded;\n return validateOrganizationLifecycleScope(orgId, loaded.value);\n },\n async retrySetup(options) {\n if (options?.signal?.aborted) {\n return {\n ok: false,\n error: Errors.cancelled({ operation: \"org.retrySetup\" }),\n };\n }\n const setup = deps.organizationSetup;\n if (setup === undefined) {\n return {\n ok: false,\n error: Errors.notImplemented(\"organizationSetup\", \"retrySetup\"),\n };\n }\n const retried = await setup.retry(\n copyInvocationObservation(options, {\n orgId,\n ...(options?.signal === undefined ? {} : { signal: options.signal }),\n }),\n );\n if (!retried.ok) return retried;\n return advanceOrganizationSetup(setup, orgId, retried.value, {\n signal: options?.signal,\n observationSource: options,\n });\n },\n profile: {\n get(_options) {\n if (_options?.signal?.aborted) {\n return Promise.resolve({\n ok: false,\n error: Errors.cancelled({ operation: \"org.profile.get\" }),\n });\n }\n return toCapxulResult(readOrgProfileProgram(orgId), layer);\n },\n depositInstructions(_options) {\n if (_options?.signal?.aborted) {\n return Promise.resolve({\n ok: false,\n error: Errors.cancelled({ operation: \"org.profile.depositInstructions\" }),\n });\n }\n return toCapxulResult(readOrgDepositInstructionsProgram(orgId), layer);\n },\n },\n treasury(options) {\n if (options?.signal?.aborted) {\n return Promise.resolve({\n ok: false,\n error: Errors.cancelled({ operation: \"org.treasury\" }),\n });\n }\n return toCapxulResult(readTreasuryProgram(orgId), layer);\n },\n account: {\n async get(options) {\n if (options?.signal?.aborted) {\n return {\n ok: false,\n error: Errors.cancelled({ operation: \"org.account.get\" }),\n };\n }\n const treasury = await toCapxulResult(readTreasuryProgram(orgId), layer);\n if (!treasury.ok) return { ok: false, error: treasury.error };\n const orgList = await toCapxulResult(listOrgsProgram(), layer);\n if (!orgList.ok) return { ok: false, error: orgList.error };\n const org = orgList.value.find((candidate) => candidate.id === orgId);\n return {\n ok: true,\n value: {\n id: treasury.value.id,\n address: org?.safeAddress ?? null,\n balance: treasury.value.balance,\n available: treasury.value.available,\n },\n };\n },\n },\n members(_options) {\n if (_options?.signal?.aborted) {\n return Promise.resolve({\n ok: false,\n error: Errors.cancelled({ operation: \"org.members\" }),\n });\n }\n return toCapxulResult(listMembersProgram(orgId), layer);\n },\n roles(_options) {\n if (_options?.signal?.aborted) {\n return Promise.resolve({\n ok: false,\n error: Errors.cancelled({ operation: \"org.roles\" }),\n });\n }\n return toCapxulResult(listRolesProgram(orgId), layer);\n },\n deployRoles(_options) {\n if (_options?.signal?.aborted) {\n return Promise.resolve({\n ok: false,\n error: Errors.cancelled({ operation: \"org.deployRoles\" }),\n });\n }\n return toCapxulResult(deployRolesProgram(orgId), layer);\n },\n invite(_input, _options) {\n if (_options?.signal?.aborted) {\n return Promise.resolve({\n ok: false,\n error: Errors.cancelled({ operation: \"org.invite\" }),\n });\n }\n return toCapxulResult(inviteMemberProgram(orgId, _input), layer);\n },\n removeMember(_input, _options) {\n if (_options?.signal?.aborted) {\n return Promise.resolve({\n ok: false,\n error: Errors.cancelled({ operation: \"org.removeMember\" }),\n });\n }\n return toCapxulResult(removeMemberProgram(orgId, _input), layer);\n },\n assignRole(_input, _options) {\n if (_options?.signal?.aborted) {\n return Promise.resolve({\n ok: false,\n error: Errors.cancelled({ operation: \"org.assignRole\" }),\n });\n }\n return toCapxulResult(assignRoleProgram(orgId, _input), layer);\n },\n spendViaPayments(_input, _options) {\n if (_options?.signal?.aborted) {\n return Promise.resolve({\n ok: false,\n error: Errors.cancelled({ operation: \"org.spendViaPayments\" }),\n });\n }\n return toCapxulResult(spendViaPaymentsProgram(orgId, _input), layer);\n },\n batchPayroll(_input, _options) {\n if (_options?.signal?.aborted) {\n return Promise.resolve({\n ok: false,\n error: Errors.cancelled({ operation: \"org.batchPayroll\" }),\n });\n }\n return toCapxulResult(batchPayrollProgram(orgId, _input), layer);\n },\n auditLog(_options) {\n if (_options?.signal?.aborted) {\n return Promise.resolve({\n ok: false,\n error: Errors.cancelled({ operation: \"org.auditLog\" }),\n });\n }\n return Promise.resolve({\n ok: false,\n error: Errors.notImplemented(\"organizationAuditLog\", \"list\"),\n });\n },\n payroll:\n convexCall === undefined\n ? makeNotImplementedPayrollMethods()\n : makePayrollMethods({ orgId: String(orgId), convexCall }),\n };\n },\n };\n}\n\nfunction makePayrollMethods(deps: {\n readonly orgId: string;\n readonly convexCall: ConvexCallPort;\n}): PayrollMethods {\n const fns = payrollContract;\n return {\n roster: {\n add: async (input, options) => {\n const employee = normalizeRefForBackend(input.employee, \"employee\");\n if (!employee.ok) return employee;\n return mapOk(\n runIfActive(options?.signal, \"payroll.roster.add\", () =>\n deps.convexCall.mutation(fns.add, {\n orgId: deps.orgId,\n employee: employee.value,\n amount: input.amount,\n timing: input.timing,\n payslipTemplate: toPayrollTemplate(input.payslipTemplate),\n }),\n ),\n mapPayrollRosterLine,\n );\n },\n list: (options) =>\n mapOk(\n runIfActive(options?.signal, \"payroll.roster.list\", () =>\n deps.convexCall.query(fns.list, { orgId: deps.orgId }),\n ),\n (lines) => lines.map(mapPayrollRosterLine),\n ),\n update: async (rosterLineId, input, options) => {\n const employee =\n input.employee === undefined\n ? undefined\n : normalizeRefForBackend(input.employee, \"employee\");\n if (employee !== undefined && !employee.ok) return employee;\n return mapOk(\n runIfActive(options?.signal, \"payroll.roster.update\", () =>\n deps.convexCall.mutation(fns.update, {\n orgId: deps.orgId,\n rosterLineId,\n ...(employee === undefined ? {} : { employee: employee.value }),\n ...(input.amount === undefined ? {} : { amount: input.amount }),\n ...(input.timing === undefined ? {} : { timing: input.timing }),\n ...(input.payslipTemplate === undefined\n ? {}\n : { payslipTemplate: toPayrollTemplate(input.payslipTemplate) }),\n }),\n ),\n mapPayrollRosterLine,\n );\n },\n remove: (rosterLineId, options) =>\n mapOk(\n runIfActive(options?.signal, \"payroll.roster.remove\", () =>\n deps.convexCall.mutation(fns.remove, { orgId: deps.orgId, rosterLineId }),\n ),\n mapPayrollRosterLine,\n ),\n },\n run: (input, options) =>\n mapOk(\n runIfActive(options?.signal, \"payroll.run\", () =>\n deps.convexCall.mutation(fns.run, {\n orgId: deps.orgId,\n period: input.period,\n from: String(input.from),\n }),\n ),\n (run) => run.payments.map(normalizePaymentTiming),\n ),\n };\n}\n\nfunction makeNotImplementedPayrollMethods(): PayrollMethods {\n return {\n roster: {\n add: () => missingConvexCall(\"payroll.roster.add\"),\n list: () => missingConvexCall(\"payroll.roster.list\"),\n update: () => missingConvexCall(\"payroll.roster.update\"),\n remove: () => missingConvexCall(\"payroll.roster.remove\"),\n },\n run: () => missingConvexCall(\"payroll.run\"),\n };\n}\n\nfunction missingConvexCall<T>(operation: string): Promise<CapxulResult<T>> {\n return Promise.resolve({\n ok: false,\n error: Errors.providerError(\"convex\", operation, \"ConvexCallPort is required\"),\n });\n}\n\nasync function mapOk<T, U>(\n resultOrPromise: CapxulResult<T> | Promise<CapxulResult<T>>,\n f: (value: T) => U,\n): Promise<CapxulResult<U>> {\n const result = await resultOrPromise;\n if (!result.ok) return result;\n return { ok: true, value: f(result.value) };\n}\n\nfunction mapPayrollRosterLine(line: PayrollBackendRosterLine): PayrollRosterLine {\n return {\n id: line.id,\n employee: line.employee,\n amount: line.amount,\n timing: line.timing,\n status: line.status === \"removed\" ? \"ended\" : line.status,\n };\n}\n\nfunction toPayrollTemplate(\n document: PaymentDocumentEnvelopeV1 | PayrollPayslipTemplate | undefined,\n): PayrollBackendPayslipTemplate {\n if (document === undefined) return { title: \"Payroll\" };\n if (\"title\" in document) {\n return {\n title: document.title,\n ...(typeof document.memo === \"string\" ? { memo: document.memo } : {}),\n };\n }\n if (document.primaryType === \"Payslip\") {\n return { title: `Payslip ${document.message.period}` };\n }\n if (\"reference\" in document.message) {\n return { title: document.primaryType, memo: document.message.reference };\n }\n return { title: document.primaryType };\n}\n\nfunction normalizePaymentTiming(payment: PaymentPayload): Payment {\n const { release: _release, ...rest } = payment;\n return {\n ...rest,\n timing: payment.timing ?? payment.release ?? { kind: \"instant\" },\n };\n}\n","// detectAuthCacheAdapter — browser-clean auto-detect (SDK publish readiness · I1).\n// Selects the AuthCachePort adapter for the default `@capxul/sdk` entry:\n//\n// - `globalThis.window?.localStorage` defined → BrowserAuthCacheAdapter\n// - else → InMemoryAuthCacheAdapter\n//\n// The Node filesystem adapter pulls in `@effect/platform-node`, which must NOT\n// reach a browser-shaped bundle (published-package-boundaries.md). Node\n// consumers that want on-disk persistence import `detectNodeAuthCacheAdapter`\n// (or `FileSystemAuthCacheAdapter`) from `@capxul/sdk/node` and pass it as\n// `createCapxulClient({ authCache })`.\n\nimport { BrowserAuthCacheAdapter } from \"../adapters/auth-cache/BrowserAuthCacheAdapter\";\nimport { InMemoryAuthCacheAdapter } from \"../adapters/auth-cache/InMemoryAuthCacheAdapter\";\nimport type { AuthCachePort } from \"../ports/auth-cache\";\nimport type { WindowLike } from \"./window-like\";\n\nexport function detectAuthCacheAdapter(): AuthCachePort {\n const globalAny = globalThis as unknown as {\n readonly window?: WindowLike;\n };\n if (globalAny.window?.localStorage !== undefined) {\n return new BrowserAuthCacheAdapter(globalAny.window.localStorage);\n }\n return new InMemoryAuthCacheAdapter();\n}\n","import { EXPECTED_OPERATION_OUTCOMES, isCapxulError, type CapxulErrorCode } from \"@capxul/errors\";\nimport {\n sanitizeObservationContext,\n type WireObservationContext,\n} from \"@capxul/wire/observation-context\";\n\nimport sdkPackageJson from \"../package.json\" with { type: \"json\" };\nimport {\n markFailureInvocationSnapshot,\n readFailureInvocationSnapshot,\n type InvocationObservationSnapshot,\n} from \"./internal/invocation-observation\";\nimport { EXCEPTION_MESSAGE } from \"./telemetry/capture-exception\";\n\n/** Host-owned correlation fields that are safe to attach to an SDK failure. */\nexport interface ObservationContext extends Omit<WireObservationContext, \"applicationId\"> {}\n\n/**\n * The small, SDK-owned failure envelope delivered to observation adapters.\n * Method arguments, response bodies, wallet payloads, and arbitrary error\n * details are deliberately absent.\n */\nexport interface SdkFailureObservation {\n readonly exception: Error;\n readonly sdkVersion: string;\n readonly operation: string;\n readonly errorKind: string;\n /** Invocation snapshot; failure correlation wins over later host state. */\n readonly context?: ObservationContext;\n}\n\nexport type ObservationDelivery = void | PromiseLike<void>;\n\n/**\n * High-level host observation boundary. The SDK owns when each method is\n * called; the host owns the destination client, consent, and delivery policy.\n */\nexport interface ObservationAdapter {\n /**\n * Optional read-only invocation context. Transport adapters snapshot it once\n * at call start; implementations must not mutate global SDK state.\n */\n readonly resolveContext?: () => ObservationContext | undefined;\n /** A method returned the SDK's typed `{ ok: false, error }` result. */\n captureOperationFailure(failure: SdkFailureObservation): ObservationDelivery;\n /** A method unexpectedly threw or rejected instead of returning a typed result. */\n captureException(exception: SdkFailureObservation): ObservationDelivery;\n}\n\n/** The host-owned PostHog capabilities consumed by the supported adapter. */\nexport interface PostHogObservationClient {\n capture(event: string, properties?: Readonly<Record<string, unknown>>): unknown;\n /** Optional host capability; the supported adapter uses ordinary capture for slim clients. */\n captureException?(exception: Error, properties?: Readonly<Record<string, unknown>>): unknown;\n}\nimport type { PostHogHostPolicy } from \"./host-observability\";\n\nconst SDK_VERSION = sdkPackageJson.version;\n\n/** Stable PostHog event used for typed failures that are expected product outcomes. */\nexport const CAPXUL_SDK_EXPECTED_OUTCOME_EVENT = \"capxul_sdk_expected_outcome\";\n\n/**\n * Adapt the host's already-initialized PostHog-like client. This function does\n * not import, initialize, configure, or own PostHog.\n */\nexport function postHogFailureObservation(\n policy: PostHogHostPolicy,\n fixedSnapshot?: InvocationObservationSnapshot,\n): ObservationAdapter {\n const prepare = (\n failure: SdkFailureObservation,\n ): readonly [SdkFailureObservation, Readonly<Record<string, unknown>>] | undefined => {\n const callStartSnapshot = readFailureInvocationSnapshot(failure) ?? fixedSnapshot;\n const directSnapshot = callStartSnapshot === undefined ? policy.snapshot() : undefined;\n if (\n !(callStartSnapshot?.active ?? directSnapshot?.active) ||\n policy.client === null ||\n policy.client === undefined\n ) {\n return;\n }\n\n const safeFailure = sanitizeFailureObservation(failure);\n const directContext = callStartSnapshot?.context ?? directSnapshot?.context;\n const properties = postHogProperties(safeFailure, directContext);\n return [safeFailure, properties];\n };\n\n const captureOperationFailure = (failure: SdkFailureObservation): void => {\n const prepared = prepare(failure);\n if (prepared === undefined || policy.client === null || policy.client === undefined) return;\n const [safeFailure, properties] = prepared;\n\n if (classifyOperationOutcome(safeFailure.errorKind) === \"expected\") {\n policy.deliver(() =>\n policy.client!.capture(CAPXUL_SDK_EXPECTED_OUTCOME_EVENT, {\n ...properties,\n outcome_class: \"expected\",\n }),\n );\n return;\n }\n\n policy.deliver(() =>\n policy.client!.capture(\"$exception\", postHogExceptionProperties(safeFailure, properties)),\n );\n };\n\n const captureException = (failure: SdkFailureObservation): void => {\n const prepared = prepare(failure);\n if (prepared === undefined || policy.client === null || policy.client === undefined) return;\n const [safeFailure, properties] = prepared;\n policy.deliver(() =>\n policy.client!.capture(\"$exception\", postHogExceptionProperties(safeFailure, properties)),\n );\n };\n\n return {\n resolveContext: () => {\n const snapshot = fixedSnapshot ?? policy.snapshot();\n if (!snapshot.active) return undefined;\n // Raw call-start snapshot: each consumer sanitizes at its own emission\n // boundary, so the pure sanitize is kept off the SDK success path.\n return snapshot.context ?? {};\n },\n captureOperationFailure,\n captureException,\n };\n}\n\nfunction classifyOperationOutcome(kind: string): \"expected\" | \"unexpected\" {\n return EXPECTED_OPERATION_OUTCOMES.has(kind as CapxulErrorCode) ? \"expected\" : \"unexpected\";\n}\n\n/**\n * Fan one SDK failure out to several adapters (issue #877). The SDK's own\n * first-party relay and an optional host-provided adapter both observe the same\n * failure. Order matters for `resolveContext`: the FIRST adapter that returns a\n * context wins, so pass the host adapter first to keep its call-start snapshot.\n * Each capture is isolated — a throwing adapter never blocks its peers or the\n * SDK. Returns `undefined` when no adapters are present (zero observation work).\n */\nexport function composeObservationAdapters(\n ...adapters: readonly (ObservationAdapter | undefined)[]\n): ObservationAdapter | undefined {\n const present = adapters.filter(\n (adapter): adapter is ObservationAdapter => adapter !== undefined,\n );\n if (present.length === 0) return undefined;\n if (present.length === 1) return present[0];\n\n const fanOut = (select: (adapter: ObservationAdapter) => ObservationDelivery): void => {\n for (const adapter of present) {\n try {\n ignoreDeliveryFailure(select(adapter));\n } catch {\n // One adapter's defect is isolated from its peers and the SDK.\n }\n }\n };\n\n return {\n resolveContext: () => {\n for (const adapter of present) {\n try {\n const context = adapter.resolveContext?.();\n if (context !== undefined) return context;\n } catch {\n // Fall through to the next adapter's snapshot.\n }\n }\n return undefined;\n },\n captureOperationFailure: (failure) =>\n fanOut((adapter) => adapter.captureOperationFailure(failure)),\n captureException: (failure) => fanOut((adapter) => adapter.captureException(failure)),\n };\n}\n\n/** @internal Reports a factory-level typed failure without changing its identity. */\nexport function observeFailedResult<T extends { readonly ok: boolean }>(\n result: T,\n adapter: ObservationAdapter | undefined,\n operation: string,\n): T {\n if (adapter !== undefined && isFailedResult(result)) {\n report(adapter, \"operation\", operation, result.error, resolveAdapterContext(adapter));\n }\n return result;\n}\n\nfunction report(\n adapter: ObservationAdapter,\n kind: \"operation\" | \"exception\",\n operation: string,\n cause: unknown,\n invocationContext?: ObservationContext,\n): void {\n const operationName = normalizeOperation(operation);\n const kindName = normalizeErrorKind(errorKind(cause));\n const context = sanitizeObservationContext({\n ...invocationContext,\n ...(isCapxulError(cause) && cause.correlationId !== undefined\n ? { correlationId: cause.correlationId }\n : {}),\n }) as ObservationContext | undefined;\n const failure = markFailureInvocationSnapshot<SdkFailureObservation>(\n {\n exception: syntheticException(operationName, kindName),\n sdkVersion: SDK_VERSION,\n operation: operationName,\n errorKind: kindName,\n ...(context === undefined ? {} : { context }),\n },\n {\n active: invocationContext !== undefined,\n ...(context === undefined ? {} : { context }),\n },\n );\n\n try {\n const delivery =\n kind === \"operation\"\n ? adapter.captureOperationFailure(failure)\n : adapter.captureException(failure);\n ignoreDeliveryFailure(delivery);\n } catch {\n // Adapter failures are isolated from SDK return values and control flow.\n }\n}\n\nfunction resolveAdapterContext(adapter: ObservationAdapter): ObservationContext | undefined {\n // The adapter snapshot is the raw call-start context. Sanitize is deferred to\n // failure time in `report` and to each transport's own emission boundary, so\n // a successful call pays no per-call sanitize cost.\n try {\n return adapter.resolveContext?.();\n } catch {\n return undefined;\n }\n}\n\nfunction ignoreDeliveryFailure(delivery: unknown): void {\n if (!isPromiseLike(delivery)) return;\n try {\n void Promise.resolve(delivery).catch(() => undefined);\n } catch {\n // A malformed thenable is an adapter defect, not an SDK failure.\n }\n}\n\n/**\n * Map an ALREADY-sanitized observation context to the snake_case PostHog\n * property keys. Shared by the failure boundary here and the host\n * success-telemetry seam (`telemetry/from-posthog.ts`) so both attach identical\n * correlation fields from one definition.\n */\nexport function observationContextProps(\n context: WireObservationContext | undefined,\n): Record<string, string> {\n const props: Record<string, string> = {};\n if (context?.application !== undefined) props.application = context.application;\n if (context?.release !== undefined) props.release = context.release;\n if (context?.sessionId !== undefined) props.session_id = context.sessionId;\n if (context?.organizationId !== undefined) props.organization_id = context.organizationId;\n if (context?.journeyId !== undefined) props.journey_id = context.journeyId;\n if (context?.correlationId !== undefined) props.correlation_id = context.correlationId;\n if (context?.anonymousId !== undefined) props.anonymous_id = context.anonymousId;\n return props;\n}\n\nfunction postHogProperties(\n failure: SdkFailureObservation,\n context: ObservationContext | undefined,\n): Readonly<Record<string, unknown>> {\n const merged = sanitizeObservationContext({ ...context, ...failure.context });\n return {\n sdk_version: failure.sdkVersion,\n operation: failure.operation,\n error_kind: failure.errorKind,\n handled: true,\n ...observationContextProps(merged),\n };\n}\n\nfunction postHogExceptionProperties(\n failure: SdkFailureObservation,\n properties: Readonly<Record<string, unknown>>,\n): Readonly<Record<string, unknown>> {\n const filename = `capxul-sdk-observation://boundary/${failure.operation}`;\n return {\n ...properties,\n $exception_type: failure.errorKind,\n $exception_message: EXCEPTION_MESSAGE,\n $exception_level: \"error\",\n $exception_list: [\n {\n type: failure.errorKind,\n value: EXCEPTION_MESSAGE,\n mechanism: { type: \"capxul_sdk_boundary\", handled: true, synthetic: true },\n stacktrace: {\n type: \"raw\",\n frames: [\n {\n platform: \"javascript\",\n filename,\n function: `CapxulSdkBoundary.${failure.operation}`,\n lineno: 1,\n colno: 1,\n in_app: true,\n },\n ],\n },\n },\n ],\n };\n}\n\nfunction errorKind(cause: unknown): string {\n try {\n if (isCapxulError(cause)) return normalizeErrorKind(cause.code);\n if (cause instanceof Error) return normalizeErrorKind(cause.name);\n return \"UnknownFailure\";\n } catch {\n return \"Error\";\n }\n}\n\nfunction sanitizeFailureObservation(failure: SdkFailureObservation): SdkFailureObservation {\n const operation = normalizeOperation(failure.operation);\n const kind = normalizeErrorKind(failure.errorKind);\n const context = sanitizeObservationContext(failure.context) as ObservationContext | undefined;\n return {\n exception: syntheticException(operation, kind),\n sdkVersion: normalizeSdkVersion(failure.sdkVersion),\n operation,\n errorKind: kind,\n ...(context === undefined ? {} : { context }),\n };\n}\n\nfunction normalizeSdkVersion(value: unknown): string {\n return typeof value === \"string\" && /^[A-Za-z0-9][A-Za-z0-9.+_-]{0,127}$/u.test(value)\n ? value\n : \"unknown\";\n}\n\nfunction normalizeOperation(value: unknown): string {\n return typeof value === \"string\" && /^[A-Za-z0-9_][A-Za-z0-9_.-]{0,255}$/u.test(value)\n ? value\n : \"unknown\";\n}\n\nfunction normalizeErrorKind(value: unknown): string {\n return typeof value === \"string\" && /^[A-Za-z][A-Za-z0-9_.-]{0,63}$/u.test(value)\n ? value\n : \"Error\";\n}\n\nfunction syntheticException(operation: string, kind: string): Error {\n const error = new Error(EXCEPTION_MESSAGE);\n error.name = kind;\n error.stack =\n `${kind}: ${error.message}\\n` +\n ` at CapxulSdkBoundary.${operation} ` +\n `(capxul-sdk-observation://boundary/${operation}:1:1)`;\n return error;\n}\n\nfunction isPromiseLike(value: unknown): value is PromiseLike<unknown> {\n return (\n (typeof value === \"object\" || typeof value === \"function\") &&\n value !== null &&\n typeof (value as { readonly then?: unknown }).then === \"function\"\n );\n}\n\nfunction isPlainObject(value: unknown): value is Record<PropertyKey, unknown> {\n if (typeof value !== \"object\" || value === null) return false;\n const prototype = Object.getPrototypeOf(value) as unknown;\n return prototype === Object.prototype || prototype === null;\n}\n\nfunction isCapxulResult(\n value: unknown,\n): value is\n | { readonly ok: true; readonly value: unknown }\n | { readonly ok: false; error: unknown } {\n return isPlainObject(value) && typeof value.ok === \"boolean\";\n}\n\nfunction isFailedResult(value: unknown): value is { readonly ok: false; readonly error: unknown } {\n return isCapxulResult(value) && value.ok === false && \"error\" in value;\n}\n","// Internal product projection for the one host observability module. The host\n// passes its own already-initialized posthog-js client; the SDK's rich events\n// (`org_created`, `faucet_requested`, `transfer_requested`, …) are delivered to\n// it and, because it is the same client the consumer called `identify()` on,\n// they attach to the browser person and light up the journey funnel.\n//\n// The SDK never imports, initializes, configures, or owns posthog. Event props\n// are PII-redacted by the shared `PostHogTelemetryAdapter`; the host-owned\n// context is sanitized with the SAME `sanitizeObservationContext` the failure\n// path uses; and the `$exception` `details` blob (amounts / org names / account\n// IDs — the one field the shared redactor has no rule for) is dropped at this\n// host boundary — so no addresses, names, or amounts reach the host sink\n// (infra#1037).\n\nimport { stampTelemetryEnvelope } from \"@capxul/observability\";\n\nimport { PostHogTelemetryAdapter } from \"../adapters/telemetry/PostHogTelemetryAdapter\";\nimport type { PostHogHostPolicy } from \"../host-observability\";\nimport {\n readInvocationObservation,\n type InvocationObservationSnapshot,\n} from \"../internal/invocation-observation\";\nimport { observationContextProps } from \"../observation\";\nimport type { TelemetryPort, TelemetryProps } from \"../ports/telemetry\";\n\nconst PRODUCT_INVOCATION = Symbol(\"capxul.product-telemetry-invocation\");\n\ntype InvocationBindableTelemetry = TelemetryPort & {\n readonly [PRODUCT_INVOCATION]?: (source: unknown) => TelemetryPort;\n};\n\n/** @internal Bind paired emit/identify/reset work to one call-start snapshot. */\nexport function bindProductTelemetryInvocation(\n telemetry: TelemetryPort,\n source: unknown,\n): TelemetryPort {\n return (telemetry as InvocationBindableTelemetry)[PRODUCT_INVOCATION]?.(source) ?? telemetry;\n}\n\n/**\n * Drop props that must never cross to a host-owned external sink. Today that is\n * the `$exception` `details` blob: `captureException` serializes\n * `CapxulError.details` (e.g. `{ asset, available, required }`, `{ name }`,\n * `{ accountId }` — errors.ts) into it, and the shared redactor has no\n * `$exception` rule, so it is stripped here at the boundary (infra#1037). The\n * safe fields (error code, operation, failure_mode, the fixed leak-safe message,\n * stack frames) are preserved.\n */\nfunction stripHostUnsafeProps(props: TelemetryProps | undefined): TelemetryProps | undefined {\n if (props === undefined) return undefined;\n const { details: _details, ...safe } = props;\n return safe;\n}\n\n/**\n * The subset of a posthog-js client the seam calls. `identify` / `group` /\n * `reset` are optional — a host that only wants event capture can omit them.\n */\n/**\n * Adapt the host's already-initialized posthog-like client into a\n * `TelemetryPort` for the `telemetry` prop / input. This port SUPPLANTS the\n * SDK's no-op default telemetry sink (`production.ts` binds it via\n * `Layer.succeed`, not `compose` — there is no client-side success relay to\n * compose with); it is additive to Capxul's backend first-party record and\n * never owns the client.\n */\nexport function postHogProductTelemetry(\n policy: PostHogHostPolicy,\n fixedSnapshot?: InvocationObservationSnapshot,\n): TelemetryPort {\n // Reuse the existing adapter for per-event PII redaction, prop cloning, and\n // fire-and-forget isolation; the deps here add consent gating + context merge.\n const telemetry = new PostHogTelemetryAdapter({\n capture: (name, props, source) => {\n const snapshot = readInvocationObservation(source) ?? fixedSnapshot ?? policy.snapshot();\n if (!snapshot.active || policy.client === null || policy.client === undefined) return;\n const event = stampTelemetryEnvelope(\n { name, props },\n { capxul_env: policy.capxulEnv, producer: \"sdk\" },\n );\n policy.deliver(() =>\n policy.client!.capture(name, {\n ...stripHostUnsafeProps(event.props),\n ...observationContextProps(snapshot.context),\n }),\n );\n },\n // NOTE: identify traits / group properties are forwarded structurally and are\n // NOT run through the per-event redactor the capture arm relies on. Callers\n // MUST pre-minimize them (send `email_domain`, never a raw email). Do not\n // pass raw PII here — it would reach the host un-redacted.\n identify: (input) => {\n if (!(fixedSnapshot ?? policy.snapshot()).active || policy.client?.identify === undefined)\n return;\n policy.deliver(() =>\n policy.client!.identify!(input.distinctId, { ...input.traits, ...input.properties }),\n );\n },\n group: (input) => {\n if (!(fixedSnapshot ?? policy.snapshot()).active || policy.client?.group === undefined)\n return;\n policy.deliver(() =>\n policy.client!.group!(\n input.groupType,\n input.groupKey,\n input.properties === undefined ? undefined : { ...input.properties },\n ),\n );\n },\n reset: () => {\n if (!(fixedSnapshot ?? policy.snapshot()).active || policy.client?.reset === undefined)\n return;\n policy.deliver(() => policy.client!.reset!());\n },\n });\n Object.defineProperty(telemetry, PRODUCT_INVOCATION, {\n enumerable: false,\n value: (source: unknown) =>\n postHogProductTelemetry(\n policy,\n readInvocationObservation(source) ?? fixedSnapshot ?? policy.snapshot(),\n ),\n });\n return telemetry;\n}\n","import { Effect } from \"effect\";\n\nimport {\n IDENTITY_EVENT_TAGS,\n type IdentityEventTag,\n type IdentityState,\n} from \"../domain/identity/model.ts\";\nimport type { IdentityTransition } from \"../domain/machine/shell.ts\";\nimport { copyInvocationObservation } from \"../internal/invocation-observation.ts\";\nimport type { TelemetryEvent, TelemetryPort } from \"../ports/telemetry.ts\";\nimport { bindProductTelemetryInvocation } from \"./from-posthog.ts\";\n\nexport type IdentityProductObservation = TelemetryEvent | null;\n\nconst NONE: IdentityProductObservation = null;\nconst IDENTITY_EVENT_TAG_SET: ReadonlySet<string> = new Set(IDENTITY_EVENT_TAGS);\n\ntype AppliedAction = \"none\" | \"otp-requested\" | \"verified\" | \"signed-out\" | \"failed\";\n\nconst APPLIED_ACTION_BY_EVENT = {\n RequestOtp: \"none\",\n VerifyOtp: \"none\",\n ReadSession: \"none\",\n SignOut: \"none\",\n RestoreSession: \"none\",\n ResumeOtpEntry: \"none\",\n Reset: \"none\",\n EnsureAccount: \"none\",\n ClaimAccount: \"none\",\n RetryAccount: \"none\",\n CreateOrganization: \"none\",\n AttachOrganization: \"none\",\n RetryOrganization: \"none\",\n LeaveOrganization: \"none\",\n OtpSent: \"otp-requested\",\n OtpFailed: \"failed\",\n Verified: \"verified\",\n VerifyFailed: \"failed\",\n SessionRead: \"none\",\n SessionReadFailed: \"none\",\n SignedOut: \"signed-out\",\n SignOutFailed: \"failed\",\n AccountAt: \"none\",\n AccountDerived: \"none\",\n AccountClaiming: \"none\",\n AccountClaimed: \"none\",\n AccountFailed: \"none\",\n OrgAt: \"none\",\n OrgReady: \"none\",\n OrgFailed: \"none\",\n} as const satisfies Record<IdentityEventTag, AppliedAction>;\n\nconst linkage = (record: IdentityTransition) => ({\n ...(record.correlation_id === undefined ? {} : { correlation_id: record.correlation_id }),\n ...(record.journey_id === undefined ? {} : { journey_id: record.journey_id }),\n});\n\nconst emailDomain = (email: string): string => email.split(\"@\")[1]?.toLowerCase() ?? \"unknown\";\n\nconst authFailure = (record: IdentityTransition, reason: string): IdentityProductObservation => ({\n name: \"auth_failed\",\n props: { auth_type: \"otp\", reason, ...linkage(record) },\n});\n\nexport function mapIdentityProductObservation(\n record: IdentityTransition,\n state: IdentityState,\n): IdentityProductObservation {\n if (record.machine !== \"identity\" || !IDENTITY_EVENT_TAG_SET.has(record.event)) return NONE;\n if (record.outcome === \"cancelled\") return NONE;\n if (record.slot === \"identity:auth\" && record.outcome === \"refused\") {\n return authFailure(record, record.refusal_code);\n }\n if (record.slot === \"identity:auth\" && record.outcome === \"failed\") {\n return authFailure(record, record.error_code);\n }\n if (record.outcome !== \"applied\") return NONE;\n switch (APPLIED_ACTION_BY_EVENT[record.event as IdentityEventTag]) {\n case \"none\":\n return NONE;\n case \"failed\":\n return state.phase !== \"faulted\" || state.failure.code === \"CANCELLED\"\n ? NONE\n : authFailure(record, state.failure.code);\n case \"otp-requested\":\n return state.phase !== \"otp_pending\"\n ? NONE\n : {\n name: \"auth_otp_requested\",\n props: { email_domain: emailDomain(state.email), ...linkage(record) },\n };\n case \"verified\":\n return state.phase !== \"authenticated\"\n ? NONE\n : {\n name: \"auth_verified\",\n props: { auth_type: \"otp\", ...linkage(record) },\n };\n case \"signed-out\":\n return state.phase !== \"signed_out\"\n ? NONE\n : {\n name: \"auth_signed_out\",\n props: linkage(record),\n };\n }\n}\n\nconst ignoreTransportFailure = (\n operation: () => Effect.Effect<void, never>,\n operationName: \"emit\" | \"identify\" | \"reset\",\n eventName: TelemetryEvent[\"name\"],\n): Effect.Effect<void, never> =>\n Effect.suspend(operation).pipe(\n Effect.catchCause(() =>\n Effect.logWarning(\"identity.product.telemetry.dropped\").pipe(\n Effect.annotateLogs({ operation: operationName, product_event: eventName }),\n Effect.catchCause(() => Effect.void),\n ),\n ),\n );\n\nexport function executeIdentityProductObservation(\n telemetry: TelemetryPort,\n record: IdentityTransition,\n state: IdentityState,\n): Effect.Effect<void, never> {\n const mapped = mapIdentityProductObservation(record, state);\n if (mapped === null) return Effect.void;\n copyInvocationObservation(record, mapped);\n const invocationTelemetry = bindProductTelemetryInvocation(telemetry, mapped);\n const after = (): Effect.Effect<void, never> =>\n mapped.name === \"auth_verified\" && state.phase === \"authenticated\"\n ? invocationTelemetry.identify({\n distinctId: state.session.authUserId,\n traits: { email_domain: emailDomain(state.session.email) },\n })\n : mapped.name === \"auth_signed_out\"\n ? invocationTelemetry.reset()\n : Effect.void;\n return ignoreTransportFailure(() => invocationTelemetry.emit(mapped), \"emit\", mapped.name).pipe(\n Effect.andThen(\n ignoreTransportFailure(\n after,\n mapped.name === \"auth_signed_out\" ? \"reset\" : \"identify\",\n mapped.name,\n ),\n ),\n );\n}\n","import { Effect, Exit, Scope } from \"effect\";\nimport { toCountryCode } from \"@capxul/types\";\n\nimport { bootIdentityFlow, type IdentityActor } from \"../flows/identity\";\nimport type { IdentityEvent, IdentityState } from \"../domain/identity/model\";\nimport { ActorFailure, type InvocationControls } from \"../domain/machine/shell\";\nimport {\n attachInvocationObservation,\n type InvocationObservationSnapshot,\n} from \"../internal/invocation-observation\";\nimport { organizationSetupProofReceiptQuery } from \"../contract/org-lifecycle\";\nimport type { FlowPorts } from \"../flows/types\";\nimport { makeAuthMethods, type AuthMethods } from \"./auth\";\nimport { makeSmartAccountMethods, type SmartAccountMethods } from \"./smart-account\";\nimport { makeIdentityMethods, type IdentityMethods } from \"./identity\";\nimport { makeAccountMethods, type AccountMethods } from \"./account\";\nimport { makeAccountsMethods, type AccountsMethods, type AccountsFaucetMethods } from \"./accounts\";\nimport { makeCurrentUserMethods, type CurrentUserMethods } from \"./current-user\";\nimport {\n makeFinancialOpsMethods,\n type ActivityMethods,\n type DestinationsMethods,\n type HandlesMethods,\n type MeMethods,\n type OfframpMethods,\n type PayeesMethods,\n type PaymentsMethods,\n type PaymentDocumentsMethods,\n type TargetsMethods,\n} from \"./money\";\nimport { makeMediaMethods, type MediaMethods } from \"./media\";\nimport { makeSystemMethods, type SystemMethods } from \"./system\";\nimport { makeSubAccountsMethods, type SubAccountsMethods } from \"./sub-accounts\";\nimport { makeOrgMethods, type OrgMethods } from \"./org\";\nimport {\n runIdentityFacade,\n runPortEffect,\n type IdentityFacadeVerb,\n} from \"./_shared/effect-actor-bridge\";\nimport { detectAuthCacheAdapter } from \"./factory\";\nimport type { AccountRequirement } from \"./account-providers\";\nimport type { AuthCachePort } from \"../ports/auth-cache\";\nimport type { BootstrapResolution } from \"../ports/bootstrap\";\nimport type { SafeDeploymentConfig } from \"../ports/smart-account\";\nimport type { OrgPort, OrgRolesDeploymentPort, OrgSpendPort } from \"../ports/org\";\nimport type { OrganizationSetupOps } from \"./org-lifecycle\";\nimport type { CapxulSigner } from \"../signer\";\nimport type { TelemetryPort } from \"../ports/telemetry\";\nimport type { CapxulResult } from \"./types\";\nimport { executeIdentityProductObservation } from \"../telemetry/identity-product\";\n\nexport type OrganizationSetupProofReceipt =\n | {\n readonly state: \"submitted\";\n readonly orgId: string;\n readonly chainId: number;\n readonly signerEoa: string;\n readonly founderAccount: string;\n readonly organizationAccount: string;\n readonly userOperationHash: string;\n readonly submittedAt: number;\n readonly attempt: number;\n }\n | {\n readonly state: \"confirmed\";\n readonly orgId: string;\n readonly chainId: number;\n readonly signerEoa: string;\n readonly founderAccount: string;\n readonly organizationAccount: string;\n readonly userOperationHash: string;\n readonly submittedAt: number;\n readonly attempt: number;\n readonly confirmationTransactionHash: string;\n readonly readyAt: number;\n };\n\ntype OrganizationSetupProofMethods = {\n readonly getProofReceipt: (\n orgId: string,\n ) => Promise<CapxulResult<OrganizationSetupProofReceipt | null>>;\n};\n\nexport type IdentityRuntimeSendResult =\n | { readonly ok: true; readonly state: IdentityState }\n | {\n readonly ok: false;\n readonly refused: import(\"@capxul/errors\").CapxulErrorCode;\n readonly state: IdentityState;\n };\n\nexport type IdentityProfileDetails = {\n readonly displayName: string;\n readonly country: string;\n readonly username?: string;\n};\n\nexport interface IdentityRuntime {\n readonly snapshot: () => IdentityState;\n readonly subscribe: IdentityActor[\"subscribe\"];\n readonly subscribeTransitions: IdentityActor[\"subscribeTransitions\"];\n readonly send: (\n event: IdentityEvent,\n controls?: InvocationControls,\n ) => Promise<IdentityRuntimeSendResult>;\n readonly completeProfile: (\n profile: IdentityProfileDetails,\n controls?: InvocationControls,\n ) => Promise<\n | { readonly ok: true }\n | { readonly ok: false; readonly reason: import(\"@capxul/errors\").CapxulErrorCode }\n >;\n /** @internal One facade bridge; optional only for pre-S2 consumer test doubles. */\n readonly runFacade?: <T>(\n verb: IdentityFacadeVerb,\n controls: InvocationControls | undefined,\n run: (controls: InvocationControls) => Promise<T>,\n ) => Promise<T>;\n}\n\nexport interface CapxulClient {\n readonly auth: AuthMethods;\n readonly smartAccount: SmartAccountMethods;\n readonly identity: IdentityMethods;\n /**\n * Liveness surface (#1149 proof lane): `health(nonce)` round-trips a nonce\n * through the configured deployment. The only method here that is useful\n * before sign-in, and the only one whose whole point is that the answer\n * came from the backend rather than from this process.\n */\n readonly system: SystemMethods;\n /**\n * Consumer-facing account readiness surface (issue #159 · AC1+AC3).\n * Exactly `getStatus` + `ensureReady`; the `_internal.account`\n * namespace with `provision` + `deploySafe` lands in sibling #161.\n */\n readonly account: AccountMethods;\n /**\n * Consumer-facing logical Account money read (M2 Slice S1a · #265).\n * Returns `{ balance, available }` as `Money` — never wei or token units.\n */\n readonly accounts: AccountsMethods;\n readonly currentUser: CurrentUserMethods;\n readonly me: MeMethods;\n readonly handles: HandlesMethods;\n readonly payees: PayeesMethods;\n readonly targets: TargetsMethods;\n readonly destinations: DestinationsMethods;\n /**\n * Direct Payments surface (G2 · #545). `pay` records a validated-recipient\n * payment; `list`/`get` read the ledger; `markSettled` is the host-execution\n * callback.\n */\n readonly payments: PaymentsMethods;\n readonly activity: ActivityMethods;\n readonly offramp: OfframpMethods;\n /** Payment document verification (G2 · #545): re-derive the EIP-712 hash. */\n readonly paymentDocuments: PaymentDocumentsMethods;\n /**\n * Media surface (#1061 / ADR-0014): profile-image + org-logo upload/record.\n */\n readonly media: MediaMethods;\n /** Sub-account lifecycle (M2 Slice S2a · #267). Transfer lands in S2b. */\n readonly subAccounts: SubAccountsMethods;\n /**\n * Organization domain surface (canon `org-domain-model.md` §C2/§C3, D13).\n * `createOrg(input)` creates an Org; `orgs()` lists the Orgs you belong to;\n * `org(orgId)` resolves the entity-scoped bundle (treasury / members / roles\n * / invite / removeMember / assignRole / spend). Explicit entity scoping —\n * NO stateful active context (D13). RED until the S1→S4 slices fill it.\n */\n readonly createOrg: OrgMethods[\"createOrg\"];\n readonly orgs: OrgMethods[\"orgs\"];\n readonly org: OrgMethods[\"org\"];\n /**\n * Internal identity integration runtime. It is consumed by\n * `@capxul/sdk-react`, not exported as the actor substrate itself.\n *\n * @internal-use\n */\n readonly _internal: {\n readonly identity: IdentityRuntime;\n /**\n * Resolved bootstrap for this client instance (chain, auth URLs, etc.).\n * Off the public surface per production-surface-policy.md (#31).\n */\n readonly bootstrap: BootstrapResolution;\n /**\n * Dev-only faucet bundle (production-surface-policy.md). `fund` lives here,\n * NOT on the public `client.accounts` surface.\n */\n readonly accounts: AccountsFaucetMethods;\n /** Quarantined Reference-harness evidence; never a product Organization method. */\n readonly organizationSetup: OrganizationSetupProofMethods;\n /** Telemetry port for error reporting. Used by React hooks to report errors before throwing. */\n readonly telemetry?: TelemetryPort;\n readonly close?: () => Promise<void>;\n };\n}\n\nexport interface CreateCapxulClientInput {\n /**\n * The 10-port `FlowPorts` bundle. The identity actor uses its auth, clock,\n * identity, smart-account, and telemetry seams internally; the remaining\n * method bundles consume the same canonical port authorities.\n */\n readonly ports: FlowPorts;\n /**\n * Bootstrap resolution for this client instance. The factory closes over\n * `bootstrap.chainId` internally; consumers do not pass a standalone\n * chainId and no method boundary accepts one.\n */\n readonly bootstrap: BootstrapResolution;\n /**\n * Optional AuthCachePort. When omitted, `detectAuthCacheAdapter()` selects\n * the appropriate per-environment adapter (Browser/FileSystem/InMemory).\n */\n readonly authCache?: AuthCachePort;\n /**\n * Optional AbortSignal reserved for callers that coordinate client lifetime.\n */\n readonly signal?: AbortSignal;\n /**\n * OTP TTL window in ms. Default 300_000 (5 min).\n */\n readonly otpTtlMs?: number;\n /**\n * Optional per-call timeout for invoked auth requests.\n */\n readonly invokeTimeoutMs?: number;\n /**\n * Init-time account readiness target (issue #159 · AC4). The factory\n * closes over this so `client.account.{getStatus,ensureReady}` don't\n * need to take a per-call requirement arg. REQUIRED — there is no\n * hidden default. Consumers building flows that never need a smart\n * account pass `\"none\"`; flows that want a counterfactual deposit\n * address pass `\"counterfactual\"`; flows that need an on-chain Safe\n * pass `\"deployed\"` (deploy path lands in sibling #161).\n */\n readonly requirement: AccountRequirement;\n /**\n * Consumer-held signer (backend-orchestrated-deploy.md). Required for\n * `requirement: \"deployed\"` flows: `provision` reads `getAddress()` and the\n * deploy path signs the backend's SafeOp digest via `signUserOpHash()`. The\n * backend orchestrates build + gas + paymaster + submit — the client never\n * holds an RPC URL, a gas-sponsorship policy, or a bundler.\n */\n readonly signer?: CapxulSigner;\n /**\n * Optional live Org-deploy lane (canon D10 SDK-orchestrated Org Safe deploy +\n * D3 RPC treasury). When supplied, `client.createOrg` / `org(id).treasury`\n * run the live path (real deploy + on-chain balance); when omitted, the\n * hermetic `$0` path runs (a fresh Org has no on-chain funds). The adapter\n * that CONSTRUCTS this port (deployer key + RPC + authenticated Convex seam)\n * is wired by the CLI deploy-stack; the factory only threads it through.\n */\n readonly orgDeploymentPort?: OrgPort;\n /** Locked D6 data-port name. Prefer over `orgDeploymentPort` in new code. */\n readonly orgPort?: OrgPort;\n /** S2 deploy/grant/revoke port. S2 uses deploy; S3 adds grant/revoke. */\n readonly orgRolesDeploymentPort?: OrgRolesDeploymentPort;\n /** S4 treasury-spend authority + submit port. */\n readonly orgSpendPort?: OrgSpendPort;\n /**\n * Internal Organization lifecycle capability. The Core SDK owns its\n * choreography; production composition supplies the provider/backend steps.\n */\n readonly organizationSetup?: OrganizationSetupOps;\n readonly orgDeploymentConfig?: SafeDeploymentConfig;\n /** Internal runner carrying the composition root's logger/tracer references. */\n readonly effectRunner?: {\n readonly runSync: <A, E>(effect: Effect.Effect<A, E>) => A;\n readonly runPromise: <A, E>(effect: Effect.Effect<A, E>) => Promise<A>;\n };\n}\n\n/** Join the assembled actor lifetime to the adapter lifetime for internal client factories. */\nexport function withAdapterClose(\n client: CapxulClient,\n closeAdapter: () => Promise<void>,\n): CapxulClient {\n const closeActor = client._internal.close;\n let closePromise: Promise<void> | undefined;\n const close = (): Promise<void> => {\n closePromise ??= Promise.all([\n Promise.resolve().then(() => closeActor?.()),\n Promise.resolve().then(closeAdapter),\n ]).then(() => undefined);\n return closePromise;\n };\n return { ...client, _internal: { ...client._internal, close } };\n}\n\nexport function assembleCapxulClient(input: CreateCapxulClientInput): CapxulClient {\n const authCache = input.authCache ?? detectAuthCacheAdapter();\n const effectRunner = input.effectRunner ?? {\n runSync: Effect.runSync,\n runPromise: Effect.runPromise,\n };\n const scope = effectRunner.runSync(Scope.make());\n const rawActor = effectRunner.runSync(\n Scope.provide(\n bootIdentityFlow({\n ports: input.ports,\n chainId: input.bootstrap.chainId,\n requirement: input.requirement,\n ...(input.signer === undefined ? {} : { signer: input.signer }),\n ...(input.organizationSetup === undefined\n ? {}\n : { organizationSetup: input.organizationSetup }),\n ...(input.otpTtlMs === undefined ? {} : { otpTtlMs: input.otpTtlMs }),\n }),\n scope,\n ),\n );\n const actor = withHostObservation(\n rawActor,\n (input as HostObservationSnapshotSeam).hostObservationSnapshot,\n );\n const unsubscribeProductTelemetry = actor.subscribeTransitions((record) => {\n void effectRunner\n .runPromise(\n executeIdentityProductObservation(input.ports.telemetry, record, actor.snapshot()),\n )\n .catch(() => {});\n });\n let stopPromise: Promise<void> | null = null;\n const stopActor = (): Promise<void> => {\n if (stopPromise === null) {\n unsubscribeProductTelemetry();\n stopPromise = effectRunner.runPromise(Scope.close(scope, Exit.void));\n }\n return stopPromise;\n };\n if (input.signal !== undefined) {\n input.signal.addEventListener(\"abort\", () => void stopActor(), { once: true });\n }\n const selectedOrgPort = input.orgPort ?? input.orgDeploymentPort;\n let detectPendingOrgInvitations: (() => Promise<void>) | undefined;\n let kickProvisioning: (() => void) | undefined;\n const financialOps = makeFinancialOpsMethods({ convexCall: input.ports.convexCall });\n const accountInput: Parameters<typeof makeAccountMethods>[0] = {\n actor,\n authCache,\n identityPort: input.ports.identity,\n smartAccountPort: input.ports.smartAccount,\n telemetry: input.ports.telemetry,\n chainId: input.bootstrap.chainId,\n requirement: input.requirement,\n accountReadPort: input.ports.accountRead,\n profileMethods: financialOps.me,\n convexCall: input.ports.convexCall,\n ...(input.signer === undefined ? {} : { signer: input.signer }),\n };\n const accountBundle = makeAccountMethods(accountInput);\n kickProvisioning = accountBundle.kickProvisioning;\n const account = accountBundle.methods;\n const authMethodsInput: Parameters<typeof makeAuthMethods>[0] = {\n actor,\n authClient: input.ports.authClient,\n authCache,\n clock: input.ports.clock,\n telemetry: input.ports.telemetry,\n ...(input.otpTtlMs === undefined ? {} : { otpTtlMs: input.otpTtlMs }),\n ...(input.invokeTimeoutMs === undefined ? {} : { invokeTimeoutMs: input.invokeTimeoutMs }),\n // PRD #462: no binding/pregen step exists — the lane provisions from the\n // authenticated email alone; the signer (when present) only claims.\n afterVerifyOtp: async () => {\n const browserSigner = input.signer;\n if (\n browserSigner !== undefined &&\n \"resetSession\" in browserSigner &&\n typeof browserSigner.resetSession === \"function\"\n ) {\n // Fresh OTP in the same browser tab reuses OpenFort localStorage + an\n // in-memory cached EOA unless we reset before the account lane runs.\n browserSigner.resetSession();\n }\n await detectPendingOrgInvitations?.();\n kickProvisioning?.();\n },\n };\n const auth = makeAuthMethods(authMethodsInput);\n const smartAccountInput: Parameters<typeof makeSmartAccountMethods>[0] = {\n actor,\n smartAccountPort: input.ports.smartAccount,\n chainId: input.bootstrap.chainId,\n sessionAuthUserIdFallback: null,\n telemetry: input.ports.telemetry,\n };\n const smartAccount = makeSmartAccountMethods(smartAccountInput);\n const identityInput: Parameters<typeof makeIdentityMethods>[0] = {\n identityPort: input.ports.identity,\n actor,\n convexCall: input.ports.convexCall,\n };\n const identity = makeIdentityMethods(identityInput);\n const system = makeSystemMethods({ convexCall: input.ports.convexCall });\n const media = makeMediaMethods({ convexCall: input.ports.convexCall });\n const accountsInput: Parameters<typeof makeAccountsMethods>[0] = {\n accountReadPort: input.ports.accountRead,\n chainId: input.bootstrap.chainId,\n telemetry: input.ports.telemetry,\n };\n const accounts = makeAccountsMethods(accountsInput);\n const subAccountsInput: Parameters<typeof makeSubAccountsMethods>[0] = {\n subAccountPort: input.ports.subAccount,\n telemetry: input.ports.telemetry,\n };\n const subAccounts = makeSubAccountsMethods(subAccountsInput);\n // Organization domain surface (canon §C2/§C3, D13). S1 wires `createOrg` /\n // `orgs` / `treasury` to their Effect programs; the live `OrgPort` (D10\n // SDK-orchestrated deploy + D3 RPC treasury) is supplied by the live-proof\n // slice — until then the hermetic `$0` path runs. Entity scoping is explicit\n // per `org(orgId)` call.\n const orgMethods = makeOrgMethods({\n chainId: input.bootstrap.chainId,\n telemetry: input.ports.telemetry,\n ...(selectedOrgPort === undefined ? {} : { orgPort: selectedOrgPort }),\n ...(input.orgRolesDeploymentPort === undefined\n ? {}\n : { orgRolesDeploymentPort: input.orgRolesDeploymentPort }),\n ...(input.orgSpendPort === undefined ? {} : { orgSpendPort: input.orgSpendPort }),\n convexCall: input.ports.convexCall,\n ...(input.organizationSetup === undefined\n ? {}\n : { organizationSetup: input.organizationSetup }),\n });\n if (selectedOrgPort !== undefined) {\n detectPendingOrgInvitations = async () => {\n await orgMethods.orgs.detectAndAcceptPendingInvitations();\n };\n }\n const currentUser = makeCurrentUserMethods({\n me: financialOps.me,\n accounts,\n smartAccount,\n orgs: orgMethods.orgs,\n });\n const identityRuntime: IdentityRuntime = {\n snapshot: actor.snapshot,\n subscribe: actor.subscribe,\n subscribeTransitions: actor.subscribeTransitions,\n runFacade: (verb, controls, run) =>\n runIdentityFacade(verb, controls, run, effectRunner.runPromise),\n async send(event, controls) {\n try {\n return { ok: true, state: await effectRunner.runPromise(actor.ask(event, controls)) };\n } catch (cause) {\n if (cause instanceof ActorFailure) {\n return { ok: false, refused: cause.reason, state: actor.snapshot() };\n }\n throw cause;\n }\n },\n async completeProfile(profile, controls) {\n if (\n typeof profile !== \"object\" ||\n profile === null ||\n typeof profile.displayName !== \"string\" ||\n typeof profile.country !== \"string\" ||\n (profile.username !== undefined && typeof profile.username !== \"string\")\n ) {\n return { ok: false, reason: \"INVALID_INPUT\" };\n }\n const displayName = profile.displayName.trim();\n if (displayName.length === 0) {\n return { ok: false, reason: \"INVALID_INPUT\" };\n }\n let country: ReturnType<typeof toCountryCode>;\n try {\n country = toCountryCode(profile.country);\n } catch {\n return { ok: false, reason: \"INVALID_INPUT\" };\n }\n const username = profile.username?.trim();\n if (profile.username !== undefined && username?.length === 0) {\n return { ok: false, reason: \"INVALID_INPUT\" };\n }\n const session = actor.authSession();\n if (session === null) return { ok: false, reason: \"NOT_AUTHENTICATED\" };\n const result = await runPortEffect(\n input.ports.identity.completeOnboarding({\n authUserId: session.authUserId,\n email: session.email,\n displayName,\n country,\n ...(username === undefined ? {} : { username }),\n }),\n controls,\n \"identity.completeProfile\",\n effectRunner.runPromise,\n );\n return result.ok ? { ok: true } : { ok: false, reason: result.error.code };\n },\n };\n const client = {\n auth,\n smartAccount,\n identity,\n system,\n account,\n accounts,\n currentUser,\n me: financialOps.me,\n handles: financialOps.handles,\n payees: financialOps.payees,\n targets: financialOps.targets,\n destinations: financialOps.destinations,\n payments: financialOps.payments,\n activity: financialOps.activity,\n offramp: financialOps.offramp,\n paymentDocuments: financialOps.paymentDocuments,\n media,\n subAccounts,\n createOrg: orgMethods.createOrg,\n orgs: orgMethods.orgs,\n org: orgMethods.org,\n _internal: {\n identity: identityRuntime,\n bootstrap: input.bootstrap,\n // Expose ONLY the dev faucet here, not the full bundle — the runtime\n // shape matches the narrower `AccountsFaucetMethods` type so `read`\n // never leaks onto `_internal.accounts` (production-surface-policy.md).\n accounts: { fund: accounts.fund },\n organizationSetup: {\n getProofReceipt: (orgId) =>\n runPortEffect(\n input.ports.convexCall.query(organizationSetupProofReceiptQuery, { orgId }),\n ),\n },\n telemetry: input.ports.telemetry,\n close: stopActor,\n },\n } satisfies CapxulClient;\n\n return client;\n}\n\ninterface HostObservationSnapshotSeam {\n readonly hostObservationSnapshot?: () => InvocationObservationSnapshot | undefined;\n}\n\nfunction withHostObservation(\n actor: IdentityActor,\n snapshot: (() => InvocationObservationSnapshot | undefined) | undefined,\n): IdentityActor {\n if (snapshot === undefined) return actor;\n const controls = (input: InvocationControls | undefined): InvocationControls => {\n const captured = snapshot();\n const copied = { ...input };\n return captured === undefined ? copied : attachInvocationObservation(copied, captured);\n };\n return {\n ...actor,\n ask: (event, input) => actor.ask(event, controls(input)),\n tell: (event, input) => actor.tell(event, controls(input)),\n restoreAuthSession: (session, input) => actor.restoreAuthSession(session, controls(input)),\n };\n}\n"],"mappings":";;;;;AA4BA,MAAM,QAAiB,EAAE,SAAS,cAAc;;AAGhD,MAAa,eAAe,YAA8B;CACxD,IAAI,QAAQ,SAAS,eAAe,QAAQ,SAAS,mBAAmB,OAAO;CAC/E,IAAI,QAAQ,SAAS,kBAAkB;EACrC,MAAM,OAAO,QAAQ;EACrB,OACE,SAAS,0BACT,SAAS,uBACT,SAAS;CAEb;CACA,OAAO,QAAQ,SAAS,mBAAmB,QAAQ,SAAS;AAC9D;AA0FA,MAAa,aAA4B,EAAE,OAAO,aAAa;AA6B/D,MAAa,SAAS,UAAqC;CACzD,IAAI,MAAM,UAAU,iBAAiB,OAAO,MAAM;CAClD,IAAI,MAAM,QAAQ,OAAO,WAAW,OAAO,iBAAiB,MAAM,QAAQ;CAC1E,MAAM,MAAM,MAAM,QAAQ;CAC1B,OAAO,QAAQ,OAAO,0BAA0B,yBAAyB,IAAI;AAC/E;AAsEA,MAAa,aAAa;CACxB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAIA,MAAa,qBAAqB;CAChC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAIA,MAAa,sBAAsB,CACjC,GAAG,YACH,GAAG,kBACL;;AASA,MAAM,iBAAiB;CAAC;CAAe;CAAW;AAAO;AAEzD,MAAa,mBAA4D;CAEvE,YAAY;EAAC;EAAc;EAAe;EAAkB;CAA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