@happyvertical/smrt-sales 0.57.45 → 0.57.47

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.
Files changed (33) hide show
  1. package/AGENTS.md +1 -1
  2. package/agents/commissions.md +3 -3
  3. package/dist/agreements.js +1 -1
  4. package/dist/chunks/__smrt-register__-D1H7oo6b.js +6 -0
  5. package/dist/chunks/__smrt-register__-D1H7oo6b.js.map +1 -0
  6. package/dist/chunks/{commissions-B1WnBKsn.js → commissions-DbhfPQbi.js} +78 -36
  7. package/dist/chunks/commissions-DbhfPQbi.js.map +1 -0
  8. package/dist/chunks/{referrals-DE0tKm5G.js → referrals-DQaEehr8.js} +2 -2
  9. package/dist/chunks/{referrals-DE0tKm5G.js.map → referrals-DQaEehr8.js.map} +1 -1
  10. package/dist/commissions/collections/CommissionCollection.d.ts +8 -2
  11. package/dist/commissions/collections/CommissionCollection.d.ts.map +1 -1
  12. package/dist/commissions/collections/CommissionPayoutCollection.d.ts +8 -2
  13. package/dist/commissions/collections/CommissionPayoutCollection.d.ts.map +1 -1
  14. package/dist/commissions/collections/EarningEventCollection.d.ts +12 -5
  15. package/dist/commissions/collections/EarningEventCollection.d.ts.map +1 -1
  16. package/dist/commissions/models/Commission.d.ts.map +1 -1
  17. package/dist/commissions/models/CommissionPayout.d.ts.map +1 -1
  18. package/dist/commissions/models/EarningEvent.d.ts +5 -5
  19. package/dist/commissions/models/EarningEvent.d.ts.map +1 -1
  20. package/dist/commissions/replay-owner.d.ts +35 -0
  21. package/dist/commissions/replay-owner.d.ts.map +1 -0
  22. package/dist/commissions/services/CommissionCalculationService.d.ts.map +1 -1
  23. package/dist/commissions/services/CommissionPayoutService.d.ts.map +1 -1
  24. package/dist/commissions.js +2 -2
  25. package/dist/crm.js +1 -1
  26. package/dist/index.js +3 -3
  27. package/dist/manifest.json +225 -13
  28. package/dist/referrals.js +2 -2
  29. package/dist/smrt-knowledge.json +16 -10
  30. package/package.json +8 -8
  31. package/dist/chunks/__smrt-register__-CyAtSSJB.js +0 -6
  32. package/dist/chunks/__smrt-register__-CyAtSSJB.js.map +0 -1
  33. package/dist/chunks/commissions-B1WnBKsn.js.map +0 -1
@@ -3,15 +3,15 @@
3
3
  "sensitiveFieldsExcluded": true,
4
4
  "generatedAt": "1970-01-01T00:00:00.000Z",
5
5
  "packageName": "@happyvertical/smrt-sales",
6
- "packageVersion": "0.57.45",
6
+ "packageVersion": "0.57.47",
7
7
  "sourceManifestPath": "dist/manifest.json",
8
8
  "agentDocPath": "AGENTS.md",
9
9
  "sourceHashes": {
10
- "manifest": "17aca95054df7d359c866e970e08216ded10e4ed917da50c456cd7eecafefb57",
11
- "packageJson": "283c13f11b1d8eeb8fe9d3c6907f50e5a417dc2ed26154c4b9257ff32dd0c641",
12
- "agents": "a96547d3b8105fd1a2d767b3c05341cf9f8ea9dec56c3c212d6239d19fb689ea",
10
+ "manifest": "c6cfa730f8ef3f4e1b78aed9e7d65f8c34e4664699d52121bb5a81397a0267c6",
11
+ "packageJson": "42f69b450b9bd0797644d477478e0e00de381bf6efbe9e8ca1fa2733629bf9f5",
12
+ "agents": "50157c8c1d2f3ef2d03dcb583ff0ade2048d497456ce2b9395d4721ee2e63bd2",
13
13
  "moduleDoc:agents/agreements.md": "86609271b56633c1b6a3d9b1905a200cad1cb15de54adb8ca9f1200f6af8b9ce",
14
- "moduleDoc:agents/commissions.md": "2f41ada34b583f037d9337f9ba3f4c93fd64d1cfcd0830cb7e1c260a6b339374",
14
+ "moduleDoc:agents/commissions.md": "476439bdc831649302441f53394d9dada0910d15602850ab496a41ad8183c3b0",
15
15
  "moduleDoc:agents/crm.md": "074eff9e3ca7ae6d86e65a1d29ac7b9b555b719b3801918678b15df7538f99e0",
16
16
  "moduleDoc:agents/referrals.md": "ef48c88e63155e3d08b9003f4643bc66ebb1942f1fb713252dc042ddcaad38e5",
17
17
  "moduleDoc:agents/svelte.md": "75e26f56185b5c2ce3895d9969522405131efcee4af4f5aaa66232a26fb27c8b"
@@ -2127,7 +2127,8 @@
2127
2127
  "name": "findByDedupeKey",
2128
2128
  "async": true,
2129
2129
  "params": [
2130
- "dedupeKey: string"
2130
+ "dedupeKey: string",
2131
+ "options?: object"
2131
2132
  ],
2132
2133
  "returns": "Promise<Commission | null>"
2133
2134
  },
@@ -2302,7 +2303,8 @@
2302
2303
  "name": "findByIdempotencyKey",
2303
2304
  "async": true,
2304
2305
  "params": [
2305
- "idempotencyKey: string"
2306
+ "idempotencyKey: string",
2307
+ "options?: object"
2306
2308
  ],
2307
2309
  "returns": "Promise<CommissionPayout | null>"
2308
2310
  },
@@ -2670,7 +2672,8 @@
2670
2672
  "name": "findByDedupeKey",
2671
2673
  "async": true,
2672
2674
  "params": [
2673
- "dedupeKey: string"
2675
+ "dedupeKey: string",
2676
+ "options?: object"
2674
2677
  ],
2675
2678
  "returns": "Promise<EarningEvent | null>"
2676
2679
  },
@@ -3070,6 +3073,7 @@
3070
3073
  "field": "tenantId"
3071
3074
  },
3072
3075
  "conflictColumns": [
3076
+ "tenant_id",
3073
3077
  "dedupe_key"
3074
3078
  ],
3075
3079
  "surfaces": [
@@ -3804,6 +3808,7 @@
3804
3808
  "field": "tenantId"
3805
3809
  },
3806
3810
  "conflictColumns": [
3811
+ "tenant_id",
3807
3812
  "idempotency_key"
3808
3813
  ],
3809
3814
  "surfaces": [
@@ -5219,6 +5224,7 @@
5219
5224
  "field": "tenantId"
5220
5225
  },
5221
5226
  "conflictColumns": [
5227
+ "tenant_id",
5222
5228
  "dedupe_key"
5223
5229
  ],
5224
5230
  "surfaces": [
@@ -13995,7 +14001,7 @@
13995
14001
  "polymorphicAssociations": 0,
13996
14002
  "uuidColumns": 232
13997
14003
  },
