@happyvertical/smrt-sales 0.40.0 → 0.40.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +14 -6
- package/dist/agreements/collections/AgreementExecutionCollection.d.ts +106 -0
- package/dist/agreements/collections/AgreementExecutionCollection.d.ts.map +1 -0
- package/dist/agreements/collections/AgreementExecutionEventCollection.d.ts +16 -0
- package/dist/agreements/collections/AgreementExecutionEventCollection.d.ts.map +1 -0
- package/dist/agreements/collections/ExecutedAgreementCollection.d.ts +17 -0
- package/dist/agreements/collections/ExecutedAgreementCollection.d.ts.map +1 -0
- package/dist/agreements/index.d.ts +18 -0
- package/dist/agreements/index.d.ts.map +1 -0
- package/dist/agreements/models/AgreementExecution.d.ts +66 -0
- package/dist/agreements/models/AgreementExecution.d.ts.map +1 -0
- package/dist/agreements/models/AgreementExecutionEvent.d.ts +25 -0
- package/dist/agreements/models/AgreementExecutionEvent.d.ts.map +1 -0
- package/dist/agreements/models/ExecutedAgreement.d.ts +35 -0
- package/dist/agreements/models/ExecutedAgreement.d.ts.map +1 -0
- package/dist/agreements/services/AgreementExecutionService.d.ts +85 -0
- package/dist/agreements/services/AgreementExecutionService.d.ts.map +1 -0
- package/dist/agreements/types.d.ts +140 -0
- package/dist/agreements/types.d.ts.map +1 -0
- package/dist/agreements.d.ts +2 -0
- package/dist/agreements.d.ts.map +1 -0
- package/dist/agreements.js +3 -0
- package/dist/chunks/__smrt-register__-Cwn1Fb4I.js +6 -0
- package/dist/chunks/{__smrt-register__-DGR1u9K2.js.map → __smrt-register__-Cwn1Fb4I.js.map} +1 -1
- package/dist/chunks/agreements-DbzW1Pcq.js +1640 -0
- package/dist/chunks/agreements-DbzW1Pcq.js.map +1 -0
- package/dist/chunks/{referrals-CzkrPeKv.js → referrals-cYYg4YZw.js} +163 -40
- package/dist/chunks/referrals-cYYg4YZw.js.map +1 -0
- package/dist/commissions.js +1 -1
- package/dist/crm.js +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -3
- package/dist/manifest.json +1853 -99
- package/dist/referrals/collections/ReferralAgreementCollection.d.ts +0 -4
- package/dist/referrals/collections/ReferralAgreementCollection.d.ts.map +1 -1
- package/dist/referrals/index.d.ts +1 -0
- package/dist/referrals/index.d.ts.map +1 -1
- package/dist/referrals/models/ReferralAgreement.d.ts +8 -19
- package/dist/referrals/models/ReferralAgreement.d.ts.map +1 -1
- package/dist/referrals/services/ReferralAgreementExecutionService.d.ts +55 -0
- package/dist/referrals/services/ReferralAgreementExecutionService.d.ts.map +1 -0
- package/dist/referrals/types.d.ts +2 -4
- package/dist/referrals/types.d.ts.map +1 -1
- package/dist/referrals.js +3 -3
- package/dist/smrt-knowledge.json +780 -33
- package/dist/svelte/components/ExecutedAgreementsList.svelte +36 -10
- package/dist/svelte/components/ExecutedAgreementsList.svelte.d.ts +2 -0
- package/dist/svelte/components/ExecutedAgreementsList.svelte.d.ts.map +1 -1
- package/dist/svelte/types.d.ts +7 -3
- package/dist/svelte/types.d.ts.map +1 -1
- package/package.json +13 -7
- package/dist/chunks/__smrt-register__-DGR1u9K2.js +0 -6
- package/dist/chunks/referrals-CzkrPeKv.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"agreements-DbzW1Pcq.js","names":[],"sources":["../../src/agreements/types.ts","../../src/agreements/models/AgreementExecution.ts","../../src/agreements/collections/AgreementExecutionCollection.ts","../../src/agreements/models/AgreementExecutionEvent.ts","../../src/agreements/collections/AgreementExecutionEventCollection.ts","../../src/agreements/models/ExecutedAgreement.ts","../../src/agreements/collections/ExecutedAgreementCollection.ts","../../src/agreements/services/AgreementExecutionService.ts"],"sourcesContent":["/** Provider-neutral agreement execution contracts. */\n\nimport type {\n SignatureAuthenticationMethod,\n SignatureDocument,\n SignatureRequestStatus,\n SignatureSigner,\n SignatureSignerInput,\n} from '@happyvertical/signatures';\nimport type { SmrtObjectOptions } from '@happyvertical/smrt-core';\n\nexport const AGREEMENT_EXECUTION_STATUSES = [\n 'prepared',\n 'sent',\n 'delivered',\n 'viewed',\n 'partially_signed',\n 'completed',\n 'declined',\n 'cancelled',\n 'expired',\n 'failed',\n] as const satisfies readonly SignatureRequestStatus[];\n\nexport type AgreementExecutionStatus =\n (typeof AGREEMENT_EXECUTION_STATUSES)[number];\n\nexport interface AgreementSignerIntent {\n name: string;\n email: string;\n role?: string;\n order?: number;\n authenticationMethod: SignatureAuthenticationMethod;\n}\n\nexport interface AgreementExecutionOptions extends SmrtObjectOptions {\n tenantId?: string;\n provider?: string;\n providerAccountRef?: string;\n credentialRef?: string;\n idempotencyKey?: string;\n sourceKind?: string;\n sourceId?: string;\n sourceVersion?: number;\n sourceAssetId?: string;\n sourceSha256?: string;\n sourceSizeBytes?: number;\n requestIntentSha256?: string;\n title?: string;\n signerIntent?: string;\n providerRequestId?: string;\n providerRequestKey?: string | null;\n status?: AgreementExecutionStatus;\n expiresAt?: Date | string | number | null;\n cancellationReason?: string;\n lastProviderEventAt?: Date | string | number | null;\n lastReconciledAt?: Date | string | number | null;\n completedAt?: Date | string | number | null;\n effectiveFrom?: Date | string | number | null;\n effectiveTo?: Date | string | number | null;\n supersedesExecutedAgreementId?: string;\n signedDocumentAssetId?: string;\n signedDocumentSha256?: string;\n signedDocumentSizeBytes?: number;\n signedDocumentMediaType?: string;\n signedDocumentFilename?: string;\n auditTrailAssetId?: string;\n auditTrailSha256?: string;\n auditTrailSizeBytes?: number;\n auditTrailMediaType?: string;\n auditTrailFilename?: string;\n attemptCount?: number;\n createLeaseId?: string;\n createLeaseExpiresAt?: Date | string | number | null;\n lastError?: string;\n metadata?: string;\n}\n\nexport interface AgreementExecutionEventOptions extends SmrtObjectOptions {\n tenantId?: string;\n executionId?: string;\n provider?: string;\n providerEventId?: string;\n eventOrigin?: string;\n operationId?: string;\n dedupeKey?: string;\n orderingKey?: string;\n eventType?: string;\n status?: AgreementExecutionStatus;\n occurredAt?: Date | string | number;\n receivedAt?: Date | string | number;\n payloadSha256?: string;\n signerEvidence?: string;\n payload?: string;\n}\n\nexport type VerifiedAgreementExecutionEventOptions =\n AgreementExecutionEventOptions &\n Required<\n Pick<\n AgreementExecutionEventOptions,\n 'dedupeKey' | 'occurredAt' | 'receivedAt'\n >\n >;\n\nexport interface ExecutedAgreementOptions extends SmrtObjectOptions {\n tenantId?: string;\n executionId?: string;\n sourceKind?: string;\n sourceId?: string;\n sourceVersion?: number;\n sourceAssetId?: string;\n sourceSha256?: string;\n sourceSizeBytes?: number;\n signedDocumentAssetId?: string;\n signedDocumentSha256?: string;\n signedDocumentSizeBytes?: number;\n signedDocumentMediaType?: string;\n signedDocumentFilename?: string;\n auditTrailAssetId?: string;\n auditTrailSha256?: string;\n auditTrailSizeBytes?: number;\n auditTrailMediaType?: string;\n auditTrailFilename?: string;\n signerEvidence?: string;\n acceptedAt?: Date | string | number;\n effectiveFrom?: Date | string | number | null;\n effectiveTo?: Date | string | number | null;\n supersedesExecutedAgreementId?: string;\n metadata?: string;\n}\n\nexport interface CreateAgreementExecutionInput {\n tenantId: string;\n idempotencyKey: string;\n sourceKind: string;\n sourceId: string;\n sourceVersion: number;\n title: string;\n document: SignatureDocument;\n signers: readonly SignatureSignerInput[];\n message?: string;\n signingOrder?: boolean;\n expiresInDays?: number;\n providerAccountRef?: string;\n /** Secret-store reference only. Credential values must stay in the provider. */\n credentialRef?: string;\n effectiveFrom?: Date | string | number | null;\n effectiveTo?: Date | string | number | null;\n supersedesExecutedAgreementId?: string;\n metadata?: Readonly<Record<string, string>>;\n signal?: AbortSignal;\n}\n\nexport interface IngestAgreementWebhookInput {\n tenantId: string;\n payload: string;\n signature: string;\n}\n\nexport interface AgreementExecutionResult {\n executionId: string;\n /** Absent only while another idempotent create caller owns the remote attempt. */\n providerRequestId?: string;\n status: AgreementExecutionStatus;\n replayed: boolean;\n}\n\nexport interface AgreementWebhookIngestionResult {\n executionId: string;\n eventId: string;\n replayed: boolean;\n executedAgreementId?: string;\n}\n\nexport function sanitizeSignerIntent(\n signers: readonly SignatureSignerInput[],\n): AgreementSignerIntent[] {\n return signers.map((signer) => ({\n name: signer.name,\n email: signer.email,\n ...(signer.role ? { role: signer.role } : {}),\n ...(signer.order !== undefined ? { order: signer.order } : {}),\n authenticationMethod: signer.authentication?.method ?? 'none',\n }));\n}\n\nexport function sanitizeSignerEvidence(\n signers: readonly SignatureSigner[],\n): SignatureSigner[] {\n return signers.map((signer) => ({\n ...(signer.id ? { id: signer.id } : {}),\n name: signer.name,\n email: signer.email,\n ...(signer.role ? { role: signer.role } : {}),\n ...(signer.order !== undefined ? { order: signer.order } : {}),\n status: signer.status,\n ...(signer.authenticationMethod\n ? { authenticationMethod: signer.authenticationMethod }\n : {}),\n ...(signer.viewed !== undefined ? { viewed: signer.viewed } : {}),\n ...(signer.deliveryFailed !== undefined\n ? { deliveryFailed: signer.deliveryFailed }\n : {}),\n }));\n}\n\nexport function coerceAgreementDate(value: unknown): Date | null {\n if (value == null) return null;\n if (value instanceof Date) return value;\n if (typeof value === 'string' || typeof value === 'number') {\n const date = new Date(value);\n return Number.isNaN(date.getTime()) ? null : date;\n }\n return null;\n}\n","/** Mutable orchestration state for one tenant-scoped signature request. */\n\nimport {\n crossPackageRef,\n field,\n SmrtObject,\n smrt,\n} from '@happyvertical/smrt-core';\nimport { TenantScoped, tenantId } from '@happyvertical/smrt-tenancy';\nimport type {\n AgreementExecutionOptions,\n AgreementExecutionStatus,\n AgreementSignerIntent,\n} from '../types.js';\nimport { coerceAgreementDate } from '../types.js';\n\ninterface PersistedExecutionIdentity {\n intent: string;\n providerRequestId: string;\n providerRequestKey: string | null;\n signedDocumentEvidence: string;\n auditTrailEvidence: string;\n}\n\nconst persistedExecutionIdentity = new WeakMap<\n AgreementExecution,\n PersistedExecutionIdentity\n>();\n\n@TenantScoped({ mode: 'required' })\n@smrt({\n conflictColumns: ['tenant_id', 'idempotency_key'],\n api: false,\n mcp: false,\n cli: false,\n})\nexport class AgreementExecution extends SmrtObject {\n @tenantId()\n tenantId: string = '';\n\n @field({ required: true })\n provider: string = '';\n\n /** Non-secret provider account/region reference used for operations. */\n providerAccountRef: string = '';\n\n /** SDK/SMRT secret-store reference only; never a credential value. */\n credentialRef: string = '';\n\n @field({ required: true })\n idempotencyKey: string = '';\n\n @field({ required: true })\n sourceKind: string = '';\n\n @field({ required: true })\n sourceId: string = '';\n\n sourceVersion: number = 1;\n\n @crossPackageRef('@happyvertical/smrt-assets:Asset')\n sourceAssetId: string = '';\n\n sourceSha256: string = '';\n sourceSizeBytes: number = 0;\n requestIntentSha256: string = '';\n title: string = '';\n signerIntent: string = '[]';\n providerRequestId: string = '';\n\n /** Unique tenant/provider/request binding fence; derived, never a secret. */\n @field({ type: 'text', nullable: true, unique: true })\n providerRequestKey: string | null = null;\n\n status: AgreementExecutionStatus = 'prepared';\n expiresAt: Date | null = null;\n cancellationReason: string = '';\n lastProviderEventAt: Date | null = null;\n lastReconciledAt: Date | null = null;\n completedAt: Date | null = null;\n effectiveFrom: Date | null = null;\n effectiveTo: Date | null = null;\n\n /**\n * Opaque prior-evidence provenance copied into the immutable result.\n * The authoritative relationship is on ExecutedAgreement; making this\n * mutable orchestration hint a foreign key would create a registry cycle.\n */\n supersedesExecutedAgreementId: string = '';\n\n @crossPackageRef('@happyvertical/smrt-assets:Asset')\n signedDocumentAssetId: string = '';\n\n signedDocumentSha256: string = '';\n signedDocumentSizeBytes: number = 0;\n signedDocumentMediaType: string = '';\n signedDocumentFilename: string = '';\n\n @crossPackageRef('@happyvertical/smrt-assets:Asset')\n auditTrailAssetId: string = '';\n\n auditTrailSha256: string = '';\n auditTrailSizeBytes: number = 0;\n auditTrailMediaType: string = '';\n auditTrailFilename: string = '';\n attemptCount: number = 0;\n\n /** Operation id holding the current provider-create lease. */\n createLeaseId: string = '';\n\n /** A crashed create attempt stops fencing recovery after this instant. */\n createLeaseExpiresAt: Date | null = null;\n\n lastError: string = '';\n metadata: string = '{}';\n\n constructor(options: AgreementExecutionOptions = {}) {\n super(options);\n if (options.tenantId !== undefined) this.tenantId = options.tenantId;\n if (options.provider !== undefined) this.provider = options.provider;\n if (options.providerAccountRef !== undefined)\n this.providerAccountRef = options.providerAccountRef;\n if (options.credentialRef !== undefined)\n this.credentialRef = options.credentialRef;\n if (options.idempotencyKey !== undefined)\n this.idempotencyKey = options.idempotencyKey;\n if (options.sourceKind !== undefined) this.sourceKind = options.sourceKind;\n if (options.sourceId !== undefined) this.sourceId = options.sourceId;\n if (options.sourceVersion !== undefined)\n this.sourceVersion = options.sourceVersion;\n if (options.sourceAssetId !== undefined)\n this.sourceAssetId = options.sourceAssetId;\n if (options.sourceSha256 !== undefined)\n this.sourceSha256 = options.sourceSha256;\n if (options.sourceSizeBytes !== undefined)\n this.sourceSizeBytes = options.sourceSizeBytes;\n if (options.requestIntentSha256 !== undefined)\n this.requestIntentSha256 = options.requestIntentSha256;\n if (options.title !== undefined) this.title = options.title;\n if (options.signerIntent !== undefined)\n this.signerIntent = options.signerIntent;\n if (options.providerRequestId !== undefined)\n this.providerRequestId = options.providerRequestId;\n if (options.providerRequestKey !== undefined)\n this.providerRequestKey = options.providerRequestKey;\n this.syncProviderRequestKey();\n if (options.status !== undefined) this.status = options.status;\n if (options.expiresAt !== undefined)\n this.expiresAt = coerceAgreementDate(options.expiresAt);\n if (options.cancellationReason !== undefined)\n this.cancellationReason = options.cancellationReason;\n if (options.lastProviderEventAt !== undefined)\n this.lastProviderEventAt = coerceAgreementDate(\n options.lastProviderEventAt,\n );\n if (options.lastReconciledAt !== undefined)\n this.lastReconciledAt = coerceAgreementDate(options.lastReconciledAt);\n if (options.completedAt !== undefined)\n this.completedAt = coerceAgreementDate(options.completedAt);\n if (options.effectiveFrom !== undefined)\n this.effectiveFrom = coerceAgreementDate(options.effectiveFrom);\n if (options.effectiveTo !== undefined)\n this.effectiveTo = coerceAgreementDate(options.effectiveTo);\n if (options.supersedesExecutedAgreementId !== undefined)\n this.supersedesExecutedAgreementId =\n options.supersedesExecutedAgreementId;\n if (options.signedDocumentAssetId !== undefined)\n this.signedDocumentAssetId = options.signedDocumentAssetId;\n if (options.signedDocumentSha256 !== undefined)\n this.signedDocumentSha256 = options.signedDocumentSha256;\n if (options.signedDocumentSizeBytes !== undefined)\n this.signedDocumentSizeBytes = options.signedDocumentSizeBytes;\n if (options.signedDocumentMediaType !== undefined)\n this.signedDocumentMediaType = options.signedDocumentMediaType;\n if (options.signedDocumentFilename !== undefined)\n this.signedDocumentFilename = options.signedDocumentFilename;\n if (options.auditTrailAssetId !== undefined)\n this.auditTrailAssetId = options.auditTrailAssetId;\n if (options.auditTrailSha256 !== undefined)\n this.auditTrailSha256 = options.auditTrailSha256;\n if (options.auditTrailSizeBytes !== undefined)\n this.auditTrailSizeBytes = options.auditTrailSizeBytes;\n if (options.auditTrailMediaType !== undefined)\n this.auditTrailMediaType = options.auditTrailMediaType;\n if (options.auditTrailFilename !== undefined)\n this.auditTrailFilename = options.auditTrailFilename;\n if (options.attemptCount !== undefined)\n this.attemptCount = options.attemptCount;\n if (options.createLeaseId !== undefined)\n this.createLeaseId = options.createLeaseId;\n if (options.createLeaseExpiresAt !== undefined)\n this.createLeaseExpiresAt = coerceAgreementDate(\n options.createLeaseExpiresAt,\n );\n if (options.lastError !== undefined) this.lastError = options.lastError;\n if (options.metadata !== undefined) this.metadata = options.metadata;\n }\n\n override async initialize(): Promise<this> {\n await super.initialize();\n this.expiresAt = coerceAgreementDate(this.expiresAt);\n this.lastProviderEventAt = coerceAgreementDate(this.lastProviderEventAt);\n this.lastReconciledAt = coerceAgreementDate(this.lastReconciledAt);\n this.completedAt = coerceAgreementDate(this.completedAt);\n this.effectiveFrom = coerceAgreementDate(this.effectiveFrom);\n this.effectiveTo = coerceAgreementDate(this.effectiveTo);\n this.createLeaseExpiresAt = coerceAgreementDate(this.createLeaseExpiresAt);\n if (this.isPersisted)\n persistedExecutionIdentity.set(this, this.captureIdentity());\n return this;\n }\n\n override async save(): Promise<this> {\n const captured = persistedExecutionIdentity.get(this);\n if (captured) {\n this.assertBoundValueUnchanged(\n 'provider request',\n captured.providerRequestId,\n this.providerRequestId,\n );\n }\n this.syncProviderRequestKey();\n if (captured) {\n if (captured.intent !== this.serializeIntent()) {\n throw new Error(\n `AgreementExecution ${this.id ?? '<new>'}: execution identity is immutable`,\n );\n }\n this.assertBoundValueUnchanged(\n 'provider request key',\n captured.providerRequestKey ?? '',\n this.providerRequestKey ?? '',\n );\n this.assertBoundValueUnchanged(\n 'signed document evidence',\n captured.signedDocumentEvidence,\n this.serializeSignedDocumentEvidence(),\n );\n this.assertBoundValueUnchanged(\n 'audit trail evidence',\n captured.auditTrailEvidence,\n this.serializeAuditTrailEvidence(),\n );\n }\n const saved = (await super.save()) as this;\n persistedExecutionIdentity.set(this, this.captureIdentity());\n return saved;\n }\n\n getSignerIntent(): AgreementSignerIntent[] {\n try {\n const value = JSON.parse(this.signerIntent) as unknown;\n return Array.isArray(value) ? (value as AgreementSignerIntent[]) : [];\n } catch {\n return [];\n }\n }\n\n private captureIdentity(): PersistedExecutionIdentity {\n return {\n intent: this.serializeIntent(),\n providerRequestId: this.providerRequestId,\n providerRequestKey: this.providerRequestKey,\n signedDocumentEvidence: this.serializeSignedDocumentEvidence(),\n auditTrailEvidence: this.serializeAuditTrailEvidence(),\n };\n }\n\n private serializeIntent(): string {\n return JSON.stringify({\n tenantId: this.tenantId,\n provider: this.provider,\n providerAccountRef: this.providerAccountRef,\n credentialRef: this.credentialRef,\n idempotencyKey: this.idempotencyKey,\n sourceKind: this.sourceKind,\n sourceId: this.sourceId,\n sourceVersion: this.sourceVersion,\n sourceAssetId: this.sourceAssetId,\n sourceSha256: this.sourceSha256,\n sourceSizeBytes: this.sourceSizeBytes,\n requestIntentSha256: this.requestIntentSha256,\n title: this.title,\n signerIntent: this.signerIntent,\n effectiveFrom: this.effectiveFrom?.toISOString() ?? null,\n effectiveTo: this.effectiveTo?.toISOString() ?? null,\n supersedesExecutedAgreementId: this.supersedesExecutedAgreementId,\n metadata: this.metadata,\n });\n }\n\n private serializeSignedDocumentEvidence(): string {\n if (!this.signedDocumentAssetId) return '';\n return JSON.stringify({\n assetId: this.signedDocumentAssetId,\n sha256: this.signedDocumentSha256,\n sizeBytes: this.signedDocumentSizeBytes,\n mediaType: this.signedDocumentMediaType,\n filename: this.signedDocumentFilename,\n });\n }\n\n private serializeAuditTrailEvidence(): string {\n if (!this.auditTrailAssetId) return '';\n return JSON.stringify({\n assetId: this.auditTrailAssetId,\n sha256: this.auditTrailSha256,\n sizeBytes: this.auditTrailSizeBytes,\n mediaType: this.auditTrailMediaType,\n filename: this.auditTrailFilename,\n });\n }\n\n private assertBoundValueUnchanged(\n label: string,\n captured: string,\n current: string,\n ): void {\n if (captured && captured !== current) {\n throw new Error(\n `AgreementExecution ${this.id ?? '<new>'}: ${label} is immutable once bound`,\n );\n }\n }\n\n private syncProviderRequestKey(): void {\n if (!this.providerRequestId) {\n this.providerRequestKey = null;\n return;\n }\n if (!this.tenantId || !this.provider) {\n throw new Error(\n 'AgreementExecution provider request binding requires tenant and provider',\n );\n }\n const expected = `${this.tenantId}:${this.provider}:${this.providerRequestId}`;\n if (this.providerRequestKey && this.providerRequestKey !== expected) {\n throw new Error(\n `AgreementExecution ${this.id ?? '<new>'}: provider request key does not match its binding`,\n );\n }\n this.providerRequestKey = expected;\n }\n}\n\nexport default AgreementExecution;\n","import { SmrtCollection } from '@happyvertical/smrt-core';\nimport { requireTenantId } from '@happyvertical/smrt-tenancy';\nimport { AgreementExecution } from '../models/AgreementExecution.js';\nimport type { AgreementExecutionStatus } from '../types.js';\n\nexport interface ClaimAgreementCreateAttemptInput {\n tenantId: string;\n executionId: string;\n expectedAttemptCount: number;\n expectedLeaseId: string;\n expectedStatus: string;\n expectedLastError: string;\n operationId: string;\n leaseExpiresAt: Date;\n now: Date;\n}\n\nexport interface CompleteAgreementCreateAttemptInput {\n tenantId: string;\n executionId: string;\n operationId: string;\n provider: string;\n providerRequestId: string;\n status: AgreementExecutionStatus;\n expiresAt: Date | null;\n}\n\nexport interface FailAgreementCreateAttemptInput {\n tenantId: string;\n executionId: string;\n operationId: string;\n lastError: string;\n}\n\nexport interface BindAgreementProviderRequestInput {\n tenantId: string;\n executionId: string;\n provider: string;\n providerRequestId: string;\n}\n\nexport interface CompareAndSetAgreementLifecycleInput {\n tenantId: string;\n executionId: string;\n expectedStatus: AgreementExecutionStatus;\n status: AgreementExecutionStatus;\n expiresAt: Date | null;\n cancellationReason: string;\n lastProviderEventAt: Date;\n lastReconciledAt: Date | null;\n completedAt: Date | null;\n}\n\nexport interface UpdateAgreementExecutionErrorInput {\n tenantId: string;\n executionId: string;\n lastError: string;\n}\n\nexport type AgreementEvidenceArtifactKind = 'signed_document' | 'audit_trail';\n\nexport interface BindAgreementEvidenceArtifactInput {\n tenantId: string;\n executionId: string;\n kind: AgreementEvidenceArtifactKind;\n assetId: string;\n sha256: string;\n sizeBytes: number;\n mediaType: string;\n filename: string;\n}\n\nexport class AgreementExecutionCollection extends SmrtCollection<AgreementExecution> {\n static readonly _itemClass = AgreementExecution;\n\n async findByIdempotencyKey(\n idempotencyKey: string,\n ): Promise<AgreementExecution | null> {\n const rows = await this.list({ where: { idempotencyKey }, limit: 1 });\n return rows[0] ?? null;\n }\n\n async findByProviderRequest(\n provider: string,\n providerRequestId: string,\n ): Promise<AgreementExecution | null> {\n const rows = await this.list({\n where: { provider, providerRequestId },\n limit: 1,\n });\n return rows[0] ?? null;\n }\n\n /**\n * Atomically claim an expired or cleared provider-create lease.\n *\n * The explicit tenant predicate and expected-state predicates make the raw\n * compare-and-swap fail closed across workers. `RETURNING id` is used\n * because not every database adapter reports affected-row counts reliably.\n */\n async claimCreateAttempt(\n input: ClaimAgreementCreateAttemptInput,\n ): Promise<AgreementExecution | null> {\n const ambientTenantId = requireTenantId();\n if (ambientTenantId !== input.tenantId) {\n throw new Error('AgreementExecution create-lease tenant mismatch');\n }\n const result = await this._db.query(\n `UPDATE ${this.tableName}\n SET attempt_count = attempt_count + 1,\n status = ?,\n last_error = '',\n create_lease_id = ?,\n create_lease_expires_at = ?\n WHERE id = ?\n AND tenant_id = ?\n AND attempt_count = ?\n AND status = ?\n AND COALESCE(last_error, '') = ?\n AND COALESCE(create_lease_id, '') = ?\n AND (provider_request_id IS NULL OR provider_request_id = '')\n AND (create_lease_expires_at IS NULL OR create_lease_expires_at <= ?)\n RETURNING id`,\n 'prepared',\n input.operationId,\n input.leaseExpiresAt.toISOString(),\n input.executionId,\n input.tenantId,\n input.expectedAttemptCount,\n input.expectedStatus,\n input.expectedLastError,\n input.expectedLeaseId,\n input.now.toISOString(),\n );\n const claimed = (result.rows as Array<{ id?: unknown }>)[0];\n if (typeof claimed?.id !== 'string') return null;\n return await this.get({ id: claimed.id });\n }\n\n /**\n * Persist a provider-create result only while the caller still owns its\n * lease. This prevents a slow, expired attempt from overwriting a newer\n * recovery attempt after returning from the provider.\n */\n async completeCreateAttempt(\n input: CompleteAgreementCreateAttemptInput,\n ): Promise<AgreementExecution | null> {\n this.assertCreateAttemptTenant(input.tenantId);\n const providerRequestKey = `${input.tenantId}:${input.provider}:${input.providerRequestId}`;\n const result = await this._db.query(\n `UPDATE ${this.tableName}\n SET provider_request_id = ?,\n provider_request_key = ?,\n status = ?,\n expires_at = ?,\n last_error = '',\n create_lease_id = '',\n create_lease_expires_at = NULL\n WHERE id = ?\n AND tenant_id = ?\n AND provider = ?\n AND COALESCE(create_lease_id, '') = ?\n AND (provider_request_id IS NULL OR provider_request_id = '')\n RETURNING id`,\n input.providerRequestId,\n providerRequestKey,\n input.status,\n input.expiresAt?.toISOString() ?? null,\n input.executionId,\n input.tenantId,\n input.provider,\n input.operationId,\n );\n return await this.getReturnedExecution(result);\n }\n\n /** Record a create failure only while the caller still owns its lease. */\n async failCreateAttempt(\n input: FailAgreementCreateAttemptInput,\n ): Promise<AgreementExecution | null> {\n this.assertCreateAttemptTenant(input.tenantId);\n const result = await this._db.query(\n `UPDATE ${this.tableName}\n SET status = ?,\n last_error = ?,\n create_lease_id = '',\n create_lease_expires_at = NULL\n WHERE id = ?\n AND tenant_id = ?\n AND COALESCE(create_lease_id, '') = ?\n AND (provider_request_id IS NULL OR provider_request_id = '')\n RETURNING id`,\n 'failed',\n input.lastError,\n input.executionId,\n input.tenantId,\n input.operationId,\n );\n return await this.getReturnedExecution(result);\n }\n\n /** Bind an adopted provider request without saving a stale object snapshot. */\n async bindProviderRequest(\n input: BindAgreementProviderRequestInput,\n ): Promise<AgreementExecution | null> {\n this.assertCreateAttemptTenant(input.tenantId);\n const providerRequestKey = `${input.tenantId}:${input.provider}:${input.providerRequestId}`;\n const result = await this._db.query(\n `UPDATE ${this.tableName}\n SET provider_request_id = ?,\n provider_request_key = ?\n WHERE id = ?\n AND tenant_id = ?\n AND provider = ?\n AND (provider_request_id IS NULL OR provider_request_id = '' OR provider_request_id = ?)\n RETURNING id`,\n input.providerRequestId,\n providerRequestKey,\n input.executionId,\n input.tenantId,\n input.provider,\n input.providerRequestId,\n );\n return await this.getReturnedExecution(result);\n }\n\n /**\n * Apply provider lifecycle state only while status still matches the\n * caller's snapshot and the candidate observation is not older than the\n * persisted provider event. Service retries re-read the winner before\n * deciding whether the candidate state remains monotonic.\n */\n async compareAndSetLifecycle(\n input: CompareAndSetAgreementLifecycleInput,\n ): Promise<AgreementExecution | null> {\n this.assertCreateAttemptTenant(input.tenantId);\n const result = await this._db.query(\n `UPDATE ${this.tableName}\n SET status = ?,\n expires_at = ?,\n cancellation_reason = ?,\n last_provider_event_at = ?,\n last_reconciled_at = ?,\n completed_at = ?,\n last_error = ''\n WHERE id = ?\n AND tenant_id = ?\n AND status = ?\n AND (last_provider_event_at IS NULL OR last_provider_event_at <= ?)\n RETURNING id`,\n input.status,\n input.expiresAt?.toISOString() ?? null,\n input.cancellationReason,\n input.lastProviderEventAt.toISOString(),\n input.lastReconciledAt?.toISOString() ?? null,\n input.completedAt?.toISOString() ?? null,\n input.executionId,\n input.tenantId,\n input.expectedStatus,\n input.lastProviderEventAt.toISOString(),\n );\n return await this.getReturnedExecution(result);\n }\n\n /** Increment audit attempts without writing any lifecycle columns. */\n async incrementAttemptCount(\n tenantId: string,\n executionId: string,\n ): Promise<AgreementExecution> {\n this.assertCreateAttemptTenant(tenantId);\n const result = await this._db.query(\n `UPDATE ${this.tableName}\n SET attempt_count = attempt_count + 1\n WHERE id = ?\n AND tenant_id = ?\n RETURNING id`,\n executionId,\n tenantId,\n );\n const execution = await this.getReturnedExecution(result);\n if (!execution) {\n throw new Error(`AgreementExecution '${executionId}' was not found`);\n }\n return execution;\n }\n\n /** Update failure diagnostics without writing a stale lifecycle snapshot. */\n async updateLastError(\n input: UpdateAgreementExecutionErrorInput,\n ): Promise<AgreementExecution> {\n this.assertCreateAttemptTenant(input.tenantId);\n const result = await this._db.query(\n `UPDATE ${this.tableName}\n SET last_error = ?\n WHERE id = ?\n AND tenant_id = ?\n RETURNING id`,\n input.lastError,\n input.executionId,\n input.tenantId,\n );\n const execution = await this.getReturnedExecution(result);\n if (!execution) {\n throw new Error(\n `AgreementExecution '${input.executionId}' was not found`,\n );\n }\n return execution;\n }\n\n /**\n * Bind one immutable evidence artifact with a tenant-fenced compare-and-swap.\n * Concurrent finalizers can only publish one asset identity for each kind.\n */\n async bindEvidenceArtifact(\n input: BindAgreementEvidenceArtifactInput,\n ): Promise<AgreementExecution | null> {\n this.assertCreateAttemptTenant(input.tenantId);\n const columns =\n input.kind === 'signed_document'\n ? {\n assetId: 'signed_document_asset_id',\n sha256: 'signed_document_sha256',\n sizeBytes: 'signed_document_size_bytes',\n mediaType: 'signed_document_media_type',\n filename: 'signed_document_filename',\n }\n : {\n assetId: 'audit_trail_asset_id',\n sha256: 'audit_trail_sha256',\n sizeBytes: 'audit_trail_size_bytes',\n mediaType: 'audit_trail_media_type',\n filename: 'audit_trail_filename',\n };\n const result = await this._db.query(\n `UPDATE ${this.tableName}\n SET ${columns.assetId} = ?,\n ${columns.sha256} = ?,\n ${columns.sizeBytes} = ?,\n ${columns.mediaType} = ?,\n ${columns.filename} = ?\n WHERE id = ?\n AND tenant_id = ?\n AND provider_request_id IS NOT NULL\n AND provider_request_id <> ''\n AND ${columns.assetId} IS NULL\n RETURNING id`,\n input.assetId,\n input.sha256,\n input.sizeBytes,\n input.mediaType,\n input.filename,\n input.executionId,\n input.tenantId,\n );\n return await this.getReturnedExecution(result);\n }\n\n async findBySource(\n sourceKind: string,\n sourceId: string,\n ): Promise<AgreementExecution[]> {\n return await this.list({\n where: { sourceKind, sourceId },\n orderBy: 'source_version DESC',\n });\n }\n\n private assertCreateAttemptTenant(tenantId: string): void {\n if (requireTenantId() !== tenantId) {\n throw new Error('AgreementExecution create-lease tenant mismatch');\n }\n }\n\n private async getReturnedExecution(result: {\n rows?: unknown;\n }): Promise<AgreementExecution | null> {\n const returned = (result.rows as Array<{ id?: unknown }> | undefined)?.[0];\n if (typeof returned?.id !== 'string') return null;\n return await this.get({ id: returned.id });\n }\n}\n\nexport default AgreementExecutionCollection;\n","/** Append-only evidence of one verified provider webhook event. */\n\nimport { field, foreignKey, SmrtObject, smrt } from '@happyvertical/smrt-core';\nimport { TenantScoped, tenantId } from '@happyvertical/smrt-tenancy';\nimport type {\n AgreementExecutionEventOptions,\n AgreementExecutionStatus,\n} from '../types.js';\nimport { coerceAgreementDate } from '../types.js';\n\nconst persistedEventState = new WeakMap<AgreementExecutionEvent, string>();\n\n@TenantScoped({ mode: 'required' })\n@smrt({\n conflictColumns: ['tenant_id', 'dedupe_key'],\n api: false,\n mcp: false,\n cli: false,\n})\nexport class AgreementExecutionEvent extends SmrtObject {\n @tenantId()\n tenantId: string = '';\n\n @foreignKey('AgreementExecution', { required: true })\n executionId: string = '';\n\n provider: string = '';\n providerEventId: string = '';\n eventOrigin: string = 'provider_webhook';\n operationId: string = '';\n\n @field({ required: true })\n dedupeKey: string = '';\n\n orderingKey: string = '';\n eventType: string = '';\n status: AgreementExecutionStatus = 'prepared';\n occurredAt: Date = new Date();\n receivedAt: Date = new Date();\n payloadSha256: string = '';\n signerEvidence: string = '[]';\n payload: string = '{}';\n\n constructor(options: AgreementExecutionEventOptions = {}) {\n super(options);\n if (options.tenantId !== undefined) this.tenantId = options.tenantId;\n if (options.executionId !== undefined)\n this.executionId = options.executionId;\n if (options.provider !== undefined) this.provider = options.provider;\n if (options.providerEventId !== undefined)\n this.providerEventId = options.providerEventId;\n if (options.eventOrigin !== undefined)\n this.eventOrigin = options.eventOrigin;\n if (options.operationId !== undefined)\n this.operationId = options.operationId;\n if (options.dedupeKey !== undefined) this.dedupeKey = options.dedupeKey;\n if (options.orderingKey !== undefined)\n this.orderingKey = options.orderingKey;\n if (options.eventType !== undefined) this.eventType = options.eventType;\n if (options.status !== undefined) this.status = options.status;\n if (options.occurredAt !== undefined)\n this.occurredAt = coerceAgreementDate(options.occurredAt) ?? new Date();\n if (options.receivedAt !== undefined)\n this.receivedAt = coerceAgreementDate(options.receivedAt) ?? new Date();\n if (options.payloadSha256 !== undefined)\n this.payloadSha256 = options.payloadSha256;\n if (options.signerEvidence !== undefined)\n this.signerEvidence = options.signerEvidence;\n if (options.payload !== undefined) this.payload = options.payload;\n }\n\n override async initialize(): Promise<this> {\n await super.initialize();\n this.occurredAt = coerceAgreementDate(this.occurredAt) ?? new Date();\n this.receivedAt = coerceAgreementDate(this.receivedAt) ?? new Date();\n if (this.isPersisted) persistedEventState.set(this, this.serializeState());\n return this;\n }\n\n override async save(): Promise<this> {\n const captured = persistedEventState.get(this);\n if (captured !== undefined && captured !== this.serializeState()) {\n throw new Error(\n `AgreementExecutionEvent ${this.id ?? '<new>'}: verified events are immutable`,\n );\n }\n if (captured === undefined && !this.isPersisted) this.requireInsertOnSave();\n const result = (await super.save()) as this;\n persistedEventState.set(this, this.serializeState());\n return result;\n }\n\n private serializeState(): string {\n return JSON.stringify({\n tenantId: this.tenantId,\n executionId: this.executionId,\n provider: this.provider,\n providerEventId: this.providerEventId,\n eventOrigin: this.eventOrigin,\n operationId: this.operationId,\n dedupeKey: this.dedupeKey,\n orderingKey: this.orderingKey,\n eventType: this.eventType,\n status: this.status,\n occurredAt: this.occurredAt.toISOString(),\n receivedAt: this.receivedAt.toISOString(),\n payloadSha256: this.payloadSha256,\n signerEvidence: this.signerEvidence,\n payload: this.payload,\n });\n }\n}\n\nexport default AgreementExecutionEvent;\n","import { SmrtCollection } from '@happyvertical/smrt-core';\nimport { AgreementExecutionEvent } from '../models/AgreementExecutionEvent.js';\nimport type { VerifiedAgreementExecutionEventOptions } from '../types.js';\nimport { coerceAgreementDate } from '../types.js';\n\nexport class AgreementExecutionEventCollection extends SmrtCollection<AgreementExecutionEvent> {\n static readonly _itemClass = AgreementExecutionEvent;\n\n async findByDedupeKey(\n dedupeKey: string,\n ): Promise<AgreementExecutionEvent | null> {\n const rows = await this.list({ where: { dedupeKey }, limit: 1 });\n return rows[0] ?? null;\n }\n\n async recordVerified(\n options: VerifiedAgreementExecutionEventOptions,\n ): Promise<{ event: AgreementExecutionEvent; created: boolean }> {\n if (!options.dedupeKey) {\n throw new Error('AgreementExecutionEvent requires a dedupe key');\n }\n const occurredAt = coerceAgreementDate(options.occurredAt);\n if (!occurredAt) {\n throw new Error('AgreementExecutionEvent requires a valid occurredAt');\n }\n const receivedAt = coerceAgreementDate(options.receivedAt);\n if (!receivedAt) {\n throw new Error('AgreementExecutionEvent requires a valid receivedAt');\n }\n const existing = await this.findByDedupeKey(options.dedupeKey);\n if (existing) {\n this.assertSameVerifiedEvent(existing, options, occurredAt);\n return { event: existing, created: false };\n }\n const {\n occurredAt: _occurredAt,\n receivedAt: _receivedAt,\n ...rest\n } = options;\n try {\n return {\n event: await this.create({\n ...rest,\n occurredAt,\n receivedAt,\n _insertOnly: true,\n }),\n created: true,\n };\n } catch (error) {\n const raced = await this.findByDedupeKey(options.dedupeKey);\n if (!raced) throw error;\n this.assertSameVerifiedEvent(raced, options, occurredAt);\n return { event: raced, created: false };\n }\n }\n\n private assertSameVerifiedEvent(\n existing: AgreementExecutionEvent,\n options: VerifiedAgreementExecutionEventOptions,\n occurredAt: Date,\n ): void {\n if (\n existing.executionId !== options.executionId ||\n existing.provider !== options.provider ||\n existing.providerEventId !== (options.providerEventId ?? '') ||\n existing.eventOrigin !== (options.eventOrigin ?? 'provider_webhook') ||\n existing.operationId !== (options.operationId ?? '') ||\n existing.orderingKey !== (options.orderingKey ?? '') ||\n existing.eventType !== (options.eventType ?? '') ||\n existing.status !== options.status ||\n existing.occurredAt.toISOString() !== occurredAt.toISOString() ||\n existing.payloadSha256 !== (options.payloadSha256 ?? '') ||\n existing.signerEvidence !== (options.signerEvidence ?? '[]') ||\n existing.payload !== (options.payload ?? '{}')\n ) {\n throw new Error(\n `AgreementExecutionEvent dedupe key '${options.dedupeKey}' collides with different verified evidence`,\n );\n }\n }\n\n async findByExecution(\n executionId: string,\n ): Promise<AgreementExecutionEvent[]> {\n return await this.list({\n where: { executionId },\n orderBy: 'occurred_at ASC',\n });\n }\n\n async findProviderEventsByExecution(\n executionId: string,\n ): Promise<AgreementExecutionEvent[]> {\n return await this.list({\n where: { executionId, eventOrigin: 'provider_webhook' },\n orderBy: 'occurred_at ASC',\n });\n }\n}\n\nexport default AgreementExecutionEventCollection;\n","/** Immutable accepted agreement version and its durable evidence artifacts. */\n\nimport {\n crossPackageRef,\n field,\n foreignKey,\n SmrtObject,\n smrt,\n} from '@happyvertical/smrt-core';\nimport { TenantScoped, tenantId } from '@happyvertical/smrt-tenancy';\nimport type { ExecutedAgreementOptions } from '../types.js';\nimport { coerceAgreementDate } from '../types.js';\n\nconst persistedAgreementState = new WeakMap<ExecutedAgreement, string>();\n\n@TenantScoped({ mode: 'required' })\n@smrt({\n conflictColumns: ['tenant_id', 'execution_id'],\n api: { include: ['list', 'get'] },\n mcp: { include: ['list', 'get'] },\n cli: false,\n})\nexport class ExecutedAgreement extends SmrtObject {\n @tenantId()\n tenantId: string = '';\n\n @foreignKey('AgreementExecution', { required: true })\n executionId: string = '';\n\n @field({ required: true })\n sourceKind: string = '';\n\n @field({ required: true })\n sourceId: string = '';\n\n sourceVersion: number = 1;\n\n @crossPackageRef('@happyvertical/smrt-assets:Asset')\n sourceAssetId: string = '';\n\n sourceSha256: string = '';\n sourceSizeBytes: number = 0;\n\n @crossPackageRef('@happyvertical/smrt-assets:Asset')\n signedDocumentAssetId: string = '';\n\n signedDocumentSha256: string = '';\n signedDocumentSizeBytes: number = 0;\n signedDocumentMediaType: string = '';\n signedDocumentFilename: string = '';\n\n @crossPackageRef('@happyvertical/smrt-assets:Asset')\n auditTrailAssetId: string = '';\n\n auditTrailSha256: string = '';\n auditTrailSizeBytes: number = 0;\n auditTrailMediaType: string = '';\n auditTrailFilename: string = '';\n signerEvidence: string = '[]';\n acceptedAt: Date = new Date();\n effectiveFrom: Date | null = null;\n effectiveTo: Date | null = null;\n\n @foreignKey('ExecutedAgreement')\n supersedesExecutedAgreementId: string = '';\n\n metadata: string = '{}';\n\n constructor(options: ExecutedAgreementOptions = {}) {\n super(options);\n if (options.tenantId !== undefined) this.tenantId = options.tenantId;\n if (options.executionId !== undefined)\n this.executionId = options.executionId;\n if (options.sourceKind !== undefined) this.sourceKind = options.sourceKind;\n if (options.sourceId !== undefined) this.sourceId = options.sourceId;\n if (options.sourceVersion !== undefined)\n this.sourceVersion = options.sourceVersion;\n if (options.sourceAssetId !== undefined)\n this.sourceAssetId = options.sourceAssetId;\n if (options.sourceSha256 !== undefined)\n this.sourceSha256 = options.sourceSha256;\n if (options.sourceSizeBytes !== undefined)\n this.sourceSizeBytes = options.sourceSizeBytes;\n if (options.signedDocumentAssetId !== undefined)\n this.signedDocumentAssetId = options.signedDocumentAssetId;\n if (options.signedDocumentSha256 !== undefined)\n this.signedDocumentSha256 = options.signedDocumentSha256;\n if (options.signedDocumentSizeBytes !== undefined)\n this.signedDocumentSizeBytes = options.signedDocumentSizeBytes;\n if (options.signedDocumentMediaType !== undefined)\n this.signedDocumentMediaType = options.signedDocumentMediaType;\n if (options.signedDocumentFilename !== undefined)\n this.signedDocumentFilename = options.signedDocumentFilename;\n if (options.auditTrailAssetId !== undefined)\n this.auditTrailAssetId = options.auditTrailAssetId;\n if (options.auditTrailSha256 !== undefined)\n this.auditTrailSha256 = options.auditTrailSha256;\n if (options.auditTrailSizeBytes !== undefined)\n this.auditTrailSizeBytes = options.auditTrailSizeBytes;\n if (options.auditTrailMediaType !== undefined)\n this.auditTrailMediaType = options.auditTrailMediaType;\n if (options.auditTrailFilename !== undefined)\n this.auditTrailFilename = options.auditTrailFilename;\n if (options.signerEvidence !== undefined)\n this.signerEvidence = options.signerEvidence;\n if (options.acceptedAt !== undefined)\n this.acceptedAt = coerceAgreementDate(options.acceptedAt) ?? new Date();\n if (options.effectiveFrom !== undefined)\n this.effectiveFrom = coerceAgreementDate(options.effectiveFrom);\n if (options.effectiveTo !== undefined)\n this.effectiveTo = coerceAgreementDate(options.effectiveTo);\n if (options.supersedesExecutedAgreementId !== undefined)\n this.supersedesExecutedAgreementId =\n options.supersedesExecutedAgreementId;\n if (options.metadata !== undefined) this.metadata = options.metadata;\n }\n\n override async initialize(): Promise<this> {\n await super.initialize();\n this.acceptedAt = coerceAgreementDate(this.acceptedAt) ?? new Date();\n this.effectiveFrom = coerceAgreementDate(this.effectiveFrom);\n this.effectiveTo = coerceAgreementDate(this.effectiveTo);\n if (this.isPersisted)\n persistedAgreementState.set(this, this.serializeState());\n return this;\n }\n\n isEffectiveAt(at: Date): boolean {\n return !(\n (this.effectiveFrom && at < this.effectiveFrom) ||\n (this.effectiveTo && at > this.effectiveTo)\n );\n }\n\n override async save(): Promise<this> {\n const captured = persistedAgreementState.get(this);\n if (captured !== undefined && captured !== this.serializeState()) {\n throw new Error(\n `ExecutedAgreement ${this.id ?? '<new>'}: executed agreements are immutable; create a versioned amendment`,\n );\n }\n if (captured === undefined && !this.isPersisted) this.requireInsertOnSave();\n const result = (await super.save()) as this;\n persistedAgreementState.set(this, this.serializeState());\n return result;\n }\n\n private serializeState(): string {\n return JSON.stringify({\n tenantId: this.tenantId,\n executionId: this.executionId,\n sourceKind: this.sourceKind,\n sourceId: this.sourceId,\n sourceVersion: this.sourceVersion,\n sourceAssetId: this.sourceAssetId,\n sourceSha256: this.sourceSha256,\n sourceSizeBytes: this.sourceSizeBytes,\n signedDocumentAssetId: this.signedDocumentAssetId,\n signedDocumentSha256: this.signedDocumentSha256,\n signedDocumentSizeBytes: this.signedDocumentSizeBytes,\n signedDocumentMediaType: this.signedDocumentMediaType,\n signedDocumentFilename: this.signedDocumentFilename,\n auditTrailAssetId: this.auditTrailAssetId,\n auditTrailSha256: this.auditTrailSha256,\n auditTrailSizeBytes: this.auditTrailSizeBytes,\n auditTrailMediaType: this.auditTrailMediaType,\n auditTrailFilename: this.auditTrailFilename,\n signerEvidence: this.signerEvidence,\n acceptedAt: this.acceptedAt.toISOString(),\n effectiveFrom: this.effectiveFrom?.toISOString() ?? null,\n effectiveTo: this.effectiveTo?.toISOString() ?? null,\n supersedesExecutedAgreementId: this.supersedesExecutedAgreementId,\n metadata: this.metadata,\n });\n }\n}\n\nexport default ExecutedAgreement;\n","import { SmrtCollection } from '@happyvertical/smrt-core';\nimport { ExecutedAgreement } from '../models/ExecutedAgreement.js';\nimport type { ExecutedAgreementOptions } from '../types.js';\nimport { coerceAgreementDate } from '../types.js';\n\nexport class ExecutedAgreementCollection extends SmrtCollection<ExecutedAgreement> {\n static readonly _itemClass = ExecutedAgreement;\n\n async findByExecution(\n executionId: string,\n ): Promise<ExecutedAgreement | null> {\n const rows = await this.list({ where: { executionId }, limit: 1 });\n return rows[0] ?? null;\n }\n\n async createImmutable(\n options: ExecutedAgreementOptions,\n ): Promise<{ agreement: ExecutedAgreement; created: boolean }> {\n if (!options.executionId) {\n throw new Error('ExecutedAgreement requires an executionId');\n }\n this.assertCompleteEvidence(options);\n const existing = await this.findByExecution(options.executionId);\n if (existing) {\n this.assertSameEvidence(existing, options);\n return { agreement: existing, created: false };\n }\n const { acceptedAt, effectiveFrom, effectiveTo, ...rest } = options;\n try {\n return {\n agreement: await this.create({\n ...rest,\n ...(acceptedAt !== undefined\n ? { acceptedAt: coerceAgreementDate(acceptedAt) ?? new Date() }\n : {}),\n ...(effectiveFrom !== undefined\n ? { effectiveFrom: coerceAgreementDate(effectiveFrom) }\n : {}),\n ...(effectiveTo !== undefined\n ? { effectiveTo: coerceAgreementDate(effectiveTo) }\n : {}),\n _insertOnly: true,\n }),\n created: true,\n };\n } catch (error) {\n const raced = await this.findByExecution(options.executionId);\n if (!raced) throw error;\n this.assertSameEvidence(raced, options);\n return { agreement: raced, created: false };\n }\n }\n\n private assertSameEvidence(\n existing: ExecutedAgreement,\n options: ExecutedAgreementOptions,\n ): void {\n const acceptedAt = coerceAgreementDate(options.acceptedAt);\n const effectiveFrom = coerceAgreementDate(options.effectiveFrom);\n const effectiveTo = coerceAgreementDate(options.effectiveTo);\n if (\n existing.sourceKind !== options.sourceKind ||\n existing.sourceId !== options.sourceId ||\n existing.sourceVersion !== options.sourceVersion ||\n existing.sourceAssetId !== options.sourceAssetId ||\n existing.sourceSha256 !== (options.sourceSha256 ?? '') ||\n existing.sourceSizeBytes !== options.sourceSizeBytes ||\n existing.signedDocumentAssetId !== options.signedDocumentAssetId ||\n existing.signedDocumentSha256 !== (options.signedDocumentSha256 ?? '') ||\n existing.signedDocumentSizeBytes !== options.signedDocumentSizeBytes ||\n existing.signedDocumentMediaType !== options.signedDocumentMediaType ||\n existing.signedDocumentFilename !== options.signedDocumentFilename ||\n existing.auditTrailAssetId !== options.auditTrailAssetId ||\n existing.auditTrailSha256 !== (options.auditTrailSha256 ?? '') ||\n existing.auditTrailSizeBytes !== options.auditTrailSizeBytes ||\n existing.auditTrailMediaType !== options.auditTrailMediaType ||\n existing.auditTrailFilename !== options.auditTrailFilename ||\n existing.signerEvidence !== options.signerEvidence ||\n existing.acceptedAt.toISOString() !== acceptedAt?.toISOString() ||\n (existing.effectiveFrom?.toISOString() ?? null) !==\n (effectiveFrom?.toISOString() ?? null) ||\n (existing.effectiveTo?.toISOString() ?? null) !==\n (effectiveTo?.toISOString() ?? null) ||\n (existing.supersedesExecutedAgreementId ?? '') !==\n (options.supersedesExecutedAgreementId ?? '') ||\n existing.metadata !== (options.metadata ?? '{}')\n ) {\n throw new Error(\n `ExecutedAgreement execution '${options.executionId}' collides with different immutable evidence`,\n );\n }\n }\n\n private assertCompleteEvidence(options: ExecutedAgreementOptions): void {\n for (const [label, value] of [\n ['sourceKind', options.sourceKind],\n ['sourceId', options.sourceId],\n ['sourceAssetId', options.sourceAssetId],\n ['sourceSha256', options.sourceSha256],\n ['signedDocumentAssetId', options.signedDocumentAssetId],\n ['signedDocumentSha256', options.signedDocumentSha256],\n ['signedDocumentMediaType', options.signedDocumentMediaType],\n ['signedDocumentFilename', options.signedDocumentFilename],\n ['auditTrailAssetId', options.auditTrailAssetId],\n ['auditTrailSha256', options.auditTrailSha256],\n ['auditTrailMediaType', options.auditTrailMediaType],\n ['auditTrailFilename', options.auditTrailFilename],\n ['signerEvidence', options.signerEvidence],\n ] as const) {\n if (typeof value !== 'string' || !value) {\n throw new Error(`ExecutedAgreement requires ${label}`);\n }\n }\n if (\n typeof options.sourceVersion !== 'number' ||\n !Number.isSafeInteger(options.sourceVersion) ||\n options.sourceVersion < 1\n ) {\n throw new Error('ExecutedAgreement requires a positive sourceVersion');\n }\n for (const [label, value] of [\n ['sourceSizeBytes', options.sourceSizeBytes],\n ['signedDocumentSizeBytes', options.signedDocumentSizeBytes],\n ['auditTrailSizeBytes', options.auditTrailSizeBytes],\n ] as const) {\n if (\n typeof value !== 'number' ||\n !Number.isSafeInteger(value) ||\n value < 1\n ) {\n throw new Error(`ExecutedAgreement requires a positive ${label}`);\n }\n }\n if (!coerceAgreementDate(options.acceptedAt)) {\n throw new Error('ExecutedAgreement requires a valid acceptedAt');\n }\n try {\n const signers = JSON.parse(options.signerEvidence ?? '') as unknown;\n if (\n !Array.isArray(signers) ||\n signers.length === 0 ||\n signers.some(\n (signer) =>\n !signer ||\n typeof signer !== 'object' ||\n (signer as { status?: unknown }).status !== 'signed',\n )\n ) {\n throw new Error('incomplete');\n }\n } catch {\n throw new Error(\n 'ExecutedAgreement requires non-empty signed signerEvidence',\n );\n }\n }\n\n async findVersionsBySource(\n sourceKind: string,\n sourceId: string,\n ): Promise<ExecutedAgreement[]> {\n return await this.list({\n where: { sourceKind, sourceId },\n orderBy: 'source_version DESC',\n });\n }\n\n async effectiveForSource(\n sourceKind: string,\n sourceId: string,\n at: Date = new Date(),\n ): Promise<ExecutedAgreement | null> {\n const versions = await this.findVersionsBySource(sourceKind, sourceId);\n return versions.find((agreement) => agreement.isEffectiveAt(at)) ?? null;\n }\n}\n\nexport default ExecutedAgreementCollection;\n","/** Provider-neutral signature orchestration and immutable evidence ingestion. */\n\nimport { createHash, randomUUID } from 'node:crypto';\nimport type {\n SignatureArtifact,\n SignatureByteSource,\n SignatureProvider,\n SignatureRequest,\n SignatureWebhookEvent,\n} from '@happyvertical/signatures';\nimport type { Asset, AssetRuntimeLike } from '@happyvertical/smrt-assets';\nimport { requireTenantId } from '@happyvertical/smrt-tenancy';\nimport type { AgreementExecutionCollection } from '../collections/AgreementExecutionCollection.js';\nimport type { AgreementExecutionEventCollection } from '../collections/AgreementExecutionEventCollection.js';\nimport type { ExecutedAgreementCollection } from '../collections/ExecutedAgreementCollection.js';\nimport type { AgreementExecution } from '../models/AgreementExecution.js';\nimport type { ExecutedAgreement } from '../models/ExecutedAgreement.js';\nimport type {\n AgreementExecutionResult,\n AgreementWebhookIngestionResult,\n CreateAgreementExecutionInput,\n IngestAgreementWebhookInput,\n} from '../types.js';\nimport {\n coerceAgreementDate,\n sanitizeSignerEvidence,\n sanitizeSignerIntent,\n} from '../types.js';\n\nexport interface AgreementExecutionServiceDeps {\n provider: SignatureProvider;\n assets: AssetRuntimeLike;\n executions: AgreementExecutionCollection;\n events: AgreementExecutionEventCollection;\n executedAgreements: ExecutedAgreementCollection;\n now?: () => Date;\n createLeaseDurationMs?: number;\n}\n\nexport interface AdoptAgreementProviderRequestInput {\n tenantId: string;\n executionId: string;\n providerRequestId: string;\n signal?: AbortSignal;\n}\n\nexport interface AgreementExecutionOperationInput {\n tenantId: string;\n executionId: string;\n signal?: AbortSignal;\n}\n\nexport interface CancelAgreementExecutionInput\n extends AgreementExecutionOperationInput {\n reason: string;\n}\n\nexport interface ExtendAgreementExecutionInput\n extends AgreementExecutionOperationInput {\n expiresAt: Date | string;\n warnPrior?: boolean;\n}\n\ninterface PersistAgreementLifecycleInput {\n status: AgreementExecution['status'];\n observedAt: Date;\n enforceEventOrder?: boolean;\n expiresAt?: Date;\n cancellationReason?: string;\n lastReconciledAt?: Date;\n completedAt?: Date;\n}\n\ninterface AuditedOperationStart {\n execution: AgreementExecution;\n operationId: string;\n}\n\nconst TERMINAL_STATUSES = new Set([\n 'completed',\n 'declined',\n 'cancelled',\n 'expired',\n 'failed',\n]);\n\nconst STATUS_PROGRESS = new Map([\n ['prepared', 0],\n ['sent', 1],\n ['delivered', 2],\n ['viewed', 3],\n ['partially_signed', 4],\n]);\n\nconst DEFAULT_CREATE_LEASE_DURATION_MS = 5 * 60 * 1000;\n\nexport class AgreementExecutionService {\n private readonly now: () => Date;\n private readonly createLeaseDurationMs: number;\n\n constructor(private readonly deps: AgreementExecutionServiceDeps) {\n this.now = deps.now ?? (() => new Date());\n this.createLeaseDurationMs =\n deps.createLeaseDurationMs ?? DEFAULT_CREATE_LEASE_DURATION_MS;\n if (\n !Number.isFinite(this.createLeaseDurationMs) ||\n this.createLeaseDurationMs <= 0\n ) {\n throw new Error('Agreement execution create lease must be positive');\n }\n }\n\n async createExecution(\n input: CreateAgreementExecutionInput,\n ): Promise<AgreementExecutionResult> {\n this.assertTenant(input.tenantId);\n this.assertProviderCapabilities();\n this.assertCreateInput(input);\n\n const sourceBytes = await readByteSource(input.document.data);\n if (sourceBytes.byteLength === 0) {\n throw new Error('Agreement execution document must not be empty');\n }\n const sourceSha256 = sha256(sourceBytes);\n const effectiveFrom = normalizeOptionalAgreementDate(\n input.effectiveFrom,\n 'effectiveFrom',\n );\n const effectiveTo = normalizeOptionalAgreementDate(\n input.effectiveTo,\n 'effectiveTo',\n );\n if (effectiveFrom && effectiveTo && effectiveTo < effectiveFrom) {\n throw new Error(\n 'Agreement execution effectiveTo must not precede effectiveFrom',\n );\n }\n const requestIntentSha256 = hashRequestIntent(\n input,\n this.deps.provider.capabilities.id,\n sourceSha256,\n effectiveFrom,\n effectiveTo,\n );\n\n const existing = await this.deps.executions.findByIdempotencyKey(\n input.idempotencyKey,\n );\n if (existing) {\n this.assertSameIntent(existing, input, requestIntentSha256);\n return await this.resumeOrReplayCreate(existing, input, sourceBytes);\n }\n\n const sourceAsset = await this.deps.assets.storeSourceAsset(\n input.document.name,\n sourceBytes,\n {\n mimeType: input.document.mediaType,\n typeSlug: 'agreement-source',\n sourceType: 'agreement-execution',\n externalId: input.idempotencyKey,\n metadata: {\n sourceKind: input.sourceKind,\n sourceId: input.sourceId,\n sourceVersion: input.sourceVersion,\n sha256: sourceSha256,\n },\n },\n );\n this.assertTenantValue(\n sourceAsset.tenantId,\n input.tenantId,\n 'source asset',\n );\n if (!sourceAsset.id) throw new Error('Stored source Asset has no id');\n\n const operationId = randomUUID();\n const createLeaseExpiresAt = this.newCreateLeaseExpiry();\n let execution: AgreementExecution;\n try {\n execution = await this.deps.executions.create({\n tenantId: input.tenantId,\n provider: this.deps.provider.capabilities.id,\n providerAccountRef: input.providerAccountRef ?? '',\n credentialRef: input.credentialRef ?? '',\n idempotencyKey: input.idempotencyKey,\n sourceKind: input.sourceKind,\n sourceId: input.sourceId,\n sourceVersion: input.sourceVersion,\n sourceAssetId: sourceAsset.id,\n sourceSha256,\n sourceSizeBytes: sourceBytes.byteLength,\n requestIntentSha256,\n title: input.title,\n signerIntent: JSON.stringify(sanitizeSignerIntent(input.signers)),\n status: 'prepared',\n effectiveFrom,\n effectiveTo,\n supersedesExecutedAgreementId:\n input.supersedesExecutedAgreementId ?? '',\n metadata: JSON.stringify(input.metadata ?? {}),\n // Persist the remote-attempt fence in the same INSERT that wins the\n // idempotency race. Other callers observe an in-flight attempt and\n // never issue a second provider create.\n attemptCount: 1,\n createLeaseId: operationId,\n createLeaseExpiresAt,\n _insertOnly: true,\n });\n } catch (error) {\n const raced = await this.deps.executions.findByIdempotencyKey(\n input.idempotencyKey,\n );\n if (!raced || raced.sourceAssetId !== sourceAsset.id) {\n await this.removeStoredAsset(sourceAsset);\n }\n if (!raced) throw error;\n this.assertSameIntent(raced, input, requestIntentSha256);\n return await this.resumeOrReplayCreate(raced, input, sourceBytes);\n }\n try {\n await this.ensureAssetAssociation(\n 'AgreementExecution',\n execution.id ?? '',\n sourceAsset.id,\n 'source_document',\n );\n } catch (error) {\n await this.failOwnedCreateAttempt(\n execution,\n operationId,\n summarizeError(error, false),\n );\n throw error;\n }\n return await this.sendProviderRequest(\n execution,\n input,\n sourceBytes,\n operationId,\n );\n }\n\n private async sendProviderRequest(\n execution: AgreementExecution,\n input: CreateAgreementExecutionInput,\n sourceBytes: Buffer,\n operationId: string,\n ): Promise<AgreementExecutionResult> {\n if (execution.createLeaseId !== operationId) {\n throw new Error(\n `AgreementExecution ${execution.id}: provider-create lease is not owned by this operation`,\n );\n }\n try {\n await this.recordOperationAudit(\n execution,\n operationId,\n 'create.started',\n 'system',\n { attemptCount: execution.attemptCount },\n );\n } catch (error) {\n // No provider mutation occurred, so a later idempotent caller may retry.\n await this.failOwnedCreateAttempt(\n execution,\n operationId,\n summarizeError(error, false),\n );\n throw error;\n }\n let request: SignatureRequest;\n let providerResponded = false;\n try {\n request = await this.deps.provider.createRequest({\n tenantId: input.tenantId,\n idempotencyKey: input.idempotencyKey,\n title: input.title,\n ...(input.message ? { message: input.message } : {}),\n documents: [\n {\n name: input.document.name,\n mediaType: input.document.mediaType,\n data: sourceBytes,\n },\n ],\n signers: input.signers,\n ...(input.signingOrder !== undefined\n ? { signingOrder: input.signingOrder }\n : {}),\n ...(input.expiresInDays !== undefined\n ? { expiresInDays: input.expiresInDays }\n : {}),\n metadata: {\n ...(input.metadata ?? {}),\n smrtExecutionId: execution.id ?? '',\n smrtSourceKind: input.sourceKind,\n smrtSourceId: input.sourceId,\n smrtSourceVersion: String(input.sourceVersion),\n smrtSourceSha256: execution.sourceSha256,\n },\n ...(input.signal ? { signal: input.signal } : {}),\n });\n providerResponded = true;\n this.assertProviderRequest(request, input.tenantId);\n await this.assertProviderRequestAvailable(execution, request.id);\n const completed = await this.deps.executions.completeCreateAttempt({\n tenantId: input.tenantId,\n executionId: execution.id ?? '',\n operationId,\n provider: execution.provider,\n providerRequestId: request.id,\n status: request.status,\n expiresAt: request.expiresAt ?? null,\n });\n if (completed) {\n execution = completed;\n } else {\n const latest = await this.requireExecution(execution.id ?? '');\n if (latest.providerRequestId !== request.id) {\n throw new Error(\n `AgreementExecution ${execution.id}: provider-create lease ownership changed before the provider result was persisted; reconcile the current attempt`,\n );\n }\n execution = latest;\n }\n } catch (error) {\n const mayHaveSucceeded =\n providerResponded || requestMayHaveSucceeded(error);\n const lastError = summarizeError(error, mayHaveSucceeded);\n execution = await this.failOwnedCreateAttempt(\n execution,\n operationId,\n lastError,\n );\n await this.recordOperationAudit(\n execution,\n operationId,\n mayHaveSucceeded ? 'create.uncertain' : 'create.failed',\n 'provider_operation',\n { error: lastError },\n );\n throw error;\n }\n // Keep the confirmed provider state when append-only audit persistence\n // fails. A replay can safely return the bound request and operators can\n // reconcile the missing audit outcome without duplicating the request.\n await this.recordOperationAudit(\n execution,\n operationId,\n 'create.succeeded',\n 'provider_operation',\n { providerRequestId: request.id },\n );\n return this.result(execution, execution.attemptCount > 1);\n }\n\n private async resumeOrReplayCreate(\n execution: AgreementExecution,\n input: CreateAgreementExecutionInput,\n sourceBytes: Buffer,\n ): Promise<AgreementExecutionResult> {\n if (execution.providerRequestId) return this.result(execution, true);\n const now = this.now();\n if (this.isCreateLeaseActive(execution, now)) {\n return this.result(execution, true);\n }\n const abandonedCreate = this.isAbandonedCreate(execution);\n if (\n abandonedCreate &&\n !this.deps.provider.capabilities.providerEnforcedIdempotency\n ) {\n throw new Error(\n `AgreementExecution ${execution.id}: the provider-create lease expired without a confirmed request id; reconcile or adopt the provider request before retrying`,\n );\n }\n if (!abandonedCreate && !this.canSafelyRetryCreate(execution)) {\n throw new Error(\n `AgreementExecution ${execution.id}: the prior provider create has no confirmed request id; reconcile or adopt the provider request before retrying`,\n );\n }\n await this.ensureAssetAssociation(\n 'AgreementExecution',\n execution.id ?? '',\n execution.sourceAssetId,\n 'source_document',\n );\n const operationId = randomUUID();\n const claimed = await this.deps.executions.claimCreateAttempt({\n tenantId: input.tenantId,\n executionId: execution.id ?? '',\n expectedAttemptCount: execution.attemptCount,\n expectedLeaseId: execution.createLeaseId,\n expectedStatus: execution.status,\n expectedLastError: execution.lastError,\n operationId,\n leaseExpiresAt: this.newCreateLeaseExpiry(now),\n now,\n });\n if (!claimed) {\n const latest = await this.requireExecution(execution.id ?? '');\n if (\n latest.providerRequestId ||\n this.isCreateLeaseActive(latest, this.now())\n ) {\n return this.result(latest, true);\n }\n throw new Error(\n `AgreementExecution ${execution.id}: provider-create state changed while claiming recovery; retry the operation`,\n );\n }\n return await this.sendProviderRequest(\n claimed,\n input,\n sourceBytes,\n operationId,\n );\n }\n\n /**\n * Bind an operator-reconciled provider request after an uncertain create.\n * This is the safe recovery path for providers without atomic idempotency.\n */\n async adoptProviderRequest(\n input: AdoptAgreementProviderRequestInput,\n ): Promise<AgreementExecutionResult> {\n this.assertTenant(input.tenantId);\n let execution = await this.requireExecution(input.executionId);\n if (\n execution.providerRequestId &&\n execution.providerRequestId !== input.providerRequestId\n ) {\n throw new Error(\n `AgreementExecution ${execution.id} is already bound to a different provider request`,\n );\n }\n const started = await this.beginAuditedOperation(\n execution,\n 'adopt',\n 'operator',\n );\n execution = started.execution;\n const { operationId } = started;\n try {\n const request = await this.deps.provider.getRequest({\n tenantId: input.tenantId,\n requestId: input.providerRequestId,\n ...(input.signal ? { signal: input.signal } : {}),\n });\n this.assertProviderRequest(\n request,\n input.tenantId,\n input.providerRequestId,\n );\n await this.assertProviderRequestAvailable(execution, request.id);\n const linkedExecutionId = request.metadata?.smrtExecutionId;\n if (linkedExecutionId && linkedExecutionId !== execution.id) {\n throw new Error(\n `Provider request '${request.id}' belongs to a different agreement execution`,\n );\n }\n execution = await this.bindProviderRequest(execution, request.id);\n const observedAt = this.now();\n execution = await this.applyProviderState(\n execution,\n request,\n observedAt,\n { lastReconciledAt: observedAt },\n );\n await this.completeAuditedOperation(execution, operationId, 'adopt', {\n providerRequestId: request.id,\n });\n return this.result(execution, false);\n } catch (error) {\n await this.failAuditedOperation(\n execution,\n operationId,\n 'adopt',\n error,\n false,\n );\n throw error;\n }\n }\n\n async reconcile(\n input: AgreementExecutionOperationInput,\n ): Promise<AgreementExecutionResult> {\n this.assertTenant(input.tenantId);\n let execution = await this.requireExecution(input.executionId);\n this.requireProviderRequestId(execution);\n const started = await this.beginAuditedOperation(\n execution,\n 'reconcile',\n 'system',\n );\n execution = started.execution;\n const { operationId } = started;\n try {\n const request = await this.deps.provider.getRequest({\n tenantId: input.tenantId,\n requestId: execution.providerRequestId,\n ...(input.signal ? { signal: input.signal } : {}),\n });\n this.assertProviderRequest(\n request,\n input.tenantId,\n execution.providerRequestId,\n );\n const observedAt = this.now();\n execution = await this.applyProviderState(\n execution,\n request,\n observedAt,\n { lastReconciledAt: observedAt },\n );\n if (execution.status === 'completed') {\n await this.finalizeExecution(execution);\n }\n await this.completeAuditedOperation(execution, operationId, 'reconcile', {\n providerStatus: request.status,\n });\n return this.result(execution, false);\n } catch (error) {\n await this.failAuditedOperation(\n execution,\n operationId,\n 'reconcile',\n error,\n false,\n );\n throw error;\n }\n }\n\n async cancel(\n input: CancelAgreementExecutionInput,\n ): Promise<AgreementExecutionResult> {\n this.assertTenant(input.tenantId);\n if (!input.reason.trim())\n throw new Error('Cancellation reason is required');\n let execution = await this.requireExecution(input.executionId);\n this.requireProviderRequestId(execution);\n if (execution.status === 'cancelled') return this.result(execution, true);\n this.assertNonTerminalOperation(execution, 'cancel');\n const started = await this.beginAuditedOperation(\n execution,\n 'cancel',\n 'operator',\n { reason: input.reason },\n );\n execution = started.execution;\n const { operationId } = started;\n let providerResponded = false;\n try {\n this.assertNonTerminalOperation(execution, 'cancel');\n const request = await this.deps.provider.cancelRequest({\n tenantId: input.tenantId,\n requestId: execution.providerRequestId,\n reason: input.reason,\n ...(input.signal ? { signal: input.signal } : {}),\n });\n providerResponded = true;\n this.assertProviderRequest(\n request,\n input.tenantId,\n execution.providerRequestId,\n );\n execution = await this.applyProviderState(\n execution,\n request,\n this.now(),\n { cancellationReason: input.reason },\n );\n await this.completeAuditedOperation(execution, operationId, 'cancel', {\n providerStatus: request.status,\n });\n return this.result(execution, false);\n } catch (error) {\n await this.failAuditedOperation(\n execution,\n operationId,\n 'cancel',\n error,\n true,\n providerResponded,\n );\n throw error;\n }\n }\n\n async extendExpiry(\n input: ExtendAgreementExecutionInput,\n ): Promise<AgreementExecutionResult> {\n this.assertTenant(input.tenantId);\n let execution = await this.requireExecution(input.executionId);\n this.requireProviderRequestId(execution);\n this.assertNonTerminalOperation(execution, 'extend expiry for');\n const started = await this.beginAuditedOperation(\n execution,\n 'extend_expiry',\n 'operator',\n {\n expiresAt: normalizeRequiredAgreementDate(\n input.expiresAt,\n ).toISOString(),\n },\n );\n execution = started.execution;\n const { operationId } = started;\n let providerResponded = false;\n try {\n this.assertNonTerminalOperation(execution, 'extend expiry for');\n const request = await this.deps.provider.extendExpiry({\n tenantId: input.tenantId,\n requestId: execution.providerRequestId,\n expiresAt: input.expiresAt,\n ...(input.warnPrior !== undefined\n ? { warnPrior: input.warnPrior }\n : {}),\n ...(input.signal ? { signal: input.signal } : {}),\n });\n providerResponded = true;\n this.assertProviderRequest(\n request,\n input.tenantId,\n execution.providerRequestId,\n );\n execution = await this.applyProviderState(execution, request, this.now());\n await this.completeAuditedOperation(\n execution,\n operationId,\n 'extend_expiry',\n { expiresAt: request.expiresAt?.toISOString() ?? null },\n );\n return this.result(execution, false);\n } catch (error) {\n await this.failAuditedOperation(\n execution,\n operationId,\n 'extend_expiry',\n error,\n true,\n providerResponded,\n );\n throw error;\n }\n }\n\n async ingestWebhook(\n input: IngestAgreementWebhookInput,\n ): Promise<AgreementWebhookIngestionResult> {\n this.assertTenant(input.tenantId);\n\n // The SDK adapter verifies authenticity and freshness before any state is\n // read or written. Signature headers are deliberately never persisted.\n const providerEvent = this.deps.provider.parseWebhook({\n payload: input.payload,\n signature: input.signature,\n });\n this.assertTenantValue(\n providerEvent.tenantId,\n input.tenantId,\n 'verified webhook',\n );\n if (providerEvent.provider !== this.deps.provider.capabilities.id) {\n throw new Error('Verified webhook provider does not match the adapter');\n }\n\n let execution = await this.deps.executions.findByProviderRequest(\n providerEvent.provider,\n providerEvent.requestId,\n );\n if (!execution) {\n throw new Error(\n `No AgreementExecution is bound to provider request '${providerEvent.requestId}'`,\n );\n }\n\n const dedupeKey = `${input.tenantId}:${providerEvent.provider}:${providerEvent.replay.deduplicationKey}`;\n const recorded = await this.deps.events.recordVerified({\n tenantId: input.tenantId,\n executionId: execution.id ?? '',\n provider: providerEvent.provider,\n providerEventId: providerEvent.id,\n eventOrigin: 'provider_webhook',\n dedupeKey,\n orderingKey: providerEvent.replay.orderingKey,\n eventType: providerEvent.type,\n status: providerEvent.status,\n occurredAt: providerEvent.createdAt,\n receivedAt: this.now(),\n payloadSha256: sha256(Buffer.from(input.payload, 'utf8')),\n signerEvidence: JSON.stringify(\n sanitizeSignerEvidence(providerEvent.signers),\n ),\n payload: input.payload,\n });\n\n execution = await this.persistLifecycleState(execution, {\n status: providerEvent.status,\n observedAt: providerEvent.createdAt,\n completedAt:\n providerEvent.status === 'completed'\n ? providerEvent.createdAt\n : undefined,\n });\n\n let executedAgreement: ExecutedAgreement | null = null;\n if (execution.status === 'completed') {\n const started = await this.beginAuditedOperation(\n execution,\n 'finalize',\n 'system',\n { providerEventId: providerEvent.id },\n );\n execution = started.execution;\n const { operationId } = started;\n try {\n executedAgreement = await this.finalizeExecution(\n execution,\n providerEvent,\n );\n await this.completeAuditedOperation(\n execution,\n operationId,\n 'finalize',\n { executedAgreementId: executedAgreement.id ?? '' },\n );\n } catch (error) {\n await this.failAuditedOperation(\n execution,\n operationId,\n 'finalize',\n error,\n false,\n );\n throw error;\n }\n }\n\n return {\n executionId: execution.id ?? '',\n eventId: recorded.event.id ?? '',\n replayed: !recorded.created,\n ...(executedAgreement?.id\n ? { executedAgreementId: executedAgreement.id }\n : {}),\n };\n }\n\n private async finalizeExecution(\n execution: AgreementExecution,\n verifiedEvent?: SignatureWebhookEvent,\n ): Promise<ExecutedAgreement> {\n this.assertTenant(execution.tenantId);\n const existing = await this.deps.executedAgreements.findByExecution(\n execution.id ?? '',\n );\n if (existing) {\n await this.ensureExecutedAgreementAssociations(existing);\n return existing;\n }\n this.requireProviderRequestId(execution);\n\n const request = await this.deps.provider.getRequest({\n tenantId: execution.tenantId,\n requestId: execution.providerRequestId,\n });\n this.assertProviderRequest(\n request,\n execution.tenantId,\n execution.providerRequestId,\n );\n if (request.status !== 'completed') {\n throw new Error(\n `Provider request '${request.id}' is '${request.status}', not completed`,\n );\n }\n\n const signedResult = await this.ensureEvidenceArtifact(\n execution,\n 'signed_document',\n );\n execution = signedResult.execution;\n const auditResult = await this.ensureEvidenceArtifact(\n execution,\n 'audit_trail',\n );\n // Reload after both compare-and-swap boundaries so every concurrent\n // finalizer constructs immutable evidence from the same persisted row.\n execution = await this.requireExecution(auditResult.execution.id ?? '');\n const signed = this.requireStoredArtifactMetadata(\n execution,\n 'signed_document',\n );\n const audit = this.requireStoredArtifactMetadata(execution, 'audit_trail');\n // The authenticated provider read is authoritative and complete; webhook\n // payloads may contain only the signer affected by that event.\n const signerEvidence = sanitizeSignerEvidence(request.signers);\n const acceptedAt =\n execution.completedAt ?? verifiedEvent?.createdAt ?? this.now();\n\n const created = await this.deps.executedAgreements.createImmutable({\n tenantId: execution.tenantId,\n executionId: execution.id ?? '',\n sourceKind: execution.sourceKind,\n sourceId: execution.sourceId,\n sourceVersion: execution.sourceVersion,\n sourceAssetId: execution.sourceAssetId,\n sourceSha256: execution.sourceSha256,\n sourceSizeBytes: execution.sourceSizeBytes,\n signedDocumentAssetId: signed.assetId,\n signedDocumentSha256: signed.sha256,\n signedDocumentSizeBytes: signed.sizeBytes,\n signedDocumentMediaType: signed.mediaType,\n signedDocumentFilename: signed.filename,\n auditTrailAssetId: audit.assetId,\n auditTrailSha256: audit.sha256,\n auditTrailSizeBytes: audit.sizeBytes,\n auditTrailMediaType: audit.mediaType,\n auditTrailFilename: audit.filename,\n signerEvidence: JSON.stringify(signerEvidence),\n acceptedAt,\n effectiveFrom: execution.effectiveFrom ?? acceptedAt,\n effectiveTo: execution.effectiveTo,\n supersedesExecutedAgreementId: execution.supersedesExecutedAgreementId,\n metadata: execution.metadata,\n });\n await this.ensureExecutedAgreementAssociations(created.agreement);\n return created.agreement;\n }\n\n private async ensureEvidenceArtifact(\n execution: AgreementExecution,\n kind: 'signed_document' | 'audit_trail',\n ): Promise<{\n execution: AgreementExecution;\n metadata: StoredArtifactMetadata;\n }> {\n const existing = this.getStoredArtifactMetadata(execution, kind);\n if (existing) {\n await this.ensureAssetAssociation(\n 'AgreementExecution',\n execution.id ?? '',\n existing.assetId,\n kind,\n );\n return { execution, metadata: existing };\n }\n\n const stored = await this.retrieveAndStoreArtifact(execution, kind);\n let bound: AgreementExecution | null;\n try {\n bound = await this.deps.executions.bindEvidenceArtifact({\n tenantId: execution.tenantId,\n executionId: execution.id ?? '',\n kind,\n ...stored.metadata,\n });\n } catch (error) {\n const latest = await this.requireExecution(execution.id ?? '');\n if (\n this.getStoredArtifactMetadata(latest, kind)?.assetId !==\n stored.asset.id\n ) {\n await this.removeStoredAsset(stored.asset);\n }\n throw error;\n }\n\n if (!bound) {\n await this.removeStoredAsset(stored.asset);\n bound = await this.requireExecution(execution.id ?? '');\n }\n const metadata = this.requireStoredArtifactMetadata(bound, kind);\n await this.ensureAssetAssociation(\n 'AgreementExecution',\n bound.id ?? '',\n metadata.assetId,\n kind,\n );\n return { execution: bound, metadata };\n }\n\n private async retrieveAndStoreArtifact(\n execution: AgreementExecution,\n kind: 'signed_document' | 'audit_trail',\n ): Promise<{ asset: Asset; metadata: StoredArtifactMetadata }> {\n const artifact = await this.deps.provider.downloadArtifact({\n tenantId: execution.tenantId,\n requestId: execution.providerRequestId,\n kind,\n });\n this.assertArtifact(artifact, execution, kind);\n const bytes = await readReadableStream(artifact.stream);\n if (bytes.byteLength === 0) {\n throw new Error(`Downloaded ${kind} artifact was empty`);\n }\n const computed = sha256(bytes);\n const providerHash = (await artifact.sha256).toLowerCase();\n if (computed !== providerHash) {\n throw new Error(\n `Downloaded ${kind} hash did not match the SDK evidence hash`,\n );\n }\n const asset = await this.deps.assets.storeSourceAsset(\n artifact.filename,\n bytes,\n {\n mimeType: artifact.mediaType,\n typeSlug: 'agreement-evidence',\n sourceType: execution.provider,\n externalId: `${execution.providerRequestId}:${kind}`,\n metadata: {\n executionId: execution.id,\n provider: execution.provider,\n providerRequestId: execution.providerRequestId,\n artifactKind: kind,\n sha256: computed,\n retrievedAt: artifact.retrievedAt.toISOString(),\n },\n },\n );\n this.assertTenantValue(asset.tenantId, execution.tenantId, `${kind} asset`);\n if (!asset.id) throw new Error(`Stored ${kind} Asset has no id`);\n return {\n asset,\n metadata: {\n assetId: asset.id,\n sha256: computed,\n sizeBytes: bytes.byteLength,\n filename: artifact.filename,\n mediaType: artifact.mediaType,\n },\n };\n }\n\n private getStoredArtifactMetadata(\n execution: AgreementExecution,\n kind: 'signed_document' | 'audit_trail',\n ): StoredArtifactMetadata | null {\n const metadata =\n kind === 'signed_document'\n ? {\n assetId: execution.signedDocumentAssetId,\n sha256: execution.signedDocumentSha256,\n sizeBytes: execution.signedDocumentSizeBytes,\n mediaType: execution.signedDocumentMediaType,\n filename: execution.signedDocumentFilename,\n }\n : {\n assetId: execution.auditTrailAssetId,\n sha256: execution.auditTrailSha256,\n sizeBytes: execution.auditTrailSizeBytes,\n mediaType: execution.auditTrailMediaType,\n filename: execution.auditTrailFilename,\n };\n if (!metadata.assetId) return null;\n if (\n !metadata.sha256 ||\n !Number.isSafeInteger(metadata.sizeBytes) ||\n metadata.sizeBytes < 1 ||\n !metadata.mediaType ||\n !metadata.filename\n ) {\n throw new Error(\n `AgreementExecution ${execution.id}: ${kind} evidence is incomplete`,\n );\n }\n return metadata;\n }\n\n private requireStoredArtifactMetadata(\n execution: AgreementExecution,\n kind: 'signed_document' | 'audit_trail',\n ): StoredArtifactMetadata {\n const metadata = this.getStoredArtifactMetadata(execution, kind);\n if (!metadata) {\n throw new Error(\n `AgreementExecution ${execution.id}: ${kind} evidence was not bound`,\n );\n }\n return metadata;\n }\n\n private async removeStoredAsset(asset: Asset): Promise<void> {\n await this.deps.assets.store.remove(asset);\n }\n\n private async ensureExecutedAgreementAssociations(\n agreement: ExecutedAgreement,\n ): Promise<void> {\n if (!agreement.id) throw new Error('ExecutedAgreement has no id');\n await this.ensureAssetAssociation(\n 'ExecutedAgreement',\n agreement.id,\n agreement.sourceAssetId,\n 'source_document',\n );\n await this.ensureAssetAssociation(\n 'ExecutedAgreement',\n agreement.id,\n agreement.signedDocumentAssetId,\n 'signed_document',\n );\n await this.ensureAssetAssociation(\n 'ExecutedAgreement',\n agreement.id,\n agreement.auditTrailAssetId,\n 'audit_trail',\n );\n }\n\n private async applyProviderState(\n execution: AgreementExecution,\n request: SignatureRequest,\n observedAt: Date,\n options: {\n cancellationReason?: string;\n lastReconciledAt?: Date;\n } = {},\n ): Promise<AgreementExecution> {\n return await this.persistLifecycleState(execution, {\n status: request.status,\n observedAt,\n // Authenticated request reads are authoritative even when a provider's\n // webhook clock is ahead of the local observation clock. The CAS still\n // preserves the greatest persisted observation timestamp.\n enforceEventOrder: false,\n ...(request.expiresAt ? { expiresAt: request.expiresAt } : {}),\n ...(options.cancellationReason !== undefined\n ? { cancellationReason: options.cancellationReason }\n : {}),\n ...(options.lastReconciledAt\n ? { lastReconciledAt: options.lastReconciledAt }\n : {}),\n ...(request.status === 'completed' ? { completedAt: observedAt } : {}),\n });\n }\n\n private async persistLifecycleState(\n execution: AgreementExecution,\n input: PersistAgreementLifecycleInput,\n ): Promise<AgreementExecution> {\n const executionId = execution.id ?? '';\n let current = await this.requireExecution(executionId);\n for (let attempt = 0; attempt < 8; attempt += 1) {\n if (\n input.enforceEventOrder !== false &&\n current.lastProviderEventAt &&\n input.observedAt < current.lastProviderEventAt\n ) {\n return current;\n }\n if (!canAdvanceStatus(current.status, input.status)) return current;\n const persistedObservedAt =\n input.enforceEventOrder === false &&\n current.lastProviderEventAt &&\n current.lastProviderEventAt > input.observedAt\n ? current.lastProviderEventAt\n : input.observedAt;\n\n const updated = await this.deps.executions.compareAndSetLifecycle({\n tenantId: current.tenantId,\n executionId,\n expectedStatus: current.status,\n status: input.status,\n expiresAt: input.expiresAt ?? current.expiresAt,\n cancellationReason:\n input.cancellationReason ?? current.cancellationReason,\n lastProviderEventAt: persistedObservedAt,\n lastReconciledAt: input.lastReconciledAt ?? current.lastReconciledAt,\n completedAt:\n input.status === 'completed'\n ? (current.completedAt ?? input.completedAt ?? input.observedAt)\n : current.completedAt,\n });\n if (updated) return updated;\n current = await this.requireExecution(executionId);\n }\n throw new Error(\n `AgreementExecution ${executionId}: lifecycle state remained contended; retry the operation`,\n );\n }\n\n private assertProviderRequest(\n request: SignatureRequest,\n tenantId: string,\n expectedRequestId?: string,\n ): void {\n this.assertTenantValue(request.tenantId, tenantId, 'provider request');\n if (request.provider !== this.deps.provider.capabilities.id) {\n throw new Error('Provider request does not match the configured adapter');\n }\n if (!request.id) throw new Error('Provider request has no id');\n if (expectedRequestId && request.id !== expectedRequestId) {\n throw new Error(\n `Provider returned request '${request.id}' while '${expectedRequestId}' was requested`,\n );\n }\n }\n\n private assertArtifact(\n artifact: SignatureArtifact,\n execution: AgreementExecution,\n kind: 'signed_document' | 'audit_trail',\n ): void {\n this.assertTenantValue(artifact.tenantId, execution.tenantId, kind);\n if (\n artifact.provider !== execution.provider ||\n artifact.requestId !== execution.providerRequestId ||\n artifact.kind !== kind\n ) {\n throw new Error(`Downloaded ${kind} does not match its execution`);\n }\n }\n\n private assertProviderCapabilities(): void {\n const caps = this.deps.provider.capabilities;\n if (\n !caps.supportsWebhooks ||\n !caps.supportsCancellation ||\n !caps.supportsExpiryExtension ||\n !caps.supportsSignedDocument ||\n !caps.supportsAuditTrail\n ) {\n throw new Error(\n `Signature provider '${caps.id}' lacks required agreement-execution capabilities`,\n );\n }\n }\n\n private assertSameIntent(\n existing: AgreementExecution,\n input: CreateAgreementExecutionInput,\n requestIntentSha256: string,\n ): void {\n if (\n existing.provider !== this.deps.provider.capabilities.id ||\n existing.sourceKind !== input.sourceKind ||\n existing.sourceId !== input.sourceId ||\n existing.sourceVersion !== input.sourceVersion ||\n existing.title !== input.title ||\n existing.requestIntentSha256 !== requestIntentSha256\n ) {\n throw new Error(\n `Idempotency key '${input.idempotencyKey}' belongs to a different agreement execution`,\n );\n }\n }\n\n private assertCreateInput(input: CreateAgreementExecutionInput): void {\n for (const [label, value] of [\n ['idempotencyKey', input.idempotencyKey],\n ['sourceKind', input.sourceKind],\n ['sourceId', input.sourceId],\n ['title', input.title],\n ['document.name', input.document.name],\n ['document.mediaType', input.document.mediaType],\n ] as const) {\n if (!value.trim()) {\n throw new Error(`Agreement execution ${label} is required`);\n }\n }\n if (!Number.isSafeInteger(input.sourceVersion) || input.sourceVersion < 1) {\n throw new Error(\n 'Agreement execution sourceVersion must be a positive integer',\n );\n }\n if (\n input.expiresInDays !== undefined &&\n (!Number.isSafeInteger(input.expiresInDays) || input.expiresInDays < 1)\n ) {\n throw new Error(\n 'Agreement execution expiresInDays must be a positive integer',\n );\n }\n if (\n input.credentialRef &&\n !/^[a-z][a-z0-9+.-]*:\\/\\//i.test(input.credentialRef)\n ) {\n throw new Error(\n 'Agreement execution credentialRef must be a secret-store reference URI',\n );\n }\n if (input.signers.length === 0) {\n throw new Error('Agreement execution requires at least one signer');\n }\n }\n\n private async requireExecution(id: string): Promise<AgreementExecution> {\n const execution = await this.deps.executions.get({ id });\n if (!execution) throw new Error(`AgreementExecution '${id}' was not found`);\n return execution;\n }\n\n private requireProviderRequestId(execution: AgreementExecution): void {\n if (!execution.providerRequestId) {\n throw new Error(\n `AgreementExecution ${execution.id}: provider request is not confirmed; reconcile or adopt it first`,\n );\n }\n }\n\n private async assertProviderRequestAvailable(\n execution: AgreementExecution,\n providerRequestId: string,\n ): Promise<void> {\n const bound = await this.deps.executions.findByProviderRequest(\n execution.provider,\n providerRequestId,\n );\n if (bound && bound.id !== execution.id) {\n throw new Error(\n `Provider request '${providerRequestId}' is already bound to another AgreementExecution`,\n );\n }\n }\n\n private async bindProviderRequest(\n execution: AgreementExecution,\n providerRequestId: string,\n ): Promise<AgreementExecution> {\n if (execution.providerRequestId === providerRequestId) return execution;\n // The derived unique providerRequestKey closes the race left by the\n // application-level availability check without saving stale lifecycle\n // fields from the service snapshot.\n const bound = await this.deps.executions.bindProviderRequest({\n tenantId: execution.tenantId,\n executionId: execution.id ?? '',\n provider: execution.provider,\n providerRequestId,\n });\n if (!bound) {\n const current = await this.requireExecution(execution.id ?? '');\n if (current.providerRequestId === providerRequestId) return current;\n throw new Error(\n `AgreementExecution ${execution.id}: provider request binding changed concurrently`,\n );\n }\n return bound;\n }\n\n private canSafelyRetryCreate(execution: AgreementExecution): boolean {\n if (execution.attemptCount === 0 && execution.status === 'prepared') {\n return true;\n }\n try {\n const summary = JSON.parse(execution.lastError) as {\n requestMayHaveSucceeded?: unknown;\n };\n return summary.requestMayHaveSucceeded === false;\n } catch {\n return false;\n }\n }\n\n private isAbandonedCreate(execution: AgreementExecution): boolean {\n return (\n execution.status === 'prepared' &&\n execution.attemptCount > 0 &&\n !execution.providerRequestId &&\n !execution.lastError\n );\n }\n\n private isCreateLeaseActive(\n execution: AgreementExecution,\n at: Date,\n ): boolean {\n return Boolean(\n this.isAbandonedCreate(execution) &&\n execution.createLeaseId &&\n execution.createLeaseExpiresAt &&\n execution.createLeaseExpiresAt.getTime() > at.getTime(),\n );\n }\n\n private newCreateLeaseExpiry(from = this.now()): Date {\n return new Date(from.getTime() + this.createLeaseDurationMs);\n }\n\n private async failOwnedCreateAttempt(\n execution: AgreementExecution,\n operationId: string,\n lastError: string,\n ): Promise<AgreementExecution> {\n return (\n (await this.deps.executions.failCreateAttempt({\n tenantId: execution.tenantId,\n executionId: execution.id ?? '',\n operationId,\n lastError,\n })) ?? (await this.requireExecution(execution.id ?? ''))\n );\n }\n\n private async ensureAssetAssociation(\n ownerType: 'AgreementExecution' | 'ExecutedAgreement',\n ownerId: string,\n assetId: string,\n role: 'source_document' | 'signed_document' | 'audit_trail',\n ): Promise<void> {\n if (!ownerId || !assetId) {\n throw new Error(`Cannot link ${role}: owner and Asset ids are required`);\n }\n await this.deps.assets.associations.attach(\n `@happyvertical/smrt-sales:${ownerType}`,\n ownerId,\n assetId,\n { role },\n );\n }\n\n private async beginAuditedOperation(\n execution: AgreementExecution,\n operation: string,\n origin: 'operator' | 'system',\n metadata: Record<string, unknown> = {},\n ): Promise<AuditedOperationStart> {\n const current = await this.deps.executions.incrementAttemptCount(\n execution.tenantId,\n execution.id ?? '',\n );\n const operationId = randomUUID();\n try {\n await this.recordOperationAudit(\n current,\n operationId,\n `${operation}.started`,\n origin,\n { attemptCount: current.attemptCount, ...metadata },\n );\n } catch (error) {\n await this.deps.executions.updateLastError({\n tenantId: current.tenantId,\n executionId: current.id ?? '',\n lastError: summarizeError(error, false),\n });\n throw error;\n }\n return { execution: current, operationId };\n }\n\n private async completeAuditedOperation(\n execution: AgreementExecution,\n operationId: string,\n operation: string,\n metadata: Record<string, unknown>,\n ): Promise<void> {\n await this.recordOperationAudit(\n execution,\n operationId,\n `${operation}.succeeded`,\n 'provider_operation',\n metadata,\n );\n }\n\n private async failAuditedOperation(\n execution: AgreementExecution,\n operationId: string,\n operation: string,\n error: unknown,\n mayMutateProvider: boolean,\n providerMutationConfirmed = false,\n ): Promise<void> {\n // Write diagnostics as a partial update so failure handling cannot erase a\n // concurrent lifecycle, provider-request, or evidence CAS winner.\n const current = await this.deps.executions.updateLastError({\n tenantId: execution.tenantId,\n executionId: execution.id ?? '',\n lastError: summarizeError(error),\n });\n const uncertain =\n mayMutateProvider &&\n (providerMutationConfirmed || isPotentiallyUncertain(error));\n await this.recordOperationAudit(\n current,\n operationId,\n `${operation}.${uncertain ? 'uncertain' : 'failed'}`,\n 'provider_operation',\n { error: current.lastError },\n );\n }\n\n private async recordOperationAudit(\n execution: AgreementExecution,\n operationId: string,\n eventType: string,\n eventOrigin: 'operator' | 'provider_operation' | 'system',\n metadata: Record<string, unknown>,\n ): Promise<void> {\n const occurredAt = this.now();\n const payload = JSON.stringify(metadata);\n await this.deps.events.recordVerified({\n tenantId: execution.tenantId,\n executionId: execution.id ?? '',\n provider: execution.provider,\n providerEventId: '',\n eventOrigin,\n operationId,\n dedupeKey: `${execution.tenantId}:${execution.provider}:operation:${operationId}:${eventType}`,\n orderingKey: execution.providerRequestId || execution.id || operationId,\n eventType: `operation.${eventType}`,\n status: execution.status,\n occurredAt,\n receivedAt: occurredAt,\n payloadSha256: sha256(Buffer.from(payload, 'utf8')),\n signerEvidence: '[]',\n payload,\n });\n }\n\n private assertNonTerminalOperation(\n execution: AgreementExecution,\n operation: string,\n ): void {\n if (TERMINAL_STATUSES.has(execution.status)) {\n throw new Error(\n `Cannot ${operation} terminal AgreementExecution ${execution.id} in status '${execution.status}'`,\n );\n }\n }\n\n private result(\n execution: AgreementExecution,\n replayed: boolean,\n ): AgreementExecutionResult {\n return {\n executionId: execution.id ?? '',\n ...(execution.providerRequestId\n ? { providerRequestId: execution.providerRequestId }\n : {}),\n status: execution.status,\n replayed,\n };\n }\n\n private assertTenant(expected: string): void {\n this.assertTenantValue(requireTenantId(), expected, 'tenant context');\n }\n\n private assertTenantValue(\n actual: string | null | undefined,\n expected: string,\n context: string,\n ): void {\n if (actual !== expected) {\n throw new Error(\n `Agreement execution tenant mismatch for ${context}: expected '${expected}'`,\n );\n }\n }\n}\n\ninterface StoredArtifactMetadata {\n assetId: string;\n sha256: string;\n sizeBytes: number;\n filename: string;\n mediaType: string;\n}\n\nfunction sha256(data: Uint8Array): string {\n return createHash('sha256').update(data).digest('hex');\n}\n\nfunction hashRequestIntent(\n input: CreateAgreementExecutionInput,\n provider: string,\n sourceSha256: string,\n effectiveFrom: Date | null,\n effectiveTo: Date | null,\n): string {\n const sortedMetadata = Object.fromEntries(\n Object.entries(input.metadata ?? {}).sort(([left], [right]) =>\n left.localeCompare(right),\n ),\n );\n return sha256(\n Buffer.from(\n JSON.stringify({\n provider,\n providerAccountRef: input.providerAccountRef ?? '',\n credentialRef: input.credentialRef ?? '',\n sourceKind: input.sourceKind,\n sourceId: input.sourceId,\n sourceVersion: input.sourceVersion,\n sourceSha256,\n documentName: input.document.name,\n documentMediaType: input.document.mediaType,\n title: input.title,\n messageSha256: input.message\n ? sha256(Buffer.from(input.message, 'utf8'))\n : '',\n signers: input.signers.map((signer) => ({\n ...sanitizeSignerIntent([signer])[0],\n privateMessageSha256: signer.privateMessage\n ? sha256(Buffer.from(signer.privateMessage, 'utf8'))\n : '',\n phoneSha256: signer.authentication?.phone\n ? sha256(\n Buffer.from(\n `${signer.authentication.phone.countryCode}:${signer.authentication.phone.number}`,\n 'utf8',\n ),\n )\n : '',\n identityVerification:\n signer.authentication?.identityVerification ?? null,\n fields: signer.fields.map((field) => ({\n id: field.id,\n type: field.type,\n page: field.page,\n bounds: field.bounds,\n required: field.required ?? true,\n valueSha256: field.value\n ? sha256(Buffer.from(field.value, 'utf8'))\n : '',\n })),\n })),\n signingOrder: input.signingOrder ?? false,\n expiresInDays: input.expiresInDays ?? null,\n effectiveFrom: effectiveFrom?.toISOString() ?? null,\n effectiveTo: effectiveTo?.toISOString() ?? null,\n supersedesExecutedAgreementId:\n input.supersedesExecutedAgreementId ?? '',\n metadata: sortedMetadata,\n }),\n 'utf8',\n ),\n );\n}\n\nfunction normalizeOptionalAgreementDate(\n value: Date | string | number | null | undefined,\n label: string,\n): Date | null {\n if (value == null) return null;\n const date = coerceAgreementDate(value);\n if (!date) throw new Error(`Agreement execution ${label} is invalid`);\n return date;\n}\n\nfunction normalizeRequiredAgreementDate(value: Date | string): Date {\n const date = coerceAgreementDate(value);\n if (!date) throw new Error('Agreement execution expiresAt is invalid');\n return date;\n}\n\nasync function readByteSource(source: SignatureByteSource): Promise<Buffer> {\n if (source instanceof Uint8Array) return Buffer.from(source);\n if (isReadableStream(source)) return await readReadableStream(source);\n const chunks: Uint8Array[] = [];\n for await (const chunk of source) chunks.push(chunk);\n return Buffer.concat(chunks.map((chunk) => Buffer.from(chunk)));\n}\n\nasync function readReadableStream(\n stream: ReadableStream<Uint8Array>,\n): Promise<Buffer> {\n const reader = stream.getReader();\n const chunks: Buffer[] = [];\n try {\n while (true) {\n const result = await reader.read();\n if (result.done) break;\n chunks.push(Buffer.from(result.value));\n }\n } finally {\n reader.releaseLock();\n }\n return Buffer.concat(chunks);\n}\n\nfunction isReadableStream(\n value: SignatureByteSource,\n): value is ReadableStream<Uint8Array> {\n return typeof (value as ReadableStream<Uint8Array>).getReader === 'function';\n}\n\nfunction summarizeError(\n error: unknown,\n requestMayHaveSucceededOverride?: boolean,\n): string {\n const candidate = (error && typeof error === 'object' ? error : {}) as {\n name?: unknown;\n code?: unknown;\n status?: unknown;\n retryable?: unknown;\n requestMayHaveSucceeded?: unknown;\n };\n return JSON.stringify({\n name: typeof candidate.name === 'string' ? candidate.name : 'Error',\n ...(typeof candidate.code === 'string' ? { code: candidate.code } : {}),\n ...(typeof candidate.status === 'number'\n ? { status: candidate.status }\n : {}),\n ...(typeof candidate.retryable === 'boolean'\n ? { retryable: candidate.retryable }\n : {}),\n ...(requestMayHaveSucceededOverride !== undefined\n ? { requestMayHaveSucceeded: requestMayHaveSucceededOverride }\n : typeof candidate.requestMayHaveSucceeded === 'boolean'\n ? { requestMayHaveSucceeded: candidate.requestMayHaveSucceeded }\n : {}),\n });\n}\n\nfunction requestMayHaveSucceeded(error: unknown): boolean {\n return Boolean(\n error &&\n typeof error === 'object' &&\n (error as { requestMayHaveSucceeded?: unknown })\n .requestMayHaveSucceeded === true,\n );\n}\n\nfunction isPotentiallyUncertain(error: unknown): boolean {\n if (requestMayHaveSucceeded(error)) return true;\n return Boolean(\n error &&\n typeof error === 'object' &&\n (error as { retryable?: unknown }).retryable === true,\n );\n}\n\nfunction canAdvanceStatus(\n current: AgreementExecution['status'],\n next: AgreementExecution['status'],\n): boolean {\n if (current === next) return true;\n // `failed` is also used for local orchestration failures before a provider\n // request is adopted; an authoritative provider read may recover it.\n if (current === 'failed') return true;\n if (TERMINAL_STATUSES.has(current)) return false;\n if (TERMINAL_STATUSES.has(next)) return true;\n return (\n (STATUS_PROGRESS.get(next) ?? -1) >= (STATUS_PROGRESS.get(current) ?? -1)\n );\n}\n\nexport default AgreementExecutionService;\n"],"mappings":";;;;AAWO,IAAM,+BAA+B;CAC1C;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAyJO,SAAS,qBACd,SACyB;CACzB,OAAO,QAAQ,KAAK,YAAY;EAC9B,MAAM,OAAO;EACb,OAAO,OAAO;EACd,GAAI,OAAO,OAAO,EAAE,MAAM,OAAO,KAAK,IAAI,CAAC;EAC3C,GAAI,OAAO,UAAU,KAAA,IAAY,EAAE,OAAO,OAAO,MAAM,IAAI,CAAC;EAC5D,sBAAsB,OAAO,gBAAgB,UAAU;CACzD,EAAE;AACJ;AAEO,SAAS,uBACd,SACmB;CACnB,OAAO,QAAQ,KAAK,YAAY;EAC9B,GAAI,OAAO,KAAK,EAAE,IAAI,OAAO,GAAG,IAAI,CAAC;EACrC,MAAM,OAAO;EACb,OAAO,OAAO;EACd,GAAI,OAAO,OAAO,EAAE,MAAM,OAAO,KAAK,IAAI,CAAC;EAC3C,GAAI,OAAO,UAAU,KAAA,IAAY,EAAE,OAAO,OAAO,MAAM,IAAI,CAAC;EAC5D,QAAQ,OAAO;E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