@decionis/mcp 0.1.0 → 0.1.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.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../protocol/src/app.ts","../../protocol/src/store/MemoryProtocolStore.ts","../../protocol/src/ledger/LedgerChain.ts","../../protocol/src/store/StoreContracts.ts","../../protocol/src/store/StoreHelpers.ts","../../protocol/src/auth/McpAuth.ts","../../protocol/src/mcp/McpContracts.ts","../../protocol/src/mcp/McpSupport.ts","../../protocol/src/mcp/McpAuthGuard.ts","../../protocol/src/mcp/McpRoutes.ts","../../../packages/shared/src/Connectors/ConnectorRegistry.ts","../../protocol/src/mcp/McpResources.ts","../../protocol/src/mcp/McpPrompts.ts","../../protocol/src/mcp/McpTools.ts","../../protocol/src/execution-gating/ExecutionGatingSupport.ts","../../protocol/src/execution-gating/ExecutionGatingService.ts","../../protocol/src/execution-gating/ExecutionGatingRoutes.ts","../../protocol/src/support/Parsing.ts","../../protocol/src/support/Hashing.ts","../../protocol/src/integrity/DossierIntegrity.ts","../../protocol/src/policy-graph/PolicyGraph.ts","../../protocol/src/agent-gateway/AgentTaskPolicyResolver.ts","../../protocol/src/agent-gateway/MemoryAgentTaskReservationStore.ts","../../protocol/src/agent-gateway/AgentTaskCostEstimator.ts","../../protocol/src/agent-gateway/AgentTaskIntentParser.ts","../../protocol/src/agent-gateway/AgentTaskGatewayService.ts","../../protocol/src/agent-gateway/AgentGatewayAuthGuard.ts","../../protocol/src/agent-gateway/AgentProviderProxy.ts","../../protocol/src/agent-gateway/providers/AnthropicProviderAdapter.ts","../../protocol/src/agent-gateway/providers/AgentProviderAdapter.ts","../../protocol/src/agent-gateway/providers/OpenAiProviderAdapter.ts","../../protocol/src/agent-gateway/providers/AgentProviderRegistry.ts","../../protocol/src/agent-gateway/AgentTaskGatewayRoutes.ts","../../protocol/src/ProtocolInfo.ts","../../protocol/src/health/HealthRoutes.ts","../../protocol/src/finance-overrides/FinanceOverrideRoutes.ts","../../protocol/src/validation/ProtocolArtifacts.ts","../../../docs/decionis.protocol.schemas/v1/audit-ledger-entry.schema.json","../../../docs/decionis.protocol.schemas/v1/context-snapshot.schema.json","../../../docs/decionis.protocol.schemas/v1/decision-resolution.schema.json","../../../docs/decionis.protocol.schemas/v1/execution-dispatch.schema.json","../../../docs/decionis.protocol.schemas/v1/policy-bundle.schema.json","../../../docs/decionis.protocol.schemas/v1/signal-envelope.schema.json","../../protocol/src/finance-overrides/FinanceOverrideContracts.ts","../../protocol/src/finance-overrides/FinanceOverrides.ts","../../protocol/src/evaluate-decision/EvaluateDecisionRoutes.ts","../../protocol/src/support/Performance.ts","../../protocol/src/verticals/affiliate-rewards/AffiliateRewardsPack.ts","../../protocol/src/verticals/core/CorePack.ts","../../protocol/src/verticals/devops/DevopsPack.ts","../../protocol/src/verticals/finance/FinancePack.ts","../../protocol/src/verticals/hospitality/HospitalityPack.ts","../../../packages/shared/src/Verticals/OpsDualGate.ts","../../protocol/src/verticals/personal/PersonalPack.ts","../../protocol/src/verticals/salesforce/SalesforcePack.ts","../../protocol/src/verticals/sap/SapPack.ts","../../protocol/src/verticals/template/TemplatePack.ts","../../protocol/src/verticals/workday/WorkdayPack.ts","../../protocol/src/verticals/workday-financials/WorkdayFinancialsPack.ts","../../protocol/src/verticals/workflows/WorkflowPacks.ts","../../protocol/src/verticals/VerticalRegistry.ts","../../protocol/src/verticals/VerticalResolver.ts","../../protocol/src/decision-chains/DecisionChains.ts","../../protocol/src/integrity/DossierProofBundle.ts","../../protocol/src/support/PanDetection.ts","../../protocol/src/support/ProtocolUrls.ts","../../protocol/src/evaluate-decision/EvaluateDecisionParsing.ts","../../protocol/src/webex/WebexGovernance.ts","../../protocol/src/dossiers/DossierBuilder.ts","../../protocol/src/reproduce/ReproduceDecision.ts","../../protocol/src/support/FeatureFlags.ts","../../protocol/src/evaluate-decision/EvaluateDecisionGovernance.ts","../../protocol/src/evaluate-decision/EvaluateDecisionResolution.ts","../../protocol/src/webex/WebexRoutes.ts","../../protocol/src/surface-verify/SapVerifyRoutes.ts","../../protocol/src/verticals/sap/SapSurface.ts","../../protocol/src/verticals/shared/DuplicateDetection.ts","../../protocol/src/surface-verify/SurfaceVerifyShared.ts","../../protocol/src/surface-verify/SalesforceVerifyRoutes.ts","../../protocol/src/verticals/salesforce/SalesforceSurface.ts","../../protocol/src/verticals/salesforce/SapCostBasis.ts","../../protocol/src/surface-verify/OpsVerifyRoutes.ts","../../protocol/src/verticals/ops/OpsSurface.ts","../../protocol/src/surface-verify/WorkdayVerifyRoutes.ts","../../protocol/src/verticals/workday/WorkdaySurface.ts","../../protocol/src/surface-verify/WorkdayFinancialsVerifyRoutes.ts","../../protocol/src/verticals/workday-financials/WorkdayFinancialsSurface.ts","../../protocol/src/surface-verify/SurfaceDecisionRoutes.ts","../../protocol/src/enforcement/EnforcementRolloutRoutes.ts","../../protocol/src/integrity/DossierProofVerifier.ts","../../protocol/src/integrity/ProofPacket.ts","../../protocol/src/dossiers/ProofPacketAuth.ts","../../protocol/src/dossiers/DossierRoutes.ts","../../protocol/src/decision-chains/DecisionChainRoutes.ts","../../protocol/src/artifacts/ArtifactIngestion.ts","../../protocol/src/artifacts/ArtifactRoutes.ts","../../protocol/src/marketplaces/MarketplaceProfiles.ts","../../protocol/src/marketplaces/MarketplaceContracts.ts","../../protocol/src/marketplaces/MarketplaceRoutes.ts","../../protocol/src/verticals/VerticalRoutes.ts","../../protocol/src/shadow/ShadowRoutes.ts","../../protocol/src/shadow/ShadowDecisioning.ts","../../protocol/src/shadow/ShadowReports.ts","../src/RulesBlock.ts","../src/Gateway.ts","../src/agent/PolicyFileRepository.ts"],"sourcesContent":["import Fastify, { type FastifyInstance } from \"fastify\";\nimport { createMemoryProtocolStore } from \"./store/MemoryProtocolStore.js\";\nimport type { ProtocolStore } from \"./store/StoreContracts.js\";\nimport type { ProtocolMcpAuthLookup } from \"./auth/McpAuth.js\";\nimport { registerProtocolMcpRoutes } from \"./mcp.js\";\nimport type { McpTelemetrySink } from \"./mcp/McpTelemetry.js\";\nimport {\n createExecutionGatingService,\n registerExecutionGatingRoutes,\n type ExecutionGatingOptions,\n} from \"./execution-gating/ExecutionGating.js\";\nimport type {\n AgentTaskPolicyResolver,\n AgentTaskReservationStore,\n} from \"./agent-gateway/AgentTaskContracts.js\";\nimport { PolicyGraphAgentTaskPolicyResolver } from \"./agent-gateway/AgentTaskPolicyResolver.js\";\nimport { createMemoryAgentTaskReservationStore } from \"./agent-gateway/MemoryAgentTaskReservationStore.js\";\nimport { AgentTaskGatewayService } from \"./agent-gateway/AgentTaskGatewayService.js\";\nimport { AgentTaskGatewayRoutes } from \"./agent-gateway/AgentTaskGatewayRoutes.js\";\nimport type { AgentProviderProxyOptions } from \"./agent-gateway/AgentProviderProxy.js\";\nimport { PROTOCOL_SERVICE, PROTOCOL_VERSION } from \"./ProtocolInfo.js\";\nimport { registerHealthRoutes } from \"./health/HealthRoutes.js\";\nimport { registerFinanceOverrideRoutes } from \"./finance-overrides/FinanceOverrideRoutes.js\";\nimport { registerEvaluateDecisionRoutes } from \"./evaluate-decision/EvaluateDecisionRoutes.js\";\nimport { registerWebexRoutes } from \"./webex/WebexRoutes.js\";\nimport { registerSapVerifyRoutes } from \"./surface-verify/SapVerifyRoutes.js\";\nimport { registerSalesforceVerifyRoutes } from \"./surface-verify/SalesforceVerifyRoutes.js\";\nimport { registerOpsVerifyRoutes } from \"./surface-verify/OpsVerifyRoutes.js\";\nimport { registerWorkdayVerifyRoutes } from \"./surface-verify/WorkdayVerifyRoutes.js\";\nimport { registerWorkdayFinancialsVerifyRoutes } from \"./surface-verify/WorkdayFinancialsVerifyRoutes.js\";\nimport { registerSurfaceDecisionRoutes } from \"./surface-verify/SurfaceDecisionRoutes.js\";\nimport { registerEnforcementRolloutRoutes } from \"./enforcement/EnforcementRolloutRoutes.js\";\nimport { registerDossierRoutes } from \"./dossiers/DossierRoutes.js\";\nimport { registerDecisionChainRoutes } from \"./decision-chains/DecisionChainRoutes.js\";\nimport { registerArtifactRoutes } from \"./artifacts/ArtifactRoutes.js\";\nimport { registerMarketplaceRoutes } from \"./marketplaces/MarketplaceRoutes.js\";\nimport { registerVerticalRoutes } from \"./verticals/VerticalRoutes.js\";\nimport { registerShadowRoutes } from \"./shadow/ShadowRoutes.js\";\n\nexport { PROTOCOL_SERVICE, PROTOCOL_VERSION } from \"./ProtocolInfo.js\";\n\nexport function buildProtocolApp(options?: {\n store?: ProtocolStore;\n mcpAuthLookup?: ProtocolMcpAuthLookup | null;\n mcpTelemetry?: McpTelemetrySink | null;\n executionGating?: ExecutionGatingOptions;\n agentTaskStore?: AgentTaskReservationStore;\n agentTaskPolicyResolver?: AgentTaskPolicyResolver;\n agentProviderProxy?: AgentProviderProxyOptions;\n /** Disable for embedded hosts whose stdout is a protocol channel (local MCP). */\n logger?: boolean;\n}): FastifyInstance {\n const app = Fastify({\n logger: options?.logger ?? true,\n });\n\n const store = options?.store ?? createMemoryProtocolStore();\n\n app.setErrorHandler((err, _req, reply) => {\n const maybeStatusCode = (err as { statusCode?: number }).statusCode;\n const statusCode = typeof maybeStatusCode === \"number\" ? maybeStatusCode : 500;\n\n if (statusCode >= 500) {\n app.log.error({ err }, \"Unhandled protocol error\");\n }\n\n return reply.code(statusCode).send({\n error: statusCode >= 500 ? \"INTERNAL_ERROR\" : \"BAD_REQUEST\",\n message:\n statusCode >= 500\n ? \"Unexpected protocol service error\"\n : err instanceof Error\n ? err.message\n : \"Invalid request\",\n });\n });\n\n registerHealthRoutes(app, { store });\n\n registerFinanceOverrideRoutes(app, { store });\n\n registerEvaluateDecisionRoutes(app, { store });\n\n registerWebexRoutes(app, { store });\n\n const protocolAuthLookup = options?.mcpAuthLookup ?? null;\n\n registerSapVerifyRoutes(app, { store, authLookup: protocolAuthLookup });\n registerSalesforceVerifyRoutes(app, { store, authLookup: protocolAuthLookup });\n registerOpsVerifyRoutes(app, { store, authLookup: protocolAuthLookup });\n registerWorkdayVerifyRoutes(app, { store, authLookup: protocolAuthLookup });\n registerWorkdayFinancialsVerifyRoutes(app, { store, authLookup: protocolAuthLookup });\n registerSurfaceDecisionRoutes(app, { store, authLookup: protocolAuthLookup });\n\n registerEnforcementRolloutRoutes(app, { store });\n\n registerDossierRoutes(app, { store, authLookup: protocolAuthLookup });\n\n registerDecisionChainRoutes(app, { store, authLookup: protocolAuthLookup });\n\n registerArtifactRoutes(app, { store });\n\n registerMarketplaceRoutes(app);\n\n registerVerticalRoutes(app, { store });\n\n registerShadowRoutes(app, { store });\n\n registerProtocolMcpRoutes(app, {\n serviceName: PROTOCOL_SERVICE,\n serviceVersion: PROTOCOL_VERSION,\n authLookup: options?.mcpAuthLookup ?? null,\n telemetry: options?.mcpTelemetry ?? null,\n });\n\n const executionAuthority = createExecutionGatingService(options?.executionGating);\n registerExecutionGatingRoutes(app, {\n serviceName: PROTOCOL_SERVICE,\n serviceVersion: PROTOCOL_VERSION,\n service: executionAuthority,\n });\n\n const agentTaskStore = options?.agentTaskStore ?? createMemoryAgentTaskReservationStore();\n const agentTaskPolicyResolver =\n options?.agentTaskPolicyResolver ?? new PolicyGraphAgentTaskPolicyResolver(store);\n AgentTaskGatewayRoutes.register(app, {\n gateway: new AgentTaskGatewayService(\n agentTaskStore,\n agentTaskPolicyResolver,\n executionAuthority,\n ),\n authLookup: options?.mcpAuthLookup ?? null,\n proxy: options?.agentProviderProxy,\n });\n\n return app;\n}\n","import { randomUUID } from \"node:crypto\";\nimport type { ProtocolArtifact } from \"../validation/ProtocolArtifacts.js\";\nimport { verifyLedgerChain } from \"../ledger/LedgerChain.js\";\nimport { getArtifactId, getOccurredAt, getOrgId, getProtocolVersion } from \"./StoreHelpers.js\";\nimport type {\n AuditLedgerHead,\n DecisionChainLinkRow,\n DecisionDossierRow,\n DecisionEvaluationMode,\n DecisionEvaluationRow,\n EnforcementRolloutRow,\n GovernanceMetricSnapshot,\n ListDecisionEvaluationsInput,\n OrgVerticalPackRow,\n PolicyBundleArtifactRow,\n ProtocolPayload,\n ProtocolStore,\n SaveDecisionChainLinkInput,\n SaveDecisionEvaluationInput,\n SaveArtifactResult,\n} from \"./StoreContracts.js\";\n\ninterface MemoryRow {\n kind: ProtocolArtifact;\n artifact_id: string;\n org_id: string;\n protocol_version: string;\n occurred_at: Date | null;\n payload: ProtocolPayload;\n saved_at: string;\n}\n\ninterface MemoryMetricSnapshotRow {\n id: string;\n org_id: string;\n decision_evaluation_id: string;\n metric_name: string;\n metric_value: number;\n dimensions: Record<string, unknown>;\n created_at: string;\n}\n\n/** In-memory {@link ProtocolStore} used by tests and local single-process runs. */\nexport class MemoryProtocolStore implements ProtocolStore {\n private readonly byKey = new Map<string, MemoryRow>();\n private readonly orgVerticalPacks = new Map<string, OrgVerticalPackRow>();\n private readonly evaluationById = new Map<string, DecisionEvaluationRow>();\n private readonly evaluationByIdempotency = new Map<string, string>();\n private readonly dossierById = new Map<string, DecisionDossierRow>();\n private readonly chainLinkByEvaluation = new Map<string, DecisionChainLinkRow>();\n private readonly enforcementRollouts = new Map<string, EnforcementRolloutRow>();\n private readonly metricSnapshots: MemoryMetricSnapshotRow[] = [];\n\n async healthCheck(): Promise<{ ok: boolean; message?: string }> {\n return { ok: true };\n }\n\n async saveArtifact(\n kind: ProtocolArtifact,\n payload: ProtocolPayload,\n ): Promise<SaveArtifactResult> {\n const artifactId = getArtifactId(kind, payload);\n const orgId = getOrgId(payload);\n const protocolVersion = getProtocolVersion(payload);\n const occurredAt = getOccurredAt(kind, payload);\n const savedAt = new Date().toISOString();\n const key = `${kind}:${artifactId}`;\n if (!(kind === \"audit_ledger_entry\" && this.byKey.has(key))) {\n this.byKey.set(key, {\n kind,\n artifact_id: artifactId,\n org_id: orgId,\n protocol_version: protocolVersion,\n occurred_at: occurredAt,\n payload,\n saved_at: savedAt,\n });\n }\n\n return {\n artifact_id: artifactId,\n org_id: orgId,\n saved_at: savedAt,\n };\n }\n\n async listAuditLedgerEntries(input: {\n orgId?: string | null;\n limit: number;\n }): Promise<ProtocolPayload[]> {\n const rows = Array.from(this.byKey.values())\n .filter((row) => row.kind === \"audit_ledger_entry\")\n .filter((row) => (input.orgId ? row.org_id === input.orgId : true))\n .sort((left, right) => {\n const leftTs = left.occurred_at?.getTime() ?? 0;\n const rightTs = right.occurred_at?.getTime() ?? 0;\n return rightTs - leftTs;\n })\n .slice(0, input.limit);\n\n return rows.map((row) => row.payload);\n }\n\n async getLatestAuditLedgerHead(orgId: string): Promise<AuditLedgerHead | null> {\n const latest = Array.from(this.byKey.values())\n .filter((row) => row.kind === \"audit_ledger_entry\")\n .filter((row) => row.org_id === orgId)\n .sort((left, right) => {\n const leftTs = left.occurred_at?.getTime() ?? 0;\n const rightTs = right.occurred_at?.getTime() ?? 0;\n return rightTs - leftTs;\n })[0];\n\n if (!latest) return null;\n const chain = latest.payload.chain as Record<string, unknown> | undefined;\n const entryHash = typeof chain?.entry_hash === \"string\" ? chain.entry_hash : null;\n if (!entryHash) return null;\n return {\n ledger_entry_id: latest.artifact_id,\n entry_hash: entryHash,\n occurred_at: latest.occurred_at ? latest.occurred_at.toISOString() : null,\n };\n }\n\n async verifyAuditLedgerChain(input: { orgId: string; limit: number }) {\n const rows = Array.from(this.byKey.values())\n .filter((row) => row.kind === \"audit_ledger_entry\")\n .filter((row) => row.org_id === input.orgId)\n .sort((left, right) => {\n const leftTs = left.occurred_at?.getTime() ?? 0;\n const rightTs = right.occurred_at?.getTime() ?? 0;\n return leftTs - rightTs;\n })\n .slice(0, Math.max(1, Math.min(input.limit, 5000)));\n\n return verifyLedgerChain(\n input.orgId,\n rows.map((row) => {\n const chain = (row.payload.chain ?? {}) as Record<string, unknown>;\n return {\n ledger_entry_id: row.artifact_id,\n prev_hash: typeof chain.prev_hash === \"string\" ? chain.prev_hash : null,\n entry_hash: typeof chain.entry_hash === \"string\" ? chain.entry_hash : \"\",\n payload: row.payload,\n };\n }),\n );\n }\n\n async listPolicyBundles(input: {\n orgId: string;\n limit: number;\n }): Promise<PolicyBundleArtifactRow[]> {\n const rows = Array.from(this.byKey.values())\n .filter((row) => row.kind === \"policy_bundle\")\n .filter((row) => row.org_id === input.orgId)\n .sort((left, right) => {\n const leftTs = left.occurred_at?.getTime() ?? 0;\n const rightTs = right.occurred_at?.getTime() ?? 0;\n return rightTs - leftTs;\n })\n .slice(0, Math.max(1, Math.min(input.limit, 500)));\n\n return rows.map((row) => {\n const payload =\n row.payload && typeof row.payload === \"object\" && !Array.isArray(row.payload)\n ? (row.payload as Record<string, unknown>)\n : {};\n const rules = Array.isArray(payload.rules)\n ? payload.rules.filter(\n (rule): rule is Record<string, unknown> =>\n Boolean(rule) && typeof rule === \"object\" && !Array.isArray(rule),\n )\n : [];\n\n return {\n bundle_id: row.artifact_id,\n org_id: row.org_id,\n version: typeof payload.version === \"string\" ? payload.version : \"unknown\",\n effective_from: typeof payload.effective_from === \"string\" ? payload.effective_from : null,\n effective_to: typeof payload.effective_to === \"string\" ? payload.effective_to : null,\n rules,\n payload,\n created_at: row.saved_at,\n updated_at: row.saved_at,\n };\n });\n }\n\n async getOrgVerticalPack(orgId: string): Promise<string | null> {\n return this.orgVerticalPacks.get(orgId)?.pack_key ?? null;\n }\n\n async setOrgVerticalPack(input: {\n orgId: string;\n packKey: string;\n config?: Record<string, unknown>;\n updatedBy?: string | null;\n }): Promise<OrgVerticalPackRow> {\n const row: OrgVerticalPackRow = {\n org_id: input.orgId,\n pack_key: input.packKey,\n config: input.config ?? {},\n updated_at: new Date().toISOString(),\n };\n this.orgVerticalPacks.set(input.orgId, row);\n return row;\n }\n\n async getDecisionEvaluationByIdempotency(input: {\n orgId: string;\n idempotencyKey: string;\n }): Promise<DecisionEvaluationRow | null> {\n const key = `${input.orgId}:${input.idempotencyKey}`;\n const evaluationId = this.evaluationByIdempotency.get(key);\n if (!evaluationId) return null;\n return this.evaluationById.get(evaluationId) ?? null;\n }\n\n async getDecisionEvaluation(input: {\n orgId: string;\n evaluationId: string;\n }): Promise<DecisionEvaluationRow | null> {\n const evaluation = this.evaluationById.get(input.evaluationId);\n if (!evaluation || evaluation.org_id !== input.orgId) return null;\n return evaluation;\n }\n\n async listDecisionEvaluations(\n input: ListDecisionEvaluationsInput,\n ): Promise<DecisionEvaluationRow[]> {\n const sinceMs = input.since?.getTime() ?? null;\n return Array.from(this.evaluationById.values())\n .filter((row) => row.org_id === input.orgId)\n .filter((row) => (input.mode ? row.mode === input.mode : true))\n .filter((row) => {\n if (sinceMs == null) return true;\n const createdAtMs = Date.parse(row.created_at);\n return Number.isFinite(createdAtMs) && createdAtMs >= sinceMs;\n })\n .sort((left, right) => right.created_at.localeCompare(left.created_at))\n .slice(0, Math.max(1, Math.min(input.limit, 500)));\n }\n\n async saveDecisionEvaluation(input: SaveDecisionEvaluationInput): Promise<DecisionEvaluationRow> {\n const now = new Date().toISOString();\n const row: DecisionEvaluationRow = {\n id: input.id ?? randomUUID(),\n org_id: input.org_id,\n idempotency_key: input.idempotency_key ?? null,\n decision_type: input.decision_type,\n amount: input.amount ?? null,\n risk_score: input.risk_score ?? null,\n channel: input.channel ?? null,\n source: input.source ?? null,\n policy_version: input.policy_version,\n objective_profile: input.objective_profile,\n outcome: input.outcome,\n confidence: input.confidence,\n dossier_id: input.dossier_id,\n mode: input.mode,\n fallback_triggered: input.fallback_triggered ?? false,\n request_payload: input.request_payload,\n response_payload: input.response_payload,\n created_at: now,\n updated_at: now,\n };\n\n this.evaluationById.set(row.id, row);\n if (row.idempotency_key) {\n this.evaluationByIdempotency.set(`${row.org_id}:${row.idempotency_key}`, row.id);\n }\n\n this.dossierById.set(row.dossier_id, {\n dossier_id: row.dossier_id,\n org_id: row.org_id,\n decision_evaluation_id: row.id,\n dossier_payload: input.dossier_payload,\n evidence_hashes: input.evidence_hashes ?? [],\n created_at: now,\n updated_at: now,\n });\n\n const metrics: GovernanceMetricSnapshot[] = input.governance_metrics ?? [];\n for (const metric of metrics) {\n this.metricSnapshots.push({\n id: randomUUID(),\n org_id: row.org_id,\n decision_evaluation_id: row.id,\n metric_name: metric.metric_name,\n metric_value: metric.metric_value,\n dimensions: metric.dimensions ?? {},\n created_at: now,\n });\n }\n\n return row;\n }\n\n async saveDecisionChainLink(input: SaveDecisionChainLinkInput): Promise<DecisionChainLinkRow> {\n const now = new Date().toISOString();\n const existing = this.chainLinkByEvaluation.get(input.decision_evaluation_id);\n const row: DecisionChainLinkRow = {\n ...input,\n id: existing?.id ?? randomUUID(),\n metadata: input.metadata ?? {},\n created_at: existing?.created_at ?? now,\n updated_at: now,\n };\n this.chainLinkByEvaluation.set(row.decision_evaluation_id, row);\n return row;\n }\n\n async getDecisionChainLinkForEvaluation(input: {\n orgId: string;\n evaluationId: string;\n }): Promise<DecisionChainLinkRow | null> {\n const row = this.chainLinkByEvaluation.get(input.evaluationId);\n if (!row || row.org_id !== input.orgId) return null;\n return row;\n }\n\n async listDecisionChainLinks(input: {\n orgId: string;\n chainId: string;\n }): Promise<DecisionChainLinkRow[]> {\n return Array.from(this.chainLinkByEvaluation.values())\n .filter((row) => row.org_id === input.orgId && row.chain_id === input.chainId)\n .sort((left, right) => {\n const leftSequence = left.sequence ?? left.lineage_depth;\n const rightSequence = right.sequence ?? right.lineage_depth;\n return (\n leftSequence - rightSequence ||\n left.created_at.localeCompare(right.created_at) ||\n left.decision_evaluation_id.localeCompare(right.decision_evaluation_id)\n );\n });\n }\n\n async getDecisionDossier(input: {\n orgId: string;\n dossierId: string;\n }): Promise<DecisionDossierRow | null> {\n const dossier = this.dossierById.get(input.dossierId);\n if (!dossier || dossier.org_id !== input.orgId) return null;\n return dossier;\n }\n\n async listDecisionDossiers(input: {\n orgId: string;\n dossierIds: string[];\n }): Promise<DecisionDossierRow[]> {\n return Array.from(new Set(input.dossierIds))\n .map((dossierId) => this.dossierById.get(dossierId))\n .filter(\n (dossier): dossier is DecisionDossierRow =>\n dossier !== undefined && dossier.org_id === input.orgId,\n );\n }\n\n async getEnforcementRollout(input: {\n orgId: string;\n decisionBand: string;\n transactionType: string;\n }): Promise<EnforcementRolloutRow | null> {\n const key = `${input.orgId}:${input.decisionBand}:${input.transactionType}`;\n return this.enforcementRollouts.get(key) ?? null;\n }\n\n async listEnforcementRollouts(input: { orgId: string }): Promise<EnforcementRolloutRow[]> {\n return Array.from(this.enforcementRollouts.values())\n .filter((row) => row.org_id === input.orgId)\n .sort((a, b) => b.updated_at.localeCompare(a.updated_at));\n }\n\n async upsertEnforcementRollout(input: {\n orgId: string;\n decisionBand: string;\n transactionType: string;\n mode: DecisionEvaluationMode;\n featureFlag?: string | null;\n fallbackToLegacy?: boolean;\n reconciliationRequired?: boolean;\n notes?: string | null;\n }): Promise<EnforcementRolloutRow> {\n const key = `${input.orgId}:${input.decisionBand}:${input.transactionType}`;\n const current = this.enforcementRollouts.get(key);\n const now = new Date().toISOString();\n const row: EnforcementRolloutRow = {\n id: current?.id ?? randomUUID(),\n org_id: input.orgId,\n decision_band: input.decisionBand,\n transaction_type: input.transactionType,\n mode: input.mode,\n feature_flag: input.featureFlag ?? null,\n fallback_to_legacy: input.fallbackToLegacy ?? true,\n reconciliation_required: input.reconciliationRequired ?? true,\n downtime_events: current?.downtime_events ?? 0,\n notes: input.notes ?? null,\n created_at: current?.created_at ?? now,\n updated_at: now,\n };\n this.enforcementRollouts.set(key, row);\n return row;\n }\n}\n\n/** Factory facade — original exported constructor for the in-memory store. */\nexport function createMemoryProtocolStore(): ProtocolStore {\n return new MemoryProtocolStore();\n}\n","import { createHash } from \"node:crypto\";\n\ntype ProtocolPayload = Record<string, unknown>;\n\nexport interface LedgerHashInput {\n ledger_entry_id: string;\n org_id: string;\n event_type: string;\n occurred_at: string;\n action: string;\n actor: unknown;\n object: unknown;\n links: unknown;\n payload: unknown;\n prev_hash: string | null;\n}\n\nexport interface LedgerChainIssue {\n ledger_entry_id: string;\n index: number;\n reason: \"PREV_HASH_MISMATCH\" | \"ENTRY_HASH_MISMATCH\" | \"ROW_PAYLOAD_MISMATCH\";\n expected?: string | null;\n actual?: string | null;\n}\n\nexport interface LedgerChainVerification {\n org_id: string;\n checked: number;\n broken_links: number;\n valid: boolean;\n head_hash: string | null;\n tail_hash: string | null;\n issues: LedgerChainIssue[];\n}\n\n/** Hash-chain computation and verification for the audit ledger. */\nexport class LedgerChain {\n static computeLedgerEntryHash(input: LedgerHashInput): string {\n const canonicalPayload = {\n ledger_entry_id: input.ledger_entry_id,\n org_id: input.org_id,\n event_type: input.event_type,\n occurred_at: input.occurred_at,\n action: input.action,\n actor: LedgerChain.canonicalize(input.actor),\n object: LedgerChain.canonicalize(input.object),\n links: LedgerChain.canonicalize(input.links),\n payload: LedgerChain.canonicalize(input.payload),\n prev_hash: input.prev_hash ?? null,\n };\n return createHash(\"sha256\")\n .update(LedgerChain.stableStringify(canonicalPayload), \"utf8\")\n .digest(\"hex\");\n }\n\n static extractLedgerHashInput(\n payload: ProtocolPayload,\n overridePrevHash?: string | null,\n ): LedgerHashInput {\n const chain = LedgerChain.asRecord(payload.chain);\n const prevHash = overridePrevHash ?? LedgerChain.normalizeHash(chain.prev_hash);\n return {\n ledger_entry_id: LedgerChain.asRequiredString(payload.ledger_entry_id),\n org_id: LedgerChain.asRequiredString(payload.org_id),\n event_type: LedgerChain.asRequiredString(payload.event_type),\n occurred_at: LedgerChain.asRequiredString(payload.occurred_at),\n action: LedgerChain.asRequiredString(payload.action),\n actor: payload.actor ?? {},\n object: payload.object ?? {},\n links: payload.links ?? {},\n payload: payload.payload ?? {},\n prev_hash: prevHash,\n };\n }\n\n static extractChainHashes(payload: ProtocolPayload): {\n prev_hash: string | null;\n entry_hash: string | null;\n } {\n const chain = LedgerChain.asRecord(payload.chain);\n return {\n prev_hash: LedgerChain.normalizeHash(chain.prev_hash),\n entry_hash: LedgerChain.normalizeHash(chain.entry_hash),\n };\n }\n\n static verifyLedgerChain(\n orgId: string,\n entries: Array<{\n ledger_entry_id: string;\n prev_hash: string | null;\n entry_hash: string;\n payload: ProtocolPayload;\n }>,\n ): LedgerChainVerification {\n const issues: LedgerChainIssue[] = [];\n let expectedPrev: string | null = null;\n\n for (let index = 0; index < entries.length; index += 1) {\n const entry = entries[index]!;\n\n const payloadHashes = LedgerChain.extractChainHashes(entry.payload);\n if (\n payloadHashes.prev_hash !== entry.prev_hash ||\n payloadHashes.entry_hash !== entry.entry_hash\n ) {\n issues.push({\n ledger_entry_id: entry.ledger_entry_id,\n index,\n reason: \"ROW_PAYLOAD_MISMATCH\",\n });\n }\n\n if (entry.prev_hash !== expectedPrev) {\n issues.push({\n ledger_entry_id: entry.ledger_entry_id,\n index,\n reason: \"PREV_HASH_MISMATCH\",\n expected: expectedPrev,\n actual: entry.prev_hash,\n });\n }\n\n const expectedEntryHash = LedgerChain.computeLedgerEntryHash(\n LedgerChain.extractLedgerHashInput(entry.payload, entry.prev_hash),\n );\n if (entry.entry_hash !== expectedEntryHash) {\n issues.push({\n ledger_entry_id: entry.ledger_entry_id,\n index,\n reason: \"ENTRY_HASH_MISMATCH\",\n expected: expectedEntryHash,\n actual: entry.entry_hash,\n });\n }\n\n expectedPrev = entry.entry_hash;\n }\n\n return {\n org_id: orgId,\n checked: entries.length,\n broken_links: issues.length,\n valid: issues.length === 0,\n tail_hash: entries.length > 0 ? entries[0]!.entry_hash : null,\n head_hash: entries.length > 0 ? entries[entries.length - 1]!.entry_hash : null,\n issues,\n };\n }\n\n private static normalizeHash(value: unknown): string | null {\n if (typeof value !== \"string\") return null;\n const hash = value.trim();\n return /^[a-f0-9]{64}$/i.test(hash) ? hash.toLowerCase() : null;\n }\n\n private static canonicalize(value: unknown): unknown {\n if (Array.isArray(value)) {\n return value.map((item) => LedgerChain.canonicalize(item));\n }\n if (!value || typeof value !== \"object\") {\n return value;\n }\n const obj = value as Record<string, unknown>;\n const sortedKeys = Object.keys(obj).sort();\n const out: Record<string, unknown> = {};\n for (const key of sortedKeys) {\n out[key] = LedgerChain.canonicalize(obj[key]);\n }\n return out;\n }\n\n private static stableStringify(value: unknown): string {\n return JSON.stringify(LedgerChain.canonicalize(value));\n }\n\n private static asRecord(value: unknown): Record<string, unknown> {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return {};\n return value as Record<string, unknown>;\n }\n\n private static asRequiredString(value: unknown): string {\n if (typeof value !== \"string\") return \"\";\n return value.trim();\n }\n}\n\n/** Functional alias for {@link LedgerChain.computeLedgerEntryHash}. */\nexport function computeLedgerEntryHash(input: LedgerHashInput): string {\n return LedgerChain.computeLedgerEntryHash(input);\n}\n\n/** Functional alias for {@link LedgerChain.extractLedgerHashInput}. */\nexport function extractLedgerHashInput(\n payload: ProtocolPayload,\n overridePrevHash?: string | null,\n): LedgerHashInput {\n return LedgerChain.extractLedgerHashInput(payload, overridePrevHash);\n}\n\n/** Functional alias for {@link LedgerChain.extractChainHashes}. */\nexport function extractChainHashes(payload: ProtocolPayload): {\n prev_hash: string | null;\n entry_hash: string | null;\n} {\n return LedgerChain.extractChainHashes(payload);\n}\n\n/** Functional alias for {@link LedgerChain.verifyLedgerChain}. */\nexport function verifyLedgerChain(\n orgId: string,\n entries: Array<{\n ledger_entry_id: string;\n prev_hash: string | null;\n entry_hash: string;\n payload: ProtocolPayload;\n }>,\n): LedgerChainVerification {\n return LedgerChain.verifyLedgerChain(orgId, entries);\n}\n","import type { ProtocolArtifact } from \"../validation/ProtocolArtifacts.js\";\nimport type { LedgerChainVerification } from \"../ledger/LedgerChain.js\";\n\nexport type ProtocolPayload = Record<string, unknown>;\n\nexport interface SaveArtifactResult {\n artifact_id: string;\n org_id: string;\n saved_at: string;\n}\n\nexport type DecisionEvaluationMode = \"SHADOW\" | \"PARALLEL\" | \"ENFORCEMENT\";\n\nexport type DecisionEvaluationOutcome = \"APPROVE\" | \"ESCALATE\" | \"REJECT\" | \"REVIEW\";\n\nexport interface GovernanceMetricSnapshot {\n metric_name: string;\n metric_value: number;\n dimensions?: Record<string, unknown>;\n}\n\nexport interface SaveDecisionEvaluationInput {\n id?: string;\n org_id: string;\n idempotency_key?: string | null;\n decision_type: string;\n amount?: number | null;\n risk_score?: number | null;\n channel?: string | null;\n source?: string | null;\n policy_version: string;\n objective_profile: string;\n outcome: DecisionEvaluationOutcome;\n confidence: number;\n dossier_id: string;\n mode: DecisionEvaluationMode;\n fallback_triggered?: boolean;\n request_payload: Record<string, unknown>;\n response_payload: Record<string, unknown>;\n dossier_payload: Record<string, unknown>;\n evidence_hashes?: string[];\n governance_metrics?: GovernanceMetricSnapshot[];\n}\n\nexport interface DecisionEvaluationRow {\n id: string;\n org_id: string;\n idempotency_key: string | null;\n decision_type: string;\n amount: number | null;\n risk_score: number | null;\n channel: string | null;\n source: string | null;\n policy_version: string;\n objective_profile: string;\n outcome: DecisionEvaluationOutcome;\n confidence: number;\n dossier_id: string;\n mode: DecisionEvaluationMode;\n fallback_triggered: boolean;\n request_payload: Record<string, unknown>;\n response_payload: Record<string, unknown>;\n created_at: string;\n updated_at: string;\n}\n\nexport interface SaveDecisionChainLinkInput {\n org_id: string;\n chain_id: string;\n workflow_id: string;\n step_id: string;\n sequence: number | null;\n decision_evaluation_id: string;\n dossier_id: string;\n parent_evaluation_ids: string[];\n parent_dossier_ids: string[];\n root_evaluation_id: string;\n lineage_depth: number;\n integrity_hash: string;\n metadata?: Record<string, unknown>;\n}\n\nexport interface DecisionChainLinkRow extends SaveDecisionChainLinkInput {\n id: string;\n created_at: string;\n updated_at: string;\n}\n\nexport interface ListDecisionEvaluationsInput {\n orgId: string;\n mode?: DecisionEvaluationMode | null;\n since?: Date | null;\n limit: number;\n}\n\nexport interface DecisionDossierRow {\n dossier_id: string;\n org_id: string;\n decision_evaluation_id: string;\n dossier_payload: Record<string, unknown>;\n evidence_hashes: string[];\n created_at: string;\n updated_at: string;\n}\n\nexport interface EnforcementRolloutRow {\n id: string;\n org_id: string;\n decision_band: string;\n transaction_type: string;\n mode: DecisionEvaluationMode;\n feature_flag: string | null;\n fallback_to_legacy: boolean;\n reconciliation_required: boolean;\n downtime_events: number;\n notes: string | null;\n created_at: string;\n updated_at: string;\n}\n\nexport interface OrgVerticalPackRow {\n org_id: string;\n pack_key: string;\n config: Record<string, unknown>;\n updated_at: string;\n}\n\nexport interface PolicyBundleArtifactRow {\n bundle_id: string;\n org_id: string;\n version: string;\n effective_from: string | null;\n effective_to: string | null;\n rules: Record<string, unknown>[];\n payload: Record<string, unknown>;\n created_at: string;\n updated_at: string;\n}\n\nexport interface AuditLedgerHead {\n ledger_entry_id: string;\n entry_hash: string;\n occurred_at: string | null;\n}\n\nexport interface ProtocolStore {\n healthCheck(): Promise<{ ok: boolean; message?: string }>;\n saveArtifact(kind: ProtocolArtifact, payload: ProtocolPayload): Promise<SaveArtifactResult>;\n listAuditLedgerEntries(input: {\n orgId?: string | null;\n limit: number;\n }): Promise<ProtocolPayload[]>;\n getLatestAuditLedgerHead(orgId: string): Promise<AuditLedgerHead | null>;\n verifyAuditLedgerChain(input: { orgId: string; limit: number }): Promise<LedgerChainVerification>;\n listPolicyBundles(input: { orgId: string; limit: number }): Promise<PolicyBundleArtifactRow[]>;\n getOrgVerticalPack(orgId: string): Promise<string | null>;\n setOrgVerticalPack(input: {\n orgId: string;\n packKey: string;\n config?: Record<string, unknown>;\n updatedBy?: string | null;\n }): Promise<OrgVerticalPackRow>;\n getDecisionEvaluationByIdempotency(input: {\n orgId: string;\n idempotencyKey: string;\n }): Promise<DecisionEvaluationRow | null>;\n getDecisionEvaluation(input: {\n orgId: string;\n evaluationId: string;\n }): Promise<DecisionEvaluationRow | null>;\n listDecisionEvaluations(input: ListDecisionEvaluationsInput): Promise<DecisionEvaluationRow[]>;\n saveDecisionEvaluation(input: SaveDecisionEvaluationInput): Promise<DecisionEvaluationRow>;\n saveDecisionChainLink(input: SaveDecisionChainLinkInput): Promise<DecisionChainLinkRow>;\n getDecisionChainLinkForEvaluation(input: {\n orgId: string;\n evaluationId: string;\n }): Promise<DecisionChainLinkRow | null>;\n listDecisionChainLinks(input: {\n orgId: string;\n chainId: string;\n }): Promise<DecisionChainLinkRow[]>;\n getDecisionDossier(input: {\n orgId: string;\n dossierId: string;\n }): Promise<DecisionDossierRow | null>;\n listDecisionDossiers(input: {\n orgId: string;\n dossierIds: string[];\n }): Promise<DecisionDossierRow[]>;\n getEnforcementRollout(input: {\n orgId: string;\n decisionBand: string;\n transactionType: string;\n }): Promise<EnforcementRolloutRow | null>;\n listEnforcementRollouts(input: { orgId: string }): Promise<EnforcementRolloutRow[]>;\n upsertEnforcementRollout(input: {\n orgId: string;\n decisionBand: string;\n transactionType: string;\n mode: DecisionEvaluationMode;\n featureFlag?: string | null;\n fallbackToLegacy?: boolean;\n reconciliationRequired?: boolean;\n notes?: string | null;\n }): Promise<EnforcementRolloutRow>;\n}\n\nexport class ProtocolStoreValidationError extends Error {\n readonly issues: Array<{ path: string; message: string }>;\n\n constructor(message: string, issues: Array<{ path: string; message: string }>) {\n super(message);\n this.name = \"ProtocolStoreValidationError\";\n this.issues = issues;\n }\n}\n","import type { ProtocolArtifact } from \"../validation/ProtocolArtifacts.js\";\nimport { ProtocolStoreValidationError, type ProtocolPayload } from \"./StoreContracts.js\";\n\nconst UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\n\nconst ARTIFACT_ID_FIELDS: Record<ProtocolArtifact, string> = {\n signal_envelope: \"envelope_id\",\n context_snapshot: \"snapshot_id\",\n policy_bundle: \"bundle_id\",\n decision_resolution: \"resolution_id\",\n execution_dispatch: \"dispatch_id\",\n audit_ledger_entry: \"ledger_entry_id\",\n};\n\n/** Field extraction/validation helpers shared by the protocol store implementations. */\nexport class StoreHelpers {\n static getArtifactId(kind: ProtocolArtifact, payload: ProtocolPayload): string {\n const field = ARTIFACT_ID_FIELDS[kind];\n const value = StoreHelpers.asString(payload[field]);\n if (!value || !UUID_REGEX.test(value)) {\n throw new ProtocolStoreValidationError(\"Invalid artifact identifier\", [\n { path: field, message: \"expected UUID\" },\n ]);\n }\n return value;\n }\n\n static getOrgId(payload: ProtocolPayload): string {\n const value = StoreHelpers.asString(payload.org_id);\n if (!value || !UUID_REGEX.test(value)) {\n throw new ProtocolStoreValidationError(\"Invalid org_id\", [\n { path: \"org_id\", message: \"expected UUID\" },\n ]);\n }\n return value;\n }\n\n static getProtocolVersion(payload: ProtocolPayload): string {\n const value = StoreHelpers.asString(payload.protocol_version);\n if (!value) {\n throw new ProtocolStoreValidationError(\"Invalid protocol_version\", [\n { path: \"protocol_version\", message: \"required\" },\n ]);\n }\n return value;\n }\n\n static getOccurredAt(kind: ProtocolArtifact, payload: ProtocolPayload): Date | null {\n switch (kind) {\n case \"signal_envelope\":\n return StoreHelpers.parseDateMaybe(payload.recorded_at);\n case \"context_snapshot\":\n return StoreHelpers.parseDateMaybe(payload.generated_at);\n case \"policy_bundle\":\n return StoreHelpers.parseDateMaybe(payload.effective_from);\n case \"decision_resolution\":\n return StoreHelpers.parseDateMaybe(payload.decided_at);\n case \"execution_dispatch\":\n return (\n StoreHelpers.parseDateMaybe(payload.scheduled_at) ??\n StoreHelpers.parseDateMaybe(payload.sent_at) ??\n StoreHelpers.parseDateMaybe(payload.delivered_at) ??\n StoreHelpers.parseDateMaybe(payload.failed_at)\n );\n case \"audit_ledger_entry\":\n return StoreHelpers.parseDateMaybe(payload.occurred_at);\n default:\n return null;\n }\n }\n\n private static asString(value: unknown): string | null {\n if (typeof value !== \"string\") return null;\n const trimmed = value.trim();\n return trimmed.length > 0 ? trimmed : null;\n }\n\n private static parseDateMaybe(value: unknown): Date | null {\n const text = StoreHelpers.asString(value);\n if (!text) return null;\n const parsed = Date.parse(text);\n if (!Number.isFinite(parsed)) return null;\n return new Date(parsed);\n }\n}\n\n/** Functional alias for {@link StoreHelpers.getArtifactId}. */\nexport function getArtifactId(kind: ProtocolArtifact, payload: ProtocolPayload): string {\n return StoreHelpers.getArtifactId(kind, payload);\n}\n\n/** Functional alias for {@link StoreHelpers.getOrgId}. */\nexport function getOrgId(payload: ProtocolPayload): string {\n return StoreHelpers.getOrgId(payload);\n}\n\n/** Functional alias for {@link StoreHelpers.getProtocolVersion}. */\nexport function getProtocolVersion(payload: ProtocolPayload): string {\n return StoreHelpers.getProtocolVersion(payload);\n}\n\n/** Functional alias for {@link StoreHelpers.getOccurredAt}. */\nexport function getOccurredAt(kind: ProtocolArtifact, payload: ProtocolPayload): Date | null {\n return StoreHelpers.getOccurredAt(kind, payload);\n}\n","import { createHash } from \"node:crypto\";\nimport type pg from \"pg\";\n\nexport interface ProtocolMcpBreakglassAuthContext {\n kind: \"breakglass\";\n source: \"env_api_key\" | \"custom_header\";\n}\n\nexport interface ProtocolMcpOrgApiKeyAuthContext {\n kind: \"org_api_key\";\n api_key_id: string;\n org_id: string;\n role: string;\n scopes: string[];\n key_prefix: string;\n key_name: string;\n}\n\nexport type ProtocolMcpAuthContext =\n | ProtocolMcpBreakglassAuthContext\n | ProtocolMcpOrgApiKeyAuthContext;\n\nexport type ProtocolMcpAuthLookup = (\n rawKey: string,\n) => Promise<ProtocolMcpOrgApiKeyAuthContext | null>;\n\n/** API-key hashing and scope checks for the protocol MCP surface. */\nexport class McpAuth {\n static hashApiKey(rawKey: string, env: NodeJS.ProcessEnv = process.env): string {\n const hash = createHash(\"sha256\");\n const pepper = McpAuth.normalizedHashSecret(env);\n if (pepper) {\n hash.update(pepper);\n hash.update(\":\");\n }\n hash.update(rawKey);\n return hash.digest(\"hex\");\n }\n\n static hasScope(grantedScopes: string[], requiredScope: string): boolean {\n const required = requiredScope.trim();\n if (!required) return true;\n\n for (const raw of grantedScopes) {\n const scope = raw.trim();\n if (!scope) continue;\n if (scope === \"*\" || scope === required) return true;\n if (scope.endsWith(\"*\")) {\n const prefix = scope.slice(0, -1);\n if (required.startsWith(prefix)) return true;\n }\n }\n return false;\n }\n\n static hasAnyScope(grantedScopes: string[], requiredScopes: string[]): boolean {\n return requiredScopes.some((scope) => McpAuth.hasScope(grantedScopes, scope));\n }\n\n static createDatabaseOrgApiKeyLookup(\n pool: pg.Pool,\n env: NodeJS.ProcessEnv = process.env,\n ): ProtocolMcpAuthLookup {\n return async (rawKey: string) => {\n const keyHash = McpAuth.hashApiKey(rawKey, env);\n const res = await pool.query<{\n id: string;\n org_id: string;\n role: string;\n scopes: string[] | null;\n key_prefix: string;\n name: string;\n }>(\n `select id, org_id, role, scopes, key_prefix, name\n from org_api_keys\n where key_hash = $1\n and revoked_at is null\n and (expires_at is null or expires_at > now())\n limit 1`,\n [keyHash],\n );\n\n const row = res.rows[0];\n if (!row) return null;\n\n return {\n kind: \"org_api_key\",\n api_key_id: row.id,\n org_id: row.org_id,\n role: row.role,\n scopes: row.scopes ?? [],\n key_prefix: row.key_prefix,\n key_name: row.name,\n };\n };\n }\n\n private static normalizedHashSecret(env: NodeJS.ProcessEnv = process.env): string {\n return env.API_KEY_HASH_SECRET?.trim() ?? \"\";\n }\n}\n\n/** Functional alias for {@link McpAuth.hashApiKey}. */\nexport function hashApiKey(rawKey: string, env: NodeJS.ProcessEnv = process.env): string {\n return McpAuth.hashApiKey(rawKey, env);\n}\n\n/** Functional alias for {@link McpAuth.hasScope}. */\nexport function hasScope(grantedScopes: string[], requiredScope: string): boolean {\n return McpAuth.hasScope(grantedScopes, requiredScope);\n}\n\n/** Functional alias for {@link McpAuth.hasAnyScope}. */\nexport function hasAnyScope(grantedScopes: string[], requiredScopes: string[]): boolean {\n return McpAuth.hasAnyScope(grantedScopes, requiredScopes);\n}\n\n/** Functional alias for {@link McpAuth.createDatabaseOrgApiKeyLookup}. */\nexport function createDatabaseOrgApiKeyLookup(\n pool: pg.Pool,\n env: NodeJS.ProcessEnv = process.env,\n): ProtocolMcpAuthLookup {\n return McpAuth.createDatabaseOrgApiKeyLookup(pool, env);\n}\n","export type JsonRpcId = string | number;\n\nexport type JsonRpcErrorShape = {\n code: number;\n message: string;\n data?: unknown;\n};\n\nexport type JsonRpcResponse =\n | {\n jsonrpc: \"2.0\";\n id: JsonRpcId;\n result: Record<string, unknown>;\n }\n | {\n jsonrpc: \"2.0\";\n id: JsonRpcId | null;\n error: JsonRpcErrorShape;\n };\n\nexport type McpToolInvocationResult = {\n content: Array<{ type: \"text\"; text: string }>;\n structuredContent?: Record<string, unknown>;\n isError?: boolean;\n};\n\nexport interface McpToolDefinition {\n name: string;\n title: string;\n description: string;\n inputSchema: Record<string, unknown>;\n outputSchema?: Record<string, unknown>;\n annotations: {\n readOnlyHint: boolean;\n destructiveHint: boolean;\n idempotentHint: boolean;\n openWorldHint: boolean;\n };\n aliases?: string[];\n handler: (args: Record<string, unknown>) => Promise<unknown>;\n}\n\nexport interface McpPromptDefinition {\n name: string;\n title: string;\n description: string;\n arguments?: Array<{ name: string; description: string; required?: boolean }>;\n handler: (args: Record<string, unknown>) => string;\n}\n\nexport interface McpStaticResource {\n uri: string;\n name: string;\n title: string;\n description: string;\n mimeType: string;\n}\n\nexport interface McpResourceReadResult {\n mimeType?: string;\n value: unknown;\n}\n\nexport const MCP_PROTOCOL_VERSIONS = [\n \"2025-11-25\",\n \"2025-06-18\",\n \"2025-03-26\",\n \"2024-11-05\",\n] as const;\nexport const MCP_DEFAULT_PROTOCOL_VERSION = \"2025-11-25\";\nexport const DEFAULT_PUBLIC_BASE_URL = \"https://protocol.decionis.com\";\nexport const MCP_HTTP_PATHS = [\"/mcp\", \"/v1/protocol/mcp\"] as const;\n","import type { FastifyInstance } from \"fastify\";\nimport { DEFAULT_PUBLIC_BASE_URL, type JsonRpcId, type JsonRpcResponse } from \"./McpContracts.js\";\n\n/** JSON-RPC envelopes, MCP-local parsing, and in-process route invocation helpers. */\nexport class McpSupport {\n static asRecord(value: unknown): Record<string, unknown> | null {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return null;\n return value as Record<string, unknown>;\n }\n\n static asString(value: unknown): string | null {\n if (typeof value !== \"string\") return null;\n const trimmed = value.trim();\n return trimmed.length > 0 ? trimmed : null;\n }\n\n static toPrettyText(value: unknown): string {\n if (typeof value === \"string\") return value;\n try {\n return JSON.stringify(value, null, 2);\n } catch {\n return String(value);\n }\n }\n\n static asStructuredContent(value: unknown): Record<string, unknown> {\n const record = asRecord(value);\n if (record) return record;\n return { value };\n }\n\n static jsonRpcSuccess(id: JsonRpcId, result: Record<string, unknown>): JsonRpcResponse {\n return {\n jsonrpc: \"2.0\",\n id,\n result,\n };\n }\n\n static jsonRpcError(\n id: JsonRpcId | null,\n code: number,\n message: string,\n data?: unknown,\n ): JsonRpcResponse {\n return {\n jsonrpc: \"2.0\",\n id,\n error: data === undefined ? { code, message } : { code, message, data },\n };\n }\n\n static getPublicBaseUrl(): string {\n const raw =\n process.env.DECIONIS_PROTOCOL_PUBLIC_BASE_URL?.trim() ??\n process.env.DECIONIS_PROTOCOL_BASE_URL?.trim() ??\n DEFAULT_PUBLIC_BASE_URL;\n return raw.replace(/\\/$/, \"\");\n }\n\n static durationMs(startedAt: bigint): number {\n return Number(process.hrtime.bigint() - startedAt) / 1_000_000;\n }\n\n static buildServerTimingHeader(input: {\n total_ms: number;\n stages?: Record<string, number>;\n }): string {\n const entries: Array<[string, number]> = [[\"total\", input.total_ms]];\n for (const [key, value] of Object.entries(input.stages ?? {})) {\n entries.push([key.replace(/_ms$/i, \"\"), value]);\n }\n return entries\n .filter(([, value]) => Number.isFinite(value) && value >= 0)\n .map(([label, value]) => `${label.replace(/[^a-z0-9_-]/gi, \"_\")};dur=${value.toFixed(3)}`)\n .join(\", \");\n }\n\n static async invokeProtocolRoute(\n app: FastifyInstance,\n input: {\n method: \"GET\" | \"POST\" | \"PUT\";\n url: string;\n payload?: Record<string, unknown>;\n },\n ): Promise<{ ok: boolean; statusCode: number; body: unknown }> {\n const response = await app.inject({\n method: input.method,\n url: input.url,\n payload: input.payload,\n });\n\n const rawBody = response.body;\n let body: unknown = null;\n if (rawBody) {\n try {\n body = JSON.parse(rawBody);\n } catch {\n body = rawBody;\n }\n }\n\n return {\n ok: response.statusCode >= 200 && response.statusCode < 300,\n statusCode: response.statusCode,\n body,\n };\n }\n\n static withQuery(path: string, query: Record<string, string | null | undefined>): string {\n const params = new URLSearchParams();\n for (const [key, value] of Object.entries(query)) {\n if (value) params.set(key, value);\n }\n const suffix = params.toString();\n return suffix ? `${path}?${suffix}` : path;\n }\n}\n\n/** Functional alias for {@link McpSupport.asRecord}. */\nexport function asRecord(value: unknown): Record<string, unknown> | null {\n return McpSupport.asRecord(value);\n}\n\n/** Functional alias for {@link McpSupport.asString}. */\nexport function asString(value: unknown): string | null {\n return McpSupport.asString(value);\n}\n\n/** Functional alias for {@link McpSupport.toPrettyText}. */\nexport function toPrettyText(value: unknown): string {\n return McpSupport.toPrettyText(value);\n}\n\n/** Functional alias for {@link McpSupport.asStructuredContent}. */\nexport function asStructuredContent(value: unknown): Record<string, unknown> {\n return McpSupport.asStructuredContent(value);\n}\n\n/** Functional alias for {@link McpSupport.jsonRpcSuccess}. */\nexport function jsonRpcSuccess(id: JsonRpcId, result: Record<string, unknown>): JsonRpcResponse {\n return McpSupport.jsonRpcSuccess(id, result);\n}\n\n/** Functional alias for {@link McpSupport.jsonRpcError}. */\nexport function jsonRpcError(\n id: JsonRpcId | null,\n code: number,\n message: string,\n data?: unknown,\n): JsonRpcResponse {\n return McpSupport.jsonRpcError(id, code, message, data);\n}\n\n/** Functional alias for {@link McpSupport.getPublicBaseUrl}. */\nexport function getPublicBaseUrl(): string {\n return McpSupport.getPublicBaseUrl();\n}\n\n/** Functional alias for {@link McpSupport.durationMs}. */\nexport function durationMs(startedAt: bigint): number {\n return McpSupport.durationMs(startedAt);\n}\n\n/** Functional alias for {@link McpSupport.buildServerTimingHeader}. */\nexport function buildServerTimingHeader(input: {\n total_ms: number;\n stages?: Record<string, number>;\n}): string {\n return McpSupport.buildServerTimingHeader(input);\n}\n\n/** Functional alias for {@link McpSupport.invokeProtocolRoute}. */\nexport function invokeProtocolRoute(\n app: FastifyInstance,\n input: {\n method: \"GET\" | \"POST\" | \"PUT\";\n url: string;\n payload?: Record<string, unknown>;\n },\n): Promise<{ ok: boolean; statusCode: number; body: unknown }> {\n return McpSupport.invokeProtocolRoute(app, input);\n}\n\n/** Functional alias for {@link McpSupport.withQuery}. */\nexport function withQuery(path: string, query: Record<string, string | null | undefined>): string {\n return McpSupport.withQuery(path, query);\n}\n","import type { FastifyRequest } from \"fastify\";\nimport {\n hasAnyScope,\n type ProtocolMcpAuthContext,\n type ProtocolMcpAuthLookup,\n} from \"../auth/McpAuth.js\";\nimport type { JsonRpcErrorShape } from \"./McpContracts.js\";\nimport { asString } from \"./McpSupport.js\";\n\n/** MCP request authentication, org scoping, and tool/resource authorization guards. */\nexport class McpAuthGuard {\n static getMcpAuthConfig(env: NodeJS.ProcessEnv = process.env): {\n apiKey: string | null;\n customHeaderName: string | null;\n customHeaderValue: string | null;\n } {\n const apiKey = asString(env.DECIONIS_PROTOCOL_MCP_API_KEY);\n const customHeaderName =\n asString(env.DECIONIS_PROTOCOL_MCP_AUTH_HEADER_NAME)?.toLowerCase() ?? null;\n const customHeaderValue = asString(env.DECIONIS_PROTOCOL_MCP_AUTH_HEADER_VALUE);\n return { apiKey, customHeaderName, customHeaderValue };\n }\n\n static describeMcpAuthConfig(\n env: NodeJS.ProcessEnv = process.env,\n options?: { hasDynamicOrgKeyLookup?: boolean },\n ): Record<string, unknown> {\n const config = getMcpAuthConfig(env);\n const hasDynamicOrgKeyLookup = options?.hasDynamicOrgKeyLookup === true;\n if (\n !config.apiKey &&\n !config.customHeaderName &&\n !config.customHeaderValue &&\n !hasDynamicOrgKeyLookup\n ) {\n return {\n mode: \"none\",\n accepted_auth_types: [\"none\"],\n registration_hint:\n \"Open registration is enabled. For production or Webex Beta onboarding, use a Decionis org API key or configure breakglass auth.\",\n };\n }\n\n const acceptedAuthTypes: string[] = [];\n if (config.apiKey) acceptedAuthTypes.push(\"ApiKey\");\n if (config.customHeaderName && config.customHeaderValue)\n acceptedAuthTypes.push(\"CustomHeaderAuth\");\n\n if (hasDynamicOrgKeyLookup) acceptedAuthTypes.push(\"ApiKey\");\n const mode =\n acceptedAuthTypes.length > 1\n ? \"api_key_or_custom_header\"\n : acceptedAuthTypes[0] === \"ApiKey\"\n ? \"api_key\"\n : acceptedAuthTypes[0] === \"CustomHeaderAuth\"\n ? \"custom_header\"\n : \"none\";\n\n return {\n mode,\n accepted_auth_types: [...new Set(acceptedAuthTypes)],\n api_key_headers:\n hasDynamicOrgKeyLookup || config.apiKey\n ? [\"authorization: Bearer <org_api_key>\", \"x-api-key: <org_api_key>\"]\n : [],\n api_key_source: hasDynamicOrgKeyLookup\n ? {\n type: \"org_api_key\",\n issued_via: [\n \"pilot deployment bundle during org registration\",\n \"POST /v1/orgs/:orgId/protocol/mcp/runtime/api-key on api.decionis.com\",\n ],\n }\n : null,\n custom_header:\n config.customHeaderName && config.customHeaderValue\n ? {\n name: config.customHeaderName,\n value_configured: true,\n }\n : null,\n };\n }\n\n static async authenticateMcpRequest(\n req: FastifyRequest,\n authLookup: ProtocolMcpAuthLookup | null,\n ): Promise<ProtocolMcpAuthContext | null> {\n const config = getMcpAuthConfig();\n const authorizationHeader = asString(req.headers.authorization);\n const bearerToken = authorizationHeader?.replace(/^Bearer\\s+/i, \"\").trim() ?? null;\n const xApiKey = asString(req.headers[\"x-api-key\"]);\n const providedKey = bearerToken ?? xApiKey;\n\n if (config.apiKey && (bearerToken === config.apiKey || xApiKey === config.apiKey)) {\n return {\n kind: \"breakglass\",\n source: \"env_api_key\",\n };\n }\n\n if (config.customHeaderName && config.customHeaderValue) {\n const headerValue = req.headers[config.customHeaderName];\n const normalized =\n typeof headerValue === \"string\"\n ? headerValue\n : Array.isArray(headerValue)\n ? headerValue[0]\n : null;\n if (normalized?.trim() === config.customHeaderValue) {\n return {\n kind: \"breakglass\",\n source: \"custom_header\",\n };\n }\n }\n\n if (providedKey && authLookup) {\n return await authLookup(providedKey);\n }\n\n if (!config.apiKey && !(config.customHeaderName && config.customHeaderValue) && !authLookup) {\n return {\n kind: \"breakglass\",\n source: \"env_api_key\",\n };\n }\n\n return null;\n }\n\n static isAuthenticationRequired(authLookup: ProtocolMcpAuthLookup | null): boolean {\n const config = getMcpAuthConfig();\n return Boolean(\n config.apiKey || (config.customHeaderName && config.customHeaderValue) || authLookup,\n );\n }\n\n static isOrgApiKeyAuth(\n auth: ProtocolMcpAuthContext | null,\n ): auth is Extract<ProtocolMcpAuthContext, { kind: \"org_api_key\" }> {\n return auth?.kind === \"org_api_key\";\n }\n\n static findTargetOrgIdForTool(name: string, args: Record<string, unknown>): string | null {\n if (\n name === \"decionis.evaluate_decision\" ||\n name === \"evaluate_decision\" ||\n name === \"decionis.agentic_checkout_authorize\" ||\n name === \"agentic_checkout_authorize\" ||\n name === \"decionis.evaluate_webex_agent_intent\" ||\n name === \"evaluate_webex_agent_intent\" ||\n name === \"decionis.get_decision_dossier\" ||\n name === \"get_decision_dossier\" ||\n name === \"decionis.get_decision_chain\" ||\n name === \"get_decision_chain\" ||\n name === \"decionis.list_enforcement_rollouts\" ||\n name === \"list_enforcement_rollouts\" ||\n name === \"decionis.upsert_enforcement_rollout\" ||\n name === \"upsert_enforcement_rollout\" ||\n name === \"decionis.resolve_vertical_pack\" ||\n name === \"resolve_vertical_pack\" ||\n name === \"decionis.run_shadow_decisioning\" ||\n name === \"run_shadow_decisioning\"\n ) {\n return asString(args.org_id);\n }\n return null;\n }\n\n static requiredScopesForTool(name: string): string[] {\n if (\n name === \"decionis.evaluate_decision\" ||\n name === \"evaluate_decision\" ||\n name === \"decionis.agentic_checkout_authorize\" ||\n name === \"agentic_checkout_authorize\" ||\n name === \"decionis.evaluate_webex_agent_intent\" ||\n name === \"evaluate_webex_agent_intent\" ||\n name === \"decionis.run_shadow_decisioning\" ||\n name === \"run_shadow_decisioning\"\n ) {\n return [\"decision:run\", \"decision:*\", \"org:*\"];\n }\n if (\n name === \"decionis.get_decision_dossier\" ||\n name === \"get_decision_dossier\" ||\n name === \"decionis.get_decision_chain\" ||\n name === \"get_decision_chain\" ||\n name === \"decionis.list_enforcement_rollouts\" ||\n name === \"list_enforcement_rollouts\" ||\n name === \"decionis.resolve_vertical_pack\" ||\n name === \"resolve_vertical_pack\"\n ) {\n return [\"decision:read\", \"org:read\", \"decision:*\", \"org:*\"];\n }\n if (name === \"decionis.upsert_enforcement_rollout\" || name === \"upsert_enforcement_rollout\") {\n return [\"decision:write\", \"decision:*\", \"org:*\"];\n }\n return [];\n }\n\n static readAuthorizationForResource(uri: string): {\n orgId: string | null;\n requiredScopes: string[];\n } {\n if (uri.startsWith(\"decionis://dossiers/\")) {\n const parsed = new URL(uri);\n const [orgId] = parsed.pathname\n .split(\"/\")\n .filter(Boolean)\n .map((segment) => decodeURIComponent(segment));\n return {\n orgId: orgId ?? null,\n requiredScopes: [\"decision:read\", \"org:read\", \"decision:*\", \"org:*\"],\n };\n }\n if (uri.startsWith(\"decionis://enforcement-rollouts/\")) {\n const parsed = new URL(uri);\n const [orgId] = parsed.pathname\n .split(\"/\")\n .filter(Boolean)\n .map((segment) => decodeURIComponent(segment));\n return {\n orgId: orgId ?? null,\n requiredScopes: [\"decision:read\", \"org:read\", \"decision:*\", \"org:*\"],\n };\n }\n return { orgId: null, requiredScopes: [] };\n }\n\n static authorizeToolInvocation(\n auth: ProtocolMcpAuthContext | null,\n name: string,\n args: Record<string, unknown>,\n ): JsonRpcErrorShape | null {\n if (!isOrgApiKeyAuth(auth)) return null;\n\n const targetOrgId = findTargetOrgIdForTool(name, args);\n if (targetOrgId && targetOrgId !== auth.org_id) {\n return {\n code: -32003,\n message: \"API key is not authorized for this organization\",\n };\n }\n\n const requiredScopes = requiredScopesForTool(name);\n if (requiredScopes.length > 0 && !hasAnyScope(auth.scopes, requiredScopes)) {\n return {\n code: -32003,\n message: `API key missing required scope. Need one of: ${requiredScopes.join(\", \")}`,\n };\n }\n\n return null;\n }\n\n static authorizeResourceRead(\n auth: ProtocolMcpAuthContext | null,\n uri: string,\n ): JsonRpcErrorShape | null {\n if (!isOrgApiKeyAuth(auth)) return null;\n\n const { orgId, requiredScopes } = readAuthorizationForResource(uri);\n if (orgId && orgId !== auth.org_id) {\n return {\n code: -32003,\n message: \"API key is not authorized for this organization\",\n };\n }\n\n if (requiredScopes.length > 0 && !hasAnyScope(auth.scopes, requiredScopes)) {\n return {\n code: -32003,\n message: `API key missing required scope. Need one of: ${requiredScopes.join(\", \")}`,\n };\n }\n\n return null;\n }\n}\n\n/** Functional alias for {@link McpAuthGuard.getMcpAuthConfig}. */\nexport function getMcpAuthConfig(env: NodeJS.ProcessEnv = process.env): {\n apiKey: string | null;\n customHeaderName: string | null;\n customHeaderValue: string | null;\n} {\n return McpAuthGuard.getMcpAuthConfig(env);\n}\n\n/** Functional alias for {@link McpAuthGuard.describeMcpAuthConfig}. */\nexport function describeMcpAuthConfig(\n env: NodeJS.ProcessEnv = process.env,\n options?: { hasDynamicOrgKeyLookup?: boolean },\n): Record<string, unknown> {\n return McpAuthGuard.describeMcpAuthConfig(env, options);\n}\n\n/** Functional alias for {@link McpAuthGuard.authenticateMcpRequest}. */\nexport async function authenticateMcpRequest(\n req: FastifyRequest,\n authLookup: ProtocolMcpAuthLookup | null,\n): Promise<ProtocolMcpAuthContext | null> {\n return McpAuthGuard.authenticateMcpRequest(req, authLookup);\n}\n\n/** Functional alias for {@link McpAuthGuard.isAuthenticationRequired}. */\nexport function isAuthenticationRequired(authLookup: ProtocolMcpAuthLookup | null): boolean {\n return McpAuthGuard.isAuthenticationRequired(authLookup);\n}\n\n/** Functional alias for {@link McpAuthGuard.isOrgApiKeyAuth}. */\nexport function isOrgApiKeyAuth(\n auth: ProtocolMcpAuthContext | null,\n): auth is Extract<ProtocolMcpAuthContext, { kind: \"org_api_key\" }> {\n return McpAuthGuard.isOrgApiKeyAuth(auth);\n}\n\n/** Functional alias for {@link McpAuthGuard.findTargetOrgIdForTool}. */\nexport function findTargetOrgIdForTool(name: string, args: Record<string, unknown>): string | null {\n return McpAuthGuard.findTargetOrgIdForTool(name, args);\n}\n\n/** Functional alias for {@link McpAuthGuard.requiredScopesForTool}. */\nexport function requiredScopesForTool(name: string): string[] {\n return McpAuthGuard.requiredScopesForTool(name);\n}\n\n/** Functional alias for {@link McpAuthGuard.readAuthorizationForResource}. */\nexport function readAuthorizationForResource(uri: string): {\n orgId: string | null;\n requiredScopes: string[];\n} {\n return McpAuthGuard.readAuthorizationForResource(uri);\n}\n\n/** Functional alias for {@link McpAuthGuard.authorizeToolInvocation}. */\nexport function authorizeToolInvocation(\n auth: ProtocolMcpAuthContext | null,\n name: string,\n args: Record<string, unknown>,\n): JsonRpcErrorShape | null {\n return McpAuthGuard.authorizeToolInvocation(auth, name, args);\n}\n\n/** Functional alias for {@link McpAuthGuard.authorizeResourceRead}. */\nexport function authorizeResourceRead(\n auth: ProtocolMcpAuthContext | null,\n uri: string,\n): JsonRpcErrorShape | null {\n return McpAuthGuard.authorizeResourceRead(auth, uri);\n}\n","import { randomUUID } from \"node:crypto\";\nimport type { FastifyInstance, FastifyReply, FastifyRequest } from \"fastify\";\nimport type { ProtocolMcpAuthContext, ProtocolMcpAuthLookup } from \"../auth/McpAuth.js\";\nimport {\n MCP_DEFAULT_PROTOCOL_VERSION,\n MCP_HTTP_PATHS,\n MCP_PROTOCOL_VERSIONS,\n type JsonRpcId,\n type JsonRpcResponse,\n} from \"./McpContracts.js\";\nimport {\n asRecord,\n asString,\n buildServerTimingHeader,\n durationMs,\n getPublicBaseUrl,\n jsonRpcError,\n jsonRpcSuccess,\n toPrettyText,\n} from \"./McpSupport.js\";\nimport {\n authenticateMcpRequest,\n authorizeResourceRead,\n authorizeToolInvocation,\n describeMcpAuthConfig,\n isAuthenticationRequired,\n} from \"./McpAuthGuard.js\";\nimport { buildStaticResources, readResource } from \"./McpResources.js\";\nimport { buildPrompts } from \"./McpPrompts.js\";\nimport { buildTools, findTool, handleToolCall } from \"./McpTools.js\";\nimport type { McpRuntimeEvent, McpTelemetrySink } from \"./McpTelemetry.js\";\n\nasync function recordTelemetry(\n app: FastifyInstance,\n sink: McpTelemetrySink | null,\n event: McpRuntimeEvent,\n): Promise<void> {\n if (!sink) return;\n try {\n await sink.record(event);\n } catch (err) {\n app.log.warn({ err, event: event.event }, \"MCP telemetry write failed\");\n }\n}\n\nfunction canonicalAuthorizationOutcome(value: unknown): string | null {\n const record = asRecord(value);\n const raw = asString(record?.outcome) ?? asString(record?.decision) ?? asString(record?.verdict);\n if (!raw) return null;\n switch (raw.trim().toUpperCase()) {\n case \"ALLOW\":\n case \"APPROVE\":\n case \"AUTO_APPROVE\":\n return \"ALLOW\";\n case \"BLOCK\":\n case \"REJECT\":\n case \"AUTO_REJECT\":\n return \"BLOCK\";\n case \"ESCALATE\":\n return \"ESCALATE\";\n case \"REVIEW\":\n case \"RESTRAIN\":\n case \"REQUIRE_REVIEW\":\n return \"REVIEW\";\n default:\n return null;\n }\n}\n\nfunction buildInitializeResult(\n serviceName: string,\n serviceVersion: string,\n): Record<string, unknown> {\n return {\n protocolVersion: MCP_DEFAULT_PROTOCOL_VERSION,\n capabilities: {\n prompts: { listChanged: false },\n resources: { listChanged: false, subscribe: false },\n tools: { listChanged: false },\n },\n serverInfo: {\n name: serviceName,\n title: \"Decionis Protocol MCP\",\n version: serviceVersion,\n },\n instructions:\n \"Use Decionis Protocol to evaluate a proposed action before execution and inspect its signed governance evidence. Evaluation tools record Decionis decisions but never perform the downstream mutation. Use read-only dossier, chain, marketplace, and vertical tools for inspection.\",\n };\n}\n\nasync function handleJsonRpcRequest(\n app: FastifyInstance,\n requestBody: Record<string, unknown>,\n options: {\n publicBaseUrl: string;\n serviceName: string;\n serviceVersion: string;\n auth: ProtocolMcpAuthContext | null;\n authLookup: ProtocolMcpAuthLookup | null;\n telemetry: McpTelemetrySink | null;\n connectionId: string | null;\n },\n): Promise<{ statusCode: number; payload?: JsonRpcResponse }> {\n const idValue = requestBody.id;\n const id =\n typeof idValue === \"string\" || typeof idValue === \"number\"\n ? idValue\n : (null as JsonRpcId | null);\n const method = asString(requestBody.method);\n if (!method) {\n return {\n statusCode: 400,\n payload: jsonRpcError(id, -32600, \"JSON-RPC method is required\"),\n };\n }\n\n const params = asRecord(requestBody.params) ?? {};\n const tools = buildTools(app);\n const prompts = buildPrompts(\n options.publicBaseUrl,\n describeMcpAuthConfig(process.env, {\n hasDynamicOrgKeyLookup: Boolean(options.authLookup),\n }),\n );\n const staticResources = buildStaticResources(\n options.publicBaseUrl,\n options.serviceName,\n options.serviceVersion,\n );\n\n if (method === \"notifications/initialized\" && id == null) {\n return { statusCode: 202 };\n }\n\n if (method === \"initialize\") {\n if (id == null) {\n return {\n statusCode: 400,\n payload: jsonRpcError(null, -32600, \"initialize requests must include an id\"),\n };\n }\n const requestedVersion = asString(params.protocolVersion);\n const negotiatedVersion =\n requestedVersion && MCP_PROTOCOL_VERSIONS.includes(requestedVersion as never)\n ? requestedVersion\n : MCP_DEFAULT_PROTOCOL_VERSION;\n const clientInfo = asRecord(params.clientInfo);\n await recordTelemetry(app, options.telemetry, {\n event: \"connection_succeeded\",\n connectionId: options.connectionId,\n clientName: asString(clientInfo?.name),\n clientVersion: asString(clientInfo?.version),\n protocolVersion: negotiatedVersion,\n authMode: options.auth?.kind ?? \"none\",\n statusCode: 200,\n });\n return {\n statusCode: 200,\n payload: jsonRpcSuccess(id, {\n ...buildInitializeResult(options.serviceName, options.serviceVersion),\n protocolVersion: negotiatedVersion,\n }),\n };\n }\n\n if (id == null) {\n return { statusCode: 202 };\n }\n\n switch (method) {\n case \"ping\":\n return { statusCode: 200, payload: jsonRpcSuccess(id, {}) };\n case \"tools/list\":\n await recordTelemetry(app, options.telemetry, {\n event: \"tools_listed\",\n connectionId: options.connectionId,\n authMode: options.auth?.kind ?? \"none\",\n statusCode: 200,\n });\n return {\n statusCode: 200,\n payload: jsonRpcSuccess(id, {\n tools: tools.map((tool) => ({\n name: tool.name,\n title: tool.title,\n description: tool.description,\n inputSchema: tool.inputSchema,\n ...(tool.outputSchema ? { outputSchema: tool.outputSchema } : {}),\n annotations: tool.annotations,\n })),\n }),\n };\n case \"tools/call\": {\n const name = asString(params.name);\n if (!name) {\n return {\n statusCode: 400,\n payload: jsonRpcError(id, -32602, \"tools/call requires params.name\"),\n };\n }\n const tool = findTool(tools, name);\n if (!tool) {\n return {\n statusCode: 404,\n payload: jsonRpcError(id, -32601, `Unknown tool '${name}'`),\n };\n }\n const toolStartedAt = process.hrtime.bigint();\n await recordTelemetry(app, options.telemetry, {\n event: \"tool_called\",\n connectionId: options.connectionId,\n toolName: tool.name,\n authMode: options.auth?.kind ?? \"none\",\n });\n const args = asRecord(params.arguments) ?? {};\n const authError = authorizeToolInvocation(options.auth, name, args);\n if (authError) {\n await recordTelemetry(app, options.telemetry, {\n event: \"authorization_outcome\",\n connectionId: options.connectionId,\n toolName: tool.name,\n outcome: \"DENIED\",\n authMode: options.auth?.kind ?? \"none\",\n statusCode: 403,\n durationMs: durationMs(toolStartedAt),\n });\n await recordTelemetry(app, options.telemetry, {\n event: \"tool_failed\",\n connectionId: options.connectionId,\n toolName: tool.name,\n outcome: \"DENIED\",\n authMode: options.auth?.kind ?? \"none\",\n statusCode: 403,\n durationMs: durationMs(toolStartedAt),\n });\n return {\n statusCode: 403,\n payload: jsonRpcError(id, authError.code, authError.message),\n };\n }\n const result = await handleToolCall(tool, args);\n const outcome = canonicalAuthorizationOutcome(result.structuredContent);\n await recordTelemetry(app, options.telemetry, {\n event: result.isError ? \"tool_failed\" : \"tool_succeeded\",\n connectionId: options.connectionId,\n toolName: tool.name,\n outcome,\n authMode: options.auth?.kind ?? \"none\",\n statusCode: 200,\n durationMs: durationMs(toolStartedAt),\n });\n if (outcome) {\n await recordTelemetry(app, options.telemetry, {\n event: \"authorization_outcome\",\n connectionId: options.connectionId,\n toolName: tool.name,\n outcome,\n authMode: options.auth?.kind ?? \"none\",\n statusCode: 200,\n durationMs: durationMs(toolStartedAt),\n });\n }\n return {\n statusCode: 200,\n payload: jsonRpcSuccess(id, result),\n };\n }\n case \"resources/list\":\n return {\n statusCode: 200,\n payload: jsonRpcSuccess(id, { resources: staticResources }),\n };\n case \"resources/templates/list\":\n return {\n statusCode: 200,\n payload: jsonRpcSuccess(id, {\n resourceTemplates: [\n {\n uriTemplate: \"decionis://connectors/{slug}\",\n name: \"connector_detail\",\n title: \"Connector Detail\",\n description:\n \"Read one Connector Registry row: status, install channels, governed actions, verification.\",\n mimeType: \"application/json\",\n },\n {\n uriTemplate: \"decionis://marketplaces/targets/{target}\",\n name: \"marketplace_target_detail\",\n title: \"Marketplace Target Detail\",\n description: \"Read one marketplace target profile and readiness bundle.\",\n mimeType: \"application/json\",\n },\n {\n uriTemplate: \"decionis://dossiers/{org_id}/{dossier_id}\",\n name: \"decision_dossier\",\n title: \"Decision Dossier\",\n description: \"Read a stored Decision Dossier by org and dossier ID.\",\n mimeType: \"application/json\",\n },\n {\n uriTemplate: \"decionis://enforcement-rollouts/{org_id}\",\n name: \"enforcement_rollouts\",\n title: \"Enforcement Rollouts\",\n description: \"Read rollout controls for an org.\",\n mimeType: \"application/json\",\n },\n ],\n }),\n };\n case \"resources/read\": {\n const uri = asString(params.uri);\n if (!uri) {\n return {\n statusCode: 400,\n payload: jsonRpcError(id, -32602, \"resources/read requires params.uri\"),\n };\n }\n const authError = authorizeResourceRead(options.auth, uri);\n if (authError) {\n return {\n statusCode: 403,\n payload: jsonRpcError(id, authError.code, authError.message),\n };\n }\n try {\n const read = await readResource(app, uri, options);\n return {\n statusCode: 200,\n payload: jsonRpcSuccess(id, {\n contents: [\n {\n uri,\n mimeType: read.mimeType ?? \"application/json\",\n text: toPrettyText(read.value),\n },\n ],\n }),\n };\n } catch (err) {\n return {\n statusCode: 404,\n payload: jsonRpcError(\n id,\n -32002,\n err instanceof Error ? err.message : \"Unable to read resource\",\n ),\n };\n }\n }\n case \"prompts/list\":\n return {\n statusCode: 200,\n payload: jsonRpcSuccess(id, {\n prompts: prompts.map((prompt) => ({\n name: prompt.name,\n title: prompt.title,\n description: prompt.description,\n ...(prompt.arguments ? { arguments: prompt.arguments } : {}),\n })),\n }),\n };\n case \"prompts/get\": {\n const name = asString(params.name);\n if (!name) {\n return {\n statusCode: 400,\n payload: jsonRpcError(id, -32602, \"prompts/get requires params.name\"),\n };\n }\n const prompt = prompts.find((entry) => entry.name === name);\n if (!prompt) {\n return {\n statusCode: 404,\n payload: jsonRpcError(id, -32601, `Unknown prompt '${name}'`),\n };\n }\n const args = asRecord(params.arguments) ?? {};\n return {\n statusCode: 200,\n payload: jsonRpcSuccess(id, {\n description: prompt.description,\n messages: [\n {\n role: \"user\",\n content: {\n type: \"text\",\n text: prompt.handler(args),\n },\n },\n ],\n }),\n };\n }\n default:\n return {\n statusCode: 404,\n payload: jsonRpcError(id, -32601, `Unknown method '${method}'`),\n };\n }\n}\n\nfunction isLegacyToolCall(value: unknown): value is {\n tool_name: string;\n tool_version?: string;\n input?: unknown;\n} {\n const record = asRecord(value);\n return Boolean(record && !record.jsonrpc && asString(record.tool_name));\n}\n\nasync function handleLegacyToolCall(\n app: FastifyInstance,\n auth: ProtocolMcpAuthContext | null,\n body: { tool_name: string; tool_version?: string; input?: unknown },\n): Promise<Record<string, unknown>> {\n const tools = buildTools(app);\n const tool = findTool(tools, body.tool_name);\n if (!tool) {\n return {\n error: \"UNKNOWN_TOOL\",\n tool_name: body.tool_name,\n };\n }\n\n const args = asRecord(body.input) ?? {};\n const authError = authorizeToolInvocation(auth, body.tool_name, args);\n if (authError) {\n return {\n error: \"FORBIDDEN\",\n message: authError.message,\n tool_name: body.tool_name,\n is_error: true,\n };\n }\n\n const result = await handleToolCall(tool, args);\n return {\n output: result.structuredContent ?? { text: result.content[0]?.text ?? \"\" },\n event: {\n id: `${tool.name}:${randomUUID().slice(0, 12)}`,\n tool_name: tool.name,\n tool_version: body.tool_version ?? \"mcp\",\n input_hash: \"legacy-tool-call\",\n output_hash: \"legacy-tool-call\",\n output: result.structuredContent ?? null,\n started_at: new Date().toISOString(),\n finished_at: new Date().toISOString(),\n },\n is_error: result.isError ?? false,\n };\n}\n\nasync function handleMcpHttpRequest(\n app: FastifyInstance,\n req: FastifyRequest,\n reply: FastifyReply,\n options: {\n publicBaseUrl: string;\n serviceName: string;\n serviceVersion: string;\n authLookup?: ProtocolMcpAuthLookup | null;\n telemetry?: McpTelemetrySink | null;\n },\n) {\n const requestStartedAt = process.hrtime.bigint();\n const authLookup = options.authLookup ?? null;\n const authStartedAt = process.hrtime.bigint();\n const auth = await authenticateMcpRequest(req, authLookup);\n const authDurationMs = durationMs(authStartedAt);\n if (!auth && isAuthenticationRequired(authLookup)) {\n await recordTelemetry(app, options.telemetry ?? null, {\n event: \"authentication_failed\",\n statusCode: 401,\n durationMs: authDurationMs,\n });\n const maybeId = asRecord(req.body)?.id;\n const id =\n typeof maybeId === \"string\" || typeof maybeId === \"number\"\n ? maybeId\n : (null as JsonRpcId | null);\n reply.header(\n \"server-timing\",\n buildServerTimingHeader({\n total_ms: durationMs(requestStartedAt),\n stages: { auth_ms: authDurationMs },\n }),\n );\n reply.header(\n \"www-authenticate\",\n `Bearer resource_metadata=\"${options.publicBaseUrl}/.well-known/oauth-protected-resource\", error=\"invalid_token\"`,\n );\n return reply.code(401).send(jsonRpcError(id, -32001, \"Unauthorized MCP request\"));\n }\n\n if (Array.isArray(req.body)) {\n reply.header(\n \"server-timing\",\n buildServerTimingHeader({\n total_ms: durationMs(requestStartedAt),\n stages: { auth_ms: authDurationMs },\n }),\n );\n return reply.code(400).send(jsonRpcError(null, -32600, \"Batch requests are not supported\"));\n }\n\n if (isLegacyToolCall(req.body)) {\n const rpcStartedAt = process.hrtime.bigint();\n const connectionId = asString(req.headers[\"mcp-session-id\"]);\n await recordTelemetry(app, options.telemetry ?? null, {\n event: \"tool_called\",\n connectionId,\n toolName: req.body.tool_name,\n authMode: auth?.kind ?? \"none\",\n });\n const payload = await handleLegacyToolCall(app, auth, req.body);\n const outcome = canonicalAuthorizationOutcome(payload.output);\n await recordTelemetry(app, options.telemetry ?? null, {\n event: payload.is_error || payload.error ? \"tool_failed\" : \"tool_succeeded\",\n connectionId,\n toolName: req.body.tool_name,\n outcome,\n authMode: auth?.kind ?? \"none\",\n statusCode: 200,\n durationMs: durationMs(rpcStartedAt),\n });\n if (outcome) {\n await recordTelemetry(app, options.telemetry ?? null, {\n event: \"authorization_outcome\",\n connectionId,\n toolName: req.body.tool_name,\n outcome,\n authMode: auth?.kind ?? \"none\",\n statusCode: 200,\n durationMs: durationMs(rpcStartedAt),\n });\n }\n reply.header(\n \"server-timing\",\n buildServerTimingHeader({\n total_ms: durationMs(requestStartedAt),\n stages: {\n auth_ms: authDurationMs,\n rpc_ms: durationMs(rpcStartedAt),\n },\n }),\n );\n return reply.code(200).send(payload);\n }\n\n const requestBody = asRecord(req.body);\n if (!requestBody) {\n reply.header(\n \"server-timing\",\n buildServerTimingHeader({\n total_ms: durationMs(requestStartedAt),\n stages: { auth_ms: authDurationMs },\n }),\n );\n return reply.code(400).send(jsonRpcError(null, -32600, \"JSON-RPC request body required\"));\n }\n\n const rpcStartedAt = process.hrtime.bigint();\n const requestedMethod = asString(requestBody.method);\n const incomingSession = asString(req.headers[\"mcp-session-id\"]);\n const connectionId = requestedMethod === \"initialize\" ? randomUUID() : incomingSession;\n const result = await handleJsonRpcRequest(app, requestBody, {\n publicBaseUrl: options.publicBaseUrl,\n serviceName: options.serviceName,\n serviceVersion: options.serviceVersion,\n auth,\n authLookup,\n telemetry: options.telemetry ?? null,\n connectionId,\n });\n if (requestedMethod === \"initialize\" && result.statusCode === 200) {\n reply.header(\"mcp-session-id\", connectionId);\n }\n reply.header(\n \"server-timing\",\n buildServerTimingHeader({\n total_ms: durationMs(requestStartedAt),\n stages: {\n auth_ms: authDurationMs,\n rpc_ms: durationMs(rpcStartedAt),\n },\n }),\n );\n if (!result.payload) {\n return reply.code(result.statusCode).send();\n }\n return reply.code(result.statusCode).send(result.payload);\n}\n\n/** Registers the native MCP streamable-HTTP routes and metadata endpoints. */\nexport function registerProtocolMcpRoutes(\n app: FastifyInstance,\n options: {\n serviceName: string;\n serviceVersion: string;\n authLookup?: ProtocolMcpAuthLookup | null;\n telemetry?: McpTelemetrySink | null;\n },\n): void {\n const publicBaseUrl = getPublicBaseUrl();\n const authLookup = options.authLookup ?? null;\n const auth = describeMcpAuthConfig(process.env, {\n hasDynamicOrgKeyLookup: Boolean(authLookup),\n });\n const metadata = {\n ok: true,\n service: options.serviceName,\n version: options.serviceVersion,\n transport: \"streamable_http\",\n endpoint: `${publicBaseUrl}/v1/protocol/mcp`,\n endpoint_aliases: MCP_HTTP_PATHS,\n supported_protocol_versions: [...MCP_PROTOCOL_VERSIONS],\n auth,\n oauth: {\n protected_resource_metadata: `${publicBaseUrl}/.well-known/oauth-protected-resource`,\n authorization_server_metadata:\n \"https://api.decionis.com/.well-known/oauth-authorization-server\",\n },\n };\n\n const oauthProtectedResource = {\n resource: `${publicBaseUrl}/mcp`,\n authorization_servers: [\"https://api.decionis.com\"],\n bearer_methods_supported: [\"header\"],\n scopes_supported: [\"decision:read\", \"decision:run\", \"decision:write\"],\n resource_documentation: \"https://decionis.com/docs/protocol-mcp\",\n };\n\n app.get(\"/.well-known/oauth-protected-resource\", async () => oauthProtectedResource);\n app.get(\"/.well-known/oauth-protected-resource/mcp\", async () => oauthProtectedResource);\n\n for (const path of MCP_HTTP_PATHS) {\n app.get(path, async () => metadata);\n app.delete(path, async (_req, reply) => reply.code(204).send());\n app.post(path, async (req, reply) =>\n handleMcpHttpRequest(app, req, reply, {\n publicBaseUrl,\n serviceName: options.serviceName,\n serviceVersion: options.serviceVersion,\n authLookup,\n telemetry: options.telemetry ?? null,\n }),\n );\n }\n}\n","/**\n * The Decionis Connector Registry — the single source of truth every\n * connector surface derives from.\n *\n * Row discipline:\n * - Claims are scoped to shipped behavior in the owning doc's vocabulary;\n * each row's provenance comment names its sources and the live-URL sweep\n * date (discovery rules 1.1 / 1.2).\n * - Deliberate exclusions, so their absence reads as a decision rather\n * than an oversight: chat approval channels (Slack, Teams, Webex, Power\n * Automate) and cloud billing marketplaces (AWS, Google Cloud,\n * Microsoft, Atlassian) are not connectors; MCP and the GitHub Action\n * are surfaces and live in the machine-discovery inventories; Kong,\n * Envoy, and Vercel enforcement adapters belong to Presence and are\n * cross-linked, never claimed here; SFCC returns when its cartridge and\n * a resolving public page exist; the Workday verticals ship inside the\n * protocol, not as a connector artifact.\n */\n\nimport type { ConnectorDefinition, ConnectorStatus } from \"./ConnectorContracts\";\n\nconst SITE = \"https://decionis.com\";\n\nconst connectors: readonly ConnectorDefinition[] = [\n // ── Commerce ──────────────────────────────────────────────────────────\n {\n // Live Shopify App Store listing (sweep 2026-08-10, also pinned by\n // apps/web ShopifyAppStore.listingUrl + the distributionSameAs sweep).\n // Copy scoped to the published listing description.\n slug: \"shopify\",\n name: \"Decionis for Shopify\",\n vendor: \"Shopify\",\n category: \"commerce\",\n status: \"production\",\n summary:\n \"Deterministic policy enforcement on refunds, discounts, oversells, and risky orders at Shopify checkout — every governed action becomes a signed Decision Dossier with a public verification link.\",\n capabilities: [\n \"margin-floor-enforcement\",\n \"checkout-policy-enforcement\",\n \"signed-decision-dossier\",\n ],\n decisionsSupported: [\"refund\", \"discount\", \"oversell\", \"risky-order\"],\n installation: [\n {\n kind: \"marketplace\",\n url: \"https://apps.shopify.com/decionis-checkout-gate\",\n label: \"Shopify App Store\",\n },\n ],\n // Shopify predates the marketplace-target program (it is the original\n // commerce wedge with its own app workspace), so it deliberately has no\n // `marketplaceTarget` join — /commerce is its owning page.\n documentation: `${SITE}/commerce`,\n distribution: { download: false, guidedInstall: true, remoteInstall: false },\n activation: { method: \"marketplace_install\", requiresWorkspace: true },\n presenceSupport: \"planned\",\n marketplaceListingId: \"shopify-app\",\n providerId: \"SHOPIFY\",\n },\n {\n // Published in the WordPress.org plugin directory (slug `decionis`,\n // 1.0.0) — sweep 2026-08-10 via the distributionSameAs verification.\n // Copy reuses the shared readiness provenance: verified end to end on a\n // staging store before the listing went live; shadow first,\n // enforcement opt-in.\n slug: \"woo\",\n name: \"Decionis for WooCommerce\",\n vendor: \"WooCommerce\",\n category: \"commerce\",\n status: \"production\",\n version: \"1.0.0\",\n summary:\n \"Margin floors enforced at WooCommerce checkout — Block and classic, using core COGS, with a signed Decision Dossier per evaluation. New stores start in shadow mode; enforcement is opt-in.\",\n capabilities: [\n \"margin-floor-enforcement\",\n \"checkout-policy-enforcement\",\n \"shadow-mode\",\n \"signed-decision-dossier\",\n ],\n decisionsSupported: [\"checkout-order\"],\n installation: [\n {\n kind: \"marketplace\",\n url: \"https://wordpress.org/plugins/decionis/\",\n label: \"WordPress.org Plugin Directory\",\n },\n ],\n documentation: `${SITE}/marketplace/woo`,\n distribution: { download: false, guidedInstall: true, remoteInstall: false },\n activation: { method: \"api_key\", requiresWorkspace: true },\n presenceSupport: \"planned\",\n marketplaceTarget: \"woo\",\n marketplaceListingId: \"woo-plugin\",\n providerId: \"WOO\",\n },\n {\n // eBay approved the app for production and the connector is deployed and\n // marketplace-account-deletion compliant; the first read-only Fulfillment\n // probe passed against a live seller account (docs/marketplace/ebay/\n // evidence/latest.json). No public eBay listing directory exists, so the\n // channel is the guided OAuth connect — and enforcement stays honest:\n // shadow dossiers today, write-scope approval pending.\n slug: \"ebay\",\n name: \"Decionis for eBay\",\n vendor: \"eBay\",\n category: \"commerce\",\n status: \"installable\",\n summary:\n \"Margin and promo-hygiene guardrails for eBay Sell-API listings, orders, and promotions — eBay OAuth connect, production-approved, shadow-mode dossiers with enforcement pending write-scope approval.\",\n capabilities: [\"margin-guardrails\", \"promo-hygiene\", \"shadow-mode\", \"signed-decision-dossier\"],\n decisionsSupported: [\"listing-change\", \"order-fulfillment\", \"promotion\"],\n installation: [\n {\n kind: \"guided\",\n url: `${SITE}/marketplace/ebay`,\n label: \"eBay OAuth connect (guided)\",\n },\n ],\n documentation: `${SITE}/marketplace/ebay`,\n verification: {\n validatedBy: \"eBay production approval + Decionis live verification\",\n evidence:\n \"eBay approved the app for production; read-only Fulfillment probe verified against a live seller account (docs/marketplace/ebay/evidence/latest.json, deployment 2026-07-14).\",\n lastValidated: \"2026-07-14\",\n },\n distribution: { download: false, guidedInstall: true, remoteInstall: false },\n activation: { method: \"oauth\", requiresWorkspace: true },\n presenceSupport: \"planned\",\n marketplaceTarget: \"ebay\",\n providerId: \"EBAY\",\n },\n {\n // Passed ALL Adobe Commerce Marketplace technical review phases (SID\n // qv4l7d2ak6): automated EQP 2026-07-08, full technical-review\n // confirmation received 2026-08-10 (tested by Adobe on Magento 2.4.9\n // EE + CE, PHP 8.5.5). Marketplace release awaits the remaining\n // marketing review, and the gate has not been validated against a live\n // merchant store — so no channels yet; the customer-deployable kit\n // ships next (docs/claims DECIONIS-CLM-022).\n slug: \"adobe-commerce\",\n name: \"Decionis Connector for Adobe Commerce\",\n vendor: \"Adobe\",\n category: \"commerce\",\n status: \"validated\",\n version: \"1.0.0\",\n summary:\n \"Synchronous checkout-webhook enforcement for Adobe Commerce / Magento — halts a margin-breaching order (op:exception) or lets it through, failing open on any engine error, with promo-hygiene checks and federated signed Decision Dossiers.\",\n capabilities: [\n \"margin-floor-enforcement\",\n \"checkout-policy-enforcement\",\n \"promo-hygiene\",\n \"fail-open-checkout-gate\",\n \"signed-decision-dossier\",\n ],\n decisionsSupported: [\"checkout-order\", \"pricing-change\", \"promotion\"],\n installation: [\n {\n // The kit page hosts the reviewed composer module + checksum,\n // manifest, and SBOM — shipped in the same change that makes the URL\n // resolve (rule 1.1 by construction).\n kind: \"hosted_download\",\n url: `${SITE}/marketplace/adobe-commerce/connector-kit`,\n label: \"Connector kit (guided deployment)\",\n },\n ],\n package: {\n artifact:\n \"/marketplace/adobe-commerce/connector-kit/decionis-module-checkout-guardrail-1.0.0.zip\",\n sha256Path:\n \"/marketplace/adobe-commerce/connector-kit/decionis-module-checkout-guardrail-1.0.0.sha256.txt\",\n manifestPath: \"/marketplace/adobe-commerce/connector-kit/manifest.json\",\n sbomPath: \"/marketplace/adobe-commerce/connector-kit/SBOM.json\",\n format: \"magento2-module\",\n },\n documentation: `${SITE}/marketplace/adobe-commerce`,\n verification: {\n validatedBy: \"Adobe Commerce Marketplace technical review (EQP)\",\n evidence:\n \"Passed all technical review phases (SID qv4l7d2ak6): automated EQP pass 2026-07-08, full technical-review confirmation 2026-08-10, tested by Adobe on Magento 2.4.9 Enterprise + Community Edition (PHP 8.5.5). Not yet validated against a live merchant store.\",\n lastValidated: \"2026-08-10\",\n },\n distribution: { download: true, guidedInstall: false, remoteInstall: false },\n activation: { method: \"enrollment_token\", requiresWorkspace: true },\n presenceSupport: \"planned\",\n marketplaceTarget: \"adobe-commerce\",\n providerId: \"ADOBE_COMMERCE\",\n },\n {\n // SP-API connector built and unit-tested; shadow-mode first while live\n // seller validation completes (homepage Beta tile is the owning copy).\n slug: \"amazon\",\n name: \"Decionis for Amazon\",\n vendor: \"Amazon\",\n category: \"commerce\",\n status: \"validated\",\n summary:\n \"Margin and pricing guardrails for Amazon SP-API listings and orders — Login with Amazon connect, shadow-mode first while live seller validation completes.\",\n capabilities: [\"margin-guardrails\", \"shadow-mode\", \"signed-decision-dossier\"],\n decisionsSupported: [\"listing-change\", \"order\"],\n installation: [],\n documentation: `${SITE}/marketplace/amazon`,\n distribution: { download: false, guidedInstall: false, remoteInstall: false },\n activation: { method: \"oauth\", requiresWorkspace: true },\n presenceSupport: \"planned\",\n marketplaceTarget: \"amazon\",\n providerId: \"AMAZON\",\n },\n {\n // Post-purchase fulfillment circuit breaker — OAuth + refresh, signed\n // Open API, webhook intake/verification, margin gate, Ship-Package\n // release built and unit-tested; TikTok App Store review not submitted\n // (shared readiness provenance).\n slug: \"tiktok\",\n name: \"Decionis for TikTok Shop\",\n vendor: \"TikTok Shop\",\n category: \"commerce\",\n status: \"validated\",\n summary:\n \"Post-purchase fulfillment circuit breaker for TikTok Shop — orders clear a margin gate before Ship-Package release, with signed Decision Dossiers per governed order.\",\n capabilities: [\"fulfillment-circuit-breaker\", \"margin-guardrails\", \"signed-decision-dossier\"],\n decisionsSupported: [\"order-fulfillment\"],\n installation: [],\n documentation: `${SITE}/marketplace/tiktok`,\n distribution: { download: false, guidedInstall: false, remoteInstall: false },\n activation: { method: \"oauth\", requiresWorkspace: true },\n presenceSupport: \"planned\",\n marketplaceTarget: \"tiktok\",\n providerId: \"TIKTOK_SHOP\",\n },\n {\n // Solution Provider OAuth, PO-created webhook intake with HMAC\n // verification, margin gate, Acknowledge-Order release/hold — built and\n // unit-tested; Solution Provider approval and live seller verification\n // remain (shared readiness provenance).\n slug: \"walmart\",\n name: \"Decionis for Walmart Marketplace\",\n vendor: \"Walmart\",\n category: \"commerce\",\n status: \"validated\",\n summary:\n \"Post-purchase fulfillment circuit breaker for Walmart Marketplace — purchase orders clear a margin gate (COGS + referral fee + shipping) before Acknowledge-Order release.\",\n capabilities: [\"fulfillment-circuit-breaker\", \"margin-guardrails\", \"signed-decision-dossier\"],\n decisionsSupported: [\"order-acknowledgement\"],\n installation: [],\n documentation: `${SITE}/marketplace/walmart`,\n distribution: { download: false, guidedInstall: false, remoteInstall: false },\n activation: { method: \"oauth\", requiresWorkspace: true },\n presenceSupport: \"planned\",\n marketplaceTarget: \"walmart\",\n providerId: \"WALMART_MARKETPLACE\",\n },\n {\n // Vendor Center GOP integration — centralized Mastershop OAuth, durable\n // order polling, multi-market margin/COD/SLA evaluation, guarded\n // fulfillment; live Vendor Center verification still required before\n // enforcement (shared readiness provenance).\n slug: \"jumia\",\n name: \"Decionis for Jumia\",\n vendor: \"Jumia\",\n category: \"commerce\",\n status: \"validated\",\n summary:\n \"Guarded fulfillment for Jumia Vendor Center — multi-market margin, COD, and SLA evaluation before order release, with signed Decision Dossiers per governed order.\",\n capabilities: [\"fulfillment-circuit-breaker\", \"margin-guardrails\", \"signed-decision-dossier\"],\n decisionsSupported: [\"order-fulfillment\"],\n installation: [],\n documentation: `${SITE}/marketplace/jumia`,\n distribution: { download: false, guidedInstall: false, remoteInstall: false },\n activation: { method: \"oauth\", requiresWorkspace: true },\n presenceSupport: \"planned\",\n marketplaceTarget: \"jumia\",\n providerId: \"JUMIA\",\n },\n {\n // Headless / Open Checkout gate built and unit-tested; not live-store\n // validated (rotated off the homepage tiles in favour of WooCommerce).\n slug: \"bigcommerce\",\n name: \"Decionis for BigCommerce\",\n vendor: \"BigCommerce\",\n category: \"commerce\",\n status: \"validated\",\n summary:\n \"Checkout margin gate for BigCommerce headless and Open Checkout storefronts — built and unit-tested, pending validation against a live store.\",\n capabilities: [\"margin-floor-enforcement\", \"checkout-policy-enforcement\"],\n decisionsSupported: [\"checkout-order\"],\n installation: [],\n documentation: `${SITE}/marketplace/bigcommerce`,\n distribution: { download: false, guidedInstall: false, remoteInstall: false },\n activation: { method: \"api_key\", requiresWorkspace: true },\n presenceSupport: \"planned\",\n marketplaceTarget: \"bigcommerce\",\n },\n {\n // Shopware 6 App System handshake, shop-signed webhooks, fail-open\n // synchronous checkout gate — built and unit-tested, not yet validated\n // against a live Shopware store (docs/claims DECIONIS-CLM-023).\n slug: \"shopware\",\n name: \"Decionis for Shopware\",\n vendor: \"Shopware\",\n category: \"commerce\",\n status: \"validated\",\n summary:\n \"Fail-open synchronous checkout gate for Shopware 6 — App System registration handshake, shop-signed webhooks, and promo-hygiene checks, pending validation against a live store.\",\n capabilities: [\n \"margin-floor-enforcement\",\n \"checkout-policy-enforcement\",\n \"promo-hygiene\",\n \"fail-open-checkout-gate\",\n ],\n decisionsSupported: [\"checkout-order\", \"promotion\"],\n installation: [],\n documentation: `${SITE}/marketplace/shopware`,\n distribution: { download: false, guidedInstall: false, remoteInstall: false },\n activation: { method: \"api_key\", requiresWorkspace: true },\n presenceSupport: \"planned\",\n marketplaceTarget: \"shopware\",\n },\n\n // ── Enterprise ────────────────────────────────────────────────────────\n {\n // SAP PartnerEdge Solution Review approved 2026-06-22 (solution id\n // 2004368, docs/marketplace/sap/solution-hub-listing.md). The PartnerEdge\n // solution URL is partner-gated (anonymous fetch 404s — sweep\n // 2026-08-10), so it is deliberately NOT an install channel here; the\n // customer-deployable BTP deployment kit ships next. Dual-gate wording\n // from the owning listing copy.\n slug: \"sap\",\n name: \"Decionis Governed Execution Gate for SAP\",\n vendor: \"SAP\",\n category: \"enterprise\",\n status: \"validated\",\n version: \"0.1.0\",\n summary:\n \"Dual-gate governed execution for SAP S/4HANA, BTP, and CAP-side workflows — vendor payment release, procurement approval, and finance controls checked before they execute, with a signed Decision Dossier written back to the governed document.\",\n capabilities: [\n \"dual-gate-execution\",\n \"segregation-of-duties\",\n \"three-way-match\",\n \"s4hana-write-back\",\n \"signed-decision-dossier\",\n ],\n decisionsSupported: [\n \"vendor-payment-release\",\n \"procurement-approval\",\n \"finance-control-change\",\n ],\n installation: [\n {\n // Customer-deployed BTP kit (curated CAP source, mbt build →\n // cf deploy) — shipped in the same change that makes the URL resolve\n // (rule 1.1 by construction).\n kind: \"hosted_download\",\n url: `${SITE}/marketplace/sap/deployment-kit`,\n label: \"SAP BTP deployment kit (customer-deployed)\",\n },\n ],\n package: {\n artifact: \"/marketplace/sap/deployment-kit/decionis-sap-deployment-kit-0.1.0.zip\",\n sha256Path: \"/marketplace/sap/deployment-kit/decionis-sap-deployment-kit-0.1.0.sha256.txt\",\n manifestPath: \"/marketplace/sap/deployment-kit/manifest.json\",\n sbomPath: \"/marketplace/sap/deployment-kit/SBOM.json\",\n format: \"sap-mta-deployment-kit\",\n },\n documentation: `${SITE}/marketplace/sap`,\n verification: {\n validatedBy: \"SAP PartnerEdge Solution Review\",\n evidence:\n \"Solution Review completed and approved 2026-06-22 (SAP PartnerEdge solution id 2004368); SAP Store content listing is the next, contract-gated step.\",\n lastValidated: \"2026-06-22\",\n },\n distribution: { download: true, guidedInstall: false, remoteInstall: false },\n activation: { method: \"enrollment_token\", requiresWorkspace: true },\n presenceSupport: \"planned\",\n providerId: \"SAP\",\n },\n {\n // Scoped app x_dec_decionis (tables, script includes, Flow Designer\n // verify-intent action, shadow observers, workspace dossier panel,\n // scoped REST API). Self-attested platform evidence — tenant mapping,\n // ACLs, live policy-check execution, workflow trigger routing — is\n // recorded in the packaged evidence exports (docs/marketplace/servicenow\n // submission checklist, evidence refreshed as of the 2026-08-10 sweep).\n // Store publication deliberately deferred. The customer-deploy kit\n // CONTENT exists (full-app update-set XML + coverage manifest + INSTALL\n // under docs/marketplace/servicenow/connector-kit), but the public\n // download channel + `installable` flip are gated on a real\n // dev-instance import validation — a user-owned step; never claim the\n // install before it passes (rule 1.1 on the install claim itself).\n slug: \"servicenow\",\n name: \"Decionis Connector for ServiceNow\",\n vendor: \"ServiceNow\",\n category: \"enterprise\",\n status: \"validated\",\n summary:\n \"Scoped ServiceNow app (x_dec_decionis) that wires Decision Dossiers and Decision Drift evidence into incident, change, and risk-case workflows — a Flow Designer verify-intent action with shadow-mode observers.\",\n capabilities: [\n \"flow-designer-verify-intent\",\n \"shadow-mode\",\n \"decision-drift-evidence\",\n \"signed-decision-dossier\",\n ],\n decisionsSupported: [\"itsm-change\", \"incident-action\", \"risk-case-action\"],\n installation: [],\n documentation: `${SITE}/marketplace/servicenow`,\n verification: {\n validatedBy: \"Decionis platform evidence (self-attested)\",\n evidence:\n \"Live vendor-instance evidence exports: tenant mapping, ACLs and ACL-role links, live policy-check execution against the authenticated Decionis API, and workflow trigger routing (docs/marketplace/servicenow, evidence current as of 2026-08-10).\",\n lastValidated: \"2026-08-10\",\n },\n distribution: { download: false, guidedInstall: false, remoteInstall: false },\n activation: { method: \"enrollment_token\", requiresWorkspace: true },\n presenceSupport: \"planned\",\n marketplaceTarget: \"servicenow\",\n providerId: \"SERVICENOW\",\n },\n {\n // Customer-deployed starter package (Apex Action Gate, LWC, platform\n // event, permission set) served as committed zips with checksums;\n // AppExchange Security Review in progress, so no marketplace channel is\n // claimed (homepage Beta tile is the owning copy).\n slug: \"salesforce\",\n name: \"Decionis Action Gate for Salesforce\",\n vendor: \"Salesforce\",\n category: \"enterprise\",\n status: \"installable\",\n summary:\n \"Pre-execution Action Gate for Salesforce — Flow, Apex, and Agentforce actions checked before they run (allow / hold / escalate) with signed Decision Dossiers on the record. Customer-deployed starter package, shadow-first rollout.\",\n capabilities: [\n \"pre-execution-action-gate\",\n \"shadow-mode\",\n \"agentforce-governance\",\n \"signed-decision-dossier\",\n ],\n decisionsSupported: [\"flow-action\", \"apex-action\", \"agentforce-action\"],\n installation: [\n {\n kind: \"hosted_download\",\n url: `${SITE}/marketplace/salesforce/starter-package`,\n label: \"Salesforce starter package (customer-deployed)\",\n },\n ],\n package: {\n artifact: \"/marketplace/salesforce/starter-package/decionis-salesforce-starter-package.zip\",\n sha256Path:\n \"/marketplace/salesforce/starter-package/decionis-salesforce-starter-package.sha256.txt\",\n format: \"salesforce-metadata-source\",\n },\n documentation: `${SITE}/marketplace/salesforce`,\n distribution: { download: true, guidedInstall: false, remoteInstall: false },\n activation: { method: \"api_key\", requiresWorkspace: true },\n presenceSupport: \"planned\",\n marketplaceTarget: \"salesforce\",\n marketplaceListingId: \"salesforce-app\",\n providerId: \"SALESFORCE\",\n },\n\n // ── Automation ────────────────────────────────────────────────────────\n {\n // Live Zapier app-directory listing (sweep 2026-08-10: page resolves and\n // shows the Decionis app with the Create Decision Dossier action).\n slug: \"zapier\",\n name: \"Decionis for Zapier\",\n vendor: \"Zapier\",\n category: \"automation\",\n status: \"production\",\n summary:\n \"Create a governed decision and signed Decision Dossier inside any Zap — OAuth connection, Shadow Mode by default, and idempotent replay for temporary service failures.\",\n capabilities: [\"automation-step-governance\", \"shadow-mode\", \"signed-decision-dossier\"],\n decisionsSupported: [\"automation-step\"],\n installation: [\n {\n kind: \"marketplace\",\n url: \"https://zapier.com/apps/decionis/integrations\",\n label: \"Zapier app directory\",\n },\n ],\n documentation: `${SITE}/docs/zapier`,\n distribution: { download: false, guidedInstall: true, remoteInstall: false },\n activation: { method: \"oauth\", requiresWorkspace: true },\n presenceSupport: \"planned\",\n marketplaceListingId: \"zapier\",\n },\n {\n // The native Make app is built with its OAuth on-ramp live, but the Make\n // listing is private in review — so the installable path today is the\n // documented HTTP recipe (AutomationConnectors owning copy, status\n // `preview`).\n slug: \"make\",\n name: \"Decionis for Make\",\n vendor: \"Make\",\n category: \"automation\",\n status: \"installable\",\n summary:\n \"Evaluate an Action before the protected module runs — the native Decionis app is in Make listing review, and the documented HTTP recipe calls the same gate and returns the same signed Decision Dossier today.\",\n capabilities: [\"automation-step-governance\", \"signed-decision-dossier\"],\n decisionsSupported: [\"automation-step\"],\n installation: [\n {\n kind: \"docs\",\n url: `${SITE}/docs/automation-connectors#make`,\n label: \"HTTP recipe (native app listing in review)\",\n },\n ],\n documentation: `${SITE}/docs/automation-connectors#make`,\n distribution: { download: false, guidedInstall: false, remoteInstall: false },\n activation: { method: \"oauth\", requiresWorkspace: true },\n presenceSupport: \"planned\",\n },\n {\n // Community node published on npm (registry sweep 2026-08-10:\n // n8n-nodes-decionis@0.1.0).\n slug: \"n8n\",\n name: \"Decionis for n8n\",\n vendor: \"n8n\",\n category: \"automation\",\n status: \"production\",\n version: \"0.1.0\",\n summary:\n \"Every automation step asks permission before it executes — install the n8n community node from npm, or start from the HTTP Request recipe and four importable example workflows.\",\n capabilities: [\"automation-step-governance\", \"signed-decision-dossier\"],\n decisionsSupported: [\"automation-step\"],\n installation: [\n {\n kind: \"npm\",\n url: \"https://www.npmjs.com/package/n8n-nodes-decionis\",\n label: \"n8n community node on npm\",\n },\n ],\n documentation: `${SITE}/docs/automation-connectors#n8n`,\n distribution: { download: false, guidedInstall: false, remoteInstall: false },\n activation: { method: \"api_key\", requiresWorkspace: true },\n presenceSupport: \"planned\",\n },\n\n // ── Platform ──────────────────────────────────────────────────────────\n {\n // The standard webhook path into the protocol — the same Gate 1\n // admission check, any backend (owning copy: ERP & Webhooks tile +\n // /docs/webhooks).\n // `installable`, not `production`: the webhook path is live product\n // capability, but there is no public marketplace/registry listing to\n // install it from — you wire it from the documented recipe.\n slug: \"webhooks\",\n name: \"ERP & Webhooks\",\n vendor: \"Any system of record\",\n category: \"platform\",\n status: \"installable\",\n summary:\n \"Cross-verify cost basis and inventory against your system of record via standard webhooks — the same Gate 1 admission check, any backend.\",\n capabilities: [\"erp-cross-verification\", \"webhook-intake\"],\n decisionsSupported: [\"cost-basis-verification\", \"inventory-verification\"],\n installation: [\n { kind: \"docs\", url: `${SITE}/docs/webhooks`, label: \"Webhook integration guide\" },\n ],\n documentation: `${SITE}/docs/webhooks`,\n distribution: { download: false, guidedInstall: false, remoteInstall: false },\n activation: { method: \"api_key\", requiresWorkspace: true },\n presenceSupport: \"planned\",\n providerId: \"WEBHOOK\",\n },\n];\n\n/** Registry accessors. */\nexport class ConnectorRegistry {\n static readonly connectors = connectors;\n\n static bySlug(slug: string): ConnectorDefinition | undefined {\n return connectors.find((connector) => connector.slug === slug);\n }\n\n static byCategory(category: ConnectorDefinition[\"category\"]): readonly ConnectorDefinition[] {\n return connectors.filter((connector) => connector.category === category);\n }\n\n static byStatus(status: ConnectorStatus): readonly ConnectorDefinition[] {\n return connectors.filter((connector) => connector.status === status);\n }\n\n static slugs(): readonly string[] {\n return connectors.map((connector) => connector.slug);\n }\n}\n\n/** Alias for {@link ConnectorRegistry.connectors}. */\nexport const CONNECTOR_REGISTRY = ConnectorRegistry.connectors;\n\n/** Alias for {@link ConnectorRegistry.bySlug}. */\nexport const getConnector = ConnectorRegistry.bySlug;\n\n/** Alias for {@link ConnectorRegistry.slugs}. */\nexport const CONNECTOR_SLUGS = ConnectorRegistry.slugs();\n","import type { FastifyInstance } from \"fastify\";\nimport type { ProtocolMcpAuthLookup } from \"../auth/McpAuth.js\";\nimport {\n MCP_HTTP_PATHS,\n MCP_PROTOCOL_VERSIONS,\n type McpResourceReadResult,\n type McpStaticResource,\n} from \"./McpContracts.js\";\nimport { invokeProtocolRoute } from \"./McpSupport.js\";\nimport { describeMcpAuthConfig } from \"./McpAuthGuard.js\";\nimport { CONNECTOR_REGISTRY, getConnector } from \"@decionis/shared/connectors\";\n\n/** MCP static resource catalog and resource-read resolution. */\nexport class McpResources {\n static buildStaticResources(\n publicBaseUrl: string,\n serviceName: string,\n serviceVersion: string,\n ): McpStaticResource[] {\n return [\n {\n uri: \"decionis://protocol/overview\",\n name: \"protocol_overview\",\n title: \"Decionis Protocol Overview\",\n description: \"Native MCP, decisioning, governance, and Decision Dossier surface summary.\",\n mimeType: \"application/json\",\n },\n {\n uri: \"decionis://protocol/connection-surfaces\",\n name: \"connection_surfaces\",\n title: \"Decionis Connection Surfaces\",\n description:\n \"External integration surfaces exposed by Decionis Protocol for Webex and enterprise adapters.\",\n mimeType: \"application/json\",\n },\n {\n uri: \"decionis://marketplaces/targets\",\n name: \"marketplace_targets\",\n title: \"Marketplace Targets\",\n description: \"List of marketplace targets captured by Decionis Protocol.\",\n mimeType: \"application/json\",\n },\n {\n uri: \"decionis://marketplaces/readiness\",\n name: \"marketplace_readiness\",\n title: \"Marketplace Readiness\",\n description: \"Readiness and launch state for protocol marketplace surfaces.\",\n mimeType: \"application/json\",\n },\n {\n uri: \"decionis://verticals/packs\",\n name: \"vertical_packs\",\n title: \"Vertical Packs\",\n description: \"Available vertical packs and workflow overlays exposed by Decionis Protocol.\",\n mimeType: \"application/json\",\n },\n {\n uri: \"decionis://connectors/registry\",\n name: \"connector_registry\",\n title: \"Decionis Connector Registry\",\n description:\n \"Every Decionis connector with availability status, install channels, governed actions, and verification evidence — the same registry that generates decionis.com/integrations.\",\n mimeType: \"application/json\",\n },\n {\n uri: \"decionis://protocol/webex-mcp-registration\",\n name: \"webex_mcp_registration\",\n title: \"Webex MCP Registration\",\n description:\n \"Exact fields to use when registering Decionis Protocol as a Webex Agentic App.\",\n mimeType: \"application/json\",\n },\n {\n uri: \"decionis://protocol/webex-agent-intent-contract\",\n name: \"webex_agent_intent_contract\",\n title: \"Webex Agent Intent Contract\",\n description:\n \"Canonical payload contract for governed Webex AI-agent intents routed through Decionis Protocol.\",\n mimeType: \"application/json\",\n },\n {\n uri: \"decionis://protocol/webex-reviewer-scenarios\",\n name: \"webex_reviewer_scenarios\",\n title: \"Webex Reviewer Scenarios\",\n description:\n \"Reviewer-style Webex governance scenarios bound to first-class Decionis workflow packs.\",\n mimeType: \"application/json\",\n },\n ].map((resource) => ({\n ...resource,\n description:\n resource.uri === \"decionis://protocol/overview\"\n ? `${resource.description} Server ${serviceName}@${serviceVersion} at ${publicBaseUrl}.`\n : resource.description,\n }));\n }\n\n static async readResource(\n app: FastifyInstance,\n uri: string,\n options: {\n publicBaseUrl: string;\n serviceName: string;\n authLookup?: ProtocolMcpAuthLookup | null;\n serviceVersion: string;\n },\n ): Promise<McpResourceReadResult> {\n if (uri === \"decionis://protocol/overview\") {\n return {\n mimeType: \"application/json\",\n value: {\n service: options.serviceName,\n version: options.serviceVersion,\n native_mcp: {\n endpoint: `${options.publicBaseUrl}/v1/protocol/mcp`,\n endpoint_aliases: MCP_HTTP_PATHS,\n transport: \"streamable_http\",\n supported_protocol_versions: [...MCP_PROTOCOL_VERSIONS],\n auth: describeMcpAuthConfig(process.env, {\n hasDynamicOrgKeyLookup: Boolean(options.authLookup),\n }),\n },\n protocol_surfaces: {\n health: `${options.publicBaseUrl}/v1/protocol/health`,\n evaluate_decision: `${options.publicBaseUrl}/v1/protocol/evaluate-decision`,\n evaluate_webex_agent_intent: `${options.publicBaseUrl}/v1/protocol/webex/agent-intents/evaluate`,\n shadow_decisioning: `${options.publicBaseUrl}/v1/protocol/shadow/decisioning`,\n dossiers: `${options.publicBaseUrl}/v1/protocol/dossiers/:dossierId?org_id=:org_id`,\n enforcement_rollouts: `${options.publicBaseUrl}/v1/protocol/enforcement/rollouts`,\n marketplaces: `${options.publicBaseUrl}/v1/protocol/marketplaces/targets`,\n },\n },\n };\n }\n\n if (uri === \"decionis://protocol/connection-surfaces\") {\n return {\n mimeType: \"application/json\",\n value: {\n server: {\n endpoint: `${options.publicBaseUrl}/v1/protocol/mcp`,\n transport: \"streamable_http\",\n },\n external_integration_surfaces: [\n {\n name: \"evaluate_decision\",\n use_case: \"Policy encoding and governed execution-time decisioning\",\n route: \"/v1/protocol/evaluate-decision\",\n },\n {\n name: \"evaluate_webex_agent_intent\",\n use_case: \"Canonical Webex AI-agent intent intercept contract for governed execution\",\n route: \"/v1/protocol/webex/agent-intents/evaluate\",\n },\n {\n name: \"decision_dossier_lookup\",\n use_case: \"Retrieve a stored Decision Dossier by org and dossier ID\",\n route: \"/v1/protocol/dossiers/:dossierId?org_id=:org_id\",\n },\n {\n name: \"enforcement_rollouts\",\n use_case: \"Stage or enforce rollout policy for governed execution bands\",\n route: \"/v1/protocol/enforcement/rollouts\",\n },\n {\n name: \"shadow_decisioning\",\n use_case: \"Review-style shadow validation before turning on enforcement\",\n route: \"/v1/protocol/shadow/decisioning\",\n },\n {\n name: \"marketplace_and_vertical_catalog\",\n use_case: \"Discover target surfaces and workflow packs exposed by Decionis\",\n resources: [\n \"decionis://marketplaces/targets\",\n \"decionis://marketplaces/readiness\",\n \"decionis://verticals/packs\",\n ],\n },\n ],\n },\n };\n }\n\n if (uri === \"decionis://protocol/webex-mcp-registration\") {\n return {\n mimeType: \"application/json\",\n value: {\n module: \"MCP\",\n transport_type: \"Streamable HTTP\",\n suggested_name: \"Decionis Protocol MCP\",\n suggested_description:\n \"Deterministic execution-governance server for policy encoding, governed enforcement, and Decision Dossier verification across Webex and external enterprise workflow surfaces.\",\n app_url: `${options.publicBaseUrl}/v1/protocol/mcp`,\n auth: describeMcpAuthConfig(process.env, {\n hasDynamicOrgKeyLookup: Boolean(options.authLookup),\n }),\n control_surfaces: [\n \"Policy encoding\",\n \"Enforcement rollout control\",\n \"Decision Dossier retrieval\",\n \"Marketplace target readiness\",\n \"Vertical pack resolution\",\n ],\n },\n };\n }\n\n if (uri === \"decionis://protocol/webex-agent-intent-contract\") {\n return {\n mimeType: \"application/json\",\n value: {\n route: `${options.publicBaseUrl}/v1/protocol/webex/agent-intents/evaluate`,\n tool_name: \"decionis.evaluate_webex_agent_intent\",\n decision_type: \"WEBEX_AGENT_INTENT_GATE\",\n defaults: {\n channel: \"webex\",\n mode: \"SHADOW\",\n objective_profile: \"risk_conservative\",\n vertical_pack: \"auto_resolve\",\n },\n required_fields: [\n \"org_id\",\n \"room_id\",\n \"intent_type\",\n \"proposed_action\",\n \"system_of_record\",\n ],\n optional_fields: [\n \"message_id\",\n \"person_id\",\n \"person_email\",\n \"agent_id\",\n \"agent_name\",\n \"workspace_id\",\n \"location_id\",\n \"device_id\",\n \"trust_context\",\n \"record_type\",\n \"record_id\",\n \"amount\",\n \"risk_score\",\n \"approval_path\",\n \"vertical_pack\",\n \"workflow_key\",\n \"policy_version\",\n \"context\",\n ],\n execution_state_rules: {\n ALLOW: \"Only returned when the resulting outcome is APPROVE in ENFORCEMENT mode.\",\n HOLD: \"Returned for non-enforcement review stages and reviewer-safe shadow validation.\",\n ESCALATE: \"Returned when policy requires explicit escalation in ENFORCEMENT mode.\",\n DENY: \"Returned when the governed outcome is REJECT.\",\n },\n },\n };\n }\n\n if (uri === \"decionis://protocol/webex-reviewer-scenarios\") {\n return {\n mimeType: \"application/json\",\n value: {\n scenarios: [\n {\n key: \"fund_disbursement\",\n title: \"Fund Disbursement\",\n workflow_key: \"webex_fund_disbursement\",\n vertical_pack: \"webex_fund_disbursement\",\n system_of_record: \"ERP\",\n intent_type: \"FUND_DISBURSEMENT\",\n proposed_action: \"Release approved beneficiary payment from treasury queue.\",\n focus:\n \"Treasury approval, liquidity evidence, and execute-vs-hold gating before money movement.\",\n expected_execution_state: \"ALLOW\",\n expected_outcome: \"APPROVE\",\n },\n {\n key: \"procurement_override\",\n title: \"Procurement Override\",\n workflow_key: \"webex_procurement_override\",\n vertical_pack: \"webex_procurement_override\",\n system_of_record: \"ServiceNow\",\n intent_type: \"PROCUREMENT_OVERRIDE\",\n proposed_action:\n \"Approve a blocked-supplier override for a time-sensitive purchase request.\",\n focus:\n \"Supplier exception governance, accountable approval path, and audit-ready override evidence.\",\n expected_execution_state: \"ALLOW\",\n expected_outcome: \"APPROVE\",\n },\n {\n key: \"sensitive_system_change\",\n title: \"Sensitive System Change\",\n workflow_key: \"webex_sensitive_system_change\",\n vertical_pack: \"webex_sensitive_system_change\",\n system_of_record: \"ITSM\",\n intent_type: \"SENSITIVE_SYSTEM_CHANGE\",\n proposed_action:\n \"Authorize a privileged production configuration change requested through a Webex agent.\",\n focus: \"Blast-radius, rollback, and privileged-change gating before state mutation.\",\n expected_execution_state: \"ESCALATE\",\n expected_outcome: \"ESCALATE\",\n },\n ],\n recommended_sequence: [\n \"initialize\",\n \"tools/list\",\n \"tools/call -> decionis.list_vertical_packs\",\n \"tools/call -> decionis.resolve_vertical_pack\",\n \"resources/read -> decionis://protocol/webex-agent-intent-contract\",\n \"resources/read -> decionis://protocol/webex-reviewer-scenarios\",\n \"tools/call -> decionis.evaluate_webex_agent_intent\",\n \"tools/call -> decionis.get_decision_dossier\",\n \"tools/call -> decionis.get_decision_chain\",\n ],\n },\n };\n }\n\n if (uri === \"decionis://marketplaces/targets\") {\n const response = await invokeProtocolRoute(app, {\n method: \"GET\",\n url: \"/v1/protocol/marketplaces/targets\",\n });\n return { mimeType: \"application/json\", value: response.body };\n }\n\n if (uri === \"decionis://marketplaces/readiness\") {\n const response = await invokeProtocolRoute(app, {\n method: \"GET\",\n url: \"/v1/protocol/marketplaces/readiness\",\n });\n return { mimeType: \"application/json\", value: response.body };\n }\n\n if (uri === \"decionis://verticals/packs\") {\n const response = await invokeProtocolRoute(app, {\n method: \"GET\",\n url: \"/v1/protocol/verticals/packs\",\n });\n return { mimeType: \"application/json\", value: response.body };\n }\n\n if (uri === \"decionis://connectors/registry\") {\n // Inline literal from @decionis/shared/connectors — the same registry\n // that generates the decionis.com surfaces, so an agent reading this\n // resource and a crawler reading /integrations see one truth.\n return {\n mimeType: \"application/json\",\n value: {\n registry: \"decionis-connectors\",\n statuses: {\n production: \"generally available today through a live public channel\",\n installable: \"customer-deployable today outside public marketplaces\",\n validated:\n \"built and verified (see each connector's verification); downloadable when a package is listed\",\n planned: \"roadmap; never carries install channels\",\n },\n connectors: CONNECTOR_REGISTRY,\n human_catalogue: \"https://decionis.com/integrations\",\n },\n };\n }\n\n const parsed = new URL(uri);\n if (parsed.protocol !== \"decionis:\") {\n throw new Error(`Unsupported resource URI '${uri}'`);\n }\n\n if (parsed.hostname === \"connectors\") {\n const slug = decodeURIComponent(parsed.pathname.replace(/^\\//, \"\"));\n const connector = getConnector(slug);\n if (!connector) {\n throw new Error(`Unknown connector '${slug}'`);\n }\n return { mimeType: \"application/json\", value: connector };\n }\n\n if (parsed.hostname === \"marketplaces\" && parsed.pathname.startsWith(\"/targets/\")) {\n const target = decodeURIComponent(parsed.pathname.replace(\"/targets/\", \"\"));\n const response = await invokeProtocolRoute(app, {\n method: \"GET\",\n url: `/v1/protocol/marketplaces/targets/${encodeURIComponent(target)}`,\n });\n return { mimeType: \"application/json\", value: response.body };\n }\n\n if (parsed.hostname === \"dossiers\") {\n const [orgId, dossierId] = parsed.pathname\n .split(\"/\")\n .filter(Boolean)\n .map((segment) => decodeURIComponent(segment));\n if (!orgId || !dossierId) {\n throw new Error(\"Dossier resource URI must include org_id and dossier_id\");\n }\n const response = await invokeProtocolRoute(app, {\n method: \"GET\",\n url: `/v1/protocol/dossiers/${encodeURIComponent(dossierId)}?org_id=${encodeURIComponent(orgId)}`,\n });\n return { mimeType: \"application/json\", value: response.body };\n }\n\n if (parsed.hostname === \"enforcement-rollouts\") {\n const [orgId] = parsed.pathname\n .split(\"/\")\n .filter(Boolean)\n .map((segment) => decodeURIComponent(segment));\n if (!orgId) {\n throw new Error(\"Enforcement rollout resource URI must include org_id\");\n }\n const response = await invokeProtocolRoute(app, {\n method: \"GET\",\n url: `/v1/protocol/enforcement/rollouts?org_id=${encodeURIComponent(orgId)}`,\n });\n return { mimeType: \"application/json\", value: response.body };\n }\n\n throw new Error(`Unknown resource URI '${uri}'`);\n }\n}\n\n/** Functional alias for {@link McpResources.buildStaticResources}. */\nexport function buildStaticResources(\n publicBaseUrl: string,\n serviceName: string,\n serviceVersion: string,\n): McpStaticResource[] {\n return McpResources.buildStaticResources(publicBaseUrl, serviceName, serviceVersion);\n}\n\n/** Functional alias for {@link McpResources.readResource}. */\nexport function readResource(\n app: FastifyInstance,\n uri: string,\n options: {\n publicBaseUrl: string;\n serviceName: string;\n authLookup?: ProtocolMcpAuthLookup | null;\n serviceVersion: string;\n },\n): Promise<McpResourceReadResult> {\n return McpResources.readResource(app, uri, options);\n}\n","import type { McpPromptDefinition } from \"./McpContracts.js\";\nimport { asString, toPrettyText } from \"./McpSupport.js\";\n\n/** MCP prompt catalog for Webex onboarding and governance review flows. */\nexport class McpPrompts {\n static buildPrompts(\n publicBaseUrl: string,\n authDescription: Record<string, unknown>,\n ): McpPromptDefinition[] {\n return [\n {\n name: \"webex_mcp_onboarding\",\n title: \"Webex MCP Onboarding\",\n description:\n \"Generate the exact Webex Agentic App registration instructions for the Decionis Protocol MCP surface.\",\n arguments: [\n {\n name: \"auth_type\",\n description:\n \"Preferred Webex auth type to register, for example ApiKey or CustomHeaderAuth.\",\n },\n ],\n handler(args) {\n const authType = asString(args.auth_type) ?? \"ApiKey\";\n return [\n \"Register Decionis Protocol as a Webex Agentic App with these fields:\",\n `- Module: MCP`,\n `- Transport Type: Streamable HTTP`,\n `- Name: Decionis Protocol MCP`,\n `- Description: Deterministic execution-governance server for policy encoding, governed enforcement, and Decision Dossier verification across Webex and external enterprise workflow surfaces.`,\n `- App URL: ${publicBaseUrl}/v1/protocol/mcp`,\n `- Auth Type: ${authType}`,\n \"\",\n \"After registration, validate these MCP actions in order:\",\n \"1. initialize\",\n \"2. tools/list\",\n \"3. tools/call -> decionis.evaluate_webex_agent_intent\",\n \"4. tools/call -> decionis.get_decision_dossier\",\n \"5. resources/read -> decionis://protocol/webex-agent-intent-contract\",\n \"\",\n `Current server auth posture: ${toPrettyText(authDescription)}`,\n ].join(\"\\n\");\n },\n },\n {\n name: \"webex_agent_intent_governance\",\n title: \"Webex Agent Intent Governance\",\n description:\n \"Generate a reviewer-safe Decionis Webex agent-intent call sequence for high-risk AI actions.\",\n arguments: [\n {\n name: \"intent_type\",\n description: \"Intent type such as FUND_DISBURSEMENT.\",\n required: true,\n },\n {\n name: \"proposed_action\",\n description: \"Action the Webex AI agent wants to execute.\",\n required: true,\n },\n {\n name: \"system_of_record\",\n description: \"Target system of record such as ERP or ServiceNow.\",\n required: true,\n },\n { name: \"workflow_key\", description: \"Optional workflow key for the governed surface.\" },\n ],\n handler(args) {\n const intentType = asString(args.intent_type) ?? \"<intent_type>\";\n const proposedAction = asString(args.proposed_action) ?? \"<proposed_action>\";\n const systemOfRecord = asString(args.system_of_record) ?? \"<system_of_record>\";\n const workflowKey = asString(args.workflow_key) ?? \"not specified\";\n return [\n \"Use the canonical Webex agent-intent contract for governed execution:\",\n `- intent_type: ${intentType}`,\n `- proposed_action: ${proposedAction}`,\n `- system_of_record: ${systemOfRecord}`,\n `- workflow_key: ${workflowKey}`,\n \"\",\n \"Sequence:\",\n \"1. Read decionis://protocol/webex-agent-intent-contract for the exact payload shape.\",\n \"2. Call decionis.evaluate_webex_agent_intent with the Webex room, actor, and risk context.\",\n \"3. Treat execution_state=ALLOW as the only execute path.\",\n \"4. For HOLD, ESCALATE, or DENY, keep the action out of execution and inspect the resulting Decision Dossier.\",\n ].join(\"\\n\");\n },\n },\n {\n name: \"webex_reviewer_run\",\n title: \"Webex Reviewer Run\",\n description:\n \"Produce the reviewer-style Decionis MCP validation sequence for the three first-class Webex governance scenarios.\",\n arguments: [],\n handler() {\n return [\n \"Reviewer-style MCP run for Webex Agentic App validation:\",\n \"\",\n \"1. Read decionis://protocol/webex-reviewer-scenarios.\",\n \"2. Call decionis.list_vertical_packs and confirm the three Webex workflow packs are exposed.\",\n \"3. For each scenario, call decionis.resolve_vertical_pack with org_id and workflow_key.\",\n \"4. Call decionis.evaluate_webex_agent_intent with the matching workflow_key and vertical_pack.\",\n \"5. Treat execution_state=ALLOW as the only execute path.\",\n \"6. Retrieve each resulting Decision Dossier with decionis.get_decision_dossier.\",\n \"\",\n \"Scenarios:\",\n \"- webex_fund_disbursement\",\n \"- webex_procurement_override\",\n \"- webex_sensitive_system_change\",\n ].join(\"\\n\");\n },\n },\n {\n name: \"policy_encoding\",\n title: \"Policy Encoding\",\n description:\n \"Turn an operator request into a Decionis policy-encoding and evaluation sequence.\",\n arguments: [\n {\n name: \"intent\",\n description: \"Natural-language operator intent to encode under governance.\",\n required: true,\n },\n {\n name: \"vertical_pack\",\n description: \"Optional vertical pack to pin before evaluation.\",\n },\n { name: \"workflow_key\", description: \"Optional workflow key for the target surface.\" },\n ],\n handler(args) {\n const intent = asString(args.intent) ?? \"<describe the operator intent>\";\n const verticalPack = asString(args.vertical_pack) ?? \"auto-resolve\";\n const workflowKey = asString(args.workflow_key) ?? \"not specified\";\n return [\n \"Use Decionis Protocol to encode and govern this intent:\",\n intent,\n \"\",\n `Recommended vertical pack: ${verticalPack}`,\n `Workflow key: ${workflowKey}`,\n \"\",\n \"Sequence:\",\n \"1. If needed, resolve the org vertical pack with decionis.resolve_vertical_pack.\",\n \"2. Evaluate the decision with decionis.evaluate_decision.\",\n \"3. If rollout configuration is needed before enforcement, use decionis.upsert_enforcement_rollout.\",\n \"4. Retrieve the dossier with decionis.get_decision_dossier for final verification and downstream delivery.\",\n ].join(\"\\n\");\n },\n },\n {\n name: \"governance_enforcement_review\",\n title: \"Governance Enforcement Review\",\n description:\n \"Review how to move a flow from shadow to governed enforcement without losing auditability.\",\n arguments: [\n { name: \"org_id\", description: \"Org ID whose rollout is being staged.\", required: true },\n { name: \"decision_band\", description: \"Decision band being controlled.\" },\n { name: \"transaction_type\", description: \"Transaction or route type under rollout.\" },\n ],\n handler(args) {\n const orgId = asString(args.org_id) ?? \"<org_id>\";\n const decisionBand = asString(args.decision_band) ?? \"<decision_band>\";\n const transactionType = asString(args.transaction_type) ?? \"<transaction_type>\";\n return [\n `Review governance rollout for org ${orgId}.`,\n `Decision band: ${decisionBand}`,\n `Transaction type: ${transactionType}`,\n \"\",\n \"Recommended sequence:\",\n \"1. Use decionis.list_enforcement_rollouts to inspect current rollout state.\",\n \"2. Use decionis.upsert_enforcement_rollout to stage SHADOW, PARALLEL, or ENFORCEMENT mode explicitly.\",\n \"3. Use decionis.run_shadow_decisioning for reviewer-style dry runs where needed.\",\n \"4. Use decionis.evaluate_decision after rollout changes and verify the resulting Decision Dossier.\",\n ].join(\"\\n\");\n },\n },\n {\n name: \"decision_dossier_review\",\n title: \"Decision Dossier Review\",\n description:\n \"Guide an agent through verifying a Decision Dossier, integrity chain, and rollout context.\",\n arguments: [\n { name: \"org_id\", description: \"Org ID that owns the dossier.\", required: true },\n { name: \"dossier_id\", description: \"Dossier ID to verify.\", required: true },\n ],\n handler(args) {\n const orgId = asString(args.org_id) ?? \"<org_id>\";\n const dossierId = asString(args.dossier_id) ?? \"<dossier_id>\";\n return [\n `Retrieve and review Decision Dossier ${dossierId} for org ${orgId}.`,\n \"\",\n \"Checklist:\",\n \"1. Call decionis.get_decision_dossier.\",\n \"2. Verify outcome, confidence, governance metrics, and rollout metadata.\",\n \"3. Verify integrity fields such as payload_sha256, decision_resolution_id, ledger_entry_id, and ledger_entry_hash.\",\n \"4. If the dossier came from a staged rollout, compare it with decionis.list_enforcement_rollouts for the org.\",\n ].join(\"\\n\");\n },\n },\n ];\n }\n}\n\n/** Functional alias for {@link McpPrompts.buildPrompts}. */\nexport function buildPrompts(\n publicBaseUrl: string,\n authDescription: Record<string, unknown>,\n): McpPromptDefinition[] {\n return McpPrompts.buildPrompts(publicBaseUrl, authDescription);\n}\n","import type { FastifyInstance } from \"fastify\";\nimport type { McpToolDefinition, McpToolInvocationResult } from \"./McpContracts.js\";\nimport {\n asRecord,\n asString,\n asStructuredContent,\n invokeProtocolRoute,\n toPrettyText,\n withQuery,\n} from \"./McpSupport.js\";\n\n/** MCP tool catalog, lookup, and invocation-result shaping. */\nexport class McpTools {\n /** Map a protocol outcome to an agentic decision + ACP checkout-session status. */\n static mapAgenticOutcomeToAcpStatus(outcome: string | null): {\n decision: \"allow\" | \"block\" | \"escalate\";\n acp_status: \"ready_for_payment\" | \"not_ready_for_payment\" | \"requires_escalation\";\n } {\n switch (outcome) {\n case \"APPROVE\":\n return { decision: \"allow\", acp_status: \"ready_for_payment\" };\n case \"ESCALATE\":\n case \"REVIEW\":\n return { decision: \"escalate\", acp_status: \"requires_escalation\" };\n default:\n return { decision: \"block\", acp_status: \"not_ready_for_payment\" };\n }\n }\n\n /** Best-effort order amount from an ACP session or AP2 cart mandate (see api deriveAmount). */\n static deriveAgenticAmount(\n session: Record<string, unknown> | null,\n mandates: Record<string, unknown> | null,\n ): number | undefined {\n if (session) {\n if (typeof session.total_amount === \"number\") return session.total_amount;\n const items = Array.isArray(session.line_items) ? session.line_items : [];\n let sum = 0;\n let sawValue = false;\n for (const raw of items) {\n const item = asRecord(raw);\n if (!item) continue;\n if (typeof item.total_amount === \"number\") {\n sum += item.total_amount;\n sawValue = true;\n } else if (typeof item.base_amount === \"number\") {\n sum += item.base_amount * (typeof item.quantity === \"number\" ? item.quantity : 1);\n sawValue = true;\n }\n }\n if (sawValue) return sum;\n }\n const cart = asRecord(mandates?.cart);\n return cart && typeof cart.amount === \"number\" ? cart.amount : undefined;\n }\n\n static buildTools(app: FastifyInstance): McpToolDefinition[] {\n const tools = [\n {\n name: \"decionis.evaluate_decision\",\n aliases: [\"evaluate_decision\"],\n title: \"Evaluate Decision\",\n description: \"Evaluate a governed decision and issue a Decision Dossier.\",\n inputSchema: {\n type: \"object\",\n required: [\"org_id\", \"decision_type\"],\n additionalProperties: true,\n properties: {\n org_id: { type: \"string\", description: \"Org UUID.\" },\n decision_type: { type: \"string\", description: \"Decision type to evaluate.\" },\n amount: { type: [\"number\", \"null\"] },\n risk_score: { type: [\"number\", \"null\"] },\n channel: { type: [\"string\", \"null\"] },\n policy_version: { type: \"string\" },\n objective_profile: { type: \"string\" },\n vertical_pack: { type: [\"string\", \"null\"] },\n workflow_key: { type: [\"string\", \"null\"] },\n mode: { type: \"string\", enum: [\"SHADOW\", \"PARALLEL\", \"ENFORCEMENT\"] },\n decision_band: { type: [\"string\", \"null\"] },\n transaction_type: { type: [\"string\", \"null\"] },\n idempotency_key: { type: [\"string\", \"null\"] },\n context: { type: \"object\", additionalProperties: true },\n },\n },\n outputSchema: { type: \"object\", additionalProperties: true },\n async handler(args) {\n const response = await invokeProtocolRoute(app, {\n method: \"POST\",\n url: \"/v1/protocol/evaluate-decision\",\n payload: args,\n });\n if (!response.ok) {\n throw new Error(`Evaluate-decision failed (${response.statusCode})`);\n }\n return response.body;\n },\n },\n {\n name: \"decionis.agentic_checkout_authorize\",\n aliases: [\"agentic_checkout_authorize\"],\n title: \"Authorize Agentic Checkout\",\n description:\n \"Gate an autonomous buying agent's checkout (ACP session or AP2 mandate bundle) and return a governed verdict mapped to ACP statuses (ready_for_payment / not_ready_for_payment / requires_escalation). On ALLOW, redeem execution authority via the Decionis API endpoint POST /v1/agentic/checkout/authorize (Execution Grant issuance is API-tier).\",\n inputSchema: {\n type: \"object\",\n required: [\"org_id\"],\n additionalProperties: true,\n properties: {\n org_id: { type: \"string\", description: \"Org UUID.\" },\n protocol: { type: \"string\", enum: [\"acp\", \"ap2\"], description: \"Agentic protocol.\" },\n checkout_session: {\n type: \"object\",\n additionalProperties: true,\n description: \"ACP checkout session (id, total_amount, line_items, payment).\",\n },\n mandates: {\n type: \"object\",\n additionalProperties: true,\n description: \"AP2 mandate bundle (intent, cart, payment).\",\n },\n agent: {\n type: \"object\",\n additionalProperties: true,\n description: \"Agent identity { id, human_present }.\",\n },\n context: { type: \"object\", additionalProperties: true },\n idempotency_key: { type: [\"string\", \"null\"] },\n },\n },\n outputSchema: { type: \"object\", additionalProperties: true },\n async handler(args) {\n const protocol = asString(args.protocol) === \"ap2\" ? \"ap2\" : \"acp\";\n const session = asRecord(args.checkout_session);\n const mandates = asRecord(args.mandates);\n const agent = asRecord(args.agent);\n const amount = deriveAgenticAmount(session, mandates);\n const payload: Record<string, unknown> = {\n org_id: args.org_id,\n decision_type: \"agentic_checkout\",\n ...(amount !== undefined ? { amount } : {}),\n channel: \"agentic\",\n transaction_type: protocol,\n ...(asString(args.idempotency_key)\n ? { idempotency_key: asString(args.idempotency_key) }\n : {}),\n context: {\n ...(asRecord(args.context) ?? {}),\n transaction_source: \"agentic\",\n source_protocol: protocol,\n source_surface: \"mcp\",\n agent_id: agent ? (asString(agent.id) ?? null) : null,\n human_present: agent?.human_present === true,\n checkout_session_id: session ? (asString(session.id) ?? null) : null,\n },\n };\n const response = await invokeProtocolRoute(app, {\n method: \"POST\",\n url: \"/v1/protocol/evaluate-decision\",\n payload,\n });\n if (!response.ok) {\n throw new Error(`Agentic checkout authorize failed (${response.statusCode})`);\n }\n const body = asRecord(response.body) ?? {};\n const mapped = mapAgenticOutcomeToAcpStatus(asString(body.outcome) ?? null);\n return {\n ...body,\n decision: mapped.decision,\n acp_status: mapped.acp_status,\n protocol,\n // On ALLOW, redeem a single-use, cart-bound Execution Grant via the API.\n grant_endpoint: mapped.decision === \"allow\" ? \"/v1/agentic/checkout/authorize\" : null,\n };\n },\n },\n {\n name: \"decionis.evaluate_webex_agent_intent\",\n aliases: [\"evaluate_webex_agent_intent\"],\n title: \"Evaluate Webex Agent Intent\",\n description:\n \"Evaluate a canonical Webex AI-agent intent and return a governed execution state plus Decision Dossier.\",\n inputSchema: {\n type: \"object\",\n required: [\"org_id\", \"room_id\", \"intent_type\", \"proposed_action\", \"system_of_record\"],\n additionalProperties: true,\n properties: {\n org_id: { type: \"string\", description: \"Org UUID.\" },\n room_id: { type: \"string\", description: \"Target Webex Space ID.\" },\n message_id: { type: [\"string\", \"null\"] },\n person_id: { type: [\"string\", \"null\"] },\n person_email: { type: [\"string\", \"null\"] },\n agent_id: { type: [\"string\", \"null\"] },\n agent_name: { type: [\"string\", \"null\"] },\n workspace_id: { type: [\"string\", \"null\"] },\n location_id: { type: [\"string\", \"null\"] },\n device_id: { type: [\"string\", \"null\"] },\n trust_context: {\n type: \"object\",\n additionalProperties: true,\n description:\n \"Optional Webex trust evidence envelope. Supports room/operator/workspace/location/device metadata and verification states.\",\n properties: {\n room: {\n type: \"object\",\n additionalProperties: true,\n properties: {\n room_name: { type: [\"string\", \"null\"] },\n room_type: { type: [\"string\", \"null\"] },\n },\n },\n operator: {\n type: \"object\",\n additionalProperties: true,\n properties: {\n operator_name: { type: [\"string\", \"null\"] },\n verified: { type: [\"boolean\", \"null\"] },\n verification_source: { type: [\"string\", \"null\"] },\n },\n },\n workspace: {\n type: \"object\",\n additionalProperties: true,\n properties: {\n workspace_name: { type: [\"string\", \"null\"] },\n verified: { type: [\"boolean\", \"null\"] },\n },\n },\n location: {\n type: \"object\",\n additionalProperties: true,\n properties: {\n location_name: { type: [\"string\", \"null\"] },\n verified: { type: [\"boolean\", \"null\"] },\n },\n },\n device: {\n type: \"object\",\n additionalProperties: true,\n properties: {\n device_name: { type: [\"string\", \"null\"] },\n platform: { type: [\"string\", \"null\"] },\n device_type: { type: [\"string\", \"null\"] },\n roomos: { type: [\"boolean\", \"null\"] },\n attested: { type: [\"boolean\", \"null\"] },\n },\n },\n },\n },\n intent_type: {\n type: \"string\",\n description: \"High-risk intent class from the Webex agent.\",\n },\n proposed_action: {\n type: \"string\",\n description: \"Requested action before governed execution.\",\n },\n system_of_record: { type: \"string\", description: \"Target system of record.\" },\n record_type: { type: [\"string\", \"null\"] },\n record_id: { type: [\"string\", \"null\"] },\n amount: { type: [\"number\", \"null\"] },\n risk_score: { type: [\"number\", \"null\"] },\n objective_profile: { type: [\"string\", \"null\"] },\n policy_version: { type: [\"string\", \"null\"] },\n vertical_pack: { type: [\"string\", \"null\"] },\n workflow_key: { type: [\"string\", \"null\"] },\n mode: { type: \"string\", enum: [\"SHADOW\", \"PARALLEL\", \"ENFORCEMENT\"] },\n approval_path: {\n type: \"array\",\n items: { type: \"string\" },\n },\n idempotency_key: { type: [\"string\", \"null\"] },\n context: { type: \"object\", additionalProperties: true },\n },\n },\n outputSchema: { type: \"object\", additionalProperties: true },\n async handler(args) {\n const response = await invokeProtocolRoute(app, {\n method: \"POST\",\n url: \"/v1/protocol/webex/agent-intents/evaluate\",\n payload: args,\n });\n if (!response.ok) {\n throw new Error(`Webex agent intent evaluation failed (${response.statusCode})`);\n }\n return response.body;\n },\n },\n {\n name: \"decionis.get_decision_dossier\",\n aliases: [\"get_decision_dossier\"],\n title: \"Get Decision Dossier\",\n description: \"Retrieve a stored Decision Dossier by org and dossier ID.\",\n inputSchema: {\n type: \"object\",\n required: [\"org_id\", \"dossier_id\"],\n additionalProperties: false,\n properties: {\n org_id: { type: \"string\", description: \"Org UUID.\" },\n dossier_id: { type: \"string\", description: \"Dossier UUID.\" },\n },\n },\n outputSchema: { type: \"object\", additionalProperties: true },\n async handler(args) {\n const orgId = asString(args.org_id);\n const dossierId = asString(args.dossier_id);\n if (!orgId || !dossierId) {\n throw new Error(\"org_id and dossier_id are required\");\n }\n const response = await invokeProtocolRoute(app, {\n method: \"GET\",\n url: `/v1/protocol/dossiers/${encodeURIComponent(dossierId)}?org_id=${encodeURIComponent(orgId)}`,\n });\n if (!response.ok) {\n throw new Error(`Decision dossier lookup failed (${response.statusCode})`);\n }\n return response.body;\n },\n },\n {\n name: \"decionis.get_decision_chain\",\n aliases: [\"get_decision_chain\"],\n title: \"Get Decision Chain\",\n description:\n \"Read the workflow lineage for linked Decionis decisions: the chain summary of evaluations, their outcomes, and the dossiers each sealed. The read-only status view for a multi-step workflow an agent is participating in.\",\n inputSchema: {\n type: \"object\",\n required: [\"org_id\", \"chain_id\"],\n additionalProperties: false,\n properties: {\n org_id: { type: \"string\", description: \"Org UUID.\" },\n chain_id: { type: \"string\", description: \"Decision chain UUID.\" },\n },\n },\n outputSchema: { type: \"object\", additionalProperties: true },\n async handler(args) {\n const orgId = asString(args.org_id);\n const chainId = asString(args.chain_id);\n if (!orgId || !chainId) {\n throw new Error(\"org_id and chain_id are required\");\n }\n const response = await invokeProtocolRoute(app, {\n method: \"GET\",\n url: `/v1/protocol/decision-chains/${encodeURIComponent(chainId)}?org_id=${encodeURIComponent(orgId)}`,\n });\n if (!response.ok) {\n throw new Error(`Decision chain lookup failed (${response.statusCode})`);\n }\n return response.body;\n },\n },\n {\n name: \"decionis.list_enforcement_rollouts\",\n aliases: [\"list_enforcement_rollouts\"],\n title: \"List Enforcement Rollouts\",\n description:\n \"List enforcement rollout controls for an org, optionally narrowed to one band and transaction type.\",\n inputSchema: {\n type: \"object\",\n required: [\"org_id\"],\n additionalProperties: false,\n properties: {\n org_id: { type: \"string\" },\n decision_band: { type: \"string\" },\n transaction_type: { type: \"string\" },\n },\n },\n async handler(args) {\n const orgId = asString(args.org_id);\n if (!orgId) throw new Error(\"org_id is required\");\n const url = withQuery(\"/v1/protocol/enforcement/rollouts\", {\n org_id: orgId,\n decision_band: asString(args.decision_band),\n transaction_type: asString(args.transaction_type),\n });\n const response = await invokeProtocolRoute(app, { method: \"GET\", url });\n if (!response.ok) {\n throw new Error(`Enforcement rollout lookup failed (${response.statusCode})`);\n }\n return response.body;\n },\n },\n {\n name: \"decionis.upsert_enforcement_rollout\",\n aliases: [\"upsert_enforcement_rollout\"],\n title: \"Upsert Enforcement Rollout\",\n description:\n \"Stage or enforce rollout policy for a governed decision band and transaction type.\",\n inputSchema: {\n type: \"object\",\n required: [\"org_id\", \"decision_band\", \"transaction_type\", \"mode\"],\n additionalProperties: false,\n properties: {\n org_id: { type: \"string\" },\n decision_band: { type: \"string\" },\n transaction_type: { type: \"string\" },\n mode: { type: \"string\", enum: [\"SHADOW\", \"PARALLEL\", \"ENFORCEMENT\"] },\n feature_flag: { type: \"string\" },\n fallback_to_legacy: { type: \"boolean\" },\n reconciliation_required: { type: \"boolean\" },\n notes: { type: \"string\" },\n },\n },\n async handler(args) {\n const response = await invokeProtocolRoute(app, {\n method: \"PUT\",\n url: \"/v1/protocol/enforcement/rollouts\",\n payload: args,\n });\n if (!response.ok) {\n throw new Error(`Enforcement rollout update failed (${response.statusCode})`);\n }\n return response.body;\n },\n },\n {\n name: \"decionis.list_marketplace_targets\",\n aliases: [\"list_marketplace_targets\"],\n title: \"List Marketplace Targets\",\n description: \"List marketplace targets captured by Decionis Protocol.\",\n inputSchema: {\n type: \"object\",\n additionalProperties: false,\n properties: {},\n },\n async handler() {\n const response = await invokeProtocolRoute(app, {\n method: \"GET\",\n url: \"/v1/protocol/marketplaces/targets\",\n });\n if (!response.ok) {\n throw new Error(`Marketplace target lookup failed (${response.statusCode})`);\n }\n return response.body;\n },\n },\n {\n name: \"decionis.get_marketplace_target\",\n aliases: [\"get_marketplace_target\"],\n title: \"Get Marketplace Target\",\n description: \"Retrieve one marketplace target profile and readiness bundle.\",\n inputSchema: {\n type: \"object\",\n required: [\"target\"],\n additionalProperties: false,\n properties: {\n target: { type: \"string\" },\n },\n },\n async handler(args) {\n const target = asString(args.target);\n if (!target) throw new Error(\"target is required\");\n const response = await invokeProtocolRoute(app, {\n method: \"GET\",\n url: `/v1/protocol/marketplaces/targets/${encodeURIComponent(target)}`,\n });\n if (!response.ok) {\n throw new Error(`Marketplace target detail lookup failed (${response.statusCode})`);\n }\n return response.body;\n },\n },\n {\n name: \"decionis.list_marketplace_readiness\",\n aliases: [\"list_marketplace_readiness\"],\n title: \"List Marketplace Readiness\",\n description: \"List protocol readiness states across marketplace targets.\",\n inputSchema: {\n type: \"object\",\n additionalProperties: false,\n properties: {\n target: { type: \"string\" },\n },\n },\n async handler(args) {\n const url = withQuery(\"/v1/protocol/marketplaces/readiness\", {\n target: asString(args.target),\n });\n const response = await invokeProtocolRoute(app, { method: \"GET\", url });\n if (!response.ok) {\n throw new Error(`Marketplace readiness lookup failed (${response.statusCode})`);\n }\n return response.body;\n },\n },\n {\n name: \"decionis.list_vertical_packs\",\n aliases: [\"list_vertical_packs\"],\n title: \"List Vertical Packs\",\n description:\n \"List the vertical packs and workflow overlays currently exposed by Decionis Protocol.\",\n inputSchema: {\n type: \"object\",\n additionalProperties: false,\n properties: {},\n },\n async handler() {\n const response = await invokeProtocolRoute(app, {\n method: \"GET\",\n url: \"/v1/protocol/verticals/packs\",\n });\n if (!response.ok) {\n throw new Error(`Vertical pack lookup failed (${response.statusCode})`);\n }\n return response.body;\n },\n },\n {\n name: \"decionis.resolve_vertical_pack\",\n aliases: [\"resolve_vertical_pack\"],\n title: \"Resolve Vertical Pack\",\n description: \"Resolve the effective vertical pack for an org and optional workflow key.\",\n inputSchema: {\n type: \"object\",\n required: [\"org_id\"],\n additionalProperties: false,\n properties: {\n org_id: { type: \"string\" },\n pack_key: { type: \"string\" },\n workflow_key: { type: \"string\" },\n },\n },\n async handler(args) {\n const orgId = asString(args.org_id);\n if (!orgId) throw new Error(\"org_id is required\");\n const url = withQuery(\"/v1/protocol/verticals/resolve\", {\n org_id: orgId,\n pack_key: asString(args.pack_key),\n workflow_key: asString(args.workflow_key),\n });\n const response = await invokeProtocolRoute(app, { method: \"GET\", url });\n if (!response.ok) {\n throw new Error(`Vertical pack resolution failed (${response.statusCode})`);\n }\n return response.body;\n },\n },\n {\n name: \"decionis.run_shadow_decisioning\",\n aliases: [\"run_shadow_decisioning\"],\n title: \"Run Shadow Decisioning\",\n description:\n \"Run reviewer-style shadow decisioning before switching a flow to live enforcement.\",\n inputSchema: {\n type: \"object\",\n required: [\"request_id\", \"org_id\", \"intent\"],\n additionalProperties: true,\n properties: {\n request_id: { type: \"string\" },\n org_id: { type: \"string\" },\n cycle_id: { type: \"string\" },\n engine_key: { type: \"string\" },\n engine_chain: { type: \"array\", items: { type: \"string\" } },\n vertical_pack: { type: \"string\" },\n workflow_key: { type: \"string\" },\n intent: { type: \"string\" },\n intake: { type: \"object\", additionalProperties: true },\n attachments: { type: \"array\", items: { type: \"object\", additionalProperties: true } },\n },\n },\n async handler(args) {\n const response = await invokeProtocolRoute(app, {\n method: \"POST\",\n url: \"/v1/protocol/shadow/decisioning\",\n payload: args,\n });\n if (!response.ok) {\n throw new Error(`Shadow decisioning failed (${response.statusCode})`);\n }\n return response.body;\n },\n },\n ] satisfies Array<Omit<McpToolDefinition, \"annotations\">>;\n\n const readOnlyTools = new Set([\n \"decionis.get_decision_dossier\",\n \"decionis.get_decision_chain\",\n \"decionis.list_enforcement_rollouts\",\n \"decionis.list_marketplace_targets\",\n \"decionis.get_marketplace_target\",\n \"decionis.list_marketplace_readiness\",\n \"decionis.list_vertical_packs\",\n \"decionis.resolve_vertical_pack\",\n ]);\n const idempotentWriteTools = new Set([\"decionis.upsert_enforcement_rollout\"]);\n\n return tools.map((tool) => {\n const readOnly = readOnlyTools.has(tool.name);\n return {\n ...tool,\n annotations: {\n readOnlyHint: readOnly,\n destructiveHint: false,\n idempotentHint: readOnly || idempotentWriteTools.has(tool.name),\n openWorldHint: false,\n },\n };\n });\n }\n\n static buildTextToolResult(\n value: unknown,\n options?: { isError?: boolean },\n ): McpToolInvocationResult {\n const text = toPrettyText(value);\n return {\n content: [{ type: \"text\", text }],\n structuredContent: asStructuredContent(value),\n ...(options?.isError ? { isError: true } : {}),\n };\n }\n\n static async handleToolCall(\n tool: McpToolDefinition,\n args: Record<string, unknown>,\n ): Promise<McpToolInvocationResult> {\n try {\n const value = await tool.handler(args);\n return buildTextToolResult(value);\n } catch (err) {\n const message = err instanceof Error ? err.message : \"Tool call failed\";\n return buildTextToolResult(\n {\n error: message,\n tool_name: tool.name,\n },\n { isError: true },\n );\n }\n }\n\n static findTool(tools: McpToolDefinition[], name: string): McpToolDefinition | null {\n const normalized = name.trim();\n for (const tool of tools) {\n if (tool.name === normalized) return tool;\n if (tool.aliases?.includes(normalized)) return tool;\n }\n return null;\n }\n}\n\n/** Functional alias for {@link McpTools.mapAgenticOutcomeToAcpStatus}. */\nexport function mapAgenticOutcomeToAcpStatus(outcome: string | null): {\n decision: \"allow\" | \"block\" | \"escalate\";\n acp_status: \"ready_for_payment\" | \"not_ready_for_payment\" | \"requires_escalation\";\n} {\n return McpTools.mapAgenticOutcomeToAcpStatus(outcome);\n}\n\n/** Functional alias for {@link McpTools.deriveAgenticAmount}. */\nexport function deriveAgenticAmount(\n session: Record<string, unknown> | null,\n mandates: Record<string, unknown> | null,\n): number | undefined {\n return McpTools.deriveAgenticAmount(session, mandates);\n}\n\n/** Functional alias for {@link McpTools.buildTools}. */\nexport function buildTools(app: FastifyInstance): McpToolDefinition[] {\n return McpTools.buildTools(app);\n}\n\n/** Functional alias for {@link McpTools.buildTextToolResult}. */\nexport function buildTextToolResult(\n value: unknown,\n options?: { isError?: boolean },\n): McpToolInvocationResult {\n return McpTools.buildTextToolResult(value, options);\n}\n\n/** Functional alias for {@link McpTools.handleToolCall}. */\nexport function handleToolCall(\n tool: McpToolDefinition,\n args: Record<string, unknown>,\n): Promise<McpToolInvocationResult> {\n return McpTools.handleToolCall(tool, args);\n}\n\n/** Functional alias for {@link McpTools.findTool}. */\nexport function findTool(tools: McpToolDefinition[], name: string): McpToolDefinition | null {\n return McpTools.findTool(tools, name);\n}\n","import { createHash, createHmac, randomUUID, timingSafeEqual } from \"node:crypto\";\nimport type {\n AuthorityMode,\n AuthorityRequest,\n ExecutionLedgerEntry,\n PolicyLimits,\n} from \"./ExecutionGatingContracts.js\";\n\nexport const DEFAULT_POLICY_LIMITS: PolicyLimits = {\n max_single_payment_usd: 2,\n max_spend_per_minute_usd: 10,\n max_transactions_per_minute: 20,\n max_recursive_calls_per_task: 5,\n};\n\nexport const POLICY_SNAPSHOT = {\n policy_id: \"autonomous-spend-policy\",\n version: \"0.1.0\",\n hash: \"sha256:6c58f1b36fb5c7a54a7c6d54dbcf967dfbe091fb9d3ffbb2d51d8ce49d8f9a9f\",\n limits: DEFAULT_POLICY_LIMITS,\n circuit_breakers: {\n block_recursive_loop: true,\n replay_protection: true,\n },\n};\n\nexport function asRecord(value: unknown): Record<string, unknown> {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return {};\n return value as Record<string, unknown>;\n}\n\nexport function asString(value: unknown): string | null {\n return typeof value === \"string\" && value.trim() ? value.trim() : null;\n}\n\nexport function asNumber(value: unknown): number | null {\n if (typeof value === \"number\" && Number.isFinite(value)) return value;\n if (typeof value === \"string\" && value.trim()) {\n const parsed = Number.parseFloat(value);\n return Number.isFinite(parsed) ? parsed : null;\n }\n return null;\n}\n\nexport function canonicalize(value: unknown): unknown {\n if (Array.isArray(value)) return value.map((item) => canonicalize(item));\n if (!value || typeof value !== \"object\") return value;\n const input = value as Record<string, unknown>;\n const output: Record<string, unknown> = {};\n for (const key of Object.keys(input).sort()) output[key] = canonicalize(input[key]);\n return output;\n}\n\nexport function stableStringify(value: unknown): string {\n return JSON.stringify(canonicalize(value));\n}\n\nexport function sha256(value: unknown): string {\n return createHash(\"sha256\").update(stableStringify(value), \"utf8\").digest(\"hex\");\n}\n\nexport function base64UrlEncode(value: string): string {\n return Buffer.from(value, \"utf8\").toString(\"base64url\");\n}\n\nexport function base64UrlDecode(value: string): string {\n return Buffer.from(value, \"base64url\").toString(\"utf8\");\n}\n\nexport function sign(value: string, secret: string): string {\n return createHmac(\"sha256\", secret).update(value, \"utf8\").digest(\"base64url\");\n}\n\nexport function safeEqual(left: string, right: string): boolean {\n const leftBuffer = Buffer.from(left);\n const rightBuffer = Buffer.from(right);\n return leftBuffer.length === rightBuffer.length && timingSafeEqual(leftBuffer, rightBuffer);\n}\n\nexport function createId(prefix: string): string {\n return `${prefix}_${randomUUID()}`;\n}\n\nexport function parseAuthorityRequest(\n body: unknown,\n): { ok: true; value: AuthorityRequest } | { ok: false; message: string } {\n const input = asRecord(body);\n const actor = asRecord(input.actor);\n const action = asRecord(input.action);\n const target = asRecord(input.downstream_target);\n const actorId = asString(actor.id);\n const actionType = asString(action.type);\n const targetSystem = asString(target.system);\n const targetOperation = asString(target.operation);\n const tenantId = asString(input.tenant_id) ?? asString(input.org_id);\n if (!tenantId) return { ok: false, message: \"tenant_id is required\" };\n if (!actorId) return { ok: false, message: \"actor.id is required\" };\n if (!actionType) return { ok: false, message: \"action.type is required\" };\n if (!targetSystem || !targetOperation) {\n return { ok: false, message: \"downstream_target.system and operation are required\" };\n }\n\n const modeRaw = (asString(input.mode) ?? \"ENFORCE\").toUpperCase();\n const mode: AuthorityMode =\n modeRaw === \"SHADOW\" || modeRaw === \"ENFORCE\" || modeRaw === \"ENFORCEMENT\"\n ? modeRaw\n : \"ENFORCE\";\n\n return {\n ok: true,\n value: {\n tenant_id: tenantId,\n correlation_id: asString(input.correlation_id) ?? createId(\"corr\"),\n idempotency_key: asString(input.idempotency_key) ?? createId(\"idem\"),\n mode,\n actor: {\n id: actorId,\n type: asString(actor.type) ?? \"AI_AGENT\",\n runtime: asString(actor.runtime),\n trust_level: asString(actor.trust_level),\n },\n action: {\n type: actionType,\n resource: asString(action.resource) ?? \"wallet.usdc\",\n amount: asNumber(action.amount),\n currency: (asString(action.currency) ?? \"USD\").toUpperCase(),\n payload_hash: asString(action.payload_hash),\n },\n context: asRecord(input.context),\n policy_refs: Array.isArray(input.policy_refs)\n ? input.policy_refs.filter((item): item is string => typeof item === \"string\")\n : [\"autonomous-spend-policy-v0.1\"],\n downstream_target: {\n system: targetSystem,\n operation: targetOperation,\n endpoint: asString(target.endpoint),\n },\n },\n };\n}\n\nexport function computeActionHash(request: AuthorityRequest): string {\n return `sha256:${sha256({\n tenant_id: request.tenant_id,\n actor: {\n id: request.actor.id,\n type: request.actor.type,\n },\n action: request.action,\n downstream_target: request.downstream_target,\n })}`;\n}\n\nexport function hashLedgerEntry(input: Omit<ExecutionLedgerEntry, \"entry_hash\">): string {\n return sha256(input);\n}\n","import type {\n AuthorityDecisionResponse,\n AuthorityRequest,\n DecisionRecord,\n DossierRecord,\n ExecutionDecisionStatus,\n ExecutionGatingOptions,\n ExecutionLedgerEntry,\n TokenClaims,\n TokenRecord,\n TokenVerificationResult,\n VerifyTokenInput,\n} from \"./ExecutionGatingContracts.js\";\nimport {\n DEFAULT_POLICY_LIMITS,\n POLICY_SNAPSHOT,\n asNumber,\n asRecord,\n asString,\n base64UrlDecode,\n base64UrlEncode,\n computeActionHash,\n createId,\n hashLedgerEntry,\n parseAuthorityRequest,\n safeEqual,\n sha256,\n sign,\n stableStringify,\n} from \"./ExecutionGatingSupport.js\";\n\n/**\n * In-memory execution-gating authority: policy evaluation, single-use execution\n * tokens, signed dossiers, and a hash-chained execution ledger.\n */\nexport class ExecutionGatingService {\n private readonly secret: string;\n private readonly tokenTtlSeconds: number;\n private readonly now: () => Date;\n private readonly decisions = new Map<string, DecisionRecord>();\n private readonly dossiers = new Map<string, DossierRecord>();\n private readonly tokens = new Map<string, TokenRecord>();\n private readonly ledger: ExecutionLedgerEntry[] = [];\n\n constructor(options: ExecutionGatingOptions = {}) {\n this.secret =\n options.signingSecret ??\n process.env.DECIONIS_EXECUTION_TOKEN_SECRET ??\n \"decionis-execution-gating-v0.1-dev-secret\";\n this.tokenTtlSeconds = options.tokenTtlSeconds ?? 60;\n this.now = options.now ?? (() => new Date());\n }\n\n evaluate(request: AuthorityRequest): AuthorityDecisionResponse {\n return this.decide(request, false);\n }\n\n enforce(request: AuthorityRequest): AuthorityDecisionResponse {\n return this.decide(request, false);\n }\n\n enforceAndBind(request: AuthorityRequest): AuthorityDecisionResponse {\n return this.decide(request, true);\n }\n\n parseAuthorityRequest(\n body: unknown,\n ): { ok: true; value: AuthorityRequest } | { ok: false; message: string } {\n return parseAuthorityRequest(body);\n }\n\n verifyToken(input: VerifyTokenInput): TokenVerificationResult {\n const parsed = this.parseToken(input.execution_token);\n if (!parsed.valid || !parsed.claims) return parsed;\n const claims = parsed.claims;\n const record = this.tokens.get(claims.jti);\n const reasonCodes: string[] = [];\n if (!record) reasonCodes.push(\"TOKEN_NOT_ISSUED\");\n if (record?.consumed_at) reasonCodes.push(\"TOKEN_REPLAYED\");\n if (claims.exp <= Math.floor(this.now().getTime() / 1000)) reasonCodes.push(\"TOKEN_EXPIRED\");\n if (input.actor_id && input.actor_id !== claims.actor_id) reasonCodes.push(\"ACTOR_MISMATCH\");\n if (input.actor_type && input.actor_type !== claims.actor_type)\n reasonCodes.push(\"ACTOR_MISMATCH\");\n if (input.action_type && input.action_type !== claims.action_type)\n reasonCodes.push(\"ACTION_MISMATCH\");\n if (input.resource && input.resource !== claims.resource) reasonCodes.push(\"RESOURCE_MISMATCH\");\n if (input.amount != null && input.amount !== claims.amount) reasonCodes.push(\"AMOUNT_MISMATCH\");\n if (input.currency && input.currency.toUpperCase() !== claims.currency) {\n reasonCodes.push(\"AMOUNT_MISMATCH\");\n }\n const target = input.downstream_target ?? {};\n if (target.system && target.system !== claims.target_system)\n reasonCodes.push(\"TARGET_MISMATCH\");\n if (target.operation && target.operation !== claims.target_operation) {\n reasonCodes.push(\"TARGET_MISMATCH\");\n }\n if (target.endpoint && target.endpoint !== claims.target_endpoint) {\n reasonCodes.push(\"TARGET_MISMATCH\");\n }\n return {\n valid: reasonCodes.length === 0,\n reason_codes: reasonCodes.length === 0 ? [\"TOKEN_VALID\"] : [...new Set(reasonCodes)],\n claims,\n };\n }\n\n consumeToken(input: VerifyTokenInput): TokenVerificationResult {\n const verification = this.verifyToken(input);\n const claims = verification.claims;\n if (!verification.valid || !claims) {\n this.recordTokenRejection({\n tenant_id: claims?.sub ?? \"unknown\",\n actor_id: input.actor_id ?? claims?.actor_id ?? null,\n action_type: input.action_type ?? claims?.action_type ?? null,\n resource: input.resource ?? claims?.resource ?? null,\n amount: input.amount ?? claims?.amount ?? null,\n reason_codes: verification.reason_codes,\n metadata: { source: \"consume-token\" },\n });\n return verification;\n }\n const record = this.tokens.get(claims.jti);\n if (!record) {\n return { valid: false, reason_codes: [\"TOKEN_NOT_ISSUED\"], claims };\n }\n this.appendLedger({\n tenant_id: claims.sub,\n event_type: \"execution.token.verified\",\n actor_id: claims.actor_id,\n chain_id: claims.chain_id,\n decision_id: claims.decision_id,\n action_type: claims.action_type,\n resource: claims.resource,\n amount: claims.amount,\n status: \"VERIFIED\",\n reason_codes: [\"TOKEN_VALID\"],\n metadata: { boundary: \"token_verifier\" },\n });\n record.consumed_at = this.now().toISOString();\n this.appendLedger({\n tenant_id: claims.sub,\n event_type: \"execution.token.consumed\",\n actor_id: claims.actor_id,\n chain_id: claims.chain_id,\n decision_id: claims.decision_id,\n action_type: claims.action_type,\n resource: claims.resource,\n amount: claims.amount,\n status: \"CONSUMED\",\n reason_codes: [\"TOKEN_CONSUMED\"],\n metadata: { token_hash: record.token_hash },\n });\n return verification;\n }\n\n recordExecutionEvent(input: Record<string, unknown>): ExecutionLedgerEntry {\n const tenant_id = asString(input.tenant_id) ?? \"unknown\";\n return this.appendLedger({\n tenant_id,\n event_type: asString(input.event_type) ?? \"tool.execution.completed\",\n actor_id: asString(input.actor_id),\n chain_id: asString(input.chain_id),\n decision_id: asString(input.decision_id),\n action_type: asString(input.action_type),\n resource: asString(input.resource),\n amount: asNumber(input.amount),\n status: asString(input.status) ?? \"RECORDED\",\n reason_codes: [],\n metadata: asRecord(input.metadata),\n });\n }\n\n recordTokenRejection(input: {\n tenant_id: string;\n actor_id: string | null;\n action_type: string | null;\n resource: string | null;\n amount: number | null;\n reason_codes: string[];\n metadata: Record<string, unknown>;\n }): ExecutionLedgerEntry {\n return this.appendLedger({\n tenant_id: input.tenant_id,\n event_type: \"execution.token.rejected\",\n actor_id: input.actor_id,\n chain_id: null,\n decision_id: null,\n action_type: input.action_type,\n resource: input.resource,\n amount: input.amount,\n status: \"REJECTED\",\n reason_codes: input.reason_codes,\n metadata: input.metadata,\n });\n }\n\n getDossier(dossierId: string): DossierRecord | null {\n return this.dossiers.get(dossierId) ?? null;\n }\n\n listLedger(input: { tenant_id?: string | null; limit?: number } = {}): ExecutionLedgerEntry[] {\n const filtered = input.tenant_id\n ? this.ledger.filter((entry) => entry.tenant_id === input.tenant_id)\n : this.ledger;\n return filtered.slice(-(input.limit ?? 500));\n }\n\n stats(): { decisions: number; dossiers: number; tokens: number; ledger_entries: number } {\n return {\n decisions: this.decisions.size,\n dossiers: this.dossiers.size,\n tokens: this.tokens.size,\n ledger_entries: this.ledger.length,\n };\n }\n\n private appendLedger(\n input: Omit<ExecutionLedgerEntry, \"event_id\" | \"timestamp\" | \"prev_hash\" | \"entry_hash\"> & {\n timestamp?: string;\n },\n ): ExecutionLedgerEntry {\n const prev_hash = this.ledger.at(-1)?.entry_hash ?? null;\n const entryBase = {\n event_id: createId(\"evt\"),\n tenant_id: input.tenant_id,\n timestamp: input.timestamp ?? this.now().toISOString(),\n event_type: input.event_type,\n actor_id: input.actor_id,\n chain_id: input.chain_id,\n decision_id: input.decision_id,\n action_type: input.action_type,\n resource: input.resource,\n amount: input.amount,\n status: input.status,\n reason_codes: input.reason_codes,\n metadata: input.metadata,\n prev_hash,\n };\n const entry = {\n ...entryBase,\n entry_hash: hashLedgerEntry(entryBase),\n };\n this.ledger.push(entry);\n return entry;\n }\n\n private evaluatePolicy(request: AuthorityRequest) {\n const amount = request.action.amount ?? 0;\n const nowMs = this.now().getTime();\n const minuteAgo = nowMs - 60_000;\n const recentAllowed = this.ledger.filter(\n (entry) =>\n entry.tenant_id === request.tenant_id &&\n entry.actor_id === request.actor.id &&\n entry.action_type === request.action.type &&\n entry.status === \"ALLOW\" &&\n Date.parse(entry.timestamp) >= minuteAgo,\n );\n const spendLastMinute = recentAllowed.reduce((sum, entry) => sum + (entry.amount ?? 0), 0);\n const txCountLastMinute = recentAllowed.length;\n const loopDepth = asNumber(request.context.agent_loop_depth) ?? 0;\n const recursiveLoop = request.context.recursive_loop === true;\n const reasonCodes: string[] = [];\n\n if (\n request.action.type === \"SEND_PAYMENT\" &&\n amount > DEFAULT_POLICY_LIMITS.max_single_payment_usd\n ) {\n reasonCodes.push(\"SPEND_CAP_EXCEEDED\");\n }\n if (request.action.type === \"SEND_PAYMENT\") {\n if (spendLastMinute + amount > DEFAULT_POLICY_LIMITS.max_spend_per_minute_usd) {\n reasonCodes.push(\"SPEND_CAP_EXCEEDED\");\n }\n if (txCountLastMinute >= DEFAULT_POLICY_LIMITS.max_transactions_per_minute) {\n reasonCodes.push(\"VELOCITY_LIMIT_EXCEEDED\");\n }\n }\n if (recursiveLoop || loopDepth > DEFAULT_POLICY_LIMITS.max_recursive_calls_per_task) {\n reasonCodes.push(\"RECURSIVE_LOOP_DETECTED\");\n }\n\n return {\n status: reasonCodes.length > 0 ? (\"BLOCK\" as const) : (\"ALLOW\" as const),\n reason_codes:\n reasonCodes.length > 0\n ? [...new Set(reasonCodes)]\n : [\"WITHIN_SPEND_LIMIT\", \"VELOCITY_WITHIN_THRESHOLD\"],\n telemetry: {\n spend_last_minute: Number(spendLastMinute.toFixed(2)),\n tx_count_last_minute: txCountLastMinute,\n attempted_amount: amount,\n agent_loop_depth: loopDepth,\n },\n risk_score: reasonCodes.length > 0 ? 0.92 : 0.12,\n };\n }\n\n private issueToken(input: {\n request: AuthorityRequest;\n decision_id: string;\n chain_id: string;\n action_hash: string;\n }) {\n const issuedAt = Math.floor(this.now().getTime() / 1000);\n const claims: TokenClaims = {\n iss: \"decionis\",\n sub: input.request.tenant_id,\n jti: createId(\"exec\"),\n decision_id: input.decision_id,\n chain_id: input.chain_id,\n actor_id: input.request.actor.id,\n actor_type: input.request.actor.type,\n action_type: input.request.action.type,\n resource: input.request.action.resource,\n amount: input.request.action.amount,\n currency: input.request.action.currency,\n target_system: input.request.downstream_target.system,\n target_operation: input.request.downstream_target.operation,\n target_endpoint: input.request.downstream_target.endpoint,\n action_hash: input.action_hash,\n iat: issuedAt,\n exp: issuedAt + this.tokenTtlSeconds,\n single_use: true,\n };\n const payload = base64UrlEncode(stableStringify(claims));\n const signature = sign(payload, this.secret);\n const token = `exec_tok_${payload}.${signature}`;\n const tokenHash = sha256(token);\n this.tokens.set(claims.jti, {\n claims,\n token_hash: tokenHash,\n consumed_at: null,\n });\n return {\n token,\n claims,\n token_hash: tokenHash,\n expires_at: new Date(claims.exp * 1000).toISOString(),\n };\n }\n\n private buildDossier(input: {\n request: AuthorityRequest;\n decision_id: string;\n chain_id: string;\n status: ExecutionDecisionStatus;\n reason_codes: string[];\n telemetry: Record<string, unknown>;\n token_hash: string | null;\n }): DossierRecord {\n const dossierBase = {\n dossier_id: createId(\"dos\"),\n decision_id: input.decision_id,\n chain_id: input.chain_id,\n tenant_id: input.request.tenant_id,\n actor: input.request.actor,\n action: input.request.action,\n downstream_target: input.request.downstream_target,\n status: input.status,\n reason_codes: input.reason_codes,\n policy_snapshot: POLICY_SNAPSHOT,\n telemetry: input.telemetry,\n execution_token_hash: input.token_hash,\n created_at: this.now().toISOString(),\n };\n const dossier: DossierRecord = {\n ...dossierBase,\n signature: {\n algorithm: \"HMAC-SHA256\",\n value: sign(stableStringify(dossierBase), this.secret),\n },\n };\n this.dossiers.set(dossier.dossier_id, dossier);\n return dossier;\n }\n\n private parseToken(token: string): TokenVerificationResult {\n if (!token.startsWith(\"exec_tok_\")) {\n return { valid: false, reason_codes: [\"MALFORMED_EXECUTION_TOKEN\"], claims: null };\n }\n const compact = token.slice(\"exec_tok_\".length);\n const [payload, signature] = compact.split(\".\");\n if (!payload || !signature) {\n return { valid: false, reason_codes: [\"MALFORMED_EXECUTION_TOKEN\"], claims: null };\n }\n const expected = sign(payload, this.secret);\n if (!safeEqual(signature, expected)) {\n return { valid: false, reason_codes: [\"TOKEN_SIGNATURE_INVALID\"], claims: null };\n }\n try {\n const claims = JSON.parse(base64UrlDecode(payload)) as TokenClaims;\n return { valid: true, reason_codes: [], claims };\n } catch {\n return { valid: false, reason_codes: [\"MALFORMED_EXECUTION_TOKEN\"], claims: null };\n }\n }\n\n private decide(request: AuthorityRequest, bindExecution: boolean): AuthorityDecisionResponse {\n const decision_id = createId(\"dec\");\n const chain_id = asString(request.context.chain_id) ?? createId(\"chain\");\n const action_hash = computeActionHash(request);\n this.appendLedger({\n tenant_id: request.tenant_id,\n event_type: \"tool.execution.requested\",\n actor_id: request.actor.id,\n chain_id,\n decision_id,\n action_type: request.action.type,\n resource: request.action.resource,\n amount: request.action.amount,\n status: \"ATTEMPTED\",\n reason_codes: [],\n metadata: {\n idempotency_key: request.idempotency_key,\n correlation_id: request.correlation_id,\n source: request.context.source ?? \"authority_api\",\n },\n });\n const evaluation = this.evaluatePolicy(request);\n const status = request.mode === \"SHADOW\" ? \"ALLOW\" : evaluation.status;\n const token =\n bindExecution && status === \"ALLOW\"\n ? this.issueToken({ request, decision_id, chain_id, action_hash })\n : null;\n const ledgerEntry = this.appendLedger({\n tenant_id: request.tenant_id,\n event_type: status === \"ALLOW\" ? \"tool.execution.allowed\" : \"tool.execution.blocked\",\n actor_id: request.actor.id,\n chain_id,\n decision_id,\n action_type: request.action.type,\n resource: request.action.resource,\n amount: request.action.amount,\n status,\n reason_codes: evaluation.reason_codes,\n metadata: {\n action_hash,\n target: request.downstream_target,\n token_issued: Boolean(token),\n },\n });\n if (token) {\n this.appendLedger({\n tenant_id: request.tenant_id,\n event_type: \"execution.token.issued\",\n actor_id: request.actor.id,\n chain_id,\n decision_id,\n action_type: request.action.type,\n resource: request.action.resource,\n amount: request.action.amount,\n status: \"ISSUED\",\n reason_codes: [\"EXECUTION_TOKEN_ISSUED\"],\n metadata: { token_hash: token.token_hash, expires_at: token.expires_at },\n });\n }\n this.decisions.set(decision_id, {\n decision_id,\n chain_id,\n tenant_id: request.tenant_id,\n status,\n reason_codes: evaluation.reason_codes,\n action_hash,\n request,\n created_at: this.now().toISOString(),\n });\n const dossier = this.buildDossier({\n request,\n decision_id,\n chain_id,\n status,\n reason_codes: evaluation.reason_codes,\n telemetry: evaluation.telemetry,\n token_hash: token?.token_hash ?? null,\n });\n const responseBase = {\n decision_id,\n chain_id,\n status,\n should_execute: status === \"ALLOW\",\n reason_codes: evaluation.reason_codes,\n policy_snapshot: POLICY_SNAPSHOT,\n risk_score: evaluation.risk_score,\n blast_radius: request.action.amount && request.action.amount > 1 ? \"medium\" : \"low\",\n required_escalation: null,\n action_hash,\n execution_token: token?.token ?? null,\n execution_token_expires_at: token?.expires_at ?? null,\n dossier_id: dossier.dossier_id,\n dossier_url: `/v1/authority/dossiers/${dossier.dossier_id}`,\n ledger_entry_id: ledgerEntry.event_id,\n };\n return {\n ...responseBase,\n signature: {\n algorithm: \"HMAC-SHA256\",\n value: sign(stableStringify(responseBase), this.secret),\n },\n };\n }\n}\n\n/** Factory facade — original exported constructor for the gating service. */\nexport function createExecutionGatingService(\n options: ExecutionGatingOptions = {},\n): ExecutionGatingService {\n return new ExecutionGatingService(options);\n}\n","import type { FastifyInstance } from \"fastify\";\nimport type {\n AuthorityRequest,\n ExecutionGatingOptions,\n VerifyTokenInput,\n} from \"./ExecutionGatingContracts.js\";\nimport { createExecutionGatingService } from \"./ExecutionGatingService.js\";\nimport type { ExecutionGatingService } from \"./ExecutionGatingService.js\";\nimport { asNumber, asRecord, asString, createId } from \"./ExecutionGatingSupport.js\";\n\nfunction verificationInputFromBody(body: unknown, tokenFallback?: string | null): VerifyTokenInput {\n const input = asRecord(body);\n const target = asRecord(input.downstream_target);\n return {\n execution_token: asString(input.execution_token) ?? tokenFallback ?? \"\",\n actor_id: asString(input.actor_id) ?? undefined,\n actor_type: asString(input.actor_type) ?? undefined,\n action_type: asString(input.action_type) ?? undefined,\n resource: asString(input.resource) ?? undefined,\n amount: asNumber(input.amount) ?? undefined,\n currency: asString(input.currency) ?? undefined,\n downstream_target: {\n system: asString(target.system) ?? undefined,\n operation: asString(target.operation) ?? undefined,\n endpoint: asString(target.endpoint) ?? undefined,\n },\n };\n}\n\nfunction buildPaymentAuthorityRequest(body: unknown, source: string): AuthorityRequest {\n const input = asRecord(body);\n const amount = asNumber(input.amount) ?? 0.25;\n const actor_id = asString(input.actor_id) ?? asString(input.actor) ?? \"research_agent\";\n const currency = (asString(input.currency) ?? \"USD\").toUpperCase();\n return {\n tenant_id: asString(input.tenant_id) ?? \"tenant_demo\",\n correlation_id: asString(input.correlation_id) ?? createId(\"run\"),\n idempotency_key: asString(input.idempotency_key) ?? createId(\"payment\"),\n mode: \"ENFORCE\",\n actor: {\n id: actor_id,\n type: asString(input.actor_type) ?? \"AI_AGENT\",\n runtime: asString(input.actor_runtime) ?? \"mcp\",\n trust_level: asString(input.trust_level) ?? \"external\",\n },\n action: {\n type: \"SEND_PAYMENT\",\n resource: asString(input.resource) ?? \"wallet.usdc\",\n amount,\n currency,\n payload_hash: asString(input.payload_hash),\n },\n context: {\n ...asRecord(input.context),\n source,\n },\n policy_refs: [\"autonomous-spend-policy-v0.1\"],\n downstream_target: {\n system: \"payment_api\",\n operation: \"send_payment\",\n endpoint: \"POST /payments\",\n },\n };\n}\n\nfunction sendInvalidAuthority(\n reply: { code(statusCode: number): { send(body: unknown): unknown } },\n reason_codes: string[],\n) {\n return reply.code(403).send({\n error: \"NO_VALID_DECIONIS_AUTHORITY\",\n reason_codes,\n });\n}\n\n/** Registers the authority/execution-gating HTTP routes on a Fastify app. */\nexport class ExecutionGatingRoutes {\n static register(\n app: FastifyInstance,\n options: {\n serviceName: string;\n serviceVersion: string;\n executionGating?: ExecutionGatingOptions;\n service?: ExecutionGatingService;\n },\n ): void {\n const service = options.service ?? createExecutionGatingService(options.executionGating);\n\n async function handleAuthority(\n body: unknown,\n reply: { code(statusCode: number): { send(body: unknown): unknown } },\n method: \"evaluate\" | \"enforce\" | \"enforceAndBind\",\n ) {\n const parsed = service.parseAuthorityRequest(body);\n if (!parsed.ok) {\n return reply.code(400).send({ error: \"VALIDATION_ERROR\", message: parsed.message });\n }\n return reply.code(200).send(service[method](parsed.value));\n }\n\n app.post(\"/v1/authority/evaluate\", async (req, reply) =>\n handleAuthority(req.body, reply, \"evaluate\"),\n );\n app.post(\"/v1/authority/enforce\", async (req, reply) =>\n handleAuthority(req.body, reply, \"enforce\"),\n );\n app.post(\"/v1/authority/enforce-and-bind\", async (req, reply) =>\n handleAuthority(req.body, reply, \"enforceAndBind\"),\n );\n\n app.post(\"/v1/execution/verify-token\", async (req, reply) => {\n const verification = service.verifyToken(verificationInputFromBody(req.body));\n return reply.code(verification.valid ? 200 : 403).send(verification);\n });\n\n app.post(\"/v1/execution/consume-token\", async (req, reply) => {\n const verification = service.consumeToken(verificationInputFromBody(req.body));\n return reply.code(verification.valid ? 200 : 403).send(verification);\n });\n\n app.post(\"/v1/events/execution\", async (req, reply) => {\n const entry = service.recordExecutionEvent(asRecord(req.body));\n return reply.code(202).send({ accepted: true, ledger_entry: entry });\n });\n\n app.get(\"/v1/authority/dossiers/:dossierId\", async (req, reply) => {\n const dossierId = asString(asRecord(req.params).dossierId);\n const dossier = dossierId ? service.getDossier(dossierId) : null;\n if (!dossier)\n return reply.code(404).send({ error: \"NOT_FOUND\", message: \"Dossier not found\" });\n return reply\n .code(200)\n .send({ service: options.serviceName, version: options.serviceVersion, dossier });\n });\n\n app.get(\"/v1/authority/ledger\", async (req) => {\n const query = asRecord(req.query);\n const limit = asNumber(query.limit) ?? 500;\n return {\n service: options.serviceName,\n version: options.serviceVersion,\n count: service.listLedger({ tenant_id: asString(query.tenant_id), limit }).length,\n entries: service.listLedger({ tenant_id: asString(query.tenant_id), limit }),\n };\n });\n\n app.get(\"/v1/authority/stats\", async () => ({\n service: options.serviceName,\n version: options.serviceVersion,\n ...service.stats(),\n }));\n\n app.post(\"/v1/demo/payment-api/payments\", async (req, reply) => {\n const headerToken = asString(\n (req.headers as Record<string, unknown>)[\"x-decionis-execution-token\"],\n );\n if (!headerToken) {\n const body = asRecord(req.body);\n service.recordTokenRejection({\n tenant_id: asString(body.tenant_id) ?? \"tenant_demo\",\n actor_id: asString(body.actor_id) ?? asString(body.actor),\n action_type: \"SEND_PAYMENT\",\n resource: asString(body.resource) ?? \"wallet.usdc\",\n amount: asNumber(body.amount),\n reason_codes: [\"NO_VALID_EXECUTION_TOKEN\"],\n metadata: { boundary: \"payment_api\", source: \"missing_header\" },\n });\n return sendInvalidAuthority(reply, [\"NO_VALID_EXECUTION_TOKEN\"]);\n }\n\n const body = asRecord(req.body);\n const verification = service.consumeToken({\n execution_token: headerToken,\n actor_id: asString(body.actor_id) ?? asString(body.actor) ?? undefined,\n action_type: \"SEND_PAYMENT\",\n resource: asString(body.resource) ?? \"wallet.usdc\",\n amount: asNumber(body.amount) ?? undefined,\n currency: asString(body.currency) ?? \"USD\",\n downstream_target: {\n system: \"payment_api\",\n operation: \"send_payment\",\n endpoint: \"POST /payments\",\n },\n });\n if (!verification.valid) {\n return sendInvalidAuthority(reply, verification.reason_codes);\n }\n const claims = verification.claims!;\n service.recordExecutionEvent({\n tenant_id: claims.sub,\n event_type: \"tool.execution.completed\",\n actor_id: claims.actor_id,\n chain_id: claims.chain_id,\n decision_id: claims.decision_id,\n action_type: claims.action_type,\n resource: claims.resource,\n amount: claims.amount,\n status: \"EXECUTED\",\n metadata: { boundary: \"payment_api\" },\n });\n return reply.code(200).send({\n payment_id: createId(\"pay\"),\n status: \"SUBMITTED\",\n decision_id: claims.decision_id,\n amount: claims.amount,\n currency: claims.currency,\n });\n });\n\n app.post(\"/v1/gateways/mcp/tools/send-payment\", async (req, reply) => {\n const request = buildPaymentAuthorityRequest(req.body, \"mcp_gateway\");\n const decision = service.enforceAndBind(request);\n if (decision.status !== \"ALLOW\" || !decision.execution_token) {\n return reply.code(200).send({\n gateway: \"mcp\",\n called_downstream: false,\n decision,\n });\n }\n const consumed = service.consumeToken({\n execution_token: decision.execution_token,\n actor_id: request.actor.id,\n action_type: request.action.type,\n resource: request.action.resource,\n amount: request.action.amount ?? undefined,\n currency: request.action.currency,\n downstream_target: request.downstream_target,\n });\n if (!consumed.valid) {\n return sendInvalidAuthority(reply, consumed.reason_codes);\n }\n service.recordExecutionEvent({\n tenant_id: request.tenant_id,\n event_type: \"tool.execution.completed\",\n actor_id: request.actor.id,\n chain_id: decision.chain_id,\n decision_id: decision.decision_id,\n action_type: request.action.type,\n resource: request.action.resource,\n amount: request.action.amount,\n status: \"EXECUTED\",\n metadata: { gateway: \"mcp\", downstream_target: request.downstream_target },\n });\n return reply.code(200).send({\n gateway: \"mcp\",\n called_downstream: true,\n decision,\n tool_result: {\n payment_id: createId(\"pay\"),\n status: \"SUBMITTED\",\n },\n });\n });\n\n app.post(\"/v1/gateways/a2a/tasks\", async (req, reply) => {\n const input = asRecord(req.body);\n const request = buildPaymentAuthorityRequest(\n {\n ...input,\n context: {\n ...asRecord(input.context),\n a2a_task_id: asString(input.task_id) ?? createId(\"task\"),\n },\n },\n \"a2a_gateway\",\n );\n const decision = service.enforce(request);\n return reply.code(200).send({\n gateway: \"a2a\",\n delivered_to_internal_agent: decision.status === \"ALLOW\",\n decision,\n limitation:\n \"Decionis governs tasks crossing this boundary; external agents must also use Decionis at their own execution boundaries.\",\n });\n });\n }\n}\n\n/** Functional alias for {@link ExecutionGatingRoutes.register}. */\nexport function registerExecutionGatingRoutes(\n app: FastifyInstance,\n options: {\n serviceName: string;\n serviceVersion: string;\n executionGating?: ExecutionGatingOptions;\n service?: ExecutionGatingService;\n },\n): void {\n ExecutionGatingRoutes.register(app, options);\n}\n","/** Generic value/request parsing helpers shared across protocol features. */\nexport class Parsing {\n static asRecord(value: unknown): Record<string, unknown> {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return {};\n return value as Record<string, unknown>;\n }\n\n static asString(value: unknown): string | null {\n if (typeof value !== \"string\") return null;\n const trimmed = value.trim();\n return trimmed.length > 0 ? trimmed : null;\n }\n\n static asNumber(value: unknown): number | null {\n if (typeof value === \"number\" && Number.isFinite(value)) return value;\n if (typeof value === \"string\" && value.trim().length > 0) {\n const parsed = Number.parseFloat(value);\n if (Number.isFinite(parsed)) return parsed;\n }\n return null;\n }\n\n static clamp(value: number, min: number, max: number): number {\n return Math.max(min, Math.min(max, value));\n }\n\n static mergeNestedRecords(\n base: Record<string, unknown>,\n extra: Record<string, unknown>,\n keys: string[],\n ): Record<string, unknown> {\n const merged: Record<string, unknown> = { ...base, ...extra };\n for (const key of keys) {\n const baseNested = asRecord(base[key]);\n const extraNested = asRecord(extra[key]);\n if (Object.keys(baseNested).length > 0 || Object.keys(extraNested).length > 0) {\n merged[key] = { ...baseNested, ...extraNested };\n }\n }\n return merged;\n }\n\n static parseListQuery(query: unknown): {\n orgId: string | null;\n limit: number;\n } {\n const raw = query && typeof query === \"object\" ? (query as Record<string, unknown>) : {};\n const orgId = typeof raw.org_id === \"string\" && raw.org_id.trim() ? raw.org_id.trim() : null;\n\n const parsedLimit = typeof raw.limit === \"string\" ? Number.parseInt(raw.limit, 10) : Number.NaN;\n const limit = Number.isFinite(parsedLimit) && parsedLimit > 0 ? Math.min(parsedLimit, 500) : 50;\n\n return { orgId, limit };\n }\n\n static parseOptionalBoolean(value: unknown): boolean | null {\n if (typeof value === \"boolean\") return value;\n return null;\n }\n\n static parseIdempotencyHeader(headers: Record<string, unknown>): string | null {\n const headerValue = headers[\"idempotency-key\"];\n return typeof headerValue === \"string\"\n ? headerValue.trim() || null\n : Array.isArray(headerValue)\n ? (headerValue[0]?.trim() ?? null)\n : null;\n }\n\n static parseUuidArray(value: unknown): string[] {\n if (!Array.isArray(value)) return [];\n return value\n .map((item) => asString(item))\n .filter((item): item is string => Boolean(item))\n .filter((item, index, items) => items.indexOf(item) === index);\n }\n\n static isLikelyUuid(value: string): boolean {\n return /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value);\n }\n\n static parseInstantMs(value: string | null | undefined): number | null {\n if (!value) return null;\n const parsed = Date.parse(value);\n return Number.isFinite(parsed) ? parsed : null;\n }\n}\n\n/** Functional alias for {@link Parsing.asRecord}. */\nexport function asRecord(value: unknown): Record<string, unknown> {\n return Parsing.asRecord(value);\n}\n\n/** Functional alias for {@link Parsing.asString}. */\nexport function asString(value: unknown): string | null {\n return Parsing.asString(value);\n}\n\n/** Functional alias for {@link Parsing.asNumber}. */\nexport function asNumber(value: unknown): number | null {\n return Parsing.asNumber(value);\n}\n\n/** Functional alias for {@link Parsing.clamp}. */\nexport function clamp(value: number, min: number, max: number): number {\n return Parsing.clamp(value, min, max);\n}\n\n/** Functional alias for {@link Parsing.mergeNestedRecords}. */\nexport function mergeNestedRecords(\n base: Record<string, unknown>,\n extra: Record<string, unknown>,\n keys: string[],\n): Record<string, unknown> {\n return Parsing.mergeNestedRecords(base, extra, keys);\n}\n\n/** Functional alias for {@link Parsing.parseListQuery}. */\nexport function parseListQuery(query: unknown): {\n orgId: string | null;\n limit: number;\n} {\n return Parsing.parseListQuery(query);\n}\n\n/** Functional alias for {@link Parsing.parseOptionalBoolean}. */\nexport function parseOptionalBoolean(value: unknown): boolean | null {\n return Parsing.parseOptionalBoolean(value);\n}\n\n/** Functional alias for {@link Parsing.parseIdempotencyHeader}. */\nexport function parseIdempotencyHeader(headers: Record<string, unknown>): string | null {\n return Parsing.parseIdempotencyHeader(headers);\n}\n\n/** Functional alias for {@link Parsing.parseUuidArray}. */\nexport function parseUuidArray(value: unknown): string[] {\n return Parsing.parseUuidArray(value);\n}\n\n/** Functional alias for {@link Parsing.isLikelyUuid}. */\nexport function isLikelyUuid(value: string): boolean {\n return Parsing.isLikelyUuid(value);\n}\n\n/** Functional alias for {@link Parsing.parseInstantMs}. */\nexport function parseInstantMs(value: string | null | undefined): number | null {\n return Parsing.parseInstantMs(value);\n}\n","import { createHash } from \"node:crypto\";\nimport { stableJsonStringify } from \"../integrity/DossierIntegrity.js\";\n\n/** SHA-256 and canonical-JSON hashing helpers shared across protocol features. */\nexport class Hashing {\n static sha256Hex(input: string): string {\n return createHash(\"sha256\").update(input, \"utf8\").digest(\"hex\");\n }\n\n static sha256StableJson(value: unknown): string {\n return sha256Hex(stableJsonStringify(value));\n }\n\n static canonicalizeForHash(value: unknown): unknown {\n if (Array.isArray(value)) return value.map((item) => canonicalizeForHash(item));\n if (!value || typeof value !== \"object\") return value;\n const record = value as Record<string, unknown>;\n return Object.keys(record)\n .sort()\n .reduce<Record<string, unknown>>((acc, key) => {\n acc[key] = canonicalizeForHash(record[key]);\n return acc;\n }, {});\n }\n}\n\n/** Functional alias for {@link Hashing.sha256Hex}. */\nexport function sha256Hex(input: string): string {\n return Hashing.sha256Hex(input);\n}\n\n/** Functional alias for {@link Hashing.sha256StableJson}. */\nexport function sha256StableJson(value: unknown): string {\n return Hashing.sha256StableJson(value);\n}\n\n/** Functional alias for {@link Hashing.canonicalizeForHash}. */\nexport function canonicalizeForHash(value: unknown): unknown {\n return Hashing.canonicalizeForHash(value);\n}\n","export const DECISION_DOSSIER_JWKS_PATH = \"/.well-known/decision-dossier-jwks.json\";\n\nexport type DecisionDossierKeyRotationStrategy = \"JWKS_OVERLAP\";\n\nexport interface DecisionDossierKeyRotationPolicy {\n strategy: DecisionDossierKeyRotationStrategy;\n active_key_id: string;\n previous_key_ids: string[];\n verification_grace_period_days: number;\n rotated_at: string | null;\n public_jwks_path: string;\n}\n\nexport type DecisionDossierProofArtifactKind = \"portable_artifact\" | \"json_ld\";\n\nexport interface DecisionDossierProofArtifact {\n artifact_kind: DecisionDossierProofArtifactKind;\n media_type: \"application/json\" | \"application/ld+json\";\n document_path: string;\n canonical_document_sha256: string;\n signature: string;\n}\n\nexport interface DecisionDossierAsymmetricProofBundle {\n bundle_type: \"decionis.decision_dossier.proof_bundle\";\n version: \"2.0\";\n issued_at: string;\n algorithm: \"Ed25519\";\n key_id: string;\n rotation_policy: DecisionDossierKeyRotationPolicy;\n artifacts: DecisionDossierProofArtifact[];\n}\n\nexport type DecisionDossierVerificationCheckKey =\n | \"signature\"\n | \"policy_snapshot\"\n | \"chain_integrity\"\n | \"proof_bundle\";\n\nexport type DecisionDossierVerificationCheckSeverity = \"pass\" | \"warn\" | \"fail\";\n\nexport type DecisionDossierVerificationOverallStatus = \"VERIFIED\" | \"PARTIAL\" | \"UNVERIFIED\";\n\nexport interface DecisionDossierVerificationCheck {\n key: DecisionDossierVerificationCheckKey;\n label: string;\n verified: boolean;\n severity: DecisionDossierVerificationCheckSeverity;\n detail: string;\n}\n\nexport interface DecisionDossierVerificationStatus {\n signature_verified: boolean;\n policy_snapshot_verified: boolean;\n chain_integrity_verified: boolean;\n proof_bundle_verified: boolean;\n overall: DecisionDossierVerificationOverallStatus;\n checked_at: string;\n checks: DecisionDossierVerificationCheck[];\n}\n\n/** Canonical serialization and verification-status assembly for decision dossiers. */\nexport class DossierIntegrity {\n static stableJsonStringify(value: unknown): string {\n return JSON.stringify(DossierIntegrity.canonicalize(value));\n }\n\n static isDecisionPolicySnapshotVerified(value: unknown): boolean {\n const snapshot = DossierIntegrity.asRecord(value);\n const hasPolicyVersion = DossierIntegrity.isNonEmptyString(snapshot.policy_version);\n const hasSnapshotDigest =\n DossierIntegrity.isNonEmptyString(snapshot.policy_bundle_id) ||\n DossierIntegrity.isNonEmptyString(snapshot.rules_sha256) ||\n DossierIntegrity.isNonEmptyString(snapshot.parameters_sha256);\n const hasEvaluationTime = DossierIntegrity.isNonEmptyString(snapshot.evaluated_at);\n return hasPolicyVersion && hasSnapshotDigest && hasEvaluationTime;\n }\n\n static isDecisionDossierProofBundleVerified(\n value: DecisionDossierAsymmetricProofBundle | null | undefined,\n ): boolean {\n if (!value) return false;\n if (value.bundle_type !== \"decionis.decision_dossier.proof_bundle\") return false;\n if (value.version !== \"2.0\" || value.algorithm !== \"Ed25519\") return false;\n if (\n !DossierIntegrity.isNonEmptyString(value.key_id) ||\n !DossierIntegrity.isNonEmptyString(value.issued_at)\n ) {\n return false;\n }\n if (!DossierIntegrity.isNonEmptyString(value.rotation_policy.active_key_id)) return false;\n if (!DossierIntegrity.isNonEmptyString(value.rotation_policy.public_jwks_path)) return false;\n return (\n value.artifacts.length > 0 &&\n value.artifacts.every(\n (artifact) =>\n DossierIntegrity.isNonEmptyString(artifact.artifact_kind) &&\n DossierIntegrity.isNonEmptyString(artifact.document_path) &&\n DossierIntegrity.isNonEmptyString(artifact.canonical_document_sha256) &&\n DossierIntegrity.isNonEmptyString(artifact.signature),\n )\n );\n }\n\n static buildDecisionDossierVerificationStatus(input: {\n signature_verified: boolean;\n policy_snapshot?: unknown;\n ledger_chain_verified?: boolean | null;\n proof_bundle?: DecisionDossierAsymmetricProofBundle | null;\n checked_at?: string;\n }): DecisionDossierVerificationStatus {\n const signatureVerified = input.signature_verified === true;\n const policySnapshotVerified = DossierIntegrity.isDecisionPolicySnapshotVerified(\n input.policy_snapshot,\n );\n const chainIntegrityVerified = input.ledger_chain_verified === true;\n const proofBundleVerified = DossierIntegrity.isDecisionDossierProofBundleVerified(\n input.proof_bundle,\n );\n const verifiedChecks = [\n signatureVerified,\n policySnapshotVerified,\n chainIntegrityVerified,\n ].filter(Boolean).length;\n\n return {\n signature_verified: signatureVerified,\n policy_snapshot_verified: policySnapshotVerified,\n chain_integrity_verified: chainIntegrityVerified,\n proof_bundle_verified: proofBundleVerified,\n overall: verifiedChecks === 3 ? \"VERIFIED\" : verifiedChecks > 0 ? \"PARTIAL\" : \"UNVERIFIED\",\n checked_at: input.checked_at ?? new Date().toISOString(),\n checks: [\n {\n key: \"signature\",\n label: \"Signature Verified\",\n verified: signatureVerified,\n severity: signatureVerified ? \"pass\" : \"fail\",\n detail: signatureVerified\n ? \"The public verifier signature matched the dossier integrity envelope.\"\n : \"The verifier signature did not match the dossier integrity envelope.\",\n },\n {\n key: \"policy_snapshot\",\n label: \"Policy Snapshot Verified\",\n verified: policySnapshotVerified,\n severity: policySnapshotVerified ? \"pass\" : \"warn\",\n detail: policySnapshotVerified\n ? \"The signed dossier includes a policy version and immutable policy snapshot digest.\"\n : \"The signed dossier does not include a verifiable policy snapshot digest.\",\n },\n {\n key: \"chain_integrity\",\n label: \"Chain Integrity Verified\",\n verified: chainIntegrityVerified,\n severity: chainIntegrityVerified ? \"pass\" : \"warn\",\n detail: chainIntegrityVerified\n ? \"The dossier ledger entry reports a verified hash-chain state.\"\n : \"The dossier ledger entry does not report a verified hash-chain state.\",\n },\n {\n key: \"proof_bundle\",\n label: \"Proof Bundle Verified\",\n verified: proofBundleVerified,\n severity: proofBundleVerified ? \"pass\" : \"warn\",\n detail: proofBundleVerified\n ? \"A persisted Ed25519 proof bundle is present with signed portable artifacts.\"\n : \"No persisted Ed25519 proof bundle was available for this dossier.\",\n },\n ],\n };\n }\n\n private static canonicalize(value: unknown): unknown {\n if (Array.isArray(value)) {\n return value.map((item) => DossierIntegrity.canonicalize(item));\n }\n if (!value || typeof value !== \"object\") {\n return value;\n }\n\n const record = value as Record<string, unknown>;\n const sortedKeys = Object.keys(record).sort();\n const normalized: Record<string, unknown> = {};\n for (const key of sortedKeys) {\n normalized[key] = DossierIntegrity.canonicalize(record[key]);\n }\n return normalized;\n }\n\n private static asRecord(value: unknown): Record<string, unknown> {\n return value && typeof value === \"object\" && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : {};\n }\n\n private static isNonEmptyString(value: unknown): value is string {\n return typeof value === \"string\" && value.trim().length > 0;\n }\n}\n\n/** Functional alias for {@link DossierIntegrity.stableJsonStringify}. */\nexport function stableJsonStringify(value: unknown): string {\n return DossierIntegrity.stableJsonStringify(value);\n}\n\n/** Functional alias for {@link DossierIntegrity.isDecisionPolicySnapshotVerified}. */\nexport function isDecisionPolicySnapshotVerified(value: unknown): boolean {\n return DossierIntegrity.isDecisionPolicySnapshotVerified(value);\n}\n\n/** Functional alias for {@link DossierIntegrity.isDecisionDossierProofBundleVerified}. */\nexport function isDecisionDossierProofBundleVerified(\n value: DecisionDossierAsymmetricProofBundle | null | undefined,\n): boolean {\n return DossierIntegrity.isDecisionDossierProofBundleVerified(value);\n}\n\n/** Functional alias for {@link DossierIntegrity.buildDecisionDossierVerificationStatus}. */\nexport function buildDecisionDossierVerificationStatus(input: {\n signature_verified: boolean;\n policy_snapshot?: unknown;\n ledger_chain_verified?: boolean | null;\n proof_bundle?: DecisionDossierAsymmetricProofBundle | null;\n checked_at?: string;\n}): DecisionDossierVerificationStatus {\n return DossierIntegrity.buildDecisionDossierVerificationStatus(input);\n}\n","import type { PolicyBundleArtifactRow, ProtocolStore } from \"../store/StoreContracts.js\";\nimport { asNumber, asRecord, asString, clamp, parseInstantMs } from \"../support/Parsing.js\";\nimport { sha256StableJson } from \"../support/Hashing.js\";\nimport type {\n EvaluateDecisionOutcome,\n EvaluateDecisionRequest,\n} from \"../evaluate-decision/EvaluateDecisionContracts.js\";\nimport type {\n EvaluateDecisionPolicyAction,\n EvaluateDecisionPolicyConditionNode,\n EvaluateDecisionPolicyEvaluation,\n EvaluateDecisionPolicyGuard,\n EvaluateDecisionPolicyGuardStatus,\n EvaluateDecisionPolicyPredicate,\n EvaluateDecisionPolicyPredicateOperator,\n EvaluateDecisionPolicyRule,\n EvaluateDecisionPolicySnapshot,\n ResolvedEvaluateDecisionPolicyRuntime,\n} from \"./PolicyGraphContracts.js\";\n\n/** Org policy-bundle guard resolution and the evaluate-decision policy rules engine. */\nexport class PolicyGraph {\n static sortPolicyBundlesNewestFirst(\n left: PolicyBundleArtifactRow,\n right: PolicyBundleArtifactRow,\n ): number {\n const leftEffective = parseInstantMs(left.effective_from) ?? Number.MIN_SAFE_INTEGER;\n const rightEffective = parseInstantMs(right.effective_from) ?? Number.MIN_SAFE_INTEGER;\n if (leftEffective !== rightEffective) return rightEffective - leftEffective;\n\n const leftUpdated = parseInstantMs(left.updated_at) ?? Number.MIN_SAFE_INTEGER;\n const rightUpdated = parseInstantMs(right.updated_at) ?? Number.MIN_SAFE_INTEGER;\n if (leftUpdated !== rightUpdated) return rightUpdated - leftUpdated;\n\n return right.bundle_id.localeCompare(left.bundle_id);\n }\n\n /**\n * Maker-checker activation gate (default off — zero behavior change unless opted in).\n * A bundle demands approval when its `metadata.requires_approval` is true, or globally\n * when `DECIONIS_POLICY_REQUIRE_APPROVAL=1|true`. Such a bundle activates only once\n * `metadata.approved_by` is present and differs from `metadata.author` — the maker\n * cannot be the checker. An unapproved bundle is treated as not active, so the policy\n * guard fails closed (decisions escalate) instead of running on an unapproved policy.\n */\n static isPolicyBundleApproved(bundle: PolicyBundleArtifactRow): boolean {\n const metadata = asRecord(asRecord(bundle.payload).metadata);\n const globalFlag = String(process.env.DECIONIS_POLICY_REQUIRE_APPROVAL ?? \"\")\n .trim()\n .toLowerCase();\n const requiresApproval =\n metadata.requires_approval === true || globalFlag === \"1\" || globalFlag === \"true\";\n if (!requiresApproval) return true;\n\n const approvedBy = asString(metadata.approved_by)?.trim().toLowerCase() ?? \"\";\n if (!approvedBy) return false;\n const author = asString(metadata.author)?.trim().toLowerCase() ?? \"\";\n return approvedBy !== author;\n }\n\n static isPolicyBundleActive(bundle: PolicyBundleArtifactRow, evaluatedAtMs: number): boolean {\n const effectiveFromMs = parseInstantMs(bundle.effective_from);\n const effectiveToMs = parseInstantMs(bundle.effective_to);\n if (effectiveFromMs != null && effectiveFromMs > evaluatedAtMs) return false;\n if (effectiveToMs != null && effectiveToMs < evaluatedAtMs) return false;\n return PolicyGraph.isPolicyBundleApproved(bundle);\n }\n\n static resolveEvaluateDecisionPolicyGuard(input: {\n bundles: PolicyBundleArtifactRow[];\n evaluated_at: string;\n }): EvaluateDecisionPolicyGuard {\n const evaluatedAtMs = parseInstantMs(input.evaluated_at) ?? Date.now();\n const bundles = [...input.bundles].sort(sortPolicyBundlesNewestFirst);\n const activeBundles = bundles.filter((bundle) => isPolicyBundleActive(bundle, evaluatedAtMs));\n const latestBundle = bundles[0] ?? null;\n const activeBundle = activeBundles[0] ?? null;\n\n const status: EvaluateDecisionPolicyGuardStatus =\n activeBundles.length > 0 ? \"ready\" : bundles.length > 0 ? \"configured\" : \"missing\";\n const reason =\n status === \"missing\"\n ? \"missing_org_policy_bundle\"\n : status === \"configured\"\n ? \"no_active_org_policy_bundle\"\n : null;\n\n return {\n status,\n requires_manual_review: status !== \"ready\",\n total_bundle_count: bundles.length,\n active_bundle_count: activeBundles.length,\n active_bundle_id: activeBundle?.bundle_id ?? null,\n active_bundle_version: activeBundle?.version ?? null,\n active_effective_from: activeBundle?.effective_from ?? null,\n active_effective_to: activeBundle?.effective_to ?? null,\n latest_bundle_id: latestBundle?.bundle_id ?? null,\n latest_bundle_version: latestBundle?.version ?? null,\n latest_effective_from: latestBundle?.effective_from ?? null,\n latest_effective_to: latestBundle?.effective_to ?? null,\n reason,\n evaluated_at: input.evaluated_at,\n };\n }\n\n static async loadEvaluateDecisionPolicyGuard(input: {\n store: ProtocolStore;\n orgId: string;\n evaluated_at: string;\n limit?: number;\n }): Promise<EvaluateDecisionPolicyGuard> {\n const bundles = await input.store.listPolicyBundles({\n orgId: input.orgId,\n limit: input.limit ?? 25,\n });\n return resolveEvaluateDecisionPolicyGuard({\n bundles,\n evaluated_at: input.evaluated_at,\n });\n }\n\n static resolveBlockedPolicyVersion(policyGuard: EvaluateDecisionPolicyGuard): string {\n return (\n policyGuard.active_bundle_version ??\n policyGuard.latest_bundle_version ??\n \"org-policy-required\"\n );\n }\n\n static parseEvaluateDecisionPolicyAction(input: unknown): EvaluateDecisionPolicyAction | null {\n const value = asString(input);\n if (\n value === \"REQUIRE_REVIEW\" ||\n value === \"AUTO_APPROVE\" ||\n value === \"AUTO_REJECT\" ||\n value === \"ESCALATE\" ||\n value === \"REQUEST_INFO\"\n ) {\n return value;\n }\n return null;\n }\n\n static parseEvaluateDecisionPolicySeverity(\n input: unknown,\n ): \"routine\" | \"elevated\" | \"urgent\" | null {\n const value = asString(input);\n if (value === \"routine\" || value === \"elevated\" || value === \"urgent\") return value;\n return null;\n }\n\n static parseEvaluateDecisionPolicyOperator(\n input: unknown,\n ): EvaluateDecisionPolicyPredicateOperator | null {\n const value = asString(input);\n if (\n value === \"EQ\" ||\n value === \"NEQ\" ||\n value === \"GT\" ||\n value === \"GTE\" ||\n value === \"LT\" ||\n value === \"LTE\" ||\n value === \"IN\" ||\n value === \"NOT_IN\" ||\n value === \"EXISTS\" ||\n value === \"CONTAINS\" ||\n value === \"MATCHES\"\n ) {\n return value;\n }\n return null;\n }\n\n static isEvaluateDecisionPolicyPredicate(\n record: Record<string, unknown>,\n ): record is EvaluateDecisionPolicyPredicate {\n return (\n asString(record.field) != null && parseEvaluateDecisionPolicyOperator(record.operator) != null\n );\n }\n\n static parseEvaluateDecisionPolicyConditionNode(\n input: unknown,\n ): EvaluateDecisionPolicyConditionNode | null {\n const record = asRecord(input);\n if (isEvaluateDecisionPolicyPredicate(record)) {\n return {\n field: asString(record.field) ?? \"\",\n operator: parseEvaluateDecisionPolicyOperator(record.operator) ?? \"EQ\",\n ...(Object.prototype.hasOwnProperty.call(record, \"value\") ? { value: record.value } : {}),\n ...(Array.isArray(record.values) ? { values: record.values } : {}),\n };\n }\n\n const all = Array.isArray(record.all)\n ? record.all\n .map((item) => parseEvaluateDecisionPolicyConditionNode(item))\n .filter((item): item is EvaluateDecisionPolicyConditionNode => item != null)\n : undefined;\n const any = Array.isArray(record.any)\n ? record.any\n .map((item) => parseEvaluateDecisionPolicyConditionNode(item))\n .filter((item): item is EvaluateDecisionPolicyConditionNode => item != null)\n : undefined;\n\n if (!all && !any) return null;\n return {\n ...(all ? { all } : {}),\n ...(any ? { any } : {}),\n };\n }\n\n static parseEvaluateDecisionPolicyRule(\n input: unknown,\n originalIndex: number,\n ): EvaluateDecisionPolicyRule | null {\n const record = asRecord(input);\n const ruleId = asString(record.rule_id);\n const name = asString(record.name);\n const decisionDomain = asString(record.decision_domain);\n const when = parseEvaluateDecisionPolicyConditionNode(record.when);\n const then = asRecord(record.then);\n const action = parseEvaluateDecisionPolicyAction(then.action);\n if (!ruleId || !name || !decisionDomain || !when || !action) return null;\n\n return {\n rule_id: ruleId,\n name,\n decision_domain: decisionDomain,\n when,\n then: {\n action,\n severity: parseEvaluateDecisionPolicySeverity(then.severity),\n sla_minutes: asNumber(then.sla_minutes),\n assignee_role: asString(then.assignee_role),\n },\n priority: asNumber(record.priority) ?? 0,\n enabled: typeof record.enabled === \"boolean\" ? record.enabled : false,\n rationale: asString(record.rationale),\n original_index: originalIndex,\n };\n }\n\n static normalizeEvaluateDecisionPolicyText(value: unknown): string | null {\n if (typeof value === \"string\") {\n const trimmed = value.trim();\n return trimmed.length > 0 ? trimmed.toLowerCase() : null;\n }\n if (typeof value === \"number\" || typeof value === \"boolean\") {\n return String(value).toLowerCase();\n }\n return null;\n }\n\n static parseEvaluateDecisionPolicyBoolean(value: unknown): boolean | null {\n if (typeof value === \"boolean\") return value;\n if (typeof value === \"string\") {\n const normalized = value.trim().toLowerCase();\n if (normalized === \"true\") return true;\n if (normalized === \"false\") return false;\n }\n if (typeof value === \"number\") {\n if (value === 1) return true;\n if (value === 0) return false;\n }\n return null;\n }\n\n static areEvaluateDecisionPolicyValuesEqual(actual: unknown, expected: unknown): boolean {\n if (Array.isArray(actual)) {\n return actual.some((item) => areEvaluateDecisionPolicyValuesEqual(item, expected));\n }\n if (Array.isArray(expected)) {\n return expected.some((item) => areEvaluateDecisionPolicyValuesEqual(actual, item));\n }\n\n const actualNumber = asNumber(actual);\n const expectedNumber = asNumber(expected);\n if (actualNumber != null && expectedNumber != null) return actualNumber === expectedNumber;\n\n const actualBoolean = parseEvaluateDecisionPolicyBoolean(actual);\n const expectedBoolean = parseEvaluateDecisionPolicyBoolean(expected);\n if (actualBoolean != null && expectedBoolean != null) return actualBoolean === expectedBoolean;\n\n const actualText = normalizeEvaluateDecisionPolicyText(actual);\n const expectedText = normalizeEvaluateDecisionPolicyText(expected);\n if (actualText != null && expectedText != null) return actualText === expectedText;\n\n return actual === expected;\n }\n\n static resolveEvaluateDecisionPolicyFactValue(\n facts: Record<string, unknown>,\n field: string,\n ): unknown {\n if (Object.prototype.hasOwnProperty.call(facts, field)) return facts[field];\n\n const normalizedPath = field.replace(/\\[(\\d+)\\]/g, \".$1\");\n const segments = normalizedPath\n .split(\".\")\n .map((segment) => segment.trim())\n .filter(Boolean);\n if (segments.length === 0) return undefined;\n\n let current: unknown = facts;\n for (const segment of segments) {\n if (Array.isArray(current)) {\n const index = Number.parseInt(segment, 10);\n if (!Number.isFinite(index)) return undefined;\n current = current[index];\n continue;\n }\n const record = asRecord(current);\n current = record[segment];\n }\n return current;\n }\n\n static evaluateDecisionPolicyPredicate(\n predicate: EvaluateDecisionPolicyPredicate,\n facts: Record<string, unknown>,\n ): boolean {\n const actual = resolveEvaluateDecisionPolicyFactValue(facts, predicate.field);\n const expectedValues = Array.isArray(predicate.values)\n ? predicate.values\n : Object.prototype.hasOwnProperty.call(predicate, \"value\")\n ? [predicate.value]\n : [];\n\n switch (predicate.operator) {\n case \"EQ\":\n return areEvaluateDecisionPolicyValuesEqual(actual, predicate.value);\n case \"NEQ\":\n return !areEvaluateDecisionPolicyValuesEqual(actual, predicate.value);\n case \"GT\": {\n const actualNumber = asNumber(actual);\n const expectedNumber = asNumber(predicate.value);\n return actualNumber != null && expectedNumber != null\n ? actualNumber > expectedNumber\n : false;\n }\n case \"GTE\": {\n const actualNumber = asNumber(actual);\n const expectedNumber = asNumber(predicate.value);\n return actualNumber != null && expectedNumber != null\n ? actualNumber >= expectedNumber\n : false;\n }\n case \"LT\": {\n const actualNumber = asNumber(actual);\n const expectedNumber = asNumber(predicate.value);\n return actualNumber != null && expectedNumber != null\n ? actualNumber < expectedNumber\n : false;\n }\n case \"LTE\": {\n const actualNumber = asNumber(actual);\n const expectedNumber = asNumber(predicate.value);\n return actualNumber != null && expectedNumber != null\n ? actualNumber <= expectedNumber\n : false;\n }\n case \"IN\":\n return expectedValues.some((expected) =>\n areEvaluateDecisionPolicyValuesEqual(actual, expected),\n );\n case \"NOT_IN\":\n return expectedValues.every(\n (expected) => !areEvaluateDecisionPolicyValuesEqual(actual, expected),\n );\n case \"EXISTS\": {\n const exists = actual !== undefined && actual !== null;\n const expected = parseEvaluateDecisionPolicyBoolean(predicate.value);\n return expected == null ? exists : exists === expected;\n }\n case \"CONTAINS\": {\n if (Array.isArray(actual)) {\n return expectedValues.some((expected) =>\n actual.some((item) => areEvaluateDecisionPolicyValuesEqual(item, expected)),\n );\n }\n const actualText = normalizeEvaluateDecisionPolicyText(actual);\n if (!actualText) return false;\n return expectedValues.some((expected) => {\n const expectedText = normalizeEvaluateDecisionPolicyText(expected);\n return expectedText ? actualText.includes(expectedText) : false;\n });\n }\n case \"MATCHES\": {\n const actualText = normalizeEvaluateDecisionPolicyText(actual);\n const pattern = typeof predicate.value === \"string\" ? predicate.value : null;\n if (!actualText || !pattern) return false;\n try {\n return new RegExp(pattern, \"i\").test(actualText);\n } catch {\n return false;\n }\n }\n default:\n return false;\n }\n }\n\n static evaluateDecisionPolicyConditionNode(\n node: EvaluateDecisionPolicyConditionNode,\n facts: Record<string, unknown>,\n ): boolean {\n const record = asRecord(node);\n if (isEvaluateDecisionPolicyPredicate(record)) {\n return evaluateDecisionPolicyPredicate(record, facts);\n }\n\n const all = Array.isArray(record.all)\n ? record.all.every((child) => evaluateDecisionPolicyConditionNode(child, facts))\n : true;\n const any = Array.isArray(record.any)\n ? record.any.some((child) => evaluateDecisionPolicyConditionNode(child, facts))\n : true;\n return all && any;\n }\n\n static matchesEvaluateDecisionRuleDomain(ruleDomain: string, decisionDomain: string): boolean {\n const normalizedRuleDomain = ruleDomain.trim().toUpperCase();\n const normalizedDecisionDomain = decisionDomain.trim().toUpperCase();\n return (\n normalizedRuleDomain === \"*\" ||\n normalizedRuleDomain === \"ANY\" ||\n normalizedRuleDomain === normalizedDecisionDomain\n );\n }\n\n static buildEvaluateDecisionPolicyFacts(input: {\n request: EvaluateDecisionRequest;\n decisionDomain: string;\n bundle: PolicyBundleArtifactRow;\n }): Record<string, unknown> {\n const context = asRecord(input.request.context);\n const signals = asRecord(context.signals);\n const override = asRecord(context.override);\n const evidence = asRecord(context.evidence);\n const attachments = Array.isArray(context.attachments)\n ? context.attachments\n : Array.isArray(evidence.attachments)\n ? evidence.attachments\n : [];\n\n return {\n ...context,\n org_id: input.request.org_id,\n decision_type: input.request.decision_type,\n decision_domain: input.decisionDomain,\n amount: input.request.amount,\n risk_score: input.request.risk_score,\n channel: input.request.channel,\n objective_profile: input.request.objective_profile,\n mode: input.request.mode,\n decision_band: input.request.decision_band,\n transaction_type: input.request.transaction_type,\n workflow_key: input.request.workflow_key,\n vertical_pack: input.request.vertical_pack,\n requested_policy_version: input.request.policy_version,\n context,\n intake: context,\n signals,\n override,\n evidence,\n attachments,\n attachment_count: attachments.length,\n policy: {\n bundle_id: input.bundle.bundle_id,\n version: input.bundle.version,\n },\n };\n }\n\n static sortEvaluateDecisionPolicyRules(\n left: EvaluateDecisionPolicyRule,\n right: EvaluateDecisionPolicyRule,\n ): number {\n if (left.priority !== right.priority) return right.priority - left.priority;\n return left.original_index - right.original_index;\n }\n\n static evaluateDecisionPolicyGraph(input: {\n bundle: PolicyBundleArtifactRow;\n request: EvaluateDecisionRequest;\n decision_domain: string;\n evaluated_at: string;\n }): EvaluateDecisionPolicyEvaluation {\n const facts = buildEvaluateDecisionPolicyFacts({\n request: input.request,\n decisionDomain: input.decision_domain,\n bundle: input.bundle,\n });\n const rules = input.bundle.rules\n .map((rule, index) => parseEvaluateDecisionPolicyRule(rule, index))\n .filter((rule): rule is EvaluateDecisionPolicyRule => rule != null)\n .filter((rule) => rule.enabled)\n .filter((rule) =>\n matchesEvaluateDecisionRuleDomain(rule.decision_domain, input.decision_domain),\n )\n .sort(sortEvaluateDecisionPolicyRules);\n\n const matchedRules = rules.filter((rule) =>\n evaluateDecisionPolicyConditionNode(rule.when, facts),\n );\n const selectedRule = matchedRules[0] ?? null;\n\n return {\n resolution: selectedRule ? \"matched_rule\" : \"no_matching_rule\",\n bundle_id: input.bundle.bundle_id,\n bundle_version: input.bundle.version,\n evaluated_at: input.evaluated_at,\n decision_domain: input.decision_domain,\n evaluated_rule_count: rules.length,\n matched_rule_count: matchedRules.length,\n matched_rule_ids: matchedRules.map((rule) => rule.rule_id),\n selected_rule_id: selectedRule?.rule_id ?? null,\n selected_rule_name: selectedRule?.name ?? null,\n selected_rule_action: selectedRule?.then.action ?? null,\n selected_rule_priority: selectedRule?.priority ?? null,\n selected_rule_rationale: selectedRule?.rationale ?? null,\n selected_rule_severity: selectedRule?.then.severity ?? null,\n selected_rule_assignee_role: selectedRule?.then.assignee_role ?? null,\n selected_rule_sla_minutes: selectedRule?.then.sla_minutes ?? null,\n };\n }\n\n static resolveEvaluateDecisionOutcomeFromPolicyEvaluation(\n input: EvaluateDecisionPolicyEvaluation,\n ): EvaluateDecisionOutcome {\n if (input.resolution === \"policy_guard_blocked\") return \"ESCALATE\";\n if (input.resolution === \"no_matching_rule\") return \"REVIEW\";\n\n switch (input.selected_rule_action) {\n case \"AUTO_APPROVE\":\n return \"APPROVE\";\n case \"AUTO_REJECT\":\n return \"REJECT\";\n case \"ESCALATE\":\n return \"ESCALATE\";\n case \"REQUIRE_REVIEW\":\n case \"REQUEST_INFO\":\n default:\n return \"REVIEW\";\n }\n }\n\n static resolveEvaluateDecisionConfidenceFromPolicyEvaluation(\n input: EvaluateDecisionPolicyEvaluation,\n ): number {\n if (input.resolution === \"policy_guard_blocked\") return 0.99;\n if (input.resolution === \"no_matching_rule\") return 0.96;\n\n let confidence =\n input.selected_rule_action === \"AUTO_REJECT\"\n ? 0.97\n : input.selected_rule_action === \"ESCALATE\"\n ? 0.96\n : input.selected_rule_action === \"REQUIRE_REVIEW\"\n ? 0.94\n : input.selected_rule_action === \"REQUEST_INFO\"\n ? 0.91\n : 0.92;\n\n if (input.matched_rule_count === 1) confidence += 0.02;\n if (input.selected_rule_priority != null && input.selected_rule_priority >= 100)\n confidence += 0.02;\n return Number.parseFloat(clamp(confidence, 0.55, 0.99).toFixed(4));\n }\n\n static async loadEvaluateDecisionPolicyRuntime(input: {\n store: ProtocolStore;\n orgId: string;\n evaluated_at: string;\n requested_policy_version?: string | null;\n limit?: number;\n }): Promise<ResolvedEvaluateDecisionPolicyRuntime> {\n const bundles = await input.store.listPolicyBundles({\n orgId: input.orgId,\n limit: input.limit ?? 50,\n });\n const policyGuard = resolveEvaluateDecisionPolicyGuard({\n bundles,\n evaluated_at: input.evaluated_at,\n });\n const evaluatedAtMs = parseInstantMs(input.evaluated_at) ?? Date.now();\n const activeBundles = [...bundles]\n .sort(sortPolicyBundlesNewestFirst)\n .filter((bundle) => isPolicyBundleActive(bundle, evaluatedAtMs));\n const selectedBundle =\n activeBundles.find((bundle) => bundle.version === input.requested_policy_version) ??\n activeBundles[0] ??\n null;\n\n return {\n policyGuard,\n selectedBundle,\n };\n }\n\n static policyBundleParametersForSnapshot(\n bundle: PolicyBundleArtifactRow,\n ): Record<string, unknown> {\n const payloadWithoutRules = { ...bundle.payload };\n delete payloadWithoutRules.rules;\n return {\n bundle_id: bundle.bundle_id,\n org_id: bundle.org_id,\n version: bundle.version,\n effective_from: bundle.effective_from,\n effective_to: bundle.effective_to,\n payload: payloadWithoutRules,\n };\n }\n\n static buildEvaluateDecisionPolicySnapshot(input: {\n policyGuard: EvaluateDecisionPolicyGuard;\n policyEvaluation: EvaluateDecisionPolicyEvaluation;\n selectedBundle: PolicyBundleArtifactRow | null;\n responsePolicyVersion: string;\n }): EvaluateDecisionPolicySnapshot {\n const bundle = input.selectedBundle;\n const policyBundleId =\n bundle?.bundle_id ??\n input.policyEvaluation.bundle_id ??\n input.policyGuard.active_bundle_id ??\n input.policyGuard.latest_bundle_id ??\n null;\n\n return {\n policy_version: input.responsePolicyVersion,\n policy_bundle_id: policyBundleId,\n rules_sha256: bundle ? sha256StableJson(bundle.rules) : null,\n parameters_sha256: bundle\n ? sha256StableJson(policyBundleParametersForSnapshot(bundle))\n : null,\n effective_from:\n bundle?.effective_from ??\n input.policyGuard.active_effective_from ??\n input.policyGuard.latest_effective_from ??\n null,\n effective_to:\n bundle?.effective_to ??\n input.policyGuard.active_effective_to ??\n input.policyGuard.latest_effective_to ??\n null,\n evaluated_at: input.policyEvaluation.evaluated_at,\n source: bundle\n ? \"org_policy_bundle\"\n : input.policyGuard.status !== \"ready\"\n ? \"policy_guard\"\n : \"request_default\",\n };\n }\n\n static toEvaluatePolicyGuard(input: unknown): EvaluateDecisionPolicyGuard | undefined {\n const record = asRecord(input);\n const status = asString(record.status);\n if (status !== \"ready\" && status !== \"configured\" && status !== \"missing\") return undefined;\n\n const reason = asString(record.reason);\n return {\n status,\n requires_manual_review:\n typeof record.requires_manual_review === \"boolean\" ? record.requires_manual_review : false,\n total_bundle_count: asNumber(record.total_bundle_count) ?? 0,\n active_bundle_count: asNumber(record.active_bundle_count) ?? 0,\n active_bundle_id: asString(record.active_bundle_id),\n active_bundle_version: asString(record.active_bundle_version),\n active_effective_from: asString(record.active_effective_from),\n active_effective_to: asString(record.active_effective_to),\n latest_bundle_id: asString(record.latest_bundle_id),\n latest_bundle_version: asString(record.latest_bundle_version),\n latest_effective_from: asString(record.latest_effective_from),\n latest_effective_to: asString(record.latest_effective_to),\n reason:\n reason === \"missing_org_policy_bundle\" || reason === \"no_active_org_policy_bundle\"\n ? reason\n : null,\n evaluated_at: asString(record.evaluated_at) ?? new Date().toISOString(),\n };\n }\n\n static toEvaluatePolicyEvaluation(input: unknown): EvaluateDecisionPolicyEvaluation | undefined {\n const record = asRecord(input);\n const resolution = asString(record.resolution);\n if (\n resolution !== \"policy_guard_blocked\" &&\n resolution !== \"matched_rule\" &&\n resolution !== \"no_matching_rule\"\n ) {\n return undefined;\n }\n\n const selectedRuleAction = parseEvaluateDecisionPolicyAction(record.selected_rule_action);\n const severity = parseEvaluateDecisionPolicySeverity(record.selected_rule_severity);\n return {\n resolution,\n bundle_id: asString(record.bundle_id),\n bundle_version: asString(record.bundle_version),\n evaluated_at: asString(record.evaluated_at) ?? new Date().toISOString(),\n decision_domain: asString(record.decision_domain) ?? \"UNKNOWN\",\n evaluated_rule_count: asNumber(record.evaluated_rule_count) ?? 0,\n matched_rule_count: asNumber(record.matched_rule_count) ?? 0,\n matched_rule_ids: Array.isArray(record.matched_rule_ids)\n ? record.matched_rule_ids\n .map((item) => asString(item))\n .filter((item): item is string => item != null)\n : [],\n selected_rule_id: asString(record.selected_rule_id),\n selected_rule_name: asString(record.selected_rule_name),\n selected_rule_action: selectedRuleAction,\n selected_rule_priority: asNumber(record.selected_rule_priority),\n selected_rule_rationale: asString(record.selected_rule_rationale),\n selected_rule_severity: severity,\n selected_rule_assignee_role: asString(record.selected_rule_assignee_role),\n selected_rule_sla_minutes: asNumber(record.selected_rule_sla_minutes),\n };\n }\n\n static toEvaluatePolicySnapshot(input: unknown): EvaluateDecisionPolicySnapshot | undefined {\n const record = asRecord(input);\n const policyVersion = asString(record.policy_version);\n const evaluatedAt = asString(record.evaluated_at);\n const source = asString(record.source);\n if (\n !policyVersion ||\n !evaluatedAt ||\n (source !== \"org_policy_bundle\" && source !== \"policy_guard\" && source !== \"request_default\")\n ) {\n return undefined;\n }\n\n return {\n policy_version: policyVersion,\n policy_bundle_id: asString(record.policy_bundle_id),\n rules_sha256: asString(record.rules_sha256),\n parameters_sha256: asString(record.parameters_sha256),\n effective_from: asString(record.effective_from),\n effective_to: asString(record.effective_to),\n evaluated_at: evaluatedAt,\n source,\n };\n }\n}\n\n/** Functional alias for {@link PolicyGraph.sortPolicyBundlesNewestFirst}. */\nexport function sortPolicyBundlesNewestFirst(\n left: PolicyBundleArtifactRow,\n right: PolicyBundleArtifactRow,\n): number {\n return PolicyGraph.sortPolicyBundlesNewestFirst(left, right);\n}\n\n/** Functional alias for {@link PolicyGraph.isPolicyBundleApproved}. */\nexport function isPolicyBundleApproved(bundle: PolicyBundleArtifactRow): boolean {\n return PolicyGraph.isPolicyBundleApproved(bundle);\n}\n\n/** Functional alias for {@link PolicyGraph.isPolicyBundleActive}. */\nexport function isPolicyBundleActive(\n bundle: PolicyBundleArtifactRow,\n evaluatedAtMs: number,\n): boolean {\n return PolicyGraph.isPolicyBundleActive(bundle, evaluatedAtMs);\n}\n\n/** Functional alias for {@link PolicyGraph.resolveEvaluateDecisionPolicyGuard}. */\nexport function resolveEvaluateDecisionPolicyGuard(input: {\n bundles: PolicyBundleArtifactRow[];\n evaluated_at: string;\n}): EvaluateDecisionPolicyGuard {\n return PolicyGraph.resolveEvaluateDecisionPolicyGuard(input);\n}\n\n/** Functional alias for {@link PolicyGraph.loadEvaluateDecisionPolicyGuard}. */\nexport function loadEvaluateDecisionPolicyGuard(input: {\n store: ProtocolStore;\n orgId: string;\n evaluated_at: string;\n limit?: number;\n}): Promise<EvaluateDecisionPolicyGuard> {\n return PolicyGraph.loadEvaluateDecisionPolicyGuard(input);\n}\n\n/** Functional alias for {@link PolicyGraph.resolveBlockedPolicyVersion}. */\nexport function resolveBlockedPolicyVersion(policyGuard: EvaluateDecisionPolicyGuard): string {\n return PolicyGraph.resolveBlockedPolicyVersion(policyGuard);\n}\n\n/** Functional alias for {@link PolicyGraph.parseEvaluateDecisionPolicyAction}. */\nexport function parseEvaluateDecisionPolicyAction(\n input: unknown,\n): EvaluateDecisionPolicyAction | null {\n return PolicyGraph.parseEvaluateDecisionPolicyAction(input);\n}\n\n/** Functional alias for {@link PolicyGraph.parseEvaluateDecisionPolicySeverity}. */\nexport function parseEvaluateDecisionPolicySeverity(\n input: unknown,\n): \"routine\" | \"elevated\" | \"urgent\" | null {\n return PolicyGraph.parseEvaluateDecisionPolicySeverity(input);\n}\n\n/** Functional alias for {@link PolicyGraph.parseEvaluateDecisionPolicyOperator}. */\nexport function parseEvaluateDecisionPolicyOperator(\n input: unknown,\n): EvaluateDecisionPolicyPredicateOperator | null {\n return PolicyGraph.parseEvaluateDecisionPolicyOperator(input);\n}\n\n/** Functional alias for {@link PolicyGraph.isEvaluateDecisionPolicyPredicate}. */\nexport function isEvaluateDecisionPolicyPredicate(\n record: Record<string, unknown>,\n): record is EvaluateDecisionPolicyPredicate {\n return PolicyGraph.isEvaluateDecisionPolicyPredicate(record);\n}\n\n/** Functional alias for {@link PolicyGraph.parseEvaluateDecisionPolicyConditionNode}. */\nexport function parseEvaluateDecisionPolicyConditionNode(\n input: unknown,\n): EvaluateDecisionPolicyConditionNode | null {\n return PolicyGraph.parseEvaluateDecisionPolicyConditionNode(input);\n}\n\n/** Functional alias for {@link PolicyGraph.parseEvaluateDecisionPolicyRule}. */\nexport function parseEvaluateDecisionPolicyRule(\n input: unknown,\n originalIndex: number,\n): EvaluateDecisionPolicyRule | null {\n return PolicyGraph.parseEvaluateDecisionPolicyRule(input, originalIndex);\n}\n\n/** Functional alias for {@link PolicyGraph.normalizeEvaluateDecisionPolicyText}. */\nexport function normalizeEvaluateDecisionPolicyText(value: unknown): string | null {\n return PolicyGraph.normalizeEvaluateDecisionPolicyText(value);\n}\n\n/** Functional alias for {@link PolicyGraph.parseEvaluateDecisionPolicyBoolean}. */\nexport function parseEvaluateDecisionPolicyBoolean(value: unknown): boolean | null {\n return PolicyGraph.parseEvaluateDecisionPolicyBoolean(value);\n}\n\n/** Functional alias for {@link PolicyGraph.areEvaluateDecisionPolicyValuesEqual}. */\nexport function areEvaluateDecisionPolicyValuesEqual(actual: unknown, expected: unknown): boolean {\n return PolicyGraph.areEvaluateDecisionPolicyValuesEqual(actual, expected);\n}\n\n/** Functional alias for {@link PolicyGraph.resolveEvaluateDecisionPolicyFactValue}. */\nexport function resolveEvaluateDecisionPolicyFactValue(\n facts: Record<string, unknown>,\n field: string,\n): unknown {\n return PolicyGraph.resolveEvaluateDecisionPolicyFactValue(facts, field);\n}\n\n/** Functional alias for {@link PolicyGraph.evaluateDecisionPolicyPredicate}. */\nexport function evaluateDecisionPolicyPredicate(\n predicate: EvaluateDecisionPolicyPredicate,\n facts: Record<string, unknown>,\n): boolean {\n return PolicyGraph.evaluateDecisionPolicyPredicate(predicate, facts);\n}\n\n/** Functional alias for {@link PolicyGraph.evaluateDecisionPolicyConditionNode}. */\nexport function evaluateDecisionPolicyConditionNode(\n node: EvaluateDecisionPolicyConditionNode,\n facts: Record<string, unknown>,\n): boolean {\n return PolicyGraph.evaluateDecisionPolicyConditionNode(node, facts);\n}\n\n/** Functional alias for {@link PolicyGraph.matchesEvaluateDecisionRuleDomain}. */\nexport function matchesEvaluateDecisionRuleDomain(\n ruleDomain: string,\n decisionDomain: string,\n): boolean {\n return PolicyGraph.matchesEvaluateDecisionRuleDomain(ruleDomain, decisionDomain);\n}\n\n/** Functional alias for {@link PolicyGraph.buildEvaluateDecisionPolicyFacts}. */\nexport function buildEvaluateDecisionPolicyFacts(input: {\n request: EvaluateDecisionRequest;\n decisionDomain: string;\n bundle: PolicyBundleArtifactRow;\n}): Record<string, unknown> {\n return PolicyGraph.buildEvaluateDecisionPolicyFacts(input);\n}\n\n/** Functional alias for {@link PolicyGraph.sortEvaluateDecisionPolicyRules}. */\nexport function sortEvaluateDecisionPolicyRules(\n left: EvaluateDecisionPolicyRule,\n right: EvaluateDecisionPolicyRule,\n): number {\n return PolicyGraph.sortEvaluateDecisionPolicyRules(left, right);\n}\n\n/** Functional alias for {@link PolicyGraph.evaluateDecisionPolicyGraph}. */\nexport function evaluateDecisionPolicyGraph(input: {\n bundle: PolicyBundleArtifactRow;\n request: EvaluateDecisionRequest;\n decision_domain: string;\n evaluated_at: string;\n}): EvaluateDecisionPolicyEvaluation {\n return PolicyGraph.evaluateDecisionPolicyGraph(input);\n}\n\n/** Functional alias for {@link PolicyGraph.resolveEvaluateDecisionOutcomeFromPolicyEvaluation}. */\nexport function resolveEvaluateDecisionOutcomeFromPolicyEvaluation(\n input: EvaluateDecisionPolicyEvaluation,\n): EvaluateDecisionOutcome {\n return PolicyGraph.resolveEvaluateDecisionOutcomeFromPolicyEvaluation(input);\n}\n\n/** Functional alias for {@link PolicyGraph.resolveEvaluateDecisionConfidenceFromPolicyEvaluation}. */\nexport function resolveEvaluateDecisionConfidenceFromPolicyEvaluation(\n input: EvaluateDecisionPolicyEvaluation,\n): number {\n return PolicyGraph.resolveEvaluateDecisionConfidenceFromPolicyEvaluation(input);\n}\n\n/** Functional alias for {@link PolicyGraph.loadEvaluateDecisionPolicyRuntime}. */\nexport function loadEvaluateDecisionPolicyRuntime(input: {\n store: ProtocolStore;\n orgId: string;\n evaluated_at: string;\n requested_policy_version?: string | null;\n limit?: number;\n}): Promise<ResolvedEvaluateDecisionPolicyRuntime> {\n return PolicyGraph.loadEvaluateDecisionPolicyRuntime(input);\n}\n\n/** Functional alias for {@link PolicyGraph.policyBundleParametersForSnapshot}. */\nexport function policyBundleParametersForSnapshot(\n bundle: PolicyBundleArtifactRow,\n): Record<string, unknown> {\n return PolicyGraph.policyBundleParametersForSnapshot(bundle);\n}\n\n/** Functional alias for {@link PolicyGraph.buildEvaluateDecisionPolicySnapshot}. */\nexport function buildEvaluateDecisionPolicySnapshot(input: {\n policyGuard: EvaluateDecisionPolicyGuard;\n policyEvaluation: EvaluateDecisionPolicyEvaluation;\n selectedBundle: PolicyBundleArtifactRow | null;\n responsePolicyVersion: string;\n}): EvaluateDecisionPolicySnapshot {\n return PolicyGraph.buildEvaluateDecisionPolicySnapshot(input);\n}\n\n/** Functional alias for {@link PolicyGraph.toEvaluatePolicyGuard}. */\nexport function toEvaluatePolicyGuard(input: unknown): EvaluateDecisionPolicyGuard | undefined {\n return PolicyGraph.toEvaluatePolicyGuard(input);\n}\n\n/** Functional alias for {@link PolicyGraph.toEvaluatePolicyEvaluation}. */\nexport function toEvaluatePolicyEvaluation(\n input: unknown,\n): EvaluateDecisionPolicyEvaluation | undefined {\n return PolicyGraph.toEvaluatePolicyEvaluation(input);\n}\n\n/** Functional alias for {@link PolicyGraph.toEvaluatePolicySnapshot}. */\nexport function toEvaluatePolicySnapshot(\n input: unknown,\n): EvaluateDecisionPolicySnapshot | undefined {\n return PolicyGraph.toEvaluatePolicySnapshot(input);\n}\n","import type { ProtocolStore } from \"../store/StoreContracts.js\";\nimport { PolicyGraph } from \"../policy-graph/PolicyGraph.js\";\nimport type {\n AgentBudgetPolicy,\n AgentModelRateCard,\n AgentProviderContract,\n AgentProvider,\n AgentTaskIntent,\n AgentTaskPolicyResolver,\n} from \"./AgentTaskContracts.js\";\n\n/** Resolves agent budget controls from the active organization policy bundle. */\nexport class PolicyGraphAgentTaskPolicyResolver implements AgentTaskPolicyResolver {\n constructor(private readonly store: ProtocolStore) {}\n\n async resolve(intent: AgentTaskIntent, now: Date): Promise<AgentBudgetPolicy | null> {\n const bundles = await this.store.listPolicyBundles({ orgId: intent.orgId, limit: 25 });\n const active = bundles\n .filter((bundle) => PolicyGraph.isPolicyBundleActive(bundle, now.getTime()))\n .sort(PolicyGraph.sortPolicyBundlesNewestFirst)[0];\n if (!active) return null;\n\n const payload = this.asRecord(active.payload);\n const metadata = this.asRecord(payload.metadata);\n const config = this.asRecord(payload.agentExecution ?? metadata.agentExecution);\n if (Object.keys(config).length === 0) return null;\n\n const defaults = this.asRecord(config.defaults);\n const users = this.asRecord(config.users);\n const user = this.asRecord(users[intent.userId]);\n if (config.providerContracts != null && !Array.isArray(config.providerContracts)) {\n return null;\n }\n const officialRateCards = Array.isArray(config.rateCards)\n ? config.rateCards\n .map((candidate) => this.parseRateCard(candidate, now))\n .filter((candidate): candidate is AgentModelRateCard => candidate != null)\n : [];\n const contracts = Array.isArray(config.providerContracts)\n ? config.providerContracts\n .map((candidate) => this.parseContract(candidate, now))\n .filter((candidate): candidate is AgentProviderContract => candidate != null)\n : [];\n const configuredForProvider = Array.isArray(config.providerContracts)\n ? config.providerContracts.some(\n (candidate) => this.provider(this.asRecord(candidate).provider) === intent.provider,\n )\n : false;\n const activeContract = contracts\n .filter((contract) => contract.provider === intent.provider)\n .sort((left, right) => right.effectiveFrom.localeCompare(left.effectiveFrom))[0];\n if (configuredForProvider && !activeContract) return null;\n const rateCards = activeContract\n ? [\n ...officialRateCards.filter((rateCard) => rateCard.provider !== intent.provider),\n ...activeContract.rateCards,\n ]\n : officialRateCards;\n const allowedProviders = Array.isArray(config.allowedProviders)\n ? config.allowedProviders\n .map((candidate) => this.provider(candidate))\n .filter((candidate): candidate is AgentProvider => candidate != null)\n : [];\n const allowedModels = Array.isArray(config.allowedModels)\n ? config.allowedModels.filter(\n (candidate): candidate is string =>\n typeof candidate === \"string\" && candidate.trim().length > 0,\n )\n : [];\n\n const orgMonthlyCapUsd = this.positiveNumber(config.orgMonthlyCapUsd);\n const userDailyCapUsd =\n this.positiveNumber(user.dailyCapUsd) ?? this.positiveNumber(defaults.userDailyCapUsd);\n const perRequestCapUsd =\n this.positiveNumber(user.perRequestCapUsd) ?? this.positiveNumber(defaults.perRequestCapUsd);\n if (\n orgMonthlyCapUsd == null ||\n userDailyCapUsd == null ||\n perRequestCapUsd == null ||\n rateCards.length === 0\n ) {\n return null;\n }\n\n return {\n policyId: active.bundle_id,\n version: active.version,\n mode: config.mode === \"SHADOW\" ? \"SHADOW\" : \"ENFORCEMENT\",\n orgMonthlyCapUsd,\n userDailyCapUsd,\n perRequestCapUsd,\n allowedProviders,\n allowedModels,\n reservationTtlSeconds: this.positiveInteger(config.reservationTtlSeconds) ?? 300,\n rateCards,\n };\n }\n\n private parseContract(input: unknown, now: Date): AgentProviderContract | null {\n const value = this.asRecord(input);\n const contractId = this.string(value.contractId);\n const version = this.string(value.version);\n const provider = this.provider(value.provider);\n const contractReference = this.string(value.contractReference);\n const status =\n value.status === \"DRAFT\" || value.status === \"APPROVED\" || value.status === \"REVOKED\"\n ? value.status\n : null;\n const authoredBy = this.string(value.authoredBy);\n const approvedBy = this.string(value.approvedBy);\n const approvedAt = this.instant(value.approvedAt);\n const effectiveFrom = this.instant(value.effectiveFrom);\n const expiresAt = this.instant(value.expiresAt);\n if (\n !contractId ||\n !version ||\n !provider ||\n !contractReference ||\n status !== \"APPROVED\" ||\n !authoredBy ||\n !approvedBy ||\n approvedBy.toLowerCase() === authoredBy.toLowerCase() ||\n !approvedAt ||\n !effectiveFrom ||\n (value.expiresAt != null && !expiresAt) ||\n approvedAt.getTime() > now.getTime() ||\n effectiveFrom.getTime() > now.getTime() ||\n (expiresAt &&\n (expiresAt.getTime() <= effectiveFrom.getTime() || expiresAt.getTime() <= now.getTime()))\n ) {\n return null;\n }\n const rateCards = Array.isArray(value.rateCards)\n ? value.rateCards\n .map((candidate) =>\n this.parseRateCard(candidate, now, {\n contractId,\n contractVersion: version,\n contractReference,\n provider,\n }),\n )\n .filter((candidate): candidate is AgentModelRateCard => candidate != null)\n : [];\n if (rateCards.length === 0) return null;\n return {\n contractId,\n version,\n provider,\n contractReference,\n status,\n authoredBy,\n approvedBy,\n approvedAt: approvedAt.toISOString(),\n effectiveFrom: effectiveFrom.toISOString(),\n expiresAt: expiresAt?.toISOString() ?? null,\n rateCards,\n };\n }\n\n private parseRateCard(\n input: unknown,\n now: Date,\n contract?: {\n contractId: string;\n contractVersion: string;\n contractReference: string;\n provider: AgentProvider;\n },\n ): AgentModelRateCard | null {\n const value = this.asRecord(input);\n const provider = this.provider(value.provider);\n const model = this.string(value.model);\n const inputRate = this.nonNegativeNumber(value.inputUsdPerMillionTokens);\n const outputRate = this.nonNegativeNumber(value.outputUsdPerMillionTokens);\n if (\n !provider ||\n (contract && provider !== contract.provider) ||\n (!contract && value.pricingBasis === \"NEGOTIATED_CONTRACT\") ||\n !model ||\n inputRate == null ||\n outputRate == null\n ) {\n return null;\n }\n const effectiveFrom = this.instant(value.effectiveFrom);\n const expiresAt = this.instant(value.expiresAt);\n if (value.effectiveFrom != null && !effectiveFrom) return null;\n if (value.expiresAt != null && !expiresAt) return null;\n if (effectiveFrom && effectiveFrom.getTime() > now.getTime()) return null;\n if (expiresAt && expiresAt.getTime() <= now.getTime()) return null;\n const pricingBasis = contract\n ? \"NEGOTIATED_CONTRACT\"\n : value.pricingBasis === \"NEGOTIATED_CONTRACT\"\n ? \"NEGOTIATED_CONTRACT\"\n : value.pricingBasis === \"OFFICIAL_LIST_PRICE\"\n ? \"OFFICIAL_LIST_PRICE\"\n : undefined;\n return {\n provider,\n model,\n ...(pricingBasis ? { pricingBasis } : {}),\n sourceUrl: contract ? null : this.string(value.sourceUrl),\n contractId: contract?.contractId ?? null,\n contractVersion: contract?.contractVersion ?? null,\n contractReference: contract?.contractReference ?? null,\n effectiveFrom: effectiveFrom?.toISOString() ?? null,\n expiresAt: expiresAt?.toISOString() ?? null,\n inputUsdPerMillionTokens: inputRate,\n outputUsdPerMillionTokens: outputRate,\n cachedInputUsdPerMillionTokens: this.nonNegativeNumber(value.cachedInputUsdPerMillionTokens),\n cacheCreationUsdPerMillionTokens: this.nonNegativeNumber(\n value.cacheCreationUsdPerMillionTokens,\n ),\n cacheCreationOneHourUsdPerMillionTokens: this.nonNegativeNumber(\n value.cacheCreationOneHourUsdPerMillionTokens,\n ),\n longContextThresholdTokens: this.positiveInteger(value.longContextThresholdTokens),\n longContextInputUsdPerMillionTokens: this.nonNegativeNumber(\n value.longContextInputUsdPerMillionTokens,\n ),\n longContextOutputUsdPerMillionTokens: this.nonNegativeNumber(\n value.longContextOutputUsdPerMillionTokens,\n ),\n longContextCachedInputUsdPerMillionTokens: this.nonNegativeNumber(\n value.longContextCachedInputUsdPerMillionTokens,\n ),\n longContextCacheCreationUsdPerMillionTokens: this.nonNegativeNumber(\n value.longContextCacheCreationUsdPerMillionTokens,\n ),\n toolCallUsd: this.nonNegativeNumber(value.toolCallUsd) ?? 0,\n };\n }\n\n private asRecord(value: unknown): Record<string, unknown> {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return {};\n return value as Record<string, unknown>;\n }\n\n private string(value: unknown): string | null {\n return typeof value === \"string\" && value.trim() ? value.trim() : null;\n }\n\n private provider(value: unknown): AgentProvider | null {\n return value === \"openai\" ||\n value === \"anthropic\" ||\n value === \"github_copilot\" ||\n value === \"custom\"\n ? value\n : null;\n }\n\n private positiveNumber(value: unknown): number | null {\n return typeof value === \"number\" && Number.isFinite(value) && value > 0 ? value : null;\n }\n\n private nonNegativeNumber(value: unknown): number | null {\n return typeof value === \"number\" && Number.isFinite(value) && value >= 0 ? value : null;\n }\n\n private positiveInteger(value: unknown): number | null {\n return typeof value === \"number\" && Number.isSafeInteger(value) && value > 0 ? value : null;\n }\n\n private instant(value: unknown): Date | null {\n if (typeof value !== \"string\" || !value.trim()) return null;\n const parsed = new Date(value);\n return Number.isNaN(parsed.getTime()) ? null : parsed;\n }\n}\n\n/** Injectable resolver for embedded runtimes and isolated tests. */\nexport class StaticAgentTaskPolicyResolver implements AgentTaskPolicyResolver {\n constructor(private readonly policy: AgentBudgetPolicy | null) {}\n\n async resolve(): Promise<AgentBudgetPolicy | null> {\n return this.policy;\n }\n}\n","import { randomUUID } from \"node:crypto\";\nimport type {\n AgentTaskReleaseInput,\n AgentTaskReservation,\n AgentTaskReservationStore,\n AgentTaskStoreReserveInput,\n AgentTaskStoreReserveResult,\n AgentTokenUsage,\n} from \"./AgentTaskContracts.js\";\n\n/** Atomic, single-process reservation ledger used by tests and embedded protocol hosts. */\nexport class MemoryAgentTaskReservationStore implements AgentTaskReservationStore {\n private readonly reservations = new Map<string, AgentTaskReservation>();\n private readonly idempotencyIndex = new Map<string, string>();\n\n async reserve(input: AgentTaskStoreReserveInput): Promise<AgentTaskStoreReserveResult> {\n const idempotencyKey = `${input.intent.orgId}:${input.intent.idempotencyKey}`;\n const existingId = this.idempotencyIndex.get(idempotencyKey);\n const existing = existingId ? this.reservations.get(existingId) : null;\n if (existing) {\n if (existing.intentHash !== input.intentHash) {\n return {\n outcome: \"conflict\",\n reasonCodes: [\"IDEMPOTENCY_KEY_REUSED\"],\n reservation: null,\n };\n }\n return {\n outcome: \"idempotent\",\n reasonCodes: existing.reasonCodes,\n reservation: this.view(existing, input.now),\n };\n }\n\n const capReasons = this.capReasons(input);\n if (input.enforceLimits && capReasons.length > 0) {\n return { outcome: \"blocked\", reasonCodes: capReasons, reservation: null };\n }\n\n const nowIso = input.now.toISOString();\n const reasonCodes = [\n ...input.reasonCodes,\n ...capReasons,\n ...(capReasons.length > 0 ? [\"SHADOW_POLICY_BREACH\"] : []),\n \"TASK_BUDGET_RESERVED\",\n ];\n const reservation: AgentTaskReservation = {\n reservationId: randomUUID(),\n orgId: input.intent.orgId,\n userId: input.intent.userId,\n provider: input.intent.provider,\n model: input.intent.model,\n sessionId: input.intent.sessionId,\n idempotencyKey: input.intent.idempotencyKey,\n intentHash: input.intentHash,\n status: \"RESERVED\",\n reservedCostUsd: input.projection.projectedCostUsd,\n actualCostUsd: null,\n projectedUsage: this.usage(input.projection),\n actualUsage: null,\n rateCard: input.projection.rateCard,\n downstreamTarget: input.intent.downstreamTarget,\n policyId: input.policy.policyId,\n policyVersion: input.policy.version,\n reasonCodes: [...new Set(reasonCodes)],\n expiresAt: new Date(\n input.now.getTime() + input.policy.reservationTtlSeconds * 1000,\n ).toISOString(),\n createdAt: nowIso,\n grantIssuedAt: null,\n reconciledAt: null,\n releasedAt: null,\n };\n this.reservations.set(reservation.reservationId, reservation);\n this.idempotencyIndex.set(idempotencyKey, reservation.reservationId);\n return { outcome: \"reserved\", reasonCodes: reservation.reasonCodes, reservation };\n }\n\n async get(input: {\n reservationId: string;\n orgId: string;\n now: Date;\n }): Promise<AgentTaskReservation | null> {\n const reservation = this.reservations.get(input.reservationId);\n if (!reservation || reservation.orgId !== input.orgId) return null;\n return this.view(reservation, input.now);\n }\n\n async reconcile(input: {\n reservationId: string;\n orgId: string;\n usage: AgentTokenUsage;\n actualCostUsd: number;\n now: Date;\n }): Promise<AgentTaskReservation | null> {\n const reservation = this.reservations.get(input.reservationId);\n if (!reservation || reservation.orgId !== input.orgId) return null;\n if (reservation.status === \"RECONCILED\") return reservation;\n if (reservation.status === \"RELEASED\") return null;\n\n reservation.status = \"RECONCILED\";\n reservation.actualUsage = this.usage(input.usage);\n reservation.actualCostUsd = input.actualCostUsd;\n reservation.reconciledAt = input.now.toISOString();\n reservation.reasonCodes = [\n ...reservation.reasonCodes,\n ...(input.actualCostUsd > reservation.reservedCostUsd\n ? [\"RESERVATION_UNDERESTIMATED\"]\n : [\"UNUSED_BUDGET_RELEASED\"]),\n \"TASK_USAGE_RECONCILED\",\n ];\n return reservation;\n }\n\n async claimGrant(input: { reservationId: string; orgId: string; now: Date }): Promise<boolean> {\n const reservation = this.reservations.get(input.reservationId);\n if (\n !reservation ||\n reservation.orgId !== input.orgId ||\n reservation.status !== \"RESERVED\" ||\n reservation.grantIssuedAt != null ||\n Date.parse(reservation.expiresAt) <= input.now.getTime()\n ) {\n return false;\n }\n reservation.grantIssuedAt = input.now.toISOString();\n return true;\n }\n\n async release(\n input: AgentTaskReleaseInput & { now: Date },\n ): Promise<AgentTaskReservation | null> {\n const reservation = this.reservations.get(input.reservationId);\n if (!reservation || reservation.orgId !== input.orgId) return null;\n if (reservation.status === \"RELEASED\") return reservation;\n if (reservation.status === \"RECONCILED\") return null;\n reservation.status = \"RELEASED\";\n reservation.releasedAt = input.now.toISOString();\n reservation.reasonCodes = [...reservation.reasonCodes, \"TASK_BUDGET_RELEASED\", input.reason];\n return reservation;\n }\n\n private capReasons(input: AgentTaskStoreReserveInput): string[] {\n const nowMs = input.now.getTime();\n const monthStart = Date.UTC(input.now.getUTCFullYear(), input.now.getUTCMonth(), 1);\n const dayStart = Date.UTC(\n input.now.getUTCFullYear(),\n input.now.getUTCMonth(),\n input.now.getUTCDate(),\n );\n let orgCommitted = 0;\n let userCommitted = 0;\n for (const reservation of this.reservations.values()) {\n if (reservation.orgId !== input.intent.orgId) continue;\n const createdAt = Date.parse(reservation.createdAt);\n const committed = this.committedCost(reservation, nowMs);\n if (createdAt >= monthStart) orgCommitted += committed;\n if (reservation.userId === input.intent.userId && createdAt >= dayStart) {\n userCommitted += committed;\n }\n }\n\n const reasons: string[] = [];\n if (orgCommitted + input.projection.projectedCostUsd > input.policy.orgMonthlyCapUsd) {\n reasons.push(\"ORG_MONTHLY_BUDGET_EXCEEDED\");\n }\n if (userCommitted + input.projection.projectedCostUsd > input.policy.userDailyCapUsd) {\n reasons.push(\"USER_DAILY_BUDGET_EXCEEDED\");\n }\n return reasons;\n }\n\n private committedCost(reservation: AgentTaskReservation, nowMs: number): number {\n if (reservation.status === \"RECONCILED\") return reservation.actualCostUsd ?? 0;\n if (reservation.status === \"RESERVED\" && Date.parse(reservation.expiresAt) > nowMs) {\n return reservation.reservedCostUsd;\n }\n return 0;\n }\n\n private view(reservation: AgentTaskReservation, now: Date): AgentTaskReservation {\n if (reservation.status === \"RESERVED\" && Date.parse(reservation.expiresAt) <= now.getTime()) {\n return { ...reservation, status: \"EXPIRED\" };\n }\n return reservation;\n }\n\n private usage(input: AgentTokenUsage): AgentTokenUsage {\n return {\n inputTokens: input.inputTokens,\n outputTokens: input.outputTokens,\n cachedInputTokens: input.cachedInputTokens,\n cacheCreationInputTokens: input.cacheCreationInputTokens,\n cacheCreationOneHourInputTokens: input.cacheCreationOneHourInputTokens,\n toolCalls: input.toolCalls,\n };\n }\n}\n\nexport function createMemoryAgentTaskReservationStore(): AgentTaskReservationStore {\n return new MemoryAgentTaskReservationStore();\n}\n","import type {\n AgentBudgetPolicy,\n AgentModelRateCard,\n AgentTaskIntent,\n AgentTaskProjection,\n AgentTokenUsage,\n} from \"./AgentTaskContracts.js\";\n\nconst TOKENS_PER_MILLION = 1_000_000;\n\n/** Conservative task projection and provider-usage reconciliation. */\nexport class AgentTaskCostEstimator {\n project(intent: AgentTaskIntent, policy: AgentBudgetPolicy): AgentTaskProjection | null {\n const rateCard = this.resolveRateCard(intent, policy);\n if (!rateCard) return null;\n\n const inputTokens =\n intent.prompt.estimatedInputTokens ?? Math.max(1, intent.prompt.characterCount ?? 0);\n const usage: AgentTokenUsage = {\n inputTokens,\n outputTokens: intent.limits.maxOutputTokens,\n cachedInputTokens: 0,\n cacheCreationInputTokens: 0,\n cacheCreationOneHourInputTokens: 0,\n toolCalls: intent.limits.estimatedToolCalls,\n };\n return {\n ...usage,\n projectedCostUsd: this.cost(usage, rateCard),\n rateCard,\n };\n }\n\n actualCost(usage: AgentTokenUsage, rateCard: AgentModelRateCard): number {\n return this.cost(usage, rateCard);\n }\n\n private cost(usage: AgentTokenUsage, rateCard: AgentModelRateCard): number {\n const rates = this.rates(usage, rateCard);\n const cachedInputTokens =\n rateCard.provider === \"anthropic\"\n ? usage.cachedInputTokens\n : Math.min(usage.cachedInputTokens, usage.inputTokens);\n const cacheCreationInputTokens =\n rateCard.provider === \"anthropic\"\n ? usage.cacheCreationInputTokens\n : Math.min(\n usage.cacheCreationInputTokens,\n Math.max(0, usage.inputTokens - cachedInputTokens),\n );\n const uncachedInputTokens =\n rateCard.provider === \"anthropic\"\n ? usage.inputTokens\n : Math.max(0, usage.inputTokens - cachedInputTokens - cacheCreationInputTokens);\n const oneHourCacheCreationTokens = Math.min(\n usage.cacheCreationOneHourInputTokens,\n cacheCreationInputTokens,\n );\n const fiveMinuteCacheCreationTokens = cacheCreationInputTokens - oneHourCacheCreationTokens;\n const cachedInputRate = rates.cachedInputUsdPerMillionTokens ?? rates.inputUsdPerMillionTokens;\n const cacheCreationRate =\n rates.cacheCreationUsdPerMillionTokens ?? rates.inputUsdPerMillionTokens;\n const oneHourCacheCreationRate =\n rateCard.cacheCreationOneHourUsdPerMillionTokens ?? cacheCreationRate;\n const total =\n (uncachedInputTokens * rates.inputUsdPerMillionTokens) / TOKENS_PER_MILLION +\n (cachedInputTokens * cachedInputRate) / TOKENS_PER_MILLION +\n (fiveMinuteCacheCreationTokens * cacheCreationRate) / TOKENS_PER_MILLION +\n (oneHourCacheCreationTokens * oneHourCacheCreationRate) / TOKENS_PER_MILLION +\n (usage.outputTokens * rates.outputUsdPerMillionTokens) / TOKENS_PER_MILLION +\n usage.toolCalls * rateCard.toolCallUsd;\n return Math.round((total + Number.EPSILON) * 1_000_000) / 1_000_000;\n }\n\n private rates(usage: AgentTokenUsage, rateCard: AgentModelRateCard) {\n const useLongContext =\n rateCard.longContextThresholdTokens != null &&\n usage.inputTokens > rateCard.longContextThresholdTokens;\n if (!useLongContext) return rateCard;\n return {\n inputUsdPerMillionTokens:\n rateCard.longContextInputUsdPerMillionTokens ?? rateCard.inputUsdPerMillionTokens,\n outputUsdPerMillionTokens:\n rateCard.longContextOutputUsdPerMillionTokens ?? rateCard.outputUsdPerMillionTokens,\n cachedInputUsdPerMillionTokens:\n rateCard.longContextCachedInputUsdPerMillionTokens ??\n rateCard.cachedInputUsdPerMillionTokens,\n cacheCreationUsdPerMillionTokens:\n rateCard.longContextCacheCreationUsdPerMillionTokens ??\n rateCard.cacheCreationUsdPerMillionTokens,\n };\n }\n\n private resolveRateCard(\n intent: AgentTaskIntent,\n policy: AgentBudgetPolicy,\n ): AgentModelRateCard | null {\n return (\n policy.rateCards.find(\n (candidate) => candidate.provider === intent.provider && candidate.model === intent.model,\n ) ??\n policy.rateCards.find(\n (candidate) => candidate.provider === intent.provider && candidate.model === \"*\",\n ) ??\n null\n );\n }\n}\n","import { createHash } from \"node:crypto\";\nimport type {\n AgentProvider,\n AgentTaskIntent,\n AgentTaskTarget,\n AgentTokenUsage,\n} from \"./AgentTaskContracts.js\";\nimport { canonicalize } from \"../execution-gating/ExecutionGatingSupport.js\";\n\n/** Validates wire payloads and keeps raw prompt content outside the reservation contract. */\nexport class AgentTaskIntentParser {\n static parse(\n input: unknown,\n ): { ok: true; value: AgentTaskIntent } | { ok: false; message: string } {\n const value = AgentTaskIntentParser.asRecord(input);\n const prompt = AgentTaskIntentParser.asRecord(value.prompt);\n const limits = AgentTaskIntentParser.asRecord(value.limits);\n const target = AgentTaskIntentParser.asRecord(value.downstreamTarget);\n const provider = AgentTaskIntentParser.provider(value.provider);\n const orgId = AgentTaskIntentParser.string(value.orgId);\n const userId = AgentTaskIntentParser.string(value.userId);\n const model = AgentTaskIntentParser.string(value.model);\n const sessionId = AgentTaskIntentParser.string(value.sessionId);\n const idempotencyKey = AgentTaskIntentParser.string(value.idempotencyKey);\n const downstreamTarget = AgentTaskIntentParser.target(target);\n if (!orgId || !userId || !provider || !model || !sessionId || !idempotencyKey) {\n return {\n ok: false,\n message: \"orgId, userId, provider, model, sessionId, and idempotencyKey are required\",\n };\n }\n if (!downstreamTarget) {\n return {\n ok: false,\n message: \"downstreamTarget.system, operation, and endpoint are required\",\n };\n }\n\n const maxOutputTokens = AgentTaskIntentParser.integer(limits.maxOutputTokens);\n const estimatedToolCalls = AgentTaskIntentParser.integer(limits.estimatedToolCalls) ?? 0;\n const characterCount = AgentTaskIntentParser.integer(prompt.characterCount);\n const estimatedInputTokens = AgentTaskIntentParser.integer(prompt.estimatedInputTokens);\n if (maxOutputTokens == null || maxOutputTokens < 1) {\n return { ok: false, message: \"limits.maxOutputTokens must be a positive integer\" };\n }\n if (estimatedToolCalls < 0) {\n return { ok: false, message: \"limits.estimatedToolCalls cannot be negative\" };\n }\n if (characterCount == null && estimatedInputTokens == null) {\n return {\n ok: false,\n message: \"prompt.characterCount or prompt.estimatedInputTokens is required\",\n };\n }\n\n return {\n ok: true,\n value: {\n orgId,\n userId,\n provider,\n model,\n sessionId,\n idempotencyKey,\n prompt: {\n sha256: AgentTaskIntentParser.string(prompt.sha256),\n characterCount,\n estimatedInputTokens,\n },\n limits: {\n maxOutputTokens,\n estimatedToolCalls,\n },\n downstreamTarget,\n metadata: AgentTaskIntentParser.asRecord(value.metadata),\n },\n };\n }\n\n static parseUsage(input: unknown): AgentTokenUsage | null {\n const value = AgentTaskIntentParser.asRecord(input);\n const inputTokens = AgentTaskIntentParser.integer(value.inputTokens);\n const outputTokens = AgentTaskIntentParser.integer(value.outputTokens);\n if (inputTokens == null || outputTokens == null) return null;\n return {\n inputTokens,\n outputTokens,\n cachedInputTokens: AgentTaskIntentParser.integer(value.cachedInputTokens) ?? 0,\n cacheCreationInputTokens: AgentTaskIntentParser.integer(value.cacheCreationInputTokens) ?? 0,\n cacheCreationOneHourInputTokens:\n AgentTaskIntentParser.integer(value.cacheCreationOneHourInputTokens) ?? 0,\n toolCalls: AgentTaskIntentParser.integer(value.toolCalls) ?? 0,\n };\n }\n\n static hash(intent: AgentTaskIntent): string {\n return createHash(\"sha256\")\n .update(JSON.stringify(canonicalize(intent)))\n .digest(\"hex\");\n }\n\n private static target(input: Record<string, unknown>): AgentTaskTarget | null {\n const system = AgentTaskIntentParser.string(input.system);\n const operation = AgentTaskIntentParser.string(input.operation);\n const endpoint = AgentTaskIntentParser.string(input.endpoint);\n return system && operation && endpoint ? { system, operation, endpoint } : null;\n }\n\n private static provider(value: unknown): AgentProvider | null {\n return value === \"openai\" ||\n value === \"anthropic\" ||\n value === \"github_copilot\" ||\n value === \"custom\"\n ? value\n : null;\n }\n\n private static asRecord(value: unknown): Record<string, unknown> {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return {};\n return value as Record<string, unknown>;\n }\n\n private static string(value: unknown): string | null {\n return typeof value === \"string\" && value.trim() ? value.trim() : null;\n }\n\n private static integer(value: unknown): number | null {\n return typeof value === \"number\" && Number.isSafeInteger(value) && value >= 0 ? value : null;\n }\n}\n","import type {\n TokenVerificationResult,\n VerifyTokenInput,\n} from \"../execution-gating/ExecutionGatingContracts.js\";\nimport type { ExecutionGatingService } from \"../execution-gating/ExecutionGatingService.js\";\nimport type {\n AgentTaskGatewayOptions,\n AgentTaskIntent,\n AgentTaskPolicyResolver,\n AgentTaskReconcileInput,\n AgentTaskReleaseInput,\n AgentTaskReservation,\n AgentTaskReservationStore,\n AgentTaskReserveResult,\n} from \"./AgentTaskContracts.js\";\nimport { AgentTaskCostEstimator } from \"./AgentTaskCostEstimator.js\";\nimport { AgentTaskIntentParser } from \"./AgentTaskIntentParser.js\";\n\n/** Orchestrates pre-prompt reservation and binds it to one downstream execution grant. */\nexport class AgentTaskGatewayService {\n private readonly now: () => Date;\n\n constructor(\n private readonly store: AgentTaskReservationStore,\n private readonly policyResolver: AgentTaskPolicyResolver,\n private readonly authority: ExecutionGatingService,\n private readonly estimator = new AgentTaskCostEstimator(),\n options: AgentTaskGatewayOptions = {},\n ) {\n this.now = options.now ?? (() => new Date());\n }\n\n async reserve(intent: AgentTaskIntent): Promise<AgentTaskReserveResult> {\n const now = this.now();\n const policy = await this.policyResolver.resolve(intent, now);\n if (!policy) return this.blocked(\"AGENT_BUDGET_POLICY_NOT_CONFIGURED\");\n\n const reasonCodes: string[] = [];\n if (policy.allowedProviders.length > 0 && !policy.allowedProviders.includes(intent.provider)) {\n reasonCodes.push(\"PROVIDER_NOT_ALLOWED\");\n }\n if (\n policy.allowedModels.length > 0 &&\n !policy.allowedModels.some((pattern) => this.matches(pattern, intent.model))\n ) {\n reasonCodes.push(\"MODEL_NOT_ALLOWED\");\n }\n\n const projection = this.estimator.project(intent, policy);\n if (!projection) reasonCodes.push(\"MODEL_RATE_CARD_MISSING\");\n if (projection && projection.projectedCostUsd > policy.perRequestCapUsd) {\n reasonCodes.push(\"PER_REQUEST_BUDGET_EXCEEDED\");\n }\n if (policy.mode === \"ENFORCEMENT\" && reasonCodes.length > 0) {\n return this.blocked(...reasonCodes);\n }\n if (!projection) return this.blocked(...reasonCodes);\n\n const stored = await this.store.reserve({\n intent,\n intentHash: AgentTaskIntentParser.hash(intent),\n projection,\n policy,\n reasonCodes,\n enforceLimits: policy.mode === \"ENFORCEMENT\",\n now,\n });\n if (!stored.reservation || stored.outcome === \"blocked\" || stored.outcome === \"conflict\") {\n return this.blocked(...stored.reasonCodes);\n }\n if (stored.reservation.status !== \"RESERVED\") {\n return this.blocked(`RESERVATION_${stored.reservation.status}`);\n }\n const claimed = await this.store.claimGrant({\n reservationId: stored.reservation.reservationId,\n orgId: stored.reservation.orgId,\n now,\n });\n if (!claimed) return this.blocked(\"BOUNDARY_GRANT_ALREADY_ISSUED\");\n stored.reservation.grantIssuedAt = now.toISOString();\n\n const decision = this.authority.enforceAndBind(\n this.authorityRequest(stored.reservation, intent),\n );\n if (!decision.should_execute || !decision.execution_token) {\n await this.store.release({\n reservationId: stored.reservation.reservationId,\n orgId: stored.reservation.orgId,\n reason: \"BOUNDARY_GRANT_NOT_ISSUED\",\n now,\n });\n return this.blocked(\"BOUNDARY_GRANT_NOT_ISSUED\", ...decision.reason_codes);\n }\n return {\n allowed: true,\n reasonCodes: stored.reasonCodes,\n reservation: stored.reservation,\n executionToken: decision.execution_token,\n executionTokenExpiresAt: decision.execution_token_expires_at,\n };\n }\n\n async get(reservationId: string, orgId: string): Promise<AgentTaskReservation | null> {\n return this.store.get({ reservationId, orgId, now: this.now() });\n }\n\n verifyEgress(reservation: AgentTaskReservation, executionToken: string): TokenVerificationResult {\n return this.authority.verifyToken(this.grantInput(reservation, executionToken));\n }\n\n consumeBoundaryGrant(\n reservation: AgentTaskReservation,\n executionToken: string,\n ): TokenVerificationResult {\n return this.authority.consumeToken(this.grantInput(reservation, executionToken));\n }\n\n async reconcile(input: AgentTaskReconcileInput): Promise<AgentTaskReservation | null> {\n const reservation = await this.get(input.reservationId, input.orgId);\n if (!reservation) return null;\n const actualCostUsd = this.estimator.actualCost(input.usage, reservation.rateCard);\n return this.store.reconcile({\n reservationId: input.reservationId,\n orgId: input.orgId,\n usage: input.usage,\n actualCostUsd,\n now: this.now(),\n });\n }\n\n async release(input: AgentTaskReleaseInput): Promise<AgentTaskReservation | null> {\n return this.store.release({ ...input, now: this.now() });\n }\n\n private authorityRequest(reservation: AgentTaskReservation, intent: AgentTaskIntent) {\n return {\n tenant_id: reservation.orgId,\n correlation_id: intent.sessionId,\n idempotency_key: `agent-reservation:${reservation.reservationId}`,\n mode: \"ENFORCE\" as const,\n actor: {\n id: reservation.userId,\n type: \"AI_AGENT\",\n runtime: typeof intent.metadata.host === \"string\" ? intent.metadata.host : intent.provider,\n trust_level: \"managed\",\n },\n action: {\n type: \"FORWARD_AGENT_TASK\",\n resource: `model:${reservation.provider}:${reservation.model}`,\n amount: reservation.reservedCostUsd,\n currency: \"USD\",\n payload_hash: reservation.intentHash,\n },\n context: {\n reservation_id: reservation.reservationId,\n policy_id: reservation.policyId,\n policy_version: reservation.policyVersion,\n source: \"agent_task_gateway\",\n },\n policy_refs: [reservation.policyId],\n downstream_target: {\n system: reservation.downstreamTarget.system,\n operation: reservation.downstreamTarget.operation,\n endpoint: reservation.downstreamTarget.endpoint,\n },\n };\n }\n\n private grantInput(reservation: AgentTaskReservation, executionToken: string): VerifyTokenInput {\n return {\n execution_token: executionToken,\n actor_id: reservation.userId,\n actor_type: \"AI_AGENT\",\n action_type: \"FORWARD_AGENT_TASK\",\n resource: `model:${reservation.provider}:${reservation.model}`,\n amount: reservation.reservedCostUsd,\n currency: \"USD\",\n downstream_target: {\n system: reservation.downstreamTarget.system,\n operation: reservation.downstreamTarget.operation,\n endpoint: reservation.downstreamTarget.endpoint,\n },\n };\n }\n\n private matches(pattern: string, model: string): boolean {\n if (pattern === \"*\") return true;\n if (!pattern.includes(\"*\")) return pattern === model;\n const escaped = pattern.replace(/[.+?^${}()|[\\]\\\\]/g, \"\\\\$&\").replace(/\\*/g, \".*\");\n return new RegExp(`^${escaped}$`).test(model);\n }\n\n private blocked(...reasonCodes: string[]): AgentTaskReserveResult {\n return {\n allowed: false,\n reasonCodes: [...new Set(reasonCodes)],\n reservation: null,\n executionToken: null,\n executionTokenExpiresAt: null,\n };\n }\n}\n","import { timingSafeEqual } from \"node:crypto\";\nimport type { FastifyRequest } from \"fastify\";\nimport {\n hasAnyScope,\n type ProtocolMcpAuthContext,\n type ProtocolMcpAuthLookup,\n} from \"../auth/McpAuth.js\";\n\nexport type AgentGatewayAuthResult =\n | { ok: true; context: ProtocolMcpAuthContext }\n | { ok: false; statusCode: 401 | 403; message: string };\n\n/** Authenticates the separate Decionis runtime key without consuming provider credentials. */\nexport class AgentGatewayAuthGuard {\n constructor(\n private readonly lookup: ProtocolMcpAuthLookup | null,\n private readonly env: NodeJS.ProcessEnv = process.env,\n ) {}\n\n async authenticate(req: FastifyRequest, orgId: string): Promise<AgentGatewayAuthResult> {\n const rawHeader = req.headers[\"x-decionis-api-key\"];\n const providedKey =\n typeof rawHeader === \"string\"\n ? rawHeader.trim()\n : Array.isArray(rawHeader)\n ? rawHeader[0]?.trim()\n : null;\n const breakglassKey =\n this.env.DECIONIS_AGENT_GATEWAY_API_KEY?.trim() ??\n this.env.DECIONIS_PROTOCOL_MCP_API_KEY?.trim() ??\n null;\n\n let context: ProtocolMcpAuthContext | null = null;\n if (providedKey && breakglassKey && this.safeEqual(providedKey, breakglassKey)) {\n context = { kind: \"breakglass\", source: \"env_api_key\" };\n } else if (providedKey && this.lookup) {\n context = await this.lookup(providedKey);\n } else if (!breakglassKey && !this.lookup) {\n context = { kind: \"breakglass\", source: \"env_api_key\" };\n }\n if (!context) {\n return { ok: false, statusCode: 401, message: \"Valid Decionis runtime key required\" };\n }\n if (context.kind === \"org_api_key\") {\n if (context.org_id !== orgId) {\n return {\n ok: false,\n statusCode: 403,\n message: \"Runtime key is not authorized for this organization\",\n };\n }\n if (\n !hasAnyScope(context.scopes, [\n \"agent:execute\",\n \"agent:*\",\n \"decision:run\",\n \"decision:*\",\n \"org:*\",\n ])\n ) {\n return {\n ok: false,\n statusCode: 403,\n message: \"Runtime key is missing the agent execution scope\",\n };\n }\n }\n return { ok: true, context };\n }\n\n private safeEqual(left: string, right: string): boolean {\n const leftBuffer = Buffer.from(left);\n const rightBuffer = Buffer.from(right);\n return leftBuffer.length === rightBuffer.length && timingSafeEqual(leftBuffer, rightBuffer);\n }\n}\n","import type { FastifyReply } from \"fastify\";\nimport type { AgentTaskGatewayService } from \"./AgentTaskGatewayService.js\";\nimport type { AgentTaskReserveResult, AgentTokenUsage } from \"./AgentTaskContracts.js\";\nimport type { AgentProviderAdapter } from \"./providers/AgentProviderAdapter.js\";\n\ntype FetchLike = typeof fetch;\n\nexport interface AgentProviderProxyOptions {\n fetchImpl?: FetchLike;\n upstreamBaseUrls?: Partial<Record<\"openai\" | \"anthropic\", string>>;\n}\n\n/** Forwards only to fixed provider endpoints and reconciles normalized response usage. */\nexport class AgentProviderProxy {\n private readonly fetchImpl: FetchLike;\n private readonly upstreamBaseUrls: Record<\"openai\" | \"anthropic\", string>;\n\n constructor(\n private readonly gateway: AgentTaskGatewayService,\n options: AgentProviderProxyOptions = {},\n ) {\n this.fetchImpl = options.fetchImpl ?? fetch;\n this.upstreamBaseUrls = {\n openai: options.upstreamBaseUrls?.openai ?? \"https://api.openai.com\",\n anthropic: options.upstreamBaseUrls?.anthropic ?? \"https://api.anthropic.com\",\n };\n }\n\n upstreamUrl(adapter: AgentProviderAdapter): string | null {\n if (adapter.provider !== \"openai\" && adapter.provider !== \"anthropic\") return null;\n const baseUrl = this.upstreamBaseUrls[adapter.provider].replace(/\\/+$/, \"\");\n return `${baseUrl}${adapter.upstreamPath}`;\n }\n\n async forward(input: {\n adapter: AgentProviderAdapter;\n providerBody: unknown;\n requestHeaders: Record<string, unknown>;\n reservation: AgentTaskReserveResult;\n reply: FastifyReply;\n }): Promise<unknown> {\n const { reservation, executionToken } = input.reservation;\n if (!reservation || !executionToken) {\n return input.reply.code(403).send({\n error: \"AGENT_TASK_NOT_AUTHORIZED\",\n reasonCodes: input.reservation.reasonCodes,\n });\n }\n const grant = this.gateway.consumeBoundaryGrant(reservation, executionToken);\n if (!grant.valid) {\n await this.gateway.release({\n reservationId: reservation.reservationId,\n orgId: reservation.orgId,\n reason: \"BOUNDARY_GRANT_REJECTED\",\n });\n return input.reply.code(403).send({\n error: \"NO_VALID_DECIONIS_AUTHORITY\",\n reasonCodes: grant.reason_codes,\n });\n }\n\n const upstreamUrl = this.upstreamUrl(input.adapter);\n if (!upstreamUrl) {\n await this.gateway.release({\n reservationId: reservation.reservationId,\n orgId: reservation.orgId,\n reason: \"PROVIDER_PROXY_UNAVAILABLE\",\n });\n return input.reply.code(400).send({ error: \"PROVIDER_PROXY_UNAVAILABLE\" });\n }\n\n let response: Response;\n try {\n response = await this.fetchImpl(upstreamUrl, {\n method: \"POST\",\n redirect: \"error\",\n headers: {\n \"content-type\": \"application/json\",\n ...input.adapter.forwardHeaders(input.requestHeaders),\n },\n body: JSON.stringify(input.providerBody),\n });\n } catch {\n await this.gateway.release({\n reservationId: reservation.reservationId,\n orgId: reservation.orgId,\n reason: \"UPSTREAM_CONNECTION_FAILED\",\n });\n return input.reply.code(502).send({\n error: \"UPSTREAM_CONNECTION_FAILED\",\n reservationId: reservation.reservationId,\n });\n }\n\n if (!response.ok) {\n await this.gateway.release({\n reservationId: reservation.reservationId,\n orgId: reservation.orgId,\n reason: `UPSTREAM_HTTP_${response.status}`,\n });\n }\n const contentType = response.headers.get(\"content-type\") ?? \"application/json\";\n if (contentType.includes(\"text/event-stream\") && response.body) {\n return this.streamResponse(input, response, reservation.reservationId);\n }\n return this.bufferResponse(input, response, reservation.reservationId);\n }\n\n private async bufferResponse(\n input: {\n adapter: AgentProviderAdapter;\n reservation: AgentTaskReserveResult;\n reply: FastifyReply;\n },\n response: Response,\n reservationId: string,\n ): Promise<unknown> {\n const bytes = Buffer.from(await response.arrayBuffer());\n const body = this.parseJson(bytes);\n const usage = response.ok ? input.adapter.extractUsage(body) : null;\n if (usage && input.reservation.reservation) {\n await this.gateway.reconcile({\n reservationId,\n orgId: input.reservation.reservation.orgId,\n usage,\n });\n }\n this.copyResponseHeaders(response, input.reply);\n input.reply.header(\"x-decionis-reservation-id\", reservationId);\n input.reply.header(\n \"x-decionis-reconciliation\",\n usage ? \"reconciled\" : response.ok ? \"pending\" : \"released\",\n );\n return input.reply.code(response.status).send(bytes);\n }\n\n private async streamResponse(\n input: {\n adapter: AgentProviderAdapter;\n reservation: AgentTaskReserveResult;\n reply: FastifyReply;\n },\n response: Response,\n reservationId: string,\n ): Promise<void> {\n const orgId = input.reservation.reservation!.orgId;\n input.reply.hijack();\n input.reply.raw.statusCode = response.status;\n for (const [name, value] of response.headers.entries()) {\n if (this.isForwardedResponseHeader(name)) input.reply.raw.setHeader(name, value);\n }\n input.reply.raw.setHeader(\"x-decionis-reservation-id\", reservationId);\n input.reply.raw.setHeader(\"x-decionis-reconciliation\", \"pending\");\n\n const reader = response.body!.getReader();\n const decoder = new TextDecoder();\n let pending = \"\";\n let usage: AgentTokenUsage | null = null;\n try {\n while (true) {\n const chunk = await reader.read();\n if (chunk.done) break;\n input.reply.raw.write(Buffer.from(chunk.value));\n pending += decoder.decode(chunk.value, { stream: true });\n const lines = pending.split(/\\r?\\n/);\n pending = lines.pop() ?? \"\";\n for (const line of lines) {\n const candidate = this.parseStreamEvent(line);\n const partial = candidate ? input.adapter.extractStreamUsage(candidate) : null;\n if (partial) usage = this.mergeUsage(usage, partial);\n }\n }\n pending += decoder.decode();\n for (const line of pending.split(/\\r?\\n/)) {\n const candidate = this.parseStreamEvent(line);\n const partial = candidate ? input.adapter.extractStreamUsage(candidate) : null;\n if (partial) usage = this.mergeUsage(usage, partial);\n }\n if (usage) {\n await this.gateway.reconcile({ reservationId, orgId, usage });\n }\n } finally {\n input.reply.raw.end();\n }\n }\n\n private parseJson(bytes: Buffer): unknown {\n try {\n return JSON.parse(bytes.toString(\"utf8\"));\n } catch {\n return null;\n }\n }\n\n private parseStreamEvent(line: string): unknown {\n if (!line.startsWith(\"data:\")) return null;\n const data = line.slice(\"data:\".length).trim();\n if (!data || data === \"[DONE]\") return null;\n try {\n return JSON.parse(data);\n } catch {\n return null;\n }\n }\n\n private mergeUsage(current: AgentTokenUsage | null, next: AgentTokenUsage): AgentTokenUsage {\n if (!current) return next;\n return {\n inputTokens: Math.max(current.inputTokens, next.inputTokens),\n outputTokens: Math.max(current.outputTokens, next.outputTokens),\n cachedInputTokens: Math.max(current.cachedInputTokens, next.cachedInputTokens),\n cacheCreationInputTokens: Math.max(\n current.cacheCreationInputTokens,\n next.cacheCreationInputTokens,\n ),\n cacheCreationOneHourInputTokens: Math.max(\n current.cacheCreationOneHourInputTokens,\n next.cacheCreationOneHourInputTokens,\n ),\n toolCalls: Math.max(current.toolCalls, next.toolCalls),\n };\n }\n\n private copyResponseHeaders(response: Response, reply: FastifyReply): void {\n for (const [name, value] of response.headers.entries()) {\n if (this.isForwardedResponseHeader(name)) reply.header(name, value);\n }\n }\n\n private isForwardedResponseHeader(name: string): boolean {\n const normalized = name.toLowerCase();\n return (\n normalized === \"content-type\" ||\n normalized === \"retry-after\" ||\n normalized === \"request-id\" ||\n normalized === \"x-request-id\" ||\n normalized.startsWith(\"openai-\") ||\n normalized.startsWith(\"anthropic-\")\n );\n }\n}\n","import { createHash } from \"node:crypto\";\nimport type { AgentTaskIntent, AgentTokenUsage } from \"../AgentTaskContracts.js\";\nimport type { AgentProviderAdapter, AgentProviderRequestContext } from \"./AgentProviderAdapter.js\";\nimport { AgentProviderValues } from \"./AgentProviderAdapter.js\";\n\n/** Anthropic Messages API normalization and usage extraction. */\nexport class AnthropicProviderAdapter implements AgentProviderAdapter {\n readonly provider = \"anthropic\" as const;\n readonly operation = \"messages.create\";\n readonly upstreamPath = \"/v1/messages\";\n\n buildIntent(body: unknown, context: AgentProviderRequestContext): AgentTaskIntent | null {\n const request = AgentProviderValues.asRecord(body);\n const model = AgentProviderValues.string(request.model);\n const maxOutputTokens = AgentProviderValues.integer(request.max_tokens);\n if (!model || maxOutputTokens == null || maxOutputTokens < 1) return null;\n const promptContent = {\n messages: request.messages,\n system: request.system,\n tools: request.tools,\n };\n return {\n orgId: context.orgId,\n userId: context.userId,\n provider: this.provider,\n model,\n sessionId: context.sessionId,\n idempotencyKey: context.idempotencyKey,\n prompt: {\n sha256: createHash(\"sha256\").update(JSON.stringify(promptContent)).digest(\"hex\"),\n characterCount: AgentProviderValues.characterCount(promptContent),\n estimatedInputTokens: null,\n },\n limits: {\n maxOutputTokens,\n estimatedToolCalls: context.estimatedToolCalls,\n },\n downstreamTarget: {\n system: \"anthropic_api\",\n operation: this.operation,\n endpoint: `POST ${this.upstreamPath}`,\n },\n metadata: {\n host: context.host,\n stream: request.stream === true,\n },\n };\n }\n\n extractUsage(body: unknown): AgentTokenUsage | null {\n return this.usage(AgentProviderValues.asRecord(AgentProviderValues.asRecord(body).usage));\n }\n\n extractStreamUsage(event: unknown): AgentTokenUsage | null {\n const value = AgentProviderValues.asRecord(event);\n if (value.type === \"message_start\") {\n const message = AgentProviderValues.asRecord(value.message);\n return this.usage(AgentProviderValues.asRecord(message.usage));\n }\n if (value.type === \"message_delta\") {\n return this.usage(AgentProviderValues.asRecord(value.usage));\n }\n return null;\n }\n\n forwardHeaders(headers: Record<string, unknown>): Record<string, string> {\n const output: Record<string, string> = {};\n for (const name of [\"x-api-key\", \"anthropic-version\", \"anthropic-beta\"]) {\n const value = AgentProviderValues.header(headers, name);\n if (value) output[name] = value;\n }\n return output;\n }\n\n private usage(value: Record<string, unknown>): AgentTokenUsage | null {\n const inputTokens = AgentProviderValues.integer(value.input_tokens);\n const outputTokens = AgentProviderValues.integer(value.output_tokens);\n if (inputTokens == null && outputTokens == null) return null;\n const cacheCreation = AgentProviderValues.asRecord(value.cache_creation);\n return {\n inputTokens: inputTokens ?? 0,\n outputTokens: outputTokens ?? 0,\n cachedInputTokens: AgentProviderValues.integer(value.cache_read_input_tokens) ?? 0,\n cacheCreationInputTokens: AgentProviderValues.integer(value.cache_creation_input_tokens) ?? 0,\n cacheCreationOneHourInputTokens:\n AgentProviderValues.integer(cacheCreation.ephemeral_1h_input_tokens) ?? 0,\n toolCalls: this.toolCalls(value.server_tool_use),\n };\n }\n\n private toolCalls(input: unknown): number {\n const usage = AgentProviderValues.asRecord(input);\n return Object.values(usage).reduce<number>(\n (total, value) => total + (AgentProviderValues.integer(value) ?? 0),\n 0,\n );\n }\n}\n","import type { AgentProvider, AgentTaskIntent, AgentTokenUsage } from \"../AgentTaskContracts.js\";\n\nexport interface AgentProviderRequestContext {\n orgId: string;\n userId: string;\n sessionId: string;\n idempotencyKey: string;\n estimatedToolCalls: number;\n host: string | null;\n}\n\nexport interface AgentProviderAdapter {\n readonly provider: AgentProvider;\n readonly operation: string;\n readonly upstreamPath: string;\n buildIntent(body: unknown, context: AgentProviderRequestContext): AgentTaskIntent | null;\n extractUsage(body: unknown): AgentTokenUsage | null;\n extractStreamUsage(event: unknown): AgentTokenUsage | null;\n forwardHeaders(headers: Record<string, unknown>): Record<string, string>;\n}\n\n/** Provider request helpers that intentionally retain prompt content only in memory. */\nexport class AgentProviderValues {\n static asRecord(value: unknown): Record<string, unknown> {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return {};\n return value as Record<string, unknown>;\n }\n\n static string(value: unknown): string | null {\n return typeof value === \"string\" && value.trim() ? value.trim() : null;\n }\n\n static integer(value: unknown): number | null {\n return typeof value === \"number\" && Number.isSafeInteger(value) && value >= 0 ? value : null;\n }\n\n static header(headers: Record<string, unknown>, name: string): string | null {\n const value = headers[name.toLowerCase()];\n if (typeof value === \"string\") return value;\n if (Array.isArray(value) && typeof value[0] === \"string\") return value[0];\n return null;\n }\n\n static characterCount(value: unknown): number {\n if (typeof value === \"string\") return value.length;\n if (Array.isArray(value)) {\n return value.reduce((total, item) => total + AgentProviderValues.characterCount(item), 0);\n }\n if (!value || typeof value !== \"object\") return 0;\n return Object.values(value as Record<string, unknown>).reduce<number>(\n (total, item) => total + AgentProviderValues.characterCount(item),\n 0,\n );\n }\n\n static emptyUsage(): AgentTokenUsage {\n return {\n inputTokens: 0,\n outputTokens: 0,\n cachedInputTokens: 0,\n cacheCreationInputTokens: 0,\n cacheCreationOneHourInputTokens: 0,\n toolCalls: 0,\n };\n }\n}\n","import { createHash } from \"node:crypto\";\nimport type { AgentTaskIntent, AgentTokenUsage } from \"../AgentTaskContracts.js\";\nimport type { AgentProviderAdapter, AgentProviderRequestContext } from \"./AgentProviderAdapter.js\";\nimport { AgentProviderValues } from \"./AgentProviderAdapter.js\";\n\n/** OpenAI Responses API normalization and usage extraction. */\nexport class OpenAiProviderAdapter implements AgentProviderAdapter {\n readonly provider = \"openai\" as const;\n readonly operation = \"responses.create\";\n readonly upstreamPath = \"/v1/responses\";\n\n buildIntent(body: unknown, context: AgentProviderRequestContext): AgentTaskIntent | null {\n const request = AgentProviderValues.asRecord(body);\n const model = AgentProviderValues.string(request.model);\n const maxOutputTokens = AgentProviderValues.integer(request.max_output_tokens);\n if (!model || maxOutputTokens == null || maxOutputTokens < 1) return null;\n const promptContent = {\n input: request.input,\n instructions: request.instructions,\n tools: request.tools,\n };\n return {\n orgId: context.orgId,\n userId: context.userId,\n provider: this.provider,\n model,\n sessionId: context.sessionId,\n idempotencyKey: context.idempotencyKey,\n prompt: {\n sha256: createHash(\"sha256\").update(JSON.stringify(promptContent)).digest(\"hex\"),\n characterCount: AgentProviderValues.characterCount(promptContent),\n estimatedInputTokens: null,\n },\n limits: {\n maxOutputTokens,\n estimatedToolCalls: context.estimatedToolCalls,\n },\n downstreamTarget: {\n system: \"openai_api\",\n operation: this.operation,\n endpoint: `POST ${this.upstreamPath}`,\n },\n metadata: {\n host: context.host,\n stream: request.stream === true,\n },\n };\n }\n\n extractUsage(body: unknown): AgentTokenUsage | null {\n const response = AgentProviderValues.asRecord(body);\n return this.usage(\n AgentProviderValues.asRecord(response.usage),\n this.toolCalls(response.output),\n );\n }\n\n extractStreamUsage(event: unknown): AgentTokenUsage | null {\n const value = AgentProviderValues.asRecord(event);\n if (value.type !== \"response.completed\" && value.type !== \"response.incomplete\") {\n return null;\n }\n const response = AgentProviderValues.asRecord(value.response);\n return this.usage(\n AgentProviderValues.asRecord(response.usage),\n this.toolCalls(response.output),\n );\n }\n\n forwardHeaders(headers: Record<string, unknown>): Record<string, string> {\n const output: Record<string, string> = {};\n for (const name of [\n \"authorization\",\n \"openai-organization\",\n \"openai-project\",\n \"openai-beta\",\n \"x-client-request-id\",\n \"idempotency-key\",\n ]) {\n const value = AgentProviderValues.header(headers, name);\n if (value) output[name] = value;\n }\n return output;\n }\n\n private usage(value: Record<string, unknown>, toolCalls: number): AgentTokenUsage | null {\n const inputTokens = AgentProviderValues.integer(value.input_tokens);\n const outputTokens = AgentProviderValues.integer(value.output_tokens);\n if (inputTokens == null || outputTokens == null) return null;\n const inputDetails = AgentProviderValues.asRecord(value.input_tokens_details);\n return {\n inputTokens,\n outputTokens,\n cachedInputTokens: AgentProviderValues.integer(inputDetails.cached_tokens) ?? 0,\n cacheCreationInputTokens: AgentProviderValues.integer(inputDetails.cache_write_tokens) ?? 0,\n cacheCreationOneHourInputTokens: 0,\n toolCalls,\n };\n }\n\n private toolCalls(output: unknown): number {\n if (!Array.isArray(output)) return 0;\n return output.filter((item) => {\n const type = AgentProviderValues.string(AgentProviderValues.asRecord(item).type);\n return type === \"function_call\" || type === \"mcp_call\" || type?.endsWith(\"_call\");\n }).length;\n }\n}\n","import type { AgentProvider } from \"../AgentTaskContracts.js\";\nimport type { AgentProviderAdapter } from \"./AgentProviderAdapter.js\";\nimport { AnthropicProviderAdapter } from \"./AnthropicProviderAdapter.js\";\nimport { OpenAiProviderAdapter } from \"./OpenAiProviderAdapter.js\";\n\n/** Fixed provider registry prevents caller-controlled upstream routing. */\nexport class AgentProviderRegistry {\n private readonly adapters: Map<AgentProvider, AgentProviderAdapter>;\n\n constructor(\n adapters: AgentProviderAdapter[] = [\n new OpenAiProviderAdapter(),\n new AnthropicProviderAdapter(),\n ],\n ) {\n this.adapters = new Map(adapters.map((adapter) => [adapter.provider, adapter]));\n }\n\n get(provider: string): AgentProviderAdapter | null {\n return this.adapters.get(provider as AgentProvider) ?? null;\n }\n}\n","import type { FastifyInstance, FastifyRequest } from \"fastify\";\nimport type { ProtocolMcpAuthLookup } from \"../auth/McpAuth.js\";\nimport { AgentGatewayAuthGuard } from \"./AgentGatewayAuthGuard.js\";\nimport type { AgentTaskGatewayService } from \"./AgentTaskGatewayService.js\";\nimport { AgentTaskIntentParser } from \"./AgentTaskIntentParser.js\";\nimport { AgentProviderProxy, type AgentProviderProxyOptions } from \"./AgentProviderProxy.js\";\nimport { AgentProviderRegistry } from \"./providers/AgentProviderRegistry.js\";\nimport { AgentProviderValues } from \"./providers/AgentProviderAdapter.js\";\n\n/** Registers reserve, egress, downstream reconciliation, and provider proxy boundaries. */\nexport class AgentTaskGatewayRoutes {\n static register(\n app: FastifyInstance,\n options: {\n gateway: AgentTaskGatewayService;\n authLookup: ProtocolMcpAuthLookup | null;\n proxy?: AgentProviderProxyOptions;\n },\n ): void {\n const auth = new AgentGatewayAuthGuard(options.authLookup);\n const providers = new AgentProviderRegistry();\n const proxy = new AgentProviderProxy(options.gateway, options.proxy);\n\n app.post(\"/v1/agent/tasks/reserve\", async (req, reply) => {\n const parsed = AgentTaskIntentParser.parse(req.body);\n if (!parsed.ok) {\n return reply.code(400).send({ error: \"VALIDATION_ERROR\", message: parsed.message });\n }\n const denied = await this.authorize(req, parsed.value.orgId, auth);\n if (denied) return reply.code(denied.statusCode).send({ error: denied.message });\n const result = await options.gateway.reserve(parsed.value);\n return reply.code(result.allowed ? 201 : 429).send(result);\n });\n\n app.get(\"/v1/agent/tasks/:reservationId\", async (req, reply) => {\n const params = AgentProviderValues.asRecord(req.params);\n const query = AgentProviderValues.asRecord(req.query);\n const reservationId = AgentProviderValues.string(params.reservationId);\n const orgId = AgentProviderValues.string(query.orgId);\n if (!reservationId || !orgId) {\n return reply.code(400).send({ error: \"reservationId and orgId are required\" });\n }\n const denied = await this.authorize(req, orgId, auth);\n if (denied) return reply.code(denied.statusCode).send({ error: denied.message });\n const reservation = await options.gateway.get(reservationId, orgId);\n return reservation\n ? reply.code(200).send({ reservation })\n : reply.code(404).send({ error: \"RESERVATION_NOT_FOUND\" });\n });\n\n app.post(\"/v1/agent/tasks/:reservationId/authorize-egress\", async (req, reply) => {\n const params = AgentProviderValues.asRecord(req.params);\n const body = AgentProviderValues.asRecord(req.body);\n const reservationId = AgentProviderValues.string(params.reservationId);\n const orgId = AgentProviderValues.string(body.orgId);\n const executionToken = AgentProviderValues.string(body.executionToken);\n if (!reservationId || !orgId || !executionToken) {\n return reply\n .code(400)\n .send({ error: \"reservationId, orgId, and executionToken are required\" });\n }\n const denied = await this.authorize(req, orgId, auth);\n if (denied) return reply.code(denied.statusCode).send({ error: denied.message });\n const reservation = await options.gateway.get(reservationId, orgId);\n if (!reservation || reservation.status !== \"RESERVED\") {\n return reply.code(409).send({ error: \"RESERVATION_NOT_ACTIVE\" });\n }\n const verified = options.gateway.verifyEgress(reservation, executionToken);\n return verified.valid\n ? reply.code(200).send({\n allowed: true,\n authorizedTarget: reservation.downstreamTarget,\n reservationId,\n })\n : reply.code(403).send({\n allowed: false,\n reasonCodes: verified.reason_codes,\n });\n });\n\n app.post(\"/v1/agent/tasks/:reservationId/reconcile\", async (req, reply) => {\n const params = AgentProviderValues.asRecord(req.params);\n const body = AgentProviderValues.asRecord(req.body);\n const reservationId = AgentProviderValues.string(params.reservationId);\n const orgId = AgentProviderValues.string(body.orgId);\n const usage = AgentTaskIntentParser.parseUsage(body.usage);\n if (!reservationId || !orgId || !usage) {\n return reply\n .code(400)\n .send({ error: \"reservationId, orgId, and valid usage are required\" });\n }\n const denied = await this.authorize(req, orgId, auth);\n if (denied) return reply.code(denied.statusCode).send({ error: denied.message });\n const reservation = await options.gateway.reconcile({ reservationId, orgId, usage });\n return reservation\n ? reply.code(200).send({ reservation })\n : reply.code(409).send({ error: \"RESERVATION_NOT_RECONCILABLE\" });\n });\n\n app.post(\"/v1/agent/tasks/:reservationId/release\", async (req, reply) => {\n const params = AgentProviderValues.asRecord(req.params);\n const body = AgentProviderValues.asRecord(req.body);\n const reservationId = AgentProviderValues.string(params.reservationId);\n const orgId = AgentProviderValues.string(body.orgId);\n const reason = AgentProviderValues.string(body.reason) ?? \"CALLER_RELEASED\";\n if (!reservationId || !orgId) {\n return reply.code(400).send({ error: \"reservationId and orgId are required\" });\n }\n const denied = await this.authorize(req, orgId, auth);\n if (denied) return reply.code(denied.statusCode).send({ error: denied.message });\n const reservation = await options.gateway.release({ reservationId, orgId, reason });\n return reservation\n ? reply.code(200).send({ reservation })\n : reply.code(409).send({ error: \"RESERVATION_NOT_RELEASABLE\" });\n });\n\n app.post(\"/v1/agent/proxy/:provider/v1/:operation\", async (req, reply) => {\n const params = AgentProviderValues.asRecord(req.params);\n const provider = AgentProviderValues.string(params.provider);\n const operation = AgentProviderValues.string(params.operation);\n const adapter = provider ? providers.get(provider) : null;\n if (!adapter || operation !== adapter.upstreamPath.split(\"/\").at(-1)) {\n return reply.code(404).send({ error: \"PROVIDER_OPERATION_NOT_SUPPORTED\" });\n }\n\n const headers = req.headers as Record<string, unknown>;\n const context = this.providerContext(headers);\n if (!context) {\n return reply.code(400).send({\n error: \"DECIONIS_TASK_CONTEXT_REQUIRED\",\n requiredHeaders: [\n \"x-decionis-org-id\",\n \"x-decionis-user-id\",\n \"x-decionis-session-id\",\n \"x-decionis-idempotency-key\",\n ],\n });\n }\n const denied = await this.authorize(req, context.orgId, auth);\n if (denied) return reply.code(denied.statusCode).send({ error: denied.message });\n\n const intent = adapter.buildIntent(req.body, context);\n if (!intent) {\n return reply.code(400).send({\n error: \"PROVIDER_REQUEST_NOT_RESERVABLE\",\n message: \"model and an explicit positive output token limit are required\",\n });\n }\n const upstreamUrl = proxy.upstreamUrl(adapter);\n if (!upstreamUrl) return reply.code(404).send({ error: \"PROVIDER_PROXY_UNAVAILABLE\" });\n intent.downstreamTarget.endpoint = `POST ${upstreamUrl}`;\n const reservation = await options.gateway.reserve(intent);\n if (!reservation.allowed) return reply.code(429).send(reservation);\n return proxy.forward({\n adapter,\n providerBody: req.body,\n requestHeaders: headers,\n reservation,\n reply,\n });\n });\n }\n\n private static async authorize(req: FastifyRequest, orgId: string, guard: AgentGatewayAuthGuard) {\n const result = await guard.authenticate(req, orgId);\n return result.ok ? null : result;\n }\n\n private static providerContext(headers: Record<string, unknown>) {\n const orgId = AgentProviderValues.header(headers, \"x-decionis-org-id\");\n const userId = AgentProviderValues.header(headers, \"x-decionis-user-id\");\n const sessionId = AgentProviderValues.header(headers, \"x-decionis-session-id\");\n const idempotencyKey = AgentProviderValues.header(headers, \"x-decionis-idempotency-key\");\n if (!orgId || !userId || !sessionId || !idempotencyKey) return null;\n const estimatedToolCalls = Number.parseInt(\n AgentProviderValues.header(headers, \"x-decionis-estimated-tool-calls\") ?? \"0\",\n 10,\n );\n return {\n orgId,\n userId,\n sessionId,\n idempotencyKey,\n estimatedToolCalls:\n Number.isSafeInteger(estimatedToolCalls) && estimatedToolCalls >= 0\n ? estimatedToolCalls\n : 0,\n host: AgentProviderValues.header(headers, \"x-decionis-agent-host\"),\n };\n }\n}\n","export const PROTOCOL_SERVICE = \"decionis-protocol\";\nexport const PROTOCOL_VERSION = \"1.0.0\";\n","import type { FastifyInstance } from \"fastify\";\nimport type { ProtocolStore } from \"../store/StoreContracts.js\";\nimport { PROTOCOL_SERVICE, PROTOCOL_VERSION } from \"../ProtocolInfo.js\";\n\n/** Registers the protocol health and readiness probe routes. */\nexport function registerHealthRoutes(app: FastifyInstance, deps: { store: ProtocolStore }): void {\n const { store } = deps;\n\n app.get(\"/v1/protocol/health\", async () => ({\n ok: true,\n service: PROTOCOL_SERVICE,\n version: PROTOCOL_VERSION,\n timestamp: new Date().toISOString(),\n }));\n\n app.get(\"/v1/protocol/ready\", async (_req, reply) => {\n const db = await store.healthCheck();\n return reply.code(db.ok ? 200 : 503).send({\n ready: db.ok,\n service: PROTOCOL_SERVICE,\n version: PROTOCOL_VERSION,\n checks: [\n { name: \"http\", status: \"ok\" },\n { name: \"schema_validator\", status: \"ok\" },\n { name: \"store\", status: db.ok ? \"ok\" : \"failed\", message: db.message },\n ],\n timestamp: new Date().toISOString(),\n });\n });\n}\n","import { randomUUID } from \"node:crypto\";\nimport type { FastifyInstance } from \"fastify\";\nimport type { ProtocolStore } from \"../store/StoreContracts.js\";\nimport { validateProtocolArtifact } from \"../validation/ProtocolArtifacts.js\";\nimport { asRecord, asString } from \"../support/Parsing.js\";\nimport {\n FINANCE_OVERRIDE_REASON_CODES,\n type FinanceOverrideReviewResponse,\n type FinanceOverrideSubmitResponse,\n type OverrideReviewOutcome,\n} from \"./FinanceOverrideContracts.js\";\nimport {\n appendFinanceOverrideLedgerEvent,\n buildFinanceOverrideDecisionResolution,\n findFinanceOverrideLedgerByIdempotency,\n findFinanceOverrideSubmission,\n isFinanceOverrideReasonCode,\n overrideReviewOutcomeToDecisionStatus,\n parseFinanceOverrideReviewRequest,\n parseFinanceOverrideSubmitRequest,\n} from \"./FinanceOverrides.js\";\n\n/** Registers the finance override submit/review routes and reason-code catalog. */\nexport function registerFinanceOverrideRoutes(\n app: FastifyInstance,\n deps: { store: ProtocolStore },\n): void {\n const { store } = deps;\n\n app.get(\"/v1/protocol/finance/override-reason-codes\", async () => ({\n reason_codes: [...FINANCE_OVERRIDE_REASON_CODES],\n }));\n\n app.post(\"/v1/protocol/finance/overrides/submit\", async (req, reply) => {\n const parsed = parseFinanceOverrideSubmitRequest(req.body);\n if (!parsed.ok) {\n return reply.code(400).send({ error: \"VALIDATION_ERROR\", message: parsed.message });\n }\n\n const now = new Date().toISOString();\n if (parsed.value.idempotency_key) {\n const existing = await findFinanceOverrideLedgerByIdempotency(store, {\n org_id: parsed.value.org_id,\n override_id: parsed.value.override_id,\n action: \"finance.override.submitted\",\n idempotency_key: parsed.value.idempotency_key,\n });\n if (existing) {\n const payload = asRecord(existing.payload);\n const links = asRecord(existing.links);\n const chain = asRecord(existing.chain);\n const replayReasonCodeRaw = asString(payload.reason_code)?.toUpperCase();\n const replayReasonCode =\n replayReasonCodeRaw && isFinanceOverrideReasonCode(replayReasonCodeRaw)\n ? replayReasonCodeRaw\n : parsed.value.reason_code;\n return reply.code(200).send({\n override_id: asString(payload.override_id) ?? parsed.value.override_id,\n status: \"SUBMITTED\",\n reason_code: replayReasonCode,\n submitted_at: asString(existing.occurred_at) ?? now,\n decision_resolution_id: asString(links.decision_resolution_id) ?? randomUUID(),\n ledger_entry_id: asString(existing.ledger_entry_id) ?? randomUUID(),\n ledger_entry_hash: asString(chain.entry_hash) ?? \"\",\n } satisfies FinanceOverrideSubmitResponse);\n }\n }\n\n const { resolutionId, payload } = buildFinanceOverrideDecisionResolution({\n org_id: parsed.value.org_id,\n override_id: parsed.value.override_id,\n decision_type: parsed.value.decision_type,\n decision_band: parsed.value.decision_band,\n transaction_type: parsed.value.transaction_type,\n reason_code: parsed.value.reason_code,\n reason_detail: parsed.value.reason_detail,\n actor_type: parsed.value.requested_by_actor_type,\n actor_id: parsed.value.requested_by_actor_id,\n confidence: parsed.value.confidence,\n risk_level: parsed.value.risk_level,\n approval_path: parsed.value.approval_path,\n evidence_refs: parsed.value.evidence_refs,\n status: \"PROPOSED\",\n review_outcome: null,\n review_note: null,\n occurred_at: now,\n });\n\n const resolutionValidation = validateProtocolArtifact(\"decision_resolution\", payload);\n if (!resolutionValidation.ok) {\n return reply.code(400).send({\n error: \"VALIDATION_ERROR\",\n message: \"decision_resolution failed schema validation\",\n issues: resolutionValidation.issues,\n });\n }\n await store.saveArtifact(\"decision_resolution\", resolutionValidation.value);\n\n const ledger = await appendFinanceOverrideLedgerEvent(store, {\n org_id: parsed.value.org_id,\n override_id: parsed.value.override_id,\n action: \"finance.override.submitted\",\n actor_type: parsed.value.requested_by_actor_type,\n actor_id: parsed.value.requested_by_actor_id,\n payload: {\n override_id: parsed.value.override_id,\n decision_type: parsed.value.decision_type,\n decision_band: parsed.value.decision_band,\n transaction_type: parsed.value.transaction_type,\n reason_code: parsed.value.reason_code,\n reason_detail: parsed.value.reason_detail,\n approval_path: parsed.value.approval_path,\n evidence_refs: parsed.value.evidence_refs,\n idempotency_key: parsed.value.idempotency_key,\n },\n decision_resolution_id: resolutionId,\n occurred_at: now,\n });\n\n const response: FinanceOverrideSubmitResponse = {\n override_id: parsed.value.override_id,\n status: \"SUBMITTED\",\n reason_code: parsed.value.reason_code,\n submitted_at: now,\n decision_resolution_id: resolutionId,\n ledger_entry_id: ledger.ledger_entry_id,\n ledger_entry_hash: ledger.ledger_entry_hash,\n };\n return reply.code(200).send(response);\n });\n\n app.post(\"/v1/protocol/finance/overrides/review\", async (req, reply) => {\n const parsed = parseFinanceOverrideReviewRequest(req.body);\n if (!parsed.ok) {\n return reply.code(400).send({ error: \"VALIDATION_ERROR\", message: parsed.message });\n }\n\n const submission = await findFinanceOverrideSubmission(store, {\n org_id: parsed.value.org_id,\n override_id: parsed.value.override_id,\n });\n if (!submission) {\n return reply.code(404).send({\n error: \"NOT_FOUND\",\n message: \"Override submission not found\",\n });\n }\n\n const now = new Date().toISOString();\n if (parsed.value.idempotency_key) {\n const existing = await findFinanceOverrideLedgerByIdempotency(store, {\n org_id: parsed.value.org_id,\n override_id: parsed.value.override_id,\n action: \"finance.override.reviewed\",\n idempotency_key: parsed.value.idempotency_key,\n });\n if (existing) {\n const payload = asRecord(existing.payload);\n const links = asRecord(existing.links);\n const chain = asRecord(existing.chain);\n const reviewOutcomeRaw = asString(payload.review_outcome)?.toUpperCase();\n const reviewOutcome: OverrideReviewOutcome =\n reviewOutcomeRaw === \"APPROVE\" ||\n reviewOutcomeRaw === \"REJECT\" ||\n reviewOutcomeRaw === \"ESCALATE\"\n ? reviewOutcomeRaw\n : parsed.value.review_outcome;\n return reply.code(200).send({\n override_id: asString(payload.override_id) ?? parsed.value.override_id,\n status: overrideReviewOutcomeToDecisionStatus(reviewOutcome),\n review_outcome: reviewOutcome,\n reviewed_at: asString(existing.occurred_at) ?? now,\n decision_resolution_id: asString(links.decision_resolution_id) ?? randomUUID(),\n ledger_entry_id: asString(existing.ledger_entry_id) ?? randomUUID(),\n ledger_entry_hash: asString(chain.entry_hash) ?? \"\",\n } satisfies FinanceOverrideReviewResponse);\n }\n }\n\n const submissionPayload = asRecord(submission.payload);\n const reasonCode = asString(submissionPayload.reason_code)?.toUpperCase();\n if (!reasonCode || !isFinanceOverrideReasonCode(reasonCode)) {\n return reply.code(409).send({\n error: \"INVALID_OVERRIDE_STATE\",\n message: \"Submitted override is missing deterministic reason_code\",\n });\n }\n\n const decisionType = asString(submissionPayload.decision_type) ?? \"TRANSACTION_ROUTING\";\n const decisionBand = asString(submissionPayload.decision_band) ?? \"UNSPECIFIED\";\n const transactionType = asString(submissionPayload.transaction_type) ?? \"UNSPECIFIED\";\n const approvalPath = Array.isArray(submissionPayload.approval_path)\n ? submissionPayload.approval_path.filter((item): item is string => typeof item === \"string\")\n : [];\n const evidenceRefs = Array.isArray(submissionPayload.evidence_refs)\n ? submissionPayload.evidence_refs.filter((item): item is string => typeof item === \"string\")\n : [];\n\n const status = overrideReviewOutcomeToDecisionStatus(parsed.value.review_outcome);\n const { resolutionId, payload } = buildFinanceOverrideDecisionResolution({\n org_id: parsed.value.org_id,\n override_id: parsed.value.override_id,\n decision_type: decisionType,\n decision_band: decisionBand,\n transaction_type: transactionType,\n reason_code: reasonCode,\n reason_detail: asString(submissionPayload.reason_detail),\n actor_type: parsed.value.reviewer_actor_type,\n actor_id: parsed.value.reviewer_actor_id,\n confidence: parsed.value.confidence,\n risk_level: \"high\",\n approval_path: approvalPath,\n evidence_refs: evidenceRefs,\n status,\n review_outcome: parsed.value.review_outcome,\n review_note: parsed.value.review_note,\n occurred_at: now,\n });\n\n const resolutionValidation = validateProtocolArtifact(\"decision_resolution\", payload);\n if (!resolutionValidation.ok) {\n return reply.code(400).send({\n error: \"VALIDATION_ERROR\",\n message: \"decision_resolution failed schema validation\",\n issues: resolutionValidation.issues,\n });\n }\n await store.saveArtifact(\"decision_resolution\", resolutionValidation.value);\n\n const ledger = await appendFinanceOverrideLedgerEvent(store, {\n org_id: parsed.value.org_id,\n override_id: parsed.value.override_id,\n action: \"finance.override.reviewed\",\n actor_type: parsed.value.reviewer_actor_type,\n actor_id: parsed.value.reviewer_actor_id,\n payload: {\n override_id: parsed.value.override_id,\n review_outcome: parsed.value.review_outcome,\n review_note: parsed.value.review_note,\n reason_code: reasonCode,\n idempotency_key: parsed.value.idempotency_key,\n },\n decision_resolution_id: resolutionId,\n occurred_at: now,\n });\n\n const response: FinanceOverrideReviewResponse = {\n override_id: parsed.value.override_id,\n status,\n review_outcome: parsed.value.review_outcome,\n reviewed_at: now,\n decision_resolution_id: resolutionId,\n ledger_entry_id: ledger.ledger_entry_id,\n ledger_entry_hash: ledger.ledger_entry_hash,\n };\n return reply.code(200).send(response);\n });\n}\n","import { type ErrorObject } from \"ajv\";\nimport Ajv2020 from \"ajv/dist/2020.js\";\nimport addFormats from \"ajv-formats\";\nimport auditLedgerEntrySchema from \"../../../../docs/decionis.protocol.schemas/v1/audit-ledger-entry.schema.json\";\nimport contextSnapshotSchema from \"../../../../docs/decionis.protocol.schemas/v1/context-snapshot.schema.json\";\nimport decisionResolutionSchema from \"../../../../docs/decionis.protocol.schemas/v1/decision-resolution.schema.json\";\nimport executionDispatchSchema from \"../../../../docs/decionis.protocol.schemas/v1/execution-dispatch.schema.json\";\nimport policyBundleSchema from \"../../../../docs/decionis.protocol.schemas/v1/policy-bundle.schema.json\";\nimport signalEnvelopeSchema from \"../../../../docs/decionis.protocol.schemas/v1/signal-envelope.schema.json\";\n\nexport interface ValidationIssue {\n path: string;\n keyword: string;\n message: string;\n}\n\nexport type ProtocolArtifact =\n | \"signal_envelope\"\n | \"context_snapshot\"\n | \"policy_bundle\"\n | \"decision_resolution\"\n | \"execution_dispatch\"\n | \"audit_ledger_entry\";\n\ntype ProtocolPayload = Record<string, unknown>;\n\nconst ajv = new Ajv2020({ allErrors: true, strict: false });\naddFormats(ajv);\n\n/** JSON-schema validation for the v1 protocol artifacts. */\nexport class ProtocolArtifacts {\n private static readonly validators = {\n signal_envelope: ajv.compile<ProtocolPayload>(signalEnvelopeSchema),\n context_snapshot: ajv.compile<ProtocolPayload>(contextSnapshotSchema),\n policy_bundle: ajv.compile<ProtocolPayload>(policyBundleSchema),\n decision_resolution: ajv.compile<ProtocolPayload>(decisionResolutionSchema),\n execution_dispatch: ajv.compile<ProtocolPayload>(executionDispatchSchema),\n audit_ledger_entry: ajv.compile<ProtocolPayload>(auditLedgerEntrySchema),\n } as const;\n\n static validate(\n artifact: ProtocolArtifact,\n payload: unknown,\n ): { ok: true; value: ProtocolPayload } | { ok: false; issues: ValidationIssue[] } {\n const validator = ProtocolArtifacts.validators[artifact];\n if (validator(payload)) {\n return { ok: true, value: payload as ProtocolPayload };\n }\n\n return {\n ok: false,\n issues: ProtocolArtifacts.mapValidationIssues(validator.errors),\n };\n }\n\n private static mapValidationIssues(errors: ErrorObject[] | null | undefined): ValidationIssue[] {\n if (!errors || errors.length === 0) return [];\n return errors.map((error) => ({\n path: error.instancePath || \"/\",\n keyword: error.keyword,\n message: error.message ?? \"invalid\",\n }));\n }\n}\n\n/** Functional alias for {@link ProtocolArtifacts.validate}. */\nexport function validateProtocolArtifact(\n artifact: ProtocolArtifact,\n payload: unknown,\n): { ok: true; value: ProtocolPayload } | { ok: false; issues: ValidationIssue[] } {\n return ProtocolArtifacts.validate(artifact, payload);\n}\n","{\n \"$schema\": \"https://json-schema.org/draft/2020-12/schema\",\n \"$id\": \"https://decionis.io/protocol/schemas/v1/audit-ledger-entry.schema.json\",\n \"title\": \"Audit Ledger Entry\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"protocol_version\": {\n \"type\": \"string\",\n \"pattern\": \"^1\\\\.[0-9]+(\\\\.[0-9]+)?$\"\n },\n \"ledger_entry_id\": {\n \"type\": \"string\",\n \"format\": \"uuid\"\n },\n \"org_id\": {\n \"type\": \"string\"\n },\n \"event_type\": {\n \"type\": \"string\",\n \"enum\": [\n \"SIGNAL_INGESTED\",\n \"CONTEXT_ISSUED\",\n \"POLICY_EVALUATED\",\n \"DECISION_RESOLVED\",\n \"EXECUTION_DISPATCHED\",\n \"EXECUTION_STATUS_CHANGED\",\n \"EXPORT_GENERATED\",\n \"ACCESS_GRANTED\",\n \"ACCESS_REVOKED\"\n ]\n },\n \"occurred_at\": {\n \"type\": \"string\",\n \"format\": \"date-time\"\n },\n \"actor\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"type\": {\n \"type\": \"string\",\n \"enum\": [\"SYSTEM\", \"ORG_API_KEY\", \"PLATFORM_API_KEY\", \"USER\", \"SERVICE\"]\n },\n \"id\": {\n \"type\": \"string\",\n \"maxLength\": 200\n }\n },\n \"required\": [\"type\", \"id\"]\n },\n \"object\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"type\": {\n \"type\": \"string\",\n \"enum\": [\n \"SIGNAL\",\n \"CONTEXT\",\n \"POLICY_BUNDLE\",\n \"DECISION\",\n \"DISPATCH\",\n \"EXPORT\",\n \"ORG\",\n \"API_KEY\"\n ]\n },\n \"id\": {\n \"type\": \"string\",\n \"maxLength\": 200\n }\n },\n \"required\": [\"type\", \"id\"]\n },\n \"action\": {\n \"type\": \"string\",\n \"minLength\": 1,\n \"maxLength\": 200\n },\n \"payload\": {\n \"type\": \"object\"\n },\n \"links\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"signal_id\": {\n \"type\": \"string\",\n \"maxLength\": 200\n },\n \"context_snapshot_id\": {\n \"type\": \"string\",\n \"format\": \"uuid\"\n },\n \"policy_bundle_id\": {\n \"type\": \"string\",\n \"format\": \"uuid\"\n },\n \"decision_resolution_id\": {\n \"type\": \"string\",\n \"format\": \"uuid\"\n },\n \"dispatch_id\": {\n \"type\": \"string\",\n \"format\": \"uuid\"\n }\n }\n },\n \"chain\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"prev_hash\": {\n \"type\": \"string\",\n \"pattern\": \"^[A-Fa-f0-9]{64}$\"\n },\n \"entry_hash\": {\n \"type\": \"string\",\n \"pattern\": \"^[A-Fa-f0-9]{64}$\"\n },\n \"algorithm\": {\n \"type\": \"string\",\n \"enum\": [\"SHA256\"]\n }\n },\n \"required\": [\"entry_hash\", \"algorithm\"]\n },\n \"integrity\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"verified\": {\n \"type\": \"boolean\"\n },\n \"verified_at\": {\n \"type\": \"string\",\n \"format\": \"date-time\"\n },\n \"verifier\": {\n \"type\": \"string\",\n \"maxLength\": 200\n }\n },\n \"required\": [\"verified\"]\n }\n },\n \"required\": [\n \"protocol_version\",\n \"ledger_entry_id\",\n \"org_id\",\n \"event_type\",\n \"occurred_at\",\n \"actor\",\n \"object\",\n \"action\",\n \"chain\"\n ]\n}\n","{\n \"$schema\": \"https://json-schema.org/draft/2020-12/schema\",\n \"$id\": \"https://decionis.io/protocol/schemas/v1/context-snapshot.schema.json\",\n \"title\": \"Context Snapshot\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"protocol_version\": {\n \"type\": \"string\",\n \"pattern\": \"^1\\\\.[0-9]+(\\\\.[0-9]+)?$\"\n },\n \"snapshot_id\": {\n \"type\": \"string\",\n \"format\": \"uuid\"\n },\n \"org_id\": {\n \"type\": \"string\"\n },\n \"generated_at\": {\n \"type\": \"string\",\n \"format\": \"date-time\"\n },\n \"lookback\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"hours\": {\n \"type\": \"integer\",\n \"minimum\": 1,\n \"maximum\": 4320\n }\n },\n \"required\": [\"hours\"]\n },\n \"signal_window\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"from\": {\n \"type\": \"string\",\n \"format\": \"date-time\"\n },\n \"to\": {\n \"type\": \"string\",\n \"format\": \"date-time\"\n }\n },\n \"required\": [\"from\", \"to\"]\n },\n \"signals_summary\": {\n \"type\": \"object\",\n \"additionalProperties\": {\n \"type\": \"number\"\n }\n },\n \"derived_features\": {\n \"type\": \"object\"\n },\n \"anomalies\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"anomaly_id\": {\n \"type\": \"string\",\n \"format\": \"uuid\"\n },\n \"domain\": {\n \"type\": \"string\"\n },\n \"metric_name\": {\n \"type\": \"string\"\n },\n \"severity\": {\n \"type\": \"string\",\n \"enum\": [\"mild\", \"moderate\", \"extreme\"]\n },\n \"z_score\": {\n \"type\": \"number\"\n },\n \"observed_value\": {\n \"type\": \"number\"\n },\n \"baseline_mean\": {\n \"type\": \"number\"\n },\n \"detected_at\": {\n \"type\": \"string\",\n \"format\": \"date-time\"\n }\n },\n \"required\": [\"domain\", \"metric_name\", \"severity\", \"detected_at\"]\n }\n },\n \"correlations\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"left_metric\": {\n \"type\": \"string\"\n },\n \"right_metric\": {\n \"type\": \"string\"\n },\n \"correlation\": {\n \"type\": \"number\",\n \"minimum\": -1,\n \"maximum\": 1\n },\n \"window_days\": {\n \"type\": \"integer\",\n \"minimum\": 1,\n \"maximum\": 365\n }\n },\n \"required\": [\"left_metric\", \"right_metric\", \"correlation\"]\n }\n },\n \"provenance\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"connector_ids\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\"\n }\n },\n \"signal_count\": {\n \"type\": \"integer\",\n \"minimum\": 0\n },\n \"hash\": {\n \"type\": \"string\",\n \"pattern\": \"^[A-Fa-f0-9]{64}$\"\n }\n },\n \"required\": [\"signal_count\"]\n }\n },\n \"required\": [\n \"protocol_version\",\n \"snapshot_id\",\n \"org_id\",\n \"generated_at\",\n \"signal_window\",\n \"signals_summary\",\n \"provenance\"\n ]\n}\n","{\n \"$schema\": \"https://json-schema.org/draft/2020-12/schema\",\n \"$id\": \"https://decionis.io/protocol/schemas/v1/decision-resolution.schema.json\",\n \"title\": \"Decision Resolution\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"protocol_version\": {\n \"type\": \"string\",\n \"pattern\": \"^1\\\\.[0-9]+(\\\\.[0-9]+)?$\"\n },\n \"resolution_id\": {\n \"type\": \"string\",\n \"format\": \"uuid\"\n },\n \"org_id\": {\n \"type\": \"string\"\n },\n \"cycle_id\": {\n \"type\": \"string\",\n \"maxLength\": 200\n },\n \"decision_domain\": {\n \"type\": \"string\",\n \"minLength\": 1,\n \"maxLength\": 120\n },\n \"status\": {\n \"type\": \"string\",\n \"enum\": [\"PROPOSED\", \"APPROVED\", \"REJECTED\", \"ESCALATED\", \"AUTO_APPROVED\", \"AUTO_REJECTED\"]\n },\n \"confidence\": {\n \"type\": \"number\",\n \"minimum\": 0,\n \"maximum\": 1\n },\n \"risk_level\": {\n \"type\": \"string\",\n \"enum\": [\"low\", \"medium\", \"high\", \"critical\"]\n },\n \"rationale\": {\n \"type\": \"string\",\n \"minLength\": 1,\n \"maxLength\": 12000\n },\n \"decided_at\": {\n \"type\": \"string\",\n \"format\": \"date-time\"\n },\n \"inputs\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"context_snapshot_id\": {\n \"type\": \"string\",\n \"format\": \"uuid\"\n },\n \"policy_bundle_id\": {\n \"type\": \"string\",\n \"format\": \"uuid\"\n },\n \"signal_ids\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"maxLength\": 200\n }\n }\n },\n \"required\": [\"context_snapshot_id\", \"policy_bundle_id\"]\n },\n \"outputs\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"recommended_action\": {\n \"type\": \"string\",\n \"minLength\": 1,\n \"maxLength\": 1000\n },\n \"owner\": {\n \"type\": \"string\",\n \"maxLength\": 200\n },\n \"due_at\": {\n \"type\": \"string\",\n \"format\": \"date-time\"\n },\n \"tags\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"maxLength\": 100\n },\n \"maxItems\": 100\n },\n \"artifacts\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"maxLength\": 2000\n }\n }\n },\n \"required\": [\"recommended_action\"]\n },\n \"trace\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"trigger_id\": {\n \"type\": \"string\",\n \"maxLength\": 200\n },\n \"queue_entry_id\": {\n \"type\": \"string\",\n \"maxLength\": 200\n },\n \"resolver_version\": {\n \"type\": \"string\",\n \"maxLength\": 100\n },\n \"deterministic_seed\": {\n \"type\": \"string\",\n \"maxLength\": 200\n }\n }\n },\n \"compliance\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"checks\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"name\": {\n \"type\": \"string\",\n \"maxLength\": 200\n },\n \"result\": {\n \"type\": \"string\",\n \"enum\": [\"PASS\", \"FAIL\", \"WAIVED\"]\n },\n \"details\": {\n \"type\": \"string\",\n \"maxLength\": 4000\n }\n },\n \"required\": [\"name\", \"result\"]\n }\n }\n }\n }\n },\n \"required\": [\n \"protocol_version\",\n \"resolution_id\",\n \"org_id\",\n \"decision_domain\",\n \"status\",\n \"confidence\",\n \"risk_level\",\n \"rationale\",\n \"decided_at\",\n \"inputs\",\n \"outputs\"\n ]\n}\n","{\n \"$schema\": \"https://json-schema.org/draft/2020-12/schema\",\n \"$id\": \"https://decionis.io/protocol/schemas/v1/execution-dispatch.schema.json\",\n \"title\": \"Execution Dispatch\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"protocol_version\": {\n \"type\": \"string\",\n \"pattern\": \"^1\\\\.[0-9]+(\\\\.[0-9]+)?$\"\n },\n \"dispatch_id\": {\n \"type\": \"string\",\n \"format\": \"uuid\"\n },\n \"org_id\": {\n \"type\": \"string\"\n },\n \"decision_resolution_id\": {\n \"type\": \"string\",\n \"format\": \"uuid\"\n },\n \"channel\": {\n \"type\": \"string\",\n \"enum\": [\"SLACK\", \"JIRA\", \"LINEAR\", \"NOTION\", \"GITHUB\", \"WEBHOOK\", \"EMAIL\", \"INTERNAL\"]\n },\n \"endpoint\": {\n \"type\": \"string\",\n \"maxLength\": 2000\n },\n \"payload\": {\n \"type\": \"object\"\n },\n \"status\": {\n \"type\": \"string\",\n \"enum\": [\"QUEUED\", \"SENT\", \"DELIVERED\", \"FAILED\", \"RETRYING\", \"CANCELLED\"]\n },\n \"attempt_count\": {\n \"type\": \"integer\",\n \"minimum\": 0\n },\n \"max_attempts\": {\n \"type\": \"integer\",\n \"minimum\": 1,\n \"maximum\": 100\n },\n \"scheduled_at\": {\n \"type\": \"string\",\n \"format\": \"date-time\"\n },\n \"sent_at\": {\n \"type\": \"string\",\n \"format\": \"date-time\"\n },\n \"delivered_at\": {\n \"type\": \"string\",\n \"format\": \"date-time\"\n },\n \"failed_at\": {\n \"type\": \"string\",\n \"format\": \"date-time\"\n },\n \"error\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"code\": {\n \"type\": \"string\",\n \"maxLength\": 120\n },\n \"message\": {\n \"type\": \"string\",\n \"maxLength\": 2000\n },\n \"retryable\": {\n \"type\": \"boolean\"\n }\n },\n \"required\": [\"code\", \"message\", \"retryable\"]\n },\n \"idempotency_key\": {\n \"type\": \"string\",\n \"minLength\": 1,\n \"maxLength\": 255\n },\n \"trace\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"event_name\": {\n \"type\": \"string\",\n \"maxLength\": 200\n },\n \"dedupe_key\": {\n \"type\": \"string\",\n \"maxLength\": 255\n },\n \"correlation_id\": {\n \"type\": \"string\",\n \"maxLength\": 200\n }\n }\n }\n },\n \"required\": [\n \"protocol_version\",\n \"dispatch_id\",\n \"org_id\",\n \"decision_resolution_id\",\n \"channel\",\n \"payload\",\n \"status\",\n \"attempt_count\",\n \"max_attempts\",\n \"idempotency_key\"\n ]\n}\n","{\n \"$schema\": \"https://json-schema.org/draft/2020-12/schema\",\n \"$id\": \"https://decionis.io/protocol/schemas/v1/policy-bundle.schema.json\",\n \"title\": \"Policy Bundle\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"protocol_version\": {\n \"type\": \"string\",\n \"pattern\": \"^1\\\\.[0-9]+(\\\\.[0-9]+)?$\"\n },\n \"bundle_id\": {\n \"type\": \"string\",\n \"format\": \"uuid\"\n },\n \"org_id\": {\n \"type\": \"string\"\n },\n \"version\": {\n \"type\": \"string\",\n \"minLength\": 1,\n \"maxLength\": 100\n },\n \"effective_from\": {\n \"type\": \"string\",\n \"format\": \"date-time\"\n },\n \"effective_to\": {\n \"type\": \"string\",\n \"format\": \"date-time\"\n },\n \"rules\": {\n \"type\": \"array\",\n \"minItems\": 1,\n \"items\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"rule_id\": {\n \"type\": \"string\",\n \"minLength\": 1,\n \"maxLength\": 120\n },\n \"name\": {\n \"type\": \"string\",\n \"minLength\": 1,\n \"maxLength\": 200\n },\n \"decision_domain\": {\n \"type\": \"string\",\n \"minLength\": 1,\n \"maxLength\": 120\n },\n \"when\": {\n \"$ref\": \"#/$defs/condition_group\"\n },\n \"then\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"action\": {\n \"type\": \"string\",\n \"enum\": [\n \"REQUIRE_REVIEW\",\n \"AUTO_APPROVE\",\n \"AUTO_REJECT\",\n \"ESCALATE\",\n \"REQUEST_INFO\"\n ]\n },\n \"severity\": {\n \"type\": \"string\",\n \"enum\": [\"routine\", \"elevated\", \"urgent\"]\n },\n \"assignee_role\": {\n \"type\": \"string\",\n \"maxLength\": 120\n },\n \"sla_minutes\": {\n \"type\": \"integer\",\n \"minimum\": 1,\n \"maximum\": 10080\n }\n },\n \"required\": [\"action\"]\n },\n \"priority\": {\n \"type\": \"integer\",\n \"minimum\": 0,\n \"maximum\": 100000\n },\n \"enabled\": {\n \"type\": \"boolean\"\n },\n \"rationale\": {\n \"type\": \"string\",\n \"maxLength\": 4000\n }\n },\n \"required\": [\"rule_id\", \"name\", \"decision_domain\", \"when\", \"then\", \"priority\", \"enabled\"]\n }\n },\n \"agentExecution\": {\n \"$ref\": \"#/$defs/agent_execution_policy\"\n },\n \"metadata\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"author\": {\n \"type\": \"string\",\n \"maxLength\": 200\n },\n \"source\": {\n \"type\": \"string\",\n \"maxLength\": 200\n },\n \"change_ticket\": {\n \"type\": \"string\",\n \"maxLength\": 200\n },\n \"approved_by\": {\n \"type\": \"string\",\n \"maxLength\": 200,\n \"description\": \"Maker-checker approver. When approval is required, must be present and differ from `author` for the bundle to activate.\"\n },\n \"requires_approval\": {\n \"type\": \"boolean\",\n \"description\": \"When true, the bundle only activates once `approved_by` is set by someone other than `author` (maker-checker).\"\n },\n \"agentExecution\": {\n \"$ref\": \"#/$defs/agent_execution_policy\"\n }\n }\n },\n \"signature\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"algo\": {\n \"type\": \"string\",\n \"maxLength\": 100\n },\n \"digest\": {\n \"type\": \"string\",\n \"maxLength\": 200\n },\n \"signed_at\": {\n \"type\": \"string\",\n \"format\": \"date-time\"\n },\n \"signed_by\": {\n \"type\": \"string\",\n \"maxLength\": 200\n }\n }\n }\n },\n \"$defs\": {\n \"agent_execution_user_policy\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"dailyCapUsd\": {\n \"type\": \"number\",\n \"exclusiveMinimum\": 0\n },\n \"perRequestCapUsd\": {\n \"type\": \"number\",\n \"exclusiveMinimum\": 0\n }\n }\n },\n \"agent_execution_defaults\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"userDailyCapUsd\": {\n \"type\": \"number\",\n \"exclusiveMinimum\": 0\n },\n \"perRequestCapUsd\": {\n \"type\": \"number\",\n \"exclusiveMinimum\": 0\n }\n },\n \"required\": [\"userDailyCapUsd\", \"perRequestCapUsd\"]\n },\n \"agent_model_rate_card\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"provider\": {\n \"type\": \"string\",\n \"enum\": [\"openai\", \"anthropic\", \"github_copilot\", \"custom\"]\n },\n \"model\": {\n \"type\": \"string\",\n \"minLength\": 1,\n \"maxLength\": 200\n },\n \"pricingBasis\": {\n \"type\": \"string\",\n \"enum\": [\"OFFICIAL_LIST_PRICE\", \"NEGOTIATED_CONTRACT\"]\n },\n \"sourceUrl\": {\n \"type\": [\"string\", \"null\"],\n \"format\": \"uri\",\n \"maxLength\": 2000\n },\n \"contractId\": {\n \"type\": [\"string\", \"null\"],\n \"maxLength\": 200\n },\n \"contractVersion\": {\n \"type\": [\"string\", \"null\"],\n \"maxLength\": 100\n },\n \"contractReference\": {\n \"type\": [\"string\", \"null\"],\n \"maxLength\": 1000\n },\n \"effectiveFrom\": {\n \"type\": [\"string\", \"null\"],\n \"format\": \"date-time\"\n },\n \"expiresAt\": {\n \"type\": [\"string\", \"null\"],\n \"format\": \"date-time\"\n },\n \"inputUsdPerMillionTokens\": {\n \"type\": \"number\",\n \"minimum\": 0\n },\n \"outputUsdPerMillionTokens\": {\n \"type\": \"number\",\n \"minimum\": 0\n },\n \"cachedInputUsdPerMillionTokens\": {\n \"type\": [\"number\", \"null\"],\n \"minimum\": 0\n },\n \"cacheCreationUsdPerMillionTokens\": {\n \"type\": [\"number\", \"null\"],\n \"minimum\": 0\n },\n \"cacheCreationOneHourUsdPerMillionTokens\": {\n \"type\": [\"number\", \"null\"],\n \"minimum\": 0\n },\n \"longContextThresholdTokens\": {\n \"type\": [\"integer\", \"null\"],\n \"minimum\": 1\n },\n \"longContextInputUsdPerMillionTokens\": {\n \"type\": [\"number\", \"null\"],\n \"minimum\": 0\n },\n \"longContextOutputUsdPerMillionTokens\": {\n \"type\": [\"number\", \"null\"],\n \"minimum\": 0\n },\n \"longContextCachedInputUsdPerMillionTokens\": {\n \"type\": [\"number\", \"null\"],\n \"minimum\": 0\n },\n \"longContextCacheCreationUsdPerMillionTokens\": {\n \"type\": [\"number\", \"null\"],\n \"minimum\": 0\n },\n \"toolCallUsd\": {\n \"type\": \"number\",\n \"minimum\": 0\n }\n },\n \"required\": [\n \"provider\",\n \"model\",\n \"inputUsdPerMillionTokens\",\n \"outputUsdPerMillionTokens\",\n \"cachedInputUsdPerMillionTokens\",\n \"cacheCreationUsdPerMillionTokens\",\n \"toolCallUsd\"\n ]\n },\n \"agent_provider_contract\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"contractId\": {\n \"type\": \"string\",\n \"minLength\": 1,\n \"maxLength\": 200\n },\n \"version\": {\n \"type\": \"string\",\n \"minLength\": 1,\n \"maxLength\": 100\n },\n \"provider\": {\n \"type\": \"string\",\n \"enum\": [\"openai\", \"anthropic\", \"github_copilot\", \"custom\"]\n },\n \"contractReference\": {\n \"type\": \"string\",\n \"minLength\": 1,\n \"maxLength\": 1000\n },\n \"status\": {\n \"type\": \"string\",\n \"enum\": [\"DRAFT\", \"APPROVED\", \"REVOKED\"]\n },\n \"authoredBy\": {\n \"type\": \"string\",\n \"minLength\": 1,\n \"maxLength\": 200\n },\n \"approvedBy\": {\n \"type\": [\"string\", \"null\"],\n \"minLength\": 1,\n \"maxLength\": 200\n },\n \"approvedAt\": {\n \"type\": [\"string\", \"null\"],\n \"format\": \"date-time\"\n },\n \"effectiveFrom\": {\n \"type\": \"string\",\n \"format\": \"date-time\"\n },\n \"expiresAt\": {\n \"type\": [\"string\", \"null\"],\n \"format\": \"date-time\"\n },\n \"rateCards\": {\n \"type\": \"array\",\n \"minItems\": 1,\n \"items\": {\n \"$ref\": \"#/$defs/agent_model_rate_card\"\n }\n }\n },\n \"required\": [\n \"contractId\",\n \"version\",\n \"provider\",\n \"contractReference\",\n \"status\",\n \"authoredBy\",\n \"approvedBy\",\n \"approvedAt\",\n \"effectiveFrom\",\n \"expiresAt\",\n \"rateCards\"\n ],\n \"allOf\": [\n {\n \"if\": {\n \"properties\": {\n \"status\": {\n \"const\": \"APPROVED\"\n }\n },\n \"required\": [\"status\"]\n },\n \"then\": {\n \"properties\": {\n \"approvedBy\": {\n \"type\": \"string\",\n \"minLength\": 1\n },\n \"approvedAt\": {\n \"type\": \"string\",\n \"format\": \"date-time\"\n }\n }\n }\n }\n ]\n },\n \"agent_execution_policy\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"mode\": {\n \"type\": \"string\",\n \"enum\": [\"SHADOW\", \"ENFORCEMENT\"]\n },\n \"orgMonthlyCapUsd\": {\n \"type\": \"number\",\n \"exclusiveMinimum\": 0\n },\n \"allowedProviders\": {\n \"type\": \"array\",\n \"uniqueItems\": true,\n \"items\": {\n \"type\": \"string\",\n \"enum\": [\"openai\", \"anthropic\", \"github_copilot\", \"custom\"]\n }\n },\n \"allowedModels\": {\n \"type\": \"array\",\n \"uniqueItems\": true,\n \"items\": {\n \"type\": \"string\",\n \"minLength\": 1,\n \"maxLength\": 200\n }\n },\n \"reservationTtlSeconds\": {\n \"type\": \"integer\",\n \"minimum\": 30,\n \"maximum\": 3600\n },\n \"defaults\": {\n \"$ref\": \"#/$defs/agent_execution_defaults\"\n },\n \"users\": {\n \"type\": \"object\",\n \"additionalProperties\": {\n \"$ref\": \"#/$defs/agent_execution_user_policy\"\n }\n },\n \"rateCards\": {\n \"type\": \"array\",\n \"minItems\": 1,\n \"items\": {\n \"$ref\": \"#/$defs/agent_model_rate_card\"\n }\n },\n \"providerContracts\": {\n \"type\": \"array\",\n \"items\": {\n \"$ref\": \"#/$defs/agent_provider_contract\"\n },\n \"description\": \"Organization-owned negotiated provider contracts. An entry overrides official rate cards only while approved, maker-checker valid, and effective.\"\n }\n },\n \"required\": [\n \"mode\",\n \"orgMonthlyCapUsd\",\n \"allowedProviders\",\n \"allowedModels\",\n \"reservationTtlSeconds\",\n \"defaults\",\n \"rateCards\"\n ]\n },\n \"predicate\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"field\": {\n \"type\": \"string\",\n \"minLength\": 1,\n \"maxLength\": 200\n },\n \"operator\": {\n \"type\": \"string\",\n \"enum\": [\n \"EQ\",\n \"NEQ\",\n \"GT\",\n \"GTE\",\n \"LT\",\n \"LTE\",\n \"IN\",\n \"NOT_IN\",\n \"EXISTS\",\n \"CONTAINS\",\n \"MATCHES\"\n ]\n },\n \"value\": {},\n \"values\": {\n \"type\": \"array\"\n }\n },\n \"required\": [\"field\", \"operator\"]\n },\n \"condition_group\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"all\": {\n \"type\": \"array\",\n \"items\": {\n \"oneOf\": [\n {\n \"$ref\": \"#/$defs/predicate\"\n },\n {\n \"$ref\": \"#/$defs/condition_group\"\n }\n ]\n }\n },\n \"any\": {\n \"type\": \"array\",\n \"items\": {\n \"oneOf\": [\n {\n \"$ref\": \"#/$defs/predicate\"\n },\n {\n \"$ref\": \"#/$defs/condition_group\"\n }\n ]\n }\n }\n }\n }\n },\n \"required\": [\"protocol_version\", \"bundle_id\", \"org_id\", \"version\", \"effective_from\", \"rules\"]\n}\n","{\n \"$schema\": \"https://json-schema.org/draft/2020-12/schema\",\n \"$id\": \"https://decionis.io/protocol/schemas/v1/signal-envelope.schema.json\",\n \"title\": \"Signal Envelope\",\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"protocol_version\": {\n \"type\": \"string\",\n \"pattern\": \"^1\\\\.[0-9]+(\\\\.[0-9]+)?$\"\n },\n \"envelope_id\": {\n \"type\": \"string\",\n \"format\": \"uuid\"\n },\n \"org_id\": {\n \"type\": \"string\"\n },\n \"source\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"provider\": {\n \"type\": \"string\",\n \"minLength\": 1,\n \"maxLength\": 120\n },\n \"connector_id\": {\n \"type\": \"string\",\n \"minLength\": 1,\n \"maxLength\": 200\n },\n \"mode\": {\n \"type\": \"string\",\n \"enum\": [\"DIRECT_API\", \"CUSTOMER_INFRA\", \"WEBHOOK\", \"MANUAL\"]\n }\n },\n \"required\": [\"provider\", \"mode\"]\n },\n \"domain\": {\n \"type\": \"string\",\n \"minLength\": 1,\n \"maxLength\": 120\n },\n \"metric_name\": {\n \"type\": \"string\",\n \"minLength\": 1,\n \"maxLength\": 200\n },\n \"metric_type\": {\n \"type\": \"string\",\n \"enum\": [\"gauge\", \"counter\", \"event\", \"categorical\"]\n },\n \"value\": {\n \"oneOf\": [\n {\n \"type\": \"number\"\n },\n {\n \"type\": \"string\"\n },\n {\n \"type\": \"boolean\"\n },\n {\n \"type\": \"object\"\n },\n {\n \"type\": \"array\"\n }\n ]\n },\n \"unit\": {\n \"type\": \"string\",\n \"maxLength\": 60\n },\n \"recorded_at\": {\n \"type\": \"string\",\n \"format\": \"date-time\"\n },\n \"ingested_at\": {\n \"type\": \"string\",\n \"format\": \"date-time\"\n },\n \"dimensions\": {\n \"type\": \"object\",\n \"additionalProperties\": {\n \"oneOf\": [\n {\n \"type\": \"string\"\n },\n {\n \"type\": \"number\"\n },\n {\n \"type\": \"boolean\"\n }\n ]\n }\n },\n \"evidence\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"string\",\n \"maxLength\": 2000\n },\n \"maxItems\": 100\n },\n \"trace\": {\n \"type\": \"object\",\n \"additionalProperties\": false,\n \"properties\": {\n \"request_id\": {\n \"type\": \"string\",\n \"maxLength\": 200\n },\n \"correlation_id\": {\n \"type\": \"string\",\n \"maxLength\": 200\n },\n \"producer\": {\n \"type\": \"string\",\n \"maxLength\": 200\n }\n }\n },\n \"hash\": {\n \"type\": \"string\",\n \"pattern\": \"^[A-Fa-f0-9]{64}$\"\n }\n },\n \"required\": [\n \"protocol_version\",\n \"envelope_id\",\n \"org_id\",\n \"source\",\n \"domain\",\n \"metric_name\",\n \"metric_type\",\n \"value\",\n \"recorded_at\",\n \"ingested_at\"\n ]\n}\n","export const FINANCE_OVERRIDE_REASON_CODES = [\n \"POLICY_EXCEPTION\",\n \"RISK_THRESHOLD_OVERRIDE\",\n \"CUSTOMER_IMPACT_HOTFIX\",\n \"FRAUD_SIGNAL\",\n \"REGULATORY_OBLIGATION\",\n \"SYSTEM_DEGRADATION\",\n \"BUSINESS_CONTINUITY\",\n \"MANUAL_VERIFICATION_REQUIRED\",\n] as const;\n\nexport type FinanceOverrideReasonCode = (typeof FINANCE_OVERRIDE_REASON_CODES)[number];\n\nexport type OverrideReviewOutcome = \"APPROVE\" | \"REJECT\" | \"ESCALATE\";\n\nexport type ProtocolActorType = \"ORG_API_KEY\" | \"PLATFORM_API_KEY\" | \"USER\" | \"SERVICE\";\n\nexport interface FinanceOverrideSubmitRequest {\n org_id: string;\n override_id: string;\n decision_type: string;\n decision_band: string;\n transaction_type: string;\n reason_code: FinanceOverrideReasonCode;\n reason_detail: string | null;\n approval_path: string[];\n evidence_refs: string[];\n requested_by_actor_type: ProtocolActorType;\n requested_by_actor_id: string;\n risk_level: \"low\" | \"medium\" | \"high\" | \"critical\";\n confidence: number;\n idempotency_key: string | null;\n}\n\nexport interface FinanceOverrideSubmitResponse {\n override_id: string;\n status: \"SUBMITTED\";\n reason_code: FinanceOverrideReasonCode;\n submitted_at: string;\n decision_resolution_id: string;\n ledger_entry_id: string;\n ledger_entry_hash: string;\n}\n\nexport interface FinanceOverrideReviewRequest {\n org_id: string;\n override_id: string;\n review_outcome: OverrideReviewOutcome;\n review_note: string | null;\n reviewer_actor_type: ProtocolActorType;\n reviewer_actor_id: string;\n confidence: number;\n idempotency_key: string | null;\n}\n\nexport interface FinanceOverrideReviewResponse {\n override_id: string;\n status: \"APPROVED\" | \"REJECTED\" | \"ESCALATED\";\n review_outcome: OverrideReviewOutcome;\n reviewed_at: string;\n decision_resolution_id: string;\n ledger_entry_id: string;\n ledger_entry_hash: string;\n}\n","import { createHash, randomUUID } from \"node:crypto\";\nimport {\n ProtocolStoreValidationError,\n type ProtocolPayload,\n type ProtocolStore,\n} from \"../store/StoreContracts.js\";\nimport { validateProtocolArtifact } from \"../validation/ProtocolArtifacts.js\";\nimport { computeLedgerEntryHash } from \"../ledger/LedgerChain.js\";\nimport { PROTOCOL_VERSION } from \"../ProtocolInfo.js\";\nimport { asNumber, asRecord, asString, clamp, isLikelyUuid } from \"../support/Parsing.js\";\nimport {\n FINANCE_OVERRIDE_REASON_CODES,\n type FinanceOverrideReasonCode,\n type FinanceOverrideReviewRequest,\n type FinanceOverrideSubmitRequest,\n type OverrideReviewOutcome,\n type ProtocolActorType,\n} from \"./FinanceOverrideContracts.js\";\n\n/** Finance override request parsing, resolution building, and ledger chaining. */\nexport class FinanceOverrides {\n static parseActorType(value: unknown): ProtocolActorType | null {\n const raw = asString(value)?.toUpperCase();\n if (raw === \"ORG_API_KEY\") return \"ORG_API_KEY\";\n if (raw === \"PLATFORM_API_KEY\") return \"PLATFORM_API_KEY\";\n if (raw === \"USER\") return \"USER\";\n if (raw === \"SERVICE\") return \"SERVICE\";\n return null;\n }\n\n static parseRiskLevel(value: unknown): \"low\" | \"medium\" | \"high\" | \"critical\" | null {\n const raw = asString(value)?.toLowerCase();\n if (raw === \"low\" || raw === \"medium\" || raw === \"high\" || raw === \"critical\") return raw;\n return null;\n }\n\n static isFinanceOverrideReasonCode(value: string): value is FinanceOverrideReasonCode {\n return (FINANCE_OVERRIDE_REASON_CODES as readonly string[]).includes(value);\n }\n\n static parseFinanceOverrideSubmitRequest(input: unknown):\n | { ok: true; value: FinanceOverrideSubmitRequest }\n | {\n ok: false;\n message: string;\n } {\n const record = asRecord(input);\n const orgId = asString(record.org_id);\n if (!orgId) return { ok: false, message: \"org_id is required\" };\n if (!isLikelyUuid(orgId)) return { ok: false, message: \"org_id must be a UUID\" };\n\n const overrideId = asString(record.override_id) ?? randomUUID();\n if (!isLikelyUuid(overrideId)) return { ok: false, message: \"override_id must be a UUID\" };\n\n const decisionType = asString(record.decision_type);\n if (!decisionType) return { ok: false, message: \"decision_type is required\" };\n\n const decisionBand = asString(record.decision_band);\n if (!decisionBand) return { ok: false, message: \"decision_band is required\" };\n\n const transactionType = asString(record.transaction_type);\n if (!transactionType) return { ok: false, message: \"transaction_type is required\" };\n\n const reasonCodeRaw = asString(record.reason_code)?.toUpperCase();\n if (!reasonCodeRaw || !isFinanceOverrideReasonCode(reasonCodeRaw)) {\n return {\n ok: false,\n message: `reason_code must be one of ${FINANCE_OVERRIDE_REASON_CODES.join(\", \")}`,\n };\n }\n\n const approvalPath = Array.isArray(record.approval_path)\n ? record.approval_path\n .map((item) => asString(item))\n .filter((item): item is string => Boolean(item))\n : [];\n if (approvalPath.length === 0) {\n return { ok: false, message: \"approval_path must include at least one approver stage\" };\n }\n\n const requestedByActorType = parseActorType(record.requested_by_actor_type);\n if (!requestedByActorType) {\n return {\n ok: false,\n message:\n \"requested_by_actor_type must be one of ORG_API_KEY, PLATFORM_API_KEY, USER, SERVICE\",\n };\n }\n const requestedByActorId = asString(record.requested_by_actor_id);\n if (!requestedByActorId) return { ok: false, message: \"requested_by_actor_id is required\" };\n\n const riskLevel = parseRiskLevel(record.risk_level) ?? \"high\";\n const confidence = asNumber(record.confidence) ?? 0.8;\n if (confidence < 0 || confidence > 1) {\n return { ok: false, message: \"confidence must be between 0 and 1\" };\n }\n\n const evidenceRefs = Array.isArray(record.evidence_refs)\n ? record.evidence_refs\n .map((item) => asString(item))\n .filter((item): item is string => Boolean(item))\n : [];\n\n return {\n ok: true,\n value: {\n org_id: orgId,\n override_id: overrideId,\n decision_type: decisionType,\n decision_band: decisionBand,\n transaction_type: transactionType,\n reason_code: reasonCodeRaw,\n reason_detail: asString(record.reason_detail),\n approval_path: approvalPath,\n evidence_refs: evidenceRefs,\n requested_by_actor_type: requestedByActorType,\n requested_by_actor_id: requestedByActorId,\n risk_level: riskLevel,\n confidence: Number.parseFloat(clamp(confidence, 0, 1).toFixed(4)),\n idempotency_key: asString(record.idempotency_key),\n },\n };\n }\n\n static parseFinanceOverrideReviewRequest(input: unknown):\n | { ok: true; value: FinanceOverrideReviewRequest }\n | {\n ok: false;\n message: string;\n } {\n const record = asRecord(input);\n const orgId = asString(record.org_id);\n if (!orgId) return { ok: false, message: \"org_id is required\" };\n if (!isLikelyUuid(orgId)) return { ok: false, message: \"org_id must be a UUID\" };\n\n const overrideId = asString(record.override_id);\n if (!overrideId) return { ok: false, message: \"override_id is required\" };\n if (!isLikelyUuid(overrideId)) return { ok: false, message: \"override_id must be a UUID\" };\n\n const reviewOutcomeRaw = asString(record.review_outcome)?.toUpperCase();\n const reviewOutcome =\n reviewOutcomeRaw === \"APPROVE\" ||\n reviewOutcomeRaw === \"REJECT\" ||\n reviewOutcomeRaw === \"ESCALATE\"\n ? reviewOutcomeRaw\n : null;\n if (!reviewOutcome) {\n return { ok: false, message: \"review_outcome must be one of APPROVE, REJECT, ESCALATE\" };\n }\n\n const reviewerActorType = parseActorType(record.reviewer_actor_type);\n if (!reviewerActorType) {\n return {\n ok: false,\n message: \"reviewer_actor_type must be one of ORG_API_KEY, PLATFORM_API_KEY, USER, SERVICE\",\n };\n }\n const reviewerActorId = asString(record.reviewer_actor_id);\n if (!reviewerActorId) return { ok: false, message: \"reviewer_actor_id is required\" };\n\n const confidence = asNumber(record.confidence) ?? 0.8;\n if (confidence < 0 || confidence > 1) {\n return { ok: false, message: \"confidence must be between 0 and 1\" };\n }\n\n return {\n ok: true,\n value: {\n org_id: orgId,\n override_id: overrideId,\n review_outcome: reviewOutcome,\n review_note: asString(record.review_note),\n reviewer_actor_type: reviewerActorType,\n reviewer_actor_id: reviewerActorId,\n confidence: Number.parseFloat(clamp(confidence, 0, 1).toFixed(4)),\n idempotency_key: asString(record.idempotency_key),\n },\n };\n }\n\n static overrideReviewOutcomeToDecisionStatus(\n reviewOutcome: OverrideReviewOutcome,\n ): \"APPROVED\" | \"REJECTED\" | \"ESCALATED\" {\n if (reviewOutcome === \"APPROVE\") return \"APPROVED\";\n if (reviewOutcome === \"REJECT\") return \"REJECTED\";\n return \"ESCALATED\";\n }\n\n static normalizeAuditActorType(\n input: ProtocolActorType,\n ): \"ORG_API_KEY\" | \"PLATFORM_API_KEY\" | \"USER\" | \"SERVICE\" {\n return input;\n }\n\n static buildFinanceOverrideDecisionResolution(input: {\n org_id: string;\n override_id: string;\n decision_type: string;\n decision_band: string;\n transaction_type: string;\n reason_code: FinanceOverrideReasonCode;\n reason_detail: string | null;\n actor_type: ProtocolActorType;\n actor_id: string;\n confidence: number;\n risk_level: \"low\" | \"medium\" | \"high\" | \"critical\";\n approval_path: string[];\n evidence_refs: string[];\n status: \"PROPOSED\" | \"APPROVED\" | \"REJECTED\" | \"ESCALATED\";\n review_outcome: OverrideReviewOutcome | null;\n review_note: string | null;\n occurred_at: string;\n }): { resolutionId: string; payload: ProtocolPayload } {\n const resolutionId = randomUUID();\n const lifecycleTag = input.review_outcome == null ? \"submitted\" : \"reviewed\";\n\n const payload: ProtocolPayload = {\n protocol_version: PROTOCOL_VERSION,\n resolution_id: resolutionId,\n org_id: input.org_id,\n cycle_id: input.override_id,\n decision_domain: \"FINANCIAL_ROUTING\",\n status: input.status,\n confidence: input.confidence,\n risk_level: input.risk_level,\n rationale:\n input.review_outcome == null\n ? `Override requested with reason_code=${input.reason_code}${input.reason_detail ? `; detail=${input.reason_detail}` : \"\"}`\n : `Override ${input.review_outcome.toLowerCase()} by reviewer${input.review_note ? `; note=${input.review_note}` : \"\"}`,\n decided_at: input.occurred_at,\n inputs: {\n context_snapshot_id: randomUUID(),\n policy_bundle_id: randomUUID(),\n signal_ids: [\n `override:${input.override_id}`,\n `decision_type:${input.decision_type}`,\n `transaction_type:${input.transaction_type}`,\n ],\n },\n outputs: {\n recommended_action:\n input.review_outcome == null\n ? \"Route override request for deterministic review.\"\n : `Override ${input.review_outcome.toLowerCase()} recorded.`,\n owner: input.actor_id,\n tags: [\n \"finance_override\",\n `lifecycle:${lifecycleTag}`,\n `reason_code:${input.reason_code}`,\n `decision_band:${input.decision_band}`,\n `transaction_type:${input.transaction_type}`,\n ],\n artifacts: input.evidence_refs,\n },\n trace: {\n trigger_id: input.override_id,\n resolver_version: \"finance-override-v1\",\n deterministic_seed: createHash(\"sha256\")\n .update(`${input.override_id}:${lifecycleTag}`, \"utf8\")\n .digest(\"hex\")\n .slice(0, 16),\n },\n compliance: {\n checks: [\n {\n name: \"override_reason_code_present\",\n result: \"PASS\",\n details: input.reason_code,\n },\n {\n name: \"approval_path_recorded\",\n result: input.approval_path.length > 0 ? \"PASS\" : \"FAIL\",\n details: input.approval_path.join(\" > \"),\n },\n ],\n },\n };\n\n return { resolutionId, payload };\n }\n\n static async findFinanceOverrideSubmission(\n store: ProtocolStore,\n input: { org_id: string; override_id: string },\n ): Promise<Record<string, unknown> | null> {\n const entries = await store.listAuditLedgerEntries({ orgId: input.org_id, limit: 500 });\n for (const entry of entries) {\n const record = asRecord(entry);\n if (asString(record.action) !== \"finance.override.submitted\") continue;\n const payload = asRecord(record.payload);\n if (asString(payload.override_id) === input.override_id) {\n return record;\n }\n }\n return null;\n }\n\n static async findFinanceOverrideLedgerByIdempotency(\n store: ProtocolStore,\n input: {\n org_id: string;\n override_id: string;\n action: \"finance.override.submitted\" | \"finance.override.reviewed\";\n idempotency_key: string;\n },\n ): Promise<Record<string, unknown> | null> {\n const entries = await store.listAuditLedgerEntries({ orgId: input.org_id, limit: 500 });\n for (const entry of entries) {\n const record = asRecord(entry);\n if (asString(record.action) !== input.action) continue;\n const payload = asRecord(record.payload);\n if (asString(payload.override_id) !== input.override_id) continue;\n if (asString(payload.idempotency_key) !== input.idempotency_key) continue;\n return record;\n }\n return null;\n }\n\n static async appendFinanceOverrideLedgerEvent(\n store: ProtocolStore,\n input: {\n org_id: string;\n override_id: string;\n action: \"finance.override.submitted\" | \"finance.override.reviewed\";\n actor_type: ProtocolActorType;\n actor_id: string;\n payload: Record<string, unknown>;\n decision_resolution_id: string;\n occurred_at: string;\n },\n ): Promise<{ ledger_entry_id: string; ledger_entry_hash: string }> {\n const previousHead = await store.getLatestAuditLedgerHead(input.org_id);\n const ledgerEntryId = randomUUID();\n const entryHash = computeLedgerEntryHash({\n ledger_entry_id: ledgerEntryId,\n org_id: input.org_id,\n event_type: \"DECISION_RESOLVED\",\n occurred_at: input.occurred_at,\n action: input.action,\n actor: {\n type: normalizeAuditActorType(input.actor_type),\n id: input.actor_id,\n },\n object: {\n type: \"DECISION\",\n id: input.override_id,\n },\n links: {\n decision_resolution_id: input.decision_resolution_id,\n },\n payload: input.payload,\n prev_hash: previousHead?.entry_hash ?? null,\n });\n\n const ledgerPayload: ProtocolPayload = {\n protocol_version: PROTOCOL_VERSION,\n ledger_entry_id: ledgerEntryId,\n org_id: input.org_id,\n event_type: \"DECISION_RESOLVED\",\n occurred_at: input.occurred_at,\n actor: {\n type: normalizeAuditActorType(input.actor_type),\n id: input.actor_id,\n },\n object: {\n type: \"DECISION\",\n id: input.override_id,\n },\n action: input.action,\n payload: input.payload,\n links: {\n decision_resolution_id: input.decision_resolution_id,\n },\n chain: {\n prev_hash: previousHead?.entry_hash ?? undefined,\n entry_hash: entryHash,\n algorithm: \"SHA256\",\n },\n integrity: {\n verified: false,\n },\n };\n\n const validation = validateProtocolArtifact(\"audit_ledger_entry\", ledgerPayload);\n if (!validation.ok) {\n throw new ProtocolStoreValidationError(\n \"Invalid finance override ledger payload\",\n validation.issues,\n );\n }\n await store.saveArtifact(\"audit_ledger_entry\", validation.value);\n return { ledger_entry_id: ledgerEntryId, ledger_entry_hash: entryHash };\n }\n}\n\n/** Functional alias for {@link FinanceOverrides.parseActorType}. */\nexport function parseActorType(value: unknown): ProtocolActorType | null {\n return FinanceOverrides.parseActorType(value);\n}\n\n/** Functional alias for {@link FinanceOverrides.parseRiskLevel}. */\nexport function parseRiskLevel(value: unknown): \"low\" | \"medium\" | \"high\" | \"critical\" | null {\n return FinanceOverrides.parseRiskLevel(value);\n}\n\n/** Functional alias for {@link FinanceOverrides.isFinanceOverrideReasonCode}. */\nexport function isFinanceOverrideReasonCode(value: string): value is FinanceOverrideReasonCode {\n return FinanceOverrides.isFinanceOverrideReasonCode(value);\n}\n\n/** Functional alias for {@link FinanceOverrides.parseFinanceOverrideSubmitRequest}. */\nexport function parseFinanceOverrideSubmitRequest(input: unknown):\n | { ok: true; value: FinanceOverrideSubmitRequest }\n | {\n ok: false;\n message: string;\n } {\n return FinanceOverrides.parseFinanceOverrideSubmitRequest(input);\n}\n\n/** Functional alias for {@link FinanceOverrides.parseFinanceOverrideReviewRequest}. */\nexport function parseFinanceOverrideReviewRequest(input: unknown):\n | { ok: true; value: FinanceOverrideReviewRequest }\n | {\n ok: false;\n message: string;\n } {\n return FinanceOverrides.parseFinanceOverrideReviewRequest(input);\n}\n\n/** Functional alias for {@link FinanceOverrides.overrideReviewOutcomeToDecisionStatus}. */\nexport function overrideReviewOutcomeToDecisionStatus(\n reviewOutcome: OverrideReviewOutcome,\n): \"APPROVED\" | \"REJECTED\" | \"ESCALATED\" {\n return FinanceOverrides.overrideReviewOutcomeToDecisionStatus(reviewOutcome);\n}\n\n/** Functional alias for {@link FinanceOverrides.normalizeAuditActorType}. */\nexport function normalizeAuditActorType(\n input: ProtocolActorType,\n): \"ORG_API_KEY\" | \"PLATFORM_API_KEY\" | \"USER\" | \"SERVICE\" {\n return FinanceOverrides.normalizeAuditActorType(input);\n}\n\n/** Functional alias for {@link FinanceOverrides.buildFinanceOverrideDecisionResolution}. */\nexport function buildFinanceOverrideDecisionResolution(input: {\n org_id: string;\n override_id: string;\n decision_type: string;\n decision_band: string;\n transaction_type: string;\n reason_code: FinanceOverrideReasonCode;\n reason_detail: string | null;\n actor_type: ProtocolActorType;\n actor_id: string;\n confidence: number;\n risk_level: \"low\" | \"medium\" | \"high\" | \"critical\";\n approval_path: string[];\n evidence_refs: string[];\n status: \"PROPOSED\" | \"APPROVED\" | \"REJECTED\" | \"ESCALATED\";\n review_outcome: OverrideReviewOutcome | null;\n review_note: string | null;\n occurred_at: string;\n}): { resolutionId: string; payload: ProtocolPayload } {\n return FinanceOverrides.buildFinanceOverrideDecisionResolution(input);\n}\n\n/** Functional alias for {@link FinanceOverrides.findFinanceOverrideSubmission}. */\nexport function findFinanceOverrideSubmission(\n store: ProtocolStore,\n input: { org_id: string; override_id: string },\n): Promise<Record<string, unknown> | null> {\n return FinanceOverrides.findFinanceOverrideSubmission(store, input);\n}\n\n/** Functional alias for {@link FinanceOverrides.findFinanceOverrideLedgerByIdempotency}. */\nexport function findFinanceOverrideLedgerByIdempotency(\n store: ProtocolStore,\n input: {\n org_id: string;\n override_id: string;\n action: \"finance.override.submitted\" | \"finance.override.reviewed\";\n idempotency_key: string;\n },\n): Promise<Record<string, unknown> | null> {\n return FinanceOverrides.findFinanceOverrideLedgerByIdempotency(store, input);\n}\n\n/** Functional alias for {@link FinanceOverrides.appendFinanceOverrideLedgerEvent}. */\nexport function appendFinanceOverrideLedgerEvent(\n store: ProtocolStore,\n input: {\n org_id: string;\n override_id: string;\n action: \"finance.override.submitted\" | \"finance.override.reviewed\";\n actor_type: ProtocolActorType;\n actor_id: string;\n payload: Record<string, unknown>;\n decision_resolution_id: string;\n occurred_at: string;\n },\n): Promise<{ ledger_entry_id: string; ledger_entry_hash: string }> {\n return FinanceOverrides.appendFinanceOverrideLedgerEvent(store, input);\n}\n","import { createHash, randomUUID } from \"node:crypto\";\nimport type { FastifyInstance, FastifyReply, FastifyRequest } from \"fastify\";\nimport type { ProtocolStore } from \"../store/StoreContracts.js\";\nimport { validateProtocolArtifact } from \"../validation/ProtocolArtifacts.js\";\nimport { asRecord, asString, parseIdempotencyHeader } from \"../support/Parsing.js\";\nimport {\n buildProtocolPerformanceSnapshot,\n buildServerTimingHeader,\n durationMs,\n roundDurationMs,\n} from \"../support/Performance.js\";\nimport {\n buildEvaluateDecisionPolicySnapshot,\n evaluateDecisionPolicyGraph,\n loadEvaluateDecisionPolicyRuntime,\n resolveBlockedPolicyVersion,\n resolveEvaluateDecisionConfidenceFromPolicyEvaluation,\n resolveEvaluateDecisionOutcomeFromPolicyEvaluation,\n} from \"../policy-graph/PolicyGraph.js\";\nimport type { EvaluateDecisionPolicyEvaluation } from \"../policy-graph/PolicyGraphContracts.js\";\nimport { getVerticalPack } from \"../verticals/VerticalRegistry.js\";\nimport { resolveVerticalPackForRequest } from \"../verticals/VerticalResolver.js\";\nimport {\n buildDecisionChainLinkInput,\n decisionChainSummaryFromRow,\n} from \"../decision-chains/DecisionChains.js\";\nimport { buildDecisionDossier, computeDossierContentSha } from \"../dossiers/DossierBuilder.js\";\nimport { reproduceDecisionFromDossierPayload } from \"../reproduce/ReproduceDecision.js\";\nimport {\n hydrateCachedEvaluateResponse,\n parseEvaluateDecisionRequest,\n} from \"./EvaluateDecisionParsing.js\";\nimport {\n buildGovernanceMetrics,\n resolveEvaluateRolloutPolicy,\n} from \"./EvaluateDecisionGovernance.js\";\nimport {\n appendEvaluateDecisionLedgerEvent,\n buildEvaluateDecisionResolution,\n resolveEvaluateDecisionDomain,\n} from \"./EvaluateDecisionResolution.js\";\nimport type {\n EvaluateDecisionReconciliationStatus,\n EvaluateDecisionRequest,\n EvaluateDecisionResponse,\n} from \"./EvaluateDecisionContracts.js\";\n\n/** Registers the shared evaluate-decision pipeline routes (legacy and versioned paths). */\nexport function registerEvaluateDecisionRoutes(\n app: FastifyInstance,\n deps: { store: ProtocolStore },\n): void {\n const { store } = deps;\n\n const evaluateDecisionHandler = async (req: FastifyRequest, reply: FastifyReply) => {\n const handlerStartedAt = process.hrtime.bigint();\n const measuredAt = new Date().toISOString();\n const performanceStages: Record<string, number> = {};\n const idempotencyHeader = parseIdempotencyHeader(req.headers as Record<string, unknown>);\n\n const parsed = parseEvaluateDecisionRequest(req.body, idempotencyHeader);\n if (!parsed.ok) {\n return reply.code(400).send({ error: \"VALIDATION_ERROR\", message: parsed.message });\n }\n if (parsed.value.vertical_pack && !getVerticalPack(parsed.value.vertical_pack)) {\n return reply.code(400).send({\n error: \"VALIDATION_ERROR\",\n message: `Unknown vertical pack '${parsed.value.vertical_pack}'`,\n });\n }\n\n if (parsed.value.idempotency_key) {\n const existing = await store.getDecisionEvaluationByIdempotency({\n orgId: parsed.value.org_id,\n idempotencyKey: parsed.value.idempotency_key,\n });\n if (existing) {\n const cachedResponse = hydrateCachedEvaluateResponse(existing);\n reply.header(\n \"server-timing\",\n buildServerTimingHeader({\n measured_at: measuredAt,\n total_latency_ms: roundDurationMs(durationMs(handlerStartedAt)),\n stages: {\n cache_hit_ms: roundDurationMs(durationMs(handlerStartedAt)),\n },\n }),\n );\n return reply.code(200).send({\n ...cachedResponse,\n idempotent_replay: true,\n });\n }\n }\n\n const verticalPackStartedAt = process.hrtime.bigint();\n const resolvedVerticalPack = await resolveVerticalPackForRequest({\n store,\n orgId: parsed.value.org_id,\n requestedPackKey: parsed.value.vertical_pack ?? undefined,\n workflowKey: parsed.value.workflow_key ?? undefined,\n });\n performanceStages.vertical_pack_resolution_ms = durationMs(verticalPackStartedAt);\n const requestRecord = asRecord(req.body);\n const explicitPolicyVersion = asString(requestRecord.policy_version);\n const requestedPolicyVersion =\n explicitPolicyVersion ?? resolvedVerticalPack.pack.policy_bundle.version;\n\n const evaluateInputBase: EvaluateDecisionRequest = {\n ...parsed.value,\n policy_version: requestedPolicyVersion,\n context: {\n ...parsed.value.context,\n vertical_pack: resolvedVerticalPack.pack.key,\n workflow_key: parsed.value.workflow_key ?? null,\n },\n };\n\n const rolloutPolicyStartedAt = process.hrtime.bigint();\n const rolloutPolicy = await resolveEvaluateRolloutPolicy(store, evaluateInputBase);\n performanceStages.rollout_resolution_ms = durationMs(rolloutPolicyStartedAt);\n const effectiveInput: EvaluateDecisionRequest = {\n ...evaluateInputBase,\n mode: rolloutPolicy.effective_mode,\n };\n const policyGuardStartedAt = process.hrtime.bigint();\n const policyRuntime = await loadEvaluateDecisionPolicyRuntime({\n store,\n orgId: parsed.value.org_id,\n evaluated_at: measuredAt,\n requested_policy_version: explicitPolicyVersion,\n });\n performanceStages.policy_guard_resolution_ms = durationMs(policyGuardStartedAt);\n const policyGuard = policyRuntime.policyGuard;\n const decisionDomain = resolveEvaluateDecisionDomain({\n pack: resolvedVerticalPack.pack,\n request: effectiveInput,\n });\n\n const blockedByPolicyGuard = policyGuard.status !== \"ready\";\n const policyEvaluation: EvaluateDecisionPolicyEvaluation = blockedByPolicyGuard\n ? {\n resolution: \"policy_guard_blocked\",\n bundle_id: policyRuntime.selectedBundle?.bundle_id ?? policyGuard.active_bundle_id,\n bundle_version:\n policyRuntime.selectedBundle?.version ?? resolveBlockedPolicyVersion(policyGuard),\n evaluated_at: measuredAt,\n decision_domain: decisionDomain,\n evaluated_rule_count: 0,\n matched_rule_count: 0,\n matched_rule_ids: [],\n selected_rule_id: null,\n selected_rule_name: null,\n selected_rule_action: null,\n selected_rule_priority: null,\n selected_rule_rationale: null,\n selected_rule_severity: null,\n selected_rule_assignee_role: null,\n selected_rule_sla_minutes: null,\n }\n : policyRuntime.selectedBundle\n ? evaluateDecisionPolicyGraph({\n bundle: policyRuntime.selectedBundle,\n request: effectiveInput,\n decision_domain: decisionDomain,\n evaluated_at: measuredAt,\n })\n : {\n resolution: \"policy_guard_blocked\",\n bundle_id: policyGuard.active_bundle_id,\n bundle_version: resolveBlockedPolicyVersion(policyGuard),\n evaluated_at: measuredAt,\n decision_domain: decisionDomain,\n evaluated_rule_count: 0,\n matched_rule_count: 0,\n matched_rule_ids: [],\n selected_rule_id: null,\n selected_rule_name: null,\n selected_rule_action: null,\n selected_rule_priority: null,\n selected_rule_rationale: null,\n selected_rule_severity: null,\n selected_rule_assignee_role: null,\n selected_rule_sla_minutes: null,\n };\n const outcome = resolveEvaluateDecisionOutcomeFromPolicyEvaluation(policyEvaluation);\n const confidence = resolveEvaluateDecisionConfidenceFromPolicyEvaluation(policyEvaluation);\n const evaluationId = randomUUID();\n const dossierId = randomUUID();\n const fallbackTriggered = blockedByPolicyGuard\n ? false\n : effectiveInput.mode !== \"ENFORCEMENT\" || outcome !== \"APPROVE\";\n const fallbackToLegacy = blockedByPolicyGuard\n ? false\n : fallbackTriggered && rolloutPolicy.fallback_to_legacy_allowed;\n const fallbackReason = blockedByPolicyGuard\n ? policyGuard.reason\n : fallbackTriggered\n ? !rolloutPolicy.fallback_to_legacy_allowed\n ? \"fallback_disabled_by_rollout\"\n : rolloutPolicy.feature_flag && rolloutPolicy.feature_flag_enabled === false\n ? \"feature_flag_disabled\"\n : effectiveInput.mode !== \"ENFORCEMENT\"\n ? \"mode_not_enforcement\"\n : \"non_approve_outcome\"\n : null;\n const reconciliationRequired = blockedByPolicyGuard\n ? false\n : fallbackTriggered\n ? true\n : rolloutPolicy.reconciliation_required_default;\n const reconciliationStatus: EvaluateDecisionReconciliationStatus = reconciliationRequired\n ? \"PENDING\"\n : \"NOT_REQUIRED\";\n const governanceMetrics = buildGovernanceMetrics(effectiveInput, outcome);\n const responsePolicyVersion = blockedByPolicyGuard\n ? resolveBlockedPolicyVersion(policyGuard)\n : (policyEvaluation.bundle_version ?? effectiveInput.policy_version);\n const policySnapshot = buildEvaluateDecisionPolicySnapshot({\n policyGuard,\n policyEvaluation,\n selectedBundle: policyRuntime.selectedBundle,\n responsePolicyVersion,\n });\n\n const responseBase: Omit<EvaluateDecisionResponse, \"idempotent_replay\"> = {\n outcome,\n confidence,\n policy_version: responsePolicyVersion,\n objective_profile: effectiveInput.objective_profile,\n dossier_id: dossierId,\n dossier_sha256: null,\n evaluation_id: evaluationId,\n decision_resolution_id: null,\n ledger_entry_id: null,\n ledger_entry_hash: null,\n mode: effectiveInput.mode,\n fallback_to_legacy: fallbackToLegacy,\n fallback_reason: fallbackReason,\n reconciliation_required: reconciliationRequired,\n reconciliation_status: reconciliationStatus,\n rollout: {\n source: rolloutPolicy.source,\n decision_band: effectiveInput.decision_band,\n transaction_type: effectiveInput.transaction_type,\n configured_mode: rolloutPolicy.configured_mode,\n effective_mode: effectiveInput.mode,\n feature_flag: rolloutPolicy.feature_flag,\n feature_flag_enabled: rolloutPolicy.feature_flag_enabled,\n },\n governance_metrics: governanceMetrics,\n policy_guard: policyGuard,\n policy_evaluation: policyEvaluation,\n policy_snapshot: policySnapshot,\n decision_domain: decisionDomain,\n vertical_pack: {\n key: resolvedVerticalPack.pack.key,\n source: resolvedVerticalPack.source,\n workflow_key: parsed.value.workflow_key,\n },\n };\n\n const decisionChainValidation = await buildDecisionChainLinkInput({\n store,\n request: effectiveInput,\n response: responseBase,\n });\n if (!decisionChainValidation.ok) {\n return reply\n .code(400)\n .send({ error: \"VALIDATION_ERROR\", message: decisionChainValidation.message });\n }\n\n const evidenceHashes = [\n createHash(\"sha256\")\n .update(JSON.stringify(effectiveInput.context ?? {}), \"utf8\")\n .digest(\"hex\"),\n ];\n const generatedAt = new Date().toISOString();\n const dossierBuildStartedAt = process.hrtime.bigint();\n const provisionalDossier = buildDecisionDossier(\n effectiveInput,\n responseBase,\n evidenceHashes,\n generatedAt,\n );\n const dossierSha256 = computeDossierContentSha(provisionalDossier);\n\n responseBase.dossier_sha256 = dossierSha256;\n\n const resolutionStartedAt = process.hrtime.bigint();\n const { resolutionId, payload: resolutionPayload } = buildEvaluateDecisionResolution({\n request: effectiveInput,\n decision_domain: decisionDomain,\n vertical_pack: resolvedVerticalPack,\n response: responseBase,\n dossierSha256,\n occurred_at: new Date().toISOString(),\n });\n const resolutionValidation = validateProtocolArtifact(\"decision_resolution\", resolutionPayload);\n if (!resolutionValidation.ok) {\n return reply.code(400).send({\n error: \"VALIDATION_ERROR\",\n message: \"decision_resolution failed schema validation\",\n issues: resolutionValidation.issues,\n });\n }\n await store.saveArtifact(\"decision_resolution\", resolutionValidation.value);\n performanceStages.dossier_build_ms = durationMs(dossierBuildStartedAt);\n performanceStages.resolution_write_ms = durationMs(resolutionStartedAt);\n\n const ledgerStartedAt = process.hrtime.bigint();\n const ledger = await appendEvaluateDecisionLedgerEvent(store, {\n org_id: effectiveInput.org_id,\n dossier_id: responseBase.dossier_id,\n decision_resolution_id: resolutionId,\n occurred_at: new Date().toISOString(),\n outcome,\n mode: effectiveInput.mode,\n dossier_sha256: dossierSha256,\n });\n performanceStages.ledger_append_ms = durationMs(ledgerStartedAt);\n responseBase.decision_resolution_id = resolutionId;\n responseBase.ledger_entry_id = ledger.ledger_entry_id;\n responseBase.ledger_entry_hash = ledger.ledger_entry_hash;\n const decisionChainLink = await buildDecisionChainLinkInput({\n store,\n request: effectiveInput,\n response: responseBase,\n });\n if (!decisionChainLink.ok) {\n return reply\n .code(400)\n .send({ error: \"VALIDATION_ERROR\", message: decisionChainLink.message });\n }\n responseBase.decision_chain = decisionChainLink.summary;\n const dossierPayload = buildDecisionDossier(\n effectiveInput,\n responseBase,\n evidenceHashes,\n generatedAt,\n );\n\n try {\n const persistenceStartedAt = process.hrtime.bigint();\n const saved = await store.saveDecisionEvaluation({\n id: evaluationId,\n org_id: effectiveInput.org_id,\n idempotency_key: effectiveInput.idempotency_key,\n decision_type: effectiveInput.decision_type,\n amount: effectiveInput.amount,\n risk_score: effectiveInput.risk_score,\n channel: effectiveInput.channel,\n source: effectiveInput.source,\n policy_version: responseBase.policy_version,\n objective_profile: effectiveInput.objective_profile,\n outcome,\n confidence,\n dossier_id: dossierId,\n mode: effectiveInput.mode,\n fallback_triggered: fallbackTriggered,\n request_payload: {\n ...evaluateInputBase,\n mode_requested: parsed.value.mode,\n mode_effective: effectiveInput.mode,\n rollout_source: rolloutPolicy.source,\n rollout_feature_flag: rolloutPolicy.feature_flag,\n rollout_feature_flag_enabled: rolloutPolicy.feature_flag_enabled,\n vertical_pack_resolved: resolvedVerticalPack.pack.key,\n vertical_pack_source: resolvedVerticalPack.source,\n workflow_key: parsed.value.workflow_key,\n policy_guard_status: policyGuard.status,\n policy_guard_reason: policyGuard.reason,\n policy_guard_active_bundle_version: policyGuard.active_bundle_version,\n policy_guard_latest_bundle_version: policyGuard.latest_bundle_version,\n evaluated_policy_bundle_id: policyEvaluation.bundle_id,\n evaluated_policy_bundle_version: policyEvaluation.bundle_version,\n policy_evaluation_resolution: policyEvaluation.resolution,\n policy_evaluation_selected_rule_id: policyEvaluation.selected_rule_id,\n policy_evaluation_selected_rule_action: policyEvaluation.selected_rule_action,\n policy_snapshot: policySnapshot,\n } as Record<string, unknown>,\n response_payload: {\n ...responseBase,\n },\n dossier_payload: dossierPayload,\n evidence_hashes: evidenceHashes,\n governance_metrics: [\n {\n metric_name: \"override_drift_rate\",\n metric_value: governanceMetrics.override_drift_rate,\n dimensions: { decision_type: effectiveInput.decision_type, mode: effectiveInput.mode },\n },\n {\n metric_name: \"governance_tension_index\",\n metric_value: governanceMetrics.governance_tension_index,\n dimensions: { decision_type: effectiveInput.decision_type, mode: effectiveInput.mode },\n },\n {\n metric_name: \"boundary_volatility_score\",\n metric_value: governanceMetrics.boundary_volatility_score,\n dimensions: { decision_type: effectiveInput.decision_type, mode: effectiveInput.mode },\n },\n {\n metric_name: \"decision_volume_under_governance\",\n metric_value: governanceMetrics.decision_volume_under_governance,\n dimensions: { decision_type: effectiveInput.decision_type, mode: effectiveInput.mode },\n },\n ],\n });\n const savedChainLink = await store.saveDecisionChainLink(decisionChainLink.value);\n responseBase.decision_chain = decisionChainSummaryFromRow(savedChainLink);\n performanceStages.evaluation_persist_ms = durationMs(persistenceStartedAt);\n const performance = buildProtocolPerformanceSnapshot({\n measured_at: measuredAt,\n started_at: handlerStartedAt,\n stages: performanceStages,\n });\n\n const response: EvaluateDecisionResponse = {\n ...responseBase,\n evaluation_id: saved.id,\n performance,\n idempotent_replay: false,\n };\n\n reply.header(\"server-timing\", buildServerTimingHeader(performance));\n return reply.code(200).send(response);\n } catch (err) {\n const errorCode =\n typeof err === \"object\" && err !== null ? (err as { code?: string }).code : \"\";\n if (errorCode === \"23505\" && parsed.value.idempotency_key) {\n const existing = await store.getDecisionEvaluationByIdempotency({\n orgId: parsed.value.org_id,\n idempotencyKey: parsed.value.idempotency_key,\n });\n if (existing) {\n const cachedResponse = hydrateCachedEvaluateResponse(existing);\n return reply.code(200).send({\n ...cachedResponse,\n idempotent_replay: true,\n });\n }\n }\n app.log.error({ err }, \"Evaluate-decision execution failed\");\n return reply.code(500).send({\n error: \"EVALUATION_FAILED\",\n message: \"Failed to evaluate decision\",\n });\n }\n };\n\n app.post(\"/evaluate-decision\", evaluateDecisionHandler);\n app.post(\"/v1/protocol/evaluate-decision\", evaluateDecisionHandler);\n\n // Internal reproduce endpoint. The public, capability-gated route lives in the\n // API service and proxies here with the resolved org_id; this handler owns the\n // store + deterministic engine and never persists anything.\n const reproduceDecisionHandler = async (req: FastifyRequest, reply: FastifyReply) => {\n const body = (req.body ?? {}) as Record<string, unknown>;\n const orgId = typeof body.org_id === \"string\" ? body.org_id.trim() : \"\";\n const dossierId = typeof body.dossier_id === \"string\" ? body.dossier_id.trim() : \"\";\n if (!orgId || !dossierId) {\n return reply.code(400).send({\n error: \"VALIDATION_ERROR\",\n message: \"org_id and dossier_id are required\",\n });\n }\n\n const dossier = await store.getDecisionDossier({ orgId, dossierId });\n if (!dossier) {\n return reply.code(404).send({\n error: \"DECISION_DOSSIER_NOT_FOUND\",\n message: \"Decision Dossier was not found\",\n });\n }\n\n const reproduction = await reproduceDecisionFromDossierPayload({\n store,\n org_id: orgId,\n dossier_payload: dossier.dossier_payload,\n });\n return reply.code(200).send({ dossier_id: dossierId, reproduction });\n };\n\n app.post(\"/decision-dossiers/reproduce\", reproduceDecisionHandler);\n app.post(\"/v1/protocol/decision-dossiers/reproduce\", reproduceDecisionHandler);\n}\n","import { asNumber, asRecord, asString } from \"./Parsing.js\";\n\nexport interface ProtocolPerformanceSnapshot {\n measured_at: string;\n total_latency_ms: number;\n stages: Record<string, number>;\n}\n\n/** Handler-latency measurement and Server-Timing header helpers. */\nexport class ProtocolPerformance {\n static durationMs(startedAt: bigint): number {\n return Number(process.hrtime.bigint() - startedAt) / 1_000_000;\n }\n\n static roundDurationMs(value: number): number {\n return Number(value.toFixed(3));\n }\n\n static buildProtocolPerformanceSnapshot(input: {\n measured_at: string;\n started_at: bigint;\n stages: Record<string, number>;\n }): ProtocolPerformanceSnapshot {\n const stages: Record<string, number> = {};\n for (const [key, value] of Object.entries(input.stages)) {\n if (!Number.isFinite(value) || value < 0) continue;\n stages[key] = roundDurationMs(value);\n }\n return {\n measured_at: input.measured_at,\n total_latency_ms: roundDurationMs(durationMs(input.started_at)),\n stages,\n };\n }\n\n static buildServerTimingHeader(snapshot: ProtocolPerformanceSnapshot): string {\n const entries: Array<[string, number]> = [[\"total\", snapshot.total_latency_ms]];\n for (const [key, value] of Object.entries(snapshot.stages)) {\n entries.push([key.replace(/_ms$/i, \"\"), value]);\n }\n return entries\n .map(([label, value]) => `${label.replace(/[^a-z0-9_-]/gi, \"_\")};dur=${value.toFixed(3)}`)\n .join(\", \");\n }\n\n static toProtocolPerformanceSnapshot(value: unknown): ProtocolPerformanceSnapshot | undefined {\n const record = asRecord(value);\n const totalLatencyMs = asNumber(record.total_latency_ms);\n if (totalLatencyMs == null) return undefined;\n const stagesRecord = asRecord(record.stages);\n const stages: Record<string, number> = {};\n for (const [key, rawValue] of Object.entries(stagesRecord)) {\n const parsed = asNumber(rawValue);\n if (parsed != null) stages[key] = parsed;\n }\n return {\n measured_at: asString(record.measured_at) ?? new Date().toISOString(),\n total_latency_ms: totalLatencyMs,\n stages,\n };\n }\n}\n\n/** Functional alias for {@link ProtocolPerformance.durationMs}. */\nexport function durationMs(startedAt: bigint): number {\n return ProtocolPerformance.durationMs(startedAt);\n}\n\n/** Functional alias for {@link ProtocolPerformance.roundDurationMs}. */\nexport function roundDurationMs(value: number): number {\n return ProtocolPerformance.roundDurationMs(value);\n}\n\n/** Functional alias for {@link ProtocolPerformance.buildProtocolPerformanceSnapshot}. */\nexport function buildProtocolPerformanceSnapshot(input: {\n measured_at: string;\n started_at: bigint;\n stages: Record<string, number>;\n}): ProtocolPerformanceSnapshot {\n return ProtocolPerformance.buildProtocolPerformanceSnapshot(input);\n}\n\n/** Functional alias for {@link ProtocolPerformance.buildServerTimingHeader}. */\nexport function buildServerTimingHeader(snapshot: ProtocolPerformanceSnapshot): string {\n return ProtocolPerformance.buildServerTimingHeader(snapshot);\n}\n\n/** Functional alias for {@link ProtocolPerformance.toProtocolPerformanceSnapshot}. */\nexport function toProtocolPerformanceSnapshot(\n value: unknown,\n): ProtocolPerformanceSnapshot | undefined {\n return ProtocolPerformance.toProtocolPerformanceSnapshot(value);\n}\n","import type { VerticalPack } from \"../VerticalContracts.js\";\n\n/**\n * Affiliate rewards vertical pack.\n *\n * Governs affiliate/referral **funnel agents** that issue reward and commission\n * payouts (e.g. Patchr's funnel domain reward gate: decision_type\n * `REFERRAL_REWARD_PAYOUT`, workflow_key `reward_payout`). Payouts are held\n * fail-closed unless a rule approves them.\n */\nexport const affiliateRewardsVerticalPack: VerticalPack = {\n key: \"affiliate_rewards\",\n display_name: \"Affiliate Rewards\",\n description:\n \"Governance for affiliate/referral funnel agents that issue reward and commission payouts.\",\n workflow_keys: [\"reward_payout\", \"referral_reward\", \"affiliate_commission\"],\n default_domain: \"AFFILIATE_REWARDS\",\n signal_mappings: [\n { domain: \"AFFILIATE_REWARDS\", metric_name: \"payout_amount\", source_hint: \"funnel\" },\n { domain: \"AFFILIATE_REWARDS\", metric_name: \"fraud_risk_score\", source_hint: \"risk\" },\n ],\n policy_bundle: {\n version: \"affiliate_rewards-v1\",\n rules: [\n {\n rule_id: \"reject_negative_amount\",\n name: \"Reject structurally invalid negative payout amounts\",\n decision_domain: \"AFFILIATE_REWARDS\",\n when: { all: [{ field: \"amount\", operator: \"LT\", value: 0 }] },\n then: { action: \"AUTO_REJECT\", severity: \"urgent\", sla_minutes: 60 },\n priority: 200,\n enabled: true,\n rationale: \"Negative reward amounts are invalid and must never be paid.\",\n },\n {\n rule_id: \"review_high_risk_payout\",\n name: \"Review elevated-risk reward payouts\",\n decision_domain: \"AFFILIATE_REWARDS\",\n when: { all: [{ field: \"risk_score\", operator: \"GTE\", value: 0.6 }] },\n then: { action: \"REQUIRE_REVIEW\", severity: \"elevated\", sla_minutes: 240 },\n priority: 150,\n enabled: true,\n rationale: \"Elevated fraud/risk signals hold the payout for accountable review.\",\n },\n {\n rule_id: \"review_large_payout\",\n name: \"Review large reward payouts\",\n decision_domain: \"AFFILIATE_REWARDS\",\n when: { all: [{ field: \"amount\", operator: \"GT\", value: 100 }] },\n then: { action: \"REQUIRE_REVIEW\", severity: \"elevated\", sla_minutes: 240 },\n priority: 140,\n enabled: true,\n rationale: \"Large payouts (in the funnel's amount unit) get a manual accountability check.\",\n },\n {\n rule_id: \"approve_standard_payout\",\n name: \"Approve standard referral reward payouts\",\n decision_domain: \"AFFILIATE_REWARDS\",\n when: {\n all: [{ field: \"decision_type\", operator: \"EQ\", value: \"REFERRAL_REWARD_PAYOUT\" }],\n },\n then: { action: \"AUTO_APPROVE\", severity: \"routine\", sla_minutes: 30 },\n priority: 20,\n enabled: true,\n rationale: \"Standard low-value, low-risk referral rewards are credited automatically.\",\n },\n ],\n },\n resolver_overrides: {\n domain_by_engine: { funnel: \"AFFILIATE_REWARDS\", affiliate: \"AFFILIATE_REWARDS\" },\n intent_domain_hints: [\n {\n domain: \"AFFILIATE_REWARDS\",\n keywords: [\"referral\", \"reward\", \"affiliate\", \"commission\", \"payout\"],\n },\n ],\n evidence_required_keywords: [\"referral\", \"conversion\"],\n missing_evidence_fields: [\"referral_proof\"],\n base_confidence: 0.6,\n attachment_confidence_bonus: 0.1,\n intake_confidence_bonus: 0.05,\n missing_evidence_penalty: 0.2,\n },\n execution_templates: {\n SUCCEEDED: [\"Credit reward\", \"Notify affiliate\", \"Record ledger entry\"],\n NEEDS_EVIDENCE: [\"Request referral proof\", \"Verify conversion\", \"Re-run evaluation\"],\n FAILED: [\"Hold payout\", \"Escalate to control owner\", \"Capture override reason\"],\n },\n ui_copy: {\n recommendation_success: \"Credit the {domain} payout.\",\n recommendation_needs_evidence: \"Collect referral evidence for {domain}.\",\n recommendation_failed: \"Hold the payout for manual review.\",\n },\n};\n","import type { VerticalPack } from \"../VerticalContracts.js\";\n\nexport const coreVerticalPack: VerticalPack = {\n key: \"core\",\n display_name: \"Core Operations\",\n description: \"Default cross-industry pack for general decision governance.\",\n default_domain: \"OPERATIONS\",\n signal_mappings: [\n { domain: \"OPERATIONS\", metric_name: \"cycle_time_minutes\", source_hint: \"workflow\" },\n { domain: \"FINANCE\", metric_name: \"cost_delta_usd\", source_hint: \"finance_system\" },\n { domain: \"PROCUREMENT\", metric_name: \"vendor_risk_score\", source_hint: \"procurement\" },\n ],\n policy_bundle: {\n version: \"core-v1\",\n rules: [\n {\n rule_id: \"evidence-required\",\n name: \"Evidence completeness gate\",\n decision_domain: \"OPERATIONS\",\n when: {\n all: [{ field: \"evidence.attachments\", operator: \"LT\", value: 1 }],\n },\n then: {\n action: \"REQUEST_INFO\",\n severity: \"elevated\",\n sla_minutes: 60,\n },\n priority: 100,\n enabled: true,\n rationale: \"Require evidence before final recommendation.\",\n },\n ],\n },\n resolver_overrides: {\n domain_by_engine: {\n software: \"OPERATIONS\",\n procure: \"PROCUREMENT\",\n hiring: \"HIRING\",\n finance: \"FINANCE\",\n },\n intent_domain_hints: [\n { domain: \"PROCUREMENT\", keywords: [\"procure\", \"vendor\", \"renewal\", \"quote\", \"sow\"] },\n { domain: \"HIRING\", keywords: [\"hiring\", \"candidate\", \"compensation\", \"headcount\"] },\n { domain: \"FINANCE\", keywords: [\"budget\", \"spend\", \"variance\", \"forecast\"] },\n ],\n evidence_required_keywords: [\n \"renewal\",\n \"purchase\",\n \"vendor\",\n \"procure\",\n \"budget\",\n \"headcount\",\n \"compensation\",\n ],\n missing_evidence_fields: [\"supporting_attachment\"],\n base_confidence: 0.52,\n attachment_confidence_bonus: 0.11,\n intake_confidence_bonus: 0.02,\n missing_evidence_penalty: 0.22,\n },\n execution_templates: {\n SUCCEEDED: [\n \"Assign owner and SLA\",\n \"Create linked execution dispatch\",\n \"Schedule revisit reminder\",\n ],\n NEEDS_EVIDENCE: [\"Collect missing evidence\", \"Re-run shadow evaluation\", \"Escalate to owner\"],\n FAILED: [\n \"Escalate this decision to an owner\",\n \"Attach remediation notes\",\n \"Retry with context\",\n ],\n },\n ui_copy: {\n recommendation_success:\n \"Proceed with {domain} decision while tracking revisit triggers and owner accountability.\",\n recommendation_needs_evidence:\n \"Collect missing evidence for {domain} decision before final approval.\",\n recommendation_failed: \"Escalate this decision to an owner for manual review.\",\n },\n};\n","import type { VerticalPack } from \"../VerticalContracts.js\";\n\n/**\n * DevOps / CI vertical pack.\n *\n * Governs CI/CD and infrastructure workflows — Terraform apply/destroy, on-chain\n * and release deploys (e.g. the decionis/govern CI gate actions\n * `github_infra_apply`, `github_infra_destroy`, `github_escrow_deploy`). The\n * govern action keys are listed as `workflow_keys` so evaluate requests resolve\n * to this pack even when no explicit `vertical_pack` is supplied.\n */\nexport const devopsVerticalPack: VerticalPack = {\n key: \"devops\",\n display_name: \"DevOps & CI\",\n description:\n \"Governance for CI/CD and infrastructure workflows — Terraform apply/destroy and release/on-chain deploys.\",\n workflow_keys: [\n \"ci\",\n \"devops\",\n \"github_infra_apply\",\n \"github_infra_destroy\",\n \"github_escrow_deploy\",\n \"infra-apply\",\n \"infra-destroy\",\n \"escrow-deploy\",\n ],\n default_domain: \"DEVOPS\",\n signal_mappings: [\n { domain: \"DEVOPS\", metric_name: \"change_risk_score\", source_hint: \"ci\" },\n { domain: \"DEVOPS\", metric_name: \"blast_radius\", source_hint: \"infra\" },\n ],\n policy_bundle: {\n version: \"devops-v1\",\n rules: [\n {\n rule_id: \"escalate_infra_destroy\",\n name: \"Escalate destroy of production infrastructure\",\n decision_domain: \"DEVOPS\",\n when: {\n all: [\n {\n field: \"decision_type\",\n operator: \"IN\",\n values: [\"github_infra_destroy\", \"infra-destroy\"],\n },\n ],\n },\n then: { action: \"ESCALATE\", severity: \"urgent\", sla_minutes: 120 },\n priority: 200,\n enabled: true,\n rationale: \"Destroys must never run unattended; route to an authorized operator.\",\n },\n {\n rule_id: \"reject_extreme_risk_change\",\n name: \"Reject near-certain-risk changes\",\n decision_domain: \"DEVOPS\",\n when: { all: [{ field: \"risk_score\", operator: \"GTE\", value: 0.95 }] },\n then: { action: \"AUTO_REJECT\", severity: \"urgent\", sla_minutes: 60 },\n priority: 180,\n enabled: true,\n rationale: \"A near-certain risk signal blocks the change outright.\",\n },\n {\n rule_id: \"review_infra_apply\",\n name: \"Review production Terraform apply\",\n decision_domain: \"DEVOPS\",\n when: {\n all: [\n {\n field: \"decision_type\",\n operator: \"IN\",\n values: [\"github_infra_apply\", \"infra-apply\"],\n },\n ],\n },\n then: { action: \"REQUIRE_REVIEW\", severity: \"elevated\", sla_minutes: 240 },\n priority: 150,\n enabled: true,\n rationale: \"Production infrastructure changes require accountable review.\",\n },\n {\n rule_id: \"review_release_deploy\",\n name: \"Review on-chain / release deploy\",\n decision_domain: \"DEVOPS\",\n when: {\n all: [\n {\n field: \"decision_type\",\n operator: \"IN\",\n values: [\"github_escrow_deploy\", \"escrow-deploy\"],\n },\n ],\n },\n then: { action: \"REQUIRE_REVIEW\", severity: \"elevated\", sla_minutes: 240 },\n priority: 140,\n enabled: true,\n rationale: \"Irreversible deploys require review of program authority/keypair.\",\n },\n {\n rule_id: \"approve_routine_ci\",\n name: \"Approve routine CI executions\",\n decision_domain: \"DEVOPS\",\n when: { all: [{ field: \"decision_type\", operator: \"EXISTS\", value: true }] },\n then: { action: \"AUTO_APPROVE\", severity: \"routine\", sla_minutes: 30 },\n priority: 10,\n enabled: true,\n rationale: \"Routine CI/devops steps proceed automatically when no control fires.\",\n },\n ],\n },\n resolver_overrides: {\n domain_by_engine: { software: \"DEVOPS\", ci: \"DEVOPS\", infra: \"DEVOPS\" },\n intent_domain_hints: [\n {\n domain: \"DEVOPS\",\n keywords: [\"deploy\", \"terraform\", \"infrastructure\", \"ci\", \"pipeline\", \"release\", \"escrow\"],\n },\n ],\n evidence_required_keywords: [\"plan\", \"approval\"],\n missing_evidence_fields: [\"change_plan\"],\n base_confidence: 0.55,\n attachment_confidence_bonus: 0.1,\n intake_confidence_bonus: 0.03,\n missing_evidence_penalty: 0.25,\n },\n execution_templates: {\n SUCCEEDED: [\"Apply change\", \"Record deployment\", \"Notify platform team\"],\n NEEDS_EVIDENCE: [\"Attach change plan\", \"Confirm approver\", \"Re-run evaluation\"],\n FAILED: [\"Block deploy\", \"Escalate to security approver\", \"Capture override reason\"],\n },\n ui_copy: {\n recommendation_success: \"Proceed with the {domain} change.\",\n recommendation_needs_evidence: \"Attach the change plan for {domain}.\",\n recommendation_failed: \"Escalate the change for manual approval.\",\n },\n};\n","import type { VerticalPack } from \"../VerticalContracts.js\";\n\nexport const financeVerticalPack: VerticalPack = {\n key: \"finance\",\n display_name: \"Financial Decision Authority\",\n description:\n \"Finance-first pack for transaction routing, payment authorization, override governance, and audit-grade decision traceability.\",\n default_domain: \"FINANCIAL_ROUTING\",\n signal_mappings: [\n {\n domain: \"FINANCIAL_ROUTING\",\n metric_name: \"routing_policy_drift_rate\",\n source_hint: \"core_banking_orchestrator\",\n },\n {\n domain: \"PAYMENT_AUTHORIZATION\",\n metric_name: \"auth_decline_anomaly_rate\",\n source_hint: \"payment_switch\",\n },\n {\n domain: \"CREDIT_ROUTING\",\n metric_name: \"credit_routing_override_ratio\",\n source_hint: \"credit_decisioning\",\n },\n {\n domain: \"FINANCIAL_GOVERNANCE\",\n metric_name: \"override_without_reason_count\",\n source_hint: \"manual_approval_console\",\n },\n ],\n policy_bundle: {\n version: \"finance-v1\",\n rules: [\n {\n rule_id: \"policy-snapshot-required\",\n name: \"Policy snapshot required for routing decisions\",\n decision_domain: \"FINANCIAL_ROUTING\",\n when: {\n all: [{ field: \"policy.version\", operator: \"EXISTS\" }],\n },\n then: {\n action: \"REQUIRE_REVIEW\",\n severity: \"elevated\",\n sla_minutes: 30,\n },\n priority: 140,\n enabled: true,\n rationale:\n \"Routing decisions must carry an explicit policy snapshot to remain defensible in audits.\",\n },\n {\n rule_id: \"manual-override-reason-required\",\n name: \"Manual override requires deterministic reason code\",\n decision_domain: \"FINANCIAL_GOVERNANCE\",\n when: {\n all: [{ field: \"override.requested\", operator: \"EQ\", value: true }],\n },\n then: {\n action: \"REQUEST_INFO\",\n severity: \"urgent\",\n sla_minutes: 15,\n },\n priority: 150,\n enabled: true,\n rationale:\n \"Manual overrides without structured reason codes create escalation ambiguity and audit fragility.\",\n },\n {\n rule_id: \"high-value-authorization-escalation\",\n name: \"Escalate high-value payment authorization\",\n decision_domain: \"PAYMENT_AUTHORIZATION\",\n when: {\n all: [{ field: \"intake.amount\", operator: \"GTE\", value: 100000 }],\n },\n then: {\n action: \"ESCALATE\",\n severity: \"urgent\",\n sla_minutes: 10,\n },\n priority: 160,\n enabled: true,\n },\n ],\n },\n resolver_overrides: {\n domain_by_engine: {\n finance: \"FINANCIAL_ROUTING\",\n procure: \"VENDOR_APPROVAL\",\n software: \"FINANCIAL_GOVERNANCE\",\n },\n intent_domain_hints: [\n {\n domain: \"CREDIT_ROUTING\",\n keywords: [\"credit routing\", \"credit path\", \"risk tier routing\", \"underwriting route\"],\n },\n {\n domain: \"PAYMENT_AUTHORIZATION\",\n keywords: [\"payment authorization\", \"auth path\", \"payment route\", \"issuer routing\"],\n },\n {\n domain: \"FINANCIAL_GOVERNANCE\",\n keywords: [\"override\", \"escalation\", \"approval authority\", \"policy exception\"],\n },\n {\n domain: \"FINANCIAL_ROUTING\",\n keywords: [\n \"transaction routing\",\n \"routing decision\",\n \"decision authority\",\n \"manual review\",\n ],\n },\n ],\n evidence_required_keywords: [\n \"routing\",\n \"authorization\",\n \"override\",\n \"escalation\",\n \"payment\",\n \"credit\",\n ],\n missing_evidence_fields: [\n \"policy_version\",\n \"decision_owner\",\n \"override_reason_code\",\n \"approval_path\",\n \"routing_target\",\n ],\n base_confidence: 0.56,\n attachment_confidence_bonus: 0.1,\n intake_confidence_bonus: 0.03,\n missing_evidence_penalty: 0.28,\n },\n execution_templates: {\n SUCCEEDED: [\n \"Publish governed routing decision with policy snapshot\",\n \"Attach decision dossier metadata and evidence hashes\",\n \"Set revisit trigger on policy drift and override variance\",\n ],\n NEEDS_EVIDENCE: [\n \"Collect missing routing evidence and policy references\",\n \"Capture deterministic override reason code\",\n \"Escalate to named financial authority owner\",\n ],\n FAILED: [\n \"Freeze automated routing branch for this decision\",\n \"Escalate to finance risk authority with SLA\",\n \"Record manual override rationale in immutable audit chain\",\n ],\n },\n ui_copy: {\n recommendation_success:\n \"Proceed with governed {domain} routing and preserve policy-linked audit evidence.\",\n recommendation_needs_evidence:\n \"Collect missing governance and override evidence for {domain} before approval.\",\n recommendation_failed:\n \"Pause autonomous routing and escalate to financial decision authority for manual adjudication.\",\n },\n};\n","import type { VerticalPack } from \"../VerticalContracts.js\";\n\nexport const hospitalityVerticalPack: VerticalPack = {\n key: \"hospitality\",\n display_name: \"Hospitality Operations\",\n description:\n \"Hospitality-first pack for guest-impacting, occupancy, staffing, and supplier decisions.\",\n default_domain: \"HOSPITALITY_OPERATIONS\",\n signal_mappings: [\n { domain: \"HOSPITALITY_REVENUE\", metric_name: \"occupancy_rate\", source_hint: \"pms\" },\n { domain: \"HOSPITALITY_REVENUE\", metric_name: \"revpar\", source_hint: \"pms\" },\n { domain: \"GUEST_EXPERIENCE\", metric_name: \"guest_incident_rate\", source_hint: \"crm\" },\n { domain: \"HOSPITALITY_OPERATIONS\", metric_name: \"staffing_gap_hours\", source_hint: \"wfm\" },\n ],\n policy_bundle: {\n version: \"hospitality-v1\",\n rules: [\n {\n rule_id: \"guest-impact-evidence\",\n name: \"Guest impact evidence check\",\n decision_domain: \"GUEST_EXPERIENCE\",\n when: {\n all: [{ field: \"evidence.attachments\", operator: \"LT\", value: 1 }],\n },\n then: {\n action: \"REQUEST_INFO\",\n severity: \"urgent\",\n sla_minutes: 30,\n },\n priority: 110,\n enabled: true,\n rationale: \"Guest-impacting decisions require attached proof before finalization.\",\n },\n {\n rule_id: \"revenue-anomaly-escalation\",\n name: \"Escalate severe occupancy variance\",\n decision_domain: \"HOSPITALITY_REVENUE\",\n when: {\n all: [{ field: \"signals.occupancy_variance_pct\", operator: \"GT\", value: 20 }],\n },\n then: {\n action: \"ESCALATE\",\n severity: \"urgent\",\n sla_minutes: 20,\n },\n priority: 120,\n enabled: true,\n },\n ],\n },\n resolver_overrides: {\n domain_by_engine: {\n operations: \"HOSPITALITY_OPERATIONS\",\n procure: \"PROCUREMENT\",\n hiring: \"PEOPLE\",\n finance: \"FINANCE\",\n },\n intent_domain_hints: [\n {\n domain: \"HOSPITALITY_REVENUE\",\n keywords: [\"occupancy\", \"room\", \"booking\", \"revpar\", \"adr\"],\n },\n {\n domain: \"GUEST_EXPERIENCE\",\n keywords: [\"guest\", \"complaint\", \"service\", \"customer-impacting\", \"incident\", \"sla\"],\n },\n { domain: \"PROCUREMENT\", keywords: [\"vendor\", \"renewal\", \"quote\", \"sow\", \"supplier\"] },\n { domain: \"PEOPLE\", keywords: [\"staffing\", \"roster\", \"hiring\", \"headcount\"] },\n ],\n evidence_required_keywords: [\"guest\", \"incident\", \"renewal\", \"vendor\", \"supplier\", \"headcount\"],\n missing_evidence_fields: [\"guest_impact_evidence\", \"supporting_attachment\"],\n base_confidence: 0.54,\n attachment_confidence_bonus: 0.12,\n intake_confidence_bonus: 0.02,\n missing_evidence_penalty: 0.24,\n },\n execution_templates: {\n SUCCEEDED: [\n \"Assign on-duty owner with SLA\",\n \"Post status update to operating channel\",\n \"Schedule revisit for next service window\",\n ],\n NEEDS_EVIDENCE: [\n \"Collect guest-impact evidence\",\n \"Attach quote/SOW or incident context\",\n \"Escalate to duty manager\",\n ],\n FAILED: [\n \"Escalate to incident commander\",\n \"Log manual override rationale\",\n \"Create follow-up decision checkpoint\",\n ],\n },\n ui_copy: {\n recommendation_success:\n \"Proceed with {domain} action while preserving guest-impact traceability and revisit triggers.\",\n recommendation_needs_evidence:\n \"Collect missing guest-impact and operational evidence for {domain} before approval.\",\n recommendation_failed:\n \"Pause automated progression and escalate to an accountable owner for manual decisioning.\",\n },\n};\n","import type { VerticalPack, VerticalPackRule } from \"./PackTypes\";\n\n/**\n * Ops / spend-control dual-gate — the declarative pack plus its pure, deterministic\n * evaluator. Extracted to @decionis/shared so the procurement disbursement path in\n * apps/api can run the two gates inline (in-process, no HTTP hop to the protocol\n * service) while apps/protocol keeps the same single source of truth via re-export.\n *\n * Pure and isomorphic: NO node:crypto, NO I/O — safe for the browser-bundled barrel\n * if ever imported there. The one stateful fact (`duplicate_suspected`) defaults to\n * false here and is injected by the caller (store lookback lives in apps/protocol).\n *\n * Gate 1 \"spend admission\" (well-formed, within limits) and Gate 2 \"disbursement\n * authority\" (authorized actor, segregation of duties, dual auth, no duplicate).\n * Highest matched `priority` wins; no match ⇒ ALLOW.\n */\n\nexport type OpsGate = \"spend_admission\" | \"disbursement_authority\";\nexport type OpsDecision = \"ALLOW\" | \"BLOCK\" | \"ESCALATE\" | \"DELAY\";\nexport type OpsOutcome = \"APPROVE\" | \"REJECT\" | \"ESCALATE\" | \"REVIEW\";\n\nexport interface OpsPayload {\n source_system?: string;\n object_type?: string;\n object_id?: string;\n action?: string;\n proposed_state?: Record<string, unknown>;\n actor?: Record<string, unknown>;\n context?: Record<string, unknown>;\n}\n\nexport interface OpsVerdict {\n decision: OpsDecision;\n outcome: OpsOutcome;\n reason: string;\n required_action: string | null;\n decision_domain: \"OPS_SPEND_ADMISSION\" | \"OPS_DISBURSEMENT_AUTHORITY\";\n rule_id: string | null;\n gate: OpsGate;\n}\n\n/**\n * Deterministic evaluator for the ops dual-gate: derives PII-free facts from the\n * payload and resolves them against the ops vertical pack's rule bundle.\n */\nexport class OpsDualGate {\n private static readonly requiredSpendFields = [\"amount\", \"currency\", \"vendor_id\"] as const;\n private static readonly authorizedRoles = new Set([\n \"AccountsPayable\",\n \"FinanceManager\",\n \"Controller\",\n \"TreasuryHead\",\n \"CFO\",\n ]);\n private static readonly defaultExpenseThreshold = 1000;\n private static readonly defaultRefundLimit = 500;\n private static readonly defaultCreditLimit = 500;\n private static readonly dualAuthDisbursementThreshold = 10000;\n\n /** Per-rule reason + structured required-action, kept out of the declarative pack. */\n static readonly ruleMeta: Record<string, { reason: string; required_action: string }> = {\n \"spend-required-fields\": {\n reason: \"Required spend fields are missing.\",\n required_action: \"COMPLETE_SPEND_REQUEST\",\n },\n \"spend-amount-valid\": {\n reason: \"Spend amount must be a positive numeric value.\",\n required_action: \"CORRECT_SPEND_AMOUNT\",\n },\n \"spend-vendor-verified\": {\n reason: \"Vendor is not verified for governed disbursement.\",\n required_action: \"VERIFY_VENDOR\",\n },\n \"spend-refund-over-limit\": {\n reason: \"Refund amount exceeds the configured refund approval limit.\",\n required_action: \"REFUND_LIMIT_APPROVAL\",\n },\n \"spend-credit-over-limit\": {\n reason: \"Credit amount exceeds the configured credit approval limit.\",\n required_action: \"CREDIT_LIMIT_APPROVAL\",\n },\n \"spend-over-threshold-needs-dual-auth\": {\n reason: \"Spend exceeds the approval threshold and lacks a second authorizer.\",\n required_action: \"SECOND_APPROVER\",\n },\n \"disb-duplicate-payment\": {\n reason: \"A prior payment with the same vendor + invoice/amount fingerprint was found.\",\n required_action: \"DUPLICATE_PAYMENT_REVIEW\",\n },\n \"disb-authorized-role\": {\n reason: \"Actor role is not authorized to release a disbursement.\",\n required_action: \"AUTHORIZED_DISBURSEMENT_ROLE\",\n },\n \"disb-segregation-of-duties\": {\n reason: \"Segregation-of-duties check failed because requester and approver match.\",\n required_action: \"SEGREGATION_OF_DUTIES_REVIEW\",\n },\n \"disb-dual-auth-missing\": {\n reason:\n \"Disbursement exceeds the dual-authorization threshold and a second approver is missing.\",\n required_action: \"SECOND_APPROVER\",\n },\n };\n\n static readonly outcomeToDecision: Record<OpsOutcome, OpsDecision> = {\n APPROVE: \"ALLOW\",\n REJECT: \"BLOCK\",\n ESCALATE: \"ESCALATE\",\n REVIEW: \"DELAY\",\n };\n\n static normalizePayload(payload: OpsPayload): Required<OpsPayload> {\n return {\n source_system: payload.source_system ?? \"ERP\",\n object_type: payload.object_type ?? \"VendorPayment\",\n object_id: payload.object_id ?? \"UNKNOWN\",\n action: payload.action ?? \"RELEASE_PAYMENT\",\n proposed_state: payload.proposed_state ?? {},\n actor: payload.actor ?? {},\n context: payload.context ?? {},\n };\n }\n\n private static isBlank(value: unknown): boolean {\n return value === undefined || value === null || value === \"\";\n }\n\n private static numOr(value: unknown, fallback: number): number {\n const n = Number(value);\n return Number.isFinite(n) ? n : fallback;\n }\n\n /**\n * Derive the boolean/number facts the pack rules match against. Pure and\n * deterministic. `duplicate_suspected` defaults to false here and is overridden by\n * the caller via a store lookback. `vendor_id`/`invoice_number`/`currency` are\n * passed through so a later duplicate-detection pass can rebuild the fingerprint.\n */\n static deriveFacts(payload: OpsPayload, gate: OpsGate): Record<string, unknown> {\n const p = OpsDualGate.normalizePayload(payload);\n const state = p.proposed_state;\n const context = p.context;\n const actor = p.actor;\n\n const amount = Number(state.amount);\n const amountFinite = Number.isFinite(amount);\n const objectType = p.object_type;\n\n const expenseThreshold = OpsDualGate.numOr(\n state.expense_threshold,\n OpsDualGate.defaultExpenseThreshold,\n );\n const refundLimit = OpsDualGate.numOr(state.refund_limit, OpsDualGate.defaultRefundLimit);\n const creditLimit = OpsDualGate.numOr(state.credit_limit, OpsDualGate.defaultCreditLimit);\n\n const vendorStatus = String(state.vendor_status ?? \"VERIFIED\").toUpperCase();\n const actorRole = String(actor.role ?? \"\");\n\n const requestedBy = context.requested_by;\n const approvedBy = context.approved_by;\n const secondApprover = context.second_approver;\n const dualAuthPresent =\n !OpsDualGate.isBlank(approvedBy) &&\n !OpsDualGate.isBlank(secondApprover) &&\n String(approvedBy) !== String(secondApprover);\n\n return {\n gate,\n object_type: objectType,\n amount: amountFinite ? amount : null,\n vendor_id: state.vendor_id ?? null,\n invoice_number: state.invoice_number ?? null,\n currency: state.currency ?? null,\n // Gate 1 — spend admission\n missing_required_fields: OpsDualGate.requiredSpendFields.filter((f) =>\n OpsDualGate.isBlank(state[f]),\n ).length,\n missing_fields_list: OpsDualGate.requiredSpendFields.filter((f) =>\n OpsDualGate.isBlank(state[f]),\n ),\n amount_invalid: !amountFinite || amount <= 0,\n vendor_verified:\n vendorStatus === \"VERIFIED\" && !/^UNVERIFIED|^BLOCK/.test(String(state.vendor_id ?? \"\")),\n over_expense_threshold: amountFinite && amount > expenseThreshold,\n refund_over_limit: objectType === \"Refund\" && amountFinite && amount > refundLimit,\n credit_over_limit:\n (objectType === \"Credit\" || objectType === \"CreditMemo\") &&\n amountFinite &&\n amount > creditLimit,\n // Gate 2 — disbursement authority\n actor_role: actorRole,\n actor_authorized: OpsDualGate.authorizedRoles.has(actorRole),\n sod_violation:\n !OpsDualGate.isBlank(requestedBy) &&\n !OpsDualGate.isBlank(approvedBy) &&\n String(requestedBy) === String(approvedBy),\n dual_auth_required: amountFinite && amount > OpsDualGate.dualAuthDisbursementThreshold,\n dual_auth_present: dualAuthPresent,\n duplicate_suspected: false,\n };\n }\n\n /** Minimal predicate matcher mirroring the protocol rule-engine operator semantics. */\n private static matchPredicate(\n facts: Record<string, unknown>,\n pred: VerticalPackRule[\"when\"][\"all\"][number],\n ): boolean {\n const actual = facts[pred.field];\n const expected = pred.value;\n switch (pred.operator) {\n case \"EQ\":\n return actual === expected;\n case \"NEQ\":\n return actual !== expected;\n case \"GT\":\n return Number(actual) > Number(expected);\n case \"GTE\":\n return Number(actual) >= Number(expected);\n case \"LT\":\n return Number(actual) < Number(expected);\n case \"LTE\":\n return Number(actual) <= Number(expected);\n case \"IN\":\n return Array.isArray(pred.values) && pred.values.includes(actual);\n case \"NOT_IN\":\n return Array.isArray(pred.values) && !pred.values.includes(actual);\n case \"EXISTS\":\n return actual !== undefined && actual !== null;\n default:\n return false;\n }\n }\n\n private static outcomeForAction(action: VerticalPackRule[\"then\"][\"action\"]): OpsOutcome {\n switch (action) {\n case \"AUTO_REJECT\":\n return \"REJECT\";\n case \"ESCALATE\":\n return \"ESCALATE\";\n case \"AUTO_APPROVE\":\n return \"APPROVE\";\n default:\n return \"REVIEW\"; // REQUIRE_REVIEW | REQUEST_INFO\n }\n }\n\n static decisionDomainForGate(gate: OpsGate): OpsVerdict[\"decision_domain\"] {\n return gate === \"spend_admission\" ? \"OPS_SPEND_ADMISSION\" : \"OPS_DISBURSEMENT_AUTHORITY\";\n }\n\n static cleanReason(gate: OpsGate): string {\n return gate === \"spend_admission\"\n ? \"Spend request is complete, within limits, and eligible for disbursement review.\"\n : \"Disbursement authority is present and no duplicate was detected.\";\n }\n\n /**\n * Evaluate an ops gate deterministically against the ops vertical pack. Pass\n * `extraFacts` (e.g. `{ duplicate_suspected: true }`) to inject store-derived facts.\n * No match means every check passed → ALLOW. Highest-priority matched rule wins.\n */\n static evaluate(\n payload: OpsPayload,\n gate: OpsGate,\n extraFacts?: Record<string, unknown>,\n ): OpsVerdict {\n const facts = { ...OpsDualGate.deriveFacts(payload, gate), ...(extraFacts ?? {}) };\n const decisionDomain = OpsDualGate.decisionDomainForGate(gate);\n\n const matched = opsVerticalPack.policy_bundle.rules\n .filter((rule) => rule.enabled)\n .filter((rule) => rule.when.all.every((pred) => OpsDualGate.matchPredicate(facts, pred)))\n .sort((a, b) => b.priority - a.priority);\n\n const selected = matched[0];\n if (!selected) {\n return {\n decision: \"ALLOW\",\n outcome: \"APPROVE\",\n reason: OpsDualGate.cleanReason(gate),\n required_action: null,\n decision_domain: decisionDomain,\n rule_id: null,\n gate,\n };\n }\n\n const outcome = OpsDualGate.outcomeForAction(selected.then.action);\n const meta = OpsDualGate.ruleMeta[selected.rule_id];\n let reason = meta?.reason ?? selected.rationale ?? selected.name;\n if (selected.rule_id === \"spend-required-fields\") {\n const list = (facts.missing_fields_list as string[]) ?? [];\n reason = `Required spend fields are missing: ${list.join(\", \")}.`;\n } else if (selected.rule_id === \"disb-authorized-role\") {\n reason = `Actor role ${String(facts.actor_role) || \"UNKNOWN\"} is not authorized to release a disbursement.`;\n }\n\n return {\n decision: OpsDualGate.outcomeToDecision[outcome],\n outcome,\n reason,\n required_action: meta?.required_action ?? null,\n decision_domain: decisionDomain,\n rule_id: selected.rule_id,\n gate,\n };\n }\n}\n\nexport const opsVerticalPack: VerticalPack = {\n key: \"ops\",\n display_name: \"Ops Spend Control\",\n description:\n \"Dual-gate governance for back-office spend — spend admission (completeness, valid amount, verified vendor, expense/refund/credit limits) and disbursement authority (authorized role, segregation of duties, dual authorization, duplicate-payment detection) before money moves.\",\n default_domain: \"OPS_DISBURSEMENT_AUTHORITY\",\n workflow_keys: [\"expense_approval\", \"vendor_payment\", \"refund_approval\", \"ap_disbursement\"],\n signal_mappings: [\n {\n domain: \"OPS_SPEND_ADMISSION\",\n metric_name: \"ops_spend_completeness_rate\",\n source_hint: \"erp\",\n },\n {\n domain: \"OPS_DISBURSEMENT_AUTHORITY\",\n metric_name: \"ops_duplicate_payment_rate\",\n source_hint: \"erp\",\n },\n ],\n policy_bundle: {\n version: \"ops-spend-v1\",\n rules: [\n // ── Gate 1: spend admission ──────────────────────────────────────\n {\n rule_id: \"spend-required-fields\",\n name: \"Required spend fields present\",\n decision_domain: \"*\",\n when: {\n all: [\n { field: \"gate\", operator: \"EQ\", value: \"spend_admission\" },\n { field: \"missing_required_fields\", operator: \"GT\", value: 0 },\n ],\n },\n then: { action: \"AUTO_REJECT\", severity: \"urgent\" },\n priority: 200,\n enabled: true,\n rationale: \"Spend request is incomplete; required fields must be present before admission.\",\n },\n {\n rule_id: \"spend-amount-valid\",\n name: \"Spend amount is valid\",\n decision_domain: \"*\",\n when: {\n all: [\n { field: \"gate\", operator: \"EQ\", value: \"spend_admission\" },\n { field: \"amount_invalid\", operator: \"EQ\", value: true },\n ],\n },\n then: { action: \"AUTO_REJECT\", severity: \"urgent\" },\n priority: 195,\n enabled: true,\n rationale: \"Spend amount must be a positive numeric value.\",\n },\n {\n rule_id: \"spend-vendor-verified\",\n name: \"Vendor is verified\",\n decision_domain: \"*\",\n when: {\n all: [\n { field: \"gate\", operator: \"EQ\", value: \"spend_admission\" },\n { field: \"vendor_verified\", operator: \"EQ\", value: false },\n ],\n },\n then: { action: \"AUTO_REJECT\", severity: \"urgent\" },\n priority: 190,\n enabled: true,\n rationale: \"Vendor is not verified for governed disbursement.\",\n },\n {\n rule_id: \"spend-refund-over-limit\",\n name: \"Refund exceeds the approval limit\",\n decision_domain: \"*\",\n when: {\n all: [\n { field: \"gate\", operator: \"EQ\", value: \"spend_admission\" },\n { field: \"refund_over_limit\", operator: \"EQ\", value: true },\n ],\n },\n then: { action: \"ESCALATE\", severity: \"urgent\", sla_minutes: 30 },\n priority: 185,\n enabled: true,\n rationale: \"Refund amount exceeds the configured refund approval limit.\",\n },\n {\n rule_id: \"spend-credit-over-limit\",\n name: \"Credit exceeds the approval limit\",\n decision_domain: \"*\",\n when: {\n all: [\n { field: \"gate\", operator: \"EQ\", value: \"spend_admission\" },\n { field: \"credit_over_limit\", operator: \"EQ\", value: true },\n ],\n },\n then: { action: \"ESCALATE\", severity: \"urgent\", sla_minutes: 30 },\n priority: 180,\n enabled: true,\n rationale: \"Credit amount exceeds the configured credit approval limit.\",\n },\n {\n rule_id: \"spend-over-threshold-needs-dual-auth\",\n name: \"Over-threshold spend requires dual authorization\",\n decision_domain: \"*\",\n when: {\n all: [\n { field: \"gate\", operator: \"EQ\", value: \"spend_admission\" },\n { field: \"over_expense_threshold\", operator: \"EQ\", value: true },\n { field: \"dual_auth_present\", operator: \"EQ\", value: false },\n ],\n },\n then: { action: \"REQUIRE_REVIEW\", severity: \"elevated\", sla_minutes: 60 },\n priority: 170,\n enabled: true,\n rationale: \"Spend exceeds the approval threshold and lacks a second authorizer.\",\n },\n // ── Gate 2: disbursement authority ───────────────────────────────\n {\n rule_id: \"disb-duplicate-payment\",\n name: \"Duplicate payment / invoice suspected\",\n decision_domain: \"*\",\n when: {\n all: [\n { field: \"gate\", operator: \"EQ\", value: \"disbursement_authority\" },\n { field: \"duplicate_suspected\", operator: \"EQ\", value: true },\n ],\n },\n then: { action: \"AUTO_REJECT\", severity: \"urgent\" },\n priority: 210,\n enabled: true,\n rationale: \"A prior payment with the same vendor + invoice/amount fingerprint was found.\",\n },\n {\n rule_id: \"disb-authorized-role\",\n name: \"Actor holds an authorized disbursement role\",\n decision_domain: \"*\",\n when: {\n all: [\n { field: \"gate\", operator: \"EQ\", value: \"disbursement_authority\" },\n { field: \"actor_authorized\", operator: \"EQ\", value: false },\n ],\n },\n then: { action: \"AUTO_REJECT\", severity: \"urgent\" },\n priority: 200,\n enabled: true,\n rationale: \"Actor role is not authorized to release a disbursement.\",\n },\n {\n rule_id: \"disb-segregation-of-duties\",\n name: \"Segregation of duties enforced\",\n decision_domain: \"*\",\n when: {\n all: [\n { field: \"gate\", operator: \"EQ\", value: \"disbursement_authority\" },\n { field: \"sod_violation\", operator: \"EQ\", value: true },\n ],\n },\n then: { action: \"AUTO_REJECT\", severity: \"urgent\" },\n priority: 195,\n enabled: true,\n rationale: \"Segregation-of-duties check failed because requester and approver match.\",\n },\n {\n rule_id: \"disb-dual-auth-missing\",\n name: \"High-value disbursement requires dual authorization\",\n decision_domain: \"*\",\n when: {\n all: [\n { field: \"gate\", operator: \"EQ\", value: \"disbursement_authority\" },\n { field: \"dual_auth_required\", operator: \"EQ\", value: true },\n { field: \"dual_auth_present\", operator: \"EQ\", value: false },\n ],\n },\n then: { action: \"ESCALATE\", severity: \"urgent\", sla_minutes: 10 },\n priority: 180,\n enabled: true,\n rationale:\n \"Disbursement exceeds the dual-authorization threshold and a second approver is missing.\",\n },\n // ── Catch-all admits (lowest priority) ───────────────────────────\n {\n rule_id: \"spend-admit-default\",\n name: \"Admit a clean spend request\",\n decision_domain: \"*\",\n when: { all: [{ field: \"gate\", operator: \"EQ\", value: \"spend_admission\" }] },\n then: { action: \"AUTO_APPROVE\" },\n priority: 1,\n enabled: true,\n rationale:\n \"Spend request is complete, within limits, and eligible for disbursement review.\",\n },\n {\n rule_id: \"disb-authorize-default\",\n name: \"Authorize a clean disbursement\",\n decision_domain: \"*\",\n when: { all: [{ field: \"gate\", operator: \"EQ\", value: \"disbursement_authority\" }] },\n then: { action: \"AUTO_APPROVE\" },\n priority: 1,\n enabled: true,\n rationale: \"Disbursement authority is present and no duplicate was detected.\",\n },\n ],\n },\n resolver_overrides: {\n domain_by_engine: {\n ops: \"OPS_DISBURSEMENT_AUTHORITY\",\n spend: \"OPS_SPEND_ADMISSION\",\n },\n intent_domain_hints: [\n {\n domain: \"OPS_SPEND_ADMISSION\",\n keywords: [\"expense\", \"reimbursement\", \"purchase request\", \"refund\", \"credit memo\"],\n },\n {\n domain: \"OPS_DISBURSEMENT_AUTHORITY\",\n keywords: [\"vendor payment\", \"pay invoice\", \"release payment\", \"disbursement\", \"wire\"],\n },\n ],\n evidence_required_keywords: [\"vendor\", \"invoice\", \"payment\", \"expense\", \"refund\"],\n missing_evidence_fields: [\"amount\", \"currency\", \"vendor_id\"],\n base_confidence: 0.6,\n attachment_confidence_bonus: 0.08,\n intake_confidence_bonus: 0.03,\n missing_evidence_penalty: 0.3,\n },\n execution_templates: {\n SUCCEEDED: [\n \"Release the governed disbursement with the signed dossier reference attached\",\n \"Continue the ERP workflow with the policy version and evidence hashes\",\n \"Record the decision in the shared audit ledger\",\n ],\n NEEDS_EVIDENCE: [\n \"Pause the disbursement and create an approval task\",\n \"Request the missing second authorizer or limit exception\",\n \"Hold for budget-owner review\",\n ],\n FAILED: [\n \"Stop the disbursement and notify the requester\",\n \"Record the blocking reason and required action in the dossier\",\n \"Escalate to an authorized approver for adjudication\",\n ],\n },\n ui_copy: {\n recommendation_success:\n \"Proceed with the governed {domain} action; the signed dossier is chained into the audit ledger.\",\n recommendation_needs_evidence:\n \"Hold the {domain} action until the missing approval or limit exception is supplied.\",\n recommendation_failed:\n \"Block the {domain} action and escalate to an authorized approver with the recorded reason.\",\n },\n};\n\nexport const OPS_PACK_VERSION = opsVerticalPack.policy_bundle.version;\n\n/** Alias for {@link OpsDualGate.ruleMeta}. */\nexport const RULE_META = OpsDualGate.ruleMeta;\n\n/** Alias for {@link OpsDualGate.outcomeToDecision}. */\nexport const OUTCOME_TO_DECISION = OpsDualGate.outcomeToDecision;\n\n/** Functional alias for {@link OpsDualGate.normalizePayload}. */\nexport function normalizeOpsPayload(payload: OpsPayload): Required<OpsPayload> {\n return OpsDualGate.normalizePayload(payload);\n}\n\n/** Functional alias for {@link OpsDualGate.deriveFacts}. */\nexport function deriveOpsFacts(payload: OpsPayload, gate: OpsGate): Record<string, unknown> {\n return OpsDualGate.deriveFacts(payload, gate);\n}\n\n/** Functional alias for {@link OpsDualGate.decisionDomainForGate}. */\nexport function decisionDomainForGate(gate: OpsGate): OpsVerdict[\"decision_domain\"] {\n return OpsDualGate.decisionDomainForGate(gate);\n}\n\n/** Functional alias for {@link OpsDualGate.cleanReason}. */\nexport function cleanOpsReason(gate: OpsGate): string {\n return OpsDualGate.cleanReason(gate);\n}\n\n/** Functional alias for {@link OpsDualGate.evaluate}. */\nexport function evaluateOpsGate(\n payload: OpsPayload,\n gate: OpsGate,\n extraFacts?: Record<string, unknown>,\n): OpsVerdict {\n return OpsDualGate.evaluate(payload, gate, extraFacts);\n}\n","import type { VerticalPack } from \"../VerticalContracts.js\";\n\nexport const personalVerticalPack: VerticalPack = {\n key: \"personal_productivity\",\n display_name: \"Personal Productivity\",\n description:\n \"Personal pack for deterministic planning gates, contextual recall, state capsules, and context-switch boundaries.\",\n workflow_keys: [\n \"personal_planning_gate\",\n \"personal_contextual_recall\",\n \"personal_state_capsule\",\n \"personal_flow_boundary\",\n ],\n default_domain: \"PERSONAL_PRODUCTIVITY\",\n signal_mappings: [\n {\n domain: \"PERSONAL_PRODUCTIVITY\",\n metric_name: \"focus_capacity_violation_count\",\n source_hint: \"personal_planning_gate\",\n },\n {\n domain: \"PERSONAL_PRODUCTIVITY\",\n metric_name: \"contextual_recall_match_count\",\n source_hint: \"personal_recall_rules\",\n },\n {\n domain: \"PERSONAL_PRODUCTIVITY\",\n metric_name: \"state_capsule_resume_count\",\n source_hint: \"personal_local_agent\",\n },\n {\n domain: \"PERSONAL_PRODUCTIVITY\",\n metric_name: \"context_switch_boundary_count\",\n source_hint: \"personal_flow_boundary\",\n },\n ],\n policy_bundle: {\n version: \"personal-productivity-v1\",\n rules: [\n {\n rule_id: \"personal.context_missing\",\n name: \"Personal realm context required\",\n decision_domain: \"PERSONAL_PRODUCTIVITY\",\n when: {\n all: [{ field: \"realm\", operator: \"EXISTS\", value: false }],\n },\n then: {\n action: \"REQUEST_INFO\",\n severity: \"elevated\",\n sla_minutes: 15,\n },\n priority: 100,\n enabled: true,\n rationale: \"Personal decisions must include an explicit realm before local execution.\",\n },\n ],\n },\n resolver_overrides: {\n domain_by_engine: {\n finance: \"PERSONAL_PRODUCTIVITY\",\n software: \"PERSONAL_PRODUCTIVITY\",\n procure: \"PERSONAL_PRODUCTIVITY\",\n hiring: \"PERSONAL_PRODUCTIVITY\",\n },\n intent_domain_hints: [\n {\n domain: \"PERSONAL_PRODUCTIVITY\",\n keywords: [\n \"personal\",\n \"planning gate\",\n \"contextual recall\",\n \"state capsule\",\n \"flow boundary\",\n \"focus capacity\",\n ],\n },\n ],\n evidence_required_keywords: [\"resume\", \"restore\", \"capture\", \"capacity\", \"recall\"],\n missing_evidence_fields: [\"realm\", \"signal_type\", \"device_id\"],\n base_confidence: 0.6,\n attachment_confidence_bonus: 0.04,\n intake_confidence_bonus: 0.04,\n missing_evidence_penalty: 0.24,\n },\n execution_templates: {\n SUCCEEDED: [\n \"Return deterministic local execution dispatch\",\n \"Attach Personal Decision Dossier metadata\",\n \"Update personal decision ledger\",\n ],\n NEEDS_EVIDENCE: [\n \"Request missing local signal context\",\n \"Hold personal execution dispatch\",\n \"Re-run evaluation after device context refresh\",\n ],\n FAILED: [\n \"Block or restrain the local personal action\",\n \"Surface remediation in the native personal surface\",\n \"Record controlled exception evidence\",\n ],\n },\n ui_copy: {\n recommendation_success: \"Proceed with {domain} action under the active personal policy bundle.\",\n recommendation_needs_evidence:\n \"Collect missing personal context before dispatching the {domain} action.\",\n recommendation_failed: \"Restrict the {domain} action and surface deterministic remediation.\",\n },\n};\n","import type { VerticalPack } from \"../VerticalContracts.js\";\n\n/**\n * Salesforce vertical pack — governs the Salesforce → Decionis → SAP \"front-to-back\"\n * pipeline for e-commerce & Enterprise/Retail Ops. Salesforce (Commerce Cloud, CPQ\n * / Sales Cloud, Data Cloud) captures customer/quote intent; Decionis evaluates it\n * deterministically *before* it becomes an SAP sales order; SAP stays the system of\n * record.\n *\n * Like the SAP pack, this is the declarative form of the dual-gate logic. Facts are\n * derived by the surface adapter (`SalesforceSurface.ts`) from a normalized\n * Salesforce intent payload (customer_master, order_header, order_items). Each rule\n * carries a `gate` predicate so one pack serves both gates; `decision_domain: \"*\"`\n * keeps rules domain-agnostic. Highest matched `priority` wins.\n *\n * Gate 1 — state admission: can this Salesforce intent safely become an SAP order?\n * (SAP master-data sync, field-shape safety: KUNNR present, MATNR length, sales org).\n * Gate 2 — execution authority: is it allowed to commit? (margin floor vs cost\n * basis, manual-discount floor, credit limit, payment terms, promo stacking).\n *\n * Reason/required-action text lives in the adapter, keyed by `rule_id`.\n */\nexport const salesforceVerticalPack: VerticalPack = {\n key: \"salesforce\",\n display_name: \"Salesforce Revenue Execution\",\n description:\n \"Dual-gate governance for the Salesforce → SAP front-to-back pipeline — state admission (SAP master-data sync and field-shape safety for Commerce Cloud orders and CPQ quotes) and execution authority (margin floor, manual-discount floor, credit limit, payment terms, promo hygiene) before a sales order is committed.\",\n default_domain: \"SALESFORCE_EXECUTION_AUTHORITY\",\n signal_mappings: [\n {\n domain: \"SALESFORCE_STATE_ADMISSION\",\n metric_name: \"salesforce_order_admission_rate\",\n source_hint: \"salesforce_commerce_cpq\",\n },\n {\n domain: \"SALESFORCE_EXECUTION_AUTHORITY\",\n metric_name: \"salesforce_revenue_policy_breach_rate\",\n source_hint: \"salesforce_commerce_cpq\",\n },\n ],\n policy_bundle: {\n version: \"salesforce-revops-v1\",\n rules: [\n // ── Gate 1: state admission (SAP-compatibility / master-data safety) ──\n {\n rule_id: \"state-required-fields\",\n name: \"Required SAP-mapping fields present\",\n decision_domain: \"*\",\n when: {\n all: [\n { field: \"gate\", operator: \"EQ\", value: \"state_admission\" },\n { field: \"missing_required_fields\", operator: \"GT\", value: 0 },\n ],\n },\n then: { action: \"AUTO_REJECT\", severity: \"urgent\" },\n priority: 200,\n enabled: true,\n rationale:\n \"Salesforce payload is missing fields required to build a valid SAP sales order.\",\n },\n {\n rule_id: \"state-customer-master-synced\",\n name: \"Salesforce account is synced to an SAP customer master\",\n decision_domain: \"*\",\n when: {\n all: [\n { field: \"gate\", operator: \"EQ\", value: \"state_admission\" },\n { field: \"customer_master_synced\", operator: \"EQ\", value: false },\n ],\n },\n then: { action: \"AUTO_REJECT\", severity: \"urgent\" },\n priority: 195,\n enabled: true,\n rationale:\n \"Salesforce Account must map to a validated SAP customer master (KNA1/KUNNR) before order admission.\",\n },\n {\n rule_id: \"state-material-number-valid\",\n name: \"Material numbers fit SAP field limits\",\n decision_domain: \"*\",\n when: {\n all: [\n { field: \"gate\", operator: \"EQ\", value: \"state_admission\" },\n { field: \"material_number_overflow\", operator: \"EQ\", value: true },\n ],\n },\n then: { action: \"AUTO_REJECT\", severity: \"urgent\" },\n priority: 190,\n enabled: true,\n rationale: \"A material number exceeds the SAP 18-character limit (VBAP overflow).\",\n },\n {\n rule_id: \"state-sales-org-valid\",\n name: \"Sales organization and distribution channel present\",\n decision_domain: \"*\",\n when: {\n all: [\n { field: \"gate\", operator: \"EQ\", value: \"state_admission\" },\n { field: \"sales_org_valid\", operator: \"EQ\", value: false },\n ],\n },\n then: { action: \"AUTO_REJECT\", severity: \"urgent\" },\n priority: 185,\n enabled: true,\n rationale:\n \"Sales organization (VKORG) and distribution channel (VTWEG) are required for the SAP order header.\",\n },\n {\n rule_id: \"state-amounts-valid\",\n name: \"Order line amounts and quantities are valid\",\n decision_domain: \"*\",\n when: {\n all: [\n { field: \"gate\", operator: \"EQ\", value: \"state_admission\" },\n { field: \"amounts_invalid\", operator: \"EQ\", value: true },\n ],\n },\n then: { action: \"AUTO_REJECT\", severity: \"urgent\" },\n priority: 180,\n enabled: true,\n rationale: \"Order line net price and quantity must be positive numeric values.\",\n },\n // ── Gate 2: execution authority (revenue policy) ─────────────────────\n {\n rule_id: \"exec-credit-limit\",\n name: \"Order within the SAP credit limit\",\n decision_domain: \"*\",\n when: {\n all: [\n { field: \"gate\", operator: \"EQ\", value: \"execution_authority\" },\n { field: \"over_credit_limit\", operator: \"EQ\", value: true },\n ],\n },\n then: { action: \"ESCALATE\", severity: \"urgent\", sla_minutes: 30 },\n priority: 200,\n enabled: true,\n rationale: \"Order total exceeds the customer's SAP-defined credit limit.\",\n },\n {\n rule_id: \"exec-margin-floor\",\n name: \"Net margin floor protected\",\n decision_domain: \"*\",\n when: {\n all: [\n { field: \"gate\", operator: \"EQ\", value: \"execution_authority\" },\n { field: \"margin_below_floor\", operator: \"EQ\", value: true },\n ],\n },\n then: { action: \"AUTO_REJECT\", severity: \"urgent\" },\n priority: 195,\n enabled: true,\n rationale:\n \"Order net margin falls below the policy floor against the SAP cost basis (e.g., a flash-sale promo breaching margin).\",\n },\n {\n rule_id: \"exec-discount-floor\",\n name: \"Manual discount within compliance floor\",\n decision_domain: \"*\",\n when: {\n all: [\n { field: \"gate\", operator: \"EQ\", value: \"execution_authority\" },\n { field: \"manual_discount_violation\", operator: \"EQ\", value: true },\n ],\n },\n then: { action: \"REQUIRE_REVIEW\", severity: \"elevated\", sla_minutes: 120 },\n priority: 185,\n enabled: true,\n rationale:\n \"A manual line discount exceeds the threshold for a non-Strategic account and needs manager override.\",\n },\n {\n rule_id: \"exec-data-cloud-risk\",\n name: \"Behavioral risk within tolerance (Data Cloud)\",\n decision_domain: \"*\",\n when: {\n all: [\n { field: \"gate\", operator: \"EQ\", value: \"execution_authority\" },\n { field: \"risk_elevated\", operator: \"EQ\", value: true },\n ],\n },\n then: { action: \"REQUIRE_REVIEW\", severity: \"elevated\", sla_minutes: 60 },\n priority: 180,\n enabled: true,\n rationale:\n \"Salesforce Data Cloud behavioral risk for this customer is elevated; hold B2B purchasing eligibility for review.\",\n },\n {\n rule_id: \"exec-payment-terms-allowed\",\n name: \"B2B payment terms permitted for region\",\n decision_domain: \"*\",\n when: {\n all: [\n { field: \"gate\", operator: \"EQ\", value: \"execution_authority\" },\n { field: \"payment_terms_allowed\", operator: \"EQ\", value: false },\n ],\n },\n then: { action: \"REQUIRE_REVIEW\", severity: \"elevated\", sla_minutes: 120 },\n priority: 175,\n enabled: true,\n rationale: \"Requested B2B payment terms are not permitted for this region without review.\",\n },\n {\n rule_id: \"exec-promo-stacking\",\n name: \"Promotion / coupon stacking review\",\n decision_domain: \"*\",\n when: {\n all: [\n { field: \"gate\", operator: \"EQ\", value: \"execution_authority\" },\n { field: \"promo_stacking\", operator: \"EQ\", value: true },\n ],\n },\n then: { action: \"REQUIRE_REVIEW\", severity: \"elevated\", sla_minutes: 60 },\n priority: 170,\n enabled: true,\n rationale: \"Multiple concurrent discount sources are stacked on one order and need review.\",\n },\n // ── Catch-all admits (lowest priority) ───────────────────────────────\n {\n rule_id: \"state-admit-default\",\n name: \"Admit a clean Salesforce order intent\",\n decision_domain: \"*\",\n when: { all: [{ field: \"gate\", operator: \"EQ\", value: \"state_admission\" }] },\n then: { action: \"AUTO_APPROVE\" },\n priority: 1,\n enabled: true,\n rationale:\n \"Salesforce intent maps cleanly to SAP structures and is eligible for execution review.\",\n },\n {\n rule_id: \"exec-authorize-default\",\n name: \"Authorize a compliant Salesforce order\",\n decision_domain: \"*\",\n when: { all: [{ field: \"gate\", operator: \"EQ\", value: \"execution_authority\" }] },\n then: { action: \"AUTO_APPROVE\" },\n priority: 1,\n enabled: true,\n rationale: \"Order satisfies revenue policy and may be committed to SAP.\",\n },\n ],\n },\n resolver_overrides: {\n domain_by_engine: {\n salesforce: \"SALESFORCE_EXECUTION_AUTHORITY\",\n commerce: \"SALESFORCE_STATE_ADMISSION\",\n cpq: \"SALESFORCE_EXECUTION_AUTHORITY\",\n },\n intent_domain_hints: [\n {\n domain: \"SALESFORCE_STATE_ADMISSION\",\n keywords: [\"customer master\", \"material number\", \"sales org\", \"order mapping\", \"checkout\"],\n },\n {\n domain: \"SALESFORCE_EXECUTION_AUTHORITY\",\n keywords: [\n \"discount\",\n \"credit limit\",\n \"payment terms\",\n \"margin\",\n \"quote approval\",\n \"promo\",\n ],\n },\n ],\n evidence_required_keywords: [\"account\", \"opportunity\", \"quote\", \"order\", \"discount\", \"margin\"],\n missing_evidence_fields: [\"kunnr\", \"vkorg\", \"matnr\", \"netpr\"],\n base_confidence: 0.6,\n attachment_confidence_bonus: 0.08,\n intake_confidence_bonus: 0.03,\n missing_evidence_penalty: 0.3,\n },\n execution_templates: {\n SUCCEEDED: [\n \"Append the signed Decision Dossier id to the Salesforce record (Decionis_Dossier__c)\",\n \"Release the order payload to create the SAP sales order with the dossier reference\",\n \"Record the decision in the shared audit ledger\",\n ],\n NEEDS_EVIDENCE: [\n \"Hold the Salesforce checkout or quote progression\",\n \"Request the missing approval (manager discount override, credit or payment-terms review)\",\n \"Sync the Salesforce account to a valid SAP customer master before retrying\",\n ],\n FAILED: [\n \"Block the order from reaching the SAP order-to-cash pipeline\",\n \"Record the blocking reason and required action in the dossier\",\n \"Return the verdict to Salesforce/Slack for operator clearance\",\n ],\n },\n ui_copy: {\n recommendation_success:\n \"Proceed with the governed Salesforce {domain} action; the signed dossier is chained into the audit ledger and ready for SAP commit.\",\n recommendation_needs_evidence:\n \"Hold the Salesforce {domain} action until the missing approval or master-data sync is supplied.\",\n recommendation_failed:\n \"Block the Salesforce {domain} action and return the recorded reason for operator clearance.\",\n },\n};\n","import type { VerticalPack } from \"../VerticalContracts.js\";\n\n/**\n * SAP vertical pack — governs SAP ERP execution authority (vendor payments,\n * purchase orders, procurement approvals) before they execute.\n *\n * The rules are the declarative form of the dual-gate logic that previously\n * lived hardcoded in `apps/sap/srv/decionis-client.js`. They are matched\n * against derived facts the SAP surface adapter (`SapSurface.ts`) computes from\n * a native SAP payload. Each rule carries a `gate` predicate so a single pack\n * serves both Gate 1 (state admission) and Gate 2 (execution authority);\n * `decision_domain: \"*\"` keeps the rules domain-agnostic so the surface — not\n * the domain resolver — selects them. Highest `priority` matched wins, which\n * reproduces the short-circuit order of the original imperative gates.\n *\n * Reason/required-action text for each rule lives in the adapter, keyed by\n * `rule_id`, so this pack stays purely declarative.\n */\nexport const sapVerticalPack: VerticalPack = {\n key: \"sap\",\n display_name: \"SAP Execution Authority\",\n description:\n \"Dual-gate governance for SAP ERP actions — state admission (completeness, budget, vendor, cost center) and execution authority (role, segregation of duties, regional holds, payment thresholds) before they execute.\",\n default_domain: \"SAP_EXECUTION_AUTHORITY\",\n signal_mappings: [\n {\n domain: \"SAP_STATE_ADMISSION\",\n metric_name: \"sap_state_completeness_rate\",\n source_hint: \"sap_s4hana\",\n },\n {\n domain: \"SAP_EXECUTION_AUTHORITY\",\n metric_name: \"sap_unauthorized_execution_rate\",\n source_hint: \"sap_s4hana\",\n },\n ],\n policy_bundle: {\n version: \"sap-procurement-v2\",\n rules: [\n // ── Gate 1: state admission ──────────────────────────────────────\n {\n rule_id: \"state-required-fields\",\n name: \"Required SAP state fields present\",\n decision_domain: \"*\",\n when: {\n all: [\n { field: \"gate\", operator: \"EQ\", value: \"state_admission\" },\n { field: \"missing_required_fields\", operator: \"GT\", value: 0 },\n ],\n },\n then: { action: \"AUTO_REJECT\", severity: \"urgent\" },\n priority: 200,\n enabled: true,\n rationale: \"PO state is incomplete; required fields must be present before admission.\",\n },\n {\n rule_id: \"state-amount-valid\",\n name: \"Purchase order amount is valid\",\n decision_domain: \"*\",\n when: {\n all: [\n { field: \"gate\", operator: \"EQ\", value: \"state_admission\" },\n { field: \"amount_invalid\", operator: \"EQ\", value: true },\n ],\n },\n then: { action: \"AUTO_REJECT\", severity: \"urgent\" },\n priority: 195,\n enabled: true,\n rationale: \"Purchase order amount must be a positive numeric value.\",\n },\n {\n rule_id: \"state-within-budget\",\n name: \"Purchase order within approved budget\",\n decision_domain: \"*\",\n when: {\n all: [\n { field: \"gate\", operator: \"EQ\", value: \"state_admission\" },\n { field: \"over_budget\", operator: \"EQ\", value: true },\n ],\n },\n then: { action: \"AUTO_REJECT\", severity: \"urgent\" },\n priority: 190,\n enabled: true,\n rationale: \"Purchase order amount exceeds the approved budget on the SAP state.\",\n },\n {\n rule_id: \"state-vendor-verified\",\n name: \"Vendor is verified\",\n decision_domain: \"*\",\n when: {\n all: [\n { field: \"gate\", operator: \"EQ\", value: \"state_admission\" },\n { field: \"vendor_verified\", operator: \"EQ\", value: false },\n ],\n },\n then: { action: \"AUTO_REJECT\", severity: \"urgent\" },\n priority: 185,\n enabled: true,\n rationale: \"Vendor is not verified for governed purchase order execution.\",\n },\n {\n rule_id: \"state-cost-center-valid\",\n name: \"Cost center is valid\",\n decision_domain: \"*\",\n when: {\n all: [\n { field: \"gate\", operator: \"EQ\", value: \"state_admission\" },\n { field: \"cost_center_valid\", operator: \"EQ\", value: false },\n ],\n },\n then: { action: \"AUTO_REJECT\", severity: \"urgent\" },\n priority: 180,\n enabled: true,\n rationale: \"Cost center is invalid or not eligible for this purchase order.\",\n },\n // ── Gate 2: execution authority ──────────────────────────────────\n {\n rule_id: \"exec-duplicate-payment\",\n name: \"Duplicate vendor payment suspected\",\n decision_domain: \"*\",\n when: {\n all: [\n { field: \"gate\", operator: \"EQ\", value: \"execution_authority\" },\n { field: \"duplicate_suspected\", operator: \"EQ\", value: true },\n ],\n },\n then: { action: \"AUTO_REJECT\", severity: \"urgent\" },\n priority: 210,\n enabled: true,\n rationale: \"A prior payment with the same vendor + amount fingerprint was found.\",\n },\n {\n rule_id: \"exec-authorized-role\",\n name: \"Actor holds an authorized SAP role\",\n decision_domain: \"*\",\n when: {\n all: [\n { field: \"gate\", operator: \"EQ\", value: \"execution_authority\" },\n { field: \"actor_authorized\", operator: \"EQ\", value: false },\n ],\n },\n then: { action: \"AUTO_REJECT\", severity: \"urgent\" },\n priority: 200,\n enabled: true,\n rationale: \"Actor role is not authorized for governed SAP execution.\",\n },\n {\n rule_id: \"exec-segregation-of-duties\",\n name: \"Segregation of duties enforced\",\n decision_domain: \"*\",\n when: {\n all: [\n { field: \"gate\", operator: \"EQ\", value: \"execution_authority\" },\n { field: \"sod_violation\", operator: \"EQ\", value: true },\n ],\n },\n then: { action: \"AUTO_REJECT\", severity: \"urgent\" },\n priority: 195,\n enabled: true,\n rationale: \"Segregation-of-duties check failed because requester and approver match.\",\n },\n {\n rule_id: \"exec-three-way-match\",\n name: \"Three-way match before payment release\",\n decision_domain: \"*\",\n when: {\n all: [\n { field: \"gate\", operator: \"EQ\", value: \"execution_authority\" },\n { field: \"three_way_match_failed\", operator: \"EQ\", value: true },\n ],\n },\n then: { action: \"REQUIRE_REVIEW\", severity: \"elevated\", sla_minutes: 120 },\n priority: 175,\n enabled: true,\n rationale:\n \"Goods receipt does not confirm the invoiced quantity/amount; hold payment until the PO, goods receipt, and invoice reconcile.\",\n },\n {\n rule_id: \"exec-regional-hold\",\n name: \"Regional compliance hold\",\n decision_domain: \"*\",\n when: {\n all: [\n { field: \"gate\", operator: \"EQ\", value: \"execution_authority\" },\n { field: \"regional_hold\", operator: \"EQ\", value: true },\n ],\n },\n then: { action: \"REQUIRE_REVIEW\", severity: \"elevated\", sla_minutes: 60 },\n priority: 170,\n enabled: true,\n rationale: \"Regional constraint requires a revisit trigger before SAP execution.\",\n },\n {\n rule_id: \"exec-treasury-threshold\",\n name: \"High-value PO requires Treasury Head approval\",\n decision_domain: \"*\",\n when: {\n all: [\n { field: \"gate\", operator: \"EQ\", value: \"execution_authority\" },\n { field: \"po_over_threshold\", operator: \"EQ\", value: true },\n { field: \"treasury_approved\", operator: \"EQ\", value: false },\n ],\n },\n then: { action: \"ESCALATE\", severity: \"urgent\", sla_minutes: 10 },\n priority: 160,\n enabled: true,\n rationale: \"PO amount exceeds threshold and Treasury Head approval is missing.\",\n },\n // ── Catch-all admits (lowest priority) ───────────────────────────\n // A clean action matches only its gate's catch-all → APPROVE, instead of\n // the engine's `no_matching_rule → REVIEW` default. Any block/escalate/\n // review rule above (priority ≥ 160) outranks these.\n {\n rule_id: \"state-admit-default\",\n name: \"Admit a clean SAP state\",\n decision_domain: \"*\",\n when: { all: [{ field: \"gate\", operator: \"EQ\", value: \"state_admission\" }] },\n then: { action: \"AUTO_APPROVE\" },\n priority: 1,\n enabled: true,\n rationale:\n \"SAP proposed state is complete, non-conflicting, and eligible for execution review.\",\n },\n {\n rule_id: \"exec-authorize-default\",\n name: \"Authorize a clean SAP execution\",\n decision_domain: \"*\",\n when: { all: [{ field: \"gate\", operator: \"EQ\", value: \"execution_authority\" }] },\n then: { action: \"AUTO_APPROVE\" },\n priority: 1,\n enabled: true,\n rationale: \"Execution authority is present for the proposed SAP action.\",\n },\n ],\n },\n resolver_overrides: {\n domain_by_engine: {\n sap: \"SAP_EXECUTION_AUTHORITY\",\n procure: \"SAP_STATE_ADMISSION\",\n },\n intent_domain_hints: [\n {\n domain: \"SAP_STATE_ADMISSION\",\n keywords: [\"purchase order\", \"vendor\", \"cost center\", \"budget\", \"procurement state\"],\n },\n {\n domain: \"SAP_EXECUTION_AUTHORITY\",\n keywords: [\n \"payment release\",\n \"vendor payment\",\n \"approval authority\",\n \"segregation of duties\",\n ],\n },\n ],\n evidence_required_keywords: [\"vendor\", \"purchase order\", \"payment\", \"approval\", \"cost center\"],\n missing_evidence_fields: [\"amount\", \"currency\", \"vendor_id\", \"cost_center\"],\n base_confidence: 0.6,\n attachment_confidence_bonus: 0.08,\n intake_confidence_bonus: 0.03,\n missing_evidence_penalty: 0.3,\n },\n execution_templates: {\n SUCCEEDED: [\n \"Write back governed decision dossier reference to the SAP document\",\n \"Continue SAP workflow with attached policy version and evidence hashes\",\n \"Record the decision in the shared audit ledger\",\n ],\n NEEDS_EVIDENCE: [\n \"Pause SAP workflow and create an escalation task\",\n \"Request the missing approval or Treasury Head signature\",\n \"Set a revisit trigger for regional compliance review\",\n ],\n FAILED: [\n \"Stop SAP execution and notify the user\",\n \"Record the blocking reason and required action in the dossier\",\n \"Escalate to the authorized SAP role for adjudication\",\n ],\n },\n ui_copy: {\n recommendation_success:\n \"Proceed with the governed SAP {domain} action; the signed dossier is chained into the audit ledger.\",\n recommendation_needs_evidence:\n \"Hold the SAP {domain} action until the missing approval or evidence is supplied.\",\n recommendation_failed:\n \"Block the SAP {domain} action and escalate to the authorized role with the recorded reason.\",\n },\n};\n","import type { VerticalPack } from \"../VerticalContracts.js\";\n\n/**\n * Reference scaffold for future vertical packs.\n * Keep this generic and implementation-neutral.\n */\nexport const templateVerticalPack: VerticalPack = {\n key: \"template\",\n display_name: \"Template Vertical Pack\",\n description: \"Scaffold for onboarding additional industry packs.\",\n default_domain: \"OPERATIONS\",\n signal_mappings: [\n { domain: \"OPERATIONS\", metric_name: \"decision_latency_ms\", source_hint: \"app\" },\n ],\n policy_bundle: {\n version: \"template-v1\",\n rules: [\n {\n rule_id: \"template-evidence-check\",\n name: \"Template evidence gate\",\n decision_domain: \"OPERATIONS\",\n when: {\n all: [{ field: \"evidence.attachments\", operator: \"LT\", value: 1 }],\n },\n then: {\n action: \"REQUEST_INFO\",\n severity: \"routine\",\n sla_minutes: 240,\n },\n priority: 10,\n enabled: true,\n },\n ],\n },\n resolver_overrides: {\n domain_by_engine: {\n software: \"OPERATIONS\",\n },\n intent_domain_hints: [{ domain: \"OPERATIONS\", keywords: [\"decision\", \"workflow\"] }],\n evidence_required_keywords: [\"approval\", \"risk\"],\n missing_evidence_fields: [\"supporting_attachment\"],\n base_confidence: 0.5,\n attachment_confidence_bonus: 0.1,\n intake_confidence_bonus: 0.02,\n missing_evidence_penalty: 0.2,\n },\n execution_templates: {\n SUCCEEDED: [\"Assign owner\", \"Publish outcome\", \"Schedule revisit\"],\n NEEDS_EVIDENCE: [\"Collect evidence\", \"Validate policy alignment\", \"Re-run evaluation\"],\n FAILED: [\"Escalate to reviewer\", \"Capture override reason\", \"Retry with context\"],\n },\n ui_copy: {\n recommendation_success: \"Proceed with {domain} decision.\",\n recommendation_needs_evidence: \"Collect missing evidence for {domain}.\",\n recommendation_failed: \"Escalate decision for manual review.\",\n },\n};\n","import type { VerticalPack } from \"../VerticalContracts.js\";\n\n/**\n * Workday HR vertical pack — governs Workday HCM business processes\n * (terminations, compensation changes, job/org changes, hires) before they\n * execute, so an autonomous agent or a delegated approver cannot commit a\n * high-stakes employment action without the required completeness, authority,\n * and fairness checks.\n *\n * Same dual-gate shape as the SAP pack (`SapPack.ts`): Gate 1 admits a proposed\n * HR state only when it is complete and eligible, and Gate 2 authorizes the\n * execution only when the actor holds authority and policy constraints (SoD,\n * pay equity, compensation thresholds, offboarding coordination, works-council\n * consultation) are satisfied. Each rule carries a `gate` predicate so one pack\n * serves both gates; `decision_domain: \"*\"` keeps the rules domain-agnostic so\n * the surface — not the domain resolver — selects them. Highest matched\n * `priority` wins, reproducing a short-circuit check order.\n *\n * Reason/required-action text for each rule lives in the adapter\n * (`WorkdaySurface.ts`), keyed by `rule_id`, so this pack stays purely\n * declarative.\n */\nexport const workdayVerticalPack: VerticalPack = {\n key: \"workday\",\n display_name: \"Workday HR Governance\",\n description:\n \"Dual-gate governance for Workday HCM business processes — state admission (completeness, effective date, worker status, termination reason, compensation structure) and execution authority (authorized role, segregation of duties, compensation thresholds, pay-equity review, offboarding coordination, works-council consultation) before they execute.\",\n default_domain: \"WORKDAY_HR_EXECUTION_AUTHORITY\",\n workflow_keys: [\"hr_hiring_governance\"],\n signal_mappings: [\n {\n domain: \"WORKDAY_HR_STATE_ADMISSION\",\n metric_name: \"workday_hr_state_completeness_rate\",\n source_hint: \"workday_hcm\",\n },\n {\n domain: \"WORKDAY_HR_EXECUTION_AUTHORITY\",\n metric_name: \"workday_hr_unauthorized_execution_rate\",\n source_hint: \"workday_hcm\",\n },\n ],\n policy_bundle: {\n version: \"workday-hr-governance-v1\",\n rules: [\n // ── Gate 1: state admission ──────────────────────────────────────\n {\n rule_id: \"state-required-fields\",\n name: \"Required Workday HR state fields present\",\n decision_domain: \"*\",\n when: {\n all: [\n { field: \"gate\", operator: \"EQ\", value: \"state_admission\" },\n { field: \"missing_required_fields\", operator: \"GT\", value: 0 },\n ],\n },\n then: { action: \"AUTO_REJECT\", severity: \"urgent\" },\n priority: 200,\n enabled: true,\n rationale:\n \"HR business process is incomplete; worker, process, effective date, and initiator must be present before admission.\",\n },\n {\n rule_id: \"state-effective-date-valid\",\n name: \"Effective date is valid\",\n decision_domain: \"*\",\n when: {\n all: [\n { field: \"gate\", operator: \"EQ\", value: \"state_admission\" },\n { field: \"effective_date_invalid\", operator: \"EQ\", value: true },\n ],\n },\n then: { action: \"AUTO_REJECT\", severity: \"urgent\" },\n priority: 195,\n enabled: true,\n rationale: \"The business process effective date must be a valid calendar date.\",\n },\n {\n rule_id: \"state-worker-active\",\n name: \"Worker record is actionable\",\n decision_domain: \"*\",\n when: {\n all: [\n { field: \"gate\", operator: \"EQ\", value: \"state_admission\" },\n { field: \"worker_actionable\", operator: \"EQ\", value: false },\n ],\n },\n then: { action: \"AUTO_REJECT\", severity: \"urgent\" },\n priority: 190,\n enabled: true,\n rationale: \"Worker record is terminated or inactive and cannot receive this process.\",\n },\n {\n rule_id: \"state-termination-reason\",\n name: \"Termination carries a reason code\",\n decision_domain: \"*\",\n when: {\n all: [\n { field: \"gate\", operator: \"EQ\", value: \"state_admission\" },\n { field: \"termination_reason_missing\", operator: \"EQ\", value: true },\n ],\n },\n then: { action: \"AUTO_REJECT\", severity: \"urgent\" },\n priority: 185,\n enabled: true,\n rationale: \"A termination must specify a reason code before it can be admitted.\",\n },\n {\n rule_id: \"state-compensation-structured\",\n name: \"Compensation change cites a pay structure\",\n decision_domain: \"*\",\n when: {\n all: [\n { field: \"gate\", operator: \"EQ\", value: \"state_admission\" },\n { field: \"compensation_change\", operator: \"EQ\", value: true },\n { field: \"structured_criteria_used\", operator: \"EQ\", value: false },\n ],\n },\n then: { action: \"AUTO_REJECT\", severity: \"urgent\" },\n priority: 180,\n enabled: true,\n rationale:\n \"A compensation change must reference a salary band or documented pay structure before admission.\",\n },\n // ── Gate 2: execution authority ──────────────────────────────────\n {\n rule_id: \"exec-duplicate-process\",\n name: \"Duplicate business process suspected\",\n decision_domain: \"*\",\n when: {\n all: [\n { field: \"gate\", operator: \"EQ\", value: \"execution_authority\" },\n { field: \"duplicate_suspected\", operator: \"EQ\", value: true },\n ],\n },\n then: { action: \"AUTO_REJECT\", severity: \"urgent\" },\n priority: 210,\n enabled: true,\n rationale:\n \"A prior business process for the same worker, type, and effective date was found.\",\n },\n {\n rule_id: \"exec-authorized-role\",\n name: \"Actor holds an authorized HR role\",\n decision_domain: \"*\",\n when: {\n all: [\n { field: \"gate\", operator: \"EQ\", value: \"execution_authority\" },\n { field: \"actor_authorized\", operator: \"EQ\", value: false },\n ],\n },\n then: { action: \"AUTO_REJECT\", severity: \"urgent\" },\n priority: 200,\n enabled: true,\n rationale: \"Actor role is not authorized to execute governed Workday HR processes.\",\n },\n {\n rule_id: \"exec-segregation-of-duties\",\n name: \"Segregation of duties enforced\",\n decision_domain: \"*\",\n when: {\n all: [\n { field: \"gate\", operator: \"EQ\", value: \"execution_authority\" },\n { field: \"sod_violation\", operator: \"EQ\", value: true },\n ],\n },\n then: { action: \"AUTO_REJECT\", severity: \"urgent\" },\n priority: 195,\n enabled: true,\n rationale:\n \"Segregation-of-duties check failed because the initiator and approver are the same person.\",\n },\n {\n rule_id: \"exec-compensation-threshold\",\n name: \"High-impact compensation change requires committee approval\",\n decision_domain: \"*\",\n when: {\n all: [\n { field: \"gate\", operator: \"EQ\", value: \"execution_authority\" },\n { field: \"compensation_over_threshold\", operator: \"EQ\", value: true },\n { field: \"compensation_committee_approved\", operator: \"EQ\", value: false },\n ],\n },\n then: { action: \"ESCALATE\", severity: \"urgent\", sla_minutes: 10 },\n priority: 185,\n enabled: true,\n rationale:\n \"Compensation change exceeds the policy threshold and Compensation Committee approval is missing.\",\n },\n {\n rule_id: \"exec-pay-equity\",\n name: \"Pay-equity review before compensation execution\",\n decision_domain: \"*\",\n when: {\n all: [\n { field: \"gate\", operator: \"EQ\", value: \"execution_authority\" },\n { field: \"pay_equity_flagged\", operator: \"EQ\", value: true },\n { field: \"pay_equity_cleared\", operator: \"EQ\", value: false },\n ],\n },\n then: { action: \"REQUIRE_REVIEW\", severity: \"elevated\", sla_minutes: 120 },\n priority: 180,\n enabled: true,\n rationale:\n \"An adverse-impact / pay-equity signal is open; hold the compensation change until it is cleared.\",\n },\n {\n rule_id: \"exec-termination-offboarding\",\n name: \"Termination coordinates access revocation\",\n decision_domain: \"*\",\n when: {\n all: [\n { field: \"gate\", operator: \"EQ\", value: \"execution_authority\" },\n { field: \"is_termination\", operator: \"EQ\", value: true },\n { field: \"offboarding_ready\", operator: \"EQ\", value: false },\n ],\n },\n then: { action: \"REQUIRE_REVIEW\", severity: \"elevated\", sla_minutes: 60 },\n priority: 175,\n enabled: true,\n rationale:\n \"Termination has no confirmed access-revocation / offboarding plan; hold until offboarding is coordinated.\",\n },\n {\n rule_id: \"exec-works-council-hold\",\n name: \"Regional works-council consultation\",\n decision_domain: \"*\",\n when: {\n all: [\n { field: \"gate\", operator: \"EQ\", value: \"execution_authority\" },\n { field: \"works_council_hold\", operator: \"EQ\", value: true },\n ],\n },\n then: { action: \"REQUIRE_REVIEW\", severity: \"elevated\", sla_minutes: 60 },\n priority: 170,\n enabled: true,\n rationale:\n \"A regional works-council consultation is required before this employment action can execute.\",\n },\n // ── Catch-all admits (lowest priority) ───────────────────────────\n // A clean action matches only its gate's catch-all → APPROVE, instead of\n // the engine's `no_matching_rule → REVIEW` default. Any reject/escalate/\n // review rule above (priority ≥ 170) outranks these.\n {\n rule_id: \"state-admit-default\",\n name: \"Admit a clean Workday HR state\",\n decision_domain: \"*\",\n when: { all: [{ field: \"gate\", operator: \"EQ\", value: \"state_admission\" }] },\n then: { action: \"AUTO_APPROVE\" },\n priority: 1,\n enabled: true,\n rationale:\n \"Workday HR proposed state is complete, non-conflicting, and eligible for execution review.\",\n },\n {\n rule_id: \"exec-authorize-default\",\n name: \"Authorize a clean Workday HR execution\",\n decision_domain: \"*\",\n when: { all: [{ field: \"gate\", operator: \"EQ\", value: \"execution_authority\" }] },\n then: { action: \"AUTO_APPROVE\" },\n priority: 1,\n enabled: true,\n rationale: \"Execution authority is present for the proposed Workday HR action.\",\n },\n ],\n },\n resolver_overrides: {\n domain_by_engine: {\n hiring: \"WORKDAY_HR_EXECUTION_AUTHORITY\",\n hr: \"WORKDAY_HR_EXECUTION_AUTHORITY\",\n hcm: \"WORKDAY_HR_STATE_ADMISSION\",\n },\n intent_domain_hints: [\n {\n domain: \"WORKDAY_HR_STATE_ADMISSION\",\n keywords: [\n \"worker record\",\n \"effective date\",\n \"job change\",\n \"position\",\n \"business process state\",\n ],\n },\n {\n domain: \"WORKDAY_HR_EXECUTION_AUTHORITY\",\n keywords: [\n \"termination\",\n \"offboarding\",\n \"compensation change\",\n \"pay equity\",\n \"approval authority\",\n \"segregation of duties\",\n ],\n },\n ],\n evidence_required_keywords: [\n \"worker\",\n \"termination\",\n \"compensation\",\n \"approval\",\n \"effective date\",\n ],\n missing_evidence_fields: [\"worker_id\", \"business_process\", \"effective_date\", \"reason_code\"],\n base_confidence: 0.6,\n attachment_confidence_bonus: 0.08,\n intake_confidence_bonus: 0.03,\n missing_evidence_penalty: 0.3,\n },\n execution_templates: {\n SUCCEEDED: [\n \"Write back the governed decision dossier reference to the Workday business process\",\n \"Continue the Workday business process with the attached policy version and evidence hashes\",\n \"Record the decision in the shared audit ledger\",\n ],\n NEEDS_EVIDENCE: [\n \"Pause the Workday business process and create an escalation task\",\n \"Request the missing approval, offboarding plan, or pay-equity clearance\",\n \"Set a revisit trigger for the works-council consultation\",\n ],\n FAILED: [\n \"Stop the Workday business process and notify the initiator\",\n \"Record the blocking reason and required action in the dossier\",\n \"Escalate to the authorized HR role for adjudication\",\n ],\n },\n ui_copy: {\n recommendation_success:\n \"Proceed with the governed Workday {domain} action; the signed dossier is chained into the audit ledger.\",\n recommendation_needs_evidence:\n \"Hold the Workday {domain} action until the missing approval, offboarding plan, or clearance is supplied.\",\n recommendation_failed:\n \"Block the Workday {domain} action and escalate to the authorized HR role with the recorded reason.\",\n },\n};\n","import type { VerticalPack } from \"../VerticalContracts.js\";\n\n/**\n * Workday Financials circuit-breaker pack — governs Workday Financials commits\n * (payroll runs, expense payouts, supplier invoices, purchase orders) inline at\n * the API boundary, before they write to the ledger or treasury queue. This is\n * the \"prevent, don't audit-and-recover\" surface: it blocks a bad commit rather\n * than logging it after the ACH/payment file is generated.\n *\n * Same dual-gate shape as the SAP and Workday HR packs. Gate 1 admits a proposed\n * financial state only when it is complete and the amount is valid; Gate 2 is the\n * circuit breaker — hard-cap breach, payroll variance, duplicate payment,\n * off-contract invoice, unit-price anomaly, and approver authority. Each rule\n * carries a `gate` predicate; `decision_domain: \"*\"` keeps the rules\n * domain-agnostic so the surface (`WorkdayFinancialsSurface.ts`) selects them via\n * derived facts. Highest matched `priority` wins.\n *\n * Reason/required-action text per rule lives in the adapter, keyed by `rule_id`,\n * so this pack stays purely declarative.\n */\nexport const workdayFinancialsVerticalPack: VerticalPack = {\n key: \"workday_financials\",\n display_name: \"Workday Financials Circuit Breaker\",\n description:\n \"Pre-execution circuit breaker for Workday Financials — state admission (completeness, valid amount) and execution authority (hard-cap breach, payroll variance, duplicate payment, off-contract invoice, unit-price anomaly, approver authority) enforced inline before a payroll run, expense payout, or supplier invoice commits.\",\n default_domain: \"WORKDAY_FIN_EXECUTION_AUTHORITY\",\n signal_mappings: [\n {\n domain: \"WORKDAY_FIN_STATE_ADMISSION\",\n metric_name: \"workday_fin_state_completeness_rate\",\n source_hint: \"workday_financials\",\n },\n {\n domain: \"WORKDAY_FIN_EXECUTION_AUTHORITY\",\n metric_name: \"workday_fin_blocked_commit_rate\",\n source_hint: \"workday_financials\",\n },\n ],\n policy_bundle: {\n version: \"workday-financials-v1\",\n rules: [\n // ── Gate 1: state admission ──────────────────────────────────────\n {\n rule_id: \"state-required-fields\",\n name: \"Required Financials state fields present\",\n decision_domain: \"*\",\n when: {\n all: [\n { field: \"gate\", operator: \"EQ\", value: \"state_admission\" },\n { field: \"missing_required_fields\", operator: \"GT\", value: 0 },\n ],\n },\n then: { action: \"AUTO_REJECT\", severity: \"urgent\" },\n priority: 200,\n enabled: true,\n rationale:\n \"Financial payload is incomplete; the payee, amount, and currency must be present before admission.\",\n },\n {\n rule_id: \"state-amount-valid\",\n name: \"Amount is a valid positive value\",\n decision_domain: \"*\",\n when: {\n all: [\n { field: \"gate\", operator: \"EQ\", value: \"state_admission\" },\n { field: \"amount_invalid\", operator: \"EQ\", value: true },\n ],\n },\n then: { action: \"AUTO_REJECT\", severity: \"urgent\" },\n priority: 195,\n enabled: true,\n rationale: \"Payout / invoice amount must be a positive numeric value.\",\n },\n // ── Gate 2: execution authority (the circuit breaker) ────────────\n {\n rule_id: \"exec-duplicate-payment\",\n name: \"Duplicate payment suspected\",\n decision_domain: \"*\",\n when: {\n all: [\n { field: \"gate\", operator: \"EQ\", value: \"execution_authority\" },\n { field: \"duplicate_suspected\", operator: \"EQ\", value: true },\n ],\n },\n then: { action: \"AUTO_REJECT\", severity: \"urgent\" },\n priority: 210,\n enabled: true,\n rationale:\n \"A prior payment with the same payee + amount (or vendor + invoice) fingerprint was found.\",\n },\n {\n rule_id: \"exec-hard-cap\",\n name: \"Single payout breaches the hard cap\",\n decision_domain: \"*\",\n when: {\n all: [\n { field: \"gate\", operator: \"EQ\", value: \"execution_authority\" },\n { field: \"over_hard_cap\", operator: \"EQ\", value: true },\n ],\n },\n then: { action: \"AUTO_REJECT\", severity: \"urgent\" },\n priority: 205,\n enabled: true,\n rationale: \"A single payout exceeds the hard cap and is blocked before it commits.\",\n },\n {\n rule_id: \"exec-authorized-approver\",\n name: \"Actor holds an authorized Finance role\",\n decision_domain: \"*\",\n when: {\n all: [\n { field: \"gate\", operator: \"EQ\", value: \"execution_authority\" },\n { field: \"actor_authorized\", operator: \"EQ\", value: false },\n ],\n },\n then: { action: \"AUTO_REJECT\", severity: \"urgent\" },\n priority: 200,\n enabled: true,\n rationale: \"Actor role is not authorized to release governed Workday Financials commits.\",\n },\n {\n rule_id: \"exec-payroll-variance\",\n name: \"Payroll variance exceeds the logical threshold\",\n decision_domain: \"*\",\n when: {\n all: [\n { field: \"gate\", operator: \"EQ\", value: \"execution_authority\" },\n { field: \"variance_exceeded\", operator: \"EQ\", value: true },\n ],\n },\n then: { action: \"ESCALATE\", severity: \"urgent\", sla_minutes: 10 },\n priority: 190,\n enabled: true,\n rationale:\n \"Payroll / expense amount exceeds the allowed variance from the historical baseline; hold and escalate before committing.\",\n },\n {\n rule_id: \"exec-off-contract\",\n name: \"Invoice is off active contract terms\",\n decision_domain: \"*\",\n when: {\n all: [\n { field: \"gate\", operator: \"EQ\", value: \"execution_authority\" },\n { field: \"off_contract\", operator: \"EQ\", value: true },\n ],\n },\n then: { action: \"REQUIRE_REVIEW\", severity: \"elevated\", sla_minutes: 120 },\n priority: 185,\n enabled: true,\n rationale:\n \"Invoice does not reconcile to an active contract (missing, inactive, or over remaining value); hold for review.\",\n },\n {\n rule_id: \"exec-unit-price-anomaly\",\n name: \"Unit price exceeds the contract baseline\",\n decision_domain: \"*\",\n when: {\n all: [\n { field: \"gate\", operator: \"EQ\", value: \"execution_authority\" },\n { field: \"unit_price_anomaly\", operator: \"EQ\", value: true },\n ],\n },\n then: { action: \"REQUIRE_REVIEW\", severity: \"elevated\", sla_minutes: 120 },\n priority: 180,\n enabled: true,\n rationale:\n \"Invoiced unit price exceeds the contract / baseline unit price beyond tolerance; hold for review.\",\n },\n // ── Catch-all admits (lowest priority) ───────────────────────────\n {\n rule_id: \"state-admit-default\",\n name: \"Admit a clean Financials state\",\n decision_domain: \"*\",\n when: { all: [{ field: \"gate\", operator: \"EQ\", value: \"state_admission\" }] },\n then: { action: \"AUTO_APPROVE\" },\n priority: 1,\n enabled: true,\n rationale: \"Financial proposed state is complete and eligible for execution review.\",\n },\n {\n rule_id: \"exec-authorize-default\",\n name: \"Authorize a clean Financials commit\",\n decision_domain: \"*\",\n when: { all: [{ field: \"gate\", operator: \"EQ\", value: \"execution_authority\" }] },\n then: { action: \"AUTO_APPROVE\" },\n priority: 1,\n enabled: true,\n rationale: \"Circuit-breaker checks passed for the proposed Workday Financials commit.\",\n },\n ],\n },\n resolver_overrides: {\n domain_by_engine: {\n payroll: \"WORKDAY_FIN_EXECUTION_AUTHORITY\",\n procure: \"WORKDAY_FIN_EXECUTION_AUTHORITY\",\n finance: \"WORKDAY_FIN_STATE_ADMISSION\",\n },\n intent_domain_hints: [\n {\n domain: \"WORKDAY_FIN_STATE_ADMISSION\",\n keywords: [\"payroll state\", \"expense payload\", \"invoice intake\", \"amount\", \"currency\"],\n },\n {\n domain: \"WORKDAY_FIN_EXECUTION_AUTHORITY\",\n keywords: [\n \"payroll run\",\n \"duplicate payment\",\n \"hard cap\",\n \"vendor invoice\",\n \"off contract\",\n \"unit price\",\n \"treasury release\",\n ],\n },\n ],\n evidence_required_keywords: [\"payment\", \"payroll\", \"invoice\", \"vendor\", \"amount\"],\n missing_evidence_fields: [\"amount\", \"currency\", \"vendor_id\", \"worker_id\"],\n base_confidence: 0.6,\n attachment_confidence_bonus: 0.08,\n intake_confidence_bonus: 0.03,\n missing_evidence_penalty: 0.3,\n },\n execution_templates: {\n SUCCEEDED: [\n \"Release the Workday Financials commit with the attached policy version and evidence hashes\",\n \"Write back the governed decision dossier reference to the Workday transaction\",\n \"Record the decision in the shared audit ledger\",\n ],\n NEEDS_EVIDENCE: [\n \"Hold the payroll run / invoice and create an escalation task\",\n \"Request the missing approval, contract match, or variance justification\",\n \"Set a revisit trigger for the finance reviewer\",\n ],\n FAILED: [\n \"Block the commit before it reaches the ledger or treasury queue\",\n \"Record the blocking reason and required action in the signed dossier\",\n \"Escalate to the authorized Finance role for adjudication\",\n ],\n },\n ui_copy: {\n recommendation_success:\n \"Release the governed Workday {domain} commit; the signed dossier is chained into the audit ledger.\",\n recommendation_needs_evidence:\n \"Hold the Workday {domain} commit until the missing approval, contract match, or justification is supplied.\",\n recommendation_failed:\n \"Block the Workday {domain} commit before it writes to the ledger and escalate with the recorded reason.\",\n },\n};\n","import type { VerticalPack } from \"../VerticalContracts.js\";\n\ninterface WorkflowPackConfig {\n key:\n | \"engineering_workflow_embedding\"\n | \"procurement_authority\"\n | \"servicenow_execution_governance\"\n | \"salesforce_execution_governance\"\n | \"trade_ops_decisioning\"\n | \"finance_transaction_routing\"\n | \"cfd_trade_execution\"\n | \"hr_hiring_governance\"\n | \"revenue_intake_governance\"\n | \"sales_service_ops\"\n | \"security_risk_governance\"\n | \"webex_fund_disbursement\"\n | \"webex_procurement_override\"\n | \"webex_sensitive_system_change\"\n | \"hospitality_operations\"\n | \"team_task_triage\"\n | \"ops_customer_impact\";\n display_name: string;\n description: string;\n default_domain: string;\n signal_source: string;\n primary_engine: \"software\" | \"procure\" | \"finance\" | \"hiring\";\n intent_keywords: string[];\n required_evidence_fields: string[];\n success_actions: string[];\n needs_evidence_actions: string[];\n failed_actions: string[];\n}\n\n/** Factory for the config-driven workflow vertical packs. */\nclass WorkflowPackFactory {\n static create(config: WorkflowPackConfig): VerticalPack {\n return {\n key: config.key,\n display_name: config.display_name,\n description: config.description,\n workflow_keys: [config.key],\n default_domain: config.default_domain,\n signal_mappings: [\n {\n domain: config.default_domain,\n metric_name: \"decision_cycle_count\",\n source_hint: config.signal_source,\n },\n {\n domain: config.default_domain,\n metric_name: \"escalation_ratio\",\n source_hint: config.signal_source,\n },\n {\n domain: config.default_domain,\n metric_name: \"evidence_completeness_rate\",\n source_hint: config.signal_source,\n },\n ],\n policy_bundle: {\n version: `${config.key}-v1`,\n rules: [\n {\n rule_id: \"evidence-required\",\n name: \"Evidence completeness gate\",\n decision_domain: config.default_domain,\n when: {\n all: [{ field: \"evidence.attachments\", operator: \"LT\", value: 1 }],\n },\n then: {\n action: \"REQUEST_INFO\",\n severity: \"elevated\",\n sla_minutes: 45,\n },\n priority: 120,\n enabled: true,\n rationale: \"Do not finalize high-consequence decisions without evidence.\",\n },\n {\n rule_id: \"owner-accountability\",\n name: \"Owner and escalation accountability\",\n decision_domain: config.default_domain,\n when: {\n all: [{ field: \"intake.owner\", operator: \"EXISTS\" }],\n },\n then: {\n action: \"REQUIRE_REVIEW\",\n severity: \"routine\",\n sla_minutes: 60,\n },\n priority: 100,\n enabled: true,\n rationale: \"Every routed decision must have a named accountable owner.\",\n },\n ],\n },\n resolver_overrides: {\n domain_by_engine: {\n [config.primary_engine]: config.default_domain,\n },\n intent_domain_hints: [\n {\n domain: config.default_domain,\n keywords: config.intent_keywords,\n },\n ],\n evidence_required_keywords: config.intent_keywords,\n missing_evidence_fields: config.required_evidence_fields,\n base_confidence: 0.56,\n attachment_confidence_bonus: 0.1,\n intake_confidence_bonus: 0.02,\n missing_evidence_penalty: 0.25,\n },\n execution_templates: {\n SUCCEEDED: config.success_actions,\n NEEDS_EVIDENCE: config.needs_evidence_actions,\n FAILED: config.failed_actions,\n },\n ui_copy: {\n recommendation_success:\n \"Proceed with {domain} decision while keeping policy and execution traceability intact.\",\n recommendation_needs_evidence:\n \"Collect missing context and evidence for {domain} before final approval.\",\n recommendation_failed:\n \"Escalate {domain} to accountable authority for manual adjudication.\",\n },\n };\n }\n}\n\nexport const workflowVerticalPacks: VerticalPack[] = [\n WorkflowPackFactory.create({\n key: \"engineering_workflow_embedding\",\n display_name: \"Engineering Workflow Embedding\",\n description: \"Embed decision governance into engineering issue, ADR, and release workflows.\",\n default_domain: \"ENGINEERING_GOVERNANCE\",\n signal_source: \"engineering_workflow\",\n primary_engine: \"software\",\n intent_keywords: [\"engineering\", \"release\", \"architecture\", \"adr\", \"pull request\"],\n required_evidence_fields: [\"workflow_name\", \"owner\", \"blast_radius\"],\n success_actions: [\n \"Attach recommendation to issue or ADR record\",\n \"Assign owner and release checkpoint\",\n \"Set revisit trigger for incident or drift signals\",\n ],\n needs_evidence_actions: [\n \"Capture blast radius and rollback evidence\",\n \"Add accountable engineering owner\",\n \"Re-run decision evaluation\",\n ],\n failed_actions: [\n \"Escalate to engineering leadership\",\n \"Pause release workflow\",\n \"Record manual adjudication rationale\",\n ],\n }),\n WorkflowPackFactory.create({\n key: \"procurement_authority\",\n display_name: \"Procurement Authority\",\n description:\n \"Evaluate procurement renewals/new buys with policy checks, quote/SOW evidence, and routing controls.\",\n default_domain: \"PROCUREMENT_AUTHORITY\",\n signal_source: \"procurement_workflow\",\n primary_engine: \"procure\",\n intent_keywords: [\"procure\", \"vendor\", \"renewal\", \"quote\", \"sow\", \"purchase\"],\n required_evidence_fields: [\"vendor\", \"amount\", \"currency\", \"category\"],\n success_actions: [\n \"Emit procurement decision dossier\",\n \"Route approval to accountable procurement owner\",\n \"Set revisit trigger on contract renewal and spend variance\",\n ],\n needs_evidence_actions: [\n \"Attach quote and SOW evidence\",\n \"Capture policy references for approval\",\n \"Re-run procurement decision flow\",\n ],\n failed_actions: [\n \"Escalate to procurement governance authority\",\n \"Hold vendor commitment\",\n \"Record override request requirements\",\n ],\n }),\n WorkflowPackFactory.create({\n key: \"servicenow_execution_governance\",\n display_name: \"ServiceNow Execution Governance\",\n description:\n \"Govern ServiceNow GRC, ITOM, and finance-adjacent execution paths with policy checks, dossiers, and shadow-mode rollout.\",\n default_domain: \"SERVICENOW_GOVERNANCE\",\n signal_source: \"servicenow_workflow\",\n primary_engine: \"finance\",\n intent_keywords: [\n \"servicenow\",\n \"risk exception\",\n \"change approval\",\n \"grc\",\n \"itom\",\n \"vendor onboarding\",\n \"approval\",\n ],\n required_evidence_fields: [\n \"record_table\",\n \"record_id\",\n \"requested_action\",\n \"policy_version\",\n \"assignment_group\",\n ],\n success_actions: [\n \"Write governed outcome back to ServiceNow record\",\n \"Attach Decision Dossier metadata and evidence link\",\n \"Route execution or collaboration follow-through to bound systems\",\n ],\n needs_evidence_actions: [\n \"Keep workflow in shadow mode or hold state\",\n \"Collect missing ServiceNow context and policy evidence\",\n \"Re-run policy check with refreshed record data\",\n ],\n failed_actions: [\n \"Escalate to governance or finance authority\",\n \"Block downstream execution from the ServiceNow workflow\",\n \"Record controlled exception rationale and owner\",\n ],\n }),\n WorkflowPackFactory.create({\n key: \"salesforce_execution_governance\",\n display_name: \"Salesforce Execution Governance\",\n description:\n \"Govern Salesforce Flow, Apex, Agentforce, and cross-system customer-operation actions with a deterministic Action Gate, portable Decision Dossiers, and shadow-mode rollout.\",\n default_domain: \"SALESFORCE_GOVERNANCE\",\n signal_source: \"salesforce_workflow\",\n primary_engine: \"finance\",\n intent_keywords: [\n \"salesforce\",\n \"agentforce\",\n \"discount approval\",\n \"contract activation\",\n \"refund\",\n \"opportunity stage\",\n \"campaign execution\",\n ],\n required_evidence_fields: [\n \"object_type\",\n \"record_id\",\n \"action_name\",\n \"policy_version\",\n \"record_owner\",\n ],\n success_actions: [\n \"Return execute decision to Salesforce Flow or Agentforce wrapper\",\n \"Attach a portable Decision Dossier with verification link and signature\",\n \"Route governed downstream execution to MuleSoft or connected enterprise systems\",\n ],\n needs_evidence_actions: [\n \"Keep the action in shadow mode or deliberate delay\",\n \"Collect missing Salesforce, finance, or customer context before re-evaluating\",\n \"Re-run the Action Gate with refreshed evidence and policy state\",\n ],\n failed_actions: [\n \"Escalate to revenue, finance, or compliance authority\",\n \"Block downstream execution from Salesforce automation\",\n \"Record controlled exception rationale and owner for audit traceability\",\n ],\n }),\n WorkflowPackFactory.create({\n key: \"trade_ops_decisioning\",\n display_name: \"Trade Ops Decisioning\",\n description:\n \"Structure trade-ops implementation, replacement, and do-nothing decisions with compliance, logistics, and settlement evidence.\",\n default_domain: \"TRADE_OPERATIONS\",\n signal_source: \"trade_ops_workflow\",\n primary_engine: \"procure\",\n intent_keywords: [\n \"trade ops\",\n \"exporter\",\n \"buyer discovery\",\n \"compliance\",\n \"logistics\",\n \"settlement\",\n ],\n required_evidence_fields: [\n \"buyer_profile\",\n \"compliance_requirements\",\n \"logistics_path\",\n \"settlement_terms\",\n \"do_nothing_criteria\",\n ],\n success_actions: [\n \"Publish trade-ops decision dossier with implementation/replace/do-nothing verdict\",\n \"Assign accountable operations owner and milestone checkpoint\",\n \"Set revisit trigger for compliance rejection or settlement delays\",\n ],\n needs_evidence_actions: [\n \"Capture missing buyer discovery and compliance evidence\",\n \"Attach logistics and settlement dependency details\",\n \"Re-run trade-ops decision flow with updated inputs\",\n ],\n failed_actions: [\n \"Escalate to trade operations governance owner\",\n \"Pause operating-model cutover\",\n \"Record controlled do-nothing rationale for audit\",\n ],\n }),\n WorkflowPackFactory.create({\n key: \"finance_transaction_routing\",\n display_name: \"Finance Transaction Routing\",\n description:\n \"Govern high-frequency financial routing and authorization decisions with explicit override controls.\",\n default_domain: \"FINANCIAL_ROUTING\",\n signal_source: \"finance_routing\",\n primary_engine: \"finance\",\n intent_keywords: [\"routing\", \"payment\", \"authorization\", \"credit\", \"override\"],\n required_evidence_fields: [\n \"amount\",\n \"currency\",\n \"routing_target\",\n \"approval_path\",\n \"policy_version\",\n ],\n success_actions: [\n \"Publish routing decision with policy snapshot\",\n \"Record override guardrails and owner\",\n \"Attach regulator-ready decision dossier\",\n ],\n needs_evidence_actions: [\n \"Capture missing routing controls\",\n \"Add deterministic override reason code\",\n \"Re-run finance routing evaluation\",\n ],\n failed_actions: [\n \"Escalate to finance risk authority\",\n \"Freeze automated routing branch\",\n \"Record incident-level governance notes\",\n ],\n }),\n WorkflowPackFactory.create({\n key: \"cfd_trade_execution\",\n display_name: \"CFD Trade Execution\",\n description:\n \"Govern leveraged CFD trade requests with margin guardrails, exit controls, and broker-order execution checks.\",\n default_domain: \"CFD_TRADE_EXECUTION\",\n signal_source: \"cfd_trade_execution\",\n primary_engine: \"finance\",\n intent_keywords: [\n \"cfd\",\n \"trade execution\",\n \"leverage\",\n \"margin\",\n \"stop loss\",\n \"take profit\",\n \"broker order\",\n ],\n required_evidence_fields: [\n \"instrument\",\n \"side\",\n \"order_type\",\n \"size_or_notional\",\n \"leverage\",\n \"margin_available\",\n \"approval_path\",\n \"policy_version\",\n ],\n success_actions: [\n \"Publish governed CFD trade decision with leverage and margin guardrails\",\n \"Record exit-control posture plus accountable approval path\",\n \"Attach broker-order control evidence to the decision dossier\",\n ],\n needs_evidence_actions: [\n \"Capture missing sizing, leverage, or margin evidence\",\n \"Add exit controls and accountable approval-path details\",\n \"Re-run CFD trade evaluation before broker release\",\n ],\n failed_actions: [\n \"Escalate to dealing-risk authority\",\n \"Hold broker release for the proposed trade\",\n \"Record override and market-risk governance notes\",\n ],\n }),\n WorkflowPackFactory.create({\n key: \"hr_hiring_governance\",\n display_name: \"HR Hiring Governance\",\n description:\n \"Govern candidate progression, compensation exceptions, and headcount approvals with fairness checks.\",\n default_domain: \"HR_GOVERNANCE\",\n signal_source: \"hiring_workflow\",\n primary_engine: \"hiring\",\n intent_keywords: [\"hiring\", \"candidate\", \"headcount\", \"compensation\", \"fairness\"],\n required_evidence_fields: [\n \"role_title\",\n \"team\",\n \"hiring_manager\",\n \"business_justification\",\n \"structured_criteria_used\",\n ],\n success_actions: [\n \"Record rationale and fairness checklist\",\n \"Assign accountable people owner\",\n \"Set revisit trigger for probation/plan cycles\",\n ],\n needs_evidence_actions: [\n \"Complete fairness and compliance checklist\",\n \"Attach candidate progression evidence\",\n \"Re-run hiring governance flow\",\n ],\n failed_actions: [\n \"Escalate to people leadership\",\n \"Pause candidate progression\",\n \"Capture exception rationale for audit\",\n ],\n }),\n WorkflowPackFactory.create({\n key: \"revenue_intake_governance\",\n display_name: \"Revenue Intake Governance\",\n description:\n \"Classify search, inbound, and demo-readiness signals into one governed revenue-intake verdict with close-proof traceability.\",\n default_domain: \"REVENUE_INTAKE_GOVERNANCE\",\n signal_source: \"revenue_intake_workflow\",\n primary_engine: \"software\",\n intent_keywords: [\n \"search intent\",\n \"lead qualification\",\n \"demo readiness\",\n \"attribution\",\n \"inbound\",\n \"revenue ops\",\n \"gtm\",\n ],\n required_evidence_fields: [\n \"query_intent\",\n \"landing_page\",\n \"cta_interaction\",\n \"firmographic_hint\",\n \"attribution_confidence\",\n ],\n success_actions: [\n \"Publish educate / qualify / route / hold verdict with observable evidence\",\n \"Assign revenue owner and next-step SLA\",\n \"Attach close-proof rationale to CRM or collaboration thread\",\n ],\n needs_evidence_actions: [\n \"Capture missing query, landing-page, or CTA evidence\",\n \"Add attribution confidence and firmographic hints\",\n \"Re-run revenue intake decision flow\",\n ],\n failed_actions: [\n \"Escalate to revenue operations owner\",\n \"Hold ambiguous inbound from automatic routing\",\n \"Record manual override and trust-gap rationale\",\n ],\n }),\n WorkflowPackFactory.create({\n key: \"sales_service_ops\",\n display_name: \"Sales / Service / Ops Decisions\",\n description:\n \"Govern customer-facing escalation and service operations decisions inside frontline workflows.\",\n default_domain: \"CUSTOMER_SERVICE_OPERATIONS\",\n signal_source: \"service_ops_workflow\",\n primary_engine: \"software\",\n intent_keywords: [\"customer\", \"service\", \"escalation\", \"sla\", \"operations\"],\n required_evidence_fields: [\"customer_impact\", \"owner\", \"sla_target\", \"escalation_path\"],\n success_actions: [\n \"Route decision into service workflow system\",\n \"Assign owner and SLA checkpoint\",\n \"Post status update to linked channel/ticket\",\n ],\n needs_evidence_actions: [\n \"Capture missing customer impact evidence\",\n \"Define escalation owner and path\",\n \"Re-run service ops decision flow\",\n ],\n failed_actions: [\n \"Escalate to service incident command\",\n \"Pause automated workflow path\",\n \"Record controlled manual override\",\n ],\n }),\n WorkflowPackFactory.create({\n key: \"security_risk_governance\",\n display_name: \"Security & Risk Governance\",\n description:\n \"Centralize risk exceptions and security governance decisions with deterministic audit traceability.\",\n default_domain: \"SECURITY_RISK_GOVERNANCE\",\n signal_source: \"security_risk_workflow\",\n primary_engine: \"finance\",\n intent_keywords: [\"security\", \"risk\", \"exception\", \"override\", \"compliance\"],\n required_evidence_fields: [\"vendor\", \"service_criticality\", \"data_access_level\", \"approver\"],\n success_actions: [\n \"Write exception decision to governance ledger\",\n \"Assign accountable risk owner\",\n \"Set revisit trigger for control drift\",\n ],\n needs_evidence_actions: [\n \"Capture missing risk evidence and control references\",\n \"Attach approval path details\",\n \"Re-run risk governance evaluation\",\n ],\n failed_actions: [\n \"Escalate to security risk authority\",\n \"Block non-governed exception path\",\n \"Capture adjudication notes\",\n ],\n }),\n WorkflowPackFactory.create({\n key: \"webex_fund_disbursement\",\n display_name: \"Webex Fund Disbursement Governance\",\n description:\n \"Govern AI-initiated fund disbursement intents originating from Webex Spaces before treasury or ERP execution begins.\",\n default_domain: \"WEBEX_FUND_DISBURSEMENT\",\n signal_source: \"webex_agentic_fund_disbursement\",\n primary_engine: \"finance\",\n intent_keywords: [\n \"webex\",\n \"fund disbursement\",\n \"payment release\",\n \"wire transfer\",\n \"beneficiary payment\",\n \"treasury\",\n ],\n required_evidence_fields: [\n \"amount\",\n \"currency\",\n \"beneficiary\",\n \"approval_path\",\n \"liquidity_status\",\n \"policy_version\",\n ],\n success_actions: [\n \"Return governed ALLOW state to the Webex agent only after enforcement approval\",\n \"Attach Decision Dossier and treasury policy snapshot to the execution record\",\n \"Route the disbursement to ERP or treasury execution with accountable owner context\",\n ],\n needs_evidence_actions: [\n \"Hold the Webex agent intent before money movement\",\n \"Collect beneficiary, liquidity, and approval-path evidence\",\n \"Re-run fund disbursement governance after evidence refresh\",\n ],\n failed_actions: [\n \"Deny disbursement execution or escalate to treasury risk authority\",\n \"Block downstream payment initiation\",\n \"Record exception rationale for regulator and audit review\",\n ],\n }),\n WorkflowPackFactory.create({\n key: \"webex_procurement_override\",\n display_name: \"Webex Procurement Override Governance\",\n description:\n \"Govern procurement overrides initiated through Webex agents, including blocked supplier exceptions and purchase authority changes.\",\n default_domain: \"WEBEX_PROCUREMENT_OVERRIDE\",\n signal_source: \"webex_agentic_procurement_override\",\n primary_engine: \"procure\",\n intent_keywords: [\n \"webex\",\n \"procurement override\",\n \"supplier exception\",\n \"vendor override\",\n \"purchase override\",\n \"blocked supplier\",\n ],\n required_evidence_fields: [\n \"vendor\",\n \"override_reason\",\n \"supplier_risk_tier\",\n \"amount\",\n \"approval_path\",\n ],\n success_actions: [\n \"Return governed approval state to the Webex procurement agent\",\n \"Attach override rationale and Decision Dossier to the sourcing record\",\n \"Route the approved exception to procurement system execution with accountable owner\",\n ],\n needs_evidence_actions: [\n \"Hold the override before supplier or PO mutation\",\n \"Collect supplier risk, policy exception, and approval evidence\",\n \"Re-run procurement override governance with updated support\",\n ],\n failed_actions: [\n \"Escalate to procurement governance or deny the override\",\n \"Block supplier or purchase-order changes from execution\",\n \"Record controlled exception handling notes for audit defensibility\",\n ],\n }),\n WorkflowPackFactory.create({\n key: \"webex_sensitive_system_change\",\n display_name: \"Webex Sensitive System Change Governance\",\n description:\n \"Govern privileged system changes proposed through Webex agents before production, infrastructure, or security-affecting execution is allowed.\",\n default_domain: \"WEBEX_SENSITIVE_SYSTEM_CHANGE\",\n signal_source: \"webex_agentic_sensitive_system_change\",\n primary_engine: \"software\",\n intent_keywords: [\n \"webex\",\n \"sensitive system change\",\n \"privileged change\",\n \"production change\",\n \"configuration override\",\n \"access change\",\n ],\n required_evidence_fields: [\n \"system_name\",\n \"change_scope\",\n \"blast_radius\",\n \"approval_path\",\n \"rollback_plan\",\n ],\n success_actions: [\n \"Return governed execution clearance only after enforcement approval\",\n \"Attach Decision Dossier and change-risk context to the system-change record\",\n \"Route the approved change into the bound ITSM or automation system with owner and rollback context\",\n ],\n needs_evidence_actions: [\n \"Hold the sensitive change in review or shadow mode\",\n \"Collect blast radius, rollback, and privileged-approval evidence\",\n \"Re-run system change governance after context refresh\",\n ],\n failed_actions: [\n \"Deny or escalate the privileged change to security or platform authority\",\n \"Block production-impacting execution\",\n \"Record adjudication rationale and exception path for forensic review\",\n ],\n }),\n WorkflowPackFactory.create({\n key: \"hospitality_operations\",\n display_name: \"Hospitality Operations\",\n description:\n \"Run hospitality operations decisions with guest-impact traceability, owner routing, and revisit governance.\",\n default_domain: \"HOSPITALITY_OPERATIONS\",\n signal_source: \"hospitality_ops_workflow\",\n primary_engine: \"software\",\n intent_keywords: [\"guest\", \"incident\", \"hospitality\", \"occupancy\", \"service recovery\"],\n required_evidence_fields: [\"location\", \"incident_type\", \"owner\", \"guest_impact\"],\n success_actions: [\n \"Assign on-duty owner and SLA\",\n \"Post operational status to team channel\",\n \"Schedule revisit in next service window\",\n ],\n needs_evidence_actions: [\n \"Capture guest-impact evidence\",\n \"Attach incident context and supporting artifacts\",\n \"Re-run hospitality operations flow\",\n ],\n failed_actions: [\n \"Escalate to incident commander\",\n \"Pause automated progression\",\n \"Record manual service recovery decision\",\n ],\n }),\n WorkflowPackFactory.create({\n key: \"team_task_triage\",\n display_name: \"Team Task Triage\",\n description:\n \"Prioritize one accountable team decision per cycle and route execution into daily tools.\",\n default_domain: \"TEAM_TASK_TRIAGE\",\n signal_source: \"team_task_workflow\",\n primary_engine: \"software\",\n intent_keywords: [\"team\", \"task\", \"priority\", \"triage\", \"backlog\"],\n required_evidence_fields: [\"workflow_name\", \"owner\", \"priority\", \"due_window\"],\n success_actions: [\n \"Create one decision issue/ticket for this cycle\",\n \"Assign owner and delivery window\",\n \"Set revisit trigger for stalled execution\",\n ],\n needs_evidence_actions: [\n \"Capture task priority rationale\",\n \"Attach dependency and due-window context\",\n \"Re-run team triage flow\",\n ],\n failed_actions: [\n \"Escalate task triage to team lead\",\n \"Pause auto-prioritization\",\n \"Record manual prioritization rationale\",\n ],\n }),\n WorkflowPackFactory.create({\n key: \"ops_customer_impact\",\n display_name: \"Ops Customer-Impact Triage\",\n description:\n \"Track and govern customer-impacting operations decisions with SLA ownership and reminder loops.\",\n default_domain: \"CUSTOMER_IMPACT_OPERATIONS\",\n signal_source: \"ops_customer_impact_workflow\",\n primary_engine: \"software\",\n intent_keywords: [\"customer-impact\", \"incident\", \"ops\", \"sla\", \"reminder\"],\n required_evidence_fields: [\"customer_impact\", \"owner\", \"sla_hours\", \"incident_channel\"],\n success_actions: [\n \"Create customer-impact decision record\",\n \"Assign owner and SLA\",\n \"Sync status updates to connected workflows\",\n ],\n needs_evidence_actions: [\n \"Capture missing customer-impact context\",\n \"Define explicit owner and SLA target\",\n \"Re-run ops customer-impact flow\",\n ],\n failed_actions: [\n \"Escalate to operations leadership\",\n \"Suspend autonomous resolution path\",\n \"Record manual mitigation decision\",\n ],\n }),\n];\n","import { affiliateRewardsVerticalPack } from \"./affiliate-rewards/AffiliateRewardsPack.js\";\nimport { coreVerticalPack } from \"./core/CorePack.js\";\nimport { devopsVerticalPack } from \"./devops/DevopsPack.js\";\nimport { financeVerticalPack } from \"./finance/FinancePack.js\";\nimport { hospitalityVerticalPack } from \"./hospitality/HospitalityPack.js\";\nimport { opsVerticalPack } from \"./ops/OpsPack.js\";\nimport { personalVerticalPack } from \"./personal/PersonalPack.js\";\nimport { salesforceVerticalPack } from \"./salesforce/SalesforcePack.js\";\nimport { sapVerticalPack } from \"./sap/SapPack.js\";\nimport { templateVerticalPack } from \"./template/TemplatePack.js\";\nimport { workdayVerticalPack } from \"./workday/WorkdayPack.js\";\nimport { workdayFinancialsVerticalPack } from \"./workday-financials/WorkdayFinancialsPack.js\";\nimport { workflowVerticalPacks } from \"./workflows/WorkflowPacks.js\";\nimport type { VerticalPack } from \"./VerticalContracts.js\";\n\nexport const DEFAULT_VERTICAL_PACK_KEY = \"core\";\n\nconst packRegistry = new Map<string, VerticalPack>([\n [coreVerticalPack.key, coreVerticalPack],\n [affiliateRewardsVerticalPack.key, affiliateRewardsVerticalPack],\n [devopsVerticalPack.key, devopsVerticalPack],\n [financeVerticalPack.key, financeVerticalPack],\n [hospitalityVerticalPack.key, hospitalityVerticalPack],\n [opsVerticalPack.key, opsVerticalPack],\n [personalVerticalPack.key, personalVerticalPack],\n [salesforceVerticalPack.key, salesforceVerticalPack],\n [sapVerticalPack.key, sapVerticalPack],\n [templateVerticalPack.key, templateVerticalPack],\n [workdayVerticalPack.key, workdayVerticalPack],\n [workdayFinancialsVerticalPack.key, workdayFinancialsVerticalPack],\n ...workflowVerticalPacks.map((pack) => [pack.key, pack] as const),\n]);\n\n/** Lookup surface over the static vertical-pack registry. */\nexport class VerticalRegistry {\n static list(): VerticalPack[] {\n return Array.from(packRegistry.values());\n }\n\n static get(key: string | null | undefined): VerticalPack | null {\n if (!key) return null;\n return packRegistry.get(key) ?? null;\n }\n\n static getForWorkflowKey(workflowKey: string | null | undefined): VerticalPack | null {\n const key = workflowKey?.trim().toLowerCase();\n if (!key) return null;\n\n const direct = VerticalRegistry.get(key);\n if (direct) return direct;\n\n for (const pack of packRegistry.values()) {\n if (!Array.isArray(pack.workflow_keys)) continue;\n if (pack.workflow_keys.some((candidate) => candidate.toLowerCase() === key)) {\n return pack;\n }\n }\n\n return null;\n }\n\n static require(key: string): VerticalPack {\n const pack = VerticalRegistry.get(key);\n if (!pack) {\n throw new Error(`Unknown vertical pack: ${key}`);\n }\n return pack;\n }\n}\n\n/** Functional alias for {@link VerticalRegistry.list}. */\nexport function listVerticalPacks(): VerticalPack[] {\n return VerticalRegistry.list();\n}\n\n/** Functional alias for {@link VerticalRegistry.get}. */\nexport function getVerticalPack(key: string | null | undefined): VerticalPack | null {\n return VerticalRegistry.get(key);\n}\n\n/** Functional alias for {@link VerticalRegistry.getForWorkflowKey}. */\nexport function getVerticalPackForWorkflowKey(\n workflowKey: string | null | undefined,\n): VerticalPack | null {\n return VerticalRegistry.getForWorkflowKey(workflowKey);\n}\n\n/** Functional alias for {@link VerticalRegistry.require}. */\nexport function requireVerticalPack(key: string): VerticalPack {\n return VerticalRegistry.require(key);\n}\n","import type { ProtocolStore } from \"../store/StoreContracts.js\";\nimport {\n DEFAULT_VERTICAL_PACK_KEY,\n getVerticalPack,\n getVerticalPackForWorkflowKey,\n requireVerticalPack,\n} from \"./VerticalRegistry.js\";\nimport type { ResolvedVerticalPack } from \"./VerticalContracts.js\";\n\n/** Resolves the effective vertical pack for an evaluate-decision request. */\nexport class VerticalResolver {\n static async resolveForRequest(input: {\n store: ProtocolStore;\n orgId: string;\n requestedPackKey?: string;\n workflowKey?: string;\n }): Promise<ResolvedVerticalPack> {\n const requested = getVerticalPack(input.requestedPackKey);\n if (requested) {\n return { pack: requested, source: \"request\" };\n }\n\n const workflowPack = getVerticalPackForWorkflowKey(input.workflowKey);\n if (workflowPack) {\n return { pack: workflowPack, source: \"workflow_key\" };\n }\n\n const configuredPackKey = await input.store.getOrgVerticalPack(input.orgId);\n const configuredPack = getVerticalPack(configuredPackKey);\n if (configuredPack) {\n return { pack: configuredPack, source: \"org_config\" };\n }\n\n const envOverrides = VerticalResolver.parseOrgPackOverrides(\n process.env.DECIONIS_PROTOCOL_VERTICAL_PACK_OVERRIDES,\n );\n const envPack = getVerticalPack(envOverrides.get(input.orgId));\n if (envPack) {\n return { pack: envPack, source: \"env_override\" };\n }\n\n return {\n pack: requireVerticalPack(DEFAULT_VERTICAL_PACK_KEY),\n source: \"default\",\n };\n }\n\n private static parseOrgPackOverrides(raw: string | undefined): Map<string, string> {\n const output = new Map<string, string>();\n const text = raw?.trim();\n if (!text) return output;\n\n for (const pair of text.split(\",\")) {\n const [orgIdRaw, packKeyRaw] = pair.split(\":\");\n const orgId = orgIdRaw?.trim();\n const packKey = packKeyRaw?.trim();\n if (!orgId || !packKey) continue;\n output.set(orgId, packKey);\n }\n return output;\n }\n}\n\n/** Functional alias for {@link VerticalResolver.resolveForRequest}. */\nexport async function resolveVerticalPackForRequest(input: {\n store: ProtocolStore;\n orgId: string;\n requestedPackKey?: string;\n workflowKey?: string;\n}): Promise<ResolvedVerticalPack> {\n return VerticalResolver.resolveForRequest(input);\n}\n","import { randomUUID } from \"node:crypto\";\nimport type { DecisionChainLinkRow, ProtocolStore } from \"../store/StoreContracts.js\";\nimport { PROTOCOL_SERVICE, PROTOCOL_VERSION } from \"../ProtocolInfo.js\";\nimport { asNumber, asRecord, asString, isLikelyUuid, parseUuidArray } from \"../support/Parsing.js\";\nimport { canonicalizeForHash, sha256Hex } from \"../support/Hashing.js\";\nimport type {\n EvaluateDecisionChainRequest,\n EvaluateDecisionChainSummary,\n EvaluateDecisionRequest,\n EvaluateDecisionResponse,\n} from \"../evaluate-decision/EvaluateDecisionContracts.js\";\n\n/** Decision-chain request parsing, lineage link building, and integrity summaries. */\nexport class DecisionChains {\n static parseDecisionChainRequest(\n input: unknown,\n ): { ok: true; value: EvaluateDecisionChainRequest | null } | { ok: false; message: string } {\n const record = asRecord(input);\n if (Object.keys(record).length === 0) return { ok: true, value: null };\n\n const chainId = asString(record.chain_id);\n if (chainId && !isLikelyUuid(chainId)) {\n return { ok: false, message: \"decision_chain.chain_id must be a UUID\" };\n }\n\n const parentEvaluationIds = parseUuidArray(\n record.parent_evaluation_ids ??\n record.previous_evaluation_ids ??\n record.parent_decision_ids ??\n record.previous_decision_ids,\n );\n const parentDossierIds = parseUuidArray(\n record.parent_dossier_ids ?? record.previous_dossier_ids,\n );\n const invalidParentEvaluation = parentEvaluationIds.find((item) => !isLikelyUuid(item));\n if (invalidParentEvaluation) {\n return {\n ok: false,\n message: \"decision_chain parent evaluation references must be UUIDs\",\n };\n }\n const invalidParentDossier = parentDossierIds.find((item) => !isLikelyUuid(item));\n if (invalidParentDossier) {\n return {\n ok: false,\n message: \"decision_chain parent dossier references must be UUIDs\",\n };\n }\n if (parentEvaluationIds.length + parentDossierIds.length > 20) {\n return { ok: false, message: \"decision_chain supports at most 20 parent references\" };\n }\n\n const sequence = asNumber(record.sequence);\n if (sequence != null && (!Number.isInteger(sequence) || sequence < 0)) {\n return { ok: false, message: \"decision_chain.sequence must be a non-negative integer\" };\n }\n\n return {\n ok: true,\n value: {\n chain_id: chainId ?? null,\n workflow_id: asString(record.workflow_id),\n step_id: asString(record.step_id),\n sequence: sequence == null ? null : Math.trunc(sequence),\n parent_evaluation_ids: parentEvaluationIds,\n parent_dossier_ids: parentDossierIds,\n metadata: asRecord(record.metadata),\n },\n };\n }\n\n static computeDecisionChainIntegrityHash(input: {\n org_id: string;\n chain_id: string;\n workflow_id: string;\n step_id: string;\n sequence: number | null;\n decision_evaluation_id: string;\n dossier_id: string;\n parent_evaluation_ids: string[];\n parent_dossier_ids: string[];\n root_evaluation_id: string;\n lineage_depth: number;\n outcome?: string;\n policy_version?: string;\n ledger_entry_hash?: string | null;\n }): string {\n return sha256Hex(JSON.stringify(canonicalizeForHash(input)));\n }\n\n static decisionChainSummaryFromRow(row: DecisionChainLinkRow): EvaluateDecisionChainSummary {\n return {\n chain_id: row.chain_id,\n workflow_id: row.workflow_id,\n step_id: row.step_id,\n sequence: row.sequence,\n root_evaluation_id: row.root_evaluation_id,\n parent_evaluation_ids: row.parent_evaluation_ids,\n parent_dossier_ids: row.parent_dossier_ids,\n lineage_depth: row.lineage_depth,\n integrity_hash: row.integrity_hash,\n chain_api_path: `/v1/protocol/decision-chains/${row.chain_id}?org_id=${encodeURIComponent(row.org_id)}`,\n };\n }\n\n static summarizeDecisionChainRows(input: {\n orgId: string;\n chainId: string;\n rows: DecisionChainLinkRow[];\n }) {\n const links = input.rows.map((row) => {\n const metadata = asRecord(row.metadata);\n const expectedIntegrityHash = computeDecisionChainIntegrityHash({\n org_id: row.org_id,\n chain_id: row.chain_id,\n workflow_id: row.workflow_id,\n step_id: row.step_id,\n sequence: row.sequence,\n decision_evaluation_id: row.decision_evaluation_id,\n dossier_id: row.dossier_id,\n parent_evaluation_ids: row.parent_evaluation_ids,\n parent_dossier_ids: row.parent_dossier_ids,\n root_evaluation_id: row.root_evaluation_id,\n lineage_depth: row.lineage_depth,\n outcome: asString(metadata.outcome) ?? undefined,\n policy_version: asString(metadata.policy_version) ?? undefined,\n ledger_entry_hash: asString(metadata.ledger_entry_hash),\n });\n return {\n id: row.id,\n chain_id: row.chain_id,\n workflow_id: row.workflow_id,\n step_id: row.step_id,\n sequence: row.sequence,\n decision_evaluation_id: row.decision_evaluation_id,\n dossier_id: row.dossier_id,\n parent_evaluation_ids: row.parent_evaluation_ids,\n parent_dossier_ids: row.parent_dossier_ids,\n root_evaluation_id: row.root_evaluation_id,\n lineage_depth: row.lineage_depth,\n integrity_hash: row.integrity_hash,\n integrity_verified: row.integrity_hash === expectedIntegrityHash,\n outcome: asString(metadata.outcome),\n policy_version: asString(metadata.policy_version),\n dossier_api_path: `/v1/protocol/dossiers/${row.dossier_id}?org_id=${encodeURIComponent(row.org_id)}`,\n created_at: row.created_at,\n };\n });\n\n return {\n service: PROTOCOL_SERVICE,\n protocol_version: PROTOCOL_VERSION,\n org_id: input.orgId,\n chain_id: input.chainId,\n workflow_id: links[0]?.workflow_id ?? null,\n root_evaluation_id: links[0]?.root_evaluation_id ?? null,\n count: links.length,\n max_lineage_depth: links.reduce((max, link) => Math.max(max, link.lineage_depth), 0),\n integrity_verified: links.every((link) => link.integrity_verified),\n links,\n };\n }\n\n static async buildDecisionChainLinkInput(input: {\n store: ProtocolStore;\n request: EvaluateDecisionRequest;\n response: Omit<EvaluateDecisionResponse, \"idempotent_replay\">;\n }): Promise<\n | {\n ok: true;\n value: Parameters<ProtocolStore[\"saveDecisionChainLink\"]>[0];\n summary: EvaluateDecisionChainSummary;\n }\n | { ok: false; message: string }\n > {\n const requested = input.request.decision_chain;\n const parentEvaluations = new Map<string, { id: string; dossier_id: string }>();\n\n for (const evaluationId of requested?.parent_evaluation_ids ?? []) {\n if (evaluationId === input.response.evaluation_id) {\n return { ok: false, message: \"decision_chain cannot reference the current evaluation\" };\n }\n const evaluation = await input.store.getDecisionEvaluation({\n orgId: input.request.org_id,\n evaluationId,\n });\n if (!evaluation) {\n return {\n ok: false,\n message: `decision_chain parent evaluation not found: ${evaluationId}`,\n };\n }\n parentEvaluations.set(evaluation.id, {\n id: evaluation.id,\n dossier_id: evaluation.dossier_id,\n });\n }\n\n for (const dossierId of requested?.parent_dossier_ids ?? []) {\n if (dossierId === input.response.dossier_id) {\n return { ok: false, message: \"decision_chain cannot reference the current dossier\" };\n }\n const dossier = await input.store.getDecisionDossier({\n orgId: input.request.org_id,\n dossierId,\n });\n if (!dossier) {\n return {\n ok: false,\n message: `decision_chain parent dossier not found: ${dossierId}`,\n };\n }\n parentEvaluations.set(dossier.decision_evaluation_id, {\n id: dossier.decision_evaluation_id,\n dossier_id: dossier.dossier_id,\n });\n }\n\n const parentEvaluationIds = Array.from(parentEvaluations.keys());\n const parentDossierIds = Array.from(\n new Set(Array.from(parentEvaluations.values()).map((evaluation) => evaluation.dossier_id)),\n );\n const parentLinks: DecisionChainLinkRow[] = [];\n for (const parentEvaluationId of parentEvaluationIds) {\n const parentLink = await input.store.getDecisionChainLinkForEvaluation({\n orgId: input.request.org_id,\n evaluationId: parentEvaluationId,\n });\n if (parentLink) parentLinks.push(parentLink);\n }\n\n const firstParentLink = parentLinks[0];\n const firstParentEvaluationId = parentEvaluationIds[0] ?? null;\n const chainId = requested?.chain_id ?? firstParentLink?.chain_id ?? randomUUID();\n const workflowId =\n requested?.workflow_id ??\n firstParentLink?.workflow_id ??\n asString(input.request.context.workflow) ??\n input.request.workflow_key ??\n input.request.decision_type;\n const stepId = requested?.step_id ?? input.request.decision_type;\n const sequence =\n requested?.sequence ??\n (parentLinks.length > 0\n ? Math.max(...parentLinks.map((link) => link.sequence ?? link.lineage_depth)) + 1\n : parentEvaluationIds.length > 0\n ? 1\n : 0);\n const lineageDepth =\n parentLinks.length > 0\n ? Math.max(...parentLinks.map((link) => link.lineage_depth)) + 1\n : parentEvaluationIds.length > 0\n ? 1\n : 0;\n const rootEvaluationId =\n firstParentLink?.root_evaluation_id ??\n firstParentEvaluationId ??\n input.response.evaluation_id;\n const metadata = {\n ...(requested?.metadata ?? {}),\n decision_type: input.request.decision_type,\n outcome: input.response.outcome,\n policy_version: input.response.policy_version,\n mode: input.response.mode,\n decision_resolution_id: input.response.decision_resolution_id,\n ledger_entry_hash: input.response.ledger_entry_hash,\n };\n const integrityHash = computeDecisionChainIntegrityHash({\n org_id: input.request.org_id,\n chain_id: chainId,\n workflow_id: workflowId,\n step_id: stepId,\n sequence,\n decision_evaluation_id: input.response.evaluation_id,\n dossier_id: input.response.dossier_id,\n parent_evaluation_ids: parentEvaluationIds,\n parent_dossier_ids: parentDossierIds,\n root_evaluation_id: rootEvaluationId,\n lineage_depth: lineageDepth,\n outcome: input.response.outcome,\n policy_version: input.response.policy_version,\n ledger_entry_hash: input.response.ledger_entry_hash,\n });\n const linkInput = {\n org_id: input.request.org_id,\n chain_id: chainId,\n workflow_id: workflowId,\n step_id: stepId,\n sequence,\n decision_evaluation_id: input.response.evaluation_id,\n dossier_id: input.response.dossier_id,\n parent_evaluation_ids: parentEvaluationIds,\n parent_dossier_ids: parentDossierIds,\n root_evaluation_id: rootEvaluationId,\n lineage_depth: lineageDepth,\n integrity_hash: integrityHash,\n metadata,\n };\n\n return {\n ok: true,\n value: linkInput,\n summary: decisionChainSummaryFromRow({\n ...linkInput,\n id: \"\",\n created_at: \"\",\n updated_at: \"\",\n }),\n };\n }\n}\n\n/** Functional alias for {@link DecisionChains.parseDecisionChainRequest}. */\nexport function parseDecisionChainRequest(\n input: unknown,\n): { ok: true; value: EvaluateDecisionChainRequest | null } | { ok: false; message: string } {\n return DecisionChains.parseDecisionChainRequest(input);\n}\n\n/** Functional alias for {@link DecisionChains.computeDecisionChainIntegrityHash}. */\nexport function computeDecisionChainIntegrityHash(input: {\n org_id: string;\n chain_id: string;\n workflow_id: string;\n step_id: string;\n sequence: number | null;\n decision_evaluation_id: string;\n dossier_id: string;\n parent_evaluation_ids: string[];\n parent_dossier_ids: string[];\n root_evaluation_id: string;\n lineage_depth: number;\n outcome?: string;\n policy_version?: string;\n ledger_entry_hash?: string | null;\n}): string {\n return DecisionChains.computeDecisionChainIntegrityHash(input);\n}\n\n/** Functional alias for {@link DecisionChains.decisionChainSummaryFromRow}. */\nexport function decisionChainSummaryFromRow(\n row: DecisionChainLinkRow,\n): EvaluateDecisionChainSummary {\n return DecisionChains.decisionChainSummaryFromRow(row);\n}\n\n/** Functional alias for {@link DecisionChains.summarizeDecisionChainRows}. */\nexport function summarizeDecisionChainRows(input: {\n orgId: string;\n chainId: string;\n rows: DecisionChainLinkRow[];\n}) {\n return DecisionChains.summarizeDecisionChainRows(input);\n}\n\n/** Functional alias for {@link DecisionChains.buildDecisionChainLinkInput}. */\nexport function buildDecisionChainLinkInput(input: {\n store: ProtocolStore;\n request: EvaluateDecisionRequest;\n response: Omit<EvaluateDecisionResponse, \"idempotent_replay\">;\n}): Promise<\n | {\n ok: true;\n value: Parameters<ProtocolStore[\"saveDecisionChainLink\"]>[0];\n summary: EvaluateDecisionChainSummary;\n }\n | { ok: false; message: string }\n> {\n return DecisionChains.buildDecisionChainLinkInput(input);\n}\n","import {\n createHash,\n createPrivateKey,\n createPublicKey,\n hkdfSync,\n sign,\n type KeyObject,\n} from \"node:crypto\";\nimport {\n DECISION_DOSSIER_JWKS_PATH,\n type DecisionDossierAsymmetricProofBundle,\n type DecisionDossierProofArtifact,\n type DecisionDossierProofArtifactKind,\n type DecisionDossierKeyRotationPolicy,\n stableJsonStringify,\n} from \"./DossierIntegrity.js\";\n\ninterface DossierSigner {\n key_id: string;\n private_key: KeyObject;\n}\n\n/** Ed25519 proof-bundle signing for decision dossiers (env-configured key material). */\nexport class DossierProofBundle {\n /**\n * The public verification key for the active dossier signer. Derived from the\n * SAME key material `resolveSigner` uses, so a proof packet can be verified\n * cryptographically without a second source of truth. Returns null when no\n * signing secret/PEM is configured (unsigned-dev mode).\n */\n static resolveDossierVerificationKey(): { key_id: string; public_key: KeyObject } | null {\n const signer = DossierProofBundle.resolveSigner();\n if (!signer) return null;\n return { key_id: signer.key_id, public_key: createPublicKey(signer.private_key) };\n }\n\n static buildDecisionDossierPersistedProofBundle(input: {\n issued_at: string;\n portable_artifact: Record<string, unknown>;\n json_ld?: Record<string, unknown> | null;\n }): DecisionDossierAsymmetricProofBundle | null {\n const signer = DossierProofBundle.resolveSigner();\n if (!signer) return null;\n\n const artifacts: DecisionDossierProofArtifact[] = [\n DossierProofBundle.signArtifact({\n signer,\n artifact_kind: \"portable_artifact\",\n media_type: \"application/json\",\n document_path: \"/portable_artifact\",\n document: input.portable_artifact,\n }),\n ];\n\n if (input.json_ld) {\n artifacts.push(\n DossierProofBundle.signArtifact({\n signer,\n artifact_kind: \"json_ld\",\n media_type: \"application/ld+json\",\n document_path: \"/linked_data/document\",\n document: input.json_ld,\n }),\n );\n }\n\n return {\n bundle_type: \"decionis.decision_dossier.proof_bundle\",\n version: \"2.0\",\n issued_at: input.issued_at,\n algorithm: \"Ed25519\",\n key_id: signer.key_id,\n rotation_policy: DossierProofBundle.resolveRotationPolicy(signer.key_id),\n artifacts,\n };\n }\n\n private static normalizePem(value: string): string {\n return value.includes(\"\\\\n\") ? value.replace(/\\\\n/g, \"\\n\") : value;\n }\n\n private static resolvePrivateKeyPem(): string | null {\n const rawPem = process.env.DECISION_DOSSIER_ASYMMETRIC_SIGNING_PRIVATE_KEY_PEM?.trim();\n if (rawPem) return DossierProofBundle.normalizePem(rawPem);\n\n const rawBase64 =\n process.env.DECISION_DOSSIER_ASYMMETRIC_SIGNING_PRIVATE_KEY_BASE64?.trim() ?? null;\n if (!rawBase64) return null;\n return Buffer.from(rawBase64, \"base64\").toString(\"utf8\");\n }\n\n private static resolveExplicitKeyId(): string | null {\n return process.env.DECISION_DOSSIER_ASYMMETRIC_SIGNING_KEY_ID?.trim() || null;\n }\n\n private static resolveDerivedSigningSecret(): string | null {\n if (process.env.DECISION_DOSSIER_ASYMMETRIC_SIGNING_DISABLE_DERIVED_DEFAULT === \"1\") {\n return null;\n }\n return (\n process.env.API_KEY_HASH_SECRET?.trim() ||\n process.env.DECIONIS_DOSSIER_VERIFICATION_SECRET?.trim() ||\n null\n );\n }\n\n private static resolvePreviousKeyIds(): string[] {\n return (process.env.DECISION_DOSSIER_ASYMMETRIC_SIGNING_PREVIOUS_KEY_IDS ?? \"\")\n .split(\",\")\n .map((value) => value.trim())\n .filter((value) => value.length > 0);\n }\n\n private static resolveVerificationGracePeriodDays(): number {\n const parsed = Number.parseInt(\n process.env.DECISION_DOSSIER_ASYMMETRIC_SIGNING_VERIFICATION_GRACE_PERIOD_DAYS ?? \"\",\n 10,\n );\n return Number.isFinite(parsed) && parsed > 0 ? parsed : 90;\n }\n\n private static resolveRotationPolicy(keyId: string): DecisionDossierKeyRotationPolicy {\n return {\n strategy: \"JWKS_OVERLAP\",\n active_key_id: keyId,\n previous_key_ids: DossierProofBundle.resolvePreviousKeyIds(),\n verification_grace_period_days: DossierProofBundle.resolveVerificationGracePeriodDays(),\n rotated_at: process.env.DECISION_DOSSIER_ASYMMETRIC_SIGNING_ROTATED_AT?.trim() ?? null,\n public_jwks_path: DECISION_DOSSIER_JWKS_PATH,\n };\n }\n\n private static derivePrivateKeyFromSharedSecret(secret: string) {\n const seedMaterial = hkdfSync(\n \"sha256\",\n Buffer.from(secret, \"utf8\"),\n Buffer.from(\"decionis.decision-dossier\", \"utf8\"),\n Buffer.from(\"ed25519.seed.v1\", \"utf8\"),\n 32,\n );\n const seed = Buffer.isBuffer(seedMaterial) ? seedMaterial : Buffer.from(seedMaterial);\n const pkcs8Prefix = Buffer.from(\"302e020100300506032b657004220420\", \"hex\");\n return createPrivateKey({\n key: Buffer.concat([pkcs8Prefix, seed]),\n format: \"der\",\n type: \"pkcs8\",\n });\n }\n\n private static buildDerivedKeyId(privateKey: ReturnType<typeof createPrivateKey>): string {\n const fingerprint = createHash(\"sha256\")\n .update(privateKey.export({ format: \"der\", type: \"pkcs8\" }))\n .digest(\"hex\")\n .slice(0, 12);\n return `decionis-dossier-derived-${fingerprint}`;\n }\n\n private static resolveSigner(): DossierSigner | null {\n const pem = DossierProofBundle.resolvePrivateKeyPem();\n try {\n if (pem) {\n const privateKey = createPrivateKey(pem);\n return {\n key_id: DossierProofBundle.resolveExplicitKeyId() || \"decionis-dossier-v1\",\n private_key: privateKey,\n };\n }\n\n const derivedSecret = DossierProofBundle.resolveDerivedSigningSecret();\n if (!derivedSecret) return null;\n const privateKey = DossierProofBundle.derivePrivateKeyFromSharedSecret(derivedSecret);\n return {\n key_id:\n DossierProofBundle.resolveExplicitKeyId() ||\n DossierProofBundle.buildDerivedKeyId(privateKey),\n private_key: privateKey,\n };\n } catch {\n return null;\n }\n }\n\n private static signArtifact(input: {\n signer: DossierSigner;\n artifact_kind: DecisionDossierProofArtifactKind;\n media_type: DecisionDossierProofArtifact[\"media_type\"];\n document_path: string;\n document: unknown;\n }): DecisionDossierProofArtifact {\n const canonicalDocument = stableJsonStringify(input.document);\n return {\n artifact_kind: input.artifact_kind,\n media_type: input.media_type,\n document_path: input.document_path,\n canonical_document_sha256: createHash(\"sha256\")\n .update(canonicalDocument, \"utf8\")\n .digest(\"hex\"),\n signature: sign(\n null,\n Buffer.from(canonicalDocument, \"utf8\"),\n input.signer.private_key,\n ).toString(\"base64url\"),\n };\n }\n}\n\n/** Functional alias for {@link DossierProofBundle.resolveDossierVerificationKey}. */\nexport function resolveDossierVerificationKey(): { key_id: string; public_key: KeyObject } | null {\n return DossierProofBundle.resolveDossierVerificationKey();\n}\n\n/** Functional alias for {@link DossierProofBundle.buildDecisionDossierPersistedProofBundle}. */\nexport function buildDecisionDossierPersistedProofBundle(input: {\n issued_at: string;\n portable_artifact: Record<string, unknown>;\n json_ld?: Record<string, unknown> | null;\n}): DecisionDossierAsymmetricProofBundle | null {\n return DossierProofBundle.buildDecisionDossierPersistedProofBundle(input);\n}\n","/** Raw-PAN (card number) detection helpers for inbound decision payloads. */\nexport class PanDetection {\n private static readonly UUID_SHAPE =\n /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\n static toDigits(value: unknown): string | null {\n if (typeof value !== \"string\" && typeof value !== \"number\") return null;\n const digits = String(value).replace(/\\D/g, \"\");\n return digits.length > 0 ? digits : null;\n }\n\n static isLuhnValid(digits: string): boolean {\n let sum = 0;\n let shouldDouble = false;\n for (let i = digits.length - 1; i >= 0; i -= 1) {\n const code = digits.charCodeAt(i) - 48;\n if (code < 0 || code > 9) return false;\n let value = code;\n if (shouldDouble) {\n value *= 2;\n if (value > 9) value -= 9;\n }\n sum += value;\n shouldDouble = !shouldDouble;\n }\n return sum % 10 === 0;\n }\n\n /**\n * Candidate card numbers inside a value: runs of digits separated only by the\n * characters a card number is actually written with (spaces and dashes).\n *\n * Splitting on everything else is the whole point. Stripping every non-digit\n * from the value instead — which this used to do — welds unrelated digits\n * together across letters and punctuation, and a UUID is the case that bites:\n * discard its letters and roughly 4% of them are a 13-to-19-digit string that\n * satisfies Luhn. Since we put UUIDs into decision context ourselves (the\n * duplicate-payment fact carries the prior dossier id), that turned a\n * legitimate duplicate-payment decision into \"raw PAN-like value detected\"\n * about one time in twenty-five.\n */\n private static panCandidates(value: unknown): string[] {\n if (typeof value === \"number\") return [String(value).replace(/[^\\d]/g, \"\")];\n if (typeof value !== \"string\") return [];\n // A canonical UUID is never a card number, whichever way its hex falls.\n if (PanDetection.UUID_SHAPE.test(value.trim())) return [];\n // The run must be delimited by something other than an alphanumeric: a card\n // number written down is bounded by whitespace or punctuation, whereas the\n // digit runs inside an identifier are welded to letters.\n const runs = value.match(/(?<![0-9A-Za-z])\\d[\\d \\-]*\\d(?![0-9A-Za-z])/g) ?? [];\n return runs.map((run) => run.replace(/[^\\d]/g, \"\")).filter((digits) => digits.length > 0);\n }\n\n static looksLikeRawPan(value: unknown): boolean {\n return PanDetection.panCandidates(value).some((digits) => {\n if (digits.length < 13 || digits.length > 19) return false;\n if (/^(\\d)\\1+$/.test(digits)) return false;\n return isLuhnValid(digits);\n });\n }\n\n static findRawPanPath(\n value: unknown,\n path: string,\n visited: Set<unknown> = new Set(),\n ): string | null {\n if (looksLikeRawPan(value)) return path;\n if (Array.isArray(value)) {\n for (let i = 0; i < value.length; i += 1) {\n const found = findRawPanPath(value[i], `${path}[${i}]`, visited);\n if (found) return found;\n }\n return null;\n }\n if (!value || typeof value !== \"object\") return null;\n if (visited.has(value)) return null;\n visited.add(value);\n for (const [key, child] of Object.entries(value as Record<string, unknown>)) {\n const found = findRawPanPath(child, `${path}.${key}`, visited);\n if (found) return found;\n }\n return null;\n }\n}\n\n/** Functional alias for {@link PanDetection.toDigits}. */\nexport function toDigits(value: unknown): string | null {\n return PanDetection.toDigits(value);\n}\n\n/** Functional alias for {@link PanDetection.isLuhnValid}. */\nexport function isLuhnValid(digits: string): boolean {\n return PanDetection.isLuhnValid(digits);\n}\n\n/** Functional alias for {@link PanDetection.looksLikeRawPan}. */\nexport function looksLikeRawPan(value: unknown): boolean {\n return PanDetection.looksLikeRawPan(value);\n}\n\n/** Functional alias for {@link PanDetection.findRawPanPath}. */\nexport function findRawPanPath(\n value: unknown,\n path: string,\n visited: Set<unknown> = new Set(),\n): string | null {\n return PanDetection.findRawPanPath(value, path, visited);\n}\n","/** Public base-URL resolution for externally addressable protocol links. */\nexport class ProtocolUrls {\n static getProtocolPublicBaseUrl(): string {\n const raw =\n process.env.DECIONIS_PROTOCOL_PUBLIC_BASE_URL?.trim() ??\n process.env.DECIONIS_PROTOCOL_BASE_URL?.trim() ??\n \"https://protocol.decionis.com\";\n return raw.replace(/\\/$/, \"\");\n }\n}\n\n/** Functional alias for {@link ProtocolUrls.getProtocolPublicBaseUrl}. */\nexport function getProtocolPublicBaseUrl(): string {\n return ProtocolUrls.getProtocolPublicBaseUrl();\n}\n","import { asNumber, asRecord, asString, isLikelyUuid, parseUuidArray } from \"../support/Parsing.js\";\nimport { findRawPanPath } from \"../support/PanDetection.js\";\nimport { toProtocolPerformanceSnapshot } from \"../support/Performance.js\";\nimport {\n toEvaluatePolicyEvaluation,\n toEvaluatePolicyGuard,\n toEvaluatePolicySnapshot,\n} from \"../policy-graph/PolicyGraph.js\";\nimport { parseDecisionChainRequest } from \"../decision-chains/DecisionChains.js\";\nimport type { ResolvedVerticalPack } from \"../verticals/VerticalContracts.js\";\nimport type {\n EvaluateDecisionMetrics,\n EvaluateDecisionMode,\n EvaluateDecisionOutcome,\n EvaluateDecisionReconciliationStatus,\n EvaluateDecisionRequest,\n EvaluateDecisionResponse,\n} from \"./EvaluateDecisionContracts.js\";\n\n/** Evaluate-decision request parsing and cached idempotent-response hydration. */\nexport class EvaluateDecisionParsing {\n static parseEvaluateMode(value: unknown): EvaluateDecisionMode {\n const raw = asString(value)?.toUpperCase();\n if (raw === \"PARALLEL\") return \"PARALLEL\";\n if (raw === \"ENFORCEMENT\") return \"ENFORCEMENT\";\n return \"SHADOW\";\n }\n\n static parseEvaluateModeStrict(value: unknown): EvaluateDecisionMode | null {\n const raw = asString(value)?.toUpperCase();\n if (raw === \"SHADOW\" || raw === \"PARALLEL\" || raw === \"ENFORCEMENT\") {\n return raw;\n }\n return null;\n }\n\n static parseEvaluateDecisionRequest(\n input: unknown,\n idempotencyHeader: string | null,\n ):\n | { ok: true; value: EvaluateDecisionRequest }\n | {\n ok: false;\n message: string;\n } {\n const record = asRecord(input);\n const orgId = asString(record.org_id);\n if (!orgId) return { ok: false, message: \"org_id is required\" };\n if (!isLikelyUuid(orgId)) return { ok: false, message: \"org_id must be a UUID\" };\n\n const decisionType = asString(record.decision_type);\n if (!decisionType) return { ok: false, message: \"decision_type is required\" };\n\n const amount = asNumber(record.amount);\n const riskScore = asNumber(record.risk_score);\n if (riskScore != null && (riskScore < 0 || riskScore > 1)) {\n return { ok: false, message: \"risk_score must be between 0 and 1\" };\n }\n\n const objectiveProfile = asString(record.objective_profile) ?? \"risk_conservative\";\n const policyVersion = asString(record.policy_version) ?? \"finance-v1\";\n const channel = asString(record.channel);\n // Product-surface label for the cross-product gate metric; bounded, never\n // rejected — an oversized label is truncated rather than failing the gate.\n const source = asString(record.source)?.slice(0, 120) ?? null;\n const decisionBand = asString(record.decision_band);\n const transactionType = asString(record.transaction_type);\n const mode = parseEvaluateMode(record.mode);\n const context = asRecord(record.context);\n const verticalPack = asString(record.vertical_pack) ?? asString(context.vertical_pack);\n const workflowKey = asString(record.workflow_key) ?? asString(context.workflow_key);\n const parsedDecisionChain = parseDecisionChainRequest(record.decision_chain);\n if (!parsedDecisionChain.ok) return parsedDecisionChain;\n\n const rawPanPath = findRawPanPath(context, \"context\");\n if (rawPanPath) {\n return {\n ok: false,\n message: `raw PAN-like value detected at ${rawPanPath}; tokenized identifiers required`,\n };\n }\n\n const idempotencyKeyFromBody = asString(record.idempotency_key);\n const idempotencyKey = idempotencyHeader ?? idempotencyKeyFromBody ?? null;\n\n return {\n ok: true,\n value: {\n org_id: orgId,\n decision_type: decisionType,\n amount,\n risk_score: riskScore,\n channel,\n source,\n policy_version: policyVersion,\n objective_profile: objectiveProfile,\n vertical_pack: verticalPack,\n workflow_key: workflowKey,\n mode,\n decision_band: decisionBand,\n transaction_type: transactionType,\n idempotency_key: idempotencyKey,\n decision_chain: parsedDecisionChain.value,\n context,\n },\n };\n }\n\n static toEvaluateMetrics(input: unknown): EvaluateDecisionMetrics {\n const record = asRecord(input);\n return {\n override_drift_rate: asNumber(record.override_drift_rate) ?? 0,\n governance_tension_index: asNumber(record.governance_tension_index) ?? 0,\n boundary_volatility_score: asNumber(record.boundary_volatility_score) ?? 0,\n decision_volume_under_governance: asNumber(record.decision_volume_under_governance) ?? 0,\n };\n }\n\n static toReconciliationStatus(\n input: unknown,\n reconciliationRequired: boolean,\n ): EvaluateDecisionReconciliationStatus {\n const raw = asString(input)?.toUpperCase();\n if (raw === \"PENDING\") return \"PENDING\";\n if (raw === \"NOT_REQUIRED\") return \"NOT_REQUIRED\";\n return reconciliationRequired ? \"PENDING\" : \"NOT_REQUIRED\";\n }\n\n static hydrateCachedEvaluateResponse(existing: {\n id: string;\n org_id: string;\n mode: string;\n outcome: string;\n confidence: number;\n policy_version: string;\n objective_profile: string;\n dossier_id: string;\n fallback_triggered: boolean;\n request_payload: Record<string, unknown>;\n response_payload: Record<string, unknown>;\n }): EvaluateDecisionResponse {\n const cached = asRecord(existing.response_payload);\n const requestPayload = asRecord(existing.request_payload);\n const mode =\n parseEvaluateModeStrict(cached.mode) ?? parseEvaluateModeStrict(existing.mode) ?? \"SHADOW\";\n const fallbackToLegacy =\n typeof cached.fallback_to_legacy === \"boolean\"\n ? cached.fallback_to_legacy\n : existing.fallback_triggered;\n const reconciliationRequired =\n typeof cached.reconciliation_required === \"boolean\"\n ? cached.reconciliation_required\n : fallbackToLegacy || existing.fallback_triggered;\n const rollout = asRecord(cached.rollout);\n\n return {\n outcome: (asString(cached.outcome) ?? existing.outcome) as EvaluateDecisionOutcome,\n confidence: asNumber(cached.confidence) ?? Number(existing.confidence),\n policy_version: asString(cached.policy_version) ?? existing.policy_version,\n objective_profile: asString(cached.objective_profile) ?? existing.objective_profile,\n dossier_id: asString(cached.dossier_id) ?? existing.dossier_id,\n dossier_sha256: asString(cached.dossier_sha256),\n evaluation_id: asString(cached.evaluation_id) ?? existing.id,\n decision_resolution_id: asString(cached.decision_resolution_id),\n ledger_entry_id: asString(cached.ledger_entry_id),\n ledger_entry_hash: asString(cached.ledger_entry_hash),\n mode,\n fallback_to_legacy: fallbackToLegacy,\n fallback_reason: asString(cached.fallback_reason),\n reconciliation_required: reconciliationRequired,\n reconciliation_status: toReconciliationStatus(\n cached.reconciliation_status,\n reconciliationRequired,\n ),\n rollout: {\n source:\n asString(rollout.source) === \"ENFORCEMENT_ROLLOUT\" ? \"ENFORCEMENT_ROLLOUT\" : \"REQUEST\",\n decision_band:\n asString(rollout.decision_band) ?? asString(requestPayload.decision_band) ?? null,\n transaction_type:\n asString(rollout.transaction_type) ?? asString(requestPayload.transaction_type) ?? null,\n configured_mode: parseEvaluateModeStrict(rollout.configured_mode),\n effective_mode: parseEvaluateModeStrict(rollout.effective_mode) ?? mode,\n feature_flag: asString(rollout.feature_flag),\n feature_flag_enabled:\n typeof rollout.feature_flag_enabled === \"boolean\" ? rollout.feature_flag_enabled : null,\n },\n governance_metrics: toEvaluateMetrics(cached.governance_metrics),\n decision_chain: (() => {\n const chain = asRecord(cached.decision_chain);\n const chainId = asString(chain.chain_id);\n const workflowId = asString(chain.workflow_id);\n const stepId = asString(chain.step_id);\n const rootEvaluationId = asString(chain.root_evaluation_id);\n const integrityHash = asString(chain.integrity_hash);\n const chainApiPath = asString(chain.chain_api_path);\n if (!chainId || !workflowId || !stepId || !rootEvaluationId || !integrityHash) {\n return undefined;\n }\n return {\n chain_id: chainId,\n workflow_id: workflowId,\n step_id: stepId,\n sequence: asNumber(chain.sequence),\n root_evaluation_id: rootEvaluationId,\n parent_evaluation_ids: parseUuidArray(chain.parent_evaluation_ids),\n parent_dossier_ids: parseUuidArray(chain.parent_dossier_ids),\n lineage_depth: asNumber(chain.lineage_depth) ?? 0,\n integrity_hash: integrityHash,\n chain_api_path:\n chainApiPath ??\n `/v1/protocol/decision-chains/${chainId}?org_id=${encodeURIComponent(existing.org_id)}`,\n };\n })(),\n policy_guard: toEvaluatePolicyGuard(cached.policy_guard),\n policy_evaluation: toEvaluatePolicyEvaluation(cached.policy_evaluation),\n policy_snapshot: toEvaluatePolicySnapshot(cached.policy_snapshot),\n vertical_pack: (() => {\n const verticalPack = asRecord(cached.vertical_pack);\n const key = asString(verticalPack.key);\n if (!key) return undefined;\n return {\n key,\n source:\n (asString(verticalPack.source) as ResolvedVerticalPack[\"source\"] | null) ?? \"default\",\n workflow_key: asString(verticalPack.workflow_key),\n };\n })(),\n decision_domain: asString(cached.decision_domain) ?? undefined,\n performance: toProtocolPerformanceSnapshot(cached.performance),\n idempotent_replay: false,\n };\n }\n}\n\n/** Functional alias for {@link EvaluateDecisionParsing.parseEvaluateMode}. */\nexport function parseEvaluateMode(value: unknown): EvaluateDecisionMode {\n return EvaluateDecisionParsing.parseEvaluateMode(value);\n}\n\n/** Functional alias for {@link EvaluateDecisionParsing.parseEvaluateModeStrict}. */\nexport function parseEvaluateModeStrict(value: unknown): EvaluateDecisionMode | null {\n return EvaluateDecisionParsing.parseEvaluateModeStrict(value);\n}\n\n/** Functional alias for {@link EvaluateDecisionParsing.parseEvaluateDecisionRequest}. */\nexport function parseEvaluateDecisionRequest(\n input: unknown,\n idempotencyHeader: string | null,\n):\n | { ok: true; value: EvaluateDecisionRequest }\n | {\n ok: false;\n message: string;\n } {\n return EvaluateDecisionParsing.parseEvaluateDecisionRequest(input, idempotencyHeader);\n}\n\n/** Functional alias for {@link EvaluateDecisionParsing.toEvaluateMetrics}. */\nexport function toEvaluateMetrics(input: unknown): EvaluateDecisionMetrics {\n return EvaluateDecisionParsing.toEvaluateMetrics(input);\n}\n\n/** Functional alias for {@link EvaluateDecisionParsing.toReconciliationStatus}. */\nexport function toReconciliationStatus(\n input: unknown,\n reconciliationRequired: boolean,\n): EvaluateDecisionReconciliationStatus {\n return EvaluateDecisionParsing.toReconciliationStatus(input, reconciliationRequired);\n}\n\n/** Functional alias for {@link EvaluateDecisionParsing.hydrateCachedEvaluateResponse}. */\nexport function hydrateCachedEvaluateResponse(existing: {\n id: string;\n org_id: string;\n mode: string;\n outcome: string;\n confidence: number;\n policy_version: string;\n objective_profile: string;\n dossier_id: string;\n fallback_triggered: boolean;\n request_payload: Record<string, unknown>;\n response_payload: Record<string, unknown>;\n}): EvaluateDecisionResponse {\n return EvaluateDecisionParsing.hydrateCachedEvaluateResponse(existing);\n}\n","import {\n asNumber,\n asRecord,\n asString,\n isLikelyUuid,\n mergeNestedRecords,\n parseOptionalBoolean,\n} from \"../support/Parsing.js\";\nimport { findRawPanPath } from \"../support/PanDetection.js\";\nimport { getProtocolPublicBaseUrl } from \"../support/ProtocolUrls.js\";\nimport { parseEvaluateMode } from \"../evaluate-decision/EvaluateDecisionParsing.js\";\nimport type {\n EvaluateDecisionMode,\n EvaluateDecisionOutcome,\n EvaluateDecisionRequest,\n EvaluateDecisionResponse,\n} from \"../evaluate-decision/EvaluateDecisionContracts.js\";\nimport type {\n WebexAgentIntentExecutionState,\n WebexAgentIntentRequest,\n WebexTrustBindingState,\n WebexTrustContext,\n} from \"./WebexContracts.js\";\n\n/** Webex agent-intent parsing, trust-context binding, and JSON-LD dossier enrichment. */\nexport class WebexGovernance {\n static parseWebexAgentIntentRequest(\n input: unknown,\n idempotencyHeader: string | null,\n ):\n | { ok: true; value: WebexAgentIntentRequest }\n | {\n ok: false;\n message: string;\n } {\n const record = asRecord(input);\n const orgId = asString(record.org_id);\n if (!orgId) return { ok: false, message: \"org_id is required\" };\n if (!isLikelyUuid(orgId)) return { ok: false, message: \"org_id must be a UUID\" };\n\n const roomId = asString(record.room_id);\n if (!roomId) return { ok: false, message: \"room_id is required\" };\n\n const intentType = asString(record.intent_type);\n if (!intentType) return { ok: false, message: \"intent_type is required\" };\n\n const proposedAction = asString(record.proposed_action);\n if (!proposedAction) return { ok: false, message: \"proposed_action is required\" };\n\n const systemOfRecord = asString(record.system_of_record);\n if (!systemOfRecord) return { ok: false, message: \"system_of_record is required\" };\n\n const amount = asNumber(record.amount);\n const riskScore = asNumber(record.risk_score);\n if (riskScore != null && (riskScore < 0 || riskScore > 1)) {\n return { ok: false, message: \"risk_score must be between 0 and 1\" };\n }\n\n const context = asRecord(record.context);\n const trustContext = mergeNestedRecords(\n asRecord(context.trust_context),\n asRecord(record.trust_context),\n [\"room\", \"operator\", \"workspace\", \"location\", \"device\"],\n );\n const rawPanPath = findRawPanPath(context, \"context\");\n if (rawPanPath) {\n return {\n ok: false,\n message: `raw PAN-like value detected at ${rawPanPath}; tokenized identifiers required`,\n };\n }\n\n const approvalPath = Array.isArray(record.approval_path)\n ? record.approval_path\n .map((item) => asString(item))\n .filter((item): item is string => Boolean(item))\n : [];\n\n const idempotencyKeyFromBody = asString(record.idempotency_key);\n const idempotencyKey = idempotencyHeader ?? idempotencyKeyFromBody ?? null;\n\n return {\n ok: true,\n value: {\n org_id: orgId,\n room_id: roomId,\n message_id: asString(record.message_id),\n person_id: asString(record.person_id),\n person_email: asString(record.person_email),\n agent_id: asString(record.agent_id),\n agent_name: asString(record.agent_name),\n workspace_id: asString(record.workspace_id),\n location_id: asString(record.location_id),\n device_id: asString(record.device_id),\n intent_type: intentType,\n proposed_action: proposedAction,\n system_of_record: systemOfRecord,\n record_type: asString(record.record_type),\n record_id: asString(record.record_id),\n amount,\n risk_score: riskScore,\n objective_profile: asString(record.objective_profile) ?? \"risk_conservative\",\n policy_version: asString(record.policy_version),\n vertical_pack: asString(record.vertical_pack) ?? asString(context.vertical_pack),\n workflow_key: asString(record.workflow_key) ?? asString(context.workflow_key),\n mode: parseEvaluateMode(record.mode),\n approval_path: approvalPath,\n idempotency_key: idempotencyKey,\n trust_context: trustContext,\n context,\n },\n };\n }\n\n static resolveWebexExecutionState(input: {\n mode: EvaluateDecisionMode;\n outcome: EvaluateDecisionOutcome;\n }): WebexAgentIntentExecutionState {\n if (input.outcome === \"REJECT\") return \"DENY\";\n if (input.mode !== \"ENFORCEMENT\") return \"HOLD\";\n if (input.outcome === \"APPROVE\") return \"ALLOW\";\n if (input.outcome === \"ESCALATE\") return \"ESCALATE\";\n return \"HOLD\";\n }\n\n static resolveWebexTrustBindingState(input: {\n attested?: boolean | null;\n verified?: boolean | null;\n declared?: boolean;\n }): WebexTrustBindingState {\n if (input.attested) return \"ATTESTED\";\n if (input.verified) return \"VERIFIED\";\n if (input.declared) return \"DECLARED\";\n return \"NOT_PROVIDED\";\n }\n\n static buildWebexTrustContext(input: EvaluateDecisionRequest): WebexTrustContext | null {\n const context = asRecord(input.context);\n const trustContext = asRecord(context.trust_context);\n const room = asRecord(trustContext.room);\n const operator = asRecord(trustContext.operator);\n const workspace = asRecord(trustContext.workspace);\n const location = asRecord(trustContext.location);\n const device = asRecord(trustContext.device);\n\n const roomId = asString(context.room_id);\n if (!roomId) return null;\n\n const personId = asString(context.person_id);\n const personEmail = asString(context.person_email);\n const operatorName =\n asString(operator.operator_name) ??\n asString(operator.name) ??\n asString(context.person_display_name) ??\n asString(context.operator_name);\n const operatorVerified =\n parseOptionalBoolean(operator.verified) ??\n parseOptionalBoolean(operator.operator_verified) ??\n parseOptionalBoolean(context.operator_verified);\n const operatorVerificationSource =\n asString(operator.verification_source) ?? asString(context.operator_verification_source);\n\n const workspaceId = asString(context.workspace_id) ?? asString(workspace.workspace_id);\n const workspaceName =\n asString(workspace.workspace_name) ??\n asString(workspace.name) ??\n asString(context.workspace_name);\n const workspaceVerified =\n parseOptionalBoolean(workspace.verified) ?? parseOptionalBoolean(context.workspace_verified);\n\n const locationId = asString(context.location_id) ?? asString(location.location_id);\n const locationName =\n asString(location.location_name) ??\n asString(location.name) ??\n asString(context.location_name);\n const locationVerified =\n parseOptionalBoolean(location.verified) ?? parseOptionalBoolean(context.location_verified);\n\n const deviceId = asString(context.device_id) ?? asString(device.device_id);\n const deviceName =\n asString(device.device_name) ?? asString(device.name) ?? asString(context.device_name);\n const devicePlatform =\n asString(device.platform) ??\n asString(device.device_platform) ??\n asString(context.device_platform);\n const deviceType =\n asString(device.device_type) ?? asString(device.type) ?? asString(context.device_type);\n const roomos =\n parseOptionalBoolean(device.roomos) ??\n parseOptionalBoolean(device.room_os) ??\n parseOptionalBoolean(device.roomos_capable) ??\n parseOptionalBoolean(context.device_roomos) ??\n devicePlatform?.trim().toUpperCase() === \"ROOMOS\";\n const deviceAttested =\n parseOptionalBoolean(device.attested) ??\n parseOptionalBoolean(device.device_attested) ??\n parseOptionalBoolean(context.device_attested);\n\n const normalized: WebexTrustContext = {\n room: {\n room_id: roomId,\n room_name: asString(room.room_name) ?? asString(room.name) ?? asString(context.room_name),\n room_type: asString(room.room_type) ?? asString(context.room_type),\n },\n operator: {\n person_id: personId,\n person_email: personEmail,\n operator_name: operatorName,\n binding_state: resolveWebexTrustBindingState({\n verified: operatorVerified,\n declared: Boolean(personId || personEmail || operatorName),\n }),\n verification_source: operatorVerificationSource,\n },\n workspace: {\n workspace_id: workspaceId,\n workspace_name: workspaceName,\n binding_state: resolveWebexTrustBindingState({\n verified: workspaceVerified,\n declared: Boolean(workspaceId || workspaceName),\n }),\n },\n location: {\n location_id: locationId,\n location_name: locationName,\n binding_state: resolveWebexTrustBindingState({\n verified: locationVerified,\n declared: Boolean(locationId || locationName),\n }),\n },\n device: {\n device_id: deviceId,\n device_name: deviceName,\n platform: devicePlatform,\n device_type: deviceType,\n roomos: Boolean(roomos),\n binding_state: resolveWebexTrustBindingState({\n attested: deviceAttested,\n declared: Boolean(deviceId || deviceName || devicePlatform || deviceType),\n }),\n },\n trust_semantics: {\n assurance_level: deviceAttested ? \"DEVICE_ATTESTED\" : \"CONTEXT_BOUND\",\n hardware_assurance: deviceAttested\n ? \"DEVICE_ATTESTED\"\n : roomos\n ? \"ROOMOS_CONTEXT\"\n : \"NOT_PROVIDED\",\n statement: deviceAttested\n ? \"Decionis bound Webex device, workspace, location, and operator evidence to this dossier and the caller supplied a device-attested signal.\"\n : \"Decionis bound Webex room, workspace, location, and operator context to this dossier. This is contextual governance evidence, not standalone hardware attestation.\",\n supported_claim_boundary: deviceAttested\n ? \"Device attestation was supplied and bound to the dossier.\"\n : \"Device/workspace/location context is bound to the dossier.\",\n },\n };\n\n return normalized;\n }\n\n static buildWebexGovernanceClaimSupport(input: WebexTrustContext): Record<string, unknown> {\n return {\n zero_trust_intercept: \"shipped\",\n decision_dossier_json_ld: \"shipped\",\n hardware_linked_auditing:\n input.device.binding_state === \"ATTESTED\"\n ? \"device_attested\"\n : input.device.roomos\n ? \"roomos_context_bound\"\n : \"not_claimed\",\n };\n }\n\n static buildWebexDecisionDossierJsonLd(input: {\n request: EvaluateDecisionRequest;\n response: Omit<EvaluateDecisionResponse, \"idempotent_replay\">;\n generated_at: string;\n trust_context: WebexTrustContext;\n }): Record<string, unknown> {\n const context = asRecord(input.request.context);\n const dossierUrl = `${getProtocolPublicBaseUrl()}/v1/protocol/dossiers/${encodeURIComponent(input.response.dossier_id)}?org_id=${encodeURIComponent(input.request.org_id)}`;\n const intentType = asString(context.intent_type) ?? input.request.decision_type;\n const proposedAction = asString(context.proposed_action);\n const systemOfRecord = asString(context.system_of_record);\n const executionState = resolveWebexExecutionState({\n mode: input.response.mode,\n outcome: input.response.outcome,\n });\n\n return {\n \"@context\": [\n \"https://schema.org\",\n {\n decionis: \"https://schema.decionis.com/ns#\",\n executionState: \"decionis:executionState\",\n policyVersion: \"decionis:policyVersion\",\n objectiveProfile: \"decionis:objectiveProfile\",\n intentType: \"decionis:intentType\",\n systemOfRecord: \"decionis:systemOfRecord\",\n approvalPath: \"decionis:approvalPath\",\n roomId: \"decionis:roomId\",\n roomName: \"decionis:roomName\",\n roomType: \"decionis:roomType\",\n workspaceId: \"decionis:workspaceId\",\n workspaceName: \"decionis:workspaceName\",\n workspaceBindingState: \"decionis:workspaceBindingState\",\n locationId: \"decionis:locationId\",\n locationName: \"decionis:locationName\",\n locationBindingState: \"decionis:locationBindingState\",\n deviceId: \"decionis:deviceId\",\n deviceName: \"decionis:deviceName\",\n devicePlatform: \"decionis:devicePlatform\",\n deviceType: \"decionis:deviceType\",\n roomOS: \"decionis:roomOS\",\n deviceBindingState: \"decionis:deviceBindingState\",\n operatorBindingState: \"decionis:operatorBindingState\",\n verificationSource: \"decionis:verificationSource\",\n trustSemantics: \"decionis:trustSemantics\",\n verticalPack: \"decionis:verticalPack\",\n workflowKey: \"decionis:workflowKey\",\n },\n ],\n \"@id\": `urn:decionis:dossier:${input.response.dossier_id}`,\n \"@type\": [\"CreativeWork\", \"decionis:DecisionDossier\", \"decionis:WebexGovernedIntentDossier\"],\n identifier: input.response.dossier_id,\n url: dossierUrl,\n dateCreated: input.generated_at,\n publisher: {\n \"@type\": \"Organization\",\n name: \"Decionis\",\n },\n about: {\n \"@type\": [\"Action\", \"decionis:WebexAgentIntent\"],\n name: proposedAction ?? intentType,\n description:\n proposedAction ?? `Governed ${intentType} for ${systemOfRecord ?? \"unknown system\"}`,\n intentType,\n systemOfRecord,\n approvalPath: asRecord(input.request.context).approval_path ?? [],\n roomId: input.trust_context.room.room_id,\n roomName: input.trust_context.room.room_name,\n roomType: input.trust_context.room.room_type,\n agent: {\n \"@type\": \"SoftwareApplication\",\n identifier: asString(context.agent_id),\n name: asString(context.agent_name),\n },\n participant: {\n \"@type\": \"Person\",\n identifier: input.trust_context.operator.person_id,\n email: input.trust_context.operator.person_email,\n name: input.trust_context.operator.operator_name,\n },\n },\n result: {\n \"@type\": \"decionis:GovernedExecutionVerdict\",\n executionState,\n outcome: input.response.outcome,\n confidence: input.response.confidence,\n policyVersion: input.response.policy_version,\n objectiveProfile: input.response.objective_profile,\n mode: input.response.mode,\n },\n instrument: {\n \"@type\": \"SoftwareApplication\",\n name: \"Decionis Protocol MCP\",\n applicationCategory: \"Governance\",\n verticalPack: input.response.vertical_pack?.key ?? null,\n workflowKey: input.response.vertical_pack?.workflow_key ?? asString(context.workflow_key),\n },\n spatialCoverage: {\n \"@type\": \"Place\",\n identifier:\n input.trust_context.location.location_id ?? input.trust_context.workspace.workspace_id,\n name:\n input.trust_context.location.location_name ??\n input.trust_context.workspace.workspace_name,\n },\n location: {\n \"@type\": \"Place\",\n locationId: input.trust_context.location.location_id,\n locationName: input.trust_context.location.location_name,\n locationBindingState: input.trust_context.location.binding_state,\n },\n workspace: {\n \"@type\": \"Place\",\n workspaceId: input.trust_context.workspace.workspace_id,\n workspaceName: input.trust_context.workspace.workspace_name,\n workspaceBindingState: input.trust_context.workspace.binding_state,\n },\n device: {\n \"@type\": \"Product\",\n deviceId: input.trust_context.device.device_id,\n deviceName: input.trust_context.device.device_name,\n devicePlatform: input.trust_context.device.platform,\n deviceType: input.trust_context.device.device_type,\n roomOS: input.trust_context.device.roomos,\n deviceBindingState: input.trust_context.device.binding_state,\n },\n operator: {\n \"@type\": \"Person\",\n identifier: input.trust_context.operator.person_id,\n email: input.trust_context.operator.person_email,\n name: input.trust_context.operator.operator_name,\n operatorBindingState: input.trust_context.operator.binding_state,\n verificationSource: input.trust_context.operator.verification_source,\n },\n trustSemantics: input.trust_context.trust_semantics,\n };\n }\n\n static buildWebexDossierEnhancements(\n input: EvaluateDecisionRequest,\n response: Omit<EvaluateDecisionResponse, \"idempotent_replay\">,\n generatedAt: string,\n ): {\n execution_state: WebexAgentIntentExecutionState;\n trust_context: WebexTrustContext;\n claim_support: Record<string, unknown>;\n json_ld: Record<string, unknown>;\n } | null {\n const context = asRecord(input.context);\n const isWebexRequest =\n input.decision_type === \"WEBEX_AGENT_INTENT_GATE\" ||\n input.channel === \"webex\" ||\n asString(context.collaboration_surface) === \"webex\" ||\n asString(context.workflow_surface) === \"webex_agentic_app\";\n if (!isWebexRequest) return null;\n\n const trustContext = buildWebexTrustContext(input);\n if (!trustContext) return null;\n\n return {\n execution_state: resolveWebexExecutionState({\n mode: response.mode,\n outcome: response.outcome,\n }),\n trust_context: trustContext,\n claim_support: buildWebexGovernanceClaimSupport(trustContext),\n json_ld: buildWebexDecisionDossierJsonLd({\n request: input,\n response,\n generated_at: generatedAt,\n trust_context: trustContext,\n }),\n };\n }\n}\n\n/** Functional alias for {@link WebexGovernance.parseWebexAgentIntentRequest}. */\nexport function parseWebexAgentIntentRequest(\n input: unknown,\n idempotencyHeader: string | null,\n):\n | { ok: true; value: WebexAgentIntentRequest }\n | {\n ok: false;\n message: string;\n } {\n return WebexGovernance.parseWebexAgentIntentRequest(input, idempotencyHeader);\n}\n\n/** Functional alias for {@link WebexGovernance.resolveWebexExecutionState}. */\nexport function resolveWebexExecutionState(input: {\n mode: EvaluateDecisionMode;\n outcome: EvaluateDecisionOutcome;\n}): WebexAgentIntentExecutionState {\n return WebexGovernance.resolveWebexExecutionState(input);\n}\n\n/** Functional alias for {@link WebexGovernance.resolveWebexTrustBindingState}. */\nexport function resolveWebexTrustBindingState(input: {\n attested?: boolean | null;\n verified?: boolean | null;\n declared?: boolean;\n}): WebexTrustBindingState {\n return WebexGovernance.resolveWebexTrustBindingState(input);\n}\n\n/** Functional alias for {@link WebexGovernance.buildWebexTrustContext}. */\nexport function buildWebexTrustContext(input: EvaluateDecisionRequest): WebexTrustContext | null {\n return WebexGovernance.buildWebexTrustContext(input);\n}\n\n/** Functional alias for {@link WebexGovernance.buildWebexGovernanceClaimSupport}. */\nexport function buildWebexGovernanceClaimSupport(\n input: WebexTrustContext,\n): Record<string, unknown> {\n return WebexGovernance.buildWebexGovernanceClaimSupport(input);\n}\n\n/** Functional alias for {@link WebexGovernance.buildWebexDecisionDossierJsonLd}. */\nexport function buildWebexDecisionDossierJsonLd(input: {\n request: EvaluateDecisionRequest;\n response: Omit<EvaluateDecisionResponse, \"idempotent_replay\">;\n generated_at: string;\n trust_context: WebexTrustContext;\n}): Record<string, unknown> {\n return WebexGovernance.buildWebexDecisionDossierJsonLd(input);\n}\n\n/** Functional alias for {@link WebexGovernance.buildWebexDossierEnhancements}. */\nexport function buildWebexDossierEnhancements(\n input: EvaluateDecisionRequest,\n response: Omit<EvaluateDecisionResponse, \"idempotent_replay\">,\n generatedAt: string,\n): {\n execution_state: WebexAgentIntentExecutionState;\n trust_context: WebexTrustContext;\n claim_support: Record<string, unknown>;\n json_ld: Record<string, unknown>;\n} | null {\n return WebexGovernance.buildWebexDossierEnhancements(input, response, generatedAt);\n}\n","import { asNumber, asRecord, asString } from \"../support/Parsing.js\";\nimport { sha256Hex } from \"../support/Hashing.js\";\nimport { buildDecisionDossierPersistedProofBundle } from \"../integrity/DossierProofBundle.js\";\nimport { buildWebexDossierEnhancements } from \"../webex/WebexGovernance.js\";\nimport type {\n EvaluateDecisionRequest,\n EvaluateDecisionResponse,\n} from \"../evaluate-decision/EvaluateDecisionContracts.js\";\n\n/** Decision Dossier assembly: portable artifact core, full payload, and content hashing. */\nexport class DossierBuilder {\n static formatConfidencePercent(confidence: number): string {\n return `${(confidence * 100).toFixed(1)}%`;\n }\n\n static resolvePortableDecisionSourceSystem(\n input: EvaluateDecisionRequest,\n webexEnhancements: ReturnType<typeof buildWebexDossierEnhancements>,\n ): string | null {\n const context = asRecord(input.context);\n return (\n asString(context.source_system) ??\n asString(context.system_of_record) ??\n (webexEnhancements ? \"webex\" : null) ??\n input.channel\n );\n }\n\n static resolvePortableDecisionEntity(input: EvaluateDecisionRequest): string | null {\n const context = asRecord(input.context);\n return (\n asString(context.entity) ??\n asString(context.object_type) ??\n asString(context.record_type) ??\n (input.decision_type === \"WEBEX_AGENT_INTENT_GATE\" ? \"WebexAgentIntent\" : null)\n );\n }\n\n static resolvePortableDecisionEntityId(input: EvaluateDecisionRequest): string | null {\n const context = asRecord(input.context);\n return asString(context.entity_id) ?? asString(context.record_id);\n }\n\n static resolvePortableDecisionAction(input: EvaluateDecisionRequest): string | null {\n const context = asRecord(input.context);\n return (\n asString(context.action) ??\n asString(context.action_name) ??\n asString(context.proposed_action) ??\n asString(context.intent_type)\n );\n }\n\n static resolvePortableSignalsEvaluated(input: EvaluateDecisionRequest): number {\n const context = asRecord(input.context);\n return (\n asNumber(context.signals_evaluated) ??\n Object.keys(context).filter(\n (key) => key !== \"workflow_key\" && key !== \"vertical_pack\" && key !== \"trust_context\",\n ).length\n );\n }\n\n static buildPortableDecisionDossierCore(input: {\n request: EvaluateDecisionRequest;\n response: Omit<EvaluateDecisionResponse, \"idempotent_replay\">;\n generated_at: string;\n evidence_hashes: string[];\n webex_enhancements: ReturnType<typeof buildWebexDossierEnhancements>;\n }): Record<string, unknown> {\n const sourceSystem = resolvePortableDecisionSourceSystem(\n input.request,\n input.webex_enhancements,\n );\n const entity = resolvePortableDecisionEntity(input.request);\n const entityId = resolvePortableDecisionEntityId(input.request);\n const action = resolvePortableDecisionAction(input.request);\n const signalsEvaluated = resolvePortableSignalsEvaluated(input.request);\n const lines = [\n `Decision: ${input.request.decision_type}`,\n `Outcome: ${input.response.outcome}`,\n `Confidence: ${formatConfidencePercent(input.response.confidence)}`,\n `Policy Version: ${input.response.policy_version}`,\n `Signals Evaluated: ${signalsEvaluated}`,\n `Timestamp: ${input.generated_at}`,\n ];\n if (input.response.policy_evaluation?.selected_rule_id) {\n lines.splice(\n 4,\n 0,\n `Policy Rule: ${input.response.policy_evaluation.selected_rule_id} (${input.response.policy_evaluation.selected_rule_action ?? \"UNKNOWN\"})`,\n );\n } else if (input.response.policy_evaluation?.resolution === \"no_matching_rule\") {\n lines.splice(4, 0, \"Policy Rule: no matching org policy rule\");\n }\n if (input.response.policy_snapshot) {\n lines.splice(\n 5,\n 0,\n `Policy Snapshot: ${input.response.policy_snapshot.policy_version} - ${input.response.policy_snapshot.policy_bundle_id ?? \"unresolved\"}`,\n );\n }\n\n return {\n artifact: {\n kind: \"Decision Dossier\",\n title: `${input.request.decision_type} Decision Dossier`,\n summary: `${input.response.outcome} at ${formatConfidencePercent(input.response.confidence)} confidence under ${input.response.policy_version}.`,\n message: \"Logs explain what systems did. Decision Dossiers explain why systems acted.\",\n },\n human_readable: {\n lines,\n markdown: lines.join(\"\\n\"),\n },\n machine_readable: {\n dossier_id: input.response.dossier_id,\n decision_type: input.request.decision_type,\n decision_domain: input.response.decision_domain ?? null,\n source_system: sourceSystem,\n entity,\n entity_id: entityId,\n action,\n outcome: input.response.outcome,\n confidence: input.response.confidence,\n confidence_percent: formatConfidencePercent(input.response.confidence),\n policy_version: input.response.policy_version,\n policy_evaluation: input.response.policy_evaluation ?? null,\n policy_snapshot: input.response.policy_snapshot ?? null,\n objective_profile: input.response.objective_profile,\n mode: input.response.mode,\n signals_evaluated: signalsEvaluated,\n evidence_hash_count: input.evidence_hashes.length,\n generated_at: input.generated_at,\n },\n };\n }\n\n static buildDecisionDossier(\n input: EvaluateDecisionRequest,\n response: Omit<EvaluateDecisionResponse, \"idempotent_replay\">,\n evidenceHashes: string[],\n generatedAt: string,\n ): Record<string, unknown> {\n const webexEnhancements = buildWebexDossierEnhancements(input, response, generatedAt);\n const portableArtifact = buildPortableDecisionDossierCore({\n request: input,\n response,\n generated_at: generatedAt,\n evidence_hashes: evidenceHashes,\n webex_enhancements: webexEnhancements,\n });\n const proofBundle = buildDecisionDossierPersistedProofBundle({\n issued_at: generatedAt,\n portable_artifact: portableArtifact,\n json_ld: webexEnhancements?.json_ld ?? null,\n });\n return {\n dossier_type: webexEnhancements\n ? \"WEBEX_AGENT_INTENT_DECISION_DOSSIER_V1\"\n : \"FINANCE_ROUTING_DECISION_DOSSIER_V1\",\n dossier_schema_version: webexEnhancements ? \"1.1.0\" : \"1.0.0\",\n dossier_id: response.dossier_id,\n generated_at: generatedAt,\n routing_decision: {\n decision_type: input.decision_type,\n decision_domain: response.decision_domain ?? null,\n decision_band: input.decision_band,\n transaction_type: input.transaction_type,\n channel: input.channel,\n outcome: response.outcome,\n confidence: response.confidence,\n policy_version: response.policy_version,\n objective_profile: response.objective_profile,\n mode: response.mode,\n fallback_to_legacy: response.fallback_to_legacy,\n fallback_reason: response.fallback_reason,\n reconciliation_required: response.reconciliation_required,\n reconciliation_status: response.reconciliation_status,\n policy_guard: response.policy_guard ?? null,\n policy_evaluation: response.policy_evaluation ?? null,\n policy_snapshot: response.policy_snapshot ?? null,\n vertical_pack: response.vertical_pack ?? null,\n decision_chain: response.decision_chain ?? null,\n },\n rollout: response.rollout,\n decision_chain: response.decision_chain ?? null,\n governance: {\n metrics: response.governance_metrics,\n fallback_to_legacy: response.fallback_to_legacy,\n fallback_reason: response.fallback_reason,\n reconciliation_required: response.reconciliation_required,\n reconciliation_status: response.reconciliation_status,\n policy_guard: response.policy_guard ?? null,\n policy_evaluation: response.policy_evaluation ?? null,\n policy_snapshot: response.policy_snapshot ?? null,\n },\n inputs_snapshot: {\n amount: input.amount,\n risk_score: input.risk_score,\n context: input.context,\n },\n evidence: {\n context_hashes: evidenceHashes,\n ...(webexEnhancements\n ? {\n trust_context_sha256: sha256Hex(JSON.stringify(webexEnhancements.trust_context)),\n }\n : {}),\n },\n portable_artifact: portableArtifact,\n ...(webexEnhancements\n ? {\n webex_governance: {\n execution_state: webexEnhancements.execution_state,\n intent: {\n room_id: asString(input.context.room_id),\n message_id: asString(input.context.message_id),\n person_id: asString(input.context.person_id),\n person_email: asString(input.context.person_email),\n agent_id: asString(input.context.agent_id),\n agent_name: asString(input.context.agent_name),\n proposed_action: asString(input.context.proposed_action),\n system_of_record: asString(input.context.system_of_record),\n record_type: asString(input.context.record_type),\n record_id: asString(input.context.record_id),\n approval_path: Array.isArray(input.context.approval_path)\n ? input.context.approval_path\n : [],\n },\n trust_context: webexEnhancements.trust_context,\n claim_support: webexEnhancements.claim_support,\n },\n linked_data: {\n format: \"application/ld+json\",\n document: webexEnhancements.json_ld,\n },\n }\n : {}),\n integrity: {\n payload_sha256: response.dossier_sha256,\n decision_resolution_id: response.decision_resolution_id,\n ledger_entry_id: response.ledger_entry_id,\n ledger_entry_hash: response.ledger_entry_hash,\n ledger_chain_verified: false,\n proof_bundle: proofBundle,\n },\n };\n }\n\n static computeDossierContentSha(dossierPayload: Record<string, unknown>): string {\n const copy: Record<string, unknown> = { ...dossierPayload };\n delete copy.integrity;\n return sha256Hex(JSON.stringify(copy));\n }\n}\n\n/** Functional alias for {@link DossierBuilder.formatConfidencePercent}. */\nexport function formatConfidencePercent(confidence: number): string {\n return DossierBuilder.formatConfidencePercent(confidence);\n}\n\n/** Functional alias for {@link DossierBuilder.resolvePortableDecisionSourceSystem}. */\nexport function resolvePortableDecisionSourceSystem(\n input: EvaluateDecisionRequest,\n webexEnhancements: ReturnType<typeof buildWebexDossierEnhancements>,\n): string | null {\n return DossierBuilder.resolvePortableDecisionSourceSystem(input, webexEnhancements);\n}\n\n/** Functional alias for {@link DossierBuilder.resolvePortableDecisionEntity}. */\nexport function resolvePortableDecisionEntity(input: EvaluateDecisionRequest): string | null {\n return DossierBuilder.resolvePortableDecisionEntity(input);\n}\n\n/** Functional alias for {@link DossierBuilder.resolvePortableDecisionEntityId}. */\nexport function resolvePortableDecisionEntityId(input: EvaluateDecisionRequest): string | null {\n return DossierBuilder.resolvePortableDecisionEntityId(input);\n}\n\n/** Functional alias for {@link DossierBuilder.resolvePortableDecisionAction}. */\nexport function resolvePortableDecisionAction(input: EvaluateDecisionRequest): string | null {\n return DossierBuilder.resolvePortableDecisionAction(input);\n}\n\n/** Functional alias for {@link DossierBuilder.resolvePortableSignalsEvaluated}. */\nexport function resolvePortableSignalsEvaluated(input: EvaluateDecisionRequest): number {\n return DossierBuilder.resolvePortableSignalsEvaluated(input);\n}\n\n/** Functional alias for {@link DossierBuilder.buildPortableDecisionDossierCore}. */\nexport function buildPortableDecisionDossierCore(input: {\n request: EvaluateDecisionRequest;\n response: Omit<EvaluateDecisionResponse, \"idempotent_replay\">;\n generated_at: string;\n evidence_hashes: string[];\n webex_enhancements: ReturnType<typeof buildWebexDossierEnhancements>;\n}): Record<string, unknown> {\n return DossierBuilder.buildPortableDecisionDossierCore(input);\n}\n\n/** Functional alias for {@link DossierBuilder.buildDecisionDossier}. */\nexport function buildDecisionDossier(\n input: EvaluateDecisionRequest,\n response: Omit<EvaluateDecisionResponse, \"idempotent_replay\">,\n evidenceHashes: string[],\n generatedAt: string,\n): Record<string, unknown> {\n return DossierBuilder.buildDecisionDossier(input, response, evidenceHashes, generatedAt);\n}\n\n/** Functional alias for {@link DossierBuilder.computeDossierContentSha}. */\nexport function computeDossierContentSha(dossierPayload: Record<string, unknown>): string {\n return DossierBuilder.computeDossierContentSha(dossierPayload);\n}\n","import type {\n EvaluateDecisionMode,\n EvaluateDecisionRequest,\n} from \"../evaluate-decision/EvaluateDecisionContracts.js\";\nimport {\n evaluateDecisionPolicyGraph,\n resolveEvaluateDecisionOutcomeFromPolicyEvaluation,\n} from \"../policy-graph/PolicyGraph.js\";\nimport type { PolicyBundleArtifactRow, ProtocolStore } from \"../store/StoreContracts.js\";\nimport { sha256StableJson } from \"../support/Hashing.js\";\n\n/**\n * Reproducing a decision can land in one of three states:\n * - `reproduced` — the recorded policy bundle was retrievable, its rules hash\n * matched the dossier's recorded digest, and re-running the deterministic\n * engine yielded the SAME outcome. The determinism claim holds.\n * - `mismatch` — same bundle (hash matched), but re-running produced a\n * DIFFERENT outcome. This is a genuine integrity red flag.\n * - `indeterminate`— we could not faithfully re-run: the versioned bundle is no\n * longer retained, its rules hash no longer matches (policy mutated), or the\n * dossier lacks the inputs needed to rebuild the request. Never reported as a\n * failure of the decision — only as \"cannot prove either way\".\n */\nexport type ReproduceDecisionStatus = \"reproduced\" | \"mismatch\" | \"indeterminate\";\n\nexport interface ReproduceDecisionResult {\n status: ReproduceDecisionStatus;\n recorded_outcome: string | null;\n reproduced_outcome: string | null;\n outcome_matches: boolean;\n policy_version: string | null;\n decision_domain: string | null;\n evaluated_at: string | null;\n rules_sha256_recorded: string | null;\n rules_sha256_recomputed: string | null;\n rules_sha256_match: boolean;\n parameters_sha256_recorded: string | null;\n parameters_sha256_recomputed: string | null;\n parameters_sha256_match: boolean;\n detail: string;\n}\n\nfunction asRecord(value: unknown): Record<string, unknown> {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return {};\n return value as Record<string, unknown>;\n}\n\nfunction asString(value: unknown): string | null {\n return typeof value === \"string\" && value.trim().length > 0 ? value : null;\n}\n\nfunction asNumberOrNull(value: unknown): number | null {\n return typeof value === \"number\" && Number.isFinite(value) ? value : null;\n}\n\nfunction resolvePolicySnapshot(payload: Record<string, unknown>): Record<string, unknown> {\n const routing = asRecord(payload.routing_decision);\n const fromRouting = asRecord(routing.policy_snapshot);\n if (Object.keys(fromRouting).length > 0) return fromRouting;\n return asRecord(asRecord(payload.governance).policy_snapshot);\n}\n\n/**\n * Rebuild the exact request the deterministic engine saw, from the fields the\n * dossier persists. The dossier is built from the *effective* request, so\n * `inputs_snapshot.context` already carries the injected vertical_pack /\n * workflow_key, and `routing_decision` carries the remaining top-level inputs\n * the engine reads for rule matching.\n */\nfunction reconstructRequest(input: {\n org_id: string;\n payload: Record<string, unknown>;\n policySnapshot: Record<string, unknown>;\n}): EvaluateDecisionRequest {\n const routing = asRecord(input.payload.routing_decision);\n const inputs = asRecord(input.payload.inputs_snapshot);\n const context = asRecord(inputs.context);\n const policyVersion =\n asString(input.policySnapshot.policy_version) ?? asString(routing.policy_version) ?? \"\";\n\n return {\n org_id: input.org_id,\n decision_type: asString(routing.decision_type) ?? \"\",\n amount: asNumberOrNull(inputs.amount),\n risk_score: asNumberOrNull(inputs.risk_score),\n channel: asString(routing.channel),\n source: asString(routing.source),\n policy_version: policyVersion,\n objective_profile: asString(routing.objective_profile) ?? \"\",\n vertical_pack: asString(routing.vertical_pack) ?? asString(context.vertical_pack),\n workflow_key: asString(context.workflow_key),\n mode: (asString(routing.mode) as EvaluateDecisionMode | null) ?? \"ENFORCEMENT\",\n decision_band: asString(routing.decision_band),\n transaction_type: asString(routing.transaction_type),\n idempotency_key: null,\n decision_chain: null,\n context,\n };\n}\n\nfunction findRecordedBundle(input: {\n bundles: PolicyBundleArtifactRow[];\n policyVersion: string | null;\n policyBundleId: string | null;\n}): PolicyBundleArtifactRow | null {\n const { bundles, policyVersion, policyBundleId } = input;\n if (policyBundleId) {\n const byId = bundles.find((bundle) => bundle.bundle_id === policyBundleId);\n if (byId) return byId;\n }\n if (policyVersion) {\n const byVersion = bundles.find((bundle) => bundle.version === policyVersion);\n if (byVersion) return byVersion;\n }\n return null;\n}\n\nfunction indeterminate(\n base: Omit<\n ReproduceDecisionResult,\n \"status\" | \"reproduced_outcome\" | \"outcome_matches\" | \"detail\"\n >,\n detail: string,\n): ReproduceDecisionResult {\n return {\n ...base,\n status: \"indeterminate\",\n reproduced_outcome: null,\n outcome_matches: false,\n detail,\n };\n}\n\n/**\n * Deterministically re-run a recorded decision from its dossier and report\n * whether the same policy, applied to the same inputs, yields the same outcome.\n * Reproduces ONLY against the exact recorded bundle (matched by id/version and\n * verified by rules hash); anything less returns `indeterminate` rather than a\n * misleading pass/fail.\n */\nexport async function reproduceDecisionFromDossierPayload(input: {\n store: Pick<ProtocolStore, \"listPolicyBundles\">;\n org_id: string;\n dossier_payload: Record<string, unknown>;\n bundle_list_limit?: number;\n}): Promise<ReproduceDecisionResult> {\n const payload = asRecord(input.dossier_payload);\n const routing = asRecord(payload.routing_decision);\n const policySnapshot = resolvePolicySnapshot(payload);\n\n const recordedOutcome = asString(routing.outcome);\n const policyVersion = asString(policySnapshot.policy_version) ?? asString(routing.policy_version);\n const policyBundleId = asString(policySnapshot.policy_bundle_id);\n const decisionDomain = asString(routing.decision_domain);\n const evaluatedAt =\n asString(policySnapshot.evaluated_at) ??\n asString(asRecord(routing.policy_evaluation).evaluated_at) ??\n asString(payload.generated_at);\n const rulesShaRecorded = asString(policySnapshot.rules_sha256);\n const parametersShaRecorded = asString(policySnapshot.parameters_sha256);\n\n const base = {\n recorded_outcome: recordedOutcome,\n policy_version: policyVersion,\n decision_domain: decisionDomain,\n evaluated_at: evaluatedAt,\n rules_sha256_recorded: rulesShaRecorded,\n rules_sha256_recomputed: null as string | null,\n rules_sha256_match: false,\n parameters_sha256_recorded: parametersShaRecorded,\n parameters_sha256_recomputed: null as string | null,\n parameters_sha256_match: false,\n };\n\n if (!policyVersion || !evaluatedAt) {\n return indeterminate(\n base,\n \"The dossier does not record the policy version and evaluation time needed to reproduce it.\",\n );\n }\n\n const bundles = await input.store.listPolicyBundles({\n orgId: input.org_id,\n limit: input.bundle_list_limit ?? 200,\n });\n const bundle = findRecordedBundle({ bundles, policyVersion, policyBundleId });\n if (!bundle) {\n return indeterminate(\n base,\n `The policy bundle for version ${policyVersion} is no longer retained, so this decision cannot be re-run against its original policy.`,\n );\n }\n\n const rulesShaRecomputed = sha256StableJson(bundle.rules);\n const parametersShaRecomputed = sha256StableJson(bundle.payload);\n const rulesMatch = rulesShaRecorded ? rulesShaRecomputed === rulesShaRecorded : false;\n const parametersMatch = parametersShaRecorded\n ? parametersShaRecomputed === parametersShaRecorded\n : false;\n const enriched = {\n ...base,\n rules_sha256_recomputed: rulesShaRecomputed,\n rules_sha256_match: rulesMatch,\n parameters_sha256_recomputed: parametersShaRecomputed,\n parameters_sha256_match: parametersMatch,\n };\n\n // Refuse to reproduce against a bundle whose rules no longer hash to the\n // recorded digest — that is a different policy, and a \"match\" would be a lie.\n if (rulesShaRecorded && !rulesMatch) {\n return indeterminate(\n enriched,\n \"The retained policy bundle's rules no longer match the digest recorded in this dossier; the policy has changed since the decision.\",\n );\n }\n\n const request = reconstructRequest({ org_id: input.org_id, payload, policySnapshot });\n const evaluation = evaluateDecisionPolicyGraph({\n bundle,\n request,\n decision_domain: decisionDomain ?? \"\",\n evaluated_at: evaluatedAt,\n });\n const reproducedOutcome = resolveEvaluateDecisionOutcomeFromPolicyEvaluation(evaluation);\n const outcomeMatches = recordedOutcome !== null && reproducedOutcome === recordedOutcome;\n\n return {\n ...enriched,\n status: outcomeMatches ? \"reproduced\" : \"mismatch\",\n reproduced_outcome: reproducedOutcome,\n outcome_matches: outcomeMatches,\n detail: outcomeMatches\n ? \"Re-running the recorded inputs through the recorded policy bundle produced the same outcome.\"\n : \"Re-running the recorded inputs through the recorded policy bundle produced a different outcome.\",\n };\n}\n","/** Env-driven feature-flag resolution for enforcement rollouts. */\nexport class FeatureFlags {\n static parseFeatureFlagAllowlist(raw: string | undefined): Set<string> {\n return new Set(\n (raw ?? \"\")\n .split(\",\")\n .map((item) => item.trim().toLowerCase())\n .filter(Boolean),\n );\n }\n\n static resolveFeatureFlagState(flag: string | null): boolean | null {\n if (!flag) return null;\n const normalized = flag.trim().toLowerCase();\n if (!normalized) return null;\n\n const allowlist = parseFeatureFlagAllowlist(process.env.DECIONIS_PROTOCOL_FEATURE_FLAGS);\n if (allowlist.has(\"*\") || allowlist.has(normalized)) return true;\n\n const envKey = `DECIONIS_PROTOCOL_FLAG_${normalized.replace(/[^a-z0-9]+/gi, \"_\").toUpperCase()}`;\n const raw = process.env[envKey];\n if (!raw) return false;\n const enabledValue = raw.trim().toLowerCase();\n return [\"1\", \"true\", \"yes\", \"on\", \"enabled\"].includes(enabledValue);\n }\n}\n\n/** Functional alias for {@link FeatureFlags.parseFeatureFlagAllowlist}. */\nexport function parseFeatureFlagAllowlist(raw: string | undefined): Set<string> {\n return FeatureFlags.parseFeatureFlagAllowlist(raw);\n}\n\n/** Functional alias for {@link FeatureFlags.resolveFeatureFlagState}. */\nexport function resolveFeatureFlagState(flag: string | null): boolean | null {\n return FeatureFlags.resolveFeatureFlagState(flag);\n}\n","import type { ProtocolStore } from \"../store/StoreContracts.js\";\nimport { asNumber, clamp } from \"../support/Parsing.js\";\nimport { resolveFeatureFlagState } from \"../support/FeatureFlags.js\";\nimport type {\n EvaluateDecisionMetrics,\n EvaluateDecisionMode,\n EvaluateDecisionOutcome,\n EvaluateDecisionRequest,\n ResolvedEvaluateRolloutPolicy,\n} from \"./EvaluateDecisionContracts.js\";\n\n/** Governance-metric derivation and enforcement-rollout mode resolution. */\nexport class EvaluateDecisionGovernance {\n static toNonNegativeNumber(value: unknown, fallback: number): number {\n const parsed = asNumber(value);\n if (parsed == null || parsed < 0) return fallback;\n return parsed;\n }\n\n static buildGovernanceMetrics(\n input: EvaluateDecisionRequest,\n outcome: EvaluateDecisionOutcome,\n ): EvaluateDecisionMetrics {\n const risk = input.risk_score ?? 0.55;\n const amount = Math.max(0, input.amount ?? 0);\n const boundaryEvents = toNonNegativeNumber(input.context.boundary_events, 0);\n const volume = Math.max(1, Math.round(toNonNegativeNumber(input.context.decision_volume, 1)));\n\n const overrideDriftRate = Number.parseFloat(\n clamp(risk * 0.42 + (outcome === \"ESCALATE\" ? 0.22 : 0.08), 0, 1).toFixed(4),\n );\n const governanceTensionIndex = Number.parseFloat(\n clamp((amount >= 100_000 ? 0.42 : amount >= 25_000 ? 0.24 : 0.1) + risk * 0.35, 0, 1).toFixed(\n 4,\n ),\n );\n const boundaryVolatilityScore = Number.parseFloat(\n clamp(boundaryEvents * 0.05 + (outcome === \"REVIEW\" ? 0.24 : 0.11), 0, 1).toFixed(4),\n );\n\n return {\n override_drift_rate: overrideDriftRate,\n governance_tension_index: governanceTensionIndex,\n boundary_volatility_score: boundaryVolatilityScore,\n decision_volume_under_governance: volume,\n };\n }\n\n static async resolveEvaluateRolloutPolicy(\n store: ProtocolStore,\n input: EvaluateDecisionRequest,\n ): Promise<ResolvedEvaluateRolloutPolicy> {\n if (!input.decision_band || !input.transaction_type) {\n return {\n source: \"REQUEST\",\n configured_mode: null,\n effective_mode: input.mode,\n feature_flag: null,\n feature_flag_enabled: null,\n fallback_to_legacy_allowed: true,\n reconciliation_required_default: true,\n };\n }\n\n const rollout = await store.getEnforcementRollout({\n orgId: input.org_id,\n decisionBand: input.decision_band,\n transactionType: input.transaction_type,\n });\n\n if (!rollout) {\n return {\n source: \"REQUEST\",\n configured_mode: null,\n effective_mode: input.mode,\n feature_flag: null,\n feature_flag_enabled: null,\n fallback_to_legacy_allowed: true,\n reconciliation_required_default: true,\n };\n }\n\n const featureFlagEnabled = resolveFeatureFlagState(rollout.feature_flag);\n const configuredMode = rollout.mode as EvaluateDecisionMode;\n const effectiveMode = featureFlagEnabled === false ? \"SHADOW\" : configuredMode;\n\n return {\n source: \"ENFORCEMENT_ROLLOUT\",\n configured_mode: configuredMode,\n effective_mode: effectiveMode,\n feature_flag: rollout.feature_flag,\n feature_flag_enabled: featureFlagEnabled,\n fallback_to_legacy_allowed: rollout.fallback_to_legacy,\n reconciliation_required_default: rollout.reconciliation_required,\n };\n }\n}\n\n/** Functional alias for {@link EvaluateDecisionGovernance.toNonNegativeNumber}. */\nexport function toNonNegativeNumber(value: unknown, fallback: number): number {\n return EvaluateDecisionGovernance.toNonNegativeNumber(value, fallback);\n}\n\n/** Functional alias for {@link EvaluateDecisionGovernance.buildGovernanceMetrics}. */\nexport function buildGovernanceMetrics(\n input: EvaluateDecisionRequest,\n outcome: EvaluateDecisionOutcome,\n): EvaluateDecisionMetrics {\n return EvaluateDecisionGovernance.buildGovernanceMetrics(input, outcome);\n}\n\n/** Functional alias for {@link EvaluateDecisionGovernance.resolveEvaluateRolloutPolicy}. */\nexport function resolveEvaluateRolloutPolicy(\n store: ProtocolStore,\n input: EvaluateDecisionRequest,\n): Promise<ResolvedEvaluateRolloutPolicy> {\n return EvaluateDecisionGovernance.resolveEvaluateRolloutPolicy(store, input);\n}\n","import { createHash, randomUUID } from \"node:crypto\";\nimport {\n ProtocolStoreValidationError,\n type ProtocolPayload,\n type ProtocolStore,\n} from \"../store/StoreContracts.js\";\nimport { validateProtocolArtifact } from \"../validation/ProtocolArtifacts.js\";\nimport { computeLedgerEntryHash } from \"../ledger/LedgerChain.js\";\nimport { PROTOCOL_SERVICE, PROTOCOL_VERSION } from \"../ProtocolInfo.js\";\nimport { asString } from \"../support/Parsing.js\";\nimport type { ResolvedVerticalPack, VerticalPack } from \"../verticals/VerticalContracts.js\";\nimport type {\n EvaluateDecisionMode,\n EvaluateDecisionOutcome,\n EvaluateDecisionRequest,\n EvaluateDecisionResponse,\n} from \"./EvaluateDecisionContracts.js\";\n\nconst POLICY_BUNDLE_UNRESOLVED_SENTINEL_ID = \"00000000-0000-0000-0000-000000000000\";\n\n/** Decision-resolution artifact building and evaluate-decision ledger chaining. */\nexport class EvaluateDecisionResolution {\n static evaluateOutcomeToDecisionStatus(\n outcome: EvaluateDecisionOutcome,\n ): \"PROPOSED\" | \"APPROVED\" | \"REJECTED\" | \"ESCALATED\" {\n if (outcome === \"APPROVE\") return \"APPROVED\";\n if (outcome === \"ESCALATE\") return \"ESCALATED\";\n if (outcome === \"REJECT\") return \"REJECTED\";\n return \"PROPOSED\";\n }\n\n static riskScoreToRiskLevel(score: number | null): \"low\" | \"medium\" | \"high\" | \"critical\" {\n if (score == null) return \"medium\";\n if (score >= 0.9) return \"critical\";\n if (score >= 0.75) return \"high\";\n if (score >= 0.4) return \"medium\";\n return \"low\";\n }\n\n static resolveDecisionDomain(pack: VerticalPack, engineKey: string, intentLower: string): string {\n const engineDomain = pack.resolver_overrides.domain_by_engine[engineKey];\n if (engineDomain) return engineDomain;\n\n for (const hint of pack.resolver_overrides.intent_domain_hints) {\n if (hint.keywords.some((keyword) => intentLower.includes(keyword.toLowerCase()))) {\n return hint.domain;\n }\n }\n\n return pack.default_domain;\n }\n\n static resolveEvaluateDecisionDomain(input: {\n pack: VerticalPack;\n request: EvaluateDecisionRequest;\n }): string {\n const text = [\n input.request.decision_type,\n input.request.decision_band ?? \"\",\n input.request.transaction_type ?? \"\",\n asString(input.request.context.workflow_key) ?? \"\",\n asString(input.request.context.workflow_vertical) ?? \"\",\n ]\n .join(\" \")\n .toLowerCase();\n return resolveDecisionDomain(input.pack, \"finance\", text);\n }\n\n static buildEvaluateDecisionResolution(input: {\n request: EvaluateDecisionRequest;\n decision_domain: string;\n vertical_pack: ResolvedVerticalPack;\n response: Omit<EvaluateDecisionResponse, \"idempotent_replay\">;\n dossierSha256: string;\n occurred_at: string;\n }): { resolutionId: string; payload: ProtocolPayload } {\n const resolutionId = randomUUID();\n const status = evaluateOutcomeToDecisionStatus(input.response.outcome);\n const selectedRuleId = input.response.policy_evaluation?.selected_rule_id ?? null;\n const selectedRuleAction = input.response.policy_evaluation?.selected_rule_action ?? null;\n const recommendedAction =\n input.response.outcome === \"APPROVE\"\n ? \"Execute decision under active policy controls.\"\n : input.response.outcome === \"ESCALATE\"\n ? \"Escalate decision to designated approval path.\"\n : input.response.outcome === \"REJECT\"\n ? \"Block decision and request corrected evidence.\"\n : \"Hold decision for additional review evidence.\";\n const rationale =\n input.response.policy_evaluation?.resolution === \"matched_rule\" && selectedRuleId\n ? `Routing decision evaluated under org policy ${input.response.policy_version} using rule ${selectedRuleId} (${selectedRuleAction ?? \"UNKNOWN\"}).`\n : input.response.policy_evaluation?.resolution === \"no_matching_rule\"\n ? `Routing decision held because no org policy rule matched under ${input.response.policy_version}.`\n : `Routing decision blocked until an active org policy bundle is available.`;\n\n const payload: ProtocolPayload = {\n protocol_version: PROTOCOL_VERSION,\n resolution_id: resolutionId,\n org_id: input.request.org_id,\n cycle_id: input.response.dossier_id,\n decision_domain: input.decision_domain,\n status,\n confidence: input.response.confidence,\n risk_level: riskScoreToRiskLevel(input.request.risk_score),\n rationale,\n decided_at: input.occurred_at,\n inputs: {\n context_snapshot_id: randomUUID(),\n policy_bundle_id:\n input.response.policy_snapshot?.policy_bundle_id ??\n input.response.policy_evaluation?.bundle_id ??\n POLICY_BUNDLE_UNRESOLVED_SENTINEL_ID,\n signal_ids: [\n `decision_type:${input.request.decision_type}`,\n `decision_band:${input.request.decision_band ?? \"UNSPECIFIED\"}`,\n `transaction_type:${input.request.transaction_type ?? \"UNSPECIFIED\"}`,\n ],\n },\n outputs: {\n recommended_action: recommendedAction,\n tags: [\n `vertical_pack:${input.vertical_pack.pack.key}`,\n `vertical_pack_source:${input.vertical_pack.source}`,\n `workflow_key:${input.request.workflow_key ?? \"none\"}`,\n `mode:${input.response.mode}`,\n `outcome:${input.response.outcome}`,\n `policy_bundle:${input.response.policy_snapshot?.policy_version ?? input.response.policy_evaluation?.bundle_version ?? input.response.policy_version}`,\n `policy_snapshot:${input.response.policy_snapshot?.rules_sha256 ?? \"unresolved\"}`,\n `policy_rule:${selectedRuleId ?? \"none\"}`,\n `dossier_sha256:${input.dossierSha256}`,\n ],\n artifacts: [`dossier:${input.response.dossier_id}`],\n },\n trace: {\n trigger_id: input.response.dossier_id,\n resolver_version: \"org-policy-decision-graph-v1\",\n deterministic_seed: createHash(\"sha256\")\n .update(\n `${input.response.dossier_id}:${input.response.outcome}:${input.response.mode}`,\n \"utf8\",\n )\n .digest(\"hex\")\n .slice(0, 16),\n },\n compliance: {\n checks: [\n {\n name: \"dossier_present\",\n result: \"PASS\",\n details: input.response.dossier_id,\n },\n {\n name: \"routing_scope_defined\",\n result:\n input.request.decision_band && input.request.transaction_type ? \"PASS\" : \"WAIVED\",\n details: `decision_band=${input.request.decision_band ?? \"none\"}; transaction_type=${input.request.transaction_type ?? \"none\"}`,\n },\n {\n name: \"org_policy_graph_evaluated\",\n result:\n input.response.policy_evaluation &&\n input.response.policy_evaluation.resolution !== \"policy_guard_blocked\"\n ? \"PASS\"\n : \"WAIVED\",\n details:\n input.response.policy_evaluation?.selected_rule_id ??\n input.response.policy_evaluation?.resolution ??\n \"policy_guard_blocked\",\n },\n ],\n },\n };\n\n return { resolutionId, payload };\n }\n\n static async appendEvaluateDecisionLedgerEvent(\n store: ProtocolStore,\n input: {\n org_id: string;\n dossier_id: string;\n decision_resolution_id: string;\n occurred_at: string;\n outcome: EvaluateDecisionOutcome;\n mode: EvaluateDecisionMode;\n dossier_sha256: string;\n },\n ): Promise<{ ledger_entry_id: string; ledger_entry_hash: string }> {\n const previousHead = await store.getLatestAuditLedgerHead(input.org_id);\n const ledgerEntryId = randomUUID();\n const entryHash = computeLedgerEntryHash({\n ledger_entry_id: ledgerEntryId,\n org_id: input.org_id,\n event_type: \"DECISION_RESOLVED\",\n occurred_at: input.occurred_at,\n action: \"protocol.evaluate.resolved\",\n actor: {\n type: \"SYSTEM\",\n id: PROTOCOL_SERVICE,\n },\n object: {\n type: \"DECISION\",\n id: input.dossier_id,\n },\n links: {\n decision_resolution_id: input.decision_resolution_id,\n },\n payload: {\n dossier_id: input.dossier_id,\n outcome: input.outcome,\n mode: input.mode,\n dossier_sha256: input.dossier_sha256,\n },\n prev_hash: previousHead?.entry_hash ?? null,\n });\n\n const ledgerPayload: ProtocolPayload = {\n protocol_version: PROTOCOL_VERSION,\n ledger_entry_id: ledgerEntryId,\n org_id: input.org_id,\n event_type: \"DECISION_RESOLVED\",\n occurred_at: input.occurred_at,\n actor: {\n type: \"SYSTEM\",\n id: PROTOCOL_SERVICE,\n },\n object: {\n type: \"DECISION\",\n id: input.dossier_id,\n },\n action: \"protocol.evaluate.resolved\",\n payload: {\n dossier_id: input.dossier_id,\n outcome: input.outcome,\n mode: input.mode,\n dossier_sha256: input.dossier_sha256,\n },\n links: {\n decision_resolution_id: input.decision_resolution_id,\n },\n chain: {\n prev_hash: previousHead?.entry_hash ?? undefined,\n entry_hash: entryHash,\n algorithm: \"SHA256\",\n },\n integrity: {\n verified: false,\n },\n };\n\n const validation = validateProtocolArtifact(\"audit_ledger_entry\", ledgerPayload);\n if (!validation.ok) {\n throw new ProtocolStoreValidationError(\n \"Invalid evaluate decision ledger payload\",\n validation.issues,\n );\n }\n await store.saveArtifact(\"audit_ledger_entry\", validation.value);\n return { ledger_entry_id: ledgerEntryId, ledger_entry_hash: entryHash };\n }\n}\n\n/** Functional alias for {@link EvaluateDecisionResolution.evaluateOutcomeToDecisionStatus}. */\nexport function evaluateOutcomeToDecisionStatus(\n outcome: EvaluateDecisionOutcome,\n): \"PROPOSED\" | \"APPROVED\" | \"REJECTED\" | \"ESCALATED\" {\n return EvaluateDecisionResolution.evaluateOutcomeToDecisionStatus(outcome);\n}\n\n/** Functional alias for {@link EvaluateDecisionResolution.riskScoreToRiskLevel}. */\nexport function riskScoreToRiskLevel(score: number | null): \"low\" | \"medium\" | \"high\" | \"critical\" {\n return EvaluateDecisionResolution.riskScoreToRiskLevel(score);\n}\n\n/** Functional alias for {@link EvaluateDecisionResolution.resolveDecisionDomain}. */\nexport function resolveDecisionDomain(\n pack: VerticalPack,\n engineKey: string,\n intentLower: string,\n): string {\n return EvaluateDecisionResolution.resolveDecisionDomain(pack, engineKey, intentLower);\n}\n\n/** Functional alias for {@link EvaluateDecisionResolution.resolveEvaluateDecisionDomain}. */\nexport function resolveEvaluateDecisionDomain(input: {\n pack: VerticalPack;\n request: EvaluateDecisionRequest;\n}): string {\n return EvaluateDecisionResolution.resolveEvaluateDecisionDomain(input);\n}\n\n/** Functional alias for {@link EvaluateDecisionResolution.buildEvaluateDecisionResolution}. */\nexport function buildEvaluateDecisionResolution(input: {\n request: EvaluateDecisionRequest;\n decision_domain: string;\n vertical_pack: ResolvedVerticalPack;\n response: Omit<EvaluateDecisionResponse, \"idempotent_replay\">;\n dossierSha256: string;\n occurred_at: string;\n}): { resolutionId: string; payload: ProtocolPayload } {\n return EvaluateDecisionResolution.buildEvaluateDecisionResolution(input);\n}\n\n/** Functional alias for {@link EvaluateDecisionResolution.appendEvaluateDecisionLedgerEvent}. */\nexport function appendEvaluateDecisionLedgerEvent(\n store: ProtocolStore,\n input: {\n org_id: string;\n dossier_id: string;\n decision_resolution_id: string;\n occurred_at: string;\n outcome: EvaluateDecisionOutcome;\n mode: EvaluateDecisionMode;\n dossier_sha256: string;\n },\n): Promise<{ ledger_entry_id: string; ledger_entry_hash: string }> {\n return EvaluateDecisionResolution.appendEvaluateDecisionLedgerEvent(store, input);\n}\n","import type { FastifyInstance, FastifyReply, FastifyRequest } from \"fastify\";\nimport type { ProtocolStore } from \"../store/StoreContracts.js\";\nimport { asRecord, parseIdempotencyHeader } from \"../support/Parsing.js\";\nimport {\n buildProtocolPerformanceSnapshot,\n buildServerTimingHeader,\n durationMs,\n} from \"../support/Performance.js\";\nimport { getVerticalPack } from \"../verticals/VerticalRegistry.js\";\nimport type {\n EvaluateDecisionRequest,\n EvaluateDecisionResponse,\n} from \"../evaluate-decision/EvaluateDecisionContracts.js\";\nimport {\n buildWebexTrustContext,\n parseWebexAgentIntentRequest,\n resolveWebexExecutionState,\n} from \"./WebexGovernance.js\";\nimport type { WebexAgentIntentResponse, WebexTrustContext } from \"./WebexContracts.js\";\n\n/** Registers the governed Webex agent-intent evaluation routes. */\nexport function registerWebexRoutes(app: FastifyInstance, deps: { store: ProtocolStore }): void {\n const { store } = deps;\n\n const evaluateWebexAgentIntentHandler = async (req: FastifyRequest, reply: FastifyReply) => {\n const handlerStartedAt = process.hrtime.bigint();\n const measuredAt = new Date().toISOString();\n const performanceStages: Record<string, number> = {};\n const idempotencyHeader = parseIdempotencyHeader(req.headers as Record<string, unknown>);\n const parsed = parseWebexAgentIntentRequest(req.body, idempotencyHeader);\n if (!parsed.ok) {\n return reply.code(400).send({ error: \"VALIDATION_ERROR\", message: parsed.message });\n }\n if (parsed.value.vertical_pack && !getVerticalPack(parsed.value.vertical_pack)) {\n return reply.code(400).send({\n error: \"VALIDATION_ERROR\",\n message: `Unknown vertical pack '${parsed.value.vertical_pack}'`,\n });\n }\n\n const evaluatePayload = {\n org_id: parsed.value.org_id,\n decision_type: \"WEBEX_AGENT_INTENT_GATE\",\n amount: parsed.value.amount,\n risk_score: parsed.value.risk_score,\n channel: \"webex\",\n ...(parsed.value.policy_version ? { policy_version: parsed.value.policy_version } : {}),\n objective_profile: parsed.value.objective_profile,\n ...(parsed.value.vertical_pack ? { vertical_pack: parsed.value.vertical_pack } : {}),\n ...(parsed.value.workflow_key ? { workflow_key: parsed.value.workflow_key } : {}),\n mode: parsed.value.mode,\n context: {\n ...parsed.value.context,\n source_system: \"webex\",\n workflow_surface: \"webex_agentic_app\",\n collaboration_surface: \"webex\",\n room_id: parsed.value.room_id,\n message_id: parsed.value.message_id,\n person_id: parsed.value.person_id,\n person_email: parsed.value.person_email,\n agent_id: parsed.value.agent_id,\n agent_name: parsed.value.agent_name,\n workspace_id: parsed.value.workspace_id,\n location_id: parsed.value.location_id,\n device_id: parsed.value.device_id,\n intent_type: parsed.value.intent_type,\n proposed_action: parsed.value.proposed_action,\n system_of_record: parsed.value.system_of_record,\n record_type: parsed.value.record_type,\n record_id: parsed.value.record_id,\n approval_path: parsed.value.approval_path,\n trust_context: parsed.value.trust_context,\n },\n ...(parsed.value.idempotency_key ? { idempotency_key: parsed.value.idempotency_key } : {}),\n };\n\n const actionGateStartedAt = process.hrtime.bigint();\n const evaluateRes = await app.inject({\n method: \"POST\",\n url: \"/v1/protocol/evaluate-decision\",\n headers: parsed.value.idempotency_key\n ? {\n \"idempotency-key\": parsed.value.idempotency_key,\n }\n : undefined,\n payload: evaluatePayload,\n });\n performanceStages.decision_evaluation_ms = durationMs(actionGateStartedAt);\n\n const evaluateBody = evaluateRes.json();\n if (evaluateRes.statusCode !== 200) {\n return reply.code(evaluateRes.statusCode).send(evaluateBody);\n }\n\n const result = evaluateBody as EvaluateDecisionResponse;\n const executionState = resolveWebexExecutionState({\n mode: result.mode,\n outcome: result.outcome,\n });\n const dossierLookupStartedAt = process.hrtime.bigint();\n const storedDossier = await store.getDecisionDossier({\n orgId: parsed.value.org_id,\n dossierId: result.dossier_id,\n });\n performanceStages.dossier_lookup_ms = durationMs(dossierLookupStartedAt);\n const storedPayload = asRecord(storedDossier?.dossier_payload);\n const webexGovernance = asRecord(storedPayload.webex_governance);\n const linkedData = asRecord(storedPayload.linked_data);\n const linkedDataDocument = asRecord(linkedData.document);\n const storedTrustContext = asRecord(webexGovernance.trust_context);\n const fallbackTrustContext = buildWebexTrustContext(\n evaluatePayload as unknown as EvaluateDecisionRequest,\n );\n const trustContext: WebexTrustContext =\n Object.keys(storedTrustContext).length > 0\n ? (storedTrustContext as WebexTrustContext)\n : (fallbackTrustContext ?? {\n room: {\n room_id: parsed.value.room_id,\n room_name: null,\n room_type: null,\n },\n operator: {\n person_id: parsed.value.person_id,\n person_email: parsed.value.person_email,\n operator_name: null,\n binding_state:\n parsed.value.person_id || parsed.value.person_email ? \"DECLARED\" : \"NOT_PROVIDED\",\n verification_source: null,\n },\n workspace: {\n workspace_id: parsed.value.workspace_id,\n workspace_name: null,\n binding_state: parsed.value.workspace_id ? \"DECLARED\" : \"NOT_PROVIDED\",\n },\n location: {\n location_id: parsed.value.location_id,\n location_name: null,\n binding_state: parsed.value.location_id ? \"DECLARED\" : \"NOT_PROVIDED\",\n },\n device: {\n device_id: parsed.value.device_id,\n device_name: null,\n platform: null,\n device_type: null,\n roomos: false,\n binding_state: parsed.value.device_id ? \"DECLARED\" : \"NOT_PROVIDED\",\n },\n trust_semantics: {\n assurance_level: \"CONTEXT_BOUND\",\n hardware_assurance: \"NOT_PROVIDED\",\n statement:\n \"Decionis bound Webex room, workspace, location, and operator context to this dossier. This is contextual governance evidence, not standalone hardware attestation.\",\n supported_claim_boundary:\n \"Device/workspace/location context is bound to the dossier.\",\n },\n });\n const performance = buildProtocolPerformanceSnapshot({\n measured_at: measuredAt,\n started_at: handlerStartedAt,\n stages: {\n ...performanceStages,\n ...(result.performance?.total_latency_ms != null\n ? {\n decision_evaluation_server_ms: result.performance.total_latency_ms,\n }\n : {}),\n },\n });\n\n const response: WebexAgentIntentResponse = {\n ...result,\n performance,\n execution_state: executionState,\n should_execute: executionState === \"ALLOW\",\n should_hold: executionState === \"HOLD\",\n should_escalate: executionState === \"ESCALATE\",\n should_deny: executionState === \"DENY\",\n decision_dossier_json_ld:\n Object.keys(linkedDataDocument).length > 0 ? linkedDataDocument : null,\n webex_governance: webexGovernance,\n webex_intent: {\n room_id: parsed.value.room_id,\n message_id: parsed.value.message_id,\n person_id: parsed.value.person_id,\n person_email: parsed.value.person_email,\n agent_id: parsed.value.agent_id,\n agent_name: parsed.value.agent_name,\n workspace_id: parsed.value.workspace_id,\n location_id: parsed.value.location_id,\n device_id: parsed.value.device_id,\n intent_type: parsed.value.intent_type,\n proposed_action: parsed.value.proposed_action,\n system_of_record: parsed.value.system_of_record,\n record_type: parsed.value.record_type,\n record_id: parsed.value.record_id,\n approval_path: parsed.value.approval_path,\n trust_context: trustContext,\n },\n };\n\n reply.header(\"server-timing\", buildServerTimingHeader(performance));\n return reply.code(200).send(response);\n };\n\n app.post(\"/webex/agent-intents/evaluate\", evaluateWebexAgentIntentHandler);\n app.post(\"/v1/protocol/webex/agent-intents/evaluate\", evaluateWebexAgentIntentHandler);\n}\n","import { randomUUID } from \"node:crypto\";\nimport type { FastifyInstance, FastifyReply, FastifyRequest } from \"fastify\";\nimport type { ProtocolPayload, ProtocolStore } from \"../store/StoreContracts.js\";\nimport { validateProtocolArtifact } from \"../validation/ProtocolArtifacts.js\";\nimport { PROTOCOL_VERSION } from \"../ProtocolInfo.js\";\nimport { asRecord, asString, isLikelyUuid } from \"../support/Parsing.js\";\nimport { authenticateMcpRequest, isAuthenticationRequired } from \"../mcp.js\";\nimport type { ProtocolMcpAuthLookup } from \"../auth/McpAuth.js\";\nimport { sapVerticalPack } from \"../verticals/sap/SapPack.js\";\nimport {\n buildSapEvaluateRequest,\n deriveSapDuplicateFacts,\n mapPipelineToSapVerdict,\n type SapGate,\n type SapPayload,\n} from \"../verticals/sap/SapSurface.js\";\nimport {\n DUPLICATE_LOOKBACK_DAYS,\n SAP_DEFAULT_ORG_ID,\n SAP_VERIFY_BASE_URL,\n} from \"./SurfaceVerifyShared.js\";\n\n// ── SAP surface (federates apps/sap into the shared engine) ─────────\n// sap-btp's DecionisClient already calls these two paths; previously they did\n// not exist (silent local fallback). Each computes a deterministic verdict via\n// the SAP vertical pack and chains a signed decision into the shared audit\n// ledger, returning the verdict shape sap-btp expects.\n\n/** Registers the SAP dual-gate verification routes (state admission + execution authority). */\nexport function registerSapVerifyRoutes(\n app: FastifyInstance,\n deps: { store: ProtocolStore; authLookup: ProtocolMcpAuthLookup | null },\n): void {\n const { store } = deps;\n const protocolAuthLookup = deps.authLookup ?? null;\n\n // Seed the org's policy bundle from the SAP pack (idempotent) so the shared\n // evaluate-decision pipeline has a \"ready\" policy guard for SAP requests.\n const ensureSapPolicyBundle = async (orgId: string) => {\n const bundles = await store.listPolicyBundles({ orgId, limit: 50 });\n if (bundles.some((bundle) => bundle.version === sapVerticalPack.policy_bundle.version)) return;\n const bundlePayload: ProtocolPayload = {\n protocol_version: PROTOCOL_VERSION,\n bundle_id: randomUUID(),\n org_id: orgId,\n version: sapVerticalPack.policy_bundle.version,\n effective_from: new Date(Date.now() - 60_000).toISOString(),\n rules: sapVerticalPack.policy_bundle.rules.map((rule) => ({\n ...rule,\n rule_id: `sap:${rule.rule_id}`,\n })),\n metadata: {\n author: \"decionis-sap-adapter\",\n source: \"protocol_service\",\n change_ticket: \"sap-federation\",\n },\n };\n const validation = validateProtocolArtifact(\"policy_bundle\", bundlePayload);\n if (validation.ok) await store.saveArtifact(\"policy_bundle\", validation.value);\n };\n\n const handleSapGate = async (gate: SapGate, req: FastifyRequest, reply: FastifyReply) => {\n // Auth — enforced only when the protocol has auth configured (env breakglass\n // key, custom header, or org-API-key lookup); open in unconfigured dev/test.\n const authCtx = await authenticateMcpRequest(req, protocolAuthLookup);\n if (isAuthenticationRequired(protocolAuthLookup) && !authCtx) {\n return reply.code(401).send({\n error: \"UNAUTHORIZED\",\n message: \"Valid API key required for SAP governance routes\",\n });\n }\n\n const payload = (req.body ?? {}) as SapPayload;\n\n // Tenant seam → org. The full pipeline requires a UUID org id; an\n // authenticated org-API key wins, then a request org_id, env, default.\n const ctx = asRecord(payload.context);\n const authedOrgId = authCtx && authCtx.kind === \"org_api_key\" ? authCtx.org_id : null;\n const candidateOrg =\n authedOrgId ||\n asString(ctx.org_id)?.trim() ||\n process.env.DECIONIS_SAP_ORG_ID?.trim() ||\n SAP_DEFAULT_ORG_ID;\n const orgId = isLikelyUuid(candidateOrg) ? candidateOrg : SAP_DEFAULT_ORG_ID;\n\n // Route through the FULL shared evaluate-decision pipeline in-process: org\n // policy-bundle evaluation, Ed25519-signed dossier, decision-chain lineage,\n // audit ledger, and idempotency replay — all reused, no logic duplicated.\n await ensureSapPolicyBundle(orgId);\n\n // Gate 2 (execution authority) gets the stateful duplicate-payment fact from a\n // store lookback (shared with the ops surface); Gate 1 is purely declarative.\n let extraFacts: Record<string, unknown> | undefined;\n if (gate === \"execution_authority\") {\n const since = new Date(Date.now() - DUPLICATE_LOOKBACK_DAYS * 24 * 60 * 60 * 1000);\n extraFacts = await deriveSapDuplicateFacts({ store, orgId, payload, since });\n }\n\n const evalRes = await app.inject({\n method: \"POST\",\n url: \"/v1/protocol/evaluate-decision\",\n payload: buildSapEvaluateRequest(payload, gate, orgId, extraFacts),\n });\n if (evalRes.statusCode !== 200) {\n return reply.code(502).send({\n error: \"SAP_PIPELINE_FAILED\",\n message: \"The shared evaluate-decision pipeline rejected the SAP request.\",\n status: evalRes.statusCode,\n });\n }\n\n const response = evalRes.json() as {\n outcome?: string;\n dossier_id?: string;\n dossier_sha256?: string | null;\n decision_resolution_id?: string | null;\n evaluation_id?: string | null;\n ledger_entry_id?: string | null;\n ledger_entry_hash?: string | null;\n policy_version?: string;\n decision_chain?: unknown;\n idempotent_replay?: boolean;\n policy_evaluation?: {\n selected_rule_id?: string | null;\n selected_rule_rationale?: string | null;\n } | null;\n };\n const verdict = mapPipelineToSapVerdict(response, gate);\n const dossierId = response.dossier_id ?? null;\n const verificationUrl = dossierId\n ? `${process.env.DECIONIS_VERIFY_BASE_URL ?? SAP_VERIFY_BASE_URL}/${dossierId}`\n : null;\n\n return reply.code(200).send({\n decision: verdict.decision,\n reason: verdict.reason,\n required_action: verdict.required_action,\n gate,\n decision_domain: verdict.decision_domain,\n rule_id: verdict.rule_id,\n outcome: verdict.outcome,\n duplicate_suspected: Boolean(extraFacts?.duplicate_suspected),\n policy_version: response.policy_version ?? sapVerticalPack.policy_bundle.version,\n dossier_id: dossierId,\n dossier_sha256: response.dossier_sha256 ?? null,\n dossier_hash: response.dossier_sha256 ? `sha256:${response.dossier_sha256}` : null,\n verification_url: verificationUrl,\n org_id: orgId,\n decision_resolution_id: response.decision_resolution_id ?? null,\n evaluation_id: response.evaluation_id ?? null,\n ledger_entry_id: response.ledger_entry_id ?? null,\n ledger_entry_hash: response.ledger_entry_hash ?? null,\n decision_chain: response.decision_chain ?? null,\n idempotent_replay: Boolean(response.idempotent_replay),\n federated: true,\n pipeline: true,\n });\n };\n\n app.post(\"/sap/state-admission/verify\", (req, reply) =>\n handleSapGate(\"state_admission\", req, reply),\n );\n app.post(\"/v1/protocol/sap/state-admission/verify\", (req, reply) =>\n handleSapGate(\"state_admission\", req, reply),\n );\n app.post(\"/sap/execution-authority/verify\", (req, reply) =>\n handleSapGate(\"execution_authority\", req, reply),\n );\n app.post(\"/v1/protocol/sap/execution-authority/verify\", (req, reply) =>\n handleSapGate(\"execution_authority\", req, reply),\n );\n}\n","import { createHash } from \"node:crypto\";\n\nimport { sapVerticalPack } from \"./SapPack.js\";\nimport type { VerticalPackRule } from \"../VerticalContracts.js\";\nimport {\n deriveDuplicateFacts,\n duplicateFingerprintFromContext,\n type DuplicateFacts,\n type DuplicateLookbackStore,\n} from \"../shared/DuplicateDetection.js\";\n\n/**\n * SAP surface adapter — the concrete implementation of the native-surface\n * contract for SAP. Surface-specific work is normalization + derivation; the\n * decision logic is the declarative `sapVerticalPack`. This module is pure\n * (no I/O, no store) so it is fully unit-testable and deterministic, and it is\n * the source of truth that the protocol `/sap/*` routes call.\n *\n * Behaviour is a faithful port of the previous hardcoded gates in\n * `apps/sap/srv/decionis-client.js` (`decionis_verify_state` /\n * `decionis_verify_execution`); see `SapSurface.test.ts` for the parity table.\n */\n\nexport type SapGate = \"state_admission\" | \"execution_authority\";\nexport type SapDecision = \"ALLOW\" | \"BLOCK\" | \"ESCALATE\" | \"DELAY\";\nexport type SapOutcome = \"APPROVE\" | \"REJECT\" | \"ESCALATE\" | \"REVIEW\";\n\nexport interface SapPayload {\n source_system?: string;\n object_type?: string;\n object_id?: string;\n action?: string;\n proposed_state?: Record<string, unknown>;\n actor?: Record<string, unknown>;\n context?: Record<string, unknown>;\n}\n\nexport interface SapVerdict {\n decision: SapDecision;\n outcome: SapOutcome;\n reason: string;\n required_action: string | null;\n decision_domain: \"SAP_STATE_ADMISSION\" | \"SAP_EXECUTION_AUTHORITY\";\n rule_id: string | null;\n gate: SapGate;\n}\n\nconst REQUIRED_STATE_FIELDS = [\"amount\", \"currency\", \"vendor_id\", \"cost_center\"] as const;\nconst AUTHORIZED_ROLES = new Set([\"ProcurementManager\", \"TreasuryHead\", \"Controller\", \"CFO\"]);\nconst PO_TREASURY_THRESHOLD = 50000;\n/** Invoice may exceed the PO amount by at most this fraction before the match fails. */\nconst THREE_WAY_MATCH_TOLERANCE = 0.01;\n\n/** Per-rule reason + structured required-action, kept out of the declarative pack. */\nexport const RULE_META: Record<string, { reason: string; required_action: string }> = {\n \"state-required-fields\": {\n reason: \"Required SAP state fields are missing.\",\n required_action: \"COMPLETE_SOURCE_STATE\",\n },\n \"state-amount-valid\": {\n reason: \"Purchase order amount must be a positive numeric value.\",\n required_action: \"CORRECT_PURCHASE_ORDER_AMOUNT\",\n },\n \"state-within-budget\": {\n reason: \"Purchase order amount exceeds the approved budget on the SAP state.\",\n required_action: \"BUDGET_OWNER_REVIEW\",\n },\n \"state-vendor-verified\": {\n reason: \"Vendor is not verified for governed purchase order execution.\",\n required_action: \"VERIFY_VENDOR\",\n },\n \"state-cost-center-valid\": {\n reason: \"Cost center is invalid or not eligible for this purchase order.\",\n required_action: \"VALID_COST_CENTER\",\n },\n \"exec-authorized-role\": {\n reason: \"Actor role is not authorized for governed SAP execution.\",\n required_action: \"AUTHORIZED_SAP_ROLE\",\n },\n \"exec-segregation-of-duties\": {\n reason: \"Segregation-of-duties check failed because requester and approver match.\",\n required_action: \"SEGREGATION_OF_DUTIES_REVIEW\",\n },\n \"exec-regional-hold\": {\n reason: \"Regional constraint requires a revisit trigger before SAP execution.\",\n required_action: \"REGIONAL_COMPLIANCE_REVISIT\",\n },\n \"exec-treasury-threshold\": {\n reason: \"PO amount exceeds threshold and Treasury Head approval is missing.\",\n required_action: \"TREASURY_HEAD_APPROVAL\",\n },\n \"exec-duplicate-payment\": {\n reason: \"A prior payment with the same vendor + amount fingerprint was found.\",\n required_action: \"DUPLICATE_PAYMENT_REVIEW\",\n },\n \"exec-three-way-match\": {\n reason:\n \"Three-way match failed: goods receipt does not confirm the invoiced quantity or amount.\",\n required_action: \"GOODS_RECEIPT_VERIFICATION\",\n },\n};\n\ninterface PipelineEvaluateResponse {\n outcome?: string;\n policy_evaluation?: {\n selected_rule_id?: string | null;\n selected_rule_rationale?: string | null;\n } | null;\n}\n\n/** SAP native-surface adapter: fact derivation + deterministic dual-gate evaluation. */\nexport class SapSurface {\n /** SAP version of the protocol vertical pack (rule_ids carry the `sap:` prefix). */\n private static readonly PACK_VERSION = sapVerticalPack.policy_bundle.version;\n\n /**\n * Derive the boolean/number facts the pack rules match against. These mirror the\n * exact conditions of the original imperative gates so behaviour is preserved.\n */\n static deriveFacts(payload: SapPayload, gate: SapGate): Record<string, unknown> {\n const p = SapSurface.normalizePayload(payload);\n const state = p.proposed_state;\n const context = p.context;\n const actor = p.actor;\n\n const missingList = REQUIRED_STATE_FIELDS.filter((f) => SapSurface.isBlank(state[f]));\n const amount = Number(state.amount);\n const amountFinite = Number.isFinite(amount);\n\n const vendorStatus = String(state.vendor_status ?? \"VERIFIED\").toUpperCase();\n const costCenterStatus = String(state.cost_center_status ?? \"VALID\").toUpperCase();\n const actorRole = String(actor.role ?? \"\");\n const threeWayMatchApplicable = SapSurface.isThreeWayMatchApplicable(p);\n\n return {\n gate,\n object_type: p.object_type,\n amount: amountFinite ? amount : null,\n // Fingerprint passthrough for duplicate-payment detection (SAP has no invoice\n // number, so the shared fingerprint falls back to vendor + amount + currency).\n vendor_id: state.vendor_id ?? null,\n currency: state.currency ?? null,\n // Overridden by the store-backed duplicate pass; safe default for pure eval.\n duplicate_suspected: false,\n // Gate 1\n missing_required_fields: missingList.length,\n missing_fields_list: missingList,\n amount_invalid: !amountFinite || amount <= 0,\n over_budget:\n !SapSurface.isBlank(state.approved_budget) &&\n amountFinite &&\n amount > Number(state.approved_budget),\n vendor_verified:\n vendorStatus === \"VERIFIED\" && !/^UNVERIFIED|^BLOCK/.test(String(state.vendor_id ?? \"\")),\n cost_center_valid:\n costCenterStatus === \"VALID\" && !/^INVALID/.test(String(state.cost_center ?? \"\")),\n // Gate 2\n actor_role: actorRole,\n actor_authorized: AUTHORIZED_ROLES.has(actorRole),\n sod_violation:\n !SapSurface.isBlank(context.requested_by) &&\n !SapSurface.isBlank(context.approved_by) &&\n String(context.requested_by) === String(context.approved_by),\n regional_hold: state.region === \"EU\" && context.regional_hold === true,\n po_over_threshold:\n p.object_type === \"PurchaseOrder\" && amountFinite && amount > PO_TREASURY_THRESHOLD,\n treasury_approved: SapSurface.hasTreasuryApproval(context),\n // Three-way match (AP control): only payment/invoice actions are subject to it,\n // so PO create/change is never flagged.\n three_way_match_required: threeWayMatchApplicable,\n three_way_match_failed: threeWayMatchApplicable && SapSurface.threeWayMatchFailed(p),\n };\n }\n\n /**\n * Build the canonical `evaluate-decision` request body for a SAP gate so the\n * decision runs through the full shared pipeline (org policy bundle, signed\n * dossier, decision-chain, idempotency). The derived facts live in `context`,\n * which the engine spreads into the rule-matching facts; `policy_version` pins\n * the SAP bundle so it is selected even when the org has other bundles.\n */\n static buildEvaluateRequest(\n payload: SapPayload,\n gate: SapGate,\n orgId: string,\n extraFacts?: Record<string, unknown>,\n ): Record<string, unknown> {\n const facts = { ...SapSurface.deriveFacts(payload, gate), ...(extraFacts ?? {}) };\n return {\n org_id: orgId,\n decision_type: gate === \"state_admission\" ? \"sap_state_admission\" : \"sap_execution_authority\",\n vertical_pack: \"sap\",\n policy_version: SapSurface.PACK_VERSION,\n mode: \"ENFORCEMENT\",\n amount: typeof facts.amount === \"number\" ? facts.amount : null,\n idempotency_key: SapSurface.idempotencyKey(payload, gate),\n context: facts,\n };\n }\n\n /**\n * Map a shared-pipeline `EvaluateDecisionResponse` back into the SAP verdict\n * shape sap-btp consumes. The selected rule id (stripped of its `sap:` prefix)\n * keys the structured `required_action`; the reason prefers the static rule text\n * and falls back to the rule rationale the engine returned.\n */\n static mapPipelineToVerdict(response: PipelineEvaluateResponse, gate: SapGate): SapVerdict {\n const outcome = (response.outcome ?? \"REVIEW\") as SapOutcome;\n const rawRuleId = response.policy_evaluation?.selected_rule_id ?? null;\n const ruleId = rawRuleId ? rawRuleId.replace(/^sap:/, \"\") : null;\n const meta = ruleId ? RULE_META[ruleId] : undefined;\n const fallbackReason =\n gate === \"state_admission\"\n ? \"SAP proposed state is complete, non-conflicting, and eligible for execution review.\"\n : \"Execution authority is present for the proposed SAP action.\";\n return {\n decision: OUTCOME_TO_DECISION[outcome] ?? \"DELAY\",\n outcome,\n reason: meta?.reason ?? response.policy_evaluation?.selected_rule_rationale ?? fallbackReason,\n required_action: meta?.required_action ?? null,\n decision_domain: SapSurface.decisionDomainForGate(gate),\n rule_id: ruleId,\n gate,\n };\n }\n\n /**\n * Evaluate a SAP gate deterministically against the SAP vertical pack.\n * No match means every check passed → ALLOW (mirrors the original `else ALLOW`).\n * Highest-priority matched rule wins, reproducing the gates' short-circuit order.\n */\n static evaluateGate(\n payload: SapPayload,\n gate: SapGate,\n extraFacts?: Record<string, unknown>,\n ): SapVerdict {\n const facts = { ...SapSurface.deriveFacts(payload, gate), ...(extraFacts ?? {}) };\n const decisionDomain =\n gate === \"state_admission\" ? \"SAP_STATE_ADMISSION\" : \"SAP_EXECUTION_AUTHORITY\";\n\n const matched = sapVerticalPack.policy_bundle.rules\n .filter((rule) => rule.enabled)\n .filter((rule) => rule.when.all.every((pred) => SapSurface.matchPredicate(facts, pred)))\n .sort((a, b) => b.priority - a.priority);\n\n const selected = matched[0];\n if (!selected) {\n return {\n decision: \"ALLOW\",\n outcome: \"APPROVE\",\n reason:\n gate === \"state_admission\"\n ? \"SAP proposed state is complete, non-conflicting, and eligible for execution review.\"\n : \"Execution authority is present for the proposed SAP action.\",\n required_action: null,\n decision_domain: decisionDomain,\n rule_id: null,\n gate,\n };\n }\n\n const outcome = SapSurface.outcomeForAction(selected.then.action);\n const meta = RULE_META[selected.rule_id];\n let reason = meta?.reason ?? selected.rationale ?? selected.name;\n // Enrich the missing-fields reason with the concrete field list, as the\n // original gate did, without putting dynamic text in the declarative pack.\n if (selected.rule_id === \"state-required-fields\") {\n const list = (facts.missing_fields_list as string[]) ?? [];\n reason = `Required SAP state fields are missing: ${list.join(\", \")}.`;\n } else if (selected.rule_id === \"exec-authorized-role\") {\n reason = `Actor role ${String(facts.actor_role) || \"UNKNOWN\"} is not authorized for governed SAP execution.`;\n }\n\n return {\n decision: OUTCOME_TO_DECISION[outcome],\n outcome,\n reason,\n required_action: meta?.required_action ?? null,\n decision_domain: decisionDomain,\n rule_id: selected.rule_id,\n gate,\n };\n }\n\n /**\n * Idempotency key for a SAP gate decision. Scoped to object + gate AND a digest\n * of the derived facts, so a genuine retry of the *same* state replays the cached\n * decision while a changed state (e.g. the vendor became verified) re-evaluates\n * instead of returning a stale verdict.\n */\n static idempotencyKey(payload: SapPayload, gate: SapGate): string {\n const p = SapSurface.normalizePayload(payload);\n const digest = createHash(\"sha256\")\n .update(JSON.stringify(SapSurface.deriveFacts(payload, gate)))\n .digest(\"hex\")\n .slice(0, 24);\n return `sap:${p.object_type}:${p.object_id}:${gate}:${digest}`;\n }\n\n /**\n * Derive the stateful `duplicate_suspected` fact for a SAP execution-authority\n * action. SAP payloads carry no invoice number, so the shared fingerprint falls\n * back to vendor + amount + currency. Delegates to the shared `deriveDuplicateFacts`.\n */\n static async deriveDuplicateFacts(input: {\n store: DuplicateLookbackStore;\n orgId: string;\n payload: SapPayload;\n since?: Date | null;\n limit?: number;\n }): Promise<DuplicateFacts> {\n return deriveDuplicateFacts({\n store: input.store,\n orgId: input.orgId,\n currentKey: SapSurface.idempotencyKey(input.payload, \"execution_authority\"),\n fingerprint: duplicateFingerprintFromContext(\n SapSurface.deriveFacts(input.payload, \"execution_authority\"),\n ),\n since: input.since,\n limit: input.limit,\n });\n }\n\n private static normalizePayload(payload: SapPayload): Required<SapPayload> {\n return {\n source_system: payload.source_system ?? \"SAP_S4HANA\",\n object_type: payload.object_type ?? \"PurchaseOrder\",\n object_id: payload.object_id ?? \"UNKNOWN\",\n action: payload.action ?? \"CHANGE_PURCHASE_ORDER\",\n proposed_state: payload.proposed_state ?? {},\n actor: payload.actor ?? {},\n context: payload.context ?? {},\n };\n }\n\n private static isBlank(value: unknown): boolean {\n return value === undefined || value === null || value === \"\";\n }\n\n private static hasTreasuryApproval(context: Record<string, unknown>): boolean {\n const approvalStatus = String(context.approval_status ?? \"\").toUpperCase();\n const approvalRole = String(context.approval_role ?? context.approved_by_role ?? \"\");\n const signature = String(context.treasury_head_signature ?? context.approval_signature ?? \"\");\n return (\n approvalStatus === \"APPROVED\" &&\n /treasury\\s*head/i.test(approvalRole) &&\n signature.trim().length > 0\n );\n }\n\n private static toFiniteNumber(value: unknown): number | null {\n if (SapSurface.isBlank(value)) return null;\n const n = Number(value);\n return Number.isFinite(n) ? n : null;\n }\n\n /**\n * Three-way match applies only to payment-/invoice-style actions (releasing a\n * payment against an invoice). A plain PO create/change needs no goods receipt\n * yet, so it is exempt. `context.require_three_way_match` overrides the inference.\n */\n private static isThreeWayMatchApplicable(p: Required<SapPayload>): boolean {\n const override = p.context.require_three_way_match;\n if (override === true) return true;\n if (override === false) return false;\n const type = String(p.object_type).toLowerCase();\n const action = String(p.action).toLowerCase();\n return /invoice|payment/.test(type) || /payment|invoice|release|disburse/.test(action);\n }\n\n /**\n * Reconcile purchase order ↔ goods receipt ↔ invoice. Fails closed: when goods\n * receipt cannot be confirmed at all, the payment is held for verification.\n */\n private static threeWayMatchFailed(p: Required<SapPayload>): boolean {\n const ctx = p.context;\n const state = p.proposed_state;\n const grStatus = String(ctx.goods_receipt_status ?? \"\").toUpperCase();\n const receivedQty = SapSurface.toFiniteNumber(ctx.received_quantity);\n const invoicedQty = SapSurface.toFiniteNumber(ctx.invoiced_quantity);\n const poQty = SapSurface.toFiniteNumber(ctx.po_quantity ?? state.po_quantity);\n const poAmount = SapSurface.toFiniteNumber(state.amount);\n const invoiceAmount = SapSurface.toFiniteNumber(ctx.invoice_amount ?? state.invoice_amount);\n\n // No goods-receipt signal at all → cannot confirm receipt → fail closed.\n if (grStatus === \"\" && receivedQty === null) return true;\n // Goods receipt exists but does not confirm full receipt.\n if (grStatus !== \"\" && grStatus !== \"RECEIVED\" && grStatus !== \"COMPLETE\") return true;\n // Quantity reconciliation: received must cover invoiced; invoiced must not exceed PO.\n if (receivedQty !== null && invoicedQty !== null && receivedQty < invoicedQty) return true;\n if (poQty !== null && invoicedQty !== null && invoicedQty > poQty) return true;\n // Amount reconciliation: invoice must not exceed the PO amount beyond tolerance.\n if (\n poAmount !== null &&\n invoiceAmount !== null &&\n invoiceAmount > poAmount * (1 + THREE_WAY_MATCH_TOLERANCE)\n ) {\n return true;\n }\n return false;\n }\n\n /** Minimal predicate matcher mirroring the protocol rule-engine operator semantics. */\n private static matchPredicate(\n facts: Record<string, unknown>,\n pred: VerticalPackRule[\"when\"][\"all\"][number],\n ): boolean {\n const actual = facts[pred.field];\n const expected = pred.value;\n switch (pred.operator) {\n case \"EQ\":\n return actual === expected;\n case \"NEQ\":\n return actual !== expected;\n case \"GT\":\n return Number(actual) > Number(expected);\n case \"GTE\":\n return Number(actual) >= Number(expected);\n case \"LT\":\n return Number(actual) < Number(expected);\n case \"LTE\":\n return Number(actual) <= Number(expected);\n case \"IN\":\n return Array.isArray(pred.values) && pred.values.includes(actual);\n case \"NOT_IN\":\n return Array.isArray(pred.values) && !pred.values.includes(actual);\n case \"EXISTS\":\n return actual !== undefined && actual !== null;\n default:\n return false;\n }\n }\n\n private static outcomeForAction(action: VerticalPackRule[\"then\"][\"action\"]): SapOutcome {\n switch (action) {\n case \"AUTO_REJECT\":\n return \"REJECT\";\n case \"ESCALATE\":\n return \"ESCALATE\";\n case \"AUTO_APPROVE\":\n return \"APPROVE\";\n default:\n return \"REVIEW\"; // REQUIRE_REVIEW | REQUEST_INFO\n }\n }\n\n private static decisionDomainForGate(gate: SapGate): SapVerdict[\"decision_domain\"] {\n return gate === \"state_admission\" ? \"SAP_STATE_ADMISSION\" : \"SAP_EXECUTION_AUTHORITY\";\n }\n}\n\nexport const OUTCOME_TO_DECISION: Record<SapOutcome, SapDecision> = {\n APPROVE: \"ALLOW\",\n REJECT: \"BLOCK\",\n ESCALATE: \"ESCALATE\",\n REVIEW: \"DELAY\",\n};\n\n/** Functional alias for {@link SapSurface.deriveFacts}. */\nexport function deriveSapFacts(payload: SapPayload, gate: SapGate): Record<string, unknown> {\n return SapSurface.deriveFacts(payload, gate);\n}\n\n/** Functional alias for {@link SapSurface.buildEvaluateRequest}. */\nexport function buildSapEvaluateRequest(\n payload: SapPayload,\n gate: SapGate,\n orgId: string,\n extraFacts?: Record<string, unknown>,\n): Record<string, unknown> {\n return SapSurface.buildEvaluateRequest(payload, gate, orgId, extraFacts);\n}\n\n/** Functional alias for {@link SapSurface.mapPipelineToVerdict}. */\nexport function mapPipelineToSapVerdict(\n response: PipelineEvaluateResponse,\n gate: SapGate,\n): SapVerdict {\n return SapSurface.mapPipelineToVerdict(response, gate);\n}\n\n/** Functional alias for {@link SapSurface.evaluateGate}. */\nexport function evaluateSapGate(\n payload: SapPayload,\n gate: SapGate,\n extraFacts?: Record<string, unknown>,\n): SapVerdict {\n return SapSurface.evaluateGate(payload, gate, extraFacts);\n}\n\n/** Functional alias for {@link SapSurface.idempotencyKey}. */\nexport function sapIdempotencyKey(payload: SapPayload, gate: SapGate): string {\n return SapSurface.idempotencyKey(payload, gate);\n}\n\n/** Functional alias for {@link SapSurface.deriveDuplicateFacts}. */\nexport async function deriveSapDuplicateFacts(input: {\n store: DuplicateLookbackStore;\n orgId: string;\n payload: SapPayload;\n since?: Date | null;\n limit?: number;\n}): Promise<DuplicateFacts> {\n return SapSurface.deriveDuplicateFacts(input);\n}\n","/**\n * Shared duplicate-payment detection for vertical surfaces (ops, SAP, …). The\n * only stateful piece of governance: it compares a payment's fingerprint against\n * prior org evaluations in a lookback window. Surface-agnostic — each surface\n * feeds its own fingerprint + idempotency key.\n */\n\n/** Minimal store seam for the lookback (a structural subset of ProtocolStore). */\nexport interface DuplicateLookbackStore {\n listDecisionEvaluations(input: { orgId: string; since?: Date | null; limit: number }): Promise<\n Array<{\n idempotency_key: string | null;\n dossier_id: string;\n request_payload: Record<string, unknown>;\n }>\n >;\n}\n\n// Kept as a `type` alias (not an interface): app.ts assigns a DuplicateFacts to a\n// `Record<string, unknown>` extraFacts slot, which relies on the implicit index\n// signature a type alias carries but an interface does not.\nexport type DuplicateFacts = {\n duplicate_suspected: boolean;\n duplicate_match_count: number;\n duplicate_of: string | null;\n};\n\n/** Store-backed duplicate-payment detection shared by the vertical surfaces. */\nexport class DuplicateDetection {\n /**\n * Vendor + invoice/amount fingerprint for duplicate-payment detection, or null.\n * Keys on vendor + invoice when an invoice number is present (strongest signal),\n * else vendor + amount + currency. Source-neutral: works for any surface that puts\n * `vendor_id`/`invoice_number`/`amount`/`currency` into its evaluate-decision context.\n */\n static fingerprintFromContext(facts: Record<string, unknown>): string | null {\n const vendor = String(facts.vendor_id ?? \"\").trim();\n if (!vendor) return null;\n const invoice = String(facts.invoice_number ?? \"\").trim();\n if (invoice) return `v:${vendor}|inv:${invoice}`;\n const amount = facts.amount;\n if (typeof amount === \"number\") {\n const currency = String(facts.currency ?? \"\").trim();\n return `v:${vendor}|amt:${amount}|cur:${currency}`;\n }\n return null;\n }\n\n /**\n * Compare a precomputed `fingerprint` against prior org evaluations in the\n * lookback window. Excludes the current idempotency key so a genuine retry of the\n * same payment is not mis-flagged as its own duplicate.\n */\n static async deriveFacts(input: {\n store: DuplicateLookbackStore;\n orgId: string;\n currentKey: string;\n fingerprint: string | null;\n since?: Date | null;\n limit?: number;\n }): Promise<DuplicateFacts> {\n if (!input.fingerprint) {\n return { duplicate_suspected: false, duplicate_match_count: 0, duplicate_of: null };\n }\n const priors = await input.store.listDecisionEvaluations({\n orgId: input.orgId,\n since: input.since ?? null,\n limit: input.limit ?? 500,\n });\n\n let count = 0;\n let dupOf: string | null = null;\n for (const row of priors) {\n if (row.idempotency_key && row.idempotency_key === input.currentKey) continue; // genuine replay\n const ctx = (row.request_payload?.context ?? {}) as Record<string, unknown>;\n if (DuplicateDetection.fingerprintFromContext(ctx) === input.fingerprint) {\n count += 1;\n if (!dupOf) dupOf = row.dossier_id ?? row.idempotency_key ?? null;\n }\n }\n return { duplicate_suspected: count > 0, duplicate_match_count: count, duplicate_of: dupOf };\n }\n}\n\n/** Functional alias for {@link DuplicateDetection.fingerprintFromContext}. */\nexport function duplicateFingerprintFromContext(facts: Record<string, unknown>): string | null {\n return DuplicateDetection.fingerprintFromContext(facts);\n}\n\n/** Functional alias for {@link DuplicateDetection.deriveFacts}. */\nexport async function deriveDuplicateFacts(input: {\n store: DuplicateLookbackStore;\n orgId: string;\n currentKey: string;\n fingerprint: string | null;\n since?: Date | null;\n limit?: number;\n}): Promise<DuplicateFacts> {\n return DuplicateDetection.deriveFacts(input);\n}\n","/** Single-tenant fallback org for SAP requests that don't carry an org_id (see plan: tenant seam). */\nexport const SAP_DEFAULT_ORG_ID = \"5ab00000-0000-4000-8000-000000000001\";\nexport const SAP_VERIFY_BASE_URL = \"https://verify.decionis.com\";\n/** Single-tenant fallback org for ops requests that don't carry an org_id (see SAP seam). */\nexport const OPS_DEFAULT_ORG_ID = \"09500000-0000-4000-8000-000000000001\";\n/** Single-tenant fallback org for Workday HR requests that don't carry an org_id (see SAP seam). */\nexport const WORKDAY_DEFAULT_ORG_ID = \"d0d00000-0000-4000-8000-000000000001\";\n/** Single-tenant fallback org for Workday Financials requests that don't carry an org_id (see SAP seam). */\nexport const WORKDAY_FIN_DEFAULT_ORG_ID = \"d0f00000-0000-4000-8000-000000000001\";\n/** Duplicate-payment lookback window for the ops/SAP disbursement gates. */\nexport const DUPLICATE_LOOKBACK_DAYS = 90;\n","import { randomUUID } from \"node:crypto\";\nimport type { FastifyInstance, FastifyReply, FastifyRequest } from \"fastify\";\nimport type { ProtocolPayload, ProtocolStore } from \"../store/StoreContracts.js\";\nimport { validateProtocolArtifact } from \"../validation/ProtocolArtifacts.js\";\nimport { PROTOCOL_VERSION } from \"../ProtocolInfo.js\";\nimport { asRecord, asString, isLikelyUuid } from \"../support/Parsing.js\";\nimport { authenticateMcpRequest, isAuthenticationRequired } from \"../mcp.js\";\nimport type { ProtocolMcpAuthLookup } from \"../auth/McpAuth.js\";\nimport { salesforceVerticalPack } from \"../verticals/salesforce/SalesforcePack.js\";\nimport {\n buildSalesforceEvaluateRequest,\n mapPipelineToSalesforceVerdict,\n resolveSalesforceMode,\n type SalesforceGate,\n type SalesforcePayload,\n} from \"../verticals/salesforce/SalesforceSurface.js\";\nimport {\n applySapCostBasis,\n fetchSapCostBasis,\n hasResolvedCost,\n resolveSapCostConfig,\n} from \"../verticals/salesforce/SapCostBasis.js\";\nimport { SAP_DEFAULT_ORG_ID, SAP_VERIFY_BASE_URL } from \"./SurfaceVerifyShared.js\";\n\n// ── Salesforce revenue-execution surface ────────────────────────────────\n// Dual-gate governance for the Salesforce → Decionis → SAP front-to-back pipeline\n// (Commerce Cloud checkout + CPQ/B2B quoting). Same federation pattern as SAP:\n// each gate routes through the full shared evaluate-decision pipeline and chains a\n// signed decision into the audit ledger. Cost basis for the margin gate is carried\n// in the payload (the SAP cost of record); no store lookback is needed.\n\n/** Registers the Salesforce dual-gate verification routes (state admission + execution authority). */\nexport function registerSalesforceVerifyRoutes(\n app: FastifyInstance,\n deps: { store: ProtocolStore; authLookup: ProtocolMcpAuthLookup | null },\n): void {\n const { store } = deps;\n const protocolAuthLookup = deps.authLookup ?? null;\n\n const ensureSalesforcePolicyBundle = async (orgId: string) => {\n const bundles = await store.listPolicyBundles({ orgId, limit: 50 });\n if (bundles.some((bundle) => bundle.version === salesforceVerticalPack.policy_bundle.version)) {\n return;\n }\n const bundlePayload: ProtocolPayload = {\n protocol_version: PROTOCOL_VERSION,\n bundle_id: randomUUID(),\n org_id: orgId,\n version: salesforceVerticalPack.policy_bundle.version,\n effective_from: new Date(Date.now() - 60_000).toISOString(),\n rules: salesforceVerticalPack.policy_bundle.rules.map((rule) => ({\n ...rule,\n rule_id: `salesforce:${rule.rule_id}`,\n })),\n metadata: {\n author: \"decionis-salesforce-adapter\",\n source: \"protocol_service\",\n change_ticket: \"salesforce-federation\",\n },\n };\n const validation = validateProtocolArtifact(\"policy_bundle\", bundlePayload);\n if (validation.ok) await store.saveArtifact(\"policy_bundle\", validation.value);\n };\n\n const handleSalesforceGate = async (\n gate: SalesforceGate,\n req: FastifyRequest,\n reply: FastifyReply,\n ) => {\n const authCtx = await authenticateMcpRequest(req, protocolAuthLookup);\n if (isAuthenticationRequired(protocolAuthLookup) && !authCtx) {\n return reply.code(401).send({\n error: \"UNAUTHORIZED\",\n message: \"Valid API key required for Salesforce governance routes\",\n });\n }\n\n const payload = (req.body ?? {}) as SalesforcePayload;\n const ctx = asRecord(payload.context);\n const authedOrgId = authCtx && authCtx.kind === \"org_api_key\" ? authCtx.org_id : null;\n const candidateOrg =\n authedOrgId ||\n asString(ctx.org_id)?.trim() ||\n process.env.DECIONIS_SALESFORCE_ORG_ID?.trim() ||\n SAP_DEFAULT_ORG_ID;\n const orgId = isLikelyUuid(candidateOrg) ? candidateOrg : SAP_DEFAULT_ORG_ID;\n\n await ensureSalesforcePolicyBundle(orgId);\n\n // Margin gate (execution authority): override the order lines' cost basis with\n // the live SAP cost of record so the margin floor is checked against truth, not\n // the Salesforce-claimed cost. Fail-safe — keep the payload cost if SAP is\n // unconfigured or unreachable.\n let evalPayload = payload;\n let costBasisSource: \"payload\" | \"sap\" = \"payload\";\n if (gate === \"execution_authority\") {\n const costConfig = resolveSapCostConfig(process.env, orgId);\n if (costConfig) {\n try {\n const skus = (payload.order_items ?? [])\n .map((it) => String(it.matnr ?? \"\").trim())\n .filter(Boolean);\n const costMap = await fetchSapCostBasis(costConfig, skus);\n if (hasResolvedCost(costMap)) {\n evalPayload = applySapCostBasis(payload, costMap);\n costBasisSource = \"sap\";\n }\n } catch {\n // fail-safe: evaluate against the payload's own cost basis\n }\n }\n }\n\n const evalRes = await app.inject({\n method: \"POST\",\n url: \"/v1/protocol/evaluate-decision\",\n payload: buildSalesforceEvaluateRequest(evalPayload, gate, orgId),\n });\n if (evalRes.statusCode !== 200) {\n return reply.code(502).send({\n error: \"SALESFORCE_PIPELINE_FAILED\",\n message: \"The shared evaluate-decision pipeline rejected the Salesforce request.\",\n status: evalRes.statusCode,\n });\n }\n\n const response = evalRes.json() as {\n outcome?: string;\n dossier_id?: string;\n dossier_sha256?: string | null;\n decision_resolution_id?: string | null;\n evaluation_id?: string | null;\n ledger_entry_id?: string | null;\n ledger_entry_hash?: string | null;\n policy_version?: string;\n decision_chain?: unknown;\n idempotent_replay?: boolean;\n policy_evaluation?: {\n selected_rule_id?: string | null;\n selected_rule_rationale?: string | null;\n } | null;\n };\n const verdict = mapPipelineToSalesforceVerdict(response, gate);\n const dossierId = response.dossier_id ?? null;\n const verificationUrl = dossierId\n ? `${process.env.DECIONIS_VERIFY_BASE_URL ?? SAP_VERIFY_BASE_URL}/${dossierId}`\n : null;\n\n // SHADOW: the full evaluation, dossier, and ledger entry are recorded exactly as in\n // enforcement, but the reported decision never blocks the caller — the enforcement\n // verdict travels in `would_decision`/`would_outcome` instead (same convention as\n // the execution-gating surface, where SHADOW forces ALLOW).\n const mode = resolveSalesforceMode(payload);\n const shadow = mode === \"SHADOW\";\n\n return reply.code(200).send({\n decision: shadow ? \"ALLOW\" : verdict.decision,\n mode,\n would_decision: shadow ? verdict.decision : null,\n would_outcome: shadow ? verdict.outcome : null,\n reason: verdict.reason,\n required_action: shadow ? null : verdict.required_action,\n gate,\n decision_domain: verdict.decision_domain,\n rule_id: verdict.rule_id,\n outcome: verdict.outcome,\n policy_version: response.policy_version ?? salesforceVerticalPack.policy_bundle.version,\n dossier_id: dossierId,\n dossier_sha256: response.dossier_sha256 ?? null,\n dossier_hash: response.dossier_sha256 ? `sha256:${response.dossier_sha256}` : null,\n verification_url: verificationUrl,\n org_id: orgId,\n decision_resolution_id: response.decision_resolution_id ?? null,\n evaluation_id: response.evaluation_id ?? null,\n ledger_entry_id: response.ledger_entry_id ?? null,\n ledger_entry_hash: response.ledger_entry_hash ?? null,\n decision_chain: response.decision_chain ?? null,\n idempotent_replay: Boolean(response.idempotent_replay),\n cost_basis_source: costBasisSource,\n federated: true,\n pipeline: true,\n });\n };\n\n app.post(\"/salesforce/state-admission/verify\", (req, reply) =>\n handleSalesforceGate(\"state_admission\", req, reply),\n );\n app.post(\"/v1/protocol/salesforce/state-admission/verify\", (req, reply) =>\n handleSalesforceGate(\"state_admission\", req, reply),\n );\n app.post(\"/salesforce/execution-authority/verify\", (req, reply) =>\n handleSalesforceGate(\"execution_authority\", req, reply),\n );\n app.post(\"/v1/protocol/salesforce/execution-authority/verify\", (req, reply) =>\n handleSalesforceGate(\"execution_authority\", req, reply),\n );\n}\n","import { createHash } from \"node:crypto\";\n\nimport { salesforceVerticalPack } from \"./SalesforcePack.js\";\nimport type { VerticalPackRule } from \"../VerticalContracts.js\";\n\n/**\n * Salesforce surface adapter — concrete implementation of the native-surface\n * contract for the Salesforce → Decionis → SAP pipeline. Surface-specific work is\n * normalization + fact derivation; decision logic is the declarative\n * `salesforceVerticalPack`. Pure (no I/O), so it is fully unit-testable and is the\n * source of truth the protocol `/salesforce/*` routes call.\n *\n * The input is a normalized Salesforce intent payload (Commerce Cloud order or CPQ\n * quote) shaped for SAP mapping: `customer_master` (KNA1), `order_header` (VBAK),\n * `order_items` (VBAP). The adapter derives the facts the pack rules match against.\n */\n\nexport type SalesforceGate = \"state_admission\" | \"execution_authority\";\nexport type SalesforceDecision = \"ALLOW\" | \"BLOCK\" | \"ESCALATE\" | \"HOLD\";\nexport type SalesforceOutcome = \"APPROVE\" | \"REJECT\" | \"ESCALATE\" | \"REVIEW\";\n/** SHADOW observes (evaluation + dossier recorded, nothing held); ENFORCEMENT gates. */\nexport type SalesforceMode = \"SHADOW\" | \"ENFORCEMENT\";\n\nexport interface SalesforceItem {\n posnr?: string;\n matnr?: string;\n kwmeng?: number | string;\n netpr?: number | string;\n cost_basis?: number | string;\n sf_line_item_discount_pct?: number | string;\n}\n\nexport interface SalesforcePayload {\n source_system?: string;\n object_type?: string;\n object_id?: string;\n action?: string;\n /** Optional gate mode; anything other than \"SHADOW\" evaluates as ENFORCEMENT. */\n mode?: string;\n context?: Record<string, unknown>;\n customer_master?: Record<string, unknown>;\n order_header?: Record<string, unknown>;\n order_items?: SalesforceItem[];\n}\n\nexport interface SalesforceVerdict {\n decision: SalesforceDecision;\n outcome: SalesforceOutcome;\n reason: string;\n required_action: string | null;\n decision_domain: \"SALESFORCE_STATE_ADMISSION\" | \"SALESFORCE_EXECUTION_AUTHORITY\";\n rule_id: string | null;\n gate: SalesforceGate;\n}\n\nconst MATNR_MAX_LENGTH = 18;\nconst MANUAL_DISCOUNT_THRESHOLD_PCT = 15;\nconst MARGIN_FLOOR_PCT = 12;\nconst MAX_DISCOUNT_SOURCES = 1;\nconst STRATEGIC_RATING = \"strategic\";\n/** Salesforce Data Cloud behavioral risk score (0..1) at/above which to hold. */\nconst RISK_SCORE_THRESHOLD = 0.7;\n\n/** Per-rule reason + structured required-action, kept out of the declarative pack. */\nexport const RULE_META: Record<string, { reason: string; required_action: string }> = {\n \"state-required-fields\": {\n reason: \"Salesforce payload is missing fields required to build a valid SAP sales order.\",\n required_action: \"COMPLETE_ORDER_INTENT\",\n },\n \"state-customer-master-synced\": {\n reason:\n \"SAP_ERR_KNA1_MISSING: Salesforce Account must be synced to a valid SAP customer master (KUNNR) before order admission.\",\n required_action: \"SYNC_SAP_CUSTOMER_MASTER\",\n },\n \"state-material-number-valid\": {\n reason: \"SAP_ERR_VBAP_MATNR_OVERFLOW: a material number exceeds the SAP 18-character limit.\",\n required_action: \"CORRECT_MATERIAL_NUMBER\",\n },\n \"state-sales-org-valid\": {\n reason: \"Sales organization (VKORG) and distribution channel (VTWEG) are required.\",\n required_action: \"SET_SALES_ORG\",\n },\n \"state-amounts-valid\": {\n reason: \"Order line net price and quantity must be positive numeric values.\",\n required_action: \"CORRECT_ORDER_AMOUNTS\",\n },\n \"exec-credit-limit\": {\n reason: \"Order total exceeds the customer's SAP-defined credit limit.\",\n required_action: \"CREDIT_REVIEW\",\n },\n \"exec-margin-floor\": {\n reason: \"Order net margin falls below the policy floor against the SAP cost basis.\",\n required_action: \"MARGIN_REVIEW\",\n },\n \"exec-discount-floor\": {\n reason:\n \"Manual line discount exceeds the threshold for a non-Strategic account; requires manager override.\",\n required_action: \"MANAGER_DISCOUNT_OVERRIDE\",\n },\n \"exec-payment-terms-allowed\": {\n reason: \"Requested B2B payment terms are not permitted for this region without review.\",\n required_action: \"PAYMENT_TERMS_REVIEW\",\n },\n \"exec-promo-stacking\": {\n reason: \"Multiple concurrent discount sources are stacked on one order.\",\n required_action: \"PROMO_STACKING_REVIEW\",\n },\n \"exec-data-cloud-risk\": {\n reason:\n \"Salesforce Data Cloud behavioral risk for this customer is elevated; B2B purchasing eligibility is held for review.\",\n required_action: \"RISK_REVIEW\",\n },\n};\n\ninterface PipelineEvaluateResponse {\n outcome?: string;\n policy_evaluation?: {\n selected_rule_id?: string | null;\n selected_rule_rationale?: string | null;\n } | null;\n}\n\n/** Salesforce native-surface adapter: fact derivation + deterministic dual-gate evaluation. */\nexport class SalesforceSurface {\n private static readonly PACK_VERSION = salesforceVerticalPack.policy_bundle.version;\n\n /**\n * Derive the boolean/number facts the pack rules match against, from a normalized\n * Salesforce intent payload.\n */\n static deriveFacts(payload: SalesforcePayload, gate: SalesforceGate): Record<string, unknown> {\n const p = SalesforceSurface.normalizePayload(payload);\n const cm = p.customer_master;\n const oh = p.order_header;\n const items = p.order_items;\n const context = p.context;\n\n // ── Gate 1 facts (SAP-compatibility / master-data safety) ──\n // `missing_required_fields` only covers structural gaps without a dedicated rule\n // (an empty order). KUNNR, sales org, MATNR length, and amounts each have their\n // own more-specific rule, so they are intentionally not double-counted here.\n const missingList: string[] = [];\n if (items.length === 0) missingList.push(\"order_items\");\n\n const customerMasterSynced =\n !SalesforceSurface.isBlank(cm.kunnr) && String(cm.kunnr).trim().length > 0;\n const materialNumberOverflow = items.some(\n (it) => String(it.matnr ?? \"\").length > MATNR_MAX_LENGTH,\n );\n const salesOrgValid =\n !SalesforceSurface.isBlank(oh.vkorg) && !SalesforceSurface.isBlank(oh.vtweg);\n const amountsInvalid =\n items.length > 0 &&\n items.some((it) => {\n const net = SalesforceSurface.toFiniteNumber(it.netpr);\n const qty = SalesforceSurface.toFiniteNumber(it.kwmeng);\n return net === null || net <= 0 || qty === null || qty <= 0;\n });\n\n // ── Gate 2 facts (revenue policy) ──\n const orderTotal = items.reduce((sum, it) => {\n const net = SalesforceSurface.toFiniteNumber(it.netpr) ?? 0;\n const qty = SalesforceSurface.toFiniteNumber(it.kwmeng) ?? 0;\n return sum + net * qty;\n }, 0);\n const creditLimit = SalesforceSurface.toFiniteNumber(cm.credit_limit ?? context.credit_limit);\n const overCreditLimit = creditLimit !== null && orderTotal > creditLimit;\n\n // Margin floor: only evaluable for lines that carry an SAP cost basis.\n const marginBelowFloor = items.some((it) => {\n const net = SalesforceSurface.toFiniteNumber(it.netpr);\n const cost = SalesforceSurface.toFiniteNumber(it.cost_basis);\n if (net === null || net <= 0 || cost === null) return false;\n const marginPct = ((net - cost) / net) * 100;\n return marginPct < MARGIN_FLOOR_PCT;\n });\n\n const rating = String(cm.salesforce_account_rating ?? \"\")\n .trim()\n .toLowerCase();\n const manualDiscountViolation =\n rating !== STRATEGIC_RATING &&\n items.some(\n (it) =>\n (SalesforceSurface.toFiniteNumber(it.sf_line_item_discount_pct) ?? 0) >\n MANUAL_DISCOUNT_THRESHOLD_PCT,\n );\n\n const paymentTerms = String(oh.payment_terms ?? \"\").trim();\n const allowedTerms = SalesforceSurface.asStringArray(\n oh.allowed_payment_terms ?? context.allowed_payment_terms,\n );\n const paymentTermsAllowed = !(\n paymentTerms.length > 0 &&\n allowedTerms.length > 0 &&\n !allowedTerms.includes(paymentTerms)\n );\n\n const discountSources = SalesforceSurface.asStringArray(\n context.discount_sources ?? oh.coupon_codes ?? context.applied_coupons,\n );\n const promoStacking = discountSources.length > MAX_DISCOUNT_SOURCES;\n\n // Salesforce Data Cloud behavioral risk signal (0..1) — dynamically gates B2B\n // purchasing eligibility without storing clickstream in the SAP backend.\n const riskScore = SalesforceSurface.toFiniteNumber(\n context.risk_score ?? context.data_cloud_risk_score,\n );\n\n return {\n gate,\n object_type: p.object_type,\n order_total: orderTotal,\n account_rating: rating,\n // Gate 1\n missing_required_fields: missingList.length,\n missing_fields_list: missingList,\n customer_master_synced: customerMasterSynced,\n material_number_overflow: materialNumberOverflow,\n sales_org_valid: salesOrgValid,\n amounts_invalid: amountsInvalid,\n // Gate 2\n over_credit_limit: overCreditLimit,\n margin_below_floor: marginBelowFloor,\n manual_discount_violation: manualDiscountViolation,\n payment_terms_allowed: paymentTermsAllowed,\n promo_stacking: promoStacking,\n risk_score: riskScore,\n risk_elevated: riskScore !== null && riskScore >= RISK_SCORE_THRESHOLD,\n };\n }\n\n /**\n * Evaluate a Salesforce gate deterministically against the vertical pack. No match\n * means every check passed → ALLOW. Highest-priority matched rule wins.\n */\n static evaluateGate(\n payload: SalesforcePayload,\n gate: SalesforceGate,\n extraFacts?: Record<string, unknown>,\n ): SalesforceVerdict {\n const facts = { ...SalesforceSurface.deriveFacts(payload, gate), ...(extraFacts ?? {}) };\n const decisionDomain = SalesforceSurface.decisionDomainForGate(gate);\n\n const matched = salesforceVerticalPack.policy_bundle.rules\n .filter((rule) => rule.enabled)\n .filter((rule) =>\n rule.when.all.every((pred) => SalesforceSurface.matchPredicate(facts, pred)),\n )\n .sort((a, b) => b.priority - a.priority);\n\n const selected = matched[0];\n if (!selected) {\n return {\n decision: \"ALLOW\",\n outcome: \"APPROVE\",\n reason:\n gate === \"state_admission\"\n ? \"Salesforce intent maps cleanly to SAP structures and is eligible for execution review.\"\n : \"Order satisfies revenue policy and may be committed to SAP.\",\n required_action: null,\n decision_domain: decisionDomain,\n rule_id: null,\n gate,\n };\n }\n\n const outcome = SalesforceSurface.outcomeForAction(selected.then.action);\n const meta = RULE_META[selected.rule_id];\n let reason = meta?.reason ?? selected.rationale ?? selected.name;\n if (selected.rule_id === \"state-required-fields\") {\n const list = (facts.missing_fields_list as string[]) ?? [];\n reason = `Salesforce payload is missing required SAP-mapping fields: ${list.join(\", \")}.`;\n }\n\n return {\n decision: OUTCOME_TO_DECISION[outcome],\n outcome,\n reason,\n required_action: meta?.required_action ?? null,\n decision_domain: decisionDomain,\n rule_id: selected.rule_id,\n gate,\n };\n }\n\n /**\n * Idempotency key for a Salesforce gate decision. Scoped to object + gate AND a\n * digest of derived facts, so a genuine retry replays the cached decision while a\n * changed payload re-evaluates.\n */\n static idempotencyKey(payload: SalesforcePayload, gate: SalesforceGate): string {\n const p = SalesforceSurface.normalizePayload(payload);\n const digest = createHash(\"sha256\")\n .update(JSON.stringify(SalesforceSurface.deriveFacts(payload, gate)))\n .digest(\"hex\")\n .slice(0, 24);\n return `salesforce:${p.object_type}:${p.object_id}:${gate}:${digest}`;\n }\n\n /**\n * Build the canonical `evaluate-decision` request body for a Salesforce gate so the\n * decision runs through the shared pipeline (org policy bundle, signed dossier,\n * decision-chain, idempotency). Derived facts live in `context`.\n */\n /**\n * Resolve the gate mode from the payload. Only an explicit \"SHADOW\" (case-insensitive)\n * observes; everything else — including absence — enforces, so the gate fails closed\n * on typos rather than silently passing traffic through.\n */\n static resolveMode(payload: SalesforcePayload): SalesforceMode {\n return String(payload.mode ?? \"\").trim().toUpperCase() === \"SHADOW\"\n ? \"SHADOW\"\n : \"ENFORCEMENT\";\n }\n\n static buildEvaluateRequest(\n payload: SalesforcePayload,\n gate: SalesforceGate,\n orgId: string,\n extraFacts?: Record<string, unknown>,\n ): Record<string, unknown> {\n const facts = { ...SalesforceSurface.deriveFacts(payload, gate), ...(extraFacts ?? {}) };\n const mode = SalesforceSurface.resolveMode(payload);\n // Shadow evaluations get their own idempotency lane so a later ENFORCEMENT call for\n // the same intent is a fresh decision, not a replay of the shadow one. The\n // enforcement key shape is unchanged for continuity with existing decisions.\n const idempotencyKey =\n SalesforceSurface.idempotencyKey(payload, gate) + (mode === \"SHADOW\" ? \":shadow\" : \"\");\n return {\n org_id: orgId,\n decision_type:\n gate === \"state_admission\"\n ? \"salesforce_state_admission\"\n : \"salesforce_execution_authority\",\n vertical_pack: \"salesforce\",\n policy_version: SalesforceSurface.PACK_VERSION,\n mode,\n amount: typeof facts.order_total === \"number\" ? facts.order_total : null,\n idempotency_key: idempotencyKey,\n context: facts,\n };\n }\n\n /**\n * Map a shared-pipeline `EvaluateDecisionResponse` back into the Salesforce verdict\n * shape. The selected rule id (stripped of its `salesforce:` prefix) keys the\n * structured `required_action`.\n */\n static mapPipelineToVerdict(\n response: PipelineEvaluateResponse,\n gate: SalesforceGate,\n ): SalesforceVerdict {\n const outcome = (response.outcome ?? \"REVIEW\") as SalesforceOutcome;\n const rawRuleId = response.policy_evaluation?.selected_rule_id ?? null;\n const ruleId = rawRuleId ? rawRuleId.replace(/^salesforce:/, \"\") : null;\n const meta = ruleId ? RULE_META[ruleId] : undefined;\n const fallbackReason =\n gate === \"state_admission\"\n ? \"Salesforce intent maps cleanly to SAP structures and is eligible for execution review.\"\n : \"Order satisfies revenue policy and may be committed to SAP.\";\n return {\n decision: OUTCOME_TO_DECISION[outcome] ?? \"HOLD\",\n outcome,\n reason: meta?.reason ?? response.policy_evaluation?.selected_rule_rationale ?? fallbackReason,\n required_action: meta?.required_action ?? null,\n decision_domain: SalesforceSurface.decisionDomainForGate(gate),\n rule_id: ruleId,\n gate,\n };\n }\n\n private static normalizePayload(payload: SalesforcePayload): Required<SalesforcePayload> {\n return {\n source_system: payload.source_system ?? \"Salesforce\",\n object_type: payload.object_type ?? \"Order\",\n object_id: payload.object_id ?? \"UNKNOWN\",\n action: payload.action ?? \"SUBMIT_ORDER\",\n mode: SalesforceSurface.resolveMode(payload),\n context: payload.context ?? {},\n customer_master: payload.customer_master ?? {},\n order_header: payload.order_header ?? {},\n order_items: Array.isArray(payload.order_items) ? payload.order_items : [],\n };\n }\n\n private static isBlank(value: unknown): boolean {\n return value === undefined || value === null || value === \"\";\n }\n\n private static toFiniteNumber(value: unknown): number | null {\n if (SalesforceSurface.isBlank(value)) return null;\n const n = Number(value);\n return Number.isFinite(n) ? n : null;\n }\n\n private static asStringArray(value: unknown): string[] {\n if (Array.isArray(value)) return value.map((v) => String(v).trim()).filter(Boolean);\n return [];\n }\n\n /** Minimal predicate matcher mirroring the protocol rule-engine operator semantics. */\n private static matchPredicate(\n facts: Record<string, unknown>,\n pred: VerticalPackRule[\"when\"][\"all\"][number],\n ): boolean {\n const actual = facts[pred.field];\n const expected = pred.value;\n switch (pred.operator) {\n case \"EQ\":\n return actual === expected;\n case \"NEQ\":\n return actual !== expected;\n case \"GT\":\n return Number(actual) > Number(expected);\n case \"GTE\":\n return Number(actual) >= Number(expected);\n case \"LT\":\n return Number(actual) < Number(expected);\n case \"LTE\":\n return Number(actual) <= Number(expected);\n case \"IN\":\n return Array.isArray(pred.values) && pred.values.includes(actual);\n case \"NOT_IN\":\n return Array.isArray(pred.values) && !pred.values.includes(actual);\n case \"EXISTS\":\n return actual !== undefined && actual !== null;\n default:\n return false;\n }\n }\n\n private static outcomeForAction(action: VerticalPackRule[\"then\"][\"action\"]): SalesforceOutcome {\n switch (action) {\n case \"AUTO_REJECT\":\n return \"REJECT\";\n case \"ESCALATE\":\n return \"ESCALATE\";\n case \"AUTO_APPROVE\":\n return \"APPROVE\";\n default:\n return \"REVIEW\"; // REQUIRE_REVIEW | REQUEST_INFO\n }\n }\n\n private static decisionDomainForGate(gate: SalesforceGate): SalesforceVerdict[\"decision_domain\"] {\n return gate === \"state_admission\"\n ? \"SALESFORCE_STATE_ADMISSION\"\n : \"SALESFORCE_EXECUTION_AUTHORITY\";\n }\n}\n\nexport const OUTCOME_TO_DECISION: Record<SalesforceOutcome, SalesforceDecision> = {\n APPROVE: \"ALLOW\",\n REJECT: \"BLOCK\",\n ESCALATE: \"ESCALATE\",\n REVIEW: \"HOLD\",\n};\n\n/** Functional alias for {@link SalesforceSurface.deriveFacts}. */\nexport function deriveSalesforceFacts(\n payload: SalesforcePayload,\n gate: SalesforceGate,\n): Record<string, unknown> {\n return SalesforceSurface.deriveFacts(payload, gate);\n}\n\n/** Functional alias for {@link SalesforceSurface.evaluateGate}. */\nexport function evaluateSalesforceGate(\n payload: SalesforcePayload,\n gate: SalesforceGate,\n extraFacts?: Record<string, unknown>,\n): SalesforceVerdict {\n return SalesforceSurface.evaluateGate(payload, gate, extraFacts);\n}\n\n/** Functional alias for {@link SalesforceSurface.idempotencyKey}. */\nexport function salesforceIdempotencyKey(payload: SalesforcePayload, gate: SalesforceGate): string {\n return SalesforceSurface.idempotencyKey(payload, gate);\n}\n\n/** Functional alias for {@link SalesforceSurface.buildEvaluateRequest}. */\nexport function buildSalesforceEvaluateRequest(\n payload: SalesforcePayload,\n gate: SalesforceGate,\n orgId: string,\n extraFacts?: Record<string, unknown>,\n): Record<string, unknown> {\n return SalesforceSurface.buildEvaluateRequest(payload, gate, orgId, extraFacts);\n}\n\n/** Functional alias for {@link SalesforceSurface.mapPipelineToVerdict}. */\nexport function mapPipelineToSalesforceVerdict(\n response: PipelineEvaluateResponse,\n gate: SalesforceGate,\n): SalesforceVerdict {\n return SalesforceSurface.mapPipelineToVerdict(response, gate);\n}\n\n/** Functional alias for {@link SalesforceSurface.resolveMode}. */\nexport function resolveSalesforceMode(payload: SalesforcePayload): SalesforceMode {\n return SalesforceSurface.resolveMode(payload);\n}\n","/**\n * Live SAP cost-basis reader for the Salesforce margin gate.\n *\n * The Salesforce execution-authority gate checks net margin against the SAP cost of\n * record. Rather than trust the cost a Salesforce payload claims, the protocol\n * reads authoritative material cost from S/4HANA OData and overrides each order\n * line's `cost_basis` before evaluation — so the margin floor is checked against\n * truth. This is the protocol-side counterpart of the Shopify SoR reader.\n *\n * Pure + injectable (`transport`); fail-safe — when no destination is configured or\n * a read fails, the payload's own cost is left in place (the gate degrades to the\n * pre-wiring behavior rather than erroring).\n */\n\nconst FETCH_TIMEOUT_MS = 2500;\n\nconst DEFAULTS = {\n servicePath: \"/sap/opu/odata/sap/API_PRODUCT_SRV\",\n entitySet: \"A_ProductValuationArea\",\n skuProperty: \"Product\",\n costProperty: \"StandardPrice\",\n} as const;\n\nexport interface SapCostConfig {\n baseUrl: string;\n token: string | null;\n servicePath: string;\n entitySet: string;\n skuProperty: string;\n costProperty: string;\n}\n\ntype PerOrgCostOverride = Partial<{\n url: string;\n token: string;\n servicePath: string;\n entitySet: string;\n skuProperty: string;\n costProperty: string;\n}>;\n\nexport type CostTransport = (\n url: string,\n init: { method: string; headers: Record<string, string>; signal?: AbortSignal },\n) => Promise<{ ok: boolean; status: number; json: () => Promise<unknown> }>;\n\n/** S/4HANA OData cost-of-record reader and destination resolution for the margin gate. */\nexport class SapCostBasis {\n /**\n * Resolve the S/4HANA OData cost destination. With `orgId`, a per-org override in\n * `DECIONIS_SAP_SOR_BY_ORG` wins (multi-tenant); otherwise the global env destination\n * is used. Returns null when neither is configured.\n */\n static resolveConfig(env = process.env, orgId?: string | null): SapCostConfig | null {\n const o = SapCostBasis.readPerOrgCostOverride(env, orgId);\n const baseUrl = String(o?.url ?? env.DECIONIS_SAP_SOR_URL ?? \"\").trim();\n if (!baseUrl) return null;\n return {\n baseUrl: baseUrl.replace(/\\/$/, \"\"),\n token: String(o?.token ?? env.DECIONIS_SAP_SOR_TOKEN ?? \"\").trim() || null,\n servicePath: String(\n o?.servicePath ?? env.DECIONIS_SAP_SOR_SERVICE_PATH ?? DEFAULTS.servicePath,\n ).replace(/\\/$/, \"\"),\n entitySet: String(o?.entitySet ?? env.DECIONIS_SAP_SOR_ENTITY ?? DEFAULTS.entitySet),\n skuProperty: String(\n o?.skuProperty ?? env.DECIONIS_SAP_SOR_SKU_PROPERTY ?? DEFAULTS.skuProperty,\n ),\n costProperty: String(\n o?.costProperty ?? env.DECIONIS_SAP_SOR_COST_PROPERTY ?? DEFAULTS.costProperty,\n ),\n };\n }\n\n /** The destination is operator-configured, but require TLS and reject internal hosts. */\n static isSafeUrl(rawUrl: string): boolean {\n let url: URL;\n try {\n url = new URL(rawUrl);\n } catch {\n return false;\n }\n if (url.protocol !== \"https:\") return false;\n const h = url.hostname.toLowerCase().replace(/^\\[|\\]$/g, \"\");\n if (\n h === \"localhost\" ||\n h === \"127.0.0.1\" ||\n h === \"::1\" ||\n h === \"169.254.169.254\" || // cloud metadata\n h.endsWith(\".local\") ||\n h.endsWith(\".internal\") ||\n h.startsWith(\"10.\") ||\n h.startsWith(\"192.168.\") ||\n /^172\\.(1[6-9]|2\\d|3[01])\\./.test(h)\n ) {\n return false;\n }\n return true;\n }\n\n static buildCostQueryUrl(config: SapCostConfig, skus: string[]): string {\n const filter = skus\n .map((sku) => `${config.skuProperty} eq ${SapCostBasis.odataString(sku)}`)\n .join(\" or \");\n const params = new URLSearchParams({\n $select: `${config.skuProperty},${config.costProperty}`,\n $filter: filter,\n $format: \"json\",\n });\n return `${config.baseUrl}${config.servicePath}/${config.entitySet}?${params.toString()}`;\n }\n\n /**\n * Returns SKU → SAP cost (or null when SAP can't confirm it). Every requested SKU\n * is present in the map. Fail-safe: returns all-null on SSRF rejection, missing\n * transport, non-2xx, or error.\n */\n static async fetchCostBasis(\n config: SapCostConfig,\n skus: string[],\n options: { transport?: CostTransport } = {},\n ): Promise<Map<string, number | null>> {\n const result = new Map<string, number | null>();\n const unique = [...new Set(skus.filter(Boolean))];\n for (const sku of unique) result.set(sku, null);\n if (unique.length === 0) return result;\n if (!SapCostBasis.isSafeUrl(config.baseUrl)) return result;\n\n const transport = (options.transport ?? (globalThis.fetch as unknown)) as\n | CostTransport\n | undefined;\n if (!transport) return result;\n\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);\n try {\n const res = await transport(SapCostBasis.buildCostQueryUrl(config, unique), {\n method: \"GET\",\n headers: {\n accept: \"application/json\",\n ...(config.token ? { authorization: `Bearer ${config.token}` } : {}),\n },\n signal: controller.signal,\n });\n if (!res.ok) return result;\n const rows = SapCostBasis.extractRows(await res.json());\n for (const row of rows) {\n const sku = row[config.skuProperty];\n if (typeof sku !== \"string\" || !result.has(sku)) continue;\n const cost = Number(row[config.costProperty]);\n result.set(sku, Number.isFinite(cost) ? cost : null);\n }\n } catch {\n // fail-safe: leave costs null\n } finally {\n clearTimeout(timer);\n }\n return result;\n }\n\n /**\n * Override each order line's `cost_basis` with the SAP cost when available; lines\n * SAP can't confirm keep their existing (payload) cost. Pure.\n */\n static applyCostBasis<\n T extends { order_items?: Array<{ matnr?: string; cost_basis?: number | string }> },\n >(payload: T, costMap: Map<string, number | null>): T {\n const items = Array.isArray(payload.order_items) ? payload.order_items : [];\n return {\n ...payload,\n order_items: items.map((it) => {\n const matnr = String(it.matnr ?? \"\");\n const sapCost = matnr ? costMap.get(matnr) : null;\n return sapCost != null ? { ...it, cost_basis: sapCost } : it;\n }),\n };\n }\n\n /** True when at least one SKU got an authoritative SAP cost. */\n static hasResolvedCost(costMap: Map<string, number | null>): boolean {\n for (const value of costMap.values()) if (value != null) return true;\n return false;\n }\n\n /** Per-org SAP destination override from `DECIONIS_SAP_SOR_BY_ORG` (JSON keyed by org id). */\n private static readPerOrgCostOverride(\n env: Record<string, string | undefined>,\n orgId: string | null | undefined,\n ): PerOrgCostOverride | null {\n if (!orgId) return null;\n const raw = env.DECIONIS_SAP_SOR_BY_ORG;\n if (!raw) return null;\n try {\n const map = JSON.parse(raw);\n const entry = map && typeof map === \"object\" ? map[orgId] : null;\n return entry && typeof entry === \"object\" ? (entry as PerOrgCostOverride) : null;\n } catch {\n return null;\n }\n }\n\n private static odataString(value: string): string {\n return `'${value.replace(/'/g, \"''\")}'`;\n }\n\n /** OData v2 (`d.results`) and v4 (`value`) both supported. */\n private static extractRows(json: unknown): Array<Record<string, unknown>> {\n if (!json || typeof json !== \"object\") return [];\n const v2 = (json as { d?: { results?: unknown } }).d?.results;\n if (Array.isArray(v2)) return v2 as Array<Record<string, unknown>>;\n const v4 = (json as { value?: unknown }).value;\n if (Array.isArray(v4)) return v4 as Array<Record<string, unknown>>;\n return [];\n }\n}\n\n/** Functional alias for {@link SapCostBasis.resolveConfig}. */\nexport function resolveSapCostConfig(\n env = process.env,\n orgId?: string | null,\n): SapCostConfig | null {\n return SapCostBasis.resolveConfig(env, orgId);\n}\n\n/** Functional alias for {@link SapCostBasis.isSafeUrl}. */\nexport function isSafeSapUrl(rawUrl: string): boolean {\n return SapCostBasis.isSafeUrl(rawUrl);\n}\n\n/** Functional alias for {@link SapCostBasis.buildCostQueryUrl}. */\nexport function buildCostQueryUrl(config: SapCostConfig, skus: string[]): string {\n return SapCostBasis.buildCostQueryUrl(config, skus);\n}\n\n/** Functional alias for {@link SapCostBasis.fetchCostBasis}. */\nexport async function fetchSapCostBasis(\n config: SapCostConfig,\n skus: string[],\n options: { transport?: CostTransport } = {},\n): Promise<Map<string, number | null>> {\n return SapCostBasis.fetchCostBasis(config, skus, options);\n}\n\n/** Functional alias for {@link SapCostBasis.applyCostBasis}. */\nexport function applySapCostBasis<\n T extends { order_items?: Array<{ matnr?: string; cost_basis?: number | string }> },\n>(payload: T, costMap: Map<string, number | null>): T {\n return SapCostBasis.applyCostBasis(payload, costMap);\n}\n\n/** Functional alias for {@link SapCostBasis.hasResolvedCost}. */\nexport function hasResolvedCost(costMap: Map<string, number | null>): boolean {\n return SapCostBasis.hasResolvedCost(costMap);\n}\n","import { randomUUID } from \"node:crypto\";\nimport type { FastifyInstance, FastifyReply, FastifyRequest } from \"fastify\";\nimport type { ProtocolPayload, ProtocolStore } from \"../store/StoreContracts.js\";\nimport { validateProtocolArtifact } from \"../validation/ProtocolArtifacts.js\";\nimport { PROTOCOL_VERSION } from \"../ProtocolInfo.js\";\nimport { asRecord, asString, isLikelyUuid } from \"../support/Parsing.js\";\nimport { authenticateMcpRequest, isAuthenticationRequired } from \"../mcp.js\";\nimport type { ProtocolMcpAuthLookup } from \"../auth/McpAuth.js\";\nimport { opsVerticalPack } from \"../verticals/ops/OpsPack.js\";\nimport {\n buildOpsEvaluateRequest,\n deriveOpsDuplicateFacts,\n mapPipelineToOpsVerdict,\n type OpsGate,\n type OpsPayload,\n} from \"../verticals/ops/OpsSurface.js\";\nimport {\n DUPLICATE_LOOKBACK_DAYS,\n OPS_DEFAULT_ORG_ID,\n SAP_VERIFY_BASE_URL,\n} from \"./SurfaceVerifyShared.js\";\n\n// ── Ops / spend-control surface ─────────────────────────────────────────\n// Dual-gate governance for back-office spend (expense approvals, vendor\n// payments, refunds/credits, duplicate-payment detection). Same federation\n// pattern as SAP: each gate routes through the full shared evaluate-decision\n// pipeline and chains a signed decision into the audit ledger. The disbursement\n// gate additionally derives a `duplicate_suspected` fact from a store lookback.\n\n/** Registers the ops dual-gate verification routes (spend admission + disbursement authority). */\nexport function registerOpsVerifyRoutes(\n app: FastifyInstance,\n deps: { store: ProtocolStore; authLookup: ProtocolMcpAuthLookup | null },\n): void {\n const { store } = deps;\n const protocolAuthLookup = deps.authLookup ?? null;\n\n const ensureOpsPolicyBundle = async (orgId: string) => {\n const bundles = await store.listPolicyBundles({ orgId, limit: 50 });\n if (bundles.some((bundle) => bundle.version === opsVerticalPack.policy_bundle.version)) return;\n const bundlePayload: ProtocolPayload = {\n protocol_version: PROTOCOL_VERSION,\n bundle_id: randomUUID(),\n org_id: orgId,\n version: opsVerticalPack.policy_bundle.version,\n effective_from: new Date(Date.now() - 60_000).toISOString(),\n rules: opsVerticalPack.policy_bundle.rules.map((rule) => ({\n ...rule,\n rule_id: `ops:${rule.rule_id}`,\n })),\n metadata: {\n author: \"decionis-ops-adapter\",\n source: \"protocol_service\",\n change_ticket: \"ops-spend-control\",\n },\n };\n const validation = validateProtocolArtifact(\"policy_bundle\", bundlePayload);\n if (validation.ok) await store.saveArtifact(\"policy_bundle\", validation.value);\n };\n\n const handleOpsGate = async (gate: OpsGate, req: FastifyRequest, reply: FastifyReply) => {\n const authCtx = await authenticateMcpRequest(req, protocolAuthLookup);\n if (isAuthenticationRequired(protocolAuthLookup) && !authCtx) {\n return reply.code(401).send({\n error: \"UNAUTHORIZED\",\n message: \"Valid API key required for ops governance routes\",\n });\n }\n\n const payload = (req.body ?? {}) as OpsPayload;\n const ctx = asRecord(payload.context);\n const authedOrgId = authCtx && authCtx.kind === \"org_api_key\" ? authCtx.org_id : null;\n const candidateOrg =\n authedOrgId ||\n asString(ctx.org_id)?.trim() ||\n process.env.DECIONIS_OPS_ORG_ID?.trim() ||\n OPS_DEFAULT_ORG_ID;\n const orgId = isLikelyUuid(candidateOrg) ? candidateOrg : OPS_DEFAULT_ORG_ID;\n\n await ensureOpsPolicyBundle(orgId);\n\n // The disbursement gate gets the stateful duplicate-payment fact from a\n // store lookback; the admission gate is purely declarative.\n let extraFacts: Record<string, unknown> | undefined;\n if (gate === \"disbursement_authority\") {\n const since = new Date(Date.now() - DUPLICATE_LOOKBACK_DAYS * 24 * 60 * 60 * 1000);\n extraFacts = await deriveOpsDuplicateFacts({ store, orgId, payload, since });\n }\n\n const evalRes = await app.inject({\n method: \"POST\",\n url: \"/v1/protocol/evaluate-decision\",\n payload: buildOpsEvaluateRequest(payload, gate, orgId, extraFacts),\n });\n if (evalRes.statusCode !== 200) {\n return reply.code(502).send({\n error: \"OPS_PIPELINE_FAILED\",\n message: \"The shared evaluate-decision pipeline rejected the ops request.\",\n status: evalRes.statusCode,\n });\n }\n\n const response = evalRes.json() as {\n outcome?: string;\n dossier_id?: string;\n dossier_sha256?: string | null;\n decision_resolution_id?: string | null;\n evaluation_id?: string | null;\n ledger_entry_id?: string | null;\n ledger_entry_hash?: string | null;\n policy_version?: string;\n decision_chain?: unknown;\n idempotent_replay?: boolean;\n policy_evaluation?: {\n selected_rule_id?: string | null;\n selected_rule_rationale?: string | null;\n } | null;\n };\n const verdict = mapPipelineToOpsVerdict(response, gate);\n const dossierId = response.dossier_id ?? null;\n const verificationUrl = dossierId\n ? `${process.env.DECIONIS_VERIFY_BASE_URL ?? SAP_VERIFY_BASE_URL}/${dossierId}`\n : null;\n\n return reply.code(200).send({\n decision: verdict.decision,\n reason: verdict.reason,\n required_action: verdict.required_action,\n gate,\n decision_domain: verdict.decision_domain,\n rule_id: verdict.rule_id,\n outcome: verdict.outcome,\n duplicate_suspected: Boolean(extraFacts?.duplicate_suspected),\n policy_version: response.policy_version ?? opsVerticalPack.policy_bundle.version,\n dossier_id: dossierId,\n dossier_sha256: response.dossier_sha256 ?? null,\n dossier_hash: response.dossier_sha256 ? `sha256:${response.dossier_sha256}` : null,\n verification_url: verificationUrl,\n org_id: orgId,\n decision_resolution_id: response.decision_resolution_id ?? null,\n evaluation_id: response.evaluation_id ?? null,\n ledger_entry_id: response.ledger_entry_id ?? null,\n ledger_entry_hash: response.ledger_entry_hash ?? null,\n decision_chain: response.decision_chain ?? null,\n idempotent_replay: Boolean(response.idempotent_replay),\n federated: true,\n pipeline: true,\n });\n };\n\n app.post(\"/ops/spend-admission/verify\", (req, reply) =>\n handleOpsGate(\"spend_admission\", req, reply),\n );\n app.post(\"/v1/protocol/ops/spend-admission/verify\", (req, reply) =>\n handleOpsGate(\"spend_admission\", req, reply),\n );\n app.post(\"/ops/disbursement-authority/verify\", (req, reply) =>\n handleOpsGate(\"disbursement_authority\", req, reply),\n );\n app.post(\"/v1/protocol/ops/disbursement-authority/verify\", (req, reply) =>\n handleOpsGate(\"disbursement_authority\", req, reply),\n );\n}\n","import { createHash } from \"node:crypto\";\n\nimport {\n RULE_META,\n OUTCOME_TO_DECISION,\n OPS_PACK_VERSION,\n deriveOpsFacts,\n decisionDomainForGate,\n cleanOpsReason,\n normalizeOpsPayload,\n type OpsGate,\n type OpsOutcome,\n type OpsPayload,\n type OpsVerdict,\n} from \"@decionis/shared/verticals\";\nimport {\n deriveDuplicateFacts,\n duplicateFingerprintFromContext,\n type DuplicateFacts,\n type DuplicateLookbackStore,\n} from \"../shared/DuplicateDetection.js\";\n\n/**\n * Ops / spend-control surface adapter. The pure pieces — the dual-gate types, fact\n * derivation, and the deterministic `evaluateOpsGate` — now live in\n * `@decionis/shared/verticals` (one source of truth with apps/api's inline procurement\n * dual-gate) and are re-exported below for back-compat. What stays here is the\n * surface-specific, non-isomorphic work: the idempotency key + the store-backed\n * duplicate-detection pass that injects `duplicate_suspected` before evaluation.\n */\n\n// Re-export the pure ops dual-gate surface so existing imports from \"./OpsSurface.js\"\n// keep working unchanged.\nexport {\n RULE_META,\n OUTCOME_TO_DECISION,\n deriveOpsFacts,\n evaluateOpsGate,\n} from \"@decionis/shared/verticals\";\nexport type {\n OpsGate,\n OpsDecision,\n OpsOutcome,\n OpsPayload,\n OpsVerdict,\n} from \"@decionis/shared/verticals\";\n\ninterface PipelineEvaluateResponse {\n outcome?: string;\n policy_evaluation?: {\n selected_rule_id?: string | null;\n selected_rule_rationale?: string | null;\n } | null;\n}\n\n/** Surface-specific ops gate adapter: pipeline request/verdict mapping + duplicate pass. */\nexport class OpsSurface {\n /**\n * Build the canonical `evaluate-decision` request body for an ops gate so the decision\n * runs through the full shared pipeline. Derived facts (plus any `extraFacts`, e.g.\n * `duplicate_suspected` from the store lookback) live in `context`; `policy_version`\n * pins the ops bundle. The idempotency key is derived from the payload only (NOT the\n * duplicate fact) so a genuine retry of the same disbursement replays the cached\n * decision.\n */\n static buildEvaluateRequest(\n payload: OpsPayload,\n gate: OpsGate,\n orgId: string,\n extraFacts?: Record<string, unknown>,\n ): Record<string, unknown> {\n const facts = { ...deriveOpsFacts(payload, gate), ...(extraFacts ?? {}) };\n return {\n org_id: orgId,\n decision_type:\n gate === \"spend_admission\" ? \"ops_spend_admission\" : \"ops_disbursement_authority\",\n vertical_pack: \"ops\",\n policy_version: OPS_PACK_VERSION,\n mode: \"ENFORCEMENT\",\n amount: typeof facts.amount === \"number\" ? facts.amount : null,\n idempotency_key: OpsSurface.idempotencyKey(payload, gate),\n context: facts,\n };\n }\n\n /** Map a shared-pipeline response back into the ops verdict shape. */\n static mapPipelineToVerdict(response: PipelineEvaluateResponse, gate: OpsGate): OpsVerdict {\n const outcome = (response.outcome ?? \"REVIEW\") as OpsOutcome;\n const rawRuleId = response.policy_evaluation?.selected_rule_id ?? null;\n const ruleId = rawRuleId ? rawRuleId.replace(/^ops:/, \"\") : null;\n const meta = ruleId ? RULE_META[ruleId] : undefined;\n return {\n decision: OUTCOME_TO_DECISION[outcome] ?? \"DELAY\",\n outcome,\n reason:\n meta?.reason ?? response.policy_evaluation?.selected_rule_rationale ?? cleanOpsReason(gate),\n required_action: meta?.required_action ?? null,\n decision_domain: decisionDomainForGate(gate),\n rule_id: ruleId,\n gate,\n };\n }\n\n /**\n * Idempotency key for an ops gate decision. Scoped to object + gate AND a digest of the\n * derived facts (NOT the duplicate fact), so a genuine retry of the same payment replays\n * the cached decision while a changed payment re-evaluates.\n */\n static idempotencyKey(payload: OpsPayload, gate: OpsGate): string {\n const p = normalizeOpsPayload(payload);\n const digest = createHash(\"sha256\")\n .update(JSON.stringify(deriveOpsFacts(payload, gate)))\n .digest(\"hex\")\n .slice(0, 24);\n return `ops:${p.object_type}:${p.object_id}:${gate}:${digest}`;\n }\n\n /**\n * Derive the stateful `duplicate_suspected` fact for a disbursement by comparing the\n * payment's vendor+invoice/amount fingerprint against prior org evaluations. Delegates\n * to the shared `deriveDuplicateFacts` (reused by the SAP surface).\n */\n static async deriveDuplicateFacts(input: {\n store: DuplicateLookbackStore;\n orgId: string;\n payload: OpsPayload;\n since?: Date | null;\n limit?: number;\n }): Promise<DuplicateFacts> {\n return deriveDuplicateFacts({\n store: input.store,\n orgId: input.orgId,\n currentKey: OpsSurface.idempotencyKey(input.payload, \"disbursement_authority\"),\n fingerprint: duplicateFingerprintFromContext(\n deriveOpsFacts(input.payload, \"disbursement_authority\"),\n ),\n since: input.since,\n limit: input.limit,\n });\n }\n}\n\n/** Functional alias for {@link OpsSurface.buildEvaluateRequest}. */\nexport function buildOpsEvaluateRequest(\n payload: OpsPayload,\n gate: OpsGate,\n orgId: string,\n extraFacts?: Record<string, unknown>,\n): Record<string, unknown> {\n return OpsSurface.buildEvaluateRequest(payload, gate, orgId, extraFacts);\n}\n\n/** Functional alias for {@link OpsSurface.mapPipelineToVerdict}. */\nexport function mapPipelineToOpsVerdict(\n response: PipelineEvaluateResponse,\n gate: OpsGate,\n): OpsVerdict {\n return OpsSurface.mapPipelineToVerdict(response, gate);\n}\n\n/** Functional alias for {@link OpsSurface.idempotencyKey}. */\nexport function opsIdempotencyKey(payload: OpsPayload, gate: OpsGate): string {\n return OpsSurface.idempotencyKey(payload, gate);\n}\n\n/** Vendor + invoice/amount fingerprint for duplicate-payment detection, or null.\n * Re-exported from the shared helper for back-compat. */\nexport const opsDuplicateFingerprint = duplicateFingerprintFromContext;\n\n/** Functional alias for {@link OpsSurface.deriveDuplicateFacts}. */\nexport async function deriveOpsDuplicateFacts(input: {\n store: DuplicateLookbackStore;\n orgId: string;\n payload: OpsPayload;\n since?: Date | null;\n limit?: number;\n}): Promise<DuplicateFacts> {\n return OpsSurface.deriveDuplicateFacts(input);\n}\n","import { randomUUID } from \"node:crypto\";\nimport type { FastifyInstance, FastifyReply, FastifyRequest } from \"fastify\";\nimport type { ProtocolPayload, ProtocolStore } from \"../store/StoreContracts.js\";\nimport { validateProtocolArtifact } from \"../validation/ProtocolArtifacts.js\";\nimport { PROTOCOL_VERSION } from \"../ProtocolInfo.js\";\nimport { asRecord, asString, isLikelyUuid } from \"../support/Parsing.js\";\nimport { authenticateMcpRequest, isAuthenticationRequired } from \"../mcp.js\";\nimport type { ProtocolMcpAuthLookup } from \"../auth/McpAuth.js\";\nimport { workdayVerticalPack } from \"../verticals/workday/WorkdayPack.js\";\nimport {\n buildWorkdayEvaluateRequest,\n deriveWorkdayDuplicateFacts,\n mapPipelineToWorkdayVerdict,\n type WorkdayGate,\n type WorkdayPayload,\n} from \"../verticals/workday/WorkdaySurface.js\";\nimport {\n DUPLICATE_LOOKBACK_DAYS,\n SAP_VERIFY_BASE_URL,\n WORKDAY_DEFAULT_ORG_ID,\n} from \"./SurfaceVerifyShared.js\";\n\n// ── Workday HR surface (federates Workday HCM into the shared engine) ─────────\n// A Workday Studio/Extend callback (or middleware) calls these two paths before\n// committing a business process. Each computes a deterministic verdict via the\n// Workday vertical pack and chains a signed decision into the shared audit\n// ledger, returning the verdict shape the Workday-side workflow expects.\n\n/** Registers the Workday HR dual-gate verification routes (state admission + execution authority). */\nexport function registerWorkdayVerifyRoutes(\n app: FastifyInstance,\n deps: { store: ProtocolStore; authLookup: ProtocolMcpAuthLookup | null },\n): void {\n const { store } = deps;\n const protocolAuthLookup = deps.authLookup ?? null;\n\n // Seed the org's policy bundle from the Workday pack (idempotent) so the shared\n // evaluate-decision pipeline has a \"ready\" policy guard for Workday requests.\n const ensureWorkdayPolicyBundle = async (orgId: string) => {\n const bundles = await store.listPolicyBundles({ orgId, limit: 50 });\n if (bundles.some((bundle) => bundle.version === workdayVerticalPack.policy_bundle.version)) {\n return;\n }\n const bundlePayload: ProtocolPayload = {\n protocol_version: PROTOCOL_VERSION,\n bundle_id: randomUUID(),\n org_id: orgId,\n version: workdayVerticalPack.policy_bundle.version,\n effective_from: new Date(Date.now() - 60_000).toISOString(),\n rules: workdayVerticalPack.policy_bundle.rules.map((rule) => ({\n ...rule,\n rule_id: `workday:${rule.rule_id}`,\n })),\n metadata: {\n author: \"decionis-workday-adapter\",\n source: \"protocol_service\",\n change_ticket: \"workday-federation\",\n },\n };\n const validation = validateProtocolArtifact(\"policy_bundle\", bundlePayload);\n if (validation.ok) await store.saveArtifact(\"policy_bundle\", validation.value);\n };\n\n const handleWorkdayGate = async (gate: WorkdayGate, req: FastifyRequest, reply: FastifyReply) => {\n // Auth — enforced only when the protocol has auth configured (env breakglass\n // key, custom header, or org-API-key lookup); open in unconfigured dev/test.\n const authCtx = await authenticateMcpRequest(req, protocolAuthLookup);\n if (isAuthenticationRequired(protocolAuthLookup) && !authCtx) {\n return reply.code(401).send({\n error: \"UNAUTHORIZED\",\n message: \"Valid API key required for Workday governance routes\",\n });\n }\n\n const payload = (req.body ?? {}) as WorkdayPayload;\n\n // Tenant seam → org. The full pipeline requires a UUID org id; an\n // authenticated org-API key wins, then a request org_id, env, default.\n const ctx = asRecord(payload.context);\n const authedOrgId = authCtx && authCtx.kind === \"org_api_key\" ? authCtx.org_id : null;\n const candidateOrg =\n authedOrgId ||\n asString(ctx.org_id)?.trim() ||\n process.env.DECIONIS_WORKDAY_ORG_ID?.trim() ||\n WORKDAY_DEFAULT_ORG_ID;\n const orgId = isLikelyUuid(candidateOrg) ? candidateOrg : WORKDAY_DEFAULT_ORG_ID;\n\n // Route through the FULL shared evaluate-decision pipeline in-process: org\n // policy-bundle evaluation, Ed25519-signed dossier, decision-chain lineage,\n // audit ledger, and idempotency replay — all reused, no logic duplicated.\n await ensureWorkdayPolicyBundle(orgId);\n\n // Gate 2 (execution authority) gets the stateful duplicate-process fact from a\n // store lookback (same worker + process + effective date); Gate 1 is declarative.\n let extraFacts: Record<string, unknown> | undefined;\n if (gate === \"execution_authority\") {\n const since = new Date(Date.now() - DUPLICATE_LOOKBACK_DAYS * 24 * 60 * 60 * 1000);\n extraFacts = await deriveWorkdayDuplicateFacts({ store, orgId, payload, since });\n }\n\n const evalRes = await app.inject({\n method: \"POST\",\n url: \"/v1/protocol/evaluate-decision\",\n payload: buildWorkdayEvaluateRequest(payload, gate, orgId, extraFacts),\n });\n if (evalRes.statusCode !== 200) {\n return reply.code(502).send({\n error: \"WORKDAY_PIPELINE_FAILED\",\n message: \"The shared evaluate-decision pipeline rejected the Workday request.\",\n status: evalRes.statusCode,\n });\n }\n\n const response = evalRes.json() as {\n outcome?: string;\n dossier_id?: string;\n dossier_sha256?: string | null;\n decision_resolution_id?: string | null;\n evaluation_id?: string | null;\n ledger_entry_id?: string | null;\n ledger_entry_hash?: string | null;\n policy_version?: string;\n decision_chain?: unknown;\n idempotent_replay?: boolean;\n policy_evaluation?: {\n selected_rule_id?: string | null;\n selected_rule_rationale?: string | null;\n } | null;\n };\n const verdict = mapPipelineToWorkdayVerdict(response, gate);\n const dossierId = response.dossier_id ?? null;\n const verificationUrl = dossierId\n ? `${process.env.DECIONIS_VERIFY_BASE_URL ?? SAP_VERIFY_BASE_URL}/${dossierId}`\n : null;\n\n return reply.code(200).send({\n decision: verdict.decision,\n reason: verdict.reason,\n required_action: verdict.required_action,\n gate,\n decision_domain: verdict.decision_domain,\n rule_id: verdict.rule_id,\n outcome: verdict.outcome,\n duplicate_suspected: Boolean(extraFacts?.duplicate_suspected),\n policy_version: response.policy_version ?? workdayVerticalPack.policy_bundle.version,\n dossier_id: dossierId,\n dossier_sha256: response.dossier_sha256 ?? null,\n dossier_hash: response.dossier_sha256 ? `sha256:${response.dossier_sha256}` : null,\n verification_url: verificationUrl,\n org_id: orgId,\n decision_resolution_id: response.decision_resolution_id ?? null,\n evaluation_id: response.evaluation_id ?? null,\n ledger_entry_id: response.ledger_entry_id ?? null,\n ledger_entry_hash: response.ledger_entry_hash ?? null,\n decision_chain: response.decision_chain ?? null,\n idempotent_replay: Boolean(response.idempotent_replay),\n federated: true,\n pipeline: true,\n });\n };\n\n app.post(\"/workday/state-admission/verify\", (req, reply) =>\n handleWorkdayGate(\"state_admission\", req, reply),\n );\n app.post(\"/v1/protocol/workday/state-admission/verify\", (req, reply) =>\n handleWorkdayGate(\"state_admission\", req, reply),\n );\n app.post(\"/workday/execution-authority/verify\", (req, reply) =>\n handleWorkdayGate(\"execution_authority\", req, reply),\n );\n app.post(\"/v1/protocol/workday/execution-authority/verify\", (req, reply) =>\n handleWorkdayGate(\"execution_authority\", req, reply),\n );\n}\n","import { createHash } from \"node:crypto\";\n\nimport { workdayVerticalPack } from \"./WorkdayPack.js\";\nimport type { VerticalPackRule } from \"../VerticalContracts.js\";\nimport type { DuplicateFacts, DuplicateLookbackStore } from \"../shared/DuplicateDetection.js\";\n\n/**\n * Workday HR surface adapter — the concrete implementation of the native-surface\n * contract for Workday HCM. Surface-specific work is normalization + derivation;\n * the decision logic is the declarative `workdayVerticalPack`. This module is\n * pure (no I/O, no store) so it is fully unit-testable and deterministic, and it\n * is the source of truth the protocol `/workday/*` routes call.\n *\n * A Workday payload is a business process (Termination, CompensationChange,\n * JobChange, Hire, …) with a `proposed_state` (worker, effective date, reason,\n * salary), an `actor` (role), and a `context` (approvals, offboarding, region).\n * `deriveFacts` normalizes those into the boolean/number facts the pack matches.\n */\n\nexport type WorkdayGate = \"state_admission\" | \"execution_authority\";\nexport type WorkdayDecision = \"ALLOW\" | \"BLOCK\" | \"ESCALATE\" | \"DELAY\";\nexport type WorkdayOutcome = \"APPROVE\" | \"REJECT\" | \"ESCALATE\" | \"REVIEW\";\n\nexport interface WorkdayPayload {\n source_system?: string;\n /** The Workday business process type, e.g. \"Termination\", \"CompensationChange\". */\n object_type?: string;\n object_id?: string;\n action?: string;\n proposed_state?: Record<string, unknown>;\n actor?: Record<string, unknown>;\n context?: Record<string, unknown>;\n}\n\nexport interface WorkdayVerdict {\n decision: WorkdayDecision;\n outcome: WorkdayOutcome;\n reason: string;\n required_action: string | null;\n decision_domain: \"WORKDAY_HR_STATE_ADMISSION\" | \"WORKDAY_HR_EXECUTION_AUTHORITY\";\n rule_id: string | null;\n gate: WorkdayGate;\n}\n\n/** Roles allowed to execute a governed Workday HR business process. */\nconst AUTHORIZED_HR_ROLES = new Set([\n \"HRBusinessPartner\",\n \"HRPartner\",\n \"CompensationPartner\",\n \"HRDirector\",\n \"PeopleOpsAdmin\",\n \"CHRO\",\n]);\n/** Compensation-change guardrails: escalate a >15% raise or one landing above the cap. */\nconst COMP_INCREASE_THRESHOLD = 0.15;\nconst COMP_ABSOLUTE_THRESHOLD = 250000;\n/** Regions where a works-council consultation is required before a termination executes. */\nconst WORKS_COUNCIL_REGIONS = new Set([\"EU\", \"DE\", \"FR\", \"NL\", \"AT\", \"BE\", \"IT\", \"ES\"]);\n\n/** Per-rule reason + structured required-action, kept out of the declarative pack. */\nexport const RULE_META: Record<string, { reason: string; required_action: string }> = {\n \"state-required-fields\": {\n reason: \"Required Workday HR state fields are missing.\",\n required_action: \"COMPLETE_SOURCE_STATE\",\n },\n \"state-effective-date-valid\": {\n reason: \"The business process effective date must be a valid calendar date.\",\n required_action: \"CORRECT_EFFECTIVE_DATE\",\n },\n \"state-worker-active\": {\n reason: \"Worker record is terminated or inactive and cannot receive this process.\",\n required_action: \"VERIFY_WORKER_RECORD\",\n },\n \"state-termination-reason\": {\n reason: \"A termination must specify a reason code before it can be admitted.\",\n required_action: \"PROVIDE_TERMINATION_REASON\",\n },\n \"state-compensation-structured\": {\n reason: \"A compensation change must reference a salary band or documented pay structure.\",\n required_action: \"ATTACH_COMPENSATION_STRUCTURE\",\n },\n \"exec-duplicate-process\": {\n reason: \"A prior business process with the same worker + type + effective date was found.\",\n required_action: \"DUPLICATE_PROCESS_REVIEW\",\n },\n \"exec-authorized-role\": {\n reason: \"Actor role is not authorized to execute governed Workday HR processes.\",\n required_action: \"AUTHORIZED_HR_ROLE\",\n },\n \"exec-segregation-of-duties\": {\n reason: \"Segregation-of-duties check failed because the initiator and approver match.\",\n required_action: \"SEGREGATION_OF_DUTIES_REVIEW\",\n },\n \"exec-compensation-threshold\": {\n reason: \"Compensation change exceeds the policy threshold and committee approval is missing.\",\n required_action: \"COMPENSATION_COMMITTEE_APPROVAL\",\n },\n \"exec-pay-equity\": {\n reason: \"An adverse-impact / pay-equity signal is open on this compensation change.\",\n required_action: \"PAY_EQUITY_REVIEW\",\n },\n \"exec-termination-offboarding\": {\n reason: \"Termination has no confirmed access-revocation / offboarding plan.\",\n required_action: \"COORDINATE_ACCESS_REVOCATION\",\n },\n \"exec-works-council-hold\": {\n reason: \"A regional works-council consultation is required before this action can execute.\",\n required_action: \"WORKS_COUNCIL_CONSULTATION\",\n },\n};\n\nconst REQUIRED_STATE_FIELDS = [\"worker_id\", \"effective_date\"] as const;\n\ninterface PipelineEvaluateResponse {\n outcome?: string;\n policy_evaluation?: {\n selected_rule_id?: string | null;\n selected_rule_rationale?: string | null;\n } | null;\n}\n\n/** Workday HR native-surface adapter: fact derivation + deterministic dual-gate evaluation. */\nexport class WorkdaySurface {\n private static readonly PACK_VERSION = workdayVerticalPack.policy_bundle.version;\n\n /**\n * Derive the boolean/number facts the pack rules match against. Deterministic\n * (no wall-clock reads): effective-date validity is structural, and the\n * stateful `duplicate_suspected` fact is supplied by the route via `extraFacts`.\n */\n static deriveFacts(payload: WorkdayPayload, gate: WorkdayGate): Record<string, unknown> {\n const p = WorkdaySurface.normalizePayload(payload);\n const state = p.proposed_state;\n const context = p.context;\n const actor = p.actor;\n\n const businessProcess = p.object_type;\n const isTermination = /termination|offboard/i.test(businessProcess);\n const isCompensationChange =\n /compensation|comp\\s*change|merit|pay\\s*change/i.test(businessProcess) ||\n !WorkdaySurface.isBlank(state.new_salary) ||\n !WorkdaySurface.isBlank(state.proposed_salary);\n\n const missingList = [\n ...REQUIRED_STATE_FIELDS.filter((f) => WorkdaySurface.isBlank(state[f])),\n ...(WorkdaySurface.isBlank(businessProcess) ? ([\"business_process\"] as const) : []),\n ...(WorkdaySurface.isBlank(context.initiated_by) ? ([\"initiated_by\"] as const) : []),\n ];\n\n const workerStatus = String(state.worker_status ?? \"ACTIVE\").toUpperCase();\n const region = String(state.region ?? context.region ?? \"\").toUpperCase();\n\n const structuredCriteriaUsed =\n context.structured_criteria_used === true ||\n !WorkdaySurface.isBlank(state.salary_band) ||\n !WorkdaySurface.isBlank(state.pay_range) ||\n !WorkdaySurface.isBlank(state.compensation_grade);\n\n const compOverThreshold = WorkdaySurface.isCompensationOverThreshold(state);\n\n return {\n gate,\n business_process: businessProcess,\n worker_id: state.worker_id ?? null,\n effective_date: state.effective_date ?? null,\n is_termination: isTermination,\n compensation_change: isCompensationChange,\n // Overridden by the store-backed duplicate pass; safe default for pure eval.\n duplicate_suspected: false,\n // Gate 1\n missing_required_fields: missingList.length,\n missing_fields_list: missingList,\n effective_date_invalid: WorkdaySurface.isEffectiveDateInvalid(state.effective_date),\n worker_actionable: workerStatus !== \"TERMINATED\" && workerStatus !== \"INACTIVE\",\n termination_reason_missing: isTermination && WorkdaySurface.isBlank(state.reason_code),\n structured_criteria_used: structuredCriteriaUsed,\n // Gate 2\n actor_role: String(actor.role ?? \"\"),\n actor_authorized: AUTHORIZED_HR_ROLES.has(String(actor.role ?? \"\")),\n sod_violation:\n !WorkdaySurface.isBlank(context.initiated_by) &&\n !WorkdaySurface.isBlank(context.approved_by) &&\n String(context.initiated_by) === String(context.approved_by),\n compensation_over_threshold: compOverThreshold,\n compensation_committee_approved: WorkdaySurface.hasCommitteeApproval(context),\n pay_equity_flagged: context.pay_equity_flag === true || context.adverse_impact === true,\n pay_equity_cleared: context.pay_equity_cleared === true,\n offboarding_ready:\n context.offboarding_ready === true || context.access_revocation_scheduled === true,\n works_council_hold:\n isTermination &&\n WORKS_COUNCIL_REGIONS.has(region) &&\n context.works_council_cleared !== true,\n };\n }\n\n /**\n * Build the canonical `evaluate-decision` request body for a Workday gate so\n * the decision runs through the full shared pipeline (org policy bundle, signed\n * dossier, decision-chain, idempotency). The derived facts live in `context`,\n * which the engine spreads into the rule-matching facts; `policy_version` pins\n * the Workday bundle so it is selected even when the org has other bundles.\n */\n static buildEvaluateRequest(\n payload: WorkdayPayload,\n gate: WorkdayGate,\n orgId: string,\n extraFacts?: Record<string, unknown>,\n ): Record<string, unknown> {\n const facts = { ...WorkdaySurface.deriveFacts(payload, gate), ...(extraFacts ?? {}) };\n return {\n org_id: orgId,\n decision_type:\n gate === \"state_admission\"\n ? \"workday_hr_state_admission\"\n : \"workday_hr_execution_authority\",\n vertical_pack: \"workday\",\n policy_version: WorkdaySurface.PACK_VERSION,\n mode: \"ENFORCEMENT\",\n idempotency_key: WorkdaySurface.idempotencyKey(payload, gate),\n context: facts,\n };\n }\n\n /**\n * Map a shared-pipeline `EvaluateDecisionResponse` back into the Workday verdict\n * shape the connector consumes. The selected rule id (stripped of its `workday:`\n * prefix) keys the structured `required_action`; the reason prefers the static\n * rule text and falls back to the rule rationale the engine returned.\n */\n static mapPipelineToVerdict(\n response: PipelineEvaluateResponse,\n gate: WorkdayGate,\n ): WorkdayVerdict {\n const outcome = (response.outcome ?? \"REVIEW\") as WorkdayOutcome;\n const rawRuleId = response.policy_evaluation?.selected_rule_id ?? null;\n const ruleId = rawRuleId ? rawRuleId.replace(/^workday:/, \"\") : null;\n const meta = ruleId ? RULE_META[ruleId] : undefined;\n return {\n decision: OUTCOME_TO_DECISION[outcome] ?? \"DELAY\",\n outcome,\n reason:\n meta?.reason ??\n response.policy_evaluation?.selected_rule_rationale ??\n WorkdaySurface.cleanReason(gate),\n required_action: meta?.required_action ?? null,\n decision_domain: WorkdaySurface.decisionDomainForGate(gate),\n rule_id: ruleId,\n gate,\n };\n }\n\n /**\n * Evaluate a Workday gate deterministically against the Workday vertical pack.\n * No match means every check passed → ALLOW. Highest-priority matched rule wins,\n * reproducing the gates' short-circuit order.\n */\n static evaluateGate(\n payload: WorkdayPayload,\n gate: WorkdayGate,\n extraFacts?: Record<string, unknown>,\n ): WorkdayVerdict {\n const facts = { ...WorkdaySurface.deriveFacts(payload, gate), ...(extraFacts ?? {}) };\n const decisionDomain = WorkdaySurface.decisionDomainForGate(gate);\n\n const matched = workdayVerticalPack.policy_bundle.rules\n .filter((rule) => rule.enabled)\n .filter((rule) => rule.when.all.every((pred) => WorkdaySurface.matchPredicate(facts, pred)))\n .sort((a, b) => b.priority - a.priority);\n\n const selected = matched[0];\n if (!selected) {\n return {\n decision: \"ALLOW\",\n outcome: \"APPROVE\",\n reason: WorkdaySurface.cleanReason(gate),\n required_action: null,\n decision_domain: decisionDomain,\n rule_id: null,\n gate,\n };\n }\n\n const outcome = WorkdaySurface.outcomeForAction(selected.then.action);\n const meta = RULE_META[selected.rule_id];\n let reason = meta?.reason ?? selected.rationale ?? selected.name;\n // Enrich the missing-fields reason with the concrete field list, without\n // putting dynamic text in the declarative pack.\n if (selected.rule_id === \"state-required-fields\") {\n const list = (facts.missing_fields_list as string[]) ?? [];\n reason = `Required Workday HR state fields are missing: ${list.join(\", \")}.`;\n } else if (selected.rule_id === \"exec-authorized-role\") {\n reason = `Actor role ${String(facts.actor_role) || \"UNKNOWN\"} is not authorized to execute governed Workday HR processes.`;\n }\n\n return {\n decision: OUTCOME_TO_DECISION[outcome],\n outcome,\n reason,\n required_action: meta?.required_action ?? null,\n decision_domain: decisionDomain,\n rule_id: selected.rule_id,\n gate,\n };\n }\n\n /**\n * Idempotency key for a Workday gate decision. Scoped to worker + process +\n * gate AND a digest of the derived facts, so a genuine retry of the *same*\n * state replays the cached decision while a changed state (e.g. an approval was\n * added) re-evaluates instead of returning a stale verdict.\n */\n static idempotencyKey(payload: WorkdayPayload, gate: WorkdayGate): string {\n const p = WorkdaySurface.normalizePayload(payload);\n const digest = createHash(\"sha256\")\n .update(JSON.stringify(WorkdaySurface.deriveFacts(payload, gate)))\n .digest(\"hex\")\n .slice(0, 24);\n return `workday:${p.object_type}:${p.object_id}:${gate}:${digest}`;\n }\n\n /**\n * Stable fingerprint for duplicate-process detection: same worker + business\n * process + effective date. Null when the worker is unknown (nothing to match).\n */\n static duplicateFingerprint(facts: Record<string, unknown>): string | null {\n const worker = String(facts.worker_id ?? \"\").trim();\n if (!worker) return null;\n const process = String(facts.business_process ?? \"\").trim();\n const effective = String(facts.effective_date ?? \"\").trim();\n return `w:${worker}|bp:${process}|eff:${effective}`;\n }\n\n /**\n * Derive the stateful `duplicate_suspected` fact for a Workday execution-\n * authority action by comparing this process's fingerprint against prior org\n * evaluations in a lookback window. Excludes the current idempotency key so a\n * genuine retry is not mis-flagged as its own duplicate.\n */\n static async deriveDuplicateFacts(input: {\n store: DuplicateLookbackStore;\n orgId: string;\n payload: WorkdayPayload;\n since?: Date | null;\n limit?: number;\n }): Promise<DuplicateFacts> {\n const facts = WorkdaySurface.deriveFacts(input.payload, \"execution_authority\");\n const fingerprint = WorkdaySurface.duplicateFingerprint(facts);\n if (!fingerprint) {\n return { duplicate_suspected: false, duplicate_match_count: 0, duplicate_of: null };\n }\n const currentKey = WorkdaySurface.idempotencyKey(input.payload, \"execution_authority\");\n const priors = await input.store.listDecisionEvaluations({\n orgId: input.orgId,\n since: input.since ?? null,\n limit: input.limit ?? 500,\n });\n\n let count = 0;\n let dupOf: string | null = null;\n for (const row of priors) {\n if (row.idempotency_key && row.idempotency_key === currentKey) continue; // genuine replay\n const ctx = (row.request_payload?.context ?? {}) as Record<string, unknown>;\n if (WorkdaySurface.duplicateFingerprint(ctx) === fingerprint) {\n count += 1;\n if (!dupOf) dupOf = row.dossier_id ?? row.idempotency_key ?? null;\n }\n }\n return { duplicate_suspected: count > 0, duplicate_match_count: count, duplicate_of: dupOf };\n }\n\n private static normalizePayload(payload: WorkdayPayload): Required<WorkdayPayload> {\n return {\n source_system: payload.source_system ?? \"WORKDAY_HCM\",\n object_type: payload.object_type ?? \"CompensationChange\",\n object_id: payload.object_id ?? \"UNKNOWN\",\n action: payload.action ?? \"SUBMIT_BUSINESS_PROCESS\",\n proposed_state: payload.proposed_state ?? {},\n actor: payload.actor ?? {},\n context: payload.context ?? {},\n };\n }\n\n private static isBlank(value: unknown): boolean {\n return value === undefined || value === null || value === \"\";\n }\n\n /** Structural (deterministic) validity of an effective date — no wall-clock read. */\n private static isEffectiveDateInvalid(value: unknown): boolean {\n if (WorkdaySurface.isBlank(value)) return true;\n const parsed = Date.parse(String(value));\n return Number.isNaN(parsed);\n }\n\n private static toFiniteNumber(value: unknown): number | null {\n if (WorkdaySurface.isBlank(value)) return null;\n const n = Number(value);\n return Number.isFinite(n) ? n : null;\n }\n\n private static isCompensationOverThreshold(state: Record<string, unknown>): boolean {\n const proposed =\n WorkdaySurface.toFiniteNumber(state.new_salary) ??\n WorkdaySurface.toFiniteNumber(state.proposed_salary);\n if (proposed === null) return false;\n if (proposed > COMP_ABSOLUTE_THRESHOLD) return true;\n const current = WorkdaySurface.toFiniteNumber(state.current_salary);\n if (current !== null && current > 0) {\n return (proposed - current) / current > COMP_INCREASE_THRESHOLD;\n }\n return false;\n }\n\n private static hasCommitteeApproval(context: Record<string, unknown>): boolean {\n if (context.compensation_committee_approved === true) return true;\n const status = String(context.compensation_committee_status ?? \"\").toUpperCase();\n const signature = String(\n context.compensation_committee_signature ?? context.approval_signature ?? \"\",\n );\n return status === \"APPROVED\" && signature.trim().length > 0;\n }\n\n private static cleanReason(gate: WorkdayGate): string {\n return gate === \"state_admission\"\n ? \"Workday HR proposed state is complete, non-conflicting, and eligible for execution review.\"\n : \"Execution authority is present for the proposed Workday HR action.\";\n }\n\n /** Minimal predicate matcher mirroring the protocol rule-engine operator semantics. */\n private static matchPredicate(\n facts: Record<string, unknown>,\n pred: VerticalPackRule[\"when\"][\"all\"][number],\n ): boolean {\n const actual = facts[pred.field];\n const expected = pred.value;\n switch (pred.operator) {\n case \"EQ\":\n return actual === expected;\n case \"NEQ\":\n return actual !== expected;\n case \"GT\":\n return Number(actual) > Number(expected);\n case \"GTE\":\n return Number(actual) >= Number(expected);\n case \"LT\":\n return Number(actual) < Number(expected);\n case \"LTE\":\n return Number(actual) <= Number(expected);\n case \"IN\":\n return Array.isArray(pred.values) && pred.values.includes(actual);\n case \"NOT_IN\":\n return Array.isArray(pred.values) && !pred.values.includes(actual);\n case \"EXISTS\":\n return actual !== undefined && actual !== null;\n default:\n return false;\n }\n }\n\n private static outcomeForAction(action: VerticalPackRule[\"then\"][\"action\"]): WorkdayOutcome {\n switch (action) {\n case \"AUTO_REJECT\":\n return \"REJECT\";\n case \"ESCALATE\":\n return \"ESCALATE\";\n case \"AUTO_APPROVE\":\n return \"APPROVE\";\n default:\n return \"REVIEW\"; // REQUIRE_REVIEW | REQUEST_INFO\n }\n }\n\n private static decisionDomainForGate(gate: WorkdayGate): WorkdayVerdict[\"decision_domain\"] {\n return gate === \"state_admission\"\n ? \"WORKDAY_HR_STATE_ADMISSION\"\n : \"WORKDAY_HR_EXECUTION_AUTHORITY\";\n }\n}\n\nexport const OUTCOME_TO_DECISION: Record<WorkdayOutcome, WorkdayDecision> = {\n APPROVE: \"ALLOW\",\n REJECT: \"BLOCK\",\n ESCALATE: \"ESCALATE\",\n REVIEW: \"DELAY\",\n};\n\n/** Functional alias for {@link WorkdaySurface.deriveFacts}. */\nexport function deriveWorkdayFacts(\n payload: WorkdayPayload,\n gate: WorkdayGate,\n): Record<string, unknown> {\n return WorkdaySurface.deriveFacts(payload, gate);\n}\n\n/** Functional alias for {@link WorkdaySurface.buildEvaluateRequest}. */\nexport function buildWorkdayEvaluateRequest(\n payload: WorkdayPayload,\n gate: WorkdayGate,\n orgId: string,\n extraFacts?: Record<string, unknown>,\n): Record<string, unknown> {\n return WorkdaySurface.buildEvaluateRequest(payload, gate, orgId, extraFacts);\n}\n\n/** Functional alias for {@link WorkdaySurface.mapPipelineToVerdict}. */\nexport function mapPipelineToWorkdayVerdict(\n response: PipelineEvaluateResponse,\n gate: WorkdayGate,\n): WorkdayVerdict {\n return WorkdaySurface.mapPipelineToVerdict(response, gate);\n}\n\n/** Functional alias for {@link WorkdaySurface.evaluateGate}. */\nexport function evaluateWorkdayGate(\n payload: WorkdayPayload,\n gate: WorkdayGate,\n extraFacts?: Record<string, unknown>,\n): WorkdayVerdict {\n return WorkdaySurface.evaluateGate(payload, gate, extraFacts);\n}\n\n/** Functional alias for {@link WorkdaySurface.idempotencyKey}. */\nexport function workdayIdempotencyKey(payload: WorkdayPayload, gate: WorkdayGate): string {\n return WorkdaySurface.idempotencyKey(payload, gate);\n}\n\n/** Functional alias for {@link WorkdaySurface.deriveDuplicateFacts}. */\nexport async function deriveWorkdayDuplicateFacts(input: {\n store: DuplicateLookbackStore;\n orgId: string;\n payload: WorkdayPayload;\n since?: Date | null;\n limit?: number;\n}): Promise<DuplicateFacts> {\n return WorkdaySurface.deriveDuplicateFacts(input);\n}\n","import { randomUUID } from \"node:crypto\";\nimport type { FastifyInstance, FastifyReply, FastifyRequest } from \"fastify\";\nimport type { ProtocolPayload, ProtocolStore } from \"../store/StoreContracts.js\";\nimport { validateProtocolArtifact } from \"../validation/ProtocolArtifacts.js\";\nimport { PROTOCOL_VERSION } from \"../ProtocolInfo.js\";\nimport { asRecord, asString, isLikelyUuid } from \"../support/Parsing.js\";\nimport { authenticateMcpRequest, isAuthenticationRequired } from \"../mcp.js\";\nimport type { ProtocolMcpAuthLookup } from \"../auth/McpAuth.js\";\nimport { workdayFinancialsVerticalPack } from \"../verticals/workday-financials/WorkdayFinancialsPack.js\";\nimport {\n buildWorkdayFinancialsEvaluateRequest,\n deriveWorkdayFinancialsDuplicateFacts,\n mapPipelineToWorkdayFinancialsVerdict,\n type WorkdayFinancialsGate,\n type WorkdayFinancialsPayload,\n} from \"../verticals/workday-financials/WorkdayFinancialsSurface.js\";\nimport {\n DUPLICATE_LOOKBACK_DAYS,\n SAP_VERIFY_BASE_URL,\n WORKDAY_FIN_DEFAULT_ORG_ID,\n} from \"./SurfaceVerifyShared.js\";\n\n// ── Workday Financials surface (federates Workday Financials into the shared engine) ──\n// A Workday Studio/Extend callback (or middleware) calls these two paths inline at\n// the payroll / invoice API boundary, before the commit reaches the ledger or\n// treasury queue. Each computes a deterministic verdict via the Financials pack and\n// chains a signed decision into the shared audit ledger.\n\n/** Registers the Workday Financials dual-gate verification routes (state admission + execution authority). */\nexport function registerWorkdayFinancialsVerifyRoutes(\n app: FastifyInstance,\n deps: { store: ProtocolStore; authLookup: ProtocolMcpAuthLookup | null },\n): void {\n const { store } = deps;\n const protocolAuthLookup = deps.authLookup ?? null;\n\n // Seed the org's policy bundle from the Financials pack (idempotent) so the shared\n // evaluate-decision pipeline has a \"ready\" policy guard for Financials requests.\n const ensureFinancialsPolicyBundle = async (orgId: string) => {\n const bundles = await store.listPolicyBundles({ orgId, limit: 50 });\n if (\n bundles.some(\n (bundle) => bundle.version === workdayFinancialsVerticalPack.policy_bundle.version,\n )\n ) {\n return;\n }\n const bundlePayload: ProtocolPayload = {\n protocol_version: PROTOCOL_VERSION,\n bundle_id: randomUUID(),\n org_id: orgId,\n version: workdayFinancialsVerticalPack.policy_bundle.version,\n effective_from: new Date(Date.now() - 60_000).toISOString(),\n rules: workdayFinancialsVerticalPack.policy_bundle.rules.map((rule) => ({\n ...rule,\n rule_id: `workday_financials:${rule.rule_id}`,\n })),\n metadata: {\n author: \"decionis-workday-financials-adapter\",\n source: \"protocol_service\",\n change_ticket: \"workday-financials-federation\",\n },\n };\n const validation = validateProtocolArtifact(\"policy_bundle\", bundlePayload);\n if (validation.ok) await store.saveArtifact(\"policy_bundle\", validation.value);\n };\n\n const handleFinancialsGate = async (\n gate: WorkdayFinancialsGate,\n req: FastifyRequest,\n reply: FastifyReply,\n ) => {\n const authCtx = await authenticateMcpRequest(req, protocolAuthLookup);\n if (isAuthenticationRequired(protocolAuthLookup) && !authCtx) {\n return reply.code(401).send({\n error: \"UNAUTHORIZED\",\n message: \"Valid API key required for Workday Financials governance routes\",\n });\n }\n\n const payload = (req.body ?? {}) as WorkdayFinancialsPayload;\n\n const ctx = asRecord(payload.context);\n const authedOrgId = authCtx && authCtx.kind === \"org_api_key\" ? authCtx.org_id : null;\n const candidateOrg =\n authedOrgId ||\n asString(ctx.org_id)?.trim() ||\n process.env.DECIONIS_WORKDAY_FIN_ORG_ID?.trim() ||\n WORKDAY_FIN_DEFAULT_ORG_ID;\n const orgId = isLikelyUuid(candidateOrg) ? candidateOrg : WORKDAY_FIN_DEFAULT_ORG_ID;\n\n await ensureFinancialsPolicyBundle(orgId);\n\n // Gate 2 (execution authority) gets the stateful duplicate-payment fact from a\n // store lookback (payee + period + amount, or vendor + invoice); Gate 1 is declarative.\n let extraFacts: Record<string, unknown> | undefined;\n if (gate === \"execution_authority\") {\n const since = new Date(Date.now() - DUPLICATE_LOOKBACK_DAYS * 24 * 60 * 60 * 1000);\n extraFacts = await deriveWorkdayFinancialsDuplicateFacts({ store, orgId, payload, since });\n }\n\n const evalRes = await app.inject({\n method: \"POST\",\n url: \"/v1/protocol/evaluate-decision\",\n payload: buildWorkdayFinancialsEvaluateRequest(payload, gate, orgId, extraFacts),\n });\n if (evalRes.statusCode !== 200) {\n return reply.code(502).send({\n error: \"WORKDAY_FIN_PIPELINE_FAILED\",\n message: \"The shared evaluate-decision pipeline rejected the Workday Financials request.\",\n status: evalRes.statusCode,\n });\n }\n\n const response = evalRes.json() as {\n outcome?: string;\n dossier_id?: string;\n dossier_sha256?: string | null;\n decision_resolution_id?: string | null;\n evaluation_id?: string | null;\n ledger_entry_id?: string | null;\n ledger_entry_hash?: string | null;\n policy_version?: string;\n decision_chain?: unknown;\n idempotent_replay?: boolean;\n policy_evaluation?: {\n selected_rule_id?: string | null;\n selected_rule_rationale?: string | null;\n } | null;\n };\n const verdict = mapPipelineToWorkdayFinancialsVerdict(response, gate);\n const dossierId = response.dossier_id ?? null;\n const verificationUrl = dossierId\n ? `${process.env.DECIONIS_VERIFY_BASE_URL ?? SAP_VERIFY_BASE_URL}/${dossierId}`\n : null;\n\n return reply.code(200).send({\n decision: verdict.decision,\n reason: verdict.reason,\n required_action: verdict.required_action,\n gate,\n decision_domain: verdict.decision_domain,\n rule_id: verdict.rule_id,\n outcome: verdict.outcome,\n duplicate_suspected: Boolean(extraFacts?.duplicate_suspected),\n policy_version:\n response.policy_version ?? workdayFinancialsVerticalPack.policy_bundle.version,\n dossier_id: dossierId,\n dossier_sha256: response.dossier_sha256 ?? null,\n dossier_hash: response.dossier_sha256 ? `sha256:${response.dossier_sha256}` : null,\n verification_url: verificationUrl,\n org_id: orgId,\n decision_resolution_id: response.decision_resolution_id ?? null,\n evaluation_id: response.evaluation_id ?? null,\n ledger_entry_id: response.ledger_entry_id ?? null,\n ledger_entry_hash: response.ledger_entry_hash ?? null,\n decision_chain: response.decision_chain ?? null,\n idempotent_replay: Boolean(response.idempotent_replay),\n federated: true,\n pipeline: true,\n });\n };\n\n app.post(\"/workday/financials/state-admission/verify\", (req, reply) =>\n handleFinancialsGate(\"state_admission\", req, reply),\n );\n app.post(\"/v1/protocol/workday/financials/state-admission/verify\", (req, reply) =>\n handleFinancialsGate(\"state_admission\", req, reply),\n );\n app.post(\"/workday/financials/execution-authority/verify\", (req, reply) =>\n handleFinancialsGate(\"execution_authority\", req, reply),\n );\n app.post(\"/v1/protocol/workday/financials/execution-authority/verify\", (req, reply) =>\n handleFinancialsGate(\"execution_authority\", req, reply),\n );\n}\n","import { createHash } from \"node:crypto\";\n\nimport { workdayFinancialsVerticalPack } from \"./WorkdayFinancialsPack.js\";\nimport type { VerticalPackRule } from \"../VerticalContracts.js\";\nimport type { DuplicateFacts, DuplicateLookbackStore } from \"../shared/DuplicateDetection.js\";\n\n/**\n * Workday Financials surface adapter — the concrete native-surface implementation\n * for Workday Financials. Surface-specific work is normalization + derivation; the\n * decision logic is the declarative `workdayFinancialsVerticalPack`. Pure (no I/O,\n * no store) so it is fully unit-testable and deterministic, and it is the source of\n * truth the protocol `/workday/financials/*` routes call.\n *\n * A payload is a financial commit — a payroll run / expense payout (`fin_family`\n * \"payroll\") or a supplier invoice / purchase order (\"invoice\") — with a\n * `proposed_state` (amount, currency, payee, contract, unit price), an `actor`\n * (role), and a `context` (approvals, hard-cap / variance overrides, baselines).\n */\n\nexport type WorkdayFinancialsGate = \"state_admission\" | \"execution_authority\";\nexport type WorkdayFinancialsDecision = \"ALLOW\" | \"BLOCK\" | \"ESCALATE\" | \"DELAY\";\nexport type WorkdayFinancialsOutcome = \"APPROVE\" | \"REJECT\" | \"ESCALATE\" | \"REVIEW\";\nexport type FinFamily = \"payroll\" | \"invoice\";\n\nexport interface WorkdayFinancialsPayload {\n source_system?: string;\n /** Workday Financials object type, e.g. \"PayrollRun\", \"ExpensePayout\", \"SupplierInvoice\". */\n object_type?: string;\n object_id?: string;\n action?: string;\n proposed_state?: Record<string, unknown>;\n actor?: Record<string, unknown>;\n context?: Record<string, unknown>;\n}\n\nexport interface WorkdayFinancialsVerdict {\n decision: WorkdayFinancialsDecision;\n outcome: WorkdayFinancialsOutcome;\n reason: string;\n required_action: string | null;\n decision_domain: \"WORKDAY_FIN_STATE_ADMISSION\" | \"WORKDAY_FIN_EXECUTION_AUTHORITY\";\n rule_id: string | null;\n gate: WorkdayFinancialsGate;\n}\n\n/** Roles allowed to release a governed Workday Financials commit. */\nconst AUTHORIZED_FINANCE_ROLES = new Set([\n \"PayrollAdministrator\",\n \"APManager\",\n \"FinanceManager\",\n \"Controller\",\n \"TreasuryAnalyst\",\n \"CFO\",\n]);\n/** Default single-payout hard cap (overridable via context.hard_cap). */\nconst DEFAULT_HARD_CAP = 1_000_000;\n/** Default payroll variance multiple over the historical baseline (500% => 5x). */\nconst DEFAULT_VARIANCE_MULTIPLE = 5;\n/** Invoiced unit price may exceed the contract/baseline by at most this fraction. */\nconst UNIT_PRICE_TOLERANCE = 0.1;\n\n/** Per-rule reason + structured required-action, kept out of the declarative pack. */\nexport const RULE_META: Record<string, { reason: string; required_action: string }> = {\n \"state-required-fields\": {\n reason: \"Required Workday Financials state fields are missing.\",\n required_action: \"COMPLETE_SOURCE_STATE\",\n },\n \"state-amount-valid\": {\n reason: \"Payout / invoice amount must be a positive numeric value.\",\n required_action: \"CORRECT_AMOUNT\",\n },\n \"exec-duplicate-payment\": {\n reason: \"A prior payment with the same payee/vendor + amount fingerprint was found.\",\n required_action: \"DUPLICATE_PAYMENT_REVIEW\",\n },\n \"exec-hard-cap\": {\n reason: \"A single payout exceeds the hard cap.\",\n required_action: \"HARD_CAP_OVERRIDE_APPROVAL\",\n },\n \"exec-authorized-approver\": {\n reason: \"Actor role is not authorized to release governed Workday Financials commits.\",\n required_action: \"AUTHORIZED_FINANCE_ROLE\",\n },\n \"exec-payroll-variance\": {\n reason: \"Payroll / expense amount exceeds the allowed variance from the historical baseline.\",\n required_action: \"PAYROLL_VARIANCE_REVIEW\",\n },\n \"exec-off-contract\": {\n reason: \"Invoice does not reconcile to an active contract.\",\n required_action: \"CONTRACT_TERMS_REVIEW\",\n },\n \"exec-unit-price-anomaly\": {\n reason: \"Invoiced unit price exceeds the contract / baseline unit price beyond tolerance.\",\n required_action: \"UNIT_PRICE_REVIEW\",\n },\n};\n\ninterface PipelineEvaluateResponse {\n outcome?: string;\n policy_evaluation?: {\n selected_rule_id?: string | null;\n selected_rule_rationale?: string | null;\n } | null;\n}\n\n/** Workday Financials native-surface adapter: fact derivation + deterministic dual-gate evaluation. */\nexport class WorkdayFinancialsSurface {\n private static readonly PACK_VERSION = workdayFinancialsVerticalPack.policy_bundle.version;\n\n /**\n * Derive the boolean/number facts the pack rules match against. Deterministic:\n * variance/hard-cap/unit-price checks are structural, and the stateful\n * `duplicate_suspected` fact is supplied by the route via `extraFacts`.\n */\n static deriveFacts(\n payload: WorkdayFinancialsPayload,\n gate: WorkdayFinancialsGate,\n ): Record<string, unknown> {\n const p = WorkdayFinancialsSurface.normalizePayload(payload);\n const state = p.proposed_state;\n const context = p.context;\n const actor = p.actor;\n\n const family = WorkdayFinancialsSurface.familyFor(p.object_type);\n const amount = WorkdayFinancialsSurface.toFiniteNumber(state.amount);\n const amountValid = amount !== null && amount > 0;\n\n const payeeField =\n family === \"payroll\" ? (state.worker_id ?? state.pay_group) : state.vendor_id;\n const missingList = [\n ...(WorkdaySurfaceIsBlank(payeeField)\n ? ([family === \"payroll\" ? \"worker_id\" : \"vendor_id\"] as const)\n : []),\n ...(WorkdaySurfaceIsBlank(state.amount) ? ([\"amount\"] as const) : []),\n ...(WorkdaySurfaceIsBlank(state.currency) ? ([\"currency\"] as const) : []),\n ];\n\n const hardCap = WorkdayFinancialsSurface.toFiniteNumber(context.hard_cap) ?? DEFAULT_HARD_CAP;\n const varianceMultiple =\n WorkdayFinancialsSurface.toFiniteNumber(context.variance_threshold) ??\n DEFAULT_VARIANCE_MULTIPLE;\n const historicalAverage = WorkdayFinancialsSurface.toFiniteNumber(\n state.historical_average ?? context.historical_average,\n );\n\n return {\n gate,\n fin_family: family,\n object_type: p.object_type,\n // Fingerprint passthrough for duplicate detection.\n vendor_id: state.vendor_id ?? null,\n worker_id: state.worker_id ?? null,\n pay_group: state.pay_group ?? null,\n pay_period: state.pay_period ?? null,\n invoice_number: state.invoice_number ?? null,\n amount,\n currency: state.currency ?? null,\n // Overridden by the store-backed duplicate pass; safe default for pure eval.\n duplicate_suspected: false,\n // Gate 1\n missing_required_fields: missingList.length,\n missing_fields_list: missingList,\n amount_invalid: !amountValid,\n // Gate 2 — payroll/expense\n over_hard_cap: family === \"payroll\" && amount !== null && amount > hardCap,\n variance_exceeded:\n family === \"payroll\" &&\n amount !== null &&\n historicalAverage !== null &&\n historicalAverage > 0 &&\n (amount - historicalAverage) / historicalAverage > varianceMultiple,\n // Gate 2 — approver authority (both families)\n actor_role: String(actor.role ?? \"\"),\n actor_authorized: AUTHORIZED_FINANCE_ROLES.has(String(actor.role ?? \"\")),\n // Gate 2 — procurement/invoice\n off_contract:\n family === \"invoice\" && WorkdayFinancialsSurface.isOffContract(state, context, amount),\n unit_price_anomaly:\n family === \"invoice\" && WorkdayFinancialsSurface.isUnitPriceAnomaly(state, context),\n };\n }\n\n /**\n * Build the canonical `evaluate-decision` request body for a Financials gate so\n * the decision runs through the full shared pipeline (org policy bundle, signed\n * dossier, decision-chain, idempotency). Derived facts live in `context`;\n * `policy_version` pins the Financials bundle.\n */\n static buildEvaluateRequest(\n payload: WorkdayFinancialsPayload,\n gate: WorkdayFinancialsGate,\n orgId: string,\n extraFacts?: Record<string, unknown>,\n ): Record<string, unknown> {\n const facts = { ...WorkdayFinancialsSurface.deriveFacts(payload, gate), ...(extraFacts ?? {}) };\n return {\n org_id: orgId,\n decision_type:\n gate === \"state_admission\"\n ? \"workday_fin_state_admission\"\n : \"workday_fin_execution_authority\",\n vertical_pack: \"workday_financials\",\n policy_version: WorkdayFinancialsSurface.PACK_VERSION,\n mode: \"ENFORCEMENT\",\n amount: typeof facts.amount === \"number\" ? facts.amount : null,\n idempotency_key: WorkdayFinancialsSurface.idempotencyKey(payload, gate),\n context: facts,\n };\n }\n\n /**\n * Map a shared-pipeline `EvaluateDecisionResponse` back into the Financials verdict\n * shape. The selected rule id (stripped of its `workday_financials:` prefix) keys\n * the structured `required_action`.\n */\n static mapPipelineToVerdict(\n response: PipelineEvaluateResponse,\n gate: WorkdayFinancialsGate,\n ): WorkdayFinancialsVerdict {\n const outcome = (response.outcome ?? \"REVIEW\") as WorkdayFinancialsOutcome;\n const rawRuleId = response.policy_evaluation?.selected_rule_id ?? null;\n const ruleId = rawRuleId ? rawRuleId.replace(/^workday_financials:/, \"\") : null;\n const meta = ruleId ? RULE_META[ruleId] : undefined;\n return {\n decision: OUTCOME_TO_DECISION[outcome] ?? \"DELAY\",\n outcome,\n reason:\n meta?.reason ??\n response.policy_evaluation?.selected_rule_rationale ??\n WorkdayFinancialsSurface.cleanReason(gate),\n required_action: meta?.required_action ?? null,\n decision_domain: WorkdayFinancialsSurface.decisionDomainForGate(gate),\n rule_id: ruleId,\n gate,\n };\n }\n\n /**\n * Evaluate a Financials gate deterministically against the pack. No match means\n * every check passed → ALLOW. Highest-priority matched rule wins.\n */\n static evaluateGate(\n payload: WorkdayFinancialsPayload,\n gate: WorkdayFinancialsGate,\n extraFacts?: Record<string, unknown>,\n ): WorkdayFinancialsVerdict {\n const facts = { ...WorkdayFinancialsSurface.deriveFacts(payload, gate), ...(extraFacts ?? {}) };\n const decisionDomain = WorkdayFinancialsSurface.decisionDomainForGate(gate);\n\n const matched = workdayFinancialsVerticalPack.policy_bundle.rules\n .filter((rule) => rule.enabled)\n .filter((rule) =>\n rule.when.all.every((pred) => WorkdayFinancialsSurface.matchPredicate(facts, pred)),\n )\n .sort((a, b) => b.priority - a.priority);\n\n const selected = matched[0];\n if (!selected) {\n return {\n decision: \"ALLOW\",\n outcome: \"APPROVE\",\n reason: WorkdayFinancialsSurface.cleanReason(gate),\n required_action: null,\n decision_domain: decisionDomain,\n rule_id: null,\n gate,\n };\n }\n\n const outcome = WorkdayFinancialsSurface.outcomeForAction(selected.then.action);\n const meta = RULE_META[selected.rule_id];\n let reason = meta?.reason ?? selected.rationale ?? selected.name;\n if (selected.rule_id === \"state-required-fields\") {\n const list = (facts.missing_fields_list as string[]) ?? [];\n reason = `Required Workday Financials state fields are missing: ${list.join(\", \")}.`;\n } else if (selected.rule_id === \"exec-authorized-approver\") {\n reason = `Actor role ${String(facts.actor_role) || \"UNKNOWN\"} is not authorized to release governed Workday Financials commits.`;\n }\n\n return {\n decision: OUTCOME_TO_DECISION[outcome],\n outcome,\n reason,\n required_action: meta?.required_action ?? null,\n decision_domain: decisionDomain,\n rule_id: selected.rule_id,\n gate,\n };\n }\n\n /**\n * Idempotency key scoped to object + gate AND a digest of the derived facts, so a\n * genuine retry of the same state replays while a changed state re-evaluates.\n */\n static idempotencyKey(payload: WorkdayFinancialsPayload, gate: WorkdayFinancialsGate): string {\n const p = WorkdayFinancialsSurface.normalizePayload(payload);\n const digest = createHash(\"sha256\")\n .update(JSON.stringify(WorkdayFinancialsSurface.deriveFacts(payload, gate)))\n .digest(\"hex\")\n .slice(0, 24);\n return `workday_fin:${p.object_type}:${p.object_id}:${gate}:${digest}`;\n }\n\n /**\n * Duplicate-payment fingerprint. Invoice family keys on vendor + invoice (or\n * vendor + amount + currency); payroll family keys on payee + period + amount.\n * Null when the payee is unknown (nothing to match).\n */\n static duplicateFingerprint(facts: Record<string, unknown>): string | null {\n const family = String(facts.fin_family ?? \"\");\n if (family === \"invoice\") {\n const vendor = String(facts.vendor_id ?? \"\").trim();\n if (!vendor) return null;\n const invoice = String(facts.invoice_number ?? \"\").trim();\n if (invoice) return `v:${vendor}|inv:${invoice}`;\n const amount = facts.amount;\n if (typeof amount === \"number\") {\n return `v:${vendor}|amt:${amount}|cur:${String(facts.currency ?? \"\").trim()}`;\n }\n return null;\n }\n const payee = String(facts.worker_id ?? facts.pay_group ?? \"\").trim();\n if (!payee) return null;\n const period = String(facts.pay_period ?? \"\").trim();\n const amount = facts.amount;\n return `w:${payee}|per:${period}|amt:${typeof amount === \"number\" ? amount : \"\"}`;\n }\n\n /**\n * Derive the stateful `duplicate_suspected` fact by comparing this commit's\n * fingerprint against prior org evaluations in a lookback window. Excludes the\n * current idempotency key so a genuine retry is not mis-flagged.\n */\n static async deriveDuplicateFacts(input: {\n store: DuplicateLookbackStore;\n orgId: string;\n payload: WorkdayFinancialsPayload;\n since?: Date | null;\n limit?: number;\n }): Promise<DuplicateFacts> {\n const facts = WorkdayFinancialsSurface.deriveFacts(input.payload, \"execution_authority\");\n const fingerprint = WorkdayFinancialsSurface.duplicateFingerprint(facts);\n if (!fingerprint) {\n return { duplicate_suspected: false, duplicate_match_count: 0, duplicate_of: null };\n }\n const currentKey = WorkdayFinancialsSurface.idempotencyKey(\n input.payload,\n \"execution_authority\",\n );\n const priors = await input.store.listDecisionEvaluations({\n orgId: input.orgId,\n since: input.since ?? null,\n limit: input.limit ?? 500,\n });\n\n let count = 0;\n let dupOf: string | null = null;\n for (const row of priors) {\n if (row.idempotency_key && row.idempotency_key === currentKey) continue; // genuine replay\n const ctx = (row.request_payload?.context ?? {}) as Record<string, unknown>;\n if (WorkdayFinancialsSurface.duplicateFingerprint(ctx) === fingerprint) {\n count += 1;\n if (!dupOf) dupOf = row.dossier_id ?? row.idempotency_key ?? null;\n }\n }\n return { duplicate_suspected: count > 0, duplicate_match_count: count, duplicate_of: dupOf };\n }\n\n private static normalizePayload(\n payload: WorkdayFinancialsPayload,\n ): Required<WorkdayFinancialsPayload> {\n return {\n source_system: payload.source_system ?? \"WORKDAY_FINANCIALS\",\n object_type: payload.object_type ?? \"SupplierInvoice\",\n object_id: payload.object_id ?? \"UNKNOWN\",\n action: payload.action ?? \"RELEASE_COMMIT\",\n proposed_state: payload.proposed_state ?? {},\n actor: payload.actor ?? {},\n context: payload.context ?? {},\n };\n }\n\n /** Classify the Workday Financials object into the payroll/expense or invoice/PO family. */\n static familyFor(objectType: string): FinFamily {\n return /payroll|expense|reimburse|disburse|payout/i.test(objectType) ? \"payroll\" : \"invoice\";\n }\n\n private static isOffContract(\n state: Record<string, unknown>,\n context: Record<string, unknown>,\n amount: number | null,\n ): boolean {\n const contractId = state.contract_id ?? context.contract_id;\n const contractStatus = String(\n state.contract_status ?? context.contract_status ?? \"ACTIVE\",\n ).toUpperCase();\n const contractRemaining = WorkdayFinancialsSurface.toFiniteNumber(\n state.contract_remaining ?? context.contract_remaining,\n );\n // Policy may require every invoice to cite a contract.\n if (context.require_contract === true && WorkdaySurfaceIsBlank(contractId)) return true;\n // A cited contract that is not active.\n if (!WorkdaySurfaceIsBlank(contractId) && contractStatus !== \"ACTIVE\") return true;\n // Invoice exceeds the remaining contract value.\n if (contractRemaining !== null && amount !== null && amount > contractRemaining) return true;\n return false;\n }\n\n private static isUnitPriceAnomaly(\n state: Record<string, unknown>,\n context: Record<string, unknown>,\n ): boolean {\n const unitPrice = WorkdayFinancialsSurface.toFiniteNumber(state.unit_price);\n const baseline = WorkdayFinancialsSurface.toFiniteNumber(\n state.contract_unit_price ?? context.unit_price_baseline,\n );\n if (unitPrice === null || baseline === null || baseline <= 0) return false;\n return unitPrice > baseline * (1 + UNIT_PRICE_TOLERANCE);\n }\n\n private static toFiniteNumber(value: unknown): number | null {\n if (WorkdaySurfaceIsBlank(value)) return null;\n const n = Number(value);\n return Number.isFinite(n) ? n : null;\n }\n\n private static cleanReason(gate: WorkdayFinancialsGate): string {\n return gate === \"state_admission\"\n ? \"Financial proposed state is complete and eligible for execution review.\"\n : \"Circuit-breaker checks passed for the proposed Workday Financials commit.\";\n }\n\n private static matchPredicate(\n facts: Record<string, unknown>,\n pred: VerticalPackRule[\"when\"][\"all\"][number],\n ): boolean {\n const actual = facts[pred.field];\n const expected = pred.value;\n switch (pred.operator) {\n case \"EQ\":\n return actual === expected;\n case \"NEQ\":\n return actual !== expected;\n case \"GT\":\n return Number(actual) > Number(expected);\n case \"GTE\":\n return Number(actual) >= Number(expected);\n case \"LT\":\n return Number(actual) < Number(expected);\n case \"LTE\":\n return Number(actual) <= Number(expected);\n case \"IN\":\n return Array.isArray(pred.values) && pred.values.includes(actual);\n case \"NOT_IN\":\n return Array.isArray(pred.values) && !pred.values.includes(actual);\n case \"EXISTS\":\n return actual !== undefined && actual !== null;\n default:\n return false;\n }\n }\n\n private static outcomeForAction(\n action: VerticalPackRule[\"then\"][\"action\"],\n ): WorkdayFinancialsOutcome {\n switch (action) {\n case \"AUTO_REJECT\":\n return \"REJECT\";\n case \"ESCALATE\":\n return \"ESCALATE\";\n case \"AUTO_APPROVE\":\n return \"APPROVE\";\n default:\n return \"REVIEW\"; // REQUIRE_REVIEW | REQUEST_INFO\n }\n }\n\n private static decisionDomainForGate(\n gate: WorkdayFinancialsGate,\n ): WorkdayFinancialsVerdict[\"decision_domain\"] {\n return gate === \"state_admission\"\n ? \"WORKDAY_FIN_STATE_ADMISSION\"\n : \"WORKDAY_FIN_EXECUTION_AUTHORITY\";\n }\n}\n\n/** Shared blank check (module-scoped so the private derivation helpers can use it). */\nfunction WorkdaySurfaceIsBlank(value: unknown): boolean {\n return value === undefined || value === null || value === \"\";\n}\n\nexport const OUTCOME_TO_DECISION: Record<WorkdayFinancialsOutcome, WorkdayFinancialsDecision> = {\n APPROVE: \"ALLOW\",\n REJECT: \"BLOCK\",\n ESCALATE: \"ESCALATE\",\n REVIEW: \"DELAY\",\n};\n\n/** Functional alias for {@link WorkdayFinancialsSurface.deriveFacts}. */\nexport function deriveWorkdayFinancialsFacts(\n payload: WorkdayFinancialsPayload,\n gate: WorkdayFinancialsGate,\n): Record<string, unknown> {\n return WorkdayFinancialsSurface.deriveFacts(payload, gate);\n}\n\n/** Functional alias for {@link WorkdayFinancialsSurface.buildEvaluateRequest}. */\nexport function buildWorkdayFinancialsEvaluateRequest(\n payload: WorkdayFinancialsPayload,\n gate: WorkdayFinancialsGate,\n orgId: string,\n extraFacts?: Record<string, unknown>,\n): Record<string, unknown> {\n return WorkdayFinancialsSurface.buildEvaluateRequest(payload, gate, orgId, extraFacts);\n}\n\n/** Functional alias for {@link WorkdayFinancialsSurface.mapPipelineToVerdict}. */\nexport function mapPipelineToWorkdayFinancialsVerdict(\n response: PipelineEvaluateResponse,\n gate: WorkdayFinancialsGate,\n): WorkdayFinancialsVerdict {\n return WorkdayFinancialsSurface.mapPipelineToVerdict(response, gate);\n}\n\n/** Functional alias for {@link WorkdayFinancialsSurface.evaluateGate}. */\nexport function evaluateWorkdayFinancialsGate(\n payload: WorkdayFinancialsPayload,\n gate: WorkdayFinancialsGate,\n extraFacts?: Record<string, unknown>,\n): WorkdayFinancialsVerdict {\n return WorkdayFinancialsSurface.evaluateGate(payload, gate, extraFacts);\n}\n\n/** Functional alias for {@link WorkdayFinancialsSurface.idempotencyKey}. */\nexport function workdayFinancialsIdempotencyKey(\n payload: WorkdayFinancialsPayload,\n gate: WorkdayFinancialsGate,\n): string {\n return WorkdayFinancialsSurface.idempotencyKey(payload, gate);\n}\n\n/** Functional alias for {@link WorkdayFinancialsSurface.deriveDuplicateFacts}. */\nexport async function deriveWorkdayFinancialsDuplicateFacts(input: {\n store: DuplicateLookbackStore;\n orgId: string;\n payload: WorkdayFinancialsPayload;\n since?: Date | null;\n limit?: number;\n}): Promise<DuplicateFacts> {\n return WorkdayFinancialsSurface.deriveDuplicateFacts(input);\n}\n","import { randomUUID } from \"node:crypto\";\nimport type { FastifyInstance, FastifyReply, FastifyRequest } from \"fastify\";\nimport type { ProtocolStore } from \"../store/StoreContracts.js\";\nimport { buildDecisionDossierPersistedProofBundle } from \"../integrity/DossierProofBundle.js\";\nimport { asRecord, asString } from \"../support/Parsing.js\";\nimport { authenticateMcpRequest, isAuthenticationRequired } from \"../mcp.js\";\nimport type { ProtocolMcpAuthLookup } from \"../auth/McpAuth.js\";\nimport { appendEvaluateDecisionLedgerEvent } from \"../evaluate-decision/EvaluateDecisionResolution.js\";\nimport { SAP_DEFAULT_ORG_ID } from \"./SurfaceVerifyShared.js\";\n\n// External surface decision → shared audit ledger. Layer-A surfaces (Amazon,\n// Shopify) evaluate locally with the shared @decionis/surface gates, then\n// federate their signed dossier here so it lands in the SAME cross-surface\n// SHA256 ledger chain as the protocol's own decisions (and SAP).\n\n/** Registers the external surface-decision federation routes. */\nexport function registerSurfaceDecisionRoutes(\n app: FastifyInstance,\n deps: { store: ProtocolStore; authLookup: ProtocolMcpAuthLookup | null },\n): void {\n const { store } = deps;\n const protocolAuthLookup = deps.authLookup ?? null;\n\n const handleSurfaceDecision = async (req: FastifyRequest, reply: FastifyReply) => {\n const authCtx = await authenticateMcpRequest(req, protocolAuthLookup);\n if (isAuthenticationRequired(protocolAuthLookup) && !authCtx) {\n return reply.code(401).send({\n error: \"UNAUTHORIZED\",\n message: \"Valid API key required to federate surface decisions\",\n });\n }\n\n const body = asRecord(req.body);\n const surface = asString(body.surface);\n const decision = asString(body.decision); // authorize | block | review\n const dossierId = asString(body.dossier_id);\n const dossierSha256 = asString(body.dossier_sha256);\n if (!surface || !decision || !dossierId || !dossierSha256) {\n return reply.code(400).send({\n error: \"VALIDATION_ERROR\",\n message: \"surface, decision, dossier_id and dossier_sha256 are required\",\n });\n }\n\n const authedOrgId = authCtx && authCtx.kind === \"org_api_key\" ? authCtx.org_id : null;\n const orgId = authedOrgId || asString(body.org_id)?.trim() || SAP_DEFAULT_ORG_ID;\n const outcome =\n decision === \"authorize\" ? \"APPROVE\" : decision === \"block\" ? \"REJECT\" : \"REVIEW\";\n const mode = asString(body.mode) === \"enforced\" ? \"ENFORCEMENT\" : \"SHADOW\";\n\n let ledger: { ledger_entry_id: string; ledger_entry_hash: string } | null = null;\n let ledgerError: string | null = null;\n try {\n ledger = await appendEvaluateDecisionLedgerEvent(store, {\n org_id: orgId,\n dossier_id: dossierId,\n decision_resolution_id: randomUUID(),\n occurred_at: new Date().toISOString(),\n outcome,\n mode,\n dossier_sha256: dossierSha256,\n });\n } catch (error) {\n ledgerError = error instanceof Error ? error.message : \"ledger_append_failed\";\n }\n\n // When the surface federates the FULL signed dossier (not just id + sha),\n // adopt it into the protocol's signed-evidence format and persist it so it is\n // retrievable (GET /dossiers/:id) and exportable as a proof packet. The surface\n // dossier becomes the portable artifact inside a protocol Ed25519 proof bundle.\n // Backward-compatible: a summary-only POST (no `dossier`) stays ledger-only.\n let persisted = false;\n const surfaceDossier = asRecord(body.dossier);\n if (ledger && Object.keys(surfaceDossier).length > 0) {\n try {\n const generatedAt = new Date().toISOString();\n const proofBundle = buildDecisionDossierPersistedProofBundle({\n issued_at: generatedAt,\n portable_artifact: surfaceDossier,\n json_ld: null,\n });\n const dossierPayload: Record<string, unknown> = {\n dossier_type: \"SURFACE_DECISION_DOSSIER_V1\",\n dossier_schema_version: \"1.0.0\",\n dossier_id: dossierId,\n surface,\n generated_at: generatedAt,\n routing_decision: {\n decision_domain: surface,\n outcome,\n policy_snapshot: body.policy_snapshot ?? null,\n },\n portable_artifact: surfaceDossier,\n integrity: {\n payload_sha256: dossierSha256,\n ledger_entry_id: ledger.ledger_entry_id,\n ledger_entry_hash: ledger.ledger_entry_hash,\n ledger_chain_verified: false,\n proof_bundle: proofBundle,\n },\n };\n await store.saveDecisionEvaluation({\n id: randomUUID(),\n org_id: orgId,\n idempotency_key: `surface:${surface}:${dossierId}`,\n decision_type: `${surface}_surface_decision`,\n amount: null,\n source: asString(body.source) ?? `${surface}.gate`,\n policy_version: asString(surfaceDossier.policyVersion) || \"surface\",\n objective_profile: `${surface}_surface`,\n outcome,\n confidence: 1,\n dossier_id: dossierId,\n mode,\n request_payload: { surface, decision, mode },\n response_payload: { dossier_sha256: dossierSha256 },\n dossier_payload: dossierPayload,\n });\n persisted = true;\n } catch {\n persisted = false;\n }\n }\n\n return reply.code(ledger ? 200 : 502).send({\n federated: ledger != null,\n persisted,\n surface,\n org_id: orgId,\n dossier_id: dossierId,\n ledger_entry_id: ledger?.ledger_entry_id ?? null,\n ledger_entry_hash: ledger?.ledger_entry_hash ?? null,\n ledger_error: ledgerError,\n });\n };\n app.post(\"/surfaces/decisions\", handleSurfaceDecision);\n app.post(\"/v1/protocol/surfaces/decisions\", handleSurfaceDecision);\n}\n","import type { FastifyInstance } from \"fastify\";\nimport type { ProtocolStore } from \"../store/StoreContracts.js\";\nimport { asRecord, asString, isLikelyUuid, parseOptionalBoolean } from \"../support/Parsing.js\";\nimport { parseEvaluateModeStrict } from \"../evaluate-decision/EvaluateDecisionParsing.js\";\nimport type { EvaluateDecisionMode } from \"../evaluate-decision/EvaluateDecisionContracts.js\";\n\n/** Enforcement-rollout mutation parsing for the rollout control routes. */\nexport class EnforcementRolloutParsing {\n static parseEnforcementRolloutMutation(input: unknown):\n | {\n ok: true;\n value: {\n org_id: string;\n decision_band: string;\n transaction_type: string;\n mode: EvaluateDecisionMode;\n feature_flag: string | null;\n fallback_to_legacy: boolean | null;\n reconciliation_required: boolean | null;\n notes: string | null;\n };\n }\n | { ok: false; message: string } {\n const record = asRecord(input);\n const orgId = asString(record.org_id);\n if (!orgId) return { ok: false, message: \"org_id is required\" };\n if (!isLikelyUuid(orgId)) return { ok: false, message: \"org_id must be a UUID\" };\n\n const decisionBand = asString(record.decision_band);\n if (!decisionBand) return { ok: false, message: \"decision_band is required\" };\n\n const transactionType = asString(record.transaction_type);\n if (!transactionType) return { ok: false, message: \"transaction_type is required\" };\n\n const mode = parseEvaluateModeStrict(record.mode);\n if (!mode) {\n return {\n ok: false,\n message: \"mode must be one of SHADOW, PARALLEL, ENFORCEMENT\",\n };\n }\n\n const fallbackToLegacy = parseOptionalBoolean(record.fallback_to_legacy);\n if (record.fallback_to_legacy !== undefined && fallbackToLegacy == null) {\n return { ok: false, message: \"fallback_to_legacy must be a boolean when provided\" };\n }\n\n const reconciliationRequired = parseOptionalBoolean(record.reconciliation_required);\n if (record.reconciliation_required !== undefined && reconciliationRequired == null) {\n return { ok: false, message: \"reconciliation_required must be a boolean when provided\" };\n }\n\n return {\n ok: true,\n value: {\n org_id: orgId,\n decision_band: decisionBand,\n transaction_type: transactionType,\n mode,\n feature_flag: asString(record.feature_flag),\n fallback_to_legacy: fallbackToLegacy,\n reconciliation_required: reconciliationRequired,\n notes: asString(record.notes),\n },\n };\n }\n}\n\n/** Functional alias for {@link EnforcementRolloutParsing.parseEnforcementRolloutMutation}. */\nexport function parseEnforcementRolloutMutation(input: unknown):\n | {\n ok: true;\n value: {\n org_id: string;\n decision_band: string;\n transaction_type: string;\n mode: EvaluateDecisionMode;\n feature_flag: string | null;\n fallback_to_legacy: boolean | null;\n reconciliation_required: boolean | null;\n notes: string | null;\n };\n }\n | { ok: false; message: string } {\n return EnforcementRolloutParsing.parseEnforcementRolloutMutation(input);\n}\n\n/** Registers the enforcement-rollout inspection and mutation routes. */\nexport function registerEnforcementRolloutRoutes(\n app: FastifyInstance,\n deps: { store: ProtocolStore },\n): void {\n const { store } = deps;\n\n app.get(\"/v1/protocol/enforcement/rollouts\", async (req, reply) => {\n const query = asRecord(req.query);\n const orgId = asString(query.org_id);\n if (!orgId || !isLikelyUuid(orgId)) {\n return reply.code(400).send({ error: \"VALIDATION_ERROR\", message: \"Valid org_id required\" });\n }\n\n const decisionBand = asString(query.decision_band);\n const transactionType = asString(query.transaction_type);\n if ((decisionBand && !transactionType) || (!decisionBand && transactionType)) {\n return reply.code(400).send({\n error: \"VALIDATION_ERROR\",\n message: \"decision_band and transaction_type must be provided together\",\n });\n }\n\n if (decisionBand && transactionType) {\n const rollout = await store.getEnforcementRollout({\n orgId,\n decisionBand,\n transactionType,\n });\n return reply.code(200).send({\n org_id: orgId,\n count: rollout ? 1 : 0,\n rollouts: rollout ? [rollout] : [],\n });\n }\n\n const rollouts = await store.listEnforcementRollouts({ orgId });\n return reply.code(200).send({\n org_id: orgId,\n count: rollouts.length,\n rollouts,\n });\n });\n\n app.put(\"/v1/protocol/enforcement/rollouts\", async (req, reply) => {\n const parsed = parseEnforcementRolloutMutation(req.body);\n if (!parsed.ok) {\n return reply.code(400).send({ error: \"VALIDATION_ERROR\", message: parsed.message });\n }\n\n const rollout = await store.upsertEnforcementRollout({\n orgId: parsed.value.org_id,\n decisionBand: parsed.value.decision_band,\n transactionType: parsed.value.transaction_type,\n mode: parsed.value.mode,\n featureFlag: parsed.value.feature_flag,\n fallbackToLegacy:\n parsed.value.fallback_to_legacy == null ? undefined : parsed.value.fallback_to_legacy,\n reconciliationRequired:\n parsed.value.reconciliation_required == null\n ? undefined\n : parsed.value.reconciliation_required,\n notes: parsed.value.notes,\n });\n\n return reply.code(200).send({\n updated: true,\n rollout,\n });\n });\n}\n","import { createHash, verify } from \"node:crypto\";\n\nimport {\n stableJsonStringify,\n type DecisionDossierAsymmetricProofBundle,\n} from \"./DossierIntegrity.js\";\nimport { resolveDossierVerificationKey } from \"./DossierProofBundle.js\";\n\n/**\n * Cryptographic verifier for a persisted Ed25519 proof bundle. The repo signs\n * proof bundles (`DossierProofBundle.ts`) but historically only checked\n * their structural presence (`isDecisionDossierProofBundleVerified`). An\n * escalation/dispute artifact needs a real signature check, so this recomputes\n * each artifact's canonical SHA-256 and verifies its Ed25519 signature against\n * the active public key — derived from the same key material the signer uses.\n */\n\nexport interface ProofArtifactVerification {\n artifact_kind: string;\n document_path: string;\n document_found: boolean;\n digest_matched: boolean;\n signature_verified: boolean;\n}\n\nexport interface ProofBundleVerification {\n /** True only when a key is available AND every artifact's digest + signature verify. */\n signature_verified: boolean;\n /** Whether the bundle's key_id matches the active verification key. */\n key_id_matched: boolean;\n /** True when no signing key is configured (unsigned-dev mode) — not a failure. */\n key_unavailable: boolean;\n artifact_results: ProofArtifactVerification[];\n}\n\n/** Recomputes digests and verifies Ed25519 signatures for persisted dossier proof bundles. */\nexport class DossierProofVerifier {\n static verifyDecisionDossierProofBundle(\n bundle: DecisionDossierAsymmetricProofBundle | null | undefined,\n dossierPayload: Record<string, unknown>,\n ): ProofBundleVerification {\n if (!bundle || !Array.isArray(bundle.artifacts) || bundle.artifacts.length === 0) {\n return {\n signature_verified: false,\n key_id_matched: false,\n key_unavailable: false,\n artifact_results: [],\n };\n }\n\n const key = resolveDossierVerificationKey();\n if (!key) {\n return {\n signature_verified: false,\n key_id_matched: false,\n key_unavailable: true,\n artifact_results: bundle.artifacts.map((a) => ({\n artifact_kind: a.artifact_kind,\n document_path: a.document_path,\n document_found:\n DossierProofVerifier.resolveDocument(a.document_path, dossierPayload) !== undefined,\n digest_matched: false,\n signature_verified: false,\n })),\n };\n }\n\n const artifact_results: ProofArtifactVerification[] = bundle.artifacts.map((artifact) => {\n const document = DossierProofVerifier.resolveDocument(artifact.document_path, dossierPayload);\n if (document === undefined) {\n return {\n artifact_kind: artifact.artifact_kind,\n document_path: artifact.document_path,\n document_found: false,\n digest_matched: false,\n signature_verified: false,\n };\n }\n const canonical = stableJsonStringify(document);\n const digest = createHash(\"sha256\").update(canonical, \"utf8\").digest(\"hex\");\n const digestMatched = digest === artifact.canonical_document_sha256;\n let signatureVerified = false;\n try {\n signatureVerified = verify(\n null,\n Buffer.from(canonical, \"utf8\"),\n key.public_key,\n Buffer.from(artifact.signature, \"base64url\"),\n );\n } catch {\n signatureVerified = false;\n }\n return {\n artifact_kind: artifact.artifact_kind,\n document_path: artifact.document_path,\n document_found: true,\n digest_matched: digestMatched,\n signature_verified: signatureVerified && digestMatched,\n };\n });\n\n return {\n signature_verified: artifact_results.every((r) => r.signature_verified),\n key_id_matched: bundle.key_id === key.key_id,\n key_unavailable: false,\n artifact_results,\n };\n }\n\n /** Resolve an artifact `document_path` (e.g. \"/portable_artifact\") within the dossier payload. */\n private static resolveDocument(\n documentPath: string,\n dossierPayload: Record<string, unknown>,\n ): unknown {\n const segments = documentPath.split(\"/\").filter((s) => s.length > 0);\n let cursor: unknown = dossierPayload;\n for (const segment of segments) {\n if (!cursor || typeof cursor !== \"object\") return undefined;\n cursor = (cursor as Record<string, unknown>)[segment];\n }\n return cursor;\n }\n}\n\n/** Functional alias for {@link DossierProofVerifier.verifyDecisionDossierProofBundle}. */\nexport function verifyDecisionDossierProofBundle(\n bundle: DecisionDossierAsymmetricProofBundle | null | undefined,\n dossierPayload: Record<string, unknown>,\n): ProofBundleVerification {\n return DossierProofVerifier.verifyDecisionDossierProofBundle(bundle, dossierPayload);\n}\n","import {\n buildDecisionDossierVerificationStatus,\n DECISION_DOSSIER_JWKS_PATH,\n type DecisionDossierAsymmetricProofBundle,\n type DecisionDossierVerificationStatus,\n} from \"./DossierIntegrity.js\";\nimport {\n verifyDecisionDossierProofBundle,\n type ProofArtifactVerification,\n} from \"./DossierProofVerifier.js\";\n\n/**\n * Escalation-ready proof packet — a portable, cryptographically verified bundle\n * for a single dossier (or a full decision chain) suitable for refund/overcharge\n * dispute escalation and audit. Pure assembly (no I/O): the route handler fetches\n * the dossier(s) + ledger-chain validity and passes them in.\n */\n\nconst VERIFY_STEPS = [\n \"Canonicalize each proof-bundle artifact's source document with stable (sorted-key) JSON.\",\n \"Recompute SHA-256 over the canonical bytes and confirm it matches canonical_document_sha256.\",\n \"Verify the Ed25519 signature over those bytes against the JWKS key identified by key_id.\",\n \"Confirm the ledger_entry_hash chains into the shared audit ledger (chain_verification.valid).\",\n];\n\nexport interface DossierProofResult {\n verification: DecisionDossierVerificationStatus;\n proof_artifact_results: ProofArtifactVerification[];\n proof_bundle: DecisionDossierAsymmetricProofBundle | null;\n}\n\n/** Assembles escalation-ready proof packets for dossiers and decision chains. */\nexport class ProofPacket {\n /** Verify one dossier payload: real signature check → full verification status. */\n static verifyDossierPayload(\n dossierPayload: Record<string, unknown>,\n ledgerChainValid: boolean | null,\n checkedAt: string,\n ): DossierProofResult {\n const proofBundle = ProofPacket.extractProofBundle(dossierPayload);\n const proof = verifyDecisionDossierProofBundle(proofBundle, dossierPayload);\n const verification = buildDecisionDossierVerificationStatus({\n signature_verified: proof.signature_verified,\n policy_snapshot: ProofPacket.extractPolicySnapshot(dossierPayload),\n ledger_chain_verified: ledgerChainValid,\n proof_bundle: proofBundle,\n checked_at: checkedAt,\n });\n return {\n verification,\n proof_artifact_results: proof.artifact_results,\n proof_bundle: proofBundle,\n };\n }\n\n static buildDecisionDossierProofPacket(input: {\n service: string;\n protocol_version: string;\n org_id: string;\n dossier_id: string;\n dossier_payload: Record<string, unknown>;\n ledger_chain_valid: boolean | null;\n issued_at: string;\n }): Record<string, unknown> {\n const integrity = ProofPacket.asRecord(input.dossier_payload.integrity);\n const { verification, proof_artifact_results, proof_bundle } = ProofPacket.verifyDossierPayload(\n input.dossier_payload,\n input.ledger_chain_valid,\n input.issued_at,\n );\n\n return {\n service: input.service,\n protocol_version: input.protocol_version,\n packet_type: \"decionis.decision_dossier.proof_packet\",\n packet_version: \"1.0\",\n issued_at: input.issued_at,\n subject: { org_id: input.org_id, dossier_id: input.dossier_id },\n dossier: input.dossier_payload,\n policy_snapshot: ProofPacket.extractPolicySnapshot(input.dossier_payload),\n ledger_anchor: {\n ledger_entry_id: integrity.ledger_entry_id ?? null,\n ledger_entry_hash: integrity.ledger_entry_hash ?? null,\n chain_verification: { valid: input.ledger_chain_valid },\n },\n proof_bundle,\n proof_artifact_results,\n verification,\n verify_instructions: ProofPacket.buildVerifyInstructions(proof_bundle),\n };\n }\n\n static buildDecisionChainProofPacket(input: {\n service: string;\n protocol_version: string;\n org_id: string;\n chain_id: string;\n chain_summary: unknown;\n links: Array<{ dossier_id: string; dossier_payload: Record<string, unknown> | null }>;\n ledger_chain_valid: boolean | null;\n issued_at: string;\n }): Record<string, unknown> {\n const linkResults = input.links.map((link) => {\n if (!link.dossier_payload) {\n return {\n dossier_id: link.dossier_id,\n found: false,\n verification: null,\n proof_artifact_results: [],\n };\n }\n const { verification, proof_artifact_results } = ProofPacket.verifyDossierPayload(\n link.dossier_payload,\n input.ledger_chain_valid,\n input.issued_at,\n );\n return { dossier_id: link.dossier_id, found: true, verification, proof_artifact_results };\n });\n\n const allVerified =\n linkResults.length > 0 &&\n linkResults.every((r) => r.found && r.verification?.overall === \"VERIFIED\");\n const anyVerified = linkResults.some((r) => r.found && r.verification?.signature_verified);\n const overall = allVerified ? \"VERIFIED\" : anyVerified ? \"PARTIAL\" : \"UNVERIFIED\";\n\n return {\n service: input.service,\n protocol_version: input.protocol_version,\n packet_type: \"decionis.decision_chain.proof_packet\",\n packet_version: \"1.0\",\n issued_at: input.issued_at,\n subject: { org_id: input.org_id, chain_id: input.chain_id },\n chain: input.chain_summary,\n ledger_anchor: { chain_verification: { valid: input.ledger_chain_valid } },\n links: linkResults,\n overall,\n verify_instructions: ProofPacket.buildVerifyInstructions(null),\n };\n }\n\n private static asRecord(value: unknown): Record<string, unknown> {\n return value && typeof value === \"object\" && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : {};\n }\n\n private static extractProofBundle(\n dossierPayload: Record<string, unknown>,\n ): DecisionDossierAsymmetricProofBundle | null {\n const integrity = ProofPacket.asRecord(dossierPayload.integrity);\n const bundle = integrity.proof_bundle;\n return (bundle as DecisionDossierAsymmetricProofBundle | null | undefined) ?? null;\n }\n\n private static extractPolicySnapshot(dossierPayload: Record<string, unknown>): unknown {\n const routing = ProofPacket.asRecord(dossierPayload.routing_decision);\n if (routing.policy_snapshot) return routing.policy_snapshot;\n const governance = ProofPacket.asRecord(dossierPayload.governance);\n return governance.policy_snapshot ?? null;\n }\n\n private static buildVerifyInstructions(bundle: DecisionDossierAsymmetricProofBundle | null) {\n return {\n algorithm: \"Ed25519\" as const,\n public_jwks_path: bundle?.rotation_policy?.public_jwks_path ?? DECISION_DOSSIER_JWKS_PATH,\n key_id: bundle?.key_id ?? null,\n rotation_policy: bundle?.rotation_policy ?? null,\n steps: VERIFY_STEPS,\n };\n }\n}\n\n/** Functional alias for {@link ProofPacket.verifyDossierPayload}. */\nexport function verifyDossierPayload(\n dossierPayload: Record<string, unknown>,\n ledgerChainValid: boolean | null,\n checkedAt: string,\n): DossierProofResult {\n return ProofPacket.verifyDossierPayload(dossierPayload, ledgerChainValid, checkedAt);\n}\n\n/** Functional alias for {@link ProofPacket.buildDecisionDossierProofPacket}. */\nexport function buildDecisionDossierProofPacket(input: {\n service: string;\n protocol_version: string;\n org_id: string;\n dossier_id: string;\n dossier_payload: Record<string, unknown>;\n ledger_chain_valid: boolean | null;\n issued_at: string;\n}): Record<string, unknown> {\n return ProofPacket.buildDecisionDossierProofPacket(input);\n}\n\n/** Functional alias for {@link ProofPacket.buildDecisionChainProofPacket}. */\nexport function buildDecisionChainProofPacket(input: {\n service: string;\n protocol_version: string;\n org_id: string;\n chain_id: string;\n chain_summary: unknown;\n links: Array<{ dossier_id: string; dossier_payload: Record<string, unknown> | null }>;\n ledger_chain_valid: boolean | null;\n issued_at: string;\n}): Record<string, unknown> {\n return ProofPacket.buildDecisionChainProofPacket(input);\n}\n","import type { FastifyRequest } from \"fastify\";\nimport { authenticateMcpRequest, isAuthenticationRequired } from \"../mcp.js\";\nimport type { ProtocolMcpAuthLookup } from \"../auth/McpAuth.js\";\n\n// Proof packets are escalation/audit-sensitive, so they are guarded more\n// tightly than the plain dossier/chain GETs: auth when configured, and an\n// authenticated org-API key must match the requested org (no cross-org reads).\n\n/** Authorization guard shared by the dossier and decision-chain proof-packet routes. */\nexport class ProofPacketAuth {\n static async authorizeProofPacketRead(\n req: FastifyRequest,\n orgId: string,\n authLookup: ProtocolMcpAuthLookup | null,\n ): Promise<{ code: number; body: Record<string, unknown> } | null> {\n const authCtx = await authenticateMcpRequest(req, authLookup);\n if (isAuthenticationRequired(authLookup) && !authCtx) {\n return {\n code: 401,\n body: { error: \"UNAUTHORIZED\", message: \"Valid API key required for proof packets\" },\n };\n }\n if (authCtx && authCtx.kind === \"org_api_key\" && authCtx.org_id !== orgId) {\n return {\n code: 403,\n body: { error: \"FORBIDDEN\", message: \"API key org does not match requested org_id\" },\n };\n }\n return null;\n }\n}\n\n/** Functional alias for {@link ProofPacketAuth.authorizeProofPacketRead}. */\nexport function authorizeProofPacketRead(\n req: FastifyRequest,\n orgId: string,\n authLookup: ProtocolMcpAuthLookup | null,\n): Promise<{ code: number; body: Record<string, unknown> } | null> {\n return ProofPacketAuth.authorizeProofPacketRead(req, orgId, authLookup);\n}\n","import type { FastifyInstance } from \"fastify\";\nimport type { ProtocolStore } from \"../store/StoreContracts.js\";\nimport type { ProtocolMcpAuthLookup } from \"../auth/McpAuth.js\";\nimport { buildDecisionDossierProofPacket } from \"../integrity/ProofPacket.js\";\nimport { PROTOCOL_SERVICE, PROTOCOL_VERSION } from \"../ProtocolInfo.js\";\nimport { asRecord, asString, isLikelyUuid } from \"../support/Parsing.js\";\nimport { authorizeProofPacketRead } from \"./ProofPacketAuth.js\";\n\n/** Registers the dossier retrieval and dossier proof-packet export routes. */\nexport function registerDossierRoutes(\n app: FastifyInstance,\n deps: { store: ProtocolStore; authLookup: ProtocolMcpAuthLookup | null },\n): void {\n const { store } = deps;\n const protocolAuthLookup = deps.authLookup ?? null;\n\n app.get(\"/v1/protocol/dossiers/:dossierId\", async (req, reply) => {\n const params = asRecord(req.params);\n const query = asRecord(req.query);\n const dossierId = asString(params.dossierId);\n const orgId = asString(query.org_id);\n\n if (!dossierId || !isLikelyUuid(dossierId)) {\n return reply\n .code(400)\n .send({ error: \"VALIDATION_ERROR\", message: \"Valid dossierId required\" });\n }\n if (!orgId || !isLikelyUuid(orgId)) {\n return reply.code(400).send({ error: \"VALIDATION_ERROR\", message: \"Valid org_id required\" });\n }\n\n const dossier = await store.getDecisionDossier({ orgId, dossierId });\n if (!dossier) {\n return reply.code(404).send({ error: \"NOT_FOUND\", message: \"Dossier not found\" });\n }\n return reply.code(200).send({\n service: PROTOCOL_SERVICE,\n protocol_version: PROTOCOL_VERSION,\n dossier,\n });\n });\n\n app.get(\"/v1/protocol/dossiers/:dossierId/proof-packet\", async (req, reply) => {\n const params = asRecord(req.params);\n const query = asRecord(req.query);\n const dossierId = asString(params.dossierId);\n const orgId = asString(query.org_id);\n\n if (!dossierId || !isLikelyUuid(dossierId)) {\n return reply\n .code(400)\n .send({ error: \"VALIDATION_ERROR\", message: \"Valid dossierId required\" });\n }\n if (!orgId || !isLikelyUuid(orgId)) {\n return reply.code(400).send({ error: \"VALIDATION_ERROR\", message: \"Valid org_id required\" });\n }\n const authErr = await authorizeProofPacketRead(req, orgId, protocolAuthLookup);\n if (authErr) return reply.code(authErr.code).send(authErr.body);\n\n const dossier = await store.getDecisionDossier({ orgId, dossierId });\n if (!dossier) {\n return reply.code(404).send({ error: \"NOT_FOUND\", message: \"Dossier not found\" });\n }\n const ledger = await store.verifyAuditLedgerChain({ orgId, limit: 5000 });\n const packet = buildDecisionDossierProofPacket({\n service: PROTOCOL_SERVICE,\n protocol_version: PROTOCOL_VERSION,\n org_id: orgId,\n dossier_id: dossierId,\n dossier_payload: dossier.dossier_payload,\n ledger_chain_valid: ledger.valid,\n issued_at: new Date().toISOString(),\n });\n return reply.code(200).send(packet);\n });\n}\n","import type { FastifyInstance } from \"fastify\";\nimport type { ProtocolStore } from \"../store/StoreContracts.js\";\nimport type { ProtocolMcpAuthLookup } from \"../auth/McpAuth.js\";\nimport { buildDecisionChainProofPacket } from \"../integrity/ProofPacket.js\";\nimport { PROTOCOL_SERVICE, PROTOCOL_VERSION } from \"../ProtocolInfo.js\";\nimport { asRecord, asString, isLikelyUuid } from \"../support/Parsing.js\";\nimport { authorizeProofPacketRead } from \"../dossiers/ProofPacketAuth.js\";\nimport { summarizeDecisionChainRows } from \"./DecisionChains.js\";\n\n/** Registers the decision-chain lookup and chain proof-packet export routes. */\nexport function registerDecisionChainRoutes(\n app: FastifyInstance,\n deps: { store: ProtocolStore; authLookup: ProtocolMcpAuthLookup | null },\n): void {\n const { store } = deps;\n const protocolAuthLookup = deps.authLookup ?? null;\n\n app.get(\"/v1/protocol/decision-chains/:chainId/proof-packet\", async (req, reply) => {\n const params = asRecord(req.params);\n const query = asRecord(req.query);\n const chainId = asString(params.chainId);\n const orgId = asString(query.org_id);\n\n if (!chainId || !isLikelyUuid(chainId)) {\n return reply.code(400).send({ error: \"VALIDATION_ERROR\", message: \"Valid chainId required\" });\n }\n if (!orgId || !isLikelyUuid(orgId)) {\n return reply.code(400).send({ error: \"VALIDATION_ERROR\", message: \"Valid org_id required\" });\n }\n const authErr = await authorizeProofPacketRead(req, orgId, protocolAuthLookup);\n if (authErr) return reply.code(authErr.code).send(authErr.body);\n\n const rows = await store.listDecisionChainLinks({ orgId, chainId });\n if (rows.length === 0) {\n return reply.code(404).send({ error: \"NOT_FOUND\", message: \"Decision chain not found\" });\n }\n const ledger = await store.verifyAuditLedgerChain({ orgId, limit: 5000 });\n const dossiers = await store.listDecisionDossiers({\n orgId,\n dossierIds: rows.map((row) => row.dossier_id),\n });\n const dossierById = new Map(dossiers.map((dossier) => [dossier.dossier_id, dossier]));\n const links = rows.map((row) => ({\n dossier_id: row.dossier_id,\n dossier_payload: dossierById.get(row.dossier_id)?.dossier_payload ?? null,\n }));\n const packet = buildDecisionChainProofPacket({\n service: PROTOCOL_SERVICE,\n protocol_version: PROTOCOL_VERSION,\n org_id: orgId,\n chain_id: chainId,\n chain_summary: summarizeDecisionChainRows({ orgId, chainId, rows }),\n links,\n ledger_chain_valid: ledger.valid,\n issued_at: new Date().toISOString(),\n });\n return reply.code(200).send(packet);\n });\n\n app.get(\"/v1/protocol/decision-chains/:chainId\", async (req, reply) => {\n const params = asRecord(req.params);\n const query = asRecord(req.query);\n const chainId = asString(params.chainId);\n const orgId = asString(query.org_id);\n\n if (!chainId || !isLikelyUuid(chainId)) {\n return reply.code(400).send({ error: \"VALIDATION_ERROR\", message: \"Valid chainId required\" });\n }\n if (!orgId || !isLikelyUuid(orgId)) {\n return reply.code(400).send({ error: \"VALIDATION_ERROR\", message: \"Valid org_id required\" });\n }\n\n const rows = await store.listDecisionChainLinks({ orgId, chainId });\n if (rows.length === 0) {\n return reply.code(404).send({ error: \"NOT_FOUND\", message: \"Decision chain not found\" });\n }\n\n return reply.code(200).send(summarizeDecisionChainRows({ orgId, chainId, rows }));\n });\n\n app.get(\"/v1/protocol/decision-chains/by-evaluation/:evaluationId\", async (req, reply) => {\n const params = asRecord(req.params);\n const query = asRecord(req.query);\n const evaluationId = asString(params.evaluationId);\n const orgId = asString(query.org_id);\n\n if (!evaluationId || !isLikelyUuid(evaluationId)) {\n return reply\n .code(400)\n .send({ error: \"VALIDATION_ERROR\", message: \"Valid evaluationId required\" });\n }\n if (!orgId || !isLikelyUuid(orgId)) {\n return reply.code(400).send({ error: \"VALIDATION_ERROR\", message: \"Valid org_id required\" });\n }\n\n const link = await store.getDecisionChainLinkForEvaluation({ orgId, evaluationId });\n if (!link) {\n return reply.code(404).send({ error: \"NOT_FOUND\", message: \"Decision chain not found\" });\n }\n const rows = await store.listDecisionChainLinks({ orgId, chainId: link.chain_id });\n return reply\n .code(200)\n .send(summarizeDecisionChainRows({ orgId, chainId: link.chain_id, rows }));\n });\n}\n","import { createHash, randomUUID } from \"node:crypto\";\nimport type { FastifyInstance, FastifyReply } from \"fastify\";\nimport {\n ProtocolStoreValidationError,\n type ProtocolPayload,\n type ProtocolStore,\n} from \"../store/StoreContracts.js\";\nimport {\n type ProtocolArtifact,\n validateProtocolArtifact,\n} from \"../validation/ProtocolArtifacts.js\";\nimport { computeLedgerEntryHash } from \"../ledger/LedgerChain.js\";\nimport { PROTOCOL_SERVICE, PROTOCOL_VERSION } from \"../ProtocolInfo.js\";\nimport { asString } from \"../support/Parsing.js\";\nimport type { ResolvedVerticalPack } from \"../verticals/VerticalContracts.js\";\nimport type { ShadowDecisionRequest, ShadowDecisionResult } from \"../shadow/ShadowContracts.js\";\n\n/** Shadow artifact-payload generation and generic protocol artifact ingestion. */\nexport class ArtifactIngestion {\n static createArtifactPayloads(\n request: ShadowDecisionRequest,\n shadow: ShadowDecisionResult,\n resolvedVerticalPack: ResolvedVerticalPack,\n previousLedgerHash: string | null,\n ) {\n const nowIso = new Date().toISOString();\n const engineKey = (request.engine_key ?? request.engine_chain?.[0] ?? \"software\").toLowerCase();\n const verticalPack = resolvedVerticalPack.pack;\n\n const envelopeId = randomUUID();\n const snapshotId = randomUUID();\n const bundleId = randomUUID();\n const resolutionId = randomUUID();\n const dispatchId = randomUUID();\n const ledgerEntryId = randomUUID();\n\n const intentHash = createHash(\"sha256\")\n .update(`${request.request_id}:${request.intent}`, \"utf8\")\n .digest(\"hex\");\n\n const signalEnvelope: ProtocolPayload = {\n protocol_version: PROTOCOL_VERSION,\n envelope_id: envelopeId,\n org_id: request.org_id,\n source: {\n provider: \"decionis_shadow_adapter\",\n mode: \"MANUAL\",\n },\n domain: shadow.decision_domain,\n metric_name: \"shadow_confidence\",\n metric_type: \"gauge\",\n value: shadow.confidence,\n recorded_at: nowIso,\n ingested_at: nowIso,\n dimensions: {\n engine_key: engineKey,\n request_id: request.request_id,\n vertical_pack: verticalPack.key,\n ...(request.workflow_key ? { workflow_key: request.workflow_key } : {}),\n },\n evidence: request.attachments\n .map((attachment) => asString(attachment.name))\n .filter((name): name is string => Boolean(name)),\n trace: {\n request_id: request.request_id,\n correlation_id: resolutionId,\n producer: PROTOCOL_SERVICE,\n },\n hash: intentHash,\n };\n\n const contextSnapshot: ProtocolPayload = {\n protocol_version: PROTOCOL_VERSION,\n snapshot_id: snapshotId,\n org_id: request.org_id,\n generated_at: nowIso,\n lookback: {\n hours: 24,\n },\n signal_window: {\n from: nowIso,\n to: nowIso,\n },\n signals_summary: {\n attachment_count: request.attachments.length,\n intake_signal_count: Object.keys(request.intake).length,\n confidence: shadow.confidence,\n },\n derived_features: {\n decision_domain: shadow.decision_domain,\n risk_level: shadow.risk_level,\n },\n anomalies: [],\n correlations: [],\n provenance: {\n connector_ids: [],\n signal_count: 1,\n hash: intentHash,\n },\n };\n\n const policyBundle: ProtocolPayload = {\n protocol_version: PROTOCOL_VERSION,\n bundle_id: bundleId,\n org_id: request.org_id,\n version: verticalPack.policy_bundle.version,\n effective_from: nowIso,\n rules: verticalPack.policy_bundle.rules.map((rule) => ({\n ...rule,\n rule_id: `${verticalPack.key}:${rule.rule_id}`,\n })),\n metadata: {\n author: \"decionis-shadow-adapter\",\n source: \"protocol_service\",\n change_ticket: `phase4:${verticalPack.key}`,\n },\n };\n\n const decisionResolution: ProtocolPayload = {\n protocol_version: PROTOCOL_VERSION,\n resolution_id: resolutionId,\n org_id: request.org_id,\n cycle_id: request.cycle_id,\n decision_domain: shadow.decision_domain,\n status:\n shadow.status === \"SUCCEEDED\"\n ? \"PROPOSED\"\n : shadow.status === \"NEEDS_EVIDENCE\"\n ? \"ESCALATED\"\n : \"REJECTED\",\n confidence: shadow.confidence,\n risk_level: shadow.risk_level,\n rationale: shadow.why.join(\"; \"),\n decided_at: nowIso,\n inputs: {\n context_snapshot_id: snapshotId,\n policy_bundle_id: bundleId,\n signal_ids: [envelopeId],\n },\n outputs: {\n recommended_action: shadow.recommendation,\n tags: [\"shadow\", `engine:${engineKey}`, `vertical_pack:${verticalPack.key}`],\n },\n trace: {\n trigger_id: request.request_id,\n resolver_version: \"shadow-v1\",\n deterministic_seed: intentHash.slice(0, 16),\n },\n compliance: {\n checks: [\n {\n name: \"evidence_presence\",\n result: shadow.missing_evidence.length === 0 ? \"PASS\" : \"FAIL\",\n details:\n shadow.missing_evidence.length === 0\n ? \"Required evidence available\"\n : `Missing: ${shadow.missing_evidence.join(\", \")}`,\n },\n ],\n },\n };\n\n const executionDispatch: ProtocolPayload = {\n protocol_version: PROTOCOL_VERSION,\n dispatch_id: dispatchId,\n org_id: request.org_id,\n decision_resolution_id: resolutionId,\n channel: \"INTERNAL\",\n endpoint: \"protocol://shadow\",\n payload: {\n request_id: request.request_id,\n recommendation: shadow.recommendation,\n status: shadow.status,\n vertical_pack: verticalPack.key,\n ...(request.workflow_key ? { workflow_key: request.workflow_key } : {}),\n },\n status: \"QUEUED\",\n attempt_count: 0,\n max_attempts: 3,\n scheduled_at: nowIso,\n idempotency_key: `shadow:${request.request_id}`,\n trace: {\n event_name: \"protocol.shadow.decisioning\",\n dedupe_key: request.request_id,\n correlation_id: resolutionId,\n },\n };\n\n const auditLedgerEntry: ProtocolPayload = {\n protocol_version: PROTOCOL_VERSION,\n ledger_entry_id: ledgerEntryId,\n org_id: request.org_id,\n event_type: \"DECISION_RESOLVED\",\n occurred_at: nowIso,\n actor: {\n type: \"SYSTEM\",\n id: PROTOCOL_SERVICE,\n },\n object: {\n type: \"DECISION\",\n id: resolutionId,\n },\n action: \"protocol.shadow.resolved\",\n payload: {\n request_id: request.request_id,\n status: shadow.status,\n confidence: shadow.confidence,\n vertical_pack: verticalPack.key,\n ...(request.workflow_key ? { workflow_key: request.workflow_key } : {}),\n },\n links: {\n signal_id: envelopeId,\n context_snapshot_id: snapshotId,\n policy_bundle_id: bundleId,\n decision_resolution_id: resolutionId,\n dispatch_id: dispatchId,\n },\n chain: {\n prev_hash: previousLedgerHash ?? undefined,\n entry_hash: \"\",\n algorithm: \"SHA256\",\n },\n integrity: {\n verified: false,\n },\n };\n\n const entryHash = computeLedgerEntryHash({\n ledger_entry_id: ledgerEntryId,\n org_id: request.org_id,\n event_type: \"DECISION_RESOLVED\",\n occurred_at: nowIso,\n action: \"protocol.shadow.resolved\",\n actor: auditLedgerEntry.actor,\n object: auditLedgerEntry.object,\n links: auditLedgerEntry.links,\n payload: auditLedgerEntry.payload,\n prev_hash: previousLedgerHash,\n });\n (auditLedgerEntry.chain as Record<string, unknown>).entry_hash = entryHash;\n\n return {\n ids: {\n envelope_id: envelopeId,\n snapshot_id: snapshotId,\n bundle_id: bundleId,\n resolution_id: resolutionId,\n dispatch_id: dispatchId,\n ledger_entry_id: ledgerEntryId,\n vertical_pack: verticalPack.key,\n vertical_pack_source: resolvedVerticalPack.source,\n ...(request.workflow_key ? { workflow_key: request.workflow_key } : {}),\n },\n artifacts: [\n { kind: \"signal_envelope\" as const, payload: signalEnvelope },\n { kind: \"context_snapshot\" as const, payload: contextSnapshot },\n { kind: \"policy_bundle\" as const, payload: policyBundle },\n { kind: \"decision_resolution\" as const, payload: decisionResolution },\n { kind: \"execution_dispatch\" as const, payload: executionDispatch },\n { kind: \"audit_ledger_entry\" as const, payload: auditLedgerEntry },\n ],\n };\n }\n\n static async ingestArtifact(\n app: FastifyInstance,\n reply: FastifyReply,\n store: ProtocolStore,\n kind: ProtocolArtifact,\n payload: unknown,\n ) {\n const validation = validateProtocolArtifact(kind, payload);\n if (!validation.ok) {\n return reply.code(400).send({\n error: \"VALIDATION_ERROR\",\n message: `${kind} failed schema validation`,\n issues: validation.issues,\n });\n }\n\n try {\n const saved = await store.saveArtifact(kind, validation.value);\n\n return reply.code(202).send({\n accepted: true,\n service: PROTOCOL_SERVICE,\n protocol_version: PROTOCOL_VERSION,\n artifact: kind,\n artifact_id: saved.artifact_id,\n org_id: saved.org_id,\n received_at: saved.saved_at,\n });\n } catch (err) {\n if (err instanceof ProtocolStoreValidationError) {\n return reply.code(400).send({\n error: \"VALIDATION_ERROR\",\n message: err.message,\n issues: err.issues,\n });\n }\n\n app.log.error({ err, kind }, \"Protocol artifact persistence failed\");\n return reply.code(500).send({\n error: \"PERSISTENCE_ERROR\",\n message: \"Failed to persist protocol artifact\",\n });\n }\n }\n}\n\n/** Functional alias for {@link ArtifactIngestion.createArtifactPayloads}. */\nexport function createArtifactPayloads(\n request: ShadowDecisionRequest,\n shadow: ShadowDecisionResult,\n resolvedVerticalPack: ResolvedVerticalPack,\n previousLedgerHash: string | null,\n) {\n return ArtifactIngestion.createArtifactPayloads(\n request,\n shadow,\n resolvedVerticalPack,\n previousLedgerHash,\n );\n}\n\n/** Functional alias for {@link ArtifactIngestion.ingestArtifact}. */\nexport function ingestArtifact(\n app: FastifyInstance,\n reply: FastifyReply,\n store: ProtocolStore,\n kind: ProtocolArtifact,\n payload: unknown,\n) {\n return ArtifactIngestion.ingestArtifact(app, reply, store, kind, payload);\n}\n","import type { FastifyInstance } from \"fastify\";\nimport type { ProtocolStore } from \"../store/StoreContracts.js\";\nimport { PROTOCOL_SERVICE, PROTOCOL_VERSION } from \"../ProtocolInfo.js\";\nimport { asRecord, asString, isLikelyUuid, parseListQuery } from \"../support/Parsing.js\";\nimport { loadEvaluateDecisionPolicyGuard } from \"../policy-graph/PolicyGraph.js\";\nimport { ingestArtifact } from \"./ArtifactIngestion.js\";\n\n/** Registers protocol artifact ingestion, policy runtime-status, and audit-ledger routes. */\nexport function registerArtifactRoutes(app: FastifyInstance, deps: { store: ProtocolStore }): void {\n const { store } = deps;\n\n app.post(\"/v1/protocol/signals/envelopes\", async (req, reply) =>\n ingestArtifact(app, reply, store, \"signal_envelope\", req.body),\n );\n\n app.post(\"/v1/protocol/contexts/snapshots\", async (req, reply) =>\n ingestArtifact(app, reply, store, \"context_snapshot\", req.body),\n );\n\n app.post(\"/v1/protocol/policies/bundles\", async (req, reply) =>\n ingestArtifact(app, reply, store, \"policy_bundle\", req.body),\n );\n\n app.get(\"/v1/protocol/policies/runtime-status\", async (req, reply) => {\n const query = asRecord(req.query);\n const orgId = asString(query.org_id);\n if (!orgId || !isLikelyUuid(orgId)) {\n return reply.code(400).send({ error: \"VALIDATION_ERROR\", message: \"Valid org_id required\" });\n }\n\n const policyGuard = await loadEvaluateDecisionPolicyGuard({\n store,\n orgId,\n evaluated_at: new Date().toISOString(),\n });\n\n return reply.code(200).send({\n service: PROTOCOL_SERVICE,\n protocol_version: PROTOCOL_VERSION,\n org_id: orgId,\n policy_guard: policyGuard,\n });\n });\n\n app.post(\"/v1/protocol/decisions/resolutions\", async (req, reply) =>\n ingestArtifact(app, reply, store, \"decision_resolution\", req.body),\n );\n\n app.post(\"/v1/protocol/executions/dispatches\", async (req, reply) =>\n ingestArtifact(app, reply, store, \"execution_dispatch\", req.body),\n );\n\n app.post(\"/v1/protocol/audit/ledger\", async (req, reply) =>\n ingestArtifact(app, reply, store, \"audit_ledger_entry\", req.body),\n );\n\n app.get(\"/v1/protocol/audit/ledger\", async (req) => {\n const { orgId, limit } = parseListQuery(req.query);\n const entries = await store.listAuditLedgerEntries({ orgId, limit });\n\n return {\n service: PROTOCOL_SERVICE,\n protocol_version: PROTOCOL_VERSION,\n count: entries.length,\n entries,\n };\n });\n\n app.get(\"/v1/protocol/audit/ledger/verify\", async (req, reply) => {\n const query = asRecord(req.query);\n const orgId = asString(query.org_id);\n if (!orgId) {\n return reply.code(400).send({\n error: \"VALIDATION_ERROR\",\n message: \"org_id is required\",\n });\n }\n const parsedLimit = typeof query.limit === \"string\" ? Number.parseInt(query.limit, 10) : 500;\n const limit =\n Number.isFinite(parsedLimit) && parsedLimit > 0 ? Math.min(parsedLimit, 5000) : 500;\n const verification = await store.verifyAuditLedgerChain({ orgId, limit });\n return {\n service: PROTOCOL_SERVICE,\n protocol_version: PROTOCOL_VERSION,\n ...verification,\n };\n });\n}\n","import type {\n MarketplaceProfile,\n MarketplaceReadiness,\n MarketplaceTarget,\n} from \"./MarketplaceContracts.js\";\n\nconst commonContracts = [\n \"signal_envelope\",\n \"context_snapshot\",\n \"policy_bundle\",\n \"decision_resolution\",\n \"execution_dispatch\",\n \"audit_ledger_entry\",\n];\n\nconst commonDocs = [\n \"listing-copy.md\",\n \"submission-checklist.md\",\n \"security-answers.md\",\n \"data-handling.md\",\n \"support-policy.md\",\n \"pricing-packaging.md\",\n];\n\nconst profiles: Record<MarketplaceTarget, MarketplaceProfile> = {\n atlassian: {\n target: \"atlassian\",\n display_name: \"Atlassian Marketplace\",\n ecosystem: \"Atlassian Forge private distribution\",\n delivery_model: \"WORKFLOW_COMPANION\",\n ideal_buyer: \"ITSM, engineering, and operations leaders\",\n primary_motion:\n \"Private Forge distribution with Jira-side governance panels while Decionis remains the policy source of truth\",\n required_protocol_contracts: commonContracts,\n required_docs: commonDocs,\n integration_highlights: [\n \"Forge issue panel and admin configuration wrapper\",\n \"Binding-driven Action Gate evaluation without policy logic in Forge\",\n \"Jira lifecycle sync and portable Decision Dossier distribution\",\n ],\n },\n microsoft: {\n target: \"microsoft\",\n display_name: \"Microsoft Marketplace\",\n ecosystem: \"AppSource + Azure Marketplace\",\n delivery_model: \"TRANSACTABLE_SAAS\",\n ideal_buyer: \"COO/CIO teams using Microsoft procurement channels\",\n primary_motion: \"Private-offer enterprise pilot to annual expansion\",\n required_protocol_contracts: commonContracts,\n required_docs: commonDocs,\n integration_highlights: [\n \"Commercial packaging alignment for private offers\",\n \"Enterprise security/compliance evidence export\",\n \"Azure-native identity and deployment options\",\n ],\n },\n webex: {\n target: \"webex\",\n display_name: \"Webex App Hub\",\n ecosystem: \"Webex collaboration and agentic app distribution\",\n delivery_model: \"WORKFLOW_COMPANION\",\n ideal_buyer: \"Operations, IT, and collaboration teams standardizing governed AI actions\",\n primary_motion:\n \"Keep Decionis as the policy and Decision Dossier authority while Webex remains the native collaboration and agentic-action surface\",\n required_protocol_contracts: commonContracts,\n required_docs: commonDocs,\n integration_highlights: [\n \"Native Webex delivery surface with governed route binding and Decision Dossier verification\",\n \"Agentic App packaging path through Webex MCP registration and Control Hub provisioning\",\n \"External integration surfaces exposed through Decionis Protocol without embedding policy logic in Webex\",\n ],\n },\n aws: {\n target: \"aws\",\n display_name: \"AWS Marketplace\",\n ecosystem: \"AWS commercial procurement\",\n delivery_model: \"TRANSACTABLE_SAAS\",\n ideal_buyer: \"Cloud-native platform and operations teams on AWS\",\n primary_motion: \"SaaS contract listing with private offers\",\n required_protocol_contracts: commonContracts,\n required_docs: commonDocs,\n integration_highlights: [\n \"AWS buyer procurement flow compatibility\",\n \"API-first integration for existing enterprise stacks\",\n \"Audit-ready decision dossier exports for governance teams\",\n ],\n },\n \"google-cloud\": {\n target: \"google-cloud\",\n display_name: \"Google Cloud Marketplace\",\n ecosystem: \"Google Cloud procurement\",\n delivery_model: \"TRANSACTABLE_SAAS\",\n ideal_buyer: \"Data and platform teams operating on GCP\",\n primary_motion:\n \"Integrated SaaS listing plus Vertex AI extension distribution while Decionis Protocol remains the decision authority\",\n required_protocol_contracts: commonContracts,\n required_docs: commonDocs,\n integration_highlights: [\n \"Vertex AI Extension and ADK tool surface can distribute governed decisions without embedding policy logic in Vertex\",\n \"Decisioning API compatibility with GCP-centric data stacks\",\n \"Policy-governed routing with Decision Dossier proof and auditable outcomes\",\n ],\n },\n slack: {\n target: \"slack\",\n display_name: \"Decionis for Slack\",\n ecosystem: \"Slack App Directory\",\n delivery_model: \"WORKFLOW_COMPANION\",\n ideal_buyer: \"SMB finance, revenue operations, and customer-impact teams\",\n primary_motion:\n \"Use Slack as the native acknowledgment surface for governed Decision Dossiers while Decionis remains the policy and execution authority\",\n required_protocol_contracts: commonContracts,\n required_docs: commonDocs,\n integration_highlights: [\n \"Decision Dossier Block Kit cards with verdict, risk, reason, policy version, actions, and verification\",\n \"Slack-native approve, reject, escalate, delay, request-context, and explain-decision interactions\",\n \"Shadow Mode onboarding before enforcement blocks or releases downstream execution\",\n ],\n },\n github: {\n target: \"github\",\n display_name: \"GitHub Marketplace\",\n ecosystem: \"GitHub apps + marketplace listing\",\n delivery_model: \"WORKFLOW_COMPANION\",\n ideal_buyer: \"Engineering and platform leadership teams\",\n primary_motion: \"Decision governance linked to repos/issues/PR workflows\",\n required_protocol_contracts: commonContracts,\n required_docs: commonDocs,\n integration_highlights: [\n \"ADR and decision-log workflow integration\",\n \"Issue/PR-linked governance evidence\",\n \"Engineering-first distribution motion\",\n ],\n },\n servicenow: {\n target: \"servicenow\",\n display_name: \"ServiceNow Store\",\n ecosystem: \"ServiceNow enterprise workflows\",\n delivery_model: \"ENTERPRISE_CONNECTOR\",\n ideal_buyer: \"Enterprise service and IT operations owners\",\n primary_motion:\n \"ServiceNow stays the workflow record while Decionis enforces deterministic execution governance\",\n required_protocol_contracts: commonContracts,\n required_docs: commonDocs,\n integration_highlights: [\n \"Callable policy-check action for approvals and governed execution\",\n \"Decision Dossier panel with audit-ready outcome evidence\",\n \"Shadow-mode rollout before enforcement in GRC, ITOM, and finance-adjacent flows\",\n ],\n },\n salesforce: {\n target: \"salesforce\",\n display_name: \"Salesforce AppExchange\",\n ecosystem: \"Salesforce CRM + Service Cloud\",\n delivery_model: \"ENTERPRISE_CONNECTOR\",\n ideal_buyer: \"Revenue, finance, and service operations leaders\",\n primary_motion:\n \"Decision authority for autonomous Salesforce actions and cross-system execution governance\",\n required_protocol_contracts: commonContracts,\n required_docs: commonDocs,\n integration_highlights: [\n \"Callable Action Gate wrapper for Flow, Apex, and Agentforce\",\n \"Record-side Decision Dossier component with verification link and signature\",\n \"Shadow-mode rollout and MuleSoft handoff for cross-system execution\",\n ],\n },\n amazon: {\n target: \"amazon\",\n display_name: \"Amazon Selling Partner\",\n ecosystem: \"Amazon marketplace (SP-API)\",\n delivery_model: \"ENTERPRISE_CONNECTOR\",\n ideal_buyer: \"High-volume Amazon sellers and marketplace operations teams\",\n primary_motion:\n \"Deterministic margin and pricing governance for Amazon listings and orders via SP-API\",\n required_protocol_contracts: commonContracts,\n required_docs: commonDocs,\n integration_highlights: [\n \"Login with Amazon (LWA) OAuth with encrypted refresh-token storage\",\n \"SP-API Orders and Product Pricing margin gate reusing the shared commerce engine\",\n \"Signed Decision Dossiers federated into the cross-surface audit ledger\",\n ],\n },\n ebay: {\n target: \"ebay\",\n display_name: \"eBay Marketplace\",\n ecosystem: \"eBay marketplace (Sell APIs)\",\n delivery_model: \"ENTERPRISE_CONNECTOR\",\n ideal_buyer: \"High-volume eBay sellers and marketplace operations teams\",\n primary_motion:\n \"Deterministic margin and promo-hygiene governance for eBay listings, orders, and promotions via the Sell APIs\",\n required_protocol_contracts: commonContracts,\n required_docs: commonDocs,\n integration_highlights: [\n \"eBay OAuth2 (Basic-auth token exchange) with encrypted refresh-token storage\",\n \"Sell Fulfillment + Marketing margin & promo-hygiene gates reusing the shared commerce engine\",\n \"Signed Decision Dossiers federated into the cross-surface audit ledger\",\n ],\n },\n sap: {\n target: \"sap\",\n display_name: \"SAP S/4HANA\",\n ecosystem: \"SAP BTP + S/4HANA (OData / Event Mesh)\",\n delivery_model: \"ENTERPRISE_CONNECTOR\",\n ideal_buyer: \"Procurement, finance, and treasury operations on SAP S/4HANA\",\n primary_motion:\n \"Dual-gate governance for high-value SAP execution (purchase orders, vendor payments) with signed dossiers written back into S/4HANA at the execution boundary\",\n required_protocol_contracts: commonContracts,\n required_docs: commonDocs,\n integration_highlights: [\n \"Dual-gate evaluation (state admission + execution authority) federated into the shared decision engine\",\n \"Duplicate-payment and three-way-match (PO ↔ goods receipt ↔ invoice) controls before payment release\",\n \"Active S/4HANA write-back via BTP destination plus Event Mesh bypass reconciliation, and SAP-as-system-of-record cost truth for the commerce surfaces\",\n ],\n },\n bigcommerce: {\n target: \"bigcommerce\",\n display_name: \"BigCommerce\",\n ecosystem: \"BigCommerce SaaS storefronts (Store API + Webhooks v3)\",\n delivery_model: \"SaaS\",\n ideal_buyer: \"Mid-market omnichannel merchants on BigCommerce (incl. headless)\",\n primary_motion:\n \"Synchronous margin-floor enforcement at checkout (headless / Open Checkout) plus promo-hygiene governance for BigCommerce carts, orders, and promotions\",\n required_protocol_contracts: commonContracts,\n required_docs: commonDocs,\n integration_highlights: [\n \"BigCommerce OAuth app install (permanent store token) with encrypted credential storage\",\n \"Synchronous checkout-validate gate (fail-open) reusing the shared margin engine; Webhooks v3 observe path\",\n \"Signed Decision Dossiers federated into the cross-surface audit ledger\",\n ],\n },\n \"adobe-commerce\": {\n target: \"adobe-commerce\",\n display_name: \"Adobe Commerce\",\n ecosystem: \"Adobe Commerce / Magento (App Builder webhooks + REST)\",\n delivery_model: \"ENTERPRISE_CONNECTOR\",\n ideal_buyer: \"Enterprise ops and B2B teams on Adobe Commerce / Magento\",\n primary_motion:\n \"Synchronous margin-floor enforcement at checkout via Adobe Commerce webhooks (block/allow) plus promo-hygiene governance for quotes, orders, and cart price rules\",\n required_protocol_contracts: commonContracts,\n required_docs: commonDocs,\n integration_highlights: [\n \"Adobe IMS (App Builder) server-to-server auth and/or Magento integration token, with encrypted credential storage\",\n \"Synchronous checkout webhook gate (op:success / op:exception, fail-open) reusing the shared margin engine; cost basis derived from Magento product cost\",\n \"Signed Decision Dossiers federated into the cross-surface audit ledger\",\n ],\n },\n shopware: {\n target: \"shopware\",\n display_name: \"Shopware\",\n ecosystem: \"Shopware 6 App System (registration handshake + signed webhooks)\",\n delivery_model: \"ENTERPRISE_CONNECTOR\",\n ideal_buyer: \"European mid-market and B2B retail on Shopware 6\",\n primary_motion:\n \"Promo-hygiene and margin governance for Shopware carts, orders, and promotions, with a best-effort synchronous checkout gate for app-script / headless callers\",\n required_protocol_contracts: commonContracts,\n required_docs: commonDocs,\n integration_highlights: [\n \"Shopware App System registration handshake (proof + per-shop secret) with encrypted credential storage\",\n \"Shop-signed webhook ingestion + Admin-API client; synchronous checkout gate (fail-open) reusing the shared margin engine\",\n \"Signed Decision Dossiers federated into the cross-surface audit ledger\",\n ],\n },\n sfcc: {\n target: \"sfcc\",\n display_name: \"Salesforce Commerce Cloud\",\n ecosystem: \"SFCC B2C Commerce (SCAPI + OCAPI checkout hooks)\",\n delivery_model: \"ENTERPRISE_CONNECTOR\",\n ideal_buyer: \"Fortune 500 B2C/B2B retail networks on Salesforce Commerce Cloud\",\n primary_motion:\n \"Synchronous margin-floor enforcement at order placement via an OCAPI/SCAPI checkout hook calling the hosted Decionis gate, plus promo-hygiene governance\",\n required_protocol_contracts: commonContracts,\n required_docs: commonDocs,\n integration_highlights: [\n \"SFCC Account Manager OAuth (client credentials) + SCAPI baskets/orders client, with encrypted credential storage\",\n \"Hosted synchronous /sfcc/basket/validate gate (shared-bearer authenticated, fail-open) called by the OCAPI checkout hook; reuses the shared margin engine\",\n \"Signed Decision Dossiers federated into the cross-surface audit ledger\",\n ],\n },\n woo: {\n target: \"woo\",\n display_name: \"WooCommerce\",\n ecosystem: \"WooCommerce (Block Checkout, classic checkout, REST API, and HPOS)\",\n delivery_model: \"SaaS\",\n ideal_buyer: \"SMB and mid-market merchants running WooCommerce\",\n primary_motion:\n \"Shadow-first margin-floor governance at checkout through a native Woo plugin and hosted fail-open decision gate\",\n required_protocol_contracts: commonContracts,\n required_docs: commonDocs,\n integration_highlights: [\n \"Native /wc-auth/v1/authorize connection with encrypted REST credentials\",\n \"One shared gate for Block and classic checkout, backed by WooCommerce core COGS and the shared commerce engine\",\n \"HPOS-compatible order receipts and signed Decision Dossiers in the cross-surface audit ledger\",\n ],\n },\n jumia: {\n target: \"jumia\",\n display_name: \"Jumia Vendor Center\",\n ecosystem: \"Jumia Vendor Center GOP API\",\n delivery_model: \"ENTERPRISE_CONNECTOR\",\n ideal_buyer: \"Multi-market Jumia sellers managing margin, COD, FX, and fulfillment SLAs\",\n primary_motion:\n \"Shadow-first post-order governance before pack and ready-to-ship actions across connected Jumia shops\",\n required_protocol_contracts: commonContracts,\n required_docs: commonDocs,\n integration_highlights: [\n \"Centralized Mastershop OAuth with encrypted token refresh and shop discovery\",\n \"Durable, rate-limited pending-order polling with country-aware risk signals\",\n \"Guarded fulfillment release and sanitized Decision Dossiers in the shared audit ledger\",\n ],\n },\n};\n\nconst readiness: Record<MarketplaceTarget, MarketplaceReadiness> = {\n atlassian: {\n target: \"atlassian\",\n protocol_capture: \"CAPTURED\",\n adapter_state: \"LIVE\",\n docs_state: \"LIVE\",\n launch_state: \"BUILDING\",\n next_milestone:\n \"Finalize Forge private-distribution kit and production install-link validation\",\n },\n microsoft: {\n target: \"microsoft\",\n protocol_capture: \"CAPTURED\",\n adapter_state: \"BUILDING\",\n docs_state: \"LIVE\",\n launch_state: \"PLANNED\",\n next_milestone: \"Prepare transactable offer package and private-offer workflow evidence\",\n },\n webex: {\n target: \"webex\",\n protocol_capture: \"CAPTURED\",\n adapter_state: \"LIVE\",\n docs_state: \"LIVE\",\n launch_state: \"BUILDING\",\n next_milestone:\n \"Resubmit with zero-website JIT on-ramps (Control Hub authorization + Embedded App on-load); authorize the Service App for the target org in Control Hub and validate the on-ramps live\",\n },\n aws: {\n target: \"aws\",\n protocol_capture: \"CAPTURED\",\n adapter_state: \"LIVE\",\n docs_state: \"LIVE\",\n launch_state: \"BUILDING\",\n next_milestone:\n \"Validate Marketplace metering/entitlement against a staging SaaS product, then submit the listing\",\n },\n \"google-cloud\": {\n target: \"google-cloud\",\n protocol_capture: \"CAPTURED\",\n adapter_state: \"BUILDING\",\n docs_state: \"LIVE\",\n launch_state: \"PLANNED\",\n next_milestone:\n \"Ship the Vertex extension adapter and registration artifacts while keeping Protocol as the execution-time authority\",\n },\n slack: {\n target: \"slack\",\n protocol_capture: \"CAPTURED\",\n adapter_state: \"LIVE\",\n docs_state: \"LIVE\",\n launch_state: \"BUILDING\",\n next_milestone: \"Finalize app-directory listing metadata and production review flow\",\n },\n github: {\n target: \"github\",\n protocol_capture: \"CAPTURED\",\n adapter_state: \"LIVE\",\n docs_state: \"LIVE\",\n launch_state: \"BUILDING\",\n next_milestone: \"Complete marketplace listing prerequisites and billing validation\",\n },\n servicenow: {\n target: \"servicenow\",\n protocol_capture: \"CAPTURED\",\n adapter_state: \"LIVE\",\n docs_state: \"LIVE\",\n launch_state: \"BUILDING\",\n next_milestone: \"Run production qualification suite and store submission kit\",\n },\n salesforce: {\n target: \"salesforce\",\n protocol_capture: \"CAPTURED\",\n adapter_state: \"LIVE\",\n docs_state: \"LIVE\",\n launch_state: \"BUILDING\",\n next_milestone:\n \"Front-to-back Salesforce → SAP revenue surface federated (dual-gate, signed dossiers); wire the margin gate to live SAP cost basis and ship the SAP-side verify_dossier_proof module, then run the AppExchange security-review package\",\n },\n amazon: {\n target: \"amazon\",\n protocol_capture: \"CAPTURED\",\n adapter_state: \"BUILDING\",\n docs_state: \"PLANNED\",\n launch_state: \"PLANNED\",\n next_milestone:\n \"Verify the SP-API connector against a live seller account, then enable shadow-mode drift reports\",\n },\n ebay: {\n target: \"ebay\",\n protocol_capture: \"CAPTURED\",\n adapter_state: \"LIVE\",\n docs_state: \"LIVE\",\n launch_state: \"BUILDING\",\n next_milestone:\n \"Complete eBay partner review and verify the deployed read-only connector against a live seller account before promoting the private beta\",\n },\n sap: {\n target: \"sap\",\n protocol_capture: \"CAPTURED\",\n adapter_state: \"LIVE\",\n docs_state: \"LIVE\",\n launch_state: \"BUILDING\",\n next_milestone:\n \"Validate active S/4HANA write-back and Event Mesh reconciliation against a live BTP destination, then run the enforcement-mode rollout\",\n },\n bigcommerce: {\n target: \"bigcommerce\",\n protocol_capture: \"CAPTURED\",\n adapter_state: \"BUILDING\",\n docs_state: \"PLANNED\",\n launch_state: \"PLANNED\",\n next_milestone:\n \"Verify the Store-API connector + synchronous checkout gate against a live BigCommerce store, then enable enforcement\",\n },\n \"adobe-commerce\": {\n target: \"adobe-commerce\",\n protocol_capture: \"CAPTURED\",\n // adapter_state stays BUILDING deliberately: Adobe's Marketplace\n // technical review passed in full (all phases, SID qv4l7d2ak6 — automated\n // EQP 2026-07-08, final confirmation 2026-08-10, tested on Magento 2.4.9\n // EE + CE / PHP 8.5.5), but the gate has not yet run against a live\n // merchant store, and that is the bar LIVE means here.\n adapter_state: \"BUILDING\",\n docs_state: \"BUILDING\",\n launch_state: \"PLANNED\",\n next_milestone:\n \"All Adobe Marketplace technical review phases passed (SID qv4l7d2ak6); ship the customer-deployable connector kit, onboard a live Adobe Commerce store in shadow, verify the checkout gate, then promote it to enforcement\",\n },\n shopware: {\n target: \"shopware\",\n protocol_capture: \"CAPTURED\",\n adapter_state: \"BUILDING\",\n docs_state: \"PLANNED\",\n launch_state: \"PLANNED\",\n next_milestone:\n \"Verify the App System registration + signed webhooks against a live Shopware store; Shopware's standard webhooks are async, so enforcement runs via the app-script/headless gate\",\n },\n sfcc: {\n target: \"sfcc\",\n protocol_capture: \"CAPTURED\",\n adapter_state: \"BUILDING\",\n docs_state: \"PLANNED\",\n launch_state: \"PLANNED\",\n next_milestone:\n \"Build + certify the SFCC cartridge against an SFCC sandbox (Salesforce partner code certification), then enable the hosted synchronous gate in enforcement\",\n },\n woo: {\n target: \"woo\",\n protocol_capture: \"CAPTURED\",\n // Truth-up 2026-08-10: the plugin is published in the WordPress.org\n // directory (slug `decionis`, 1.0.0) and Block + classic checkout,\n // core COGS, HPOS order CRUD, and the signed dossier were verified end\n // to end on a staging store — including an admin-enabled ENFORCEMENT\n // block — before the listing went live (shared readiness provenance).\n // The previous PLANNED states predated the public listing.\n adapter_state: \"LIVE\",\n docs_state: \"LIVE\",\n launch_state: \"BUILDING\",\n next_milestone:\n \"WordPress.org listing is live and self-serve; grow installs and collect the first live-store enforcement evidence for the listing's proof section\",\n },\n jumia: {\n target: \"jumia\",\n protocol_capture: \"CAPTURED\",\n adapter_state: \"BUILDING\",\n docs_state: \"BUILDING\",\n launch_state: \"PLANNED\",\n next_milestone:\n \"Validate OAuth, provider mappings, and pack/ready-to-ship behavior against a live Vendor Center sandbox before enabling enforcement\",\n },\n};\n\n/** Static catalog of marketplace launch profiles and readiness states. */\nexport class MarketplaceProfiles {\n static listProfiles(): MarketplaceProfile[] {\n return Object.values(profiles);\n }\n\n static getProfile(target: MarketplaceTarget): MarketplaceProfile {\n return profiles[target];\n }\n\n static listReadiness(): MarketplaceReadiness[] {\n return Object.values(readiness);\n }\n\n static getReadiness(target: MarketplaceTarget): MarketplaceReadiness {\n return readiness[target];\n }\n}\n\n/** Functional alias for {@link MarketplaceProfiles.listProfiles}. */\nexport function listMarketplaceProfiles(): MarketplaceProfile[] {\n return MarketplaceProfiles.listProfiles();\n}\n\n/** Functional alias for {@link MarketplaceProfiles.getProfile}. */\nexport function getMarketplaceProfile(target: MarketplaceTarget): MarketplaceProfile {\n return MarketplaceProfiles.getProfile(target);\n}\n\n/** Functional alias for {@link MarketplaceProfiles.listReadiness}. */\nexport function listMarketplaceReadiness(): MarketplaceReadiness[] {\n return MarketplaceProfiles.listReadiness();\n}\n\n/** Functional alias for {@link MarketplaceProfiles.getReadiness}. */\nexport function getMarketplaceReadiness(target: MarketplaceTarget): MarketplaceReadiness {\n return MarketplaceProfiles.getReadiness(target);\n}\n","export const PROTOCOL_MARKETPLACE_TARGETS = [\n \"atlassian\",\n \"microsoft\",\n \"webex\",\n \"aws\",\n \"google-cloud\",\n \"slack\",\n \"github\",\n \"servicenow\",\n \"salesforce\",\n \"amazon\",\n \"ebay\",\n \"sap\",\n \"bigcommerce\",\n \"adobe-commerce\",\n \"shopware\",\n \"sfcc\",\n \"woo\",\n \"jumia\",\n] as const;\n\nexport type MarketplaceTarget = (typeof PROTOCOL_MARKETPLACE_TARGETS)[number];\n\nexport type MarketplaceDeliveryModel =\n | \"WORKFLOW_COMPANION\"\n | \"SaaS\"\n | \"TRANSACTABLE_SAAS\"\n | \"ENTERPRISE_CONNECTOR\";\n\nexport type MarketplaceCoverageStatus = \"LIVE\" | \"BUILDING\" | \"PLANNED\";\n\nexport interface MarketplaceProfile {\n target: MarketplaceTarget;\n display_name: string;\n ecosystem: string;\n delivery_model: MarketplaceDeliveryModel;\n ideal_buyer: string;\n primary_motion: string;\n required_protocol_contracts: string[];\n required_docs: string[];\n integration_highlights: string[];\n}\n\nexport interface MarketplaceReadiness {\n target: MarketplaceTarget;\n protocol_capture: \"CAPTURED\";\n adapter_state: MarketplaceCoverageStatus;\n docs_state: MarketplaceCoverageStatus;\n launch_state: MarketplaceCoverageStatus;\n next_milestone: string;\n}\n","import type { FastifyInstance } from \"fastify\";\nimport { PROTOCOL_SERVICE, PROTOCOL_VERSION } from \"../ProtocolInfo.js\";\nimport { asRecord, asString } from \"../support/Parsing.js\";\nimport {\n getMarketplaceProfile,\n getMarketplaceReadiness,\n listMarketplaceProfiles,\n listMarketplaceReadiness,\n} from \"./MarketplaceProfiles.js\";\nimport { PROTOCOL_MARKETPLACE_TARGETS, type MarketplaceTarget } from \"./MarketplaceContracts.js\";\n\n/** Marketplace-target query parsing for the marketplace catalog routes. */\nexport class MarketplaceRouteParsing {\n static parseMarketplaceTarget(input: unknown): MarketplaceTarget | null {\n const value = asString(input)?.toLowerCase();\n if (!value) return null;\n return PROTOCOL_MARKETPLACE_TARGETS.includes(value as MarketplaceTarget)\n ? (value as MarketplaceTarget)\n : null;\n }\n}\n\n/** Functional alias for {@link MarketplaceRouteParsing.parseMarketplaceTarget}. */\nexport function parseMarketplaceTarget(input: unknown): MarketplaceTarget | null {\n return MarketplaceRouteParsing.parseMarketplaceTarget(input);\n}\n\n/** Registers the marketplace target and readiness catalog routes. */\nexport function registerMarketplaceRoutes(app: FastifyInstance): void {\n app.get(\"/v1/protocol/marketplaces/targets\", async () => {\n const profiles = listMarketplaceProfiles().map((profile) => {\n const readiness = getMarketplaceReadiness(profile.target);\n return {\n target: profile.target,\n display_name: profile.display_name,\n ecosystem: profile.ecosystem,\n delivery_model: profile.delivery_model,\n primary_motion: profile.primary_motion,\n adapter_state: readiness.adapter_state,\n docs_state: readiness.docs_state,\n launch_state: readiness.launch_state,\n };\n });\n return {\n service: PROTOCOL_SERVICE,\n protocol_version: PROTOCOL_VERSION,\n count: profiles.length,\n targets: profiles,\n };\n });\n\n app.get(\"/v1/protocol/marketplaces/targets/:target\", async (req, reply) => {\n const params = asRecord(req.params);\n const target = parseMarketplaceTarget(params.target);\n if (!target) {\n return reply.code(404).send({\n error: \"NOT_FOUND\",\n message: \"Unknown marketplace target\",\n });\n }\n\n const profile = getMarketplaceProfile(target);\n const readiness = getMarketplaceReadiness(target);\n const docsCatalog = profile.required_docs.map((file) => ({\n file,\n path: `docs/marketplace/${profile.target}/${file}`,\n }));\n\n return {\n service: PROTOCOL_SERVICE,\n protocol_version: PROTOCOL_VERSION,\n target: profile.target,\n profile,\n readiness,\n docs_catalog: docsCatalog,\n };\n });\n\n app.get(\"/v1/protocol/marketplaces/readiness\", async (req, reply) => {\n const query = asRecord(req.query);\n const requestedTargetRaw = query.target;\n const requestedTarget = parseMarketplaceTarget(requestedTargetRaw);\n if (requestedTargetRaw != null && !requestedTarget) {\n return reply.code(400).send({\n error: \"VALIDATION_ERROR\",\n message: \"Unknown marketplace target\",\n });\n }\n\n const entries = requestedTarget\n ? [getMarketplaceReadiness(requestedTarget)]\n : listMarketplaceReadiness();\n return {\n service: PROTOCOL_SERVICE,\n protocol_version: PROTOCOL_VERSION,\n count: entries.length,\n readiness: entries,\n };\n });\n}\n","import type { FastifyInstance } from \"fastify\";\nimport type { ProtocolStore } from \"../store/StoreContracts.js\";\nimport { PROTOCOL_SERVICE, PROTOCOL_VERSION } from \"../ProtocolInfo.js\";\nimport { asRecord, asString } from \"../support/Parsing.js\";\nimport { getVerticalPack, listVerticalPacks } from \"./VerticalRegistry.js\";\nimport { resolveVerticalPackForRequest } from \"./VerticalResolver.js\";\n\n/** Org vertical-pack mutation parsing for the vertical catalog routes. */\nexport class VerticalRouteParsing {\n static parseVerticalPackMutation(input: unknown):\n | { ok: true; value: { org_id: string; pack_key: string; config: Record<string, unknown> } }\n | {\n ok: false;\n message: string;\n } {\n const record = asRecord(input);\n const orgId = asString(record.org_id);\n if (!orgId) return { ok: false, message: \"org_id is required\" };\n\n const packKey = asString(record.pack_key);\n if (!packKey) return { ok: false, message: \"pack_key is required\" };\n\n const config = asRecord(record.config);\n return {\n ok: true,\n value: {\n org_id: orgId,\n pack_key: packKey,\n config,\n },\n };\n }\n}\n\n/** Functional alias for {@link VerticalRouteParsing.parseVerticalPackMutation}. */\nexport function parseVerticalPackMutation(input: unknown):\n | { ok: true; value: { org_id: string; pack_key: string; config: Record<string, unknown> } }\n | {\n ok: false;\n message: string;\n } {\n return VerticalRouteParsing.parseVerticalPackMutation(input);\n}\n\n/** Registers the vertical pack catalog, resolution, and org-pack mutation routes. */\nexport function registerVerticalRoutes(app: FastifyInstance, deps: { store: ProtocolStore }): void {\n const { store } = deps;\n\n app.get(\"/v1/protocol/verticals/packs\", async () => {\n const packs = listVerticalPacks().map((pack) => ({\n key: pack.key,\n workflow_keys: pack.workflow_keys ?? [],\n display_name: pack.display_name,\n description: pack.description,\n default_domain: pack.default_domain,\n signal_mappings: pack.signal_mappings,\n policy_bundle_version: pack.policy_bundle.version,\n ui_copy: pack.ui_copy,\n }));\n\n return {\n service: PROTOCOL_SERVICE,\n protocol_version: PROTOCOL_VERSION,\n count: packs.length,\n packs,\n };\n });\n\n app.get(\"/v1/protocol/verticals/resolve\", async (req, reply) => {\n const query = asRecord(req.query);\n const orgId = asString(query.org_id);\n if (!orgId) {\n return reply.code(400).send({\n error: \"VALIDATION_ERROR\",\n message: \"org_id is required\",\n });\n }\n\n const requestedPackKey = asString(query.pack_key) ?? undefined;\n const workflowKey = asString(query.workflow_key) ?? undefined;\n if (requestedPackKey && !getVerticalPack(requestedPackKey)) {\n return reply.code(400).send({\n error: \"VALIDATION_ERROR\",\n message: `Unknown vertical pack '${requestedPackKey}'`,\n });\n }\n\n const resolved = await resolveVerticalPackForRequest({\n store,\n orgId,\n requestedPackKey,\n workflowKey,\n });\n\n return {\n org_id: orgId,\n workflow_key: workflowKey ?? null,\n pack_key: resolved.pack.key,\n source: resolved.source,\n display_name: resolved.pack.display_name,\n default_domain: resolved.pack.default_domain,\n };\n });\n\n app.put(\"/v1/protocol/verticals/org-pack\", async (req, reply) => {\n const parsed = parseVerticalPackMutation(req.body);\n if (!parsed.ok) {\n return reply.code(400).send({\n error: \"VALIDATION_ERROR\",\n message: parsed.message,\n });\n }\n\n if (!getVerticalPack(parsed.value.pack_key)) {\n return reply.code(400).send({\n error: \"VALIDATION_ERROR\",\n message: `Unknown vertical pack '${parsed.value.pack_key}'`,\n });\n }\n\n const updated = await store.setOrgVerticalPack({\n orgId: parsed.value.org_id,\n packKey: parsed.value.pack_key,\n config: parsed.value.config,\n updatedBy: \"protocol-api\",\n });\n\n return reply.code(200).send({\n updated: true,\n org_id: updated.org_id,\n pack_key: updated.pack_key,\n config: updated.config,\n updated_at: updated.updated_at,\n });\n });\n}\n","import { createHash } from \"node:crypto\";\nimport type { FastifyInstance } from \"fastify\";\nimport { ProtocolStoreValidationError, type ProtocolStore } from \"../store/StoreContracts.js\";\nimport { validateProtocolArtifact } from \"../validation/ProtocolArtifacts.js\";\nimport { PROTOCOL_SERVICE, PROTOCOL_VERSION } from \"../ProtocolInfo.js\";\nimport { getVerticalPack } from \"../verticals/VerticalRegistry.js\";\nimport { resolveVerticalPackForRequest } from \"../verticals/VerticalResolver.js\";\nimport { createArtifactPayloads } from \"../artifacts/ArtifactIngestion.js\";\nimport { buildShadowDecision, parseShadowRequest } from \"./ShadowDecisioning.js\";\nimport {\n parseShadowEvaluateDecisionReportsQuery,\n summarizeShadowEvaluateDecisionReports,\n toShadowEvaluateDecisionReportItem,\n} from \"./ShadowReports.js\";\nimport type { ShadowDossierSimulation } from \"./ShadowContracts.js\";\n\n/** Registers the shadow evaluate-decision report routes and shadow decisioning route. */\nexport function registerShadowRoutes(app: FastifyInstance, deps: { store: ProtocolStore }): void {\n const { store } = deps;\n\n app.get(\"/v1/protocol/shadow/evaluate-decision/reports\", async (req, reply) => {\n const parsed = parseShadowEvaluateDecisionReportsQuery(req.query);\n if (!parsed.ok) {\n return reply.code(400).send({ error: \"VALIDATION_ERROR\", message: parsed.message });\n }\n\n const rows = await store.listDecisionEvaluations({\n orgId: parsed.value.org_id,\n mode: parsed.value.mode,\n since: parsed.value.since,\n limit: parsed.value.limit,\n });\n const reports = rows.map(toShadowEvaluateDecisionReportItem);\n\n return reply.code(200).send({\n service: PROTOCOL_SERVICE,\n protocol_version: PROTOCOL_VERSION,\n generated_at: new Date().toISOString(),\n org_id: parsed.value.org_id,\n mode: parsed.value.mode,\n since: parsed.value.since_raw,\n count: reports.length,\n reports,\n summary: summarizeShadowEvaluateDecisionReports(reports),\n });\n });\n\n app.get(\"/v1/protocol/shadow/evaluate-decision/reports/summary\", async (req, reply) => {\n const parsed = parseShadowEvaluateDecisionReportsQuery(req.query);\n if (!parsed.ok) {\n return reply.code(400).send({ error: \"VALIDATION_ERROR\", message: parsed.message });\n }\n\n const rows = await store.listDecisionEvaluations({\n orgId: parsed.value.org_id,\n mode: parsed.value.mode,\n since: parsed.value.since,\n limit: parsed.value.limit,\n });\n const reports = rows.map(toShadowEvaluateDecisionReportItem);\n\n return reply.code(200).send({\n service: PROTOCOL_SERVICE,\n protocol_version: PROTOCOL_VERSION,\n generated_at: new Date().toISOString(),\n org_id: parsed.value.org_id,\n mode: parsed.value.mode,\n since: parsed.value.since_raw,\n summary: summarizeShadowEvaluateDecisionReports(reports),\n });\n });\n\n app.post(\"/v1/protocol/shadow/decisioning\", async (req, reply) => {\n const parsed = parseShadowRequest(req.body);\n if (!parsed.ok) {\n return reply.code(400).send({ error: \"VALIDATION_ERROR\", message: parsed.message });\n }\n\n if (parsed.value.vertical_pack && !getVerticalPack(parsed.value.vertical_pack)) {\n return reply.code(400).send({\n error: \"VALIDATION_ERROR\",\n message: `Unknown vertical pack '${parsed.value.vertical_pack}'`,\n });\n }\n\n const resolvedVerticalPack = await resolveVerticalPackForRequest({\n store,\n orgId: parsed.value.org_id,\n requestedPackKey: parsed.value.vertical_pack,\n workflowKey: parsed.value.workflow_key,\n });\n const shadow = buildShadowDecision(parsed.value, resolvedVerticalPack);\n const previousHead = await store.getLatestAuditLedgerHead(parsed.value.org_id);\n const artifacts = createArtifactPayloads(\n parsed.value,\n shadow,\n resolvedVerticalPack,\n previousHead?.entry_hash ?? null,\n );\n\n for (const artifact of artifacts.artifacts) {\n const validation = validateProtocolArtifact(artifact.kind, artifact.payload);\n if (!validation.ok) {\n app.log.error(\n { kind: artifact.kind, issues: validation.issues },\n \"Generated shadow artifact failed protocol validation\",\n );\n return reply.code(500).send({\n error: \"INTERNAL_ERROR\",\n message: `Generated shadow artifact '${artifact.kind}' failed validation`,\n });\n }\n\n try {\n await store.saveArtifact(artifact.kind, validation.value);\n } catch (err) {\n if (err instanceof ProtocolStoreValidationError) {\n return reply.code(400).send({\n error: \"VALIDATION_ERROR\",\n message: err.message,\n issues: err.issues,\n });\n }\n app.log.error({ err, kind: artifact.kind }, \"Shadow artifact persistence failed\");\n return reply.code(500).send({\n error: \"PERSISTENCE_ERROR\",\n message: \"Failed to persist shadow artifacts\",\n });\n }\n }\n\n const dossierSimulation: ShadowDossierSimulation = {\n dossier_id: artifacts.ids.resolution_id,\n dossier_sha256: createHash(\"sha256\")\n .update(\n `${parsed.value.request_id}:${shadow.status}:${shadow.recommendation}:${shadow.decision_domain}`,\n \"utf8\",\n )\n .digest(\"hex\"),\n summary: `Shadow dossier simulation for ${shadow.decision_domain} with status ${shadow.status}`,\n artifact_refs: [\n artifacts.ids.envelope_id,\n artifacts.ids.snapshot_id,\n artifacts.ids.bundle_id,\n artifacts.ids.resolution_id,\n artifacts.ids.dispatch_id,\n artifacts.ids.ledger_entry_id,\n ],\n };\n\n return reply.code(200).send({\n shadow_result: shadow,\n trace: artifacts.ids,\n governance_metrics: shadow.governance_metrics,\n dossier_simulation: dossierSimulation,\n vertical_pack: {\n key: resolvedVerticalPack.pack.key,\n source: resolvedVerticalPack.source,\n },\n persisted_artifacts: artifacts.artifacts.length,\n });\n });\n}\n","import { asRecord, asString, clamp } from \"../support/Parsing.js\";\nimport { resolveDecisionDomain } from \"../evaluate-decision/EvaluateDecisionResolution.js\";\nimport type { ResolvedVerticalPack } from \"../verticals/VerticalContracts.js\";\nimport type { EvaluateDecisionMetrics } from \"../evaluate-decision/EvaluateDecisionContracts.js\";\nimport type { ShadowDecisionRequest, ShadowDecisionResult } from \"./ShadowContracts.js\";\n\n/** Shadow decisioning: request parsing and deterministic dry-run decision building. */\nexport class ShadowDecisioning {\n static parseShadowRequest(\n input: unknown,\n ): { ok: true; value: ShadowDecisionRequest } | { ok: false; message: string } {\n const record = asRecord(input);\n\n const requestId = asString(record.request_id);\n if (!requestId) return { ok: false, message: \"request_id is required\" };\n\n const orgId = asString(record.org_id);\n if (!orgId) return { ok: false, message: \"org_id is required\" };\n\n const intent = asString(record.intent);\n if (!intent) return { ok: false, message: \"intent is required\" };\n\n const cycleId = asString(record.cycle_id) ?? undefined;\n const engineKey = asString(record.engine_key) ?? undefined;\n\n const engineChain = Array.isArray(record.engine_chain)\n ? record.engine_chain\n .map((item) => asString(item))\n .filter((item): item is string => Boolean(item))\n : undefined;\n\n const intake = asRecord(record.intake);\n const verticalPack =\n asString(record.vertical_pack) ?? asString(intake.vertical_pack) ?? undefined;\n const workflowKey = asString(record.workflow_key) ?? asString(intake.workflow_key) ?? undefined;\n const attachments = Array.isArray(record.attachments)\n ? record.attachments.map((item) => asRecord(item))\n : [];\n\n return {\n ok: true,\n value: {\n request_id: requestId,\n org_id: orgId,\n cycle_id: cycleId,\n engine_key: engineKey,\n engine_chain: engineChain,\n vertical_pack: verticalPack,\n workflow_key: workflowKey,\n intent,\n intake,\n attachments,\n },\n };\n }\n\n static renderRecommendation(template: string, domain: string): string {\n return template.replace(\"{domain}\", domain.toLowerCase());\n }\n\n static buildShadowGovernanceMetrics(input: {\n status: ShadowDecisionResult[\"status\"];\n confidence: number;\n missingEvidenceCount: number;\n intakeSignalCount: number;\n attachmentCount: number;\n }): EvaluateDecisionMetrics {\n const baseDrift =\n input.status === \"SUCCEEDED\" ? 0.08 : input.status === \"NEEDS_EVIDENCE\" ? 0.24 : 0.44;\n const overrideDriftRate = clamp(\n baseDrift +\n input.missingEvidenceCount * 0.04 +\n Math.max(0, 0.5 - input.confidence) * 0.35 +\n (input.attachmentCount === 0 ? 0.05 : 0),\n 0,\n 1,\n );\n\n const governanceTensionIndex = clamp(\n 0.16 +\n (input.status === \"FAILED\" ? 0.42 : input.status === \"NEEDS_EVIDENCE\" ? 0.26 : 0.08) +\n input.missingEvidenceCount * 0.07 +\n Math.max(0, 0.45 - input.confidence) * 0.3,\n 0,\n 1,\n );\n\n const boundaryVolatilityScore = clamp(\n 0.2 +\n input.missingEvidenceCount * 0.08 +\n (input.intakeSignalCount < 2 ? 0.12 : 0) +\n (input.attachmentCount === 0 ? 0.08 : 0),\n 0,\n 1,\n );\n\n const decisionVolumeUnderGovernance = Math.max(\n 1,\n input.intakeSignalCount + input.attachmentCount,\n );\n\n return {\n override_drift_rate: Number.parseFloat(overrideDriftRate.toFixed(4)),\n governance_tension_index: Number.parseFloat(governanceTensionIndex.toFixed(4)),\n boundary_volatility_score: Number.parseFloat(boundaryVolatilityScore.toFixed(4)),\n decision_volume_under_governance: decisionVolumeUnderGovernance,\n };\n }\n\n static buildShadowDecision(\n request: ShadowDecisionRequest,\n resolvedVerticalPack: ResolvedVerticalPack,\n ): ShadowDecisionResult {\n const pack = resolvedVerticalPack.pack;\n const engineKey = (request.engine_key ?? request.engine_chain?.[0] ?? \"software\").toLowerCase();\n const intentLower = request.intent.toLowerCase();\n const domain = resolveDecisionDomain(pack, engineKey, intentLower);\n\n const attachmentCount = request.attachments.length;\n const intakeSignalCount = Object.keys(request.intake).length;\n\n const evidenceRequiredKeywords = pack.resolver_overrides.evidence_required_keywords;\n\n const likelyNeedsEvidence =\n evidenceRequiredKeywords.some((keyword) => intentLower.includes(keyword.toLowerCase())) &&\n attachmentCount === 0;\n\n let confidence = pack.resolver_overrides.base_confidence;\n confidence += Math.min(\n 0.28,\n attachmentCount * pack.resolver_overrides.attachment_confidence_bonus,\n );\n confidence += Math.min(\n 0.12,\n intakeSignalCount * pack.resolver_overrides.intake_confidence_bonus,\n );\n if (likelyNeedsEvidence) confidence -= pack.resolver_overrides.missing_evidence_penalty;\n confidence = clamp(confidence, 0.1, 0.95);\n\n const status =\n confidence < 0.35\n ? \"FAILED\"\n : confidence < 0.55 || likelyNeedsEvidence\n ? \"NEEDS_EVIDENCE\"\n : \"SUCCEEDED\";\n\n const riskLevel =\n status === \"FAILED\"\n ? \"high\"\n : status === \"NEEDS_EVIDENCE\"\n ? \"medium\"\n : confidence >= 0.85\n ? \"low\"\n : \"medium\";\n\n const recommendation =\n status === \"SUCCEEDED\"\n ? renderRecommendation(pack.ui_copy.recommendation_success, domain)\n : status === \"NEEDS_EVIDENCE\"\n ? renderRecommendation(pack.ui_copy.recommendation_needs_evidence, domain)\n : renderRecommendation(pack.ui_copy.recommendation_failed, domain);\n\n const missingEvidence: string[] = [];\n if (attachmentCount === 0 && likelyNeedsEvidence) {\n missingEvidence.push(...pack.resolver_overrides.missing_evidence_fields);\n }\n if (intakeSignalCount < 2) {\n missingEvidence.push(\"context_detail\");\n }\n\n const decisionClass =\n status === \"SUCCEEDED\"\n ? \"ADD_ONE_THING\"\n : status === \"NEEDS_EVIDENCE\"\n ? \"DELAY_DECISION\"\n : \"NO_DECISION_YET\";\n\n const governanceMetrics = buildShadowGovernanceMetrics({\n status,\n confidence,\n missingEvidenceCount: missingEvidence.length,\n intakeSignalCount,\n attachmentCount,\n });\n\n return {\n status,\n recommendation,\n why: [\n `vertical_pack=${pack.key}`,\n `vertical_pack_source=${resolvedVerticalPack.source}`,\n `domain=${domain}`,\n `attachment_count=${attachmentCount}`,\n `intake_signal_count=${intakeSignalCount}`,\n ],\n actions: pack.execution_templates[status],\n missing_evidence: missingEvidence,\n confidence: Number.parseFloat(confidence.toFixed(4)),\n decision_class: decisionClass,\n decision_domain: domain,\n risk_level: riskLevel,\n governance_metrics: governanceMetrics,\n };\n }\n}\n\n/** Functional alias for {@link ShadowDecisioning.parseShadowRequest}. */\nexport function parseShadowRequest(\n input: unknown,\n): { ok: true; value: ShadowDecisionRequest } | { ok: false; message: string } {\n return ShadowDecisioning.parseShadowRequest(input);\n}\n\n/** Functional alias for {@link ShadowDecisioning.renderRecommendation}. */\nexport function renderRecommendation(template: string, domain: string): string {\n return ShadowDecisioning.renderRecommendation(template, domain);\n}\n\n/** Functional alias for {@link ShadowDecisioning.buildShadowGovernanceMetrics}. */\nexport function buildShadowGovernanceMetrics(input: {\n status: ShadowDecisionResult[\"status\"];\n confidence: number;\n missingEvidenceCount: number;\n intakeSignalCount: number;\n attachmentCount: number;\n}): EvaluateDecisionMetrics {\n return ShadowDecisioning.buildShadowGovernanceMetrics(input);\n}\n\n/** Functional alias for {@link ShadowDecisioning.buildShadowDecision}. */\nexport function buildShadowDecision(\n request: ShadowDecisionRequest,\n resolvedVerticalPack: ResolvedVerticalPack,\n): ShadowDecisionResult {\n return ShadowDecisioning.buildShadowDecision(request, resolvedVerticalPack);\n}\n","import type { DecisionEvaluationRow } from \"../store/StoreContracts.js\";\nimport { asString, asRecord, isLikelyUuid } from \"../support/Parsing.js\";\nimport { parseEvaluateModeStrict } from \"../evaluate-decision/EvaluateDecisionParsing.js\";\nimport { toEvaluatePolicyEvaluation, toEvaluatePolicyGuard } from \"../policy-graph/PolicyGraph.js\";\nimport type {\n EvaluateDecisionPolicyEvaluation,\n EvaluateDecisionPolicyGuard,\n} from \"../policy-graph/PolicyGraphContracts.js\";\nimport type {\n EvaluateDecisionMode,\n EvaluateDecisionOutcome,\n} from \"../evaluate-decision/EvaluateDecisionContracts.js\";\nimport type {\n ShadowEvaluateDecisionExecutionAction,\n ShadowEvaluateDecisionReportItem,\n ShadowEvaluateDecisionReportSummary,\n} from \"./ShadowContracts.js\";\n\n/** Shadow evaluate-decision report mapping, aggregation, and query parsing. */\nexport class ShadowReports {\n static shadowExecutionActionFromOutcome(\n outcome: EvaluateDecisionOutcome,\n ): ShadowEvaluateDecisionExecutionAction {\n if (outcome === \"APPROVE\") return \"CONTINUE\";\n if (outcome === \"REJECT\") return \"STOP\";\n if (outcome === \"ESCALATE\") return \"HAND_OFF\";\n return \"REVIEW\";\n }\n\n static resolveShadowReportReason(input: {\n outcome: EvaluateDecisionOutcome;\n policyGuard: EvaluateDecisionPolicyGuard | undefined;\n policyEvaluation: EvaluateDecisionPolicyEvaluation | undefined;\n }): string {\n if (input.policyGuard?.reason) return input.policyGuard.reason;\n if (input.policyEvaluation?.selected_rule_id) return input.policyEvaluation.selected_rule_id;\n if (input.policyEvaluation?.resolution === \"no_matching_rule\") {\n return \"no_matching_policy_rule\";\n }\n if (input.policyEvaluation?.resolution === \"policy_guard_blocked\") {\n return \"policy_guard_blocked\";\n }\n return `protocol_outcome_${input.outcome.toLowerCase()}`;\n }\n\n static toShadowEvaluateDecisionReportItem(\n row: DecisionEvaluationRow,\n ): ShadowEvaluateDecisionReportItem {\n const response = asRecord(row.response_payload);\n const policyGuard = toEvaluatePolicyGuard(response.policy_guard);\n const policyEvaluation = toEvaluatePolicyEvaluation(response.policy_evaluation);\n const outcome = row.outcome as EvaluateDecisionOutcome;\n const reason = resolveShadowReportReason({ outcome, policyGuard, policyEvaluation });\n\n return {\n evaluation_id: row.id,\n dossier_id: row.dossier_id,\n created_at: row.created_at,\n decision_type: row.decision_type,\n decision_domain: asString(response.decision_domain),\n amount: row.amount,\n risk_score: row.risk_score,\n channel: row.channel,\n policy_version: row.policy_version,\n mode: row.mode as EvaluateDecisionMode,\n outcome,\n confidence: row.confidence,\n would_execute: outcome === \"APPROVE\",\n execution_action: shadowExecutionActionFromOutcome(outcome),\n reason,\n policy_guard_reason: policyGuard?.reason ?? null,\n policy_evaluation_resolution: policyEvaluation?.resolution ?? null,\n selected_rule_id: policyEvaluation?.selected_rule_id ?? null,\n dossier_api_path: `/v1/protocol/dossiers/${row.dossier_id}?org_id=${encodeURIComponent(row.org_id)}`,\n };\n }\n\n static rate(numerator: number, denominator: number): number {\n if (denominator <= 0) return 0;\n return Number.parseFloat((numerator / denominator).toFixed(4));\n }\n\n static summarizeShadowEvaluateDecisionReports(\n reports: ShadowEvaluateDecisionReportItem[],\n ): ShadowEvaluateDecisionReportSummary {\n const outcomeCounts: Record<EvaluateDecisionOutcome, number> = {\n APPROVE: 0,\n ESCALATE: 0,\n REJECT: 0,\n REVIEW: 0,\n };\n const decisionTypeCounts = new Map<string, { count: number; nonApproveCount: number }>();\n const reasonCounts = new Map<string, number>();\n let policyMismatchCount = 0;\n\n for (const report of reports) {\n outcomeCounts[report.outcome] += 1;\n const currentDecisionType = decisionTypeCounts.get(report.decision_type) ?? {\n count: 0,\n nonApproveCount: 0,\n };\n currentDecisionType.count += 1;\n if (report.outcome !== \"APPROVE\") currentDecisionType.nonApproveCount += 1;\n decisionTypeCounts.set(report.decision_type, currentDecisionType);\n\n reasonCounts.set(report.reason, (reasonCounts.get(report.reason) ?? 0) + 1);\n if (\n report.policy_guard_reason ||\n report.policy_evaluation_resolution === \"no_matching_rule\" ||\n report.policy_evaluation_resolution === \"policy_guard_blocked\"\n ) {\n policyMismatchCount += 1;\n }\n }\n\n const total = reports.length;\n const nonApproveCount = outcomeCounts.ESCALATE + outcomeCounts.REJECT + outcomeCounts.REVIEW;\n\n return {\n total_evaluations: total,\n would_approve_count: outcomeCounts.APPROVE,\n would_block_count: outcomeCounts.REJECT,\n would_escalate_count: outcomeCounts.ESCALATE,\n review_required_count: outcomeCounts.REVIEW,\n non_approve_count: nonApproveCount,\n non_approve_rate: rate(nonApproveCount, total),\n policy_mismatch_count: policyMismatchCount,\n policy_mismatch_rate: rate(policyMismatchCount, total),\n near_miss_count: nonApproveCount,\n near_miss_rate: rate(nonApproveCount, total),\n outcome_counts: outcomeCounts,\n top_decision_types: Array.from(decisionTypeCounts.entries())\n .map(([decisionType, value]) => ({\n decision_type: decisionType,\n count: value.count,\n non_approve_count: value.nonApproveCount,\n non_approve_rate: rate(value.nonApproveCount, value.count),\n }))\n .sort(\n (left, right) =>\n right.count - left.count || left.decision_type.localeCompare(right.decision_type),\n )\n .slice(0, 10),\n top_reason_patterns: Array.from(reasonCounts.entries())\n .map(([reason, count]) => ({ reason, count }))\n .sort((left, right) => right.count - left.count || left.reason.localeCompare(right.reason))\n .slice(0, 10),\n };\n }\n\n static parseShadowEvaluateDecisionReportsQuery(input: unknown):\n | {\n ok: true;\n value: {\n org_id: string;\n mode: EvaluateDecisionMode;\n since: Date | null;\n since_raw: string | null;\n limit: number;\n };\n }\n | { ok: false; message: string } {\n const query = asRecord(input);\n const orgId = asString(query.org_id);\n if (!orgId) return { ok: false, message: \"org_id is required\" };\n if (!isLikelyUuid(orgId)) return { ok: false, message: \"org_id must be a UUID\" };\n\n const rawMode = asString(query.mode);\n const mode = rawMode ? parseEvaluateModeStrict(rawMode) : \"SHADOW\";\n if (!mode) {\n return { ok: false, message: \"mode must be one of SHADOW, PARALLEL, ENFORCEMENT\" };\n }\n\n const rawLimit =\n typeof query.limit === \"string\"\n ? Number.parseInt(query.limit, 10)\n : typeof query.limit === \"number\"\n ? Math.trunc(query.limit)\n : 50;\n const limit = Number.isFinite(rawLimit) && rawLimit > 0 ? Math.min(rawLimit, 500) : 50;\n\n const sinceRaw = asString(query.since);\n if (!sinceRaw) {\n return { ok: true, value: { org_id: orgId, mode, since: null, since_raw: null, limit } };\n }\n const sinceMs = Date.parse(sinceRaw);\n if (!Number.isFinite(sinceMs)) {\n return { ok: false, message: \"since must be an ISO-8601 datetime\" };\n }\n return {\n ok: true,\n value: {\n org_id: orgId,\n mode,\n since: new Date(sinceMs),\n since_raw: new Date(sinceMs).toISOString(),\n limit,\n },\n };\n }\n}\n\n/** Functional alias for {@link ShadowReports.shadowExecutionActionFromOutcome}. */\nexport function shadowExecutionActionFromOutcome(\n outcome: EvaluateDecisionOutcome,\n): ShadowEvaluateDecisionExecutionAction {\n return ShadowReports.shadowExecutionActionFromOutcome(outcome);\n}\n\n/** Functional alias for {@link ShadowReports.resolveShadowReportReason}. */\nexport function resolveShadowReportReason(input: {\n outcome: EvaluateDecisionOutcome;\n policyGuard: EvaluateDecisionPolicyGuard | undefined;\n policyEvaluation: EvaluateDecisionPolicyEvaluation | undefined;\n}): string {\n return ShadowReports.resolveShadowReportReason(input);\n}\n\n/** Functional alias for {@link ShadowReports.toShadowEvaluateDecisionReportItem}. */\nexport function toShadowEvaluateDecisionReportItem(\n row: DecisionEvaluationRow,\n): ShadowEvaluateDecisionReportItem {\n return ShadowReports.toShadowEvaluateDecisionReportItem(row);\n}\n\n/** Functional alias for {@link ShadowReports.rate}. */\nexport function rate(numerator: number, denominator: number): number {\n return ShadowReports.rate(numerator, denominator);\n}\n\n/** Functional alias for {@link ShadowReports.summarizeShadowEvaluateDecisionReports}. */\nexport function summarizeShadowEvaluateDecisionReports(\n reports: ShadowEvaluateDecisionReportItem[],\n): ShadowEvaluateDecisionReportSummary {\n return ShadowReports.summarizeShadowEvaluateDecisionReports(reports);\n}\n\n/** Functional alias for {@link ShadowReports.parseShadowEvaluateDecisionReportsQuery}. */\nexport function parseShadowEvaluateDecisionReportsQuery(input: unknown):\n | {\n ok: true;\n value: {\n org_id: string;\n mode: EvaluateDecisionMode;\n since: Date | null;\n since_raw: string | null;\n limit: number;\n };\n }\n | { ok: false; message: string } {\n return ShadowReports.parseShadowEvaluateDecisionReportsQuery(input);\n}\n","/**\n * Compiler for the ```decionis rules block inside DECIONIS_POLICY.md, for\n * local (developer-machine) evaluation.\n *\n * MIRROR NOTE: this is a faithful port of the canonical compiler at\n * apps/api/src/services/policyEncoding/decionisRulesBlock.ts and must stay in\n * lockstep with it (same operators, same all-or-nothing validation, same\n * defaults). Two deliberate local differences:\n * 1. Block bodies are parsed as JSON only — the canonical compiler also\n * accepts YAML. A non-JSON block compiles to a clear error here rather\n * than a wrong verdict.\n * 2. The bundle envelope targets the protocol artifact schema directly\n * (docs/decionis.protocol.schemas/v1/policy-bundle.schema.json), since we\n * publish straight into an in-process protocol app.\n */\n\nimport { createHash } from \"node:crypto\";\n\nexport type DecionisVerdict = \"allow\" | \"block\" | \"restrain\" | \"escalate\";\n\nconst ACTION_MAP: Record<DecionisVerdict, string> = {\n allow: \"AUTO_APPROVE\",\n block: \"AUTO_REJECT\",\n restrain: \"REQUIRE_REVIEW\",\n escalate: \"ESCALATE\",\n};\n\nconst OP_MAP: Record<string, string> = {\n eq: \"EQ\",\n ne: \"NEQ\",\n neq: \"NEQ\",\n gt: \"GT\",\n gte: \"GTE\",\n lt: \"LT\",\n lte: \"LTE\",\n in: \"IN\",\n not_in: \"NOT_IN\",\n exists: \"EXISTS\",\n contains: \"CONTAINS\",\n matches: \"MATCHES\",\n};\n\nconst VALUELESS_OPS = new Set([\"EXISTS\"]);\nconst VALUES_OPS = new Set([\"IN\", \"NOT_IN\"]);\n\nexport interface BundleRule {\n rule_id: string;\n name: string;\n decision_domain: string;\n when: Record<string, unknown>;\n then: { action: string };\n priority: number;\n enabled: boolean;\n rationale?: string;\n}\n\nexport interface CompileResult {\n rules: BundleRule[];\n errors: string[];\n}\n\nexport class DecionisRulesBlock {\n /** Extract the raw text inside the first ```decionis fenced block, or null. */\n static extract(markdown: string): string | null {\n if (typeof markdown !== \"string\") return null;\n const re = /```decionis(?:\\s+(?:json|ya?ml))?[ \\t]*\\r?\\n([\\s\\S]*?)\\r?\\n```/i;\n const m = re.exec(markdown);\n return m ? (m[1] ?? \"\").trim() || null : null;\n }\n\n /**\n * Compile a parsed `decionis` block object into protocol bundle rules.\n * All-or-nothing: any error means nothing is compiled.\n */\n static compile(parsed: unknown, opts: { workflowKey?: string | null } = {}): CompileResult {\n const errors: string[] = [];\n if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n return { rules: [], errors: [\"decionis block must be a JSON object\"] };\n }\n const rawRules = (parsed as Record<string, unknown>).rules;\n if (!Array.isArray(rawRules) || rawRules.length === 0) {\n return { rules: [], errors: ['decionis block needs a non-empty \"rules\" array'] };\n }\n\n const domainDefault = (opts.workflowKey ?? \"\").trim() || \"github_action\";\n const rules: BundleRule[] = [];\n const seenIds = new Set<string>();\n\n rawRules.forEach((raw, i) => {\n const path = `rules[${i}]`;\n if (!raw || typeof raw !== \"object\" || Array.isArray(raw)) {\n errors.push(`${path}: must be an object`);\n return;\n }\n const r = raw as Record<string, unknown>;\n const name = typeof r.name === \"string\" && r.name.trim() ? r.name.trim() : \"\";\n if (!name) errors.push(`${path}: needs a non-empty \"name\"`);\n\n const actionRaw = typeof r.action === \"string\" ? r.action.trim().toLowerCase() : \"\";\n const action = ACTION_MAP[actionRaw as DecionisVerdict];\n if (!action) {\n errors.push(\n `${path}: unknown action \"${r.action}\" (allowed: allow, block, restrain, escalate)`,\n );\n }\n\n const hasAll = Array.isArray(r.all) && r.all.length > 0;\n const hasAny = Array.isArray(r.any) && r.any.length > 0;\n if (hasAll === hasAny) {\n errors.push(`${path}: provide exactly one of \"all\" or \"any\" with at least one condition`);\n }\n\n const groupKey = hasAll ? \"all\" : \"any\";\n const rawPredicates = (hasAll ? r.all : r.any) as unknown[] | undefined;\n const predicates: Record<string, unknown>[] = [];\n (rawPredicates ?? []).forEach((pred, j) => {\n const compiled = DecionisRulesBlock.compilePredicate(\n pred,\n `${path}.${groupKey}[${j}]`,\n errors,\n );\n if (compiled) predicates.push(compiled);\n });\n\n if (!name || !action || hasAll === hasAny || predicates.length === 0) return;\n\n let ruleId = DecionisRulesBlock.slug(name);\n if (seenIds.has(ruleId)) ruleId = `${ruleId}-${i}`;\n seenIds.add(ruleId);\n\n const priority =\n typeof r.priority === \"number\" && Number.isFinite(r.priority)\n ? Math.max(0, Math.min(100000, Math.round(r.priority)))\n : i;\n\n rules.push({\n rule_id: ruleId,\n name,\n decision_domain:\n typeof r.domain === \"string\" && r.domain.trim() ? r.domain.trim() : domainDefault,\n when: { [groupKey]: predicates },\n then: { action },\n priority,\n enabled: true,\n ...(typeof r.rationale === \"string\" && r.rationale.trim()\n ? { rationale: r.rationale.trim().slice(0, 4000) }\n : {}),\n });\n });\n\n return { rules: errors.length === 0 ? rules : [], errors };\n }\n\n /**\n * Full pipeline: extract the block (Markdown) or take the whole document\n * (YAML policy paths are not supported locally — see MIRROR NOTE), parse as\n * JSON, compile. Returns null when there is nothing to enforce.\n */\n static compilePolicyFile(\n source: string,\n opts: { workflowKey?: string | null } = {},\n ): CompileResult | null {\n const docText = DecionisRulesBlock.extract(source);\n if (docText === null) return null;\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(docText);\n } catch (err) {\n return {\n rules: [],\n errors: [\n `decionis rules document is not valid JSON: ${(err as Error).message} ` +\n \"(the platform also accepts YAML blocks; the local MCP server currently requires JSON)\",\n ],\n };\n }\n return DecionisRulesBlock.compile(parsed, { workflowKey: opts.workflowKey });\n }\n\n /** Deterministic, UUID-formatted bundle id (stable across content revisions). */\n static deterministicBundleId(orgId: string, name: string): string {\n const h = createHash(\"sha256\").update(`decionis-policy-file:${orgId}:${name}`).digest(\"hex\");\n const variant = \"89ab\"[parseInt(h[16] ?? \"0\", 16) % 4];\n return `${h.slice(0, 8)}-${h.slice(8, 12)}-4${h.slice(13, 16)}-${variant}${h.slice(17, 20)}-${h.slice(20, 32)}`;\n }\n\n static sha256Hex(text: string): string {\n return createHash(\"sha256\").update(text, \"utf8\").digest(\"hex\");\n }\n\n /**\n * Protocol policy-bundle envelope for the local in-process publish\n * (validated by docs/decionis.protocol.schemas/v1/policy-bundle.schema.json).\n */\n static buildLocalPolicyBundle(input: {\n orgId: string;\n contentSha256: string;\n rules: BundleRule[];\n now: string;\n }): Record<string, unknown> {\n return {\n protocol_version: \"1.0\",\n bundle_id: DecionisRulesBlock.deterministicBundleId(input.orgId, \"decionis-policy-local\"),\n org_id: input.orgId,\n version: `decionis-${input.contentSha256.slice(0, 12)}`,\n effective_from: input.now,\n rules: input.rules,\n metadata: {\n source: \"decionis_policy_md (local mcp)\",\n },\n };\n }\n\n private static slug(text: string): string {\n return (\n text\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\")\n .slice(0, 80) || \"rule\"\n );\n }\n\n private static compilePredicate(\n raw: unknown,\n path: string,\n errors: string[],\n ): Record<string, unknown> | null {\n if (!raw || typeof raw !== \"object\" || Array.isArray(raw)) {\n errors.push(`${path}: predicate must be an object`);\n return null;\n }\n const p = raw as Record<string, unknown>;\n const field = typeof p.field === \"string\" ? p.field.trim() : \"\";\n if (!field) {\n errors.push(`${path}: predicate needs a non-empty \"field\"`);\n return null;\n }\n const opRaw = typeof p.op === \"string\" ? p.op.trim().toLowerCase() : \"\";\n const operator = OP_MAP[opRaw];\n if (!operator) {\n errors.push(\n `${path}: unknown operator \"${p.op}\" (allowed: ${Object.keys(OP_MAP).join(\", \")})`,\n );\n return null;\n }\n const out: Record<string, unknown> = { field, operator };\n if (VALUELESS_OPS.has(operator)) return out;\n if (VALUES_OPS.has(operator)) {\n if (!Array.isArray(p.values) || p.values.length === 0) {\n errors.push(`${path}: operator \"${opRaw}\" requires a non-empty \"values\" array`);\n return null;\n }\n out.values = p.values;\n return out;\n }\n if (!(\"value\" in p)) {\n errors.push(`${path}: operator \"${opRaw}\" requires a \"value\"`);\n return null;\n }\n out.value = p.value;\n return out;\n }\n}\n\n/** Functional alias for {@link DecionisRulesBlock.extract}. */\nexport function extractDecionisRulesBlock(markdown: string): string | null {\n return DecionisRulesBlock.extract(markdown);\n}\n\n/** Functional alias for {@link DecionisRulesBlock.compile}. */\nexport function compileDecionisRules(\n parsed: unknown,\n opts: { workflowKey?: string | null } = {},\n): CompileResult {\n return DecionisRulesBlock.compile(parsed, opts);\n}\n\n/** Functional alias for {@link DecionisRulesBlock.compilePolicyFile}. */\nexport function compilePolicyFileRules(\n source: string,\n opts: { workflowKey?: string | null } = {},\n): CompileResult | null {\n return DecionisRulesBlock.compilePolicyFile(source, opts);\n}\n\n/** Functional alias for {@link DecionisRulesBlock.deterministicBundleId}. */\nexport function deterministicBundleId(orgId: string, name: string): string {\n return DecionisRulesBlock.deterministicBundleId(orgId, name);\n}\n\n/** Functional alias for {@link DecionisRulesBlock.sha256Hex}. */\nexport function sha256Hex(text: string): string {\n return DecionisRulesBlock.sha256Hex(text);\n}\n\n/** Functional alias for {@link DecionisRulesBlock.buildLocalPolicyBundle}. */\nexport function buildLocalPolicyBundle(input: {\n orgId: string;\n contentSha256: string;\n rules: BundleRule[];\n now: string;\n}): Record<string, unknown> {\n return DecionisRulesBlock.buildLocalPolicyBundle(input);\n}\n","/**\n * Local Decionis gateway: boots the REAL protocol service (@decionis/protocol)\n * with an in-memory store and evaluates decisions through fastify's inject()\n * — the genuine platform evaluator, with zero network, zero database, and\n * zero credentials. The repo's DECIONIS_POLICY.md is compiled and published\n * through the protocol's own bundle-ingestion route (schema-validated), so a\n * policy that misbehaves locally would misbehave identically in production.\n */\n\nimport type { FastifyInstance } from \"fastify\";\nimport { buildProtocolApp } from \"@decionis/protocol/app\";\nimport { createMemoryProtocolStore } from \"@decionis/protocol/store/memory\";\n\nimport {\n buildLocalPolicyBundle,\n compilePolicyFileRules,\n sha256Hex,\n type CompileResult,\n} from \"./RulesBlock.js\";\n\n/** Fixed, uuid-shaped org id for the local sandbox evaluations. */\nexport const LOCAL_ORG_ID = \"d0c10ca1-0000-4000-8000-000000000001\";\n\nconst isPlainObject = (v: unknown): v is Record<string, unknown> =>\n typeof v === \"object\" && v !== null && !Array.isArray(v);\n\nexport type PublishResult =\n | { ok: true; version: string; sha256: string; ruleCount: number; republished: boolean }\n | { ok: false; reason: \"no_rules_block\" | \"compile_error\" | \"bundle_rejected\"; errors: string[] };\n\nexport interface EvaluateResult {\n status: number;\n body: Record<string, unknown>;\n}\n\nexport class LocalDecionisGateway {\n private app: FastifyInstance | null = null;\n private publishedVersion: string | null = null;\n\n private async ready(): Promise<FastifyInstance> {\n if (!this.app) {\n const app = buildProtocolApp({\n store: createMemoryProtocolStore(),\n logger: false, // stdout belongs to the MCP protocol channel\n });\n await app.ready();\n this.app = app;\n }\n return this.app;\n }\n\n async close(): Promise<void> {\n if (this.app) {\n await this.app.close();\n this.app = null;\n this.publishedVersion = null;\n }\n }\n\n /** Compile the policy source; does not publish. */\n compile(source: string, opts: { workflowKey?: string | null } = {}): CompileResult | null {\n return compilePolicyFileRules(source, opts);\n }\n\n /**\n * Compile + publish the policy as the active local bundle. Idempotent by\n * content hash — republished only when the file content changes.\n */\n async publishPolicy(\n source: string,\n opts: { workflowKey?: string | null } = {},\n ): Promise<PublishResult> {\n const compiled = compilePolicyFileRules(source, opts);\n if (compiled === null) {\n return {\n ok: false,\n reason: \"no_rules_block\",\n errors: [\"the policy file has no ```decionis rules block — nothing to enforce\"],\n };\n }\n if (compiled.errors.length > 0) {\n return { ok: false, reason: \"compile_error\", errors: compiled.errors };\n }\n\n const sha256 = sha256Hex(source);\n const version = `decionis-${sha256.slice(0, 12)}`;\n if (this.publishedVersion === version) {\n return { ok: true, version, sha256, ruleCount: compiled.rules.length, republished: false };\n }\n\n const app = await this.ready();\n const bundle = buildLocalPolicyBundle({\n orgId: LOCAL_ORG_ID,\n contentSha256: sha256,\n rules: compiled.rules,\n now: new Date().toISOString(),\n });\n const res = await app.inject({\n method: \"POST\",\n url: \"/v1/protocol/policies/bundles\",\n payload: bundle,\n });\n if (res.statusCode >= 300) {\n return {\n ok: false,\n reason: \"bundle_rejected\",\n errors: [`protocol rejected the policy bundle (HTTP ${res.statusCode}): ${res.body}`],\n };\n }\n this.publishedVersion = version;\n return { ok: true, version, sha256, ruleCount: compiled.rules.length, republished: true };\n }\n\n /**\n * Evaluate a candidate action through POST /v1/protocol/evaluate-decision,\n * applying the same request normalization the public API performs\n * (apps/api/src/services/protocolAdapter/normalizeEvaluateBody.ts): the\n * payload becomes `context`, and decision_type derives from the action\n * label, then the workflow key, then a stable fallback.\n */\n async evaluate(input: {\n payload: Record<string, unknown>;\n workflowKey?: string | null;\n mode?: \"shadow\" | \"enforce\";\n }): Promise<EvaluateResult> {\n const app = await this.ready();\n const payload = isPlainObject(input.payload) ? input.payload : {};\n const context = { ...payload };\n\n const candidates = [\n typeof context.action === \"string\" ? context.action : null,\n typeof input.workflowKey === \"string\" ? input.workflowKey : null,\n ];\n const derived = candidates.find((c) => typeof c === \"string\" && c.trim() !== \"\");\n const decisionType = (derived ?? \"action_gate\").toString().trim().slice(0, 120);\n\n const body: Record<string, unknown> = {\n org_id: LOCAL_ORG_ID,\n decision_type: decisionType,\n context,\n mode: input.mode === \"enforce\" ? \"ENFORCEMENT\" : \"SHADOW\",\n ...(input.workflowKey ? { workflow_key: input.workflowKey } : {}),\n };\n\n const res = await app.inject({\n method: \"POST\",\n url: \"/v1/protocol/evaluate-decision\",\n payload: body,\n });\n let parsed: Record<string, unknown>;\n try {\n parsed = JSON.parse(res.body) as Record<string, unknown>;\n } catch {\n parsed = { raw: res.body };\n }\n return { status: res.statusCode, body: parsed };\n }\n}\n\n/**\n * Map protocol outcomes onto the verdict vocabulary policy authors use\n * (matches the govern action's normalization).\n */\nexport class Verdicts {\n static normalize(outcome: unknown): string {\n const o = String(outcome ?? \"\")\n .trim()\n .toLowerCase();\n const aliases: Record<string, string> = {\n approve: \"allow\",\n auto_approve: \"allow\",\n reject: \"block\",\n auto_reject: \"block\",\n require_review: \"review\",\n request_info: \"review\",\n };\n return aliases[o] ?? o;\n }\n}\n\n/** Functional alias for {@link Verdicts.normalize}. */\nexport function normalizeVerdict(outcome: unknown): string {\n return Verdicts.normalize(outcome);\n}\n","import { readFile } from \"node:fs/promises\";\nimport { isAbsolute, resolve } from \"node:path\";\n\nexport type PolicyFileResult =\n | { ok: true; path: string; content: string }\n | { ok: false; path: string; message: string };\n\nexport class PolicyFileRepository {\n constructor(private readonly env: NodeJS.ProcessEnv = process.env) {}\n\n resolvePath(pathOverride: unknown, cwd: string = process.cwd()): string {\n const candidate =\n (typeof pathOverride === \"string\" && pathOverride.trim()) ||\n this.env.DECIONIS_POLICY_PATH ||\n \"DECIONIS_POLICY.md\";\n return isAbsolute(candidate) ? candidate : resolve(cwd, candidate);\n }\n\n async read(pathOverride: unknown, cwd: string = process.cwd()): Promise<PolicyFileResult> {\n const path = this.resolvePath(pathOverride, cwd);\n try {\n return { ok: true, path, content: await readFile(path, \"utf8\") };\n } catch (error) {\n return {\n ok: false,\n path,\n message:\n `Could not read the policy file at ${path}: ${\n error instanceof Error ? error.message : String(error)\n }. ` + \"Set DECIONIS_POLICY_PATH or create DECIONIS_POLICY.md at the repository root.\",\n };\n }\n }\n}\n"],"mappings":";;;AAAA,OAAO,aAAuC;;;ACA9C,SAAS,kBAAkB;;;ACA3B,SAAS,kBAAkB;AAoCpB,IAAM,cAAN,MAAM,aAAY;AAAA,EACvB,OAAO,uBAAuB,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ash","randomUUID","asRecord","asString","asString","asRecord","asRecord","asString","body","asRecord","asString","asNumber","createHash","createHash","asRecord","asString","asNumber","randomUUID","createHash","createHash","timingSafeEqual","timingSafeEqual","createHash","createHash","createHash","createHash","randomUUID","createHash","randomUUID","asString","asRecord","randomUUID","asNumber","createHash","payload","asRecord","asString","randomUUID","createHash","randomUUID","durationMs","asRecord","asNumber","asString","buildServerTimingHeader","randomUUID","asRecord","asString","asNumber","randomUUID","createHash","sign","createHash","privateKey","sign","asString","asRecord","asNumber","asRecord","asString","asNumber","asRecord","asString","asNumber","asRecord","asString","asNumber","createHash","randomUUID","asString","randomUUID","createHash","buildServerTimingHeader","durationMs","asRecord","asString","randomUUID","createHash","durationMs","asRecord","buildServerTimingHeader","randomUUID","createHash","RULE_META","OUTCOME_TO_DECISION","createHash","randomUUID","asRecord","asString","randomUUID","createHash","RULE_META","OUTCOME_TO_DECISION","createHash","randomUUID","asRecord","asString","randomUUID","createHash","createHash","randomUUID","asRecord","asString","randomUUID","createHash","RULE_META","REQUIRED_STATE_FIELDS","OUTCOME_TO_DECISION","createHash","process","randomUUID","asRecord","asString","randomUUID","createHash","RULE_META","OUTCOME_TO_DECISION","createHash","amount","randomUUID","asRecord","asString","randomUUID","asRecord","asString","randomUUID","asRecord","asString","createHash","createHash","asRecord","asString","asRecord","asString","createHash","randomUUID","randomUUID","createHash","asString","asRecord","asString","asString","profiles","readiness","asRecord","asRecord","asString","createHash","asRecord","asString","asRecord","asString","createHash","createHash","sha256Hex","sha256","sha256Hex"]}