13998
- "agentDoc": "# @happyvertical/smrt-sales\n\nModular sales: provider-neutral agreement execution, CRM, referral intake, a neutral commissions financial core, and reusable Svelte surfaces. One installable package with distinct subpath exports:\n\n- `@happyvertical/smrt-sales/agreements`\n- `@happyvertical/smrt-sales/crm`\n- `@happyvertical/smrt-sales/referrals`\n- `@happyvertical/smrt-sales/commissions`\n- `@happyvertical/smrt-sales/svelte`\n\nThe root export re-exports every TS module. `agreements` depends on the provider-neutral `@happyvertical/signatures` contract and `smrt-assets`; provider credentials stay in the injected SDK adapter/secret store. `referrals` binds its versioned terms to `agreements`.\n\n## Validation\n\nRun `pnpm --filter @happyvertical/smrt-sales test` and `pnpm --filter @happyvertical/smrt-sales typecheck` for package changes. PostgreSQL-sensitive changes must also run `pnpm --filter @happyvertical/smrt-sales test:postgres`; the command uses the repository's disposable PostgreSQL harness and is registered in the PostgreSQL CI shard.\n\n## Roles vs. money\n\nReferrers and Sales Representatives are **distinct roles** and stay that way. Both connect to money through one neutral financial account:\n\n- **Earner** (commissions): payout identity — method, threshold, currency, status. Referenced by every Commission and CommissionPayout.\n- **SalesRepresentative** (crm) and **Referrer** (referrals): role models, each holding `profileId` (cross-package string ref to smrt-profiles) and `earnerId`.\n\n## Modules\n\nPer-module semantics live in sibling module docs — read the one for the module\nyou are editing. This file keeps what holds in every module.\n\n| Module | Scope | Module doc |\n|---|---|---|\n| `agreements` | verified execution evidence — private orchestration state, append-only provider events, immutable executed agreements, and the provider-neutral execution service | [agents/agreements.md](agents/agreements.md) |\n| `commissions` | the neutral financial core — earners, versioned plans, earning events, commissions, adjustments, balances, and payout settlement | [agents/commissions.md](agents/commissions.md) |\n| `crm` | leads, configurable pipelines, opportunities, tenant-safe Lead follow-up, activity trail, and idempotent conversion links | [agents/crm.md](agents/crm.md) |\n| `referrals` | referrers, programs, versioned attribution policies, links/touches, referrals, exception review, and term snapshots | [agents/referrals.md](agents/referrals.md) |\n| `svelte` | props-driven presentational surfaces for CRM, the referrer portal, and operator review | [agents/svelte.md](agents/svelte.md) |\n\n## Currency\n\n**All monetary fields are integer cents** with `*Cents` suffixes; that scale is a Sales contract, not an implicit framework currency rule. Fresh PostgreSQL/DuckDB INTEGER columns are BIGINT, while JavaScript hydration rejects values outside the safe-integer range. Rates are decimal (`0`–`1`). Rounding happens once per calculation step via `roundCents()` (half-away-from-zero) and every Commission stores its `calculationTrace` so amounts are reproducible. Convert at display/commerce boundaries with `centsToAmount()`/`amountToCents()`.\n\n## Tenancy\n\nBusiness/domain models are generally `@TenantScoped({ mode: 'optional' })` with `@tenantId({ nullable: true })`. This deliberately departs from legacy smrt-affiliates (which was cross-tenant by design for ad networks): sales programs, earners, and payouts are tenant-owned, while `tenantId: null` remains available for intentional global/operator-level rows. Immutable tenant-bound execution evidence (`AgreementExecution`, `AgreementExecutionEvent`, `ExecutedAgreement`) and private orchestration fences (`CommissionAdjustmentOperation`) instead use required tenancy with a non-null owner; never weaken those rows to optional tenancy.\n\n## Cross-package references (plain strings)\n\n`profileId` → smrt-profiles Profile; `invoiceId` (CommissionPayout) → smrt-commerce Invoice; agreement artifacts → smrt-assets Asset ids. No static imports of unrelated sibling domain packages.\n\n## smrt-affiliates migration\n\n`@happyvertical/smrt-affiliates` is now a deprecated compatibility package that re-exports this package's commissions core under the legacy names (`Partner` → `Earner`, `Payout` → `CommissionPayout`, `Commission`, collections, enums) with `@deprecated` guidance and **no duplicate persistence model**. The data/API mapping lives in `packages/affiliates/MIGRATION.md`.\n\n## Gotchas\n\n- **Cents vs. rates**: `*Cents` fields are INTEGER (`= 0` defaults); `rate`/`probability`/`shareFraction` are DECIMAL (`= 0.0` defaults). Don't mix the two conventions on one field.\n- **Optional same-package foreign keys use null**: execution, supersession, earning-event, and payout references that are absent persist as `null`, never `''`; their physical database constraints remain enabled when a real id is present.\n- **Versioned terms are rows, not edits**: CommissionPlan / AttributionPolicy / ReferralAgreement amendments insert `version + 1`; active versions are save-guarded immutable.\n- **Idempotency is dedupeKey-based**: EarningEvent, Commission, and CommissionPayout carry natural keys (`conflictColumns`) — retried ingestion/settlement upserts instead of duplicating.\n- **Adjustments never rewrite**: correcting an earned/paid Commission means appending a CommissionAdjustment, not editing the Commission.\n- **Adjustment retries use the service**: CommissionAdjustment has no public operation field and rejects an untyped `operationId` constructor option; ordinary legacy creates without one remain compatible. `CommissionAdjustmentService` transactionally claims the private operation fence with insert-on-conflict-no-op, creates the explicit mapped adjustment id only for the winner, then verifies the persisted intent; the same globally unique operation UUID cannot be reused by another tenant.\n- **Manifest objects must remain root-importable**: generated consumer registration imports every manifest-advertised model and collection from `@happyvertical/smrt-sales`. The `CommissionAdjustmentOperation` and `ReferralClickOperation` model/collection values are therefore root and owning-subpath exports for runtime loading, while their `api: false`, `mcp: false`, and `cli: false` decorators keep them off generated application surfaces. Publish-pack validation imports the actual CLI-generated register against the packed tarball.\n- **CommissionPayout, not Payout**: avoids the pre-existing global table-name collision between commerce `Payout` and legacy affiliates `Payout` (`payouts`).\n- **Table names are global**: new models were named to avoid collisions across packages (`commission_payouts`, `sales_activities`, `attribution_policies`, …).\n- **Svelte validation includes interaction contracts**: intake and inbox components have runtime component tests; `typecheck` also runs `svelte-check` via `scripts/svelte-check-a11y.mjs`. Ship raw `.svelte` via `svelte-package`.\n- **Lead workflows stay generic**: call `LeadWorkflowService` for tenant-safe intake, audited follow-up, qualification, nonterminal Opportunity stage movement, and terminal closure with optional conversion links. Optional intake `profileId` is stored and fingerprinted but remains host-authorized. The service delegates CRM lifecycles to their owning collections; hosts supply authorization and create downstream records. `LeadCreateForm`, `LeadList`, and `LeadDetail` are props/callback only. See [agents/crm.md](agents/crm.md) for dedupe, retry, and inbox contracts.\n- **Model transition methods don't save**: `markEarned()/approve()/markPayable()/markPaid()` (Commission) and the payout transitions mutate + stamp timestamps only — callers save; the settlement/payout services do both.\n- **`reject()` alone strands rows**: the model method only flips status — always reject through `transitionPayoutForSource`, which releases the batch's membership in the same transaction; stamped rows on a rejected payout would be unsettleable forever.\n- **The payout source stamp is derived data, never authorization**: `sourceKind`/`sourceId` on CommissionPayout index the history listing; both the listing and the lifecycle service re-verify actual membership and fail closed when the stamp cannot be proven.\n- **`sweepClearing` treats `clearingEndsAt: null` as immediately sweepable** (no clearing configured ⇒ nothing to wait for).\n- **Agreement freeze scope**: activating a ReferralAgreement requires and freezes its execution/evidence refs along with its commercial terms. `effectiveTo` remains writable for explicit end-dating; signed bytes, hashes, signer evidence, and audit trail exist only on immutable ExecutedAgreement/Asset records.\n- **Circular FK pair by design**: `Referral.snapshotId ↔ ReferralTermSnapshot.referralId`. Fine on SQLite (and no cross-table DDL constraints are emitted for these string FKs); keep an eye on strict-DDL environments.\n- **Attribution resolution is single-writer per (target, program)**: `resolve()` is idempotent against PERSISTED state, but two workers resolving the same target concurrently can both pass the existence check and create duplicate credit — the collection layer has no cross-row transaction (the same stance as payout batching, which relies on disjoint scopes for concurrency). Run intake resolution serially per target (it naturally is, in a request handler); duplicates are visible in the portal and correctable via `override()`.\n- **recordClick inside your transaction participates, never nests**: a nested adapter `transaction()` takes an independent pooled connection (happyvertical/sdk#1108) — it deadlocks undetectably on locks the caller's transaction holds (PostgreSQL sees a promise-wait, not a lock-wait) and refuses caller-created uncommitted links as `unknown_code`. Pass the caller's transaction database as `RecordClickInput.transaction` or bind the collection to it (`{ db: tx, _reuseInitializedDb: true, _deferRuntimeInitialization: true }` — detected and honored automatically); a pool-level database passed as `transaction` is refused with typed reason `invalid_transaction`. Participating results are bound to the caller's transaction — carry ids across the commit boundary; the pool-bound default still self-transacts and rehydrates after commit.\n- **Click retries reuse one key**: pass the exact same non-empty, well-formed-Unicode `recordClick.idempotencyKey` (maximum 256 UTF-8 bytes) on transport/database retry. Omitting it remains source-compatible but creates and returns a one-shot UUID; it cannot deduplicate a later independent invocation. `maxEvidenceBytes` guards creation; changing it cannot turn an already-committed exact replay into failure. Replay validation is against the immutable operation/touch snapshot, not mutable current link fields: later link edits preserve exact replay, the result link is current, and the touch evidence is the original snapshot. The private optional-tenant `ReferralClickOperation` table is the serialization fence and must be included in schema migration. Never pre-bound caller evidence: Sales owns the authoritative final-envelope byte check.\n- **`ObjectRegistry.getConfig(X)` needs the class module imported** (decorator side effects) — manifest-only registration doesn't carry api/mcp/conflictColumns; tests asserting surface configs need a side-effect import of the module barrel.\n\n- **Governed sales use the owned service factory**: `SalesGovernanceService`\n accepts allowlisted PostgreSQL connection configuration only, owns its\n adapter and transaction executors, and guards private state/model writes.\n DuckDB support remains blocked on SDK #1452; SQLite is also rejected until\n same-process BUSY recovery is proven. Quote issue/sign always recheck\n current seller, host policy/inventory and exact finance approval; see\n [agents/crm.md](agents/crm.md#governed-sellers-quotes-and-canonical-advertiser-registration).\n\n- **Recipe `affiliates.referrals`** (`src/referrals/recipes.ts`, help in `src/referrals/referrals.recipe.md`): the affiliate feature for catalog hosts (referrers, programs, referrals, commissions, payouts). It lives here because `@happyvertical/smrt-affiliates` is a model-less shim and a recipe needs models of its own package. Fields it shows carry `@field({ description })` in plain words.\n",
14004
+ "agentDoc": "# @happyvertical/smrt-sales\n\nModular sales: provider-neutral agreement execution, CRM, referral intake, a neutral commissions financial core, and reusable Svelte surfaces. One installable package with distinct subpath exports:\n\n- `@happyvertical/smrt-sales/agreements`\n- `@happyvertical/smrt-sales/crm`\n- `@happyvertical/smrt-sales/referrals`\n- `@happyvertical/smrt-sales/commissions`\n- `@happyvertical/smrt-sales/svelte`\n\nThe root export re-exports every TS module. `agreements` depends on the provider-neutral `@happyvertical/signatures` contract and `smrt-assets`; provider credentials stay in the injected SDK adapter/secret store. `referrals` binds its versioned terms to `agreements`.\n\n## Validation\n\nRun `pnpm --filter @happyvertical/smrt-sales test` and `pnpm --filter @happyvertical/smrt-sales typecheck` for package changes. PostgreSQL-sensitive changes must also run `pnpm --filter @happyvertical/smrt-sales test:postgres`; the command uses the repository's disposable PostgreSQL harness and is registered in the PostgreSQL CI shard.\n\n## Roles vs. money\n\nReferrers and Sales Representatives are **distinct roles** and stay that way. Both connect to money through one neutral financial account:\n\n- **Earner** (commissions): payout identity — method, threshold, currency, status. Referenced by every Commission and CommissionPayout.\n- **SalesRepresentative** (crm) and **Referrer** (referrals): role models, each holding `profileId` (cross-package string ref to smrt-profiles) and `earnerId`.\n\n## Modules\n\nPer-module semantics live in sibling module docs — read the one for the module\nyou are editing. This file keeps what holds in every module.\n\n| Module | Scope | Module doc |\n|---|---|---|\n| `agreements` | verified execution evidence — private orchestration state, append-only provider events, immutable executed agreements, and the provider-neutral execution service | [agents/agreements.md](agents/agreements.md) |\n| `commissions` | the neutral financial core — earners, versioned plans, earning events, commissions, adjustments, balances, and payout settlement | [agents/commissions.md](agents/commissions.md) |\n| `crm` | leads, configurable pipelines, opportunities, tenant-safe Lead follow-up, activity trail, and idempotent conversion links | [agents/crm.md](agents/crm.md) |\n| `referrals` | referrers, programs, versioned attribution policies, links/touches, referrals, exception review, and term snapshots | [agents/referrals.md](agents/referrals.md) |\n| `svelte` | props-driven presentational surfaces for CRM, the referrer portal, and operator review | [agents/svelte.md](agents/svelte.md) |\n\n## Currency\n\n**All monetary fields are integer cents** with `*Cents` suffixes; that scale is a Sales contract, not an implicit framework currency rule. Fresh PostgreSQL/DuckDB INTEGER columns are BIGINT, while JavaScript hydration rejects values outside the safe-integer range. Rates are decimal (`0`–`1`). Rounding happens once per calculation step via `roundCents()` (half-away-from-zero) and every Commission stores its `calculationTrace` so amounts are reproducible. Convert at display/commerce boundaries with `centsToAmount()`/`amountToCents()`.\n\n## Tenancy\n\nBusiness/domain models are generally `@TenantScoped({ mode: 'optional' })` with `@tenantId({ nullable: true })`. This deliberately departs from legacy smrt-affiliates (which was cross-tenant by design for ad networks): sales programs, earners, and payouts are tenant-owned, while `tenantId: null` remains available for intentional global/operator-level rows. Immutable tenant-bound execution evidence (`AgreementExecution`, `AgreementExecutionEvent`, `ExecutedAgreement`) and private orchestration fences (`CommissionAdjustmentOperation`) instead use required tenancy with a non-null owner; never weaken those rows to optional tenancy.\n\n## Cross-package references (plain strings)\n\n`profileId` → smrt-profiles Profile; `invoiceId` (CommissionPayout) → smrt-commerce Invoice; agreement artifacts → smrt-assets Asset ids. No static imports of unrelated sibling domain packages.\n\n## smrt-affiliates migration\n\n`@happyvertical/smrt-affiliates` is now a deprecated compatibility package that re-exports this package's commissions core under the legacy names (`Partner` → `Earner`, `Payout` → `CommissionPayout`, `Commission`, collections, enums) with `@deprecated` guidance and **no duplicate persistence model**. The data/API mapping lives in `packages/affiliates/MIGRATION.md`.\n\n## Gotchas\n\n- **Cents vs. rates**: `*Cents` fields are INTEGER (`= 0` defaults); `rate`/`probability`/`shareFraction` are DECIMAL (`= 0.0` defaults). Don't mix the two conventions on one field.\n- **Optional same-package foreign keys use null**: execution, supersession, earning-event, and payout references that are absent persist as `null`, never `''`; their physical database constraints remain enabled when a real id is present.\n- **Versioned terms are rows, not edits**: CommissionPlan / AttributionPolicy / ReferralAgreement amendments insert `version + 1`; active versions are save-guarded immutable.\n- **Idempotency is dedupeKey-based, per tenant (#3305 D1)**: EarningEvent, Commission, and CommissionPayout are keyed `(tenant_id, dedupe_key|idempotency_key)`. Replay lookups (`findByDedupeKey`/`getOrCreateByDedupeKey`/`findByIdempotencyKey`) and the raw save guards resolve one owner (explicit `tenantId`, else context; neither → global rows); calculation/settlement pass the event's/earner's tenant because they run without a context; a foreign owner under a context fails closed, super-admin bypass included. Rollout: `db:migrate` adds the tenant-led uniques and drops the superseded ones in a writer-drained window; recovery is forward-only once tenants share a key.\n- **Adjustments never rewrite**: correcting an earned/paid Commission means appending a CommissionAdjustment, not editing the Commission.\n- **Adjustment retries use the service**: CommissionAdjustment has no public operation field and rejects an untyped `operationId` constructor option; ordinary legacy creates without one remain compatible. `CommissionAdjustmentService` transactionally claims the private operation fence with insert-on-conflict-no-op, creates the explicit mapped adjustment id only for the winner, then verifies the persisted intent; the same globally unique operation UUID cannot be reused by another tenant.\n- **Manifest objects must remain root-importable**: generated consumer registration imports every manifest-advertised model and collection from `@happyvertical/smrt-sales`. The `CommissionAdjustmentOperation` and `ReferralClickOperation` model/collection values are therefore root and owning-subpath exports for runtime loading, while their `api: false`, `mcp: false`, and `cli: false` decorators keep them off generated application surfaces. Publish-pack validation imports the actual CLI-generated register against the packed tarball.\n- **CommissionPayout, not Payout**: avoids the pre-existing global table-name collision between commerce `Payout` and legacy affiliates `Payout` (`payouts`).\n- **Table names are global**: new models were named to avoid collisions across packages (`commission_payouts`, `sales_activities`, `attribution_policies`, …).\n- **Svelte validation includes interaction contracts**: intake and inbox components have runtime component tests; `typecheck` also runs `svelte-check` via `scripts/svelte-check-a11y.mjs`. Ship raw `.svelte` via `svelte-package`.\n- **Lead workflows stay generic**: call `LeadWorkflowService` for tenant-safe intake, audited follow-up, qualification, nonterminal Opportunity stage movement, and terminal closure with optional conversion links. Optional intake `profileId` is stored and fingerprinted but remains host-authorized. The service delegates CRM lifecycles to their owning collections; hosts supply authorization and create downstream records. `LeadCreateForm`, `LeadList`, and `LeadDetail` are props/callback only. See [agents/crm.md](agents/crm.md) for dedupe, retry, and inbox contracts.\n- **Model transition methods don't save**: `markEarned()/approve()/markPayable()/markPaid()` (Commission) and the payout transitions mutate + stamp timestamps only — callers save; the settlement/payout services do both.\n- **`reject()` alone strands rows**: the model method only flips status — always reject through `transitionPayoutForSource`, which releases the batch's membership in the same transaction; stamped rows on a rejected payout would be unsettleable forever.\n- **The payout source stamp is derived data, never authorization**: `sourceKind`/`sourceId` on CommissionPayout index the history listing; both the listing and the lifecycle service re-verify actual membership and fail closed when the stamp cannot be proven.\n- **`sweepClearing` treats `clearingEndsAt: null` as immediately sweepable** (no clearing configured ⇒ nothing to wait for).\n- **Agreement freeze scope**: activating a ReferralAgreement requires and freezes its execution/evidence refs along with its commercial terms. `effectiveTo` remains writable for explicit end-dating; signed bytes, hashes, signer evidence, and audit trail exist only on immutable ExecutedAgreement/Asset records.\n- **Circular FK pair by design**: `Referral.snapshotId ↔ ReferralTermSnapshot.referralId`. Fine on SQLite (and no cross-table DDL constraints are emitted for these string FKs); keep an eye on strict-DDL environments.\n- **Attribution resolution is single-writer per (target, program)**: `resolve()` is idempotent against PERSISTED state, but two workers resolving the same target concurrently can both pass the existence check and create duplicate credit — the collection layer has no cross-row transaction (the same stance as payout batching, which relies on disjoint scopes for concurrency). Run intake resolution serially per target (it naturally is, in a request handler); duplicates are visible in the portal and correctable via `override()`.\n- **recordClick inside your transaction participates, never nests**: a nested adapter `transaction()` takes an independent pooled connection (happyvertical/sdk#1108) — it deadlocks undetectably on locks the caller's transaction holds (PostgreSQL sees a promise-wait, not a lock-wait) and refuses caller-created uncommitted links as `unknown_code`. Pass the caller's transaction database as `RecordClickInput.transaction` or bind the collection to it (`{ db: tx, _reuseInitializedDb: true, _deferRuntimeInitialization: true }` — detected and honored automatically); a pool-level database passed as `transaction` is refused with typed reason `invalid_transaction`. Participating results are bound to the caller's transaction — carry ids across the commit boundary; the pool-bound default still self-transacts and rehydrates after commit.\n- **Click retries reuse one key**: pass the exact same non-empty, well-formed-Unicode `recordClick.idempotencyKey` (maximum 256 UTF-8 bytes) on transport/database retry. Omitting it remains source-compatible but creates and returns a one-shot UUID; it cannot deduplicate a later independent invocation. `maxEvidenceBytes` guards creation; changing it cannot turn an already-committed exact replay into failure. Replay validation is against the immutable operation/touch snapshot, not mutable current link fields: later link edits preserve exact replay, the result link is current, and the touch evidence is the original snapshot. The private optional-tenant `ReferralClickOperation` table is the serialization fence and must be included in schema migration. Never pre-bound caller evidence: Sales owns the authoritative final-envelope byte check.\n- **`ObjectRegistry.getConfig(X)` needs the class module imported** (decorator side effects) — manifest-only registration doesn't carry api/mcp/conflictColumns; tests asserting surface configs need a side-effect import of the module barrel.\n\n- **Governed sales use the owned service factory**: `SalesGovernanceService`\n accepts allowlisted PostgreSQL connection configuration only, owns its\n adapter and transaction executors, and guards private state/model writes.\n DuckDB support remains blocked on SDK #1452; SQLite is also rejected until\n same-process BUSY recovery is proven. Quote issue/sign always recheck\n current seller, host policy/inventory and exact finance approval; see\n [agents/crm.md](agents/crm.md#governed-sellers-quotes-and-canonical-advertiser-registration).\n\n- **Recipe `affiliates.referrals`** (`src/referrals/recipes.ts`, help in `src/referrals/referrals.recipe.md`): the affiliate feature for catalog hosts (referrers, programs, referrals, commissions, payouts). It lives here because `@happyvertical/smrt-affiliates` is a model-less shim and a recipe needs models of its own package. Fields it shows carry `@field({ description })` in plain words.\n",
13999
14005
  "moduleDocs": [
14000
14006
  {
14001
14007
  "path": "agents/agreements.md",
@@ -14005,7 +14011,7 @@
14005
14011
  {
14006
14012
  "path": "agents/commissions.md",
14007
14013
  "module": "commissions",
14008
- "content": "# smrt-sales/commissions — neutral financial core\n\nPer-module semantics for `@happyvertical/smrt-sales/commissions`. Package orientation, the\ncross-module invariants (currency, tenancy, cross-package refs, roles vs.\nmoney), and the Gotchas that apply before editing anything live in\n[../AGENTS.md](../AGENTS.md) — read that first.\n\n- **Earner**: `kind` (`person|organisation|treasury`, default `person`; organisation and treasury earners need no person Profile, so `profileId` stays empty unless the host links an organisation Profile), `profileId`, `status` (`pending|active|suspended`), `payoutMethod` (`bank_transfer|check|paypal|credit|other|stripe_connect|crypto`), `payoutDestination` (typed JSON descriptor via `getPayoutDestination()`/`setPayoutDestination()`: Stripe Connect `connectedAccountId` (`acct_…`) or crypto `network`/`asset`/`address`/`memo?`; unknown fields are refused so secrets cannot ride along; its `method` must equal `payoutMethod`, and an `active` Stripe Connect/crypto earner must have one — enforced at save; `createPayoutBatch` refuses to create a NEW Stripe Connect/crypto batch, including a `payoutMethod` override, unless the earner's destination has that method; an existing idempotency key still replays/repairs its batch after the preference changes), `payoutThresholdCents`, `payoutScheduleKey` (open string: `manual`, `monthly`, …), `currency`, `metadata`. Descriptors only: nothing in this package calls a payment provider. Map an organisation earner to the host's own organisation id through `EarnerSourceAttribution`.\n- **EarnerSourceAttribution** (#1986): indexed external attribution mapping `(sourceKind, sourceId) → earnerId` with `status` (`active|inactive`) — the queryable replacement for stashing associations in `Earner.metadata`. Natural key `(tenant_id, source_kind, source_id)` (one mapping per key per tenant; a re-`create` upserts/re-points; the adapters' null-aware upsert dedups NULL-tenant keys too, but duplicate global rows minted outside the model layer remain representable). The attribution kind space is consumer-defined and need not match earning-event source kinds. `EarnerAttributionService` is the public API: `registerAttribution` (idempotent; reports `created`/`previousEarnerId`; also the documented metadata-migration backfill primitive — loop earners, register each association, verify, drop the metadata key) and `resolveActiveEarnerBySource`/`resolveActiveEarnersBySources` (single/batched; 2 queries bounded by the REQUESTED ids, never a scan of active earners; fail-closed typed reasons `no_mapping|mapping_inactive|ambiguous_mapping|earner_not_found|earner_not_active` — more than one ACTIVE row for a key refuses rather than guessing). In tenant context mappings resolve within that tenant only; without context, lookups span all rows and cross-tenant duplicates surface as `ambiguous_mapping`.\n- **CommissionPlan**: versioned calculation terms. Natural key `(tenant_id, plan_key, version)` (per-tenant keys; the adapters' null-aware upsert dedups NULL-tenant keys through the model layer, though duplicate global rows minted via raw SQL remain representable); `status` (`draft|active|superseded|retired`); `effectiveFrom`. Components are a JSON-string array (`getComponents()`): each component has `key`, `trigger` (earning-event kind or `*`), `basis` (`fixed|gross|net|margin|custom`), `rate` or `fixedAmountCents`, `recurrence` (`one_time` or `recurring` with optional `maxOccurrences`/`windowMonths`). **Immutable once active** — amendments create a new row with `version + 1`; prior versions are never rewritten. `latestActiveByKey(key, at?)` resolves the highest active version **already in effect at `at`** — a future-dated amendment can be activated ahead of time without governing earlier qualifications (same rule on `AttributionPolicyCollection`).\n- **Waterfall pool steps** (#3834): a v2 step with `pool: { metric?, residual?, zeroWeight? }` splits its amount across the members of the pool its `recipient` descriptor resolves to (through the normal recipient registry). Membership comes from an injected `WaterfallPoolMembershipResolver`, weights from an injected `MetricProvider` (omitted `metric` ⇒ equal weights, no provider call). `calculateWaterfall` stays synchronous and never calls providers: `prepareWaterfallPools()` (async) resolves pools at the authoritative event and the result is passed as `pools`; `calculateWaterfallWithPools()` does both. Weights must be non-negative safe integers (hosts scale fractional metrics); members are canonicalized to `(kind, id)` order and duplicates, non-member metric rows, and repeated rows are refused; members the provider omits weigh zero. Allocation is exact BigInt `floor(amount × weight ÷ total)`; the residual goes to the remainder sink (default) or, with `residual: 'largest_remainder'`, one unit at a time by largest fractional remainder, then larger weight, then `kind`, then `id` (UTF-16 code-unit order). An empty pool, or an all-zero pool under the default `zeroWeight: 'remainder_sink'`, sends the whole step to the sink; `zeroWeight: 'equal'` splits equally instead. The trace freezes `frozenInputs.poolsByStep` (pool identity, metric, ISO period, members, weights) so replay never re-reads metrics; frozen and prepared snapshots must match their frozen recipient and the step's declared `metric` (`null` for equal weights), and a prepared snapshot (or `null` unresolved marker) must equal what the step's descriptor resolves to at calculation, so pools prepared for another plan are refused. Replay trusts the evidence it is given — like frozen `recipientByStep`, an internally consistent edit to stored evidence is undetectable without keyed integrity, so hosts store it immutably. Pool-free plans emit no `poolsByStep` key or step `pool` field, so their traces are unchanged. A pool step cannot be the application-fee offset recipient. Each member trace carries `shareFraction` for hosts that persist member allocations as Commissions under one `splitGroupId` (for example `${earningEventId}:${stepKey}`).\n- **EarningEvent**: immutable commercial-event evidence (`conversion`, `agreement_execution`, `invoice_payment`, `collected_revenue`, `recognized_margin`, or any extensible kind). Carries `sourceKind`/`sourceId` (generic earning source), `grossAmountCents`/`netAmountCents`/`marginCents`, `currency`, `occurredAt`, and a `dedupeKey` natural key for idempotent ingestion. No update/delete surface, plus a save-time immutability guard: hydrated edits, blind id overwrites, and fresh creates onto an existing dedupe key all throw (the upsert would rotate the row id and orphan referencing Commissions) — idempotent ingestion goes through `getOrCreateByDedupeKey()`.\n- **Commission**: one earning record per earner per plan component per event occurrence. Integer-cents amounts (`baseAmountCents`, `amountCents`), decimal `rate`, `basis`, snapshot references (`planKey`/`planVersion`, generic `termsSnapshotKind`/`termsSnapshotId`), a JSON `calculationTrace` sufficient to reproduce the amount, split support (`splitGroupId`, `shareFraction`), and a `dedupeKey` for idempotent creation. Lifecycle `pending → earned → approved → payable → paid`, enforced by a save-time transition guard with an authoritative prior-status re-read (commerce pattern).\n- **CommissionAdjustment**: append-only corrections (`refund|credit|chargeback|dispute|correction`), signed `amountCents`, required `reason`, immutable once created. `CommissionAdjustmentService.createAdjustment()` is the tenant-required idempotent creation door: callers provide a stable operation UUID; the database creates exactly one row, exact retries return it, and changed tenant/commission/earner/kind/cents/currency/reason/operator/metadata fail with a typed replay conflict. Parent Commission plus denormalized tenant/Earner/currency and operator UUID are validated before insert. The financial row deliberately exposes no operation field. A private, required-tenant `CommissionAdjustmentOperation` table uses the globally unique operation UUID as its primary id, maps it to the adjustment UUID, and is inserted in the same transaction as the adjustment. Claims tolerate either primary-key or tenant/slug/context uniqueness arbitration without aborting the transaction; only the tenant-scoped operation UUID lookup and immutable intent comparison authorize a replay. Existing adjustment schemas and legacy direct creates remain unchanged. Earned/paid Commissions are never rewritten — adjustments append to them.\n- **Payable balance**: computed, not stored — `CommissionBalanceService` sums payable Commissions plus unsettled Adjustments per Earner/currency.\n- **CommissionPayout**: settlement batch per Earner. `pending → approved → processing → completed | failed` (`resetFromFailed()` is the only exit from failed), plus the terminal operator decline `rejected` reachable from pending/approved (#1987 — reject through `transitionPayoutForSource`, which also RELEASES the batch's membership so the rows settle through a future batch; `reject()` on the model mutates status only). Settles rows via the collections' **conditional `claimForPayout`** (model-layer get/save/re-read — tenancy- and dialect-safe; a row owned by another batch is never re-claimed) and stores totals recomputed from the VERIFIED claimed membership; idempotent via `idempotencyKey` natural key (default `${earnerId}:${currency}:${YYYY-MM-DD}`) — initial creation uses a strict insert so concurrent same-key creators cannot overwrite the first routing snapshot; the loser receives a unique-constraint error and can retry the same key. A clean replay touches nothing, while a pending payout whose totals disagree with its stamped rows (interrupted claim pass) is repaired on replay (the claim pass re-checks the payout is still pending first). Each batch/repair pass also derives the payout's **single-source stamp** (`sourceKind`/`sourceId`, indexed): set when every claimed commission — and every claimed adjustment through its parent commission — shares exactly one non-empty source; empty for mixed/unknown/empty membership. `completePayout` flips member commissions to `paid` BEFORE the terminal transition, so a mid-loop failure stays retryable. Enforces `totalAmountCents = commissionTotalCents + adjustmentTotalCents` at save; retains `paymentReference`/`providerRef`; optional `invoiceId` cross-package string ref to a commerce Invoice. Generated surface is read-only on ALL doors (api/mcp/cli `list`/`get`) — writes go through `CommissionPayoutService`. `createPayoutBatch` settles the whole earner+currency by default, or a **scoped** subset: pass `sourceKind`+`sourceId` to settle just one earning source (e.g. one ad network), or `commissionIds` for an explicit set (each validated payable+unsettled+earner+currency; requires its own `idempotencyKey`) — adjustments are narrowed to the same scope, and the default idempotency key folds the source in. Scoping is how concurrent per-source batches settle safely: batches scoped to different sources (or disjoint `commissionIds`) gather **disjoint** row sets and never contend. The collection layer has no cross-row transaction, so OVERLAPPING concurrent scopes (a source batch + the earner-wide batch, intersecting id sets, or a batch replay racing a lifecycle transition of the same payout) must be serialized by the caller — `claimForPayout` still won't double-own a row, but a shared commission and its adjustment could split across the two batches.\n- **Payout destination snapshot** (#4148): `CommissionPayout.payoutDestination` stores the typed Earner descriptor captured at batch creation. Use `getPayoutDestination()` on the batch for execution/review, never live Earner routing. Method and destination are immutable from first persistence (pending included); idempotency replay/repair and failed-reset preserve them. Reject through the source transition service and create a new key to change routing. Existing Connect/crypto batches with an empty migrated snapshot cannot approve/process/complete; reject/recreate rather than infer historical routing. Manual methods retain `{}`. Generated list/get surfaces expose the snapshot; no provider transfer is implemented.\n- **Source-scoped payout history** (#1985): `CommissionPayoutService.getSourcePayoutHistory({ sourceKind, sourceId, limit?, offset? })` — one page of the payouts belonging to ONE earning source, newest first (`created_at DESC, id DESC`), offset contract (`nextOffset` advances by the scanned count; `null` when exhausted). Candidates come from the indexed stamp, so work is bounded by page size (a sparse source never scans the global history); each page is re-verified against actual membership in three batched queries (no per-payout N+1) — every member commission and every adjustment's parent must carry exactly the requested source and agree on earner/currency/tenant; unprovable rows (mixed-source, missing parents, memberless artifacts, released/rejected batches) are excluded fail-closed and reported in `excluded` with reasons. Adjustment-only payouts prove ownership through parent commissions and list normally. Payouts minted before the stamp existed are invisible until backfilled with `restampPayoutSource(payoutId)` (idempotent, any status).\n- **Source-authorized lifecycle transitions** (#1987): `CommissionPayoutService.transitionPayoutForSource({ payoutId, sourceKind, sourceId, action, expectedStatus?, paymentReference?, reason? })` — atomic alternative to load-verify-transition. Actions `approve | mark_processing | complete | fail | reject`. Everything runs on one transaction database: the payout row is locked (PostgreSQL `SELECT … FOR UPDATE`, replica-safe; single-connection engines serialize transitions per database in-process), membership is re-verified under the lock (every commission and every adjustment through its parent must carry exactly the requested source and matching earner/currency/tenant — else typed fail-closed refusals with no payout/member data), and only authorized calls receive status-derived `already_applied` or `status_conflict` outcomes. Totals are then recomputed under the lock (drift refuses the money-forward actions with `totals_drift`; repair = `createPayoutBatch` replay while pending; `fail`/`reject` proceed despite drift — reject IS the remedy), and the transition plus member writes commit or roll back together (`complete` flips members to paid in the same transaction; `reject` releases membership then declines). Outcomes: `transitioned`, `already_applied` (idempotent echo — terminal completion NEVER rewrites `paymentReference`/`providerRef`/`paidAt`), or `refused` with `{ reason, detail }`. Concurrent duplicate calls for actions that retain membership resolve as one `transitioned` + `already_applied` echoes; `reject` releases its membership evidence, so serialized replays fail `membership_empty` rather than expose rejected state. `expectedStatus` adds optimistic-concurrency strictness after authorization. Memberless batch artifacts cannot pass the source-authorized door (`membership_empty`) — they stay operator-level.\n"
14014
+ "content": "# smrt-sales/commissions — neutral financial core\n\nPer-module semantics for `@happyvertical/smrt-sales/commissions`. Package orientation, the\ncross-module invariants (currency, tenancy, cross-package refs, roles vs.\nmoney), and the Gotchas that apply before editing anything live in\n[../AGENTS.md](../AGENTS.md) — read that first.\n\n- **Earner**: `kind` (`person|organisation|treasury`, default `person`; organisation and treasury earners need no person Profile, so `profileId` stays empty unless the host links an organisation Profile), `profileId`, `status` (`pending|active|suspended`), `payoutMethod` (`bank_transfer|check|paypal|credit|other|stripe_connect|crypto`), `payoutDestination` (typed JSON descriptor via `getPayoutDestination()`/`setPayoutDestination()`: Stripe Connect `connectedAccountId` (`acct_…`) or crypto `network`/`asset`/`address`/`memo?`; unknown fields are refused so secrets cannot ride along; its `method` must equal `payoutMethod`, and an `active` Stripe Connect/crypto earner must have one — enforced at save; `createPayoutBatch` refuses to create a NEW Stripe Connect/crypto batch, including a `payoutMethod` override, unless the earner's destination has that method; an existing idempotency key still replays/repairs its batch after the preference changes), `payoutThresholdCents`, `payoutScheduleKey` (open string: `manual`, `monthly`, …), `currency`, `metadata`. Descriptors only: nothing in this package calls a payment provider. Map an organisation earner to the host's own organisation id through `EarnerSourceAttribution`.\n- **EarnerSourceAttribution** (#1986): indexed external attribution mapping `(sourceKind, sourceId) → earnerId` with `status` (`active|inactive`) — the queryable replacement for stashing associations in `Earner.metadata`. Natural key `(tenant_id, source_kind, source_id)` (one mapping per key per tenant; a re-`create` upserts/re-points; the adapters' null-aware upsert dedups NULL-tenant keys too, but duplicate global rows minted outside the model layer remain representable). The attribution kind space is consumer-defined and need not match earning-event source kinds. `EarnerAttributionService` is the public API: `registerAttribution` (idempotent; reports `created`/`previousEarnerId`; also the documented metadata-migration backfill primitive — loop earners, register each association, verify, drop the metadata key) and `resolveActiveEarnerBySource`/`resolveActiveEarnersBySources` (single/batched; 2 queries bounded by the REQUESTED ids, never a scan of active earners; fail-closed typed reasons `no_mapping|mapping_inactive|ambiguous_mapping|earner_not_found|earner_not_active` — more than one ACTIVE row for a key refuses rather than guessing). In tenant context mappings resolve within that tenant only; without context, lookups span all rows and cross-tenant duplicates surface as `ambiguous_mapping`.\n- **CommissionPlan**: versioned calculation terms. Natural key `(tenant_id, plan_key, version)` (per-tenant keys; the adapters' null-aware upsert dedups NULL-tenant keys through the model layer, though duplicate global rows minted via raw SQL remain representable); `status` (`draft|active|superseded|retired`); `effectiveFrom`. Components are a JSON-string array (`getComponents()`): each component has `key`, `trigger` (earning-event kind or `*`), `basis` (`fixed|gross|net|margin|custom`), `rate` or `fixedAmountCents`, `recurrence` (`one_time` or `recurring` with optional `maxOccurrences`/`windowMonths`). **Immutable once active** — amendments create a new row with `version + 1`; prior versions are never rewritten. `latestActiveByKey(key, at?)` resolves the highest active version **already in effect at `at`** — a future-dated amendment can be activated ahead of time without governing earlier qualifications (same rule on `AttributionPolicyCollection`).\n- **Waterfall pool steps** (#3834): a v2 step with `pool: { metric?, residual?, zeroWeight? }` splits its amount across the members of the pool its `recipient` descriptor resolves to (through the normal recipient registry). Membership comes from an injected `WaterfallPoolMembershipResolver`, weights from an injected `MetricProvider` (omitted `metric` ⇒ equal weights, no provider call). `calculateWaterfall` stays synchronous and never calls providers: `prepareWaterfallPools()` (async) resolves pools at the authoritative event and the result is passed as `pools`; `calculateWaterfallWithPools()` does both. Weights must be non-negative safe integers (hosts scale fractional metrics); members are canonicalized to `(kind, id)` order and duplicates, non-member metric rows, and repeated rows are refused; members the provider omits weigh zero. Allocation is exact BigInt `floor(amount × weight ÷ total)`; the residual goes to the remainder sink (default) or, with `residual: 'largest_remainder'`, one unit at a time by largest fractional remainder, then larger weight, then `kind`, then `id` (UTF-16 code-unit order). An empty pool, or an all-zero pool under the default `zeroWeight: 'remainder_sink'`, sends the whole step to the sink; `zeroWeight: 'equal'` splits equally instead. The trace freezes `frozenInputs.poolsByStep` (pool identity, metric, ISO period, members, weights) so replay never re-reads metrics; frozen and prepared snapshots must match their frozen recipient and the step's declared `metric` (`null` for equal weights), and a prepared snapshot (or `null` unresolved marker) must equal what the step's descriptor resolves to at calculation, so pools prepared for another plan are refused. Replay trusts the evidence it is given — like frozen `recipientByStep`, an internally consistent edit to stored evidence is undetectable without keyed integrity, so hosts store it immutably. Pool-free plans emit no `poolsByStep` key or step `pool` field, so their traces are unchanged. A pool step cannot be the application-fee offset recipient. Each member trace carries `shareFraction` for hosts that persist member allocations as Commissions under one `splitGroupId` (for example `${earningEventId}:${stepKey}`).\n- **EarningEvent**: immutable commercial-event evidence (`conversion`, `agreement_execution`, `invoice_payment`, `collected_revenue`, `recognized_margin`, or any extensible kind). Carries `sourceKind`/`sourceId` (generic earning source), `grossAmountCents`/`netAmountCents`/`marginCents`, `currency`, `occurredAt`, and a `dedupeKey` natural key for idempotent ingestion, unique per tenant (`(tenant_id, dedupe_key)`, #3305 D1; callers no longer need to embed the tenant). No update/delete surface, plus a save-time immutability guard: hydrated edits, blind id overwrites, and fresh creates onto an existing dedupe key all throw (the upsert would rotate the row id and orphan referencing Commissions) — idempotent ingestion goes through `getOrCreateByDedupeKey()`.\n- **Commission**: one earning record per earner per plan component per event occurrence. Integer-cents amounts (`baseAmountCents`, `amountCents`), decimal `rate`, `basis`, snapshot references (`planKey`/`planVersion`, generic `termsSnapshotKind`/`termsSnapshotId`), a JSON `calculationTrace` sufficient to reproduce the amount, split support (`splitGroupId`, `shareFraction`), and a `dedupeKey` for idempotent creation, unique per tenant (#3305 D1); calculation looks it up in the event's tenant. Lifecycle `pending → earned → approved → payable → paid`, enforced by a save-time transition guard with an authoritative prior-status re-read (commerce pattern).\n- **CommissionAdjustment**: append-only corrections (`refund|credit|chargeback|dispute|correction`), signed `amountCents`, required `reason`, immutable once created. `CommissionAdjustmentService.createAdjustment()` is the tenant-required idempotent creation door: callers provide a stable operation UUID; the database creates exactly one row, exact retries return it, and changed tenant/commission/earner/kind/cents/currency/reason/operator/metadata fail with a typed replay conflict. Parent Commission plus denormalized tenant/Earner/currency and operator UUID are validated before insert. The financial row deliberately exposes no operation field. A private, required-tenant `CommissionAdjustmentOperation` table uses the globally unique operation UUID as its primary id, maps it to the adjustment UUID, and is inserted in the same transaction as the adjustment. Claims tolerate either primary-key or tenant/slug/context uniqueness arbitration without aborting the transaction; only the tenant-scoped operation UUID lookup and immutable intent comparison authorize a replay. Existing adjustment schemas and legacy direct creates remain unchanged. Earned/paid Commissions are never rewritten — adjustments append to them.\n- **Payable balance**: computed, not stored — `CommissionBalanceService` sums payable Commissions plus unsettled Adjustments per Earner/currency.\n- **CommissionPayout**: settlement batch per Earner. `pending → approved → processing → completed | failed` (`resetFromFailed()` is the only exit from failed), plus the terminal operator decline `rejected` reachable from pending/approved (#1987 — reject through `transitionPayoutForSource`, which also RELEASES the batch's membership so the rows settle through a future batch; `reject()` on the model mutates status only). Settles rows via the collections' **conditional `claimForPayout`** (model-layer get/save/re-read — tenancy- and dialect-safe; a row owned by another batch is never re-claimed) and stores totals recomputed from the VERIFIED claimed membership; idempotent via the per-tenant `(tenant_id, idempotency_key)` natural key (#3305 D1; settlement looks it up in the earner's tenant; default `${earnerId}:${currency}:${YYYY-MM-DD}`) — initial creation uses a strict insert so concurrent same-key creators cannot overwrite the first routing snapshot; the loser receives a unique-constraint error and can retry the same key. A clean replay touches nothing, while a pending payout whose totals disagree with its stamped rows (interrupted claim pass) is repaired on replay (the claim pass re-checks the payout is still pending first). Each batch/repair pass also derives the payout's **single-source stamp** (`sourceKind`/`sourceId`, indexed): set when every claimed commission — and every claimed adjustment through its parent commission — shares exactly one non-empty source; empty for mixed/unknown/empty membership. `completePayout` flips member commissions to `paid` BEFORE the terminal transition, so a mid-loop failure stays retryable. Enforces `totalAmountCents = commissionTotalCents + adjustmentTotalCents` at save; retains `paymentReference`/`providerRef`; optional `invoiceId` cross-package string ref to a commerce Invoice. Generated surface is read-only on ALL doors (api/mcp/cli `list`/`get`) — writes go through `CommissionPayoutService`. `createPayoutBatch` settles the whole earner+currency by default, or a **scoped** subset: pass `sourceKind`+`sourceId` to settle just one earning source (e.g. one ad network), or `commissionIds` for an explicit set (each validated payable+unsettled+earner+currency; requires its own `idempotencyKey`) — adjustments are narrowed to the same scope, and the default idempotency key folds the source in. Scoping is how concurrent per-source batches settle safely: batches scoped to different sources (or disjoint `commissionIds`) gather **disjoint** row sets and never contend. The collection layer has no cross-row transaction, so OVERLAPPING concurrent scopes (a source batch + the earner-wide batch, intersecting id sets, or a batch replay racing a lifecycle transition of the same payout) must be serialized by the caller — `claimForPayout` still won't double-own a row, but a shared commission and its adjustment could split across the two batches.\n- **Payout destination snapshot** (#4148): `CommissionPayout.payoutDestination` stores the typed Earner descriptor captured at batch creation. Use `getPayoutDestination()` on the batch for execution/review, never live Earner routing. Method and destination are immutable from first persistence (pending included); idempotency replay/repair and failed-reset preserve them. Reject through the source transition service and create a new key to change routing. Existing Connect/crypto batches with an empty migrated snapshot cannot approve/process/complete; reject/recreate rather than infer historical routing. Manual methods retain `{}`. Generated list/get surfaces expose the snapshot; no provider transfer is implemented.\n- **Source-scoped payout history** (#1985): `CommissionPayoutService.getSourcePayoutHistory({ sourceKind, sourceId, limit?, offset? })` — one page of the payouts belonging to ONE earning source, newest first (`created_at DESC, id DESC`), offset contract (`nextOffset` advances by the scanned count; `null` when exhausted). Candidates come from the indexed stamp, so work is bounded by page size (a sparse source never scans the global history); each page is re-verified against actual membership in three batched queries (no per-payout N+1) — every member commission and every adjustment's parent must carry exactly the requested source and agree on earner/currency/tenant; unprovable rows (mixed-source, missing parents, memberless artifacts, released/rejected batches) are excluded fail-closed and reported in `excluded` with reasons. Adjustment-only payouts prove ownership through parent commissions and list normally. Payouts minted before the stamp existed are invisible until backfilled with `restampPayoutSource(payoutId)` (idempotent, any status).\n- **Source-authorized lifecycle transitions** (#1987): `CommissionPayoutService.transitionPayoutForSource({ payoutId, sourceKind, sourceId, action, expectedStatus?, paymentReference?, reason? })` — atomic alternative to load-verify-transition. Actions `approve | mark_processing | complete | fail | reject`. Everything runs on one transaction database: the payout row is locked (PostgreSQL `SELECT … FOR UPDATE`, replica-safe; single-connection engines serialize transitions per database in-process), membership is re-verified under the lock (every commission and every adjustment through its parent must carry exactly the requested source and matching earner/currency/tenant — else typed fail-closed refusals with no payout/member data), and only authorized calls receive status-derived `already_applied` or `status_conflict` outcomes. Totals are then recomputed under the lock (drift refuses the money-forward actions with `totals_drift`; repair = `createPayoutBatch` replay while pending; `fail`/`reject` proceed despite drift — reject IS the remedy), and the transition plus member writes commit or roll back together (`complete` flips members to paid in the same transaction; `reject` releases membership then declines). Outcomes: `transitioned`, `already_applied` (idempotent echo — terminal completion NEVER rewrites `paymentReference`/`providerRef`/`paidAt`), or `refused` with `{ reason, detail }`. Concurrent duplicate calls for actions that retain membership resolve as one `transitioned` + `already_applied` echoes; `reject` releases its membership evidence, so serialized replays fail `membership_empty` rather than expose rejected state. `expectedStatus` adds optimistic-concurrency strictness after authorization. Memberless batch artifacts cannot pass the source-authorized door (`membership_empty`) — they stay operator-level.\n"
14009
14015
  },
14010
14016
  {
14011
14017
  "path": "agents/crm.md",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@happyvertical/smrt-sales",
3
- "version": "0.57.45",
3
+ "version": "0.57.47",
4
4
  "smrtJsdoc": "strict",
5
5
  "description": "Modular sales for the SMRT framework: agreement execution, CRM, referral intake, neutral commissions, and reusable Svelte surfaces",
6
6
  "type": "module",
@@ -42,18 +42,18 @@
42
42
  "./manifest.json": "./dist/manifest.json"
43
43
  },
44
44
  "dependencies": {
45
- "@happyvertical/signatures": "^0.111.0",
46
- "@happyvertical/smrt-assets": "0.57.45",
47
- "@happyvertical/smrt-core": "0.57.45",
48
- "@happyvertical/smrt-tenancy": "0.57.45",
49
- "@happyvertical/smrt-ui": "0.57.45",
50
- "@happyvertical/sql": "^0.111.0"
45
+ "@happyvertical/signatures": "^0.111.3",
46
+ "@happyvertical/smrt-assets": "0.57.47",
47
+ "@happyvertical/smrt-core": "0.57.47",
48
+ "@happyvertical/smrt-tenancy": "0.57.47",
49
+ "@happyvertical/smrt-ui": "0.57.47",
50
+ "@happyvertical/sql": "^0.111.3"
51
51
  },
52
52
  "peerDependencies": {
53
53
  "svelte": "^5.57.0"
54
54
  },
55
55
  "devDependencies": {
56
- "@happyvertical/smrt-vitest": "0.57.45",
56
+ "@happyvertical/smrt-vitest": "0.57.47",
57
57
  "@sveltejs/package": "^2.5.8",
58
58
  "@sveltejs/vite-plugin-svelte": "^7.3.0",
59
59
  "@types/node": "24.13.6",