{
  "version": 3,
  "sources": ["../../src/applicationIdentity.ts", "../../src/canonicalDocument.ts", "../../src/deploymentResource.ts", "../../src/identifier.ts", "../../src/profile.ts", "../../src/identity.ts", "../../src/jsonValue.ts", "../../src/applicationProvider.ts", "../../src/dappDefinition.ts", "../../src/applicationProviderDescriptor.ts", "../../src/hostArtifact.ts", "../../src/plan.ts", "../../src/applicationProviderPlan.ts", "../../src/dappConfiguration.ts", "../../src/planNormalization.ts", "../../src/validation.ts", "../../src/projectArtifact.ts", "../../src/artifactDistributionPolicy.ts", "../../src/dappEngineModel.ts", "../../src/status.ts", "../../src/lifecycle.ts", "../../src/dappEngineSystem.ts", "../../src/dappEngineValidation.ts", "../../src/dappLaunch.ts", "../../src/dappEngine.ts", "../../src/dappSessionWork.ts", "../../src/dappSession.ts", "../../src/datalakeObjectStore.ts", "../../src/objectStore.ts", "../../src/projectionPublication.ts", "../../src/strictJson.ts", "../../src/deploymentIntent.ts", "../../src/deploymentManifest.ts", "../../src/deploymentRequest.ts", "../../src/deploymentManifestV2.ts", "../../src/infrastructureDescriptor.ts", "../../src/ordering.ts", "../../src/projectManifestModel.ts", "../../src/projectManifestValidation.ts", "../../src/projectManifest.ts", "../../src/deploymentLock.ts", "../../src/deploymentResolution.ts", "../../src/applicationProviderResolution.ts", "../../src/environmentCatalog.ts", "../../src/deploymentLockV2.ts", "../../src/deploymentSourceResolution.ts", "../../src/deploymentLockV3.ts", "../../src/deploymentManifestMigration.ts", "../../src/effectExecution.ts", "../../src/effectJournal.ts", "../../src/effectPreparation.ts", "../../src/effectModel.ts", "../../src/effectValidation.ts", "../../src/effectRecovery.ts", "../../src/eventPump.ts", "../../src/eventStream.ts", "../../src/eventSubscription.ts", "../../src/eventWakeOutbox.ts", "../../src/externalObservation.ts", "../../src/operationRecoveryModel.ts", "../../src/externalRecoveryOwner.ts", "../../src/headObserver.ts", "../../src/managedCapability.ts", "../../src/objectStoreRecord.ts", "../../src/operationRecoveryAdmission.ts", "../../src/portFrameModel.ts", "../../src/portFrameProgress.ts", "../../src/portFrameValidation.ts", "../../src/projection.ts", "../../src/projectionReplay.ts", "../../src/projectionValidation.ts", "../../src/protocolRelease.ts", "../../src/providerRequestTemplate.ts", "../../src/providerScopeIdentity.ts", "../../src/releaseEvidence.ts", "../../src/runRecord.ts", "../../src/secret.ts", "../../src/sideChannel.ts", "../../src/siteBootstrap.ts", "../../src/staticSiteArtifact.ts", "../../src/targetArtifactAdmission.ts", "../../src/targetComposition.ts", "../../src/targetCompositionV2.ts", "../../src/targetCompositionV3.ts", "../../src/targetObjectIdentity.ts", "../../src/targetPlanEnvelope.ts", "../../src/xl1TransactionEffectPlan.ts", "../../src/xl1TransactionEffectReconciler.ts"],
  "sourcesContent": ["import { z } from 'zod'\n\nimport { canonicalizeIJson } from './canonicalDocument.ts'\nimport type { DappDeploymentRequest } from './deploymentRequest.ts'\nimport { PublicIdentityResourceRequestZod } from './deploymentResource.ts'\nimport { IdentifierZod } from './identifier.ts'\nimport { Xl1Bip44BasePath } from './identity.ts'\nimport { JsonObjectZod } from './jsonValue.ts'\nimport type {\n  DappPlanIssue, DappPlanMaterial, ResolvedProviderNode,\n} from './plan.ts'\n\nexport const DappIdentityCapabilityMoniker = 'xyo.identity' as const\nexport const DappIdentityProviderConfigZod = z.strictObject({\n  adapter: JsonObjectZod,\n  request: PublicIdentityResourceRequestZod,\n  resourceId: IdentifierZod,\n})\nexport type DappIdentityProviderConfig = z.infer<typeof DappIdentityProviderConfigZod>\n\n/** Opt-in only: identity resources used for provisioning retain their legacy omission. */\nexport function explicitApplicationIdentityIds(request: DappDeploymentRequest): ReadonlySet<string> {\n  return new Set((request.applicationProviders ?? []).flatMap(selection => Object.values(selection.dependencies)\n    .filter(binding => binding.kind === 'resource' && request.resources[binding.resourceId]?.class === 'identity')\n    .map(binding => binding.kind === 'resource' ? binding.resourceId : '')))\n}\n\nfunction identityNode(node: ResolvedProviderNode): boolean {\n  const request = node.config.request\n  return node.providedCapabilities.some(capability => capability.moniker === DappIdentityCapabilityMoniker)\n    || (typeof request === 'object' && request !== null && !Array.isArray(request) && request.class === 'identity')\n}\n\nfunction reject(issues: DappPlanIssue[], message: string): void {\n  issues.push({\n    code: 'plan.application-provider-invalid', message, path: ['resolvedProviders'],\n  })\n}\n\nfunction consumingHosts(material: DappPlanMaterial, identityId: string): Set<string> {\n  const nodes = new Map(material.resolvedProviders.map(node => [node.instanceId, node]))\n  const roles = new Map(material.definition.actors.map(role => [role.roleId, role]))\n  const hosts = new Set<string>()\n  for (const actor of material.configuration.actors) {\n    const visited = new Set<string>()\n    const visit = (id: string): void => {\n      if (visited.has(id)) return\n      visited.add(id)\n      if (id === identityId) hosts.add(actor.host)\n      for (const dependency of nodes.get(id)?.dependencies ?? []) visit(dependency)\n    }\n    for (const capability of roles.get(actor.roleId)?.requiredCapabilities ?? []) {\n      for (const node of material.resolvedProviders) {\n        if (node.providedCapabilities.some(value => value.moniker === capability.moniker && value.version === capability.version)) visit(node.instanceId)\n      }\n    }\n  }\n  return hosts\n}\n\nfunction identityBindingIssues(material: DappPlanMaterial, node: ResolvedProviderNode, config: DappIdentityProviderConfig): DappPlanIssue[] {\n  const issues: DappPlanIssue[] = []\n  const bindings = material.configuration.identityBindings.filter(binding => binding.capabilityId === node.instanceId)\n  if (bindings.length !== 1 || !material.definition.identityRoles.includes(bindings[0]?.roleId ?? '')) {\n    reject(issues, 'selected identity must bind exactly one declared identity role')\n  }\n  const derivation = bindings[0]?.derivation\n  if (derivation !== undefined && (derivation.networkScope !== material.configuration.network.expectedChainId\n    || (config.request.mode === 'provided' && derivation.expectedAddress !== config.request.expectedAddress)\n    || (config.request.mode === 'ephemeral-local' && derivation.fullPath !== `${Xl1Bip44BasePath}/${config.request.childIndex}`))) {\n    reject(issues, 'selected identity derivation does not match its resource and network binding')\n  }\n  return issues\n}\n\nfunction identityNodeIssues(material: DappPlanMaterial, node: ResolvedProviderNode): DappPlanIssue[] {\n  const issues: DappPlanIssue[] = []\n  const config = DappIdentityProviderConfigZod.safeParse(node.config)\n  const binding = material.configuration.providerBindings[node.instanceId]\n  if (!config.success || config.data.resourceId !== node.instanceId\n    || node.dependencies.length !== 0 || node.providedCapabilities.length !== 1\n    || node.providedCapabilities[0]?.moniker !== DappIdentityCapabilityMoniker || node.providedCapabilities[0]?.version !== 1\n    || binding?.descriptorId !== node.descriptor.descriptor.id\n    || canonicalizeIJson(binding.config) !== canonicalizeIJson(node.config)) {\n    reject(issues, 'selected identity must be an exact supported resource leaf with matching public config')\n    return issues\n  }\n  const selections = material.configuration.applicationProviders ?? []\n  const consumers = selections.filter(selection => Object.entries(selection.dependencies).some(([moniker, dependency]) =>\n    moniker === DappIdentityCapabilityMoniker && dependency.kind === 'resource' && dependency.resourceId === node.instanceId))\n  const hosts = consumingHosts(material, node.instanceId)\n  if (consumers.length === 0 || hosts.size !== 1 || consumers.some(selection => !hosts.has(selection.host))) {\n    reject(issues, 'selected identity requires an explicit application binding and exactly one consuming host')\n  }\n  const applicationIds = new Set(selections.map(selection => selection.instanceId))\n  if (material.resolvedProviders.some(provider => !applicationIds.has(provider.instanceId) && provider.dependencies.includes(node.instanceId))) {\n    reject(issues, 'provisioning identity dependencies must not grant runtime signing authority')\n  }\n  return [...issues, ...identityBindingIssues(material, node, config.data)]\n}\n\n/** Persisted plans enforce the same explicit identity boundary as source planning. */\nexport function applicationIdentityPlanIssues(material: DappPlanMaterial): DappPlanIssue[] {\n  return (material.configuration.applicationProviders?.length ?? 0) === 0 ? [] : material.resolvedProviders.filter(identityNode).flatMap(node => identityNodeIssues(material, node))\n}\n", "import { sha256 } from '@noble/hashes/sha2.js'\nimport { bytesToHex, utf8ToBytes } from '@noble/hashes/utils.js'\nimport { z } from 'zod'\n\nexport const DappDocumentHashAlgorithm = 'jcs-sha256-v1' as const\n\nexport const DappDocumentKindZod = z.enum([\n  'definition',\n  'configuration',\n  'plan',\n  'status',\n  'projection-checkpoint',\n  'projection-generation',\n  'projection-head',\n  'projection-state',\n  'effect-id',\n  'effect-preparation-material',\n  'effect-receipt',\n  'port-frame',\n  'side-channel-envelope',\n  'external-observation',\n  'project-manifest',\n  'deployment-request',\n  'deployment-lock',\n  'protocol-release-inventory',\n  'protocol-release-manifest',\n  'host-artifact-content',\n  'host-artifact-manifest',\n  'static-site-artifact-content',\n  'static-site-artifact-manifest',\n  'target-composition',\n  'deployment-manifest',\n  'event-id',\n  'event-fingerprint',\n  // D-031/D-032 (2026-09-03): multi-infrastructure deployment identities.\n  'deployment-intent',\n  'infrastructure-adapter-descriptor',\n  'infrastructure-descriptor',\n  'infrastructure-policy',\n  'managed-capability-export-contract',\n  'managed-capability-export-identity',\n  'target-object-identity-contract',\n  'target-deployment-namespace',\n  'target-object',\n  'provider-scope-identity-contract',\n  'provider-scope-normalization-vectors',\n  'provider-request-template',\n  // D-025/MI5A (2026-09-06): the deterministic target-artifact admission identity.\n  'target-artifact-admission',\n  'target-artifact-content-manifest',\n  // MI5B2 (2026-09-07): the public planning policy of one distribution capability.\n  'artifact-distribution-policy',\n])\n\nexport type DappDocumentKind = z.infer<typeof DappDocumentKindZod>\n\nexport interface DappDocumentCodec<T> {\n  kind: DappDocumentKind\n  schema: z.ZodType<T>\n  schemaVersion: number\n}\n\nexport interface EncodedDappDocument<T> {\n  canonicalJson: string\n  preimage: Uint8Array\n  value: T\n}\n\nexport interface HashedDappDocument<T> extends EncodedDappDocument<T> {\n  algorithm: typeof DappDocumentHashAlgorithm\n  hash: string\n}\n\nfunction assertValidUnicode(value: string, path: string): void {\n  for (const character of value) {\n    const codePoint = character.codePointAt(0)\n    if (codePoint !== undefined && codePoint >= 0xD8_00 && codePoint <= 0xDB_FF) {\n      throw new TypeError(`${path} contains an unpaired high surrogate`)\n    }\n    if (codePoint !== undefined && codePoint >= 0xDC_00 && codePoint <= 0xDF_FF) {\n      throw new TypeError(`${path} contains an unpaired low surrogate`)\n    }\n  }\n}\n\nfunction canonicalizeArray(value: unknown[], path: string): string {\n  const enumerableKeys = Object.keys(value)\n  if (enumerableKeys.length !== value.length\n    || enumerableKeys.some((key, index) => key !== String(index))) {\n    throw new TypeError(`${path} must be a dense JSON array without extra properties`)\n  }\n  return `[${value.map((entry, index) => canonicalizeValue(entry, `${path}[${index}]`)).join(',')}]`\n}\n\nfunction canonicalizeObject(value: object, path: string): string {\n  const prototype = Object.getPrototypeOf(value) as unknown\n  if (prototype !== Object.prototype && prototype !== null) {\n    throw new TypeError(`${path} must be a plain JSON object`)\n  }\n  if (Object.getOwnPropertySymbols(value).length > 0) {\n    throw new TypeError(`${path} cannot contain symbol properties`)\n  }\n\n  const descriptors = Object.getOwnPropertyDescriptors(value)\n  const keys = Object.keys(descriptors).toSorted()\n  return `{${keys.map((key) => {\n    const descriptor = descriptors[key]\n    if (descriptor === undefined || !descriptor.enumerable || !('value' in descriptor)) {\n      throw new TypeError(`${path}.${key} must be an enumerable JSON data property`)\n    }\n    const descriptorValue = descriptor.value as unknown\n    assertValidUnicode(key, `${path} key`)\n    return `${JSON.stringify(key)}:${canonicalizeValue(descriptorValue, `${path}.${key}`)}`\n  }).join(',')}}`\n}\n\nfunction canonicalizeValue(value: unknown, path: string): string {\n  if (value === null) return 'null'\n  if (typeof value === 'boolean') return value ? 'true' : 'false'\n  if (typeof value === 'string') {\n    assertValidUnicode(value, path)\n    return JSON.stringify(value)\n  }\n  if (typeof value === 'number') {\n    if (!Number.isFinite(value)) throw new TypeError(`${path} contains a non-finite number`)\n    return JSON.stringify(value)\n  }\n  if (Array.isArray(value)) return canonicalizeArray(value, path)\n  if (typeof value === 'object') return canonicalizeObject(value, path)\n  throw new TypeError(`${path} contains unsupported value type ${typeof value}`)\n}\n\nexport function canonicalizeIJson(value: unknown): string {\n  return canonicalizeValue(value, '$')\n}\n\nexport function dappDocumentDomainSeparator(kind: DappDocumentKind, schemaVersion = 1): string {\n  if (!Number.isSafeInteger(schemaVersion) || schemaVersion < 1) {\n    throw new TypeError('dapp document schema version must be a positive safe integer')\n  }\n  return `xyo-dapp-kit:${kind}:v${schemaVersion}\\n`\n}\n\nexport function encodeDappDocument<T>(codec: DappDocumentCodec<T>, value: unknown): EncodedDappDocument<T> {\n  const parsed = codec.schema.parse(value)\n  const canonicalJson = canonicalizeIJson(parsed)\n  const preimage = utf8ToBytes(`${dappDocumentDomainSeparator(codec.kind, codec.schemaVersion)}${canonicalJson}`)\n  return {\n    canonicalJson, preimage, value: parsed,\n  }\n}\n\nexport function hashDappDocument<T>(codec: DappDocumentCodec<T>, value: unknown): HashedDappDocument<T> {\n  const encoded = encodeDappDocument(codec, value)\n  return {\n    ...encoded,\n    algorithm: DappDocumentHashAlgorithm,\n    hash: bytesToHex(sha256(encoded.preimage)),\n  }\n}\n", "import { z } from 'zod'\n\nimport {\n  IdentifierZod,\n  Xl1AddressZod,\n  Xl1ChainIdZod,\n} from './identifier.ts'\nimport {\n  ContentProtectionZod,\n  DatalakeReadAccessZod,\n  ExternalSourceKindZod,\n  StorageDurabilityZod,\n} from './profile.ts'\n\nconst HttpEndpointRegExp = /^https?:\\/\\/[^\\s/@]+(?::\\d+)?(?:\\/[^\\s]*)?$/\nconst WebSocketEndpointRegExp = /^wss?:\\/\\/[^\\s/@]+(?::\\d+)?(?:\\/[^\\s]*)?$/\n\nexport const HttpEndpointZod = z.string().min(1).max(2048).regex(HttpEndpointRegExp)\nexport const WebSocketEndpointZod = z.string().min(1).max(2048).regex(WebSocketEndpointRegExp)\n\nexport const ResourceProvisionZod = z.enum(['managed-local', 'managed', 'external'])\nexport type ResourceProvision = z.infer<typeof ResourceProvisionZod>\n\nexport const ResourcePersistenceZod = z.enum(['ephemeral', 'retained', 'external'])\nexport type ResourcePersistence = z.infer<typeof ResourcePersistenceZod>\n\nconst ManagedLocalXl1ResourceRequestZod = z.strictObject({\n  class: z.literal('xl1-network'),\n  provision: z.literal('managed-local'),\n  persistence: z.enum(['ephemeral', 'retained']),\n  networkId: z.literal('local'),\n})\n\nconst ManagedXl1ResourceRequestZod = z.strictObject({\n  class: z.literal('xl1-network'),\n  provision: z.literal('managed'),\n  persistence: z.literal('retained'),\n  networkId: IdentifierZod,\n  expectedChainId: Xl1ChainIdZod.optional(),\n})\n\nconst ExternalXl1ResourceRequestZod = z.strictObject({\n  class: z.literal('xl1-network'),\n  provision: z.literal('external'),\n  persistence: z.literal('external'),\n  networkId: IdentifierZod,\n  expectedChainId: Xl1ChainIdZod,\n  endpoint: HttpEndpointZod,\n})\n\nexport const Xl1NetworkResourceRequestZod = z.union([\n  ManagedLocalXl1ResourceRequestZod,\n  ManagedXl1ResourceRequestZod,\n  ExternalXl1ResourceRequestZod,\n])\n\nexport type Xl1NetworkResourceRequest = z.infer<typeof Xl1NetworkResourceRequestZod>\n\nconst DatalakeResourcePolicyFields = {\n  readAccess: DatalakeReadAccessZod,\n  contentProtection: ContentProtectionZod,\n  minimumCopies: z.number().int().positive(),\n  retentionSeconds: z.number().int().nonnegative(),\n}\n\nconst ManagedLocalDatalakeResourceRequestZod = z.strictObject({\n  class: z.literal('datalake'),\n  provision: z.literal('managed-local'),\n  persistence: z.enum(['ephemeral', 'retained']),\n  ...DatalakeResourcePolicyFields,\n})\n\nconst ManagedDatalakeResourceRequestZod = z.strictObject({\n  class: z.literal('datalake'),\n  provision: z.literal('managed'),\n  persistence: z.literal('retained'),\n  ...DatalakeResourcePolicyFields,\n})\n\nconst ExternalDatalakeResourceRequestZod = z.strictObject({\n  class: z.literal('datalake'),\n  provision: z.literal('external'),\n  persistence: z.literal('external'),\n  endpoint: HttpEndpointZod,\n  ...DatalakeResourcePolicyFields,\n})\n\nexport const DatalakeResourceRequestZod = z.union([\n  ManagedLocalDatalakeResourceRequestZod,\n  ManagedDatalakeResourceRequestZod,\n  ExternalDatalakeResourceRequestZod,\n])\n\nexport type DatalakeResourceRequest = z.infer<typeof DatalakeResourceRequestZod>\n\nconst StoreResourceClasses = [\n  'effect-journal',\n  'projection-store',\n  'checkpoint-store',\n] as const\n\nexport const StoreResourceClassZod = z.enum(StoreResourceClasses)\nexport type StoreResourceClass = z.infer<typeof StoreResourceClassZod>\n\nconst ManagedStoreResourceRequestZod = z.strictObject({\n  class: StoreResourceClassZod,\n  provision: z.enum(['managed-local', 'managed']),\n  persistence: z.enum(['ephemeral', 'retained']),\n  durability: StorageDurabilityZod,\n})\n\nconst ExternalStoreResourceRequestZod = z.strictObject({\n  class: StoreResourceClassZod,\n  provision: z.literal('external'),\n  persistence: z.literal('external'),\n  durability: StorageDurabilityZod,\n  externalRef: IdentifierZod,\n})\n\nexport const StoreResourceRequestZod = z.union([\n  ManagedStoreResourceRequestZod,\n  ExternalStoreResourceRequestZod,\n])\n\nexport type StoreResourceRequest = z.infer<typeof StoreResourceRequestZod>\n\nconst ManagedSecretResourceRequestZod = z.strictObject({\n  class: z.literal('secret'),\n  provision: z.enum(['managed-local', 'managed']),\n  persistence: z.enum(['ephemeral', 'retained']),\n  durability: StorageDurabilityZod,\n})\n\nconst ExternalSecretResourceRequestZod = z.strictObject({\n  class: z.literal('secret'),\n  provision: z.literal('external'),\n  persistence: z.literal('external'),\n  durability: StorageDurabilityZod,\n  secretRef: IdentifierZod,\n})\n\nexport const SecretResourceRequestZod = z.union([\n  ManagedSecretResourceRequestZod,\n  ExternalSecretResourceRequestZod,\n])\n\nexport type SecretResourceRequest = z.infer<typeof SecretResourceRequestZod>\n\nconst EphemeralIdentityResourceRequestZod = z.strictObject({\n  class: z.literal('identity'),\n  provision: z.literal('managed-local'),\n  persistence: z.literal('ephemeral'),\n  mode: z.literal('ephemeral-local'),\n  childIndex: z.number().int().min(0).max(2_147_483_647),\n})\n\nconst ManagedIdentityResourceRequestZod = z.strictObject({\n  class: z.literal('identity'),\n  provision: z.literal('managed'),\n  persistence: z.literal('retained'),\n  mode: z.literal('provided'),\n  expectedAddress: Xl1AddressZod,\n})\n\nconst ExternalIdentityResourceRequestZod = z.strictObject({\n  class: z.literal('identity'),\n  provision: z.literal('external'),\n  persistence: z.literal('external'),\n  mode: z.literal('provided'),\n  secretRef: IdentifierZod,\n  expectedAddress: Xl1AddressZod,\n})\n\nexport const IdentityResourceRequestZod = z.union([\n  EphemeralIdentityResourceRequestZod,\n  ManagedIdentityResourceRequestZod,\n  ExternalIdentityResourceRequestZod,\n])\n\nexport type IdentityResourceRequest = z.infer<typeof IdentityResourceRequestZod>\n\n/** Public identity selection: external secret references never enter a plan. */\nexport const PublicIdentityResourceRequestZod = z.union([\n  EphemeralIdentityResourceRequestZod,\n  ManagedIdentityResourceRequestZod,\n  ExternalIdentityResourceRequestZod.omit({ secretRef: true }),\n])\nexport type PublicIdentityResourceRequest = z.infer<typeof PublicIdentityResourceRequestZod>\n\nconst ManagedSideChannelResourceRequestZod = z.strictObject({\n  class: z.literal('side-channel'),\n  provision: z.literal('managed'),\n  persistence: z.literal('retained'),\n})\n\nconst ExternalSideChannelResourceRequestZod = z.strictObject({\n  class: z.literal('side-channel'),\n  provision: z.literal('external'),\n  persistence: z.literal('external'),\n  endpoint: WebSocketEndpointZod,\n})\n\nexport const SideChannelResourceRequestZod = z.union([\n  ManagedSideChannelResourceRequestZod,\n  ExternalSideChannelResourceRequestZod,\n])\n\nexport type SideChannelResourceRequest = z.infer<typeof SideChannelResourceRequestZod>\n\nexport const ExternalSourceResourceRequestZod = z.strictObject({\n  class: z.literal('external-source'),\n  provision: z.literal('external'),\n  persistence: z.literal('external'),\n  sourceKind: ExternalSourceKindZod,\n  endpoint: HttpEndpointZod,\n})\n\nexport type ExternalSourceResourceRequest = z.infer<typeof ExternalSourceResourceRequestZod>\n\nexport const DappEventStreamCapabilityMoniker = 'xyo.event.stream' as const\nexport const DappEventSubscriptionCapabilityMoniker = 'xyo.event.subscription' as const\n\nconst ManagedEventStreamResourceRequestZod = z.strictObject({\n  class: z.literal('event-stream'),\n  provision: z.enum(['managed-local', 'managed']),\n  persistence: z.literal('retained'),\n})\n\nconst ExternalEventStreamResourceRequestZod = z.strictObject({\n  class: z.literal('event-stream'),\n  provision: z.literal('external'),\n  persistence: z.literal('external'),\n  externalRef: IdentifierZod,\n})\n\nexport const EventStreamResourceRequestZod = z.union([\n  ManagedEventStreamResourceRequestZod,\n  ExternalEventStreamResourceRequestZod,\n])\n\nexport type EventStreamResourceRequest = z.infer<typeof EventStreamResourceRequestZod>\n\nconst EventSubscriptionResourceFields = { streamResource: IdentifierZod }\n\nconst ManagedEventSubscriptionResourceRequestZod = z.strictObject({\n  class: z.literal('event-subscription'),\n  provision: z.enum(['managed-local', 'managed']),\n  persistence: z.literal('retained'),\n  ...EventSubscriptionResourceFields,\n})\n\nconst ExternalEventSubscriptionResourceRequestZod = z.strictObject({\n  class: z.literal('event-subscription'),\n  provision: z.literal('external'),\n  persistence: z.literal('external'),\n  externalRef: IdentifierZod,\n  ...EventSubscriptionResourceFields,\n})\n\nexport const EventSubscriptionResourceRequestZod = z.union([\n  ManagedEventSubscriptionResourceRequestZod,\n  ExternalEventSubscriptionResourceRequestZod,\n])\n\nexport type EventSubscriptionResourceRequest = z.infer<typeof EventSubscriptionResourceRequestZod>\n\nexport const DappResourceRequestZod = z.union([\n  Xl1NetworkResourceRequestZod,\n  DatalakeResourceRequestZod,\n  StoreResourceRequestZod,\n  SecretResourceRequestZod,\n  IdentityResourceRequestZod,\n  SideChannelResourceRequestZod,\n  ExternalSourceResourceRequestZod,\n  EventStreamResourceRequestZod,\n  EventSubscriptionResourceRequestZod,\n])\n\nexport type DappResourceRequest = z.infer<typeof DappResourceRequestZod>\n", "import { z } from 'zod'\n\nexport const XyoSchemaRegExp = /^(?:[a-z0-9]+\\.)*[a-z0-9]+$/\nexport const IdentifierRegExp = /^[a-z0-9]+(?:[._-][a-z0-9]+)*$/\nconst semanticVersionCore = String.raw`(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)\\.(?:0|[1-9]\\d*)`\nconst semanticVersionPreRelease = String.raw`(?:0|[1-9]\\d*|\\d*[A-Za-z-][0-9A-Za-z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[A-Za-z-][0-9A-Za-z-]*))*`\nconst semanticVersionBuild = String.raw`[0-9A-Za-z-]+(?:\\.[0-9A-Za-z-]+)*`\nexport const SemanticVersionRegExp = new RegExp(String.raw`^${semanticVersionCore}(?:-${semanticVersionPreRelease})?(?:\\+${semanticVersionBuild})?$`)\nexport const ProtocolVersionRegExp = /^(?:0|[1-9]\\d*)$/\nexport const Xl1ChainIdRegExp = /^[0-9a-f]{40}$/\nexport const Xl1AddressRegExp = /^[0-9a-f]{40}$/\nexport const HashRegExp = /^[0-9a-f]{64}$/\nexport const Base64UrlRegExp = /^[A-Za-z0-9_-]+$/\n\nexport const XyoSchemaZod = z.string().min(1).max(255).regex(XyoSchemaRegExp)\nexport const IdentifierZod = z.string().min(1).max(255).regex(IdentifierRegExp)\nexport const DappIdZod = XyoSchemaZod\nexport const SemanticVersionZod = z.string().regex(SemanticVersionRegExp)\nexport const ProtocolVersionZod = z.string().regex(ProtocolVersionRegExp)\nexport const SchemaVersionZod = z.number().int().positive()\nexport const Xl1ChainIdZod = z.string().regex(Xl1ChainIdRegExp)\nexport const Xl1AddressZod = z.string().regex(Xl1AddressRegExp)\nexport const HashZod = z.string().regex(HashRegExp)\nexport const Base64UrlZod = z.string().min(1).regex(Base64UrlRegExp)\n", "import { z } from 'zod'\n\nexport const DappSubstrateRelationshipZod = z.enum([\n  'consumes-finalized',\n  'projects-finalized',\n  'bridges-external',\n])\n\nexport type DappSubstrateRelationship = z.infer<typeof DappSubstrateRelationshipZod>\n\nexport const ExecutionModeZod = z.enum([\n  'on-demand',\n  'event-driven',\n  'scheduled',\n  'resident',\n])\n\nexport type ExecutionMode = z.infer<typeof ExecutionModeZod>\n\nexport const EffectAuthorityZod = z.enum([\n  'read-only',\n  'user-mediated',\n  'service-authorized',\n  'multi-party',\n])\n\nexport type EffectAuthority = z.infer<typeof EffectAuthorityZod>\n\nexport const CoordinationProfileZod = z.enum([\n  'none',\n  'optional-optimization',\n  'required-for-liveness',\n])\n\nexport type CoordinationProfile = z.infer<typeof CoordinationProfileZod>\n\nexport const SideChannelMessageKindZod = z.enum([\n  'ephemeral',\n  'proposal',\n  'attestation',\n  'projection-hint',\n])\n\nexport type SideChannelMessageKind = z.infer<typeof SideChannelMessageKindZod>\n\nexport const SideChannelTransportZod = z.enum([\n  'in-memory',\n  'post-message',\n  'http',\n  'websocket',\n  'webrtc',\n  'chatter',\n])\n\nexport type SideChannelTransport = z.infer<typeof SideChannelTransportZod>\n\nexport const ExternalInteractionModeZod = z.enum([\n  'none',\n  'observe',\n  'attest-import',\n  'actuate-export',\n])\n\nexport type ExternalInteractionMode = z.infer<typeof ExternalInteractionModeZod>\n\nexport const ExternalSourceKindZod = z.enum([\n  'api',\n  'evm-chain',\n  'sensor',\n  'clock',\n  'other',\n])\n\nexport type ExternalSourceKind = z.infer<typeof ExternalSourceKindZod>\n\nexport const CanonicalContentModeZod = z.enum([\n  'chain-only',\n  'commitment-only',\n  'datalake-backed',\n])\n\nexport type CanonicalContentMode = z.infer<typeof CanonicalContentModeZod>\n\nexport const DatalakeModeZod = z.enum(['none', 'optional', 'required'])\nexport type DatalakeMode = z.infer<typeof DatalakeModeZod>\n\nexport const DatalakeReadAccessZod = z.enum([\n  'public-read',\n  'capability-read',\n  'private-network',\n])\n\nexport type DatalakeReadAccess = z.infer<typeof DatalakeReadAccessZod>\n\nexport const ContentProtectionZod = z.enum([\n  'plaintext',\n  'encrypted',\n  'selectively-disclosed',\n])\n\nexport type ContentProtection = z.infer<typeof ContentProtectionZod>\n\nexport const DatalakeUnavailableBehaviorZod = z.enum([\n  'fail-closed',\n  'degrade-read-only',\n  'ignore-missing',\n])\n\nexport type DatalakeUnavailableBehavior = z.infer<typeof DatalakeUnavailableBehaviorZod>\n\nexport const AuxiliaryStorageClassZod = z.enum([\n  'secret',\n  'private-draft',\n  'effect-journal',\n  'replay-checkpoint',\n  'projection',\n  'disposable-cache',\n])\n\nexport type AuxiliaryStorageClass = z.infer<typeof AuxiliaryStorageClassZod>\n\nexport const StorageDurabilityZod = z.enum(['host-ephemeral', 'crash-durable'])\nexport type StorageDurability = z.infer<typeof StorageDurabilityZod>\n\nexport const RequirementLevelZod = z.enum(['optional', 'required'])\nexport type RequirementLevel = z.infer<typeof RequirementLevelZod>\n\nexport const ProjectionProfileZod = z.enum([\n  'none',\n  'ephemeral',\n  'private-durable',\n  'public-served',\n  'signed-publication',\n])\n\nexport type ProjectionProfile = z.infer<typeof ProjectionProfileZod>\n\nexport const ActiveProjectionProfileZod = z.enum([\n  'ephemeral',\n  'private-durable',\n  'public-served',\n  'signed-publication',\n])\n\nexport type ActiveProjectionProfile = z.infer<typeof ActiveProjectionProfileZod>\n\nexport const DurableProjectionProfileZod = z.enum([\n  'private-durable',\n  'public-served',\n  'signed-publication',\n])\n\nexport type DurableProjectionProfile = z.infer<typeof DurableProjectionProfileZod>\n\nexport const ProjectionTemporalityZod = z.enum(['bounded', 'unbounded'])\nexport type ProjectionTemporality = z.infer<typeof ProjectionTemporalityZod>\n\nexport const ProjectionPublicationZod = z.enum([\n  'none',\n  'query-service',\n  'generation-head-last',\n])\n\nexport type ProjectionPublication = z.infer<typeof ProjectionPublicationZod>\n", "import { z } from 'zod'\n\nimport {\n  IdentifierZod,\n  Xl1AddressZod,\n  Xl1ChainIdZod,\n} from './identifier.ts'\n\nexport const IdentityDerivationAlgorithm = 'bip44-secp256k1-v1' as const\nexport const Xl1Bip44BasePath = \"m/44'/60'/0'/0\" as const\nexport const MaximumBip32ChildIndex = 2_147_483_647\n\nconst Xl1Bip44ChildPathRegExp = /^m\\/44'\\/60'\\/0'\\/0\\/(0|[1-9]\\d*)$/\n\nexport const Xl1Bip44ChildPathZod = z.string().regex(Xl1Bip44ChildPathRegExp).superRefine((path, context) => {\n  const childIndex = Number(path.slice(path.lastIndexOf('/') + 1))\n  if (!Number.isSafeInteger(childIndex) || childIndex > MaximumBip32ChildIndex) {\n    context.addIssue({ code: 'custom', message: 'child index exceeds the non-hardened BIP-32 range' })\n  }\n})\n\nexport const IdentityMigrationZod = z.discriminatedUnion('mode', [\n  z.strictObject({ mode: z.literal('none') }),\n  z.strictObject({\n    mode: z.literal('rotate-from'),\n    predecessorAddress: Xl1AddressZod,\n    authorization: z.literal('application-protocol'),\n  }),\n])\n\nexport type IdentityMigration = z.infer<typeof IdentityMigrationZod>\n\nexport const IdentityDerivationZod = z.strictObject({\n  algorithm: z.literal(IdentityDerivationAlgorithm),\n  rootCapabilityId: IdentifierZod,\n  fullPath: Xl1Bip44ChildPathZod,\n  expectedAddress: Xl1AddressZod,\n  networkScope: Xl1ChainIdZod,\n  migration: IdentityMigrationZod,\n})\n\nexport type IdentityDerivation = z.infer<typeof IdentityDerivationZod>\n\nexport const IdentityBindingZod = z.strictObject({\n  roleId: IdentifierZod,\n  capabilityId: IdentifierZod,\n  derivation: IdentityDerivationZod.optional(),\n})\n\nexport type IdentityBinding = z.infer<typeof IdentityBindingZod>\n\nexport const IdentityBindingIssueCodes = [\n  'identity.address-duplicate',\n  'identity.capability-duplicate',\n  'identity.expected-address-mismatch',\n  'identity.invalid',\n  'identity.migration-cycle',\n  'identity.network-scope-mismatch',\n  'identity.path-duplicate',\n  'identity.role-duplicate',\n] as const\n\nexport const IdentityBindingIssueCodeZod = z.enum(IdentityBindingIssueCodes)\nexport type IdentityBindingIssueCode = z.infer<typeof IdentityBindingIssueCodeZod>\n\nexport interface IdentityBindingIssue {\n  code: IdentityBindingIssueCode\n  message: string\n  path: (number | string)[]\n}\n\nexport interface IdentityBindingValidationContext {\n  expectedChainId: string\n  resolvedAddresses?: Readonly<Record<string, string>>\n}\n\nexport interface IdentityBindingValidationSuccess {\n  success: true\n  value: IdentityBinding[]\n}\n\nexport interface IdentityBindingValidationFailure {\n  issues: IdentityBindingIssue[]\n  success: false\n}\n\nexport type IdentityBindingValidationResult = IdentityBindingValidationFailure | IdentityBindingValidationSuccess\n\nfunction issue(\n  code: IdentityBindingIssueCode,\n  message: string,\n  path: (number | string)[],\n): IdentityBindingIssue {\n  return {\n    code, message, path,\n  }\n}\n\nfunction duplicateIssues(\n  bindings: readonly IdentityBinding[],\n  key: (binding: IdentityBinding) => string | undefined,\n  code: IdentityBindingIssueCode,\n  message: string,\n  pathSuffix: string,\n): IdentityBindingIssue[] {\n  const firstIndexes = new Map<string, number>()\n  const issues: IdentityBindingIssue[] = []\n  for (const [index, binding] of bindings.entries()) {\n    const value = key(binding)\n    if (value === undefined) continue\n    if (firstIndexes.has(value)) {\n      issues.push(issue(code, message, [index, pathSuffix]))\n    } else {\n      firstIndexes.set(value, index)\n    }\n  }\n  return issues\n}\n\nfunction semanticIssues(\n  bindings: readonly IdentityBinding[],\n  context: IdentityBindingValidationContext,\n): IdentityBindingIssue[] {\n  const issues = [\n    ...duplicateIssues(bindings, binding => binding.roleId, 'identity.role-duplicate', 'identity roles may be bound once', 'roleId'),\n    ...duplicateIssues(bindings, binding => binding.capabilityId, 'identity.capability-duplicate', 'signer capabilities may be bound once', 'capabilityId'),\n    ...duplicateIssues(\n      bindings,\n      binding => binding.derivation === undefined\n        ? undefined\n        : `${binding.derivation.rootCapabilityId}:${binding.derivation.fullPath}`,\n      'identity.path-duplicate',\n      'derived identity paths may be bound once per root capability',\n      'derivation',\n    ),\n    ...duplicateIssues(\n      bindings,\n      binding => context.resolvedAddresses?.[binding.capabilityId] ?? binding.derivation?.expectedAddress,\n      'identity.address-duplicate',\n      'resolved identity addresses may be bound once',\n      'derivation',\n    ),\n  ]\n\n  for (const [index, binding] of bindings.entries()) {\n    const derivation = binding.derivation\n    if (derivation === undefined) continue\n    if (derivation.networkScope !== context.expectedChainId) {\n      issues.push(issue(\n        'identity.network-scope-mismatch',\n        'derived identity network scope must equal the configuration chain ID',\n        [index, 'derivation', 'networkScope'],\n      ))\n    }\n    const resolvedAddress = context.resolvedAddresses?.[binding.capabilityId]\n    if (resolvedAddress !== undefined && resolvedAddress !== derivation.expectedAddress) {\n      issues.push(issue(\n        'identity.expected-address-mismatch',\n        'resolved identity address does not match the configured expected address',\n        [index, 'derivation', 'expectedAddress'],\n      ))\n    }\n    if (derivation.migration.mode === 'rotate-from'\n      && derivation.migration.predecessorAddress === derivation.expectedAddress) {\n      issues.push(issue(\n        'identity.migration-cycle',\n        'identity rotation predecessor must differ from the successor address',\n        [index, 'derivation', 'migration', 'predecessorAddress'],\n      ))\n    }\n  }\n  return issues\n}\n\nexport function validateIdentityBindings(\n  value: unknown,\n  context: IdentityBindingValidationContext,\n): IdentityBindingValidationResult {\n  const result = z.array(IdentityBindingZod).safeParse(value)\n  if (!result.success) {\n    return {\n      issues: result.error.issues.map(validationIssue => issue(\n        'identity.invalid',\n        validationIssue.message,\n        validationIssue.path.map(value => typeof value === 'symbol' ? value.toString() : value),\n      )),\n      success: false,\n    }\n  }\n  const issues = semanticIssues(result.data, context)\n  return issues.length > 0 ? { issues, success: false } : { success: true, value: result.data }\n}\n", "import { z } from 'zod'\n\nexport type JsonPrimitive = boolean | null | number | string\n\nexport interface JsonObject {\n  [key: string]: JsonValue\n}\n\nexport type JsonValue = JsonObject | JsonPrimitive | JsonValue[]\n\nexport const JsonValueZod: z.ZodType<JsonValue> = z.lazy(() => z.union([\n  z.string(),\n  z.number(),\n  z.boolean(),\n  z.null(),\n  z.array(JsonValueZod),\n  z.record(z.string(), JsonValueZod),\n]))\n\nexport const JsonObjectZod: z.ZodType<JsonObject> = z.record(z.string(), JsonValueZod)\n", "import { z } from 'zod'\n\nimport { CapabilityRequirementZod, InstalledDescriptorReferenceZod } from './dappDefinition.ts'\nimport { IdentifierZod } from './identifier.ts'\nimport { JsonObjectZod } from './jsonValue.ts'\n\nexport const ApplicationProviderDependencyZod = z.discriminatedUnion('kind', [\n  z.strictObject({ kind: z.literal('application-provider'), instanceId: IdentifierZod }),\n  z.strictObject({ kind: z.literal('resource'), resourceId: IdentifierZod }),\n])\n\nexport type ApplicationProviderDependency = z.infer<typeof ApplicationProviderDependencyZod>\n\nexport const ApplicationProviderSelectionZod = z.strictObject({\n  instanceId: IdentifierZod,\n  artifactId: IdentifierZod,\n  descriptor: InstalledDescriptorReferenceZod,\n  host: IdentifierZod,\n  config: JsonObjectZod,\n  dependencies: z.record(IdentifierZod, ApplicationProviderDependencyZod),\n})\n\nexport type ApplicationProviderSelection = z.infer<typeof ApplicationProviderSelectionZod>\n\nexport const ApplicationProviderMetadataZod = z.strictObject({\n  providedCapabilities: z.array(CapabilityRequirementZod).min(1),\n  requiredCapabilities: z.array(CapabilityRequirementZod),\n}).superRefine((metadata, context) => {\n  for (const key of ['providedCapabilities', 'requiredCapabilities'] as const) {\n    const monikers = metadata[key].map(capability => capability.moniker)\n    const unique = new Set(monikers)\n    if (unique.size !== monikers.length) {\n      context.addIssue({\n        code: 'custom', message: 'application capability monikers must be unique', path: [key],\n      })\n    }\n  }\n})\n\nexport type ApplicationProviderMetadata = z.infer<typeof ApplicationProviderMetadataZod>\n\nexport function normalizeApplicationProviderSelections(selections: readonly ApplicationProviderSelection[]): ApplicationProviderSelection[] {\n  return selections.map(selection => ({\n    ...selection,\n    dependencies: Object.fromEntries(Object.entries(selection.dependencies).toSorted(([left], [right]) => left.localeCompare(right))),\n  })).toSorted((left, right) => left.instanceId.localeCompare(right.instanceId))\n}\n\nexport function normalizeApplicationProviderMetadata(metadata: ApplicationProviderMetadata): ApplicationProviderMetadata {\n  const sorted = (values: ApplicationProviderMetadata['providedCapabilities']) => [...values]\n    .toSorted((left, right) => left.moniker.localeCompare(right.moniker))\n  return { providedCapabilities: sorted(metadata.providedCapabilities), requiredCapabilities: sorted(metadata.requiredCapabilities) }\n}\n", "import { asSchema } from '@xyo-network/sdk'\nimport { z } from 'zod'\n\nimport {\n  DappIdZod,\n  IdentifierZod,\n  ProtocolVersionZod,\n  SchemaVersionZod,\n  SemanticVersionZod,\n  XyoSchemaZod,\n} from './identifier.ts'\nimport {\n  ActiveProjectionProfileZod,\n  AuxiliaryStorageClassZod,\n  CanonicalContentModeZod,\n  ContentProtectionZod,\n  DappSubstrateRelationshipZod,\n  DatalakeReadAccessZod,\n  DatalakeUnavailableBehaviorZod,\n  EffectAuthorityZod,\n  ExecutionModeZod,\n  ExternalSourceKindZod,\n  ProjectionPublicationZod,\n  ProjectionTemporalityZod,\n  RequirementLevelZod,\n  SideChannelMessageKindZod,\n  StorageDurabilityZod,\n} from './profile.ts'\nconst addDuplicateIssue = (values: readonly string[], path: PropertyKey[], context: z.core.$RefinementCtx<unknown>) => {\n  const unique = new Set(values)\n  if (unique.size !== values.length) {\n    context.addIssue({\n      code: 'custom', message: 'values must be unique', path,\n    })\n  }\n}\n\nexport const DappDefinitionSchema = asSchema('network.xyo.dapp.definition', true)\n\nexport const DappSchemaReferenceZod = z.strictObject({\n  schema: XyoSchemaZod,\n  version: SchemaVersionZod,\n})\n\nexport type DappSchemaReference = z.infer<typeof DappSchemaReferenceZod>\n\nexport const InstalledDescriptorReferenceZod = z.strictObject({\n  id: IdentifierZod,\n  version: SchemaVersionZod,\n})\n\nexport type InstalledDescriptorReference = z.infer<typeof InstalledDescriptorReferenceZod>\n\nconst CoordinationRequirementFields = {\n  messageKinds: z.array(SideChannelMessageKindZod).min(1),\n  authorizedSenderRoles: z.array(IdentifierZod).min(1),\n  delivery: z.literal('unordered-at-least-once'),\n  historyCanonical: z.literal(false),\n  detachedSignatures: z.literal(true),\n  maximumMessageBytes: z.number().int().positive(),\n  minimumReplayRetentionSeconds: z.number().int().positive(),\n  maximumClockSkewMilliseconds: z.number().int().nonnegative(),\n}\n\nexport const CoordinationRequirementZod = z.discriminatedUnion('profile', [\n  z.strictObject({ profile: z.literal('none') }),\n  z.strictObject({\n    profile: z.literal('optional-optimization'),\n    ...CoordinationRequirementFields,\n  }),\n  z.strictObject({\n    profile: z.literal('required-for-liveness'),\n    ...CoordinationRequirementFields,\n  }),\n]).superRefine((coordination, context) => {\n  if (coordination.profile === 'none') return\n  addDuplicateIssue(coordination.messageKinds, ['messageKinds'], context)\n  addDuplicateIssue(coordination.authorizedSenderRoles, ['authorizedSenderRoles'], context)\n})\n\nexport type CoordinationRequirement = z.infer<typeof CoordinationRequirementZod>\n\nconst ExternalObservationRequirementFields = {\n  allowedSourceKinds: z.array(ExternalSourceKindZod).min(1),\n  provenancePolicy: InstalledDescriptorReferenceZod,\n  finalityPolicy: InstalledDescriptorReferenceZod,\n}\n\nexport const ExternalInteractionRequirementZod = z.discriminatedUnion('mode', [\n  z.strictObject({ mode: z.literal('none') }),\n  z.strictObject({\n    mode: z.literal('observe'),\n    ...ExternalObservationRequirementFields,\n  }),\n  z.strictObject({\n    mode: z.literal('attest-import'),\n    ...ExternalObservationRequirementFields,\n    observationSchemas: z.array(DappSchemaReferenceZod).min(1),\n    commitBeforeReduction: z.literal(true),\n  }),\n  z.strictObject({\n    mode: z.literal('actuate-export'),\n    effectFamily: IdentifierZod,\n  }),\n]).superRefine((externalInteraction, context) => {\n  if (externalInteraction.mode === 'none' || externalInteraction.mode === 'actuate-export') return\n  addDuplicateIssue(externalInteraction.allowedSourceKinds, ['allowedSourceKinds'], context)\n  if (externalInteraction.mode === 'attest-import') {\n    addDuplicateIssue(\n      externalInteraction.observationSchemas.map(schema => `${schema.schema}@${schema.version}`),\n      ['observationSchemas'],\n      context,\n    )\n  }\n})\n\nexport type ExternalInteractionRequirement = z.infer<typeof ExternalInteractionRequirementZod>\n\nexport const ProjectionRequirementZod = z.discriminatedUnion('profile', [\n  z.strictObject({ profile: z.literal('none') }),\n  z.strictObject({\n    profile: ActiveProjectionProfileZod,\n    reducer: InstalledDescriptorReferenceZod,\n    inputSchemas: z.array(DappSchemaReferenceZod).min(1),\n    temporality: ProjectionTemporalityZod,\n    replayOrder: z.literal('forward'),\n    finalizedOnly: z.literal(true),\n    rebuildable: z.literal(true),\n    queryAccess: DatalakeReadAccessZod,\n    publication: ProjectionPublicationZod,\n    progressWatermark: z.boolean(),\n  }),\n]).superRefine((projection, context) => {\n  if (projection.profile === 'none') return\n  addDuplicateIssue(\n    projection.inputSchemas.map(schema => `${schema.schema}@${schema.version}`),\n    ['inputSchemas'],\n    context,\n  )\n})\n\nexport type ProjectionRequirement = z.infer<typeof ProjectionRequirementZod>\n\nexport const CapabilityRequirementZod = z.strictObject({\n  moniker: IdentifierZod,\n  version: SchemaVersionZod,\n})\n\nexport type CapabilityRequirement = z.infer<typeof CapabilityRequirementZod>\n\nexport const DappActorDefinitionZod = z.strictObject({\n  roleId: IdentifierZod,\n  descriptor: InstalledDescriptorReferenceZod,\n  supportedExecutionModes: z.array(ExecutionModeZod).min(1),\n  effectAuthority: EffectAuthorityZod,\n  requiredCapabilities: z.array(CapabilityRequirementZod),\n}).superRefine((actor, context) => {\n  addDuplicateIssue(actor.supportedExecutionModes, ['supportedExecutionModes'], context)\n  addDuplicateIssue(\n    actor.requiredCapabilities.map(capability => `${capability.moniker}@${capability.version}`),\n    ['requiredCapabilities'],\n    context,\n  )\n})\n\nexport type DappActorDefinition = z.infer<typeof DappActorDefinitionZod>\n\nexport const DappPortDefinitionZod = z.strictObject({\n  portId: IdentifierZod,\n  version: ProtocolVersionZod,\n  commands: z.array(IdentifierZod),\n  queries: z.array(IdentifierZod),\n  subscriptions: z.array(IdentifierZod),\n}).superRefine((port, context) => {\n  addDuplicateIssue(port.commands, ['commands'], context)\n  addDuplicateIssue(port.queries, ['queries'], context)\n  addDuplicateIssue(port.subscriptions, ['subscriptions'], context)\n})\n\nexport type DappPortDefinition = z.infer<typeof DappPortDefinitionZod>\n\nconst DatalakeRequirementFields = {\n  allowedReadAccess: z.array(DatalakeReadAccessZod).min(1),\n  allowedContentProtection: z.array(ContentProtectionZod).min(1),\n  minimumCopies: z.number().int().nonnegative(),\n  minimumRetentionSeconds: z.number().int().nonnegative(),\n  unavailableBehavior: DatalakeUnavailableBehaviorZod,\n}\n\nexport const DatalakeRequirementZod = z.discriminatedUnion('mode', [\n  z.strictObject({ mode: z.literal('none') }),\n  z.strictObject({\n    mode: z.literal('optional'),\n    ...DatalakeRequirementFields,\n  }),\n  z.strictObject({\n    mode: z.literal('required'),\n    ...DatalakeRequirementFields,\n    minimumCopies: z.number().int().positive(),\n  }),\n]).superRefine((requirement, context) => {\n  if (requirement.mode === 'none') return\n  addDuplicateIssue(requirement.allowedReadAccess, ['allowedReadAccess'], context)\n  addDuplicateIssue(requirement.allowedContentProtection, ['allowedContentProtection'], context)\n})\n\nexport type DatalakeRequirement = z.infer<typeof DatalakeRequirementZod>\n\nexport const AuxiliaryStoreRequirementZod = z.strictObject({\n  class: AuxiliaryStorageClassZod,\n  requirement: RequirementLevelZod,\n  minimumDurability: StorageDurabilityZod,\n})\n\nexport type AuxiliaryStoreRequirement = z.infer<typeof AuxiliaryStoreRequirementZod>\n\nconst DappDefinitionDocumentZod = z.strictObject({\n  schema: z.literal(DappDefinitionSchema),\n  schemaVersion: z.literal(1),\n  dappId: DappIdZod,\n  definitionVersion: SemanticVersionZod,\n  protocolVersion: ProtocolVersionZod,\n  substrate: z.strictObject({\n    canonicalSource: z.literal('xl1-finalized'),\n    relationships: z.array(DappSubstrateRelationshipZod).min(1),\n  }),\n  schemas: z.array(DappSchemaReferenceZod),\n  actors: z.array(DappActorDefinitionZod),\n  ports: z.array(DappPortDefinitionZod),\n  identityRoles: z.array(IdentifierZod),\n  coordination: CoordinationRequirementZod,\n  externalInteraction: ExternalInteractionRequirementZod,\n  durability: z.strictObject({\n    contentMode: CanonicalContentModeZod,\n    datalake: DatalakeRequirementZod,\n    projection: ProjectionRequirementZod,\n    auxiliaryStores: z.array(AuxiliaryStoreRequirementZod),\n    consistency: z.literal('finalized'),\n  }),\n  compatibility: z.strictObject({\n    minimumHostProtocol: ProtocolVersionZod,\n    acceptedPriorProtocolVersions: z.array(ProtocolVersionZod),\n  }),\n})\n\nexport type DappDefinition = z.infer<typeof DappDefinitionDocumentZod>\n\nfunction addDefinitionDuplicateIssues(definition: DappDefinition, context: z.core.$RefinementCtx<unknown>) {\n  addDuplicateIssue(definition.substrate.relationships, ['substrate', 'relationships'], context)\n  addDuplicateIssue(\n    definition.schemas.map(schema => `${schema.schema}@${schema.version}`),\n    ['schemas'],\n    context,\n  )\n  addDuplicateIssue(definition.actors.map(actor => actor.roleId), ['actors'], context)\n  addDuplicateIssue(definition.ports.map(port => port.portId), ['ports'], context)\n  addDuplicateIssue(definition.identityRoles, ['identityRoles'], context)\n  addDuplicateIssue(definition.durability.auxiliaryStores.map(store => store.class), ['durability', 'auxiliaryStores'], context)\n  addDuplicateIssue(definition.compatibility.acceptedPriorProtocolVersions, ['compatibility', 'acceptedPriorProtocolVersions'], context)\n}\n\nfunction addSubstrateIssues(definition: DappDefinition, context: z.core.$RefinementCtx<unknown>) {\n  if (!definition.substrate.relationships.includes('consumes-finalized')) {\n    context.addIssue({\n      code: 'custom',\n      message: 'an XL1 dApp must consume finalized XL1',\n      path: ['substrate', 'relationships'],\n    })\n  }\n}\n\nfunction addCoordinationIssues(definition: DappDefinition, context: z.core.$RefinementCtx<unknown>) {\n  if (definition.coordination.profile === 'none') {\n    return\n  }\n\n  const identityRoles = new Set(definition.identityRoles)\n  for (const [index, role] of definition.coordination.authorizedSenderRoles.entries()) {\n    if (!identityRoles.has(role)) {\n      context.addIssue({\n        code: 'custom',\n        message: 'coordination sender role must be declared by the definition',\n        path: ['coordination', 'authorizedSenderRoles', index],\n      })\n    }\n  }\n}\n\nfunction addExternalInteractionIssues(definition: DappDefinition, context: z.core.$RefinementCtx<unknown>) {\n  const externalInteraction = definition.externalInteraction\n  const hasExternalRelationship = definition.substrate.relationships.includes('bridges-external')\n  const hasExternalInteraction = externalInteraction.mode !== 'none'\n  if (hasExternalRelationship !== hasExternalInteraction) {\n    context.addIssue({\n      code: 'custom',\n      message: 'external substrate relationship and interaction mode must agree',\n      path: ['externalInteraction', 'mode'],\n    })\n  }\n  if (externalInteraction.mode === 'actuate-export') {\n    context.addIssue({\n      code: 'custom',\n      message: 'generic outbound external actuation is unsupported in dapp-kit V1',\n      path: ['externalInteraction', 'mode'],\n    })\n  }\n  if (externalInteraction.mode !== 'attest-import') return\n  const declaredSchemas = new Set(definition.schemas.map(schema => `${schema.schema}@${schema.version}`))\n  for (const [index, schema] of externalInteraction.observationSchemas.entries()) {\n    if (!declaredSchemas.has(`${schema.schema}@${schema.version}`)) {\n      context.addIssue({\n        code: 'custom',\n        message: 'external observation schema must be declared by the definition',\n        path: ['externalInteraction', 'observationSchemas', index],\n      })\n    }\n  }\n}\n\nfunction addProjectionRelationshipIssues(definition: DappDefinition, context: z.core.$RefinementCtx<unknown>) {\n  const hasProjectionRelationship = definition.substrate.relationships.includes('projects-finalized')\n  const hasProjection = definition.durability.projection.profile !== 'none'\n  if (hasProjectionRelationship !== hasProjection) {\n    context.addIssue({\n      code: 'custom',\n      message: 'projection relationship and durability profile must agree',\n      path: ['durability', 'projection'],\n    })\n  }\n}\n\nfunction addContentModeIssues(definition: DappDefinition, context: z.core.$RefinementCtx<unknown>) {\n  const contentMode = definition.durability.contentMode\n  const datalakeMode = definition.durability.datalake.mode\n  const isDatalakeModeCompatible = contentMode === 'chain-only'\n    ? datalakeMode === 'none'\n    : contentMode === 'commitment-only'\n      ? datalakeMode !== 'required'\n      : datalakeMode === 'required'\n\n  if (!isDatalakeModeCompatible) {\n    context.addIssue({\n      code: 'custom',\n      message: 'canonical content mode and definition datalake requirement are incompatible',\n      path: ['durability', 'datalake', 'mode'],\n    })\n  }\n}\n\nfunction addProjectionIssues(definition: DappDefinition, context: z.core.$RefinementCtx<unknown>) {\n  const projection = definition.durability.projection\n  if (projection.profile === 'none') return\n  const declaredSchemas = new Set(definition.schemas.map(schema => `${schema.schema}@${schema.version}`))\n  for (const [index, schema] of projection.inputSchemas.entries()) {\n    if (!declaredSchemas.has(`${schema.schema}@${schema.version}`)) {\n      context.addIssue({\n        code: 'custom',\n        message: 'projection input schema must be declared by the definition',\n        path: ['durability', 'projection', 'inputSchemas', index],\n      })\n    }\n  }\n\n  if (projection.profile === 'ephemeral') return\n  const stores = new Map(definition.durability.auxiliaryStores.map(store => [store.class, store]))\n  for (const requiredClass of ['projection', 'replay-checkpoint'] as const) {\n    const store = stores.get(requiredClass)\n    if (store?.requirement !== 'required' || store.minimumDurability !== 'crash-durable') {\n      context.addIssue({\n        code: 'custom',\n        message: 'durable projections require crash-durable projection and replay-checkpoint stores',\n        path: ['durability', 'auxiliaryStores'],\n      })\n      break\n    }\n  }\n}\n\nexport const DappDefinitionZod = DappDefinitionDocumentZod.superRefine((definition, context) => {\n  addDefinitionDuplicateIssues(definition, context)\n  addSubstrateIssues(definition, context)\n  addCoordinationIssues(definition, context)\n  addExternalInteractionIssues(definition, context)\n  addProjectionRelationshipIssues(definition, context)\n  addContentModeIssues(definition, context)\n  addProjectionIssues(definition, context)\n})\n", "import { z } from 'zod'\n\nimport { HostArtifactProviderDescriptorZod } from './hostArtifact.ts'\nimport { IdentifierZod } from './identifier.ts'\n\n/** Supplied by the admitting artifact planner, never by app configuration. */\nexport const ApplicationProviderDescriptorZod = z.strictObject({\n  artifactId: IdentifierZod,\n  descriptor: HostArtifactProviderDescriptorZod,\n})\n\nexport type ApplicationProviderDescriptor = z.infer<typeof ApplicationProviderDescriptorZod>\n", "import { asSchema } from '@xyo-network/sdk'\nimport { z } from 'zod'\n\nimport { ApplicationProviderMetadataZod, normalizeApplicationProviderMetadata } from './applicationProvider.ts'\nimport {\n  DappDocumentHashAlgorithm,\n  hashDappDocument,\n} from './canonicalDocument.ts'\nimport {\n  HashZod,\n  IdentifierZod,\n  ProtocolVersionZod,\n  SemanticVersionZod,\n} from './identifier.ts'\nimport { InstalledDescriptorMetadataZod } from './plan.ts'\nimport { ExecutionModeZod } from './profile.ts'\nimport {\n  PackageNameZod,\n  RepositoryRelativePathZod,\n} from './projectArtifact.ts'\nconst JavaScriptExportNameRegExp = /^[A-Za-z_$][0-9A-Za-z_$]*$/\n\nexport const DappHostArtifactSchema = asSchema('network.xyo.dapp.host.artifact', true)\n\nexport const HostArtifactExecutableFileZod = z.strictObject({\n  path: RepositoryRelativePathZod,\n  sha256: HashZod,\n  size: z.number().int().nonnegative(),\n})\n\nexport type HostArtifactExecutableFile = z.infer<typeof HostArtifactExecutableFileZod>\n\nexport const HostArtifactActorDescriptorZod = z.strictObject({\n  kind: z.literal('actor'),\n  metadata: InstalledDescriptorMetadataZod,\n  actorSystemRunMode: z.enum(['one-shot', 'resident']),\n  supportedExecutionModes: z.array(ExecutionModeZod).min(1),\n  requiredMonikers: z.array(IdentifierZod),\n})\n\nexport type HostArtifactActorDescriptor = z.infer<typeof HostArtifactActorDescriptorZod>\n\nexport const HostArtifactProviderDescriptorZod = z.strictObject({\n  application: ApplicationProviderMetadataZod.optional(),\n  kind: z.literal('provider'),\n  metadata: InstalledDescriptorMetadataZod,\n  connectionTypes: z.array(z.string().min(1)),\n  providedMonikers: z.array(IdentifierZod).min(1),\n  requiredMonikers: z.array(IdentifierZod),\n}).superRefine((descriptor, context) => {\n  const application = descriptor.application\n  if (application === undefined) return\n  for (const [field, capabilities] of [\n    ['providedMonikers', application.providedCapabilities],\n    ['requiredMonikers', application.requiredCapabilities],\n  ] as const) {\n    const expected = capabilities.map(capability => capability.moniker).toSorted()\n    const actual = [...descriptor[field]].toSorted()\n    if (expected.length !== actual.length || expected.some((value, index) => value !== actual[index])) {\n      context.addIssue({\n        code: 'custom', message: 'application capabilities must exactly match descriptor monikers', path: [field],\n      })\n    }\n  }\n})\n\nexport type HostArtifactProviderDescriptor = z.infer<typeof HostArtifactProviderDescriptorZod>\n\nexport const HostArtifactDescriptorZod = z.discriminatedUnion('kind', [\n  HostArtifactActorDescriptorZod,\n  HostArtifactProviderDescriptorZod,\n])\n\nexport type HostArtifactDescriptor = z.infer<typeof HostArtifactDescriptorZod>\n\nfunction descriptorKey(descriptor: HostArtifactDescriptor): string {\n  return `${descriptor.kind}:${descriptor.metadata.descriptor.id}@${descriptor.metadata.descriptor.version}`\n}\n\nfunction duplicateValues(values: readonly string[]): boolean {\n  const unique = new Set(values)\n  return unique.size !== values.length\n}\n\nexport const DappHostArtifactManifestZod = z.strictObject({\n  schema: z.literal(DappHostArtifactSchema),\n  schemaVersion: z.literal(1),\n  hashAlgorithm: z.literal(DappDocumentHashAlgorithm),\n  artifactId: IdentifierZod,\n  package: z.strictObject({\n    name: PackageNameZod,\n    version: SemanticVersionZod,\n  }),\n  runtime: z.literal('node'),\n  nodeVersionRange: z.string().min(1).max(255),\n  hostProtocolVersions: z.array(ProtocolVersionZod).min(1),\n  installation: z.strictObject({\n    module: RepositoryRelativePathZod,\n    export: z.string().min(1).max(255).regex(JavaScriptExportNameRegExp),\n  }),\n  hosts: z.array(IdentifierZod).min(1),\n  artifactRoot: RepositoryRelativePathZod,\n  files: z.array(HostArtifactExecutableFileZod).min(1),\n  descriptors: z.array(HostArtifactDescriptorZod),\n  buildInputHash: HashZod,\n  contentRoot: HashZod,\n}).superRefine((manifest, context) => {\n  if (duplicateValues(manifest.hostProtocolVersions)) {\n    context.addIssue({\n      code: 'custom', message: 'host protocol versions must be unique', path: ['hostProtocolVersions'],\n    })\n  }\n  if (duplicateValues(manifest.hosts)) {\n    context.addIssue({\n      code: 'custom', message: 'host IDs must be unique', path: ['hosts'],\n    })\n  }\n  if (duplicateValues(manifest.files.map(file => file.path))) {\n    context.addIssue({\n      code: 'custom', message: 'artifact file paths must be unique', path: ['files'],\n    })\n  }\n  if (duplicateValues(manifest.descriptors.map(descriptorKey))) {\n    context.addIssue({\n      code: 'custom', message: 'artifact descriptors must be unique', path: ['descriptors'],\n    })\n  }\n  for (const [index, descriptor] of manifest.descriptors.entries()) {\n    const arrays = descriptor.kind === 'actor'\n      ? [descriptor.supportedExecutionModes, descriptor.requiredMonikers]\n      : [descriptor.connectionTypes, descriptor.providedMonikers, descriptor.requiredMonikers]\n    if (arrays.some(duplicateValues)) {\n      context.addIssue({\n        code: 'custom', message: 'descriptor inventory arrays must be unique', path: ['descriptors', index],\n      })\n    }\n  }\n  const rootPrefix = `${manifest.artifactRoot}/`\n  for (const [index, file] of manifest.files.entries()) {\n    if (!file.path.startsWith(rootPrefix)) {\n      context.addIssue({\n        code: 'custom',\n        message: 'artifact files must be children of artifactRoot',\n        path: ['files', index, 'path'],\n      })\n    }\n  }\n  if (manifest.files.every(file => file.path !== manifest.installation.module)) {\n    context.addIssue({\n      code: 'custom',\n      message: 'installation module must be present in the artifact file inventory',\n      path: ['installation', 'module'],\n    })\n  }\n  if (hashHostArtifactContent(manifest.files) !== manifest.contentRoot) {\n    context.addIssue({\n      code: 'custom', message: 'content root does not match artifact files', path: ['contentRoot'],\n    })\n  }\n})\n\nexport type DappHostArtifactManifest = z.infer<typeof DappHostArtifactManifestZod>\n\nfunction sortedUnique(values: readonly string[]): string[] {\n  return [...values].toSorted()\n}\n\nfunction normalizeDescriptor(descriptor: HostArtifactDescriptor): HostArtifactDescriptor {\n  return descriptor.kind === 'actor'\n    ? {\n        ...descriptor,\n        requiredMonikers: sortedUnique(descriptor.requiredMonikers),\n        supportedExecutionModes: sortedUnique(descriptor.supportedExecutionModes) as typeof descriptor.supportedExecutionModes,\n      }\n    : {\n        ...descriptor,\n        ...(descriptor.application === undefined ? {} : { application: normalizeApplicationProviderMetadata(descriptor.application) }),\n        connectionTypes: sortedUnique(descriptor.connectionTypes),\n        providedMonikers: sortedUnique(descriptor.providedMonikers),\n        requiredMonikers: sortedUnique(descriptor.requiredMonikers),\n      }\n}\n\nexport function normalizeHostArtifactFiles(\n  files: readonly HostArtifactExecutableFile[],\n): HostArtifactExecutableFile[] {\n  return [...files].toSorted((left, right) => left.path.localeCompare(right.path))\n}\n\nexport function hashHostArtifactContent(filesValue: unknown): string {\n  const files = z.array(HostArtifactExecutableFileZod).parse(filesValue)\n  return hashDappDocument({\n    kind: 'host-artifact-content',\n    schema: z.array(HostArtifactExecutableFileZod),\n    schemaVersion: 1,\n  }, normalizeHostArtifactFiles(files)).hash\n}\n\nexport function normalizeDappHostArtifactManifest(value: unknown): DappHostArtifactManifest {\n  const manifest = DappHostArtifactManifestZod.parse(value)\n  return DappHostArtifactManifestZod.parse({\n    ...manifest,\n    hostProtocolVersions: sortedUnique(manifest.hostProtocolVersions),\n    hosts: sortedUnique(manifest.hosts),\n    files: normalizeHostArtifactFiles(manifest.files),\n    descriptors: manifest.descriptors.map(normalizeDescriptor).toSorted((left, right) => (\n      descriptorKey(left).localeCompare(descriptorKey(right))\n    )),\n  })\n}\n\nexport function hashDappHostArtifactManifest(value: unknown) {\n  const manifest = normalizeDappHostArtifactManifest(value)\n  return hashDappDocument({\n    kind: 'host-artifact-manifest',\n    schema: DappHostArtifactManifestZod,\n    schemaVersion: 1,\n  }, manifest)\n}\n", "import { asSchema } from '@xyo-network/sdk'\nimport { z } from 'zod'\n\nimport { applicationIdentityPlanIssues } from './applicationIdentity.ts'\nimport { applicationProviderPlanIssues } from './applicationProviderPlan.ts'\nimport { hashDappDocument } from './canonicalDocument.ts'\nimport type { DappConfiguration } from './dappConfiguration.ts'\nimport { DappConfigurationZod } from './dappConfiguration.ts'\nimport {\n  CapabilityRequirementZod,\n  DappDefinitionZod,\n  InstalledDescriptorReferenceZod,\n} from './dappDefinition.ts'\nimport {\n  HashZod,\n  IdentifierZod,\n} from './identifier.ts'\nimport { JsonObjectZod } from './jsonValue.ts'\nimport {\n  normalizeDappConfiguration,\n  normalizeDappDefinition,\n} from './planNormalization.ts'\nimport { validateDappProfile } from './validation.ts'\nexport const DappPlanSchema = asSchema('network.xyo.dapp.plan', true)\n\nexport const InstalledDescriptorMetadataZod = z.strictObject({\n  descriptor: InstalledDescriptorReferenceZod,\n  configSchemaHash: HashZod,\n  implementationHash: HashZod,\n})\n\nexport type InstalledDescriptorMetadata = z.infer<typeof InstalledDescriptorMetadataZod>\n\nexport const ResolvedProviderNodeZod = z.strictObject({\n  instanceId: IdentifierZod,\n  descriptor: InstalledDescriptorMetadataZod,\n  config: JsonObjectZod,\n  providedCapabilities: z.array(CapabilityRequirementZod),\n  dependencies: z.array(IdentifierZod),\n}).superRefine((provider, context) => {\n  const unique = new Set(provider.dependencies)\n  if (unique.size !== provider.dependencies.length) {\n    context.addIssue({\n      code: 'custom',\n      message: 'provider dependencies must be unique',\n      path: ['dependencies'],\n    })\n  }\n  const capabilities = provider.providedCapabilities.map(capabilityKey)\n  const unique2 = new Set(capabilities)\n  if (unique2.size !== capabilities.length) {\n    context.addIssue({\n      code: 'custom',\n      message: 'provided capabilities must be unique',\n      path: ['providedCapabilities'],\n    })\n  }\n})\n\nexport type ResolvedProviderNode = z.infer<typeof ResolvedProviderNodeZod>\n\nexport const DappPlanPortBindingZod = z.strictObject({\n  portId: IdentifierZod,\n  host: IdentifierZod,\n})\n\nexport type DappPlanPortBinding = z.infer<typeof DappPlanPortBindingZod>\n\nexport const DappPlanMaterialZod = z.strictObject({\n  definition: DappDefinitionZod,\n  configuration: DappConfigurationZod,\n  actorDescriptors: z.array(InstalledDescriptorMetadataZod),\n  resolvedProviders: z.array(ResolvedProviderNodeZod),\n  portBindings: z.array(DappPlanPortBindingZod),\n}).superRefine((material, context) => {\n  addUniqueIssue(\n    material.actorDescriptors.map(descriptorMetadataKey),\n    ['actorDescriptors'],\n    'actor descriptor metadata entries must be unique',\n    context,\n  )\n  addUniqueIssue(\n    material.resolvedProviders.map(provider => provider.instanceId),\n    ['resolvedProviders'],\n    'resolved provider instance IDs must be unique',\n    context,\n  )\n  addUniqueIssue(\n    material.portBindings.map(binding => binding.portId),\n    ['portBindings'],\n    'port bindings must be unique',\n    context,\n  )\n})\n\nexport type DappPlanMaterial = z.infer<typeof DappPlanMaterialZod>\n\nexport const DappPlanHostPartitionZod = z.strictObject({\n  host: IdentifierZod,\n  actorInstanceIds: z.array(IdentifierZod),\n  portIds: z.array(IdentifierZod),\n})\n\nexport type DappPlanHostPartition = z.infer<typeof DappPlanHostPartitionZod>\n\nexport const DappPlanPreimageZod = z.strictObject({\n  schema: z.literal(DappPlanSchema),\n  schemaVersion: z.literal(1),\n  definitionHash: HashZod,\n  configurationHash: HashZod,\n  definition: DappDefinitionZod,\n  configuration: DappConfigurationZod,\n  actorDescriptors: z.array(InstalledDescriptorMetadataZod),\n  resolvedProviders: z.array(ResolvedProviderNodeZod),\n  portBindings: z.array(DappPlanPortBindingZod),\n  hostPartitions: z.array(DappPlanHostPartitionZod),\n})\n\nexport type DappPlanPreimage = z.infer<typeof DappPlanPreimageZod>\n\nexport const DappPlanZod = DappPlanPreimageZod.extend({ planId: HashZod })\n\nexport type DappPlan = z.infer<typeof DappPlanZod>\n\nexport const DappPlanIssueCodes = [\n  'plan.application-provider-invalid',\n  'plan.actor-descriptor-missing',\n  'plan.actor-descriptor-unexpected',\n  'plan.capability-ambiguous',\n  'plan.capability-missing',\n  'plan.material-invalid',\n  'plan.port-binding-host-unknown',\n  'plan.port-binding-missing',\n  'plan.port-binding-unexpected',\n  'plan.profile-invalid',\n  'plan.provider-dependency-cycle',\n  'plan.provider-dependency-missing',\n] as const\n\nexport const DappPlanIssueCodeZod = z.enum(DappPlanIssueCodes)\n\nexport type DappPlanIssueCode = z.infer<typeof DappPlanIssueCodeZod>\n\nexport interface DappPlanIssue {\n  code: DappPlanIssueCode\n  message: string\n  path: (number | string)[]\n}\n\nexport interface DappPlanSuccess {\n  preimage: DappPlanPreimage\n  success: true\n  value: DappPlan\n}\n\nexport interface DappPlanFailure {\n  issues: DappPlanIssue[]\n  success: false\n}\n\nexport type DappPlanResult = DappPlanFailure | DappPlanSuccess\n\nfunction addUniqueIssue(\n  values: readonly string[],\n  path: PropertyKey[],\n  message: string,\n  context: z.core.$RefinementCtx<unknown>,\n): void {\n  const unique3 = new Set(values)\n  if (unique3.size !== values.length) {\n    context.addIssue({\n      code: 'custom', message, path,\n    })\n  }\n}\n\nfunction capabilityKey(capability: z.infer<typeof CapabilityRequirementZod>): string {\n  return `${capability.moniker}@${capability.version}`\n}\n\nfunction descriptorReferenceKey(descriptor: z.infer<typeof InstalledDescriptorReferenceZod>): string {\n  return `${descriptor.id}@${descriptor.version}`\n}\n\nfunction descriptorMetadataKey(descriptor: InstalledDescriptorMetadata): string {\n  return descriptorReferenceKey(descriptor.descriptor)\n}\n\nfunction sortedStrings(values: readonly string[]): string[] {\n  return [...values].toSorted()\n}\n\nfunction normalizeDescriptorMetadata(descriptor: InstalledDescriptorMetadata): InstalledDescriptorMetadata {\n  return InstalledDescriptorMetadataZod.parse(descriptor)\n}\n\nfunction planIssue(code: DappPlanIssueCode, message: string, path: (number | string)[]): DappPlanIssue {\n  return {\n    code, message, path,\n  }\n}\n\nfunction issuePath(path: PropertyKey[]): (number | string)[] {\n  return path.map(value => typeof value === 'symbol' ? value.description ?? value.toString() : value)\n}\n\nfunction materialStructuralIssues(issues: z.core.$ZodIssue[]): DappPlanIssue[] {\n  return issues.map(issue => planIssue('plan.material-invalid', issue.message, issuePath(issue.path)))\n}\n\nfunction profileIssues(material: DappPlanMaterial): DappPlanIssue[] {\n  const result = validateDappProfile(material.definition, material.configuration)\n  return result.success\n    ? []\n    : result.issues.map(issue => planIssue('plan.profile-invalid', `${issue.code}: ${issue.message}`, issue.path))\n}\n\nfunction descriptorIssues(material: DappPlanMaterial): DappPlanIssue[] {\n  const issues: DappPlanIssue[] = []\n  const roleDefinitions = new Map(material.definition.actors.map(actor => [actor.roleId, actor]))\n  const requiredKeys = new Set(material.configuration.actors.map((actor) => {\n    const role = roleDefinitions.get(actor.roleId)\n    return role === undefined ? undefined : descriptorReferenceKey(role.descriptor)\n  }).filter(key => key !== undefined))\n  const suppliedKeys = new Set(material.actorDescriptors.map(descriptorMetadataKey))\n\n  for (const key of [...requiredKeys].toSorted()) {\n    if (!suppliedKeys.has(key)) {\n      issues.push(planIssue(\n        'plan.actor-descriptor-missing',\n        `installed actor descriptor metadata is missing for ${key}`,\n        ['actorDescriptors'],\n      ))\n    }\n  }\n  for (const [index, descriptor] of material.actorDescriptors.entries()) {\n    const key = descriptorMetadataKey(descriptor)\n    if (!requiredKeys.has(key)) {\n      issues.push(planIssue(\n        'plan.actor-descriptor-unexpected',\n        `actor descriptor ${key} is not selected by any configured actor`,\n        ['actorDescriptors', index],\n      ))\n    }\n  }\n  return issues\n}\n\nfunction providerGraphIssues(providers: readonly ResolvedProviderNode[]): DappPlanIssue[] {\n  const issues: DappPlanIssue[] = []\n  const providersById = new Map(providers.map(provider => [provider.instanceId, provider]))\n  for (const [index, provider] of providers.entries()) {\n    for (const dependency of provider.dependencies) {\n      if (!providersById.has(dependency)) {\n        issues.push(planIssue(\n          'plan.provider-dependency-missing',\n          `provider dependency ${dependency} is not in the resolved graph`,\n          ['resolvedProviders', index, 'dependencies'],\n        ))\n      }\n    }\n  }\n  return issues\n}\n\nfunction visitProvider(\n  instanceId: string,\n  providersById: ReadonlyMap<string, ResolvedProviderNode>,\n  states: Map<string, 'done' | 'visiting'>,\n  ordered: ResolvedProviderNode[],\n): DappPlanIssue | undefined {\n  const state = states.get(instanceId)\n  if (state === 'done') return undefined\n  if (state === 'visiting') {\n    return planIssue(\n      'plan.provider-dependency-cycle',\n      `provider dependency cycle contains ${instanceId}`,\n      ['resolvedProviders'],\n    )\n  }\n  const provider = providersById.get(instanceId)\n  if (provider === undefined) return undefined\n  states.set(instanceId, 'visiting')\n  for (const dependency of sortedStrings(provider.dependencies)) {\n    const issue = visitProvider(dependency, providersById, states, ordered)\n    if (issue !== undefined) return issue\n  }\n  states.set(instanceId, 'done')\n  ordered.push({\n    ...provider,\n    descriptor: normalizeDescriptorMetadata(provider.descriptor),\n    providedCapabilities: [...provider.providedCapabilities]\n      .toSorted((left, right) => capabilityKey(left).localeCompare(capabilityKey(right))),\n    dependencies: sortedStrings(provider.dependencies),\n  })\n  return undefined\n}\n\nfunction normalizeProviderGraph(providers: readonly ResolvedProviderNode[]): DappPlanFailure | ResolvedProviderNode[] {\n  const graphIssues = providerGraphIssues(providers)\n  if (graphIssues.length > 0) return { success: false, issues: graphIssues }\n\n  const providersById = new Map(providers.map(provider => [provider.instanceId, provider]))\n  const states = new Map<string, 'done' | 'visiting'>()\n  const ordered: ResolvedProviderNode[] = []\n  for (const instanceId of sortedStrings(providersById.keys().toArray())) {\n    const issue = visitProvider(instanceId, providersById, states, ordered)\n    if (issue !== undefined) return { success: false, issues: [issue] }\n  }\n  return ordered\n}\n\nfunction capabilityIssues(material: DappPlanMaterial): DappPlanIssue[] {\n  const issues: DappPlanIssue[] = []\n  const roleDefinitions = new Map(material.definition.actors.map(actor => [actor.roleId, actor]))\n  const capabilityProviders = new Map<string, string[]>()\n  for (const provider of material.resolvedProviders) {\n    for (const capability of provider.providedCapabilities) {\n      const key = capabilityKey(capability)\n      capabilityProviders.set(key, [...capabilityProviders.get(key) ?? [], provider.instanceId])\n    }\n  }\n  for (const [key, providerIds] of capabilityProviders) {\n    if (providerIds.length > 1) {\n      issues.push(planIssue(\n        'plan.capability-ambiguous',\n        `capability ${key} is provided by multiple resolved providers: ${providerIds.toSorted().join(', ')}`,\n        ['resolvedProviders'],\n      ))\n    }\n  }\n  for (const [actorIndex, actor] of material.configuration.actors.entries()) {\n    const role = roleDefinitions.get(actor.roleId)\n    if (role === undefined) continue\n    for (const capability of role.requiredCapabilities) {\n      const key = capabilityKey(capability)\n      if (!capabilityProviders.has(key)) {\n        issues.push(planIssue(\n          'plan.capability-missing',\n          `actor ${actor.instanceId} requires unresolved capability ${key}`,\n          ['configuration', 'actors', actorIndex, 'roleId'],\n        ))\n      }\n    }\n  }\n  return issues\n}\n\nfunction portBindingIssues(material: DappPlanMaterial): DappPlanIssue[] {\n  const issues: DappPlanIssue[] = []\n  const ports = new Set(material.definition.ports.map(port => port.portId))\n  const bindings = new Set(material.portBindings.map(binding => binding.portId))\n  const hosts = new Set(material.configuration.actors.map(actor => actor.host))\n  for (const portId of [...ports].toSorted()) {\n    if (!bindings.has(portId)) {\n      issues.push(planIssue(\n        'plan.port-binding-missing',\n        `application port ${portId} has no host binding`,\n        ['portBindings'],\n      ))\n    }\n  }\n  for (const [index, binding] of material.portBindings.entries()) {\n    if (!ports.has(binding.portId)) {\n      issues.push(planIssue(\n        'plan.port-binding-unexpected',\n        `port binding ${binding.portId} is not declared by the definition`,\n        ['portBindings', index, 'portId'],\n      ))\n    }\n    if (!hosts.has(binding.host)) {\n      issues.push(planIssue(\n        'plan.port-binding-host-unknown',\n        `port binding host ${binding.host} has no configured actor partition`,\n        ['portBindings', index, 'host'],\n      ))\n    }\n  }\n  return issues\n}\n\nfunction createHostPartitions(\n  configuration: DappConfiguration,\n  portBindings: readonly DappPlanPortBinding[],\n): DappPlanHostPartition[] {\n  const actorOrder = configuration.supervision.policy === 'sequential'\n    ? new Map(configuration.supervision.actorOrder.map((instanceId, index) => [instanceId, index]))\n    : undefined\n  const hosts = new Map<string, DappPlanHostPartition>()\n  for (const actor of configuration.actors) {\n    const partition = hosts.get(actor.host) ?? {\n      host: actor.host, actorInstanceIds: [], portIds: [],\n    }\n    partition.actorInstanceIds.push(actor.instanceId)\n    hosts.set(actor.host, partition)\n  }\n  for (const binding of portBindings) {\n    const partition = hosts.get(binding.host)\n    if (partition !== undefined) partition.portIds.push(binding.portId)\n  }\n  return hosts.values()\n    .map(partition => ({\n      ...partition,\n      actorInstanceIds: [...partition.actorInstanceIds].toSorted((left, right) => {\n        return actorOrder === undefined ? left.localeCompare(right) : (actorOrder.get(left) ?? Number.MAX_SAFE_INTEGER) - (actorOrder.get(right) ?? Number.MAX_SAFE_INTEGER)\n      }),\n      portIds: sortedStrings(partition.portIds),\n    })).toArray()\n    .toSorted((left, right) => left.host.localeCompare(right.host))\n}\n\nexport function createDappPlan(value: unknown): DappPlanResult {\n  const materialResult = DappPlanMaterialZod.safeParse(value)\n  if (!materialResult.success) {\n    return { success: false, issues: materialStructuralIssues(materialResult.error.issues) }\n  }\n  const material = materialResult.data\n  const issues = [\n    ...applicationProviderPlanIssues(material),\n    ...applicationIdentityPlanIssues(material),\n    ...profileIssues(material),\n    ...descriptorIssues(material),\n    ...capabilityIssues(material),\n    ...portBindingIssues(material),\n  ]\n  if (issues.length > 0) return { success: false, issues }\n\n  const resolvedProviders = normalizeProviderGraph(material.resolvedProviders)\n  if (!Array.isArray(resolvedProviders)) return resolvedProviders\n\n  const definition = normalizeDappDefinition(material.definition)\n  const configuration = normalizeDappConfiguration(material.configuration)\n  const actorDescriptors = [...material.actorDescriptors]\n    .map(normalizeDescriptorMetadata)\n    .toSorted((left, right) => descriptorMetadataKey(left).localeCompare(descriptorMetadataKey(right)))\n  const portBindings = [...material.portBindings]\n    .toSorted((left, right) => left.portId.localeCompare(right.portId))\n  const definitionHash = hashDappDocument({\n    kind: 'definition', schema: DappDefinitionZod, schemaVersion: 1,\n  }, definition).hash\n  const configurationHash = hashDappDocument({\n    kind: 'configuration', schema: DappConfigurationZod, schemaVersion: 1,\n  }, configuration).hash\n  const preimage = DappPlanPreimageZod.parse({\n    schema: DappPlanSchema,\n    schemaVersion: 1,\n    definitionHash,\n    configurationHash,\n    definition,\n    configuration,\n    actorDescriptors,\n    resolvedProviders,\n    portBindings,\n    hostPartitions: createHostPartitions(configuration, portBindings),\n  })\n  const planId = hashDappDocument({\n    kind: 'plan', schema: DappPlanPreimageZod, schemaVersion: 1,\n  }, preimage).hash\n  return {\n    success: true,\n    preimage,\n    value: DappPlanZod.parse({ ...preimage, planId }),\n  }\n}\n", "import type { ApplicationProviderSelection } from './applicationProvider.ts'\nimport { canonicalizeIJson } from './canonicalDocument.ts'\nimport type {\n  DappPlanIssue, DappPlanMaterial, ResolvedProviderNode,\n} from './plan.ts'\n\ninterface ApplicationPlanContext {\n  issues: DappPlanIssue[]\n  material: DappPlanMaterial\n  nodes: Map<string, ResolvedProviderNode>\n  selections: Map<string, ApplicationProviderSelection>\n}\n\nfunction reject(context: ApplicationPlanContext, message: string, selection: ApplicationProviderSelection): void {\n  context.issues.push({\n    code: 'plan.application-provider-invalid',\n    message,\n    path: ['configuration', 'applicationProviders', context.material.configuration.applicationProviders?.indexOf(selection) ?? 0],\n  })\n}\n\nfunction validateNode(context: ApplicationPlanContext, selection: ApplicationProviderSelection): void {\n  const { material, nodes } = context\n  const node = nodes.get(selection.instanceId)\n  const binding = material.configuration.providerBindings[selection.instanceId]\n  const selectedConfig = canonicalizeIJson(selection.config)\n  if (node?.descriptor.descriptor.id !== selection.descriptor.id\n    || node.descriptor.descriptor.version !== selection.descriptor.version\n    || canonicalizeIJson(node.config) !== selectedConfig\n    || binding?.descriptorId !== selection.descriptor.id\n    || canonicalizeIJson(binding.config) !== selectedConfig\n    || material.configuration.actors.every(actor => actor.host !== selection.host)\n    || node.providedCapabilities.length === 0) {\n    reject(context, 'application Provider selection, node, config and host must agree', selection)\n    return\n  }\n  const expected = [...new Set(Object.values(selection.dependencies).map(dependency => dependency.kind === 'resource'\n    ? dependency.resourceId\n    : dependency.instanceId))].toSorted()\n  const actual = [...node.dependencies].toSorted()\n  if (expected.length !== actual.length || expected.some((id, position) => id !== actual[position])) {\n    reject(context, 'application Provider node dependencies differ from its selection', selection)\n  }\n}\n\nfunction validateBindings(context: ApplicationPlanContext, selection: ApplicationProviderSelection): void {\n  for (const [moniker, dependency] of Object.entries(selection.dependencies)) {\n    const id = dependency.kind === 'resource' ? dependency.resourceId : dependency.instanceId\n    const selected = context.selections.get(id)\n    if (id === selection.instanceId\n      || (dependency.kind === 'resource' ? selected !== undefined : selected?.host !== selection.host)\n      || !context.nodes.get(id)?.providedCapabilities.some(capability => capability.moniker === moniker)) {\n      reject(context, 'application Provider dependency binding is missing, mismatched or crosses hosts', selection)\n    }\n  }\n}\n\nfunction actorClosure(context: ApplicationPlanContext): Set<string> {\n  const roles = new Map(context.material.definition.actors.map(role => [role.roleId, role]))\n  const reached = new Set<string>()\n  for (const actor of context.material.configuration.actors) {\n    const visited = new Set<string>()\n    const visit = (id: string): void => {\n      if (visited.has(id)) return\n      visited.add(id)\n      const selection = context.selections.get(id)\n      if (selection !== undefined) {\n        reached.add(id)\n        if (selection.host !== actor.host) reject(context, 'Actor reaches an application Provider owned by another host', selection)\n      }\n      for (const dependency of context.nodes.get(id)?.dependencies ?? []) visit(dependency)\n    }\n    for (const capability of roles.get(actor.roleId)?.requiredCapabilities ?? []) {\n      for (const node of context.material.resolvedProviders) {\n        if (node.providedCapabilities.some(value => value.moniker === capability.moniker && value.version === capability.version)) visit(node.instanceId)\n      }\n    }\n  }\n  return reached\n}\n\n/** Semantic checks also run when a persisted plan is verified without its source. */\nexport function applicationProviderPlanIssues(material: DappPlanMaterial): DappPlanIssue[] {\n  const selections = material.configuration.applicationProviders ?? []\n  if (selections.length === 0) return []\n  const context: ApplicationPlanContext = {\n    issues: [],\n    material,\n    nodes: new Map(material.resolvedProviders.map(provider => [provider.instanceId, provider])),\n    selections: new Map(selections.map(selection => [selection.instanceId, selection])),\n  }\n  if (context.selections.size !== selections.length) reject(context, 'application Provider IDs must be unique', selections[0])\n  for (const selection of selections) {\n    validateNode(context, selection)\n    validateBindings(context, selection)\n  }\n  const reached = actorClosure(context)\n  for (const selection of selections) {\n    if (!reached.has(selection.instanceId)) reject(context, 'selected application Provider is outside Actor dependency closure', selection)\n  }\n  return context.issues\n}\n", "import { asSchema } from '@xyo-network/sdk'\nimport { z } from 'zod'\n\nimport { ApplicationProviderSelectionZod } from './applicationProvider.ts'\nimport {\n  DappIdZod, IdentifierZod, SemanticVersionZod, Xl1ChainIdZod,\n} from './identifier.ts'\nimport { IdentityBindingZod, validateIdentityBindings } from './identity.ts'\nimport { JsonObjectZod } from './jsonValue.ts'\nimport {\n  AuxiliaryStorageClassZod,\n  ContentProtectionZod,\n  DatalakeReadAccessZod,\n  DatalakeUnavailableBehaviorZod,\n  DurableProjectionProfileZod,\n  ExecutionModeZod,\n  ExternalSourceKindZod,\n  SideChannelTransportZod,\n  StorageDurabilityZod,\n} from './profile.ts'\nexport const DappConfigurationSchema = asSchema('network.xyo.dapp.configuration', true)\n\nexport const DappActorConfigurationZod = z.strictObject({\n  instanceId: IdentifierZod,\n  roleId: IdentifierZod,\n  host: IdentifierZod,\n  executionMode: ExecutionModeZod,\n  config: JsonObjectZod,\n})\n\nexport type DappActorConfiguration = z.infer<typeof DappActorConfigurationZod>\n\nexport const DappSupervisionConfigurationZod = z.discriminatedUnion('policy', [\n  z.strictObject({\n    policy: z.literal('sequential'),\n    actorOrder: z.array(IdentifierZod),\n  }),\n  z.strictObject({ policy: z.literal('parallel') }),\n])\n\nexport type DappSupervisionConfiguration = z.infer<typeof DappSupervisionConfigurationZod>\n\nexport const ProviderBindingZod = z.strictObject({\n  descriptorId: IdentifierZod,\n  config: JsonObjectZod,\n})\n\nexport type ProviderBinding = z.infer<typeof ProviderBindingZod>\n\nconst SideChannelPolicyFields = {\n  channelCapabilityId: IdentifierZod,\n  detachedSigningCapabilityId: IdentifierZod,\n  transport: SideChannelTransportZod,\n  maximumMessageBytes: z.number().int().positive(),\n  replayRetentionSeconds: z.number().int().positive(),\n  acceptedClockSkewMilliseconds: z.number().int().nonnegative(),\n}\n\nexport const SideChannelPolicyZod = z.discriminatedUnion('profile', [\n  z.strictObject({ profile: z.literal('none') }),\n  z.strictObject({\n    profile: z.literal('optional-optimization'),\n    ...SideChannelPolicyFields,\n    unavailableBehavior: z.literal('continue-without-channel'),\n  }),\n  z.strictObject({\n    profile: z.literal('required-for-liveness'),\n    ...SideChannelPolicyFields,\n    unavailableBehavior: z.enum(['pending', 'expire', 'fail-operation']),\n  }),\n])\n\nexport type SideChannelPolicy = z.infer<typeof SideChannelPolicyZod>\n\nexport const ExternalSourceBindingZod = z.strictObject({\n  sourceId: IdentifierZod,\n  sourceKind: ExternalSourceKindZod,\n  observerCapabilityId: IdentifierZod,\n  config: JsonObjectZod,\n})\n\nexport type ExternalSourceBinding = z.infer<typeof ExternalSourceBindingZod>\n\nexport const ExternalInteractionPolicyZod = z.discriminatedUnion('mode', [\n  z.strictObject({ mode: z.literal('none') }),\n  z.strictObject({\n    mode: z.literal('observe'),\n    sources: z.array(ExternalSourceBindingZod).min(1),\n  }),\n  z.strictObject({\n    mode: z.literal('attest-import'),\n    sources: z.array(ExternalSourceBindingZod).min(1),\n    commitBeforeReduction: z.literal(true),\n  }),\n])\n\nexport type ExternalInteractionPolicy = z.infer<typeof ExternalInteractionPolicyZod>\n\nexport const DatalakePolicyZod = z.discriminatedUnion('mode', [\n  z.strictObject({ mode: z.literal('none') }),\n  z.strictObject({\n    mode: z.literal('optional'),\n    readAccess: DatalakeReadAccessZod,\n    contentProtection: ContentProtectionZod,\n    writeBeforeBroadcast: z.boolean(),\n    requiredCopies: z.number().int().nonnegative(),\n    retentionSeconds: z.number().int().nonnegative(),\n    unavailableBehavior: DatalakeUnavailableBehaviorZod,\n  }),\n  z.strictObject({\n    mode: z.literal('required'),\n    readAccess: DatalakeReadAccessZod,\n    contentProtection: ContentProtectionZod,\n    writeBeforeBroadcast: z.literal(true),\n    requiredCopies: z.number().int().positive(),\n    retentionSeconds: z.number().int().nonnegative(),\n    unavailableBehavior: DatalakeUnavailableBehaviorZod,\n  }),\n])\n\nexport type DatalakePolicy = z.infer<typeof DatalakePolicyZod>\n\nexport const AuxiliaryStoreBindingZod = z.strictObject({\n  class: AuxiliaryStorageClassZod,\n  capabilityId: IdentifierZod,\n  durability: StorageDurabilityZod,\n})\n\nexport type AuxiliaryStoreBinding = z.infer<typeof AuxiliaryStoreBindingZod>\n\nexport const ProjectionFloorZod = z.discriminatedUnion('mode', [\n  z.strictObject({ mode: z.literal('bounded'), block: z.number().int().positive() }),\n  z.strictObject({ mode: z.literal('genesis'), block: z.literal(0) }),\n])\n\nexport type ProjectionFloor = z.infer<typeof ProjectionFloorZod>\n\nconst ProjectionPolicyFields = {\n  projectionCapabilityId: IdentifierZod,\n  floor: ProjectionFloorZod,\n  maximumLagBlocks: z.number().int().nonnegative(),\n  progressWatermark: z.boolean(),\n}\n\nexport const ProjectionPolicyZod = z.discriminatedUnion('profile', [\n  z.strictObject({ profile: z.literal('none') }),\n  z.strictObject({\n    profile: z.literal('ephemeral'),\n    ...ProjectionPolicyFields,\n  }),\n  z.strictObject({\n    profile: DurableProjectionProfileZod,\n    ...ProjectionPolicyFields,\n    checkpointCapabilityId: IdentifierZod,\n  }),\n])\n\nexport type ProjectionPolicy = z.infer<typeof ProjectionPolicyZod>\n\nexport const DappConfigurationZod = z.strictObject({\n  applicationProviders: z.array(ApplicationProviderSelectionZod).optional(),\n  schema: z.literal(DappConfigurationSchema),\n  schemaVersion: z.literal(1),\n  dappId: DappIdZod,\n  definitionVersion: SemanticVersionZod,\n  network: z.strictObject({\n    networkId: IdentifierZod,\n    expectedChainId: Xl1ChainIdZod,\n  }),\n  actors: z.array(DappActorConfigurationZod),\n  supervision: DappSupervisionConfigurationZod,\n  providerBindings: z.record(IdentifierZod, ProviderBindingZod),\n  identityBindings: z.array(IdentityBindingZod),\n  sideChannelPolicy: SideChannelPolicyZod,\n  externalInteractionPolicy: ExternalInteractionPolicyZod,\n  datalakePolicy: DatalakePolicyZod,\n  auxiliaryStores: z.array(AuxiliaryStoreBindingZod),\n  projectionPolicy: ProjectionPolicyZod,\n  consistency: z.strictObject({\n    read: z.literal('finalized'),\n    readinessMaxLag: z.number().int().nonnegative(),\n  }),\n}).superRefine((configuration, context) => {\n  const instanceIds = configuration.actors.map(actor => actor.instanceId)\n  const unique = new Set(instanceIds)\n  if (unique.size !== instanceIds.length) {\n    context.addIssue({\n      code: 'custom', message: 'actor instance IDs must be unique', path: ['actors'],\n    })\n  }\n\n  const identityResult = validateIdentityBindings(\n    configuration.identityBindings,\n    { expectedChainId: configuration.network.expectedChainId },\n  )\n  if (!identityResult.success) {\n    for (const issue of identityResult.issues) {\n      context.addIssue({\n        code: 'custom',\n        message: `${issue.code}: ${issue.message}`,\n        path: ['identityBindings', ...issue.path],\n      })\n    }\n  }\n\n  if (configuration.externalInteractionPolicy.mode !== 'none') {\n    const sourceIds = configuration.externalInteractionPolicy.sources.map(source => source.sourceId)\n    const unique2 = new Set(sourceIds)\n    if (unique2.size !== sourceIds.length) {\n      context.addIssue({\n        code: 'custom', message: 'external source IDs must be unique', path: ['externalInteractionPolicy', 'sources'],\n      })\n    }\n  }\n\n  const auxiliaryStoreClasses = configuration.auxiliaryStores.map(store => store.class)\n  const unique3 = new Set(auxiliaryStoreClasses)\n  if (unique3.size !== auxiliaryStoreClasses.length) {\n    context.addIssue({\n      code: 'custom', message: 'auxiliary storage classes may be bound once', path: ['auxiliaryStores'],\n    })\n  }\n\n  if (configuration.supervision.policy !== 'sequential') return\n  const actorOrder = configuration.supervision.actorOrder\n  const orderSet = new Set(actorOrder)\n  const instanceSet = new Set(instanceIds)\n  const isExactOrder = actorOrder.length === instanceIds.length\n    && orderSet.size === actorOrder.length\n    && actorOrder.every(instanceId => instanceSet.has(instanceId))\n\n  if (!isExactOrder) {\n    context.addIssue({\n      code: 'custom',\n      message: 'sequential actor order must contain every actor instance exactly once',\n      path: ['supervision', 'actorOrder'],\n    })\n  }\n})\n\nexport type DappConfiguration = z.infer<typeof DappConfigurationZod>\n", "import { normalizeApplicationProviderSelections } from './applicationProvider.ts'\nimport type { DappConfiguration } from './dappConfiguration.ts'\nimport { DappConfigurationZod } from './dappConfiguration.ts'\nimport type {\n  DappActorDefinition,\n  DappDefinition,\n  DappPortDefinition,\n} from './dappDefinition.ts'\nimport { DappDefinitionZod } from './dappDefinition.ts'\n\ninterface SchemaReference {\n  schema: string\n  version: number\n}\n\nfunction capabilityKey(capability: { moniker: string; version: number }): string {\n  return `${capability.moniker}@${capability.version}`\n}\n\nfunction schemaReferenceKey(schema: SchemaReference): string {\n  return `${schema.schema}@${schema.version}`\n}\n\nfunction sortedStrings(values: readonly string[]): string[] {\n  return [...values].toSorted()\n}\n\nfunction normalizeActorDefinition(actor: DappActorDefinition): DappActorDefinition {\n  return {\n    ...actor,\n    supportedExecutionModes: [...actor.supportedExecutionModes].toSorted(),\n    requiredCapabilities: [...actor.requiredCapabilities]\n      .toSorted((left, right) => capabilityKey(left).localeCompare(capabilityKey(right))),\n  }\n}\n\nfunction normalizePortDefinition(port: DappPortDefinition): DappPortDefinition {\n  return {\n    ...port,\n    commands: sortedStrings(port.commands),\n    queries: sortedStrings(port.queries),\n    subscriptions: sortedStrings(port.subscriptions),\n  }\n}\n\nexport function normalizeDappDefinition(value: unknown): DappDefinition {\n  const definition = DappDefinitionZod.parse(value)\n  const coordination = definition.coordination.profile === 'none'\n    ? definition.coordination\n    : {\n        ...definition.coordination,\n        messageKinds: [...definition.coordination.messageKinds].toSorted(),\n        authorizedSenderRoles: sortedStrings(definition.coordination.authorizedSenderRoles),\n      }\n  const externalInteraction = definition.externalInteraction.mode === 'none'\n    || definition.externalInteraction.mode === 'actuate-export'\n    ? definition.externalInteraction\n    : definition.externalInteraction.mode === 'observe'\n      ? {\n          ...definition.externalInteraction,\n          allowedSourceKinds: [...definition.externalInteraction.allowedSourceKinds].toSorted(),\n        }\n      : {\n          ...definition.externalInteraction,\n          allowedSourceKinds: [...definition.externalInteraction.allowedSourceKinds].toSorted(),\n          observationSchemas: [...definition.externalInteraction.observationSchemas]\n            .toSorted((left, right) => schemaReferenceKey(left).localeCompare(schemaReferenceKey(right))),\n        }\n  const datalake = definition.durability.datalake.mode === 'none'\n    ? definition.durability.datalake\n    : {\n        ...definition.durability.datalake,\n        allowedReadAccess: [...definition.durability.datalake.allowedReadAccess].toSorted(),\n        allowedContentProtection: [...definition.durability.datalake.allowedContentProtection].toSorted(),\n      }\n  const projection = definition.durability.projection.profile === 'none'\n    ? definition.durability.projection\n    : {\n        ...definition.durability.projection,\n        inputSchemas: [...definition.durability.projection.inputSchemas]\n          .toSorted((left, right) => schemaReferenceKey(left).localeCompare(schemaReferenceKey(right))),\n      }\n\n  return DappDefinitionZod.parse({\n    ...definition,\n    substrate: {\n      ...definition.substrate,\n      relationships: [...definition.substrate.relationships].toSorted(),\n    },\n    schemas: [...definition.schemas]\n      .toSorted((left, right) => schemaReferenceKey(left).localeCompare(schemaReferenceKey(right))),\n    actors: [...definition.actors]\n      .map(normalizeActorDefinition)\n      .toSorted((left, right) => left.roleId.localeCompare(right.roleId)),\n    ports: [...definition.ports]\n      .map(normalizePortDefinition)\n      .toSorted((left, right) => left.portId.localeCompare(right.portId)),\n    identityRoles: sortedStrings(definition.identityRoles),\n    coordination,\n    externalInteraction,\n    durability: {\n      ...definition.durability,\n      datalake,\n      projection,\n      auxiliaryStores: [...definition.durability.auxiliaryStores]\n        .toSorted((left, right) => left.class.localeCompare(right.class)),\n    },\n    compatibility: {\n      ...definition.compatibility,\n      acceptedPriorProtocolVersions: sortedStrings(definition.compatibility.acceptedPriorProtocolVersions),\n    },\n  })\n}\n\nexport function normalizeDappConfiguration(value: unknown): DappConfiguration {\n  const configuration = DappConfigurationZod.parse(value)\n  const externalInteractionPolicy = configuration.externalInteractionPolicy.mode === 'none'\n    ? configuration.externalInteractionPolicy\n    : {\n        ...configuration.externalInteractionPolicy,\n        sources: [...configuration.externalInteractionPolicy.sources]\n          .toSorted((left, right) => left.sourceId.localeCompare(right.sourceId)),\n      }\n  const { applicationProviders, ...legacy } = configuration\n  return DappConfigurationZod.parse({\n    ...legacy,\n    ...(applicationProviders?.length ? { applicationProviders: normalizeApplicationProviderSelections(applicationProviders) } : {}),\n    actors: [...configuration.actors].toSorted((left, right) => left.instanceId.localeCompare(right.instanceId)),\n    identityBindings: [...configuration.identityBindings]\n      .toSorted((left, right) => left.roleId.localeCompare(right.roleId)),\n    externalInteractionPolicy,\n    auxiliaryStores: [...configuration.auxiliaryStores]\n      .toSorted((left, right) => left.class.localeCompare(right.class)),\n  })\n}\n", "import { z } from 'zod'\n\nimport type { DappConfiguration } from './dappConfiguration.ts'\nimport { DappConfigurationZod } from './dappConfiguration.ts'\nimport type { DappDefinition } from './dappDefinition.ts'\nimport { DappDefinitionZod } from './dappDefinition.ts'\n\nexport const DappModelIssueCodes = [\n  'configuration.invalid',\n  'definition.invalid',\n  'profile.actor-role-unknown',\n  'profile.auxiliary-store-durability-insufficient',\n  'profile.auxiliary-store-missing',\n  'profile.auxiliary-store-undeclared',\n  'profile.content-policy-mismatch',\n  'profile.coordination-clock-skew-excessive',\n  'profile.coordination-message-limit-excessive',\n  'profile.coordination-profile-mismatch',\n  'profile.coordination-replay-retention-insufficient',\n  'profile.datalake-access-unsupported',\n  'profile.datalake-protection-unsupported',\n  'profile.datalake-replication-insufficient',\n  'profile.datalake-retention-insufficient',\n  'profile.datalake-unavailability-mismatch',\n  'profile.dapp-id-mismatch',\n  'profile.definition-version-mismatch',\n  'profile.execution-mode-unsupported',\n  'profile.external-interaction-mode-mismatch',\n  'profile.external-source-kind-unsupported',\n  'profile.identity-role-unknown',\n  'profile.projection-capability-mismatch',\n  'profile.projection-floor-mismatch',\n  'profile.projection-profile-mismatch',\n  'profile.projection-progress-mismatch',\n] as const\n\nexport const DappModelIssueCodeZod = z.enum(DappModelIssueCodes)\n\nexport type DappModelIssueCode = z.infer<typeof DappModelIssueCodeZod>\n\nexport interface DappModelIssue {\n  code: DappModelIssueCode\n  message: string\n  path: (number | string)[]\n}\n\nexport interface DappProfile {\n  configuration: DappConfiguration\n  definition: DappDefinition\n}\n\nexport interface DappModelValidationSuccess<T> {\n  success: true\n  value: T\n}\n\nexport interface DappModelValidationFailure {\n  issues: DappModelIssue[]\n  success: false\n}\n\nexport type DappModelValidationResult<T> = DappModelValidationFailure | DappModelValidationSuccess<T>\n\nconst issuePath = (path: PropertyKey[]): (number | string)[] => path.map(value => typeof value === 'symbol' ? value.description ?? value.toString() : value)\n\nconst structuralIssues = (code: 'configuration.invalid' | 'definition.invalid', issues: z.core.$ZodIssue[]): DappModelIssue[] => issues.map(issue => ({\n  code,\n  message: issue.message,\n  path: issuePath(issue.path),\n}))\n\nexport function validateDappDefinition(value: unknown): DappModelValidationResult<DappDefinition> {\n  const result = DappDefinitionZod.safeParse(value)\n  return result.success\n    ? { success: true, value: result.data }\n    : { issues: structuralIssues('definition.invalid', result.error.issues), success: false }\n}\n\nexport function validateDappConfiguration(value: unknown): DappModelValidationResult<DappConfiguration> {\n  const result = DappConfigurationZod.safeParse(value)\n  return result.success\n    ? { success: true, value: result.data }\n    : { issues: structuralIssues('configuration.invalid', result.error.issues), success: false }\n}\n\nfunction documentIdentityIssues(definition: DappDefinition, configuration: DappConfiguration): DappModelIssue[] {\n  const issues: DappModelIssue[] = []\n  if (configuration.dappId !== definition.dappId) {\n    issues.push({\n      code: 'profile.dapp-id-mismatch',\n      message: 'configuration dApp ID does not match definition',\n      path: ['configuration', 'dappId'],\n    })\n  }\n\n  if (configuration.definitionVersion !== definition.definitionVersion) {\n    issues.push({\n      code: 'profile.definition-version-mismatch',\n      message: 'configuration definition version does not match definition',\n      path: ['configuration', 'definitionVersion'],\n    })\n  }\n  return issues\n}\n\nfunction actorProfileIssues(definition: DappDefinition, configuration: DappConfiguration): DappModelIssue[] {\n  const issues: DappModelIssue[] = []\n  const actorDefinitions = new Map(definition.actors.map(actor => [actor.roleId, actor]))\n  for (const [index, actor] of configuration.actors.entries()) {\n    const actorDefinition = actorDefinitions.get(actor.roleId)\n    if (!actorDefinition) {\n      issues.push({\n        code: 'profile.actor-role-unknown',\n        message: 'configured actor role is not declared by the definition',\n        path: ['configuration', 'actors', index, 'roleId'],\n      })\n    } else if (!actorDefinition.supportedExecutionModes.includes(actor.executionMode)) {\n      issues.push({\n        code: 'profile.execution-mode-unsupported',\n        message: 'configured execution mode is not supported by the actor descriptor',\n        path: ['configuration', 'actors', index, 'executionMode'],\n      })\n    }\n  }\n  return issues\n}\n\nfunction identityProfileIssues(definition: DappDefinition, configuration: DappConfiguration): DappModelIssue[] {\n  const issues: DappModelIssue[] = []\n  const identityRoles = new Set(definition.identityRoles)\n  for (const [index, binding] of configuration.identityBindings.entries()) {\n    if (!identityRoles.has(binding.roleId)) {\n      issues.push({\n        code: 'profile.identity-role-unknown',\n        message: 'configured identity role is not declared by the definition',\n        path: ['configuration', 'identityBindings', index, 'roleId'],\n      })\n    }\n  }\n  return issues\n}\n\nfunction coordinationProfileIssues(definition: DappDefinition, configuration: DappConfiguration): DappModelIssue[] {\n  const issues: DappModelIssue[] = []\n  const requirement = definition.coordination\n  const policy = configuration.sideChannelPolicy\n  if (requirement.profile === 'none' || policy.profile === 'none') {\n    return requirement.profile === policy.profile\n      ? issues\n      : [{\n          code: 'profile.coordination-profile-mismatch',\n          message: 'configured side-channel presence does not match the definition',\n          path: ['configuration', 'sideChannelPolicy', 'profile'],\n        }]\n  }\n\n  if (requirement.profile !== policy.profile) {\n    issues.push({\n      code: 'profile.coordination-profile-mismatch',\n      message: 'configured side-channel criticality does not match the definition',\n      path: ['configuration', 'sideChannelPolicy', 'profile'],\n    })\n  }\n  if (policy.maximumMessageBytes > requirement.maximumMessageBytes) {\n    issues.push({\n      code: 'profile.coordination-message-limit-excessive',\n      message: 'configured side-channel message limit exceeds the definition maximum',\n      path: ['configuration', 'sideChannelPolicy', 'maximumMessageBytes'],\n    })\n  }\n  if (policy.replayRetentionSeconds < requirement.minimumReplayRetentionSeconds) {\n    issues.push({\n      code: 'profile.coordination-replay-retention-insufficient',\n      message: 'configured side-channel replay retention is below the definition minimum',\n      path: ['configuration', 'sideChannelPolicy', 'replayRetentionSeconds'],\n    })\n  }\n  if (policy.acceptedClockSkewMilliseconds > requirement.maximumClockSkewMilliseconds) {\n    issues.push({\n      code: 'profile.coordination-clock-skew-excessive',\n      message: 'configured side-channel clock skew exceeds the definition maximum',\n      path: ['configuration', 'sideChannelPolicy', 'acceptedClockSkewMilliseconds'],\n    })\n  }\n  return issues\n}\n\nfunction externalInteractionProfileIssues(definition: DappDefinition, configuration: DappConfiguration): DappModelIssue[] {\n  const issues: DappModelIssue[] = []\n  const requirement = definition.externalInteraction\n  const policy = configuration.externalInteractionPolicy\n  if (requirement.mode !== policy.mode) {\n    return [{\n      code: 'profile.external-interaction-mode-mismatch',\n      message: 'configured external interaction mode does not match the definition',\n      path: ['configuration', 'externalInteractionPolicy', 'mode'],\n    }]\n  }\n  if (requirement.mode === 'none' || policy.mode === 'none') return issues\n\n  for (const [index, source] of policy.sources.entries()) {\n    if (!requirement.allowedSourceKinds.includes(source.sourceKind)) {\n      issues.push({\n        code: 'profile.external-source-kind-unsupported',\n        message: 'configured external source kind is not allowed by the definition',\n        path: ['configuration', 'externalInteractionPolicy', 'sources', index, 'sourceKind'],\n      })\n    }\n  }\n  return issues\n}\n\nfunction isContentModeCompatible(definition: DappDefinition, configuration: DappConfiguration): boolean {\n  const datalakeMode = configuration.datalakePolicy.mode\n  const contentMode = definition.durability.contentMode\n  return contentMode === 'chain-only'\n    ? datalakeMode === 'none'\n    : contentMode === 'commitment-only'\n      ? datalakeMode !== 'required'\n      : datalakeMode === 'required'\n}\n\nfunction isDefinitionDatalakeModeCompatible(definition: DappDefinition, configuration: DappConfiguration): boolean {\n  const datalakeMode = configuration.datalakePolicy.mode\n  const definitionDatalakeMode = definition.durability.datalake.mode\n  return definitionDatalakeMode === 'none'\n    ? datalakeMode === 'none'\n    : definitionDatalakeMode === 'optional'\n      ? datalakeMode !== 'required'\n      : datalakeMode === 'required'\n}\n\nfunction contentProfileIssues(definition: DappDefinition, configuration: DappConfiguration): DappModelIssue[] {\n  return isContentModeCompatible(definition, configuration) && isDefinitionDatalakeModeCompatible(definition, configuration)\n    ? []\n    : [{\n        code: 'profile.content-policy-mismatch',\n        message: 'canonical content mode and datalake policy are incompatible',\n        path: ['configuration', 'datalakePolicy', 'mode'],\n      }]\n}\n\nfunction datalakeProfileIssues(definition: DappDefinition, configuration: DappConfiguration): DappModelIssue[] {\n  const issues: DappModelIssue[] = []\n  const datalakeRequirement = definition.durability.datalake\n  const datalakePolicy = configuration.datalakePolicy\n  if (datalakeRequirement.mode === 'none' || datalakePolicy.mode === 'none') return issues\n\n  if (!datalakeRequirement.allowedReadAccess.includes(datalakePolicy.readAccess)) {\n    issues.push({\n      code: 'profile.datalake-access-unsupported',\n      message: 'configured datalake read access is not allowed by the definition',\n      path: ['configuration', 'datalakePolicy', 'readAccess'],\n    })\n  }\n  if (!datalakeRequirement.allowedContentProtection.includes(datalakePolicy.contentProtection)) {\n    issues.push({\n      code: 'profile.datalake-protection-unsupported',\n      message: 'configured datalake content protection is not allowed by the definition',\n      path: ['configuration', 'datalakePolicy', 'contentProtection'],\n    })\n  }\n  if (datalakePolicy.requiredCopies < datalakeRequirement.minimumCopies) {\n    issues.push({\n      code: 'profile.datalake-replication-insufficient',\n      message: 'configured datalake copies are below the definition minimum',\n      path: ['configuration', 'datalakePolicy', 'requiredCopies'],\n    })\n  }\n  if (datalakePolicy.retentionSeconds < datalakeRequirement.minimumRetentionSeconds) {\n    issues.push({\n      code: 'profile.datalake-retention-insufficient',\n      message: 'configured datalake retention is below the definition minimum',\n      path: ['configuration', 'datalakePolicy', 'retentionSeconds'],\n    })\n  }\n  if (datalakePolicy.unavailableBehavior !== datalakeRequirement.unavailableBehavior) {\n    issues.push({\n      code: 'profile.datalake-unavailability-mismatch',\n      message: 'configured missing-body behavior does not match the definition',\n      path: ['configuration', 'datalakePolicy', 'unavailableBehavior'],\n    })\n  }\n  return issues\n}\n\nfunction auxiliaryStoreProfileIssues(definition: DappDefinition, configuration: DappConfiguration): DappModelIssue[] {\n  const issues: DappModelIssue[] = []\n  const auxiliaryRequirements = new Map(definition.durability.auxiliaryStores.map(store => [store.class, store]))\n  const auxiliaryBindings = new Map(configuration.auxiliaryStores.map(store => [store.class, store]))\n  for (const [index, binding] of configuration.auxiliaryStores.entries()) {\n    const requirement = auxiliaryRequirements.get(binding.class)\n    if (!requirement) {\n      issues.push({\n        code: 'profile.auxiliary-store-undeclared',\n        message: 'configured auxiliary storage class is not declared by the definition',\n        path: ['configuration', 'auxiliaryStores', index, 'class'],\n      })\n    } else if (requirement.minimumDurability === 'crash-durable' && binding.durability !== 'crash-durable') {\n      issues.push({\n        code: 'profile.auxiliary-store-durability-insufficient',\n        message: 'configured auxiliary store does not meet the minimum durability',\n        path: ['configuration', 'auxiliaryStores', index, 'durability'],\n      })\n    }\n  }\n  for (const [index, requirement] of definition.durability.auxiliaryStores.entries()) {\n    if (requirement.requirement === 'required' && !auxiliaryBindings.has(requirement.class)) {\n      issues.push({\n        code: 'profile.auxiliary-store-missing',\n        message: 'required auxiliary storage class is not configured',\n        path: ['configuration', 'auxiliaryStores', index],\n      })\n    }\n  }\n  return issues\n}\n\nfunction projectionProfileIssues(definition: DappDefinition, configuration: DappConfiguration): DappModelIssue[] {\n  const issues: DappModelIssue[] = []\n  const requirement = definition.durability.projection\n  const policy = configuration.projectionPolicy\n  if (requirement.profile === 'none' || policy.profile === 'none') {\n    return requirement.profile === policy.profile\n      ? issues\n      : [{\n          code: 'profile.projection-profile-mismatch',\n          message: 'configured projection presence does not match the definition',\n          path: ['configuration', 'projectionPolicy', 'profile'],\n        }]\n  }\n\n  if (requirement.profile !== policy.profile) {\n    issues.push({\n      code: 'profile.projection-profile-mismatch',\n      message: 'configured projection profile does not match the definition',\n      path: ['configuration', 'projectionPolicy', 'profile'],\n    })\n  }\n  const expectedFloorMode = requirement.temporality === 'bounded' ? 'bounded' : 'genesis'\n  if (policy.floor.mode !== expectedFloorMode) {\n    issues.push({\n      code: 'profile.projection-floor-mismatch',\n      message: 'configured projection floor does not match definition temporality',\n      path: ['configuration', 'projectionPolicy', 'floor'],\n    })\n  }\n  if (policy.progressWatermark !== requirement.progressWatermark) {\n    issues.push({\n      code: 'profile.projection-progress-mismatch',\n      message: 'configured projection progress policy does not match the definition',\n      path: ['configuration', 'projectionPolicy', 'progressWatermark'],\n    })\n  }\n\n  const stores = new Map(configuration.auxiliaryStores.map(store => [store.class, store.capabilityId]))\n  if (stores.get('projection') !== policy.projectionCapabilityId) {\n    issues.push({\n      code: 'profile.projection-capability-mismatch',\n      message: 'projection policy must reference the configured projection store capability',\n      path: ['configuration', 'projectionPolicy', 'projectionCapabilityId'],\n    })\n  }\n  if (policy.profile !== 'ephemeral' && stores.get('replay-checkpoint') !== policy.checkpointCapabilityId) {\n    issues.push({\n      code: 'profile.projection-capability-mismatch',\n      message: 'projection policy must reference the configured replay checkpoint capability',\n      path: ['configuration', 'projectionPolicy', 'checkpointCapabilityId'],\n    })\n  }\n  return issues\n}\n\nexport function validateDappProfile(definitionValue: unknown, configurationValue: unknown): DappModelValidationResult<DappProfile> {\n  const definitionResult = validateDappDefinition(definitionValue)\n  const configurationResult = validateDappConfiguration(configurationValue)\n  const structuralProfileIssues = [\n    ...(definitionResult.success ? [] : definitionResult.issues),\n    ...(configurationResult.success ? [] : configurationResult.issues),\n  ]\n  if (!definitionResult.success || !configurationResult.success) return { issues: structuralProfileIssues, success: false }\n\n  const { value: definition } = definitionResult\n  const { value: configuration } = configurationResult\n  const issues = [\n    ...documentIdentityIssues(definition, configuration),\n    ...actorProfileIssues(definition, configuration),\n    ...identityProfileIssues(definition, configuration),\n    ...coordinationProfileIssues(definition, configuration),\n    ...externalInteractionProfileIssues(definition, configuration),\n    ...contentProfileIssues(definition, configuration),\n    ...datalakeProfileIssues(definition, configuration),\n    ...auxiliaryStoreProfileIssues(definition, configuration),\n    ...projectionProfileIssues(definition, configuration),\n  ]\n\n  return issues.length > 0\n    ? { issues, success: false }\n    : { success: true, value: { configuration, definition } }\n}\n", "import { z } from 'zod'\n\nimport { IdentifierZod } from './identifier.ts'\n\nconst PackageNameRegExp = /^(?:@[a-z0-9][a-z0-9._-]*\\/)?[a-z0-9][a-z0-9._-]*$/\nconst PackageScriptNameRegExp = /^[a-z0-9]+(?:[:._-][a-z0-9]+)*$/\nconst RepositoryPathCharacterRegExp = /^[A-Za-z0-9._@/-]+$/\nconst ApplicationPathRegExp = /^\\/(?:[A-Za-z0-9._~-]+(?:\\/[A-Za-z0-9._~-]+)*)?$/\n\nexport const PackageNameZod = z.string().min(1).max(214).regex(PackageNameRegExp)\nexport const PackageScriptNameZod = z.string().min(1).max(255).regex(PackageScriptNameRegExp)\n\nexport const RepositoryRelativePathZod = z.string().min(1).max(1024)\n  .regex(RepositoryPathCharacterRegExp)\n  .superRefine((path, context) => {\n    if (path.startsWith('/') || path.includes('\\\\')) {\n      context.addIssue({ code: 'custom', message: 'repository path must use relative forward-slash syntax' })\n    }\n    const segments = path.split('/')\n    if (segments.some(segment => segment === '' || segment === '.' || segment === '..')) {\n      context.addIssue({ code: 'custom', message: 'repository path cannot contain empty, dot, or parent segments' })\n    }\n    if (segments.some(segment => segment === '.git' || segment === '.xl1' || segment === 'node_modules')) {\n      context.addIssue({ code: 'custom', message: 'repository path enters a reserved directory' })\n    }\n  })\n\nexport const ApplicationPathZod = z.string().min(1).max(255).regex(ApplicationPathRegExp)\n\nexport const DappHostArtifactDeclarationZod = z.strictObject({\n  kind: z.literal('dapp-host'),\n  runtime: z.literal('node'),\n  package: PackageNameZod,\n  artifactManifest: RepositoryRelativePathZod,\n  hosts: z.array(IdentifierZod).min(1),\n}).superRefine((artifact, context) => {\n  const unique = new Set(artifact.hosts)\n  if (unique.size !== artifact.hosts.length) {\n    context.addIssue({\n      code: 'custom',\n      message: 'artifact host IDs must be unique',\n      path: ['hosts'],\n    })\n  }\n})\n\nexport type DappHostArtifactDeclaration = z.infer<typeof DappHostArtifactDeclarationZod>\n\nexport const StaticSiteArtifactDeclarationZod = z.strictObject({\n  kind: z.literal('static-site'),\n  package: PackageNameZod,\n  root: RepositoryRelativePathZod,\n  buildScript: PackageScriptNameZod,\n  outputDirectory: RepositoryRelativePathZod,\n  applicationPortPath: ApplicationPathZod,\n  spaFallback: z.boolean(),\n})\n\nexport type StaticSiteArtifactDeclaration = z.infer<typeof StaticSiteArtifactDeclarationZod>\n\nexport const DappArtifactDeclarationZod = z.union([\n  DappHostArtifactDeclarationZod,\n  StaticSiteArtifactDeclarationZod,\n])\n\nexport type DappArtifactDeclaration = z.infer<typeof DappArtifactDeclarationZod>\n", "import { asSchema } from '@xyo-network/sdk'\nimport { z } from 'zod'\n\nimport {\n  DappDocumentHashAlgorithm,\n  hashDappDocument,\n} from './canonicalDocument.ts'\nimport {\n  HashZod,\n  XyoSchemaZod,\n} from './identifier.ts'\nimport { JsonObjectZod } from './jsonValue.ts'\n\n/**\n * The public planning policy of one artifact-distribution capability (plan\n * Section 9's registry slice). `distributionPolicyHash` has exactly one\n * meaning, and this is it: the D-002 identity of the adapter-normalized\n * public-safe policy under the exact policy schema the adapter validated.\n *\n * It carries the same public-disclosure rule as the infrastructure planning\n * policy. A registry host, namespace, repository, route, credential, grant,\n * secret identifier, or live inventory is a protected fact and belongs in the\n * host's own `xyo-dapp-kit-host:` domains, never here -- a target plan carries\n * this hash, so anything inside its preimage is published in effect.\n */\nexport const DappArtifactDistributionPolicyIdentitySchema = asSchema('network.xyo.dapp.artifact.distribution.policy.identity', true)\n\n/** The closed distribution-kind vocabulary; the first slice registers only an OCI registry. */\nexport const DappDistributionKindZod = z.literal('oci-registry')\nexport type DappDistributionKind = z.infer<typeof DappDistributionKindZod>\n\nexport const DappArtifactDistributionPolicyIdentityV1PreimageZod = z.strictObject({\n  schema: z.literal(DappArtifactDistributionPolicyIdentitySchema),\n  schemaVersion: z.literal(1),\n  hashAlgorithm: z.literal(DappDocumentHashAlgorithm),\n  distributionKind: DappDistributionKindZod,\n  distributionAdapterDescriptorHash: HashZod,\n  policySchema: XyoSchemaZod,\n  policySchemaVersion: z.number().int().positive(),\n  policySchemaHash: HashZod,\n  /** Exact adapter-normalized strict public-safe policy; the adapter validates it against `policySchemaHash`. */\n  policy: JsonObjectZod,\n})\nexport type DappArtifactDistributionPolicyIdentityV1Preimage = z.infer<typeof DappArtifactDistributionPolicyIdentityV1PreimageZod>\n\nexport const DappArtifactDistributionPolicyIdentityV1Zod = DappArtifactDistributionPolicyIdentityV1PreimageZod\n  .safeExtend({ distributionPolicyHash: HashZod })\nexport type DappArtifactDistributionPolicyIdentityV1 = z.infer<typeof DappArtifactDistributionPolicyIdentityV1Zod>\n\n/** D-002 kind `artifact-distribution-policy` version 1. */\nexport function hashDappArtifactDistributionPolicyIdentityV1(preimage: unknown): string {\n  return hashDappDocument({\n    kind: 'artifact-distribution-policy',\n    schema: DappArtifactDistributionPolicyIdentityV1PreimageZod,\n    schemaVersion: 1,\n  }, preimage).hash\n}\n\nexport function verifyDappArtifactDistributionPolicyIdentityV1(value: unknown): DappArtifactDistributionPolicyIdentityV1 {\n  const identity = DappArtifactDistributionPolicyIdentityV1Zod.parse(value)\n  const { distributionPolicyHash, ...preimage } = identity\n  if (hashDappArtifactDistributionPolicyIdentityV1(preimage) !== distributionPolicyHash) {\n    throw new TypeError(`artifact distribution policy for ${identity.distributionKind} does not reproduce its distributionPolicyHash`)\n  }\n  return identity\n}\n", "import { asSchema } from '@xyo-network/sdk'\nimport { z } from 'zod'\n\nimport {\n  DappIdZod, HashZod, IdentifierZod, Xl1ChainIdZod,\n} from './identifier.ts'\nimport type { DappHealth } from './status.ts'\nimport { DappHealthZod, DappStatusZod } from './status.ts'\n\nexport const DappEngineConfigurationSchema = asSchema('network.xyo.dapp.engine.configuration', true)\nexport const DappEngineStatusSchema = asSchema('network.xyo.dapp.engine.status', true)\nexport const DappEngineMaximumSystems = 128\n\nexport const DappEngineNetworkZod = z.discriminatedUnion('kind', [\n  z.strictObject({ kind: z.literal('offline') }),\n  z.strictObject({\n    kind: z.literal('xl1'), chainId: Xl1ChainIdZod, genesisHash: HashZod,\n  }),\n])\nexport type DappEngineNetwork = z.infer<typeof DappEngineNetworkZod>\n\nexport const DappEngineSystemDeclarationZod = z.strictObject({\n  systemId: IdentifierZod,\n  profileId: IdentifierZod,\n  failurePolicy: z.enum(['required', 'isolated']),\n  network: DappEngineNetworkZod,\n})\nexport type DappEngineSystemDeclaration = z.infer<typeof DappEngineSystemDeclarationZod>\n\nexport const DappEngineConfigurationZod = z.strictObject({\n  schema: z.literal(DappEngineConfigurationSchema),\n  schemaVersion: z.literal(1),\n  dappId: DappIdZod,\n  systems: z.array(DappEngineSystemDeclarationZod).min(1).max(DappEngineMaximumSystems),\n}).superRefine((configuration, context) => {\n  const logicalIds = new Set(configuration.systems.map(system => system.systemId))\n  if (logicalIds.size !== configuration.systems.length) {\n    context.addIssue({\n      code: 'custom', message: 'logical system IDs must be unique', path: ['systems'],\n    })\n  }\n})\nexport type DappEngineConfiguration = z.infer<typeof DappEngineConfigurationZod>\n\nexport const DappEngineSystemStatusZod = z.strictObject({\n  declaration: DappEngineSystemDeclarationZod,\n  status: DappStatusZod,\n}).superRefine((system, context) => {\n  const { network } = system.declaration\n  const { convergence } = system.status\n  if (convergence.status === 'tracking' && (network.kind !== 'xl1' || convergence.chainId !== network.chainId)) {\n    context.addIssue({\n      code: 'custom', message: 'convergence must match the declared XL1 network', path: ['status', 'convergence'],\n    })\n  }\n  if (system.status.ready && !system.status.live) {\n    context.addIssue({\n      code: 'custom', message: 'a ready engine system must be live', path: ['status', 'live'],\n    })\n  }\n})\nexport type DappEngineSystemStatus = z.infer<typeof DappEngineSystemStatusZod>\n\nexport const DappEnginePhaseZod = z.enum(['starting', 'running', 'stopping', 'stopped', 'failed'])\nexport type DappEnginePhase = z.infer<typeof DappEnginePhaseZod>\n\n/** Summarizes lifecycle health only; it grants no operation or signing authority. */\nexport function summarizeDappEngineSystems(\n  phase: DappEnginePhase,\n  systems: readonly DappEngineSystemStatus[],\n): { health: DappHealth; ready: boolean } {\n  const failed = phase === 'failed' || systems.some(system => system.declaration.failurePolicy === 'required'\n    && (system.status.phase === 'failed' || system.status.health === 'failed'))\n  const degraded = systems.some(system => system.status.health !== 'healthy'\n    || (system.declaration.failurePolicy === 'isolated' && !system.status.ready))\n  return {\n    health: failed ? 'failed' : degraded ? 'degraded' : 'healthy',\n    ready: phase === 'running' && !failed\n      && systems.every(system => system.declaration.failurePolicy === 'isolated' || system.status.ready),\n  }\n}\n\nconst DappEngineStatusDocumentZod = z.strictObject({\n  schema: z.literal(DappEngineStatusSchema),\n  schemaVersion: z.literal(1),\n  dappId: DappIdZod,\n  hostSessionId: IdentifierZod,\n  engineInstanceId: IdentifierZod,\n  phase: DappEnginePhaseZod,\n  health: DappHealthZod,\n  ready: z.boolean(),\n  systems: z.array(DappEngineSystemStatusZod).min(1).max(DappEngineMaximumSystems),\n})\nexport type DappEngineStatus = z.infer<typeof DappEngineStatusDocumentZod>\n\nexport const DappEngineStatusZod = DappEngineStatusDocumentZod.superRefine((status, context) => {\n  const summary = summarizeDappEngineSystems(status.phase, status.systems)\n  if (summary.health !== status.health || summary.ready !== status.ready) {\n    context.addIssue({\n      code: 'custom', message: 'engine readiness and health must summarize its systems', path: [],\n    })\n  }\n  const logicalIds = new Set<string>()\n  const launches = new Set<string>()\n  const incarnations = new Set<string>()\n  for (const [index, system] of status.systems.entries()) {\n    if (logicalIds.has(system.declaration.systemId) || launches.has(system.status.launchId)\n      || (system.status.systemInstanceId !== undefined && incarnations.has(system.status.systemInstanceId))) {\n      context.addIssue({\n        code: 'custom', message: 'system identities must be unique within the engine', path: ['systems', index],\n      })\n    }\n    logicalIds.add(system.declaration.systemId)\n    launches.add(system.status.launchId)\n    if (system.status.systemInstanceId !== undefined) incarnations.add(system.status.systemInstanceId)\n    if (system.status.dappId !== status.dappId) {\n      context.addIssue({\n        code: 'custom', message: 'system dApp identity must match the engine', path: ['systems', index, 'status', 'dappId'],\n      })\n    }\n    if (status.phase === 'stopped' && (system.status.phase !== 'stopped' || system.status.live)) {\n      context.addIssue({\n        code: 'custom', message: 'a stopped engine must have stopped children', path: ['systems', index, 'status'],\n      })\n    }\n  }\n})\n\nexport const DappEngineSystemReferenceZod = z.strictObject({\n  engineInstanceId: IdentifierZod,\n  systemId: IdentifierZod,\n  systemInstanceId: IdentifierZod,\n})\nexport type DappEngineSystemReference = z.infer<typeof DappEngineSystemReferenceZod>\n", "import { asSchema } from '@xyo-network/sdk'\nimport { z } from 'zod'\n\nimport {\n  DappIdZod,\n  HashZod,\n  IdentifierZod,\n  ProtocolVersionZod,\n  Xl1ChainIdZod,\n} from './identifier.ts'\nimport { DappLifecyclePhaseZod } from './lifecycle.ts'\nexport const DappStatusSchema = asSchema('network.xyo.dapp.status', true)\n\nexport const DappHealthZod = z.enum(['healthy', 'degraded', 'failed'])\nexport type DappHealth = z.infer<typeof DappHealthZod>\n\nexport const DappWriteStateZod = z.enum(['none', 'partial', 'full', 'not-applicable'])\nexport type DappWriteState = z.infer<typeof DappWriteStateZod>\n\nexport const DappWriteCapabilityZod = z.strictObject({\n  portId: IdentifierZod,\n  operationId: IdentifierZod,\n  writable: z.boolean(),\n  reasonCodes: z.array(IdentifierZod),\n}).superRefine((capability, context) => {\n  const unique = new Set(capability.reasonCodes)\n  if (unique.size !== capability.reasonCodes.length) {\n    context.addIssue({\n      code: 'custom', message: 'reason codes must be unique', path: ['reasonCodes'],\n    })\n  }\n  if (capability.writable && capability.reasonCodes.length > 0) {\n    context.addIssue({\n      code: 'custom', message: 'writable operations cannot have blocking reason codes', path: ['reasonCodes'],\n    })\n  }\n  if (!capability.writable && capability.reasonCodes.length === 0) {\n    context.addIssue({\n      code: 'custom', message: 'non-writable operations require a stable reason code', path: ['reasonCodes'],\n    })\n  }\n})\n\nexport type DappWriteCapability = z.infer<typeof DappWriteCapabilityZod>\n\nexport const DappBlockPositionZod = z.strictObject({\n  number: z.number().int().nonnegative(),\n  hash: HashZod,\n})\n\nexport type DappBlockPosition = z.infer<typeof DappBlockPositionZod>\n\nexport const DappConvergenceZod = z.discriminatedUnion('status', [\n  z.strictObject({ status: z.literal('not-applicable') }),\n  z.strictObject({\n    status: z.literal('tracking'),\n    chainId: Xl1ChainIdZod,\n    consistency: z.literal('finalized'),\n    projectionId: IdentifierZod.optional(),\n    projectionVersion: ProtocolVersionZod.optional(),\n    finalizedHead: DappBlockPositionZod,\n    processed: DappBlockPositionZod,\n    target: DappBlockPositionZod,\n    lag: z.number().int().nonnegative(),\n  }).superRefine((convergence, context) => {\n    const hasProjectionId = convergence.projectionId !== undefined\n    const hasProjectionVersion = convergence.projectionVersion !== undefined\n    if (hasProjectionId !== hasProjectionVersion) {\n      context.addIssue({\n        code: 'custom', message: 'projection ID and version must appear together', path: ['projectionId'],\n      })\n    }\n    if (convergence.processed.number > convergence.finalizedHead.number) {\n      context.addIssue({\n        code: 'custom', message: 'processed position cannot exceed the finalized head', path: ['processed', 'number'],\n      })\n    }\n    if (convergence.target.number > convergence.finalizedHead.number) {\n      context.addIssue({\n        code: 'custom', message: 'startup target cannot exceed the finalized head', path: ['target', 'number'],\n      })\n    }\n    if (convergence.lag !== convergence.finalizedHead.number - convergence.processed.number) {\n      context.addIssue({\n        code: 'custom', message: 'lag must equal finalized head minus processed position', path: ['lag'],\n      })\n    }\n  }),\n])\n\nexport type DappConvergence = z.infer<typeof DappConvergenceZod>\n\nconst DappStatusDocumentZod = z.strictObject({\n  schema: z.literal(DappStatusSchema),\n  schemaVersion: z.literal(1),\n  dappId: DappIdZod,\n  launchId: IdentifierZod,\n  planId: HashZod.optional(),\n  systemInstanceId: IdentifierZod.optional(),\n  hostSessionId: IdentifierZod,\n  phase: DappLifecyclePhaseZod,\n  health: DappHealthZod,\n  live: z.boolean(),\n  ready: z.boolean(),\n  writeState: DappWriteStateZod,\n  writeCapabilities: z.array(DappWriteCapabilityZod),\n  convergence: DappConvergenceZod,\n  degradations: z.array(IdentifierZod),\n})\n\nexport type DappStatus = z.infer<typeof DappStatusDocumentZod>\n\nfunction addStatusIdentityIssues(status: DappStatus, context: z.core.$RefinementCtx<unknown>) {\n  if (status.ready && (status.planId === undefined || status.systemInstanceId === undefined)) {\n    context.addIssue({\n      code: 'custom', message: 'ready status requires plan and system incarnation IDs', path: [],\n    })\n  }\n  if (status.ready !== (status.phase === 'ready')) {\n    context.addIssue({\n      code: 'custom', message: 'ready flag must agree with lifecycle phase', path: ['ready'],\n    })\n  }\n  if (status.phase === 'stopped' && status.live) {\n    context.addIssue({\n      code: 'custom', message: 'a stopped incarnation cannot be live', path: ['live'],\n    })\n  }\n}\n\nfunction addWriteSummaryIssues(status: DappStatus, context: z.core.$RefinementCtx<unknown>) {\n  const capabilityIds = status.writeCapabilities.map(capability => `${capability.portId}.${capability.operationId}`)\n  const unique2 = new Set(capabilityIds)\n  if (unique2.size !== capabilityIds.length) {\n    context.addIssue({\n      code: 'custom', message: 'write capabilities must be unique per operation', path: ['writeCapabilities'],\n    })\n  }\n\n  const writableCount = status.writeCapabilities.filter(capability => capability.writable).length\n  const totalCount = status.writeCapabilities.length\n  const expectedWriteState = totalCount === 0\n    ? 'not-applicable'\n    : writableCount === 0\n      ? 'none'\n      : writableCount === totalCount\n        ? 'full'\n        : 'partial'\n  if (status.writeState !== expectedWriteState) {\n    context.addIssue({\n      code: 'custom', message: 'write state must summarize per-operation writability', path: ['writeState'],\n    })\n  }\n}\n\nexport const DappStatusZod = DappStatusDocumentZod.superRefine((status, context) => {\n  addStatusIdentityIssues(status, context)\n  addWriteSummaryIssues(status, context)\n  const unique3 = new Set(status.degradations)\n  if (unique3.size !== status.degradations.length) {\n    context.addIssue({\n      code: 'custom', message: 'degradation codes must be unique', path: ['degradations'],\n    })\n  }\n})\n", "import { z } from 'zod'\n\nimport { IdentifierZod } from './identifier.ts'\n\nexport const DappLifecyclePhaseZod = z.enum([\n  'planning',\n  'provisioning',\n  'recovering',\n  'starting',\n  'ready',\n  'draining',\n  'stopping',\n  'stopped',\n  'failed',\n])\n\nexport type DappLifecyclePhase = z.infer<typeof DappLifecyclePhaseZod>\n\nexport const DappLifecycleEventZod = z.enum([\n  'planning-complete',\n  'provisioning-complete',\n  'recovery-complete',\n  'start-complete',\n  'stop-requested',\n  'drain-complete',\n  'teardown-complete',\n  'required-invariant-failed',\n])\n\nexport type DappLifecycleEvent = z.infer<typeof DappLifecycleEventZod>\n\nconst DappLifecycleTransitions: Readonly<Partial<Record<DappLifecyclePhase, Readonly<Partial<Record<DappLifecycleEvent, DappLifecyclePhase>>>>>> = {\n  planning: {\n    'planning-complete': 'provisioning',\n    'required-invariant-failed': 'failed',\n    'stop-requested': 'stopping',\n  },\n  provisioning: {\n    'provisioning-complete': 'recovering',\n    'required-invariant-failed': 'failed',\n    'stop-requested': 'stopping',\n  },\n  recovering: {\n    'recovery-complete': 'starting',\n    'required-invariant-failed': 'failed',\n    'stop-requested': 'stopping',\n  },\n  starting: {\n    'required-invariant-failed': 'failed',\n    'start-complete': 'ready',\n    'stop-requested': 'stopping',\n  },\n  ready: {\n    'required-invariant-failed': 'failed',\n    'stop-requested': 'draining',\n  },\n  draining: {\n    'drain-complete': 'stopping',\n    'required-invariant-failed': 'failed',\n    'stop-requested': 'draining',\n  },\n  failed: { 'stop-requested': 'stopping' },\n  stopping: {\n    'stop-requested': 'stopping',\n    'teardown-complete': 'stopped',\n  },\n  stopped: { 'stop-requested': 'stopped' },\n}\n\nexport interface DappLifecycleTransition {\n  changed: boolean\n  event: DappLifecycleEvent\n  from: DappLifecyclePhase\n  to: DappLifecyclePhase\n}\n\nexport interface DappLifecycleTransitionSuccess {\n  success: true\n  value: DappLifecycleTransition\n}\n\nexport interface DappLifecycleTransitionFailure {\n  issue: {\n    code: 'lifecycle.invalid-transition'\n    event: DappLifecycleEvent\n    phase: DappLifecyclePhase\n  }\n  success: false\n}\n\nexport type DappLifecycleTransitionResult = DappLifecycleTransitionFailure | DappLifecycleTransitionSuccess\n\nexport function transitionDappLifecycle(\n  phase: DappLifecyclePhase,\n  event: DappLifecycleEvent,\n): DappLifecycleTransitionResult {\n  const nextPhase = DappLifecycleTransitions[phase]?.[event]\n  return nextPhase === undefined\n    ? {\n        issue: {\n          code: 'lifecycle.invalid-transition', event, phase,\n        },\n        success: false,\n      }\n    : {\n        success: true,\n        value: {\n          changed: phase !== nextPhase,\n          event,\n          from: phase,\n          to: nextPhase,\n        },\n      }\n}\n\nexport const DappErrorZod = z.strictObject({\n  code: IdentifierZod,\n  message: z.string().min(1),\n  source: IdentifierZod.optional(),\n  causeCodes: z.array(IdentifierZod),\n})\n\nexport type DappError = z.infer<typeof DappErrorZod>\n\nexport const DappLaunchOutcomeZod = z.discriminatedUnion('outcome', [\n  z.strictObject({\n    outcome: z.literal('ready'),\n    launchId: IdentifierZod,\n    systemInstanceId: IdentifierZod,\n  }),\n  z.strictObject({\n    outcome: z.literal('stopped'),\n    launchId: IdentifierZod,\n  }),\n  z.strictObject({\n    outcome: z.literal('failed'),\n    launchId: IdentifierZod,\n    error: DappErrorZod,\n  }),\n])\n\nexport type DappLaunchOutcome = z.infer<typeof DappLaunchOutcomeZod>\n", "import type { DappEngineSystemLauncher } from './dappEngine.ts'\nimport type { DappEngineSystemDeclaration } from './dappEngineModel.ts'\nimport type { DappLaunch } from './dappLaunch.ts'\nimport type { DappSession } from './dappSession.ts'\nimport type { DappStatus } from './status.ts'\nimport { DappStatusSchema } from './status.ts'\n\nexport interface OwnedEngineSystem {\n  cleanupFailed: boolean\n  readonly declaration: DappEngineSystemDeclaration\n  failed: boolean\n  last: DappStatus\n  launch?: DappLaunch<unknown>\n  readonly launcher: DappEngineSystemLauncher\n  retiring: boolean\n  session?: DappSession<unknown>\n  stopPromise?: Promise<void>\n  stopped: boolean\n}\n\nexport function createOwnedEngineSystem(\n  declaration: DappEngineSystemDeclaration,\n  launcher: DappEngineSystemLauncher,\n  dappId: string,\n  hostSessionId: string,\n): OwnedEngineSystem {\n  Object.freeze(declaration.network)\n  Object.freeze(declaration)\n  return {\n    cleanupFailed: false,\n    declaration,\n    failed: false,\n    launcher,\n    retiring: false,\n    stopped: false,\n    last: {\n      schema: DappStatusSchema,\n      schemaVersion: 1,\n      dappId,\n      hostSessionId,\n      launchId: launcher.launchId,\n      phase: 'planning',\n      health: 'healthy',\n      live: true,\n      ready: false,\n      writeState: 'not-applicable',\n      writeCapabilities: [],\n      convergence: { status: 'not-applicable' },\n      degradations: [],\n    },\n  }\n}\n\nexport function ownedEngineSystemStatus(record: OwnedEngineSystem): DappStatus {\n  if (!record.failed && !record.stopped && !record.cleanupFailed && !record.retiring) return record.last\n  const failed = record.failed || record.cleanupFailed\n  const code = record.cleanupFailed\n    ? 'engine.system-cleanup-failed'\n    : failed ? 'engine.system-failed' : record.stopped ? 'engine.system-stopped' : 'engine.system-replacing'\n  return {\n    ...record.last,\n    phase: failed ? 'failed' : record.stopped ? 'stopped' : 'stopping',\n    health: failed ? 'failed' : record.last.health,\n    live: record.cleanupFailed || !record.stopped,\n    ready: false,\n    writeCapabilities: record.last.writeCapabilities.map(capability => ({\n      ...capability, writable: false, reasonCodes: [code],\n    })),\n    writeState: record.last.writeCapabilities.length === 0 ? 'not-applicable' : 'none',\n    degradations: [...new Set([...record.last.degradations, code])],\n  }\n}\n", "import type {\n  DappEngineNetwork, DappEngineStatus, DappEngineSystemDeclaration, DappEngineSystemStatus,\n} from './dappEngineModel.ts'\nimport {\n  DappEngineConfigurationZod, DappEngineStatusZod, DappEngineSystemReferenceZod, DappEngineSystemStatusZod,\n} from './dappEngineModel.ts'\n\nexport type DappEngineValidationIssueCode\n  = | 'engine.configuration-invalid'\n    | 'engine.status-invalid'\n    | 'engine.configuration-mismatch'\n    | 'engine.reference-invalid'\n    | 'engine.stale-engine'\n    | 'engine.system-unknown'\n    | 'engine.stale-system'\n    | 'engine.system-unavailable'\n    | 'engine.replacement-invalid'\n\nexport type DappEngineValidationResult<T>\n  = | { success: true; value: T }\n    | { issue: { code: DappEngineValidationIssueCode }; success: false }\n\nfunction invalid(code: DappEngineValidationIssueCode): { issue: { code: DappEngineValidationIssueCode }; success: false } {\n  return { success: false, issue: { code } }\n}\n\nfunction sameNetwork(left: DappEngineNetwork, right: DappEngineNetwork): boolean {\n  return left.kind === 'offline'\n    ? right.kind === 'offline'\n    : right.kind === 'xl1'\n      && left.chainId === right.chainId && left.genesisHash === right.genesisHash\n}\n\nfunction sameBinding(left: DappEngineSystemDeclaration, right: DappEngineSystemDeclaration): boolean {\n  return left.systemId === right.systemId && left.failurePolicy === right.failurePolicy && sameNetwork(left.network, right.network)\n}\n\n/** Verifies complete configuration coverage without acquiring or resolving any system. */\nexport function validateDappEngineStatus(configurationValue: unknown, statusValue: unknown): DappEngineValidationResult<DappEngineStatus> {\n  const configuration = DappEngineConfigurationZod.safeParse(configurationValue)\n  if (!configuration.success) return invalid('engine.configuration-invalid')\n  const status = DappEngineStatusZod.safeParse(statusValue)\n  if (!status.success) return invalid('engine.status-invalid')\n  if (configuration.data.dappId !== status.data.dappId || configuration.data.systems.length !== status.data.systems.length) {\n    return invalid('engine.configuration-mismatch')\n  }\n  for (const declaration of configuration.data.systems) {\n    const current = status.data.systems.find(system => system.declaration.systemId === declaration.systemId)?.declaration\n    if (current === undefined || !sameBinding(declaration, current) || declaration.profileId !== current.profileId) {\n      return invalid('engine.configuration-mismatch')\n    }\n  }\n  return { success: true, value: status.data }\n}\n\n/** Checks an exact incarnation reference. Success does not authorize a write. */\nexport function validateDappEngineSystemReference(statusValue: unknown, referenceValue: unknown): DappEngineValidationResult<DappEngineSystemStatus> {\n  const status = DappEngineStatusZod.safeParse(statusValue)\n  if (!status.success) return invalid('engine.status-invalid')\n  const reference = DappEngineSystemReferenceZod.safeParse(referenceValue)\n  if (!reference.success) return invalid('engine.reference-invalid')\n  if (reference.data.engineInstanceId !== status.data.engineInstanceId) return invalid('engine.stale-engine')\n  const system = status.data.systems.find(entry => entry.declaration.systemId === reference.data.systemId)\n  if (system === undefined) return invalid('engine.system-unknown')\n  if (system.status.systemInstanceId !== reference.data.systemInstanceId) return invalid('engine.stale-system')\n  return status.data.phase !== 'running' || status.data.health === 'failed' || !system.status.ready || system.status.health === 'failed'\n    ? invalid('engine.system-unavailable')\n    : { success: true, value: system }\n}\n\n/** Checks the publication boundary after old teardown and new readiness, never retargeting a reference. */\nexport function validateDappEngineSystemReplacement(previousValue: unknown, replacementValue: unknown): DappEngineValidationResult<DappEngineSystemStatus> {\n  const previous = DappEngineSystemStatusZod.safeParse(previousValue)\n  const replacement = DappEngineSystemStatusZod.safeParse(replacementValue)\n  if (!previous.success || !replacement.success) return invalid('engine.replacement-invalid')\n  const before = previous.data\n  const after = replacement.data\n  return !sameBinding(before.declaration, after.declaration) || before.status.dappId !== after.status.dappId\n    || before.status.phase !== 'stopped' || before.status.live || !after.status.ready || after.status.health === 'failed'\n    || before.status.launchId === after.status.launchId || before.status.systemInstanceId === after.status.systemInstanceId\n    ? invalid('engine.replacement-invalid')\n    : { success: true, value: after }\n}\n", "import type { DappSession } from './dappSession.ts'\nimport {\n  HashZod,\n  IdentifierZod,\n} from './identifier.ts'\nimport type {\n  DappError,\n  DappLifecyclePhase,\n} from './lifecycle.ts'\nimport {\n  DappErrorZod,\n  transitionDappLifecycle,\n} from './lifecycle.ts'\nimport type {\n  DappStatus,\n  DappWriteCapability,\n  DappWriteState,\n} from './status.ts'\nimport { DappStatusZod } from './status.ts'\n\nexport const DappLaunchErrorCode = {\n  failed: 'dapp-launch.failed',\n  stopped: 'dapp-launch.stopped',\n  statusIdentityChanged: 'dapp-launch.status-identity-changed',\n  statusInvalid: 'dapp-launch.status-invalid',\n} as const\n\nexport interface DappLaunchOwnedResource {\n  stop(): Promise<void>\n}\n\nexport interface DappBootContext {\n  readonly whenStopRequested: Promise<void>\n  isStopRequested(): boolean\n  own(resource: DappLaunchOwnedResource): void\n  planned(planId: string): void\n  provisioned(systemInstanceId: string): void\n  recovered(): void\n  throwIfStopRequested(): void\n}\n\nexport interface LaunchDappOptions<TPorts> {\n  readonly boot: (context: DappBootContext) => Promise<DappSession<TPorts>>\n  readonly mapError?: (cause: unknown) => DappError\n  /** Supplies changing health/convergence dimensions with planning-phase identity. */\n  readonly readStatus: () => DappStatus\n}\n\nexport interface DappLaunchReady<TPorts> {\n  readonly launchId: string\n  readonly outcome: 'ready'\n  readonly session: DappSession<TPorts>\n  readonly systemInstanceId: string\n}\n\nexport interface DappLaunchStopped {\n  readonly launchId: string\n  readonly outcome: 'stopped'\n}\n\nexport interface DappLaunchFailed {\n  readonly cause: unknown\n  readonly error: DappError\n  readonly launchId: string\n  readonly outcome: 'failed'\n}\n\nexport type DappLaunchResult<TPorts> = DappLaunchFailed | DappLaunchReady<TPorts> | DappLaunchStopped\n\nexport interface DappLaunch<TPorts = Readonly<Record<string, unknown>>> {\n  readonly outcome: Promise<DappLaunchResult<TPorts>>\n  status(): DappStatus\n  stop(): Promise<void>\n  whenReady(): Promise<DappSession<TPorts>>\n}\n\ninterface LaunchIdentity {\n  readonly dappId: string\n  readonly hostSessionId: string\n  readonly launchId: string\n}\n\nexport class DappLaunchStoppedError extends Error {\n  readonly code = DappLaunchErrorCode.stopped\n  readonly launchId: string\n\n  constructor(launchId: string) {\n    super(`Dapp launch \"${launchId}\" stopped before readiness`)\n    this.name = 'DappLaunchStoppedError'\n    this.launchId = launchId\n  }\n}\n\nexport class DappLaunchFailedError extends Error {\n  readonly code = DappLaunchErrorCode.failed\n  readonly dappError: DappError\n  readonly launchId: string\n\n  constructor(launchId: string, dappError: DappError, cause: unknown) {\n    super(dappError.message, { cause })\n    this.name = 'DappLaunchFailedError'\n    this.dappError = dappError\n    this.launchId = launchId\n  }\n}\n\nexport class DappLaunchStatusError extends Error {\n  readonly code: string\n\n  constructor(code: string, message: string) {\n    super(message)\n    this.name = 'DappLaunchStatusError'\n    this.code = code\n  }\n}\n\nfunction initialStatus(readStatus: () => DappStatus): DappStatus {\n  const status = DappStatusZod.parse(readStatus())\n  if (status.phase !== 'planning' || !status.live || status.ready\n    || status.planId !== undefined || status.systemInstanceId !== undefined) {\n    throw new DappLaunchStatusError(\n      DappLaunchErrorCode.statusInvalid,\n      'A dApp launch requires a live planning status without plan or system incarnation IDs',\n    )\n  }\n  return status\n}\n\nfunction writeState(capabilities: readonly DappWriteCapability[]): DappWriteState {\n  if (capabilities.length === 0) return 'not-applicable'\n  const writable = capabilities.filter(capability => capability.writable).length\n  return writable === 0 ? 'none' : writable === capabilities.length ? 'full' : 'partial'\n}\n\nfunction blockedCapabilities(\n  capabilities: readonly DappWriteCapability[],\n  phase: DappLifecyclePhase,\n): DappWriteCapability[] {\n  return capabilities.map(capability => ({\n    ...capability,\n    reasonCodes: [`dapp-launch.${phase}`],\n    writable: false,\n  }))\n}\n\nfunction errorCauseCodes(cause: unknown): string[] {\n  const codes: string[] = []\n  if (cause instanceof AggregateError) {\n    for (const error of cause.errors) codes.push(...errorCauseCodes(error))\n  } else if (typeof cause === 'object' && cause !== null && 'code' in cause) {\n    const result = IdentifierZod.safeParse(cause.code)\n    if (result.success) codes.push(result.data)\n  }\n  return [...new Set(codes)]\n}\n\nfunction defaultDappError(cause: unknown): DappError {\n  const message = cause instanceof Error ? cause.message : 'Dapp launch failed'\n  const source = typeof cause === 'object' && cause !== null && 'resourceId' in cause\n    ? IdentifierZod.safeParse(cause.resourceId)\n    : undefined\n  return DappErrorZod.parse({\n    code: 'dapp-launch.boot-failed',\n    message,\n    ...source?.success === true && { source: source.data },\n    causeCodes: errorCauseCodes(cause),\n  })\n}\n\nfunction mappedDappError(cause: unknown, mapper?: (cause: unknown) => DappError): DappError {\n  if (mapper === undefined) return defaultDappError(cause)\n  try {\n    const result = DappErrorZod.safeParse(mapper(cause))\n    if (result.success) return result.data\n  } catch {\n    // Fall through to the stable default error when host mapping fails.\n  }\n  const fallback = defaultDappError(cause)\n  return { ...fallback, causeCodes: [...new Set([...fallback.causeCodes, 'dapp-launch.error-mapping-failed'])] }\n}\n\nfunction throwableError(cause: unknown): Error {\n  return cause instanceof Error\n    ? cause\n    : new Error('Dapp launch stop failed with a non-error value', { cause })\n}\n\nclass DappLaunchInstance<TPorts> {\n  readonly outcome: Promise<DappLaunchResult<TPorts>>\n  private readonly identity: LaunchIdentity\n  private isStopping = false\n  private readonly mapError?: (cause: unknown) => DappError\n  private phase: DappLifecyclePhase = 'planning'\n  private planId?: string\n  private readonly readStatus: () => DappStatus\n  private readonly resources: DappLaunchOwnedResource[] = []\n  private session?: DappSession<TPorts>\n  private readonly signalStop: () => void\n  private stopError?: unknown\n  private stopPromise?: Promise<void>\n  private readonly stopRequested: Promise<void>\n  private systemInstanceId?: string\n\n  constructor(options: LaunchDappOptions<TPorts>) {\n    const status = initialStatus(options.readStatus)\n    this.identity = {\n      dappId: status.dappId,\n      hostSessionId: status.hostSessionId,\n      launchId: status.launchId,\n    }\n    this.mapError = options.mapError\n    this.readStatus = options.readStatus\n    let signalStop: () => void = () => {\n      throw new Error('Dapp launch stop signal was not initialized')\n    }\n    this.stopRequested = new Promise(resolve => signalStop = resolve)\n    this.signalStop = signalStop\n    this.outcome = (async () => {\n      await Promise.resolve()\n      return await this.runBoot(options.boot)\n    })()\n  }\n\n  status(): DappStatus {\n    if (this.session !== undefined) return this.session.status()\n    const source = initialStatus(this.readStatus)\n    this.assertBaseIdentity(source)\n    const writeCapabilities = blockedCapabilities(source.writeCapabilities, this.phase)\n    return DappStatusZod.parse({\n      ...source,\n      health: this.phase === 'failed' ? 'failed' : source.health,\n      live: this.phase !== 'stopped',\n      phase: this.phase,\n      planId: this.planId,\n      ready: false,\n      systemInstanceId: this.systemInstanceId,\n      writeCapabilities,\n      writeState: writeState(writeCapabilities),\n    })\n  }\n\n  stop(): Promise<void> {\n    this.stopPromise ??= this.stopOnce()\n    return this.stopPromise\n  }\n\n  async whenReady(): Promise<DappSession<TPorts>> {\n    const outcome = await this.outcome\n    if (outcome.outcome === 'ready') return outcome.session\n    if (outcome.outcome === 'stopped') throw new DappLaunchStoppedError(outcome.launchId)\n    throw new DappLaunchFailedError(outcome.launchId, outcome.error, outcome.cause)\n  }\n\n  private async acceptSession(session: DappSession<TPorts>): Promise<DappLaunchResult<TPorts>> {\n    if (this.isStopping) return await this.stopReturnedSession(session)\n    if (this.phase !== 'starting') throw new Error(`Dapp boot returned a session while ${this.phase}`)\n    try {\n      this.validateSession(session)\n    } catch (validationError) {\n      this.resources.length = 0\n      try {\n        await session.stop()\n      } catch (stopError) {\n        this.stopError = stopError\n        throw new AggregateError(\n          [validationError, stopError],\n          'Dapp session identity validation and stop failed',\n          { cause: stopError },\n        )\n      }\n      throw validationError\n    }\n    this.resources.length = 0\n    this.session = session\n    this.transition('start-complete')\n    const systemInstanceId = this.systemInstanceId\n    if (systemInstanceId === undefined) throw new Error('Ready dApp launch lacks a system incarnation ID')\n    return {\n      launchId: this.identity.launchId,\n      outcome: 'ready',\n      session,\n      systemInstanceId,\n    }\n  }\n\n  private assertBaseIdentity(status: DappStatus): void {\n    for (const field of Object.keys(this.identity) as (keyof LaunchIdentity)[]) {\n      if (status[field] !== this.identity[field]) {\n        throw new DappLaunchStatusError(\n          DappLaunchErrorCode.statusIdentityChanged,\n          `Dapp launch status changed immutable ${field}`,\n        )\n      }\n    }\n  }\n\n  private bootContext(): DappBootContext {\n    return Object.freeze({\n      isStopRequested: () => this.isStopping,\n      own: (resource: DappLaunchOwnedResource) => this.own(resource),\n      planned: (planId: string) => this.planned(planId),\n      provisioned: (systemInstanceId: string) => this.provisioned(systemInstanceId),\n      recovered: () => this.recovered(),\n      throwIfStopRequested: () => this.throwIfStopRequested(),\n      whenStopRequested: this.stopRequested,\n    })\n  }\n\n  private async cleanupResources(): Promise<unknown[]> {\n    const resources = this.resources.splice(0).toReversed()\n    const errors: unknown[] = []\n    for (const resource of resources) {\n      try {\n        await resource.stop()\n      } catch (error) {\n        errors.push(error)\n      }\n    }\n    return errors\n  }\n\n  private failPhase(): void {\n    if (this.phase === 'planning' || this.phase === 'provisioning'\n      || this.phase === 'recovering' || this.phase === 'starting') {\n      this.transition('required-invariant-failed')\n    }\n  }\n\n  private own(resource: DappLaunchOwnedResource): void {\n    if (this.phase === 'planning' || this.phase === 'ready'\n      || this.phase === 'failed' || this.phase === 'stopped') {\n      throw new Error(`Dapp launch cannot acquire a resource while ${this.phase}`)\n    }\n    if (this.resources.includes(resource)) throw new Error('Dapp launch resource is already owned')\n    this.resources.push(resource)\n  }\n\n  private planned(planId: string): void {\n    this.throwIfStopRequested()\n    this.planId = HashZod.parse(planId)\n    this.transition('planning-complete')\n  }\n\n  private provisioned(systemInstanceId: string): void {\n    this.throwIfStopRequested()\n    this.systemInstanceId = IdentifierZod.parse(systemInstanceId)\n    this.transition('provisioning-complete')\n  }\n\n  private recovered(): void {\n    this.throwIfStopRequested()\n    this.transition('recovery-complete')\n  }\n\n  private async runBoot(\n    boot: (context: DappBootContext) => Promise<DappSession<TPorts>>,\n  ): Promise<DappLaunchResult<TPorts>> {\n    try {\n      this.throwIfStopRequested()\n      const session = await boot(this.bootContext())\n      return await this.acceptSession(session)\n    } catch (cause) {\n      const cleanupErrors = await this.cleanupResources()\n      if (this.isStopping) {\n        const errors = cause instanceof DappLaunchStoppedError ? cleanupErrors : [cause, ...cleanupErrors]\n        if (errors.length > 0) {\n          this.stopError = errors.length === 1\n            ? errors[0]\n            : new AggregateError(errors, 'Dapp launch stop and cleanup failed')\n        }\n        if (this.phase === 'stopping') this.transition('teardown-complete')\n        return { launchId: this.identity.launchId, outcome: 'stopped' }\n      }\n      this.failPhase()\n      if (cleanupErrors.length > 0) {\n        this.stopError = new AggregateError(cleanupErrors, 'Dapp launch cleanup failed')\n      }\n      const failure = cleanupErrors.length === 0\n        ? cause\n        : new AggregateError([cause, ...cleanupErrors], 'Dapp launch and cleanup failed', { cause })\n      return {\n        cause: failure,\n        error: mappedDappError(failure, this.mapError),\n        launchId: this.identity.launchId,\n        outcome: 'failed',\n      }\n    }\n  }\n\n  private async stopOnce(): Promise<void> {\n    if (this.session !== undefined) return await this.session.stop()\n    if (!this.isStopping) {\n      this.isStopping = true\n      this.transition('stop-requested')\n      this.signalStop()\n    }\n    await this.outcome\n    if (this.phase === 'stopping') this.transition('teardown-complete')\n    if (this.stopError !== undefined) throw throwableError(this.stopError)\n  }\n\n  private async stopReturnedSession(session: DappSession<TPorts>): Promise<DappLaunchStopped> {\n    this.resources.length = 0\n    try {\n      await session.stop()\n    } catch (error) {\n      this.stopError = error\n    }\n    this.transition('teardown-complete')\n    return { launchId: this.identity.launchId, outcome: 'stopped' }\n  }\n\n  private throwIfStopRequested(): void {\n    if (this.isStopping) throw new DappLaunchStoppedError(this.identity.launchId)\n  }\n\n  private transition(event: Parameters<typeof transitionDappLifecycle>[1]): void {\n    const result = transitionDappLifecycle(this.phase, event)\n    if (!result.success) throw new Error(`Invalid dApp launch transition ${this.phase} -> ${event}`)\n    this.phase = result.value.to\n  }\n\n  private validateSession(session: DappSession<TPorts>): void {\n    const status = session.status()\n    if (status.phase !== 'ready' || status.dappId !== this.identity.dappId\n      || status.launchId !== this.identity.launchId || status.hostSessionId !== this.identity.hostSessionId\n      || status.planId !== this.planId || status.systemInstanceId !== this.systemInstanceId) {\n      throw new Error('Ready dApp session identity does not match its launch')\n    }\n  }\n}\n\nexport function launchDapp<TPorts>(options: LaunchDappOptions<TPorts>): DappLaunch<TPorts> {\n  const instance = new DappLaunchInstance(options)\n  return Object.freeze({\n    outcome: instance.outcome,\n    status: () => instance.status(),\n    stop: () => instance.stop(),\n    whenReady: async () => await instance.whenReady(),\n  })\n}\n", "import type {\n  DappEngineConfiguration, DappEnginePhase, DappEngineStatus, DappEngineSystemDeclaration, DappEngineSystemReference,\n} from './dappEngineModel.ts'\nimport {\n  DappEngineConfigurationZod, DappEngineStatusSchema, DappEngineStatusZod, DappEngineSystemReferenceZod, DappEngineSystemStatusZod, summarizeDappEngineSystems,\n} from './dappEngineModel.ts'\nimport type { OwnedEngineSystem } from './dappEngineSystem.ts'\nimport { createOwnedEngineSystem, ownedEngineSystemStatus } from './dappEngineSystem.ts'\nimport { validateDappEngineSystemReference, validateDappEngineSystemReplacement } from './dappEngineValidation.ts'\nimport type { DappLaunch } from './dappLaunch.ts'\nimport { DappLaunchStoppedError } from './dappLaunch.ts'\nimport type {\n  DappSession, DappSessionWorkBinding, DappSessionWorkOwner,\n} from './dappSession.ts'\nimport { IdentifierZod } from './identifier.ts'\n\nexport interface DappEngineSystemLaunchContext {\n  readonly dappId: string\n  readonly declaration: DappEngineSystemDeclaration\n  readonly engineInstanceId: string\n  readonly hostSessionId: string\n  readonly launchId: string\n}\n\n/** Trusted host binding; actual provider and actor factories remain in host adapters. */\nexport interface DappEngineSystemLauncher {\n  readonly launchId: string\n  readonly systemId: string\n  launch(context: DappEngineSystemLaunchContext): DappLaunch<unknown>\n}\n\nexport interface LaunchDappEngineOptions {\n  readonly configuration: unknown\n  readonly engineInstanceId: string\n  readonly hostSessionId: string\n  readonly systems: readonly DappEngineSystemLauncher[]\n}\n\nexport interface ReplaceDappEngineSystemOptions {\n  readonly launcher: DappEngineSystemLauncher\n  readonly profileId: string\n  readonly reference: DappEngineSystemReference\n}\n\n/** Ownership facade only. No child ports, providers or locators escape through it. */\nexport interface DappEngineSession {\n  bindSystemWork(reference: DappEngineSystemReference, create: () => DappSessionWorkOwner): DappSessionWorkBinding\n  replaceSystem(options: ReplaceDappEngineSystemOptions): Promise<DappEngineSystemReference>\n  status(): DappEngineStatus\n  stop(): Promise<void>\n  whenStopped(): Promise<void>\n  whenTerminal(): Promise<never>\n}\n\nexport type DappEngineLaunchResult\n  = | { readonly outcome: 'ready'; readonly session: DappEngineSession }\n    | { readonly cause: unknown; readonly outcome: 'failed' }\n    | { readonly outcome: 'stopped' }\n\nexport interface DappEngineLaunch {\n  readonly outcome: Promise<DappEngineLaunchResult>\n  /** Unavailable until configuration and launcher identity validation succeeds. */\n  status(): DappEngineStatus | undefined\n  stop(): Promise<void>\n  whenReady(): Promise<DappEngineSession>\n  whenStopped(): Promise<void>\n  whenTerminal(): Promise<never>\n}\n\nexport class DappEngineLifecycleError extends Error {\n  readonly code: string\n  readonly systemId?: string\n\n  constructor(code: string, cause?: unknown, systemId?: string) {\n    super(code, { cause })\n    this.name = 'DappEngineLifecycleError'\n    this.code = code\n    this.systemId = systemId\n  }\n}\n\nclass DappEngineInstance {\n  readonly outcome: Promise<DappEngineLaunchResult>\n  private configuration?: DappEngineConfiguration\n  private engineInstanceId?: string\n  private readonly errors: unknown[] = []\n  private failed = false\n  private hostSessionId?: string\n  private readonly options: LaunchDappEngineOptions\n  private phase: DappEnginePhase = 'starting'\n  private readonly records: OwnedEngineSystem[] = []\n  private readonly replacements = new Map<string, Promise<DappEngineSystemReference>>()\n  private readonly stopCompletion = Promise.withResolvers<void>()\n  private stopPromise?: Promise<void>\n  private stopRequested = false\n  private readonly terminal = Promise.withResolvers<never>()\n  private readonly usedIncarnations = new Set<string>()\n  private readonly usedLaunches = new Set<string>()\n\n  constructor(options: LaunchDappEngineOptions) {\n    this.options = options\n    void this.stopCompletion.promise.catch(() => { /* Retained for stop and completion observers. */ })\n    // Nothing that validates or invokes a host callback runs before the handle exists.\n    this.outcome = (async () => {\n      await Promise.resolve()\n      return await this.runBoot()\n    })()\n    void this.terminal.promise.catch(() => { /* The owner chooses when to join terminal failure. */ })\n  }\n\n  bindSystemWork(reference: DappEngineSystemReference, create: () => DappSessionWorkOwner): DappSessionWorkBinding {\n    const admission = validateDappEngineSystemReference(this.status(), reference)\n    if (!admission.success) throw new DappEngineLifecycleError(admission.issue.code)\n    const record = this.records.find(entry => entry.declaration.systemId === admission.value.declaration.systemId)!\n    return record.session!.bindWork(create)\n  }\n\n  async replaceSystem(options: ReplaceDappEngineSystemOptions): Promise<DappEngineSystemReference> {\n    const reference = DappEngineSystemReferenceZod.parse(options.reference)\n    const admission = validateDappEngineSystemReference(this.status(), reference)\n    if (!admission.success) throw new DappEngineLifecycleError(admission.issue.code)\n    const record = this.records.find(entry => entry.declaration.systemId === reference.systemId)!\n    const profileId = IdentifierZod.parse(options.profileId)\n    const systemId = IdentifierZod.parse(options.launcher.systemId)\n    const launchId = IdentifierZod.parse(options.launcher.launchId)\n    if (systemId !== reference.systemId || this.usedLaunches.has(launchId) || typeof options.launcher.launch !== 'function') {\n      throw new DappEngineLifecycleError('engine.launcher-invalid')\n    }\n    const launcher = {\n      systemId, launchId, launch: options.launcher.launch.bind(options.launcher),\n    }\n    if (this.replacements.has(systemId)) throw new DappEngineLifecycleError('engine.system-unavailable')\n    // Revalidate after trusted host property access, which may be reentrant.\n    const rechecked = validateDappEngineSystemReference(this.status(), reference)\n    if (!rechecked.success) throw new DappEngineLifecycleError(rechecked.issue.code)\n    if (this.usedLaunches.has(launchId)) throw new DappEngineLifecycleError('engine.launcher-invalid')\n    this.usedLaunches.add(launchId)\n    record.retiring = true\n    const completion = Promise.withResolvers<DappEngineSystemReference>()\n    this.replacements.set(systemId, completion.promise)\n    void this.performReplacement(record, profileId, launcher).then(completion.resolve, completion.reject).then(() => {\n      this.replacements.delete(systemId)\n    })\n    return await completion.promise\n  }\n\n  status(): DappEngineStatus | undefined {\n    if (this.configuration === undefined || this.engineInstanceId === undefined || this.hostSessionId === undefined) return\n    for (const record of this.records) {\n      if (record.launch !== undefined && !record.failed && !record.stopped && !record.retiring) {\n        try {\n          this.captureStatus(record)\n        } catch (cause) {\n          this.failSystem(record, cause, 'engine.system-status-invalid')\n        }\n      }\n    }\n    const systems = this.records.map(record => ({ declaration: record.declaration, status: ownedEngineSystemStatus(record) }))\n    return DappEngineStatusZod.parse({\n      schema: DappEngineStatusSchema,\n      schemaVersion: 1,\n      dappId: this.configuration.dappId,\n      engineInstanceId: this.engineInstanceId,\n      hostSessionId: this.hostSessionId,\n      phase: this.phase,\n      ...summarizeDappEngineSystems(this.phase, systems),\n      systems,\n    })\n  }\n\n  stop(): Promise<void> {\n    if (this.stopPromise !== undefined) return this.stopPromise\n    const completion = this.stopCompletion\n    this.stopPromise = completion.promise\n    this.stopRequested = true\n    if (!this.failed) this.phase = 'stopping'\n    this.requestStops()\n    void this.finishStop().then(completion.resolve, completion.reject)\n    return this.stopPromise\n  }\n\n  async whenReady(): Promise<DappEngineSession> {\n    const outcome = await this.outcome\n    if (outcome.outcome === 'ready') return outcome.session\n    throw new DappEngineLifecycleError(\n      outcome.outcome === 'stopped' ? 'engine.stopped' : 'engine.failed',\n      outcome.outcome === 'failed' ? outcome.cause : undefined,\n    )\n  }\n\n  whenStopped(): Promise<void> {\n    return this.stopCompletion.promise\n  }\n\n  whenTerminal(): Promise<never> {\n    return this.terminal.promise\n  }\n\n  private async awaitSystem(record: OwnedEngineSystem): Promise<void> {\n    try {\n      const session = await record.launch!.whenReady()\n      record.session = session\n      if (this.stopRequested || this.failed) {\n        await this.stopSystem(record)\n        return\n      }\n      this.captureStatus(record)\n      if (!record.last.ready) throw new DappEngineLifecycleError('engine.system-not-ready')\n      void this.watchTerminal(record, session)\n    } catch (cause) {\n      if (!(cause instanceof DappLaunchStoppedError && (this.stopRequested || this.failed))) {\n        this.failSystem(record, cause, 'engine.system-boot-failed')\n      }\n    }\n  }\n\n  private captureStatus(record: OwnedEngineSystem): void {\n    const source = record.session?.status() ?? record.launch!.status()\n    const parsed = DappEngineSystemStatusZod.parse({ declaration: record.declaration, status: source }).status\n    const prior = record.last\n    if (parsed.dappId !== prior.dappId || parsed.hostSessionId !== prior.hostSessionId || parsed.launchId !== prior.launchId\n      || (prior.planId !== undefined && parsed.planId !== prior.planId)\n      || (prior.systemInstanceId !== undefined && parsed.systemInstanceId !== prior.systemInstanceId)\n      || (parsed.systemInstanceId !== undefined && prior.systemInstanceId !== parsed.systemInstanceId && this.usedIncarnations.has(parsed.systemInstanceId))) {\n      throw new DappEngineLifecycleError('engine.system-identity-changed')\n    }\n    if (parsed.health === 'failed' || parsed.phase === 'failed') throw new DappEngineLifecycleError('engine.system-failed')\n    if (parsed.systemInstanceId !== undefined) this.usedIncarnations.add(parsed.systemInstanceId)\n    record.last = parsed\n  }\n\n  private async cleanup(): Promise<void> {\n    await Promise.all(this.records.map(async record => await this.stopSystem(record)))\n  }\n\n  private failEngine(cause: unknown): void {\n    if (!this.failed) {\n      this.failed = true\n      this.phase = 'failed'\n      this.terminal.reject(new DappEngineLifecycleError('engine.failed', cause))\n    }\n    this.requestStops()\n  }\n\n  private failSystem(record: OwnedEngineSystem, cause: unknown, code: string): void {\n    const error = new DappEngineLifecycleError(code, cause, record.declaration.systemId)\n    this.errors.push(error)\n    record.failed = true\n    if (record.declaration.failurePolicy === 'required') this.failEngine(error)\n    else void this.stopSystem(record)\n  }\n\n  private failureCause(): unknown {\n    return this.errors.length === 1 ? this.errors[0] : new AggregateError([...this.errors], 'Engine lifecycle failed')\n  }\n\n  private async finishStop(): Promise<void> {\n    await this.outcome\n    await Promise.allSettled(this.replacements.values())\n    await this.cleanup()\n    this.phase = this.errors.length > 0 || this.failed ? 'failed' : 'stopped'\n    if (this.errors.length > 0) throw new AggregateError([...this.errors], 'Engine did not stop without lifecycle failures')\n  }\n\n  private initialize(): void {\n    const configuration = DappEngineConfigurationZod.parse(this.options.configuration)\n    const engineInstanceId = IdentifierZod.parse(this.options.engineInstanceId)\n    const hostSessionId = IdentifierZod.parse(this.options.hostSessionId)\n    const launchers = new Map<string, DappEngineSystemLauncher>()\n    const launchIds = new Set<string>()\n    for (const launcher of this.options.systems) {\n      const systemId = IdentifierZod.parse(launcher.systemId)\n      const launchId = IdentifierZod.parse(launcher.launchId)\n      if (launchers.has(systemId) || launchIds.has(launchId) || typeof launcher.launch !== 'function') {\n        throw new DappEngineLifecycleError('engine.launcher-invalid')\n      }\n      launchers.set(systemId, {\n        systemId, launchId, launch: launcher.launch.bind(launcher),\n      })\n      launchIds.add(launchId)\n    }\n    if (launchers.size !== configuration.systems.length || configuration.systems.some(system => !launchers.has(system.systemId))) {\n      throw new DappEngineLifecycleError('engine.launcher-coverage-invalid')\n    }\n    this.configuration = configuration\n    this.engineInstanceId = engineInstanceId\n    this.hostSessionId = hostSessionId\n    for (const declaration of configuration.systems) {\n      const launcher = launchers.get(declaration.systemId)!\n      this.usedLaunches.add(launcher.launchId)\n      this.records.push(createOwnedEngineSystem(declaration, launcher, configuration.dappId, hostSessionId))\n    }\n  }\n\n  private async performReplacement(\n    previous: OwnedEngineSystem,\n    profileId: string,\n    launcher: DappEngineSystemLauncher,\n  ): Promise<DappEngineSystemReference> {\n    await this.stopSystem(previous)\n    if (previous.cleanupFailed || previous.failed) {\n      if (!previous.failed) this.failSystem(previous, this.failureCause(), 'engine.replacement-cleanup-failed')\n      throw new DappEngineLifecycleError('engine.replacement-failed', this.failureCause(), launcher.systemId)\n    }\n    if (this.stopRequested || this.failed) throw new DappEngineLifecycleError('engine.stopped')\n    const replacement = createOwnedEngineSystem({ ...previous.declaration, profileId }, launcher, this.configuration!.dappId, this.hostSessionId!)\n    const index = this.records.indexOf(previous)\n    this.records[index] = replacement\n    this.configuration!.systems[index] = replacement.declaration\n    await this.startSystem(replacement)\n    if (this.stopRequested || this.failed || replacement.failed) {\n      await this.stopSystem(replacement)\n      throw new DappEngineLifecycleError(\n        this.stopRequested && !replacement.failed ? 'engine.stopped' : 'engine.replacement-failed',\n        replacement.failed ? this.failureCause() : undefined,\n        launcher.systemId,\n      )\n    }\n    const checked = validateDappEngineSystemReplacement(\n      { declaration: previous.declaration, status: ownedEngineSystemStatus(previous) },\n      { declaration: replacement.declaration, status: ownedEngineSystemStatus(replacement) },\n    )\n    if (!checked.success) {\n      this.failSystem(replacement, checked.issue, 'engine.replacement-invalid')\n      await this.stopSystem(replacement)\n      throw new DappEngineLifecycleError('engine.replacement-invalid', this.failureCause(), launcher.systemId)\n    }\n    return Object.freeze({\n      engineInstanceId: this.engineInstanceId!, systemId: launcher.systemId, systemInstanceId: replacement.last.systemInstanceId!,\n    })\n  }\n\n  private requestStops(): void {\n    for (const record of this.records) void this.stopSystem(record)\n  }\n\n  private async runBoot(): Promise<DappEngineLaunchResult> {\n    try {\n      if (this.stopRequested) {\n        this.phase = 'stopped'\n        return { outcome: 'stopped' }\n      }\n      this.initialize()\n      const pending: Promise<void>[] = []\n      for (const record of this.records) {\n        if (this.stopRequested || this.failed) break\n        pending.push(this.startSystem(record))\n      }\n      await Promise.all(pending)\n      // An isolated boot failure must finish its cleanup before readiness is reported.\n      await Promise.all(this.records.filter(record => record.failed).map(async record => await this.stopSystem(record)))\n      if (!this.stopRequested && !this.failed) {\n        this.phase = 'running'\n        const status = this.status()\n        if (status?.ready === true) return { outcome: 'ready', session: this.sessionFacade() }\n        if (!this.failed) throw new DappEngineLifecycleError('engine.not-ready')\n      }\n    } catch (cause) {\n      this.errors.push(cause)\n      this.failEngine(cause)\n    }\n    await this.cleanup()\n    if (this.failed || this.errors.length > 0) {\n      this.phase = 'failed'\n      return { outcome: 'failed', cause: this.failureCause() }\n    }\n    this.phase = 'stopped'\n    return { outcome: 'stopped' }\n  }\n\n  private sessionFacade(): DappEngineSession {\n    return Object.freeze({\n      bindSystemWork: (reference: DappEngineSystemReference, create: () => DappSessionWorkOwner) => this.bindSystemWork(reference, create),\n      replaceSystem: (options: ReplaceDappEngineSystemOptions) => this.replaceSystem(options),\n      status: () => this.status()!,\n      stop: () => this.stop(),\n      whenStopped: () => this.whenStopped(),\n      whenTerminal: () => this.whenTerminal(),\n    })\n  }\n\n  private startSystem(record: OwnedEngineSystem): Promise<void> {\n    try {\n      record.launch = record.launcher.launch(Object.freeze({\n        dappId: this.configuration!.dappId,\n        declaration: record.declaration,\n        engineInstanceId: this.engineInstanceId!,\n        hostSessionId: this.hostSessionId!,\n        launchId: record.launcher.launchId,\n      }))\n      record.stopped = false\n      this.captureStatus(record)\n      const ready = this.awaitSystem(record)\n      if (this.stopRequested || this.failed) void this.stopSystem(record)\n      return ready\n    } catch (cause) {\n      this.failSystem(record, cause, 'engine.system-launch-failed')\n      return Promise.resolve()\n    }\n  }\n\n  private stopSystem(record: OwnedEngineSystem): Promise<void> {\n    if (record.stopPromise !== undefined) return record.stopPromise\n    if (record.launch === undefined) {\n      record.stopped = true\n      return Promise.resolve()\n    }\n    const completion = Promise.withResolvers<void>()\n    record.stopPromise = completion.promise\n    void (async () => {\n      try {\n        await record.launch!.stop()\n      } catch (cause) {\n        record.cleanupFailed = true\n        this.errors.push(new DappEngineLifecycleError('engine.system-cleanup-failed', cause, record.declaration.systemId))\n      } finally {\n        record.stopped = true\n        completion.resolve()\n      }\n    })()\n    return record.stopPromise\n  }\n\n  private async watchTerminal(record: OwnedEngineSystem, session: DappSession<unknown>): Promise<void> {\n    try {\n      await session.whenTerminal()\n      throw new DappEngineLifecycleError('engine.system-terminal-resolved')\n    } catch (cause) {\n      if (!record.stopped) this.failSystem(record, cause, 'engine.system-terminal-failed')\n    }\n  }\n}\n\nexport function launchDappEngine(options: LaunchDappEngineOptions): DappEngineLaunch {\n  const instance = new DappEngineInstance(options)\n  return Object.freeze({\n    outcome: instance.outcome,\n    status: () => instance.status(),\n    stop: () => instance.stop(),\n    whenReady: async () => await instance.whenReady(),\n    whenStopped: () => instance.whenStopped(),\n    whenTerminal: () => instance.whenTerminal(),\n  })\n}\n", "import type { DappSessionWorkBinding, DappSessionWorkOwner } from './dappSession.ts'\n\ninterface OwnedWork {\n  readonly available: PromiseWithResolvers<void>\n  completion?: PromiseWithResolvers<void>\n  readonly errors: unknown[]\n  owner?: DappSessionWorkOwner\n}\n\n/** Internal lifecycle composition; app requests stay in their existing owners. */\nexport class DappSessionWorkGroup {\n  private readonly entries = new Set<OwnedWork>()\n  private readonly errors: unknown[] = []\n  private isClosed = false\n\n  bind(create: () => DappSessionWorkOwner): DappSessionWorkBinding {\n    if (this.isClosed) throw new Error('dapp-session.work-closed')\n    const entry: OwnedWork = { available: Promise.withResolvers<void>(), errors: [] }\n    this.entries.add(entry)\n    try {\n      entry.owner = create()\n    } catch (cause) {\n      this.retain(entry, cause)\n      throw cause\n    } finally {\n      if (entry.completion !== undefined && entry.owner !== undefined) this.closeOwner(entry)\n      entry.available.resolve()\n    }\n    return Object.freeze({ close: () => this.closeEntry(entry) })\n  }\n\n  close(): void {\n    if (this.isClosed) return\n    this.isClosed = true\n    for (const entry of this.entries) void this.closeEntry(entry)\n  }\n\n  async drain(): Promise<readonly unknown[]> {\n    this.close()\n    await Promise.allSettled([...this.entries].map(entry => this.closeEntry(entry)))\n    return [...this.errors]\n  }\n\n  private closeEntry(entry: OwnedWork): Promise<void> {\n    if (entry.completion !== undefined) return entry.completion.promise\n    const completion = Promise.withResolvers<void>()\n    entry.completion = completion\n    void completion.promise.catch(() => { /* Retained for binding and session owners. */ })\n    if (entry.owner !== undefined) this.closeOwner(entry)\n    void (async () => {\n      if (entry.owner === undefined) await entry.available.promise\n      try {\n        await entry.owner?.drain()\n      } catch (cause) {\n        this.retain(entry, cause)\n      }\n      this.entries.delete(entry)\n      if (entry.errors.length > 0) completion.reject(new AggregateError([...entry.errors], 'Dapp session work did not close cleanly'))\n      else completion.resolve()\n    })()\n    return completion.promise\n  }\n\n  private closeOwner(entry: OwnedWork): void {\n    try {\n      entry.owner!.close()\n    } catch (cause) {\n      this.retain(entry, cause)\n    }\n  }\n\n  private retain(entry: OwnedWork, cause: unknown): void {\n    entry.errors.push(cause)\n    this.errors.push(cause)\n  }\n}\n", "import { DappSessionWorkGroup } from './dappSessionWork.ts'\nimport type { DappLifecyclePhase } from './lifecycle.ts'\nimport { transitionDappLifecycle } from './lifecycle.ts'\nimport type {\n  DappStatus,\n  DappWriteCapability,\n  DappWriteState,\n} from './status.ts'\nimport { DappStatusZod } from './status.ts'\n\nexport const DappSessionStatusErrorCode = {\n  identityChanged: 'dapp-session.status-identity-changed',\n  notReady: 'dapp-session.status-not-ready',\n} as const\n\nexport type DappSessionStatusErrorCode = typeof DappSessionStatusErrorCode[keyof typeof DappSessionStatusErrorCode]\n\n/** A ready actor/provider system whose ownership is transferred to the dApp session. */\nexport interface DappOwnedSystemSession {\n  stop(): Promise<void>\n  whenTerminal(): Promise<never>\n}\n\n/** Dapp-kit-owned request/effect work that must close and drain before actors stop. */\nexport interface DappSessionWorkOwner {\n  close(): void\n  drain(): Promise<void>\n}\n\nexport interface DappSessionWorkBinding {\n  close(): Promise<void>\n}\n\nexport interface CreateDappSessionOptions<TPorts> {\n  readonly ports: TPorts\n  readonly readStatus: () => DappStatus\n  readonly system: DappOwnedSystemSession\n  readonly work?: DappSessionWorkOwner\n}\n\nexport interface DappSession<TPorts = Readonly<Record<string, unknown>>> {\n  readonly ports: TPorts\n  bindWork(create: () => DappSessionWorkOwner): DappSessionWorkBinding\n  status(): DappStatus\n  stop(): Promise<void>\n  whenTerminal(): Promise<never>\n}\n\ninterface DappSessionIdentity {\n  readonly dappId: string\n  readonly hostSessionId: string\n  readonly launchId: string\n  readonly planId: string\n  readonly systemInstanceId: string\n}\n\nexport class DappSessionStatusError extends Error {\n  readonly code: DappSessionStatusErrorCode\n\n  constructor(code: DappSessionStatusErrorCode, message: string) {\n    super(message)\n    this.name = 'DappSessionStatusError'\n    this.code = code\n  }\n}\n\nfunction readyStatus(readStatus: () => DappStatus): DappStatus & Required<Pick<DappStatus, 'planId' | 'systemInstanceId'>> {\n  const status = DappStatusZod.parse(readStatus())\n  if (status.phase !== 'ready' || !status.live || status.planId === undefined\n    || status.systemInstanceId === undefined) {\n    throw new DappSessionStatusError(\n      DappSessionStatusErrorCode.notReady,\n      'A dApp session requires a live ready status with plan and system incarnation IDs',\n    )\n  }\n  return status as DappStatus & Required<Pick<DappStatus, 'planId' | 'systemInstanceId'>>\n}\n\nfunction statusIdentity(status: ReturnType<typeof readyStatus>): DappSessionIdentity {\n  return {\n    dappId: status.dappId,\n    hostSessionId: status.hostSessionId,\n    launchId: status.launchId,\n    planId: status.planId,\n    systemInstanceId: status.systemInstanceId,\n  }\n}\n\nfunction writeState(capabilities: readonly DappWriteCapability[]): DappWriteState {\n  if (capabilities.length === 0) return 'not-applicable'\n  const writable = capabilities.filter(capability => capability.writable).length\n  return writable === 0 ? 'none' : writable === capabilities.length ? 'full' : 'partial'\n}\n\nfunction blockedWriteCapabilities(\n  capabilities: readonly DappWriteCapability[],\n  phase: DappLifecyclePhase,\n): DappWriteCapability[] {\n  if (phase === 'ready') return [...capabilities]\n  return capabilities.map(capability => ({\n    ...capability,\n    reasonCodes: [`dapp-session.${phase}`],\n    writable: false,\n  }))\n}\n\nfunction assertIdentity(identity: DappSessionIdentity, status: ReturnType<typeof readyStatus>): void {\n  for (const field of Object.keys(identity) as (keyof DappSessionIdentity)[]) {\n    if (status[field] !== identity[field]) {\n      throw new DappSessionStatusError(\n        DappSessionStatusErrorCode.identityChanged,\n        `Dapp session status changed immutable ${field}`,\n      )\n    }\n  }\n}\n\nclass DappSessionInstance<TPorts> {\n  private readonly identity: DappSessionIdentity\n  private phase: DappLifecyclePhase = 'ready'\n  private readonly readStatus: () => DappStatus\n  private stopPromise?: Promise<void>\n  private readonly system: DappOwnedSystemSession\n  private readonly terminalPromise: Promise<never>\n  private readonly work = new DappSessionWorkGroup()\n\n  constructor(options: CreateDappSessionOptions<TPorts>) {\n    const status = readyStatus(options.readStatus)\n    this.identity = statusIdentity(status)\n    this.readStatus = options.readStatus\n    this.system = options.system\n    if (options.work !== undefined) this.work.bind(() => options.work!)\n    this.terminalPromise = this.watchTerminal()\n    void this.terminalPromise.catch(() => {\n      // The host decides when to join the source-preserving terminal signal.\n    })\n  }\n\n  bindWork(create: () => DappSessionWorkOwner): DappSessionWorkBinding {\n    if (!this.status().ready) throw new DappSessionStatusError(DappSessionStatusErrorCode.notReady, 'A work binding requires a ready session')\n    return this.work.bind(create)\n  }\n\n  status(): DappStatus {\n    const source = readyStatus(this.readStatus)\n    assertIdentity(this.identity, source)\n    const writeCapabilities = blockedWriteCapabilities(source.writeCapabilities, this.phase)\n    return DappStatusZod.parse({\n      ...source,\n      health: this.phase === 'failed' ? 'failed' : source.health,\n      live: this.phase !== 'stopped',\n      phase: this.phase,\n      ready: this.phase === 'ready',\n      writeCapabilities,\n      writeState: writeState(writeCapabilities),\n    })\n  }\n\n  stop(): Promise<void> {\n    if (this.stopPromise !== undefined) return this.stopPromise\n    const completion = Promise.withResolvers<void>()\n    this.stopPromise = completion.promise\n    void this.stopOnce().then(completion.resolve, completion.reject)\n    return this.stopPromise\n  }\n\n  whenTerminal(): Promise<never> {\n    return this.terminalPromise\n  }\n\n  private async stopOnce(): Promise<void> {\n    const errors: unknown[] = []\n    this.transition('stop-requested')\n    this.work.close()\n    errors.push(...await this.work.drain())\n    if (this.phase === 'draining') this.transition('drain-complete')\n    else if (this.phase === 'failed') this.transition('stop-requested')\n    try {\n      await this.system.stop()\n    } catch (error) {\n      errors.push(error)\n    }\n    this.transition('teardown-complete')\n    if (errors.length > 0) throw new AggregateError(errors, 'Dapp session did not stop cleanly')\n  }\n\n  private transition(event: Parameters<typeof transitionDappLifecycle>[1]): void {\n    const result = transitionDappLifecycle(this.phase, event)\n    if (!result.success) {\n      throw new Error(`Invalid dApp session transition ${this.phase} -> ${event}`)\n    }\n    this.phase = result.value.to\n  }\n\n  private async watchTerminal(): Promise<never> {\n    try {\n      await this.system.whenTerminal()\n      throw new Error('Owned dApp system terminal signal resolved without an error')\n    } catch (error) {\n      if (this.phase === 'ready' || this.phase === 'draining') {\n        this.transition('required-invariant-failed')\n      }\n      throw error\n    }\n  }\n}\n\nexport function createDappSession<TPorts>(options: CreateDappSessionOptions<TPorts>): DappSession<TPorts> {\n  const instance = new DappSessionInstance(options)\n  return Object.freeze({\n    ports: options.ports,\n    bindWork: (create: () => DappSessionWorkOwner) => instance.bindWork(create),\n    status: () => instance.status(),\n    stop: () => instance.stop(),\n    whenTerminal: () => instance.whenTerminal(),\n  })\n}\n", "import {\n  bytesToHex, hexToBytes, utf8ToBytes,\n} from '@noble/hashes/utils.js'\nimport type {\n  Payload, ReadArchivistFunctions, WriteArchivistFunctions,\n} from '@xyo-network/sdk'\nimport {\n  asSchema, isAnyPayload, PayloadBuilder,\n} from '@xyo-network/sdk'\nimport { z } from 'zod'\n\nimport { canonicalizeIJson } from './canonicalDocument.ts'\nimport { HashZod, IdentifierZod } from './identifier.ts'\nimport type {\n  ObjectStoreGetResult,\n  ObjectStoreListPage,\n  ObjectStoreListPageOptions,\n  ObjectStoreMetadata,\n  ObjectStorePutOptions,\n  ObjectStorePutResult,\n  ObjectStoreReader,\n  ObjectStoreWriter,\n} from './objectStore.ts'\nimport { normalizeObjectStoreKey } from './objectStore.ts'\nimport { decodeUtf8, hashProjectionPublicationBytes } from './projectionPublication.ts'\nimport { parseStrictJsonText } from './strictJson.ts'\n\nexport const DatalakeObjectPayloadSchema = asSchema('network.xyo.dapp.object.bytes', true)\nexport const DatalakeObjectReferenceSchema = asSchema('network.xyo.dapp.object.reference', true)\nexport const DefaultDatalakeObjectMaximumBytes = 16 * 1024 * 1024\n\nconst MetadataZod = z.strictObject({\n  cacheControl: z.string().max(1024).optional(),\n  contentEncoding: z.string().max(256).optional(),\n  contentType: z.string().max(256).optional(),\n  metadata: z.record(z.string().min(1).max(128), z.string().max(4096))\n    .refine(value => Object.keys(value).length <= 32).optional(),\n})\n\nexport const DatalakeObjectPayloadZod = z.strictObject({\n  schema: z.literal(DatalakeObjectPayloadSchema),\n  schemaVersion: z.literal(1),\n  storeId: IdentifierZod,\n  encoding: z.literal('hex'),\n  bodyHex: z.string().regex(/^(?:[0-9a-f]{2})*$/u),\n  contentHash: HashZod,\n  size: z.number().int().nonnegative(),\n})\n\nexport type DatalakeObjectPayload = z.infer<typeof DatalakeObjectPayloadZod>\n\nexport const DatalakeObjectReferenceZod = z.strictObject({\n  schema: z.literal(DatalakeObjectReferenceSchema),\n  schemaVersion: z.literal(1),\n  storeId: IdentifierZod,\n  payloadHash: HashZod,\n  contentHash: HashZod,\n  size: z.number().int().nonnegative(),\n  metadata: MetadataZod,\n})\n\nexport type DatalakeObjectReference = z.infer<typeof DatalakeObjectReferenceZod>\nexport type DatalakeObjectHash = Awaited<ReturnType<typeof PayloadBuilder.hash>>\nexport type DatalakeObjectDataReader = Pick<ReadArchivistFunctions<Payload, DatalakeObjectHash>, 'get'>\nexport interface DatalakeObjectDataStore extends DatalakeObjectDataReader,\n  Pick<WriteArchivistFunctions<Payload, Payload, Payload, DatalakeObjectHash>, 'insert'> {}\n\nexport interface DatalakeObjectReaderOptions {\n  /** Exclusive logical-key namespace. Writers require origin-consistent reads;\n   * public readers may use the publication's declared cache policy. */\n  readonly controlStore: ObjectStoreReader\n  /** The app's own lake; an anonymous viewer is sufficient for public data. */\n  readonly dataLake: DatalakeObjectDataReader\n  readonly maximumListKeys?: number\n  readonly maximumObjectBytes?: number\n  readonly maximumReferenceBytes?: number\n  /** Stable logical identity, independent of provider hostname or physical bucket. */\n  readonly storeId: string\n}\n\nexport interface DatalakeObjectStoreOptions extends DatalakeObjectReaderOptions {\n  /** Must provide real atomic conditions and non-reused version tokens. */\n  readonly controlStore: ObjectStoreWriter\n  readonly dataLake: DatalakeObjectDataStore\n}\n\nfunction positive(value: number, label: string): number {\n  if (!Number.isSafeInteger(value) || value <= 0) throw new TypeError(`${label} must be a positive safe integer`)\n  return value\n}\n\n/** A language-neutral binary envelope. Hex is canonical lowercase and costs two\n * characters per original byte; transport limits must include the envelope. */\nexport function encodeDatalakeObjectPayload(\n  body: string | Uint8Array,\n  storeId: string,\n  maximumObjectBytes = DefaultDatalakeObjectMaximumBytes,\n): DatalakeObjectPayload {\n  if (typeof body !== 'string' && !(body instanceof Uint8Array)) throw new TypeError('datalake object body must be UTF-8 text or bytes')\n  const limit = positive(maximumObjectBytes, 'maximumObjectBytes')\n  const identity = IdentifierZod.parse(storeId)\n  const bytes = typeof body === 'string' ? utf8ToBytes(body) : new Uint8Array(body)\n  if (bytes.byteLength > limit) throw new RangeError('datalake object exceeds maximumObjectBytes')\n  return {\n    schema: DatalakeObjectPayloadSchema,\n    schemaVersion: 1,\n    storeId: identity,\n    encoding: 'hex',\n    bodyHex: bytesToHex(bytes),\n    contentHash: hashProjectionPublicationBytes(bytes),\n    size: bytes.byteLength,\n  }\n}\n\nexport function decodeDatalakeObjectPayload(\n  value: unknown,\n  storeId: string,\n  maximumObjectBytes = DefaultDatalakeObjectMaximumBytes,\n): Uint8Array {\n  if (!isAnyPayload(value)) throw new TypeError('datalake object is not a payload')\n  const limit = positive(maximumObjectBytes, 'maximumObjectBytes')\n  // Archivist storage metadata is outside content identity. All other fields\n  // still pass through the closed app schema below.\n  const fields = PayloadBuilder.hashableFields(value)\n  if (typeof fields.bodyHex !== 'string' || fields.bodyHex.length / 2 > limit) {\n    throw new RangeError('datalake object exceeds maximumObjectBytes or has no encoded body')\n  }\n  const payload = DatalakeObjectPayloadZod.parse(fields)\n  if (payload.storeId !== storeId) throw new TypeError('datalake object belongs to a different logical store')\n  const body = hexToBytes(payload.bodyHex)\n  if (body.byteLength !== payload.size || hashProjectionPublicationBytes(body) !== payload.contentHash) {\n    throw new TypeError('datalake object bytes do not match their declared size and hash')\n  }\n  return body\n}\n\nfunction referenceBytes(reference: DatalakeObjectReference, maximum: number): Uint8Array {\n  const encoded = utf8ToBytes(`${canonicalizeIJson(reference)}\\n`)\n  if (encoded.byteLength > maximum) throw new RangeError('datalake reference exceeds maximumReferenceBytes')\n  return encoded\n}\n\nfunction version(metadata: ObjectStoreMetadata): string {\n  if (typeof metadata.etag !== 'string' || metadata.etag.length === 0) {\n    throw new TypeError('atomic control store must return an opaque version token')\n  }\n  return metadata.etag\n}\n\n/** Keyed reads over immutable datalake bodies and a separately qualified atomic\n * reference store. No provider, wallet, network client or lifecycle is acquired. */\nexport class DatalakeObjectReader implements ObjectStoreReader {\n  readonly storeId: string\n\n  protected readonly controlStore: ObjectStoreReader\n  protected readonly dataLake: DatalakeObjectDataReader\n  protected readonly maximumListKeys: number\n  protected readonly maximumObjectBytes: number\n  protected readonly maximumReferenceBytes: number\n\n  constructor(options: DatalakeObjectReaderOptions) {\n    this.storeId = IdentifierZod.parse(options.storeId)\n    this.maximumObjectBytes = positive(options.maximumObjectBytes ?? DefaultDatalakeObjectMaximumBytes, 'maximumObjectBytes')\n    this.maximumReferenceBytes = positive(options.maximumReferenceBytes ?? 64 * 1024, 'maximumReferenceBytes')\n    this.maximumListKeys = positive(options.maximumListKeys ?? 10_000, 'maximumListKeys')\n    this.controlStore = options.controlStore\n    this.dataLake = options.dataLake\n  }\n\n  async get(key: string): Promise<Uint8Array | undefined> {\n    return (await this.getWithMetadata(key))?.body\n  }\n\n  async getWithMetadata(key: string): Promise<ObjectStoreGetResult | undefined> {\n    const resolved = await this.readReference(key)\n    if (resolved === undefined) return\n    const { reference, metadata } = resolved\n    const body = await this.readBody(reference)\n    return { body, metadata }\n  }\n\n  async list(prefix = ''): Promise<readonly string[]> {\n    normalizeObjectStoreKey(prefix, true)\n    const keys: string[] = []\n    const tokens = new Set<string>()\n    let pages = 0\n    let continuationToken: string | undefined\n    do {\n      // Empty pages are possible during concurrent deletion. Bound requests as\n      // well as keys so distinct continuation tokens cannot keep a scan alive.\n      if (++pages > this.maximumListKeys + 1) throw new RangeError('datalake listing exceeds page limit; use listPage')\n      const page = await this.listPage({\n        prefix, continuationToken, maximumKeys: Math.min(1000, this.maximumListKeys),\n      })\n      keys.push(...page.keys)\n      if (keys.length > this.maximumListKeys) throw new RangeError('datalake listing exceeds maximumListKeys; use listPage')\n      continuationToken = page.continuationToken\n      if (continuationToken !== undefined) {\n        if (tokens.has(continuationToken)) throw new TypeError('control store repeated its continuation token')\n        tokens.add(continuationToken)\n      }\n    } while (continuationToken !== undefined)\n    const uniqueKeys = new Set(keys)\n    if (uniqueKeys.size !== keys.length) throw new TypeError('control listing repeated a key')\n    return keys\n  }\n\n  async listPage(options: ObjectStoreListPageOptions = {}): Promise<ObjectStoreListPage> {\n    const prefix = normalizeObjectStoreKey(options.prefix ?? '', true)\n    const maximumKeys = positive(options.maximumKeys ?? 1000, 'maximumKeys')\n    if (maximumKeys > this.maximumListKeys) throw new RangeError('page exceeds maximumListKeys')\n    const page = await this.controlStore.listPage({\n      ...options, prefix, maximumKeys,\n    })\n    const uniqueKeys = new Set(page.keys)\n    if (page.keys.length > maximumKeys || uniqueKeys.size !== page.keys.length\n      || page.keys.some(key => normalizeObjectStoreKey(key) !== key || !key.startsWith(prefix))) {\n      throw new TypeError('control store returned an invalid key page')\n    }\n    if ((page.continuationToken !== undefined && (typeof page.continuationToken !== 'string' || page.continuationToken.length === 0))\n      || page.isTruncated !== (page.continuationToken !== undefined)) {\n      throw new TypeError('control store returned an inconsistent continuation')\n    }\n    return { ...page, keys: [...page.keys] }\n  }\n\n  async stat(key: string): Promise<ObjectStoreMetadata | undefined> {\n    return (await this.readReference(key))?.metadata\n  }\n\n  protected async readBody(reference: DatalakeObjectReference): Promise<Uint8Array> {\n    const found = await this.dataLake.get([reference.payloadHash as DatalakeObjectHash])\n    if (found.length !== 1 || !isAnyPayload(found[0])) throw new TypeError('referenced datalake payload is unavailable or ambiguous')\n    const payload = found[0]\n    const body = decodeDatalakeObjectPayload(payload, this.storeId, this.maximumObjectBytes)\n    if (await PayloadBuilder.hash(payload) !== reference.payloadHash\n      || body.byteLength !== reference.size || hashProjectionPublicationBytes(body) !== reference.contentHash) {\n      throw new TypeError('referenced datalake payload failed content verification')\n    }\n    return body\n  }\n\n  private async readReference(key: string) {\n    normalizeObjectStoreKey(key)\n    const value = await this.controlStore.getWithMetadata(key)\n    if (value === undefined) return\n    if (value.body.byteLength > this.maximumReferenceBytes) throw new RangeError('datalake reference exceeds maximumReferenceBytes')\n    const reference = DatalakeObjectReferenceZod.parse(parseStrictJsonText(decodeUtf8(value.body)))\n    if (reference.storeId !== this.storeId) throw new TypeError('datalake reference belongs to a different logical store')\n    if (reference.size > this.maximumObjectBytes) throw new RangeError('datalake reference exceeds maximumObjectBytes')\n    const metadata: ObjectStoreMetadata = {\n      ...reference.metadata,\n      contentLength: reference.size,\n      etag: version(value.metadata),\n      ...(value.metadata.lastModified === undefined ? {} : { lastModified: value.metadata.lastModified }),\n    }\n    return { reference, metadata }\n  }\n}\n\n/** Publishes verified immutable bytes before conditionally advancing their keyed\n * reference. A failed/ambiguous reference write never deletes the retained body. */\nexport class DatalakeObjectStore extends DatalakeObjectReader implements ObjectStoreWriter {\n  private readonly controlWriter: ObjectStoreWriter\n  private readonly dataWriter: DatalakeObjectDataStore\n\n  constructor(options: DatalakeObjectStoreOptions) {\n    super(options)\n    this.controlWriter = options.controlStore\n    this.dataWriter = options.dataLake\n  }\n\n  /** Removes only the reference. Content retention/garbage collection is a\n   * separate operator policy and cannot erase a generation's retained bodies. */\n  async delete(key: string): Promise<void> {\n    normalizeObjectStoreKey(key)\n    await this.controlWriter.delete(key)\n  }\n\n  async put(key: string, body: string | Uint8Array, options: ObjectStorePutOptions = {}): Promise<ObjectStorePutResult> {\n    normalizeObjectStoreKey(key)\n    if (options.ifNotExists !== undefined && typeof options.ifNotExists !== 'boolean') throw new TypeError('ifNotExists must be boolean')\n    if (options.ifMatch !== undefined && (typeof options.ifMatch !== 'string' || options.ifMatch.length === 0)) {\n      throw new TypeError('ifMatch requires a nonempty version token')\n    }\n    if (options.ifNotExists && options.ifMatch !== undefined) throw new TypeError('write conditions are mutually exclusive')\n    const conditions = {\n      ...(options.ifMatch === undefined ? {} : { ifMatch: options.ifMatch }),\n      ...(options.ifNotExists === undefined ? {} : { ifNotExists: options.ifNotExists }),\n    }\n    const metadata = MetadataZod.parse({\n      ...(options.cacheControl === undefined ? {} : { cacheControl: options.cacheControl }),\n      ...(options.contentEncoding === undefined ? {} : { contentEncoding: options.contentEncoding }),\n      ...(options.contentType === undefined ? {} : { contentType: options.contentType }),\n      ...(options.metadata === undefined ? {} : { metadata: options.metadata }),\n    })\n    const payload = encodeDatalakeObjectPayload(body, this.storeId, this.maximumObjectBytes)\n    const reference: DatalakeObjectReference = {\n      schema: DatalakeObjectReferenceSchema,\n      schemaVersion: 1,\n      storeId: this.storeId,\n      payloadHash: await PayloadBuilder.hash(payload),\n      contentHash: payload.contentHash,\n      size: payload.size,\n      metadata,\n    }\n    const encodedReference = referenceBytes(reference, this.maximumReferenceBytes)\n    await this.dataWriter.insert([payload])\n    await this.readBody(reference)\n    const result = await this.controlWriter.put(key, encodedReference, {\n      ...conditions,\n      cacheControl: metadata.cacheControl ?? 'no-store',\n      contentType: 'application/json',\n    })\n    return { etag: version(result) }\n  }\n}\n", "export const ObjectStorePreconditionCode = {\n  ifMatchFailed: 'object-store.if-match-failed',\n  ifNotExistsFailed: 'object-store.if-not-exists-failed',\n} as const\n\nexport type ObjectStorePreconditionCode\n  = typeof ObjectStorePreconditionCode[keyof typeof ObjectStorePreconditionCode]\n\nexport class ObjectStorePreconditionError extends Error {\n  readonly code: ObjectStorePreconditionCode\n  readonly key: string\n\n  constructor(code: ObjectStorePreconditionCode, key: string, message: string) {\n    super(message)\n    this.name = 'ObjectStorePreconditionError'\n    this.code = code\n    this.key = key\n  }\n}\n\nexport interface ObjectStoreMetadata {\n  readonly cacheControl?: string\n  readonly contentEncoding?: string\n  readonly contentLength?: number\n  readonly contentType?: string\n  readonly etag?: string\n  readonly lastModified?: number\n  readonly metadata?: Readonly<Record<string, string>>\n}\n\nexport interface ObjectStoreGetResult {\n  readonly body: Uint8Array\n  readonly metadata: ObjectStoreMetadata\n}\n\nexport interface ObjectStorePutOptions {\n  readonly cacheControl?: string\n  readonly contentEncoding?: string\n  readonly contentType?: string\n  readonly ifMatch?: string\n  readonly ifNotExists?: boolean\n  readonly metadata?: Readonly<Record<string, string>>\n}\n\nexport interface ObjectStorePutResult {\n  readonly etag?: string\n}\n\nexport interface ObjectStoreListPageOptions {\n  readonly continuationToken?: string\n  readonly maximumKeys?: number\n  readonly prefix?: string\n}\n\nexport interface ObjectStoreListPage {\n  readonly continuationToken?: string\n  readonly isTruncated: boolean\n  readonly keys: readonly string[]\n}\n\nexport interface ObjectStoreReader {\n  get(key: string): Promise<Uint8Array | undefined>\n  getWithMetadata(key: string): Promise<ObjectStoreGetResult | undefined>\n  list(prefix?: string): Promise<readonly string[]>\n  listPage(options?: ObjectStoreListPageOptions): Promise<ObjectStoreListPage>\n  stat(key: string): Promise<ObjectStoreMetadata | undefined>\n}\n\nexport interface ObjectStoreWriter extends ObjectStoreReader {\n  delete(key: string): Promise<void>\n  put(key: string, body: string | Uint8Array, options?: ObjectStorePutOptions): Promise<ObjectStorePutResult>\n}\n\nexport interface ObjectStoreRoute {\n  readonly matches: (key: string) => boolean\n  readonly store: ObjectStoreWriter\n}\n\nexport function normalizeObjectStoreKey(value: string, allowEmpty = false): string {\n  if ((!allowEmpty && value === '') || value.startsWith('/') || value.includes('\\\\') || value.includes('\\0')) {\n    throw new TypeError('object-store key must be a repository-style relative path')\n  }\n  if (value === '') return ''\n  const segments = value.split('/')\n  if (segments.some(segment => segment === '' || segment === '.' || segment === '..')) {\n    throw new TypeError('object-store key contains an empty or traversal segment')\n  }\n  return segments.join('/')\n}\n\nfunction prefixedKey(prefix: string, key: string): string {\n  const normalized = normalizeObjectStoreKey(key, true)\n  return normalized === '' ? prefix : `${prefix}/${normalized}`\n}\n\nfunction relativeKey(prefix: string, key: string): string {\n  if (key === prefix) return ''\n  if (!key.startsWith(`${prefix}/`)) {\n    throw new TypeError(`object-store returned key outside prefix ${prefix}`)\n  }\n  return key.slice(prefix.length + 1)\n}\n\nfunction pageOffset(token: string | undefined, maximum: number): number {\n  if (token === undefined) return 0\n  const value = Number(token)\n  if (!Number.isSafeInteger(value) || value < 0 || value > maximum) {\n    throw new TypeError('object-store continuation token is invalid')\n  }\n  return value\n}\n\nfunction page(keys: readonly string[], options: ObjectStoreListPageOptions): ObjectStoreListPage {\n  const offset = pageOffset(options.continuationToken, keys.length)\n  const maximumKeys = options.maximumKeys ?? 1000\n  if (!Number.isSafeInteger(maximumKeys) || maximumKeys <= 0) {\n    throw new TypeError('maximumKeys must be a positive integer')\n  }\n  const selected = keys.slice(offset, offset + maximumKeys)\n  const next = offset + selected.length\n  return {\n    ...(next < keys.length && { continuationToken: String(next) }),\n    isTruncated: next < keys.length,\n    keys: selected,\n  }\n}\n\n/** Narrows one object store to a stable relative prefix without exposing its physical backend. */\nexport class PrefixedObjectStore implements ObjectStoreWriter {\n  private readonly prefix: string\n  private readonly store: ObjectStoreWriter\n\n  constructor(store: ObjectStoreWriter, prefix: string) {\n    this.prefix = normalizeObjectStoreKey(prefix)\n    this.store = store\n  }\n\n  async delete(key: string): Promise<void> {\n    await this.store.delete(prefixedKey(this.prefix, key))\n  }\n\n  async get(key: string): Promise<Uint8Array | undefined> {\n    return await this.store.get(prefixedKey(this.prefix, key))\n  }\n\n  async getWithMetadata(key: string): Promise<ObjectStoreGetResult | undefined> {\n    return await this.store.getWithMetadata(prefixedKey(this.prefix, key))\n  }\n\n  async list(prefix = ''): Promise<readonly string[]> {\n    return (await this.store.list(prefixedKey(this.prefix, prefix)))\n      .map(key => relativeKey(this.prefix, key))\n  }\n\n  async listPage(options: ObjectStoreListPageOptions = {}): Promise<ObjectStoreListPage> {\n    return page(await this.list(options.prefix), options)\n  }\n\n  async put(\n    key: string,\n    body: string | Uint8Array,\n    options?: ObjectStorePutOptions,\n  ): Promise<ObjectStorePutResult> {\n    return await this.store.put(prefixedKey(this.prefix, key), body, options)\n  }\n\n  async stat(key: string): Promise<ObjectStoreMetadata | undefined> {\n    return await this.store.stat(prefixedKey(this.prefix, key))\n  }\n}\n\n/** Routes selected keys to specialized stores while retaining one logical object-store surface. */\nexport class RoutedObjectStore implements ObjectStoreWriter {\n  private readonly primary: ObjectStoreWriter\n  private readonly routes: readonly ObjectStoreRoute[]\n\n  constructor(primary: ObjectStoreWriter, routes: readonly ObjectStoreRoute[]) {\n    this.primary = primary\n    this.routes = routes\n  }\n\n  async delete(key: string): Promise<void> {\n    await this.store(key).delete(key)\n  }\n\n  async get(key: string): Promise<Uint8Array | undefined> {\n    return await this.store(key).get(key)\n  }\n\n  async getWithMetadata(key: string): Promise<ObjectStoreGetResult | undefined> {\n    return await this.store(key).getWithMetadata(key)\n  }\n\n  async list(prefix = ''): Promise<readonly string[]> {\n    const values = await Promise.all([this.primary, ...this.routes.map(route => route.store)]\n      .map(async store => await store.list(prefix)))\n    return [...new Set(values.flat())].toSorted()\n  }\n\n  async listPage(options: ObjectStoreListPageOptions = {}): Promise<ObjectStoreListPage> {\n    return page(await this.list(options.prefix), options)\n  }\n\n  async put(\n    key: string,\n    body: string | Uint8Array,\n    options?: ObjectStorePutOptions,\n  ): Promise<ObjectStorePutResult> {\n    return await this.store(key).put(key, body, options)\n  }\n\n  async stat(key: string): Promise<ObjectStoreMetadata | undefined> {\n    return await this.store(key).stat(key)\n  }\n\n  private store(key: string): ObjectStoreWriter {\n    return this.routes.find(route => route.matches(key))?.store ?? this.primary\n  }\n}\n", "import { sha256 } from '@noble/hashes/sha2.js'\nimport { bytesToHex, utf8ToBytes } from '@noble/hashes/utils.js'\nimport { asSchema } from '@xyo-network/sdk'\nimport { z } from 'zod'\n\nimport { canonicalizeIJson } from './canonicalDocument.ts'\nimport {\n  DappIdZod,\n  HashZod,\n  IdentifierZod,\n  ProtocolVersionZod,\n  Xl1ChainIdZod,\n} from './identifier.ts'\nimport type {\n  ObjectStoreReader,\n  ObjectStoreWriter,\n} from './objectStore.ts'\nimport {\n  normalizeObjectStoreKey,\n  ObjectStorePreconditionError,\n} from './objectStore.ts'\nexport const PublishedProjectionGenerationSchema = asSchema('network.xyo.dapp.projection.published.generation', true)\nexport const PublishedProjectionHeadSchema = asSchema('network.xyo.dapp.projection.published.head', true)\nexport const PublishedProjectionHeadKey = 'head.json' as const\n\nconst ObjectStoreKeyZod = z.string().min(1).superRefine((value, context) => {\n  try {\n    normalizeObjectStoreKey(value)\n  } catch (error) {\n    context.addIssue({\n      code: 'custom',\n      message: error instanceof Error ? error.message : 'invalid object-store key',\n    })\n  }\n})\n\nexport const PublishedProjectionScopeZod = z.strictObject({\n  dappId: DappIdZod,\n  chainId: Xl1ChainIdZod,\n  projectionId: IdentifierZod,\n  projectionVersion: ProtocolVersionZod,\n})\n\nexport type PublishedProjectionScope = z.infer<typeof PublishedProjectionScopeZod>\n\nexport const PublishedProjectionSourceZod = z.strictObject({\n  completedPosition: z.string().min(1).optional(),\n  cursor: z.string().min(1).optional(),\n  floor: z.string().min(1).optional(),\n  observedHead: z.string().min(1).optional(),\n})\n\nexport type PublishedProjectionSource = z.infer<typeof PublishedProjectionSourceZod>\n\nexport const PublishedProjectionObjectReferenceZod = z.strictObject({\n  contentHash: HashZod,\n  contentType: z.string().min(1).optional(),\n  key: ObjectStoreKeyZod,\n  logicalKey: ObjectStoreKeyZod,\n  size: z.number().int().nonnegative(),\n  storeId: IdentifierZod,\n})\n\nexport type PublishedProjectionObjectReference = z.infer<typeof PublishedProjectionObjectReferenceZod>\n\nexport const PublishedProjectionGenerationZod = z.strictObject({\n  schema: z.literal(PublishedProjectionGenerationSchema),\n  schemaVersion: z.literal(1),\n  ...PublishedProjectionScopeZod.shape,\n  generationId: IdentifierZod,\n  objects: z.array(PublishedProjectionObjectReferenceZod).min(1),\n  source: PublishedProjectionSourceZod,\n}).superRefine((generation, context) => {\n  const identities = generation.objects.map(object => `${object.storeId}\\0${object.logicalKey}`)\n  const unique = new Set(identities)\n  if (unique.size !== identities.length) {\n    context.addIssue({\n      code: 'custom',\n      message: 'published projection object store/key identities must be unique',\n      path: ['objects'],\n    })\n  }\n})\n\nexport type PublishedProjectionGeneration = z.infer<typeof PublishedProjectionGenerationZod>\n\nexport const PublishedProjectionHeadZod = z.strictObject({\n  schema: z.literal(PublishedProjectionHeadSchema),\n  schemaVersion: z.literal(1),\n  ...PublishedProjectionScopeZod.shape,\n  generationId: IdentifierZod,\n  generationHash: HashZod,\n  generationKey: ObjectStoreKeyZod,\n  previousGenerationId: IdentifierZod.optional(),\n  revision: z.number().int().positive(),\n})\n\nexport type PublishedProjectionHead = z.infer<typeof PublishedProjectionHeadZod>\n\nexport interface PublishedProjection {\n  readonly generation: PublishedProjectionGeneration\n  readonly head: PublishedProjectionHead\n  readonly headEtag?: string\n}\n\nexport interface ProjectionPublicationObject {\n  readonly body: string | Uint8Array\n  readonly cacheControl?: string\n  readonly contentType?: string\n  readonly key: string\n  readonly storeId: string\n}\n\nexport interface PublishProjectionGenerationOptions {\n  readonly expected?: PublishedProjection\n  /** HTTP policy selected by the app; excluded from content identity. */\n  readonly generationCacheControl?: string\n  readonly generationId: string\n  readonly headCacheControl?: string\n  readonly headStoreId: string\n  readonly objects: readonly ProjectionPublicationObject[]\n  readonly scope: PublishedProjectionScope\n  readonly signal?: AbortSignal\n  readonly source?: PublishedProjectionSource\n  readonly stores: Readonly<Record<string, ObjectStoreWriter>>\n}\n\nexport interface ProjectionPublicationConflict {\n  readonly key?: string\n  readonly kind: 'aborted' | 'head-conflict' | 'immutable-collision'\n  readonly message: string\n}\n\nexport interface PublishProjectionGenerationFailure {\n  readonly conflict: ProjectionPublicationConflict\n  readonly ok: false\n}\n\nexport interface PublishProjectionGenerationSuccess extends PublishedProjection {\n  readonly ok: true\n}\n\nexport type PublishProjectionGenerationResult = PublishProjectionGenerationFailure | PublishProjectionGenerationSuccess\n\nexport interface ReadPublishedProjectionOptions {\n  readonly expectedScope?: PublishedProjectionScope\n  readonly headStore: ObjectStoreReader\n}\n\nexport type PublishedProjectionObjectLoader = (\n  storeId: string,\n  key: string,\n) => Promise<Uint8Array | undefined>\n\nexport interface LoadPublishedProjectionOptions {\n  readonly expectedScope?: PublishedProjectionScope\n  readonly headStoreId: string\n  readonly load: PublishedProjectionObjectLoader\n}\n\nexport interface ResolvePublishedProjectionObjectOptions {\n  readonly key: string\n  readonly projection: PublishedProjection\n  readonly storeId: string\n  readonly stores: Readonly<Record<string, ObjectStoreReader>>\n}\n\nexport interface LoadPublishedProjectionObjectOptions {\n  readonly key: string\n  readonly load: PublishedProjectionObjectLoader\n  readonly projection: PublishedProjection\n  readonly storeId: string\n}\n\nexport interface ResolvedPublishedProjectionObject {\n  readonly body: Uint8Array\n  readonly reference: PublishedProjectionObjectReference\n}\n\nfunction bytes(value: string | Uint8Array): Uint8Array {\n  return typeof value === 'string' ? utf8ToBytes(value) : new Uint8Array(value)\n}\n\nfunction sameBytes(left: Uint8Array, right: Uint8Array): boolean {\n  return left.byteLength === right.byteLength && left.every((value, index) => value === right[index])\n}\n\nexport function hashProjectionPublicationBytes(value: string | Uint8Array): string {\n  return bytesToHex(sha256(bytes(value)))\n}\n\nfunction documentBytes(value: unknown): Uint8Array {\n  return utf8ToBytes(`${canonicalizeIJson(value)}\\n`)\n}\n\nfunction continuation(value: number | undefined): number {\n  if (value === undefined || value < 0x80 || value > 0xBF) throw new TypeError('published projection document is not valid UTF-8')\n  return value & 0x3F\n}\n\nfunction decodeTwoByteCodePoint(value: Uint8Array, index: number, first: number): number {\n  return ((first & 0x1F) << 6) | continuation(value[index + 1])\n}\n\nfunction decodeThreeByteCodePoint(value: Uint8Array, index: number, first: number): number {\n  const second = value[index + 1]\n  if (second === undefined || (first === 0xE0 && second < 0xA0)\n    || (first === 0xED && second > 0x9F)) {\n    throw new TypeError('published projection document is not valid UTF-8')\n  }\n  return ((first & 0x0F) << 12)\n    | (continuation(second) << 6)\n    | continuation(value[index + 2])\n}\n\nfunction decodeFourByteCodePoint(value: Uint8Array, index: number, first: number): number {\n  const second = value[index + 1]\n  if (second === undefined || (first === 0xF0 && second < 0x90)\n    || (first === 0xF4 && second > 0x8F)) {\n    throw new TypeError('published projection document is not valid UTF-8')\n  }\n  return ((first & 0x07) << 18)\n    | (continuation(second) << 12)\n    | (continuation(value[index + 2]) << 6)\n    | continuation(value[index + 3])\n}\n\nexport function decodeUtf8(value: Uint8Array): string {\n  let decoded = ''\n  for (let index = 0; index < value.length;) {\n    const first = value[index]\n    if (first === undefined) break\n    if (first <= 0x7F) {\n      decoded += String.fromCodePoint(first)\n      index++\n      continue\n    }\n    if (first >= 0xC2 && first <= 0xDF) {\n      decoded += String.fromCodePoint(decodeTwoByteCodePoint(value, index, first))\n      index += 2\n      continue\n    }\n    if (first >= 0xE0 && first <= 0xEF) {\n      decoded += String.fromCodePoint(decodeThreeByteCodePoint(value, index, first))\n      index += 3\n      continue\n    }\n    if (first >= 0xF0 && first <= 0xF4) {\n      decoded += String.fromCodePoint(decodeFourByteCodePoint(value, index, first))\n      index += 4\n      continue\n    }\n    throw new TypeError('published projection document is not valid UTF-8')\n  }\n  return decoded\n}\n\nfunction scopeMatches(left: PublishedProjectionScope, right: PublishedProjectionScope): boolean {\n  return left.dappId === right.dappId\n    && left.chainId === right.chainId\n    && left.projectionId === right.projectionId\n    && left.projectionVersion === right.projectionVersion\n}\n\nfunction assertScope(expected: PublishedProjectionScope, value: PublishedProjectionScope): void {\n  if (!scopeMatches(expected, value)) {\n    throw new TypeError('published projection document belongs to a different scope')\n  }\n}\n\nfunction parsePublishedProjectionHead(\n  body: Uint8Array,\n  expectedScope: PublishedProjectionScope | undefined,\n): PublishedProjectionHead {\n  const head = PublishedProjectionHeadZod.parse(JSON.parse(decodeUtf8(body)))\n  if (expectedScope !== undefined) assertScope(expectedScope, head)\n  return head\n}\n\nfunction parsePublishedProjectionGeneration(\n  body: Uint8Array,\n  head: PublishedProjectionHead,\n): PublishedProjectionGeneration {\n  if (hashProjectionPublicationBytes(body) !== head.generationHash) {\n    throw new Error(`published projection generation ${head.generationId} failed hash verification`)\n  }\n  const generation = PublishedProjectionGenerationZod.parse(JSON.parse(decodeUtf8(body)))\n  assertScope(head, generation)\n  if (generation.generationId !== head.generationId) {\n    throw new Error('published projection head and generation identities do not match')\n  }\n  return generation\n}\n\nfunction publishedProjection(\n  head: PublishedProjectionHead,\n  generationBody: Uint8Array,\n  headEtag?: string,\n): PublishedProjection {\n  return {\n    generation: parsePublishedProjectionGeneration(generationBody, head),\n    head,\n    ...(headEtag !== undefined && { headEtag }),\n  }\n}\n\nfunction throwIfAborted(signal: AbortSignal | undefined): void {\n  if (signal?.aborted === true) throw new Error('projection publication aborted')\n}\n\nfunction store<TStore extends ObjectStoreReader>(\n  stores: Readonly<Record<string, TStore>>,\n  storeIdValue: string,\n): TStore {\n  const storeId = IdentifierZod.parse(storeIdValue)\n  const value = stores[storeId]\n  if (value === undefined) throw new TypeError(`published projection store ${storeId} is unavailable`)\n  return value\n}\n\nfunction physicalObjectKey(generationId: string, logicalKey: string): string {\n  return `generations/${IdentifierZod.parse(generationId)}/${normalizeObjectStoreKey(logicalKey)}`\n}\n\nfunction generationKey(generationId: string): string {\n  return `generations/${IdentifierZod.parse(generationId)}/generation.json`\n}\n\nfunction compareReferences(\n  left: PublishedProjectionObjectReference,\n  right: PublishedProjectionObjectReference,\n): number {\n  const leftIdentity = `${left.storeId}\\0${left.logicalKey}`\n  const rightIdentity = `${right.storeId}\\0${right.logicalKey}`\n  return leftIdentity < rightIdentity ? -1 : leftIdentity > rightIdentity ? 1 : 0\n}\n\nasync function writeImmutable(\n  storeValue: ObjectStoreWriter,\n  key: string,\n  body: Uint8Array,\n  contentType: string | undefined,\n  cacheControl?: string,\n): Promise<ProjectionPublicationConflict | undefined> {\n  try {\n    await storeValue.put(key, body, {\n      ...(contentType !== undefined && { contentType }),\n      ...(cacheControl !== undefined && { cacheControl }),\n      ifNotExists: true,\n    })\n  } catch (error) {\n    if (!(error instanceof ObjectStorePreconditionError)) throw error\n    const existing = await storeValue.get(key)\n    if (existing !== undefined && sameBytes(existing, body)) return\n    return {\n      key,\n      kind: 'immutable-collision',\n      message: `immutable published projection object ${key} already has different bytes`,\n    }\n  }\n  const durable = await storeValue.get(key)\n  if (durable === undefined || !sameBytes(durable, body)) {\n    throw new Error(`immutable published projection object ${key} failed read-back verification`)\n  }\n}\n\nasync function writeObjects(\n  options: PublishProjectionGenerationOptions,\n  generationId: string,\n): Promise<PublishedProjectionObjectReference[] | ProjectionPublicationConflict> {\n  const references: PublishedProjectionObjectReference[] = []\n  for (const object of options.objects) {\n    throwIfAborted(options.signal)\n    const storeId = IdentifierZod.parse(object.storeId)\n    const logicalKey = normalizeObjectStoreKey(object.key)\n    const body = bytes(object.body)\n    const key = physicalObjectKey(generationId, logicalKey)\n    const conflict = await writeImmutable(store(options.stores, storeId), key, body, object.contentType, object.cacheControl)\n    if (conflict !== undefined) return conflict\n    references.push(PublishedProjectionObjectReferenceZod.parse({\n      contentHash: hashProjectionPublicationBytes(body),\n      ...(object.contentType !== undefined && { contentType: object.contentType }),\n      key,\n      logicalKey,\n      size: body.byteLength,\n      storeId,\n    }))\n  }\n  return references.toSorted(compareReferences)\n}\n\nasync function writeGeneration(\n  headStore: ObjectStoreWriter,\n  generation: PublishedProjectionGeneration,\n  cacheControl?: string,\n): Promise<ProjectionPublicationConflict | { generationHash: string; generationKey: string }> {\n  const key = generationKey(generation.generationId)\n  const body = documentBytes(generation)\n  const conflict = await writeImmutable(headStore, key, body, 'application/json', cacheControl)\n  return conflict ?? {\n    generationHash: hashProjectionPublicationBytes(body),\n    generationKey: key,\n  }\n}\n\nasync function publishHead(\n  headStore: ObjectStoreWriter,\n  head: PublishedProjectionHead,\n  expected: PublishedProjection | undefined,\n  cacheControl = 'public, max-age=0, must-revalidate',\n): Promise<ProjectionPublicationConflict | { headEtag?: string }> {\n  if (expected !== undefined && expected.headEtag === undefined) {\n    throw new TypeError('conditional projection head replacement requires the current head ETag')\n  }\n  try {\n    const result = await headStore.put(PublishedProjectionHeadKey, documentBytes(head), {\n      cacheControl,\n      contentType: 'application/json',\n      ...(expected === undefined ? { ifNotExists: true } : { ifMatch: expected.headEtag }),\n    })\n    return { ...(result.etag !== undefined && { headEtag: result.etag }) }\n  } catch (error) {\n    if (!(error instanceof ObjectStorePreconditionError)) throw error\n    return {\n      key: PublishedProjectionHeadKey,\n      kind: 'head-conflict',\n      message: 'published projection head changed before conditional advancement',\n    }\n  }\n}\n\nfunction headFor(\n  scope: PublishedProjectionScope,\n  generation: PublishedProjectionGeneration,\n  generationHash: string,\n  generationKeyValue: string,\n  expected: PublishedProjection | undefined,\n): PublishedProjectionHead {\n  return PublishedProjectionHeadZod.parse({\n    schema: PublishedProjectionHeadSchema,\n    schemaVersion: 1,\n    ...scope,\n    generationId: generation.generationId,\n    generationHash,\n    generationKey: generationKeyValue,\n    ...(expected === undefined ? {} : { previousGenerationId: expected.head.generationId }),\n    revision: (expected?.head.revision ?? 0) + 1,\n  })\n}\n\nexport async function readPublishedProjection(\n  options: ReadPublishedProjectionOptions,\n): Promise<PublishedProjection | undefined> {\n  const headObject = await options.headStore.getWithMetadata(PublishedProjectionHeadKey)\n  if (headObject === undefined) return\n  const head = parsePublishedProjectionHead(headObject.body, options.expectedScope)\n  const generationBody = await options.headStore.get(head.generationKey)\n  if (generationBody === undefined) throw new Error(`published projection generation ${head.generationId} is missing`)\n  return publishedProjection(head, generationBody, headObject.metadata.etag)\n}\n\n/** Reads a verified published projection through a caller-owned transport such as HTTP or a native bridge. */\nexport async function loadPublishedProjection(\n  options: LoadPublishedProjectionOptions,\n): Promise<PublishedProjection | undefined> {\n  const headStoreId = IdentifierZod.parse(options.headStoreId)\n  const headBody = await options.load(headStoreId, PublishedProjectionHeadKey)\n  if (headBody === undefined) return\n  const head = parsePublishedProjectionHead(headBody, options.expectedScope)\n  const generationBody = await options.load(headStoreId, head.generationKey)\n  if (generationBody === undefined) throw new Error(`published projection generation ${head.generationId} is missing`)\n  return publishedProjection(head, generationBody)\n}\n\nexport async function publishProjectionGeneration(\n  options: PublishProjectionGenerationOptions,\n): Promise<PublishProjectionGenerationResult> {\n  const scope = PublishedProjectionScopeZod.parse(options.scope)\n  const generationId = IdentifierZod.parse(options.generationId)\n  const headStore = store(options.stores, options.headStoreId)\n  try {\n    throwIfAborted(options.signal)\n    if (options.expected !== undefined) assertScope(scope, options.expected.head)\n    const references = await writeObjects(options, generationId)\n    if (!Array.isArray(references)) return { conflict: references, ok: false }\n    const generation = PublishedProjectionGenerationZod.parse({\n      schema: PublishedProjectionGenerationSchema,\n      schemaVersion: 1,\n      ...scope,\n      generationId,\n      objects: references,\n      source: options.source ?? {},\n    })\n    throwIfAborted(options.signal)\n    const written = await writeGeneration(headStore, generation, options.generationCacheControl)\n    if ('kind' in written) return { conflict: written, ok: false }\n    const head = headFor(scope, generation, written.generationHash, written.generationKey, options.expected)\n    throwIfAborted(options.signal)\n    const committed = await publishHead(headStore, head, options.expected, options.headCacheControl)\n    if ('kind' in committed) return { conflict: committed, ok: false }\n    const published = await readPublishedProjection({ expectedScope: scope, headStore })\n    if (published === undefined || canonicalizeIJson(published.head) !== canonicalizeIJson(head)) {\n      throw new Error('published projection head failed read-back verification')\n    }\n    return {\n      ...published,\n      ok: true,\n    }\n  } catch (error) {\n    if (options.signal?.aborted !== true) throw error\n    return {\n      conflict: {\n        kind: 'aborted',\n        message: error instanceof Error ? error.message : 'projection publication aborted',\n      },\n      ok: false,\n    }\n  }\n}\n\nexport async function resolvePublishedProjectionObject(\n  options: ResolvePublishedProjectionObjectOptions,\n): Promise<ResolvedPublishedProjectionObject | undefined> {\n  const storeId = IdentifierZod.parse(options.storeId)\n  const logicalKey = normalizeObjectStoreKey(options.key)\n  const reference = options.projection.generation.objects.find(object =>\n    object.storeId === storeId && object.logicalKey === logicalKey)\n  if (reference === undefined) return\n  const body = await store(options.stores, storeId).get(reference.key)\n  return resolvedPublishedProjectionObject(body, reference)\n}\n\nfunction resolvedPublishedProjectionObject(\n  body: Uint8Array | undefined,\n  reference: PublishedProjectionObjectReference,\n): ResolvedPublishedProjectionObject {\n  if (body === undefined) {\n    throw new Error(`published projection object ${reference.storeId}:${reference.logicalKey} is missing`)\n  }\n  if (body.byteLength !== reference.size || hashProjectionPublicationBytes(body) !== reference.contentHash) {\n    throw new Error(`published projection object ${reference.storeId}:${reference.logicalKey} failed content verification`)\n  }\n  return { body, reference }\n}\n\n/** Loads and verifies one logical projection object through a caller-owned transport. */\nexport async function loadPublishedProjectionObject(\n  options: LoadPublishedProjectionObjectOptions,\n): Promise<ResolvedPublishedProjectionObject | undefined> {\n  const storeId = IdentifierZod.parse(options.storeId)\n  const logicalKey = normalizeObjectStoreKey(options.key)\n  const reference = options.projection.generation.objects.find(object =>\n    object.storeId === storeId && object.logicalKey === logicalKey)\n  if (reference === undefined) return\n  return resolvedPublishedProjectionObject(await options.load(storeId, reference.key), reference)\n}\n", "export const StrictJsonIssueCode = {\n  bom: 'json.bom',\n  depthExceeded: 'json.depth-exceeded',\n  duplicateKey: 'json.duplicate-key',\n  invalidUtf8: 'json.invalid-utf8',\n  numberOutOfRange: 'json.number-out-of-range',\n  syntax: 'json.syntax',\n  topLevelObjectRequired: 'json.top-level-object-required',\n  unpairedSurrogate: 'json.unpaired-surrogate',\n} as const\n\nexport type StrictJsonIssueCode = typeof StrictJsonIssueCode[keyof typeof StrictJsonIssueCode]\n\nexport class StrictJsonError extends Error {\n  readonly characterOffset: number\n  readonly code: StrictJsonIssueCode\n  readonly pointer: string\n\n  constructor(code: StrictJsonIssueCode, message: string, characterOffset: number, pointer = '') {\n    super(message)\n    this.name = 'StrictJsonError'\n    this.characterOffset = characterOffset\n    this.code = code\n    this.pointer = pointer\n  }\n}\n\nfunction pointerSegment(value: string): string {\n  return value.replaceAll('~', '~0').replaceAll('/', '~1')\n}\n\nfunction childPointer(pointer: string, segment: number | string): string {\n  return `${pointer}/${pointerSegment(String(segment))}`\n}\n\nfunction assertPairedSurrogates(value: string, offset: number, pointer: string): void {\n  for (let index = 0; index < value.length; index++) {\n    const code = value.codePointAt(index)\n    if (code === undefined) return\n    if (code > 0xFF_FF) {\n      index++\n      continue\n    }\n    if (code >= 0xD8_00 && code <= 0xDB_FF) {\n      throw new StrictJsonError(\n        StrictJsonIssueCode.unpairedSurrogate,\n        'JSON string contains an unpaired high surrogate',\n        offset,\n        pointer,\n      )\n    }\n    if (code >= 0xDC_00 && code <= 0xDF_FF) {\n      throw new StrictJsonError(\n        StrictJsonIssueCode.unpairedSurrogate,\n        'JSON string contains an unpaired low surrogate',\n        offset,\n        pointer,\n      )\n    }\n  }\n}\n\nclass StrictJsonParser {\n  private readonly maximumDepth: number\n  private offset = 0\n  private readonly source: string\n\n  constructor(source: string, maximumDepth: number) {\n    this.source = source\n    this.maximumDepth = maximumDepth\n  }\n\n  parse(): unknown {\n    this.skipWhitespace()\n    const value = this.parseValue('', 0)\n    this.skipWhitespace()\n    if (this.offset !== this.source.length) this.syntax('unexpected content after the JSON value', '')\n    return value\n  }\n\n  private parseArray(pointer: string, depth: number): unknown[] {\n    this.offset++\n    this.skipWhitespace()\n    const values: unknown[] = []\n    if (this.source[this.offset] === ']') {\n      this.offset++\n      return values\n    }\n    while (true) {\n      values.push(this.parseValue(childPointer(pointer, values.length), depth))\n      this.skipWhitespace()\n      const character = this.source[this.offset]\n      if (character === ']') {\n        this.offset++\n        return values\n      }\n      if (character !== ',') this.syntax('expected a comma or closing bracket', pointer)\n      this.offset++\n      this.skipWhitespace()\n    }\n  }\n\n  private parseLiteral(literal: string, value: boolean | null, pointer: string): boolean | null {\n    if (!this.source.startsWith(literal, this.offset)) this.syntax(`expected ${literal}`, pointer)\n    this.offset += literal.length\n    return value\n  }\n\n  private parseNumber(pointer: string): number {\n    const start = this.offset\n    const match = /^-?(?:0|[1-9]\\d*)(?:\\.\\d+)?(?:[eE][+-]?\\d+)?/.exec(this.source.slice(start))\n    if (match === null) this.syntax('invalid JSON number', pointer)\n    const token = match[0]\n    this.offset += token.length\n    const value = Number(token)\n    // I-JSON allows finite floats; only integer-valued numbers must be safe.\n    // eslint-disable-next-line unicorn/prefer-number-is-safe-integer -- Number.isSafeInteger() alone would reject 1.5\n    if (!Number.isFinite(value) || (Number.isInteger(value) && !Number.isSafeInteger(value))) {\n      throw new StrictJsonError(\n        StrictJsonIssueCode.numberOutOfRange,\n        'JSON number is outside the interoperable I-JSON range',\n        start,\n        pointer,\n      )\n    }\n    return value\n  }\n\n  private parseObject(pointer: string, depth: number): Record<string, unknown> {\n    this.offset++\n    this.skipWhitespace()\n    if (this.source[this.offset] === '}') {\n      this.offset++\n      return {}\n    }\n    const entries: [string, unknown][] = []\n    const keys = new Set<string>()\n    while (true) {\n      if (this.source[this.offset] !== '\"') this.syntax('expected an object member name', pointer)\n      const keyOffset = this.offset\n      const key = this.parseString(pointer)\n      const keyPointer = childPointer(pointer, key)\n      if (keys.has(key)) {\n        throw new StrictJsonError(\n          StrictJsonIssueCode.duplicateKey,\n          `duplicate JSON object member ${JSON.stringify(key)}`,\n          keyOffset,\n          keyPointer,\n        )\n      }\n      keys.add(key)\n      this.skipWhitespace()\n      if (this.source[this.offset] !== ':') this.syntax('expected a colon after the object member name', keyPointer)\n      this.offset++\n      this.skipWhitespace()\n      entries.push([key, this.parseValue(keyPointer, depth)])\n      this.skipWhitespace()\n      const character = this.source[this.offset]\n      if (character === '}') {\n        this.offset++\n        return Object.fromEntries(entries)\n      }\n      if (character !== ',') this.syntax('expected a comma or closing brace', pointer)\n      this.offset++\n      this.skipWhitespace()\n    }\n  }\n\n  private parseString(pointer: string): string {\n    const start = this.offset\n    this.offset++\n    let isEscaped = false\n    while (this.offset < this.source.length) {\n      const character = this.source[this.offset]\n      if (character === '\"' && !isEscaped) {\n        this.offset++\n        const token = this.source.slice(start, this.offset)\n        let value: string\n        try {\n          value = JSON.parse(token) as string\n        } catch {\n          this.syntax('invalid JSON string', pointer)\n        }\n        assertPairedSurrogates(value, start, pointer)\n        return value\n      }\n      if (!isEscaped && character !== undefined && (character.codePointAt(0) ?? 0) <= 0x1F) {\n        this.syntax('unescaped control character in JSON string', pointer)\n      }\n      isEscaped = character === '\\\\' && !isEscaped ? true : false\n      this.offset++\n    }\n    this.syntax('unterminated JSON string', pointer)\n  }\n\n  private parseValue(pointer: string, depth: number): unknown {\n    if (depth > this.maximumDepth) {\n      throw new StrictJsonError(\n        StrictJsonIssueCode.depthExceeded,\n        `JSON nesting exceeds ${this.maximumDepth}`,\n        this.offset,\n        pointer,\n      )\n    }\n    const character = this.source[this.offset]\n    if (character === '{') return this.parseObject(pointer, depth + 1)\n    if (character === '[') return this.parseArray(pointer, depth + 1)\n    if (character === '\"') return this.parseString(pointer)\n    if (character === 't') return this.parseLiteral('true', true, pointer)\n    if (character === 'f') return this.parseLiteral('false', false, pointer)\n    if (character === 'n') return this.parseLiteral('null', null, pointer)\n    if (character === '-' || (character !== undefined && character >= '0' && character <= '9')) {\n      return this.parseNumber(pointer)\n    }\n    this.syntax('expected a JSON value', pointer)\n  }\n\n  private skipWhitespace(): void {\n    while (this.offset < this.source.length && /[\\t\\n\\r ]/.test(this.source[this.offset] ?? '')) this.offset++\n  }\n\n  private syntax(message: string, pointer: string): never {\n    throw new StrictJsonError(StrictJsonIssueCode.syntax, message, this.offset, pointer)\n  }\n}\n\nexport interface ParseStrictJsonOptions {\n  maximumDepth?: number\n  requireTopLevelObject?: boolean\n}\n\nexport function parseStrictJsonText(source: string, options: ParseStrictJsonOptions = {}): unknown {\n  if (source.codePointAt(0) === 0xFE_FF) {\n    throw new StrictJsonError(StrictJsonIssueCode.bom, 'JSON byte-order marks are forbidden', 0)\n  }\n  const parser = new StrictJsonParser(source, options.maximumDepth ?? 256)\n  const value = parser.parse()\n  if ((options.requireTopLevelObject ?? true)\n    && (typeof value !== 'object' || value === null || Array.isArray(value))) {\n    throw new StrictJsonError(\n      StrictJsonIssueCode.topLevelObjectRequired,\n      'the top-level JSON value must be an object',\n      0,\n    )\n  }\n  return value\n}\n", "import { asSchema } from '@xyo-network/sdk'\nimport { z } from 'zod'\n\nimport {\n  DappDocumentHashAlgorithm,\n  hashDappDocument,\n} from './canonicalDocument.ts'\nimport { DappDeployableThingZod } from './deploymentManifest.ts'\nimport {\n  type DappDeploymentManifestV2,\n  type DappInfrastructurePlacement,\n  DappInfrastructureRequirementZod,\n  normalizeDappDeploymentManifestV2,\n  selectDappDeploymentInfrastructureV2,\n} from './deploymentManifestV2.ts'\nimport {\n  DappIdZod,\n  HashZod,\n  IdentifierZod,\n} from './identifier.ts'\nimport {\n  compareDappSelectedInfrastructureV1,\n  DappInfrastructureIdZod,\n  type DappSelectedInfrastructureV1,\n  DappSelectedInfrastructureV1Zod,\n} from './infrastructureDescriptor.ts'\nimport {\n  compareCodeUnits,\n  findSortedUniqueIssue,\n} from './ordering.ts'\nimport { hashDappDeploymentRequest } from './projectManifest.ts'\n\n/**\n * Deployment intent (D-031): the public-safe, alias-free projection of one\n * selected named deployment. Aliases are authoring keys; the intent binds each\n * thing, managed resource, and host partition to the immutable\n * `infrastructureId` its alias resolved to, plus that instance's safe\n * descriptor and policy identities. Renaming an alias in both source documents\n * therefore leaves `deploymentIntentId` unchanged, while remapping a binding\n * to a different registered instance changes it.\n */\nexport const DappDeploymentIntentSchema = asSchema('network.xyo.dapp.deployment.intent', true)\n\nconst ThingEntryZod = z.strictObject({ thingId: IdentifierZod, thing: DappDeployableThingZod })\nconst ThingBindingZod = z.strictObject({ thingId: IdentifierZod, infrastructureId: DappInfrastructureIdZod })\nconst ResourceBindingZod = z.strictObject({ resourceId: IdentifierZod, infrastructureId: DappInfrastructureIdZod })\nconst HostBindingZod = z.strictObject({ hostPartitionId: IdentifierZod, infrastructureId: DappInfrastructureIdZod })\n\ninterface RefinementContext {\n  addIssue: (issue: { code: 'custom'; message: string; path: (number | string)[] }) => void\n}\n\nfunction refineSortedById<T>(\n  context: RefinementContext,\n  values: readonly T[],\n  idOf: (value: T) => string,\n  field: string,\n): void {\n  const issue = findSortedUniqueIssue(values, (left, right) => compareCodeUnits(idOf(left), idOf(right)), field)\n  if (issue !== undefined) {\n    context.addIssue({\n      code: 'custom', message: issue.message, path: [field, issue.index],\n    })\n  }\n}\n\nexport const DappDeploymentIntentV1PreimageZod = z.strictObject({\n  schema: z.literal(DappDeploymentIntentSchema),\n  schemaVersion: z.literal(1),\n  hashAlgorithm: z.literal(DappDocumentHashAlgorithm),\n  projectId: DappIdZod,\n  deploymentName: IdentifierZod,\n  requestHash: HashZod,\n  things: z.array(ThingEntryZod),\n  thingBindings: z.array(ThingBindingZod),\n  resourceBindings: z.array(ResourceBindingZod),\n  hostBindings: z.array(HostBindingZod),\n  infrastructure: z.array(DappSelectedInfrastructureV1Zod),\n}).superRefine((intent, context) => {\n  refineSortedById(context, intent.things, entry => entry.thingId, 'things')\n  refineSortedById(context, intent.thingBindings, entry => entry.thingId, 'thingBindings')\n  refineSortedById(context, intent.resourceBindings, entry => entry.resourceId, 'resourceBindings')\n  refineSortedById(context, intent.hostBindings, entry => entry.hostPartitionId, 'hostBindings')\n  refineSortedById(context, intent.infrastructure, entry => entry.infrastructureId, 'infrastructure')\n\n  const thingIds = intent.things.map(entry => entry.thingId)\n  const boundThingIds = intent.thingBindings.map(entry => entry.thingId)\n  if (thingIds.length !== boundThingIds.length || thingIds.some((thingId, index) => boundThingIds[index] !== thingId)) {\n    context.addIssue({\n      code: 'custom', message: 'every thing must be bound exactly once', path: ['thingBindings'],\n    })\n  }\n\n  const referenced = new Set([\n    ...intent.thingBindings.map(entry => entry.infrastructureId),\n    ...intent.resourceBindings.map(entry => entry.infrastructureId),\n    ...intent.hostBindings.map(entry => entry.infrastructureId),\n  ])\n  const declared = intent.infrastructure.map(entry => entry.infrastructureId)\n  const expected = [...referenced].toSorted(compareCodeUnits)\n  if (declared.length !== expected.length || declared.some((infrastructureId, index) => expected[index] !== infrastructureId)) {\n    context.addIssue({\n      code: 'custom',\n      message: 'infrastructure must be exactly the set of instances referenced by the placements',\n      path: ['infrastructure'],\n    })\n  }\n})\nexport type DappDeploymentIntentV1Preimage = z.infer<typeof DappDeploymentIntentV1PreimageZod>\n\nexport const DappDeploymentIntentV1Zod = DappDeploymentIntentV1PreimageZod.safeExtend({ deploymentIntentId: HashZod })\nexport type DappDeploymentIntentV1 = z.infer<typeof DappDeploymentIntentV1Zod>\n\nexport const DappDeploymentIntentIssueCodes = [\n  'deployment.intent-input-invalid',\n  'deployment.intent-verification-failed',\n] as const\nexport const DappDeploymentIntentIssueCodeZod = z.enum(DappDeploymentIntentIssueCodes)\nexport type DappDeploymentIntentIssueCode = z.infer<typeof DappDeploymentIntentIssueCodeZod>\n\nexport interface DappDeploymentIntentIssue {\n  code: DappDeploymentIntentIssueCode\n  message: string\n  path: (number | string)[]\n}\n\nexport type DappDeploymentIntentV1Result\n  = { issues: DappDeploymentIntentIssue[]; success: false }\n    | { success: true; value: DappDeploymentIntentV1 }\n\nexport interface CreateDappDeploymentIntentV1Input {\n  /** A Deployment Manifest V2 document; it is normalized, never trusted as already normalized. */\n  deploymentManifest: unknown\n  deploymentName: string\n  /** The host's public-safe projection of every registered entry, keyed by the manifest alias. */\n  infrastructure: Readonly<Record<string, unknown>>\n}\n\nfunction invalid(message: string, path: (number | string)[] = []): DappDeploymentIntentV1Result {\n  return {\n    issues: [{\n      code: 'deployment.intent-input-invalid', message, path,\n    }],\n    success: false,\n  }\n}\n\n/** D-002 kind `deployment-intent` version 1: `xyo-dapp-kit:deployment-intent:v1\\n`. */\nexport function hashDappDeploymentIntentV1(preimage: unknown): string {\n  return hashDappDocument({\n    kind: 'deployment-intent',\n    schema: DappDeploymentIntentV1PreimageZod,\n    schemaVersion: 1,\n  }, preimage).hash\n}\n\nfunction bindingEntries<T>(\n  map: Readonly<Record<string, DappInfrastructurePlacement>>,\n  resolve: (alias: string) => string,\n  build: (id: string, infrastructureId: string) => T,\n): T[] {\n  return Object.entries(map)\n    .toSorted(([left], [right]) => compareCodeUnits(left, right))\n    .map(([id, placement]) => build(id, resolve(placement.infrastructure)))\n}\n\n/**\n * Resolves the aliases of one named deployment through the supplied safe\n * projections and builds the intent. Every referenced alias must be supplied\n * with a matching `kind`, two aliases may never resolve to one instance, and\n * unreferenced entries are ignored so an unselected registry edit never\n * changes the intent.\n */\n// Alias resolution, projection validation, and preimage assembly are one pass.\n\nexport function createDappDeploymentIntentV1(input: CreateDappDeploymentIntentV1Input): DappDeploymentIntentV1Result {\n  let manifest: DappDeploymentManifestV2\n  try {\n    manifest = normalizeDappDeploymentManifestV2(input.deploymentManifest)\n  } catch (error) {\n    return invalid(`deployment manifest is not a valid V2 document: ${error instanceof Error ? error.message : String(error)}`)\n  }\n  const deployment = manifest.deployments[input.deploymentName]\n  if (deployment === undefined) {\n    return invalid(`deployment ${input.deploymentName} is not declared`, ['deployments', input.deploymentName])\n  }\n\n  const selected = selectDappDeploymentInfrastructureV2(manifest, input.deploymentName)\n  const resolved = new Map<string, DappSelectedInfrastructureV1>()\n  const issues: DappDeploymentIntentIssue[] = []\n  for (const [alias, requirement] of Object.entries(selected)) {\n    const projection = DappSelectedInfrastructureV1Zod.safeParse(input.infrastructure[alias])\n    if (!projection.success) {\n      issues.push({\n        code: 'deployment.intent-input-invalid',\n        message: `infrastructure alias ${alias} has no valid selected projection: ${projection.error.issues.map(issue => issue.message).join('; ')}`,\n        path: ['infrastructure', alias],\n      })\n      continue\n    }\n    if (projection.data.kind !== DappInfrastructureRequirementZod.parse(requirement).kind) {\n      issues.push({\n        code: 'deployment.intent-input-invalid',\n        message: `infrastructure alias ${alias} requires kind ${requirement.kind} but resolved to ${projection.data.kind}`,\n        path: ['infrastructure', alias, 'kind'],\n      })\n      continue\n    }\n    for (const [otherAlias, other] of resolved) {\n      if (other.infrastructureId === projection.data.infrastructureId) {\n        issues.push({\n          code: 'deployment.intent-input-invalid',\n          message: `aliases ${otherAlias} and ${alias} both resolve to infrastructure ${projection.data.infrastructureId}`,\n          path: ['infrastructure', alias, 'infrastructureId'],\n        })\n      }\n    }\n    resolved.set(alias, projection.data)\n  }\n  if (issues.length > 0) return { issues, success: false }\n\n  const resolve = (alias: string): string => {\n    const projection = resolved.get(alias)\n    if (projection === undefined) throw new TypeError(`alias ${alias} was not resolved`)\n    return projection.infrastructureId\n  }\n  const preimage = DappDeploymentIntentV1PreimageZod.parse({\n    schema: DappDeploymentIntentSchema,\n    schemaVersion: 1,\n    hashAlgorithm: DappDocumentHashAlgorithm,\n    projectId: manifest.projectId,\n    deploymentName: input.deploymentName,\n    requestHash: hashDappDeploymentRequest(deployment.request),\n    things: Object.entries(deployment.things)\n      .toSorted(([left], [right]) => compareCodeUnits(left, right))\n      .map(([thingId, thing]) => ({ thingId, thing })),\n    thingBindings: bindingEntries(deployment.bindings, resolve, (thingId, infrastructureId) => ({ thingId, infrastructureId })),\n    resourceBindings: bindingEntries(deployment.resourceBindings, resolve, (resourceId, infrastructureId) => ({ resourceId, infrastructureId })),\n    hostBindings: bindingEntries(deployment.hostBindings, resolve, (hostPartitionId, infrastructureId) => ({ hostPartitionId, infrastructureId })),\n    infrastructure: resolved.values().toArray().toSorted(compareDappSelectedInfrastructureV1),\n  })\n  return {\n    success: true,\n    value: DappDeploymentIntentV1Zod.parse({ ...preimage, deploymentIntentId: hashDappDeploymentIntentV1(preimage) }),\n  }\n}\n\nexport function verifyDappDeploymentIntentV1(value: unknown): DappDeploymentIntentV1Result {\n  const result = DappDeploymentIntentV1Zod.safeParse(value)\n  if (!result.success) {\n    return {\n      issues: result.error.issues.map(issue => ({\n        code: 'deployment.intent-verification-failed',\n        message: issue.message,\n        path: issue.path.map(entry => typeof entry === 'symbol' ? entry.toString() : entry),\n      })),\n      success: false,\n    }\n  }\n  const { deploymentIntentId, ...preimage } = result.data\n  if (hashDappDeploymentIntentV1(preimage) !== deploymentIntentId) {\n    return {\n      issues: [{\n        code: 'deployment.intent-verification-failed',\n        message: 'deployment intent ID does not match its canonical preimage',\n        path: ['deploymentIntentId'],\n      }],\n      success: false,\n    }\n  }\n  return { success: true, value: result.data }\n}\n", "import { asSchema } from '@xyo-network/sdk'\nimport { z } from 'zod'\n\nimport {\n  DappDocumentHashAlgorithm,\n  hashDappDocument,\n} from './canonicalDocument.ts'\nimport {\n  type DappDeploymentRequestDocument,\n  DappDeploymentRequestDocumentZod,\n  normalizeDappDeploymentRequest,\n} from './deploymentRequest.ts'\nimport {\n  DappIdZod,\n  IdentifierZod,\n} from './identifier.ts'\nimport { ApplicationPathZod } from './projectArtifact.ts'\nexport const DappDeploymentManifestSchema = asSchema('network.xyo.dapp.deployment', true)\nexport const DappDeploymentJsonSchemaUrl = 'https://schemas.xyo.network/dapp-kit/deployment/v1.json' as const\n\nexport const DappTargetFamilyZod = z.enum(['vercel', 'cloudflare'])\nexport type DappTargetFamily = z.infer<typeof DappTargetFamilyZod>\n\nconst RoutesZod = z.array(ApplicationPathZod).min(1).superRefine((routes, context) => {\n  const unique = new Set(routes)\n  if (unique.size !== routes.length) {\n    context.addIssue({ code: 'custom', message: 'owned routes must be unique' })\n  }\n})\n\nconst ResourceIdsZod = z.array(IdentifierZod).min(1).superRefine((resources, context) => {\n  const unique2 = new Set(resources)\n  if (unique2.size !== resources.length) {\n    context.addIssue({ code: 'custom', message: 'resource references must be unique' })\n  }\n})\n\nexport const DappDeployableThingZod = z.discriminatedUnion('kind', [\n  z.strictObject({\n    kind: z.literal('website'),\n    artifactId: IdentifierZod,\n    exposure: z.enum(['public', 'private']),\n    routes: RoutesZod,\n  }),\n  z.strictObject({\n    kind: z.literal('api'),\n    artifactId: IdentifierZod,\n    ports: z.array(IdentifierZod).min(1),\n    routes: RoutesZod,\n  }),\n  z.strictObject({\n    kind: z.literal('datalake'),\n    resourceId: IdentifierZod,\n  }),\n  z.strictObject({\n    kind: z.literal('event-ingress'),\n    artifactId: IdentifierZod,\n    eventStreamResource: IdentifierZod,\n    routes: RoutesZod,\n  }),\n  z.strictObject({\n    kind: z.literal('event-stream'),\n    resourceId: IdentifierZod,\n  }),\n  z.strictObject({\n    kind: z.literal('subscription-runner'),\n    subscriptionResource: IdentifierZod,\n    consumerActor: IdentifierZod,\n  }),\n  z.strictObject({\n    kind: z.literal('indexer'),\n    subscriptionResource: IdentifierZod,\n    consumerActor: IdentifierZod,\n    projectionResource: IdentifierZod,\n    checkpointResource: IdentifierZod,\n  }),\n  z.strictObject({\n    kind: z.literal('controller'),\n    subscriptionResource: IdentifierZod,\n    consumerActor: IdentifierZod,\n    effectJournalResource: IdentifierZod,\n  }),\n  z.strictObject({\n    kind: z.literal('publisher'),\n    subscriptionResource: IdentifierZod,\n    consumerActor: IdentifierZod,\n    publicationResources: ResourceIdsZod,\n  }),\n])\n\nexport type DappDeployableThing = z.infer<typeof DappDeployableThingZod>\n\nexport const DappThingTargetBindingZod = z.strictObject({\n  targetFamily: DappTargetFamilyZod,\n  target: IdentifierZod.optional(),\n})\n\nexport type DappThingTargetBinding = z.infer<typeof DappThingTargetBindingZod>\n\nexport const DappNamedDeploymentZod = z.strictObject({\n  request: DappDeploymentRequestDocumentZod,\n  things: z.record(IdentifierZod, DappDeployableThingZod),\n  bindings: z.record(IdentifierZod, DappThingTargetBindingZod),\n}).superRefine((deployment, context) => {\n  const thingIds = Object.keys(deployment.things).toSorted()\n  const bindingIds = Object.keys(deployment.bindings).toSorted()\n  if (thingIds.length !== bindingIds.length\n    || thingIds.some((thingId, index) => bindingIds[index] !== thingId)) {\n    context.addIssue({\n      code: 'custom',\n      message: 'every deployable thing must have exactly one target binding',\n      path: ['bindings'],\n    })\n  }\n\n  const routeOwners = new Map<string, string>()\n  for (const [thingId, thing] of Object.entries(deployment.things)) {\n    if (!('routes' in thing)) continue\n    for (const route of thing.routes) {\n      const prior = routeOwners.get(route)\n      if (prior === undefined) {\n        routeOwners.set(route, thingId)\n      } else {\n        context.addIssue({\n          code: 'custom',\n          message: `route ${route} is already owned by thing ${prior}`,\n          path: ['things', thingId, 'routes'],\n        })\n      }\n    }\n  }\n})\n\nexport type DappNamedDeployment = z.infer<typeof DappNamedDeploymentZod>\n\nexport const DappDeploymentManifestDocumentZod = z.strictObject({\n  $schema: z.literal(DappDeploymentJsonSchemaUrl),\n  schema: z.literal(DappDeploymentManifestSchema),\n  schemaVersion: z.literal(1),\n  projectId: DappIdZod,\n  deployments: z.record(IdentifierZod, DappNamedDeploymentZod),\n})\n\nexport type DappDeploymentManifest = z.infer<typeof DappDeploymentManifestDocumentZod>\n\nfunction sortedRecord<T>(record: Readonly<Record<string, T>>): Record<string, T> {\n  return Object.fromEntries(Object.entries(record).toSorted(([left], [right]) => left.localeCompare(right)))\n}\n\nfunction normalizedThing(thing: DappDeployableThing): DappDeployableThing {\n  if (thing.kind === 'api') {\n    return DappDeployableThingZod.parse({\n      ...thing, ports: [...thing.ports].toSorted(), routes: [...thing.routes].toSorted(),\n    })\n  }\n  if ('routes' in thing) return DappDeployableThingZod.parse({ ...thing, routes: [...thing.routes].toSorted() })\n  return thing.kind === 'publisher' ? DappDeployableThingZod.parse({ ...thing, publicationResources: [...thing.publicationResources].toSorted() }) : DappDeployableThingZod.parse(thing)\n}\n\nfunction normalizedRequest(document: DappDeploymentRequestDocument): DappDeploymentRequestDocument {\n  return DappDeploymentRequestDocumentZod.parse({\n    ...document,\n    request: normalizeDappDeploymentRequest(document.request),\n  })\n}\n\nexport function normalizeDappDeploymentManifest(value: unknown): DappDeploymentManifest {\n  const manifest = DappDeploymentManifestDocumentZod.parse(value)\n  return DappDeploymentManifestDocumentZod.parse({\n    ...manifest,\n    deployments: sortedRecord(Object.fromEntries(Object.entries(manifest.deployments).map(([name, deployment]) => [\n      name,\n      {\n        request: normalizedRequest(deployment.request),\n        things: sortedRecord(Object.fromEntries(Object.entries(deployment.things)\n          .map(([thingId, thing]) => [thingId, normalizedThing(thing)]))),\n        bindings: sortedRecord(deployment.bindings),\n      },\n    ]))),\n  })\n}\n\nexport function hashDappDeploymentManifest(value: unknown): string {\n  return hashDappDocument({\n    kind: 'deployment-manifest',\n    schema: DappDeploymentManifestDocumentZod,\n    schemaVersion: 1,\n  }, normalizeDappDeploymentManifest(value)).hash\n}\n\nexport function dappDeploymentJsonSchema() {\n  return {\n    ...z.toJSONSchema(DappDeploymentManifestDocumentZod, { target: 'draft-2020-12' }),\n    $id: DappDeploymentJsonSchemaUrl,\n  }\n}\n\nexport const DappDeploymentManifestIdentityZod = z.strictObject({\n  schemaVersion: z.literal(1),\n  deploymentManifestId: z.string().regex(/^[0-9a-f]{64}$/),\n  hashAlgorithm: z.literal(DappDocumentHashAlgorithm),\n})\n\nexport type DappDeploymentManifestIdentity = z.infer<typeof DappDeploymentManifestIdentityZod>\n", "import { asSchema } from '@xyo-network/sdk'\nimport { z } from 'zod'\n\nimport { ApplicationProviderSelectionZod, normalizeApplicationProviderSelections } from './applicationProvider.ts'\nimport {\n  DappActorConfigurationZod,\n  DappSupervisionConfigurationZod,\n} from './dappConfiguration.ts'\nimport { DappResourceRequestZod } from './deploymentResource.ts'\nimport {\n  DappIdZod,\n  IdentifierZod,\n} from './identifier.ts'\nimport {\n  AuxiliaryStorageClassZod,\n  ContentProtectionZod,\n  DatalakeReadAccessZod,\n  DatalakeUnavailableBehaviorZod,\n  DurableProjectionProfileZod,\n} from './profile.ts'\nimport { PackageNameZod, PackageScriptNameZod } from './projectArtifact.ts'\nexport const DappDeploymentRequestSchema = asSchema('network.xyo.dapp.deployment.request', true)\n\nexport const DappIdentityRequestBindingZod = z.strictObject({\n  roleId: IdentifierZod,\n  resource: IdentifierZod,\n})\n\nexport type DappIdentityRequestBinding = z.infer<typeof DappIdentityRequestBindingZod>\n\nexport const DappAuxiliaryStoreRequestBindingZod = z.strictObject({\n  class: AuxiliaryStorageClassZod,\n  resource: IdentifierZod,\n})\n\nexport type DappAuxiliaryStoreRequestBinding = z.infer<typeof DappAuxiliaryStoreRequestBindingZod>\n\nconst SideChannelRequestFields = {\n  resource: IdentifierZod,\n  detachedSigningIdentityRole: IdentifierZod,\n  maximumMessageBytes: z.number().int().positive(),\n  replayRetentionSeconds: z.number().int().positive(),\n  acceptedClockSkewMilliseconds: z.number().int().nonnegative(),\n}\n\nexport const DappSideChannelRequestPolicyZod = z.discriminatedUnion('profile', [\n  z.strictObject({ profile: z.literal('none') }),\n  z.strictObject({\n    profile: z.literal('optional-optimization'),\n    ...SideChannelRequestFields,\n    unavailableBehavior: z.literal('continue-without-channel'),\n  }),\n  z.strictObject({\n    profile: z.literal('required-for-liveness'),\n    ...SideChannelRequestFields,\n    unavailableBehavior: z.enum(['pending', 'expire', 'fail-operation']),\n  }),\n])\n\nexport type DappSideChannelRequestPolicy = z.infer<typeof DappSideChannelRequestPolicyZod>\n\nexport const DappExternalSourceRequestBindingZod = z.strictObject({\n  sourceId: IdentifierZod,\n  resource: IdentifierZod,\n})\n\nexport const DappExternalInteractionRequestPolicyZod = z.discriminatedUnion('mode', [\n  z.strictObject({ mode: z.literal('none') }),\n  z.strictObject({\n    mode: z.literal('observe'),\n    sources: z.array(DappExternalSourceRequestBindingZod).min(1),\n  }),\n  z.strictObject({\n    mode: z.literal('attest-import'),\n    sources: z.array(DappExternalSourceRequestBindingZod).min(1),\n    commitBeforeReduction: z.literal(true),\n  }),\n])\n\nexport type DappExternalInteractionRequestPolicy = z.infer<typeof DappExternalInteractionRequestPolicyZod>\n\nconst DatalakeRequestFields = {\n  resource: IdentifierZod,\n  readAccess: DatalakeReadAccessZod,\n  contentProtection: ContentProtectionZod,\n  writeBeforeBroadcast: z.boolean(),\n  requiredCopies: z.number().int().nonnegative(),\n  retentionSeconds: z.number().int().nonnegative(),\n  unavailableBehavior: DatalakeUnavailableBehaviorZod,\n}\n\nexport const DappDatalakeRequestPolicyZod = z.discriminatedUnion('mode', [\n  z.strictObject({ mode: z.literal('none') }),\n  z.strictObject({\n    mode: z.literal('optional'),\n    ...DatalakeRequestFields,\n  }),\n  z.strictObject({\n    mode: z.literal('required'),\n    ...DatalakeRequestFields,\n    writeBeforeBroadcast: z.literal(true),\n    requiredCopies: z.number().int().positive(),\n  }),\n])\n\nexport type DappDatalakeRequestPolicy = z.infer<typeof DappDatalakeRequestPolicyZod>\n\nconst ProjectionRequestFields = {\n  projectionResource: IdentifierZod,\n  floor: z.discriminatedUnion('mode', [\n    z.strictObject({ mode: z.literal('bounded'), block: z.number().int().positive() }),\n    z.strictObject({ mode: z.literal('genesis'), block: z.literal(0) }),\n  ]),\n  maximumLagBlocks: z.number().int().nonnegative(),\n  progressWatermark: z.boolean(),\n}\n\nexport const DappProjectionRequestPolicyZod = z.discriminatedUnion('profile', [\n  z.strictObject({ profile: z.literal('none') }),\n  z.strictObject({\n    profile: z.literal('ephemeral'),\n    ...ProjectionRequestFields,\n  }),\n  z.strictObject({\n    profile: DurableProjectionProfileZod,\n    ...ProjectionRequestFields,\n    checkpointResource: IdentifierZod,\n  }),\n])\n\nexport type DappProjectionRequestPolicy = z.infer<typeof DappProjectionRequestPolicyZod>\n\nexport const DappPortRequestBindingZod = z.strictObject({\n  portId: IdentifierZod,\n  host: IdentifierZod,\n})\n\nexport type DappPortRequestBinding = z.infer<typeof DappPortRequestBindingZod>\n\nexport const DappVerificationEvidenceZod = z.enum([\n  'model',\n  'deterministic',\n  'node',\n  'browser',\n  'local-xl1',\n  'local-datalake',\n  'sequence',\n  'mainnet',\n])\n\nexport type DappVerificationEvidence = z.infer<typeof DappVerificationEvidenceZod>\n\nexport const DappVerificationRequestZod = z.strictObject({\n  evidence: DappVerificationEvidenceZod,\n  id: IdentifierZod,\n  package: PackageNameZod,\n  script: PackageScriptNameZod,\n})\n\nexport type DappVerificationRequest = z.infer<typeof DappVerificationRequestZod>\n\nexport const DappDeploymentRequestZod = z.strictObject({\n  applicationProviders: z.array(ApplicationProviderSelectionZod).optional(),\n  network: z.strictObject({ resource: IdentifierZod }),\n  actors: z.array(DappActorConfigurationZod),\n  supervision: DappSupervisionConfigurationZod,\n  portBindings: z.array(DappPortRequestBindingZod),\n  identityBindings: z.array(DappIdentityRequestBindingZod),\n  auxiliaryStores: z.array(DappAuxiliaryStoreRequestBindingZod),\n  policies: z.strictObject({\n    sideChannel: DappSideChannelRequestPolicyZod,\n    externalInteraction: DappExternalInteractionRequestPolicyZod,\n    datalake: DappDatalakeRequestPolicyZod,\n    projection: DappProjectionRequestPolicyZod,\n    consistency: z.strictObject({\n      read: z.literal('finalized'),\n      readinessMaxLag: z.number().int().nonnegative(),\n    }),\n  }),\n  resources: z.record(IdentifierZod, DappResourceRequestZod),\n  verification: z.array(DappVerificationRequestZod).min(1),\n})\n\nexport type DappDeploymentRequest = z.infer<typeof DappDeploymentRequestZod>\n\nexport const DappDeploymentRequestDocumentZod = z.strictObject({\n  schema: z.literal(DappDeploymentRequestSchema),\n  schemaVersion: z.literal(1),\n  projectId: DappIdZod,\n  deploymentName: IdentifierZod,\n  request: DappDeploymentRequestZod,\n})\n\nexport type DappDeploymentRequestDocument = z.infer<typeof DappDeploymentRequestDocumentZod>\n\nfunction sortedRecord<T>(record: Readonly<Record<string, T>>): Record<string, T> {\n  return Object.fromEntries(Object.entries(record).toSorted(([left], [right]) => left.localeCompare(right)))\n}\n\nexport function normalizeDappDeploymentRequest(request: DappDeploymentRequest): DappDeploymentRequest {\n  const { applicationProviders, ...legacy } = request\n  return DappDeploymentRequestZod.parse({\n    ...legacy,\n    ...(applicationProviders?.length ? { applicationProviders: normalizeApplicationProviderSelections(applicationProviders) } : {}),\n    actors: [...request.actors].toSorted((left, right) => left.instanceId.localeCompare(right.instanceId)),\n    portBindings: [...request.portBindings].toSorted((left, right) => left.portId.localeCompare(right.portId)),\n    identityBindings: [...request.identityBindings].toSorted((left, right) => left.roleId.localeCompare(right.roleId)),\n    auxiliaryStores: [...request.auxiliaryStores].toSorted((left, right) => left.class.localeCompare(right.class)),\n    resources: sortedRecord(request.resources),\n    verification: [...request.verification].toSorted((left, right) => left.id.localeCompare(right.id)),\n  })\n}\n", "import { z } from 'zod'\n\nimport {\n  DappDocumentHashAlgorithm,\n  hashDappDocument,\n} from './canonicalDocument.ts'\nimport {\n  type DappDeployableThing,\n  DappDeployableThingZod,\n  DappDeploymentManifestSchema,\n} from './deploymentManifest.ts'\nimport {\n  type DappDeploymentRequestDocument,\n  DappDeploymentRequestDocumentZod,\n  normalizeDappDeploymentRequest,\n} from './deploymentRequest.ts'\nimport {\n  DappIdZod,\n  HashZod,\n  IdentifierZod,\n} from './identifier.ts'\n\n/**\n * Deployment Manifest V2 (D-031). V2 is an additive schema version of\n * `xl1.deploy.json`: it keeps the V1 request and thing declarations and adds a\n * commit-safe root registry of infrastructure requirements plus three exact\n * placement maps per named deployment. The unsuffixed V1 exports in\n * `deploymentManifest.ts` remain byte-for-byte frozen; nothing here is\n * reachable from them.\n */\nexport const DappDeploymentJsonSchemaV2Url = 'https://schemas.xyo.network/dapp-kit/deployment/v2.json' as const\nexport const DappDeploymentSourceResolutionModeV2 = 'split-manifest-v2' as const\n\n/**\n * The closed infrastructure discriminator. Widening it requires a new manifest\n * version, matching lock/composition versions, an admitted adapter decision,\n * and new independent vectors; it is never discovered from repository source.\n */\nexport const DappInfrastructureKindZod = z.enum(['vercel', 'cloudflare', 'kubernetes', 'proxmox'])\nexport type DappInfrastructureKind = z.infer<typeof DappInfrastructureKindZod>\n\n/**\n * One commit-safe infrastructure requirement. It carries only the kind: no\n * route, account, cluster, server, registration identity, policy, grant, or\n * credential may appear in repository source, so the object is strict and\n * closed by construction.\n */\nexport const DappInfrastructureRequirementZod = z.strictObject({ kind: DappInfrastructureKindZod })\nexport type DappInfrastructureRequirement = z.infer<typeof DappInfrastructureRequirementZod>\n\n/** One placement: the alias of exactly one root infrastructure entry. */\nexport const DappInfrastructurePlacementZod = z.strictObject({ infrastructure: IdentifierZod })\nexport type DappInfrastructurePlacement = z.infer<typeof DappInfrastructurePlacementZod>\n\ntype PlacementMap = Readonly<Record<string, DappInfrastructurePlacement>>\n\ninterface NamedDeploymentV2Shape {\n  bindings: PlacementMap\n  hostBindings: PlacementMap\n  request: DappDeploymentRequestDocument\n  resourceBindings: PlacementMap\n  things: Readonly<Record<string, DappDeployableThing>>\n}\n\ninterface PlacementContext {\n  addIssue: (issue: { code: 'custom'; message: string; path: (number | string)[] }) => void\n}\n\ntype ApiThing = Extract<DappDeployableThing, { kind: 'api' }>\ntype ActorBackedThing = Extract<DappDeployableThing, { consumerActor: string }>\ntype OwnedResourceThing = Extract<DappDeployableThing, { kind: 'datalake' | 'event-stream' }>\n\nfunction sortedUnique(values: Iterable<string>): string[] {\n  return [...new Set(values)].toSorted()\n}\n\nfunction sameSortedSet(left: readonly string[], right: readonly string[]): boolean {\n  return left.length === right.length && left.every((value, index) => right[index] === value)\n}\n\nfunction placementOf(map: PlacementMap, id: string): string | undefined {\n  return map[id]?.infrastructure\n}\n\nfunction refinePlacementMap(\n  context: PlacementContext,\n  map: PlacementMap,\n  expected: readonly string[],\n  field: string,\n  subject: string,\n): void {\n  const actual = Object.keys(map).toSorted()\n  if (sameSortedSet(actual, expected)) return\n  for (const id of expected) {\n    if (!actual.includes(id)) {\n      context.addIssue({\n        code: 'custom',\n        message: `${subject} ${id} must have exactly one infrastructure binding`,\n        path: [field, id],\n      })\n    }\n  }\n  for (const id of actual) {\n    if (!expected.includes(id)) {\n      context.addIssue({\n        code: 'custom',\n        message: `${field} entry ${id} does not name a bindable ${subject}`,\n        path: [field, id],\n      })\n    }\n  }\n}\n\nfunction refinePlacementCompleteness(deployment: NamedDeploymentV2Shape, context: PlacementContext): void {\n  const request = deployment.request.request\n  refinePlacementMap(context, deployment.bindings, Object.keys(deployment.things).toSorted(), 'bindings', 'deployable thing')\n\n  const managedResourceIds = sortedUnique(Object.entries(request.resources)\n    .filter(([, resource]) => resource.provision !== 'external')\n    .map(([resourceId]) => resourceId))\n  for (const resourceId of Object.keys(deployment.resourceBindings)) {\n    if (request.resources[resourceId]?.provision === 'external') {\n      context.addIssue({\n        code: 'custom',\n        message: `external resource ${resourceId} cannot have an infrastructure binding`,\n        path: ['resourceBindings', resourceId],\n      })\n    }\n  }\n  refinePlacementMap(context, deployment.resourceBindings, managedResourceIds, 'resourceBindings', 'managed resource')\n\n  const hostIds = sortedUnique(request.actors.map(actor => actor.host))\n  refinePlacementMap(context, deployment.hostBindings, hostIds, 'hostBindings', 'host partition')\n}\n\nfunction refineRouteOwnership(things: Readonly<Record<string, DappDeployableThing>>, context: PlacementContext): void {\n  const routeOwners = new Map<string, string>()\n  for (const [thingId, thing] of Object.entries(things)) {\n    if (!('routes' in thing)) continue\n    for (const route of thing.routes) {\n      const prior = routeOwners.get(route)\n      if (prior === undefined) {\n        routeOwners.set(route, thingId)\n      } else {\n        context.addIssue({\n          code: 'custom',\n          message: `route ${route} is already owned by thing ${prior}`,\n          path: ['things', thingId, 'routes'],\n        })\n      }\n    }\n  }\n}\n\nfunction refineApiThing(\n  thingId: string,\n  thing: ApiThing,\n  deployment: NamedDeploymentV2Shape,\n  context: PlacementContext,\n): void {\n  const thingInfrastructure = placementOf(deployment.bindings, thingId)\n  for (const [portIndex, portId] of thing.ports.entries()) {\n    const binding = deployment.request.request.portBindings.find(candidate => candidate.portId === portId)\n    if (binding === undefined) {\n      context.addIssue({\n        code: 'custom',\n        message: `port ${portId} is not bound to a host by the deployment request`,\n        path: ['things', thingId, 'ports', portIndex],\n      })\n      continue\n    }\n    const hostInfrastructure = placementOf(deployment.hostBindings, binding.host)\n    if (hostInfrastructure !== undefined && thingInfrastructure !== undefined && hostInfrastructure !== thingInfrastructure) {\n      context.addIssue({\n        code: 'custom',\n        message: `port ${portId} resolves to host ${binding.host} on infrastructure ${hostInfrastructure}, not the thing's ${thingInfrastructure}`,\n        path: ['things', thingId, 'ports', portIndex],\n      })\n    }\n  }\n}\n\nfunction refineActorBackedThing(\n  thingId: string,\n  thing: ActorBackedThing,\n  deployment: NamedDeploymentV2Shape,\n  context: PlacementContext,\n): void {\n  const thingInfrastructure = placementOf(deployment.bindings, thingId)\n  const actor = deployment.request.request.actors.find(candidate => candidate.instanceId === thing.consumerActor)\n  if (actor === undefined) return\n  const hostInfrastructure = placementOf(deployment.hostBindings, actor.host)\n  if (hostInfrastructure !== undefined && thingInfrastructure !== undefined && hostInfrastructure !== thingInfrastructure) {\n    context.addIssue({\n      code: 'custom',\n      message: `consumer actor ${thing.consumerActor} runs on host ${actor.host} on infrastructure ${hostInfrastructure}, not the thing's ${thingInfrastructure}`,\n      path: ['things', thingId, 'consumerActor'],\n    })\n  }\n}\n\nfunction refineOwnedResourceThing(\n  thingId: string,\n  thing: OwnedResourceThing,\n  deployment: NamedDeploymentV2Shape,\n  context: PlacementContext,\n): void {\n  const resource = deployment.request.request.resources[thing.resourceId]\n  if (resource === undefined || resource.provision === 'external') {\n    context.addIssue({\n      code: 'custom',\n      message: `${thing.kind} thing ${thingId} must name a managed or managed-local resource`,\n      path: ['things', thingId, 'resourceId'],\n    })\n    return\n  }\n  const thingInfrastructure = placementOf(deployment.bindings, thingId)\n  const owner = placementOf(deployment.resourceBindings, thing.resourceId)\n  if (owner !== undefined && thingInfrastructure !== undefined && owner !== thingInfrastructure) {\n    context.addIssue({\n      code: 'custom',\n      message: `${thing.kind} thing ${thingId} must be placed on infrastructure ${owner}, which owns resource ${thing.resourceId}`,\n      path: ['bindings', thingId, 'infrastructure'],\n    })\n  }\n}\n\nfunction refineNamedDeploymentV2(deployment: NamedDeploymentV2Shape, context: PlacementContext): void {\n  refinePlacementCompleteness(deployment, context)\n  refineRouteOwnership(deployment.things, context)\n  for (const [thingId, thing] of Object.entries(deployment.things)) {\n    if (thing.kind === 'api') refineApiThing(thingId, thing, deployment, context)\n    if ('consumerActor' in thing) refineActorBackedThing(thingId, thing, deployment, context)\n    if (thing.kind === 'datalake' || thing.kind === 'event-stream') refineOwnedResourceThing(thingId, thing, deployment, context)\n  }\n}\n\nexport const DappNamedDeploymentV2Zod = z.strictObject({\n  request: DappDeploymentRequestDocumentZod,\n  things: z.record(IdentifierZod, DappDeployableThingZod),\n  bindings: z.record(IdentifierZod, DappInfrastructurePlacementZod),\n  resourceBindings: z.record(IdentifierZod, DappInfrastructurePlacementZod),\n  hostBindings: z.record(IdentifierZod, DappInfrastructurePlacementZod),\n}).superRefine(refineNamedDeploymentV2)\n\nexport type DappNamedDeploymentV2 = z.infer<typeof DappNamedDeploymentV2Zod>\n\nconst PlacementMapFields = ['bindings', 'resourceBindings', 'hostBindings'] as const\n\nexport const DappDeploymentManifestV2DocumentZod = z.strictObject({\n  $schema: z.literal(DappDeploymentJsonSchemaV2Url),\n  schema: z.literal(DappDeploymentManifestSchema),\n  schemaVersion: z.literal(2),\n  projectId: DappIdZod,\n  infrastructure: z.record(IdentifierZod, DappInfrastructureRequirementZod),\n  deployments: z.record(IdentifierZod, DappNamedDeploymentV2Zod),\n}).superRefine((manifest, context) => {\n  for (const [name, deployment] of Object.entries(manifest.deployments)) {\n    for (const field of PlacementMapFields) {\n      for (const [id, placement] of Object.entries(deployment[field])) {\n        if (manifest.infrastructure[placement.infrastructure] === undefined) {\n          context.addIssue({\n            code: 'custom',\n            message: `infrastructure alias ${placement.infrastructure} is not declared in the root registry`,\n            path: ['deployments', name, field, id, 'infrastructure'],\n          })\n        }\n      }\n    }\n  }\n})\n\nexport type DappDeploymentManifestV2 = z.infer<typeof DappDeploymentManifestV2DocumentZod>\n\nfunction sortedRecord<T>(record: Readonly<Record<string, T>>): Record<string, T> {\n  return Object.fromEntries(Object.entries(record).toSorted(([left], [right]) => left.localeCompare(right)))\n}\n\nfunction normalizedThing(thing: DappDeployableThing): DappDeployableThing {\n  if (thing.kind === 'api') {\n    return DappDeployableThingZod.parse({\n      ...thing, ports: [...thing.ports].toSorted(), routes: [...thing.routes].toSorted(),\n    })\n  }\n  if ('routes' in thing) return DappDeployableThingZod.parse({ ...thing, routes: [...thing.routes].toSorted() })\n  return thing.kind === 'publisher' ? DappDeployableThingZod.parse({ ...thing, publicationResources: [...thing.publicationResources].toSorted() }) : DappDeployableThingZod.parse(thing)\n}\n\nfunction normalizedRequest(document: DappDeploymentRequestDocument): DappDeploymentRequestDocument {\n  return DappDeploymentRequestDocumentZod.parse({\n    ...document,\n    request: normalizeDappDeploymentRequest(document.request),\n  })\n}\n\nexport function normalizeDappDeploymentManifestV2(value: unknown): DappDeploymentManifestV2 {\n  const manifest = DappDeploymentManifestV2DocumentZod.parse(value)\n  return DappDeploymentManifestV2DocumentZod.parse({\n    ...manifest,\n    infrastructure: sortedRecord(manifest.infrastructure),\n    deployments: sortedRecord(Object.fromEntries(Object.entries(manifest.deployments).map(([name, deployment]) => [\n      name,\n      {\n        request: normalizedRequest(deployment.request),\n        things: sortedRecord(Object.fromEntries(Object.entries(deployment.things)\n          .map(([thingId, thing]) => [thingId, normalizedThing(thing)]))),\n        bindings: sortedRecord(deployment.bindings),\n        resourceBindings: sortedRecord(deployment.resourceBindings),\n        hostBindings: sortedRecord(deployment.hostBindings),\n      },\n    ]))),\n  })\n}\n\n/** D-002 kind `deployment-manifest`, schema version 2: `xyo-dapp-kit:deployment-manifest:v2\\n`. */\nexport function hashDappDeploymentManifestV2(value: unknown): string {\n  return hashDappDocument({\n    kind: 'deployment-manifest',\n    schema: DappDeploymentManifestV2DocumentZod,\n    schemaVersion: 2,\n  }, normalizeDappDeploymentManifestV2(value)).hash\n}\n\nexport function dappDeploymentJsonSchemaV2() {\n  return {\n    ...z.toJSONSchema(DappDeploymentManifestV2DocumentZod, { target: 'draft-2020-12' }),\n    $id: DappDeploymentJsonSchemaV2Url,\n  }\n}\n\n/**\n * The root entries one named deployment actually references through its three\n * placement maps, keyed by alias and sorted. Unreferenced entries never enter\n * a selected identity; they affect only the exact-source manifest hash.\n */\nexport function selectDappDeploymentInfrastructureV2(\n  manifest: DappDeploymentManifestV2,\n  deploymentName: string,\n): Record<string, DappInfrastructureRequirement> {\n  const deployment = manifest.deployments[deploymentName]\n  if (deployment === undefined) throw new TypeError(`deployment ${deploymentName} is not declared`)\n  const aliases = sortedUnique(PlacementMapFields\n    .flatMap(field => Object.values(deployment[field]).map(placement => placement.infrastructure)))\n  return Object.fromEntries(aliases.map((alias) => {\n    const requirement = manifest.infrastructure[alias]\n    if (requirement === undefined) throw new TypeError(`infrastructure alias ${alias} is not declared`)\n    return [alias, requirement]\n  }))\n}\n\nexport const DappDeploymentManifestV2IdentityZod = z.strictObject({\n  schemaVersion: z.literal(2),\n  deploymentManifestId: HashZod,\n  hashAlgorithm: z.literal(DappDocumentHashAlgorithm),\n})\n\nexport type DappDeploymentManifestV2Identity = z.infer<typeof DappDeploymentManifestV2IdentityZod>\n", "import { asSchema } from '@xyo-network/sdk'\nimport { z } from 'zod'\n\nimport {\n  DappDocumentHashAlgorithm,\n  hashDappDocument,\n} from './canonicalDocument.ts'\nimport { DappInfrastructureKindZod } from './deploymentManifestV2.ts'\nimport {\n  HashZod,\n  IdentifierZod,\n  SemanticVersionZod,\n  XyoSchemaZod,\n} from './identifier.ts'\nimport { JsonObjectZod } from './jsonValue.ts'\nimport {\n  compareCodeUnits,\n  compareNumbers,\n  findSortedUniqueIssue,\n} from './ordering.ts'\n\n/**\n * Public-safe infrastructure identities (D-032). Three hashes travel through\n * the deployment intent, Lock V3, provider target plans, and Composition V3:\n *\n * - `adapterDescriptorHash` binds one pinned, host-admitted adapter\n *   implementation and every contract it supports;\n * - `infrastructureDescriptorHash` binds one registered infrastructure\n *   instance to its kind, scope commitment, and adapter; and\n * - `infrastructurePolicyHash` binds the exact public planning policy the\n *   adapter normalized for that instance.\n *\n * None of them admits a route, account, cluster, server, credential, grant,\n * or alias. Everything protected lives in the host under its own\n * `xyo-dapp-kit-host:` domains.\n */\n// XYO schema strings admit only dot-separated lowercase alphanumeric segments,\n// so compound words are separate segments: `managed.capability`, never\n// `managed-capability`. D-002 kinds and hash domains keep their hyphens.\nexport const DappManagedCapabilityExportContractSchema = asSchema('network.xyo.dapp.managed.capability.export.contract', true)\nexport const DappInfrastructureAdapterDescriptorSchema = asSchema('network.xyo.dapp.infrastructure.adapter.descriptor', true)\nexport const DappInfrastructureDescriptorSchema = asSchema('network.xyo.dapp.infrastructure.descriptor', true)\nexport const DappInfrastructurePolicyIdentitySchema = asSchema('network.xyo.dapp.infrastructure.policy.identity', true)\n\n/** Controller-issued opaque instance identity; the first slice uses UUID URNs. */\nexport const DappInfrastructureIdZod = z.string().regex(/^urn:uuid:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/)\nexport type DappInfrastructureId = z.infer<typeof DappInfrastructureIdZod>\n\n/** `sha256:` plus 64 lowercase hex over a format-defined complete artifact. */\nexport const ContentDigestZod = z.string().regex(/^sha256:[0-9a-f]{64}$/)\n\nconst PositiveIntegerZod = z.number().int().positive()\n\nconst DomainVersionZod = z.strictObject({\n  schema: XyoSchemaZod,\n  schemaVersion: PositiveIntegerZod,\n  schemaHash: HashZod,\n})\n\nfunction compareDomainVersions(left: z.infer<typeof DomainVersionZod>, right: z.infer<typeof DomainVersionZod>): number {\n  return compareCodeUnits(left.schema, right.schema)\n    || compareNumbers(left.schemaVersion, right.schemaVersion)\n    || compareCodeUnits(left.schemaHash, right.schemaHash)\n}\n\ninterface RefinementContext {\n  addIssue: (issue: { code: 'custom'; message: string; path: (number | string)[] }) => void\n}\n\nfunction refineSortedUnique<T>(\n  context: RefinementContext,\n  values: readonly T[],\n  compare: (left: T, right: T) => number,\n  field: string,\n): void {\n  const issue = findSortedUniqueIssue(values, compare, field)\n  if (issue !== undefined) {\n    context.addIssue({\n      code: 'custom', message: issue.message, path: [field, issue.index],\n    })\n  }\n}\n\n// --- managed-capability export contract -----------------------------------\n\nexport const DappManagedCapabilityExportContractV1PreimageZod = z.strictObject({\n  schema: z.literal(DappManagedCapabilityExportContractSchema),\n  schemaVersion: z.literal(1),\n  hashAlgorithm: z.literal(DappDocumentHashAlgorithm),\n  exportContractId: IdentifierZod,\n  exportContractVersion: PositiveIntegerZod,\n  exportNormalizationId: IdentifierZod,\n  identitySchema: XyoSchemaZod,\n  identitySchemaVersion: PositiveIntegerZod,\n  identitySchemaHash: HashZod,\n  producerCapabilityId: IdentifierZod,\n  consumerCapabilityId: IdentifierZod,\n})\nexport type DappManagedCapabilityExportContractV1Preimage = z.infer<typeof DappManagedCapabilityExportContractV1PreimageZod>\n\nexport const DappManagedCapabilityExportContractV1Zod = DappManagedCapabilityExportContractV1PreimageZod\n  .safeExtend({ exportContractHash: HashZod })\nexport type DappManagedCapabilityExportContractV1 = z.infer<typeof DappManagedCapabilityExportContractV1Zod>\n\n/** D-002 kind `managed-capability-export-contract` version 1. */\nexport function hashDappManagedCapabilityExportContractV1(preimage: unknown): string {\n  return hashDappDocument({\n    kind: 'managed-capability-export-contract',\n    schema: DappManagedCapabilityExportContractV1PreimageZod,\n    schemaVersion: 1,\n  }, preimage).hash\n}\n\nexport function verifyDappManagedCapabilityExportContractV1(value: unknown): DappManagedCapabilityExportContractV1 {\n  const contract = DappManagedCapabilityExportContractV1Zod.parse(value)\n  const { exportContractHash, ...preimage } = contract\n  if (hashDappManagedCapabilityExportContractV1(preimage) !== exportContractHash) {\n    throw new TypeError(`export contract ${contract.exportContractId} does not reproduce its exportContractHash`)\n  }\n  return contract\n}\n\nfunction compareExportContracts(\n  left: DappManagedCapabilityExportContractV1,\n  right: DappManagedCapabilityExportContractV1,\n): number {\n  return compareCodeUnits(left.exportContractId, right.exportContractId)\n    || compareNumbers(left.exportContractVersion, right.exportContractVersion)\n}\n\n// --- trusted runtime artifacts --------------------------------------------\n\n/** Closed roles for trusted code an adapter must run inside a managed workload. */\nexport const DappTrustedRuntimeArtifactRoleZod = z.enum(['kubernetes-startup-gate', 'proxmox-bootstrap-agent'])\nexport type DappTrustedRuntimeArtifactRole = z.infer<typeof DappTrustedRuntimeArtifactRoleZod>\n\n/** Closed artifact formats whose complete digest rule the descriptor fixes. */\nexport const DappTrustedRuntimeArtifactFormatZod = z.enum(['oci-image', 'executable-bundle'])\nexport type DappTrustedRuntimeArtifactFormat = z.infer<typeof DappTrustedRuntimeArtifactFormatZod>\n\nexport const DappTrustedRuntimeArtifactZod = z.strictObject({\n  role: DappTrustedRuntimeArtifactRoleZod,\n  artifactFormat: DappTrustedRuntimeArtifactFormatZod,\n  contentDigest: ContentDigestZod,\n  entrypointContractHash: HashZod,\n  platformContractHash: HashZod,\n})\nexport type DappTrustedRuntimeArtifact = z.infer<typeof DappTrustedRuntimeArtifactZod>\n\nfunction compareTrustedRuntimeArtifacts(left: DappTrustedRuntimeArtifact, right: DappTrustedRuntimeArtifact): number {\n  return compareCodeUnits(left.role, right.role)\n    || compareCodeUnits(left.artifactFormat, right.artifactFormat)\n    || compareCodeUnits(left.contentDigest, right.contentDigest)\n    || compareCodeUnits(left.entrypointContractHash, right.entrypointContractHash)\n    || compareCodeUnits(left.platformContractHash, right.platformContractHash)\n}\n\n// --- adapter descriptor ---------------------------------------------------\n\nconst SortedIdentifiersZod = z.array(IdentifierZod)\n\nexport const DappInfrastructureAdapterDescriptorV1PreimageZod = z.strictObject({\n  schema: z.literal(DappInfrastructureAdapterDescriptorSchema),\n  schemaVersion: z.literal(1),\n  hashAlgorithm: z.literal(DappDocumentHashAlgorithm),\n  adapterId: IdentifierZod,\n  adapterVersion: SemanticVersionZod,\n  /** Host-computed over the admitted implementation snapshot; never adapter self-report. */\n  implementationHash: HashZod,\n  infrastructureKind: DappInfrastructureKindZod,\n  scopeIdentityFamily: IdentifierZod,\n  scopeIdentityContractHash: HashZod,\n  scopeProofVersions: z.array(PositiveIntegerZod).min(1),\n  supportedContracts: z.array(DomainVersionZod).min(1),\n  capabilityIds: SortedIdentifiersZod,\n  credentialRequirementIds: SortedIdentifiersZod.min(1),\n  actionKinds: SortedIdentifiersZod.min(1),\n  targetObjectIdentitySchemaVersion: PositiveIntegerZod,\n  targetObjectIdentityContractHash: HashZod,\n  targetObjectRoleNormalizationId: IdentifierZod,\n  targetObjectRoles: SortedIdentifiersZod.min(1),\n  trustedRuntimeArtifacts: z.array(DappTrustedRuntimeArtifactZod),\n  supportedExportContracts: z.array(DappManagedCapabilityExportContractV1Zod),\n}).superRefine((descriptor, context) => {\n  refineSortedUnique(context, descriptor.scopeProofVersions, compareNumbers, 'scopeProofVersions')\n  refineSortedUnique(context, descriptor.supportedContracts, compareDomainVersions, 'supportedContracts')\n  for (const field of ['capabilityIds', 'credentialRequirementIds', 'actionKinds', 'targetObjectRoles'] as const) {\n    refineSortedUnique(context, descriptor[field], compareCodeUnits, field)\n  }\n  refineSortedUnique(context, descriptor.trustedRuntimeArtifacts, compareTrustedRuntimeArtifacts, 'trustedRuntimeArtifacts')\n  refineSortedUnique(context, descriptor.supportedExportContracts, compareExportContracts, 'supportedExportContracts')\n  for (const [index, contract] of descriptor.supportedExportContracts.entries()) {\n    const { exportContractHash, ...preimage } = contract\n    if (hashDappManagedCapabilityExportContractV1(preimage) !== exportContractHash) {\n      context.addIssue({\n        code: 'custom',\n        message: `export contract ${contract.exportContractId} does not reproduce its exportContractHash`,\n        path: ['supportedExportContracts', index, 'exportContractHash'],\n      })\n    }\n  }\n})\nexport type DappInfrastructureAdapterDescriptorV1Preimage = z.infer<typeof DappInfrastructureAdapterDescriptorV1PreimageZod>\n\nexport const DappInfrastructureAdapterDescriptorV1Zod = DappInfrastructureAdapterDescriptorV1PreimageZod\n  .safeExtend({ adapterDescriptorHash: HashZod })\nexport type DappInfrastructureAdapterDescriptorV1 = z.infer<typeof DappInfrastructureAdapterDescriptorV1Zod>\n\n/** D-002 kind `infrastructure-adapter-descriptor` version 1. */\nexport function hashDappInfrastructureAdapterDescriptorV1(preimage: unknown): string {\n  return hashDappDocument({\n    kind: 'infrastructure-adapter-descriptor',\n    schema: DappInfrastructureAdapterDescriptorV1PreimageZod,\n    schemaVersion: 1,\n  }, preimage).hash\n}\n\nexport function verifyDappInfrastructureAdapterDescriptorV1(value: unknown): DappInfrastructureAdapterDescriptorV1 {\n  const descriptor = DappInfrastructureAdapterDescriptorV1Zod.parse(value)\n  const { adapterDescriptorHash, ...preimage } = descriptor\n  if (hashDappInfrastructureAdapterDescriptorV1(preimage) !== adapterDescriptorHash) {\n    throw new TypeError(`adapter descriptor ${descriptor.adapterId}@${descriptor.adapterVersion} does not reproduce its adapterDescriptorHash`)\n  }\n  return descriptor\n}\n\n// --- infrastructure descriptor --------------------------------------------\n\nexport const DappInfrastructureDescriptorV1PreimageZod = z.strictObject({\n  schema: z.literal(DappInfrastructureDescriptorSchema),\n  schemaVersion: z.literal(1),\n  hashAlgorithm: z.literal(DappDocumentHashAlgorithm),\n  infrastructureId: DappInfrastructureIdZod,\n  kind: DappInfrastructureKindZod,\n  expectedScopeCommitment: HashZod,\n  adapterDescriptorHash: HashZod,\n})\nexport type DappInfrastructureDescriptorV1Preimage = z.infer<typeof DappInfrastructureDescriptorV1PreimageZod>\n\nexport const DappInfrastructureDescriptorV1Zod = DappInfrastructureDescriptorV1PreimageZod\n  .safeExtend({ infrastructureDescriptorHash: HashZod })\nexport type DappInfrastructureDescriptorV1 = z.infer<typeof DappInfrastructureDescriptorV1Zod>\n\n/** D-002 kind `infrastructure-descriptor` version 1. */\nexport function hashDappInfrastructureDescriptorV1(preimage: unknown): string {\n  return hashDappDocument({\n    kind: 'infrastructure-descriptor',\n    schema: DappInfrastructureDescriptorV1PreimageZod,\n    schemaVersion: 1,\n  }, preimage).hash\n}\n\nexport function verifyDappInfrastructureDescriptorV1(value: unknown): DappInfrastructureDescriptorV1 {\n  const descriptor = DappInfrastructureDescriptorV1Zod.parse(value)\n  const { infrastructureDescriptorHash, ...preimage } = descriptor\n  if (hashDappInfrastructureDescriptorV1(preimage) !== infrastructureDescriptorHash) {\n    throw new TypeError(`infrastructure descriptor ${descriptor.infrastructureId} does not reproduce its infrastructureDescriptorHash`)\n  }\n  return descriptor\n}\n\n// --- public planning policy identity --------------------------------------\n\nexport const DappInfrastructurePolicyIdentityV1PreimageZod = z.strictObject({\n  schema: z.literal(DappInfrastructurePolicyIdentitySchema),\n  schemaVersion: z.literal(1),\n  hashAlgorithm: z.literal(DappDocumentHashAlgorithm),\n  kind: DappInfrastructureKindZod,\n  adapterDescriptorHash: HashZod,\n  policySchema: XyoSchemaZod,\n  policySchemaVersion: PositiveIntegerZod,\n  policySchemaHash: HashZod,\n  /** Exact adapter-normalized strict public-safe policy; the adapter validates it against `policySchemaHash`. */\n  policy: JsonObjectZod,\n})\nexport type DappInfrastructurePolicyIdentityV1Preimage = z.infer<typeof DappInfrastructurePolicyIdentityV1PreimageZod>\n\nexport const DappInfrastructurePolicyIdentityV1Zod = DappInfrastructurePolicyIdentityV1PreimageZod\n  .safeExtend({ infrastructurePolicyHash: HashZod })\nexport type DappInfrastructurePolicyIdentityV1 = z.infer<typeof DappInfrastructurePolicyIdentityV1Zod>\n\n/** D-002 kind `infrastructure-policy` version 1. */\nexport function hashDappInfrastructurePolicyIdentityV1(preimage: unknown): string {\n  return hashDappDocument({\n    kind: 'infrastructure-policy',\n    schema: DappInfrastructurePolicyIdentityV1PreimageZod,\n    schemaVersion: 1,\n  }, preimage).hash\n}\n\nexport function verifyDappInfrastructurePolicyIdentityV1(value: unknown): DappInfrastructurePolicyIdentityV1 {\n  const identity = DappInfrastructurePolicyIdentityV1Zod.parse(value)\n  const { infrastructurePolicyHash, ...preimage } = identity\n  if (hashDappInfrastructurePolicyIdentityV1(preimage) !== infrastructurePolicyHash) {\n    throw new TypeError(`infrastructure policy for ${identity.kind} does not reproduce its infrastructurePolicyHash`)\n  }\n  return identity\n}\n\n// --- selected infrastructure (the safe projection of one registered entry) --\n\n/**\n * The public-safe projection of one selected, registered infrastructure\n * instance. The host derives it from a protected operator entry; the portable\n * kit only checks that its descriptor hash reproduces from its own fields, so\n * a lock or intent can never carry an instance whose kind, scope commitment,\n * and adapter disagree with its descriptor identity.\n */\nexport const DappSelectedInfrastructureV1Zod = z.strictObject({\n  infrastructureId: DappInfrastructureIdZod,\n  kind: DappInfrastructureKindZod,\n  adapterId: IdentifierZod,\n  adapterVersion: SemanticVersionZod,\n  adapterDescriptorHash: HashZod,\n  infrastructureDescriptorHash: HashZod,\n  infrastructurePolicyHash: HashZod,\n  expectedScopeCommitment: HashZod,\n}).superRefine((selected, context) => {\n  const expected = hashDappInfrastructureDescriptorV1({\n    schema: DappInfrastructureDescriptorSchema,\n    schemaVersion: 1,\n    hashAlgorithm: DappDocumentHashAlgorithm,\n    infrastructureId: selected.infrastructureId,\n    kind: selected.kind,\n    expectedScopeCommitment: selected.expectedScopeCommitment,\n    adapterDescriptorHash: selected.adapterDescriptorHash,\n  })\n  if (expected !== selected.infrastructureDescriptorHash) {\n    context.addIssue({\n      code: 'custom',\n      message: `infrastructureDescriptorHash for ${selected.infrastructureId} does not reproduce from its kind, scope commitment, and adapter descriptor`,\n      path: ['infrastructureDescriptorHash'],\n    })\n  }\n})\nexport type DappSelectedInfrastructureV1 = z.infer<typeof DappSelectedInfrastructureV1Zod>\n\nexport function compareDappSelectedInfrastructureV1(\n  left: DappSelectedInfrastructureV1,\n  right: DappSelectedInfrastructureV1,\n): number {\n  return compareCodeUnits(left.infrastructureId, right.infrastructureId)\n}\n", "/**\n * Bytewise ordering helpers for semantic-set arrays. Identifiers, hashes, and\n * URNs in dapp-kit documents are ASCII, so UTF-16 code-unit order equals UTF-8\n * byte order and matches the JCS property order used for hashing.\n */\nexport function compareCodeUnits(left: string, right: string): number {\n  if (left === right) return 0\n  return left < right ? -1 : 1\n}\n\nexport function compareNumbers(left: number, right: number): number {\n  return left === right ? 0 : (left < right ? -1 : 1)\n}\n\nexport interface SortedUniqueIssue {\n  index: number\n  message: string\n}\n\n/**\n * Reports the first position at which `values` stops being strictly ascending\n * under `compare`; equal neighbours are duplicates, descending neighbours are\n * unsorted. Returns `undefined` when the array is sorted and unique.\n */\nexport function findSortedUniqueIssue<T>(\n  values: readonly T[],\n  compare: (left: T, right: T) => number,\n  subject: string,\n): SortedUniqueIssue | undefined {\n  for (let index = 1; index < values.length; index++) {\n    const order = compare(values[index - 1], values[index])\n    if (order > 0) return { index, message: `${subject} must be sorted` }\n    if (order === 0) return { index, message: `${subject} must be unique` }\n  }\n  return undefined\n}\n\nexport function isSortedUniqueStrings(values: readonly string[]): boolean {\n  return findSortedUniqueIssue(values, compareCodeUnits, 'values') === undefined\n}\n", "import { asSchema } from '@xyo-network/sdk'\nimport { z } from 'zod'\n\nimport { DappDefinitionZod } from './dappDefinition.ts'\nimport { DappDeploymentRequestDocumentZod } from './deploymentRequest.ts'\nimport {\n  DappIdZod,\n  HashZod,\n  IdentifierZod,\n  SemanticVersionZod,\n} from './identifier.ts'\nimport { DappArtifactDeclarationZod } from './projectArtifact.ts'\nexport const DappProjectManifestSchema = asSchema('network.xyo.dapp.project', true)\nexport const DappProjectJsonSchemaUrl = 'https://schemas.xyo.network/dapp-kit/project/v1.json' as const\n\nexport const DappProjectManifestDocumentZod = z.strictObject({\n  $schema: z.literal(DappProjectJsonSchemaUrl),\n  schema: z.literal(DappProjectManifestSchema),\n  schemaVersion: z.literal(1),\n  projectId: DappIdZod,\n  definition: DappDefinitionZod,\n  artifacts: z.record(IdentifierZod, DappArtifactDeclarationZod),\n  deployments: z.record(IdentifierZod, DappDeploymentRequestDocumentZod),\n})\n\nexport type DappProjectManifest = z.infer<typeof DappProjectManifestDocumentZod>\n\nexport function dappProjectJsonSchema() {\n  return {\n    ...z.toJSONSchema(DappProjectManifestDocumentZod, { target: 'draft-2020-12' }),\n    $id: DappProjectJsonSchemaUrl,\n  }\n}\n\nexport const GitCommitZod = z.string().regex(/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/)\n\nexport const DappProjectSourceIdentityZod = z.strictObject({\n  remote: z.string().min(1).max(2048).optional(),\n  commit: GitCommitZod,\n  worktree: z.enum(['clean', 'dirty']),\n  buildInputHash: HashZod,\n}).transform(({ remote, ...identity }) => {\n  return remote === undefined ? identity : { ...identity, remote }\n})\n\nexport type DappProjectSourceIdentity = z.infer<typeof DappProjectSourceIdentityZod>\n\nexport const DappPackageManagerIdentityZod = z.strictObject({\n  name: z.enum(['pnpm', 'npm', 'yarn']),\n  version: SemanticVersionZod,\n  lockfileHash: HashZod,\n})\n\nexport type DappPackageManagerIdentity = z.infer<typeof DappPackageManagerIdentityZod>\n", "import { z } from 'zod'\n\nimport type { DappDefinition } from './dappDefinition.ts'\nimport type { DappDeploymentRequest } from './deploymentRequest.ts'\nimport type { DappResourceRequest } from './deploymentResource.ts'\nimport type { AuxiliaryStorageClass } from './profile.ts'\nimport type { DappHostArtifactDeclaration } from './projectArtifact.ts'\nimport type { DappProjectManifest } from './projectManifestModel.ts'\nimport { DappProjectManifestDocumentZod } from './projectManifestModel.ts'\n\nexport const DappProjectIssueCodes = [\n  'project.actor-host-unsupported',\n  'project.actor-role-unknown',\n  'project.auxiliary-store-class-mismatch',\n  'project.datalake-resource-mismatch',\n  'project.definition-mismatch',\n  'project.external-source-resource-mismatch',\n  'project.event-subscription-stream-mismatch',\n  'project.identity-continuity-invalid',\n  'project.identity-resource-mismatch',\n  'project.identity-role-unknown',\n  'project.invalid',\n  'project.network-resource-mismatch',\n  'project.port-binding-invalid',\n  'project.profile-mismatch',\n  'project.projection-resource-mismatch',\n  'project.resource-missing',\n  'project.resource-unused',\n  'project.side-channel-resource-mismatch',\n  'project.secret-continuity-invalid',\n] as const\n\nexport const DappProjectIssueCodeZod = z.enum(DappProjectIssueCodes)\nexport type DappProjectIssueCode = z.infer<typeof DappProjectIssueCodeZod>\n\nexport interface DappProjectIssue {\n  code: DappProjectIssueCode\n  message: string\n  path: (number | string)[]\n}\n\nexport interface DappProjectValidationSuccess {\n  success: true\n  value: DappProjectManifest\n}\n\nexport interface DappProjectValidationFailure {\n  issues: DappProjectIssue[]\n  success: false\n}\n\nexport type DappProjectValidationResult = DappProjectValidationFailure | DappProjectValidationSuccess\n\nfunction projectIssue(\n  code: DappProjectIssueCode,\n  message: string,\n  path: (number | string)[],\n): DappProjectIssue {\n  return {\n    code,\n    message,\n    path,\n  }\n}\n\nfunction resourceAt(\n  request: DappDeploymentRequest,\n  resourceId: string,\n  path: (number | string)[],\n  issues: DappProjectIssue[],\n): DappResourceRequest | undefined {\n  const resource = request.resources[resourceId]\n  if (resource === undefined) {\n    issues.push(projectIssue('project.resource-missing', `resource ${resourceId} is not declared`, path))\n  }\n  return resource\n}\n\nfunction resourceClassIssue(\n  resource: DappResourceRequest | undefined,\n  expectedClass: DappResourceRequest['class'],\n  code: DappProjectIssueCode,\n  path: (number | string)[],\n  issues: DappProjectIssue[],\n): void {\n  if (resource !== undefined && resource.class !== expectedClass) {\n    issues.push(projectIssue(code, `resource must have class ${expectedClass}`, path))\n  }\n}\n\nfunction addActorAndPortIssues(\n  definition: DappDefinition,\n  manifest: DappProjectManifest,\n  deploymentName: string,\n  request: DappDeploymentRequest,\n  issues: DappProjectIssue[],\n): void {\n  const supportedHosts = new Set(Object.values(manifest.artifacts)\n    .filter((artifact): artifact is DappHostArtifactDeclaration => artifact.kind === 'dapp-host')\n    .flatMap(artifact => artifact.hosts))\n  for (const [index, actor] of request.actors.entries()) {\n    const actorDefinition = definition.actors.find(candidate => candidate.roleId === actor.roleId)\n    if (actorDefinition === undefined) {\n      issues.push(projectIssue(\n        'project.actor-role-unknown',\n        'deployment actor role is not declared by the definition',\n        ['deployments', deploymentName, 'actors', index, 'roleId'],\n      ))\n    } else if (!actorDefinition.supportedExecutionModes.includes(actor.executionMode)) {\n      issues.push(projectIssue(\n        'project.profile-mismatch',\n        'deployment actor execution mode is not supported by the definition',\n        ['deployments', deploymentName, 'actors', index, 'executionMode'],\n      ))\n    }\n    if (!supportedHosts.has(actor.host)) {\n      issues.push(projectIssue(\n        'project.actor-host-unsupported',\n        'deployment actor host is not supplied by an admitted dapp-host artifact',\n        ['deployments', deploymentName, 'actors', index, 'host'],\n      ))\n    }\n  }\n\n  if (request.supervision.policy === 'sequential') {\n    const actorIds = new Set(request.actors.map(actor => actor.instanceId))\n    const orderIds = new Set(request.supervision.actorOrder)\n    if (actorIds.size !== request.actors.length\n      || orderIds.size !== request.supervision.actorOrder.length\n      || actorIds.size !== orderIds.size\n      || [...actorIds].some(actorId => !orderIds.has(actorId))) {\n      issues.push(projectIssue(\n        'project.profile-mismatch',\n        'sequential supervision order must contain every actor instance exactly once',\n        ['deployments', deploymentName, 'supervision', 'actorOrder'],\n      ))\n    }\n  }\n\n  const definitionPorts = new Set(definition.ports.map(port => port.portId))\n  const boundPorts = new Set<string>()\n  for (const [index, binding] of request.portBindings.entries()) {\n    if (!definitionPorts.has(binding.portId) || !supportedHosts.has(binding.host) || boundPorts.has(binding.portId)) {\n      issues.push(projectIssue(\n        'project.port-binding-invalid',\n        'each definition port must be bound once to a supported host',\n        ['deployments', deploymentName, 'portBindings', index],\n      ))\n    }\n    boundPorts.add(binding.portId)\n  }\n  if (boundPorts.size !== definitionPorts.size || [...definitionPorts].some(portId => !boundPorts.has(portId))) {\n    issues.push(projectIssue(\n      'project.port-binding-invalid',\n      'deployment port bindings must contain every definition port exactly once',\n      ['deployments', deploymentName, 'portBindings'],\n    ))\n  }\n}\n\nfunction addBasicProfileIssues(\n  definition: DappDefinition,\n  deploymentName: string,\n  request: DappDeploymentRequest,\n  issues: DappProjectIssue[],\n): void {\n  const profilePath = ['deployments', deploymentName, 'policies']\n  if (request.policies.sideChannel.profile !== definition.coordination.profile) {\n    issues.push(projectIssue(\n      'project.profile-mismatch',\n      'side-channel request profile must equal the definition profile',\n      [...profilePath, 'sideChannel', 'profile'],\n    ))\n  }\n  if (request.policies.externalInteraction.mode !== definition.externalInteraction.mode) {\n    issues.push(projectIssue(\n      'project.profile-mismatch',\n      'external-interaction request mode must equal the definition mode',\n      [...profilePath, 'externalInteraction', 'mode'],\n    ))\n  }\n  if (request.policies.projection.profile !== definition.durability.projection.profile) {\n    issues.push(projectIssue(\n      'project.profile-mismatch',\n      'projection request profile must equal the definition profile',\n      [...profilePath, 'projection', 'profile'],\n    ))\n  }\n}\n\nfunction addDatalakeProfileIssues(\n  definition: DappDefinition,\n  deploymentName: string,\n  request: DappDeploymentRequest,\n  issues: DappProjectIssue[],\n): void {\n  const definitionPolicy = definition.durability.datalake\n  const requestPolicy = request.policies.datalake\n  const isModeCompatible = definitionPolicy.mode === 'none'\n    ? requestPolicy.mode === 'none'\n    : definitionPolicy.mode === 'optional'\n      ? requestPolicy.mode !== 'required'\n      : requestPolicy.mode === 'required'\n  if (!isModeCompatible) {\n    issues.push(projectIssue(\n      'project.profile-mismatch',\n      'datalake request mode is incompatible with the definition',\n      ['deployments', deploymentName, 'policies', 'datalake', 'mode'],\n    ))\n    return\n  }\n  if (definitionPolicy.mode === 'none' || requestPolicy.mode === 'none') return\n\n  const isPolicyCompatible = definitionPolicy.allowedReadAccess.includes(requestPolicy.readAccess)\n    && definitionPolicy.allowedContentProtection.includes(requestPolicy.contentProtection)\n    && requestPolicy.requiredCopies >= definitionPolicy.minimumCopies\n    && requestPolicy.retentionSeconds >= definitionPolicy.minimumRetentionSeconds\n    && requestPolicy.unavailableBehavior === definitionPolicy.unavailableBehavior\n  if (!isPolicyCompatible) {\n    issues.push(projectIssue(\n      'project.profile-mismatch',\n      'datalake request weakens definition access, protection, availability, or retention',\n      ['deployments', deploymentName, 'policies', 'datalake'],\n    ))\n  }\n}\n\nfunction addBindingProfileIssues(\n  deploymentName: string,\n  request: DappDeploymentRequest,\n  issues: DappProjectIssue[],\n): void {\n  const roleIds = request.identityBindings.map(binding => binding.roleId)\n  const resourceIds = request.identityBindings.map(binding => binding.resource)\n  const unique = new Set(roleIds)\n  const unique2 = new Set(resourceIds)\n  if (unique.size !== roleIds.length || unique2.size !== resourceIds.length) {\n    issues.push(projectIssue(\n      'project.profile-mismatch',\n      'identity roles and resources may each be bound once',\n      ['deployments', deploymentName, 'identityBindings'],\n    ))\n  }\n\n  const auxiliaryClasses = request.auxiliaryStores.map(binding => binding.class)\n  const unique3 = new Set(auxiliaryClasses)\n  if (unique3.size !== auxiliaryClasses.length) {\n    issues.push(projectIssue(\n      'project.profile-mismatch',\n      'auxiliary storage classes may each be bound once',\n      ['deployments', deploymentName, 'auxiliaryStores'],\n    ))\n  }\n\n  const retainedJournal = Object.values(request.resources).some(resource => (\n    resource.class === 'effect-journal' && resource.persistence === 'retained'\n  ))\n  const ephemeralIdentity = Object.values(request.resources).some(resource => (\n    resource.class === 'identity' && resource.mode === 'ephemeral-local'\n  ))\n  if (retainedJournal && ephemeralIdentity) {\n    issues.push(projectIssue(\n      'project.identity-continuity-invalid',\n      'retained effect state cannot depend on an ephemeral local identity',\n      ['deployments', deploymentName, 'resources'],\n    ))\n  }\n  const ephemeralSecret = Object.values(request.resources).some(resource => (\n    resource.class === 'secret' && resource.persistence === 'ephemeral'\n  ))\n  if (retainedJournal && ephemeralSecret) {\n    issues.push(projectIssue(\n      'project.secret-continuity-invalid',\n      'retained effect state cannot depend on an ephemeral local secret',\n      ['deployments', deploymentName, 'resources'],\n    ))\n  }\n}\n\nfunction addUnusedResourceIssues(\n  deploymentName: string,\n  request: DappDeploymentRequest,\n  usedResources: ReadonlySet<string>,\n  issues: DappProjectIssue[],\n): void {\n  for (const resourceId of Object.keys(request.resources).toSorted()) {\n    if (!usedResources.has(resourceId)) {\n      issues.push(projectIssue(\n        'project.resource-unused',\n        `resource ${resourceId} is not selected by the deployment`,\n        ['deployments', deploymentName, 'resources', resourceId],\n      ))\n    }\n  }\n}\n\nfunction addEventResourceIssues(\n  deploymentName: string,\n  request: DappDeploymentRequest,\n  markResource: (resourceId: string, path: (number | string)[]) => DappResourceRequest | undefined,\n  usedResources: Set<string>,\n  issues: DappProjectIssue[],\n): void {\n  for (const [resourceId, resource] of Object.entries(request.resources)) {\n    if (resource.class !== 'event-subscription') continue\n    usedResources.add(resourceId)\n    const path = ['deployments', deploymentName, 'resources', resourceId, 'streamResource']\n    resourceClassIssue(\n      markResource(resource.streamResource, path),\n      'event-stream',\n      'project.event-subscription-stream-mismatch',\n      path,\n      issues,\n    )\n  }\n}\n\nfunction markApplicationProviderResources(\n  deploymentName: string,\n  request: DappDeploymentRequest,\n  markResource: (resourceId: string, path: (number | string)[]) => DappResourceRequest | undefined,\n): void {\n  for (const [index, selection] of (request.applicationProviders ?? []).entries()) {\n    for (const [moniker, binding] of Object.entries(selection.dependencies)) {\n      if (binding.kind === 'resource') markResource(binding.resourceId, ['deployments', deploymentName, 'applicationProviders', index, 'dependencies', moniker])\n    }\n  }\n}\n\nfunction addDatalakeResourceIssues(\n  deploymentName: string,\n  request: DappDeploymentRequest,\n  markResource: (resourceId: string, path: (number | string)[]) => DappResourceRequest | undefined,\n  issues: DappProjectIssue[],\n): void {\n  const datalake = request.policies.datalake\n  if (datalake.mode !== 'none') {\n    resourceClassIssue(\n      markResource(datalake.resource, ['deployments', deploymentName, 'policies', 'datalake', 'resource']),\n      'datalake',\n      'project.datalake-resource-mismatch',\n      ['deployments', deploymentName, 'policies', 'datalake', 'resource'],\n      issues,\n    )\n  }\n}\n\nfunction addDeploymentResourceIssues(\n  definition: DappDefinition,\n  deploymentName: string,\n  request: DappDeploymentRequest,\n  issues: DappProjectIssue[],\n): void {\n  const usedResources = new Set<string>()\n  const markResource = (resourceId: string, path: (number | string)[]) => {\n    usedResources.add(resourceId)\n    return resourceAt(request, resourceId, path, issues)\n  }\n\n  resourceClassIssue(\n    markResource(request.network.resource, ['deployments', deploymentName, 'network', 'resource']),\n    'xl1-network',\n    'project.network-resource-mismatch',\n    ['deployments', deploymentName, 'network', 'resource'],\n    issues,\n  )\n\n  const identityRoles = new Set(definition.identityRoles)\n  for (const [index, binding] of request.identityBindings.entries()) {\n    if (!identityRoles.has(binding.roleId)) {\n      issues.push(projectIssue(\n        'project.identity-role-unknown',\n        'identity role is not declared by the definition',\n        ['deployments', deploymentName, 'identityBindings', index, 'roleId'],\n      ))\n    }\n    resourceClassIssue(\n      markResource(binding.resource, ['deployments', deploymentName, 'identityBindings', index, 'resource']),\n      'identity',\n      'project.identity-resource-mismatch',\n      ['deployments', deploymentName, 'identityBindings', index, 'resource'],\n      issues,\n    )\n  }\n\n  const auxiliaryClassMap: Record<AuxiliaryStorageClass, DappResourceRequest['class'] | undefined> = {\n    'secret': 'secret',\n    'private-draft': undefined,\n    'effect-journal': 'effect-journal',\n    'replay-checkpoint': 'checkpoint-store',\n    'projection': 'projection-store',\n    'disposable-cache': undefined,\n  }\n  for (const [index, binding] of request.auxiliaryStores.entries()) {\n    const resource = markResource(binding.resource, ['deployments', deploymentName, 'auxiliaryStores', index, 'resource'])\n    const expectedClass = auxiliaryClassMap[binding.class]\n    if (expectedClass === undefined || resource?.class !== expectedClass) {\n      issues.push(projectIssue(\n        'project.auxiliary-store-class-mismatch',\n        `auxiliary store ${binding.class} is not supported by the selected resource class`,\n        ['deployments', deploymentName, 'auxiliaryStores', index],\n      ))\n    }\n  }\n\n  addDatalakeResourceIssues(deploymentName, request, markResource, issues)\n\n  const projection = request.policies.projection\n  if (projection.profile !== 'none') {\n    resourceClassIssue(\n      markResource(projection.projectionResource, ['deployments', deploymentName, 'policies', 'projection', 'projectionResource']),\n      'projection-store',\n      'project.projection-resource-mismatch',\n      ['deployments', deploymentName, 'policies', 'projection', 'projectionResource'],\n      issues,\n    )\n    if (projection.profile !== 'ephemeral') {\n      resourceClassIssue(\n        markResource(projection.checkpointResource, ['deployments', deploymentName, 'policies', 'projection', 'checkpointResource']),\n        'checkpoint-store',\n        'project.projection-resource-mismatch',\n        ['deployments', deploymentName, 'policies', 'projection', 'checkpointResource'],\n        issues,\n      )\n    }\n  }\n\n  const sideChannel = request.policies.sideChannel\n  if (sideChannel.profile !== 'none') {\n    resourceClassIssue(\n      markResource(sideChannel.resource, ['deployments', deploymentName, 'policies', 'sideChannel', 'resource']),\n      'side-channel',\n      'project.side-channel-resource-mismatch',\n      ['deployments', deploymentName, 'policies', 'sideChannel', 'resource'],\n      issues,\n    )\n  }\n\n  const externalInteraction = request.policies.externalInteraction\n  if (externalInteraction.mode !== 'none') {\n    for (const [index, source] of externalInteraction.sources.entries()) {\n      const path = ['deployments', deploymentName, 'policies', 'externalInteraction', 'sources', index, 'resource']\n      resourceClassIssue(\n        markResource(source.resource, path),\n        'external-source',\n        'project.external-source-resource-mismatch',\n        path,\n        issues,\n      )\n    }\n  }\n\n  markApplicationProviderResources(deploymentName, request, markResource)\n  addEventResourceIssues(deploymentName, request, markResource, usedResources, issues)\n  addUnusedResourceIssues(deploymentName, request, usedResources, issues)\n}\n\nfunction semanticProjectIssues(manifest: DappProjectManifest): DappProjectIssue[] {\n  const issues: DappProjectIssue[] = []\n  if (manifest.projectId !== manifest.definition.dappId) {\n    issues.push(projectIssue(\n      'project.definition-mismatch',\n      'project ID must equal the embedded definition dApp ID',\n      ['projectId'],\n    ))\n  }\n  for (const [deploymentName, document] of Object.entries(manifest.deployments)) {\n    if (document.projectId !== manifest.projectId || document.deploymentName !== deploymentName) {\n      issues.push(projectIssue(\n        'project.definition-mismatch',\n        'deployment request identity must match its project and map key',\n        ['deployments', deploymentName],\n      ))\n    }\n    addActorAndPortIssues(manifest.definition, manifest, deploymentName, document.request, issues)\n    addBasicProfileIssues(manifest.definition, deploymentName, document.request, issues)\n    addDatalakeProfileIssues(manifest.definition, deploymentName, document.request, issues)\n    addBindingProfileIssues(deploymentName, document.request, issues)\n    addDeploymentResourceIssues(manifest.definition, deploymentName, document.request, issues)\n  }\n  return issues\n}\n\nfunction issuePath(path: PropertyKey[]): (number | string)[] {\n  return path.map(value => typeof value === 'symbol' ? value.toString() : value)\n}\n\nexport function validateDappProjectManifest(value: unknown): DappProjectValidationResult {\n  const result = DappProjectManifestDocumentZod.safeParse(value)\n  if (!result.success) {\n    return {\n      issues: result.error.issues.map(issue => projectIssue('project.invalid', issue.message, issuePath(issue.path))),\n      success: false,\n    }\n  }\n  const issues = semanticProjectIssues(result.data)\n  return issues.length === 0\n    ? { success: true, value: result.data }\n    : { issues, success: false }\n}\n", "import { hashDappDocument } from './canonicalDocument.ts'\nimport {\n  DappDeploymentRequestDocumentZod,\n  normalizeDappDeploymentRequest,\n} from './deploymentRequest.ts'\nimport { normalizeDappDefinition } from './planNormalization.ts'\nimport type { DappProjectManifest } from './projectManifestModel.ts'\nimport { DappProjectManifestDocumentZod } from './projectManifestModel.ts'\nimport { validateDappProjectManifest } from './projectManifestValidation.ts'\n\nexport function normalizeDappProjectManifest(value: unknown): DappProjectManifest {\n  const result = validateDappProjectManifest(value)\n  if (!result.success) {\n    throw new TypeError(result.issues.map(issue => `${issue.code}: ${issue.message}`).join('; '))\n  }\n  const deployments = Object.fromEntries(Object.entries(result.value.deployments)\n    .toSorted(([left], [right]) => left.localeCompare(right))\n    .map(([name, document]) => [name, {\n      ...document,\n      request: normalizeDappDeploymentRequest(document.request),\n    }]))\n  const artifacts = Object.fromEntries(Object.entries(result.value.artifacts)\n    .toSorted(([left], [right]) => left.localeCompare(right))\n    .map(([name, artifact]) => [name, artifact.kind === 'dapp-host'\n      ? { ...artifact, hosts: [...artifact.hosts].toSorted() }\n      : artifact]))\n  return DappProjectManifestDocumentZod.parse({\n    ...result.value,\n    artifacts,\n    definition: normalizeDappDefinition(result.value.definition),\n    deployments,\n  })\n}\n\nexport function hashDappProjectManifest(value: unknown): string {\n  const normalized = normalizeDappProjectManifest(value)\n  return hashDappDocument({\n    kind: 'project-manifest',\n    schema: DappProjectManifestDocumentZod,\n    schemaVersion: 1,\n  }, normalized).hash\n}\n\nexport function hashDappDeploymentRequest(value: unknown): string {\n  const document = DappDeploymentRequestDocumentZod.parse(value)\n  return hashDappDocument({\n    kind: 'deployment-request',\n    schema: DappDeploymentRequestDocumentZod,\n    schemaVersion: 1,\n  }, {\n    ...document,\n    request: normalizeDappDeploymentRequest(document.request),\n  }).hash\n}\n", "import { asSchema } from '@xyo-network/sdk'\nimport { z } from 'zod'\n\nimport type { ApplicationProviderDescriptor } from './applicationProviderDescriptor.ts'\nimport { ApplicationProviderDescriptorZod } from './applicationProviderDescriptor.ts'\nimport {\n  canonicalizeIJson,\n  DappDocumentHashAlgorithm,\n  hashDappDocument,\n} from './canonicalDocument.ts'\nimport { DappConfigurationZod } from './dappConfiguration.ts'\nimport {\n  resolveDappDeployment,\n  ResolvedDappResourceZod,\n} from './deploymentResolution.ts'\nimport type { DappEnvironmentCatalog } from './environmentCatalog.ts'\nimport { DappEnvironmentCatalogZod } from './environmentCatalog.ts'\nimport {\n  HashZod,\n  IdentifierZod,\n  SemanticVersionZod,\n} from './identifier.ts'\nimport type { InstalledDescriptorMetadata } from './plan.ts'\nimport {\n  createDappPlan,\n  DappPlanZod,\n  InstalledDescriptorMetadataZod,\n} from './plan.ts'\nimport { hashDappDeploymentRequest, hashDappProjectManifest } from './projectManifest.ts'\nimport {\n  DappPackageManagerIdentityZod,\n  DappProjectManifestDocumentZod,\n  DappProjectSourceIdentityZod,\n} from './projectManifestModel.ts'\nexport const DappDeploymentLockSchema = asSchema('network.xyo.dapp.deployment.lock', true)\n\nexport const DappArtifactLockZod = z.strictObject({\n  artifactId: IdentifierZod,\n  artifactManifestHash: HashZod,\n  contentRoot: HashZod,\n})\n\nexport type DappArtifactLock = z.infer<typeof DappArtifactLockZod>\n\nexport const DappDeploymentLockPreimageZod = z.strictObject({\n  schema: z.literal(DappDeploymentLockSchema),\n  schemaVersion: z.literal(1),\n  hashAlgorithm: z.literal(DappDocumentHashAlgorithm),\n  project: z.strictObject({\n    schemaVersion: z.literal(1),\n    projectHash: HashZod,\n  }),\n  deployment: z.strictObject({\n    name: IdentifierZod,\n    requestHash: HashZod,\n  }),\n  definitionHash: HashZod,\n  configurationHash: HashZod,\n  configuration: DappConfigurationZod,\n  plan: DappPlanZod,\n  source: DappProjectSourceIdentityZod,\n  packageManager: DappPackageManagerIdentityZod,\n  environment: z.strictObject({\n    catalogId: IdentifierZod,\n    catalogVersion: SemanticVersionZod,\n  }),\n  resources: z.array(ResolvedDappResourceZod),\n  artifacts: z.array(DappArtifactLockZod),\n  promotable: z.boolean(),\n}).superRefine((lock, context) => {\n  const resourceIds = lock.resources.map(resource => resource.resourceId)\n  const unique = new Set(resourceIds)\n  if (unique.size !== resourceIds.length) {\n    context.addIssue({\n      code: 'custom', message: 'resource IDs must be unique', path: ['resources'],\n    })\n  }\n  for (const selection of lock.configuration.applicationProviders ?? []) {\n    if (lock.artifacts.every(artifact => artifact.artifactId !== selection.artifactId)) {\n      context.addIssue({\n        code: 'custom', message: 'application Provider artifact is not admitted in this lock', path: ['artifacts'],\n      })\n    }\n  }\n  const artifactIds = lock.artifacts.map(artifact => artifact.artifactId)\n  const unique2 = new Set(artifactIds)\n  if (unique2.size !== artifactIds.length) {\n    context.addIssue({\n      code: 'custom', message: 'artifact IDs must be unique', path: ['artifacts'],\n    })\n  }\n})\n\nexport type DappDeploymentLockPreimage = z.infer<typeof DappDeploymentLockPreimageZod>\n\nexport const DappDeploymentLockZod = DappDeploymentLockPreimageZod.safeExtend({ lockId: HashZod })\nexport type DappDeploymentLock = z.infer<typeof DappDeploymentLockZod>\n\nexport const DappDeploymentLockIssueCodes = [\n  'deployment.lock-input-invalid',\n  'deployment.lock-plan-invalid',\n  'deployment.lock-resolution-invalid',\n  'deployment.lock-verification-failed',\n] as const\n\nexport const DappDeploymentLockIssueCodeZod = z.enum(DappDeploymentLockIssueCodes)\nexport type DappDeploymentLockIssueCode = z.infer<typeof DappDeploymentLockIssueCodeZod>\n\nexport interface DappDeploymentLockIssue {\n  code: DappDeploymentLockIssueCode\n  message: string\n  path: (number | string)[]\n}\n\nexport interface CreateDappDeploymentLockInput {\n  actorDescriptors: InstalledDescriptorMetadata[]\n  applicationProviderDescriptors?: ApplicationProviderDescriptor[]\n  artifacts: DappArtifactLock[]\n  catalog: DappEnvironmentCatalog\n  deploymentName: string\n  manifest: unknown\n  packageManager: z.input<typeof DappPackageManagerIdentityZod>\n  source: z.input<typeof DappProjectSourceIdentityZod>\n}\n\nexport interface DappDeploymentLockSuccess {\n  success: true\n  value: DappDeploymentLock\n}\n\nexport interface DappDeploymentLockFailure {\n  issues: DappDeploymentLockIssue[]\n  success: false\n}\n\nexport type DappDeploymentLockResult = DappDeploymentLockFailure | DappDeploymentLockSuccess\n\nfunction lockIssue(\n  code: DappDeploymentLockIssueCode,\n  message: string,\n  path: (number | string)[],\n): DappDeploymentLockIssue {\n  return {\n    code,\n    message,\n    path,\n  }\n}\n\nfunction sortedResources(resources: z.infer<typeof ResolvedDappResourceZod>[]) {\n  return [...resources].toSorted((left, right) => left.resourceId.localeCompare(right.resourceId))\n}\n\nfunction sortedArtifacts(artifacts: DappArtifactLock[]) {\n  return [...artifacts].toSorted((left, right) => left.artifactId.localeCompare(right.artifactId))\n}\n\nfunction parsedInput(input: CreateDappDeploymentLockInput) {\n  return z.strictObject({\n    applicationProviderDescriptors: z.array(ApplicationProviderDescriptorZod).optional(),\n    actorDescriptors: z.array(InstalledDescriptorMetadataZod),\n    artifacts: z.array(DappArtifactLockZod),\n    catalog: DappEnvironmentCatalogZod,\n    deploymentName: IdentifierZod,\n    manifest: DappProjectManifestDocumentZod,\n    packageManager: DappPackageManagerIdentityZod,\n    source: DappProjectSourceIdentityZod,\n  }).safeParse(input)\n}\n\nexport function createDappDeploymentLock(input: CreateDappDeploymentLockInput): DappDeploymentLockResult {\n  const inputResult = parsedInput(input)\n  if (!inputResult.success) {\n    return {\n      issues: inputResult.error.issues.map(issue => lockIssue(\n        'deployment.lock-input-invalid',\n        issue.message,\n        issue.path.map(entry => typeof entry === 'symbol' ? entry.toString() : entry),\n      )),\n      success: false,\n    }\n  }\n  const selected = inputResult.data.manifest.deployments[inputResult.data.deploymentName]?.request.applicationProviders ?? []\n  const admittedIds = new Set(inputResult.data.artifacts.map(artifact => artifact.artifactId))\n  if (selected.some(selection => !admittedIds.has(selection.artifactId))) {\n    return { success: false, issues: [lockIssue('deployment.lock-input-invalid', 'application Provider artifact is not admitted in this lock', ['artifacts'])] }\n  }\n  const resolution = resolveDappDeployment(\n    inputResult.data.manifest,\n    inputResult.data.deploymentName,\n    inputResult.data.catalog,\n    { applicationProviderDescriptors: inputResult.data.applicationProviderDescriptors },\n  )\n  if (!resolution.success) {\n    return {\n      issues: resolution.issues.map(issue => lockIssue(\n        'deployment.lock-resolution-invalid',\n        `${issue.code}: ${issue.message}`,\n        issue.path,\n      )),\n      success: false,\n    }\n  }\n  const planResult = createDappPlan({\n    definition: inputResult.data.manifest.definition,\n    configuration: resolution.configuration,\n    actorDescriptors: inputResult.data.actorDescriptors,\n    resolvedProviders: resolution.resolvedProviders,\n    portBindings: resolution.request.portBindings,\n  })\n  if (!planResult.success) {\n    return {\n      issues: planResult.issues.map(issue => lockIssue(\n        'deployment.lock-plan-invalid',\n        `${issue.code}: ${issue.message}`,\n        issue.path,\n      )),\n      success: false,\n    }\n  }\n  const requestDocument = inputResult.data.manifest.deployments[inputResult.data.deploymentName]\n  if (requestDocument === undefined) throw new TypeError('resolved deployment request disappeared')\n  const preimage = DappDeploymentLockPreimageZod.parse({\n    schema: DappDeploymentLockSchema,\n    schemaVersion: 1,\n    hashAlgorithm: DappDocumentHashAlgorithm,\n    project: {\n      schemaVersion: 1,\n      projectHash: hashDappProjectManifest(inputResult.data.manifest),\n    },\n    deployment: {\n      name: inputResult.data.deploymentName,\n      requestHash: hashDappDeploymentRequest(requestDocument),\n    },\n    definitionHash: planResult.preimage.definitionHash,\n    configurationHash: planResult.preimage.configurationHash,\n    configuration: planResult.preimage.configuration,\n    plan: planResult.value,\n    source: inputResult.data.source,\n    packageManager: inputResult.data.packageManager,\n    environment: {\n      catalogId: inputResult.data.catalog.catalogId,\n      catalogVersion: inputResult.data.catalog.catalogVersion,\n    },\n    resources: sortedResources(resolution.resolvedResources),\n    artifacts: sortedArtifacts(inputResult.data.artifacts),\n    promotable: inputResult.data.source.worktree === 'clean',\n  })\n  const lockId = hashDappDocument({\n    kind: 'deployment-lock',\n    schema: DappDeploymentLockPreimageZod,\n    schemaVersion: 1,\n  }, preimage).hash\n  return {\n    success: true,\n    value: DappDeploymentLockZod.parse({ ...preimage, lockId }),\n  }\n}\n\nexport function verifyDappDeploymentLock(value: unknown): DappDeploymentLockResult {\n  const result = DappDeploymentLockZod.safeParse(value)\n  if (!result.success) {\n    return {\n      issues: result.error.issues.map(issue => lockIssue(\n        'deployment.lock-input-invalid',\n        issue.message,\n        issue.path.map(entry => typeof entry === 'symbol' ? entry.toString() : entry),\n      )),\n      success: false,\n    }\n  }\n  const { lockId, ...preimage } = result.data\n  const rebuiltPlan = createDappPlan({\n    actorDescriptors: preimage.plan.actorDescriptors,\n    configuration: preimage.plan.configuration,\n    definition: preimage.plan.definition,\n    portBindings: preimage.plan.portBindings,\n    resolvedProviders: preimage.plan.resolvedProviders,\n  })\n  if (!rebuiltPlan.success\n    || rebuiltPlan.value.planId !== preimage.plan.planId\n    || preimage.definitionHash !== preimage.plan.definitionHash\n    || preimage.configurationHash !== preimage.plan.configurationHash\n    || canonicalizeIJson(preimage.configuration) !== canonicalizeIJson(preimage.plan.configuration)) {\n    return {\n      issues: [lockIssue(\n        'deployment.lock-plan-invalid',\n        'deployment lock plan does not reproduce its identity or locked configuration',\n        ['plan'],\n      )],\n      success: false,\n    }\n  }\n  const actualLockId = hashDappDocument({\n    kind: 'deployment-lock',\n    schema: DappDeploymentLockPreimageZod,\n    schemaVersion: 1,\n  }, preimage).hash\n  if (actualLockId !== lockId) {\n    return {\n      issues: [lockIssue(\n        'deployment.lock-verification-failed',\n        'deployment lock ID does not match its canonical preimage',\n        ['lockId'],\n      )],\n      success: false,\n    }\n  }\n  return { success: true, value: result.data }\n}\n", "import { z } from 'zod'\n\nimport { explicitApplicationIdentityIds } from './applicationIdentity.ts'\nimport type { ApplicationProviderResolutionOptions } from './applicationProviderResolution.ts'\nimport { resolveApplicationProviders } from './applicationProviderResolution.ts'\nimport {\n  type DappConfiguration,\n  DappConfigurationSchema,\n  DappConfigurationZod,\n} from './dappConfiguration.ts'\nimport type { DappDefinition } from './dappDefinition.ts'\nimport type { DappDeploymentRequest } from './deploymentRequest.ts'\nimport type { DappResourceRequest } from './deploymentResource.ts'\nimport {\n  type DappEnvironmentCatalog,\n  DappEnvironmentCatalogZod,\n  DappResourceClassZod,\n  type EnvironmentResourceAdapter,\n} from './environmentCatalog.ts'\nimport {\n  IdentifierZod,\n  SemanticVersionZod,\n} from './identifier.ts'\nimport type { JsonObject } from './jsonValue.ts'\nimport { JsonObjectZod } from './jsonValue.ts'\nimport type { ResolvedProviderNode } from './plan.ts'\nimport {\n  InstalledDescriptorMetadataZod,\n  ResolvedProviderNodeZod,\n} from './plan.ts'\nimport type { DappProjectManifest } from './projectManifestModel.ts'\nimport { validateDappProjectManifest } from './projectManifestValidation.ts'\nimport { validateDappProfile } from './validation.ts'\n\nexport const ResolvedDappResourceZod = z.strictObject({\n  resourceId: IdentifierZod,\n  resourceClass: DappResourceClassZod,\n  provision: z.enum(['managed-local', 'managed', 'external']),\n  persistence: z.enum(['ephemeral', 'retained', 'external']),\n  adapterId: IdentifierZod,\n  adapterVersion: SemanticVersionZod,\n  dependencies: z.array(IdentifierZod),\n  providerInstanceId: IdentifierZod.optional(),\n  providerDescriptor: InstalledDescriptorMetadataZod,\n  providerConfig: JsonObjectZod,\n})\n\nexport type ResolvedDappResource = z.infer<typeof ResolvedDappResourceZod>\n\nexport const DappDeploymentResolutionIssueCodes = [\n  'deployment.application-provider-invalid',\n  'deployment.application-provider-identity-unsupported',\n  'deployment.catalog-invalid',\n  'deployment.configuration-invalid',\n  'deployment.name-unknown',\n  'deployment.network-mismatch',\n  'deployment.profile-invalid',\n  'deployment.project-invalid',\n  'deployment.resource-adapter-ambiguous',\n  'deployment.resource-adapter-missing',\n  'deployment.resource-dependency-ambiguous',\n  'deployment.resource-dependency-missing',\n] as const\n\nexport const DappDeploymentResolutionIssueCodeZod = z.enum(DappDeploymentResolutionIssueCodes)\nexport type DappDeploymentResolutionIssueCode = z.infer<typeof DappDeploymentResolutionIssueCodeZod>\n\nexport interface DappDeploymentResolutionIssue {\n  code: DappDeploymentResolutionIssueCode\n  message: string\n  path: (number | string)[]\n}\n\nexport interface DappDeploymentResolutionSuccess {\n  configuration: DappConfiguration\n  request: DappDeploymentRequest\n  resolvedProviders: ResolvedProviderNode[]\n  resolvedResources: ResolvedDappResource[]\n  success: true\n}\n\nexport interface DappDeploymentResolutionFailure {\n  issues: DappDeploymentResolutionIssue[]\n  success: false\n}\n\nexport type DappDeploymentResolutionResult = DappDeploymentResolutionFailure | DappDeploymentResolutionSuccess\n\nfunction resolutionIssue(\n  code: DappDeploymentResolutionIssueCode,\n  message: string,\n  path: (number | string)[],\n): DappDeploymentResolutionIssue {\n  return {\n    code,\n    message,\n    path,\n  }\n}\n\nfunction publicResourceRequest(resource: DappResourceRequest): JsonObject {\n  if ((resource.class === 'identity' || resource.class === 'secret') && resource.provision === 'external') {\n    const { secretRef: _secretRef, ...publicRequest } = resource\n    if (resource.class === 'secret') return JsonObjectZod.parse(publicRequest)\n    return {\n      class: resource.class,\n      provision: resource.provision,\n      persistence: resource.persistence,\n      mode: resource.mode,\n      expectedAddress: resource.expectedAddress,\n    }\n  }\n  return JsonObjectZod.parse(resource)\n}\n\nfunction adapterCandidates(\n  resource: DappResourceRequest,\n  catalog: DappEnvironmentCatalog,\n): EnvironmentResourceAdapter[] {\n  return catalog.adapters.filter(adapter => (\n    adapter.resourceClass === resource.class && adapter.supportedProvisions.includes(resource.provision)\n  ))\n}\n\nfunction dependencyResourceIds(\n  adapter: EnvironmentResourceAdapter,\n  resourceId: string,\n  resource: DappResourceRequest,\n  resources: Readonly<Record<string, DappResourceRequest>>,\n): DappDeploymentResolutionFailure | string[] {\n  const dependencies = new Set<string>()\n  const exactDependencies = resource.class === 'event-subscription'\n    ? new Map<DappResourceRequest['class'], string>([['event-stream', resource.streamResource]])\n    : new Map<DappResourceRequest['class'], string>()\n\n  for (const [resourceClass, dependencyId] of exactDependencies) {\n    const dependency = resources[dependencyId]\n    if (dependency?.class !== resourceClass) {\n      return {\n        issues: [resolutionIssue(\n          'deployment.resource-dependency-missing',\n          `resource ${resourceId} requires exact ${resourceClass} resource ${dependencyId}`,\n          ['resources', resourceId, 'streamResource'],\n        )],\n        success: false,\n      }\n    }\n    dependencies.add(dependencyId)\n  }\n\n  for (const resourceClass of adapter.dependsOnClasses) {\n    const exactDependency = exactDependencies.get(resourceClass)\n    if (exactDependency !== undefined) {\n      dependencies.add(exactDependency)\n      continue\n    }\n    const matches = Object.entries(resources)\n      .filter(([, resource]) => resource.class === resourceClass)\n      .map(([resourceId]) => resourceId)\n    if (matches.length === 0) {\n      return {\n        issues: [resolutionIssue(\n          'deployment.resource-dependency-missing',\n          `adapter ${adapter.adapterId} requires resource class ${resourceClass}`,\n          ['resources'],\n        )],\n        success: false,\n      }\n    }\n    if (matches.length > 1) {\n      return {\n        issues: [resolutionIssue(\n          'deployment.resource-dependency-ambiguous',\n          `adapter ${adapter.adapterId} has multiple dependencies of class ${resourceClass}`,\n          ['resources'],\n        )],\n        success: false,\n      }\n    }\n    const dependency = matches[0]\n    if (dependency !== undefined) dependencies.add(dependency)\n  }\n  return [...dependencies].toSorted()\n}\n\nfunction providerConfig(\n  resourceId: string,\n  resource: DappResourceRequest,\n  adapter: EnvironmentResourceAdapter,\n): JsonObject {\n  return JsonObjectZod.parse({\n    adapter: adapter.publicConfig,\n    request: publicResourceRequest(resource),\n    resourceId,\n  })\n}\n\nfunction capabilityKey(capability: { readonly moniker: string; readonly version: number }): string {\n  return `${capability.moniker}@${capability.version}`\n}\n\nfunction activeActorCapabilityKeys(\n  definition: DappDefinition,\n  request: DappDeploymentRequest,\n): ReadonlySet<string> | undefined {\n  if (request.actors.length === 0) return undefined\n  const roles = new Map(definition.actors.map(role => [role.roleId, role]))\n  return new Set(request.actors.flatMap(actor => roles.get(actor.roleId)?.requiredCapabilities ?? [])\n    .map(capabilityKey))\n}\n\nfunction narrowActiveProviderCapabilities(\n  providers: readonly ResolvedProviderNode[],\n  requiredCapabilities: ReadonlySet<string> | undefined,\n  applicationIds: ReadonlySet<string> = new Set(),\n): ResolvedProviderNode[] {\n  if (requiredCapabilities === undefined) return [...providers]\n  const providersById = new Map(providers.map(provider => [provider.instanceId, provider]))\n  const direct = new Set(providers.filter(provider => provider.providedCapabilities\n    .some(capability => requiredCapabilities.has(capabilityKey(capability))))\n    .map(provider => provider.instanceId))\n  const selected = new Set<string>()\n  const select = (providerId: string): void => {\n    if (selected.has(providerId)) return\n    selected.add(providerId)\n    for (const dependency of providersById.get(providerId)?.dependencies ?? []) {\n      select(dependency)\n    }\n  }\n  for (const providerId of direct) select(providerId)\n  return providers.map(provider => ResolvedProviderNodeZod.parse({\n    ...provider,\n    providedCapabilities: applicationIds.has(provider.instanceId)\n      ? provider.providedCapabilities\n      : direct.has(provider.instanceId)\n        ? provider.providedCapabilities.filter(capability => requiredCapabilities.has(capabilityKey(capability)))\n        : selected.has(provider.instanceId)\n          ? provider.providedCapabilities\n          : [],\n  }))\n}\n\nfunction resolveResources(\n  request: DappDeploymentRequest,\n  catalog: DappEnvironmentCatalog,\n): DappDeploymentResolutionFailure | {\n  adapters: Map<string, EnvironmentResourceAdapter>\n  providers: ResolvedProviderNode[]\n  resources: ResolvedDappResource[]\n} {\n  const identities = explicitApplicationIdentityIds(request)\n  const adapters = new Map<string, EnvironmentResourceAdapter>()\n  const providers: ResolvedProviderNode[] = []\n  const resources: ResolvedDappResource[] = []\n  for (const [resourceId, resource] of Object.entries(request.resources).toSorted(([left], [right]) => left.localeCompare(right))) {\n    const candidates = adapterCandidates(resource, catalog)\n    if (candidates.length !== 1) {\n      return {\n        issues: [resolutionIssue(\n          candidates.length === 0 ? 'deployment.resource-adapter-missing' : 'deployment.resource-adapter-ambiguous',\n          `resource ${resourceId} resolved ${candidates.length} environment adapters`,\n          ['resources', resourceId],\n        )],\n        success: false,\n      }\n    }\n    const adapter = candidates[0]\n    if (adapter === undefined) throw new TypeError('resolved adapter disappeared')\n    const dependencies = dependencyResourceIds(adapter, resourceId, resource, request.resources)\n    if (!Array.isArray(dependencies)) return dependencies\n    if (resource.class === 'identity' && identities.has(resourceId) && dependencies.length > 0) {\n      return {\n        issues: [resolutionIssue(\n          'deployment.application-provider-invalid',\n          'selected identity resources must be independent borrowed leaves',\n          ['resources', resourceId],\n        )],\n        success: false,\n      }\n    }\n    // Provisioning dependencies never grant signing authority. Only explicit\n    // app bindings opt identity leaves into the runtime graph.\n    const providerDependencies = dependencies\n      .filter(dependency => request.resources[dependency]?.class !== 'identity')\n    const config = providerConfig(resourceId, resource, adapter)\n    adapters.set(resourceId, adapter)\n    if (resource.class !== 'identity' || identities.has(resourceId)) {\n      providers.push(ResolvedProviderNodeZod.parse({\n        instanceId: resourceId,\n        descriptor: adapter.provider,\n        config,\n        providedCapabilities: adapter.providedCapabilities,\n        dependencies: providerDependencies,\n      }))\n    }\n    resources.push(ResolvedDappResourceZod.parse({\n      resourceId,\n      resourceClass: resource.class,\n      provision: resource.provision,\n      persistence: resource.persistence,\n      adapterId: adapter.adapterId,\n      adapterVersion: adapter.adapterVersion,\n      dependencies,\n      ...(resource.class === 'identity' && !identities.has(resourceId) ? {} : { providerInstanceId: resourceId }),\n      providerDescriptor: adapter.provider,\n      providerConfig: config,\n    }))\n  }\n  return {\n    adapters,\n    providers,\n    resources,\n  }\n}\n\nfunction resolveNetwork(\n  request: DappDeploymentRequest,\n  adapters: ReadonlyMap<string, EnvironmentResourceAdapter>,\n): DappDeploymentResolutionFailure | { expectedChainId: string; networkId: string } {\n  const resource = request.resources[request.network.resource]\n  const adapter = adapters.get(request.network.resource)\n  if (resource?.class !== 'xl1-network' || adapter?.resourceClass !== 'xl1-network') {\n    return {\n      issues: [resolutionIssue('deployment.network-mismatch', 'network resource did not resolve an XL1 adapter', ['network'])],\n      success: false,\n    }\n  }\n  if (resource.networkId !== adapter.network.networkId\n    || ('expectedChainId' in resource\n      && resource.expectedChainId !== undefined\n      && resource.expectedChainId !== adapter.network.expectedChainId)) {\n    return {\n      issues: [resolutionIssue('deployment.network-mismatch', 'network request and catalog identity differ', ['network'])],\n      success: false,\n    }\n  }\n  return adapter.network\n}\n\nfunction resolveIdentityBindings(request: DappDeploymentRequest) {\n  return request.identityBindings.map(binding => ({\n    roleId: binding.roleId,\n    capabilityId: binding.resource,\n  }))\n}\n\nfunction resolveSideChannelPolicy(request: DappDeploymentRequest) {\n  const policy = request.policies.sideChannel\n  if (policy.profile === 'none') return policy\n  const signingBinding = request.identityBindings.find(binding => binding.roleId === policy.detachedSigningIdentityRole)\n  return {\n    profile: policy.profile,\n    channelCapabilityId: policy.resource,\n    detachedSigningCapabilityId: signingBinding?.resource ?? policy.detachedSigningIdentityRole,\n    maximumMessageBytes: policy.maximumMessageBytes,\n    replayRetentionSeconds: policy.replayRetentionSeconds,\n    acceptedClockSkewMilliseconds: policy.acceptedClockSkewMilliseconds,\n    unavailableBehavior: policy.unavailableBehavior,\n    transport: 'websocket' as const,\n  }\n}\n\nfunction resolveExternalInteractionPolicy(request: DappDeploymentRequest) {\n  const policy = request.policies.externalInteraction\n  if (policy.mode === 'none') return policy\n  return {\n    ...policy,\n    sources: policy.sources.map((source) => {\n      const resource = request.resources[source.resource]\n      if (resource?.class !== 'external-source') throw new TypeError('external source resource was not validated')\n      return {\n        sourceId: source.sourceId,\n        sourceKind: resource.sourceKind,\n        observerCapabilityId: source.resource,\n        config: {},\n      }\n    }),\n  }\n}\n\nfunction resolveDatalakePolicy(request: DappDeploymentRequest) {\n  const policy = request.policies.datalake\n  if (policy.mode === 'none') return policy\n  const { resource: _resource, ...configurationPolicy } = policy\n  return configurationPolicy\n}\n\nfunction resolveAuxiliaryStores(request: DappDeploymentRequest) {\n  return request.auxiliaryStores.map((binding) => {\n    const resource = request.resources[binding.resource]\n    if (resource === undefined || !('durability' in resource)) {\n      throw new TypeError('auxiliary store resource was not validated')\n    }\n    return {\n      class: binding.class,\n      capabilityId: binding.resource,\n      durability: resource.durability,\n    }\n  })\n}\n\nfunction resolveProjectionPolicy(request: DappDeploymentRequest) {\n  const policy = request.policies.projection\n  if (policy.profile === 'none') return policy\n  const common = {\n    profile: policy.profile,\n    projectionCapabilityId: policy.projectionResource,\n    floor: policy.floor,\n    maximumLagBlocks: policy.maximumLagBlocks,\n    progressWatermark: policy.progressWatermark,\n  }\n  return policy.profile === 'ephemeral'\n    ? common\n    : { ...common, checkpointCapabilityId: policy.checkpointResource }\n}\n\nfunction createConfiguration(\n  manifest: DappProjectManifest,\n  request: DappDeploymentRequest,\n  network: { expectedChainId: string; networkId: string },\n  resources: readonly ResolvedDappResource[],\n): DappConfiguration {\n  const providerBindings = Object.fromEntries(resources\n    .filter(resource => resource.providerInstanceId !== undefined)\n    .map(resource => [resource.resourceId, {\n      descriptorId: resource.providerDescriptor.descriptor.id,\n      config: resource.providerConfig,\n    }]))\n  return DappConfigurationZod.parse({\n    schema: DappConfigurationSchema,\n    schemaVersion: 1,\n    dappId: manifest.definition.dappId,\n    definitionVersion: manifest.definition.definitionVersion,\n    network,\n    actors: request.actors,\n    supervision: request.supervision,\n    providerBindings: {\n      ...providerBindings,\n      ...Object.fromEntries((request.applicationProviders ?? []).map(selection => [selection.instanceId, { descriptorId: selection.descriptor.id, config: selection.config }])),\n    },\n    ...(request.applicationProviders?.length ? { applicationProviders: request.applicationProviders } : {}),\n    identityBindings: resolveIdentityBindings(request),\n    sideChannelPolicy: resolveSideChannelPolicy(request),\n    externalInteractionPolicy: resolveExternalInteractionPolicy(request),\n    datalakePolicy: resolveDatalakePolicy(request),\n    auxiliaryStores: resolveAuxiliaryStores(request),\n    projectionPolicy: resolveProjectionPolicy(request),\n    consistency: request.policies.consistency,\n  })\n}\n\nexport function resolveDappDeployment(\n  manifestValue: unknown,\n  deploymentName: string,\n  catalogValue: unknown,\n  options: ApplicationProviderResolutionOptions = {},\n): DappDeploymentResolutionResult {\n  const manifestResult = validateDappProjectManifest(manifestValue)\n  if (!manifestResult.success) {\n    return {\n      issues: manifestResult.issues.map(issue => resolutionIssue('deployment.project-invalid', issue.message, issue.path)),\n      success: false,\n    }\n  }\n  const catalogResult = DappEnvironmentCatalogZod.safeParse(catalogValue)\n  if (!catalogResult.success) {\n    return {\n      issues: catalogResult.error.issues.map(issue => resolutionIssue(\n        'deployment.catalog-invalid',\n        issue.message,\n        issue.path.map(entry => typeof entry === 'symbol' ? entry.toString() : entry),\n      )),\n      success: false,\n    }\n  }\n  const document = manifestResult.value.deployments[deploymentName]\n  if (document === undefined) {\n    return {\n      issues: [resolutionIssue('deployment.name-unknown', `deployment ${deploymentName} is not declared`, ['deployments'])],\n      success: false,\n    }\n  }\n  const resolution = resolveResources(\n    document.request,\n    catalogResult.data,\n  )\n  if ('success' in resolution) return resolution\n  const application = resolveApplicationProviders(manifestResult.value, document.request, resolution.providers, options)\n  if (!application.success) return application\n  const network = resolveNetwork(document.request, resolution.adapters)\n  if ('success' in network) return network\n  const configuration = createConfiguration(manifestResult.value, document.request, network, resolution.resources)\n  const profileResult = validateDappProfile(manifestResult.value.definition, configuration)\n  if (!profileResult.success) {\n    return {\n      issues: profileResult.issues.map(issue => resolutionIssue('deployment.profile-invalid', issue.message, issue.path)),\n      success: false,\n    }\n  }\n  return {\n    configuration,\n    request: document.request,\n    resolvedProviders: narrowActiveProviderCapabilities(\n      [...resolution.providers, ...application.providers],\n      document.request.applicationProviders?.length\n        ? new Set([\n            ...activeActorCapabilityKeys(manifestResult.value.definition, document.request) ?? [],\n            ...(options.applicationProviderDescriptors ?? []).flatMap(entry => entry.descriptor.application?.requiredCapabilities ?? []).map(capabilityKey),\n          ])\n        : activeActorCapabilityKeys(manifestResult.value.definition, document.request),\n      new Set(application.providers.map(provider => provider.instanceId)),\n    ),\n    resolvedResources: resolution.resources,\n    success: true,\n  }\n}\n", "import type { ApplicationProviderSelection } from './applicationProvider.ts'\nimport type { ApplicationProviderDescriptor } from './applicationProviderDescriptor.ts'\nimport { ApplicationProviderDescriptorZod } from './applicationProviderDescriptor.ts'\nimport type { CapabilityRequirement } from './dappDefinition.ts'\nimport type { DappDeploymentRequest } from './deploymentRequest.ts'\nimport type { DappDeploymentResolutionIssue } from './deploymentResolution.ts'\nimport type { ResolvedProviderNode } from './plan.ts'\nimport type { DappProjectManifest } from './projectManifestModel.ts'\n\nexport interface ApplicationProviderResolutionOptions {\n  readonly applicationProviderDescriptors?: readonly ApplicationProviderDescriptor[]\n}\n\ninterface ResolutionContext {\n  descriptors: Map<string, ApplicationProviderDescriptor['descriptor']>\n  issues: DappDeploymentResolutionIssue[]\n  manifest: DappProjectManifest\n  request: DappDeploymentRequest\n  selections: Map<string, ApplicationProviderSelection>\n}\n\nfunction descriptorKey(artifactId: string, descriptor: { id: string; version: number }): string {\n  return `${artifactId}:${descriptor.id}@${descriptor.version}`\n}\n\nfunction reject(context: ResolutionContext, message: string, path: (number | string)[] = []): void {\n  context.issues.push({\n    code: 'deployment.application-provider-invalid', message, path: ['applicationProviders', ...path],\n  })\n}\n\nfunction captureDescriptors(context: ResolutionContext, options: ApplicationProviderResolutionOptions): void {\n  const keys = new Set((context.request.applicationProviders ?? []).map(selection => descriptorKey(selection.artifactId, selection.descriptor)))\n  for (const candidate of options.applicationProviderDescriptors ?? []) {\n    const parsed = ApplicationProviderDescriptorZod.safeParse(candidate)\n    if (parsed.success) {\n      const { artifactId, descriptor } = parsed.data\n      const key = descriptorKey(artifactId, descriptor.metadata.descriptor)\n      if (context.descriptors.has(key)) reject(context, 'application Provider descriptors are ambiguous')\n      if (!keys.has(key)) reject(context, 'application Provider descriptor is not selected')\n      context.descriptors.set(key, descriptor)\n    } else {\n      reject(context, 'application Provider descriptor metadata is invalid')\n    }\n  }\n}\n\nfunction captureSelection(context: ResolutionContext, selection: ApplicationProviderSelection, index: number): ResolvedProviderNode | undefined {\n  if (context.selections.has(selection.instanceId) || Object.hasOwn(context.request.resources, selection.instanceId)) {\n    reject(context, 'application Provider instance IDs must be unique and disjoint from resource IDs', [index, 'instanceId'])\n  }\n  context.selections.set(selection.instanceId, selection)\n  const artifact = context.manifest.artifacts[selection.artifactId]\n  const active = context.request.actors.some(actor => actor.host === selection.host)\n  if (!active || artifact?.kind !== 'dapp-host' || !artifact.hosts.includes(selection.host)) {\n    reject(context, 'application Provider must select its declared host artifact and an active host', [index, 'host'])\n  }\n  const descriptor = context.descriptors.get(descriptorKey(selection.artifactId, selection.descriptor))\n  if (descriptor?.application === undefined) {\n    reject(context, 'selected application Provider has no admitted application descriptor', [index, 'descriptor'])\n    return\n  }\n  const required = descriptor.application.requiredCapabilities.map(capability => capability.moniker).toSorted()\n  const bindings = Object.keys(selection.dependencies).toSorted()\n  if (required.length !== bindings.length || required.some((moniker, position) => moniker !== bindings[position])) {\n    reject(context, 'application Provider bindings must exactly match admitted required monikers', [index, 'dependencies'])\n  }\n  return {\n    instanceId: selection.instanceId,\n    descriptor: descriptor.metadata,\n    config: selection.config,\n    providedCapabilities: descriptor.application.providedCapabilities,\n    dependencies: [...new Set(Object.values(selection.dependencies).map(binding => binding.kind === 'resource'\n      ? binding.resourceId\n      : binding.instanceId))].toSorted(),\n  }\n}\n\nfunction validateIdentityTarget(\n  context: ResolutionContext,\n  capability: CapabilityRequirement,\n  target: ResolvedProviderNode | undefined,\n  path: (number | string)[],\n): void {\n  if (capability.moniker !== 'xyo.identity' || capability.version !== 1\n    || target?.providedCapabilities.length !== 1 || target.dependencies.length !== 0) {\n    reject(context, 'identity application dependencies require the exact supported xyo.identity@1 leaf', path)\n  }\n}\n\nfunction validateDependency(\n  context: ResolutionContext,\n  selection: ApplicationProviderSelection,\n  capability: CapabilityRequirement,\n  nodes: ReadonlyMap<string, ResolvedProviderNode>,\n  index: number,\n): void {\n  const binding = selection.dependencies[capability.moniker]\n  if (binding === undefined) return\n  const targetId = binding.kind === 'resource' ? binding.resourceId : binding.instanceId\n  const target = nodes.get(targetId)\n  const path = [index, 'dependencies', capability.moniker]\n  if (targetId === selection.instanceId) reject(context, 'application Provider cannot depend on itself', path)\n  if (binding.kind === 'resource' && context.request.resources[targetId]?.class === 'identity') {\n    validateIdentityTarget(context, capability, target, path)\n  }\n  const hasTarget = binding.kind === 'resource' ? Object.hasOwn(context.request.resources, targetId) : context.selections.has(targetId)\n  if (!hasTarget) reject(context, 'application Provider dependency target is missing or has the wrong kind', path)\n  if (binding.kind === 'application-provider' && context.selections.get(targetId)?.host !== selection.host) {\n    reject(context, 'application Provider dependency crosses host ownership', path)\n  }\n  if (!target?.providedCapabilities.some(value => value.moniker === capability.moniker && value.version === capability.version)) {\n    reject(context, 'application Provider dependency does not supply its admitted capability version', path)\n  }\n}\n\nexport function resolveApplicationProviders(\n  manifest: DappProjectManifest,\n  request: DappDeploymentRequest,\n  resources: readonly ResolvedProviderNode[],\n  options: ApplicationProviderResolutionOptions,\n): { providers: ResolvedProviderNode[]; success: true } | { issues: DappDeploymentResolutionIssue[]; success: false } {\n  const context: ResolutionContext = {\n    descriptors: new Map(), issues: [], manifest, request, selections: new Map(),\n  }\n  captureDescriptors(context, options)\n  const selections = request.applicationProviders ?? []\n  const providers = selections.flatMap((selection, index) => {\n    const node = captureSelection(context, selection, index)\n    return node === undefined ? [] : [node]\n  })\n  const nodes = new Map([...resources, ...providers].map(provider => [provider.instanceId, provider]))\n  for (const [index, selection] of selections.entries()) {\n    const descriptor = context.descriptors.get(descriptorKey(selection.artifactId, selection.descriptor))\n    for (const capability of descriptor?.application?.requiredCapabilities ?? []) validateDependency(context, selection, capability, nodes, index)\n  }\n  return context.issues.length > 0 ? { success: false, issues: context.issues } : { success: true, providers }\n}\n", "import { asSchema } from '@xyo-network/sdk'\nimport { z } from 'zod'\n\nimport {\n  CapabilityRequirementZod,\n  InstalledDescriptorReferenceZod,\n} from './dappDefinition.ts'\nimport { ResourceProvisionZod } from './deploymentResource.ts'\nimport {\n  HashZod,\n  IdentifierZod,\n  SemanticVersionZod,\n  Xl1ChainIdZod,\n} from './identifier.ts'\nimport { JsonObjectZod } from './jsonValue.ts'\nexport const DappEnvironmentCatalogSchema = asSchema('network.xyo.dapp.environment.catalog', true)\n\nexport const DappResourceClassZod = z.enum([\n  'xl1-network',\n  'datalake',\n  'effect-journal',\n  'projection-store',\n  'checkpoint-store',\n  'secret',\n  'identity',\n  'side-channel',\n  'external-source',\n  'event-stream',\n  'event-subscription',\n])\n\nexport type DappResourceClass = z.infer<typeof DappResourceClassZod>\n\nexport const EnvironmentProviderDescriptorZod = z.strictObject({\n  descriptor: InstalledDescriptorReferenceZod,\n  configSchemaHash: HashZod,\n  implementationHash: HashZod,\n})\n\nexport type EnvironmentProviderDescriptor = z.infer<typeof EnvironmentProviderDescriptorZod>\n\nconst ResourceAdapterFields = {\n  adapterId: IdentifierZod,\n  adapterVersion: SemanticVersionZod,\n  supportedProvisions: z.array(ResourceProvisionZod).min(1),\n  provider: EnvironmentProviderDescriptorZod,\n  providedCapabilities: z.array(CapabilityRequirementZod).min(1),\n  dependsOnClasses: z.array(DappResourceClassZod),\n}\n\nexport const Xl1EnvironmentResourceAdapterZod = z.strictObject({\n  resourceClass: z.literal('xl1-network'),\n  ...ResourceAdapterFields,\n  network: z.strictObject({\n    networkId: IdentifierZod,\n    expectedChainId: Xl1ChainIdZod,\n  }),\n  publicConfig: JsonObjectZod,\n})\n\nexport const GeneralEnvironmentResourceAdapterZod = z.strictObject({\n  resourceClass: z.enum([\n    'datalake',\n    'effect-journal',\n    'projection-store',\n    'checkpoint-store',\n    'secret',\n    'identity',\n    'side-channel',\n    'external-source',\n    'event-stream',\n    'event-subscription',\n  ]),\n  ...ResourceAdapterFields,\n  publicConfig: JsonObjectZod,\n})\n\nexport const EnvironmentResourceAdapterZod = z.union([\n  Xl1EnvironmentResourceAdapterZod,\n  GeneralEnvironmentResourceAdapterZod,\n]).superRefine((adapter, context) => {\n  const unique = new Set(adapter.supportedProvisions)\n  if (unique.size !== adapter.supportedProvisions.length) {\n    context.addIssue({\n      code: 'custom',\n      message: 'supported provisions must be unique',\n      path: ['supportedProvisions'],\n    })\n  }\n  const unique2 = new Set(adapter.dependsOnClasses)\n  if (unique2.size !== adapter.dependsOnClasses.length) {\n    context.addIssue({\n      code: 'custom',\n      message: 'adapter dependency classes must be unique',\n      path: ['dependsOnClasses'],\n    })\n  }\n  const capabilities = adapter.providedCapabilities.map(capability => `${capability.moniker}@${capability.version}`)\n  const unique3 = new Set(capabilities)\n  if (unique3.size !== capabilities.length) {\n    context.addIssue({\n      code: 'custom',\n      message: 'adapter capabilities must be unique',\n      path: ['providedCapabilities'],\n    })\n  }\n})\n\nexport type EnvironmentResourceAdapter = z.infer<typeof EnvironmentResourceAdapterZod>\n\nexport const DappEnvironmentCatalogZod = z.strictObject({\n  schema: z.literal(DappEnvironmentCatalogSchema),\n  schemaVersion: z.literal(1),\n  catalogId: IdentifierZod,\n  catalogVersion: SemanticVersionZod,\n  adapters: z.array(EnvironmentResourceAdapterZod).min(1),\n}).superRefine((catalog, context) => {\n  const adapterIds = catalog.adapters.map(adapter => adapter.adapterId)\n  const unique4 = new Set(adapterIds)\n  if (unique4.size !== adapterIds.length) {\n    context.addIssue({\n      code: 'custom', message: 'adapter IDs must be unique', path: ['adapters'],\n    })\n  }\n})\n\nexport type DappEnvironmentCatalog = z.infer<typeof DappEnvironmentCatalogZod>\n", "import { z } from 'zod'\n\nimport {\n  canonicalizeIJson,\n  DappDocumentHashAlgorithm,\n  hashDappDocument,\n} from './canonicalDocument.ts'\nimport type {\n  CreateDappDeploymentLockInput,\n  DappArtifactLock,\n  DappDeploymentLockIssue,\n} from './deploymentLock.ts'\nimport {\n  createDappDeploymentLock,\n  DappArtifactLockZod,\n  DappDeploymentLockSchema,\n} from './deploymentLock.ts'\nimport {\n  DappDeployableThingZod,\n  DappNamedDeploymentZod,\n  DappThingTargetBindingZod,\n} from './deploymentManifest.ts'\nimport { ResolvedDappResourceZod } from './deploymentResolution.ts'\nimport { resolveDappDeploymentSource } from './deploymentSourceResolution.ts'\nimport {\n  HashZod,\n  IdentifierZod,\n  SemanticVersionZod,\n} from './identifier.ts'\nimport {\n  createDappPlan,\n  DappPlanZod,\n} from './plan.ts'\nimport { hashDappDeploymentRequest, hashDappProjectManifest } from './projectManifest.ts'\nimport {\n  DappPackageManagerIdentityZod,\n  DappProjectManifestDocumentZod,\n  DappProjectSourceIdentityZod,\n} from './projectManifestModel.ts'\n\nexport const DappDeploymentLockV2PreimageZod = z.strictObject({\n  schema: z.literal(DappDeploymentLockSchema),\n  schemaVersion: z.literal(2),\n  hashAlgorithm: z.literal(DappDocumentHashAlgorithm),\n  project: z.strictObject({\n    schemaVersion: z.literal(1),\n    projectHash: HashZod,\n  }),\n  deployment: z.strictObject({\n    name: IdentifierZod,\n    requestHash: HashZod,\n    manifest: z.strictObject({\n      schemaVersion: z.literal(1),\n      deploymentManifestId: HashZod,\n    }),\n  }),\n  things: z.record(IdentifierZod, DappDeployableThingZod),\n  bindings: z.record(IdentifierZod, DappThingTargetBindingZod),\n  definitionHash: HashZod,\n  configurationHash: HashZod,\n  configuration: DappPlanZod.shape.configuration,\n  plan: DappPlanZod,\n  source: DappProjectSourceIdentityZod,\n  packageManager: DappPackageManagerIdentityZod,\n  environment: z.strictObject({\n    catalogId: IdentifierZod,\n    catalogVersion: SemanticVersionZod,\n  }),\n  resources: z.array(ResolvedDappResourceZod),\n  artifacts: z.array(DappArtifactLockZod),\n  promotable: z.boolean(),\n}).superRefine((lock, context) => {\n  const thingIds = Object.keys(lock.things).toSorted()\n  const bindingIds = Object.keys(lock.bindings).toSorted()\n  if (thingIds.length !== bindingIds.length || thingIds.some((thingId, index) => bindingIds[index] !== thingId)) {\n    context.addIssue({\n      code: 'custom', message: 'every thing must be bound exactly once', path: ['bindings'],\n    })\n  }\n  const resourceIds = lock.resources.map(resource => resource.resourceId)\n  const unique = new Set(resourceIds)\n  if (unique.size !== resourceIds.length) {\n    context.addIssue({\n      code: 'custom', message: 'resource IDs must be unique', path: ['resources'],\n    })\n  }\n  for (const selection of lock.configuration.applicationProviders ?? []) {\n    if (lock.artifacts.every(artifact => artifact.artifactId !== selection.artifactId)) {\n      context.addIssue({\n        code: 'custom', message: 'application Provider artifact is not admitted in this lock', path: ['artifacts'],\n      })\n    }\n  }\n  const artifactIds = lock.artifacts.map(artifact => artifact.artifactId)\n  const unique2 = new Set(artifactIds)\n  if (unique2.size !== artifactIds.length) {\n    context.addIssue({\n      code: 'custom', message: 'artifact IDs must be unique', path: ['artifacts'],\n    })\n  }\n})\n\nexport type DappDeploymentLockV2Preimage = z.infer<typeof DappDeploymentLockV2PreimageZod>\nexport const DappDeploymentLockV2Zod = DappDeploymentLockV2PreimageZod.safeExtend({ lockId: HashZod })\nexport type DappDeploymentLockV2 = z.infer<typeof DappDeploymentLockV2Zod>\n\nexport interface CreateDappDeploymentLockV2Input extends Omit<CreateDappDeploymentLockInput, 'manifest'> {\n  deploymentManifest: unknown\n  projectManifest: unknown\n}\n\nexport type DappDeploymentLockV2Result\n  = { issues: DappDeploymentLockIssue[]; success: false }\n    | { success: true; value: DappDeploymentLockV2 }\n\nfunction invalid(message: string, path: (number | string)[] = []): DappDeploymentLockV2Result {\n  return {\n    issues: [{\n      code: 'deployment.lock-input-invalid', message, path,\n    }],\n    success: false,\n  }\n}\n\nfunction sortedRecord<T>(record: Readonly<Record<string, T>>): Record<string, T> {\n  return Object.fromEntries(Object.entries(record).toSorted(([left], [right]) => left.localeCompare(right)))\n}\n\nfunction sortedArtifacts(artifacts: readonly DappArtifactLock[]): DappArtifactLock[] {\n  return [...artifacts].toSorted((left, right) => left.artifactId.localeCompare(right.artifactId))\n}\n\nexport function createDappDeploymentLockV2(input: CreateDappDeploymentLockV2Input): DappDeploymentLockV2Result {\n  const projectResult = DappProjectManifestDocumentZod.safeParse(input.projectManifest)\n  if (!projectResult.success) return invalid('project manifest is invalid')\n  const sourceResolution = resolveDappDeploymentSource({\n    deploymentManifest: input.deploymentManifest,\n    deploymentName: input.deploymentName,\n    projectManifest: projectResult.data,\n  })\n  if (!sourceResolution.success) {\n    return {\n      issues: sourceResolution.issues.map(sourceIssue => ({\n        code: 'deployment.lock-input-invalid',\n        message: `${sourceIssue.code}: ${sourceIssue.message}`,\n        path: sourceIssue.path,\n      })),\n      success: false,\n    }\n  }\n  if (sourceResolution.value.mode !== 'split-v2'\n    || sourceResolution.value.deploymentManifestId === undefined\n    || sourceResolution.value.split === undefined) {\n    return invalid('a split deployment source is required for a V2 lock')\n  }\n  const selected = DappNamedDeploymentZod.parse(sourceResolution.value.split)\n  const virtualProject = DappProjectManifestDocumentZod.parse({\n    ...projectResult.data,\n    deployments: { [input.deploymentName]: selected.request },\n  })\n  const v1 = createDappDeploymentLock({\n    ...(input.applicationProviderDescriptors === undefined ? {} : { applicationProviderDescriptors: input.applicationProviderDescriptors }),\n    actorDescriptors: input.actorDescriptors,\n    artifacts: input.artifacts,\n    catalog: input.catalog,\n    deploymentName: input.deploymentName,\n    manifest: virtualProject,\n    packageManager: input.packageManager,\n    source: input.source,\n  })\n  if (!v1.success) return v1\n\n  const { lockId: _v1LockId, ...v1Preimage } = v1.value\n  const preimage = DappDeploymentLockV2PreimageZod.parse({\n    ...v1Preimage,\n    schemaVersion: 2,\n    project: {\n      schemaVersion: 1,\n      projectHash: hashDappProjectManifest(projectResult.data),\n    },\n    deployment: {\n      name: input.deploymentName,\n      requestHash: hashDappDeploymentRequest(selected.request),\n      manifest: {\n        schemaVersion: 1,\n        deploymentManifestId: sourceResolution.value.deploymentManifestId,\n      },\n    },\n    things: sortedRecord(selected.things),\n    bindings: sortedRecord(selected.bindings),\n    artifacts: sortedArtifacts(v1.value.artifacts),\n  })\n  const lockId = hashDappDocument({\n    kind: 'deployment-lock',\n    schema: DappDeploymentLockV2PreimageZod,\n    schemaVersion: 2,\n  }, preimage).hash\n  return { success: true, value: DappDeploymentLockV2Zod.parse({ ...preimage, lockId }) }\n}\n\nexport function verifyDappDeploymentLockV2(value: unknown): DappDeploymentLockV2Result {\n  const result = DappDeploymentLockV2Zod.safeParse(value)\n  if (!result.success) return invalid(result.error.issues.map(issue => issue.message).join('; '))\n  const { lockId, ...preimage } = result.data\n  const rebuiltPlan = createDappPlan({\n    actorDescriptors: preimage.plan.actorDescriptors,\n    configuration: preimage.plan.configuration,\n    definition: preimage.plan.definition,\n    portBindings: preimage.plan.portBindings,\n    resolvedProviders: preimage.plan.resolvedProviders,\n  })\n  if (!rebuiltPlan.success || rebuiltPlan.value.planId !== preimage.plan.planId\n    || preimage.definitionHash !== preimage.plan.definitionHash\n    || preimage.configurationHash !== preimage.plan.configurationHash\n    || canonicalizeIJson(preimage.configuration) !== canonicalizeIJson(preimage.plan.configuration)) {\n    return {\n      issues: [{\n        code: 'deployment.lock-verification-failed',\n        message: 'deployment lock contains a plan that cannot be reproduced',\n        path: ['plan'],\n      }],\n      success: false,\n    }\n  }\n  const actual = hashDappDocument({\n    kind: 'deployment-lock',\n    schema: DappDeploymentLockV2PreimageZod,\n    schemaVersion: 2,\n  }, preimage).hash\n  if (actual !== lockId) {\n    return {\n      issues: [{\n        code: 'deployment.lock-verification-failed',\n        message: 'deployment lock ID does not match its canonical V2 preimage',\n        path: ['lockId'],\n      }],\n      success: false,\n    }\n  }\n  return { success: true, value: DappDeploymentLockV2Zod.parse({ ...preimage, lockId }) }\n}\n", "import { z } from 'zod'\n\nimport { canonicalizeIJson } from './canonicalDocument.ts'\nimport type {\n  DappDeployableThing,\n  DappDeploymentManifest,\n  DappNamedDeployment,\n} from './deploymentManifest.ts'\nimport {\n  DappDeploymentJsonSchemaUrl,\n  DappDeploymentManifestDocumentZod,\n  hashDappDeploymentManifest,\n  normalizeDappDeploymentManifest,\n} from './deploymentManifest.ts'\nimport type {\n  DappDeploymentManifestV2,\n  DappInfrastructureRequirement,\n  DappNamedDeploymentV2,\n} from './deploymentManifestV2.ts'\nimport {\n  DappDeploymentJsonSchemaV2Url,\n  DappDeploymentManifestV2DocumentZod,\n  DappDeploymentSourceResolutionModeV2,\n  hashDappDeploymentManifestV2,\n  normalizeDappDeploymentManifestV2,\n  selectDappDeploymentInfrastructureV2,\n} from './deploymentManifestV2.ts'\nimport type { DappDeploymentRequestDocument } from './deploymentRequest.ts'\nimport {\n  DappDeploymentRequestDocumentZod,\n  normalizeDappDeploymentRequest,\n} from './deploymentRequest.ts'\nimport type { DappProjectManifest } from './projectManifestModel.ts'\nimport { DappProjectManifestDocumentZod } from './projectManifestModel.ts'\nimport { validateDappProjectManifest } from './projectManifestValidation.ts'\n\nexport const DappDeploymentSourceIssueCodes = [\n  'deployment.source-conflict',\n  'deployment.source-invalid',\n  'deployment.source-project-mismatch',\n  'deployment.source-reference-invalid',\n  'deployment.source-unknown',\n] as const\n\nexport const DappDeploymentSourceIssueCodeZod = z.enum(DappDeploymentSourceIssueCodes)\nexport type DappDeploymentSourceIssueCode = z.infer<typeof DappDeploymentSourceIssueCodeZod>\n\nexport interface DappDeploymentSourceIssue {\n  code: DappDeploymentSourceIssueCode\n  message: string\n  path: (number | string)[]\n}\n\nexport interface ResolveDappDeploymentSourceInput {\n  deploymentManifest?: unknown\n  deploymentName: string\n  projectManifest: unknown\n}\n\nexport interface ResolvedDappDeploymentSource {\n  deploymentManifest?: DappDeploymentManifest\n  deploymentManifestId?: string\n  mode: 'embedded-v1' | 'split-v2'\n  request: DappDeploymentRequestDocument\n  split?: DappNamedDeployment\n}\n\nexport type DappDeploymentSourceResolutionResult\n  = { issues: DappDeploymentSourceIssue[]; success: false }\n    | { success: true; value: ResolvedDappDeploymentSource }\n\nexport interface ResolveDappDeploymentSourceV2Input {\n  deploymentManifest: unknown\n  deploymentName: string\n  projectManifest: unknown\n}\n\nexport interface ResolvedDappDeploymentSourceV2 {\n  deployment: DappNamedDeploymentV2\n  deploymentManifest: DappDeploymentManifestV2\n  deploymentManifestId: string\n  mode: typeof DappDeploymentSourceResolutionModeV2\n  request: DappDeploymentRequestDocument\n  selectedInfrastructure: Record<string, DappInfrastructureRequirement>\n}\n\nexport type DappDeploymentSourceResolutionV2Result\n  = { issues: DappDeploymentSourceIssue[]; success: false }\n    | { success: true; value: ResolvedDappDeploymentSourceV2 }\n\nexport type DappDeploymentSourceResolutionAnyResult\n  = { issues: DappDeploymentSourceIssue[]; success: false }\n    | { schemaVersion: 1; success: true; value: ResolvedDappDeploymentSource }\n    | { schemaVersion: 2; success: true; value: ResolvedDappDeploymentSourceV2 }\n\ninterface DeploymentThingSource {\n  request: DappDeploymentRequestDocument\n  things: Readonly<Record<string, DappDeployableThing>>\n}\n\nfunction issue(\n  code: DappDeploymentSourceIssueCode,\n  message: string,\n  path: (number | string)[],\n): DappDeploymentSourceIssue {\n  return {\n    code, message, path,\n  }\n}\n\nfunction normalizedRequest(document: DappDeploymentRequestDocument): DappDeploymentRequestDocument {\n  return DappDeploymentRequestDocumentZod.parse({\n    ...document,\n    request: normalizeDappDeploymentRequest(document.request),\n  })\n}\n\n// Cross-document reference validation is intentionally kept in one exhaustive pass.\n// eslint-disable-next-line max-statements\nfunction validateThingReferences(\n  project: DappProjectManifest,\n  deploymentName: string,\n  deployment: DeploymentThingSource,\n): DappDeploymentSourceIssue[] {\n  const issues: DappDeploymentSourceIssue[] = []\n  const request = deployment.request.request\n  const actorIds = new Set(request.actors.map(actor => actor.instanceId))\n  const portIds = new Set(project.definition.ports.map(port => port.portId))\n  const addResource = (\n    resourceId: string,\n    expectedClass: string | readonly string[],\n    thingId: string,\n    field: string,\n  ) => {\n    const resource = request.resources[resourceId]\n    const expected = typeof expectedClass === 'string' ? [expectedClass] : expectedClass\n    if (resource === undefined || !expected.includes(resource.class)) {\n      issues.push(issue(\n        'deployment.source-reference-invalid',\n        `resource ${resourceId} must be declared with class ${expected.join(' or ')}`,\n        ['deployments', deploymentName, 'things', thingId, field],\n      ))\n    }\n  }\n  const addActor = (actorId: string, thingId: string) => {\n    if (!actorIds.has(actorId)) {\n      issues.push(issue(\n        'deployment.source-reference-invalid',\n        `consumer actor ${actorId} is not declared by the deployment request`,\n        ['deployments', deploymentName, 'things', thingId, 'consumerActor'],\n      ))\n    }\n  }\n\n  for (const [thingId, thing] of Object.entries(deployment.things)) {\n    if ('artifactId' in thing) {\n      const artifact = project.artifacts[thing.artifactId]\n      const expectedKind = thing.kind === 'website' ? 'static-site' : 'dapp-host'\n      if (artifact?.kind !== expectedKind) {\n        issues.push(issue(\n          'deployment.source-reference-invalid',\n          `artifact ${thing.artifactId} must be a declared ${expectedKind} artifact`,\n          ['deployments', deploymentName, 'things', thingId, 'artifactId'],\n        ))\n      }\n    }\n    kindSwitch:\n    switch (thing.kind) {\n      case 'api': {\n        for (const [portIndex, portId] of thing.ports.entries()) {\n          if (!portIds.has(portId) || request.portBindings.every(binding => binding.portId !== portId)) {\n            issues.push(issue(\n              'deployment.source-reference-invalid',\n              `port ${portId} is not declared and bound by the project`,\n              ['deployments', deploymentName, 'things', thingId, 'ports', portIndex],\n            ))\n          }\n        }\n\n        break kindSwitch\n      }\n      case 'datalake': {\n        addResource(thing.resourceId, 'datalake', thingId, 'resourceId')\n\n        break kindSwitch\n      }\n      case 'event-ingress': {\n        addResource(thing.eventStreamResource, 'event-stream', thingId, 'eventStreamResource')\n\n        break kindSwitch\n      }\n      case 'event-stream': {\n        addResource(thing.resourceId, 'event-stream', thingId, 'resourceId')\n\n        break kindSwitch\n      }\n      case 'subscription-runner': {\n        addResource(thing.subscriptionResource, 'event-subscription', thingId, 'subscriptionResource')\n        addActor(thing.consumerActor, thingId)\n\n        break kindSwitch\n      }\n      case 'indexer': {\n        addResource(thing.subscriptionResource, 'event-subscription', thingId, 'subscriptionResource')\n        addResource(thing.projectionResource, 'projection-store', thingId, 'projectionResource')\n        addResource(thing.checkpointResource, 'checkpoint-store', thingId, 'checkpointResource')\n        addActor(thing.consumerActor, thingId)\n\n        break kindSwitch\n      }\n      case 'controller': {\n        addResource(thing.subscriptionResource, 'event-subscription', thingId, 'subscriptionResource')\n        addResource(thing.effectJournalResource, 'effect-journal', thingId, 'effectJournalResource')\n        addActor(thing.consumerActor, thingId)\n\n        break kindSwitch\n      }\n      case 'publisher': {\n        addResource(thing.subscriptionResource, 'event-subscription', thingId, 'subscriptionResource')\n        for (const resourceId of thing.publicationResources) {\n          addResource(resourceId, ['datalake', 'projection-store', 'checkpoint-store'], thingId, 'publicationResources')\n        }\n        addActor(thing.consumerActor, thingId)\n\n        break kindSwitch\n      }\n    // No default\n    }\n  }\n  return issues\n}\n\nexport function resolveDappDeploymentSource(\n  input: ResolveDappDeploymentSourceInput,\n): DappDeploymentSourceResolutionResult {\n  const projectResult = DappProjectManifestDocumentZod.safeParse(input.projectManifest)\n  const nameResult = z.string().min(1).safeParse(input.deploymentName)\n  if (!projectResult.success || !nameResult.success) {\n    return { issues: [issue('deployment.source-invalid', 'project manifest or deployment name is invalid', [])], success: false }\n  }\n  const project = projectResult.data\n  const embedded = project.deployments[input.deploymentName]\n  if (input.deploymentManifest === undefined) {\n    return embedded === undefined\n      ? { issues: [issue('deployment.source-unknown', `deployment ${input.deploymentName} is not declared`, ['deployments', input.deploymentName])], success: false }\n      : { success: true, value: { mode: 'embedded-v1', request: normalizedRequest(embedded) } }\n  }\n\n  const splitResult = DappDeploymentManifestDocumentZod.safeParse(input.deploymentManifest)\n  if (!splitResult.success) {\n    return {\n      issues: splitResult.error.issues.map(parseIssue => issue(\n        'deployment.source-invalid',\n        parseIssue.message,\n        parseIssue.path.map(path => typeof path === 'symbol' ? path.toString() : path),\n      )),\n      success: false,\n    }\n  }\n  const deploymentManifest = normalizeDappDeploymentManifest(splitResult.data)\n  if (deploymentManifest.projectId !== project.projectId) {\n    return {\n      issues: [issue('deployment.source-project-mismatch', 'deployment and project manifest IDs differ', ['projectId'])],\n      success: false,\n    }\n  }\n  const split = deploymentManifest.deployments[input.deploymentName]\n  if (split === undefined) {\n    return embedded === undefined\n      ? { issues: [issue('deployment.source-unknown', `deployment ${input.deploymentName} is not declared`, ['deployments', input.deploymentName])], success: false }\n      : { success: true, value: { mode: 'embedded-v1', request: normalizedRequest(embedded) } }\n  }\n  if (split.request.projectId !== project.projectId || split.request.deploymentName !== input.deploymentName) {\n    return {\n      issues: [issue('deployment.source-project-mismatch', 'split request identity must match its project and deployment key', ['deployments', input.deploymentName, 'request'])],\n      success: false,\n    }\n  }\n\n  const requestProject = { ...project, deployments: { [input.deploymentName]: split.request } }\n  const requestValidation = validateDappProjectManifest(requestProject)\n  const referenceIssues = validateThingReferences(project, input.deploymentName, split)\n  if (!requestValidation.success || referenceIssues.length > 0) {\n    return {\n      issues: [\n        ...(requestValidation.success\n          ? []\n          : requestValidation.issues.map(projectIssue => issue('deployment.source-reference-invalid', projectIssue.message, projectIssue.path))),\n        ...referenceIssues,\n      ],\n      success: false,\n    }\n  }\n\n  const normalizedSplit = normalizedRequest(split.request)\n  if (embedded !== undefined\n    && canonicalizeIJson(normalizedRequest(embedded)) !== canonicalizeIJson(normalizedSplit)) {\n    return {\n      issues: [issue(\n        'deployment.source-conflict',\n        `embedded and split deployment ${input.deploymentName} requests disagree`,\n        ['deployments', input.deploymentName, 'request'],\n      )],\n      success: false,\n    }\n  }\n  return {\n    success: true,\n    value: {\n      deploymentManifest,\n      deploymentManifestId: hashDappDeploymentManifest(deploymentManifest),\n      mode: 'split-v2',\n      request: normalizedSplit,\n      split,\n    },\n  }\n}\n\nfunction validateRequestAgainstProject(\n  project: DappProjectManifest,\n  deploymentName: string,\n  deployment: DeploymentThingSource,\n): DappDeploymentSourceIssue[] {\n  const requestProject = { ...project, deployments: { [deploymentName]: deployment.request } }\n  const requestValidation = validateDappProjectManifest(requestProject)\n  return [\n    ...(requestValidation.success\n      ? []\n      : requestValidation.issues.map(projectIssue => issue('deployment.source-reference-invalid', projectIssue.message, projectIssue.path))),\n    ...validateThingReferences(project, deploymentName, deployment),\n  ]\n}\n\n/**\n * Resolves one named deployment from a Deployment Manifest V2. A supplied V2\n * manifest is authoritative: the deployment must exist there, and there is\n * never a fallback to an embedded V1 request. An embedded request for the same\n * name must be byte-equivalent after canonicalization or resolution fails with\n * `deployment.source-conflict`.\n */\nexport function resolveDappDeploymentSourceV2(\n  input: ResolveDappDeploymentSourceV2Input,\n): DappDeploymentSourceResolutionV2Result {\n  const projectResult = DappProjectManifestDocumentZod.safeParse(input.projectManifest)\n  const nameResult = z.string().min(1).safeParse(input.deploymentName)\n  if (!projectResult.success || !nameResult.success) {\n    return { issues: [issue('deployment.source-invalid', 'project manifest or deployment name is invalid', [])], success: false }\n  }\n  const project = projectResult.data\n  const manifestResult = DappDeploymentManifestV2DocumentZod.safeParse(input.deploymentManifest)\n  if (!manifestResult.success) {\n    return {\n      issues: manifestResult.error.issues.map(parseIssue => issue(\n        'deployment.source-invalid',\n        parseIssue.message,\n        parseIssue.path.map(path => typeof path === 'symbol' ? path.toString() : path),\n      )),\n      success: false,\n    }\n  }\n  const deploymentManifest = normalizeDappDeploymentManifestV2(manifestResult.data)\n  if (deploymentManifest.projectId !== project.projectId) {\n    return {\n      issues: [issue('deployment.source-project-mismatch', 'deployment and project manifest IDs differ', ['projectId'])],\n      success: false,\n    }\n  }\n  const deployment = deploymentManifest.deployments[input.deploymentName]\n  if (deployment === undefined) {\n    return {\n      issues: [issue('deployment.source-unknown', `deployment ${input.deploymentName} is not declared by the V2 manifest`, ['deployments', input.deploymentName])],\n      success: false,\n    }\n  }\n  if (deployment.request.projectId !== project.projectId || deployment.request.deploymentName !== input.deploymentName) {\n    return {\n      issues: [issue('deployment.source-project-mismatch', 'split request identity must match its project and deployment key', ['deployments', input.deploymentName, 'request'])],\n      success: false,\n    }\n  }\n  const referenceIssues = validateRequestAgainstProject(project, input.deploymentName, deployment)\n  if (referenceIssues.length > 0) return { issues: referenceIssues, success: false }\n\n  const embedded = project.deployments[input.deploymentName]\n  if (embedded !== undefined\n    && canonicalizeIJson(normalizedRequest(embedded)) !== canonicalizeIJson(deployment.request)) {\n    return {\n      issues: [issue(\n        'deployment.source-conflict',\n        `embedded and V2 deployment ${input.deploymentName} requests disagree`,\n        ['deployments', input.deploymentName, 'request'],\n      )],\n      success: false,\n    }\n  }\n  return {\n    success: true,\n    value: {\n      deployment,\n      deploymentManifest,\n      deploymentManifestId: hashDappDeploymentManifestV2(deploymentManifest),\n      mode: DappDeploymentSourceResolutionModeV2,\n      request: deployment.request,\n      selectedInfrastructure: selectDappDeploymentInfrastructureV2(deploymentManifest, input.deploymentName),\n    },\n  }\n}\n\nconst VersionDispatchZod = z.object({\n  $schema: z.string(),\n  schemaVersion: z.number(),\n})\n\n/**\n * Dispatches on the exact (`$schema`, `schemaVersion`) pair of the supplied\n * deployment manifest. The pair must agree on one supported version; a V2 URL\n * with version 1, or any other disagreement, is rejected rather than guessed.\n * Without a deployment manifest the embedded V1 request path applies.\n */\nexport function resolveDappDeploymentSourceAny(\n  input: ResolveDappDeploymentSourceInput,\n): DappDeploymentSourceResolutionAnyResult {\n  const withVersion = (result: DappDeploymentSourceResolutionResult): DappDeploymentSourceResolutionAnyResult =>\n    result.success\n      ? {\n          schemaVersion: 1, success: true, value: result.value,\n        }\n      : result\n  if (input.deploymentManifest === undefined) return withVersion(resolveDappDeploymentSource(input))\n  const dispatch = VersionDispatchZod.safeParse(input.deploymentManifest)\n  if (!dispatch.success) {\n    return { issues: [issue('deployment.source-invalid', 'deployment manifest must declare $schema and schemaVersion', [])], success: false }\n  }\n  const { $schema, schemaVersion } = dispatch.data\n  if ($schema === DappDeploymentJsonSchemaUrl && schemaVersion === 1) return withVersion(resolveDappDeploymentSource(input))\n  if ($schema === DappDeploymentJsonSchemaV2Url && schemaVersion === 2) {\n    const result = resolveDappDeploymentSourceV2({ ...input, deploymentManifest: input.deploymentManifest })\n    return result.success\n      ? {\n          schemaVersion: 2, success: true, value: result.value,\n        }\n      : result\n  }\n  return {\n    issues: [issue(\n      'deployment.source-invalid',\n      `deployment manifest $schema ${$schema} and schemaVersion ${schemaVersion} do not agree on one supported version`,\n      ['schemaVersion'],\n    )],\n    success: false,\n  }\n}\n", "import { z } from 'zod'\n\nimport {\n  canonicalizeIJson,\n  DappDocumentHashAlgorithm,\n  hashDappDocument,\n} from './canonicalDocument.ts'\nimport {\n  createDappDeploymentIntentV1,\n  type DappDeploymentIntentV1,\n} from './deploymentIntent.ts'\nimport type {\n  DappArtifactLock,\n  DappDeploymentLockIssue,\n} from './deploymentLock.ts'\nimport {\n  createDappDeploymentLock,\n  DappDeploymentLockSchema,\n} from './deploymentLock.ts'\nimport {\n  type CreateDappDeploymentLockV2Input,\n  DappDeploymentLockV2PreimageZod,\n} from './deploymentLockV2.ts'\nimport { resolveDappDeploymentSourceV2 } from './deploymentSourceResolution.ts'\nimport {\n  HashZod,\n  IdentifierZod,\n} from './identifier.ts'\nimport {\n  DappInfrastructureIdZod,\n  DappSelectedInfrastructureV1Zod,\n} from './infrastructureDescriptor.ts'\nimport {\n  compareCodeUnits,\n  findSortedUniqueIssue,\n} from './ordering.ts'\nimport { createDappPlan } from './plan.ts'\nimport { hashDappProjectManifest } from './projectManifest.ts'\nimport { DappProjectManifestDocumentZod } from './projectManifestModel.ts'\n\n/**\n * Deployment Lock V3 (D-032). The preimage is Lock V2 without `schemaVersion`,\n * `deployment`, and `bindings`, plus a V2-manifest/intent-bound `deployment`,\n * alias-free `placements` by immutable `infrastructureId`, and the sorted\n * selected-infrastructure projection. Every other V2 field keeps its frozen\n * type and meaning. Connection profiles, grants, aliases, protected identities,\n * inventory, and operation state never enter the lock.\n */\nconst V2 = DappDeploymentLockV2PreimageZod.shape\n\nconst ThingPlacementZod = z.strictObject({ thingId: IdentifierZod, infrastructureId: DappInfrastructureIdZod })\nconst ResourcePlacementZod = z.strictObject({ resourceId: IdentifierZod, infrastructureId: DappInfrastructureIdZod })\nconst HostPlacementZod = z.strictObject({ hostPartitionId: IdentifierZod, infrastructureId: DappInfrastructureIdZod })\n\ninterface RefinementContext {\n  addIssue: (issue: { code: 'custom'; message: string; path: (number | string)[] }) => void\n}\n\nfunction refineSortedById<T>(\n  context: RefinementContext,\n  values: readonly T[],\n  idOf: (value: T) => string,\n  path: (number | string)[],\n): void {\n  const issue = findSortedUniqueIssue(values, (left, right) => compareCodeUnits(idOf(left), idOf(right)), path.join('.'))\n  if (issue !== undefined) {\n    context.addIssue({\n      code: 'custom', message: issue.message, path: [...path, issue.index],\n    })\n  }\n}\n\nexport const DappDeploymentLockV3PreimageZod = z.strictObject({\n  schema: z.literal(DappDeploymentLockSchema),\n  schemaVersion: z.literal(3),\n  hashAlgorithm: z.literal(DappDocumentHashAlgorithm),\n  project: V2.project,\n  deployment: z.strictObject({\n    name: IdentifierZod,\n    requestHash: HashZod,\n    manifest: z.strictObject({\n      schemaVersion: z.literal(2),\n      deploymentManifestId: HashZod,\n    }),\n    intent: z.strictObject({\n      schemaVersion: z.literal(1),\n      deploymentIntentId: HashZod,\n    }),\n  }),\n  things: V2.things,\n  placements: z.strictObject({\n    things: z.array(ThingPlacementZod),\n    resources: z.array(ResourcePlacementZod),\n    hosts: z.array(HostPlacementZod),\n  }),\n  infrastructure: z.array(DappSelectedInfrastructureV1Zod),\n  definitionHash: V2.definitionHash,\n  configurationHash: V2.configurationHash,\n  configuration: V2.configuration,\n  plan: V2.plan,\n  source: V2.source,\n  packageManager: V2.packageManager,\n  environment: V2.environment,\n  resources: V2.resources,\n  artifacts: V2.artifacts,\n  promotable: V2.promotable,\n}).superRefine((lock, context) => {\n  refineSortedById(context, lock.placements.things, entry => entry.thingId, ['placements', 'things'])\n  refineSortedById(context, lock.placements.resources, entry => entry.resourceId, ['placements', 'resources'])\n  refineSortedById(context, lock.placements.hosts, entry => entry.hostPartitionId, ['placements', 'hosts'])\n  refineSortedById(context, lock.infrastructure, entry => entry.infrastructureId, ['infrastructure'])\n\n  const thingIds = Object.keys(lock.things).toSorted(compareCodeUnits)\n  const placedThingIds = lock.placements.things.map(entry => entry.thingId)\n  if (thingIds.length !== placedThingIds.length || thingIds.some((thingId, index) => placedThingIds[index] !== thingId)) {\n    context.addIssue({\n      code: 'custom', message: 'every thing must be placed exactly once', path: ['placements', 'things'],\n    })\n  }\n  const referenced = [...new Set([\n    ...lock.placements.things.map(entry => entry.infrastructureId),\n    ...lock.placements.resources.map(entry => entry.infrastructureId),\n    ...lock.placements.hosts.map(entry => entry.infrastructureId),\n  ])].toSorted(compareCodeUnits)\n  const declared = lock.infrastructure.map(entry => entry.infrastructureId)\n  if (referenced.length !== declared.length || referenced.some((id, index) => declared[index] !== id)) {\n    context.addIssue({\n      code: 'custom',\n      message: 'infrastructure must be exactly the set of instances referenced by the placements',\n      path: ['infrastructure'],\n    })\n  }\n  const resourceIds = lock.resources.map(resource => resource.resourceId)\n  const unique = new Set(resourceIds)\n  if (unique.size !== resourceIds.length) {\n    context.addIssue({\n      code: 'custom', message: 'resource IDs must be unique', path: ['resources'],\n    })\n  }\n  for (const selection of lock.configuration.applicationProviders ?? []) {\n    if (lock.artifacts.every(artifact => artifact.artifactId !== selection.artifactId)) {\n      context.addIssue({\n        code: 'custom', message: 'application Provider artifact is not admitted in this lock', path: ['artifacts'],\n      })\n    }\n  }\n  const artifactIds = lock.artifacts.map(artifact => artifact.artifactId)\n  const unique2 = new Set(artifactIds)\n  if (unique2.size !== artifactIds.length) {\n    context.addIssue({\n      code: 'custom', message: 'artifact IDs must be unique', path: ['artifacts'],\n    })\n  }\n})\n\nexport type DappDeploymentLockV3Preimage = z.infer<typeof DappDeploymentLockV3PreimageZod>\nexport const DappDeploymentLockV3Zod = DappDeploymentLockV3PreimageZod.safeExtend({ lockId: HashZod })\nexport type DappDeploymentLockV3 = z.infer<typeof DappDeploymentLockV3Zod>\n\nexport interface CreateDappDeploymentLockV3Input extends CreateDappDeploymentLockV2Input {\n  /** The host's public-safe projection of every registered entry, keyed by manifest alias. */\n  infrastructure: Readonly<Record<string, unknown>>\n}\n\nexport interface DappDeploymentLockV3Success {\n  intent: DappDeploymentIntentV1\n  success: true\n  value: DappDeploymentLockV3\n}\n\nexport type DappDeploymentLockV3Result\n  = DappDeploymentLockV3Success | { issues: DappDeploymentLockIssue[]; success: false }\n\nfunction invalid(message: string, path: (number | string)[] = []): DappDeploymentLockV3Result {\n  return {\n    issues: [{\n      code: 'deployment.lock-input-invalid', message, path,\n    }],\n    success: false,\n  }\n}\n\nfunction sortedRecord<T>(record: Readonly<Record<string, T>>): Record<string, T> {\n  return Object.fromEntries(Object.entries(record).toSorted(([left], [right]) => left.localeCompare(right)))\n}\n\nfunction sortedArtifacts(artifacts: readonly DappArtifactLock[]): DappArtifactLock[] {\n  return [...artifacts].toSorted((left, right) => left.artifactId.localeCompare(right.artifactId))\n}\n\n/** D-002 kind `deployment-lock` version 3: `xyo-dapp-kit:deployment-lock:v3\\n`. */\nexport function hashDappDeploymentLockV3(preimage: unknown): string {\n  return hashDappDocument({\n    kind: 'deployment-lock',\n    schema: DappDeploymentLockV3PreimageZod,\n    schemaVersion: 3,\n  }, preimage).hash\n}\n\n/**\n * Builds a Lock V3 from a project manifest, a Deployment Manifest V2, and the\n * selected safe infrastructure projections. Resolution goes through the\n * V2-only resolver, so an embedded V1 request can never substitute for the\n * V2 deployment; the manifest and intent identities are recomputed here and\n * never accepted as inputs.\n */\nexport function createDappDeploymentLockV3(input: CreateDappDeploymentLockV3Input): DappDeploymentLockV3Result {\n  const projectResult = DappProjectManifestDocumentZod.safeParse(input.projectManifest)\n  if (!projectResult.success) return invalid('project manifest is invalid')\n  const sourceResolution = resolveDappDeploymentSourceV2({\n    deploymentManifest: input.deploymentManifest,\n    deploymentName: input.deploymentName,\n    projectManifest: projectResult.data,\n  })\n  if (!sourceResolution.success) {\n    return {\n      issues: sourceResolution.issues.map(sourceIssue => ({\n        code: 'deployment.lock-input-invalid',\n        message: `${sourceIssue.code}: ${sourceIssue.message}`,\n        path: sourceIssue.path,\n      })),\n      success: false,\n    }\n  }\n  const {\n    deployment, deploymentManifest, deploymentManifestId,\n  } = sourceResolution.value\n  const intentResult = createDappDeploymentIntentV1({\n    deploymentManifest,\n    deploymentName: input.deploymentName,\n    infrastructure: input.infrastructure,\n  })\n  if (!intentResult.success) {\n    return {\n      issues: intentResult.issues.map(intentIssue => ({\n        code: 'deployment.lock-input-invalid',\n        message: `${intentIssue.code}: ${intentIssue.message}`,\n        path: intentIssue.path,\n      })),\n      success: false,\n    }\n  }\n  const intent = intentResult.value\n\n  const virtualProject = DappProjectManifestDocumentZod.parse({\n    ...projectResult.data,\n    deployments: { [input.deploymentName]: deployment.request },\n  })\n  const v1 = createDappDeploymentLock({\n    ...(input.applicationProviderDescriptors === undefined ? {} : { applicationProviderDescriptors: input.applicationProviderDescriptors }),\n    actorDescriptors: input.actorDescriptors,\n    artifacts: input.artifacts,\n    catalog: input.catalog,\n    deploymentName: input.deploymentName,\n    manifest: virtualProject,\n    packageManager: input.packageManager,\n    source: input.source,\n  })\n  if (!v1.success) return v1\n\n  const { lockId: _v1LockId, ...v1Preimage } = v1.value\n  const preimage = DappDeploymentLockV3PreimageZod.parse({\n    ...v1Preimage,\n    schemaVersion: 3,\n    project: {\n      schemaVersion: 1,\n      projectHash: hashDappProjectManifest(projectResult.data),\n    },\n    deployment: {\n      name: input.deploymentName,\n      requestHash: intent.requestHash,\n      manifest: { schemaVersion: 2, deploymentManifestId },\n      intent: { schemaVersion: 1, deploymentIntentId: intent.deploymentIntentId },\n    },\n    things: sortedRecord(deployment.things),\n    placements: {\n      things: intent.thingBindings,\n      resources: intent.resourceBindings,\n      hosts: intent.hostBindings,\n    },\n    infrastructure: intent.infrastructure,\n    artifacts: sortedArtifacts(v1.value.artifacts),\n  })\n  const lockId = hashDappDeploymentLockV3(preimage)\n  return {\n    intent, success: true, value: DappDeploymentLockV3Zod.parse({ ...preimage, lockId }),\n  }\n}\n\nexport function verifyDappDeploymentLockV3(value: unknown): DappDeploymentLockV3Result | { success: true; value: DappDeploymentLockV3 } {\n  const result = DappDeploymentLockV3Zod.safeParse(value)\n  if (!result.success) return invalid(result.error.issues.map(issue => issue.message).join('; '))\n  const { lockId, ...preimage } = result.data\n  const rebuiltPlan = createDappPlan({\n    actorDescriptors: preimage.plan.actorDescriptors,\n    configuration: preimage.plan.configuration,\n    definition: preimage.plan.definition,\n    portBindings: preimage.plan.portBindings,\n    resolvedProviders: preimage.plan.resolvedProviders,\n  })\n  if (!rebuiltPlan.success || rebuiltPlan.value.planId !== preimage.plan.planId\n    || preimage.definitionHash !== preimage.plan.definitionHash\n    || preimage.configurationHash !== preimage.plan.configurationHash\n    || canonicalizeIJson(preimage.configuration) !== canonicalizeIJson(preimage.plan.configuration)) {\n    return {\n      issues: [{\n        code: 'deployment.lock-verification-failed',\n        message: 'deployment lock contains a plan that cannot be reproduced',\n        path: ['plan'],\n      }],\n      success: false,\n    }\n  }\n  if (hashDappDeploymentLockV3(preimage) !== lockId) {\n    return {\n      issues: [{\n        code: 'deployment.lock-verification-failed',\n        message: 'deployment lock ID does not match its canonical V3 preimage',\n        path: ['lockId'],\n      }],\n      success: false,\n    }\n  }\n  return { success: true, value: DappDeploymentLockV3Zod.parse({ ...preimage, lockId }) }\n}\n", "import { asSchema } from '@xyo-network/sdk'\nimport { z } from 'zod'\n\nimport {\n  DappDeployableThingZod,\n  DappDeploymentManifestSchema,\n  hashDappDeploymentManifest,\n  normalizeDappDeploymentManifest,\n} from './deploymentManifest.ts'\nimport {\n  DappInfrastructurePlacementZod,\n  type DappInfrastructureRequirement,\n  DappInfrastructureRequirementZod,\n} from './deploymentManifestV2.ts'\nimport { DappDeploymentRequestDocumentZod } from './deploymentRequest.ts'\nimport {\n  DappIdZod,\n  HashZod,\n  IdentifierZod,\n} from './identifier.ts'\n\n/**\n * Operator-reviewed migration from Deployment Manifest V1 to V2 (D-031).\n *\n * The scaffold is a pure projection of one V1 document. It proposes an alias\n * and a thing binding for every legacy `(targetFamily, target)` label and\n * lists everything an operator must still decide: managed-resource owners,\n * host placements, omitted targets, and alias collisions. It contains no\n * valid V2 `$schema`, no hash identity, and no lock route, so it can never\n * pass Manifest V2 validation or reach planning; the completed document is\n * authored separately and validated normally.\n */\nexport const DappDeploymentMigrationScaffoldSchema = asSchema('network.xyo.dapp.deployment.migration.scaffold', true)\nexport const DappDeploymentMigrationScaffoldJsonSchemaUrl = 'https://schemas.xyo.network/dapp-kit/deployment/migration-scaffold/v1.json' as const\nexport const DappDeploymentMigrationScaffoldFileName = 'xl1.deploy.v2.scaffold.json' as const\n\nexport const DappDeploymentMigrationUnresolvedKindZod = z.enum([\n  'legacy-target-label',\n  'thing-placement',\n  'resource-placement',\n  'host-placement',\n  'omitted-target',\n  'alias-collision',\n])\nexport type DappDeploymentMigrationUnresolvedKind = z.infer<typeof DappDeploymentMigrationUnresolvedKindZod>\n\nexport const DappDeploymentMigrationUnresolvedReasonZod = z.enum([\n  'target-not-explicit',\n  'infrastructure-alias-required',\n  'managed-resource-owner-required',\n  'host-placement-required',\n  'proposed-alias-collision',\n])\nexport type DappDeploymentMigrationUnresolvedReason = z.infer<typeof DappDeploymentMigrationUnresolvedReasonZod>\n\n/** RFC 6901 JSON Pointer into the source V1 document. */\nexport const JsonPointerZod = z.string().regex(/^(?:\\/(?:[^/~]|~0|~1)*)*$/)\n\nexport const DappDeploymentMigrationUnresolvedZod = z.strictObject({\n  kind: DappDeploymentMigrationUnresolvedKindZod,\n  sourcePath: JsonPointerZod,\n  reason: DappDeploymentMigrationUnresolvedReasonZod,\n  proposedAlias: IdentifierZod.optional(),\n})\nexport type DappDeploymentMigrationUnresolved = z.infer<typeof DappDeploymentMigrationUnresolvedZod>\n\n/**\n * The draft is V2-shaped but deliberately not a V2 document: it has no\n * `$schema`, and its placement maps are only proposals. Parsing it with\n * `DappDeploymentManifestV2DocumentZod` always fails.\n */\nexport const DappDeploymentManifestV2DraftZod = z.strictObject({\n  schema: z.literal(DappDeploymentManifestSchema),\n  schemaVersion: z.literal(2),\n  projectId: DappIdZod,\n  infrastructure: z.record(IdentifierZod, DappInfrastructureRequirementZod),\n  deployments: z.record(IdentifierZod, z.strictObject({\n    request: DappDeploymentRequestDocumentZod,\n    things: z.record(IdentifierZod, DappDeployableThingZod),\n    bindings: z.record(IdentifierZod, DappInfrastructurePlacementZod),\n    resourceBindings: z.record(IdentifierZod, DappInfrastructurePlacementZod),\n    hostBindings: z.record(IdentifierZod, DappInfrastructurePlacementZod),\n  })),\n})\nexport type DappDeploymentManifestV2Draft = z.infer<typeof DappDeploymentManifestV2DraftZod>\n\nfunction compareCodeUnits(left: string, right: string): number {\n  if (left === right) return 0\n  return left < right ? -1 : 1\n}\n\nexport function compareDappDeploymentMigrationUnresolved(\n  left: DappDeploymentMigrationUnresolved,\n  right: DappDeploymentMigrationUnresolved,\n): number {\n  return compareCodeUnits(left.sourcePath, right.sourcePath)\n    || compareCodeUnits(left.kind, right.kind)\n    || compareCodeUnits(left.reason, right.reason)\n    || compareCodeUnits(left.proposedAlias ?? '', right.proposedAlias ?? '')\n}\n\nexport const DappDeploymentManifestV1MigrationScaffoldZod = z.strictObject({\n  $schema: z.literal(DappDeploymentMigrationScaffoldJsonSchemaUrl),\n  schema: z.literal(DappDeploymentMigrationScaffoldSchema),\n  schemaVersion: z.literal(1),\n  source: z.strictObject({\n    schemaVersion: z.literal(1),\n    projectId: DappIdZod,\n    deploymentManifestId: HashZod,\n    deployments: z.array(IdentifierZod),\n  }),\n  draft: DappDeploymentManifestV2DraftZod,\n  unresolved: z.array(DappDeploymentMigrationUnresolvedZod),\n}).superRefine((scaffold, context) => {\n  for (let index = 1; index < scaffold.unresolved.length; index++) {\n    const order = compareDappDeploymentMigrationUnresolved(scaffold.unresolved[index - 1], scaffold.unresolved[index])\n    if (order >= 0) {\n      context.addIssue({\n        code: 'custom',\n        message: order === 0 ? 'unresolved entries must be unique' : 'unresolved entries must be sorted',\n        path: ['unresolved', index],\n      })\n    }\n  }\n  const names = [...scaffold.source.deployments].toSorted()\n  const unique = new Set(names)\n  if (names.some((name, index) => name !== scaffold.source.deployments[index])\n    || unique.size !== names.length) {\n    context.addIssue({\n      code: 'custom', message: 'source deployments must be sorted and unique', path: ['source', 'deployments'],\n    })\n  }\n})\n\nexport type DappDeploymentManifestV1MigrationScaffold = z.infer<typeof DappDeploymentManifestV1MigrationScaffoldZod>\n\nfunction pointer(...segments: (number | string)[]): string {\n  return segments.map(segment => `/${String(segment).replaceAll('~', '~0').replaceAll('/', '~1')}`).join('')\n}\n\n// The scaffold walks every deployment once and records each unresolved item at\n// the point it is discovered, which keeps the projection auditable as one pass.\n// eslint-disable-next-line max-statements\nexport function createDappDeploymentManifestV2Scaffold(value: unknown): DappDeploymentManifestV1MigrationScaffold {\n  const manifest = normalizeDappDeploymentManifest(value)\n  const kindsByAlias = new Map<string, Set<string>>()\n  for (const deployment of Object.values(manifest.deployments)) {\n    for (const binding of Object.values(deployment.bindings)) {\n      const alias = binding.target ?? binding.targetFamily\n      const kinds = kindsByAlias.get(alias) ?? new Set<string>()\n      kinds.add(binding.targetFamily)\n      kindsByAlias.set(alias, kinds)\n    }\n  }\n\n  const unresolved: DappDeploymentMigrationUnresolved[] = []\n  const draftDeployments: DappDeploymentManifestV2Draft['deployments'] = {}\n  for (const [name, deployment] of Object.entries(manifest.deployments)) {\n    const bindings: Record<string, { infrastructure: string }> = {}\n    for (const [thingId, binding] of Object.entries(deployment.bindings)) {\n      const alias = binding.target ?? binding.targetFamily\n      const bindingPath = pointer('deployments', name, 'bindings', thingId)\n      bindings[thingId] = { infrastructure: alias }\n      unresolved.push({\n        kind: 'legacy-target-label', sourcePath: bindingPath, reason: 'infrastructure-alias-required', proposedAlias: alias,\n      }, {\n        kind: 'thing-placement', sourcePath: pointer('deployments', name, 'things', thingId), reason: 'infrastructure-alias-required', proposedAlias: alias,\n      })\n      if (binding.target === undefined) {\n        unresolved.push({\n          kind: 'omitted-target', sourcePath: bindingPath, reason: 'target-not-explicit', proposedAlias: alias,\n        })\n      }\n      if ((kindsByAlias.get(alias)?.size ?? 0) > 1) {\n        unresolved.push({\n          kind: 'alias-collision', sourcePath: bindingPath, reason: 'proposed-alias-collision', proposedAlias: alias,\n        })\n      }\n    }\n    const request = deployment.request.request\n    nestedLoop:\n    for (const [resourceId, resource] of Object.entries(request.resources)) {\n      if (resource.provision === 'external') continue nestedLoop\n      unresolved.push({\n        kind: 'resource-placement',\n        sourcePath: pointer('deployments', name, 'request', 'request', 'resources', resourceId),\n        reason: 'managed-resource-owner-required',\n      })\n    }\n    const seenHosts = new Set<string>()\n    nestedLoop2:\n    for (const [index, actor] of request.actors.entries()) {\n      if (seenHosts.has(actor.host)) continue nestedLoop2\n      seenHosts.add(actor.host)\n      unresolved.push({\n        kind: 'host-placement',\n        sourcePath: pointer('deployments', name, 'request', 'request', 'actors', index, 'host'),\n        reason: 'host-placement-required',\n      })\n    }\n    draftDeployments[name] = {\n      request: deployment.request,\n      things: deployment.things,\n      bindings,\n      resourceBindings: {},\n      hostBindings: {},\n    }\n  }\n\n  const registryEntries: [string, DappInfrastructureRequirement][] = [...kindsByAlias]\n    .filter(([, kinds]) => kinds.size === 1)\n    .map(([alias, kinds]) => [alias, DappInfrastructureRequirementZod.parse({ kind: [...kinds][0] })])\n  const infrastructure = Object.fromEntries(registryEntries.toSorted(([left], [right]) => compareCodeUnits(left, right)))\n\n  return DappDeploymentManifestV1MigrationScaffoldZod.parse({\n    $schema: DappDeploymentMigrationScaffoldJsonSchemaUrl,\n    schema: DappDeploymentMigrationScaffoldSchema,\n    schemaVersion: 1,\n    source: {\n      schemaVersion: 1,\n      projectId: manifest.projectId,\n      deploymentManifestId: hashDappDeploymentManifest(manifest),\n      deployments: Object.keys(manifest.deployments).toSorted(),\n    },\n    draft: {\n      schema: DappDeploymentManifestSchema,\n      schemaVersion: 2,\n      projectId: manifest.projectId,\n      infrastructure,\n      deployments: draftDeployments,\n    },\n    unresolved: unresolved.toSorted(compareDappDeploymentMigrationUnresolved),\n  })\n}\n", "import { z } from 'zod'\n\nimport type {\n  EffectPreparationJournal,\n  EffectReceiptJournal,\n  EffectReceiptJournalIssueCode,\n} from './effectJournal.ts'\nimport { EffectReceiptJournalError } from './effectJournal.ts'\nimport type {\n  EffectReceipt,\n  EffectReceiptObservation,\n} from './effectModel.ts'\nimport { EffectReceiptExecutionReasonCode, EffectReceiptZod } from './effectModel.ts'\nimport type { PreparedEffectRecord } from './effectPreparation.ts'\nimport { PreparedEffectRecordZod } from './effectPreparation.ts'\nimport type { EffectReceiptIssue } from './effectValidation.ts'\nimport {\n  assessEffectReceiptExecutionSupport,\n  summarizeEffectReceipt,\n  validateEffectReceipt,\n  validateEffectReceiptAppend,\n} from './effectValidation.ts'\nimport { IdentifierZod } from './identifier.ts'\n\ntype OmitObservationSequence<T> = T extends EffectReceiptObservation ? Omit<T, 'sequence'> : never\n\nexport type EffectReceiptObservationInput = OmitObservationSequence<EffectReceiptObservation>\n\nexport const EffectExecutionMaxAdvancesZod = z.number().int().positive().max(10_000)\n\nexport interface EffectReconciliationAdvance {\n  readonly observation: EffectReceiptObservationInput\n  readonly state: 'advance'\n}\n\nexport interface EffectReconciliationPending {\n  readonly reasonCode: string\n  readonly state: 'pending'\n}\n\nexport type EffectReconciliationResult = EffectReconciliationAdvance | EffectReconciliationPending\n\nexport interface EffectReconciler {\n  /** Observe canonical evidence before retrying an incomplete external stage. */\n  reconcile(receipt: EffectReceipt): Promise<EffectReconciliationResult>\n}\n\nexport interface ExecuteEffectOptions {\n  readonly isCancellationRequested?: () => boolean\n  readonly journal: EffectReceiptJournal\n  readonly maxAdvances: number\n  readonly reconciler: EffectReconciler\n}\n\nexport interface ExecutePreparedEffectOptions extends Omit<ExecuteEffectOptions, 'journal'> {\n  readonly journal: EffectPreparationJournal\n}\n\nexport const EffectExecutionOutcomeStates = [\n  'abandoned',\n  'advance-limit',\n  'cancelled',\n  'complete',\n  'pending',\n] as const\n\nexport const EffectExecutionOutcomeStateZod = z.enum(EffectExecutionOutcomeStates)\nexport type EffectExecutionOutcomeState = z.infer<typeof EffectExecutionOutcomeStateZod>\n\nexport interface EffectExecutionOutcome {\n  readonly advances: number\n  readonly reasonCode?: string\n  readonly receipt: EffectReceipt\n  readonly state: EffectExecutionOutcomeState\n}\n\nfunction journalError(\n  code: EffectReceiptJournalIssueCode,\n  message: string,\n  receiptIssues: readonly EffectReceiptIssue[] = [],\n): EffectReceiptJournalError {\n  return new EffectReceiptJournalError({\n    code, message, receiptIssues,\n  })\n}\n\nfunction validatePreparedReceipt(value: unknown): EffectReceipt {\n  const result = validateEffectReceipt(value)\n  if (!result.success) {\n    throw journalError(\n      'effect-journal.invalid-receipt',\n      'Prepared effect receipt is invalid',\n      result.issues,\n    )\n  }\n  if (result.value.observations.length !== 1 || result.value.observations[0]?.kind !== 'prepared') {\n    throw journalError(\n      'effect-journal.stage-count-invalid',\n      'Effect execution must begin with a prepared-only receipt',\n    )\n  }\n  return result.value\n}\n\nasync function loadOrCreateReceipt(\n  journal: EffectReceiptJournal,\n  prepared: EffectReceipt,\n): Promise<EffectReceipt> {\n  const persisted = await journal.read(prepared.effectId)\n  if (persisted === undefined) return (await journal.append(undefined, prepared)).receipt\n\n  const recoveryResult = validateEffectReceiptAppend(prepared, persisted)\n  if (!recoveryResult.success) {\n    throw journalError(\n      'effect-journal.conflict',\n      'Durable effect receipt does not extend the prepared command receipt',\n      recoveryResult.issues,\n    )\n  }\n  return recoveryResult.value\n}\n\nfunction terminalOutcome(receipt: EffectReceipt, advances: number): EffectExecutionOutcome | undefined {\n  const summary = summarizeEffectReceipt(receipt)\n  if (summary.abandoned) {\n    return {\n      advances, receipt, state: 'abandoned',\n    }\n  }\n  const support = assessEffectReceiptExecutionSupport(receipt)\n  if (!support.supported) {\n    return {\n      advances, reasonCode: support.reasonCode, receipt, state: 'pending',\n    }\n  }\n  if (summary.complete) {\n    return {\n      advances, receipt, state: 'complete',\n    }\n  }\n}\n\nexport async function executeEffect(\n  preparedValue: EffectReceipt,\n  options: ExecuteEffectOptions,\n): Promise<EffectExecutionOutcome> {\n  const prepared = validatePreparedReceipt(preparedValue)\n  const maxAdvances = EffectExecutionMaxAdvancesZod.parse(options.maxAdvances)\n  let receipt = await loadOrCreateReceipt(options.journal, prepared)\n  let advances = 0\n\n  while (true) {\n    const terminal = terminalOutcome(receipt, advances)\n    if (terminal !== undefined) return terminal\n    if (options.isCancellationRequested?.() === true) {\n      return {\n        advances, receipt, state: 'cancelled',\n      }\n    }\n    if (advances >= maxAdvances) {\n      return {\n        advances, receipt, state: 'advance-limit',\n      }\n    }\n\n    const reconciliation = await options.reconciler.reconcile(EffectReceiptZod.parse(receipt))\n    if (reconciliation.state === 'pending') {\n      return {\n        advances,\n        reasonCode: IdentifierZod.parse(reconciliation.reasonCode),\n        receipt,\n        state: 'pending',\n      }\n    }\n    if (receipt.identity.effectKind === 'xl1-transaction' && reconciliation.observation.kind === 'signed'\n      && receipt.observations.some(observation => observation.kind === 'signed')) {\n      return {\n        advances,\n        reasonCode: EffectReceiptExecutionReasonCode.replacementUnsupported,\n        receipt,\n        state: 'pending',\n      }\n    }\n\n    const next = {\n      ...receipt,\n      observations: [\n        ...receipt.observations,\n        {\n          ...reconciliation.observation,\n          sequence: receipt.observations.length + 1,\n        },\n      ],\n    }\n    receipt = (await options.journal.append(receipt, next)).receipt\n    advances += 1\n  }\n}\n\n/** Atomically admits a new effect before delegating ordinary append-only execution. */\nexport async function executePreparedEffect(\n  recordValue: PreparedEffectRecord,\n  options: ExecutePreparedEffectOptions,\n): Promise<EffectExecutionOutcome> {\n  const recordResult = PreparedEffectRecordZod.safeParse(recordValue)\n  if (!recordResult.success) {\n    throw journalError('effect-journal.invalid-preparation', 'Prepared effect record is invalid')\n  }\n  const persisted = await options.journal.read(recordResult.data.receipt.effectId)\n  // Signed work was already admitted. Resume its immutable prepared prefix without\n  // recreating private material; the reconciler decides whether its durable codec can repair content.\n  if (persisted?.observations.some(observation => observation.kind === 'signed')) {\n    return await executeEffect(recordResult.data.receipt, options)\n  }\n  const prepared = await options.journal.prepare(recordResult.data)\n  return await executeEffect(prepared.record.receipt, options)\n}\n", "import { z } from 'zod'\n\nimport { canonicalizeIJson } from './canonicalDocument.ts'\nimport type { EffectReceipt } from './effectModel.ts'\nimport type { PreparedEffectRecord } from './effectPreparation.ts'\nimport { PreparedEffectRecordZod } from './effectPreparation.ts'\nimport type { EffectReceiptIssue } from './effectValidation.ts'\nimport {\n  summarizeEffectReceipt,\n  validateEffectReceipt,\n  validateEffectReceiptAppend,\n} from './effectValidation.ts'\n\nexport const EffectReceiptJournalDurabilityZod = z.enum(['crash-durable', 'test-memory'])\nexport type EffectReceiptJournalDurability = z.infer<typeof EffectReceiptJournalDurabilityZod>\n\nexport const EffectReceiptJournalIssueCodes = [\n  'effect-journal.conflict',\n  'effect-journal.corrupt',\n  'effect-journal.invalid-append',\n  'effect-journal.invalid-preparation',\n  'effect-journal.invalid-receipt',\n  'effect-journal.preparation-not-compactable',\n  'effect-journal.preparation-required',\n  'effect-journal.stage-count-invalid',\n  'effect-journal.unavailable',\n] as const\n\nexport const EffectReceiptJournalIssueCodeZod = z.enum(EffectReceiptJournalIssueCodes)\nexport type EffectReceiptJournalIssueCode = z.infer<typeof EffectReceiptJournalIssueCodeZod>\n\nexport interface EffectReceiptJournalIssue {\n  readonly code: EffectReceiptJournalIssueCode\n  readonly message: string\n  readonly receiptIssues: readonly EffectReceiptIssue[]\n}\n\nexport interface EffectReceiptJournalAppendSuccess {\n  readonly changed: boolean\n  readonly receipt: EffectReceipt\n  readonly success: true\n}\n\nexport interface EffectReceiptJournalAppendFailure {\n  readonly issue: EffectReceiptJournalIssue\n  readonly success: false\n}\n\nexport type EffectReceiptJournalAppendResult = EffectReceiptJournalAppendFailure | EffectReceiptJournalAppendSuccess\n\nexport interface EffectReceiptJournal {\n  readonly durability: EffectReceiptJournalDurability\n  append(\n    expected: EffectReceipt | undefined,\n    next: EffectReceipt,\n  ): Promise<EffectReceiptJournalAppendSuccess>\n  list(): Promise<readonly EffectReceipt[]>\n  read(effectId: string): Promise<EffectReceipt | undefined>\n}\n\nexport interface EffectPreparationJournalWriteSuccess {\n  readonly changed: boolean\n  readonly record: PreparedEffectRecord\n  readonly success: true\n}\n\nexport interface EffectPreparationJournalCompactionSuccess {\n  readonly changed: boolean\n  readonly receipt: EffectReceipt\n  readonly success: true\n}\n\n/** Privileged sidecar operations; ordinary receipt/status surfaces use EffectReceiptJournal. */\nexport interface EffectPreparationJournal extends EffectReceiptJournal {\n  compactPreparation(expected: EffectReceipt): Promise<EffectPreparationJournalCompactionSuccess>\n  prepare(record: PreparedEffectRecord): Promise<EffectPreparationJournalWriteSuccess>\n  readPreparation(effectId: string): Promise<PreparedEffectRecord | undefined>\n}\n\nexport class EffectReceiptJournalError extends Error {\n  readonly code: EffectReceiptJournalIssueCode\n  readonly issue: EffectReceiptJournalIssue\n\n  constructor(issue: EffectReceiptJournalIssue, options?: ErrorOptions) {\n    super(issue.message, options)\n    this.name = 'EffectReceiptJournalError'\n    this.code = issue.code\n    this.issue = issue\n  }\n}\n\nexport function validateEffectPreparationJournalWrite(\n  persistedValue: unknown,\n  nextValue: unknown,\n): EffectPreparationJournalWriteSuccess | EffectReceiptJournalAppendFailure {\n  const nextResult = PreparedEffectRecordZod.safeParse(nextValue)\n  if (!nextResult.success) {\n    return failure('effect-journal.invalid-preparation', 'Prepared effect record is invalid')\n  }\n  if (persistedValue === undefined) {\n    return {\n      changed: true, record: nextResult.data, success: true,\n    }\n  }\n  const persistedResult = PreparedEffectRecordZod.safeParse(persistedValue)\n  if (!persistedResult.success) {\n    return failure('effect-journal.corrupt', 'Persisted prepared effect record is corrupt')\n  }\n  return canonicalizeIJson(persistedResult.data) === canonicalizeIJson(nextResult.data)\n    ? {\n        changed: false, record: persistedResult.data, success: true,\n      }\n    : failure('effect-journal.conflict', 'Prepared effect record already exists with different material')\n}\n\nexport function assertEffectPreparationJournalWrite(\n  persistedValue: unknown,\n  nextValue: unknown,\n): EffectPreparationJournalWriteSuccess {\n  const result = validateEffectPreparationJournalWrite(persistedValue, nextValue)\n  if (!result.success) throw new EffectReceiptJournalError(result.issue)\n  return result\n}\n\nexport function isEffectPreparationCompactable(receiptValue: unknown): boolean {\n  const receiptResult = validateEffectReceipt(receiptValue)\n  if (!receiptResult.success) return false\n  const receipt = receiptResult.value\n  if (receipt.observations.every(observation => observation.kind !== 'signed')) return false\n  const availability = summarizeEffectReceipt(receipt).contentAvailability\n  return availability === 'available' || availability === 'not-applicable'\n}\n\nfunction failure(\n  code: EffectReceiptJournalIssueCode,\n  message: string,\n  receiptIssues: readonly EffectReceiptIssue[] = [],\n): EffectReceiptJournalAppendFailure {\n  return {\n    issue: {\n      code, message, receiptIssues,\n    },\n    success: false,\n  }\n}\n\nfunction validatedReceipt(\n  value: unknown,\n  code: Extract<EffectReceiptJournalIssueCode, 'effect-journal.corrupt' | 'effect-journal.invalid-receipt'>,\n): EffectReceiptJournalAppendFailure | EffectReceipt {\n  const result = validateEffectReceipt(value)\n  return result.success\n    ? result.value\n    : failure(code, code === 'effect-journal.corrupt'\n        ? 'Persisted effect receipt is corrupt'\n        : 'Effect receipt is invalid', result.issues)\n}\n\nfunction isFailure(value: EffectReceiptJournalAppendFailure | EffectReceipt): value is EffectReceiptJournalAppendFailure {\n  return 'success' in value\n}\n\nfunction journalAppend(\n  persisted: EffectReceipt,\n  expected: EffectReceipt | undefined,\n  next: EffectReceipt,\n): EffectReceiptJournalAppendResult {\n  if (canonicalizeIJson(persisted) === canonicalizeIJson(next)) {\n    return {\n      changed: false, receipt: persisted, success: true,\n    }\n  }\n  if (expected === undefined) {\n    return failure('effect-journal.conflict', 'Effect receipt already exists')\n  }\n  const expectedResult = validatedReceipt(expected, 'effect-journal.invalid-receipt')\n  if (isFailure(expectedResult) || canonicalizeIJson(expectedResult) !== canonicalizeIJson(persisted)) {\n    return failure('effect-journal.conflict', 'Expected effect receipt does not match durable state')\n  }\n  if (next.observations.length !== persisted.observations.length + 1) {\n    return failure(\n      'effect-journal.stage-count-invalid',\n      'Each durable append must add exactly one receipt observation',\n    )\n  }\n  const appendResult = validateEffectReceiptAppend(persisted, next)\n  return appendResult.success\n    ? {\n        changed: true, receipt: appendResult.value, success: true,\n      }\n    : failure('effect-journal.invalid-append', 'Effect receipt append is invalid', appendResult.issues)\n}\n\nexport function validateEffectReceiptJournalAppend(\n  persistedValue: unknown,\n  expectedValue: EffectReceipt | undefined,\n  nextValue: unknown,\n): EffectReceiptJournalAppendResult {\n  const nextResult = validatedReceipt(nextValue, 'effect-journal.invalid-receipt')\n  if (isFailure(nextResult)) return nextResult\n  if (persistedValue === undefined) {\n    if (expectedValue !== undefined) {\n      return failure('effect-journal.conflict', 'Expected receipt is absent from durable state')\n    }\n    return nextResult.observations.length === 1\n      ? {\n          changed: true, receipt: nextResult, success: true,\n        }\n      : failure(\n          'effect-journal.stage-count-invalid',\n          'A new durable receipt must contain only its prepared observation',\n        )\n  }\n  const persistedResult = validatedReceipt(persistedValue, 'effect-journal.corrupt')\n  return isFailure(persistedResult) ? persistedResult : journalAppend(persistedResult, expectedValue, nextResult)\n}\n\nexport function assertEffectReceiptJournalAppend(\n  persistedValue: unknown,\n  expectedValue: EffectReceipt | undefined,\n  nextValue: unknown,\n): EffectReceiptJournalAppendSuccess {\n  const result = validateEffectReceiptJournalAppend(persistedValue, expectedValue, nextValue)\n  if (!result.success) throw new EffectReceiptJournalError(result.issue)\n  return result\n}\n", "import { asSchema } from '@xyo-network/sdk'\nimport { z } from 'zod'\n\nimport { hashDappDocument } from './canonicalDocument.ts'\nimport { EffectReceiptZod } from './effectModel.ts'\nimport {\n  Base64UrlZod,\n  HashZod,\n  IdentifierZod,\n} from './identifier.ts'\nexport const EffectPreparationMaterialSchema = asSchema('network.xyo.dapp.effect.preparation.material', true)\nexport const PreparedEffectRecordSchema = asSchema('network.xyo.dapp.effect.prepared.record', true)\n\nexport const EffectPreparationMaterialInputZod = z.strictObject({\n  schema: z.literal(EffectPreparationMaterialSchema),\n  schemaVersion: z.literal(1),\n  effectId: HashZod,\n  codecId: IdentifierZod,\n  protection: z.enum(['cleartext', 'host-protected']),\n  encoded: Base64UrlZod,\n})\n\nexport type EffectPreparationMaterialInput = z.infer<typeof EffectPreparationMaterialInputZod>\n\nexport function deriveEffectPreparationMaterialHash(value: unknown): string {\n  return hashDappDocument({\n    kind: 'effect-preparation-material',\n    schema: EffectPreparationMaterialInputZod,\n    schemaVersion: 1,\n  }, value).hash\n}\n\nexport const EffectPreparationMaterialZod = EffectPreparationMaterialInputZod.extend({ materialHash: HashZod }).superRefine((material, context) => {\n  const { materialHash, ...input } = material\n  if (deriveEffectPreparationMaterialHash(input) !== materialHash) {\n    context.addIssue({\n      code: 'custom',\n      message: 'materialHash must match the canonical preparation material',\n      path: ['materialHash'],\n    })\n  }\n})\n\nexport type EffectPreparationMaterial = z.infer<typeof EffectPreparationMaterialZod>\n\nexport function createEffectPreparationMaterial(value: unknown): EffectPreparationMaterial {\n  const input = EffectPreparationMaterialInputZod.parse(value)\n  return EffectPreparationMaterialZod.parse({\n    ...input,\n    materialHash: deriveEffectPreparationMaterialHash(input),\n  })\n}\n\nexport const PreparedEffectRecordZod = z.strictObject({\n  schema: z.literal(PreparedEffectRecordSchema),\n  schemaVersion: z.literal(1),\n  receipt: EffectReceiptZod,\n  material: EffectPreparationMaterialZod,\n}).superRefine((record, context) => {\n  if (record.receipt.observations.length !== 1\n    || record.receipt.observations[0]?.kind !== 'prepared') {\n    context.addIssue({\n      code: 'custom',\n      message: 'prepared effect record must contain a prepared-only receipt',\n      path: ['receipt', 'observations'],\n    })\n  }\n  if (record.material.effectId !== record.receipt.effectId) {\n    context.addIssue({\n      code: 'custom',\n      message: 'material effectId must match receipt effectId',\n      path: ['material', 'effectId'],\n    })\n  }\n})\n\nexport type PreparedEffectRecord = z.infer<typeof PreparedEffectRecordZod>\n\nexport function createPreparedEffectRecord(\n  receipt: unknown,\n  material: unknown,\n): PreparedEffectRecord {\n  return PreparedEffectRecordZod.parse({\n    schema: PreparedEffectRecordSchema,\n    schemaVersion: 1,\n    receipt,\n    material,\n  })\n}\n", "import { asSchema } from '@xyo-network/sdk'\nimport { z } from 'zod'\n\nimport { hashDappDocument } from './canonicalDocument.ts'\nimport {\n  Base64UrlZod,\n  DappIdZod,\n  HashZod,\n  IdentifierZod,\n  ProtocolVersionZod,\n  SchemaVersionZod,\n  Xl1ChainIdZod,\n} from './identifier.ts'\nconst UnixMillisecondsZod = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)\nconst Xl1BlockNumberZod = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)\nconst SequenceZod = z.number().int().positive()\n\nexport const EffectIdentityInputSchema = asSchema('network.xyo.dapp.effect.identity', true)\nexport const EffectReceiptSchema = asSchema('network.xyo.dapp.effect.receipt', true)\n\nexport const EffectReceiptExecutionReasonCode = { replacementUnsupported: 'replacement-execution-unsupported' } as const\n\n/** Derived execution admission; it does not change V1 receipt validity or canonical evidence. */\nexport type EffectReceiptExecutionSupport\n  = | { readonly supported: true }\n    | {\n      readonly broadcastTransactionHashes: readonly string[]\n      readonly finalizedTransactionHashes: readonly string[]\n      readonly reasonCode: typeof EffectReceiptExecutionReasonCode.replacementUnsupported\n      readonly signedSequences: readonly number[]\n      readonly supported: false\n    }\n\nexport const EffectIdentityInputZod = z.strictObject({\n  schema: z.literal(EffectIdentityInputSchema),\n  schemaVersion: z.literal(1),\n  chainId: Xl1ChainIdZod,\n  dappId: DappIdZod,\n  protocolVersion: ProtocolVersionZod,\n  callerIdentityId: IdentifierZod,\n  callerCapabilityId: IdentifierZod,\n  commandTypeId: IdentifierZod,\n  commandInstanceKey: IdentifierZod,\n  effectKind: IdentifierZod,\n  intentHash: HashZod,\n})\n\nexport type EffectIdentityInput = z.infer<typeof EffectIdentityInputZod>\n\nexport function deriveEffectId(value: unknown): string {\n  return hashDappDocument({\n    kind: 'effect-id',\n    schema: EffectIdentityInputZod,\n    schemaVersion: 1,\n  }, value).hash\n}\n\nexport const EffectEvidenceStages = [\n  'prepared',\n  'signed',\n  'content-written',\n  'content-verified',\n  'broadcast',\n  'included',\n  'finalized',\n] as const\n\nexport const EffectEvidenceStageZod = z.enum(EffectEvidenceStages)\nexport type EffectEvidenceStage = z.infer<typeof EffectEvidenceStageZod>\n\nexport const EffectStageDeclarationZod = z.strictObject({\n  stage: EffectEvidenceStageZod,\n  applicability: z.enum(['required', 'not-applicable']),\n  rationale: z.string().min(1).max(512),\n})\n\nexport type EffectStageDeclaration = z.infer<typeof EffectStageDeclarationZod>\n\nexport const EffectKindPolicyZod = z.strictObject({\n  effectKind: IdentifierZod,\n  contentPolicy: z.enum(['none', 'required-before-broadcast']),\n  stages: z.array(EffectStageDeclarationZod).length(EffectEvidenceStages.length),\n}).superRefine((policy, context) => {\n  const declarations = new Map(policy.stages.map(declaration => [declaration.stage, declaration]))\n  if (declarations.size !== EffectEvidenceStages.length) {\n    context.addIssue({\n      code: 'custom',\n      message: 'every evidence stage must be declared exactly once',\n      path: ['stages'],\n    })\n    return\n  }\n  for (const stage of ['prepared', 'signed', 'broadcast', 'included', 'finalized'] as const) {\n    if (declarations.get(stage)?.applicability !== 'required') {\n      context.addIssue({\n        code: 'custom',\n        message: `${stage} is required for an XL1 transaction effect`,\n        path: ['stages'],\n      })\n    }\n  }\n  const expectedContentApplicability = policy.contentPolicy === 'none' ? 'not-applicable' : 'required'\n  for (const stage of ['content-written', 'content-verified'] as const) {\n    if (declarations.get(stage)?.applicability !== expectedContentApplicability) {\n      context.addIssue({\n        code: 'custom',\n        message: `${stage} applicability must match content policy`,\n        path: ['stages'],\n      })\n    }\n  }\n})\n\nexport type EffectKindPolicy = z.infer<typeof EffectKindPolicyZod>\n\nfunction addUniqueIssue(values: readonly string[], path: PropertyKey[], context: z.core.$RefinementCtx<unknown>): void {\n  const unique = new Set(values)\n  if (unique.size !== values.length) {\n    context.addIssue({\n      code: 'custom', message: 'values must be unique', path,\n    })\n  }\n}\n\nconst PreparedObservationZod = z.strictObject({\n  sequence: SequenceZod,\n  kind: z.literal('prepared'),\n  observedAt: UnixMillisecondsZod,\n  evidence: z.strictObject({\n    intentHash: HashZod,\n    payloadHashes: z.array(HashZod).min(1),\n    requiredContentHashes: z.array(HashZod),\n    signerRole: IdentifierZod,\n    retryPolicy: z.strictObject({\n      policyId: IdentifierZod,\n      policyVersion: SchemaVersionZod,\n    }),\n  }).superRefine((evidence, context) => {\n    addUniqueIssue(evidence.payloadHashes, ['payloadHashes'], context)\n    addUniqueIssue(evidence.requiredContentHashes, ['requiredContentHashes'], context)\n    const payloadHashes = new Set(evidence.payloadHashes)\n    for (const [index, hash] of evidence.requiredContentHashes.entries()) {\n      if (!payloadHashes.has(hash)) {\n        context.addIssue({\n          code: 'custom',\n          message: 'required content hash must also be a prepared payload hash',\n          path: ['requiredContentHashes', index],\n        })\n      }\n    }\n  }),\n})\n\nconst SignedObservationZod = z.strictObject({\n  sequence: SequenceZod,\n  kind: z.literal('signed'),\n  observedAt: UnixMillisecondsZod,\n  evidence: z.strictObject({\n    transactionHash: HashZod,\n    signedTransaction: Base64UrlZod,\n    nbf: Xl1BlockNumberZod,\n    exp: Xl1BlockNumberZod,\n    signerEvidenceHash: HashZod,\n    replacementPolicy: z.strictObject({\n      policyId: IdentifierZod,\n      policyVersion: SchemaVersionZod,\n    }),\n    replacesSequence: SequenceZod.optional(),\n  }).superRefine((evidence, context) => {\n    if (evidence.exp <= evidence.nbf) {\n      context.addIssue({\n        code: 'custom',\n        message: 'signed transaction exp block must follow its nbf block',\n        path: ['exp'],\n      })\n    }\n  }),\n})\n\nconst ContentWrittenObservationZod = z.strictObject({\n  sequence: SequenceZod,\n  kind: z.literal('content-written'),\n  observedAt: UnixMillisecondsZod,\n  evidence: z.strictObject({\n    contentHash: HashZod,\n    storeId: IdentifierZod,\n    acknowledgementHash: HashZod,\n  }),\n})\n\nconst ContentVerifiedObservationZod = z.strictObject({\n  sequence: SequenceZod,\n  kind: z.literal('content-verified'),\n  observedAt: UnixMillisecondsZod,\n  evidence: z.strictObject({\n    contentHash: HashZod,\n    storeIds: z.array(IdentifierZod).min(1),\n    requiredCopies: z.number().int().positive(),\n  }).superRefine((evidence, context) => {\n    addUniqueIssue(evidence.storeIds, ['storeIds'], context)\n    if (evidence.storeIds.length < evidence.requiredCopies) {\n      context.addIssue({\n        code: 'custom',\n        message: 'verified stores do not satisfy required copies',\n        path: ['storeIds'],\n      })\n    }\n  }),\n})\n\nconst ContentUnavailableObservationZod = z.strictObject({\n  sequence: SequenceZod,\n  kind: z.literal('content-unavailable'),\n  observedAt: UnixMillisecondsZod,\n  evidence: z.strictObject({\n    contentHash: HashZod,\n    availableCopies: z.number().int().nonnegative(),\n    requiredCopies: z.number().int().positive(),\n    reasonCode: IdentifierZod,\n  }).superRefine((evidence, context) => {\n    if (evidence.availableCopies >= evidence.requiredCopies) {\n      context.addIssue({\n        code: 'custom',\n        message: 'unavailable evidence must be below required copies',\n        path: ['availableCopies'],\n      })\n    }\n  }),\n})\n\nconst BroadcastObservationZod = z.strictObject({\n  sequence: SequenceZod,\n  kind: z.literal('broadcast'),\n  observedAt: UnixMillisecondsZod,\n  evidence: z.strictObject({\n    transactionHash: HashZod,\n    submissionId: IdentifierZod,\n  }),\n})\n\nconst IncludedObservationZod = z.strictObject({\n  sequence: SequenceZod,\n  kind: z.literal('included'),\n  observedAt: UnixMillisecondsZod,\n  evidence: z.strictObject({\n    transactionHash: HashZod,\n    blockNumber: z.number().int().nonnegative(),\n    blockHash: HashZod,\n    transactionIndex: z.number().int().nonnegative(),\n  }),\n})\n\nconst InclusionInvalidatedObservationZod = z.strictObject({\n  sequence: SequenceZod,\n  kind: z.literal('inclusion-invalidated'),\n  observedAt: UnixMillisecondsZod,\n  evidence: z.strictObject({\n    inclusionSequence: SequenceZod,\n    reasonCode: IdentifierZod,\n    observedFinalizedBlock: z.number().int().nonnegative(),\n    observedFinalizedBlockHash: HashZod,\n  }),\n})\n\nconst FinalizedObservationZod = z.strictObject({\n  sequence: SequenceZod,\n  kind: z.literal('finalized'),\n  observedAt: UnixMillisecondsZod,\n  evidence: z.strictObject({\n    inclusionSequence: SequenceZod,\n    blockNumber: z.number().int().nonnegative(),\n    blockHash: HashZod,\n    finalityEvidenceHash: HashZod,\n  }),\n})\n\nconst ErrorObservationZod = z.strictObject({\n  sequence: SequenceZod,\n  kind: z.literal('error'),\n  observedAt: UnixMillisecondsZod,\n  evidence: z.strictObject({\n    atStage: EffectEvidenceStageZod,\n    code: IdentifierZod,\n    retriable: z.boolean(),\n    detailsHash: HashZod,\n  }),\n})\n\nconst AbandonedObservationZod = z.strictObject({\n  sequence: SequenceZod,\n  kind: z.literal('abandoned'),\n  observedAt: UnixMillisecondsZod,\n  evidence: z.strictObject({\n    reasonCode: IdentifierZod,\n    decisionEvidenceHash: HashZod,\n  }),\n})\n\nexport const EffectReceiptObservationZod = z.discriminatedUnion('kind', [\n  PreparedObservationZod,\n  SignedObservationZod,\n  ContentWrittenObservationZod,\n  ContentVerifiedObservationZod,\n  ContentUnavailableObservationZod,\n  BroadcastObservationZod,\n  IncludedObservationZod,\n  InclusionInvalidatedObservationZod,\n  FinalizedObservationZod,\n  ErrorObservationZod,\n  AbandonedObservationZod,\n])\n\nexport type EffectReceiptObservation = z.infer<typeof EffectReceiptObservationZod>\n\nexport const EffectReceiptZod = z.strictObject({\n  schema: z.literal(EffectReceiptSchema),\n  schemaVersion: z.literal(1),\n  effectId: HashZod,\n  identity: EffectIdentityInputZod,\n  stagePolicy: EffectKindPolicyZod,\n  observations: z.array(EffectReceiptObservationZod).min(1),\n})\n\nexport type EffectReceipt = z.infer<typeof EffectReceiptZod>\n", "import { z } from 'zod'\n\nimport { canonicalizeIJson } from './canonicalDocument.ts'\nimport type {\n  EffectKindPolicy,\n  EffectReceipt,\n  EffectReceiptExecutionSupport,\n  EffectReceiptObservation,\n} from './effectModel.ts'\nimport {\n  deriveEffectId,\n  EffectEvidenceStages,\n  EffectKindPolicyZod,\n  EffectReceiptExecutionReasonCode,\n  EffectReceiptZod,\n} from './effectModel.ts'\n\ntype PreparedObservation = Extract<EffectReceiptObservation, { kind: 'prepared' }>\ntype SignedObservation = Extract<EffectReceiptObservation, { kind: 'signed' }>\ntype ContentWrittenObservation = Extract<EffectReceiptObservation, { kind: 'content-written' }>\ntype ContentVerifiedObservation = Extract<EffectReceiptObservation, { kind: 'content-verified' }>\ntype BroadcastObservation = Extract<EffectReceiptObservation, { kind: 'broadcast' }>\ntype IncludedObservation = Extract<EffectReceiptObservation, { kind: 'included' }>\ntype InclusionInvalidatedObservation = Extract<EffectReceiptObservation, { kind: 'inclusion-invalidated' }>\ntype FinalizedObservation = Extract<EffectReceiptObservation, { kind: 'finalized' }>\n\nexport const EffectReceiptIssueCodes = [\n  'effect.append-prefix-mismatch',\n  'effect.evidence-mismatch',\n  'effect.first-stage-invalid',\n  'effect.id-mismatch',\n  'effect.inclusion-invalid',\n  'effect.invalid',\n  'effect.policy-invalid',\n  'effect.sequence-invalid',\n  'effect.stage-inapplicable',\n  'effect.stage-order-invalid',\n  'effect.terminal',\n  'effect.timestamp-regression',\n] as const\n\nexport const EffectReceiptIssueCodeZod = z.enum(EffectReceiptIssueCodes)\nexport type EffectReceiptIssueCode = z.infer<typeof EffectReceiptIssueCodeZod>\n\nexport interface EffectReceiptIssue {\n  code: EffectReceiptIssueCode\n  message: string\n  path: (number | string)[]\n}\n\nexport interface EffectReceiptValidationFailure {\n  issues: EffectReceiptIssue[]\n  success: false\n}\n\nexport interface EffectReceiptValidationSuccess {\n  success: true\n  value: EffectReceipt\n}\n\nexport type EffectReceiptValidationResult = EffectReceiptValidationFailure | EffectReceiptValidationSuccess\n\ninterface InclusionState {\n  blockHash: string\n  blockNumber: number\n  finalized: boolean\n  invalidated: boolean\n  transactionHash: string\n}\n\ninterface ReceiptValidationState {\n  broadcastTransactions: Set<string>\n  currentSignedTransaction?: string\n  hasFinalized: boolean\n  inclusions: Map<number, InclusionState>\n  preparedContentHashes: Set<string>\n  signedTransactions: Map<number, string>\n  verifiedContentHashes: Set<string>\n  writtenContentStores: Map<string, Set<string>>\n}\n\nfunction issue(\n  code: EffectReceiptIssueCode,\n  message: string,\n  path: (number | string)[],\n): EffectReceiptIssue {\n  return {\n    code, message, path,\n  }\n}\n\nfunction structuralIssues(issues: z.core.$ZodIssue[]): EffectReceiptIssue[] {\n  return issues.map(value => issue(\n    'effect.invalid',\n    value.message,\n    value.path.map(path => typeof path === 'symbol' ? path.description ?? path.toString() : path),\n  ))\n}\n\nfunction normalizedStagePolicy(policy: EffectKindPolicy): EffectKindPolicy {\n  const order = new Map(EffectEvidenceStages.map((stage, index) => [stage, index]))\n  return EffectKindPolicyZod.parse({\n    ...policy,\n    stages: [...policy.stages].toSorted((left, right) => (order.get(left.stage) ?? 0) - (order.get(right.stage) ?? 0)),\n  })\n}\n\nexport function normalizeEffectReceipt(receipt: EffectReceipt): EffectReceipt {\n  return EffectReceiptZod.parse({\n    ...receipt,\n    stagePolicy: normalizedStagePolicy(receipt.stagePolicy),\n  })\n}\n\nfunction initialValidationState(): ReceiptValidationState {\n  return {\n    broadcastTransactions: new Set(),\n    hasFinalized: false,\n    inclusions: new Map(),\n    preparedContentHashes: new Set(),\n    signedTransactions: new Map(),\n    verifiedContentHashes: new Set(),\n    writtenContentStores: new Map(),\n  }\n}\n\nfunction validatePrepared(\n  receipt: EffectReceipt,\n  observation: PreparedObservation,\n  index: number,\n  state: ReceiptValidationState,\n  issues: EffectReceiptIssue[],\n): void {\n  if (index !== 0) {\n    issues.push(issue('effect.stage-order-invalid', 'prepared evidence may appear only first', ['observations', index]))\n  }\n  if (observation.evidence.intentHash !== receipt.identity.intentHash) {\n    issues.push(issue('effect.evidence-mismatch', 'prepared intent hash does not match effect identity', ['observations', index]))\n  }\n  state.preparedContentHashes = new Set(observation.evidence.requiredContentHashes)\n  const isContentRequired = receipt.stagePolicy.contentPolicy === 'required-before-broadcast'\n  if (isContentRequired !== (state.preparedContentHashes.size > 0)) {\n    issues.push(issue(\n      'effect.policy-invalid',\n      'prepared required content hashes must agree with the effect content policy',\n      ['observations', index, 'evidence', 'requiredContentHashes'],\n    ))\n  }\n}\n\nfunction validateSigned(\n  observation: SignedObservation,\n  index: number,\n  state: ReceiptValidationState,\n  issues: EffectReceiptIssue[],\n): void {\n  const replacesSequence = observation.evidence.replacesSequence\n  if (state.signedTransactions.size === 0 && replacesSequence !== undefined) {\n    issues.push(issue('effect.evidence-mismatch', 'initial signed evidence cannot replace another signature', ['observations', index]))\n  }\n  if (state.signedTransactions.size > 0 && replacesSequence === undefined) {\n    issues.push(issue('effect.evidence-mismatch', 'replacement signed evidence must reference the prior signature', ['observations', index]))\n  }\n  if (replacesSequence !== undefined && !state.signedTransactions.has(replacesSequence)) {\n    issues.push(issue('effect.evidence-mismatch', 'replacement references unknown signed evidence', ['observations', index]))\n  }\n  state.signedTransactions.set(observation.sequence, observation.evidence.transactionHash)\n  state.currentSignedTransaction = observation.evidence.transactionHash\n}\n\nfunction validateContentWritten(\n  observation: ContentWrittenObservation,\n  index: number,\n  state: ReceiptValidationState,\n  issues: EffectReceiptIssue[],\n): void {\n  if (!state.preparedContentHashes.has(observation.evidence.contentHash)) {\n    issues.push(issue('effect.evidence-mismatch', 'written content was not declared by prepared evidence', ['observations', index]))\n  }\n  const stores = state.writtenContentStores.get(observation.evidence.contentHash) ?? new Set<string>()\n  stores.add(observation.evidence.storeId)\n  state.writtenContentStores.set(observation.evidence.contentHash, stores)\n}\n\nfunction validateContentVerified(\n  observation: ContentVerifiedObservation,\n  index: number,\n  state: ReceiptValidationState,\n  issues: EffectReceiptIssue[],\n): void {\n  const writtenStores = state.writtenContentStores.get(observation.evidence.contentHash) ?? new Set<string>()\n  if (observation.evidence.storeIds.some(storeId => !writtenStores.has(storeId))) {\n    issues.push(issue('effect.evidence-mismatch', 'verified content lacks prior write evidence for every store', ['observations', index]))\n  }\n  state.verifiedContentHashes.add(observation.evidence.contentHash)\n}\n\nfunction validateBroadcast(\n  observation: BroadcastObservation,\n  receipt: EffectReceipt,\n  index: number,\n  state: ReceiptValidationState,\n  issues: EffectReceiptIssue[],\n): void {\n  if (state.currentSignedTransaction !== observation.evidence.transactionHash) {\n    issues.push(issue('effect.evidence-mismatch', 'broadcast transaction does not match current signed evidence', ['observations', index]))\n  }\n  if (receipt.stagePolicy.contentPolicy === 'required-before-broadcast'\n    && [...state.preparedContentHashes].some(hash => !state.verifiedContentHashes.has(hash))) {\n    issues.push(issue('effect.stage-order-invalid', 'required content must be verified before broadcast', ['observations', index]))\n  }\n  state.broadcastTransactions.add(observation.evidence.transactionHash)\n}\n\nfunction validateIncluded(\n  observation: IncludedObservation,\n  index: number,\n  state: ReceiptValidationState,\n  issues: EffectReceiptIssue[],\n): void {\n  if (!state.broadcastTransactions.has(observation.evidence.transactionHash)) {\n    issues.push(issue('effect.stage-order-invalid', 'included transaction lacks prior broadcast evidence', ['observations', index]))\n  }\n  state.inclusions.set(observation.sequence, {\n    blockHash: observation.evidence.blockHash,\n    blockNumber: observation.evidence.blockNumber,\n    finalized: false,\n    invalidated: false,\n    transactionHash: observation.evidence.transactionHash,\n  })\n}\n\nfunction validateInclusionInvalidated(\n  observation: InclusionInvalidatedObservation,\n  index: number,\n  state: ReceiptValidationState,\n  issues: EffectReceiptIssue[],\n): void {\n  const inclusion = state.inclusions.get(observation.evidence.inclusionSequence)\n  if (inclusion === undefined || inclusion.invalidated || inclusion.finalized) {\n    issues.push(issue('effect.inclusion-invalid', 'invalidation must reference a live unfinalized inclusion', ['observations', index]))\n    return\n  }\n  inclusion.invalidated = true\n}\n\nfunction validateFinalized(\n  observation: FinalizedObservation,\n  index: number,\n  state: ReceiptValidationState,\n  issues: EffectReceiptIssue[],\n): void {\n  const inclusion = state.inclusions.get(observation.evidence.inclusionSequence)\n  if (inclusion === undefined || inclusion.invalidated || inclusion.finalized\n    || inclusion.blockNumber !== observation.evidence.blockNumber\n    || inclusion.blockHash !== observation.evidence.blockHash) {\n    issues.push(issue('effect.inclusion-invalid', 'finality must match a live unfinalized inclusion', ['observations', index]))\n    return\n  }\n  if (state.hasFinalized) {\n    issues.push(issue('effect.terminal', 'receipt already has finalized transaction evidence', ['observations', index]))\n    return\n  }\n  inclusion.finalized = true\n  state.hasFinalized = true\n}\n\nfunction validateObservationPrerequisites(\n  receipt: EffectReceipt,\n  observation: EffectReceiptObservation,\n  index: number,\n  state: ReceiptValidationState,\n  issues: EffectReceiptIssue[],\n): void {\n  const isChainObservationAfterFinality = observation.kind === 'signed'\n    || observation.kind === 'broadcast'\n    || observation.kind === 'included'\n    || observation.kind === 'inclusion-invalidated'\n  if (state.hasFinalized && isChainObservationAfterFinality) {\n    issues.push(issue('effect.terminal', 'chain evidence cannot advance after finality', ['observations', index]))\n  }\n  const isContentObservation = observation.kind === 'content-written'\n    || observation.kind === 'content-verified'\n    || observation.kind === 'content-unavailable'\n  if (isContentObservation && receipt.stagePolicy.contentPolicy === 'none') {\n    issues.push(issue('effect.stage-inapplicable', 'content evidence is inapplicable to this effect', ['observations', index]))\n  }\n  const requiresPriorSignature = observation.kind !== 'prepared'\n    && observation.kind !== 'signed'\n    && observation.kind !== 'error'\n    && observation.kind !== 'abandoned'\n  if (requiresPriorSignature && state.signedTransactions.size === 0) {\n    issues.push(issue('effect.stage-order-invalid', 'effect evidence requires prior signed evidence', ['observations', index]))\n  }\n  if (observation.kind === 'content-unavailable'\n    && !state.preparedContentHashes.has(observation.evidence.contentHash)) {\n    issues.push(issue('effect.evidence-mismatch', 'unavailable content was not declared by prepared evidence', ['observations', index]))\n  }\n}\n\nfunction validateObservationStage(\n  receipt: EffectReceipt,\n  observation: EffectReceiptObservation,\n  index: number,\n  state: ReceiptValidationState,\n  issues: EffectReceiptIssue[],\n): void {\n  if (observation.kind === 'prepared') validatePrepared(receipt, observation, index, state, issues)\n  if (observation.kind === 'signed') validateSigned(observation, index, state, issues)\n  if (observation.kind === 'content-written') validateContentWritten(observation, index, state, issues)\n  if (observation.kind === 'content-verified') validateContentVerified(observation, index, state, issues)\n  if (observation.kind === 'broadcast') validateBroadcast(observation, receipt, index, state, issues)\n  if (observation.kind === 'included') validateIncluded(observation, index, state, issues)\n  if (observation.kind === 'inclusion-invalidated') validateInclusionInvalidated(observation, index, state, issues)\n  if (observation.kind === 'finalized') validateFinalized(observation, index, state, issues)\n}\n\nfunction validateObservation(\n  receipt: EffectReceipt,\n  observation: EffectReceiptObservation,\n  index: number,\n  state: ReceiptValidationState,\n  issues: EffectReceiptIssue[],\n): void {\n  validateObservationPrerequisites(receipt, observation, index, state, issues)\n  validateObservationStage(receipt, observation, index, state, issues)\n}\n\nexport function validateEffectReceipt(value: unknown): EffectReceiptValidationResult {\n  const result = EffectReceiptZod.safeParse(value)\n  if (!result.success) return { issues: structuralIssues(result.error.issues), success: false }\n\n  const receipt = result.data\n  const issues: EffectReceiptIssue[] = []\n  if (receipt.effectId !== deriveEffectId(receipt.identity)) {\n    issues.push(issue('effect.id-mismatch', 'effect ID does not match its canonical identity input', ['effectId']))\n  }\n  if (receipt.stagePolicy.effectKind !== receipt.identity.effectKind) {\n    issues.push(issue('effect.policy-invalid', 'stage policy effect kind does not match effect identity', ['stagePolicy', 'effectKind']))\n  }\n  if (receipt.observations[0]?.kind !== 'prepared') {\n    issues.push(issue('effect.first-stage-invalid', 'the first receipt observation must be prepared', ['observations', 0]))\n  }\n\n  const state = initialValidationState()\n  let priorTimestamp = -1\n  for (const [index, observation] of receipt.observations.entries()) {\n    if (observation.sequence !== index + 1) {\n      issues.push(issue('effect.sequence-invalid', 'observation sequences must be contiguous from one', ['observations', index, 'sequence']))\n    }\n    if (observation.observedAt < priorTimestamp) {\n      issues.push(issue('effect.timestamp-regression', 'observation time cannot move backwards', ['observations', index, 'observedAt']))\n    }\n    if (observation.kind === 'abandoned' && index !== receipt.observations.length - 1) {\n      issues.push(issue('effect.terminal', 'abandoned must be the final receipt observation', ['observations', index]))\n    }\n    priorTimestamp = observation.observedAt\n    validateObservation(receipt, observation, index, state, issues)\n  }\n\n  return issues.length > 0\n    ? { issues, success: false }\n    : { success: true, value: normalizeEffectReceipt(receipt) }\n}\n\nexport function validateEffectReceiptAppend(previousValue: unknown, currentValue: unknown): EffectReceiptValidationResult {\n  const previousResult = validateEffectReceipt(previousValue)\n  if (!previousResult.success) return previousResult\n  const currentResult = validateEffectReceipt(currentValue)\n  if (!currentResult.success) return currentResult\n\n  const previous = previousResult.value\n  const current = currentResult.value\n  const previousIdentity = canonicalizeIJson({ ...previous, observations: [] })\n  const currentIdentity = canonicalizeIJson({ ...current, observations: [] })\n  const hasPrefix = current.observations.length >= previous.observations.length\n    && previous.observations.every((observation, index) => canonicalizeIJson(observation) === canonicalizeIJson(current.observations[index]))\n  if (previousIdentity !== currentIdentity || !hasPrefix) {\n    return {\n      issues: [issue(\n        'effect.append-prefix-mismatch',\n        'new receipt must preserve immutable fields and every prior observation byte-for-byte',\n        [],\n      )],\n      success: false,\n    }\n  }\n  return currentResult\n}\n\nexport interface EffectReceiptSummary {\n  abandoned: boolean\n  complete: boolean\n  contentAvailability: 'available' | 'not-applicable' | 'unavailable' | 'unknown'\n  finalized: boolean\n}\n\n/** V1 has no qualified replacement-eligibility proof. Preserve its history and gate execution separately. */\nexport function assessEffectReceiptExecutionSupport(receipt: EffectReceipt): EffectReceiptExecutionSupport {\n  const signed = receipt.observations.filter(observation => observation.kind === 'signed')\n  if (receipt.identity.effectKind !== 'xl1-transaction'\n    || (signed.length <= 1 && signed.every(observation => observation.evidence.replacesSequence === undefined))) {\n    return { supported: true }\n  }\n  const inclusions = new Map(receipt.observations\n    .filter(observation => observation.kind === 'included')\n    .map(observation => [observation.sequence, observation.evidence.transactionHash]))\n  return {\n    broadcastTransactionHashes: receipt.observations\n      .filter(observation => observation.kind === 'broadcast')\n      .map(observation => observation.evidence.transactionHash),\n    finalizedTransactionHashes: receipt.observations\n      .filter(observation => observation.kind === 'finalized')\n      .flatMap((observation) => {\n        const hash = inclusions.get(observation.evidence.inclusionSequence)\n        return hash ?? []\n      }),\n    reasonCode: EffectReceiptExecutionReasonCode.replacementUnsupported,\n    signedSequences: signed.map(observation => observation.sequence),\n    supported: false,\n  }\n}\n\nexport function summarizeEffectReceipt(receipt: EffectReceipt): EffectReceiptSummary {\n  const prepared = receipt.observations.find(observation => observation.kind === 'prepared')\n  const requiredContentHashes = prepared?.kind === 'prepared'\n    ? new Set(prepared.evidence.requiredContentHashes)\n    : new Set<string>()\n  const contentAvailability = new Map<string, 'available' | 'unavailable'>()\n  let abandoned = false\n  let finalized = false\n  for (const observation of receipt.observations) {\n    if (observation.kind === 'content-verified') contentAvailability.set(observation.evidence.contentHash, 'available')\n    if (observation.kind === 'content-unavailable') contentAvailability.set(observation.evidence.contentHash, 'unavailable')\n    if (observation.kind === 'finalized') finalized = true\n    if (observation.kind === 'abandoned') abandoned = true\n  }\n  const availability = receipt.stagePolicy.contentPolicy === 'none'\n    ? 'not-applicable'\n    : [...requiredContentHashes].some(hash => contentAvailability.get(hash) === 'unavailable')\n        ? 'unavailable'\n        : [...requiredContentHashes].every(hash => contentAvailability.get(hash) === 'available')\n            ? 'available'\n            : 'unknown'\n  return {\n    abandoned,\n    complete: finalized && (availability === 'available' || availability === 'not-applicable'),\n    contentAvailability: availability,\n    finalized,\n  }\n}\n", "import { z } from 'zod'\n\nimport type {\n  EffectExecutionOutcome,\n  EffectReconciler,\n} from './effectExecution.ts'\nimport { executeEffect } from './effectExecution.ts'\nimport type { EffectReceiptJournal } from './effectJournal.ts'\nimport { EffectReceiptJournalError } from './effectJournal.ts'\nimport type { EffectReceipt } from './effectModel.ts'\nimport { EffectReceiptZod } from './effectModel.ts'\nimport {\n  assessEffectReceiptExecutionSupport, summarizeEffectReceipt, validateEffectReceipt,\n} from './effectValidation.ts'\n\nexport const EffectJournalRecoveryMaxEffectsZod = z.number().int().positive().max(100_000)\n\nexport const EffectJournalRecoveryStates = [\n  'cancelled',\n  'complete',\n  'effect-limit',\n  'pending',\n] as const\n\nexport const EffectJournalRecoveryStateZod = z.enum(EffectJournalRecoveryStates)\nexport type EffectJournalRecoveryState = z.infer<typeof EffectJournalRecoveryStateZod>\n\nexport interface EffectJournalRecoveryOptions {\n  readonly createReconciler: (receipt: EffectReceipt) => Promise<EffectReconciler>\n  readonly isCancellationRequested?: () => boolean\n  readonly journal: EffectReceiptJournal\n  readonly maxAdvancesPerEffect: number\n  readonly maxEffects: number\n}\n\nexport interface EffectJournalRecoveryResult {\n  readonly incompleteCount: number\n  readonly outcomes: readonly EffectExecutionOutcome[]\n  readonly processedCount: number\n  readonly state: EffectJournalRecoveryState\n}\n\nfunction preparedPrefix(receipt: EffectReceipt): EffectReceipt {\n  return EffectReceiptZod.parse({\n    ...receipt,\n    observations: receipt.observations.slice(0, 1),\n  })\n}\n\nfunction incompleteReceipts(receipts: readonly EffectReceipt[]): EffectReceipt[] {\n  return receipts\n    .map((receipt) => {\n      const validation = validateEffectReceipt(receipt)\n      if (!validation.success) {\n        throw new EffectReceiptJournalError({\n          code: 'effect-journal.invalid-receipt',\n          message: 'Durable recovery receipt is invalid',\n          receiptIssues: validation.issues,\n        })\n      }\n      return validation.value\n    })\n    .filter((receipt) => {\n      const summary = summarizeEffectReceipt(receipt)\n      return !summary.abandoned && (!summary.complete || !assessEffectReceiptExecutionSupport(receipt).supported)\n    })\n    .toSorted((left, right) => left.effectId.localeCompare(right.effectId))\n}\n\n/** Runs one finite recovery pass over the durable effects present at pass start. */\nexport async function recoverEffectJournal(\n  options: EffectJournalRecoveryOptions,\n): Promise<EffectJournalRecoveryResult> {\n  const maxEffects = EffectJournalRecoveryMaxEffectsZod.parse(options.maxEffects)\n  const incomplete = incompleteReceipts(await options.journal.list())\n  const selected = incomplete.slice(0, maxEffects)\n  const outcomes: EffectExecutionOutcome[] = []\n\n  for (const receipt of selected) {\n    if (options.isCancellationRequested?.() === true) {\n      return {\n        incompleteCount: incomplete.length,\n        outcomes: Object.freeze(outcomes),\n        processedCount: outcomes.length,\n        state: 'cancelled',\n      }\n    }\n    const support = assessEffectReceiptExecutionSupport(receipt)\n    if (!support.supported) {\n      outcomes.push({\n        advances: 0, reasonCode: support.reasonCode, receipt, state: 'pending',\n      })\n      continue\n    }\n    const reconciler = await options.createReconciler(receipt)\n    const outcome = await executeEffect(preparedPrefix(receipt), {\n      isCancellationRequested: options.isCancellationRequested,\n      journal: options.journal,\n      maxAdvances: options.maxAdvancesPerEffect,\n      reconciler,\n    })\n    outcomes.push(outcome)\n    if (outcome.state === 'cancelled') {\n      return {\n        incompleteCount: incomplete.length,\n        outcomes: Object.freeze(outcomes),\n        processedCount: outcomes.length,\n        state: 'cancelled',\n      }\n    }\n  }\n\n  const state: EffectJournalRecoveryState = incomplete.length > selected.length\n    ? 'effect-limit'\n    : outcomes.some(outcome => outcome.state !== 'complete' && outcome.state !== 'abandoned')\n      ? 'pending'\n      : 'complete'\n  return {\n    incompleteCount: incomplete.length,\n    outcomes: Object.freeze(outcomes),\n    processedCount: outcomes.length,\n    state,\n  }\n}\n", "import { z } from 'zod'\n\nimport type {\n  DappEventRecord,\n  DappEventStreamReadPort,\n} from './eventStream.ts'\nimport {\n  DappEventSequenceZod,\n  verifyDappEventRecord,\n} from './eventStream.ts'\nimport type {\n  DappEventConsumerOutcome,\n  DappEventSubscriptionRunningState,\n  DappEventSubscriptionState,\n} from './eventSubscription.ts'\nimport {\n  advanceDappEventSubscription,\n  DappEventConsumerOutcomeZod,\n  DappEventLeaseDurationZod,\n  DappEventLeaseTimeZod,\n  DappEventSubscriptionBlockedStateZod,\n  DappEventSubscriptionRunningStateZod,\n  DappEventSubscriptionScheduledStateZod,\n  DappEventSubscriptionStateZod,\n  failDappEventSubscription,\n  releaseDappEventSubscription,\n} from './eventSubscription.ts'\nimport { IdentifierZod } from './identifier.ts'\n\nexport const DappEventPumpItemBudgetZod = z.number().int().positive().max(10_000)\nexport const DappEventPumpTimeBudgetZod = z.number().int().positive().max(Number.MAX_SAFE_INTEGER)\n\nexport interface DappEventSubscriptionRunnerPort {\n  /** Atomically claim scheduled work under a fresh fence. */\n  claim(input: {\n    readonly leaseDuration: number\n    readonly now: number\n    readonly subscriptionId: string\n  }): Promise<unknown>\n  /**\n   * Atomically recheck the linked stream tail and release `expected` to the\n   * corresponding idle/scheduled state. The returned tail/state pair is the\n   * durable comparison the adapter committed, not merely the caller's earlier\n   * tail observation.\n   */\n  release(input: {\n    readonly expected: DappEventSubscriptionRunningState\n    readonly observedTail: number\n  }): Promise<unknown>\n  /** Atomically compare `expected` and replace it with `next`. */\n  transition(input: {\n    readonly expected: DappEventSubscriptionState\n    readonly next: DappEventSubscriptionState\n  }): Promise<unknown>\n}\n\nexport type DappEventConsumerCommitResult\n  = | {\n    readonly outcome: DappEventConsumerOutcome\n    readonly status: 'committed'\n  }\n  | {\n    readonly reasonCode: string\n    readonly status: 'retry'\n  }\n\nexport interface DappEventConsumerPort {\n  /** Return `committed` only after the outcome is durable and exactly replayable. */\n  commit(\n    record: DappEventRecord,\n    context: {\n      readonly signal?: AbortSignal\n      readonly subscription: DappEventSubscriptionRunningState\n    },\n  ): Promise<DappEventConsumerCommitResult>\n}\n\nexport const DappEventPumpStatuses = [\n  'blocked',\n  'cancelled',\n  'drained',\n  'item-budget',\n  'not-claimed',\n  'rescheduled',\n  'retry-scheduled',\n  'time-budget',\n] as const\n\nexport const DappEventPumpStatusZod = z.enum(DappEventPumpStatuses)\nexport type DappEventPumpStatus = z.infer<typeof DappEventPumpStatusZod>\n\nexport interface DappEventPumpResult {\n  readonly cursor?: number\n  readonly processed: number\n  readonly state?: DappEventSubscriptionState\n  readonly status: DappEventPumpStatus\n}\n\nexport interface PumpDappEventSubscriptionOptions {\n  readonly consumer: DappEventConsumerPort\n  readonly leaseDuration: number\n  readonly maxDuration: number\n  readonly maxItems: number\n  readonly now: () => number\n  readonly signal?: AbortSignal\n  readonly stream: DappEventStreamReadPort\n  readonly subscription: DappEventSubscriptionRunnerPort\n  readonly subscriptionId: string\n}\n\nconst DappEventSubscriptionReleaseResultZod = z.strictObject({\n  state: DappEventSubscriptionStateZod,\n  tail: DappEventSequenceZod,\n})\n\nfunction sameState(left: DappEventSubscriptionState, right: DappEventSubscriptionState): boolean {\n  return JSON.stringify(left) === JSON.stringify(right)\n}\n\nasync function persistTransition(\n  port: DappEventSubscriptionRunnerPort,\n  expected: DappEventSubscriptionState,\n  next: DappEventSubscriptionState,\n): Promise<DappEventSubscriptionState> {\n  const persisted = DappEventSubscriptionStateZod.parse(await port.transition({ expected, next }))\n  if (!sameState(persisted, next)) {\n    throw new TypeError('subscription transition port returned state other than the requested atomic transition')\n  }\n  return persisted\n}\n\nfunction verifyPumpedRecord(\n  state: DappEventSubscriptionRunningState,\n  value: unknown,\n): DappEventRecord {\n  const record = verifyDappEventRecord(value)\n  if (record.event.streamId !== state.streamId || record.event.partitionId !== state.partitionId) {\n    throw new TypeError('event stream returned a record from a different partition')\n  }\n  if (record.sequence !== state.cursor) {\n    throw new TypeError('event stream returned a non-contiguous record')\n  }\n  return record\n}\n\nfunction currentTime(now: () => number): number {\n  return DappEventLeaseTimeZod.parse(now())\n}\n\nfunction result(\n  status: DappEventPumpStatus,\n  processed: number,\n  state?: DappEventSubscriptionState,\n): DappEventPumpResult {\n  return {\n    ...(state === undefined ? {} : { cursor: state.cursor, state }),\n    processed,\n    status,\n  }\n}\n\nasync function recordFailure(\n  options: PumpDappEventSubscriptionOptions,\n  state: DappEventSubscriptionRunningState,\n  record: DappEventRecord,\n  reasonCodeValue: unknown,\n  processed: number,\n): Promise<DappEventPumpResult> {\n  const next = failDappEventSubscription({\n    state,\n    fenceEpoch: state.fenceEpoch,\n    now: currentTime(options.now),\n    record,\n    reasonCode: IdentifierZod.parse(reasonCodeValue),\n  })\n  const persisted = await persistTransition(options.subscription, state, next)\n  return persisted.status === 'blocked'\n    ? result('blocked', processed, DappEventSubscriptionBlockedStateZod.parse(persisted))\n    : result('retry-scheduled', processed, DappEventSubscriptionScheduledStateZod.parse(persisted))\n}\n\ntype DappEventPumpStop = 'cancelled' | 'item-budget' | 'time-budget'\n\ninterface DappEventPumpSettings {\n  readonly deadline: number\n  readonly leaseDuration: number\n  readonly maxItems: number\n  readonly startedAt: number\n  readonly subscriptionId: string\n}\n\ntype DappEventRecordConsumption\n  = | { readonly kind: 'advanced'; readonly state: DappEventSubscriptionRunningState }\n    | { readonly kind: 'terminal'; readonly result: DappEventPumpResult }\n\nfunction pumpSettings(options: PumpDappEventSubscriptionOptions): DappEventPumpSettings {\n  const subscriptionId = IdentifierZod.parse(options.subscriptionId)\n  const maxItems = DappEventPumpItemBudgetZod.parse(options.maxItems)\n  const maxDuration = DappEventPumpTimeBudgetZod.parse(options.maxDuration)\n  const leaseDuration = DappEventLeaseDurationZod.parse(options.leaseDuration)\n  if (leaseDuration <= maxDuration) {\n    throw new TypeError('subscription lease duration must exceed the pump time budget')\n  }\n  const startedAt = currentTime(options.now)\n  const deadline = startedAt > Number.MAX_SAFE_INTEGER - maxDuration\n    ? Number.MAX_SAFE_INTEGER\n    : startedAt + maxDuration\n  return {\n    deadline, leaseDuration, maxItems, startedAt, subscriptionId,\n  }\n}\n\nasync function claimSubscription(\n  options: PumpDappEventSubscriptionOptions,\n  settings: DappEventPumpSettings,\n): Promise<DappEventSubscriptionRunningState | undefined> {\n  const claimedValue = await options.subscription.claim({\n    subscriptionId: settings.subscriptionId,\n    now: settings.startedAt,\n    leaseDuration: settings.leaseDuration,\n  })\n  if (claimedValue === undefined) return undefined\n  const state = DappEventSubscriptionRunningStateZod.parse(claimedValue)\n  if (state.subscriptionId !== settings.subscriptionId || state.leaseExpiresAt <= settings.startedAt) {\n    throw new TypeError('subscription claim returned the wrong subscription or an expired lease')\n  }\n  return state\n}\n\nfunction requestedStop(\n  options: PumpDappEventSubscriptionOptions,\n  settings: DappEventPumpSettings,\n  processed: number,\n): DappEventPumpStop | undefined {\n  if (options.signal?.aborted === true) return 'cancelled'\n  if (currentTime(options.now) >= settings.deadline) return 'time-budget'\n  if (processed >= settings.maxItems) return 'item-budget'\n}\n\nasync function consumeRecord(\n  options: PumpDappEventSubscriptionOptions,\n  state: DappEventSubscriptionRunningState,\n  value: unknown,\n  processed: number,\n): Promise<DappEventRecordConsumption> {\n  const record = verifyPumpedRecord(state, value)\n  let commit: DappEventConsumerCommitResult\n  try {\n    commit = await options.consumer.commit(record, {\n      subscription: state,\n      ...(options.signal === undefined ? {} : { signal: options.signal }),\n    })\n  } catch {\n    return {\n      kind: 'terminal',\n      result: await recordFailure(options, state, record, 'consumer.unhandled-error', processed),\n    }\n  }\n  if (commit.status === 'retry') {\n    return {\n      kind: 'terminal',\n      result: await recordFailure(options, state, record, commit.reasonCode, processed),\n    }\n  }\n  const next = advanceDappEventSubscription({\n    state,\n    fenceEpoch: state.fenceEpoch,\n    now: currentTime(options.now),\n    record,\n    outcome: DappEventConsumerOutcomeZod.parse(commit.outcome),\n  })\n  return {\n    kind: 'advanced',\n    state: DappEventSubscriptionRunningStateZod.parse(\n      await persistTransition(options.subscription, state, next),\n    ),\n  }\n}\n\nasync function finishPump(\n  options: PumpDappEventSubscriptionOptions,\n  state: DappEventSubscriptionRunningState,\n  processed: number,\n  stop: DappEventPumpStop | undefined,\n): Promise<DappEventPumpResult> {\n  const observedTail = DappEventSequenceZod.parse(await options.stream.tail({\n    streamId: state.streamId,\n    partitionId: state.partitionId,\n  }))\n  const releaseResult = DappEventSubscriptionReleaseResultZod.parse(\n    await options.subscription.release({ expected: state, observedTail }),\n  )\n  if (releaseResult.tail < observedTail) {\n    throw new TypeError('subscription release returned a tail older than the pump observation')\n  }\n  const expectedRelease = releaseDappEventSubscription({\n    state,\n    fenceEpoch: state.fenceEpoch,\n    tail: releaseResult.tail,\n  })\n  if (!sameState(releaseResult.state, expectedRelease)) {\n    throw new TypeError('subscription release did not atomically select state from its returned tail')\n  }\n  const persisted = releaseResult.state\n  if (stop === 'cancelled') return result('cancelled', processed, persisted)\n  if (stop === 'time-budget') return result('time-budget', processed, persisted)\n  if (persisted.status === 'scheduled') {\n    return result(stop === 'item-budget' ? 'item-budget' : 'rescheduled', processed, persisted)\n  }\n  return result('drained', processed, persisted)\n}\n\n/**\n * Drain one subscription sequentially under explicit item/time budgets.\n *\n * The consumer's durable commit is awaited before the compare-and-set cursor\n * transition. The final tail recheck selects idle versus scheduled, closing\n * the append-while-sleeping race without treating a wake delivery as progress.\n */\nexport async function pumpDappEventSubscription(\n  options: PumpDappEventSubscriptionOptions,\n): Promise<DappEventPumpResult> {\n  const settings = pumpSettings(options)\n  let state = await claimSubscription(options, settings)\n  if (state === undefined) return result('not-claimed', 0)\n  let processed = 0\n  let stop: DappEventPumpStop | undefined\n  const readInput = {\n    streamId: state.streamId,\n    partitionId: state.partitionId,\n    cursor: state.cursor,\n    limit: settings.maxItems,\n    ...(options.signal === undefined ? {} : { signal: options.signal }),\n  }\n\n  for await (const value of options.stream.read(readInput)) {\n    stop = requestedStop(options, settings, processed)\n    if (stop !== undefined) break\n    const consumption = await consumeRecord(options, state, value, processed)\n    if (consumption.kind === 'terminal') return consumption.result\n    state = consumption.state\n    processed += 1\n  }\n  stop ??= requestedStop(options, settings, processed)\n  return await finishPump(options, state, processed, stop)\n}\n", "import { asSchema } from '@xyo-network/sdk'\nimport { z } from 'zod'\n\nimport {\n  DappDocumentHashAlgorithm,\n  hashDappDocument,\n} from './canonicalDocument.ts'\nimport {\n  HashZod,\n  IdentifierZod,\n  SchemaVersionZod,\n  XyoSchemaZod,\n} from './identifier.ts'\nimport { JsonValueZod } from './jsonValue.ts'\nexport const DappEventSchema = asSchema('network.xyo.dapp.event', true)\nexport const DappEventIdSchema = asSchema('network.xyo.dapp.event.id', true)\nexport const DappEventRecordSchema = asSchema('network.xyo.dapp.event.record', true)\n\nexport const DappEventSequenceZod = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)\nexport const DappEventStreamReadLimitZod = z.number().int().positive().max(10_000)\n\nexport const DappEventStreamPartitionZod = z.strictObject({\n  streamId: IdentifierZod,\n  partitionId: IdentifierZod,\n})\n\nexport const DappEventStreamReadInputZod = DappEventStreamPartitionZod.safeExtend({\n  cursor: DappEventSequenceZod,\n  limit: DappEventStreamReadLimitZod,\n})\n\nexport type DappEventStreamPartition = z.infer<typeof DappEventStreamPartitionZod>\nexport type DappEventStreamReadInput = z.infer<typeof DappEventStreamReadInputZod>\n\nexport const DappEventSourceZod = z.strictObject({\n  kind: IdentifierZod,\n  sourceId: IdentifierZod,\n})\n\nexport type DappEventSource = z.infer<typeof DappEventSourceZod>\n\nexport const DappEventContentZod = z.discriminatedUnion('kind', [\n  z.strictObject({\n    kind: z.literal('inline-json'),\n    contentHash: HashZod,\n    body: JsonValueZod,\n  }),\n  z.strictObject({\n    kind: z.literal('content-addressed'),\n    contentHash: HashZod,\n  }),\n])\n\nexport type DappEventContent = z.infer<typeof DappEventContentZod>\n\nexport const DappEventTransformationZod = z.strictObject({\n  id: IdentifierZod,\n  schemaVersion: SchemaVersionZod,\n})\n\nexport type DappEventTransformation = z.infer<typeof DappEventTransformationZod>\n\nexport const DappEventDraftInputZod = z.strictObject({\n  schema: z.literal(DappEventSchema),\n  schemaVersion: z.literal(1),\n  streamId: IdentifierZod,\n  partitionId: IdentifierZod,\n  eventType: XyoSchemaZod,\n  source: DappEventSourceZod,\n  content: DappEventContentZod,\n  provenanceHash: HashZod,\n  transformation: DappEventTransformationZod,\n})\n\nexport type DappEventDraftInput = z.infer<typeof DappEventDraftInputZod>\n\nexport const DappEventIdPreimageZod = z.strictObject({\n  schema: z.literal(DappEventIdSchema),\n  schemaVersion: z.literal(1),\n  hashAlgorithm: z.literal(DappDocumentHashAlgorithm),\n  streamId: IdentifierZod,\n  partitionId: IdentifierZod,\n  eventType: XyoSchemaZod,\n  source: DappEventSourceZod,\n  contentHash: HashZod,\n})\n\nexport type DappEventIdPreimage = z.infer<typeof DappEventIdPreimageZod>\n\nexport const DappEventDraftPreimageZod = DappEventDraftInputZod.safeExtend({\n  hashAlgorithm: z.literal(DappDocumentHashAlgorithm),\n  eventId: HashZod,\n})\n\nexport type DappEventDraftPreimage = z.infer<typeof DappEventDraftPreimageZod>\n\nexport const DappEventDraftZod = DappEventDraftPreimageZod.safeExtend({ fingerprint: HashZod })\n\nexport type DappEventDraft = z.infer<typeof DappEventDraftZod>\n\nexport const DappEventStreamAppendInputZod = z.strictObject({ draft: DappEventDraftZod })\nexport type DappEventStreamAppendInput = z.infer<typeof DappEventStreamAppendInputZod>\n\nexport const DappEventRecordZod = z.strictObject({\n  schema: z.literal(DappEventRecordSchema),\n  schemaVersion: z.literal(1),\n  sequence: DappEventSequenceZod,\n  event: DappEventDraftZod,\n})\n\nexport type DappEventRecord = z.infer<typeof DappEventRecordZod>\n\nexport const DappEventAppendDecisionZod = z.discriminatedUnion('kind', [\n  z.strictObject({\n    kind: z.literal('appended'),\n    nextTail: DappEventSequenceZod,\n    record: DappEventRecordZod,\n  }),\n  z.strictObject({\n    kind: z.literal('duplicate'),\n    nextTail: DappEventSequenceZod,\n    record: DappEventRecordZod,\n  }),\n  z.strictObject({\n    eventId: HashZod,\n    existingFingerprint: HashZod,\n    incomingFingerprint: HashZod,\n    kind: z.literal('collision'),\n    nextTail: DappEventSequenceZod,\n  }),\n])\n\nexport type DappEventAppendDecision = z.infer<typeof DappEventAppendDecisionZod>\n\n/**\n * Atomically allocate one partition sequence or return the existing allocation.\n * The event-ID index, record, and next tail are one durability boundary.\n */\nexport interface DappEventStreamAppendPort {\n  append(input: DappEventStreamAppendInput): Promise<unknown>\n}\n\n/** Read a finite contiguous partition snapshot without waiting for later appends. */\nexport interface DappEventStreamReadPort {\n  read(input: DappEventStreamReadInput & { readonly signal?: AbortSignal }): AsyncIterable<unknown>\n  /** Return the partition's next unallocated sequence. */\n  tail(input: DappEventStreamPartition): Promise<unknown>\n}\n\nexport interface DappEventStreamPort extends DappEventStreamAppendPort, DappEventStreamReadPort {}\n\nfunction eventIdPreimage(input: DappEventDraftInput): DappEventIdPreimage {\n  return {\n    schema: DappEventIdSchema,\n    schemaVersion: 1,\n    hashAlgorithm: DappDocumentHashAlgorithm,\n    streamId: input.streamId,\n    partitionId: input.partitionId,\n    eventType: input.eventType,\n    source: input.source,\n    contentHash: input.content.contentHash,\n  }\n}\n\nexport function hashDappEventId(value: unknown): string {\n  return hashDappDocument({\n    kind: 'event-id',\n    schema: DappEventIdPreimageZod,\n    schemaVersion: 1,\n  }, value).hash\n}\n\nexport function hashDappEventFingerprint(value: unknown): string {\n  return hashDappDocument({\n    kind: 'event-fingerprint',\n    schema: DappEventDraftPreimageZod,\n    schemaVersion: 1,\n  }, value).hash\n}\n\nexport function createDappEventDraft(value: unknown): DappEventDraft {\n  const input = DappEventDraftInputZod.parse(value)\n  const preimage = DappEventDraftPreimageZod.parse({\n    ...input,\n    hashAlgorithm: DappDocumentHashAlgorithm,\n    eventId: hashDappEventId(eventIdPreimage(input)),\n  })\n  return DappEventDraftZod.parse({\n    ...preimage,\n    fingerprint: hashDappEventFingerprint(preimage),\n  })\n}\n\nexport function verifyDappEventDraft(value: unknown): DappEventDraft {\n  const draft = DappEventDraftZod.parse(value)\n  const {\n    eventId, fingerprint, hashAlgorithm, ...unresolvedInput\n  } = draft\n  const input = DappEventDraftInputZod.parse(unresolvedInput)\n  const expectedEventId = hashDappEventId(eventIdPreimage(input))\n  if (eventId !== expectedEventId) {\n    throw new TypeError('event ID does not match its canonical preimage')\n  }\n\n  const preimage = DappEventDraftPreimageZod.parse({\n    ...input,\n    eventId,\n    hashAlgorithm,\n  })\n  if (fingerprint !== hashDappEventFingerprint(preimage)) {\n    throw new TypeError('event fingerprint does not match its canonical preimage')\n  }\n  return draft\n}\n\nexport function createDappEventRecord(draftValue: unknown, sequenceValue: unknown): DappEventRecord {\n  const event = verifyDappEventDraft(draftValue)\n  const sequence = DappEventSequenceZod.parse(sequenceValue)\n  return DappEventRecordZod.parse({\n    schema: DappEventRecordSchema,\n    schemaVersion: 1,\n    sequence,\n    event,\n  })\n}\n\nexport function verifyDappEventRecord(value: unknown): DappEventRecord {\n  const record = DappEventRecordZod.parse(value)\n  verifyDappEventDraft(record.event)\n  return record\n}\n\nexport function verifyDappEventAppendDecision(\n  value: unknown,\n  draftValue: unknown,\n): DappEventAppendDecision {\n  const decision = DappEventAppendDecisionZod.parse(value)\n  const draft = verifyDappEventDraft(draftValue)\n  if (decision.kind === 'collision') {\n    if (decision.existingFingerprint === decision.incomingFingerprint) {\n      throw new TypeError('event collision must contain different fingerprints')\n    }\n    if (decision.eventId !== draft.eventId || decision.incomingFingerprint !== draft.fingerprint) {\n      throw new TypeError('event collision does not correspond to the submitted draft')\n    }\n    return decision\n  }\n\n  const record = verifyDappEventRecord(decision.record)\n  if (record.event.eventId !== draft.eventId || record.event.fingerprint !== draft.fingerprint) {\n    throw new TypeError('event append decision does not correspond to the submitted draft')\n  }\n  if (decision.kind === 'appended') {\n    if (record.sequence === Number.MAX_SAFE_INTEGER || decision.nextTail !== record.sequence + 1) {\n      throw new TypeError('appended event must allocate the sequence immediately below its next tail')\n    }\n  } else if (record.sequence >= decision.nextTail) {\n    throw new TypeError('duplicate event sequence must remain below the partition tail')\n  }\n  return decision\n}\n\nexport function decideDappEventAppend(input: {\n  readonly draft: unknown\n  readonly existing?: unknown\n  readonly tail: unknown\n}): DappEventAppendDecision {\n  const draft = verifyDappEventDraft(input.draft)\n  const tail = DappEventSequenceZod.parse(input.tail)\n\n  if (input.existing !== undefined) {\n    const existing = verifyDappEventRecord(input.existing)\n    if (existing.event.eventId !== draft.eventId) {\n      throw new TypeError('existing event record must match the incoming event ID')\n    }\n    if (existing.sequence >= tail) {\n      throw new TypeError('existing event sequence must be allocated below the partition tail')\n    }\n    if (existing.event.fingerprint !== draft.fingerprint) {\n      return {\n        eventId: draft.eventId,\n        existingFingerprint: existing.event.fingerprint,\n        incomingFingerprint: draft.fingerprint,\n        kind: 'collision',\n        nextTail: tail,\n      }\n    }\n    return {\n      kind: 'duplicate', nextTail: tail, record: existing,\n    }\n  }\n\n  if (tail === Number.MAX_SAFE_INTEGER) {\n    throw new TypeError('event partition tail cannot be incremented safely')\n  }\n  return {\n    kind: 'appended',\n    nextTail: tail + 1,\n    record: createDappEventRecord(draft, tail),\n  }\n}\n", "import { asSchema } from '@xyo-network/sdk'\nimport { z } from 'zod'\n\nimport type { DappEventRecord } from './eventStream.ts'\nimport {\n  DappEventSequenceZod,\n  verifyDappEventRecord,\n} from './eventStream.ts'\nimport {\n  HashZod,\n  IdentifierZod,\n  SemanticVersionZod,\n} from './identifier.ts'\nexport const DappEventSubscriptionStateSchema = asSchema('network.xyo.dapp.event.subscription.state', true)\nexport const DappEventConsumerOutcomeSchema = asSchema('network.xyo.dapp.event.consumer.outcome', true)\n\nexport const DappEventFenceEpochZod = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)\nexport const DappEventLeaseTimeZod = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)\nexport const DappEventLeaseDurationZod = z.number().int().positive().max(Number.MAX_SAFE_INTEGER)\nexport const DappEventRetryLimitZod = z.number().int().positive().max(10_000)\nexport const DappEventRetryCountZod = z.number().int().nonnegative().max(10_000)\n\nexport const DappEventSubscriptionDefinitionZod = z.strictObject({\n  subscriptionId: IdentifierZod,\n  streamId: IdentifierZod,\n  partitionId: IdentifierZod,\n  consumerId: IdentifierZod,\n  consumerVersion: SemanticVersionZod,\n  retryLimit: DappEventRetryLimitZod,\n})\n\nexport type DappEventSubscriptionDefinition = z.infer<typeof DappEventSubscriptionDefinitionZod>\n\nconst DappEventSubscriptionStateFields = {\n  schema: z.literal(DappEventSubscriptionStateSchema),\n  schemaVersion: z.literal(1),\n  ...DappEventSubscriptionDefinitionZod.shape,\n  cursor: DappEventSequenceZod,\n  fenceEpoch: DappEventFenceEpochZod,\n  retryCount: DappEventRetryCountZod,\n}\n\nexport const DappEventSubscriptionIdleStateZod = z.strictObject({\n  ...DappEventSubscriptionStateFields,\n  status: z.literal('idle'),\n})\n\nexport const DappEventSubscriptionScheduledStateZod = z.strictObject({\n  ...DappEventSubscriptionStateFields,\n  status: z.literal('scheduled'),\n})\n\nexport const DappEventSubscriptionRunningStateZod = z.strictObject({\n  ...DappEventSubscriptionStateFields,\n  status: z.literal('running'),\n  leaseExpiresAt: DappEventLeaseTimeZod,\n})\n\nexport const DappEventBlockedRecordZod = z.strictObject({\n  sequence: DappEventSequenceZod,\n  eventId: HashZod,\n  eventFingerprint: HashZod,\n  reasonCode: IdentifierZod,\n})\n\nexport const DappEventSubscriptionBlockedStateZod = z.strictObject({\n  ...DappEventSubscriptionStateFields,\n  status: z.literal('blocked'),\n  blockedRecord: DappEventBlockedRecordZod,\n})\n\nexport const DappEventSubscriptionStateZod = z.discriminatedUnion('status', [\n  DappEventSubscriptionIdleStateZod,\n  DappEventSubscriptionScheduledStateZod,\n  DappEventSubscriptionRunningStateZod,\n  DappEventSubscriptionBlockedStateZod,\n]).superRefine((state, context) => {\n  if (state.status === 'blocked') {\n    if (state.blockedRecord.sequence !== state.cursor) {\n      context.addIssue({\n        code: 'custom',\n        message: 'blocked record sequence must equal the next unread cursor',\n        path: ['blockedRecord', 'sequence'],\n      })\n    }\n    if (state.retryCount < state.retryLimit) {\n      context.addIssue({\n        code: 'custom',\n        message: 'blocked state must have exhausted its retry limit',\n        path: ['retryCount'],\n      })\n    }\n  } else if (state.retryCount >= state.retryLimit) {\n    context.addIssue({\n      code: 'custom',\n      message: 'an exhausted subscription must be blocked',\n      path: ['retryCount'],\n    })\n  }\n})\n\nexport type DappEventSubscriptionState = z.infer<typeof DappEventSubscriptionStateZod>\nexport type DappEventSubscriptionIdleState = z.infer<typeof DappEventSubscriptionIdleStateZod>\nexport type DappEventSubscriptionScheduledState = z.infer<typeof DappEventSubscriptionScheduledStateZod>\nexport type DappEventSubscriptionRunningState = z.infer<typeof DappEventSubscriptionRunningStateZod>\nexport type DappEventSubscriptionBlockedState = z.infer<typeof DappEventSubscriptionBlockedStateZod>\n\nexport const DappEventConsumerOutcomeZod = z.strictObject({\n  schema: z.literal(DappEventConsumerOutcomeSchema),\n  schemaVersion: z.literal(1),\n  subscriptionId: IdentifierZod,\n  streamId: IdentifierZod,\n  partitionId: IdentifierZod,\n  consumerId: IdentifierZod,\n  consumerVersion: SemanticVersionZod,\n  sequence: DappEventSequenceZod,\n  eventId: HashZod,\n  eventFingerprint: HashZod,\n  outcomeId: HashZod,\n  disposition: z.enum(['committed', 'already-committed']),\n})\n\nexport type DappEventConsumerOutcome = z.infer<typeof DappEventConsumerOutcomeZod>\n\nexport const DappEventSubscriptionTransitionIssueCodes = [\n  'event-subscription.blocked',\n  'event-subscription.cursor-mismatch',\n  'event-subscription.fence-exhausted',\n  'event-subscription.fence-stale',\n  'event-subscription.lease-active',\n  'event-subscription.lease-expired',\n  'event-subscription.not-scheduled',\n  'event-subscription.not-running',\n  'event-subscription.outcome-mismatch',\n  'event-subscription.scope-mismatch',\n  'event-subscription.sequence-exhausted',\n  'event-subscription.tail-behind-cursor',\n] as const\n\nexport const DappEventSubscriptionTransitionIssueCodeZod = z.enum(DappEventSubscriptionTransitionIssueCodes)\nexport type DappEventSubscriptionTransitionIssueCode = z.infer<typeof DappEventSubscriptionTransitionIssueCodeZod>\n\nexport class DappEventSubscriptionTransitionError extends Error {\n  readonly code: DappEventSubscriptionTransitionIssueCode\n\n  constructor(code: DappEventSubscriptionTransitionIssueCode, message: string) {\n    super(message)\n    this.name = 'DappEventSubscriptionTransitionError'\n    this.code = code\n  }\n}\n\nfunction transitionError(code: DappEventSubscriptionTransitionIssueCode, message: string): never {\n  throw new DappEventSubscriptionTransitionError(code, message)\n}\n\nfunction safeIncrement(value: number, code: DappEventSubscriptionTransitionIssueCode, label: string): number {\n  if (value === Number.MAX_SAFE_INTEGER) transitionError(code, `${label} cannot be incremented safely`)\n  return value + 1\n}\n\nfunction safeAdd(left: number, right: number, label: string): number {\n  if (left > Number.MAX_SAFE_INTEGER - right) {\n    throw new TypeError(`${label} exceeds the safe integer range`)\n  }\n  return left + right\n}\n\nfunction parseState(value: unknown): DappEventSubscriptionState {\n  return DappEventSubscriptionStateZod.parse(value)\n}\n\nfunction assertTail(state: DappEventSubscriptionState, tailValue: unknown): number {\n  const tail = DappEventSequenceZod.parse(tailValue)\n  if (tail < state.cursor) {\n    transitionError(\n      'event-subscription.tail-behind-cursor',\n      'event stream tail cannot be behind the subscription cursor',\n    )\n  }\n  return tail\n}\n\nfunction assertRunningFence(\n  state: DappEventSubscriptionState,\n  fenceEpochValue: unknown,\n): DappEventSubscriptionRunningState {\n  if (state.status !== 'running') {\n    transitionError('event-subscription.not-running', 'subscription must be running')\n  }\n  const fenceEpoch = DappEventFenceEpochZod.parse(fenceEpochValue)\n  if (state.fenceEpoch !== fenceEpoch) {\n    transitionError('event-subscription.fence-stale', 'subscription fence is stale')\n  }\n  return state\n}\n\nfunction assertLeaseCurrent(state: DappEventSubscriptionRunningState, nowValue: unknown): number {\n  const now = DappEventLeaseTimeZod.parse(nowValue)\n  if (now >= state.leaseExpiresAt) {\n    transitionError('event-subscription.lease-expired', 'subscription lease has expired')\n  }\n  return now\n}\n\nfunction assertRecordAtCursor(\n  state: DappEventSubscriptionState,\n  recordValue: unknown,\n): DappEventRecord {\n  const record = verifyDappEventRecord(recordValue)\n  if (record.event.streamId !== state.streamId || record.event.partitionId !== state.partitionId) {\n    transitionError('event-subscription.scope-mismatch', 'event record belongs to a different stream partition')\n  }\n  if (record.sequence !== state.cursor) {\n    transitionError('event-subscription.cursor-mismatch', 'event record sequence must equal the next unread cursor')\n  }\n  return record\n}\n\nfunction assertOutcome(\n  state: DappEventSubscriptionState,\n  record: DappEventRecord,\n  outcomeValue: unknown,\n): DappEventConsumerOutcome {\n  const outcome = DappEventConsumerOutcomeZod.parse(outcomeValue)\n  const matches = outcome.subscriptionId === state.subscriptionId\n    && outcome.streamId === state.streamId\n    && outcome.partitionId === state.partitionId\n    && outcome.consumerId === state.consumerId\n    && outcome.consumerVersion === state.consumerVersion\n    && outcome.sequence === record.sequence\n    && outcome.eventId === record.event.eventId\n    && outcome.eventFingerprint === record.event.fingerprint\n  if (!matches) {\n    transitionError('event-subscription.outcome-mismatch', 'consumer outcome does not prove this exact event and subscription')\n  }\n  return outcome\n}\n\nexport function createDappEventSubscriptionState(\n  definitionValue: unknown,\n  cursorValue: unknown = 0,\n): DappEventSubscriptionIdleState {\n  const definition = DappEventSubscriptionDefinitionZod.parse(definitionValue)\n  return DappEventSubscriptionIdleStateZod.parse({\n    schema: DappEventSubscriptionStateSchema,\n    schemaVersion: 1,\n    ...definition,\n    cursor: DappEventSequenceZod.parse(cursorValue),\n    fenceEpoch: 0,\n    retryCount: 0,\n    status: 'idle',\n  })\n}\n\n/** Make an idle subscription schedulable exactly when its stream has unread work. */\nexport function scheduleDappEventSubscription(\n  stateValue: unknown,\n  tailValue: unknown,\n): DappEventSubscriptionState {\n  const state = parseState(stateValue)\n  const tail = assertTail(state, tailValue)\n  if (state.status === 'blocked' || state.status === 'running') return state\n  return DappEventSubscriptionStateZod.parse({\n    ...state,\n    status: tail > state.cursor ? 'scheduled' : 'idle',\n  })\n}\n\n/** Claim scheduled work, or reclaim an expired lease, under a fresh fence. */\nexport function claimDappEventSubscription(input: {\n  readonly leaseDuration: unknown\n  readonly now: unknown\n  readonly state: unknown\n}): DappEventSubscriptionRunningState {\n  const state = parseState(input.state)\n  const now = DappEventLeaseTimeZod.parse(input.now)\n  const leaseDuration = DappEventLeaseDurationZod.parse(input.leaseDuration)\n  if (state.status === 'blocked') {\n    transitionError('event-subscription.blocked', 'blocked subscription requires an explicit compatibility action')\n  }\n  if (state.status === 'idle') {\n    transitionError('event-subscription.not-scheduled', 'idle subscription has not been scheduled')\n  }\n  if (state.status === 'running' && now < state.leaseExpiresAt) {\n    transitionError('event-subscription.lease-active', 'subscription already has an active lease')\n  }\n  return DappEventSubscriptionRunningStateZod.parse({\n    ...state,\n    status: 'running',\n    fenceEpoch: safeIncrement(state.fenceEpoch, 'event-subscription.fence-exhausted', 'fence epoch'),\n    leaseExpiresAt: safeAdd(now, leaseDuration, 'lease expiry'),\n  })\n}\n\n/** Advance one cursor only after an exact durable consumer outcome is available. */\nexport function advanceDappEventSubscription(input: {\n  readonly fenceEpoch: unknown\n  readonly now: unknown\n  readonly outcome: unknown\n  readonly record: unknown\n  readonly state: unknown\n}): DappEventSubscriptionRunningState {\n  const state = assertRunningFence(parseState(input.state), input.fenceEpoch)\n  assertLeaseCurrent(state, input.now)\n  const record = assertRecordAtCursor(state, input.record)\n  assertOutcome(state, record, input.outcome)\n  return DappEventSubscriptionRunningStateZod.parse({\n    ...state,\n    cursor: safeIncrement(state.cursor, 'event-subscription.sequence-exhausted', 'subscription cursor'),\n    retryCount: 0,\n  })\n}\n\n/** Retain a poison event at the cursor and block once the retry bound is exhausted. */\nexport function failDappEventSubscription(input: {\n  readonly fenceEpoch: unknown\n  readonly now: unknown\n  readonly reasonCode: unknown\n  readonly record: unknown\n  readonly state: unknown\n}): DappEventSubscriptionBlockedState | DappEventSubscriptionScheduledState {\n  const state = assertRunningFence(parseState(input.state), input.fenceEpoch)\n  assertLeaseCurrent(state, input.now)\n  const record = assertRecordAtCursor(state, input.record)\n  const reasonCode = IdentifierZod.parse(input.reasonCode)\n  const retryCount = safeIncrement(state.retryCount, 'event-subscription.sequence-exhausted', 'retry count')\n  const { leaseExpiresAt: _leaseExpiresAt, ...releasedState } = state\n  if (retryCount >= state.retryLimit) {\n    return DappEventSubscriptionBlockedStateZod.parse({\n      ...releasedState,\n      status: 'blocked',\n      retryCount,\n      blockedRecord: {\n        sequence: record.sequence,\n        eventId: record.event.eventId,\n        eventFingerprint: record.event.fingerprint,\n        reasonCode,\n      },\n    })\n  }\n  return DappEventSubscriptionScheduledStateZod.parse({\n    ...releasedState,\n    status: 'scheduled',\n    retryCount,\n  })\n}\n\n/** Release a runner by comparing its fenced cursor against a current stream tail. */\nexport function releaseDappEventSubscription(input: {\n  readonly fenceEpoch: unknown\n  readonly state: unknown\n  readonly tail: unknown\n}): DappEventSubscriptionIdleState | DappEventSubscriptionScheduledState {\n  const state = assertRunningFence(parseState(input.state), input.fenceEpoch)\n  const tail = assertTail(state, input.tail)\n  const { leaseExpiresAt: _leaseExpiresAt, ...releasedState } = state\n  const released = {\n    ...releasedState,\n    status: tail > state.cursor ? 'scheduled' as const : 'idle' as const,\n  }\n  return released.status === 'scheduled'\n    ? DappEventSubscriptionScheduledStateZod.parse(released)\n    : DappEventSubscriptionIdleStateZod.parse(released)\n}\n", "import { asSchema } from '@xyo-network/sdk'\nimport { z } from 'zod'\n\nimport { DappEventSequenceZod } from './eventStream.ts'\nimport type { DappEventSubscriptionState } from './eventSubscription.ts'\nimport {\n  DappEventSubscriptionDefinitionZod,\n  DappEventSubscriptionStateZod,\n  scheduleDappEventSubscription,\n} from './eventSubscription.ts'\nexport const DappEventWakeOutboxStateSchema = asSchema('network.xyo.dapp.event.wake.outbox.state', true)\n\nexport const DappEventWakeGenerationZod = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)\nexport const DappEventWakeDispatchLimitZod = z.number().int().positive().max(10_000)\n\nexport const DappEventWakeOutboxScopeZod = DappEventSubscriptionDefinitionZod.pick({\n  subscriptionId: true,\n  streamId: true,\n  partitionId: true,\n  consumerId: true,\n  consumerVersion: true,\n})\n\nexport type DappEventWakeOutboxScope = z.infer<typeof DappEventWakeOutboxScopeZod>\n\nconst DappEventWakeOutboxStateFields = {\n  schema: z.literal(DappEventWakeOutboxStateSchema),\n  schemaVersion: z.literal(1),\n  ...DappEventWakeOutboxScopeZod.shape,\n  generation: DappEventWakeGenerationZod,\n}\n\nexport const DappEventWakeOutboxClearStateZod = z.strictObject({\n  ...DappEventWakeOutboxStateFields,\n  status: z.literal('clear'),\n})\n\nexport const DappEventWakeOutboxPendingStateZod = z.strictObject({\n  ...DappEventWakeOutboxStateFields,\n  status: z.literal('pending'),\n  requestedCursor: DappEventSequenceZod,\n  observedTail: DappEventSequenceZod,\n}).superRefine((state, context) => {\n  if (state.observedTail <= state.requestedCursor) {\n    context.addIssue({\n      code: 'custom',\n      message: 'pending wake must record unread work',\n      path: ['observedTail'],\n    })\n  }\n})\n\nexport const DappEventWakeOutboxStateZod = z.discriminatedUnion('status', [\n  DappEventWakeOutboxClearStateZod,\n  DappEventWakeOutboxPendingStateZod,\n])\n\nexport type DappEventWakeOutboxState = z.infer<typeof DappEventWakeOutboxStateZod>\nexport type DappEventWakeOutboxClearState = z.infer<typeof DappEventWakeOutboxClearStateZod>\nexport type DappEventWakeOutboxPendingState = z.infer<typeof DappEventWakeOutboxPendingStateZod>\n\nexport const DappEventSubscriptionWakeRequestResultZod = z.strictObject({\n  subscription: DappEventSubscriptionStateZod,\n  outbox: DappEventWakeOutboxStateZod,\n})\n\nexport interface DappEventSubscriptionWakeRequestResult {\n  readonly outbox: DappEventWakeOutboxState\n  readonly subscription: DappEventSubscriptionState\n}\n\nexport const DappEventSubscriptionWakePortRequestInputZod = z.strictObject({\n  observedTail: DappEventSequenceZod,\n  subscriptionId: DappEventWakeOutboxScopeZod.shape.subscriptionId,\n})\n\nexport const DappEventSubscriptionWakePortPendingInputZod = z.strictObject({ limit: DappEventWakeDispatchLimitZod })\n\nexport const DappEventSubscriptionWakePortCompleteInputZod = z.strictObject({ expected: DappEventWakeOutboxPendingStateZod })\n\nexport type DappEventSubscriptionWakePortRequestInput = z.infer<\n  typeof DappEventSubscriptionWakePortRequestInputZod\n>\nexport type DappEventSubscriptionWakePortPendingInput = z.infer<\n  typeof DappEventSubscriptionWakePortPendingInputZod\n>\nexport type DappEventSubscriptionWakePortCompleteInput = z.infer<\n  typeof DappEventSubscriptionWakePortCompleteInputZod\n>\n\nexport const DappEventWakeOutboxTransitionIssueCodes = [\n  'event-wake-outbox.generation-exhausted',\n  'event-wake-outbox.generation-stale',\n  'event-wake-outbox.scope-mismatch',\n  'event-wake-outbox.tail-behind-cursor',\n] as const\n\nexport const DappEventWakeOutboxTransitionIssueCodeZod = z.enum(\n  DappEventWakeOutboxTransitionIssueCodes,\n)\n\nexport type DappEventWakeOutboxTransitionIssueCode = z.infer<\n  typeof DappEventWakeOutboxTransitionIssueCodeZod\n>\n\nexport class DappEventWakeOutboxTransitionError extends Error {\n  readonly code: DappEventWakeOutboxTransitionIssueCode\n\n  constructor(code: DappEventWakeOutboxTransitionIssueCode, message: string) {\n    super(message)\n    this.name = 'DappEventWakeOutboxTransitionError'\n    this.code = code\n  }\n}\n\n/**\n * Provider-neutral durable scheduling boundary.\n *\n * `request` atomically schedules the subscription and persists its pending\n * outbox generation. `pending` is finite and `complete` clears only the exact\n * generation whose disposable wake delivery succeeded.\n */\nexport interface DappEventSubscriptionWakePort {\n  complete(input: DappEventSubscriptionWakePortCompleteInput): Promise<unknown>\n  pending(\n    input: DappEventSubscriptionWakePortPendingInput & { readonly signal?: AbortSignal },\n  ): AsyncIterable<unknown>\n  request(input: DappEventSubscriptionWakePortRequestInput): Promise<unknown>\n}\n\nfunction transitionError(\n  code: DappEventWakeOutboxTransitionIssueCode,\n  message: string,\n): never {\n  throw new DappEventWakeOutboxTransitionError(code, message)\n}\n\nfunction outboxScope(value: unknown): DappEventWakeOutboxScope {\n  const definition = DappEventSubscriptionDefinitionZod.parse(value)\n  return DappEventWakeOutboxScopeZod.parse({\n    subscriptionId: definition.subscriptionId,\n    streamId: definition.streamId,\n    partitionId: definition.partitionId,\n    consumerId: definition.consumerId,\n    consumerVersion: definition.consumerVersion,\n  })\n}\n\nfunction sameScope(\n  outbox: DappEventWakeOutboxState,\n  subscription: DappEventSubscriptionState,\n): boolean {\n  return outbox.subscriptionId === subscription.subscriptionId\n    && outbox.streamId === subscription.streamId\n    && outbox.partitionId === subscription.partitionId\n    && outbox.consumerId === subscription.consumerId\n    && outbox.consumerVersion === subscription.consumerVersion\n}\n\nfunction assertScope(\n  outbox: DappEventWakeOutboxState,\n  subscription: DappEventSubscriptionState,\n): void {\n  if (!sameScope(outbox, subscription)) {\n    transitionError(\n      'event-wake-outbox.scope-mismatch',\n      'wake outbox belongs to a different subscription scope',\n    )\n  }\n}\n\nfunction nextGeneration(value: number): number {\n  if (value === Number.MAX_SAFE_INTEGER) {\n    transitionError(\n      'event-wake-outbox.generation-exhausted',\n      'wake outbox generation cannot be incremented safely',\n    )\n  }\n  return value + 1\n}\n\nexport function createDappEventWakeOutboxState(\n  definitionValue: unknown,\n): DappEventWakeOutboxClearState {\n  const scope = outboxScope(definitionValue)\n  return DappEventWakeOutboxClearStateZod.parse({\n    schema: DappEventWakeOutboxStateSchema,\n    schemaVersion: 1,\n    ...scope,\n    generation: 0,\n    status: 'clear',\n  })\n}\n\n/**\n * Atomically make lag schedulable and retain one coalescing pending wake.\n * A pending generation remains sufficient when the tail grows because a wake\n * always drains current durable state rather than trusting its tail snapshot.\n */\nexport function requestDappEventSubscriptionWake(input: {\n  readonly outbox: unknown\n  readonly subscription: unknown\n  readonly tail: unknown\n}): DappEventSubscriptionWakeRequestResult {\n  const subscription = DappEventSubscriptionStateZod.parse(input.subscription)\n  const outbox = DappEventWakeOutboxStateZod.parse(input.outbox)\n  assertScope(outbox, subscription)\n  const tail = DappEventSequenceZod.parse(input.tail)\n  if (tail < subscription.cursor) {\n    transitionError(\n      'event-wake-outbox.tail-behind-cursor',\n      'event stream tail cannot be behind the subscription cursor',\n    )\n  }\n\n  if (subscription.status === 'blocked' || tail === subscription.cursor) {\n    return { subscription, outbox }\n  }\n\n  const scheduled = scheduleDappEventSubscription(subscription, tail)\n  if (outbox.status === 'pending') {\n    return { subscription: scheduled, outbox }\n  }\n\n  return {\n    subscription: scheduled,\n    outbox: DappEventWakeOutboxPendingStateZod.parse({\n      ...outbox,\n      status: 'pending',\n      generation: nextGeneration(outbox.generation),\n      requestedCursor: subscription.cursor,\n      observedTail: tail,\n    }),\n  }\n}\n\n/** Clear one delivered generation without allowing a stale delivery to clear a newer request. */\nexport function completeDappEventSubscriptionWake(\n  stateValue: unknown,\n  generationValue: unknown,\n): DappEventWakeOutboxClearState {\n  const state = DappEventWakeOutboxStateZod.parse(stateValue)\n  const generation = DappEventWakeGenerationZod.parse(generationValue)\n  if (generation !== state.generation) {\n    transitionError(\n      'event-wake-outbox.generation-stale',\n      'wake completion generation does not match durable outbox state',\n    )\n  }\n  if (state.status === 'clear') return state\n  const {\n    observedTail: _observedTail,\n    requestedCursor: _requestedCursor,\n    ...clear\n  } = state\n  return DappEventWakeOutboxClearStateZod.parse({ ...clear, status: 'clear' })\n}\n\nexport function verifyDappEventSubscriptionWakeRequestResult(\n  value: unknown,\n): DappEventSubscriptionWakeRequestResult {\n  const result = DappEventSubscriptionWakeRequestResultZod.parse(value)\n  assertScope(result.outbox, result.subscription)\n  return result\n}\n", "import { asSchema } from '@xyo-network/sdk'\nimport { z } from 'zod'\n\nimport {\n  DappIdZod,\n  HashZod,\n  IdentifierZod,\n  SchemaVersionZod,\n  Xl1ChainIdZod,\n  XyoSchemaZod,\n} from './identifier.ts'\nimport { ExternalSourceKindZod } from './profile.ts'\nexport const ExternalObservationSchema = asSchema('network.xyo.dapp.external.observation', true)\n\nconst PolicyEvidenceZod = z.strictObject({\n  policyId: IdentifierZod,\n  policyVersion: SchemaVersionZod,\n  evidenceHash: HashZod,\n})\n\nexport const ExternalObservationZod = z.strictObject({\n  schema: z.literal(ExternalObservationSchema),\n  schemaVersion: z.literal(1),\n  dappId: DappIdZod,\n  chainId: Xl1ChainIdZod,\n  observationId: IdentifierZod,\n  sourceId: IdentifierZod,\n  sourceKind: ExternalSourceKindZod,\n  observerRole: IdentifierZod,\n  observedAt: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),\n  provenance: PolicyEvidenceZod,\n  finality: PolicyEvidenceZod,\n  content: z.strictObject({\n    schema: XyoSchemaZod,\n    version: SchemaVersionZod,\n    hash: HashZod,\n  }),\n})\n\nexport type ExternalObservation = z.infer<typeof ExternalObservationZod>\n", "import { asSchema } from '@xyo-network/sdk'\nimport { z } from 'zod'\n\nimport { DappEngineNetworkZod, DappEngineSystemReferenceZod } from './dappEngineModel.ts'\nimport { EffectReceiptJournalDurabilityZod } from './effectJournal.ts'\nimport {\n  DappIdZod, HashZod, IdentifierZod,\n} from './identifier.ts'\n\nexport const DappOperationRecoveryProfileSchema = asSchema('network.xyo.dapp.operation.recovery.profile', true)\nexport const DappOperationRecoverySnapshotSchema = asSchema('network.xyo.dapp.operation.recovery.snapshot', true)\nexport const DappOperationRecoveryMaximumOperations = 128\nexport const DappRecoveryGuarantees = [\n  'retained-state-validation',\n  'original-effect-binding',\n  'uncertain-outcome-preservation',\n  'retained-artifact-reuse',\n  'cross-context-exclusion',\n  'page-termination',\n  'process-termination',\n] as const\nexport const DappRecoveryGuaranteeZod = z.enum(DappRecoveryGuarantees)\nexport type DappRecoveryGuarantee = z.infer<typeof DappRecoveryGuaranteeZod>\n\nconst guarantees = z.array(DappRecoveryGuaranteeZod).max(DappRecoveryGuarantees.length).superRefine((values, context) => {\n  const unique = new Set(values)\n  if (unique.size !== values.length) context.addIssue({ code: 'custom', message: 'guarantees must be unique' })\n})\nconst requiredGuarantees = guarantees.superRefine((values, context) => {\n  for (const required of DappRecoveryGuarantees.slice(0, 3)) {\n    if (!values.includes(required)) context.addIssue({ code: 'custom', message: `write recovery requires ${required}` })\n  }\n})\n\nexport const DappOperationRecoveryRequirementZod = z.strictObject({\n  portId: IdentifierZod,\n  operationId: IdentifierZod,\n  recovery: z.discriminatedUnion('kind', [\n    z.strictObject({ kind: z.literal('read-only') }),\n    z.strictObject({\n      kind: z.literal('external'), capabilityId: IdentifierZod, requiredGuarantees,\n    }),\n    z.strictObject({\n      kind: z.literal('kit-journal'), capabilityId: IdentifierZod, requiredGuarantees,\n    }),\n  ]),\n})\nexport type DappOperationRecoveryRequirement = z.infer<typeof DappOperationRecoveryRequirementZod>\n\nexport const DappOperationRecoveryProfileZod = z.strictObject({\n  schema: z.literal(DappOperationRecoveryProfileSchema),\n  schemaVersion: z.literal(1),\n  operations: z.array(DappOperationRecoveryRequirementZod).min(1).max(DappOperationRecoveryMaximumOperations),\n}).superRefine((profile, context) => {\n  const keys = profile.operations.map(operation => JSON.stringify([operation.portId, operation.operationId]))\n  const unique = new Set(keys)\n  if (unique.size !== keys.length) context.addIssue({\n    code: 'custom', message: 'recovery operations must be unique', path: ['operations'],\n  })\n})\nexport type DappOperationRecoveryProfile = z.infer<typeof DappOperationRecoveryProfileZod>\n\nexport const DappOperationRecoveryBindingZod = z.strictObject({\n  reference: DappEngineSystemReferenceZod,\n  dappId: DappIdZod,\n  hostSessionId: IdentifierZod,\n  planId: HashZod,\n  network: DappEngineNetworkZod,\n  authorityScopeId: IdentifierZod,\n})\nexport type DappOperationRecoveryBinding = z.infer<typeof DappOperationRecoveryBindingZod>\n\nexport const DappRecoveryCapabilityZod = z.discriminatedUnion('kind', [\n  z.strictObject({\n    kind: z.literal('external'), capabilityId: IdentifierZod, guarantees,\n  }),\n  z.strictObject({\n    kind: z.literal('kit-journal'), capabilityId: IdentifierZod, guarantees, journalDurability: EffectReceiptJournalDurabilityZod,\n  }),\n])\nexport type DappRecoveryCapability = z.infer<typeof DappRecoveryCapabilityZod>\n\nexport const DappOperationRecoveryStateZod = z.enum(['ready', 'pending', 'uncertain', 'unavailable', 'corrupt'])\nexport type DappOperationRecoveryState = z.infer<typeof DappOperationRecoveryStateZod>\n\nexport const DappOperationRecoverySnapshotZod = z.strictObject({\n  schema: z.literal(DappOperationRecoverySnapshotSchema),\n  schemaVersion: z.literal(1),\n  binding: DappOperationRecoveryBindingZod,\n  portId: IdentifierZod,\n  operationId: IdentifierZod,\n  capability: DappRecoveryCapabilityZod,\n  state: DappOperationRecoveryStateZod,\n  reasonCodes: z.array(IdentifierZod).max(32),\n  operationRefs: z.array(IdentifierZod).max(DappOperationRecoveryMaximumOperations),\n}).superRefine((snapshot, context) => {\n  if ((snapshot.state === 'ready') !== (snapshot.reasonCodes.length === 0)) {\n    context.addIssue({\n      code: 'custom', message: 'only ready recovery has no blocking reasons', path: ['reasonCodes'],\n    })\n  }\n  for (const field of ['reasonCodes', 'operationRefs'] as const) {\n    const unique = new Set(snapshot[field])\n    if (unique.size !== snapshot[field].length) context.addIssue({\n      code: 'custom', message: `${field} must be unique`, path: [field],\n    })\n  }\n})\nexport type DappOperationRecoverySnapshot = z.infer<typeof DappOperationRecoverySnapshotZod>\n", "import { canonicalizeIJson } from './canonicalDocument.ts'\nimport type { DappSessionWorkOwner } from './dappSession.ts'\nimport type {\n  DappOperationRecoveryBinding, DappOperationRecoveryProfile, DappOperationRecoveryRequirement, DappOperationRecoverySnapshot, DappRecoveryCapability,\n} from './operationRecoveryModel.ts'\nimport {\n  DappOperationRecoveryBindingZod, DappOperationRecoveryProfileZod, DappOperationRecoveryRequirementZod,\n  DappOperationRecoverySnapshotSchema, DappOperationRecoverySnapshotZod, DappRecoveryCapabilityZod,\n} from './operationRecoveryModel.ts'\n\nexport type DappExternalRecoveryCapability = Extract<DappRecoveryCapability, { kind: 'external' }>\nexport interface DappExternalRecoveryInspectionResult { readonly state: 'complete' | 'invalidated' | 'closed' }\n\nexport interface DappExternalRecoveryInspectionContext {\n  readonly binding: Readonly<DappOperationRecoveryBinding>\n  readonly capability: Readonly<DappExternalRecoveryCapability>\n  readonly requirements: readonly Readonly<DappOperationRecoveryRequirement>[]\n  readonly whenCancellationRequested: Promise<void>\n  isCancellationRequested(): boolean\n}\n\nexport interface CreateDappExternalRecoveryOwnerOptions {\n  readonly binding: DappOperationRecoveryBinding\n  readonly capability: DappExternalRecoveryCapability\n  readonly inspect: (context: DappExternalRecoveryInspectionContext) => Promise<readonly DappOperationRecoverySnapshot[]>\n  readonly profile: DappOperationRecoveryProfile\n}\n\nexport interface DappExternalRecoveryOwner extends DappSessionWorkOwner {\n  invalidate(): void\n  refresh(): Promise<DappExternalRecoveryInspectionResult>\n  snapshot(requirement: Readonly<DappOperationRecoveryRequirement>, binding: Readonly<DappOperationRecoveryBinding>): DappOperationRecoverySnapshot\n}\n\nexport class DappExternalRecoveryError extends Error {\n  readonly code: string\n  constructor(code: string, options?: ErrorOptions) {\n    super(code, options)\n    this.name = 'DappExternalRecoveryError'\n    this.code = code\n  }\n}\n\ninterface Inspection {\n  readonly cancellation: PromiseWithResolvers<void>\n  cancelled: boolean\n  readonly completion: PromiseWithResolvers<DappExternalRecoveryInspectionResult>\n  readonly token: object\n}\n\nconst key = (value: { readonly operationId: string; readonly portId: string }) => JSON.stringify([value.portId, value.operationId])\nconst capabilityIdentity = (value: DappRecoveryCapability) => canonicalizeIJson({ ...value, guarantees: [...value.guarantees].toSorted() })\nconst requirementIdentity = (value: DappOperationRecoveryRequirement) => canonicalizeIJson({\n  ...value,\n  recovery: value.recovery.kind === 'read-only' ? value.recovery : { ...value.recovery, requiredGuarantees: [...value.recovery.requiredGuarantees].toSorted() },\n})\n\nclass ExternalRecoveryOwner implements DappExternalRecoveryOwner {\n  private active?: Inspection\n  private readonly binding: DappOperationRecoveryBinding\n  private readonly capability: DappExternalRecoveryCapability\n  private closed = false\n  private closingInspection?: Promise<DappExternalRecoveryInspectionResult>\n  private drainPromise?: Promise<void>\n  private readonly inspect: CreateDappExternalRecoveryOwnerOptions['inspect']\n  private readonly requirements: readonly DappOperationRecoveryRequirement[]\n  private snapshots = new Map<string, DappOperationRecoverySnapshot>()\n  private token: object = {}\n\n  constructor(options: CreateDappExternalRecoveryOwnerOptions) {\n    this.binding = DappOperationRecoveryBindingZod.parse(options.binding)\n    const capability = DappRecoveryCapabilityZod.parse(options.capability)\n    if (capability.kind !== 'external') throw new DappExternalRecoveryError('recovery.capability-mismatch')\n    this.capability = capability\n    this.requirements = DappOperationRecoveryProfileZod.parse(options.profile).operations.filter(requirement => requirement.recovery.kind === 'external'\n      && requirement.recovery.capabilityId === capability.capabilityId)\n    if (this.requirements.length === 0 || typeof options.inspect !== 'function') throw new DappExternalRecoveryError('recovery.owner-invalid')\n    this.inspect = options.inspect.bind(options)\n    Object.freeze(this.binding.reference)\n    Object.freeze(this.binding.network)\n    Object.freeze(this.binding)\n    Object.freeze(this.capability.guarantees)\n    Object.freeze(this.capability)\n    for (const requirement of this.requirements) {\n      if (requirement.recovery.kind !== 'read-only') Object.freeze(requirement.recovery.requiredGuarantees)\n      Object.freeze(requirement.recovery)\n      Object.freeze(requirement)\n    }\n    Object.freeze(this.requirements)\n    this.block('recovery.not-inspected')\n  }\n\n  close(): void {\n    if (this.closed) return\n    this.closed = true\n    this.closingInspection = this.active?.completion.promise\n    this.cancel('recovery.owner-closed')\n  }\n\n  drain(): Promise<void> {\n    if (this.drainPromise !== undefined) return this.drainPromise\n    const completion = Promise.withResolvers<void>()\n    this.drainPromise = completion.promise\n    void completion.promise.catch(() => { /* Joined by the session/boot owner. */ })\n    this.close()\n    void (this.closingInspection ?? Promise.resolve()).then(() => completion.resolve(), completion.reject)\n    return completion.promise\n  }\n\n  invalidate(): void {\n    if (!this.closed) this.cancel('recovery.invalidated')\n  }\n\n  refresh(): Promise<DappExternalRecoveryInspectionResult> {\n    if (this.closed) return Promise.reject(new DappExternalRecoveryError('recovery.owner-closed'))\n    if (this.active !== undefined) return this.active.completion.promise\n    const inspection: Inspection = {\n      cancellation: Promise.withResolvers<void>(),\n      cancelled: false,\n      completion: Promise.withResolvers<DappExternalRecoveryInspectionResult>(),\n      token: this.token,\n    }\n    this.active = inspection\n    void inspection.completion.promise.catch(() => { /* The caller retains the rejected inspection result. */ })\n    this.block('recovery.inspecting')\n    void this.run(inspection).then((result) => {\n      if (this.active === inspection) this.active = undefined\n      inspection.completion.resolve(result)\n    }, (cause: unknown) => {\n      if (this.active === inspection) this.active = undefined\n      inspection.completion.reject(cause)\n    })\n    return inspection.completion.promise\n  }\n\n  snapshot(requirementValue: Readonly<DappOperationRecoveryRequirement>, bindingValue: Readonly<DappOperationRecoveryBinding>): DappOperationRecoverySnapshot {\n    const binding = DappOperationRecoveryBindingZod.parse(bindingValue)\n    if (canonicalizeIJson(binding) !== canonicalizeIJson(this.binding)) throw new DappExternalRecoveryError('recovery.binding-mismatch')\n    const requirement = DappOperationRecoveryRequirementZod.parse(requirementValue)\n    const selected = this.requirements.find(value => key(value) === key(requirement))\n    if (selected === undefined || requirementIdentity(selected) !== requirementIdentity(requirement)) throw new DappExternalRecoveryError('recovery.requirement-mismatch')\n    return DappOperationRecoverySnapshotZod.parse(this.snapshots.get(key(requirement)))\n  }\n\n  private block(reason: string): void {\n    this.snapshots = new Map(this.requirements.map(requirement => [key(requirement), {\n      schema: DappOperationRecoverySnapshotSchema,\n      schemaVersion: 1,\n      binding: this.binding,\n      portId: requirement.portId,\n      operationId: requirement.operationId,\n      capability: this.capability,\n      state: 'unavailable',\n      reasonCodes: [reason],\n      operationRefs: [],\n    }]))\n  }\n\n  private cancel(reason: string): void {\n    this.token = {}\n    this.block(reason)\n    if (this.active === undefined) {\n      return\n    }\n\n    this.active.cancelled = true\n    this.active.cancellation.resolve()\n  }\n\n  private async run(inspection: Inspection): Promise<DappExternalRecoveryInspectionResult> {\n    try {\n      let values: readonly DappOperationRecoverySnapshot[]\n      try {\n        values = await this.inspect(Object.freeze({\n          binding: this.binding,\n          capability: this.capability,\n          requirements: this.requirements,\n          whenCancellationRequested: inspection.cancellation.promise,\n          isCancellationRequested: () => inspection.cancelled,\n        }))\n      } catch (cause) {\n        throw new DappExternalRecoveryError('recovery.inspection-failed', { cause })\n      }\n      if (inspection.token !== this.token) return { state: this.closed ? 'closed' : 'invalidated' }\n      let snapshots: Map<string, DappOperationRecoverySnapshot>\n      try {\n        snapshots = this.validate(values)\n      } catch (cause) {\n        throw new DappExternalRecoveryError('recovery.inspection-invalid', { cause })\n      }\n      // Validation can invoke accessors supplied by an adapter; never publish after reentrant invalidation.\n      if (inspection.token !== this.token) return { state: this.closed ? 'closed' : 'invalidated' }\n      this.snapshots = snapshots\n      return { state: 'complete' }\n    } catch (cause) {\n      if (!this.closed && inspection.token === this.token) this.block('recovery.inspection-failed')\n      throw cause\n    }\n  }\n\n  private validate(values: readonly DappOperationRecoverySnapshot[]): Map<string, DappOperationRecoverySnapshot> {\n    if (!Array.isArray(values) || values.length !== this.requirements.length) throw new DappExternalRecoveryError('recovery.coverage-mismatch')\n    const snapshots = new Map<string, DappOperationRecoverySnapshot>()\n    for (const value of values) {\n      const snapshot = DappOperationRecoverySnapshotZod.parse(value)\n      if (canonicalizeIJson(snapshot.binding) !== canonicalizeIJson(this.binding)) throw new DappExternalRecoveryError('recovery.binding-mismatch')\n      if (capabilityIdentity(snapshot.capability) !== capabilityIdentity(this.capability)) throw new DappExternalRecoveryError('recovery.capability-mismatch')\n      const id = key(snapshot)\n      if (snapshots.has(id) || this.requirements.every(requirement => key(requirement) !== id)) throw new DappExternalRecoveryError('recovery.coverage-mismatch')\n      snapshots.set(id, snapshot)\n    }\n    return snapshots\n  }\n}\n\n/** Passive, explicitly driven observation over an existing externally recovered store. */\nexport function createDappExternalRecoveryOwner(options: CreateDappExternalRecoveryOwnerOptions): DappExternalRecoveryOwner {\n  const owner = new ExternalRecoveryOwner(options)\n  const facade: DappExternalRecoveryOwner = {\n    close: () => owner.close(),\n    drain: () => owner.drain(),\n    invalidate: () => owner.invalidate(),\n    refresh: () => owner.refresh(),\n    snapshot: (requirement, binding) => owner.snapshot(requirement, binding),\n  }\n  return Object.freeze(facade)\n}\n", "import { z } from 'zod'\n\nimport { HashZod, IdentifierZod } from './identifier.ts'\n\nconst CounterZod = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)\nconst TimeZod = CounterZod\nexport const DappHeadObserverTargetZod = z.strictObject({ position: CounterZod })\nexport const DappVerifiedHeadZod = z.strictObject({\n  sourceHash: HashZod,\n  position: CounterZod,\n  root: HashZod,\n})\nexport const DappHeadObserverScopeZod = z.strictObject({ sourceHash: HashZod, consumerId: IdentifierZod })\nexport const DappHeadObserverLeaseZod = z.strictObject({\n  sourceHash: HashZod,\n  consumerId: IdentifierZod,\n  fence: CounterZod.refine(value => value > 0),\n  generation: CounterZod.refine(value => value > 0),\n  acquiredAt: TimeZod,\n  expiresAt: TimeZod,\n})\nexport const DappHeadObserverSchedulingZod = z.strictObject({\n  fence: CounterZod.refine(value => value > 0),\n  generation: CounterZod.refine(value => value > 0),\n  resendAt: TimeZod,\n  status: z.enum(['sending', 'sent']),\n})\nexport const DappHeadObserverStateZod = z.strictObject({\n  schema: z.literal('network.xyo.dapp.head-observer'),\n  schemaVersion: z.literal(1),\n  sourceHash: HashZod,\n  consumerId: IdentifierZod,\n  dirtyGeneration: CounterZod,\n  completedGeneration: CounterZod,\n  fence: CounterZod,\n  scheduleFence: CounterZod,\n  lastRequestedAt: TimeZod,\n  requestedTarget: DappHeadObserverTargetZod.optional(),\n  latestVerified: DappVerifiedHeadZod.extend({ observedAt: TimeZod }).optional(),\n  lease: DappHeadObserverLeaseZod.optional(),\n  scheduled: DappHeadObserverSchedulingZod.optional(),\n}).superRefine((state, context) => {\n  if (state.completedGeneration > state.dirtyGeneration\n    || (state.latestVerified !== undefined && state.latestVerified.sourceHash !== state.sourceHash)\n    || (state.lease !== undefined && (state.lease.sourceHash !== state.sourceHash\n      || state.lease.consumerId !== state.consumerId || state.lease.fence !== state.fence\n      || state.lease.generation > state.dirtyGeneration\n      || state.lease.generation <= state.completedGeneration\n      || state.lease.expiresAt <= state.lease.acquiredAt))\n    || (state.scheduled !== undefined && (state.scheduled.fence !== state.scheduleFence\n      || state.scheduled.generation > state.dirtyGeneration\n      || state.scheduled.generation <= state.completedGeneration))) {\n    context.addIssue({ code: 'custom', message: 'head-observer state invariant failed' })\n  }\n})\n\nexport type DappHeadObserverScope = z.infer<typeof DappHeadObserverScopeZod>\nexport type DappHeadObserverTarget = z.infer<typeof DappHeadObserverTargetZod>\nexport type DappVerifiedHead = z.infer<typeof DappVerifiedHeadZod>\nexport type DappHeadObserverLease = z.infer<typeof DappHeadObserverLeaseZod>\nexport type DappHeadObserverState = z.infer<typeof DappHeadObserverStateZod>\nexport type DappHeadObserverScheduling = z.infer<typeof DappHeadObserverSchedulingZod>\n\nfunction increment(value: number): number {\n  if (value === Number.MAX_SAFE_INTEGER) throw new RangeError('head-observer counter exhausted')\n  return value + 1\n}\n\nexport function createDappHeadObserverState(scope: unknown, now: number): DappHeadObserverState {\n  return DappHeadObserverStateZod.parse({\n    schema: 'network.xyo.dapp.head-observer',\n    schemaVersion: 1,\n    ...DappHeadObserverScopeZod.parse(scope),\n    dirtyGeneration: 0,\n    completedGeneration: 0,\n    fence: 0,\n    scheduleFence: 0,\n    lastRequestedAt: TimeZod.parse(now),\n  })\n}\n\n/** Every newly admitted logical hint or independent repair makes current state dirty. */\nexport function requestDappHeadObservation(\n  value: unknown,\n  targetValue: unknown,\n  now: number,\n): DappHeadObserverState {\n  const state = DappHeadObserverStateZod.parse(value)\n  const time = TimeZod.parse(now)\n  const target = targetValue === undefined ? undefined : DappHeadObserverTargetZod.parse(targetValue)\n  return DappHeadObserverStateZod.parse({\n    ...state,\n    dirtyGeneration: increment(state.dirtyGeneration),\n    // Conditional commits and generations order requests, not captured host time.\n    lastRequestedAt: Math.max(time, state.lastRequestedAt),\n    ...(target === undefined || (state.requestedTarget !== undefined\n      && target.position < state.requestedTarget.position)\n      ? {}\n      : { requestedTarget: target }),\n  })\n}\n\n/** 'running' describes a persisted lease, not evidence of a live invocation. */\nexport function dappHeadObserverStatus(value: unknown): 'idle' | 'pending' | 'running' {\n  const state = DappHeadObserverStateZod.parse(value)\n  return state.lease === undefined\n    ? state.dirtyGeneration > state.completedGeneration ? 'pending' : 'idle'\n    : 'running'\n}\n\nexport function claimDappHeadObservation(value: unknown, now: number, leaseDurationMs: number): DappHeadObserverState {\n  const state = DappHeadObserverStateZod.parse(value)\n  const time = TimeZod.parse(now)\n  if (state.dirtyGeneration === state.completedGeneration || (state.lease !== undefined && state.lease.expiresAt > time)) {\n    return state\n  }\n  const duration = z.number().int().positive().max(Number.MAX_SAFE_INTEGER).parse(leaseDurationMs)\n  const fence = increment(state.fence)\n  const { scheduled: _scheduled, ...rest } = state\n  return DappHeadObserverStateZod.parse({\n    ...rest,\n    fence,\n    lease: {\n      sourceHash: state.sourceHash, consumerId: state.consumerId, fence, generation: state.dirtyGeneration, acquiredAt: time, expiresAt: TimeZod.parse(time + duration),\n    },\n  })\n}\n\n/** Reserve one disposable Queue wake while dirty; retries are bounded by an explicit resend time. */\nexport function reserveDappHeadObserverScheduling(value: unknown, now: number, resendAfterMs: number): DappHeadObserverState {\n  const state = DappHeadObserverStateZod.parse(value)\n  const time = TimeZod.parse(now)\n  if (state.dirtyGeneration === state.completedGeneration\n    || (state.lease !== undefined && state.lease.expiresAt > time)\n    || (state.scheduled !== undefined && state.scheduled.resendAt > time)) return state\n  const delay = z.number().int().positive().max(Number.MAX_SAFE_INTEGER).parse(resendAfterMs)\n  const fence = increment(state.scheduleFence)\n  return DappHeadObserverStateZod.parse({\n    ...state,\n    scheduleFence: fence,\n    scheduled: {\n      fence, generation: state.dirtyGeneration, resendAt: TimeZod.parse(time + delay), status: 'sending',\n    },\n  })\n}\n\n/** A late send acknowledgement/failure cannot erase a newer reservation or a consumed callback. */\nexport function finishDappHeadObserverScheduling(\n  value: unknown,\n  reservationValue: unknown,\n  sent: boolean,\n): DappHeadObserverState {\n  const state = DappHeadObserverStateZod.parse(value)\n  const reservation = DappHeadObserverSchedulingZod.parse(reservationValue)\n  if (state.scheduled === undefined || reservation.fence !== state.scheduleFence\n    || reservation.generation !== state.scheduled.generation || reservation.resendAt !== state.scheduled.resendAt) return state\n  if (sent) return DappHeadObserverStateZod.parse({ ...state, scheduled: { ...state.scheduled, status: 'sent' } })\n  const { scheduled: _scheduled, ...rest } = state\n  return DappHeadObserverStateZod.parse(rest)\n}\n\nfunction assertLease(state: DappHeadObserverState, value: unknown): DappHeadObserverLease {\n  const lease = DappHeadObserverLeaseZod.parse(value)\n  if (state.lease === undefined || lease.sourceHash !== state.sourceHash || lease.consumerId !== state.consumerId\n    || lease.fence !== state.fence || lease.generation !== state.lease.generation\n    || lease.acquiredAt !== state.lease.acquiredAt || lease.expiresAt !== state.lease.expiresAt) throw new Error('head-observer lease stale')\n  return lease\n}\n\n/** Commit only independently verified current-head evidence, preserving arrivals after capture. */\nexport function completeDappHeadObservation(\n  value: unknown,\n  leaseValue: unknown,\n  headValue: unknown,\n  now: number,\n): DappHeadObserverState {\n  const state = DappHeadObserverStateZod.parse(value)\n  const lease = assertLease(state, leaseValue)\n  const time = TimeZod.parse(now)\n  if (time < lease.acquiredAt) throw new Error('head-observer clock regressed')\n  if (time >= lease.expiresAt) throw new Error('head-observer lease expired')\n  const head = DappVerifiedHeadZod.parse(headValue)\n  if (head.sourceHash !== state.sourceHash) throw new Error('head-observer source identity mismatch')\n  const prior = state.latestVerified\n  if (prior !== undefined && (head.position < prior.position || time < prior.observedAt)) {\n    throw new Error('head-observer verified head regressed')\n  }\n  if (head.position === prior?.position && head.root !== prior.root) {\n    throw new Error('head-observer verified root conflict')\n  }\n  const { lease: _lease, ...rest } = state\n  return DappHeadObserverStateZod.parse({\n    ...rest,\n    completedGeneration: lease.generation,\n    latestVerified: { ...head, observedAt: time },\n  })\n}\n\nexport function releaseDappHeadObservation(value: unknown, leaseValue: unknown): DappHeadObserverState {\n  const state = DappHeadObserverStateZod.parse(value)\n  assertLease(state, leaseValue)\n  const { lease: _lease, ...rest } = state\n  return DappHeadObserverStateZod.parse(rest)\n}\n\n/** Repair expired leases and request an independent idle-source check after the bound. */\nexport function recoverDappHeadObservation(value: unknown, now: number, refreshAfterMs: number): DappHeadObserverState {\n  let state = DappHeadObserverStateZod.parse(value)\n  const time = TimeZod.parse(now)\n  const refresh = z.number().int().positive().max(Number.MAX_SAFE_INTEGER).parse(refreshAfterMs)\n  if (state.lease !== undefined && state.lease.expiresAt <= time) {\n    const { lease: _lease, ...rest } = state\n    state = DappHeadObserverStateZod.parse(rest)\n  }\n  if (state.dirtyGeneration === state.completedGeneration && time - state.lastRequestedAt >= refresh) {\n    state = requestDappHeadObservation(state, undefined, time)\n  }\n  return state\n}\n", "import { asSchema } from '@xyo-network/sdk'\nimport { z } from 'zod'\n\nimport {\n  DappDocumentHashAlgorithm,\n  hashDappDocument,\n} from './canonicalDocument.ts'\nimport {\n  HashZod,\n  IdentifierZod,\n} from './identifier.ts'\nimport { DappInfrastructureIdZod } from './infrastructureDescriptor.ts'\nimport { JsonValueZod } from './jsonValue.ts'\nimport {\n  compareCodeUnits,\n  compareNumbers,\n  isSortedUniqueStrings,\n} from './ordering.ts'\n\n/**\n * Managed-capability exports and imports (plan Sections 4.4 and 4.5). Every\n * managed resource has one owning infrastructure instance. Another instance\n * may consume it only through an explicitly exported capability whose identity\n * is computed by the producer adapter from admitted source and deterministic\n * target identity. Provider-created values never enter it in MI0-MI9.\n */\nexport const DappManagedCapabilityExportIdentitySchema = asSchema('network.xyo.dapp.managed.capability.export.identity', true)\n\nconst PositiveIntegerZod = z.number().int().positive()\n\n/** The export contract tuple every export, import, and composition binding repeats exactly. */\nexport const DappManagedCapabilityContractRefZod = z.strictObject({\n  exportContractId: IdentifierZod,\n  exportContractVersion: PositiveIntegerZod,\n  exportContractHash: HashZod,\n  exportNormalizationId: IdentifierZod,\n})\nexport type DappManagedCapabilityContractRef = z.infer<typeof DappManagedCapabilityContractRefZod>\n\nexport const DappManagedCapabilityExportIdentityV1PreimageZod = z.strictObject({\n  schema: z.literal(DappManagedCapabilityExportIdentitySchema),\n  schemaVersion: z.literal(1),\n  hashAlgorithm: z.literal(DappDocumentHashAlgorithm),\n  resourceId: IdentifierZod,\n  owningInfrastructureId: DappInfrastructureIdZod,\n  ...DappManagedCapabilityContractRefZod.shape,\n  /** Strict non-secret identity validated by `identitySchemaHash` and normalized by `exportNormalizationId` in the adapter. */\n  identity: JsonValueZod,\n})\nexport type DappManagedCapabilityExportIdentityV1Preimage = z.infer<typeof DappManagedCapabilityExportIdentityV1PreimageZod>\n\nexport const DappManagedCapabilityExportIdentityV1Zod = DappManagedCapabilityExportIdentityV1PreimageZod\n  .safeExtend({ exportIdentityHash: HashZod })\nexport type DappManagedCapabilityExportIdentityV1 = z.infer<typeof DappManagedCapabilityExportIdentityV1Zod>\n\n/** D-002 kind `managed-capability-export-identity` version 1. */\nexport function hashDappManagedCapabilityExportIdentityV1(preimage: unknown): string {\n  return hashDappDocument({\n    kind: 'managed-capability-export-identity',\n    schema: DappManagedCapabilityExportIdentityV1PreimageZod,\n    schemaVersion: 1,\n  }, preimage).hash\n}\n\nexport function verifyDappManagedCapabilityExportIdentityV1(value: unknown): DappManagedCapabilityExportIdentityV1 {\n  const identity = DappManagedCapabilityExportIdentityV1Zod.parse(value)\n  const { exportIdentityHash, ...preimage } = identity\n  if (hashDappManagedCapabilityExportIdentityV1(preimage) !== exportIdentityHash) {\n    throw new TypeError(`export identity for ${identity.resourceId} does not reproduce its exportIdentityHash`)\n  }\n  return identity\n}\n\nconst SortedIdentifiersZod = z.array(IdentifierZod).refine(isSortedUniqueStrings, 'identifiers must be sorted and unique')\n\n/** One export from the owning target plan; unique by (resourceId, owningInfrastructureId, exportContractId, exportContractVersion). */\nexport const DappManagedCapabilityExportV1Zod = z.strictObject({\n  resourceId: IdentifierZod,\n  owningInfrastructureId: DappInfrastructureIdZod,\n  producerTargetObjectIds: z.array(HashZod).min(1).refine(isSortedUniqueStrings, 'producer target object IDs must be sorted and unique'),\n  ...DappManagedCapabilityContractRefZod.shape,\n  exportIdentityHash: HashZod,\n})\nexport type DappManagedCapabilityExportV1 = z.infer<typeof DappManagedCapabilityExportV1Zod>\n\n/** One import into a consuming target plan; unique by the export key plus `consumerInfrastructureId`. */\nexport const DappManagedCapabilityImportV1Zod = z.strictObject({\n  resourceId: IdentifierZod,\n  owningInfrastructureId: DappInfrastructureIdZod,\n  consumerInfrastructureId: DappInfrastructureIdZod,\n  consumerThingIds: SortedIdentifiersZod,\n  consumerHostPartitionIds: SortedIdentifiersZod,\n  ...DappManagedCapabilityContractRefZod.shape,\n  exportIdentityHash: HashZod,\n}).refine(\n  entry => entry.consumerThingIds.length + entry.consumerHostPartitionIds.length > 0,\n  'an import must name at least one consuming thing or host partition',\n).refine(\n  entry => entry.owningInfrastructureId !== entry.consumerInfrastructureId,\n  'an import must cross infrastructure instances',\n)\nexport type DappManagedCapabilityImportV1 = z.infer<typeof DappManagedCapabilityImportV1Zod>\n\nexport function compareDappManagedCapabilityExportsV1(\n  left: DappManagedCapabilityExportV1,\n  right: DappManagedCapabilityExportV1,\n): number {\n  return compareCodeUnits(left.resourceId, right.resourceId)\n    || compareCodeUnits(left.owningInfrastructureId, right.owningInfrastructureId)\n    || compareCodeUnits(left.exportContractId, right.exportContractId)\n    || compareNumbers(left.exportContractVersion, right.exportContractVersion)\n}\n\nexport function compareDappManagedCapabilityImportsV1(\n  left: DappManagedCapabilityImportV1,\n  right: DappManagedCapabilityImportV1,\n): number {\n  return compareCodeUnits(left.resourceId, right.resourceId)\n    || compareCodeUnits(left.owningInfrastructureId, right.owningInfrastructureId)\n    || compareCodeUnits(left.consumerInfrastructureId, right.consumerInfrastructureId)\n    || compareCodeUnits(left.exportContractId, right.exportContractId)\n    || compareNumbers(left.exportContractVersion, right.exportContractVersion)\n}\n", "import {\n  bytesToHex, hexToBytes, utf8ToBytes,\n} from '@noble/hashes/utils.js'\nimport { z } from 'zod'\n\nimport { canonicalizeIJson } from './canonicalDocument.ts'\nimport { HashZod, IdentifierZod } from './identifier.ts'\nimport type { ObjectStorePutOptions } from './objectStore.ts'\nimport { normalizeObjectStoreKey } from './objectStore.ts'\nimport { decodeUtf8, hashProjectionPublicationBytes } from './projectionPublication.ts'\nimport { parseStrictJsonText } from './strictJson.ts'\n\n/** Ordinary mutable object transport, not a datalake payload or reference. */\nexport const ObjectStoreRecordZod = z.strictObject({\n  format: z.literal('dapp-kit.bound-record'),\n  formatVersion: z.literal(1),\n  storeId: IdentifierZod,\n  key: z.string().min(1).max(1024).refine(value => normalizeObjectStoreKey(value) === value),\n  bodyHex: z.string().regex(/^(?:[0-9a-f]{2})*$/u),\n  contentHash: HashZod,\n  size: z.number().int().nonnegative(),\n  metadata: z.strictObject({\n    cacheControl: z.string().max(1024).optional(),\n    contentEncoding: z.string().max(256).optional(),\n    contentType: z.string().max(256).optional(),\n    metadata: z.record(z.string().min(1).max(128), z.string().max(4096))\n      .refine(value => Object.keys(value).length <= 32).optional(),\n  }),\n})\n\n/** Bound the encoded transport independently of the decoded app bytes. */\nexport function objectStoreRecordMaximumBytes(maximumObjectBytes: number): number {\n  if (!Number.isSafeInteger(maximumObjectBytes) || maximumObjectBytes < 1 || maximumObjectBytes > 16 * 1024 * 1024) {\n    throw new RangeError('Invalid object record byte limit')\n  }\n  return maximumObjectBytes * 2 + 64 * 1024\n}\n\nexport function encodeObjectStoreRecord(\n  body: Uint8Array,\n  storeId: string,\n  key: string,\n  metadata: Pick<ObjectStorePutOptions, 'cacheControl' | 'contentEncoding' | 'contentType' | 'metadata'>,\n  maximumObjectBytes: number,\n): Uint8Array {\n  const maximum = objectStoreRecordMaximumBytes(maximumObjectBytes)\n  if (body.byteLength > maximumObjectBytes) throw new RangeError('Object record exceeds its decoded byte limit')\n  const record = ObjectStoreRecordZod.parse({\n    format: 'dapp-kit.bound-record',\n    formatVersion: 1,\n    storeId,\n    key,\n    metadata,\n    bodyHex: bytesToHex(body),\n    contentHash: hashProjectionPublicationBytes(body),\n    size: body.byteLength,\n  })\n  const encoded = utf8ToBytes(`${canonicalizeIJson(record)}\\n`)\n  if (encoded.byteLength > maximum) throw new RangeError('Object record exceeds its encoded byte limit')\n  return encoded\n}\n\n/** Store/key binding and a byte hash detect misrouting and corruption; they do\n * not authenticate an untrusted writer or replace the host's access policy. */\nexport function decodeObjectStoreRecord(body: Uint8Array, storeId: string, key: string, maximumObjectBytes: number) {\n  if (body.byteLength > objectStoreRecordMaximumBytes(maximumObjectBytes)) throw new RangeError('Object record exceeds its encoded byte limit')\n  const record = ObjectStoreRecordZod.parse(parseStrictJsonText(decodeUtf8(body)))\n  if (record.storeId !== storeId || record.key !== key) throw new TypeError('Object record belongs to a different store or key')\n  if (record.size > maximumObjectBytes || record.bodyHex.length / 2 > maximumObjectBytes) throw new RangeError('Object record exceeds its decoded byte limit')\n  const decoded = hexToBytes(record.bodyHex)\n  if (decoded.byteLength !== record.size || hashProjectionPublicationBytes(decoded) !== record.contentHash) {\n    throw new TypeError('Object record bytes do not match their size and hash')\n  }\n  return { body: decoded, metadata: { ...record.metadata, contentLength: decoded.byteLength } }\n}\n", "import { canonicalizeIJson } from './canonicalDocument.ts'\nimport {\n  DappOperationRecoveryBindingZod, DappOperationRecoveryRequirementZod, DappOperationRecoverySnapshotZod,\n} from './operationRecoveryModel.ts'\n\nexport const DappOperationRecoveryIssueCodes = [\n  'recovery.requirement-invalid',\n  'recovery.binding-invalid',\n  'recovery.snapshot-invalid',\n  'recovery.binding-mismatch',\n  'recovery.operation-mismatch',\n  'recovery.capability-mismatch',\n  'recovery.guarantee-missing',\n  'recovery.journal-not-durable',\n  'recovery.pending',\n  'recovery.uncertain',\n  'recovery.unavailable',\n  'recovery.corrupt',\n] as const\nexport type DappOperationRecoveryIssueCode = typeof DappOperationRecoveryIssueCodes[number]\n\nexport type DappOperationRecoveryAdmissionResult\n  = | { readonly success: true; readonly value: { readonly mode: 'read-only' | 'external' | 'kit-journal' } }\n    | { readonly issue: { readonly code: DappOperationRecoveryIssueCode }; readonly success: false }\n\nfunction failure(code: DappOperationRecoveryIssueCode): DappOperationRecoveryAdmissionResult {\n  return { success: false, issue: { code } }\n}\n\n/** Checks reported recovery readiness only. Success never authorizes an effect or proves durability. */\nexport function validateDappOperationRecoveryAdmission(\n  requirementValue: unknown,\n  bindingValue: unknown,\n  snapshotValue: unknown,\n): DappOperationRecoveryAdmissionResult {\n  const parsed = DappOperationRecoveryRequirementZod.safeParse(requirementValue)\n  if (!parsed.success) return failure('recovery.requirement-invalid')\n  const requirement = parsed.data\n  if (requirement.recovery.kind === 'read-only') return { success: true, value: { mode: 'read-only' } }\n  const binding = DappOperationRecoveryBindingZod.safeParse(bindingValue)\n  if (!binding.success) return failure('recovery.binding-invalid')\n  const snapshot = DappOperationRecoverySnapshotZod.safeParse(snapshotValue)\n  if (!snapshot.success) return failure('recovery.snapshot-invalid')\n  const state = snapshot.data\n  if (canonicalizeIJson(binding.data) !== canonicalizeIJson(state.binding)) return failure('recovery.binding-mismatch')\n  if (state.portId !== requirement.portId || state.operationId !== requirement.operationId) return failure('recovery.operation-mismatch')\n  if (state.capability.kind !== requirement.recovery.kind || state.capability.capabilityId !== requirement.recovery.capabilityId) {\n    return failure('recovery.capability-mismatch')\n  }\n  if (requirement.recovery.requiredGuarantees.some(guarantee => !state.capability.guarantees.includes(guarantee))) {\n    return failure('recovery.guarantee-missing')\n  }\n  if (state.capability.kind === 'kit-journal' && state.capability.journalDurability !== 'crash-durable') {\n    return failure('recovery.journal-not-durable')\n  }\n  return state.state === 'ready' ? { success: true, value: { mode: requirement.recovery.kind } } : failure(`recovery.${state.state}`)\n}\n", "import { asSchema } from '@xyo-network/sdk'\nimport { z } from 'zod'\n\nimport {\n  Base64UrlZod,\n  DappIdZod,\n  HashZod,\n  IdentifierZod,\n  ProtocolVersionZod,\n} from './identifier.ts'\nimport { JsonValueZod } from './jsonValue.ts'\nconst UnixMillisecondsZod = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)\nconst StreamSequenceZod = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)\n\nexport const PortFrameSchemaVersionZod = z.union([z.literal(1), z.literal(2)])\nexport type PortFrameSchemaVersion = z.infer<typeof PortFrameSchemaVersionZod>\n\nexport const PortFrameSchema = asSchema('network.xyo.dapp.port.frame', true)\n\nexport const PortFrameKinds = [\n  'request',\n  'response',\n  'error',\n  'cancel',\n  'cancel-ack',\n  'stream-open',\n  'stream-item',\n  'stream-credit',\n  'stream-close',\n  'stream-error',\n  'stream-resume',\n] as const\n\nexport const PortFrameKindZod = z.enum(PortFrameKinds)\nexport type PortFrameKind = z.infer<typeof PortFrameKindZod>\n\nconst PortFrameBaseFields = {\n  schema: z.literal(PortFrameSchema),\n  schemaVersion: z.literal(1),\n  dappId: DappIdZod,\n  protocolVersion: ProtocolVersionZod,\n  planId: HashZod,\n  systemInstanceId: IdentifierZod,\n  hostSessionId: IdentifierZod,\n  attachmentId: IdentifierZod,\n  requestId: IdentifierZod,\n  deadlineUnixMs: UnixMillisecondsZod,\n  portId: IdentifierZod,\n  operationId: IdentifierZod,\n}\n\nexport const PortConsistencyEvidenceZod = z.discriminatedUnion('mode', [\n  z.strictObject({ mode: z.literal('not-applicable') }),\n  z.strictObject({\n    mode: z.literal('finalized-through'),\n    blockNumber: z.number().int().nonnegative(),\n    blockHash: HashZod,\n  }),\n  z.strictObject({\n    mode: z.literal('projection-through'),\n    blockNumber: z.number().int().nonnegative(),\n    blockHash: HashZod,\n    projectionId: IdentifierZod,\n    projectionVersion: ProtocolVersionZod,\n  }),\n  z.strictObject({\n    mode: z.literal('provisional'),\n    blockNumber: z.number().int().nonnegative(),\n    blockHash: HashZod,\n    transactionHash: HashZod,\n  }),\n  z.strictObject({ mode: z.literal('local-ephemeral') }),\n])\n\nexport type PortConsistencyEvidence = z.infer<typeof PortConsistencyEvidenceZod>\n\nconst RequestFrameZod = z.strictObject({\n  ...PortFrameBaseFields,\n  frameKind: z.literal('request'),\n  body: JsonValueZod,\n})\n\nconst ResponseFrameZod = z.strictObject({\n  ...PortFrameBaseFields,\n  frameKind: z.literal('response'),\n  consistency: PortConsistencyEvidenceZod,\n  body: JsonValueZod,\n})\n\nconst ErrorFrameZod = z.strictObject({\n  ...PortFrameBaseFields,\n  frameKind: z.literal('error'),\n  error: z.strictObject({\n    code: IdentifierZod,\n    retriable: z.boolean(),\n    details: JsonValueZod.optional(),\n  }),\n})\n\nconst CancelFrameZod = z.strictObject({\n  ...PortFrameBaseFields,\n  frameKind: z.literal('cancel'),\n  reasonCode: IdentifierZod,\n})\n\nconst CancelAckFrameZod = z.strictObject({\n  ...PortFrameBaseFields,\n  frameKind: z.literal('cancel-ack'),\n  willEmitNoNewWork: z.literal(true),\n})\n\nconst StreamOpenFrameZod = z.strictObject({\n  ...PortFrameBaseFields,\n  frameKind: z.literal('stream-open'),\n  streamId: IdentifierZod,\n  delivery: z.literal('at-least-once'),\n  resumable: z.boolean(),\n  nextSequence: StreamSequenceZod,\n  resumeCursor: Base64UrlZod.optional(),\n}).superRefine((frame, context) => {\n  if (frame.resumable !== (frame.resumeCursor !== undefined)) {\n    context.addIssue({\n      code: 'custom',\n      message: 'resumable stream open must carry a durable resume cursor',\n      path: ['resumeCursor'],\n    })\n  }\n})\n\nconst StreamItemFrameZod = z.strictObject({\n  ...PortFrameBaseFields,\n  frameKind: z.literal('stream-item'),\n  streamId: IdentifierZod,\n  sequence: StreamSequenceZod,\n  resumeCursor: Base64UrlZod.optional(),\n  consistency: PortConsistencyEvidenceZod,\n  body: JsonValueZod,\n})\n\nconst StreamCreditFrameZod = z.strictObject({\n  ...PortFrameBaseFields,\n  frameKind: z.literal('stream-credit'),\n  streamId: IdentifierZod,\n  credit: z.number().int().positive().max(Number.MAX_SAFE_INTEGER),\n})\n\nconst StreamCloseFrameZod = z.strictObject({\n  ...PortFrameBaseFields,\n  frameKind: z.literal('stream-close'),\n  streamId: IdentifierZod,\n  lastSequence: StreamSequenceZod,\n  resumeCursor: Base64UrlZod.optional(),\n})\n\nconst StreamErrorFrameZod = z.strictObject({\n  ...PortFrameBaseFields,\n  frameKind: z.literal('stream-error'),\n  streamId: IdentifierZod,\n  lastSequence: StreamSequenceZod,\n  resumeCursor: Base64UrlZod.optional(),\n  error: z.strictObject({\n    code: IdentifierZod,\n    retriable: z.boolean(),\n    details: JsonValueZod.optional(),\n  }),\n})\n\nconst StreamResumeFrameZod = z.strictObject({\n  ...PortFrameBaseFields,\n  frameKind: z.literal('stream-resume'),\n  streamId: IdentifierZod,\n  lastAcceptedSequence: StreamSequenceZod,\n  resumeCursor: Base64UrlZod,\n  credit: z.number().int().positive().max(Number.MAX_SAFE_INTEGER),\n})\n\nexport const PortFrameZod = z.discriminatedUnion('frameKind', [\n  RequestFrameZod,\n  ResponseFrameZod,\n  ErrorFrameZod,\n  CancelFrameZod,\n  CancelAckFrameZod,\n  StreamOpenFrameZod,\n  StreamItemFrameZod,\n  StreamCreditFrameZod,\n  StreamCloseFrameZod,\n  StreamErrorFrameZod,\n  StreamResumeFrameZod,\n])\n\nexport type PortFrame = z.infer<typeof PortFrameZod>\n\n/** V1 stays frozen, including its canonical decoder and hash domain. */\nexport const PortFrameV1Zod = PortFrameZod\nexport type PortFrameV1 = PortFrame\n\nconst Version2 = { schemaVersion: z.literal(2) }\nconst StreamOpenV2Zod = z.strictObject({ ...StreamOpenFrameZod.shape, ...Version2 }).superRefine((frame, context) => {\n  if (frame.resumable !== (frame.resumeCursor !== undefined)) {\n    context.addIssue({\n      code: 'custom', message: 'resumable stream open must carry a durable resume cursor', path: ['resumeCursor'],\n    })\n  }\n})\n\n/** V2 progress is the absolute next sequence, so zero also represents an empty prefix. */\nexport const PortFrameV2Zod = z.discriminatedUnion('frameKind', [\n  z.strictObject({ ...RequestFrameZod.shape, ...Version2 }),\n  z.strictObject({ ...ResponseFrameZod.shape, ...Version2 }),\n  z.strictObject({ ...ErrorFrameZod.shape, ...Version2 }),\n  z.strictObject({ ...CancelFrameZod.shape, ...Version2 }),\n  z.strictObject({ ...CancelAckFrameZod.shape, ...Version2 }),\n  StreamOpenV2Zod,\n  z.strictObject({\n    ...StreamItemFrameZod.shape,\n    ...Version2,\n    sequence: StreamSequenceZod.max(Number.MAX_SAFE_INTEGER - 1),\n  }),\n  z.strictObject({ ...StreamCreditFrameZod.shape, ...Version2 }),\n  z.strictObject({\n    ...PortFrameBaseFields,\n    ...Version2,\n    frameKind: z.literal('stream-close'),\n    streamId: IdentifierZod,\n    nextSequence: StreamSequenceZod,\n    resumeCursor: Base64UrlZod.optional(),\n  }),\n  z.strictObject({\n    ...PortFrameBaseFields,\n    ...Version2,\n    frameKind: z.literal('stream-error'),\n    streamId: IdentifierZod,\n    nextSequence: StreamSequenceZod,\n    resumeCursor: Base64UrlZod.optional(),\n    error: StreamErrorFrameZod.shape.error,\n  }),\n  z.strictObject({\n    ...PortFrameBaseFields,\n    ...Version2,\n    frameKind: z.literal('stream-resume'),\n    streamId: IdentifierZod,\n    nextSequence: StreamSequenceZod,\n    resumeCursor: Base64UrlZod,\n    credit: StreamResumeFrameZod.shape.credit,\n  }),\n])\n\nexport type PortFrameV2 = z.infer<typeof PortFrameV2Zod>\nexport const PortFrameAnyVersionZod = z.discriminatedUnion('schemaVersion', [PortFrameZod, PortFrameV2Zod])\nexport type PortFrameAnyVersion = z.infer<typeof PortFrameAnyVersionZod>\n\nexport const PortOperationGrantZod = z.discriminatedUnion('streaming', [\n  z.strictObject({\n    portId: IdentifierZod,\n    operationId: IdentifierZod,\n    streaming: z.literal(false),\n  }),\n  z.strictObject({\n    portId: IdentifierZod,\n    operationId: IdentifierZod,\n    streaming: z.literal(true),\n    resumable: z.boolean(),\n    maximumCredit: z.number().int().positive().max(Number.MAX_SAFE_INTEGER),\n  }),\n])\n\nexport type PortOperationGrant = z.infer<typeof PortOperationGrantZod>\n\nexport const PortAttachmentGrantZod = z.strictObject({\n  attachmentId: IdentifierZod,\n  principalId: IdentifierZod,\n  dappId: DappIdZod,\n  protocolVersion: ProtocolVersionZod,\n  planId: HashZod,\n  systemInstanceId: IdentifierZod,\n  hostSessionId: IdentifierZod,\n  createdAt: UnixMillisecondsZod,\n  lastSeenAt: UnixMillisecondsZod,\n  expiresAt: UnixMillisecondsZod,\n  leasePolicy: z.enum(['fixed-expiry', 'disconnect-expiry']),\n  operations: z.array(PortOperationGrantZod),\n}).superRefine((grant, context) => {\n  const operations = grant.operations.map(operation => `${operation.portId}.${operation.operationId}`)\n  const unique = new Set(operations)\n  if (unique.size !== operations.length) {\n    context.addIssue({\n      code: 'custom', message: 'operation grants must be unique', path: ['operations'],\n    })\n  }\n  if (grant.lastSeenAt < grant.createdAt || grant.expiresAt <= grant.createdAt) {\n    context.addIssue({\n      code: 'custom', message: 'attachment lifetime is invalid', path: ['expiresAt'],\n    })\n  }\n})\n\nexport type PortAttachmentGrant = z.infer<typeof PortAttachmentGrantZod>\n", "import type { PortFrameAnyVersion, PortFrameSchemaVersion } from './portFrameModel.ts'\n\nexport const PortStreamProgressUnsupportedCode = 'port.stream-progress-unsupported' as const\n\nexport function portStreamResumeNextSequence(frame: Extract<PortFrameAnyVersion, { frameKind: 'stream-resume' }>): number {\n  const next = frame.schemaVersion === 2 ? frame.nextSequence : frame.lastAcceptedSequence + 1\n  if (!Number.isSafeInteger(next)) throw new RangeError('stream resume successor exceeds safe integer progress')\n  return next\n}\n\nexport function portStreamTerminalProgress(version: PortFrameSchemaVersion, nextSequence: number) {\n  if (version === 2) return { nextSequence }\n  if (nextSequence === 0) throw new RangeError('V1 cannot represent terminal progress before sequence zero')\n  return { lastSequence: nextSequence - 1 }\n}\n\nexport function portStreamTerminalMatches(\n  frame: Extract<PortFrameAnyVersion, { frameKind: 'stream-close' | 'stream-error' }>,\n  nextSequence: number,\n): boolean {\n  return frame.schemaVersion === 2\n    ? frame.nextSequence === nextSequence\n    : nextSequence > 0 && frame.lastSequence === nextSequence - 1\n}\n", "import { z } from 'zod'\n\nimport { canonicalizeIJson } from './canonicalDocument.ts'\nimport type {\n  PortAttachmentGrant,\n  PortFrameAnyVersion as PortFrame,\n  PortFrameSchemaVersion,\n  PortOperationGrant,\n} from './portFrameModel.ts'\nimport { PortFrameAnyVersionZod } from './portFrameModel.ts'\nimport {\n  PortStreamProgressUnsupportedCode, portStreamResumeNextSequence, portStreamTerminalMatches,\n} from './portFrameProgress.ts'\n\nexport const PortFrameIssueCodes = [\n  'port.after-terminal',\n  'port.attachment-expired',\n  'port.attachment-mismatch',\n  'port.credit-exceeded',\n  'port.dapp-id-mismatch',\n  'port.deadline-expired',\n  'port.duplicate-terminal',\n  'port.host-session-mismatch',\n  'port.frame-version-mismatch',\n  'port.invalid',\n  'port.operation-not-granted',\n  'port.principal-mismatch',\n  'port.protocol-version-mismatch',\n  'port.request-mismatch',\n  'port.resume-not-supported',\n  'port.stale-incarnation',\n  'port.stale-plan',\n  'port.stream-mismatch',\n  'port.stream-not-granted',\n  'port.stream-sequence-invalid',\n  'port.terminal-missing',\n] as const\n\nexport const PortFrameIssueCodeZod = z.enum(PortFrameIssueCodes)\nexport type PortFrameIssueCode = z.infer<typeof PortFrameIssueCodeZod>\n\nexport interface PortFrameIssue {\n  code: PortFrameIssueCode\n  message: string\n  path: (number | string)[]\n}\n\nexport interface PortFrameValidationContext {\n  authenticatedPrincipalId: string\n  frameSchemaVersion?: PortFrameSchemaVersion\n  grant: PortAttachmentGrant\n  now: number\n}\n\nexport interface PortFrameValidationFailure {\n  issues: PortFrameIssue[]\n  success: false\n}\n\nexport interface PortFrameValidationSuccess<T> {\n  success: true\n  value: T\n}\n\nexport type PortFrameValidationResult<T> = PortFrameValidationFailure | PortFrameValidationSuccess<T>\n\nfunction issue(code: PortFrameIssueCode, message: string, path: (number | string)[]): PortFrameIssue {\n  return {\n    code, message, path,\n  }\n}\n\nfunction issuePath(path: PropertyKey[]): (number | string)[] {\n  return path.map(value => typeof value === 'symbol' ? value.description ?? value.toString() : value)\n}\n\nfunction operationGrant(frame: PortFrame, grant: PortAttachmentGrant): PortOperationGrant | undefined {\n  return grant.operations.find(operation => operation.portId === frame.portId && operation.operationId === frame.operationId)\n}\n\nfunction identityIssues(frame: PortFrame, context: PortFrameValidationContext): PortFrameIssue[] {\n  const { grant } = context\n  const issues: PortFrameIssue[] = []\n  if (frame.schemaVersion !== (context.frameSchemaVersion ?? 1)) {\n    issues.push(issue('port.frame-version-mismatch', 'frame schema version does not match the selected attachment protocol', ['schemaVersion']))\n  }\n  if (frame.dappId !== grant.dappId) {\n    issues.push(issue('port.dapp-id-mismatch', 'frame dApp does not match attachment grant', ['dappId']))\n  }\n  if (frame.protocolVersion !== grant.protocolVersion) {\n    issues.push(issue('port.protocol-version-mismatch', 'frame protocol does not match attachment grant', ['protocolVersion']))\n  }\n  if (frame.planId !== grant.planId) {\n    issues.push(issue('port.stale-plan', 'frame plan does not match attachment grant', ['planId']))\n  }\n  if (frame.systemInstanceId !== grant.systemInstanceId) {\n    issues.push(issue('port.stale-incarnation', 'frame targets a different system incarnation', ['systemInstanceId']))\n  }\n  if (frame.hostSessionId !== grant.hostSessionId) {\n    issues.push(issue('port.host-session-mismatch', 'frame host session does not match attachment grant', ['hostSessionId']))\n  }\n  if (frame.attachmentId !== grant.attachmentId) {\n    issues.push(issue('port.attachment-mismatch', 'frame attachment does not match attachment grant', ['attachmentId']))\n  }\n  if (context.authenticatedPrincipalId !== grant.principalId) {\n    issues.push(issue('port.principal-mismatch', 'transport principal does not own attachment grant', []))\n  }\n  return issues\n}\n\nfunction lifetimeIssues(frame: PortFrame, context: PortFrameValidationContext): PortFrameIssue[] {\n  const issues: PortFrameIssue[] = []\n  if (context.now > context.grant.expiresAt) {\n    issues.push(issue('port.attachment-expired', 'attachment lease has expired', []))\n  }\n  if (context.now > frame.deadlineUnixMs) {\n    issues.push(issue('port.deadline-expired', 'frame deadline has expired', ['deadlineUnixMs']))\n  }\n  return issues\n}\n\nfunction grantIssues(frame: PortFrame, context: PortFrameValidationContext): PortFrameIssue[] {\n  const grant = operationGrant(frame, context.grant)\n  if (grant === undefined) {\n    return [issue('port.operation-not-granted', 'operation is not registered for this attachment', ['operationId'])]\n  }\n  const isStreamFrame = frame.frameKind.startsWith('stream-')\n  if (isStreamFrame && !grant.streaming) {\n    return [issue('port.stream-not-granted', 'unary operation cannot accept stream frames', ['frameKind'])]\n  }\n  if (frame.frameKind === 'stream-resume' && grant.streaming && !grant.resumable) {\n    return [issue('port.resume-not-supported', 'operation has no durable resume cursor contract', ['frameKind'])]\n  }\n  return (frame.frameKind === 'stream-credit' || frame.frameKind === 'stream-resume')\n    && grant.streaming && frame.credit > grant.maximumCredit\n    ? [issue('port.credit-exceeded', 'frame credit exceeds attachment grant maximum', ['credit'])]\n    : []\n}\n\nexport function validatePortFrame(value: unknown, context: PortFrameValidationContext): PortFrameValidationResult<PortFrame> {\n  const result = PortFrameAnyVersionZod.safeParse(value)\n  if (!result.success) {\n    return {\n      issues: result.error.issues.map(value => issue('port.invalid', value.message, issuePath(value.path))),\n      success: false,\n    }\n  }\n  const frame = result.data\n  const issues = [\n    ...identityIssues(frame, context),\n    ...lifetimeIssues(frame, context),\n    ...grantIssues(frame, context),\n  ]\n  if (frame.frameKind === 'stream-resume') {\n    try {\n      portStreamResumeNextSequence(frame)\n    } catch {\n      issues.push(issue('port.stream-sequence-invalid', 'resume successor exceeds safe integer progress', ['lastAcceptedSequence']))\n    }\n  }\n  return issues.length > 0\n    ? { issues, success: false }\n    : { success: true, value: frame }\n}\n\nfunction commonTranscriptIssues(frames: readonly PortFrame[]): PortFrameIssue[] {\n  const issues: PortFrameIssue[] = []\n  const first = frames[0]\n  if (first === undefined) return [issue('port.terminal-missing', 'transcript is empty', [])]\n  for (const [index, frame] of frames.entries()) {\n    if (frame.requestId !== first.requestId\n      || frame.portId !== first.portId\n      || frame.operationId !== first.operationId) {\n      issues.push(issue('port.request-mismatch', 'transcript frames must bind one request and operation', [index]))\n    }\n  }\n  return issues\n}\n\nfunction unaryTranscriptIssues(frames: readonly PortFrame[]): PortFrameIssue[] {\n  const issues: PortFrameIssue[] = []\n  let isTerminal = false\n  let terminalCount = 0\n  for (const [index, frame] of frames.entries()) {\n    if (index === 0 && frame.frameKind !== 'request') {\n      issues.push(issue('port.request-mismatch', 'unary transcript must begin with request', [index]))\n    }\n    if (index > 0 && frame.frameKind === 'request') {\n      issues.push(issue('port.request-mismatch', 'request may appear only once', [index]))\n    }\n    if (isTerminal) issues.push(issue('port.after-terminal', 'no frame may follow terminal response or cancel acknowledgement', [index]))\n    if (frame.frameKind === 'response' || frame.frameKind === 'error' || frame.frameKind === 'cancel-ack') {\n      terminalCount += 1\n      isTerminal = true\n    }\n  }\n  if (terminalCount === 0) issues.push(issue('port.terminal-missing', 'request has no terminal response, error, or cancel acknowledgement', []))\n  if (terminalCount > 1) issues.push(issue('port.duplicate-terminal', 'request has multiple terminal frames', []))\n  return issues\n}\n\ninterface StreamTranscriptState {\n  availableCredit: number\n  expectedSequence: number\n  isOpen: boolean\n  isTerminal: boolean\n  itemBodies: Map<number, string>\n  readonly resumeExpectedSequence?: number\n  streamId?: string\n}\n\ntype StreamFrame = Extract<PortFrame, { streamId: string }>\n\nfunction isStreamFrame(frame: PortFrame): frame is StreamFrame {\n  return 'streamId' in frame\n}\n\nfunction initialStreamState(first: PortFrame): StreamTranscriptState {\n  return {\n    availableCredit: first.frameKind === 'stream-resume' ? first.credit : 0,\n    expectedSequence: first.frameKind === 'stream-resume' ? portStreamResumeNextSequence(first) : 0,\n    isOpen: false,\n    isTerminal: false,\n    itemBodies: new Map(),\n    resumeExpectedSequence: first.frameKind === 'stream-resume' ? portStreamResumeNextSequence(first) : undefined,\n    streamId: first.frameKind === 'stream-resume' ? first.streamId : undefined,\n  }\n}\n\nfunction streamIdentityIssues(frame: PortFrame, index: number, state: StreamTranscriptState): PortFrameIssue[] {\n  if (!isStreamFrame(frame) || frame.frameKind === 'stream-resume') return []\n  if (state.streamId !== undefined && frame.streamId !== state.streamId) {\n    return [issue('port.stream-mismatch', 'stream frame targets another stream', [index, 'streamId'])]\n  }\n  state.streamId = frame.streamId\n  return []\n}\n\nfunction streamItemIssues(\n  frame: Extract<PortFrame, { frameKind: 'stream-item' }>,\n  index: number,\n  grant: Extract<PortOperationGrant, { streaming: true }>,\n  state: StreamTranscriptState,\n): PortFrameIssue[] {\n  const issues: PortFrameIssue[] = []\n  if (!state.isOpen) issues.push(issue('port.stream-sequence-invalid', 'stream item arrived before stream open', [index]))\n  if (state.availableCredit === 0) {\n    issues.push(issue('port.credit-exceeded', 'stream item arrived without receiver credit', [index]))\n  } else {\n    state.availableCredit -= 1\n  }\n  const priorBody = state.itemBodies.get(frame.sequence)\n  const body = canonicalizeIJson({\n    body: frame.body, consistency: frame.consistency, resumeCursor: frame.resumeCursor ?? null,\n  })\n  if (priorBody !== undefined && priorBody !== body) {\n    issues.push(issue('port.stream-sequence-invalid', 'duplicate stream sequence changed its content', [index, 'sequence']))\n  } else if (priorBody === undefined && frame.sequence !== state.expectedSequence) {\n    issues.push(issue('port.stream-sequence-invalid', 'new stream item sequence is not the next expected value', [index, 'sequence']))\n  } else if (priorBody === undefined) {\n    state.itemBodies.set(frame.sequence, body)\n    state.expectedSequence += 1\n  }\n  if (grant.resumable && frame.resumeCursor === undefined) {\n    issues.push(issue('port.resume-not-supported', 'resumable stream item lacks durable cursor', [index, 'resumeCursor']))\n  }\n  return issues\n}\n\nfunction streamOpenIssues(\n  frame: Extract<PortFrame, { frameKind: 'stream-open' }>,\n  index: number,\n  grant: Extract<PortOperationGrant, { streaming: true }>,\n  state: StreamTranscriptState,\n): PortFrameIssue[] {\n  const issues: PortFrameIssue[] = []\n  if (state.isOpen || frame.resumable !== grant.resumable) {\n    issues.push(issue('port.stream-sequence-invalid', 'stream open is duplicated or conflicts with grant', [index]))\n  }\n  if (state.resumeExpectedSequence !== undefined && frame.nextSequence !== state.resumeExpectedSequence) {\n    issues.push(issue('port.stream-sequence-invalid', 'stream open does not continue the requested resume sequence', [index, 'nextSequence']))\n  }\n  state.isOpen = true\n  state.expectedSequence = frame.nextSequence\n  return issues\n}\n\nfunction streamFrameIssues(\n  frame: PortFrame,\n  index: number,\n  grant: Extract<PortOperationGrant, { streaming: true }>,\n  state: StreamTranscriptState,\n): PortFrameIssue[] {\n  const issues: PortFrameIssue[] = []\n  if (state.isTerminal) issues.push(issue('port.after-terminal', 'no stream frame may follow a terminal frame', [index]))\n  issues.push(...streamIdentityIssues(frame, index, state))\n  if (frame.frameKind === 'error') {\n    if (state.isOpen && frame.error.code !== PortStreamProgressUnsupportedCode) {\n      issues.push(issue('port.stream-sequence-invalid', 'an open stream must terminate with stream-error', [index]))\n    }\n    state.isTerminal = true\n    return issues\n  }\n  if (frame.frameKind === 'stream-open') {\n    issues.push(...streamOpenIssues(frame, index, grant, state))\n  }\n  if (frame.frameKind === 'stream-credit') {\n    state.availableCredit += frame.credit\n    if (state.availableCredit > grant.maximumCredit) {\n      issues.push(issue('port.credit-exceeded', 'outstanding stream credit exceeds the attachment grant', [index, 'credit']))\n    }\n  }\n  if (frame.frameKind === 'stream-item') issues.push(...streamItemIssues(frame, index, grant, state))\n  if ((frame.frameKind === 'stream-close' || frame.frameKind === 'stream-error')\n    && !portStreamTerminalMatches(frame, state.expectedSequence)) {\n    issues.push(issue('port.stream-sequence-invalid', 'terminal stream progress does not match accepted items', [index, frame.schemaVersion === 2 ? 'nextSequence' : 'lastSequence']))\n  }\n  if (frame.frameKind === 'stream-close' || frame.frameKind === 'stream-error'\n    || frame.frameKind === 'cancel-ack') {\n    state.isTerminal = true\n  }\n  return issues\n}\n\nfunction streamTranscriptIssues(frames: readonly PortFrame[], grant: Extract<PortOperationGrant, { streaming: true }>): PortFrameIssue[] {\n  const issues: PortFrameIssue[] = []\n  const first = frames[0]\n  if (first === undefined) return [issue('port.terminal-missing', 'stream transcript is empty', [])]\n  if (first.frameKind !== 'request' && first.frameKind !== 'stream-resume') {\n    issues.push(issue('port.request-mismatch', 'stream transcript must begin with request or resume', [0]))\n  }\n  const state = initialStreamState(first)\n  for (const [index, frame] of frames.entries()) {\n    if (index === 0) continue\n    issues.push(...streamFrameIssues(frame, index, grant, state))\n  }\n  if (!state.isTerminal) issues.push(issue('port.terminal-missing', 'stream transcript has no close, error, or cancel acknowledgement', []))\n  return issues\n}\n\nexport function validatePortTranscript(\n  values: readonly unknown[],\n  context: PortFrameValidationContext,\n): PortFrameValidationResult<PortFrame[]> {\n  const frames: PortFrame[] = []\n  const issues: PortFrameIssue[] = []\n  for (const [index, value] of values.entries()) {\n    const result = validatePortFrame(value, context)\n    if (result.success) frames.push(result.value)\n    else issues.push(...result.issues.map(value => ({ ...value, path: [index, ...value.path] })))\n  }\n  if (issues.length > 0) return { issues, success: false }\n  issues.push(...commonTranscriptIssues(frames))\n  const first = frames[0]\n  if (first !== undefined) {\n    const grant = operationGrant(first, context.grant)\n    if (grant?.streaming === true) issues.push(...streamTranscriptIssues(frames, grant))\n    else issues.push(...unaryTranscriptIssues(frames))\n  }\n  return issues.length > 0\n    ? { issues, success: false }\n    : { success: true, value: frames }\n}\n", "import { asSchema } from '@xyo-network/sdk'\nimport { z } from 'zod'\n\nimport {\n  DappIdZod,\n  HashZod,\n  IdentifierZod,\n  ProtocolVersionZod,\n  Xl1ChainIdZod,\n  XyoSchemaZod,\n} from './identifier.ts'\nimport { JsonObjectZod } from './jsonValue.ts'\nexport const ProjectionCheckpointSchema = asSchema('network.xyo.dapp.projection.checkpoint', true)\n\nexport const ProjectionPositionZod = z.strictObject({\n  blockNumber: z.number().int().nonnegative(),\n  blockHash: HashZod,\n  transactionIndex: z.number().int().nonnegative(),\n  transactionHash: HashZod,\n  payloadIndex: z.number().int().nonnegative(),\n  payloadHash: HashZod,\n  recordIndex: z.number().int().nonnegative(),\n})\n\nexport type ProjectionPosition = z.infer<typeof ProjectionPositionZod>\n\nexport const ProjectionScopeZod = z.strictObject({\n  dappId: DappIdZod,\n  chainId: Xl1ChainIdZod,\n  projectionId: IdentifierZod,\n  projectionVersion: ProtocolVersionZod,\n})\n\nexport type ProjectionScope = z.infer<typeof ProjectionScopeZod>\n\nexport const ProjectionCheckpointZod = z.strictObject({\n  schema: z.literal(ProjectionCheckpointSchema),\n  schemaVersion: z.literal(1),\n  dappId: DappIdZod,\n  chainId: Xl1ChainIdZod,\n  position: ProjectionPositionZod,\n  projectionId: IdentifierZod,\n  projectionVersion: ProtocolVersionZod,\n  generationId: IdentifierZod,\n})\n\nexport type ProjectionCheckpoint = z.infer<typeof ProjectionCheckpointZod>\n\nexport const ProjectionReducerTraceSchema = asSchema('network.xyo.dapp.projection.reducer.trace', true)\nexport const ProjectionGenerationSchema = asSchema('network.xyo.dapp.projection.generation', true)\nexport const ProjectionHeadSchema = asSchema('network.xyo.dapp.projection.head', true)\nexport const ProjectionPublicationTraceSchema = asSchema('network.xyo.dapp.projection.publication.trace', true)\n\nexport const ProjectionInputRecordZod = z.strictObject({\n  eventId: IdentifierZod,\n  schema: XyoSchemaZod,\n  protocolVersion: ProtocolVersionZod,\n  position: ProjectionPositionZod,\n  payloadHash: HashZod,\n  body: JsonObjectZod,\n})\n\nexport type ProjectionInputRecord = z.infer<typeof ProjectionInputRecordZod>\n\nexport const ProjectionReducerResultZod = z.discriminatedUnion('outcome', [\n  z.strictObject({\n    outcome: z.literal('applied'),\n    state: JsonObjectZod,\n    facts: z.array(JsonObjectZod),\n  }),\n  z.strictObject({\n    outcome: z.literal('duplicate'),\n    state: JsonObjectZod,\n    duplicateOf: IdentifierZod,\n  }),\n  z.strictObject({\n    outcome: z.literal('rejected'),\n    state: JsonObjectZod,\n    issueCode: IdentifierZod,\n  }),\n])\n\nexport type ProjectionReducerResult = z.infer<typeof ProjectionReducerResultZod>\n\nexport const ProjectionReducerStepZod = z.strictObject({\n  record: ProjectionInputRecordZod,\n  result: ProjectionReducerResultZod,\n})\n\nexport type ProjectionReducerStep = z.infer<typeof ProjectionReducerStepZod>\n\nexport const ProjectionReducerTraceZod = z.strictObject({\n  schema: z.literal(ProjectionReducerTraceSchema),\n  schemaVersion: z.literal(1),\n  dappId: DappIdZod,\n  chainId: Xl1ChainIdZod,\n  projectionId: IdentifierZod,\n  projectionVersion: ProtocolVersionZod,\n  initialState: JsonObjectZod,\n  steps: z.array(ProjectionReducerStepZod),\n  finalState: JsonObjectZod,\n})\n\nexport type ProjectionReducerTrace = z.infer<typeof ProjectionReducerTraceZod>\n\nexport const ProjectionObjectReferenceZod = z.strictObject({\n  key: IdentifierZod,\n  contentHash: HashZod,\n})\n\nexport type ProjectionObjectReference = z.infer<typeof ProjectionObjectReferenceZod>\n\nexport const ProjectionGenerationZod = z.strictObject({\n  schema: z.literal(ProjectionGenerationSchema),\n  schemaVersion: z.literal(1),\n  dappId: DappIdZod,\n  chainId: Xl1ChainIdZod,\n  projectionId: IdentifierZod,\n  projectionVersion: ProtocolVersionZod,\n  generationId: IdentifierZod,\n  targetPosition: ProjectionPositionZod,\n  stateHash: HashZod,\n  objects: z.array(ProjectionObjectReferenceZod).min(1),\n}).superRefine((generation, context) => {\n  const keys = generation.objects.map(object => object.key)\n  const unique = new Set(keys)\n  if (unique.size !== keys.length) {\n    context.addIssue({\n      code: 'custom', message: 'generation object keys must be unique', path: ['objects'],\n    })\n  }\n})\n\nexport type ProjectionGeneration = z.infer<typeof ProjectionGenerationZod>\n\nexport const ProjectionHeadZod = z.strictObject({\n  schema: z.literal(ProjectionHeadSchema),\n  schemaVersion: z.literal(1),\n  dappId: DappIdZod,\n  chainId: Xl1ChainIdZod,\n  projectionId: IdentifierZod,\n  projectionVersion: ProtocolVersionZod,\n  generationId: IdentifierZod,\n  generationHash: HashZod,\n  previousGenerationId: IdentifierZod.optional(),\n})\n\nexport type ProjectionHead = z.infer<typeof ProjectionHeadZod>\n\nexport const ProjectionPublicationOperationZod = z.discriminatedUnion('kind', [\n  z.strictObject({\n    kind: z.literal('generation-written'),\n    generationId: IdentifierZod,\n    generationHash: HashZod,\n  }),\n  z.strictObject({\n    kind: z.literal('generation-verified'),\n    generationId: IdentifierZod,\n    generationHash: HashZod,\n  }),\n  z.strictObject({ kind: z.literal('head-published'), head: ProjectionHeadZod }),\n  z.strictObject({ kind: z.literal('checkpoint-persisted'), checkpoint: ProjectionCheckpointZod }),\n  z.strictObject({ kind: z.literal('interrupted'), reason: IdentifierZod }),\n])\n\nexport type ProjectionPublicationOperation = z.infer<typeof ProjectionPublicationOperationZod>\n\nexport const ProjectionPublicationTraceZod = z.strictObject({\n  schema: z.literal(ProjectionPublicationTraceSchema),\n  schemaVersion: z.literal(1),\n  initialHead: ProjectionHeadZod.optional(),\n  generation: ProjectionGenerationZod,\n  expectedGenerationHash: HashZod,\n  operations: z.array(ProjectionPublicationOperationZod),\n})\n\nexport type ProjectionPublicationTrace = z.infer<typeof ProjectionPublicationTraceZod>\n", "import { asSchema } from '@xyo-network/sdk'\nimport { z } from 'zod'\n\nimport { IdentifierZod } from './identifier.ts'\nimport type { ObjectStoreWriter } from './objectStore.ts'\nimport type { ProjectionPosition } from './projection.ts'\nimport { ProjectionPositionZod } from './projection.ts'\nimport type {\n  ProjectionPublicationObject,\n  PublishedProjection,\n  PublishedProjectionScope,\n  PublishedProjectionSource,\n} from './projectionPublication.ts'\nimport {\n  decodeUtf8,\n  PublishedProjectionHeadKey,\n  PublishedProjectionScopeZod,\n  publishProjectionGeneration,\n  readPublishedProjection,\n  resolvePublishedProjectionObject,\n} from './projectionPublication.ts'\nimport { compareProjectionPositions } from './projectionValidation.ts'\nexport const ProjectionReplayCheckpointSchema = asSchema('network.xyo.dapp.projection.replay.checkpoint', true)\n\n/**\n * The durable watermark the engine persists after a verified head advance. It\n * names the exact finalized position covered, the floor the replay started\n * from, and the last indexed block, so a fresh incarnation resumes from\n * finalized state rather than re-deriving blindly.\n */\nexport const ProjectionReplayCheckpointZod = z.strictObject({\n  schema: z.literal(ProjectionReplayCheckpointSchema),\n  schemaVersion: z.literal(1),\n  ...PublishedProjectionScopeZod.shape,\n  generationId: IdentifierZod,\n  cursor: ProjectionPositionZod,\n  floorBlock: z.number().int().nonnegative(),\n  lastIndexedBlock: z.number().int().nonnegative(),\n})\n\nexport type ProjectionReplayCheckpoint = z.infer<typeof ProjectionReplayCheckpointZod>\n\n/** One finalized input, tagged with the canonical position that orders it. */\nexport interface ReplayRecord<TRecord> {\n  readonly position: ProjectionPosition\n  readonly value: TRecord\n}\n\n/**\n * A finalized-only forward source. `latest` reports the finalized position\n * through which the next read can prove coverage; `readAfter` returns every\n * finalized record strictly after the cursor through that position, in\n * canonical order. An empty result therefore proves that the entire range is\n * records-free. Both read finalized state alone \u2014 a replay must never observe\n * an unfinalized block.\n */\nexport interface FinalizedReplaySource<TRecord> {\n  latest(): Promise<ProjectionPosition>\n  readAfter(cursor: ProjectionPosition | undefined): Promise<readonly ReplayRecord<TRecord>[]>\n}\n\n/** The immutable objects and provenance a reducer emits for one generation. */\nexport interface ProjectionReducerGeneration {\n  readonly objects: readonly ProjectionPublicationObject[]\n  readonly source?: PublishedProjectionSource\n}\n\n/**\n * The application-owned deterministic fold. The engine owns replay, checkpoint,\n * head-last publication, and rebuild; the reducer owns only what the state is,\n * how a record changes it, and how it materializes into published objects. It\n * must be a pure function of the finalized input: the same records always fold\n * to the same state and the same generation objects.\n */\nexport interface ProjectionReducer<TRecord, TState> {\n  readonly initialState: TState\n  deserialize(body: Uint8Array): TState\n  materialize(state: TState, target: ProjectionPosition): ProjectionReducerGeneration\n  reduce(state: TState, record: ReplayRecord<TRecord>): TState\n  /** Serialize the resumable state so a later incarnation can rehydrate it. */\n  serialize(state: TState): string\n}\n\nexport interface ProjectionReplayProgress {\n  readonly finalizedHead: number\n  readonly lag: number\n  readonly processed: number\n  readonly target: number\n}\n\nexport type ProjectionReplayStatus = 'advanced' | 'idle'\n\nexport interface ProjectionReplayResult {\n  readonly checkpoint?: ProjectionReplayCheckpoint\n  readonly generationId?: string\n  readonly head?: PublishedProjection\n  readonly progress: ProjectionReplayProgress\n  readonly status: ProjectionReplayStatus\n}\n\nexport interface ProjectionReplayEngineOptions<TRecord, TState> {\n  readonly checkpointKey: string\n  readonly checkpointStoreId: string\n  readonly floorBlock: number\n  /** Deterministic generation identity from the covered position. */\n  readonly generationId: (target: ProjectionPosition) => string\n  readonly headStoreId: string\n  readonly reducer: ProjectionReducer<TRecord, TState>\n  readonly scope: PublishedProjectionScope\n  readonly source: FinalizedReplaySource<TRecord>\n  /** Reserved logical key for the resumable serialized state. */\n  readonly stateKey?: string\n  /** Store the resumable state lands in; defaults to the head store. */\n  readonly stateStoreId?: string\n  readonly stores: Readonly<Record<string, ObjectStoreWriter>>\n}\n\nexport class ProjectionReplayError extends Error {\n  readonly kind: string\n\n  constructor(kind: string, message: string) {\n    super(message)\n    this.name = 'ProjectionReplayError'\n    this.kind = kind\n  }\n}\n\nconst DefaultStateKey = 'state.json'\n\ninterface ResumeState<TState> {\n  readonly cursor: ProjectionPosition | undefined\n  readonly state: TState\n}\n\n/**\n * The productized finalized-replay projection engine (use case UC-05).\n *\n * It resumes from a durable checkpoint, folds finalized records forward through\n * a caller-supplied deterministic reducer, writes an immutable generation, and\n * advances the published head last. A crash between the generation write and\n * the head advance leaves the new generation invisible: the next incarnation\n * re-derives from the checkpoint and reproduces it. Deleting the head and\n * checkpoint and rebuilding reproduces the identical head from finalized input\n * alone, because both replay and reduction are pure functions of that input.\n *\n * The engine performs no chain, datalake, or filesystem I/O itself. Its only\n * effects run through the injected finalized source and object stores, so the\n * same neutral engine drives a local filesystem projection or a hosted\n * object-store projection without change.\n */\nexport class ProjectionReplayEngine<TRecord, TState> {\n  readonly #options: ProjectionReplayEngineOptions<TRecord, TState>\n  readonly #stateKey: string\n  readonly #stateStoreId: string\n\n  constructor(options: ProjectionReplayEngineOptions<TRecord, TState>) {\n    this.#options = options\n    this.#stateKey = options.stateKey ?? DefaultStateKey\n    this.#stateStoreId = options.stateStoreId ?? options.headStoreId\n  }\n\n  /**\n   * Advance the projection to the current finalized head, publishing at most one\n   * new generation. A records-free range publishes a deterministic no-state-\n   * change generation at its covered position so the durable cursor can advance.\n   * Returns `idle` only when the published head already covers the finalized\n   * input and no new records exist.\n   */\n  async advance(signal?: AbortSignal): Promise<ProjectionReplayResult> {\n    const published = await readPublishedProjection({\n      expectedScope: this.#options.scope,\n      headStore: this.#headStore(),\n    })\n    const resume = await this.#resume(published)\n    const target = await this.#options.source.latest()\n    const records = await this.#options.source.readAfter(resume.cursor)\n\n    let state = resume.state\n    let processed = resume.cursor\n    for (const record of records) {\n      state = this.#options.reducer.reduce(state, record)\n      processed = record.position\n    }\n\n    if (records.length === 0) {\n      const coveredBlock = resume.cursor?.blockNumber ?? this.#options.floorBlock\n      if (target.blockNumber < coveredBlock) {\n        throw new ProjectionReplayError(\n          'target-regression',\n          `finalized replay target ${target.blockNumber} is behind durable coverage ${coveredBlock}`,\n        )\n      }\n      if (target.blockNumber > coveredBlock) {\n        return await this.#publish(state, target, target, published, signal)\n      }\n      return {\n        head: published, progress: progressFor(target, processed, this.#options.floorBlock), status: 'idle',\n      }\n    }\n    if (processed === undefined) throw new ProjectionReplayError('no-position', 'folded records without a position')\n    return await this.#publish(state, processed, target, published, signal)\n  }\n\n  async readCheckpoint(): Promise<ProjectionReplayCheckpoint | undefined> {\n    const body = await this.#checkpointStore().get(this.#options.checkpointKey)\n    if (body === undefined) return undefined\n    const checkpoint = ProjectionReplayCheckpointZod.parse(JSON.parse(decodeUtf8(body)))\n    if (!scopeMatches(this.#options.scope, checkpoint)) {\n      throw new ProjectionReplayError('scope-mismatch', 'durable checkpoint belongs to a different projection scope')\n    }\n    return checkpoint\n  }\n\n  /**\n   * Delete the published head and durable checkpoint, then rebuild from the\n   * floor. Immutable generation objects that already exist are rewritten with\n   * identical bytes, and the reproduced head is byte-for-byte identical to the\n   * head this projection last advanced to.\n   */\n  async rebuild(signal?: AbortSignal): Promise<ProjectionReplayResult> {\n    await this.#headStore().delete(PublishedProjectionHeadKey)\n    await this.#checkpointStore().delete(this.#options.checkpointKey)\n    return await this.advance(signal)\n  }\n\n  #checkpointStore(): ObjectStoreWriter {\n    return this.#store(this.#options.checkpointStoreId)\n  }\n\n  #headStore(): ObjectStoreWriter {\n    return this.#store(this.#options.headStoreId)\n  }\n\n  async #persistCheckpoint(\n    generationId: string,\n    processed: ProjectionPosition,\n  ): Promise<ProjectionReplayCheckpoint> {\n    const checkpoint = ProjectionReplayCheckpointZod.parse({\n      schema: ProjectionReplayCheckpointSchema,\n      schemaVersion: 1,\n      ...this.#options.scope,\n      generationId,\n      cursor: processed,\n      floorBlock: this.#options.floorBlock,\n      lastIndexedBlock: processed.blockNumber,\n    })\n    await this.#checkpointStore().put(this.#options.checkpointKey, `${JSON.stringify(checkpoint)}\\n`, { contentType: 'application/json' })\n    return checkpoint\n  }\n\n  async #publish(\n    state: TState,\n    processed: ProjectionPosition,\n    target: ProjectionPosition,\n    published: PublishedProjection | undefined,\n    signal: AbortSignal | undefined,\n  ): Promise<ProjectionReplayResult> {\n    const materialized = this.#options.reducer.materialize(state, processed)\n    const generationId = this.#options.generationId(processed)\n    const result = await publishProjectionGeneration({\n      ...(published !== undefined && { expected: published }),\n      generationId,\n      headStoreId: this.#options.headStoreId,\n      objects: [...materialized.objects, this.#stateObject(state)],\n      scope: this.#options.scope,\n      ...(signal !== undefined && { signal }),\n      ...(materialized.source !== undefined && { source: materialized.source }),\n      stores: this.#options.stores,\n    })\n    if (!result.ok) {\n      throw new ProjectionReplayError(result.conflict.kind, `projection head advance failed: ${result.conflict.message}`)\n    }\n    const checkpoint = await this.#persistCheckpoint(generationId, processed)\n    return {\n      checkpoint,\n      generationId,\n      head: result,\n      progress: progressFor(target, processed, this.#options.floorBlock),\n      status: 'advanced',\n    }\n  }\n\n  async #resume(published: PublishedProjection | undefined): Promise<ResumeState<TState>> {\n    const fresh: ResumeState<TState> = { cursor: undefined, state: this.#options.reducer.initialState }\n    if (published === undefined) return fresh\n    const checkpoint = await this.readCheckpoint()\n    // A torn write can leave a checkpoint and head that name different\n    // generations. Rather than trust either, re-derive from the floor; a pure\n    // replay heals the divergence deterministically.\n    if (checkpoint?.generationId !== published.head.generationId) return fresh\n    const resolved = await resolvePublishedProjectionObject({\n      key: this.#stateKey,\n      projection: published,\n      storeId: this.#stateStoreId,\n      stores: this.#options.stores,\n    })\n    return resolved === undefined ? fresh : { cursor: checkpoint.cursor, state: this.#options.reducer.deserialize(resolved.body) }\n  }\n\n  #stateObject(state: TState): ProjectionPublicationObject {\n    return {\n      body: this.#options.reducer.serialize(state),\n      contentType: 'application/json',\n      key: this.#stateKey,\n      storeId: this.#stateStoreId,\n    }\n  }\n\n  #store(storeId: string): ObjectStoreWriter {\n    const value = this.#options.stores[storeId]\n    if (value === undefined) throw new ProjectionReplayError('store-missing', `projection store ${storeId} is unavailable`)\n    return value\n  }\n}\n\nfunction scopeMatches(scope: PublishedProjectionScope, value: PublishedProjectionScope): boolean {\n  return scope.dappId === value.dappId\n    && scope.chainId === value.chainId\n    && scope.projectionId === value.projectionId\n    && scope.projectionVersion === value.projectionVersion\n}\n\nfunction progressFor(\n  target: ProjectionPosition,\n  processed: ProjectionPosition | undefined,\n  floorBlock: number,\n): ProjectionReplayProgress {\n  const processedBlock = processed?.blockNumber ?? floorBlock\n  const finalizedHead = Math.max(target.blockNumber, processedBlock)\n  // Guard against a source that reports a head behind an already-processed\n  // position; lag is a nonnegative watermark, never a negative surprise.\n  const boundedProcessed = compareProjectionPositions(\n    processed ?? zeroPosition(floorBlock),\n    target,\n  ) > 0\n    ? target.blockNumber\n    : processedBlock\n  return {\n    finalizedHead,\n    lag: Math.max(0, finalizedHead - boundedProcessed),\n    processed: boundedProcessed,\n    target: target.blockNumber,\n  }\n}\n\nfunction zeroPosition(blockNumber: number): ProjectionPosition {\n  const zeroHash = '0'.repeat(64)\n  return {\n    blockNumber,\n    blockHash: zeroHash,\n    transactionIndex: 0,\n    transactionHash: zeroHash,\n    payloadIndex: 0,\n    payloadHash: zeroHash,\n    recordIndex: 0,\n  }\n}\n", "import { z } from 'zod'\n\nimport {\n  canonicalizeIJson,\n  hashDappDocument,\n} from './canonicalDocument.ts'\nimport type {\n  ProjectionGeneration,\n  ProjectionHead,\n  ProjectionPosition,\n  ProjectionPublicationOperation,\n  ProjectionPublicationTrace,\n  ProjectionReducerStep,\n  ProjectionReducerTrace,\n} from './projection.ts'\nimport {\n  ProjectionGenerationZod,\n  ProjectionPublicationTraceZod,\n  ProjectionReducerTraceZod,\n} from './projection.ts'\n\nexport const ProjectionTraceIssueCodes = [\n  'projection.checkpoint-before-head',\n  'projection.checkpoint-mismatch',\n  'projection.duplicate-state-change',\n  'projection.duplicate-unknown',\n  'projection.event-reapplied',\n  'projection.final-state-mismatch',\n  'projection.generation-hash-mismatch',\n  'projection.head-before-verification',\n  'projection.head-mismatch',\n  'projection.interrupted-terminal',\n  'projection.invalid',\n  'projection.operation-duplicate',\n  'projection.payload-hash-mismatch',\n  'projection.position-order-invalid',\n  'projection.rejected-state-change',\n  'projection.verification-before-write',\n] as const\n\nexport const ProjectionTraceIssueCodeZod = z.enum(ProjectionTraceIssueCodes)\nexport type ProjectionTraceIssueCode = z.infer<typeof ProjectionTraceIssueCodeZod>\n\nexport interface ProjectionTraceIssue {\n  code: ProjectionTraceIssueCode\n  message: string\n  path: (number | string)[]\n}\n\nexport interface ProjectionTraceValidationFailure {\n  issues: ProjectionTraceIssue[]\n  success: false\n}\n\nexport interface ProjectionReducerTraceValidationSuccess {\n  success: true\n  value: ProjectionReducerTrace\n}\n\nexport interface ProjectionPublicationTraceValidationSuccess {\n  completion: 'checkpointed' | 'published' | 'unpublished'\n  success: true\n  value: ProjectionPublicationTrace\n  visibleHead?: ProjectionHead\n}\n\nexport type ProjectionReducerTraceValidationResult = ProjectionTraceValidationFailure | ProjectionReducerTraceValidationSuccess\n\nexport type ProjectionPublicationTraceValidationResult = ProjectionPublicationTraceValidationSuccess | ProjectionTraceValidationFailure\n\nfunction issue(\n  code: ProjectionTraceIssueCode,\n  message: string,\n  path: (number | string)[],\n): ProjectionTraceIssue {\n  return {\n    code, message, path,\n  }\n}\n\nfunction structuralIssues(issues: z.core.$ZodIssue[]): ProjectionTraceIssue[] {\n  return issues.map(value => issue(\n    'projection.invalid',\n    value.message,\n    value.path.map(path => typeof path === 'symbol' ? path.toString() : path),\n  ))\n}\n\nexport function compareProjectionPositions(left: ProjectionPosition, right: ProjectionPosition): number {\n  const leftValues = [left.blockNumber, left.transactionIndex, left.payloadIndex, left.recordIndex]\n  const rightValues = [right.blockNumber, right.transactionIndex, right.payloadIndex, right.recordIndex]\n  for (const [index, leftValue] of leftValues.entries()) {\n    const difference = leftValue - (rightValues[index] ?? 0)\n    if (difference !== 0) return difference\n  }\n  return 0\n}\n\nfunction isSameCanonicalPosition(left: ProjectionPosition, right: ProjectionPosition): boolean {\n  return compareProjectionPositions(left, right) === 0\n    && left.blockHash === right.blockHash\n    && left.transactionHash === right.transactionHash\n    && left.payloadHash === right.payloadHash\n}\n\nfunction compareStrings(left: string, right: string): number {\n  return left < right ? -1 : left > right ? 1 : 0\n}\n\ninterface ReducerValidationState {\n  appliedEventIds: Set<string>\n  currentState: ProjectionReducerTrace['initialState']\n  priorPosition?: ProjectionPosition\n  priorRecordId?: string\n}\n\nfunction validateReducerPosition(\n  step: ProjectionReducerStep,\n  index: number,\n  state: ReducerValidationState,\n  issues: ProjectionTraceIssue[],\n): number {\n  if (step.record.payloadHash !== step.record.position.payloadHash) {\n    issues.push(issue(\n      'projection.payload-hash-mismatch',\n      'record payload hash must match the canonical position payload hash',\n      ['steps', index, 'record', 'payloadHash'],\n    ))\n  }\n  const positionOrder = state.priorPosition === undefined\n    ? 1\n    : compareProjectionPositions(step.record.position, state.priorPosition)\n  const isExactRedelivery = state.priorPosition !== undefined\n    && isSameCanonicalPosition(step.record.position, state.priorPosition)\n    && step.record.eventId === state.priorRecordId\n  if (positionOrder < 0 || (positionOrder === 0 && !isExactRedelivery)) {\n    issues.push(issue(\n      'projection.position-order-invalid',\n      'reducer inputs must use forward canonical order; equal positions require exact redelivery',\n      ['steps', index, 'record', 'position'],\n    ))\n  }\n  return positionOrder\n}\n\nfunction validateReducerOutcome(\n  step: ProjectionReducerStep,\n  index: number,\n  state: ReducerValidationState,\n  issues: ProjectionTraceIssue[],\n): void {\n  const priorStateJson = canonicalizeIJson(state.currentState)\n  const nextStateJson = canonicalizeIJson(step.result.state)\n  if (step.result.outcome === 'applied') {\n    if (state.appliedEventIds.has(step.record.eventId)) {\n      issues.push(issue('projection.event-reapplied', 'an applied event ID cannot be applied twice', ['steps', index]))\n    }\n    state.appliedEventIds.add(step.record.eventId)\n    state.currentState = step.result.state\n    return\n  }\n  if (step.result.outcome === 'duplicate') {\n    if (!state.appliedEventIds.has(step.result.duplicateOf) || step.result.duplicateOf !== step.record.eventId) {\n      issues.push(issue('projection.duplicate-unknown', 'duplicate result must name a previously applied event', ['steps', index]))\n    }\n    if (priorStateJson !== nextStateJson) {\n      issues.push(issue('projection.duplicate-state-change', 'duplicate delivery must not change state', ['steps', index, 'result', 'state']))\n    }\n    return\n  }\n  if (priorStateJson !== nextStateJson) {\n    issues.push(issue('projection.rejected-state-change', 'rejected input must not change state', ['steps', index, 'result', 'state']))\n  }\n}\n\nfunction validateReducerStep(\n  step: ProjectionReducerStep,\n  index: number,\n  state: ReducerValidationState,\n  issues: ProjectionTraceIssue[],\n): void {\n  const positionOrder = validateReducerPosition(step, index, state, issues)\n  validateReducerOutcome(step, index, state, issues)\n  if (!(positionOrder > 0)) {\n    return\n  }\n\n  state.priorPosition = step.record.position\n  state.priorRecordId = step.record.eventId\n}\n\nexport function validateProjectionReducerTrace(value: unknown): ProjectionReducerTraceValidationResult {\n  const result = ProjectionReducerTraceZod.safeParse(value)\n  if (!result.success) return { issues: structuralIssues(result.error.issues), success: false }\n\n  const trace = result.data\n  const issues: ProjectionTraceIssue[] = []\n  const state: ReducerValidationState = {\n    appliedEventIds: new Set(),\n    currentState: trace.initialState,\n  }\n  for (const [index, step] of trace.steps.entries()) {\n    validateReducerStep(step, index, state, issues)\n  }\n\n  if (canonicalizeIJson(state.currentState) !== canonicalizeIJson(trace.finalState)) {\n    issues.push(issue('projection.final-state-mismatch', 'final state must equal the last reducer result state', ['finalState']))\n  }\n  return issues.length > 0 ? { issues, success: false } : { success: true, value: trace }\n}\n\nexport function normalizeProjectionGeneration(generation: ProjectionGeneration): ProjectionGeneration {\n  return ProjectionGenerationZod.parse({\n    ...generation,\n    objects: [...generation.objects].toSorted((left, right) => compareStrings(left.key, right.key)),\n  })\n}\n\nexport function deriveProjectionGenerationHash(generation: ProjectionGeneration): string {\n  return hashDappDocument({\n    kind: 'projection-generation',\n    schema: ProjectionGenerationZod,\n    schemaVersion: 1,\n  }, normalizeProjectionGeneration(generation)).hash\n}\n\nfunction publicationIdentityMatches(trace: ProjectionPublicationTrace, head: ProjectionHead): boolean {\n  const generation = trace.generation\n  return head.dappId === generation.dappId\n    && head.chainId === generation.chainId\n    && head.projectionId === generation.projectionId\n    && head.projectionVersion === generation.projectionVersion\n    && head.generationId === generation.generationId\n    && head.generationHash === trace.expectedGenerationHash\n    && head.previousGenerationId === trace.initialHead?.generationId\n}\n\nfunction publicationScopeMatches(\n  generation: ProjectionGeneration,\n  value: Pick<ProjectionGeneration, 'chainId' | 'dappId' | 'projectionId' | 'projectionVersion'>,\n): boolean {\n  return value.dappId === generation.dappId\n    && value.chainId === generation.chainId\n    && value.projectionId === generation.projectionId\n    && value.projectionVersion === generation.projectionVersion\n}\n\ninterface PublicationValidationState {\n  isCheckpointed: boolean\n  isInterrupted: boolean\n  isPublished: boolean\n  isVerified: boolean\n  isWritten: boolean\n  seenKinds: Set<string>\n  visibleHead?: ProjectionHead\n}\n\nfunction validateGenerationEvidence(\n  trace: ProjectionPublicationTrace,\n  operation: Extract<ProjectionPublicationOperation, { kind: 'generation-verified' | 'generation-written' }>,\n  index: number,\n  issues: ProjectionTraceIssue[],\n): void {\n  if (operation.generationId !== trace.generation.generationId\n    || operation.generationHash !== trace.expectedGenerationHash) {\n    issues.push(issue(\n      'projection.generation-hash-mismatch',\n      `${operation.kind} evidence does not match target generation`,\n      ['operations', index],\n    ))\n  }\n}\n\nfunction validatePublicationPreamble(\n  operation: ProjectionPublicationOperation,\n  index: number,\n  state: PublicationValidationState,\n  issues: ProjectionTraceIssue[],\n): void {\n  if (state.isInterrupted) {\n    issues.push(issue('projection.interrupted-terminal', 'publication operations cannot follow interruption', ['operations', index]))\n  }\n  if (state.seenKinds.has(operation.kind) && operation.kind !== 'interrupted') {\n    issues.push(issue('projection.operation-duplicate', 'publication stages may occur once', ['operations', index, 'kind']))\n  }\n  state.seenKinds.add(operation.kind)\n}\n\nfunction validateWrittenOperation(\n  trace: ProjectionPublicationTrace,\n  operation: Extract<ProjectionPublicationOperation, { kind: 'generation-written' }>,\n  index: number,\n  state: PublicationValidationState,\n  issues: ProjectionTraceIssue[],\n): void {\n  state.isWritten = true\n  validateGenerationEvidence(trace, operation, index, issues)\n}\n\nfunction validateVerifiedOperation(\n  trace: ProjectionPublicationTrace,\n  operation: Extract<ProjectionPublicationOperation, { kind: 'generation-verified' }>,\n  index: number,\n  state: PublicationValidationState,\n  issues: ProjectionTraceIssue[],\n): void {\n  if (!state.isWritten) {\n    issues.push(issue('projection.verification-before-write', 'generation verification requires prior write', ['operations', index]))\n  }\n  state.isVerified = true\n  validateGenerationEvidence(trace, operation, index, issues)\n}\n\nfunction validateHeadOperation(\n  trace: ProjectionPublicationTrace,\n  operation: Extract<ProjectionPublicationOperation, { kind: 'head-published' }>,\n  index: number,\n  state: PublicationValidationState,\n  issues: ProjectionTraceIssue[],\n): void {\n  if (!state.isVerified) {\n    issues.push(issue('projection.head-before-verification', 'head publication requires verified generation data', ['operations', index]))\n  }\n  if (!publicationIdentityMatches(trace, operation.head)) {\n    issues.push(issue(\n      'projection.head-mismatch',\n      'head must identify the verified target generation and prior visible head',\n      ['operations', index, 'head'],\n    ))\n  }\n  state.isPublished = true\n  state.visibleHead = operation.head\n}\n\nfunction validateCheckpointOperation(\n  trace: ProjectionPublicationTrace,\n  operation: Extract<ProjectionPublicationOperation, { kind: 'checkpoint-persisted' }>,\n  index: number,\n  state: PublicationValidationState,\n  issues: ProjectionTraceIssue[],\n): void {\n  if (!state.isPublished) {\n    issues.push(issue('projection.checkpoint-before-head', 'checkpoint persistence requires a published head', ['operations', index]))\n  }\n  if (!publicationScopeMatches(trace.generation, operation.checkpoint)\n    || operation.checkpoint.generationId !== trace.generation.generationId\n    || !isSameCanonicalPosition(operation.checkpoint.position, trace.generation.targetPosition)) {\n    issues.push(issue(\n      'projection.checkpoint-mismatch',\n      'checkpoint must identify the published generation target',\n      ['operations', index, 'checkpoint'],\n    ))\n  }\n  state.isCheckpointed = true\n}\n\nfunction validatePublicationOperation(\n  trace: ProjectionPublicationTrace,\n  operation: ProjectionPublicationOperation,\n  index: number,\n  state: PublicationValidationState,\n  issues: ProjectionTraceIssue[],\n): void {\n  validatePublicationPreamble(operation, index, state, issues)\n  switch (operation.kind) {\n    case 'generation-written': {\n      validateWrittenOperation(trace, operation, index, state, issues)\n      break\n    }\n    case 'generation-verified': {\n      validateVerifiedOperation(trace, operation, index, state, issues)\n      break\n    }\n    case 'head-published': {\n      validateHeadOperation(trace, operation, index, state, issues)\n      break\n    }\n    case 'checkpoint-persisted': {\n      validateCheckpointOperation(trace, operation, index, state, issues)\n      break\n    }\n    case 'interrupted': {\n      state.isInterrupted = true\n      break\n    }\n  }\n}\n\nexport function validateProjectionPublicationTrace(value: unknown): ProjectionPublicationTraceValidationResult {\n  const result = ProjectionPublicationTraceZod.safeParse(value)\n  if (!result.success) return { issues: structuralIssues(result.error.issues), success: false }\n  const trace = result.data\n  const issues: ProjectionTraceIssue[] = []\n  const actualGenerationHash = deriveProjectionGenerationHash(trace.generation)\n  if (actualGenerationHash !== trace.expectedGenerationHash) {\n    issues.push(issue('projection.generation-hash-mismatch', 'generation hash does not match normalized generation', ['expectedGenerationHash']))\n  }\n  if (trace.initialHead !== undefined && !publicationScopeMatches(trace.generation, trace.initialHead)) {\n    issues.push(issue(\n      'projection.head-mismatch',\n      'initial head must belong to the target projection scope',\n      ['initialHead'],\n    ))\n  }\n\n  const state: PublicationValidationState = {\n    isCheckpointed: false,\n    isInterrupted: false,\n    isPublished: false,\n    isVerified: false,\n    isWritten: false,\n    seenKinds: new Set(),\n    visibleHead: trace.initialHead,\n  }\n  for (const [index, operation] of trace.operations.entries()) {\n    validatePublicationOperation(trace, operation, index, state, issues)\n  }\n\n  if (issues.length > 0) return { issues, success: false }\n  return {\n    completion: state.isCheckpointed ? 'checkpointed' : state.isPublished ? 'published' : 'unpublished',\n    success: true,\n    value: trace,\n    ...(state.visibleHead === undefined ? {} : { visibleHead: state.visibleHead }),\n  }\n}\n", "import { asSchema } from '@xyo-network/sdk'\nimport { z } from 'zod'\n\nimport {\n  DappDocumentHashAlgorithm,\n  hashDappDocument,\n} from './canonicalDocument.ts'\nimport {\n  DappIdZod,\n  HashZod,\n  IdentifierZod,\n  SemanticVersionZod,\n} from './identifier.ts'\nimport { RepositoryRelativePathZod } from './projectArtifact.ts'\nimport { GitCommitZod } from './projectManifestModel.ts'\nexport const DappProtocolReleaseSchema = asSchema('network.xyo.dapp.protocol.release', true)\nexport const DappProtocolReleaseAnchorSchema = asSchema('network.xyo.dapp.protocol.release.anchor', true)\n\n/**\n * What a release entry is allowed to be.\n *\n * The set is closed, and nothing in it can name a deployment endpoint, a\n * provider resource, or any other target state. That exclusion is structural\n * rather than advisory: decision D-025 forbids deployment material in a\n * release, so the model gives it nowhere to live instead of validating it away\n * after the fact.\n */\nexport const ProtocolReleaseEntryKindZod = z.enum([\n  'paper',\n  'protocol-document',\n  'schema',\n  'canonicalization',\n  'conformance-vectors',\n  'reducer',\n  'verifier',\n  'headless-client',\n  'helper',\n])\n\nexport type ProtocolReleaseEntryKind = z.infer<typeof ProtocolReleaseEntryKindZod>\n\n/**\n * The kinds a release must bind to be a release at all, from D-025's\n * enumeration. A document that binds no verifier or no vectors cannot support\n * the independent verification a release exists to make possible, so it is\n * rejected rather than published as a weaker artifact of the same name.\n */\nconst RequiredEntryKinds: readonly ProtocolReleaseEntryKind[] = [\n  'conformance-vectors',\n  'paper',\n  'reducer',\n  'schema',\n  'verifier',\n]\n\n/**\n * Repository paths that carry deployment intent or resolved target state.\n * Their content is exactly what D-025 keeps out of a release, so naming one is\n * refused with the reason rather than silently inventoried.\n */\nconst ForbiddenPathPatterns: readonly RegExp[] = [\n  /^xl1\\.deploy\\.json$/,\n  /(?:^|\\/)deployment\\.lock\\.json$/,\n  /^\\.xl1\\/locks\\//,\n  /(?:^|\\/)xl1\\.catalog[^/]*\\.json$/,\n  // D-025 (2026-09-03 amendment): an infrastructure example is deployment\n  // configuration, never protocol input, so every xl1.infrastructure*.json\n  // path is refused at any depth.\n  /(?:^|\\/)xl1\\.infrastructure[^/]*\\.json$/,\n]\n\nexport const ProtocolReleaseEntryZod = z.strictObject({\n  entryId: IdentifierZod,\n  kind: ProtocolReleaseEntryKindZod,\n  /** Wire or artifact identity this entry pins, when it has one. */\n  identity: z.string().min(1).max(255).optional(),\n  path: RepositoryRelativePathZod.optional(),\n  sha256: HashZod,\n  size: z.number().int().nonnegative(),\n}).superRefine((entry, context) => {\n  if (entry.path !== undefined && ForbiddenPathPatterns.some(pattern => pattern.test(entry.path!))) {\n    context.addIssue({\n      code: 'custom',\n      message: 'deployment intent and resolved target state cannot enter a protocol release',\n      path: ['path'],\n    })\n  }\n})\n\nexport type ProtocolReleaseEntry = z.infer<typeof ProtocolReleaseEntryZod>\n\nexport const ProtocolReleaseSourceZod = z.strictObject({\n  remote: z.string().min(1).max(2048).optional(),\n  commit: GitCommitZod,\n  /**\n   * A release is generated from an exact clean commit. `dirty` is not a\n   * weaker state to record here \u2014 it means the bytes hashed cannot be\n   * recovered from the commit, so there is nothing to release.\n   */\n  worktree: z.literal('clean'),\n})\n\nexport type ProtocolReleaseSource = z.infer<typeof ProtocolReleaseSourceZod>\n\nexport const ProtocolReleasePredecessorZod = z.strictObject({\n  releaseId: IdentifierZod,\n  releaseHash: HashZod,\n})\n\nexport type ProtocolReleasePredecessor = z.infer<typeof ProtocolReleasePredecessorZod>\n\nfunction duplicateValues(values: readonly string[]): boolean {\n  const unique = new Set(values)\n  return unique.size !== values.length\n}\n\nexport const DappProtocolReleaseZod = z.strictObject({\n  schema: z.literal(DappProtocolReleaseSchema),\n  schemaVersion: z.literal(1),\n  hashAlgorithm: z.literal(DappDocumentHashAlgorithm),\n  dappId: DappIdZod,\n  releaseId: IdentifierZod,\n  version: SemanticVersionZod,\n  definitionHash: HashZod,\n  source: ProtocolReleaseSourceZod,\n  entries: z.array(ProtocolReleaseEntryZod).min(1),\n  inventoryRoot: HashZod,\n  predecessor: ProtocolReleasePredecessorZod.optional(),\n}).superRefine((release, context) => {\n  if (duplicateValues(release.entries.map(entry => entry.entryId))) {\n    context.addIssue({\n      code: 'custom', message: 'release entry IDs must be unique', path: ['entries'],\n    })\n  }\n  const kinds = new Set(release.entries.map(entry => entry.kind))\n  for (const required of RequiredEntryKinds) {\n    if (!kinds.has(required)) {\n      context.addIssue({\n        code: 'custom', message: `release inventory must bind at least one ${required} entry`, path: ['entries'],\n      })\n    }\n  }\n  if (hashProtocolReleaseInventory(release.entries) !== release.inventoryRoot) {\n    context.addIssue({\n      code: 'custom', message: 'inventory root does not match the release entries', path: ['inventoryRoot'],\n    })\n  }\n  if (release.predecessor?.releaseId === release.releaseId) {\n    context.addIssue({\n      code: 'custom', message: 'a release cannot supersede itself', path: ['predecessor', 'releaseId'],\n    })\n  }\n})\n\nexport type DappProtocolRelease = z.infer<typeof DappProtocolReleaseZod>\n\n/**\n * The small declarative payload that commits a release on XL1.\n *\n * It carries no publisher field. Attribution derives from the wrapping signed\n * transaction, and a self-declared publisher would be an unsigned claim sitting\n * next to a signed one \u2014 the exact ambiguity D-025 removes.\n */\nexport const DappProtocolReleaseAnchorZod = z.strictObject({\n  schema: z.literal(DappProtocolReleaseAnchorSchema),\n  schemaVersion: z.literal(1),\n  dappId: DappIdZod,\n  releaseId: IdentifierZod,\n  /** Canonical document hash of the release manifest. */\n  releaseHash: HashZod,\n  /** Content hash of the stored manifest bytes, for retrieval by hash. */\n  manifestContentHash: HashZod,\n  definitionHash: HashZod,\n  sourceCommit: GitCommitZod,\n  predecessorReleaseHash: HashZod.optional(),\n})\n\nexport type DappProtocolReleaseAnchor = z.infer<typeof DappProtocolReleaseAnchorZod>\n\n/**\n * Canonical entry order is by code point, not locale. A locale-aware\n * comparison would make the inventory root depend on the ICU data of whichever\n * machine generated it, and an independent implementation in another language\n * could not reproduce it.\n */\nfunction compareEntryIds(left: string, right: string): number {\n  return left < right ? -1 : left > right ? 1 : 0\n}\n\nexport function normalizeProtocolReleaseEntries(\n  entriesValue: readonly ProtocolReleaseEntry[],\n): ProtocolReleaseEntry[] {\n  const entries = z.array(ProtocolReleaseEntryZod).parse(entriesValue)\n  return [...entries].toSorted((left, right) => compareEntryIds(left.entryId, right.entryId))\n}\n\nexport function hashProtocolReleaseInventory(entriesValue: unknown): string {\n  const entries = z.array(ProtocolReleaseEntryZod).parse(entriesValue)\n  return hashDappDocument({\n    kind: 'protocol-release-inventory',\n    schema: z.array(ProtocolReleaseEntryZod),\n    schemaVersion: 1,\n  }, normalizeProtocolReleaseEntries(entries)).hash\n}\n\nexport function normalizeDappProtocolRelease(value: unknown): DappProtocolRelease {\n  const release = DappProtocolReleaseZod.parse(value)\n  return DappProtocolReleaseZod.parse({\n    ...release,\n    entries: normalizeProtocolReleaseEntries(release.entries),\n  })\n}\n\nexport function hashDappProtocolRelease(value: unknown) {\n  return hashDappDocument({\n    kind: 'protocol-release-manifest',\n    schema: DappProtocolReleaseZod,\n    schemaVersion: 1,\n  }, normalizeDappProtocolRelease(value))\n}\n\n/**\n * Derive the anchor from the release rather than accepting one alongside it, so\n * an anchor cannot disagree with the manifest it claims to commit.\n */\nexport function protocolReleaseAnchorFor(\n  releaseValue: unknown,\n  manifestContentHash: string,\n): DappProtocolReleaseAnchor {\n  const release = normalizeDappProtocolRelease(releaseValue)\n  return DappProtocolReleaseAnchorZod.parse({\n    schema: DappProtocolReleaseAnchorSchema,\n    schemaVersion: 1,\n    dappId: release.dappId,\n    releaseId: release.releaseId,\n    releaseHash: hashDappProtocolRelease(release).hash,\n    manifestContentHash: HashZod.parse(manifestContentHash),\n    definitionHash: release.definitionHash,\n    sourceCommit: release.source.commit,\n    ...(release.predecessor !== undefined && { predecessorReleaseHash: release.predecessor.releaseHash }),\n  })\n}\n\nexport const ProtocolReleaseIssueCodes = [\n  'anchor-content-mismatch',\n  'anchor-definition-mismatch',\n  'anchor-identity-mismatch',\n  'anchor-predecessor-mismatch',\n  'anchor-release-hash-mismatch',\n  'anchor-source-mismatch',\n  'succession-dapp-mismatch',\n  'succession-predecessor-absent',\n  'succession-predecessor-mismatch',\n  'succession-source-unchanged',\n  'succession-version-not-newer',\n] as const\n\nexport type ProtocolReleaseIssueCode = typeof ProtocolReleaseIssueCodes[number]\n\n/**\n * Check an anchor against the manifest and stored bytes it commits. A consumer\n * runs this after resolving the manifest by hash, so a mismatch is a refusal\n * rather than a preference for whichever document arrived first.\n */\nexport function verifyProtocolReleaseAnchor(\n  anchorValue: unknown,\n  releaseValue: unknown,\n  manifestContentHash: string,\n): readonly ProtocolReleaseIssueCode[] {\n  const anchor = DappProtocolReleaseAnchorZod.parse(anchorValue)\n  const release = normalizeDappProtocolRelease(releaseValue)\n  const issues: ProtocolReleaseIssueCode[] = []\n  if (anchor.dappId !== release.dappId || anchor.releaseId !== release.releaseId) {\n    issues.push('anchor-identity-mismatch')\n  }\n  if (anchor.releaseHash !== hashDappProtocolRelease(release).hash) issues.push('anchor-release-hash-mismatch')\n  if (anchor.manifestContentHash !== HashZod.parse(manifestContentHash)) issues.push('anchor-content-mismatch')\n  if (anchor.definitionHash !== release.definitionHash) issues.push('anchor-definition-mismatch')\n  if (anchor.sourceCommit !== release.source.commit) issues.push('anchor-source-mismatch')\n  if (anchor.predecessorReleaseHash !== release.predecessor?.releaseHash) {\n    issues.push('anchor-predecessor-mismatch')\n  }\n  return issues\n}\n\n/**\n * Check that one release properly supersedes another: same dApp, an explicit\n * predecessor naming the earlier release hash, a newer version, and different\n * source. Supersession is the only revocation this model expresses; anything\n * stronger belongs to curated listing state, per D-025.\n */\nexport function validateProtocolReleaseSuccession(\n  previousValue: unknown,\n  nextValue: unknown,\n): readonly ProtocolReleaseIssueCode[] {\n  const previous = normalizeDappProtocolRelease(previousValue)\n  const next = normalizeDappProtocolRelease(nextValue)\n  const issues: ProtocolReleaseIssueCode[] = []\n  if (previous.dappId !== next.dappId) issues.push('succession-dapp-mismatch')\n  if (next.predecessor === undefined) {\n    issues.push('succession-predecessor-absent')\n  } else if (next.predecessor.releaseHash !== hashDappProtocolRelease(previous).hash\n    || next.predecessor.releaseId !== previous.releaseId) {\n    issues.push('succession-predecessor-mismatch')\n  }\n  if (compareSemanticVersions(next.version, previous.version) <= 0) issues.push('succession-version-not-newer')\n  if (next.source.commit === previous.source.commit) issues.push('succession-source-unchanged')\n  return issues\n}\n\nfunction releasePrecedence(value: string): readonly number[] {\n  const [core = ''] = value.split('-', 1)\n  return core.split('.').map(Number)\n}\n\nfunction compareSemanticVersions(left: string, right: string): number {\n  const leftParts = releasePrecedence(left)\n  const rightParts = releasePrecedence(right)\n  for (const [index, leftPart] of leftParts.entries()) {\n    const difference = leftPart - (rightParts[index] ?? 0)\n    if (difference !== 0) return difference > 0 ? 1 : -1\n  }\n  // Equal cores: a pre-release precedes its own release, per semver ordering.\n  const leftPre = left.includes('-')\n  const rightPre = right.includes('-')\n  if (leftPre === rightPre) return left < right ? -1 : left > right ? 1 : 0\n  return leftPre ? -1 : 1\n}\n", "import { asSchema } from '@xyo-network/sdk'\nimport { z } from 'zod'\n\nimport {\n  DappDocumentHashAlgorithm,\n  hashDappDocument,\n} from './canonicalDocument.ts'\nimport {\n  HashZod,\n  IdentifierZod,\n} from './identifier.ts'\nimport {\n  compareCodeUnits,\n  findSortedUniqueIssue,\n} from './ordering.ts'\n\n/**\n * Provider request templates (plan Section 4.4). A target plan carries the\n * public shape of every provider request it will need, with typed placeholders\n * where a protected locator, commitment-bound prerequisite, or protected\n * material will be substituted by the host's pure reconciler after target\n * verification. The template therefore reproduces without leaking host facts,\n * while the protected action core still binds the exact rendered request.\n */\nexport const DappProviderRequestTemplateSchema = asSchema('network.xyo.dapp.provider.request.template', true)\n\nexport const DappProviderRequestMethodZod = z.enum(['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE'])\nexport type DappProviderRequestMethod = z.infer<typeof DappProviderRequestMethodZod>\n\n/**\n * What a placeholder is bound to. `target-object` binds a public target-object\n * ID; `provider-prerequisite` and `registry-repository` bind a public binding\n * ID whose commitment the protected reconciler must reproduce; `protected-material`\n * binds a keyed material commitment and may appear only in a body slot of a\n * separately qualified secret-bearing action.\n */\nexport const DappProviderRequestBindingClassZod = z.enum([\n  'target-object',\n  'provider-prerequisite',\n  'registry-repository',\n  'protected-material',\n])\nexport type DappProviderRequestBindingClass = z.infer<typeof DappProviderRequestBindingClassZod>\n\nexport const DappProviderRequestPlaceholderLocationZod = z.enum(['path', 'query', 'body'])\n\nexport const DappProviderRequestPlaceholderZod = z.strictObject({\n  placeholderId: IdentifierZod,\n  location: DappProviderRequestPlaceholderLocationZod,\n  bindingClass: DappProviderRequestBindingClassZod,\n  /** Public binding ID: a target object ID or a controller-issued public binding ID. */\n  bindingId: z.string().min(1).max(255),\n  /** Public commitment the protected reconciler must reproduce before substitution; absent for `target-object`. */\n  commitment: HashZod.nullable(),\n}).refine(\n  placeholder => (placeholder.bindingClass === 'target-object') === (placeholder.commitment === null),\n  'target-object placeholders carry no commitment and every other class requires one',\n).refine(\n  placeholder => placeholder.bindingClass !== 'protected-material' || placeholder.location === 'body',\n  'protected material may only fill a body slot',\n)\nexport type DappProviderRequestPlaceholder = z.infer<typeof DappProviderRequestPlaceholderZod>\n\nconst HeaderNameZod = z.string().regex(/^[a-z0-9-]+$/)\n\nexport const DappProviderRequestSemanticHeaderZod = z.strictObject({\n  name: HeaderNameZod,\n  values: z.array(z.string().min(1)).min(1),\n})\n\nexport const DappProviderRequestQueryParameterZod = z.strictObject({\n  name: z.string().min(1),\n  value: z.string(),\n})\n\nconst PlaceholderReferenceRegExp = /\\{([a-z0-9]+(?:[._-][a-z0-9]+)*)\\}/g\n\nfunction referencedPlaceholders(text: string): Set<string> {\n  return new Set(text.matchAll(PlaceholderReferenceRegExp).map(match => match[1]))\n}\n\nexport const DappProviderRequestTemplateV1PreimageZod = z.strictObject({\n  schema: z.literal(DappProviderRequestTemplateSchema),\n  schemaVersion: z.literal(1),\n  hashAlgorithm: z.literal(DappDocumentHashAlgorithm),\n  adapterDescriptorHash: HashZod,\n  actionKind: IdentifierZod,\n  method: DappProviderRequestMethodZod,\n  /** Origin-relative path; private locators appear only as `{placeholderId}` references. */\n  pathTemplate: z.string().regex(/^\\/[^\\s?#]*$/),\n  queryTemplate: z.array(DappProviderRequestQueryParameterZod),\n  semanticHeaders: z.array(DappProviderRequestSemanticHeaderZod),\n  /** Hash of the exact body template bytes with typed slots; `null` for a bodiless request. */\n  bodyTemplateHash: HashZod.nullable(),\n  placeholders: z.array(DappProviderRequestPlaceholderZod),\n}).superRefine((template, context) => {\n  for (const [field, compare] of [\n    ['queryTemplate', (left: { name: string }, right: { name: string }) => compareCodeUnits(left.name, right.name)],\n    ['semanticHeaders', (left: { name: string }, right: { name: string }) => compareCodeUnits(left.name, right.name)],\n  ] as const) {\n    const issue = findSortedUniqueIssue(template[field], compare, field)\n    if (issue !== undefined) {\n      context.addIssue({\n        code: 'custom', message: issue.message, path: [field, issue.index],\n      })\n    }\n  }\n  const placeholderIssue = findSortedUniqueIssue(\n    template.placeholders,\n    (left, right) => compareCodeUnits(left.placeholderId, right.placeholderId),\n    'placeholders',\n  )\n  if (placeholderIssue !== undefined) {\n    context.addIssue({\n      code: 'custom', message: placeholderIssue.message, path: ['placeholders', placeholderIssue.index],\n    })\n  }\n  const inPath = referencedPlaceholders(template.pathTemplate)\n  const inQuery = new Set(template.queryTemplate.flatMap(parameter => [...referencedPlaceholders(parameter.value)]))\n  const declared = new Map(template.placeholders.map(placeholder => [placeholder.placeholderId, placeholder]))\n  for (const [location, referenced] of [['path', inPath], ['query', inQuery]] as const) {\n    for (const placeholderId of referenced) {\n      if (declared.get(placeholderId)?.location !== location) {\n        context.addIssue({\n          code: 'custom',\n          message: `placeholder ${placeholderId} is referenced in the ${location} but not declared for it`,\n          path: [location === 'path' ? 'pathTemplate' : 'queryTemplate'],\n        })\n      }\n    }\n  }\n  for (const [index, placeholder] of template.placeholders.entries()) {\n    const referenced = placeholder.location === 'path'\n      ? inPath.has(placeholder.placeholderId)\n      : (placeholder.location === 'query' ? inQuery.has(placeholder.placeholderId) : template.bodyTemplateHash !== null)\n    if (!referenced) {\n      context.addIssue({\n        code: 'custom',\n        message: `placeholder ${placeholder.placeholderId} is declared for the ${placeholder.location} but never referenced there`,\n        path: ['placeholders', index],\n      })\n    }\n  }\n})\nexport type DappProviderRequestTemplateV1Preimage = z.infer<typeof DappProviderRequestTemplateV1PreimageZod>\n\nexport const DappProviderRequestTemplateV1Zod = DappProviderRequestTemplateV1PreimageZod.safeExtend({ requestTemplateHash: HashZod })\nexport type DappProviderRequestTemplateV1 = z.infer<typeof DappProviderRequestTemplateV1Zod>\n\n/** D-002 kind `provider-request-template` version 1. */\nexport function hashDappProviderRequestTemplateV1(preimage: unknown): string {\n  return hashDappDocument({\n    kind: 'provider-request-template',\n    schema: DappProviderRequestTemplateV1PreimageZod,\n    schemaVersion: 1,\n  }, preimage).hash\n}\n\nexport function verifyDappProviderRequestTemplateV1(value: unknown): DappProviderRequestTemplateV1 {\n  const template = DappProviderRequestTemplateV1Zod.parse(value)\n  const { requestTemplateHash, ...preimage } = template\n  if (hashDappProviderRequestTemplateV1(preimage) !== requestTemplateHash) {\n    throw new TypeError(`request template for ${template.actionKind} does not reproduce its requestTemplateHash`)\n  }\n  return template\n}\n", "import { asSchema } from '@xyo-network/sdk'\nimport { z } from 'zod'\n\nimport {\n  DappDocumentHashAlgorithm,\n  hashDappDocument,\n} from './canonicalDocument.ts'\nimport { DappInfrastructureKindZod } from './deploymentManifestV2.ts'\nimport {\n  HashZod,\n  IdentifierZod,\n  XyoSchemaZod,\n} from './identifier.ts'\nimport { JsonValueZod } from './jsonValue.ts'\nimport {\n  compareCodeUnits,\n  findSortedUniqueIssue,\n} from './ordering.ts'\n\n/**\n * Provider-scope identity contracts (plan Section 4.2). Each adapter declares,\n * and independently vectors, how it normalizes the stable provider evidence\n * that identifies one account, cluster, or server scope. The contract hash\n * enters the adapter descriptor; the raw evidence, the controller scope key,\n * and the per-registration nonce never leave the host.\n */\nexport const DappProviderScopeIdentityContractSchema = asSchema('network.xyo.dapp.provider.scope.identity.contract', true)\nexport const DappProviderScopeNormalizationVectorsSchema = asSchema('network.xyo.dapp.provider.scope.normalization.vectors', true)\n\nconst PositiveIntegerZod = z.number().int().positive()\n\n/** The first slice admits exactly one distribution kind. */\nexport const DappArtifactDistributionKindZod = z.enum(['oci-registry'])\nexport type DappArtifactDistributionKind = z.infer<typeof DappArtifactDistributionKindZod>\n\nexport const DappProviderScopeOwnerZod = z.discriminatedUnion('kind', [\n  z.strictObject({ kind: z.literal('infrastructure'), infrastructureKind: DappInfrastructureKindZod }),\n  z.strictObject({ kind: z.literal('artifact-distribution'), distributionKind: DappArtifactDistributionKindZod }),\n])\nexport type DappProviderScopeOwner = z.infer<typeof DappProviderScopeOwnerZod>\n\nexport const DappProviderScopeIdentityContractV1PreimageZod = z.strictObject({\n  schema: z.literal(DappProviderScopeIdentityContractSchema),\n  schemaVersion: z.literal(1),\n  hashAlgorithm: z.literal(DappDocumentHashAlgorithm),\n  scopeOwner: DappProviderScopeOwnerZod,\n  scopeIdentityFamily: IdentifierZod,\n  providerEvidenceSchema: XyoSchemaZod,\n  providerEvidenceSchemaVersion: PositiveIntegerZod,\n  providerEvidenceSchemaHash: HashZod,\n  providerScopeNormalizationId: IdentifierZod,\n  identityProjectionSchemaHash: HashZod,\n  normalizationVectorSetHash: HashZod,\n})\nexport type DappProviderScopeIdentityContractV1Preimage = z.infer<typeof DappProviderScopeIdentityContractV1PreimageZod>\n\nexport const DappProviderScopeIdentityContractV1Zod = DappProviderScopeIdentityContractV1PreimageZod\n  .safeExtend({ scopeIdentityContractHash: HashZod })\nexport type DappProviderScopeIdentityContractV1 = z.infer<typeof DappProviderScopeIdentityContractV1Zod>\n\n/** D-002 kind `provider-scope-identity-contract` version 1. */\nexport function hashDappProviderScopeIdentityContractV1(preimage: unknown): string {\n  return hashDappDocument({\n    kind: 'provider-scope-identity-contract',\n    schema: DappProviderScopeIdentityContractV1PreimageZod,\n    schemaVersion: 1,\n  }, preimage).hash\n}\n\nexport function verifyDappProviderScopeIdentityContractV1(value: unknown): DappProviderScopeIdentityContractV1 {\n  const contract = DappProviderScopeIdentityContractV1Zod.parse(value)\n  const { scopeIdentityContractHash, ...preimage } = contract\n  if (hashDappProviderScopeIdentityContractV1(preimage) !== scopeIdentityContractHash) {\n    throw new TypeError(`scope identity contract ${contract.scopeIdentityFamily} does not reproduce its scopeIdentityContractHash`)\n  }\n  return contract\n}\n\nexport const DappProviderScopeNormalizationCaseZod = z.strictObject({\n  caseId: IdentifierZod,\n  /** Synthetic provider evidence; public fixtures never contain live evidence. */\n  input: JsonValueZod,\n  expectedNormalizedIdentity: JsonValueZod,\n})\nexport type DappProviderScopeNormalizationCase = z.infer<typeof DappProviderScopeNormalizationCaseZod>\n\nexport const DappProviderScopeNormalizationVectorSetV1PreimageZod = z.strictObject({\n  schema: z.literal(DappProviderScopeNormalizationVectorsSchema),\n  schemaVersion: z.literal(1),\n  hashAlgorithm: z.literal(DappDocumentHashAlgorithm),\n  scopeOwner: DappProviderScopeOwnerZod,\n  scopeIdentityFamily: IdentifierZod,\n  providerScopeNormalizationId: IdentifierZod,\n  cases: z.array(DappProviderScopeNormalizationCaseZod).min(1),\n}).superRefine((vectors, context) => {\n  const issue = findSortedUniqueIssue(vectors.cases, (left, right) => compareCodeUnits(left.caseId, right.caseId), 'cases')\n  if (issue !== undefined) {\n    context.addIssue({\n      code: 'custom', message: issue.message, path: ['cases', issue.index],\n    })\n  }\n})\nexport type DappProviderScopeNormalizationVectorSetV1Preimage = z.infer<typeof DappProviderScopeNormalizationVectorSetV1PreimageZod>\n\nexport const DappProviderScopeNormalizationVectorSetV1Zod = DappProviderScopeNormalizationVectorSetV1PreimageZod\n  .safeExtend({ normalizationVectorSetHash: HashZod })\nexport type DappProviderScopeNormalizationVectorSetV1 = z.infer<typeof DappProviderScopeNormalizationVectorSetV1Zod>\n\n/** D-002 kind `provider-scope-normalization-vectors` version 1. */\nexport function hashDappProviderScopeNormalizationVectorSetV1(preimage: unknown): string {\n  return hashDappDocument({\n    kind: 'provider-scope-normalization-vectors',\n    schema: DappProviderScopeNormalizationVectorSetV1PreimageZod,\n    schemaVersion: 1,\n  }, preimage).hash\n}\n\nexport function verifyDappProviderScopeNormalizationVectorSetV1(value: unknown): DappProviderScopeNormalizationVectorSetV1 {\n  const vectors = DappProviderScopeNormalizationVectorSetV1Zod.parse(value)\n  const { normalizationVectorSetHash, ...preimage } = vectors\n  if (hashDappProviderScopeNormalizationVectorSetV1(preimage) !== normalizationVectorSetHash) {\n    throw new TypeError(`normalization vector set ${vectors.providerScopeNormalizationId} does not reproduce its normalizationVectorSetHash`)\n  }\n  return vectors\n}\n", "import { asSchema } from '@xyo-network/sdk'\nimport { z } from 'zod'\n\nimport { canonicalizeIJson } from './canonicalDocument.ts'\nimport { HashZod, IdentifierZod } from './identifier.ts'\nimport { GitCommitZod } from './projectManifestModel.ts'\n\nconst TextZod = z.string().min(1).max(1024)\nconst EvidenceIdZod = z.number().int().positive().max(Number.MAX_SAFE_INTEGER)\nconst SourceRefZod = TextZod.regex(/^refs\\/heads\\/[^\\s]+$/u)\n\nfunction uniqueIds<T extends { id: string | number }>(values: T[], context: z.RefinementCtx) {\n  const unique = new Set(values.map(value => value.id))\n  if (unique.size !== values.length) {\n    context.addIssue({ code: 'custom', message: 'duplicate evidence identifiers' })\n  }\n}\n\nexport const DappReleaseSourceZod = z.strictObject({\n  repository: TextZod, sourceRef: SourceRefZod, sourceSha: GitCommitZod,\n})\nexport type DappReleaseSource = z.infer<typeof DappReleaseSourceZod>\n\nexport const DappReleaseWorkflowRequirementZod = z.strictObject({\n  id: IdentifierZod, workflowPath: TextZod, workflowName: TextZod, event: TextZod,\n})\nexport const DappReleaseDeploymentRequirementZod = z.strictObject({\n  id: IdentifierZod, environment: TextZod, publishers: z.array(TextZod).min(1),\n})\nexport const DappReleaseEvidencePolicyZod = DappReleaseSourceZod.extend({\n  workflows: z.array(DappReleaseWorkflowRequirementZod).superRefine(uniqueIds),\n  deployments: z.array(DappReleaseDeploymentRequirementZod).superRefine(uniqueIds),\n}).refine(value => value.workflows.length + value.deployments.length > 0, 'release policy requires evidence')\nexport type DappReleaseEvidencePolicy = z.infer<typeof DappReleaseEvidencePolicyZod>\n\nexport const DappReleaseWorkflowRunZod = z.strictObject({\n  id: EvidenceIdZod,\n  attempt: EvidenceIdZod,\n  repository: TextZod,\n  headRepository: TextZod,\n  sourceRef: SourceRefZod,\n  sourceSha: GitCommitZod,\n  event: TextZod,\n  workflowPath: TextZod,\n  workflowName: TextZod,\n  status: TextZod,\n  conclusion: TextZod.nullable(),\n})\nexport type DappReleaseWorkflowRun = z.infer<typeof DappReleaseWorkflowRunZod>\nexport const DappReleaseDeploymentStatusZod = z.strictObject({\n  id: EvidenceIdZod, state: TextZod, publisher: TextZod,\n})\nexport const DappReleaseDeploymentZod = z.strictObject({\n  id: EvidenceIdZod,\n  repository: TextZod,\n  environment: TextZod,\n  sourceSha: GitCommitZod,\n  publisher: TextZod,\n  statuses: z.array(DappReleaseDeploymentStatusZod).superRefine(uniqueIds),\n})\nexport type DappReleaseDeployment = z.infer<typeof DappReleaseDeploymentZod>\n\nexport const DappReleaseEvidenceObservationZod = z.strictObject({\n  sourceBefore: DappReleaseSourceZod,\n  sourceAfter: DappReleaseSourceZod,\n  workflows: z.array(z.strictObject({ id: IdentifierZod, runs: z.array(DappReleaseWorkflowRunZod).superRefine(uniqueIds) })).superRefine(uniqueIds),\n  deployments: z.array(z.strictObject({ id: IdentifierZod, deployments: z.array(DappReleaseDeploymentZod).superRefine(uniqueIds) })).superRefine(uniqueIds),\n})\nexport type DappReleaseEvidenceObservation = z.infer<typeof DappReleaseEvidenceObservationZod>\n\nexport const DappReleaseEvidenceSnapshotSchema = asSchema('network.xyo.dapp.release.evidence.snapshot', true)\nexport const DappReleaseEvidenceSnapshotZod = z.strictObject({\n  schema: z.literal(DappReleaseEvidenceSnapshotSchema),\n  schemaVersion: z.literal(1),\n  policy: DappReleaseEvidencePolicyZod,\n  workflows: z.array(z.strictObject({ id: IdentifierZod, run: DappReleaseWorkflowRunZod })).superRefine(uniqueIds),\n  deployments: z.array(z.strictObject({\n    id: IdentifierZod,\n    deployment: DappReleaseDeploymentZod.omit({ statuses: true }),\n    status: DappReleaseDeploymentStatusZod,\n  })).superRefine(uniqueIds),\n})\nexport type DappReleaseEvidenceSnapshot = z.infer<typeof DappReleaseEvidenceSnapshotZod>\nconst IssueZod = z.strictObject({ code: IdentifierZod, componentId: IdentifierZod.optional() })\nexport const DappReleaseEvidenceOutcomeZod = z.discriminatedUnion('state', [\n  z.strictObject({\n    state: z.literal('eligible'), issues: z.array(IssueZod).length(0), snapshot: DappReleaseEvidenceSnapshotZod,\n  }),\n  z.strictObject({ state: z.enum(['waiting', 'blocked', 'superseded']), issues: z.array(IssueZod).min(1) }),\n])\nexport type DappReleaseEvidenceOutcome = z.infer<typeof DappReleaseEvidenceOutcomeZod>\n\nfunction newest<T extends { id: number }>(values: T[]) {\n  return values.reduce<T | undefined>((selected, value) => !selected || value.id > selected.id ? value : selected, undefined)\n}\n\n/** Input includes the adapter's latest run, never an earlier-success search. */\nexport function selectLatestDappReleaseWorkflowRun(value: unknown): DappReleaseWorkflowRun | undefined {\n  return newest(z.array(DappReleaseWorkflowRunZod).superRefine(uniqueIds).parse(value))\n}\n\n/** The adapter must read the whole environment without filtering by source commit. */\nexport function selectLatestDappReleaseDeployment(value: unknown): DappReleaseDeployment | undefined {\n  return newest(z.array(DappReleaseDeploymentZod).superRefine(uniqueIds).parse(value))\n}\n\nfunction refusal(state: 'waiting' | 'blocked' | 'superseded', code: string, componentId?: string): DappReleaseEvidenceOutcome {\n  return { state, issues: [{ code, ...(componentId === undefined ? {} : { componentId }) }] }\n}\n\nconst PendingRunStates = new Set(['queued', 'in_progress', 'waiting', 'requested', 'pending'])\nconst PendingDeploymentStates = new Set(['queued', 'pending', 'in_progress'])\n\nfunction workflowIssue(run: DappReleaseWorkflowRun | undefined, policy: DappReleaseEvidencePolicy, required: z.infer<typeof DappReleaseWorkflowRequirementZod>) {\n  if (!run) return { code: 'workflow-missing', blocked: false }\n  if (run.repository !== policy.repository || run.headRepository !== policy.repository || run.sourceRef !== policy.sourceRef\n    || run.sourceSha !== policy.sourceSha || run.event !== required.event || run.workflowPath !== required.workflowPath || run.workflowName !== required.workflowName) {\n    return { code: 'workflow-identity-mismatch', blocked: true }\n  }\n  if (PendingRunStates.has(run.status)) return { code: 'workflow-pending', blocked: false }\n  if (run.status !== 'completed' || run.conclusion !== 'success') return { code: 'workflow-unsuccessful', blocked: true }\n}\n\nfunction deploymentIssue(deployment: DappReleaseDeployment | undefined, policy: DappReleaseEvidencePolicy, required: z.infer<typeof DappReleaseDeploymentRequirementZod>) {\n  if (!deployment) return { code: 'deployment-missing', blocked: false }\n  const status = newest(deployment.statuses)\n  if (deployment.repository !== policy.repository || deployment.environment !== required.environment\n    || !required.publishers.includes(deployment.publisher) || (status && !required.publishers.includes(status.publisher))) {\n    return { code: 'deployment-identity-mismatch', blocked: true }\n  }\n  if (deployment.sourceSha !== policy.sourceSha) return { code: 'deployment-source-mismatch', blocked: false }\n  if (!status || PendingDeploymentStates.has(status.state)) return { code: 'deployment-pending', blocked: false }\n  if (status.state !== 'success') return { code: 'deployment-unsuccessful', blocked: true }\n}\n\nfunction sourceIssue(policy: DappReleaseEvidencePolicy, observation: DappReleaseEvidenceObservation) {\n  for (const source of [observation.sourceBefore, observation.sourceAfter]) {\n    if (source.repository !== policy.repository || source.sourceRef !== policy.sourceRef) return refusal('blocked', 'source-identity-mismatch')\n    if (source.sourceSha !== policy.sourceSha) return refusal('superseded', 'source-ref-moved')\n  }\n  for (const kind of ['workflows', 'deployments'] as const) {\n    if (observation[kind].some(entry => policy[kind].every(required => required.id !== entry.id))) return refusal('blocked', 'unexpected-component')\n  }\n}\n\n/** Pure eligibility from authenticated adapter observations; grants no deployment authority. */\nexport function evaluateDappReleaseEvidence(policyInput: unknown, observationInput: unknown): DappReleaseEvidenceOutcome {\n  const parsedPolicy = DappReleaseEvidencePolicyZod.safeParse(policyInput)\n  const parsedObservation = DappReleaseEvidenceObservationZod.safeParse(observationInput)\n  if (!parsedPolicy.success || !parsedObservation.success) return refusal('blocked', 'malformed-evidence')\n  const policy = parsedPolicy.data\n  const observation = parsedObservation.data\n  const issue = sourceIssue(policy, observation)\n  if (issue) return issue\n  const snapshot: DappReleaseEvidenceSnapshot = {\n    schema: DappReleaseEvidenceSnapshotSchema, schemaVersion: 1, policy, workflows: [], deployments: [],\n  }\n  const issues: (z.infer<typeof IssueZod> & { blocked: boolean })[] = []\n  for (const required of policy.workflows) {\n    const run = selectLatestDappReleaseWorkflowRun(observation.workflows.find(entry => entry.id === required.id)?.runs ?? [])\n    const issue = workflowIssue(run, policy, required)\n    if (issue) issues.push({ ...issue, componentId: required.id })\n    else if (run) snapshot.workflows.push({ id: required.id, run })\n  }\n  for (const required of policy.deployments) {\n    const deployment = selectLatestDappReleaseDeployment(observation.deployments.find(entry => entry.id === required.id)?.deployments ?? [])\n    const issue = deploymentIssue(deployment, policy, required)\n    if (issue) issues.push({ ...issue, componentId: required.id })\n    else if (deployment) {\n      const status = newest(deployment.statuses)\n      const { statuses: _statuses, ...identity } = deployment\n      if (status) snapshot.deployments.push({\n        id: required.id, deployment: identity, status,\n      })\n    }\n  }\n  if (issues.length > 0) return {\n    state: issues.some(issue => issue.blocked) ? 'blocked' : 'waiting',\n    issues: issues.map(({ blocked: _blocked, ...issue }) => issue),\n  }\n  // Selection order follows the explicit policy; callers must keep that policy fixed.\n  return {\n    state: 'eligible', issues: [], snapshot,\n  }\n}\n\n/** Re-read immediately before each authorized side effect; this is not a lease. */\nexport function recheckDappReleaseEvidence(snapshotInput: unknown, policyInput: unknown, observationInput: unknown): DappReleaseEvidenceOutcome {\n  const previous = DappReleaseEvidenceSnapshotZod.safeParse(snapshotInput)\n  if (!previous.success) return refusal('blocked', 'malformed-snapshot')\n  const outcome = evaluateDappReleaseEvidence(policyInput, observationInput)\n  if (outcome.state !== 'eligible') return outcome\n  return canonicalizeIJson(previous.data) === canonicalizeIJson(outcome.snapshot)\n    ? outcome\n    : refusal('superseded', 'release-evidence-changed')\n}\n\nexport const DappReleaseBuildMetadataZod = z.strictObject({\n  repository: TextZod,\n  sourceRef: SourceRefZod,\n  sourceSha: GitCommitZod,\n  event: TextZod,\n  workflowPath: TextZod,\n  workflowSha: GitCommitZod,\n  runId: EvidenceIdZod,\n  runAttempt: EvidenceIdZod,\n  image: TextZod,\n  digest: z.string().refine(value => value.startsWith('sha256:') && HashZod.safeParse(value.slice(7)).success),\n})\nexport type DappReleaseBuildMetadata = z.infer<typeof DappReleaseBuildMetadataZod>\n\n/** Validates declared build provenance; this does not verify an OCI signature. */\nexport function verifyDappReleaseBuildMetadata(value: unknown, runInput: unknown, image: string): DappReleaseBuildMetadata {\n  const metadata = DappReleaseBuildMetadataZod.parse(value)\n  const run = DappReleaseWorkflowRunZod.parse(runInput)\n  if (run.status !== 'completed' || run.conclusion !== 'success' || run.headRepository !== run.repository\n    || metadata.repository !== run.repository || metadata.sourceRef !== run.sourceRef || metadata.sourceSha !== run.sourceSha\n    || metadata.event !== run.event || metadata.workflowPath !== run.workflowPath || metadata.workflowSha !== run.sourceSha\n    || metadata.runId !== run.id || metadata.runAttempt !== run.attempt || metadata.image !== image) {\n    throw new TypeError('build metadata does not match the successful workflow run and image')\n  }\n  return metadata\n}\n", "import { asSchema } from '@xyo-network/sdk'\nimport { z } from 'zod'\n\nimport { HashZod, IdentifierZod } from './identifier.ts'\nexport const DappRunRecordSchema = asSchema('network.xyo.dapp.run.record', true)\n\nexport const DappRunPhaseZod = z.enum([\n  'planning',\n  'provisioning',\n  'starting',\n  'ready',\n  'draining',\n  'stopped',\n  'failed',\n])\n\nexport type DappRunPhase = z.infer<typeof DappRunPhaseZod>\n\nexport const DappRunProcessZod = z.strictObject({\n  componentId: IdentifierZod,\n  processId: z.number().int().positive(),\n  executable: z.string().min(1),\n})\n\nexport type DappRunProcess = z.infer<typeof DappRunProcessZod>\n\nexport const DappRunRecordZod = z.strictObject({\n  schema: z.literal(DappRunRecordSchema),\n  schemaVersion: z.literal(1),\n  runId: IdentifierZod,\n  deploymentName: IdentifierZod,\n  repositoryRoot: z.string().min(1),\n  lockId: HashZod,\n  planId: HashZod,\n  systemInstanceId: IdentifierZod.optional(),\n  phase: DappRunPhaseZod,\n  startedAt: z.iso.datetime({ offset: true }),\n  updatedAt: z.iso.datetime({ offset: true }),\n  stoppedAt: z.iso.datetime({ offset: true }).optional(),\n  hostSessionIds: z.record(IdentifierZod, IdentifierZod),\n  allocatedPorts: z.record(IdentifierZod, z.number().int().min(1).max(65_535)),\n  logPaths: z.record(IdentifierZod, z.string().min(1)),\n  processes: z.array(DappRunProcessZod),\n  failureCode: IdentifierZod.optional(),\n}).superRefine((record, context) => {\n  const processIds = record.processes.map(componentProcess => componentProcess.processId)\n  const unique = new Set(processIds)\n  if (unique.size !== processIds.length) {\n    context.addIssue({\n      code: 'custom', message: 'process IDs must be unique', path: ['processes'],\n    })\n  }\n  if ((record.phase === 'stopped' || record.phase === 'failed') !== (record.stoppedAt !== undefined)) {\n    context.addIssue({\n      code: 'custom',\n      message: 'terminal run phases require stoppedAt and nonterminal phases forbid it',\n      path: ['stoppedAt'],\n    })\n  }\n  if ((record.phase === 'failed') !== (record.failureCode !== undefined)) {\n    context.addIssue({\n      code: 'custom',\n      message: 'only failed runs require a failure code',\n      path: ['failureCode'],\n    })\n  }\n})\n\nexport type DappRunRecord = z.infer<typeof DappRunRecordZod>\n", "import { asSchema } from '@xyo-network/sdk'\nimport { z } from 'zod'\n\nimport {\n  Base64UrlZod,\n  HashZod,\n  IdentifierZod,\n} from './identifier.ts'\nexport const DappSecretBoxSchema = asSchema('network.xyo.dapp.secret.box', true)\nexport const DappSecretBoxAlgorithm = 'aes-256-gcm-v1' as const\n\n/**\n * Portable authenticated-encryption envelope. The key remains behind the\n * capability that produced it; this document contains ciphertext only.\n */\nexport const DappSecretBoxZod = z.strictObject({\n  schema: z.literal(DappSecretBoxSchema),\n  schemaVersion: z.literal(1),\n  algorithm: z.literal(DappSecretBoxAlgorithm),\n  keyId: IdentifierZod,\n  initializationVector: Base64UrlZod,\n  ciphertext: Base64UrlZod,\n  authenticationTag: Base64UrlZod,\n  additionalDataHash: HashZod,\n})\n\nexport type DappSecretBox = z.infer<typeof DappSecretBoxZod>\n\nexport interface DappSecretBoxCapability {\n  readonly algorithm: typeof DappSecretBoxAlgorithm\n  readonly keyId: string\n  readonly kind: 'secret-box'\n  commit(value: Uint8Array, additionalData: Uint8Array): Promise<string>\n  open(box: unknown, additionalData: Uint8Array): Promise<Uint8Array>\n  seal(plaintext: Uint8Array, additionalData: Uint8Array): Promise<DappSecretBox>\n}\n", "import { asSchema } from '@xyo-network/sdk'\nimport { z } from 'zod'\n\nimport type { HashedDappDocument } from './canonicalDocument.ts'\nimport { hashDappDocument } from './canonicalDocument.ts'\nimport {\n  DappIdZod,\n  HashZod,\n  IdentifierZod,\n  ProtocolVersionZod,\n  Xl1ChainIdZod,\n} from './identifier.ts'\nimport { SideChannelMessageKindZod } from './profile.ts'\nexport const SideChannelEnvelopeSchema = asSchema('network.xyo.dapp.side.channel.envelope', true)\nexport const SideChannelSignatureAlgorithm = 'xyo-secp256k1-compact-v1' as const\n\nconst UnixMillisecondsZod = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER)\nconst CompactSecp256k1SignatureZod = z.string().regex(/^[0-9a-f]{128}$/)\n\nconst SideChannelSigningEnvelopeShape = {\n  schema: z.literal(SideChannelEnvelopeSchema),\n  schemaVersion: z.literal(1),\n  dappId: DappIdZod,\n  protocolVersion: ProtocolVersionZod,\n  messageId: IdentifierZod,\n  correlationId: IdentifierZod,\n  sender: IdentifierZod,\n  audience: z.array(IdentifierZod).min(1),\n  kind: SideChannelMessageKindZod,\n  bodyHashAlgorithm: z.literal('sha256-v1'),\n  bodyHash: HashZod,\n  issuedAt: UnixMillisecondsZod,\n  expiresAt: UnixMillisecondsZod,\n  nonce: IdentifierZod,\n  chainContext: z.strictObject({\n    chainId: Xl1ChainIdZod,\n    finalizedBlock: z.number().int().nonnegative(),\n  }),\n  signatureAlgorithm: IdentifierZod,\n}\n\nfunction refineSideChannelEnvelope(\n  envelope: { audience: string[]; expiresAt: number; issuedAt: number },\n  context: z.RefinementCtx,\n): void {\n  const unique = new Set(envelope.audience)\n  if (unique.size !== envelope.audience.length) {\n    context.addIssue({\n      code: 'custom', message: 'audience values must be unique', path: ['audience'],\n    })\n  }\n  if (envelope.expiresAt <= envelope.issuedAt) {\n    context.addIssue({\n      code: 'custom', message: 'expiry must be after issuance', path: ['expiresAt'],\n    })\n  }\n}\n\nexport const SideChannelSigningEnvelopeZod = z.strictObject(SideChannelSigningEnvelopeShape)\n  .superRefine(refineSideChannelEnvelope)\n\nexport type SideChannelSigningEnvelope = z.infer<typeof SideChannelSigningEnvelopeZod>\n\nexport const SideChannelEnvelopeZod = z.strictObject({\n  ...SideChannelSigningEnvelopeShape,\n  signature: CompactSecp256k1SignatureZod,\n}).superRefine(refineSideChannelEnvelope)\n\nexport type SideChannelEnvelope = z.infer<typeof SideChannelEnvelopeZod>\n\nexport const SideChannelEnvelopeIssueCodes = [\n  'envelope.audience-mismatch',\n  'envelope.chain-id-mismatch',\n  'envelope.dapp-id-mismatch',\n  'envelope.expired',\n  'envelope.invalid',\n  'envelope.not-yet-valid',\n  'envelope.protocol-version-mismatch',\n  'envelope.replay',\n  'envelope.sender-unauthorized',\n  'envelope.signature-algorithm-unsupported',\n  'envelope.signature-invalid',\n] as const\n\nexport const SideChannelEnvelopeIssueCodeZod = z.enum(SideChannelEnvelopeIssueCodes)\nexport type SideChannelEnvelopeIssueCode = z.infer<typeof SideChannelEnvelopeIssueCodeZod>\n\nexport interface SideChannelSignatureVerificationInput {\n  algorithm: typeof SideChannelSignatureAlgorithm\n  sender: string\n  signature: string\n  signingHash: string\n}\n\nexport type SideChannelSignatureVerifier = (\n  input: SideChannelSignatureVerificationInput,\n) => boolean | Promise<boolean>\n\nexport interface SideChannelEnvelopeContext {\n  acceptedClockSkewMilliseconds: number\n  authorizedSenders: readonly string[]\n  expectedAudience: string\n  expectedChainId: string\n  expectedDappId: string\n  expectedProtocolVersion: string\n  now: number\n  seenMessageIds: readonly string[]\n  verifySignature: SideChannelSignatureVerifier\n}\n\nexport interface SideChannelEnvelopeIssue {\n  code: SideChannelEnvelopeIssueCode\n  path: (number | string)[]\n}\n\nexport interface SideChannelEnvelopeValidationSuccess {\n  signingHash: string\n  success: true\n  value: SideChannelEnvelope\n}\n\nexport interface SideChannelEnvelopeValidationFailure {\n  issues: SideChannelEnvelopeIssue[]\n  success: false\n}\n\nexport type SideChannelEnvelopeValidationResult = SideChannelEnvelopeValidationFailure | SideChannelEnvelopeValidationSuccess\n\nfunction signingEnvelope(envelope: SideChannelEnvelope): SideChannelSigningEnvelope {\n  const { signature: _signature, ...unsignedEnvelope } = envelope\n  return SideChannelSigningEnvelopeZod.parse(unsignedEnvelope)\n}\n\nexport function hashSideChannelEnvelopeForSigning(\n  value: unknown,\n): HashedDappDocument<SideChannelSigningEnvelope> {\n  const envelope = SideChannelEnvelopeZod.parse(value)\n  return hashDappDocument({\n    kind: 'side-channel-envelope',\n    schema: SideChannelSigningEnvelopeZod,\n    schemaVersion: 1,\n  }, signingEnvelope(envelope))\n}\n\nfunction structuralFailure(value: unknown): SideChannelEnvelopeValidationFailure | SideChannelEnvelope {\n  const result = SideChannelEnvelopeZod.safeParse(value)\n  if (result.success) return result.data\n  return {\n    issues: result.error.issues.map(issue => ({\n      code: 'envelope.invalid',\n      path: issue.path.map(path => typeof path === 'symbol' ? path.description ?? path.toString() : path),\n    })),\n    success: false,\n  }\n}\n\nfunction scopeIssues(\n  envelope: SideChannelEnvelope,\n  context: SideChannelEnvelopeContext,\n): SideChannelEnvelopeIssue[] {\n  const issues: SideChannelEnvelopeIssue[] = []\n  if (envelope.dappId !== context.expectedDappId) {\n    issues.push({ code: 'envelope.dapp-id-mismatch', path: ['dappId'] })\n  }\n  if (envelope.protocolVersion !== context.expectedProtocolVersion) {\n    issues.push({ code: 'envelope.protocol-version-mismatch', path: ['protocolVersion'] })\n  }\n  if (envelope.chainContext.chainId !== context.expectedChainId) {\n    issues.push({ code: 'envelope.chain-id-mismatch', path: ['chainContext', 'chainId'] })\n  }\n  if (!context.authorizedSenders.includes(envelope.sender)) {\n    issues.push({ code: 'envelope.sender-unauthorized', path: ['sender'] })\n  }\n  if (!envelope.audience.includes(context.expectedAudience)) {\n    issues.push({ code: 'envelope.audience-mismatch', path: ['audience'] })\n  }\n  if (envelope.signatureAlgorithm !== SideChannelSignatureAlgorithm) {\n    issues.push({ code: 'envelope.signature-algorithm-unsupported', path: ['signatureAlgorithm'] })\n  }\n  return issues\n}\n\nfunction temporalIssues(\n  envelope: SideChannelEnvelope,\n  context: SideChannelEnvelopeContext,\n): SideChannelEnvelopeIssue[] {\n  const issues: SideChannelEnvelopeIssue[] = []\n  if (envelope.issuedAt > context.now + context.acceptedClockSkewMilliseconds) {\n    issues.push({ code: 'envelope.not-yet-valid', path: ['issuedAt'] })\n  }\n  if (envelope.expiresAt + context.acceptedClockSkewMilliseconds < context.now) {\n    issues.push({ code: 'envelope.expired', path: ['expiresAt'] })\n  }\n  if (context.seenMessageIds.includes(envelope.messageId)) {\n    issues.push({ code: 'envelope.replay', path: ['messageId'] })\n  }\n  return issues\n}\n\nasync function hasValidSignature(\n  envelope: SideChannelEnvelope,\n  context: SideChannelEnvelopeContext,\n  signingHash: string,\n): Promise<boolean> {\n  try {\n    return await context.verifySignature({\n      algorithm: SideChannelSignatureAlgorithm,\n      sender: envelope.sender,\n      signature: envelope.signature,\n      signingHash,\n    })\n  } catch {\n    return false\n  }\n}\n\nexport async function validateSideChannelEnvelope(\n  value: unknown,\n  context: SideChannelEnvelopeContext,\n): Promise<SideChannelEnvelopeValidationResult> {\n  const parsed = structuralFailure(value)\n  if ('success' in parsed) return parsed\n  const envelope = parsed\n\n  const identityIssues = scopeIssues(envelope, context)\n  if (identityIssues.length > 0) return { issues: identityIssues, success: false }\n\n  const signingArtifact = hashSideChannelEnvelopeForSigning(envelope)\n  if (!await hasValidSignature(envelope, context, signingArtifact.hash)) {\n    return {\n      issues: [{ code: 'envelope.signature-invalid', path: ['signature'] }],\n      success: false,\n    }\n  }\n\n  const validityIssues = temporalIssues(envelope, context)\n  return validityIssues.length > 0\n    ? { issues: validityIssues, success: false }\n    : {\n        signingHash: signingArtifact.hash, success: true, value: envelope,\n      }\n}\n", "import { asSchema } from '@xyo-network/sdk'\nimport { z } from 'zod'\n\nimport {\n  DappIdZod,\n  HashZod,\n  ProtocolVersionZod,\n} from './identifier.ts'\nimport { ApplicationPathZod } from './projectArtifact.ts'\nexport const DappSiteBootstrapSchema = asSchema('network.xyo.dapp.site.bootstrap', true)\n\nexport const DappSiteBootstrapZod = z.strictObject({\n  schema: z.literal(DappSiteBootstrapSchema),\n  schemaVersion: z.literal(1),\n  dappId: DappIdZod,\n  protocolVersion: ProtocolVersionZod,\n  planId: HashZod,\n  applicationPortPath: ApplicationPathZod,\n  bootstrapPath: ApplicationPathZod,\n  sessionPath: ApplicationPathZod,\n  statusPath: ApplicationPathZod,\n  readinessPath: ApplicationPathZod,\n  healthPath: ApplicationPathZod,\n}).superRefine((bootstrap, context) => {\n  const paths = [\n    bootstrap.applicationPortPath,\n    bootstrap.bootstrapPath,\n    bootstrap.sessionPath,\n    bootstrap.statusPath,\n    bootstrap.readinessPath,\n    bootstrap.healthPath,\n  ]\n  const unique = new Set(paths)\n  if (unique.size !== paths.length) {\n    context.addIssue({ code: 'custom', message: 'site bootstrap endpoint paths must be distinct' })\n  }\n})\n\nexport type DappSiteBootstrap = z.infer<typeof DappSiteBootstrapZod>\n", "import { asSchema } from '@xyo-network/sdk'\nimport { z } from 'zod'\n\nimport {\n  DappDocumentHashAlgorithm,\n  hashDappDocument,\n} from './canonicalDocument.ts'\nimport {\n  HashZod,\n  IdentifierZod,\n  SemanticVersionZod,\n} from './identifier.ts'\nimport {\n  ApplicationPathZod,\n  PackageNameZod,\n  PackageScriptNameZod,\n  RepositoryRelativePathZod,\n} from './projectArtifact.ts'\n\nexport const DappStaticSiteArtifactSchema = asSchema('network.xyo.dapp.site.static.artifact', true)\n\nexport const StaticSiteArtifactFileZod = z.strictObject({\n  path: RepositoryRelativePathZod,\n  sha256: HashZod,\n  size: z.number().int().nonnegative(),\n})\n\nexport type StaticSiteArtifactFile = z.infer<typeof StaticSiteArtifactFileZod>\n\nexport const DappStaticSiteArtifactManifestZod = z.strictObject({\n  schema: z.literal(DappStaticSiteArtifactSchema),\n  schemaVersion: z.literal(1),\n  hashAlgorithm: z.literal(DappDocumentHashAlgorithm),\n  artifactId: IdentifierZod,\n  package: z.strictObject({\n    name: PackageNameZod,\n    version: SemanticVersionZod,\n  }),\n  root: RepositoryRelativePathZod,\n  buildScript: PackageScriptNameZod,\n  outputDirectory: RepositoryRelativePathZod,\n  applicationPortPath: ApplicationPathZod,\n  spaFallback: z.boolean(),\n  files: z.array(StaticSiteArtifactFileZod).min(1),\n  buildInputHash: HashZod,\n  contentRoot: HashZod,\n}).superRefine((manifest, context) => {\n  const unique = new Set(manifest.files.map(file => file.path))\n  if (unique.size !== manifest.files.length) {\n    context.addIssue({\n      code: 'custom', message: 'static-site artifact file paths must be unique', path: ['files'],\n    })\n  }\n  const outputRoot = `${manifest.root}/${manifest.outputDirectory}/`\n  for (const [index, file] of manifest.files.entries()) {\n    if (!file.path.startsWith(outputRoot)) {\n      context.addIssue({\n        code: 'custom',\n        message: 'static-site artifact files must be children of the declared output directory',\n        path: ['files', index, 'path'],\n      })\n    }\n  }\n  if (hashStaticSiteArtifactContent(manifest.files) !== manifest.contentRoot) {\n    context.addIssue({\n      code: 'custom', message: 'content root does not match static-site artifact files', path: ['contentRoot'],\n    })\n  }\n})\n\nexport type DappStaticSiteArtifactManifest = z.infer<typeof DappStaticSiteArtifactManifestZod>\n\nexport function normalizeStaticSiteArtifactFiles(\n  files: readonly StaticSiteArtifactFile[],\n): StaticSiteArtifactFile[] {\n  return [...files].toSorted((left, right) => left.path.localeCompare(right.path))\n}\n\nexport function hashStaticSiteArtifactContent(filesValue: unknown): string {\n  const files = z.array(StaticSiteArtifactFileZod).parse(filesValue)\n  return hashDappDocument({\n    kind: 'static-site-artifact-content',\n    schema: z.array(StaticSiteArtifactFileZod),\n    schemaVersion: 1,\n  }, normalizeStaticSiteArtifactFiles(files)).hash\n}\n\nexport function normalizeDappStaticSiteArtifactManifest(value: unknown): DappStaticSiteArtifactManifest {\n  const manifest = DappStaticSiteArtifactManifestZod.parse(value)\n  return DappStaticSiteArtifactManifestZod.parse({\n    ...manifest,\n    files: normalizeStaticSiteArtifactFiles(manifest.files),\n  })\n}\n\nexport function hashDappStaticSiteArtifactManifest(value: unknown) {\n  const manifest = normalizeDappStaticSiteArtifactManifest(value)\n  return hashDappDocument({\n    kind: 'static-site-artifact-manifest',\n    schema: DappStaticSiteArtifactManifestZod,\n    schemaVersion: 1,\n  }, manifest)\n}\n", "import { asSchema } from '@xyo-network/sdk'\nimport { z } from 'zod'\n\nimport {\n  DappDocumentHashAlgorithm,\n  hashDappDocument,\n} from './canonicalDocument.ts'\nimport {\n  HashZod,\n  IdentifierZod,\n  SemanticVersionZod,\n} from './identifier.ts'\nimport { ContentDigestZod } from './infrastructureDescriptor.ts'\nimport { compareCodeUnits } from './ordering.ts'\n\n/**\n * Target-artifact admission (plan Section 8). Every target plan that deploys\n * bytes binds one of these, and the identity is a pure function of the exact\n * transformation inputs: the source artifacts, the transformation contract,\n * the builder, the complete member inventory, the platforms, and the\n * normalized runtime declarations.\n *\n * Two consequences the plan makes load-bearing follow from that. Two builds of\n * the same admitted source reproduce the same `targetArtifactAdmissionId`,\n * because nothing else enters the preimage. And a partial directory hash or a\n * mutable tag can never be admitted, because `contentManifestHash` covers the\n * complete byte and member inventory and `byteLength` must equal what that\n * inventory sums to -- so a missing member fails admission rather than\n * producing a plausible different identity.\n *\n * Admission is credential free by construction: this module is in the neutral\n * package, which cannot reach a filesystem, a provider, or a registry.\n */\nexport const DappTargetArtifactAdmissionSchema = asSchema('network.xyo.dapp.target.artifact.admission', true)\n\nexport const TargetArtifactKindZod = z.enum(['vercel-output', 'cloudflare-worker-bundle', 'oci-image', 'proxmox-guest-workload'])\nexport type TargetArtifactKind = z.infer<typeof TargetArtifactKindZod>\n\n/** The kinds MI5A admits: an edge bundle runs inside a provider runtime and has no guest of its own. */\nexport const EdgeTargetArtifactKinds: readonly TargetArtifactKind[] = ['vercel-output', 'cloudflare-worker-bundle']\n\n/** The kinds MI5C admits: a workload runs as its own process, so it declares how to start and probe it. */\nexport const WorkloadTargetArtifactKinds: readonly TargetArtifactKind[] = ['oci-image', 'proxmox-guest-workload']\n\nexport const AllTargetArtifactKinds: readonly TargetArtifactKind[] = [...EdgeTargetArtifactKinds, ...WorkloadTargetArtifactKinds]\n\n/** The manifest media types an `oci-image` digest may address; a tarball or a bundle is not an image. */\nconst OciManifestMediaTypes: ReadonlySet<string> = new Set([\n  'application/vnd.docker.distribution.manifest.list.v2+json',\n  'application/vnd.docker.distribution.manifest.v2+json',\n  'application/vnd.oci.image.index.v1+json',\n  'application/vnd.oci.image.manifest.v1+json',\n])\n\nconst MemberPathZod = z.string().min(1).max(1024).regex(/^[^/](?:[^\\s\\\\]*[^/\\s\\\\])?$/, 'a member path is relative, non-empty, and has no trailing slash')\n\n/** One member of the complete inventory: an exact path, its digest, and its exact length. */\nexport const TargetArtifactMemberZod = z.strictObject({\n  path: MemberPathZod,\n  sha256: HashZod,\n  byteLength: z.number().int().nonnegative(),\n})\nexport type TargetArtifactMember = z.infer<typeof TargetArtifactMemberZod>\n\nexport function compareTargetArtifactMembers(left: TargetArtifactMember, right: TargetArtifactMember): number {\n  return compareCodeUnits(left.path, right.path)\n}\n\nexport function normalizeTargetArtifactMembers(members: readonly TargetArtifactMember[]): TargetArtifactMember[] {\n  return [...members].toSorted(compareTargetArtifactMembers)\n}\n\n/**\n * The identity of the complete member inventory. It is taken over the sorted\n * inventory rather than the directory, so an omitted member changes it and a\n * reordered listing does not.\n */\nexport function hashTargetArtifactContentManifest(membersValue: unknown): string {\n  const members = z.array(TargetArtifactMemberZod).min(1).parse(membersValue)\n  const paths = members.map(member => member.path)\n  const unique = new Set(paths)\n  if (unique.size !== paths.length) throw new TypeError('target artifact member paths must be unique')\n  return hashDappDocument({\n    kind: 'target-artifact-content-manifest', schema: z.array(TargetArtifactMemberZod), schemaVersion: 1,\n  }, normalizeTargetArtifactMembers(members)).hash\n}\n\nexport const TargetArtifactSourceZod = z.strictObject({ artifactId: IdentifierZod, contentHash: HashZod })\nexport type TargetArtifactSource = z.infer<typeof TargetArtifactSourceZod>\n\n/** The transformation contract tuple, which must equal one entry of the adapter descriptor's `supportedContracts`. */\nexport const TargetTransformationContractZod = z.strictObject({\n  schema: z.string().regex(/^[a-z0-9]+(?:\\.[a-z0-9]+)*$/),\n  schemaVersion: z.number().int().positive(),\n  schemaHash: HashZod,\n})\n\nexport const TargetArtifactBuilderZod = z.strictObject({\n  name: IdentifierZod,\n  version: SemanticVersionZod,\n  implementationHash: HashZod,\n})\n\n/** Nullable platform fields are explicit `null`, so an absent variant is never confused with an unstated one. */\nexport const TargetArtifactPlatformZod = z.strictObject({\n  os: z.enum(['darwin', 'linux', 'windows']),\n  architecture: z.enum(['amd64', 'arm64']),\n  variant: z.string().min(1).max(32).nullable(),\n  libc: z.enum(['glibc', 'musl']).nullable(),\n})\nexport type TargetArtifactPlatform = z.infer<typeof TargetArtifactPlatformZod>\n\nfunction platformKey(platform: TargetArtifactPlatform): string {\n  return `${platform.os}\\u{0}${platform.architecture}\\u{0}${platform.variant ?? ''}\\u{0}${platform.libc ?? ''}`\n}\n\nexport function compareTargetArtifactPlatforms(left: TargetArtifactPlatform, right: TargetArtifactPlatform): number {\n  return compareCodeUnits(platformKey(left), platformKey(right))\n}\n\nexport const TargetArtifactContentZod = z.strictObject({\n  mediaType: z.string().regex(/^[a-z0-9][a-z0-9!#$&^_.+-]*\\/[a-z0-9][a-z0-9!#$&^_.+-]*$/),\n  /** The exact canonical local digest of the complete content; for `oci-image` the immutable registry digest. */\n  contentDigest: ContentDigestZod,\n  byteLength: z.number().int().nonnegative(),\n  contentManifestHash: HashZod,\n})\n\n/**\n * Normalized, public-safe runtime declarations. The plan forbids any route,\n * credential, secret, grant, or host-private value here, so the shape admits\n * only the declarations a target needs to run and probe.\n */\nexport const TargetArtifactRuntimeZod = z.strictObject({\n  entrypoint: z.array(z.string().min(1)).min(1),\n  ports: z.array(z.strictObject({\n    name: IdentifierZod, containerPort: z.number().int().min(1).max(65_535), protocol: z.enum(['tcp', 'udp']),\n  })),\n  health: z.strictObject({ path: z.string().regex(/^\\/[^\\s?#]*$/), expectedStatus: z.number().int().min(100).max(599) }).nullable(),\n  readiness: z.strictObject({ path: z.string().regex(/^\\/[^\\s?#]*$/), expectedStatus: z.number().int().min(100).max(599) }).nullable(),\n  bootstrap: z.strictObject({ contractId: IdentifierZod, contractHash: HashZod }).nullable(),\n})\n\ninterface RefinementContext {\n  addIssue: (issue: { code: 'custom'; message: string; path: (number | string)[] }) => void\n}\n\ninterface KindRefinement {\n  content: z.infer<typeof TargetArtifactContentZod>\n  runtime: z.infer<typeof TargetArtifactRuntimeZod>\n  targetArtifactKind: TargetArtifactKind\n}\n\n/**\n * The rules that differ by kind. An edge bundle is handed to a provider\n * runtime that already knows how to start it, so it declares no bootstrap; a\n * workload runs as its own process, so it must declare how to start it, at\n * least one port to reach it on, and the health and readiness contract a\n * consuming target gates on. An `oci-image` additionally addresses an\n * immutable registry manifest, never a tarball and never a mutable tag.\n */\nfunction refineKind(admission: KindRefinement, context: RefinementContext): void {\n  const workload = WorkloadTargetArtifactKinds.includes(admission.targetArtifactKind)\n  if (!workload && admission.runtime.bootstrap !== null) {\n    context.addIssue({\n      code: 'custom', message: 'an edge bundle runs inside a provider runtime and declares no bootstrap contract', path: ['runtime', 'bootstrap'],\n    })\n  }\n  if (admission.targetArtifactKind === 'proxmox-guest-workload' && admission.runtime.bootstrap === null) {\n    context.addIssue({\n      code: 'custom', message: 'a guest workload is installed and launched by an admitted bootstrap contract', path: ['runtime', 'bootstrap'],\n    })\n  }\n  if (admission.targetArtifactKind === 'oci-image' && !OciManifestMediaTypes.has(admission.content.mediaType)) {\n    context.addIssue({\n      code: 'custom', message: 'an oci-image digest addresses an OCI or Docker manifest, not an archive', path: ['content', 'mediaType'],\n    })\n  }\n  if (!workload) return\n  if (admission.runtime.ports.length === 0) {\n    context.addIssue({\n      code: 'custom', message: 'a workload artifact declares at least one port', path: ['runtime', 'ports'],\n    })\n  }\n  if (admission.runtime.health === null || admission.runtime.readiness === null) {\n    context.addIssue({\n      code: 'custom', message: 'a workload artifact declares the complete health and readiness probe contract', path: ['runtime', 'health'],\n    })\n  }\n}\n\nexport const DappTargetArtifactAdmissionV1PreimageZod = z.strictObject({\n  schema: z.literal(DappTargetArtifactAdmissionSchema),\n  schemaVersion: z.literal(1),\n  hashAlgorithm: z.literal(DappDocumentHashAlgorithm),\n  targetArtifactKind: TargetArtifactKindZod,\n  targetAdapterDescriptorHash: HashZod,\n  sourceArtifacts: z.array(TargetArtifactSourceZod).min(1),\n  transformationContract: TargetTransformationContractZod,\n  builder: TargetArtifactBuilderZod,\n  content: TargetArtifactContentZod,\n  platforms: z.array(TargetArtifactPlatformZod).min(1),\n  runtime: TargetArtifactRuntimeZod,\n}).superRefine((admission, context) => {\n  const ids = admission.sourceArtifacts.map(entry => entry.artifactId)\n  const unique2 = new Set(ids)\n  if (unique2.size !== ids.length) {\n    context.addIssue({\n      code: 'custom', message: 'source artifacts must be unique by artifactId', path: ['sourceArtifacts'],\n    })\n  }\n  if (ids.some((id, index) => index > 0 && compareCodeUnits(ids[index - 1] ?? '', id) >= 0)) {\n    context.addIssue({\n      code: 'custom', message: 'source artifacts must be sorted by artifactId', path: ['sourceArtifacts'],\n    })\n  }\n  const platforms = admission.platforms.map(platformKey)\n  const unique3 = new Set(platforms)\n  if (unique3.size !== platforms.length) {\n    context.addIssue({\n      code: 'custom', message: 'platforms must be unique', path: ['platforms'],\n    })\n  }\n  if (platforms.some((key, index) => index > 0 && compareCodeUnits(platforms[index - 1] ?? '', key) >= 0)) {\n    context.addIssue({\n      code: 'custom', message: 'platforms must be sorted', path: ['platforms'],\n    })\n  }\n  refineKind(admission, context)\n})\nexport type DappTargetArtifactAdmissionV1Preimage = z.infer<typeof DappTargetArtifactAdmissionV1PreimageZod>\n\nexport const DappTargetArtifactAdmissionV1Zod = DappTargetArtifactAdmissionV1PreimageZod.safeExtend({ targetArtifactAdmissionId: HashZod })\nexport type DappTargetArtifactAdmissionV1 = z.infer<typeof DappTargetArtifactAdmissionV1Zod>\n\nexport function hashDappTargetArtifactAdmissionV1(preimage: unknown): string {\n  return hashDappDocument({\n    kind: 'target-artifact-admission', schema: DappTargetArtifactAdmissionV1PreimageZod, schemaVersion: 1,\n  }, preimage).hash\n}\n\nexport function verifyDappTargetArtifactAdmissionV1(value: unknown): DappTargetArtifactAdmissionV1 {\n  const admission = DappTargetArtifactAdmissionV1Zod.parse(value)\n  const { targetArtifactAdmissionId, ...preimage } = admission\n  if (hashDappTargetArtifactAdmissionV1(preimage) !== targetArtifactAdmissionId) {\n    throw new TypeError('target artifact admission does not reproduce its identity')\n  }\n  return admission\n}\n\nexport interface AdmitTargetArtifactInput {\n  readonly builder: z.infer<typeof TargetArtifactBuilderZod>\n  readonly contentDigest: string\n  readonly mediaType: string\n  /** The complete inventory. Admission fails if it does not account for every declared byte. */\n  readonly members: readonly TargetArtifactMember[]\n  readonly platforms: readonly TargetArtifactPlatform[]\n  readonly runtime: z.infer<typeof TargetArtifactRuntimeZod>\n  readonly sourceArtifacts: readonly TargetArtifactSource[]\n  readonly targetAdapterDescriptorHash: string\n  readonly targetArtifactKind: TargetArtifactKind\n  readonly transformationContract: z.infer<typeof TargetTransformationContractZod>\n}\n\nexport interface TargetArtifactAdmissionIssue {\n  code: 'target-artifact.incomplete-inventory' | 'target-artifact.invalid' | 'target-artifact.unsupported-kind'\n  message: string\n  path: (number | string)[]\n}\n\nexport type AdmitTargetArtifactResult\n  = { issues: TargetArtifactAdmissionIssue[]; success: false }\n    | { success: true; value: DappTargetArtifactAdmissionV1 }\n\n/**\n * Admits one target artifact from its complete inventory. The byte length is\n * derived from the members rather than declared, so an inventory that omits a\n * member cannot describe the same artifact: it either fails here or admits a\n * visibly different one. Nothing about the local filesystem, a provider, or a\n * registry enters this function.\n */\nexport function admitDappTargetArtifactV1(input: AdmitTargetArtifactInput, admittedKinds: readonly TargetArtifactKind[] = EdgeTargetArtifactKinds): AdmitTargetArtifactResult {\n  if (!admittedKinds.includes(input.targetArtifactKind)) {\n    return {\n      issues: [{\n        code: 'target-artifact.unsupported-kind', message: `target artifact kind ${input.targetArtifactKind} is not admitted by this slice`, path: ['targetArtifactKind'],\n      }],\n      success: false,\n    }\n  }\n  const issues: TargetArtifactAdmissionIssue[] = []\n  let contentManifestHash: string\n  try {\n    contentManifestHash = hashTargetArtifactContentManifest(input.members)\n  } catch (error) {\n    return {\n      issues: [{\n        code: 'target-artifact.incomplete-inventory', message: error instanceof Error ? error.message : String(error), path: ['members'],\n      }],\n      success: false,\n    }\n  }\n  const byteLength = input.members.reduce((total, member) => total + member.byteLength, 0)\n  const preimage = {\n    schema: DappTargetArtifactAdmissionSchema,\n    schemaVersion: 1 as const,\n    hashAlgorithm: DappDocumentHashAlgorithm,\n    targetArtifactKind: input.targetArtifactKind,\n    targetAdapterDescriptorHash: input.targetAdapterDescriptorHash,\n    sourceArtifacts: [...input.sourceArtifacts].toSorted((left, right) => compareCodeUnits(left.artifactId, right.artifactId)),\n    transformationContract: input.transformationContract,\n    builder: input.builder,\n    content: {\n      mediaType: input.mediaType, contentDigest: input.contentDigest, byteLength, contentManifestHash,\n    },\n    platforms: [...input.platforms].toSorted(compareTargetArtifactPlatforms),\n    runtime: input.runtime,\n  }\n  const parsed = DappTargetArtifactAdmissionV1PreimageZod.safeParse(preimage)\n  if (!parsed.success) {\n    for (const issue of parsed.error.issues) issues.push({\n      code: 'target-artifact.invalid', message: issue.message, path: issue.path.map(entry => (typeof entry === 'symbol' ? String(entry) : entry)),\n    })\n    return { issues, success: false }\n  }\n  return { success: true, value: { ...parsed.data, targetArtifactAdmissionId: hashDappTargetArtifactAdmissionV1(parsed.data) } }\n}\n", "import { asSchema } from '@xyo-network/sdk'\nimport { z } from 'zod'\n\nimport {\n  DappDocumentHashAlgorithm,\n  hashDappDocument,\n} from './canonicalDocument.ts'\nimport {\n  HashZod,\n  IdentifierZod,\n} from './identifier.ts'\nexport const DappTargetCompositionSchema = asSchema('network.xyo.dapp.target.composition', true)\n\nexport const DappTargetComponentZod = z.strictObject({\n  componentId: IdentifierZod,\n  targetKind: IdentifierZod,\n  targetPlanId: HashZod,\n})\n\nexport type DappTargetComponent = z.infer<typeof DappTargetComponentZod>\n\nexport const DappTargetResourceBindingZod = z.strictObject({\n  componentId: IdentifierZod,\n  resourceId: IdentifierZod,\n})\n\nexport type DappTargetResourceBinding = z.infer<typeof DappTargetResourceBindingZod>\n\nexport const DappTargetCompositionPreimageZod = z.strictObject({\n  schema: z.literal(DappTargetCompositionSchema),\n  schemaVersion: z.literal(1),\n  hashAlgorithm: z.literal(DappDocumentHashAlgorithm),\n  lockId: HashZod,\n  components: z.array(DappTargetComponentZod).min(1),\n  resourceBindings: z.array(DappTargetResourceBindingZod),\n}).superRefine((composition, context) => {\n  const componentIds = composition.components.map(component => component.componentId)\n  const unique = new Set(componentIds)\n  if (unique.size !== componentIds.length) {\n    context.addIssue({\n      code: 'custom',\n      message: 'target component IDs must be unique',\n      path: ['components'],\n    })\n  }\n  const knownComponents = new Set(componentIds)\n  const resourceIds = composition.resourceBindings.map(binding => binding.resourceId)\n  const unique2 = new Set(resourceIds)\n  if (unique2.size !== resourceIds.length) {\n    context.addIssue({\n      code: 'custom',\n      message: 'target resources may each be bound once',\n      path: ['resourceBindings'],\n    })\n  }\n  for (const [index, binding] of composition.resourceBindings.entries()) {\n    if (!knownComponents.has(binding.componentId)) {\n      context.addIssue({\n        code: 'custom',\n        message: `target resource references unknown component ${binding.componentId}`,\n        path: ['resourceBindings', index, 'componentId'],\n      })\n    }\n  }\n})\n\nexport type DappTargetCompositionPreimage = z.infer<typeof DappTargetCompositionPreimageZod>\n\nexport const DappTargetCompositionZod = DappTargetCompositionPreimageZod.safeExtend({ compositionId: HashZod })\nexport type DappTargetComposition = z.infer<typeof DappTargetCompositionZod>\n\nfunction normalized(value: unknown): DappTargetCompositionPreimage {\n  const composition = DappTargetCompositionPreimageZod.parse(value)\n  return DappTargetCompositionPreimageZod.parse({\n    ...composition,\n    components: [...composition.components].toSorted((left, right) => left.componentId.localeCompare(right.componentId)),\n    resourceBindings: [...composition.resourceBindings].toSorted((left, right) => left.resourceId.localeCompare(right.resourceId)),\n  })\n}\n\nexport function hashDappTargetComposition(value: unknown): string {\n  return hashDappDocument({\n    kind: 'target-composition',\n    schema: DappTargetCompositionPreimageZod,\n    schemaVersion: 1,\n  }, normalized(value)).hash\n}\n\nexport function createDappTargetComposition(value: unknown): DappTargetComposition {\n  const preimage = normalized(value)\n  return DappTargetCompositionZod.parse({\n    ...preimage,\n    compositionId: hashDappTargetComposition(preimage),\n  })\n}\n\nexport function verifyDappTargetComposition(value: unknown): DappTargetComposition {\n  const composition = DappTargetCompositionZod.parse(value)\n  const { compositionId, ...unresolvedPreimage } = composition\n  const preimage = normalized(unresolvedPreimage)\n  if (hashDappTargetComposition(preimage) !== compositionId) {\n    throw new TypeError('target composition ID does not match its canonical preimage')\n  }\n  return DappTargetCompositionZod.parse({ ...preimage, compositionId })\n}\n", "import { z } from 'zod'\n\nimport {\n  DappDocumentHashAlgorithm,\n  hashDappDocument,\n} from './canonicalDocument.ts'\nimport { DappTargetFamilyZod } from './deploymentManifest.ts'\nimport {\n  HashZod,\n  IdentifierZod,\n} from './identifier.ts'\nimport { DappTargetCompositionSchema } from './targetComposition.ts'\n\nexport const DappThingTargetPlanBindingZod = z.strictObject({\n  thingId: IdentifierZod,\n  targetFamily: DappTargetFamilyZod,\n  targetPlanId: HashZod,\n})\n\nexport type DappThingTargetPlanBinding = z.infer<typeof DappThingTargetPlanBindingZod>\n\nexport const DappThingResourceBindingZod = z.strictObject({\n  thingId: IdentifierZod,\n  resourceId: IdentifierZod,\n})\n\nexport type DappThingResourceBinding = z.infer<typeof DappThingResourceBindingZod>\n\nexport const DappTargetCompositionV2PreimageZod = z.strictObject({\n  schema: z.literal(DappTargetCompositionSchema),\n  schemaVersion: z.literal(2),\n  hashAlgorithm: z.literal(DappDocumentHashAlgorithm),\n  lockId: HashZod,\n  things: z.array(DappThingTargetPlanBindingZod).min(1),\n  resourceBindings: z.array(DappThingResourceBindingZod),\n}).superRefine((composition, context) => {\n  const thingIds = composition.things.map(thing => thing.thingId)\n  const unique = new Set(thingIds)\n  if (unique.size !== thingIds.length) {\n    context.addIssue({\n      code: 'custom', message: 'each thing must be bound exactly once', path: ['things'],\n    })\n  }\n  const knownThings = new Set(thingIds)\n  const resourceIds = composition.resourceBindings.map(binding => binding.resourceId)\n  const unique2 = new Set(resourceIds)\n  if (unique2.size !== resourceIds.length) {\n    context.addIssue({\n      code: 'custom', message: 'each resource must be bound exactly once', path: ['resourceBindings'],\n    })\n  }\n  for (const [index, binding] of composition.resourceBindings.entries()) {\n    if (!knownThings.has(binding.thingId)) {\n      context.addIssue({\n        code: 'custom',\n        message: `target resource references unknown thing ${binding.thingId}`,\n        path: ['resourceBindings', index, 'thingId'],\n      })\n    }\n  }\n})\n\nexport type DappTargetCompositionV2Preimage = z.infer<typeof DappTargetCompositionV2PreimageZod>\nexport const DappTargetCompositionV2Zod = DappTargetCompositionV2PreimageZod.safeExtend({ compositionId: HashZod })\nexport type DappTargetCompositionV2 = z.infer<typeof DappTargetCompositionV2Zod>\n\nfunction normalized(value: unknown): DappTargetCompositionV2Preimage {\n  const composition = DappTargetCompositionV2PreimageZod.parse(value)\n  return DappTargetCompositionV2PreimageZod.parse({\n    ...composition,\n    things: [...composition.things].toSorted((left, right) => left.thingId.localeCompare(right.thingId)),\n    resourceBindings: [...composition.resourceBindings].toSorted((left, right) => left.resourceId.localeCompare(right.resourceId)),\n  })\n}\n\nexport function hashDappTargetCompositionV2(value: unknown): string {\n  return hashDappDocument({\n    kind: 'target-composition',\n    schema: DappTargetCompositionV2PreimageZod,\n    schemaVersion: 2,\n  }, normalized(value)).hash\n}\n\nexport function createDappTargetCompositionV2(value: unknown): DappTargetCompositionV2 {\n  const preimage = normalized(value)\n  return DappTargetCompositionV2Zod.parse({ ...preimage, compositionId: hashDappTargetCompositionV2(preimage) })\n}\n\nexport function verifyDappTargetCompositionV2(value: unknown): DappTargetCompositionV2 {\n  const composition = DappTargetCompositionV2Zod.parse(value)\n  const { compositionId, ...preimageValue } = composition\n  const preimage = normalized(preimageValue)\n  if (hashDappTargetCompositionV2(preimage) !== compositionId) {\n    throw new TypeError('target composition ID does not match its canonical V2 preimage')\n  }\n  return DappTargetCompositionV2Zod.parse({ ...preimage, compositionId })\n}\n", "import { z } from 'zod'\n\nimport {\n  canonicalizeIJson,\n  DappDocumentHashAlgorithm,\n  hashDappDocument,\n} from './canonicalDocument.ts'\nimport type { DappDeploymentLockV3 } from './deploymentLockV3.ts'\nimport { DappInfrastructureKindZod } from './deploymentManifestV2.ts'\nimport {\n  HashZod,\n  IdentifierZod,\n  SemanticVersionZod,\n} from './identifier.ts'\nimport {\n  type DappInfrastructureAdapterDescriptorV1,\n  DappInfrastructureIdZod,\n} from './infrastructureDescriptor.ts'\nimport {\n  DappManagedCapabilityContractRefZod,\n  type DappManagedCapabilityExportV1,\n  type DappManagedCapabilityImportV1,\n} from './managedCapability.ts'\nimport {\n  compareCodeUnits,\n  compareNumbers,\n  findSortedUniqueIssue,\n} from './ordering.ts'\nimport { DappTargetCompositionSchema } from './targetComposition.ts'\nimport {\n  DappTargetObjectIdentitySchema,\n  hashDappTargetObjectIdentityV1,\n} from './targetObjectIdentity.ts'\nimport {\n  DappTargetObjectV1Zod,\n  DappTargetPlanEnvelopeV1Fields,\n  type DappTargetPlanIssue,\n  verifyDappTargetPlanEnvelopeV1,\n} from './targetPlanEnvelope.ts'\n\n/**\n * Target Composition V3 (plan Section 4.5, MI1D). The composition binds the\n * immutable infrastructure IDs of one Lock V3 to the target plans that\n * consume its slices, and binds every thing, non-external resource, host\n * partition, managed capability, and target object exactly once. Neither an\n * alias, a connection profile, a credential grant, nor a scope commitment\n * enters it. The unsuffixed and V2 compositions remain unchanged.\n */\nexport const DappTargetCompositionInfrastructureV3Zod = z.strictObject({\n  infrastructureId: DappInfrastructureIdZod,\n  kind: DappInfrastructureKindZod,\n  adapterId: IdentifierZod,\n  adapterVersion: SemanticVersionZod,\n  adapterDescriptorHash: HashZod,\n  infrastructureDescriptorHash: HashZod,\n  infrastructurePolicyHash: HashZod,\n  targetPlanId: HashZod,\n})\nexport type DappTargetCompositionInfrastructureV3 = z.infer<typeof DappTargetCompositionInfrastructureV3Zod>\n\nexport const DappThingInfrastructureBindingV3Zod = z.strictObject({ thingId: IdentifierZod, infrastructureId: DappInfrastructureIdZod })\nexport const DappResourceOwnerBindingV3Zod = z.strictObject({ resourceId: IdentifierZod, owningInfrastructureId: DappInfrastructureIdZod })\nexport const DappHostInfrastructureBindingV3Zod = z.strictObject({ hostPartitionId: IdentifierZod, infrastructureId: DappInfrastructureIdZod })\n\n/** One producer export matched to one consumer import, bound to both target plans. */\nexport const DappManagedCapabilityBindingV3Zod = z.strictObject({\n  resourceId: IdentifierZod,\n  owningInfrastructureId: DappInfrastructureIdZod,\n  consumerInfrastructureId: DappInfrastructureIdZod,\n  producerTargetPlanId: HashZod,\n  consumerTargetPlanId: HashZod,\n  ...DappManagedCapabilityContractRefZod.shape,\n  exportIdentityHash: HashZod,\n})\nexport type DappManagedCapabilityBindingV3 = z.infer<typeof DappManagedCapabilityBindingV3Zod>\n\nexport function compareDappManagedCapabilityBindingsV3(left: DappManagedCapabilityBindingV3, right: DappManagedCapabilityBindingV3): number {\n  return compareCodeUnits(left.resourceId, right.resourceId)\n    || compareCodeUnits(left.owningInfrastructureId, right.owningInfrastructureId)\n    || compareCodeUnits(left.consumerInfrastructureId, right.consumerInfrastructureId)\n    || compareCodeUnits(left.consumerTargetPlanId, right.consumerTargetPlanId)\n    || compareCodeUnits(left.exportContractId, right.exportContractId)\n    || compareNumbers(left.exportContractVersion, right.exportContractVersion)\n}\n\ninterface RefinementContext {\n  addIssue: (issue: { code: 'custom'; message: string; path: (number | string)[] }) => void\n}\n\nfunction refineSorted<T>(context: RefinementContext, values: readonly T[], compare: (left: T, right: T) => number, field: string): void {\n  const issue = findSortedUniqueIssue(values, compare, field)\n  if (issue !== undefined) {\n    context.addIssue({\n      code: 'custom', message: issue.message, path: [field, issue.index],\n    })\n  }\n}\n\nconst CompositionFields = {\n  schema: z.literal(DappTargetCompositionSchema),\n  schemaVersion: z.literal(3),\n  hashAlgorithm: z.literal(DappDocumentHashAlgorithm),\n  lockId: HashZod,\n  infrastructure: z.array(DappTargetCompositionInfrastructureV3Zod).min(1),\n  thingBindings: z.array(DappThingInfrastructureBindingV3Zod),\n  resourceBindings: z.array(DappResourceOwnerBindingV3Zod),\n  hostBindings: z.array(DappHostInfrastructureBindingV3Zod),\n  managedCapabilityBindings: z.array(DappManagedCapabilityBindingV3Zod),\n  targetObjects: z.array(DappTargetObjectV1Zod),\n}\ntype CompositionShape = z.infer<z.ZodObject<typeof CompositionFields>>\n\nfunction refineBindings(composition: CompositionShape, context: RefinementContext): void {\n  refineSorted(context, composition.infrastructure, (left, right) => compareCodeUnits(left.infrastructureId, right.infrastructureId), 'infrastructure')\n  refineSorted(context, composition.thingBindings, (left, right) => compareCodeUnits(left.thingId, right.thingId), 'thingBindings')\n  refineSorted(context, composition.resourceBindings, (left, right) => compareCodeUnits(left.resourceId, right.resourceId), 'resourceBindings')\n  refineSorted(context, composition.hostBindings, (left, right) => compareCodeUnits(left.hostPartitionId, right.hostPartitionId), 'hostBindings')\n  refineSorted(context, composition.managedCapabilityBindings, compareDappManagedCapabilityBindingsV3, 'managedCapabilityBindings')\n  refineSorted(context, composition.targetObjects, (left, right) => compareCodeUnits(left.targetObjectId, right.targetObjectId), 'targetObjects')\n  const known = new Set(composition.infrastructure.map(entry => entry.infrastructureId))\n  const referenced = new Set<string>()\n  for (const [field, ids] of [\n    ['thingBindings', composition.thingBindings.map(entry => entry.infrastructureId)],\n    ['resourceBindings', composition.resourceBindings.map(entry => entry.owningInfrastructureId)],\n    ['hostBindings', composition.hostBindings.map(entry => entry.infrastructureId)],\n  ] as const) {\n    for (const [index, id] of ids.entries()) {\n      referenced.add(id)\n      if (!known.has(id)) {\n        context.addIssue({\n          code: 'custom', message: `binding names infrastructure ${id}, which the composition does not select`, path: [field, index],\n        })\n      }\n    }\n  }\n  for (const entry of composition.infrastructure) {\n    if (!referenced.has(entry.infrastructureId)) {\n      context.addIssue({\n        code: 'custom', message: `infrastructure ${entry.infrastructureId} binds nothing`, path: ['infrastructure'],\n      })\n    }\n  }\n}\n\nfunction refineCapabilities(composition: CompositionShape, context: RefinementContext): void {\n  const plans = new Map(composition.infrastructure.map(entry => [entry.infrastructureId, entry.targetPlanId]))\n  const owners = new Map(composition.resourceBindings.map(entry => [entry.resourceId, entry.owningInfrastructureId]))\n  for (const [index, binding] of composition.managedCapabilityBindings.entries()) {\n    const path = ['managedCapabilityBindings', index]\n    if (binding.owningInfrastructureId === binding.consumerInfrastructureId) {\n      context.addIssue({\n        code: 'custom', message: 'a managed capability binding must cross infrastructure instances', path,\n      })\n    }\n    if (owners.get(binding.resourceId) !== binding.owningInfrastructureId) {\n      context.addIssue({\n        code: 'custom', message: `resource ${binding.resourceId} is not owned by ${binding.owningInfrastructureId}`, path,\n      })\n    }\n    if (plans.get(binding.owningInfrastructureId) !== binding.producerTargetPlanId || plans.get(binding.consumerInfrastructureId) !== binding.consumerTargetPlanId) {\n      context.addIssue({\n        code: 'custom', message: 'binding target-plan IDs must be the selected plans of the owner and consumer', path,\n      })\n    }\n  }\n}\n\nfunction refineTargetObjects(composition: CompositionShape, context: RefinementContext): void {\n  const kinds = new Map(composition.infrastructure.map(entry => [entry.infrastructureId, entry.kind]))\n  const things = new Map(composition.thingBindings.map(entry => [entry.thingId, entry.infrastructureId]))\n  const resources = new Map(composition.resourceBindings.map(entry => [entry.resourceId, entry.owningInfrastructureId]))\n  const hosts = new Map(composition.hostBindings.map(entry => [entry.hostPartitionId, entry.infrastructureId]))\n  for (const [index, object] of composition.targetObjects.entries()) {\n    const path = ['targetObjects', index]\n    const kind = kinds.get(object.owningInfrastructureId)\n    if (kind === undefined) {\n      context.addIssue({\n        code: 'custom', message: 'target object must be owned by a selected infrastructure', path: [...path, 'owningInfrastructureId'],\n      })\n      continue\n    }\n    const expected = hashDappTargetObjectIdentityV1({\n      schema: DappTargetObjectIdentitySchema,\n      schemaVersion: 1,\n      hashAlgorithm: DappDocumentHashAlgorithm,\n      targetObjectIdentitySchemaVersion: object.targetObjectIdentitySchemaVersion,\n      targetObjectIdentityContractHash: object.targetObjectIdentityContractHash,\n      deploymentTargetNamespaceId: object.deploymentTargetNamespaceId,\n      infrastructureId: object.owningInfrastructureId,\n      kind,\n      providerResourceKind: object.providerResourceKind,\n      targetObjectRole: object.targetObjectRole,\n      targetObjectIdentityAnchor: object.targetObjectIdentityAnchor,\n    })\n    if (expected !== object.targetObjectId) {\n      context.addIssue({\n        code: 'custom', message: 'target object does not reproduce its targetObjectId', path: [...path, 'targetObjectId'],\n      })\n    }\n    const owner = object.owningInfrastructureId\n    if (object.thingIds.some(id => things.get(id) !== owner)\n      || object.resourceIds.some(id => resources.get(id) !== owner)\n      || object.hostPartitionIds.some(id => hosts.get(id) !== owner)) {\n      context.addIssue({\n        code: 'custom', message: 'target object attribution must stay inside its owner\\'s bindings', path,\n      })\n    }\n  }\n}\n\nexport const DappTargetCompositionV3PreimageZod = z.strictObject(CompositionFields).superRefine((composition, context) => {\n  refineBindings(composition, context)\n  refineCapabilities(composition, context)\n  refineTargetObjects(composition, context)\n})\nexport type DappTargetCompositionV3Preimage = z.infer<typeof DappTargetCompositionV3PreimageZod>\nexport const DappTargetCompositionV3Zod = DappTargetCompositionV3PreimageZod.safeExtend({ compositionId: HashZod })\nexport type DappTargetCompositionV3 = z.infer<typeof DappTargetCompositionV3Zod>\n\n/** D-002 kind `target-composition` version 3: `xyo-dapp-kit:target-composition:v3\\n`. */\nexport function hashDappTargetCompositionV3(preimage: unknown): string {\n  return hashDappDocument({\n    kind: 'target-composition',\n    schema: DappTargetCompositionV3PreimageZod,\n    schemaVersion: 3,\n  }, preimage).hash\n}\n\nexport const DappTargetCompositionV3IssueCodes = [\n  'target-composition.invalid',\n  'target-composition.plan-invalid',\n  'target-composition.plan-mismatch',\n  'target-composition.lock-mismatch',\n  'target-composition.capability-mismatch',\n  'target-composition.adapter-unpinned',\n] as const\nexport type DappTargetCompositionV3IssueCode = (typeof DappTargetCompositionV3IssueCodes)[number]\n\nexport interface DappTargetCompositionV3Issue {\n  code: DappTargetCompositionV3IssueCode\n  message: string\n  path: (number | string)[]\n}\n\nexport type DappTargetCompositionV3Result\n  = { issues: DappTargetCompositionV3Issue[]; success: false }\n    | { success: true; value: DappTargetCompositionV3 }\n\n/** The common envelope of any provider target plan plus its identity; provider-specific fields are dropped. */\nconst TargetPlanProjectionZod = z.object({ ...DappTargetPlanEnvelopeV1Fields, targetPlanId: HashZod })\nexport type DappTargetPlanProjectionV1 = z.infer<typeof TargetPlanProjectionZod>\n\nfunction issue(code: DappTargetCompositionV3IssueCode, message: string, path: (number | string)[]): DappTargetCompositionV3Issue {\n  return {\n    code, message, path,\n  }\n}\n\nfunction zodPath(path: readonly PropertyKey[]): (number | string)[] {\n  return path.map(entry => typeof entry === 'symbol' ? entry.toString() : entry)\n}\n\n/**\n * Projects a provider target plan onto the common envelope and verifies that\n * envelope as one slice of the lock. Provider rules are not checked here.\n */\nexport function projectDappTargetPlanV1(lock: DappDeploymentLockV3, plan: unknown, index: number): DappTargetCompositionV3Issue[] | DappTargetPlanProjectionV1 {\n  const parsed = TargetPlanProjectionZod.safeParse(plan)\n  if (!parsed.success) {\n    return parsed.error.issues.map(entry => issue('target-composition.plan-invalid', entry.message, ['targetPlans', index, ...zodPath(entry.path)]))\n  }\n  const { targetPlanId: _id, ...envelope } = parsed.data\n  const verified = verifyDappTargetPlanEnvelopeV1(lock, envelope)\n  return verified.success ? parsed.data : verified.issues.map(entry => issue('target-composition.plan-invalid', `${entry.code}: ${entry.message}`, ['targetPlans', index, ...entry.path]))\n}\n\nfunction projectPlans(lock: DappDeploymentLockV3, targetPlans: readonly unknown[]): DappTargetCompositionV3Issue[] | Map<string, DappTargetPlanProjectionV1> {\n  const issues: DappTargetCompositionV3Issue[] = []\n  const plans = new Map<string, DappTargetPlanProjectionV1>()\n  for (const [index, plan] of targetPlans.entries()) {\n    const projected = projectDappTargetPlanV1(lock, plan, index)\n    if (Array.isArray(projected)) {\n      issues.push(...projected)\n      continue\n    }\n    const id = projected.infrastructure.infrastructureId\n    if (plans.has(id)) {\n      issues.push(issue('target-composition.plan-mismatch', `two target plans select infrastructure ${id}`, ['targetPlans', index]))\n      continue\n    }\n    plans.set(id, projected)\n  }\n  for (const entry of lock.infrastructure) {\n    if (!plans.has(entry.infrastructureId)) {\n      issues.push(issue('target-composition.plan-mismatch', `no target plan selects infrastructure ${entry.infrastructureId}`, ['targetPlans']))\n    }\n  }\n  return issues.length > 0 ? issues : plans\n}\n\nfunction exportKey(entry: Pick<DappManagedCapabilityExportV1, 'exportContractId' | 'exportContractVersion' | 'owningInfrastructureId' | 'resourceId'>): string {\n  return canonicalizeIJson([entry.resourceId, entry.owningInfrastructureId, entry.exportContractId, entry.exportContractVersion])\n}\n\nfunction importKey(entry: DappManagedCapabilityImportV1, consumerTargetPlanId: string): string {\n  return canonicalizeIJson([entry.resourceId, entry.owningInfrastructureId, entry.consumerInfrastructureId, consumerTargetPlanId, entry.exportContractId, entry.exportContractVersion])\n}\n\nfunction sameTuple(left: DappManagedCapabilityExportV1, right: DappManagedCapabilityImportV1): boolean {\n  return left.exportContractHash === right.exportContractHash\n    && left.exportNormalizationId === right.exportNormalizationId\n    && left.exportIdentityHash === right.exportIdentityHash\n}\n\n/**\n * One-to-many capability matching: every producer export has at least one\n * consumer import, every import matches exactly one export by key and the\n * whole contract/identity tuple, and imports are unique per consumer plan.\n */\nfunction bindCapabilities(plans: ReadonlyMap<string, DappTargetPlanProjectionV1>): { bindings: DappManagedCapabilityBindingV3[] } | { issues: DappTargetCompositionV3Issue[] } {\n  const issues: DappTargetCompositionV3Issue[] = []\n  const exports = new Map<string, { entry: DappManagedCapabilityExportV1; targetPlanId: string }>()\n  for (const plan of plans.values()) {\n    for (const entry of plan.exportedManagedCapabilities) {\n      const key = exportKey(entry)\n      if (exports.has(key)) {\n        issues.push(issue('target-composition.capability-mismatch', `duplicate export of ${entry.resourceId} by ${entry.owningInfrastructureId}`, ['managedCapabilityBindings']))\n      }\n      exports.set(key, { entry, targetPlanId: plan.targetPlanId })\n    }\n  }\n  const consumed = new Set<string>()\n  const seenImports = new Set<string>()\n  const bindings: DappManagedCapabilityBindingV3[] = []\n  for (const plan of plans.values()) {\n    entryLoop:\n    for (const entry of plan.importedManagedCapabilities) {\n      const key = importKey(entry, plan.targetPlanId)\n      if (seenImports.has(key)) {\n        issues.push(issue('target-composition.capability-mismatch', `duplicate import of ${entry.resourceId} into ${entry.consumerInfrastructureId}`, ['managedCapabilityBindings']))\n        continue entryLoop\n      }\n      seenImports.add(key)\n      const producer = exports.get(exportKey(entry))\n      if (producer === undefined || !sameTuple(producer.entry, entry)) {\n        issues.push(issue(\n          'target-composition.capability-mismatch',\n          `import of ${entry.resourceId} into ${entry.consumerInfrastructureId} matches no producer export with the same contract and identity`,\n          ['managedCapabilityBindings'],\n        ))\n        continue entryLoop\n      }\n      consumed.add(exportKey(entry))\n      bindings.push({\n        resourceId: entry.resourceId,\n        owningInfrastructureId: entry.owningInfrastructureId,\n        consumerInfrastructureId: entry.consumerInfrastructureId,\n        producerTargetPlanId: producer.targetPlanId,\n        consumerTargetPlanId: plan.targetPlanId,\n        exportContractId: entry.exportContractId,\n        exportContractVersion: entry.exportContractVersion,\n        exportContractHash: entry.exportContractHash,\n        exportNormalizationId: entry.exportNormalizationId,\n        exportIdentityHash: entry.exportIdentityHash,\n      })\n    }\n  }\n  for (const [key, producer] of exports) {\n    if (!consumed.has(key)) {\n      issues.push(issue('target-composition.capability-mismatch', `export of ${producer.entry.resourceId} by ${producer.entry.owningInfrastructureId} has no consumer`, ['managedCapabilityBindings']))\n    }\n  }\n  return issues.length > 0 ? { issues } : { bindings: bindings.toSorted(compareDappManagedCapabilityBindingsV3) }\n}\n\nexport interface CreateDappTargetCompositionV3Input {\n  readonly lock: DappDeploymentLockV3\n  readonly targetPlans: readonly unknown[]\n}\n\n/**\n * Builds the composition of a verified Lock V3 and exactly one target plan per\n * selected infrastructure. The bindings come from the lock's placements, the\n * target objects from the union of the plans, and the managed-capability\n * bindings from matched exports and imports; the plan IDs are taken from the\n * plans and are reproduced only by `verifyDappTargetCompositionV3`.\n */\nexport function createDappTargetCompositionV3(input: CreateDappTargetCompositionV3Input): DappTargetCompositionV3Result {\n  const plans = projectPlans(input.lock, input.targetPlans)\n  if (Array.isArray(plans)) return { issues: plans, success: false }\n  const capabilities = bindCapabilities(plans)\n  if ('issues' in capabilities) return { issues: capabilities.issues, success: false }\n  const targetObjects = plans.values().flatMap(plan => plan.targetObjects).toArray().toSorted((left, right) => compareCodeUnits(left.targetObjectId, right.targetObjectId))\n  const preimage = DappTargetCompositionV3PreimageZod.safeParse({\n    schema: DappTargetCompositionSchema,\n    schemaVersion: 3,\n    hashAlgorithm: DappDocumentHashAlgorithm,\n    lockId: input.lock.lockId,\n    infrastructure: input.lock.infrastructure.map(entry => ({\n      infrastructureId: entry.infrastructureId,\n      kind: entry.kind,\n      adapterId: entry.adapterId,\n      adapterVersion: entry.adapterVersion,\n      adapterDescriptorHash: entry.adapterDescriptorHash,\n      infrastructureDescriptorHash: entry.infrastructureDescriptorHash,\n      infrastructurePolicyHash: entry.infrastructurePolicyHash,\n      targetPlanId: plans.get(entry.infrastructureId)?.targetPlanId,\n    })).toSorted((left, right) => compareCodeUnits(left.infrastructureId, right.infrastructureId)),\n    thingBindings: [...input.lock.placements.things].toSorted((left, right) => compareCodeUnits(left.thingId, right.thingId)),\n    resourceBindings: input.lock.placements.resources.map(entry => ({ resourceId: entry.resourceId, owningInfrastructureId: entry.infrastructureId }))\n      .toSorted((left, right) => compareCodeUnits(left.resourceId, right.resourceId)),\n    hostBindings: [...input.lock.placements.hosts].toSorted((left, right) => compareCodeUnits(left.hostPartitionId, right.hostPartitionId)),\n    managedCapabilityBindings: capabilities.bindings,\n    targetObjects,\n  })\n  if (!preimage.success) {\n    return {\n      issues: preimage.error.issues.map(entry => issue('target-composition.invalid', entry.message, zodPath(entry.path))),\n      success: false,\n    }\n  }\n  return { success: true, value: DappTargetCompositionV3Zod.parse({ ...preimage.data, compositionId: hashDappTargetCompositionV3(preimage.data) }) }\n}\n\n/** The result shape every provider target-plan verifier returns. */\nexport type DappTargetPlanVerificationLikeV1\n  = { readonly issues: readonly DappTargetPlanIssue[]; readonly success: false }\n    | { readonly success: true; readonly value: { readonly targetPlanId: string } }\n\n/** A pinned adapter: its public descriptor and the provider verifier that reproduces its target plans. */\nexport interface DappTargetCompositionAdapterV3 {\n  readonly descriptor: DappInfrastructureAdapterDescriptorV1\n  readonly verifyTargetPlan: (lock: DappDeploymentLockV3, plan: unknown) => DappTargetPlanVerificationLikeV1\n}\n\nexport interface VerifyDappTargetCompositionV3Options {\n  readonly adapters: readonly DappTargetCompositionAdapterV3[]\n}\n\nfunction listsContract(descriptor: DappInfrastructureAdapterDescriptorV1, binding: DappManagedCapabilityBindingV3): boolean {\n  return descriptor.supportedExportContracts.some(contract => (\n    contract.exportContractId === binding.exportContractId\n    && contract.exportContractVersion === binding.exportContractVersion\n    && contract.exportContractHash === binding.exportContractHash\n    && contract.exportNormalizationId === binding.exportNormalizationId\n  ))\n}\n\nfunction reproducePlans(\n  lock: DappDeploymentLockV3,\n  targetPlans: readonly unknown[],\n  composition: DappTargetCompositionV3,\n  adapters: readonly DappTargetCompositionAdapterV3[],\n): DappTargetCompositionV3Issue[] {\n  const issues: DappTargetCompositionV3Issue[] = []\n  const expected = new Map(composition.infrastructure.map(entry => [entry.infrastructureId, entry]))\n  for (const [index, plan] of targetPlans.entries()) {\n    const projected = projectDappTargetPlanV1(lock, plan, index)\n    if (Array.isArray(projected)) {\n      issues.push(...projected)\n      continue\n    }\n    const entry = expected.get(projected.infrastructure.infrastructureId)\n    const adapter = adapters.find(candidate => candidate.descriptor.adapterDescriptorHash === projected.infrastructure.adapterDescriptorHash)\n    if (adapter === undefined) {\n      issues.push(issue('target-composition.adapter-unpinned', `no pinned adapter descriptor ${projected.infrastructure.adapterDescriptorHash} verifies plan ${index}`, ['targetPlans', index]))\n      continue\n    }\n    const verified = adapter.verifyTargetPlan(lock, plan)\n    if (!verified.success) {\n      issues.push(...verified.issues.map(child => issue('target-composition.plan-invalid', `${child.code}: ${child.message}`, ['targetPlans', index, ...child.path])))\n      continue\n    }\n    if (verified.value.targetPlanId !== projected.targetPlanId || entry?.targetPlanId !== projected.targetPlanId) {\n      issues.push(issue('target-composition.plan-mismatch', `target plan ${index} does not reproduce the composition's targetPlanId`, ['targetPlans', index, 'targetPlanId']))\n    }\n  }\n  return issues\n}\n\n/**\n * The exhaustive Composition V3 verifier: every target plan is reproduced by\n * its pinned adapter, one plan selects each lock infrastructure, every\n * selected-infrastructure field agrees, the bindings are exactly the lock's\n * placements, the target objects are exactly the plan union, every managed\n * capability binding matches one export and one import whose contract both\n * pinned descriptors list, and only then must `compositionId` reproduce.\n */\nexport function verifyDappTargetCompositionV3(\n  lock: DappDeploymentLockV3,\n  targetPlans: readonly unknown[],\n  value: unknown,\n  options: VerifyDappTargetCompositionV3Options,\n): DappTargetCompositionV3Result {\n  const parsed = DappTargetCompositionV3Zod.safeParse(value)\n  if (!parsed.success) {\n    return { issues: parsed.error.issues.map(entry => issue('target-composition.invalid', entry.message, zodPath(entry.path))), success: false }\n  }\n  const composition = parsed.data\n  const issues = reproducePlans(lock, targetPlans, composition, options.adapters)\n  if (composition.lockId !== lock.lockId) issues.push(issue('target-composition.lock-mismatch', 'composition lockId does not match the lock', ['lockId']))\n  const expected = createDappTargetCompositionV3({ lock, targetPlans })\n  if (!expected.success) return { issues: [...issues, ...expected.issues], success: false }\n  const { compositionId, ...preimage } = composition\n  for (const field of ['infrastructure', 'thingBindings', 'resourceBindings', 'hostBindings', 'managedCapabilityBindings', 'targetObjects'] as const) {\n    if (canonicalizeIJson(expected.value[field]) !== canonicalizeIJson(preimage[field])) {\n      issues.push(issue('target-composition.lock-mismatch', `${field} are not exactly those of the lock and its target plans`, [field]))\n    }\n  }\n  const descriptors = new Map(options.adapters.map(adapter => [adapter.descriptor.adapterDescriptorHash, adapter.descriptor]))\n  const infrastructure = new Map(composition.infrastructure.map(entry => [entry.infrastructureId, entry]))\n  for (const [index, binding] of composition.managedCapabilityBindings.entries()) {\n    const producer = descriptors.get(infrastructure.get(binding.owningInfrastructureId)?.adapterDescriptorHash ?? '')\n    const consumer = descriptors.get(infrastructure.get(binding.consumerInfrastructureId)?.adapterDescriptorHash ?? '')\n    if (producer === undefined || consumer === undefined || !listsContract(producer, binding) || !listsContract(consumer, binding)) {\n      issues.push(issue('target-composition.capability-mismatch', `both pinned adapter descriptors must list contract ${binding.exportContractId}`, ['managedCapabilityBindings', index]))\n    }\n  }\n  if (issues.length === 0 && hashDappTargetCompositionV3(preimage) !== compositionId) {\n    issues.push(issue('target-composition.invalid', 'composition does not reproduce its compositionId', ['compositionId']))\n  }\n  return issues.length > 0 ? { issues, success: false } : { success: true, value: composition }\n}\n", "import { asSchema } from '@xyo-network/sdk'\nimport { z } from 'zod'\n\nimport {\n  DappDocumentHashAlgorithm,\n  hashDappDocument,\n} from './canonicalDocument.ts'\nimport { DappInfrastructureKindZod } from './deploymentManifestV2.ts'\nimport {\n  DappIdZod,\n  HashZod,\n  IdentifierZod,\n} from './identifier.ts'\nimport { DappInfrastructureIdZod } from './infrastructureDescriptor.ts'\n\n/**\n * Target-object identity (D-034, plan Section 4.5). A target object is one\n * provider object a target plan intends to manage. Its identity is derived from\n * a descriptor-versioned identity contract, the deployment namespace, the\n * owning infrastructure, and one typed stable anchor; never from provider\n * allocations, mutable fields, positional indexes, or aggregate membership.\n * Every value here is public-safe and excludes the protected deployment owner.\n */\nexport const DappTargetObjectIdentityContractSchema = asSchema('network.xyo.dapp.target.object.identity.contract', true)\nexport const DappDeploymentTargetNamespaceSchema = asSchema('network.xyo.dapp.target.deployment.namespace', true)\nexport const DappTargetObjectIdentitySchema = asSchema('network.xyo.dapp.target.object.identity', true)\n\nconst PositiveIntegerZod = z.number().int().positive()\n\nexport const DappTargetObjectIdentityContractV1PreimageZod = z.strictObject({\n  schema: z.literal(DappTargetObjectIdentityContractSchema),\n  schemaVersion: z.literal(1),\n  hashAlgorithm: z.literal(DappDocumentHashAlgorithm),\n  targetObjectIdentitySchemaVersion: PositiveIntegerZod,\n  providerResourceKindVocabularyHash: HashZod,\n  providerResourceKindNormalizationId: IdentifierZod,\n  targetObjectRoleVocabularyHash: HashZod,\n  targetObjectRoleNormalizationId: IdentifierZod,\n  targetObjectIdentityAnchorSchemaHash: HashZod,\n  targetObjectIdentityAnchorNormalizationId: IdentifierZod,\n  targetObjectIdProjectionKind: z.literal('target-object'),\n})\nexport type DappTargetObjectIdentityContractV1Preimage = z.infer<typeof DappTargetObjectIdentityContractV1PreimageZod>\n\nexport const DappTargetObjectIdentityContractV1Zod = DappTargetObjectIdentityContractV1PreimageZod\n  .safeExtend({ targetObjectIdentityContractHash: HashZod })\nexport type DappTargetObjectIdentityContractV1 = z.infer<typeof DappTargetObjectIdentityContractV1Zod>\n\n/** D-002 kind `target-object-identity-contract` version 1. */\nexport function hashDappTargetObjectIdentityContractV1(preimage: unknown): string {\n  return hashDappDocument({\n    kind: 'target-object-identity-contract',\n    schema: DappTargetObjectIdentityContractV1PreimageZod,\n    schemaVersion: 1,\n  }, preimage).hash\n}\n\nexport function verifyDappTargetObjectIdentityContractV1(value: unknown): DappTargetObjectIdentityContractV1 {\n  const contract = DappTargetObjectIdentityContractV1Zod.parse(value)\n  const { targetObjectIdentityContractHash, ...preimage } = contract\n  if (hashDappTargetObjectIdentityContractV1(preimage) !== targetObjectIdentityContractHash) {\n    throw new TypeError('target-object identity contract does not reproduce its targetObjectIdentityContractHash')\n  }\n  return contract\n}\n\nexport const DappDeploymentTargetNamespaceV1PreimageZod = z.strictObject({\n  schema: z.literal(DappDeploymentTargetNamespaceSchema),\n  schemaVersion: z.literal(1),\n  hashAlgorithm: z.literal(DappDocumentHashAlgorithm),\n  projectId: DappIdZod,\n  deploymentName: IdentifierZod,\n})\nexport type DappDeploymentTargetNamespaceV1Preimage = z.infer<typeof DappDeploymentTargetNamespaceV1PreimageZod>\n\n/** D-002 kind `target-deployment-namespace` version 1: the public namespace of one named deployment. */\nexport function hashDappDeploymentTargetNamespaceV1(preimage: unknown): string {\n  return hashDappDocument({\n    kind: 'target-deployment-namespace',\n    schema: DappDeploymentTargetNamespaceV1PreimageZod,\n    schemaVersion: 1,\n  }, preimage).hash\n}\n\nexport function deploymentTargetNamespaceId(projectId: string, deploymentName: string): string {\n  return hashDappDeploymentTargetNamespaceV1({\n    schema: DappDeploymentTargetNamespaceSchema,\n    schemaVersion: 1,\n    hashAlgorithm: DappDocumentHashAlgorithm,\n    projectId,\n    deploymentName,\n  })\n}\n\n/**\n * The closed anchor union. A per-semantic-object target anchors to exactly one\n * stable thing, resource, or host-partition ID; an aggregate target anchors to\n * a stable deployment role plus an explicit stable partition ID, so adding or\n * removing an aggregate member changes attribution without changing identity.\n */\nexport const DappTargetObjectAnchorZod = z.discriminatedUnion('kind', [\n  z.strictObject({ kind: z.literal('thing'), thingId: IdentifierZod }),\n  z.strictObject({ kind: z.literal('resource'), resourceId: IdentifierZod }),\n  z.strictObject({ kind: z.literal('host-partition'), hostPartitionId: IdentifierZod }),\n  z.strictObject({\n    kind: z.literal('deployment-role'), role: IdentifierZod, partitionId: IdentifierZod,\n  }),\n])\nexport type DappTargetObjectAnchor = z.infer<typeof DappTargetObjectAnchorZod>\n\nexport const DappTargetObjectIdentityV1PreimageZod = z.strictObject({\n  schema: z.literal(DappTargetObjectIdentitySchema),\n  schemaVersion: z.literal(1),\n  hashAlgorithm: z.literal(DappDocumentHashAlgorithm),\n  targetObjectIdentitySchemaVersion: PositiveIntegerZod,\n  targetObjectIdentityContractHash: HashZod,\n  deploymentTargetNamespaceId: HashZod,\n  infrastructureId: DappInfrastructureIdZod,\n  kind: DappInfrastructureKindZod,\n  providerResourceKind: IdentifierZod,\n  targetObjectRole: IdentifierZod,\n  targetObjectIdentityAnchor: DappTargetObjectAnchorZod,\n})\nexport type DappTargetObjectIdentityV1Preimage = z.infer<typeof DappTargetObjectIdentityV1PreimageZod>\n\nexport const DappTargetObjectIdentityV1Zod = DappTargetObjectIdentityV1PreimageZod.safeExtend({ targetObjectId: HashZod })\nexport type DappTargetObjectIdentityV1 = z.infer<typeof DappTargetObjectIdentityV1Zod>\n\n/** D-002 kind `target-object` version 1. */\nexport function hashDappTargetObjectIdentityV1(preimage: unknown): string {\n  return hashDappDocument({\n    kind: 'target-object',\n    schema: DappTargetObjectIdentityV1PreimageZod,\n    schemaVersion: 1,\n  }, preimage).hash\n}\n\nexport function verifyDappTargetObjectIdentityV1(value: unknown): DappTargetObjectIdentityV1 {\n  const identity = DappTargetObjectIdentityV1Zod.parse(value)\n  const { targetObjectId, ...preimage } = identity\n  if (hashDappTargetObjectIdentityV1(preimage) !== targetObjectId) {\n    throw new TypeError('target object does not reproduce its targetObjectId')\n  }\n  return identity\n}\n", "import { z } from 'zod'\n\nimport {\n  canonicalizeIJson,\n  DappDocumentHashAlgorithm,\n} from './canonicalDocument.ts'\nimport type { DappDeploymentLockV3 } from './deploymentLockV3.ts'\nimport {\n  DappIdZod,\n  HashZod,\n  IdentifierZod,\n} from './identifier.ts'\nimport {\n  ContentDigestZod,\n  DappInfrastructureIdZod,\n  DappSelectedInfrastructureV1Zod,\n} from './infrastructureDescriptor.ts'\nimport {\n  compareDappManagedCapabilityExportsV1,\n  compareDappManagedCapabilityImportsV1,\n  DappManagedCapabilityExportV1Zod,\n  DappManagedCapabilityImportV1Zod,\n} from './managedCapability.ts'\nimport {\n  compareCodeUnits,\n  findSortedUniqueIssue,\n  isSortedUniqueStrings,\n} from './ordering.ts'\nimport {\n  DappProviderRequestTemplateV1Zod,\n  hashDappProviderRequestTemplateV1,\n} from './providerRequestTemplate.ts'\nimport {\n  DappTargetObjectAnchorZod,\n  DappTargetObjectIdentitySchema,\n  deploymentTargetNamespaceId,\n  hashDappTargetObjectIdentityV1,\n} from './targetObjectIdentity.ts'\n\n/**\n * The common target-plan envelope (plan Section 4.4). Every multi-infrastructure\n * provider target plan consumes exactly one Lock V3 slice and carries these\n * fields; provider packages extend the envelope with their strict\n * kind-specific target objects, configuration, and request templates. The\n * envelope contains no connection profile, credential grant, alias, protected\n * identity, inventory, or provider-assigned locator.\n */\n\n/** The closed broker operation vocabulary (plan Section 6.2). */\nexport const DappBrokerOperationZod = z.enum([\n  'infrastructure.observe-registration',\n  'infrastructure.register',\n  'infrastructure.inventory',\n  'infrastructure.verify',\n  'infrastructure.apply',\n  'infrastructure.promote',\n  'infrastructure.rollback',\n  'artifact-distribution.observe-registration',\n  'artifact-distribution.register',\n  'artifact.publish',\n  'artifact.read-back',\n  'guest.bootstrap',\n  'resource.adopt',\n  'deployment.deactivate',\n  'resource.prune',\n  'runtime-secret.deliver',\n])\nexport type DappBrokerOperation = z.infer<typeof DappBrokerOperationZod>\n\n/** The closed action-class vocabulary (plan Section 4.7). */\nexport const DappActionClassZod = z.enum([\n  'create',\n  'narrow-update',\n  'replace',\n  'read-back',\n  'inspect',\n  'publish',\n  'adopt',\n  'delete',\n  'power',\n])\nexport type DappActionClass = z.infer<typeof DappActionClassZod>\n\n/** The only action classes an MI0-MI9 adapter descriptor may declare. */\nexport const DappFirstSliceActionClasses: readonly DappActionClass[] = ['create', 'narrow-update', 'read-back', 'inspect', 'publish']\n\n/** Controller-issued public binding identities share the UUID URN form. */\nexport const DappControllerIssuedIdZod = DappInfrastructureIdZod\n\nconst SortedIdentifiersZod = z.array(IdentifierZod).refine(isSortedUniqueStrings, 'identifiers must be sorted and unique')\n\nexport const DappCredentialRequirementV1Zod = z.strictObject({\n  credentialRequirementId: IdentifierZod,\n  operation: DappBrokerOperationZod,\n  actionClass: DappActionClassZod,\n})\nexport type DappCredentialRequirementV1 = z.infer<typeof DappCredentialRequirementV1Zod>\n\nexport function compareDappCredentialRequirementsV1(left: DappCredentialRequirementV1, right: DappCredentialRequirementV1): number {\n  return compareCodeUnits(left.credentialRequirementId, right.credentialRequirementId)\n    || compareCodeUnits(left.operation, right.operation)\n    || compareCodeUnits(left.actionClass, right.actionClass)\n}\n\nexport const DappTargetArtifactRefV1Zod = z.strictObject({\n  targetArtifactAdmissionId: HashZod,\n  targetArtifactDigest: ContentDigestZod,\n})\nexport type DappTargetArtifactRefV1 = z.infer<typeof DappTargetArtifactRefV1Zod>\n\n/** A target plan sees a prerequisite only as its public binding ID, class, commitment, and allowed operations. */\nexport const DappProviderPrerequisiteRefV1Zod = z.strictObject({\n  providerPrerequisiteBindingId: DappControllerIssuedIdZod,\n  prerequisiteClass: IdentifierZod,\n  providerPrerequisiteCommitment: HashZod,\n  allowedOperations: SortedIdentifiersZod.min(1),\n})\nexport type DappProviderPrerequisiteRefV1 = z.infer<typeof DappProviderPrerequisiteRefV1Zod>\n\nexport const DappTargetObjectV1Zod = z.strictObject({\n  targetObjectId: HashZod,\n  owningInfrastructureId: DappInfrastructureIdZod,\n  providerResourceKind: IdentifierZod,\n  targetObjectIdentitySchemaVersion: z.number().int().positive(),\n  targetObjectIdentityContractHash: HashZod,\n  deploymentTargetNamespaceId: HashZod,\n  targetObjectRole: IdentifierZod,\n  targetObjectIdentityAnchor: DappTargetObjectAnchorZod,\n  thingIds: SortedIdentifiersZod,\n  resourceIds: SortedIdentifiersZod,\n  hostPartitionIds: SortedIdentifiersZod,\n})\nexport type DappTargetObjectV1 = z.infer<typeof DappTargetObjectV1Zod>\n\nexport const DappTargetPlanSliceV1Zod = z.strictObject({\n  thingIds: SortedIdentifiersZod,\n  resourceIds: SortedIdentifiersZod,\n  hostPartitionIds: SortedIdentifiersZod,\n  /** External resources the slice reads through typed prerequisite references; never owned. */\n  externalResourceIds: SortedIdentifiersZod,\n})\nexport type DappTargetPlanSliceV1 = z.infer<typeof DappTargetPlanSliceV1Zod>\n\ninterface RefinementContext {\n  addIssue: (issue: { code: 'custom'; message: string; path: (number | string)[] }) => void\n}\n\nfunction refineSorted<T>(\n  context: RefinementContext,\n  values: readonly T[],\n  compare: (left: T, right: T) => number,\n  field: string,\n): void {\n  const issue = findSortedUniqueIssue(values, compare, field)\n  if (issue !== undefined) {\n    context.addIssue({\n      code: 'custom', message: issue.message, path: [field, issue.index],\n    })\n  }\n}\n\nfunction isSubset(values: readonly string[], universe: ReadonlySet<string>): boolean {\n  return values.every(value => universe.has(value))\n}\n\ninterface AnchorTarget {\n  id: string\n  list: 'thingIds' | 'resourceIds' | 'hostPartitionIds'\n}\n\nfunction anchorTarget(anchor: DappTargetObjectV1['targetObjectIdentityAnchor']): AnchorTarget | undefined {\n  switch (anchor.kind) {\n    case 'thing': { return { list: 'thingIds', id: anchor.thingId } }\n    case 'resource': { return { list: 'resourceIds', id: anchor.resourceId } }\n    case 'host-partition': { return { list: 'hostPartitionIds', id: anchor.hostPartitionId } }\n    default: { return undefined }\n  }\n}\n\nfunction refineTargetObjects(envelope: DappTargetPlanEnvelopeV1Shape, context: RefinementContext): void {\n  refineSorted(context, envelope.targetObjects, (left, right) => compareCodeUnits(left.targetObjectId, right.targetObjectId), 'targetObjects')\n  const things = new Set(envelope.slice.thingIds)\n  const resources = new Set(envelope.slice.resourceIds)\n  const hosts = new Set(envelope.slice.hostPartitionIds)\n  for (const [index, object] of envelope.targetObjects.entries()) {\n    const path = ['targetObjects', index]\n    if (object.owningInfrastructureId !== envelope.infrastructure.infrastructureId) {\n      context.addIssue({\n        code: 'custom', message: 'target object must be owned by the plan infrastructure', path: [...path, 'owningInfrastructureId'],\n      })\n    }\n    if (object.deploymentTargetNamespaceId !== envelope.deploymentTargetNamespaceId) {\n      context.addIssue({\n        code: 'custom', message: 'target object namespace must equal the plan namespace', path: [...path, 'deploymentTargetNamespaceId'],\n      })\n    }\n    const expectedId = hashDappTargetObjectIdentityV1({\n      schema: DappTargetObjectIdentitySchema,\n      schemaVersion: 1,\n      hashAlgorithm: DappDocumentHashAlgorithm,\n      targetObjectIdentitySchemaVersion: object.targetObjectIdentitySchemaVersion,\n      targetObjectIdentityContractHash: object.targetObjectIdentityContractHash,\n      deploymentTargetNamespaceId: object.deploymentTargetNamespaceId,\n      infrastructureId: object.owningInfrastructureId,\n      kind: envelope.infrastructure.kind,\n      providerResourceKind: object.providerResourceKind,\n      targetObjectRole: object.targetObjectRole,\n      targetObjectIdentityAnchor: object.targetObjectIdentityAnchor,\n    })\n    if (expectedId !== object.targetObjectId) {\n      context.addIssue({\n        code: 'custom', message: 'target object does not reproduce its targetObjectId', path: [...path, 'targetObjectId'],\n      })\n    }\n    if (!isSubset(object.thingIds, things) || !isSubset(object.resourceIds, resources) || !isSubset(object.hostPartitionIds, hosts)) {\n      context.addIssue({\n        code: 'custom', message: 'target object attribution must stay inside the plan slice', path,\n      })\n    }\n    const anchor = anchorTarget(object.targetObjectIdentityAnchor)\n    if (anchor !== undefined && !object[anchor.list].includes(anchor.id)) {\n      context.addIssue({\n        code: 'custom', message: `anchor ${anchor.id} must be part of the target object's attribution`, path: [...path, 'targetObjectIdentityAnchor'],\n      })\n    }\n  }\n}\n\nfunction refineCapabilities(envelope: DappTargetPlanEnvelopeV1Shape, context: RefinementContext): void {\n  const self = envelope.infrastructure.infrastructureId\n  const objectIds = new Set(envelope.targetObjects.map(object => object.targetObjectId))\n  const resources = new Set(envelope.slice.resourceIds)\n  const things = new Set(envelope.slice.thingIds)\n  const hosts = new Set(envelope.slice.hostPartitionIds)\n  refineSorted(context, envelope.exportedManagedCapabilities, compareDappManagedCapabilityExportsV1, 'exportedManagedCapabilities')\n  refineSorted(context, envelope.importedManagedCapabilities, compareDappManagedCapabilityImportsV1, 'importedManagedCapabilities')\n  for (const [index, entry] of envelope.exportedManagedCapabilities.entries()) {\n    if (entry.owningInfrastructureId !== self || !resources.has(entry.resourceId)) {\n      context.addIssue({\n        code: 'custom', message: 'an export must be owned by this plan and name a resource in its slice', path: ['exportedManagedCapabilities', index],\n      })\n    }\n    if (!isSubset(entry.producerTargetObjectIds, objectIds)) {\n      context.addIssue({\n        code: 'custom', message: 'export producers must be target objects of this plan', path: ['exportedManagedCapabilities', index, 'producerTargetObjectIds'],\n      })\n    }\n  }\n  for (const [index, entry] of envelope.importedManagedCapabilities.entries()) {\n    if (entry.consumerInfrastructureId !== self || entry.owningInfrastructureId === self || resources.has(entry.resourceId)) {\n      context.addIssue({\n        code: 'custom', message: 'an import must be consumed by this plan from a resource owned elsewhere', path: ['importedManagedCapabilities', index],\n      })\n    }\n    if (!isSubset(entry.consumerThingIds, things) || !isSubset(entry.consumerHostPartitionIds, hosts)) {\n      context.addIssue({\n        code: 'custom', message: 'import consumers must stay inside the plan slice', path: ['importedManagedCapabilities', index],\n      })\n    }\n  }\n}\n\nfunction refineTemplatesAndRefs(envelope: DappTargetPlanEnvelopeV1Shape, context: RefinementContext): void {\n  refineSorted(context, envelope.credentialRequirements, compareDappCredentialRequirementsV1, 'credentialRequirements')\n  refineSorted(context, envelope.targetArtifacts, (left, right) => compareCodeUnits(left.targetArtifactAdmissionId, right.targetArtifactAdmissionId), 'targetArtifacts')\n  refineSorted(context, envelope.providerPrerequisites, (left, right) => compareCodeUnits(left.providerPrerequisiteBindingId, right.providerPrerequisiteBindingId), 'providerPrerequisites')\n  refineSorted(\n    context,\n    envelope.requestTemplates,\n    (left, right) => compareCodeUnits(left.actionKind, right.actionKind) || compareCodeUnits(left.requestTemplateHash, right.requestTemplateHash),\n    'requestTemplates',\n  )\n  const objectIds = new Set(envelope.targetObjects.map(object => object.targetObjectId))\n  const prerequisites = new Map(envelope.providerPrerequisites.map(entry => [entry.providerPrerequisiteBindingId, entry.providerPrerequisiteCommitment]))\n  for (const [index, template] of envelope.requestTemplates.entries()) {\n    const { requestTemplateHash, ...preimage } = template\n    if (hashDappProviderRequestTemplateV1(preimage) !== requestTemplateHash) {\n      context.addIssue({\n        code: 'custom', message: 'request template does not reproduce its requestTemplateHash', path: ['requestTemplates', index, 'requestTemplateHash'],\n      })\n    }\n    if (template.adapterDescriptorHash !== envelope.infrastructure.adapterDescriptorHash) {\n      context.addIssue({\n        code: 'custom', message: 'request template must belong to the plan adapter descriptor', path: ['requestTemplates', index, 'adapterDescriptorHash'],\n      })\n    }\n    for (const [placeholderIndex, placeholder] of template.placeholders.entries()) {\n      const path = ['requestTemplates', index, 'placeholders', placeholderIndex]\n      if (placeholder.bindingClass === 'target-object' && !objectIds.has(placeholder.bindingId)) {\n        context.addIssue({\n          code: 'custom', message: 'target-object placeholder must name a target object of this plan', path,\n        })\n      }\n      if (placeholder.bindingClass === 'provider-prerequisite' && prerequisites.get(placeholder.bindingId) !== placeholder.commitment) {\n        context.addIssue({\n          code: 'custom', message: 'provider-prerequisite placeholder must name a plan prerequisite with the same commitment', path,\n        })\n      }\n    }\n  }\n}\n\nconst EnvelopeFields = {\n  lockId: HashZod,\n  deploymentIntentId: HashZod,\n  projectId: DappIdZod,\n  deploymentName: IdentifierZod,\n  deploymentTargetNamespaceId: HashZod,\n  infrastructure: DappSelectedInfrastructureV1Zod,\n  slice: DappTargetPlanSliceV1Zod,\n  exportedManagedCapabilities: z.array(DappManagedCapabilityExportV1Zod),\n  importedManagedCapabilities: z.array(DappManagedCapabilityImportV1Zod),\n  targetArtifacts: z.array(DappTargetArtifactRefV1Zod),\n  credentialRequirements: z.array(DappCredentialRequirementV1Zod),\n  targetObjects: z.array(DappTargetObjectV1Zod),\n  providerPrerequisites: z.array(DappProviderPrerequisiteRefV1Zod),\n  requestTemplates: z.array(DappProviderRequestTemplateV1Zod),\n}\n\ntype DappTargetPlanEnvelopeV1Shape = z.infer<z.ZodObject<typeof EnvelopeFields>>\n\n/**\n * Intra-plan refinement shared by every provider plan schema. Provider\n * packages spread `DappTargetPlanEnvelopeV1Fields` into their strict preimage\n * and call this from their own `superRefine`, so the common rules are checked\n * once and identically everywhere.\n */\nexport function refineDappTargetPlanEnvelopeV1(envelope: DappTargetPlanEnvelopeV1Shape, context: RefinementContext): void {\n  if (envelope.deploymentTargetNamespaceId !== deploymentTargetNamespaceId(envelope.projectId, envelope.deploymentName)) {\n    context.addIssue({\n      code: 'custom', message: 'deploymentTargetNamespaceId does not reproduce from projectId and deploymentName', path: ['deploymentTargetNamespaceId'],\n    })\n  }\n  refineTargetObjects(envelope, context)\n  refineCapabilities(envelope, context)\n  refineTemplatesAndRefs(envelope, context)\n}\n\nexport const DappTargetPlanEnvelopeV1Fields = EnvelopeFields\nexport const DappTargetPlanEnvelopeV1Zod = z.strictObject(EnvelopeFields).superRefine(refineDappTargetPlanEnvelopeV1)\nexport type DappTargetPlanEnvelopeV1 = z.infer<typeof DappTargetPlanEnvelopeV1Zod>\n\n/** The exact slice of a Lock V3 that belongs to one infrastructure instance. */\nexport function sliceDappDeploymentLockV3(lock: DappDeploymentLockV3, infrastructureId: string): DappTargetPlanSliceV1 {\n  const placed = new Set(lock.placements.resources.map(entry => entry.resourceId))\n  return DappTargetPlanSliceV1Zod.parse({\n    thingIds: lock.placements.things.filter(entry => entry.infrastructureId === infrastructureId).map(entry => entry.thingId).toSorted(compareCodeUnits),\n    resourceIds: lock.placements.resources.filter(entry => entry.infrastructureId === infrastructureId).map(entry => entry.resourceId).toSorted(compareCodeUnits),\n    hostPartitionIds: lock.placements.hosts.filter(entry => entry.infrastructureId === infrastructureId).map(entry => entry.hostPartitionId).toSorted(compareCodeUnits),\n    externalResourceIds: lock.resources.filter(resource => resource.provision === 'external' && !placed.has(resource.resourceId))\n      .map(resource => resource.resourceId).toSorted(compareCodeUnits),\n  })\n}\n\nexport const DappTargetPlanIssueCodes = ['target-plan.envelope-invalid', 'target-plan.lock-mismatch'] as const\nexport const DappTargetPlanIssueCodeZod = z.enum(DappTargetPlanIssueCodes)\nexport type DappTargetPlanIssueCode = z.infer<typeof DappTargetPlanIssueCodeZod>\n\nexport interface DappTargetPlanIssue {\n  code: DappTargetPlanIssueCode\n  message: string\n  path: (number | string)[]\n}\n\nexport type DappTargetPlanEnvelopeV1Result\n  = { issues: DappTargetPlanIssue[]; success: false }\n    | { success: true; value: DappTargetPlanEnvelopeV1 }\n\nfunction mismatch(message: string, path: (number | string)[]): DappTargetPlanIssue {\n  return {\n    code: 'target-plan.lock-mismatch', message, path,\n  }\n}\n\n/**\n * Verifies that an envelope is exactly one slice of the given Lock V3: same\n * lock and intent identities, the lock's own selected-infrastructure entry,\n * exactly the things, resources, hosts, and external references the lock\n * places on that instance, and imports whose owners are the lock's owners.\n * Provider verifiers call this before checking their kind-specific fields.\n */\nexport function verifyDappTargetPlanEnvelopeV1(lock: DappDeploymentLockV3, value: unknown): DappTargetPlanEnvelopeV1Result {\n  const parsed = DappTargetPlanEnvelopeV1Zod.safeParse(value)\n  if (!parsed.success) {\n    return {\n      issues: parsed.error.issues.map(issue => ({\n        code: 'target-plan.envelope-invalid',\n        message: issue.message,\n        path: issue.path.map(entry => typeof entry === 'symbol' ? entry.toString() : entry),\n      })),\n      success: false,\n    }\n  }\n  const envelope = parsed.data\n  const issues: DappTargetPlanIssue[] = []\n  if (envelope.lockId !== lock.lockId) issues.push(mismatch('envelope lockId does not match the lock', ['lockId']))\n  if (envelope.deploymentIntentId !== lock.deployment.intent.deploymentIntentId) {\n    issues.push(mismatch('envelope deploymentIntentId does not match the lock', ['deploymentIntentId']))\n  }\n  if (envelope.deploymentName !== lock.deployment.name) issues.push(mismatch('envelope deploymentName does not match the lock', ['deploymentName']))\n  const selected = lock.infrastructure.find(entry => entry.infrastructureId === envelope.infrastructure.infrastructureId)\n  if (selected === undefined || canonicalizeIJson(selected) !== canonicalizeIJson(envelope.infrastructure)) {\n    issues.push(mismatch('envelope infrastructure is not the lock\\'s selected entry for that instance', ['infrastructure']))\n  }\n  const expectedSlice = sliceDappDeploymentLockV3(lock, envelope.infrastructure.infrastructureId)\n  if (canonicalizeIJson(expectedSlice) !== canonicalizeIJson(envelope.slice)) {\n    issues.push(mismatch('envelope slice is not exactly the lock placements for that instance', ['slice']))\n  }\n  const owners = new Map(lock.placements.resources.map(entry => [entry.resourceId, entry.infrastructureId]))\n  for (const [index, entry] of envelope.importedManagedCapabilities.entries()) {\n    if (owners.get(entry.resourceId) !== entry.owningInfrastructureId) {\n      issues.push(mismatch('import owner does not match the lock placement of that resource', ['importedManagedCapabilities', index, 'owningInfrastructureId']))\n    }\n  }\n  return issues.length > 0 ? { issues, success: false } : { success: true, value: envelope }\n}\n", "import { z } from 'zod'\n\nimport type {\n  EffectReceipt,\n  EffectReceiptObservation,\n} from './effectModel.ts'\nimport { assessEffectReceiptExecutionSupport, validateEffectReceipt } from './effectValidation.ts'\nimport { HashZod, IdentifierZod } from './identifier.ts'\n\nconst SequenceZod = z.number().int().positive()\n\nconst SignActionZod = z.strictObject({\n  action: z.literal('sign'),\n  state: z.literal('action'),\n})\n\nconst WriteContentActionZod = z.strictObject({\n  action: z.literal('write-content'),\n  contentHash: HashZod,\n  signedSequence: SequenceZod,\n  transactionHash: HashZod,\n  state: z.literal('action'),\n})\n\nconst VerifyContentActionZod = WriteContentActionZod.extend({ action: z.literal('verify-content') })\n\nconst ReconcileBroadcastActionZod = z.strictObject({\n  action: z.literal('reconcile-broadcast'),\n  signedSequence: SequenceZod,\n  transactionHash: HashZod,\n  state: z.literal('action'),\n})\n\nconst ObserveInclusionActionZod = ReconcileBroadcastActionZod.extend({ action: z.literal('observe-inclusion') })\n\nconst FinalityActionZod = z.strictObject({\n  action: z.literal('observe-finality'),\n  inclusionSequence: SequenceZod,\n  signedSequence: SequenceZod,\n  transactionHash: HashZod,\n  state: z.literal('action'),\n})\n\nconst PendingPlanZod = z.strictObject({\n  reasonCode: IdentifierZod,\n  state: z.literal('pending'),\n})\n\nconst TerminalPlanZod = z.strictObject({ state: z.enum(['abandoned', 'complete']) })\n\nexport const Xl1TransactionEffectPlanZod = z.union([\n  SignActionZod,\n  WriteContentActionZod,\n  VerifyContentActionZod,\n  ReconcileBroadcastActionZod,\n  ObserveInclusionActionZod,\n  FinalityActionZod,\n  PendingPlanZod,\n  TerminalPlanZod,\n])\n\nexport type Xl1TransactionEffectPlan = z.infer<typeof Xl1TransactionEffectPlanZod>\n\nexport const Xl1TransactionEffectPlanIssueCodes = [\n  'xl1-effect-plan.invalid-receipt',\n  'xl1-effect-plan.unsupported-effect-kind',\n] as const\n\nexport const Xl1TransactionEffectPlanIssueCodeZod = z.enum(Xl1TransactionEffectPlanIssueCodes)\nexport type Xl1TransactionEffectPlanIssueCode = z.infer<typeof Xl1TransactionEffectPlanIssueCodeZod>\n\nexport class Xl1TransactionEffectPlanError extends Error {\n  readonly code: Xl1TransactionEffectPlanIssueCode\n\n  constructor(code: Xl1TransactionEffectPlanIssueCode, message: string) {\n    super(message)\n    this.name = 'Xl1TransactionEffectPlanError'\n    this.code = code\n  }\n}\n\ntype PreparedObservation = Extract<EffectReceiptObservation, { kind: 'prepared' }>\ntype SignedObservation = Extract<EffectReceiptObservation, { kind: 'signed' }>\ntype IncludedObservation = Extract<EffectReceiptObservation, { kind: 'included' }>\n\ninterface ContentProgress {\n  readonly unavailableSequence: number\n  readonly verifiedSequence: number\n  readonly writtenSequence: number\n}\n\nfunction preparedObservation(receipt: EffectReceipt): PreparedObservation {\n  const prepared = receipt.observations[0]\n  if (prepared?.kind !== 'prepared') {\n    throw new Xl1TransactionEffectPlanError(\n      'xl1-effect-plan.invalid-receipt',\n      'XL1 transaction effect receipt must begin with prepared evidence',\n    )\n  }\n  return prepared\n}\n\nfunction currentSignedObservation(receipt: EffectReceipt): SignedObservation | undefined {\n  return receipt.observations.findLast(observation => observation.kind === 'signed')\n}\n\nfunction liveInclusion(\n  receipt: EffectReceipt,\n  transactionHash: string,\n): IncludedObservation | undefined {\n  const invalidated = new Set(receipt.observations\n    .filter(observation => observation.kind === 'inclusion-invalidated')\n    .map(observation => observation.evidence.inclusionSequence))\n  return receipt.observations.findLast(observation => observation.kind === 'included'\n    && observation.evidence.transactionHash === transactionHash\n    && !invalidated.has(observation.sequence)) as IncludedObservation | undefined\n}\n\nfunction contentProgress(receipt: EffectReceipt, contentHash: string): ContentProgress {\n  let unavailableSequence = 0\n  let verifiedSequence = 0\n  let writtenSequence = 0\n  for (const observation of receipt.observations) {\n    if (observation.kind === 'content-unavailable' && observation.evidence.contentHash === contentHash) {\n      unavailableSequence = observation.sequence\n    }\n    if (observation.kind === 'content-verified' && observation.evidence.contentHash === contentHash) {\n      verifiedSequence = observation.sequence\n    }\n    if (observation.kind === 'content-written' && observation.evidence.contentHash === contentHash) {\n      writtenSequence = observation.sequence\n    }\n  }\n  return {\n    unavailableSequence, verifiedSequence, writtenSequence,\n  }\n}\n\nfunction nextContentPlan(\n  receipt: EffectReceipt,\n  prepared: PreparedObservation,\n  signed: SignedObservation,\n): Xl1TransactionEffectPlan | undefined {\n  for (const contentHash of prepared.evidence.requiredContentHashes) {\n    const progress = contentProgress(receipt, contentHash)\n    if (progress.verifiedSequence > progress.unavailableSequence) continue\n    return {\n      action: progress.writtenSequence > progress.unavailableSequence ? 'verify-content' : 'write-content',\n      contentHash,\n      signedSequence: signed.sequence,\n      state: 'action',\n      transactionHash: signed.evidence.transactionHash,\n    }\n  }\n}\n\n/**\n * Selects the next safe baseline action without performing I/O.\n *\n * V1 replacement histories remain readable but cannot execute without a qualified\n * eligibility contract. An invalidated initial inclusion alone never authorizes replacement.\n */\nexport function planXl1TransactionEffect(receiptValue: EffectReceipt): Xl1TransactionEffectPlan {\n  const validation = validateEffectReceipt(receiptValue)\n  if (!validation.success) {\n    throw new Xl1TransactionEffectPlanError(\n      'xl1-effect-plan.invalid-receipt',\n      'XL1 transaction effect planning requires a valid receipt',\n    )\n  }\n  const receipt = validation.value\n  if (receipt.identity.effectKind !== 'xl1-transaction') {\n    throw new Xl1TransactionEffectPlanError(\n      'xl1-effect-plan.unsupported-effect-kind',\n      `Unsupported effect kind: ${receipt.identity.effectKind}`,\n    )\n  }\n\n  const latest = receipt.observations.at(-1)\n  if (latest?.kind === 'abandoned') return { state: 'abandoned' }\n  const support = assessEffectReceiptExecutionSupport(receipt)\n  if (!support.supported) return { reasonCode: support.reasonCode, state: 'pending' }\n  if (latest?.kind === 'error' && !latest.evidence.retriable) {\n    return { reasonCode: 'non-retriable-error-requires-decision', state: 'pending' }\n  }\n\n  const prepared = preparedObservation(receipt)\n  const signed = currentSignedObservation(receipt)\n  if (signed === undefined) return { action: 'sign', state: 'action' }\n\n  const content = nextContentPlan(receipt, prepared, signed)\n  if (content !== undefined) return content\n\n  const transactionHash = signed.evidence.transactionHash\n  const finalized = receipt.observations.find(observation => observation.kind === 'finalized')\n  if (finalized !== undefined) return { state: 'complete' }\n\n  const hasBroadcast = receipt.observations.some(observation => observation.kind === 'broadcast'\n    && observation.evidence.transactionHash === transactionHash)\n  if (!hasBroadcast) {\n    return {\n      action: 'reconcile-broadcast',\n      signedSequence: signed.sequence,\n      state: 'action',\n      transactionHash,\n    }\n  }\n\n  const inclusion = liveInclusion(receipt, transactionHash)\n  if (inclusion === undefined) {\n    return {\n      action: 'observe-inclusion',\n      signedSequence: signed.sequence,\n      state: 'action',\n      transactionHash,\n    }\n  }\n  return {\n    action: 'observe-finality',\n    inclusionSequence: inclusion.sequence,\n    signedSequence: signed.sequence,\n    state: 'action',\n    transactionHash,\n  }\n}\n", "import { z } from 'zod'\n\nimport type {\n  EffectReceiptObservationInput,\n  EffectReconciler,\n  EffectReconciliationPending,\n  EffectReconciliationResult,\n} from './effectExecution.ts'\nimport type {\n  EffectReceipt,\n  EffectReceiptObservation,\n} from './effectModel.ts'\nimport { EffectReceiptObservationZod, EffectReceiptZod } from './effectModel.ts'\nimport { IdentifierZod } from './identifier.ts'\nimport type { Xl1TransactionEffectPlan } from './xl1TransactionEffectPlan.ts'\nimport { planXl1TransactionEffect } from './xl1TransactionEffectPlan.ts'\n\ntype ObservationKind = EffectReceiptObservation['kind']\ntype ObservationInputOfKind<Kind extends ObservationKind> = Kind extends ObservationKind\n  ? Omit<Extract<EffectReceiptObservation, { kind: Kind }>, 'sequence'>\n  : never\n\ntype ControlObservationInput = ObservationInputOfKind<'abandoned' | 'error'>\n\nexport type Xl1TransactionEffectCapabilityResult<Kind extends ObservationKind>\n  = | EffectReconciliationPending\n    | {\n      readonly observation: ObservationInputOfKind<Kind> | ControlObservationInput\n      readonly state: 'advance'\n    }\n\ntype ActionPlan = Extract<Xl1TransactionEffectPlan, { state: 'action' }>\ntype PlanFor<Action extends ActionPlan['action']> = Extract<ActionPlan, { action: Action }>\n\nexport interface Xl1TransactionEffectCapabilityContext<Action extends ActionPlan['action']> {\n  readonly plan: PlanFor<Action>\n  readonly receipt: EffectReceipt\n}\n\nexport interface Xl1TransactionEffectCapabilities {\n  readonly observeFinality: (\n    context: Xl1TransactionEffectCapabilityContext<'observe-finality'>,\n  ) => Promise<Xl1TransactionEffectCapabilityResult<'finalized' | 'inclusion-invalidated'>>\n  readonly observeInclusion: (\n    context: Xl1TransactionEffectCapabilityContext<'observe-inclusion'>,\n  ) => Promise<Xl1TransactionEffectCapabilityResult<'included'>>\n  readonly reconcileBroadcast: (\n    context: Xl1TransactionEffectCapabilityContext<'reconcile-broadcast'>,\n  ) => Promise<Xl1TransactionEffectCapabilityResult<'broadcast'>>\n  readonly sign: (\n    context: Xl1TransactionEffectCapabilityContext<'sign'>,\n  ) => Promise<Xl1TransactionEffectCapabilityResult<'signed'>>\n  readonly verifyContent: (\n    context: Xl1TransactionEffectCapabilityContext<'verify-content'>,\n  ) => Promise<Xl1TransactionEffectCapabilityResult<'content-verified'>>\n  readonly writeContent: (\n    context: Xl1TransactionEffectCapabilityContext<'write-content'>,\n  ) => Promise<Xl1TransactionEffectCapabilityResult<'content-written'>>\n}\n\nexport const Xl1TransactionEffectReconcilerIssueCodes = [\n  'xl1-effect-reconciler.evidence-mismatch',\n  'xl1-effect-reconciler.invalid-capability-result',\n  'xl1-effect-reconciler.terminal-receipt',\n] as const\n\nexport const Xl1TransactionEffectReconcilerIssueCodeZod = z.enum(Xl1TransactionEffectReconcilerIssueCodes)\nexport type Xl1TransactionEffectReconcilerIssueCode = z.infer<typeof Xl1TransactionEffectReconcilerIssueCodeZod>\n\nexport class Xl1TransactionEffectReconcilerError extends Error {\n  readonly code: Xl1TransactionEffectReconcilerIssueCode\n\n  constructor(code: Xl1TransactionEffectReconcilerIssueCode, message: string) {\n    super(message)\n    this.name = 'Xl1TransactionEffectReconcilerError'\n    this.code = code\n  }\n}\n\nconst acceptedKinds: Readonly<Record<ActionPlan['action'], ReadonlySet<ObservationKind>>> = {\n  'observe-finality': new Set(['abandoned', 'error', 'finalized', 'inclusion-invalidated']),\n  'observe-inclusion': new Set(['abandoned', 'error', 'included']),\n  'reconcile-broadcast': new Set(['abandoned', 'broadcast', 'error']),\n  'sign': new Set(['abandoned', 'error', 'signed']),\n  'verify-content': new Set(['abandoned', 'content-verified', 'error']),\n  'write-content': new Set(['abandoned', 'content-written', 'error']),\n}\n\nfunction reconcilerError(\n  code: Xl1TransactionEffectReconcilerIssueCode,\n  message: string,\n): Xl1TransactionEffectReconcilerError {\n  return new Xl1TransactionEffectReconcilerError(code, message)\n}\n\nfunction normalizedCapabilityResult(\n  result: EffectReconciliationResult,\n  nextSequence: number,\n): EffectReconciliationResult {\n  if (result.state === 'pending') {\n    const parsed = IdentifierZod.safeParse(result.reasonCode)\n    if (!parsed.success) {\n      throw reconcilerError(\n        'xl1-effect-reconciler.invalid-capability-result',\n        'XL1 effect capability returned an invalid pending reason code',\n      )\n    }\n    return { reasonCode: parsed.data, state: 'pending' }\n  }\n\n  const parsed = EffectReceiptObservationZod.safeParse({\n    ...result.observation,\n    sequence: nextSequence,\n  })\n  if (!parsed.success) {\n    throw reconcilerError(\n      'xl1-effect-reconciler.invalid-capability-result',\n      'XL1 effect capability returned an invalid observation',\n    )\n  }\n  const { sequence: _sequence, ...observation } = parsed.data\n  return { observation, state: 'advance' }\n}\n\nfunction assertMatchingEvidence(plan: ActionPlan, observation: EffectReceiptObservationInput): void {\n  if (!acceptedKinds[plan.action].has(observation.kind)) {\n    throw reconcilerError(\n      'xl1-effect-reconciler.evidence-mismatch',\n      `XL1 effect capability returned ${observation.kind} evidence for ${plan.action}`,\n    )\n  }\n  if (observation.kind === 'abandoned' || observation.kind === 'error') return\n\n  if ((plan.action === 'write-content' || plan.action === 'verify-content')\n    && (observation.kind === 'content-written' || observation.kind === 'content-verified')\n    && observation.evidence.contentHash !== plan.contentHash) {\n    throw reconcilerError(\n      'xl1-effect-reconciler.evidence-mismatch',\n      'XL1 content evidence does not match the planned content hash',\n    )\n  }\n  if ((plan.action === 'reconcile-broadcast' || plan.action === 'observe-inclusion')\n    && (observation.kind === 'broadcast' || observation.kind === 'included')\n    && observation.evidence.transactionHash !== plan.transactionHash) {\n    throw reconcilerError(\n      'xl1-effect-reconciler.evidence-mismatch',\n      'XL1 chain evidence does not match the planned transaction hash',\n    )\n  }\n  if (plan.action === 'observe-finality'\n    && (observation.kind === 'finalized' || observation.kind === 'inclusion-invalidated')\n    && observation.evidence.inclusionSequence !== plan.inclusionSequence) {\n    throw reconcilerError(\n      'xl1-effect-reconciler.evidence-mismatch',\n      'XL1 finality evidence does not match the planned inclusion',\n    )\n  }\n}\n\nasync function invokeCapability(\n  capabilities: Xl1TransactionEffectCapabilities,\n  plan: ActionPlan,\n  receipt: EffectReceipt,\n): Promise<EffectReconciliationResult> {\n  switch (plan.action) {\n    case 'sign': return await capabilities.sign({ plan, receipt })\n    case 'write-content': return await capabilities.writeContent({ plan, receipt })\n    case 'verify-content': return await capabilities.verifyContent({ plan, receipt })\n    case 'reconcile-broadcast': return await capabilities.reconcileBroadcast({ plan, receipt })\n    case 'observe-inclusion': return await capabilities.observeInclusion({ plan, receipt })\n    case 'observe-finality': return await capabilities.observeFinality({ plan, receipt })\n  }\n}\n\nexport function createXl1TransactionEffectReconciler(\n  capabilities: Xl1TransactionEffectCapabilities,\n): EffectReconciler {\n  return {\n    reconcile: async (receiptValue): Promise<EffectReconciliationResult> => {\n      const receipt = EffectReceiptZod.parse(receiptValue)\n      const plan = planXl1TransactionEffect(receipt)\n      if (plan.state === 'pending') return plan\n      if (plan.state !== 'action') {\n        throw reconcilerError(\n          'xl1-effect-reconciler.terminal-receipt',\n          `Cannot reconcile a terminal XL1 effect receipt: ${plan.state}`,\n        )\n      }\n\n      const result = normalizedCapabilityResult(\n        await invokeCapability(capabilities, plan, receipt),\n        receipt.observations.length + 1,\n      )\n      if (result.state === 'advance') assertMatchingEvidence(plan, result.observation)\n      return result\n    },\n  }\n}\n"],
  "mappings": ";AAAA,SAAS,KAAAA,UAAS;;;ACAlB,SAAS,cAAc;AACvB,SAAS,YAAY,mBAAmB;AACxC,SAAS,SAAS;AAEX,IAAM,4BAA4B;AAElC,IAAM,sBAAsB,EAAE,KAAK;AAAA,EACxC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAEA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA,EAEA;AAAA,EACA;AAAA;AAAA,EAEA;AACF,CAAC;AAqBD,SAAS,mBAAmB,OAAe,MAAoB;AAC7D,aAAW,aAAa,OAAO;AAC7B,UAAM,YAAY,UAAU,YAAY,CAAC;AACzC,QAAI,cAAc,UAAa,aAAa,SAAW,aAAa,OAAS;AAC3E,YAAM,IAAI,UAAU,GAAG,IAAI,sCAAsC;AAAA,IACnE;AACA,QAAI,cAAc,UAAa,aAAa,SAAW,aAAa,OAAS;AAC3E,YAAM,IAAI,UAAU,GAAG,IAAI,qCAAqC;AAAA,IAClE;AAAA,EACF;AACF;AAEA,SAAS,kBAAkB,OAAkB,MAAsB;AACjE,QAAM,iBAAiB,OAAO,KAAK,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AW,OAAO,iBAAsD;AACtE,YAAM,UAAU,iBAAiB,MAAM,YAAY;AACnD,YAAM,OAAO,yBAAyB,OAAO;AAC7C,UAAI,KAAK,UAAU,UAAW,QAAO;AACrC,UAAI,KAAK,UAAU,UAAU;AAC3B,cAAM;AAAA,UACJ;AAAA,UACA,mDAAmD,KAAK,KAAK;AAAA,QAC/D;AAAA,MACF;AAEA,YAAMA,UAAS;AAAA,QACb,MAAM,iBAAiB,cAAc,MAAM,OAAO;AAAA,QAClD,QAAQ,aAAa,SAAS;AAAA,MAChC;AACA,UAAIA,QAAO,UAAU,UAAW,wBAAuB,MAAMA,QAAO,WAAW;AAC/E,aAAOA;AAAA,IACT;AAAA,EACF;AACF;",
  "names": ["z", "key", "z", "z", "z", "z", "z", "z", "key", "result", "value", "z", "z", "z", "z", "z", "store", "z", "key", "z", "asSchema", "z", "asSchema", "z", "reject", "asSchema", "z", "asSchema", "z", "issue", "store", "z", "z", "issue", "result", "store", "asSchema", "z", "capabilityKey", "sortedStrings", "issuePath", "issue", "result", "key", "z", "z", "asSchema", "z", "z", "asSchema", "z", "asSchema", "z", "asSchema", "z", "asSchema", "z", "z", "z", "asSchema", "z", "asSchema", "z", "result", "failure", "writeState", "result", "bytesToHex", "utf8ToBytes", "asSchema", "z", "key", "normalized", "store", "sha256", "bytesToHex", "utf8ToBytes", "asSchema", "z", "asSchema", "z", "utf8ToBytes", "bytesToHex", "sha256", "key", "result", "pointer", "key", "asSchema", "z", "bytes", "utf8ToBytes", "bytesToHex", "key", "page", "result", "asSchema", "z", "asSchema", "z", "asSchema", "z", "asSchema", "z", "asSchema", "z", "sortedRecord", "z", "z", "sortedUnique", "sortedRecord", "normalizedThing", "normalizedRequest", "asSchema", "z", "asSchema", "z", "issue", "asSchema", "z", "asSchema", "z", "z", "z", "issuePath", "result", "issue", "result", "issue", "normalized", "asSchema", "z", "issue", "invalid", "result", "asSchema", "z", "z", "descriptorKey", "reject", "key", "asSchema", "z", "asSchema", "z", "z", "resource", "resourceId", "capabilityKey", "issue", "asSchema", "z", "issue", "result", "z", "z", "z", "issue", "normalizedRequest", "projectIssue", "result", "z", "invalid", "sortedRecord", "sortedArtifacts", "sourceIssue", "result", "issue", "z", "z", "refineSortedById", "issue", "invalid", "sortedRecord", "sortedArtifacts", "sourceIssue", "result", "asSchema", "z", "asSchema", "z", "compareCodeUnits", "z", "z", "asSchema", "z", "asSchema", "z", "z", "asSchema", "addUniqueIssue", "asSchema", "z", "z", "z", "issue", "structuralIssues", "result", "z", "issue", "result", "z", "result", "z", "z", "z", "asSchema", "z", "asSchema", "z", "asSchema", "z", "asSchema", "z", "z", "asSchema", "z", "asSchema", "z", "transitionError", "assertScope", "result", "asSchema", "z", "asSchema", "z", "asSchema", "z", "asSchema", "z", "result", "z", "z", "asSchema", "z", "asSchema", "PositiveIntegerZod", "z", "SortedIdentifiersZod", "bytesToHex", "hexToBytes", "utf8ToBytes", "z", "z", "key", "bytesToHex", "utf8ToBytes", "hexToBytes", "failure", "asSchema", "z", "UnixMillisecondsZod", "z", "asSchema", "version", "z", "z", "issue", "issuePath", "isStreamFrame", "result", "value", "asSchema", "z", "asSchema", "z", "asSchema", "z", "z", "z", "issue", "structuralIssues", "result", "asSchema", "z", "scopeMatches", "result", "asSchema", "z", "asSchema", "z", "duplicateValues", "asSchema", "z", "asSchema", "z", "issue", "asSchema", "z", "asSchema", "PositiveIntegerZod", "z", "issue", "asSchema", "z", "z", "asSchema", "issue", "asSchema", "z", "asSchema", "z", "asSchema", "z", "asSchema", "z", "asSchema", "z", "asSchema", "UnixMillisecondsZod", "z", "result", "issue", "identityIssues", "asSchema", "z", "asSchema", "z", "asSchema", "z", "asSchema", "z", "asSchema", "z", "asSchema", "z", "key", "issue", "asSchema", "z", "asSchema", "z", "z", "z", "normalized", "z", "asSchema", "z", "asSchema", "PositiveIntegerZod", "z", "z", "z", "SortedIdentifiersZod", "issue", "z", "refineSorted", "issue", "refineCapabilities", "refineTargetObjects", "key", "z", "SequenceZod", "z", "z", "z", "result", "parsed"]
}
