chainlesschain 0.166.15 → 0.166.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (184) hide show
  1. package/package.json +1 -1
  2. package/src/assets/web-panel/assets/{AIOps-To-6rimH.js → AIOps-CTxa2Wbq.js} +1 -1
  3. package/src/assets/web-panel/assets/{ActionButton-CpdCnTv3.js → ActionButton-DHrQyYhy.js} +1 -1
  4. package/src/assets/web-panel/assets/{Analytics-DK7VNES_.js → Analytics-DQiUqcNl.js} +3 -3
  5. package/src/assets/web-panel/assets/{AppLayout-NZ5FvhCx.js → AppLayout-_Iz4r6wt.js} +5 -5
  6. package/src/assets/web-panel/assets/{Artifacts-NXceQPmN.js → Artifacts-BNs63YHo.js} +1 -1
  7. package/src/assets/web-panel/assets/{Audit-B2d64DH2.js → Audit-BgHIqRLn.js} +1 -1
  8. package/src/assets/web-panel/assets/{BackgroundAgents-ByYgvEVY.js → BackgroundAgents-DUQ5axBB.js} +1 -1
  9. package/src/assets/web-panel/assets/{Backup-BXvQLDvN.js → Backup-CJ51E9Vw.js} +1 -1
  10. package/src/assets/web-panel/assets/{BaseInput-C4GZk-As.js → BaseInput-o-5toA_R.js} +1 -1
  11. package/src/assets/web-panel/assets/{Chat-CvPuohL8.js → Chat-Cu7a-x1L.js} +6 -6
  12. package/src/assets/web-panel/assets/{ChatBubbleRenderer-DTftcclX.js → ChatBubbleRenderer-BUyYkAXr.js} +1 -1
  13. package/src/assets/web-panel/assets/{Checkbox-C8dQGIqD.js → Checkbox-DwdmZ71L.js} +1 -1
  14. package/src/assets/web-panel/assets/{Codegen-DRM6S1W4.js → Codegen-BrH2eYiP.js} +1 -1
  15. package/src/assets/web-panel/assets/{Col-BDM8l-r5.js → Col-BVJQEP2j.js} +1 -1
  16. package/src/assets/web-panel/assets/{Community-Bvmfi1fX.js → Community-FGO3vZPq.js} +1 -1
  17. package/src/assets/web-panel/assets/{Compact-DGQTCima.js → Compact-DYGAFVnT.js} +1 -1
  18. package/src/assets/web-panel/assets/{Compliance-D_0C-2P6.js → Compliance-CRvc8Bdt.js} +1 -1
  19. package/src/assets/web-panel/assets/{Cowork-3C_q99ok.js → Cowork-D6Ah2m7A.js} +3 -3
  20. package/src/assets/web-panel/assets/{Cron-CIiMQ1Hl.js → Cron-AXbU2ifR.js} +2 -2
  21. package/src/assets/web-panel/assets/{Crosschain-peebGnES.js → Crosschain-C5DXgEFd.js} +1 -1
  22. package/src/assets/web-panel/assets/{DID-OkX4KB9T.js → DID-Bxh9QV9v.js} +2 -2
  23. package/src/assets/web-panel/assets/{Dashboard-D9lm0Wxa.js → Dashboard-B-ZHEta-.js} +2 -2
  24. package/src/assets/web-panel/assets/{Dropdown-CitActXx.js → Dropdown-66Ik1jqa.js} +1 -1
  25. package/src/assets/web-panel/assets/{EmailListRenderer-DSmFkNKV.js → EmailListRenderer-CCWk1BIM.js} +1 -1
  26. package/src/assets/web-panel/assets/{FamilyGuardDashboard-CBWAi8XL.js → FamilyGuardDashboard--9faIULK.js} +1 -1
  27. package/src/assets/web-panel/assets/{Federation-afj8jDcp.js → Federation-CejW9CgX.js} +1 -1
  28. package/src/assets/web-panel/assets/{FormItemContext-Dabt59KY.js → FormItemContext-acHgcXki.js} +1 -1
  29. package/src/assets/web-panel/assets/{GenericCardRenderer-BQpXA9kj.js → GenericCardRenderer-D2ghd_K4.js} +1 -1
  30. package/src/assets/web-panel/assets/{Git-D2p2Moo1.js → Git-BOe1YJrV.js} +2 -2
  31. package/src/assets/web-panel/assets/{Governance-DkFfPykv.js → Governance-BjgzJsof.js} +1 -1
  32. package/src/assets/web-panel/assets/{Inference-C1DKpeN2.js → Inference-CXCD5rnP.js} +1 -1
  33. package/src/assets/web-panel/assets/{KnowledgeGraph-CjfVg4oQ.js → KnowledgeGraph-CHA8QgJT.js} +1 -1
  34. package/src/assets/web-panel/assets/{Logs-D-zMvdSf.js → Logs-DORPMcL6.js} +2 -2
  35. package/src/assets/web-panel/assets/{MarkdownRenderer-jzEpGkbc.js → MarkdownRenderer-CPPHz01z.js} +1 -1
  36. package/src/assets/web-panel/assets/{Marketplace-DfAjJLyS.js → Marketplace-BCFlo1Yx.js} +1 -1
  37. package/src/assets/web-panel/assets/{McpTools-BGDHQES1.js → McpTools-Dl_uZAKh.js} +3 -3
  38. package/src/assets/web-panel/assets/{Memory-BYqrGAPS.js → Memory-DupHamwz.js} +2 -2
  39. package/src/assets/web-panel/assets/{MobileBridge-CQ6FEtty.js → MobileBridge-BRSMPJxW.js} +1 -1
  40. package/src/assets/web-panel/assets/{MobileProjects-BpMvh5JW.js → MobileProjects-BHpuzsDl.js} +1 -1
  41. package/src/assets/web-panel/assets/{Mtc-CWH25SrU.js → Mtc-Ch0jOQfZ.js} +2 -2
  42. package/src/assets/web-panel/assets/{MtcAudit-D6DiLmei.js → MtcAudit-qzwQrDi7.js} +2 -2
  43. package/src/assets/web-panel/assets/{Multisig-BSxRN4jD.js → Multisig-B5wHzUcm.js} +3 -3
  44. package/src/assets/web-panel/assets/{NLProgramming-C0FDPKT4.js → NLProgramming-Hy9uAiA0.js} +1 -1
  45. package/src/assets/web-panel/assets/{Notes-VKR78bH-.js → Notes-DkuchMC7.js} +3 -3
  46. package/src/assets/web-panel/assets/{NotificationSettings-DLSklSZB.js → NotificationSettings-CYZhD7Pi.js} +1 -1
  47. package/src/assets/web-panel/assets/{OrderTableRenderer-Dpj7D6tC.js → OrderTableRenderer-DKOoqajt.js} +1 -1
  48. package/src/assets/web-panel/assets/{Organization-BB3pB27e.js → Organization-D9AXn6j8.js} +4 -4
  49. package/src/assets/web-panel/assets/{Overflow-Cr7bzwcs.js → Overflow-Bg15J6hX.js} +1 -1
  50. package/src/assets/web-panel/assets/{P2P-D1fkMMzI.js → P2P--B54HoQn.js} +2 -2
  51. package/src/assets/web-panel/assets/{PdhVaultBrowser-BiDEbLNA.js → PdhVaultBrowser-Cz9Kk2Nb.js} +3 -3
  52. package/src/assets/web-panel/assets/{Permissions-c3Ijv0v4.js → Permissions-DHx38eS1.js} +4 -4
  53. package/src/assets/web-panel/assets/{PersonalDataHub-BJwbh3P2.js → PersonalDataHub-Dw8i2hAs.js} +4 -4
  54. package/src/assets/web-panel/assets/{Pipeline-C4fhXafB.js → Pipeline-B2o6Ur2G.js} +1 -1
  55. package/src/assets/web-panel/assets/{Privacy-DzSx3CD-.js → Privacy-8g-h2fnu.js} +1 -1
  56. package/src/assets/web-panel/assets/{ProjectInit-D9fL5fED.js → ProjectInit-DuVTcINx.js} +2 -2
  57. package/src/assets/web-panel/assets/{ProjectSettings-CB5FVrOR.js → ProjectSettings-C8njvdZX.js} +2 -2
  58. package/src/assets/web-panel/assets/Projects-Ca9BAfu7.js +1 -0
  59. package/src/assets/web-panel/assets/{Providers-B9ZH4faS.js → Providers-wFqgod_W.js} +1 -1
  60. package/src/assets/web-panel/assets/{QrScannerModal-BLKDHT8_.js → QrScannerModal-9NCXrpmA.js} +1 -1
  61. package/src/assets/web-panel/assets/{QuickAsk-D1oYUcSY.js → QuickAsk-WUTNvFkY.js} +1 -1
  62. package/src/assets/web-panel/assets/{Recommend-CC2nmrOD.js → Recommend-xT4nYmju.js} +1 -1
  63. package/src/assets/web-panel/assets/{RemoteSession-qW9QF4-r.js → RemoteSession-fak1PBGC.js} +2 -2
  64. package/src/assets/web-panel/assets/{Reputation-BDWqfzcr.js → Reputation-D1AkQvD-.js} +1 -1
  65. package/src/assets/web-panel/assets/{Row-BBV2iCjT.js → Row-DVfm6xGt.js} +1 -1
  66. package/src/assets/web-panel/assets/{RssFeed-CcwrNwZB.js → RssFeed-BDunoLSE.js} +3 -3
  67. package/src/assets/web-panel/assets/{Search-Dr6fZ0D_.js → Search-OPycRoU3.js} +1 -1
  68. package/src/assets/web-panel/assets/{Security-BPzaoCU6.js → Security-C8-Fm3Dt.js} +4 -4
  69. package/src/assets/web-panel/assets/{Services-BoKUU1I_.js → Services-qM_sMpMl.js} +2 -2
  70. package/src/assets/web-panel/assets/{Skeleton-C8lT8GUg.js → Skeleton-D3HBJjVF.js} +1 -1
  71. package/src/assets/web-panel/assets/{Skills-DPpWeicz.js → Skills-jr67X-tP.js} +1 -1
  72. package/src/assets/web-panel/assets/{Sla-UiijzpMU.js → Sla-CS3ggyCg.js} +1 -1
  73. package/src/assets/web-panel/assets/{SpeechSettings-DoofrLwS.js → SpeechSettings-CTOCYxOi.js} +1 -1
  74. package/src/assets/web-panel/assets/{SyncSettings-DXnyfTDw.js → SyncSettings-D3s3cLT5.js} +2 -2
  75. package/src/assets/web-panel/assets/{Tasks-g_WHjKeg.js → Tasks-CdfoJ25m.js} +1 -1
  76. package/src/assets/web-panel/assets/{Templates-DRuCh9g2.js → Templates-Drb4AI8X.js} +1 -1
  77. package/src/assets/web-panel/assets/{Tenant-QHIq1pH1.js → Tenant-DzwR3Qkz.js} +1 -1
  78. package/src/assets/web-panel/assets/{Terminal-G0fuI216.js → Terminal-D-ESq7xp.js} +2 -2
  79. package/src/assets/web-panel/assets/{TimelineRenderer-4MT7SpGk.js → TimelineRenderer-BK-AUuws.js} +1 -1
  80. package/src/assets/web-panel/assets/{Tokens-B5xT5umA.js → Tokens-xGTouuNp.js} +1 -1
  81. package/src/assets/web-panel/assets/{Trigger-D7HPbNgc.js → Trigger-BvZj-v2H.js} +1 -1
  82. package/src/assets/web-panel/assets/{Trust-CxH69dU5.js → Trust-BLC9CGmc.js} +1 -1
  83. package/src/assets/web-panel/assets/{UkeySign-CPPosveH.js → UkeySign-BSuCXpmE.js} +1 -1
  84. package/src/assets/web-panel/assets/{VideoEditing-Du5lGwAt.js → VideoEditing-DT3A-_Ql.js} +1 -1
  85. package/src/assets/web-panel/assets/{Wallet-BBIGNESK.js → Wallet-c1OXao85.js} +4 -4
  86. package/src/assets/web-panel/assets/{WebAuthn-Cc3HSGmv.js → WebAuthn-CuA-F7KJ.js} +5 -5
  87. package/src/assets/web-panel/assets/{WorkflowEditor-DBoVPNCh.js → WorkflowEditor-MANZrf82.js} +1 -1
  88. package/src/assets/web-panel/assets/{chat-DHcjgiem.js → chat-D4Y4Ey0O.js} +1 -1
  89. package/src/assets/web-panel/assets/{colors-DrRrvJIV.js → colors-DDH06hKO.js} +1 -1
  90. package/src/assets/web-panel/assets/{compact-item-BuY_sAoN.js → compact-item-Cym756Xj.js} +1 -1
  91. package/src/assets/web-panel/assets/{createContext-CepH1Fha.js → createContext-By4Nb1k-.js} +1 -1
  92. package/src/assets/web-panel/assets/devWarning-KO3pAGeO.js +1 -0
  93. package/src/assets/web-panel/assets/{hasIn-Dh80Ot6o.js → hasIn-Ch7OY258.js} +1 -1
  94. package/src/assets/web-panel/assets/{index-BW9Pycxh.js → index-6-2eYBXr.js} +1 -1
  95. package/src/assets/web-panel/assets/{index-D7lstbTh.js → index-6CpOV3Pn.js} +1 -1
  96. package/src/assets/web-panel/assets/{index-CUnd5hyp.js → index-ArMrnx0v.js} +1 -1
  97. package/src/assets/web-panel/assets/{index-B0rvJjId.js → index-B51otVoZ.js} +1 -1
  98. package/src/assets/web-panel/assets/{index-D6tOVlq-.js → index-BBBUn5v7.js} +1 -1
  99. package/src/assets/web-panel/assets/{index-NS9dW1F1.js → index-BFydNU6a.js} +1 -1
  100. package/src/assets/web-panel/assets/{index-CiUx-tkV.js → index-BIrRX-ra.js} +1 -1
  101. package/src/assets/web-panel/assets/{index-By0qqC3S.js → index-BZB9q-Lp.js} +1 -1
  102. package/src/assets/web-panel/assets/index-Bh4Rgkg2.js +1 -0
  103. package/src/assets/web-panel/assets/{index-CNQK9DIr.js → index-Bo20BfdS.js} +1 -1
  104. package/src/assets/web-panel/assets/{index-C10033eO.js → index-CF3Lhyns.js} +1 -1
  105. package/src/assets/web-panel/assets/{index-DRy3_beb.js → index-CGsvEbbq.js} +1 -1
  106. package/src/assets/web-panel/assets/{index-DWANFMlq.js → index-CJPks33Y.js} +1 -1
  107. package/src/assets/web-panel/assets/{index-CnRK8_Dd.js → index-CT-3FYwd.js} +1 -1
  108. package/src/assets/web-panel/assets/{index-BPDEOOlA.js → index-CUSUzaB8.js} +1 -1
  109. package/src/assets/web-panel/assets/{index-DYN49m7k.js → index-CV1UC4zo.js} +1 -1
  110. package/src/assets/web-panel/assets/{index-C5vhNRqS.js → index-CV8qXTvb.js} +1 -1
  111. package/src/assets/web-panel/assets/{index-9crgJ3Id.js → index-CZn6dmZe.js} +1 -1
  112. package/src/assets/web-panel/assets/{index-DkZP_QaB.js → index-CjNUTBwe.js} +1 -1
  113. package/src/assets/web-panel/assets/{index-BoRy2yup.js → index-CpudmDhf.js} +1 -1
  114. package/src/assets/web-panel/assets/{index-Ca5d64IH.js → index-CykROEJA.js} +1 -1
  115. package/src/assets/web-panel/assets/{index-A5lVwYVq.js → index-D5sADPGY.js} +1 -1
  116. package/src/assets/web-panel/assets/{index-BnVIvc15.js → index-D9le0-dc.js} +1 -1
  117. package/src/assets/web-panel/assets/{index-Cx21_p3m.js → index-DAkk1M7x.js} +1 -1
  118. package/src/assets/web-panel/assets/{index-0TYLnd11.js → index-DNEJzc0r.js} +1 -1
  119. package/src/assets/web-panel/assets/{index-B9Gh-SOn.js → index-DNlxihs8.js} +1 -1
  120. package/src/assets/web-panel/assets/{index-BtqigRzf.js → index-DiewptTL.js} +1 -1
  121. package/src/assets/web-panel/assets/{index-CW_23-gU.js → index-DjwgJ5Jd.js} +1 -1
  122. package/src/assets/web-panel/assets/index-Dox_coTY.js +1 -0
  123. package/src/assets/web-panel/assets/{index-LBkSOwky.js → index-DtGValNi.js} +1 -1
  124. package/src/assets/web-panel/assets/{index-D5_K3GKu.js → index-DvnywwUj.js} +1 -1
  125. package/src/assets/web-panel/assets/{index-BiZQooWK.js → index-OU8DZ9BL.js} +1 -1
  126. package/src/assets/web-panel/assets/{index-CYydOga6.js → index-XGeQMvWK.js} +1 -1
  127. package/src/assets/web-panel/assets/{index-hYaigdGm.js → index-ZY2Qs_Sn.js} +1 -1
  128. package/src/assets/web-panel/assets/{index-zGH9zH3w.js → index-jx7kr6mB.js} +3 -3
  129. package/src/assets/web-panel/assets/{index-DuRYBWrj.js → index-mL3nOcH6.js} +1 -1
  130. package/src/assets/web-panel/assets/{index-DuSUCH7h.js → index-oBsfUbyH.js} +1 -1
  131. package/src/assets/web-panel/assets/{index-CEfVkKIY.js → index-q-s04OKn.js} +1 -1
  132. package/src/assets/web-panel/assets/{index-DUNyTmkS.js → index-tZ5BUdad.js} +1 -1
  133. package/src/assets/web-panel/assets/{initDefaultProps-nI_X3wKl.js → initDefaultProps-DGcX9iPP.js} +1 -1
  134. package/src/assets/web-panel/assets/{motion-LUHbQu_R.js → motion-2SeL1D8A.js} +1 -1
  135. package/src/assets/web-panel/assets/{move-DHI_KvJt.js → move-3cYbQCpS.js} +1 -1
  136. package/src/assets/web-panel/assets/{mtc-parser-AYdL_7Mo.js → mtc-parser-IDdxfw0z.js} +1 -1
  137. package/src/assets/web-panel/assets/{omit-CtV3HRKa.js → omit-BNswdKO6.js} +1 -1
  138. package/src/assets/web-panel/assets/{pickAttrs-CcJLTOu4.js → pickAttrs-BwCnem2I.js} +1 -1
  139. package/src/assets/web-panel/assets/{placementArrow-DHbiLUps.js → placementArrow-B9PtZ5rq.js} +1 -1
  140. package/src/assets/web-panel/assets/{responsiveObserve-BC2DGkWP.js → responsiveObserve-CPB6iSzV.js} +1 -1
  141. package/src/assets/web-panel/assets/{slide-B4ga4pPY.js → slide-DZgyblZa.js} +1 -1
  142. package/src/assets/web-panel/assets/{statusUtils-hzphgKfH.js → statusUtils-D82IBdsx.js} +1 -1
  143. package/src/assets/web-panel/assets/{styleChecker-IfN9Bxoi.js → styleChecker-qSHtosM-.js} +1 -1
  144. package/src/assets/web-panel/assets/{useFlexGapSupport-pcGKJ4pT.js → useFlexGapSupport-CmWO7h0I.js} +1 -1
  145. package/src/assets/web-panel/assets/{useFs-COXhQpTG.js → useFs-yLrs_ub4.js} +1 -1
  146. package/src/assets/web-panel/assets/{usePersonalDataHub-xp9F9szv.js → usePersonalDataHub-CJ1VW6rh.js} +1 -1
  147. package/src/assets/web-panel/assets/{vnode-BdSQy1Ve.js → vnode-CzY_moQ4.js} +1 -1
  148. package/src/assets/web-panel/assets/{zoom-CHCt5P55.js → zoom-DAa7rEY5.js} +1 -1
  149. package/src/assets/web-panel/index.html +1 -1
  150. package/src/commands/learning.js +71 -1
  151. package/src/commands/team.js +5 -0
  152. package/src/data/changelog.json +15 -2
  153. package/src/lib/agent-team/task-lease.js +12 -1
  154. package/src/lib/capability-manifest.js +212 -1
  155. package/src/lib/evolution/evolution-artifact-ports.js +3277 -0
  156. package/src/lib/evolution/evolution-eval-gate.js +6442 -0
  157. package/src/lib/evolution/evolution-evidence-projector.js +3786 -0
  158. package/src/lib/evolution/evolution-ledger-ports.js +2689 -0
  159. package/src/lib/evolution/evolution-ledger.js +4280 -0
  160. package/src/lib/evolution/skill-candidate-registry.js +2258 -0
  161. package/src/lib/evolution/skill-execution-manifest.js +942 -0
  162. package/src/lib/evolution/skill-mutation-authority.js +1677 -0
  163. package/src/lib/evolution/skill-promotion-controller.js +506 -0
  164. package/src/lib/evolution/skill-release-registry.js +3277 -0
  165. package/src/lib/evolution/skill-target-matrix-eval.js +3233 -0
  166. package/src/lib/evolution/skill-writer-inventory-manifest.js +998 -0
  167. package/src/lib/evolution/skill-writer-inventory-validator.js +816 -0
  168. package/src/lib/formal-quality-eval-runtime.js +100 -0
  169. package/src/lib/graph-kernel/cutover-contract.js +7 -0
  170. package/src/lib/graph-kernel/cutover-ledger.js +8 -7
  171. package/src/lib/graph-kernel/evidence-digest.js +47 -0
  172. package/src/lib/graph-kernel/graph-runtime-surfaces.json +8 -1
  173. package/src/lib/graph-kernel/production-cutover-evidence.js +342 -15
  174. package/src/lib/graph-kernel/production-source-evidence.js +1599 -0
  175. package/src/lib/graph-kernel/retirement-evidence.js +15 -5
  176. package/src/lib/graph-kernel/runtime-surface-manifest.js +67 -2
  177. package/src/lib/headless-manifest.js +3 -1
  178. package/src/lib/learning/skill-improver.js +311 -43
  179. package/src/lib/learning/skill-synthesizer.js +236 -16
  180. package/src/lib/secure-fs.js +20 -0
  181. package/src/assets/web-panel/assets/Projects-DWhwdgfY.js +0 -1
  182. package/src/assets/web-panel/assets/devWarning-DIb8j04q.js +0 -1
  183. package/src/assets/web-panel/assets/index-BJc3t4PC.js +0 -1
  184. package/src/assets/web-panel/assets/index-CkksSUnI.js +0 -1
@@ -0,0 +1,3233 @@
1
+ import { Buffer } from "node:buffer";
2
+ import { createHash, randomBytes } from "node:crypto";
3
+ import { types as utilTypes } from "node:util";
4
+
5
+ import {
6
+ EVOLUTION_EVAL_AUTHORITY_DESCRIPTOR_SCHEMA,
7
+ EvolutionEvalGate,
8
+ EvolutionEvalReceiptVerifier,
9
+ computeEvolutionEvalContextDigest,
10
+ runEvolutionEvalGate,
11
+ verifyEvolutionEvalReceipt,
12
+ } from "./evolution-eval-gate.js";
13
+ import {
14
+ verifySkillDependencyLock,
15
+ verifySkillRuntimeManifest,
16
+ verifySkillTargetMatrix,
17
+ } from "./skill-execution-manifest.js";
18
+
19
+ export const SKILL_TARGET_MATRIX_EVAL_PLAN_SCHEMA =
20
+ "chainlesschain.skill-target-matrix-eval-plan/v1";
21
+ export const SKILL_TARGET_MATRIX_EVAL_RECEIPT_SCHEMA =
22
+ "chainlesschain.skill-target-matrix-eval-receipt/v1";
23
+ export const SKILL_TARGET_MATRIX_EVAL_PLAN_RESOLUTION_SCHEMA =
24
+ "chainlesschain.skill-target-matrix-eval-plan-resolution/v1";
25
+ export const SKILL_TARGET_MATRIX_EVAL_RESERVATION_SCHEMA =
26
+ "chainlesschain.skill-target-matrix-eval-reservation/v1";
27
+ export const SKILL_TARGET_MATRIX_EVAL_FINALIZATION_SCHEMA =
28
+ "chainlesschain.skill-target-matrix-eval-finalization/v1";
29
+
30
+ export const SKILL_TARGET_MATRIX_EVAL_INVALID_CODE =
31
+ "CC_SKILL_TARGET_MATRIX_EVAL_INVALID";
32
+ export const SKILL_TARGET_MATRIX_EVAL_AUTHORITY_FAILED_CODE =
33
+ "CC_SKILL_TARGET_MATRIX_EVAL_AUTHORITY_FAILED";
34
+ export const SKILL_TARGET_MATRIX_EVAL_REPLAYED_CODE =
35
+ "CC_SKILL_TARGET_MATRIX_EVAL_REPLAYED";
36
+ export const SKILL_TARGET_MATRIX_EVAL_DEADLINE_CODE =
37
+ "CC_SKILL_TARGET_MATRIX_EVAL_DEADLINE";
38
+
39
+ /**
40
+ * This module commits trusted composition metadata and performs an all-cell
41
+ * conjunction. It is not a proof of JavaScript callable bytes and it is not a
42
+ * cross-cell statistical production gate.
43
+ */
44
+ export const SKILL_TARGET_MATRIX_EVAL_FOUNDATION_SEMANTICS = Object.freeze({
45
+ kind: "trusted-composition-configuration-commitment",
46
+ decision: "all-cells-conjunction",
47
+ cellSettlement:
48
+ "trusted-composition-bound-total-settlement-window-before-root-deadline",
49
+ crossCellStatistics: false,
50
+ requiresAttestedLoader: true,
51
+ residuals: Object.freeze([
52
+ "attested descriptor-to-callable loader",
53
+ "process-level hard termination",
54
+ "production durable plan nonce and receipt resolver",
55
+ ]),
56
+ });
57
+
58
+ const PLAN_SIGNATURE_PURPOSE = "skill-target-matrix-eval-plan";
59
+ const RESERVATION_SIGNATURE_PURPOSE = "skill-target-matrix-eval-reservation";
60
+ const FINALIZATION_SIGNATURE_PURPOSE = "skill-target-matrix-eval-finalization";
61
+ const RECEIPT_SIGNATURE_PURPOSE = "skill-target-matrix-eval-receipt";
62
+
63
+ const DIGEST_PATTERN = /^sha256:[a-f0-9]{64}$/u;
64
+ const SAFE_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,255}$/u;
65
+ const PLAN_REF_PATTERN = /^[a-z][a-z0-9+.-]{1,31}:[^\s\\]{1,1024}$/u;
66
+ const MAX_CELLS = 64;
67
+ const MAX_REASON_CODES = 8;
68
+ const MAX_CANONICAL_DEPTH = 32;
69
+ const MAX_CANONICAL_NODES = 100_000;
70
+ const MAX_CANONICAL_BYTES = 16 * 1024 * 1024;
71
+ const MAX_STRING_CHARS = 1_048_576;
72
+ const MAX_SIGNATURE_CHARS = 16_384;
73
+ const MAX_PLAN_TTL_MS = 24 * 60 * 60 * 1000;
74
+ const MAX_RECEIPT_TTL_MS = 60 * 60 * 1000;
75
+ const CLOCK_SKEW_MS = 5_000;
76
+
77
+ const NATIVE_SET_TIMEOUT = globalThis.setTimeout.bind(globalThis);
78
+ const NATIVE_CLEAR_TIMEOUT = globalThis.clearTimeout.bind(globalThis);
79
+ const NATIVE_PROMISE = globalThis.Promise;
80
+ const NATIVE_PROMISE_RACE = NATIVE_PROMISE.race.bind(NATIVE_PROMISE);
81
+ const NATIVE_PROMISE_THEN = NATIVE_PROMISE.prototype.then;
82
+ const NATIVE_MONOTONIC_NOW = globalThis.performance.now.bind(
83
+ globalThis.performance,
84
+ );
85
+
86
+ const PLAN_INPUT_KEYS = new Set([
87
+ "matrixEvalId",
88
+ "nonce",
89
+ "tenantId",
90
+ "skillName",
91
+ "candidateId",
92
+ "candidateContentDigest",
93
+ "baselineId",
94
+ "baselineReleaseDigest",
95
+ "expectedActiveContentDigest",
96
+ "expectedActiveRevision",
97
+ "dependencyLockDigest",
98
+ "runtimeManifestDigest",
99
+ "targetMatrixRoot",
100
+ "matrixAuthorityRoot",
101
+ "maxTotalWallClockMs",
102
+ "aggregateReceiptTtlMs",
103
+ "issuedAt",
104
+ "expiresAt",
105
+ "cells",
106
+ ]);
107
+ const PLAN_KEYS = new Set(["schema", ...PLAN_INPUT_KEYS, "planDigest"]);
108
+ const PLAN_CELL_KEYS = new Set([
109
+ "cellId",
110
+ "invocationId",
111
+ "invocationNonce",
112
+ "runtimeId",
113
+ "targetEnvironmentRef",
114
+ "environmentDigest",
115
+ "suiteRef",
116
+ "suiteDigest",
117
+ "policyDigest",
118
+ "evaluationAuthorityRoot",
119
+ "provenanceAudience",
120
+ "trainerAuthority",
121
+ "trainerRevision",
122
+ "maximumCellSettlementMs",
123
+ ]);
124
+ const PLAN_REF_KEYS = new Set(["ref", "digest"]);
125
+ const TRUST_KEYS = new Set([
126
+ "algorithm",
127
+ "issuer",
128
+ "keyId",
129
+ "trustPolicyDigest",
130
+ ]);
131
+ const ATTESTATION_KEYS = new Set([...TRUST_KEYS, "value"]);
132
+ const POLICY_KEYS = new Set(["trust", "revision"]);
133
+ const AUTHORITY_DESCRIPTOR_KEYS = new Set([
134
+ "schema",
135
+ "handlerId",
136
+ "handlerRevision",
137
+ "operation",
138
+ "handlerArtifactDigest",
139
+ "authority",
140
+ ]);
141
+ const PLAN_RESOLVER_KEYS = new Set(["resolve", "authorityDescriptor"]);
142
+ const VERIFY_PORT_KEYS = new Set(["verify", "authorityDescriptor"]);
143
+ const SIGN_PORT_KEYS = new Set(["sign", "authorityDescriptor"]);
144
+ const CLOCK_PORT_KEYS = new Set(["now", "authorityDescriptor"]);
145
+ const SUPERVISOR_PORT_KEYS = new Set(["run", "authorityDescriptor"]);
146
+ const RESERVATION_PORT_KEYS = new Set([
147
+ "reserve",
148
+ "finalize",
149
+ "reservationDescriptor",
150
+ "finalizationDescriptor",
151
+ ]);
152
+ const AGGREGATOR_OPTION_KEYS = new Set([
153
+ "tenantId",
154
+ "dependencyLock",
155
+ "runtimeManifest",
156
+ "targetMatrix",
157
+ "expectedEnvironmentBindings",
158
+ "expectedTargetMatrixRoot",
159
+ "cellRuntimes",
160
+ "planResolver",
161
+ "planResolverPolicy",
162
+ "planTrust",
163
+ "evidenceVerifier",
164
+ "evidenceVerifierPolicy",
165
+ "reservationAuthority",
166
+ "reservationPolicy",
167
+ "matrixSupervisor",
168
+ "supervisorPolicy",
169
+ "matrixReceiptSigner",
170
+ "matrixReceiptVerifier",
171
+ "matrixReceiptTrust",
172
+ "clock",
173
+ "clockPolicy",
174
+ "maximumMatrixWallClockMs",
175
+ ]);
176
+ const CELL_RUNTIME_KEYS = new Set([
177
+ "gate",
178
+ "receiptVerifier",
179
+ "suiteRef",
180
+ "suiteDigest",
181
+ "policyDigest",
182
+ "evaluationAuthorityRoot",
183
+ "provenanceAudience",
184
+ "trainerAuthority",
185
+ "trainerRevision",
186
+ "maximumCellSettlementMs",
187
+ "gateDescriptor",
188
+ "receiptVerifierDescriptor",
189
+ ]);
190
+ const PLAN_RESOLUTION_KEYS = new Set([
191
+ "schema",
192
+ "requestDigest",
193
+ "planRef",
194
+ "plan",
195
+ "planAttestation",
196
+ "resolverRevision",
197
+ "resolvedAt",
198
+ ]);
199
+ const RESERVATION_KEYS = new Set([
200
+ "schema",
201
+ "tenantId",
202
+ "matrixEvalId",
203
+ "planDigest",
204
+ "planNonce",
205
+ "matrixAuthorityRoot",
206
+ "requestDigest",
207
+ "reservationId",
208
+ "reservedAt",
209
+ "expiresAt",
210
+ "authorityRevision",
211
+ "attestation",
212
+ "receiptDigest",
213
+ ]);
214
+ const FINALIZATION_KEYS = new Set([
215
+ "schema",
216
+ "tenantId",
217
+ "matrixEvalId",
218
+ "planDigest",
219
+ "reservationId",
220
+ "reservationReceiptDigest",
221
+ "decisionCommitmentDigest",
222
+ "requestDigest",
223
+ "finalizedAt",
224
+ "authorityRevision",
225
+ "attestation",
226
+ "receiptDigest",
227
+ ]);
228
+ const CELL_RESULT_KEYS = new Set([
229
+ ...PLAN_CELL_KEYS,
230
+ "runId",
231
+ "runNonce",
232
+ "evaluationContextDigest",
233
+ "childReceiptDigest",
234
+ "childFullDigest",
235
+ "decision",
236
+ "reasonCodes",
237
+ "issuedAt",
238
+ "expiresAt",
239
+ ]);
240
+ const RECEIPT_KEYS = new Set([
241
+ "schema",
242
+ "matrixEvalId",
243
+ "nonce",
244
+ "tenantId",
245
+ "skillName",
246
+ "candidateId",
247
+ "candidateContentDigest",
248
+ "baselineId",
249
+ "baselineReleaseDigest",
250
+ "expectedActiveContentDigest",
251
+ "expectedActiveRevision",
252
+ "dependencyLockDigest",
253
+ "runtimeManifestDigest",
254
+ "targetMatrixRoot",
255
+ "matrixAuthorityRoot",
256
+ "planDigest",
257
+ "planIssuedAt",
258
+ "planExpiresAt",
259
+ "aggregateReceiptTtlMs",
260
+ "planAuthentication",
261
+ "reservation",
262
+ "finalization",
263
+ "cellCount",
264
+ "cellResults",
265
+ "childReceiptRoot",
266
+ "decisionCommitmentDigest",
267
+ "decision",
268
+ "reasonCodes",
269
+ "issuedAt",
270
+ "expiresAt",
271
+ "receiptDigest",
272
+ "attestation",
273
+ ]);
274
+ const PLAN_AUTH_KEYS = new Set([
275
+ "planRef",
276
+ "resolverDescriptorDigest",
277
+ "verifierDescriptorDigest",
278
+ "planAttestation",
279
+ "verifiedAt",
280
+ "evidenceDigest",
281
+ ]);
282
+ const EXPECTED_RECEIPT_KEYS = new Set([
283
+ "matrixEvalId",
284
+ "tenantId",
285
+ "skillName",
286
+ "candidateId",
287
+ "candidateContentDigest",
288
+ "baselineId",
289
+ "baselineReleaseDigest",
290
+ "expectedActiveContentDigest",
291
+ "expectedActiveRevision",
292
+ "dependencyLockDigest",
293
+ "runtimeManifestDigest",
294
+ "targetMatrixRoot",
295
+ "matrixAuthorityRoot",
296
+ "planDigest",
297
+ "decision",
298
+ ]);
299
+ const RECEIPT_VERIFIER_OPTION_KEYS = new Set([
300
+ "matrixReceiptVerifier",
301
+ "matrixReceiptSignerDescriptor",
302
+ "matrixReceiptTrust",
303
+ "matrixSupervisor",
304
+ "supervisorPolicy",
305
+ "clock",
306
+ "clockPolicy",
307
+ "maximumReceiptTtlMs",
308
+ "maximumVerificationMs",
309
+ ]);
310
+ const AUTHORITY_ROOT_INPUT_KEYS = new Set([
311
+ "planResolverDescriptor",
312
+ "evidenceVerifierDescriptor",
313
+ "reservationDescriptor",
314
+ "finalizationDescriptor",
315
+ "supervisorDescriptor",
316
+ "matrixSignerDescriptor",
317
+ "matrixVerifierDescriptor",
318
+ "clockDescriptor",
319
+ "planTrust",
320
+ "matrixReceiptTrust",
321
+ "cellAuthorities",
322
+ ]);
323
+ const CELL_AUTHORITY_KEYS = new Set([
324
+ "cellId",
325
+ "gateDescriptor",
326
+ "receiptVerifierDescriptor",
327
+ "policyDigest",
328
+ "evaluationAuthorityRoot",
329
+ "maximumCellSettlementMs",
330
+ ]);
331
+
332
+ const AGGREGATOR_INSTANCES = new WeakSet();
333
+ const RECEIPT_VERIFIER_INSTANCES = new WeakSet();
334
+
335
+ export class SkillTargetMatrixEvalError extends Error {
336
+ constructor(code, message, details = {}) {
337
+ super(message, details.cause ? { cause: details.cause } : undefined);
338
+ this.name = "SkillTargetMatrixEvalError";
339
+ this.code = code;
340
+ for (const [key, value] of Object.entries(details)) {
341
+ if (key !== "cause") this[key] = value;
342
+ }
343
+ }
344
+ }
345
+
346
+ function matrixError(code, message, details = {}) {
347
+ return new SkillTargetMatrixEvalError(code, message, details);
348
+ }
349
+
350
+ function rejectProxy(value, label) {
351
+ if (
352
+ value !== null &&
353
+ (typeof value === "object" || typeof value === "function") &&
354
+ utilTypes.isProxy(value)
355
+ ) {
356
+ throw matrixError(
357
+ SKILL_TARGET_MATRIX_EVAL_INVALID_CODE,
358
+ `${label} must not be a Proxy`,
359
+ );
360
+ }
361
+ }
362
+
363
+ function assertExactRecord(value, keys, label) {
364
+ rejectProxy(value, label);
365
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
366
+ throw matrixError(
367
+ SKILL_TARGET_MATRIX_EVAL_INVALID_CODE,
368
+ `${label} must be a plain object`,
369
+ );
370
+ }
371
+ const prototype = Object.getPrototypeOf(value);
372
+ if (prototype !== Object.prototype && prototype !== null) {
373
+ throw matrixError(
374
+ SKILL_TARGET_MATRIX_EVAL_INVALID_CODE,
375
+ `${label} must be a plain object`,
376
+ );
377
+ }
378
+ const ownKeys = Reflect.ownKeys(value);
379
+ if (
380
+ ownKeys.length !== keys.size ||
381
+ ownKeys.some((key) => typeof key !== "string" || !keys.has(key))
382
+ ) {
383
+ throw matrixError(
384
+ SKILL_TARGET_MATRIX_EVAL_INVALID_CODE,
385
+ `${label} must contain exactly the supported fields`,
386
+ );
387
+ }
388
+ for (const key of ownKeys) {
389
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
390
+ if (!descriptor || !("value" in descriptor) || !descriptor.enumerable) {
391
+ throw matrixError(
392
+ SKILL_TARGET_MATRIX_EVAL_INVALID_CODE,
393
+ `${label}.${String(key)} must be an enumerable own data property`,
394
+ );
395
+ }
396
+ }
397
+ }
398
+
399
+ function ownData(value, key, label) {
400
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
401
+ if (!descriptor || !("value" in descriptor) || !descriptor.enumerable) {
402
+ throw matrixError(
403
+ SKILL_TARGET_MATRIX_EVAL_INVALID_CODE,
404
+ `${label}.${key} must be an enumerable own data property`,
405
+ );
406
+ }
407
+ return descriptor.value;
408
+ }
409
+
410
+ function assertDenseStandardArray(value, label, { minimum = 0, maximum }) {
411
+ rejectProxy(value, label);
412
+ if (
413
+ !Array.isArray(value) ||
414
+ Object.getPrototypeOf(value) !== Array.prototype
415
+ ) {
416
+ throw matrixError(
417
+ SKILL_TARGET_MATRIX_EVAL_INVALID_CODE,
418
+ `${label} must be a standard array`,
419
+ );
420
+ }
421
+ const lengthDescriptor = Object.getOwnPropertyDescriptor(value, "length");
422
+ const length = lengthDescriptor?.value;
423
+ if (!Number.isSafeInteger(length) || length < minimum || length > maximum) {
424
+ throw matrixError(
425
+ SKILL_TARGET_MATRIX_EVAL_INVALID_CODE,
426
+ `${label} length is invalid`,
427
+ );
428
+ }
429
+ const keys = Reflect.ownKeys(value);
430
+ if (
431
+ keys.length !== length + 1 ||
432
+ keys.some(
433
+ (key) =>
434
+ typeof key !== "string" ||
435
+ (key !== "length" && !/^(?:0|[1-9]\d*)$/u.test(key)),
436
+ )
437
+ ) {
438
+ throw matrixError(
439
+ SKILL_TARGET_MATRIX_EVAL_INVALID_CODE,
440
+ `${label} must be dense and contain no extra fields`,
441
+ );
442
+ }
443
+ const output = [];
444
+ for (let index = 0; index < length; index += 1) {
445
+ const descriptor = Object.getOwnPropertyDescriptor(value, String(index));
446
+ if (!descriptor || !("value" in descriptor) || !descriptor.enumerable) {
447
+ throw matrixError(
448
+ SKILL_TARGET_MATRIX_EVAL_INVALID_CODE,
449
+ `${label}[${index}] must be an enumerable own data property`,
450
+ );
451
+ }
452
+ output.push(descriptor.value);
453
+ }
454
+ return output;
455
+ }
456
+
457
+ function normalizeId(value, label, maximum = 256) {
458
+ if (
459
+ typeof value !== "string" ||
460
+ value.length < 1 ||
461
+ value.length > maximum ||
462
+ !SAFE_ID_PATTERN.test(value)
463
+ ) {
464
+ throw matrixError(
465
+ SKILL_TARGET_MATRIX_EVAL_INVALID_CODE,
466
+ `${label} is invalid`,
467
+ );
468
+ }
469
+ return value;
470
+ }
471
+
472
+ function normalizeDigest(value, label) {
473
+ if (typeof value !== "string" || !DIGEST_PATTERN.test(value)) {
474
+ throw matrixError(
475
+ SKILL_TARGET_MATRIX_EVAL_INVALID_CODE,
476
+ `${label} must be a lowercase SHA-256 digest`,
477
+ );
478
+ }
479
+ return value;
480
+ }
481
+
482
+ function normalizeNullableDigest(value, label) {
483
+ return value === null ? null : normalizeDigest(value, label);
484
+ }
485
+
486
+ function normalizeInteger(value, label, { minimum = 0, maximum } = {}) {
487
+ const upper = maximum ?? Number.MAX_SAFE_INTEGER;
488
+ if (!Number.isSafeInteger(value) || value < minimum || value > upper) {
489
+ throw matrixError(
490
+ SKILL_TARGET_MATRIX_EVAL_INVALID_CODE,
491
+ `${label} must be an integer in range`,
492
+ );
493
+ }
494
+ return value;
495
+ }
496
+
497
+ function normalizeTimestamp(value, label) {
498
+ if (typeof value !== "string" || value.length > 64) {
499
+ throw matrixError(
500
+ SKILL_TARGET_MATRIX_EVAL_INVALID_CODE,
501
+ `${label} must be canonical ISO-8601`,
502
+ );
503
+ }
504
+ const milliseconds = new Date(value).getTime();
505
+ if (
506
+ !Number.isFinite(milliseconds) ||
507
+ new Date(milliseconds).toISOString() !== value
508
+ ) {
509
+ throw matrixError(
510
+ SKILL_TARGET_MATRIX_EVAL_INVALID_CODE,
511
+ `${label} must be canonical ISO-8601`,
512
+ );
513
+ }
514
+ return { timestamp: value, milliseconds };
515
+ }
516
+
517
+ function deepFreeze(value, seen = new WeakSet()) {
518
+ if (!value || typeof value !== "object" || seen.has(value)) return value;
519
+ seen.add(value);
520
+ for (const key of Reflect.ownKeys(value)) {
521
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
522
+ if (descriptor && "value" in descriptor) deepFreeze(descriptor.value, seen);
523
+ }
524
+ return Object.freeze(value);
525
+ }
526
+
527
+ function canonicalClone(value, label = "canonical value") {
528
+ const state = {
529
+ nodes: 0,
530
+ bytes: 0,
531
+ ancestors: new WeakSet(),
532
+ };
533
+ const addBytes = (fragment) => {
534
+ const bytes = Buffer.byteLength(fragment, "utf8");
535
+ if (state.bytes > MAX_CANONICAL_BYTES - bytes) {
536
+ throw matrixError(
537
+ SKILL_TARGET_MATRIX_EVAL_INVALID_CODE,
538
+ `${label} exceeds the canonical byte limit`,
539
+ );
540
+ }
541
+ state.bytes += bytes;
542
+ };
543
+ const visit = (current, path, depth) => {
544
+ state.nodes += 1;
545
+ if (state.nodes > MAX_CANONICAL_NODES || depth > MAX_CANONICAL_DEPTH) {
546
+ throw matrixError(
547
+ SKILL_TARGET_MATRIX_EVAL_INVALID_CODE,
548
+ `${label} exceeds the canonical structure limit`,
549
+ );
550
+ }
551
+ if (current === null || typeof current !== "object") {
552
+ if (
553
+ typeof current === "function" ||
554
+ typeof current === "symbol" ||
555
+ typeof current === "bigint" ||
556
+ current === undefined ||
557
+ (typeof current === "number" && !Number.isFinite(current))
558
+ ) {
559
+ throw matrixError(
560
+ SKILL_TARGET_MATRIX_EVAL_INVALID_CODE,
561
+ `${path} is not canonical JSON`,
562
+ );
563
+ }
564
+ if (typeof current === "string" && current.length > MAX_STRING_CHARS) {
565
+ throw matrixError(
566
+ SKILL_TARGET_MATRIX_EVAL_INVALID_CODE,
567
+ `${path} exceeds the string limit`,
568
+ );
569
+ }
570
+ const serialized = JSON.stringify(current);
571
+ addBytes(serialized);
572
+ return current;
573
+ }
574
+ rejectProxy(current, path);
575
+ if (state.ancestors.has(current)) {
576
+ throw matrixError(
577
+ SKILL_TARGET_MATRIX_EVAL_INVALID_CODE,
578
+ `${path} must not be cyclic`,
579
+ );
580
+ }
581
+ state.ancestors.add(current);
582
+ try {
583
+ if (Array.isArray(current)) {
584
+ const items = assertDenseStandardArray(current, path, {
585
+ minimum: 0,
586
+ maximum: MAX_CANONICAL_NODES,
587
+ });
588
+ addBytes("[");
589
+ const output = [];
590
+ for (let index = 0; index < items.length; index += 1) {
591
+ if (index > 0) addBytes(",");
592
+ output.push(visit(items[index], `${path}[${index}]`, depth + 1));
593
+ }
594
+ addBytes("]");
595
+ return output;
596
+ }
597
+ const prototype = Object.getPrototypeOf(current);
598
+ if (prototype !== Object.prototype && prototype !== null) {
599
+ throw matrixError(
600
+ SKILL_TARGET_MATRIX_EVAL_INVALID_CODE,
601
+ `${path} must contain only plain objects`,
602
+ );
603
+ }
604
+ const keys = Reflect.ownKeys(current);
605
+ if (keys.some((key) => typeof key !== "string")) {
606
+ throw matrixError(
607
+ SKILL_TARGET_MATRIX_EVAL_INVALID_CODE,
608
+ `${path} contains unsafe keys`,
609
+ );
610
+ }
611
+ keys.sort();
612
+ addBytes("{");
613
+ const output = Object.create(null);
614
+ for (let index = 0; index < keys.length; index += 1) {
615
+ if (index > 0) addBytes(",");
616
+ const key = keys[index];
617
+ const descriptor = Object.getOwnPropertyDescriptor(current, key);
618
+ if (!descriptor || !("value" in descriptor) || !descriptor.enumerable) {
619
+ throw matrixError(
620
+ SKILL_TARGET_MATRIX_EVAL_INVALID_CODE,
621
+ `${path}.${key} must be an enumerable own data property`,
622
+ );
623
+ }
624
+ addBytes(JSON.stringify(key));
625
+ addBytes(":");
626
+ Object.defineProperty(output, key, {
627
+ value: visit(descriptor.value, `${path}.${key}`, depth + 1),
628
+ enumerable: true,
629
+ configurable: false,
630
+ writable: false,
631
+ });
632
+ }
633
+ addBytes("}");
634
+ return output;
635
+ } finally {
636
+ state.ancestors.delete(current);
637
+ }
638
+ };
639
+ return deepFreeze(visit(value, label, 0));
640
+ }
641
+
642
+ function canonicalJson(value) {
643
+ if (value === null || typeof value !== "object") return JSON.stringify(value);
644
+ if (Array.isArray(value)) {
645
+ const items = [];
646
+ for (let index = 0; index < value.length; index += 1) {
647
+ items.push(
648
+ canonicalJson(ownData(value, String(index), "canonical array")),
649
+ );
650
+ }
651
+ return `[${items.join(",")}]`;
652
+ }
653
+ const keys = Reflect.ownKeys(value).sort();
654
+ return `{${keys
655
+ .map(
656
+ (key) =>
657
+ `${JSON.stringify(key)}:${canonicalJson(ownData(value, key, "canonical object"))}`,
658
+ )
659
+ .join(",")}}`;
660
+ }
661
+
662
+ function domainDigest(domain, value, label = "digest input") {
663
+ const snapshot = canonicalClone(value, label);
664
+ return `sha256:${createHash("sha256")
665
+ .update(domain, "utf8")
666
+ .update("\0", "utf8")
667
+ .update(canonicalJson(snapshot), "utf8")
668
+ .digest("hex")}`;
669
+ }
670
+
671
+ function sameCanonical(left, right) {
672
+ return canonicalJson(left) === canonicalJson(right);
673
+ }
674
+
675
+ function normalizeTrust(value, label) {
676
+ assertExactRecord(value, TRUST_KEYS, label);
677
+ return deepFreeze({
678
+ algorithm: normalizeId(value.algorithm, `${label}.algorithm`, 64),
679
+ issuer: normalizeId(value.issuer, `${label}.issuer`),
680
+ keyId: normalizeId(value.keyId, `${label}.keyId`),
681
+ trustPolicyDigest: normalizeDigest(
682
+ value.trustPolicyDigest,
683
+ `${label}.trustPolicyDigest`,
684
+ ),
685
+ });
686
+ }
687
+
688
+ function normalizeAttestation(value, label) {
689
+ assertExactRecord(value, ATTESTATION_KEYS, label);
690
+ const trust = normalizeTrust(
691
+ Object.fromEntries([...TRUST_KEYS].map((key) => [key, value[key]])),
692
+ label,
693
+ );
694
+ if (
695
+ typeof value.value !== "string" ||
696
+ value.value.length < 1 ||
697
+ value.value.length > MAX_SIGNATURE_CHARS
698
+ ) {
699
+ throw matrixError(
700
+ SKILL_TARGET_MATRIX_EVAL_INVALID_CODE,
701
+ `${label}.value is invalid`,
702
+ );
703
+ }
704
+ return deepFreeze({ ...trust, value: value.value });
705
+ }
706
+
707
+ function sameTrust(left, right) {
708
+ return [...TRUST_KEYS].every((key) => left[key] === right[key]);
709
+ }
710
+
711
+ function principalFingerprint(trust) {
712
+ return `${trust.algorithm}\0${trust.issuer}\0${trust.keyId}`;
713
+ }
714
+
715
+ function normalizePolicy(value, label) {
716
+ assertExactRecord(value, POLICY_KEYS, label);
717
+ return deepFreeze({
718
+ trust: normalizeTrust(value.trust, `${label}.trust`),
719
+ revision: normalizeId(value.revision, `${label}.revision`),
720
+ });
721
+ }
722
+
723
+ function normalizeDescriptor(value, label, expected = {}) {
724
+ assertExactRecord(value, AUTHORITY_DESCRIPTOR_KEYS, label);
725
+ if (value.schema !== EVOLUTION_EVAL_AUTHORITY_DESCRIPTOR_SCHEMA) {
726
+ throw matrixError(
727
+ SKILL_TARGET_MATRIX_EVAL_INVALID_CODE,
728
+ `${label}.schema is invalid`,
729
+ );
730
+ }
731
+ const normalized = deepFreeze({
732
+ schema: EVOLUTION_EVAL_AUTHORITY_DESCRIPTOR_SCHEMA,
733
+ handlerId: normalizeId(value.handlerId, `${label}.handlerId`),
734
+ handlerRevision: normalizeId(
735
+ value.handlerRevision,
736
+ `${label}.handlerRevision`,
737
+ ),
738
+ operation: normalizeId(value.operation, `${label}.operation`),
739
+ handlerArtifactDigest: normalizeDigest(
740
+ value.handlerArtifactDigest,
741
+ `${label}.handlerArtifactDigest`,
742
+ ),
743
+ authority: normalizeTrust(value.authority, `${label}.authority`),
744
+ });
745
+ if (
746
+ (expected.operation && normalized.operation !== expected.operation) ||
747
+ (expected.policy &&
748
+ (!sameTrust(normalized.authority, expected.policy.trust) ||
749
+ normalized.handlerRevision !== expected.policy.revision))
750
+ ) {
751
+ throw matrixError(
752
+ SKILL_TARGET_MATRIX_EVAL_INVALID_CODE,
753
+ `${label} differs from its exact operation or authority policy`,
754
+ );
755
+ }
756
+ return normalized;
757
+ }
758
+
759
+ function descriptorDigest(value) {
760
+ return domainDigest(
761
+ "chainlesschain.skill-target-matrix-eval-authority-descriptor/v1",
762
+ value,
763
+ "authority descriptor",
764
+ );
765
+ }
766
+
767
+ function readOwnCallable(port, key, label) {
768
+ const callable = ownData(port, key, label);
769
+ if (typeof callable !== "function") {
770
+ throw matrixError(
771
+ SKILL_TARGET_MATRIX_EVAL_INVALID_CODE,
772
+ `${label}.${key} must be callable`,
773
+ );
774
+ }
775
+ return callable;
776
+ }
777
+
778
+ function capturePort(port, keys, method, label, descriptorKey, expected) {
779
+ assertExactRecord(port, keys, label);
780
+ const raw = readOwnCallable(port, method, label);
781
+ const descriptor = normalizeDescriptor(
782
+ ownData(port, descriptorKey, label),
783
+ `${label}.${descriptorKey}`,
784
+ expected,
785
+ );
786
+ const callable = (...args) => Reflect.apply(raw, port, args);
787
+ Object.freeze(callable);
788
+ Object.freeze(port);
789
+ return Object.freeze({ callable, raw, descriptor });
790
+ }
791
+
792
+ function ensureUniqueCallables(entries) {
793
+ for (let left = 0; left < entries.length; left += 1) {
794
+ for (let right = left + 1; right < entries.length; right += 1) {
795
+ if (entries[left].raw === entries[right].raw) {
796
+ throw matrixError(
797
+ SKILL_TARGET_MATRIX_EVAL_INVALID_CODE,
798
+ `${entries[left].role} and ${entries[right].role} must not share a raw callable`,
799
+ );
800
+ }
801
+ }
802
+ }
803
+ }
804
+
805
+ function validatePrincipalMatrix(entries) {
806
+ const priorByFingerprint = new Map();
807
+ for (const entry of entries) {
808
+ const fingerprint = principalFingerprint(entry.trust);
809
+ const prior = priorByFingerprint.get(fingerprint) ?? [];
810
+ for (const existing of prior) {
811
+ const allowedAggregatePair =
812
+ new Set([existing.role, entry.role]).size === 2 &&
813
+ [existing.role, entry.role].includes("matrixSigner") &&
814
+ [existing.role, entry.role].includes("matrixVerifier") &&
815
+ sameTrust(existing.trust, entry.trust);
816
+ if (!allowedAggregatePair) {
817
+ throw matrixError(
818
+ SKILL_TARGET_MATRIX_EVAL_INVALID_CODE,
819
+ `${existing.role} and ${entry.role} must not share a principal/key identity`,
820
+ );
821
+ }
822
+ }
823
+ prior.push(entry);
824
+ priorByFingerprint.set(fingerprint, prior);
825
+ }
826
+ }
827
+
828
+ function normalizeReasonCodes(value, label) {
829
+ const items = assertDenseStandardArray(value, label, {
830
+ minimum: 1,
831
+ maximum: MAX_REASON_CODES,
832
+ });
833
+ return deepFreeze(
834
+ items.map((item, index) => normalizeId(item, `${label}[${index}]`)),
835
+ );
836
+ }
837
+
838
+ function normalizeDecision(value, label = "matrix decision") {
839
+ if (!["accepted", "rejected", "needs-more-evidence"].includes(value)) {
840
+ throw matrixError(
841
+ SKILL_TARGET_MATRIX_EVAL_INVALID_CODE,
842
+ `${label} is invalid`,
843
+ );
844
+ }
845
+ return value;
846
+ }
847
+
848
+ function normalizePlanCell(value, label) {
849
+ assertExactRecord(value, PLAN_CELL_KEYS, label);
850
+ return deepFreeze({
851
+ cellId: normalizeId(value.cellId, `${label}.cellId`),
852
+ invocationId: normalizeId(value.invocationId, `${label}.invocationId`),
853
+ invocationNonce: normalizeId(
854
+ value.invocationNonce,
855
+ `${label}.invocationNonce`,
856
+ ),
857
+ runtimeId: normalizeId(value.runtimeId, `${label}.runtimeId`),
858
+ targetEnvironmentRef: normalizeId(
859
+ value.targetEnvironmentRef,
860
+ `${label}.targetEnvironmentRef`,
861
+ ),
862
+ environmentDigest: normalizeDigest(
863
+ value.environmentDigest,
864
+ `${label}.environmentDigest`,
865
+ ),
866
+ suiteRef: normalizeId(value.suiteRef, `${label}.suiteRef`),
867
+ suiteDigest: normalizeDigest(value.suiteDigest, `${label}.suiteDigest`),
868
+ policyDigest: normalizeDigest(value.policyDigest, `${label}.policyDigest`),
869
+ evaluationAuthorityRoot: normalizeDigest(
870
+ value.evaluationAuthorityRoot,
871
+ `${label}.evaluationAuthorityRoot`,
872
+ ),
873
+ provenanceAudience: normalizeId(
874
+ value.provenanceAudience,
875
+ `${label}.provenanceAudience`,
876
+ ),
877
+ trainerAuthority: normalizeId(
878
+ value.trainerAuthority,
879
+ `${label}.trainerAuthority`,
880
+ ),
881
+ trainerRevision: normalizeId(
882
+ value.trainerRevision,
883
+ `${label}.trainerRevision`,
884
+ ),
885
+ maximumCellSettlementMs: normalizeInteger(
886
+ value.maximumCellSettlementMs,
887
+ `${label}.maximumCellSettlementMs`,
888
+ { minimum: 100, maximum: 600_000 },
889
+ ),
890
+ });
891
+ }
892
+
893
+ function normalizePlanCells(value) {
894
+ const cells = assertDenseStandardArray(
895
+ value,
896
+ "matrix evaluation plan cells",
897
+ {
898
+ minimum: 1,
899
+ maximum: MAX_CELLS,
900
+ },
901
+ ).map((cell, index) =>
902
+ normalizePlanCell(cell, `matrix evaluation plan cells[${index}]`),
903
+ );
904
+ const unique = (key) => {
905
+ const values = cells.map((cell) => cell[key]);
906
+ if (new Set(values).size !== values.length) {
907
+ throw matrixError(
908
+ SKILL_TARGET_MATRIX_EVAL_INVALID_CODE,
909
+ `matrix evaluation plan ${key} values must be unique`,
910
+ );
911
+ }
912
+ };
913
+ unique("cellId");
914
+ unique("invocationId");
915
+ unique("invocationNonce");
916
+ cells.sort((left, right) =>
917
+ left.cellId < right.cellId ? -1 : left.cellId > right.cellId ? 1 : 0,
918
+ );
919
+ return deepFreeze(cells);
920
+ }
921
+
922
+ function planCore(input) {
923
+ assertExactRecord(input, PLAN_INPUT_KEYS, "matrix evaluation plan input");
924
+ const issued = normalizeTimestamp(input.issuedAt, "plan.issuedAt");
925
+ const expires = normalizeTimestamp(input.expiresAt, "plan.expiresAt");
926
+ if (
927
+ expires.milliseconds <= issued.milliseconds ||
928
+ expires.milliseconds - issued.milliseconds > MAX_PLAN_TTL_MS
929
+ ) {
930
+ throw matrixError(
931
+ SKILL_TARGET_MATRIX_EVAL_INVALID_CODE,
932
+ "matrix evaluation plan validity window is invalid",
933
+ );
934
+ }
935
+ return deepFreeze({
936
+ schema: SKILL_TARGET_MATRIX_EVAL_PLAN_SCHEMA,
937
+ matrixEvalId: normalizeId(input.matrixEvalId, "plan.matrixEvalId"),
938
+ nonce: normalizeId(input.nonce, "plan.nonce"),
939
+ tenantId: normalizeId(input.tenantId, "plan.tenantId"),
940
+ skillName: normalizeId(input.skillName, "plan.skillName", 128),
941
+ candidateId: normalizeDigest(input.candidateId, "plan.candidateId"),
942
+ candidateContentDigest: normalizeDigest(
943
+ input.candidateContentDigest,
944
+ "plan.candidateContentDigest",
945
+ ),
946
+ baselineId: normalizeDigest(input.baselineId, "plan.baselineId"),
947
+ baselineReleaseDigest: normalizeNullableDigest(
948
+ input.baselineReleaseDigest,
949
+ "plan.baselineReleaseDigest",
950
+ ),
951
+ expectedActiveContentDigest: normalizeDigest(
952
+ input.expectedActiveContentDigest,
953
+ "plan.expectedActiveContentDigest",
954
+ ),
955
+ expectedActiveRevision: normalizeInteger(
956
+ input.expectedActiveRevision,
957
+ "plan.expectedActiveRevision",
958
+ ),
959
+ dependencyLockDigest: normalizeDigest(
960
+ input.dependencyLockDigest,
961
+ "plan.dependencyLockDigest",
962
+ ),
963
+ runtimeManifestDigest: normalizeDigest(
964
+ input.runtimeManifestDigest,
965
+ "plan.runtimeManifestDigest",
966
+ ),
967
+ targetMatrixRoot: normalizeDigest(
968
+ input.targetMatrixRoot,
969
+ "plan.targetMatrixRoot",
970
+ ),
971
+ matrixAuthorityRoot: normalizeDigest(
972
+ input.matrixAuthorityRoot,
973
+ "plan.matrixAuthorityRoot",
974
+ ),
975
+ maxTotalWallClockMs: normalizeInteger(
976
+ input.maxTotalWallClockMs,
977
+ "plan.maxTotalWallClockMs",
978
+ { minimum: 100, maximum: 3_600_000 },
979
+ ),
980
+ aggregateReceiptTtlMs: normalizeInteger(
981
+ input.aggregateReceiptTtlMs,
982
+ "plan.aggregateReceiptTtlMs",
983
+ { minimum: 1_000, maximum: MAX_RECEIPT_TTL_MS },
984
+ ),
985
+ issuedAt: issued.timestamp,
986
+ expiresAt: expires.timestamp,
987
+ cells: normalizePlanCells(input.cells),
988
+ });
989
+ }
990
+
991
+ export function buildSkillTargetMatrixEvalPlan(input) {
992
+ const core = planCore(input);
993
+ return deepFreeze({
994
+ ...core,
995
+ planDigest: domainDigest(
996
+ SKILL_TARGET_MATRIX_EVAL_PLAN_SCHEMA,
997
+ core,
998
+ "matrix evaluation plan",
999
+ ),
1000
+ });
1001
+ }
1002
+
1003
+ export function verifySkillTargetMatrixEvalPlan(value) {
1004
+ const snapshot = canonicalClone(value, "matrix evaluation plan");
1005
+ assertExactRecord(snapshot, PLAN_KEYS, "matrix evaluation plan");
1006
+ if (snapshot.schema !== SKILL_TARGET_MATRIX_EVAL_PLAN_SCHEMA) {
1007
+ throw matrixError(
1008
+ SKILL_TARGET_MATRIX_EVAL_INVALID_CODE,
1009
+ "matrix evaluation plan schema is invalid",
1010
+ );
1011
+ }
1012
+ const rebuilt = buildSkillTargetMatrixEvalPlan(
1013
+ Object.fromEntries([...PLAN_INPUT_KEYS].map((key) => [key, snapshot[key]])),
1014
+ );
1015
+ if (!sameCanonical(snapshot, rebuilt)) {
1016
+ throw matrixError(
1017
+ SKILL_TARGET_MATRIX_EVAL_INVALID_CODE,
1018
+ "matrix evaluation plan digest or canonical form is invalid",
1019
+ );
1020
+ }
1021
+ return rebuilt;
1022
+ }
1023
+
1024
+ function normalizePlanRef(value) {
1025
+ assertExactRecord(value, PLAN_REF_KEYS, "matrix evaluation planRef");
1026
+ if (typeof value.ref !== "string" || !PLAN_REF_PATTERN.test(value.ref)) {
1027
+ throw matrixError(
1028
+ SKILL_TARGET_MATRIX_EVAL_INVALID_CODE,
1029
+ "matrix evaluation planRef.ref is invalid",
1030
+ );
1031
+ }
1032
+ return deepFreeze({
1033
+ ref: value.ref,
1034
+ digest: normalizeDigest(value.digest, "matrix evaluation planRef.digest"),
1035
+ });
1036
+ }
1037
+
1038
+ function normalizeClockResult(value, label) {
1039
+ rejectProxy(value, label);
1040
+ if (value instanceof Date) {
1041
+ const milliseconds = value.getTime();
1042
+ if (!Number.isFinite(milliseconds)) {
1043
+ throw matrixError(
1044
+ SKILL_TARGET_MATRIX_EVAL_AUTHORITY_FAILED_CODE,
1045
+ `${label} returned an invalid Date`,
1046
+ );
1047
+ }
1048
+ return {
1049
+ timestamp: new Date(milliseconds).toISOString(),
1050
+ milliseconds,
1051
+ };
1052
+ }
1053
+ return normalizeTimestamp(value, label);
1054
+ }
1055
+
1056
+ function remainingMilliseconds(deadlineMs) {
1057
+ return Math.max(0, Math.ceil(deadlineMs - NATIVE_MONOTONIC_NOW()));
1058
+ }
1059
+
1060
+ function assertRootDeadline(deadlineMs, label) {
1061
+ if (NATIVE_MONOTONIC_NOW() >= deadlineMs) {
1062
+ throw matrixError(
1063
+ SKILL_TARGET_MATRIX_EVAL_DEADLINE_CODE,
1064
+ `${label} exceeded the matrix root monotonic deadline`,
1065
+ );
1066
+ }
1067
+ }
1068
+
1069
+ function nativePromiseOrValue(value, label) {
1070
+ if (!value || typeof value !== "object") return { promise: null, value };
1071
+ rejectProxy(value, `${label} result`);
1072
+ if (
1073
+ !(value instanceof NATIVE_PROMISE) ||
1074
+ Object.getPrototypeOf(value) !== NATIVE_PROMISE.prototype ||
1075
+ Reflect.ownKeys(value).length !== 0
1076
+ ) {
1077
+ throw matrixError(
1078
+ SKILL_TARGET_MATRIX_EVAL_AUTHORITY_FAILED_CODE,
1079
+ `${label} returned an untrusted thenable or object in place of a Promise`,
1080
+ );
1081
+ }
1082
+ return { promise: value, value: undefined };
1083
+ }
1084
+
1085
+ async function awaitRootBounded(value, deadlineMs, label, controller) {
1086
+ const normalized = nativePromiseOrValue(value, label);
1087
+ if (!normalized.promise) {
1088
+ assertRootDeadline(deadlineMs, label);
1089
+ return normalized.value;
1090
+ }
1091
+ const remaining = remainingMilliseconds(deadlineMs);
1092
+ if (remaining <= 0) {
1093
+ controller?.abort();
1094
+ assertRootDeadline(deadlineMs, label);
1095
+ }
1096
+ let timer;
1097
+ const timeout = new NATIVE_PROMISE((_, reject) => {
1098
+ timer = NATIVE_SET_TIMEOUT(() => {
1099
+ controller?.abort();
1100
+ reject(
1101
+ matrixError(
1102
+ SKILL_TARGET_MATRIX_EVAL_DEADLINE_CODE,
1103
+ `${label} did not settle before the matrix root deadline`,
1104
+ ),
1105
+ );
1106
+ }, remaining);
1107
+ timer?.unref?.();
1108
+ });
1109
+ try {
1110
+ const result = await NATIVE_PROMISE_RACE([normalized.promise, timeout]);
1111
+ assertRootDeadline(deadlineMs, label);
1112
+ return result;
1113
+ } finally {
1114
+ if (timer) NATIVE_CLEAR_TIMEOUT(timer);
1115
+ }
1116
+ }
1117
+
1118
+ function randomId(prefix) {
1119
+ return `${prefix}-${randomBytes(24).toString("hex")}`;
1120
+ }
1121
+
1122
+ async function invokeSupervised(
1123
+ supervision,
1124
+ label,
1125
+ payload,
1126
+ operation,
1127
+ deadlineMs,
1128
+ wallDeadlineAt,
1129
+ ) {
1130
+ assertRootDeadline(deadlineMs, label);
1131
+ const payloadSnapshot = canonicalClone(payload, `${label} payload`);
1132
+ const request = deepFreeze({
1133
+ operationId: randomId("matrix-operation"),
1134
+ label: normalizeId(label, "supervised operation label"),
1135
+ payloadDigest: domainDigest(
1136
+ "chainlesschain.skill-target-matrix-eval-supervision-payload/v1",
1137
+ payloadSnapshot,
1138
+ `${label} payload`,
1139
+ ),
1140
+ requestedAt: supervision.clock().timestamp,
1141
+ deadlineAt: wallDeadlineAt,
1142
+ });
1143
+ let accepting = true;
1144
+ let invocationCount = 0;
1145
+ let settled = false;
1146
+ let settledSnapshot;
1147
+ const controller = new AbortController();
1148
+ const capability = Object.freeze({
1149
+ invoke: Object.freeze(() => {
1150
+ if (!accepting || invocationCount !== 0) {
1151
+ throw matrixError(
1152
+ SKILL_TARGET_MATRIX_EVAL_AUTHORITY_FAILED_CODE,
1153
+ `${label} supervisor invocation was missing, replayed, or late`,
1154
+ );
1155
+ }
1156
+ invocationCount += 1;
1157
+ let result;
1158
+ try {
1159
+ result = operation(controller.signal);
1160
+ } catch (cause) {
1161
+ settled = true;
1162
+ throw cause;
1163
+ }
1164
+ const normalized = nativePromiseOrValue(result, `${label} operation`);
1165
+ if (!normalized.promise) {
1166
+ settledSnapshot = canonicalClone(
1167
+ normalized.value,
1168
+ `${label} operation result`,
1169
+ );
1170
+ settled = true;
1171
+ return settledSnapshot;
1172
+ }
1173
+ return Reflect.apply(NATIVE_PROMISE_THEN, normalized.promise, [
1174
+ (value) => {
1175
+ settledSnapshot = canonicalClone(value, `${label} operation result`);
1176
+ settled = true;
1177
+ return settledSnapshot;
1178
+ },
1179
+ ]);
1180
+ }),
1181
+ });
1182
+ let proofAccepted = false;
1183
+ try {
1184
+ const response = await awaitRootBounded(
1185
+ supervision.run(request, capability),
1186
+ deadlineMs,
1187
+ `${label} supervisor`,
1188
+ controller,
1189
+ );
1190
+ accepting = false;
1191
+ const responseSnapshot = canonicalClone(response, `${label} response`);
1192
+ assertExactRecord(
1193
+ responseSnapshot,
1194
+ new Set(["operationId", "completed", "valueDigest", "value"]),
1195
+ `${label} supervisor response`,
1196
+ );
1197
+ if (
1198
+ invocationCount !== 1 ||
1199
+ !settled ||
1200
+ responseSnapshot.operationId !== request.operationId ||
1201
+ responseSnapshot.completed !== true
1202
+ ) {
1203
+ throw matrixError(
1204
+ SKILL_TARGET_MATRIX_EVAL_AUTHORITY_FAILED_CODE,
1205
+ `${label} supervisor did not prove one-shot completion`,
1206
+ );
1207
+ }
1208
+ const actualDigest = domainDigest(
1209
+ "chainlesschain.skill-target-matrix-eval-supervised-result/v1",
1210
+ settledSnapshot,
1211
+ `${label} settled result`,
1212
+ );
1213
+ if (
1214
+ responseSnapshot.valueDigest !== actualDigest ||
1215
+ !sameCanonical(responseSnapshot.value, settledSnapshot)
1216
+ ) {
1217
+ throw matrixError(
1218
+ SKILL_TARGET_MATRIX_EVAL_AUTHORITY_FAILED_CODE,
1219
+ `${label} supervisor swapped the operation result`,
1220
+ );
1221
+ }
1222
+ assertRootDeadline(deadlineMs, label);
1223
+ proofAccepted = true;
1224
+ return settledSnapshot;
1225
+ } finally {
1226
+ accepting = false;
1227
+ if (!proofAccepted) controller.abort();
1228
+ }
1229
+ }
1230
+
1231
+ function signaturePayload(purpose, payloadDigest, attestation) {
1232
+ return deepFreeze({ purpose, payloadDigest, attestation });
1233
+ }
1234
+
1235
+ async function verifySignature(
1236
+ composition,
1237
+ purpose,
1238
+ payloadDigest,
1239
+ attestation,
1240
+ expectedTrust,
1241
+ deadlineMs,
1242
+ wallDeadlineAt,
1243
+ label,
1244
+ ) {
1245
+ const normalized = normalizeAttestation(attestation, `${label} attestation`);
1246
+ if (!sameTrust(normalized, expectedTrust)) {
1247
+ throw matrixError(
1248
+ SKILL_TARGET_MATRIX_EVAL_AUTHORITY_FAILED_CODE,
1249
+ `${label} signature trust is invalid`,
1250
+ );
1251
+ }
1252
+ const verified = await invokeSupervised(
1253
+ composition.supervision,
1254
+ `${label}-verify`,
1255
+ { purpose, payloadDigest, attestation: normalized },
1256
+ (signal) =>
1257
+ composition.evidenceVerifier.callable(
1258
+ signaturePayload(purpose, payloadDigest, normalized),
1259
+ Object.freeze({ signal }),
1260
+ ),
1261
+ deadlineMs,
1262
+ wallDeadlineAt,
1263
+ );
1264
+ if (verified !== true) {
1265
+ throw matrixError(
1266
+ SKILL_TARGET_MATRIX_EVAL_AUTHORITY_FAILED_CODE,
1267
+ `${label} signature was rejected`,
1268
+ );
1269
+ }
1270
+ return normalized;
1271
+ }
1272
+
1273
+ function normalizeCellAuthorities(value) {
1274
+ const entries = assertDenseStandardArray(value, "matrix cell authorities", {
1275
+ minimum: 1,
1276
+ maximum: MAX_CELLS,
1277
+ }).map((entry, index) => {
1278
+ const label = `matrix cell authorities[${index}]`;
1279
+ assertExactRecord(entry, CELL_AUTHORITY_KEYS, label);
1280
+ return deepFreeze({
1281
+ cellId: normalizeId(entry.cellId, `${label}.cellId`),
1282
+ gateDescriptor: normalizeDescriptor(
1283
+ entry.gateDescriptor,
1284
+ `${label}.gateDescriptor`,
1285
+ ),
1286
+ receiptVerifierDescriptor: normalizeDescriptor(
1287
+ entry.receiptVerifierDescriptor,
1288
+ `${label}.receiptVerifierDescriptor`,
1289
+ ),
1290
+ policyDigest: normalizeDigest(
1291
+ entry.policyDigest,
1292
+ `${label}.policyDigest`,
1293
+ ),
1294
+ evaluationAuthorityRoot: normalizeDigest(
1295
+ entry.evaluationAuthorityRoot,
1296
+ `${label}.evaluationAuthorityRoot`,
1297
+ ),
1298
+ maximumCellSettlementMs: normalizeInteger(
1299
+ entry.maximumCellSettlementMs,
1300
+ `${label}.maximumCellSettlementMs`,
1301
+ { minimum: 100, maximum: 600_000 },
1302
+ ),
1303
+ });
1304
+ });
1305
+ if (new Set(entries.map((entry) => entry.cellId)).size !== entries.length) {
1306
+ throw matrixError(
1307
+ SKILL_TARGET_MATRIX_EVAL_INVALID_CODE,
1308
+ "matrix cell authority cellId values must be unique",
1309
+ );
1310
+ }
1311
+ entries.sort((left, right) =>
1312
+ left.cellId < right.cellId ? -1 : left.cellId > right.cellId ? 1 : 0,
1313
+ );
1314
+ return deepFreeze(entries);
1315
+ }
1316
+
1317
+ export function computeSkillTargetMatrixEvalAuthorityRoot(input) {
1318
+ assertExactRecord(
1319
+ input,
1320
+ AUTHORITY_ROOT_INPUT_KEYS,
1321
+ "matrix authority root input",
1322
+ );
1323
+ const normalized = deepFreeze({
1324
+ semantics: SKILL_TARGET_MATRIX_EVAL_FOUNDATION_SEMANTICS,
1325
+ planResolverDescriptor: normalizeDescriptor(
1326
+ input.planResolverDescriptor,
1327
+ "matrix authority root planResolverDescriptor",
1328
+ ),
1329
+ evidenceVerifierDescriptor: normalizeDescriptor(
1330
+ input.evidenceVerifierDescriptor,
1331
+ "matrix authority root evidenceVerifierDescriptor",
1332
+ ),
1333
+ reservationDescriptor: normalizeDescriptor(
1334
+ input.reservationDescriptor,
1335
+ "matrix authority root reservationDescriptor",
1336
+ ),
1337
+ finalizationDescriptor: normalizeDescriptor(
1338
+ input.finalizationDescriptor,
1339
+ "matrix authority root finalizationDescriptor",
1340
+ ),
1341
+ supervisorDescriptor: normalizeDescriptor(
1342
+ input.supervisorDescriptor,
1343
+ "matrix authority root supervisorDescriptor",
1344
+ ),
1345
+ matrixSignerDescriptor: normalizeDescriptor(
1346
+ input.matrixSignerDescriptor,
1347
+ "matrix authority root matrixSignerDescriptor",
1348
+ ),
1349
+ matrixVerifierDescriptor: normalizeDescriptor(
1350
+ input.matrixVerifierDescriptor,
1351
+ "matrix authority root matrixVerifierDescriptor",
1352
+ ),
1353
+ clockDescriptor: normalizeDescriptor(
1354
+ input.clockDescriptor,
1355
+ "matrix authority root clockDescriptor",
1356
+ ),
1357
+ planTrust: normalizeTrust(
1358
+ input.planTrust,
1359
+ "matrix authority root planTrust",
1360
+ ),
1361
+ matrixReceiptTrust: normalizeTrust(
1362
+ input.matrixReceiptTrust,
1363
+ "matrix authority root matrixReceiptTrust",
1364
+ ),
1365
+ cellAuthorities: normalizeCellAuthorities(input.cellAuthorities),
1366
+ });
1367
+ return domainDigest(
1368
+ "chainlesschain.skill-target-matrix-eval-authority-root/v1",
1369
+ normalized,
1370
+ "matrix authority root",
1371
+ );
1372
+ }
1373
+
1374
+ function captureComposition(options) {
1375
+ const planResolverPolicy = normalizePolicy(
1376
+ options.planResolverPolicy,
1377
+ "planResolverPolicy",
1378
+ );
1379
+ const evidenceVerifierPolicy = normalizePolicy(
1380
+ options.evidenceVerifierPolicy,
1381
+ "evidenceVerifierPolicy",
1382
+ );
1383
+ const reservationPolicy = normalizePolicy(
1384
+ options.reservationPolicy,
1385
+ "reservationPolicy",
1386
+ );
1387
+ const supervisorPolicy = normalizePolicy(
1388
+ options.supervisorPolicy,
1389
+ "supervisorPolicy",
1390
+ );
1391
+ const clockPolicy = normalizePolicy(options.clockPolicy, "clockPolicy");
1392
+ const planResolver = capturePort(
1393
+ options.planResolver,
1394
+ PLAN_RESOLVER_KEYS,
1395
+ "resolve",
1396
+ "planResolver",
1397
+ "authorityDescriptor",
1398
+ { operation: "matrix-plan-resolve", policy: planResolverPolicy },
1399
+ );
1400
+ const evidenceVerifier = capturePort(
1401
+ options.evidenceVerifier,
1402
+ VERIFY_PORT_KEYS,
1403
+ "verify",
1404
+ "evidenceVerifier",
1405
+ "authorityDescriptor",
1406
+ { operation: "matrix-evidence-verify", policy: evidenceVerifierPolicy },
1407
+ );
1408
+ assertExactRecord(
1409
+ options.reservationAuthority,
1410
+ RESERVATION_PORT_KEYS,
1411
+ "reservationAuthority",
1412
+ );
1413
+ const reserveRaw = readOwnCallable(
1414
+ options.reservationAuthority,
1415
+ "reserve",
1416
+ "reservationAuthority",
1417
+ );
1418
+ const finalizeRaw = readOwnCallable(
1419
+ options.reservationAuthority,
1420
+ "finalize",
1421
+ "reservationAuthority",
1422
+ );
1423
+ const reservationDescriptor = normalizeDescriptor(
1424
+ ownData(
1425
+ options.reservationAuthority,
1426
+ "reservationDescriptor",
1427
+ "reservationAuthority",
1428
+ ),
1429
+ "reservationAuthority.reservationDescriptor",
1430
+ { operation: "matrix-plan-reserve", policy: reservationPolicy },
1431
+ );
1432
+ const finalizationDescriptor = normalizeDescriptor(
1433
+ ownData(
1434
+ options.reservationAuthority,
1435
+ "finalizationDescriptor",
1436
+ "reservationAuthority",
1437
+ ),
1438
+ "reservationAuthority.finalizationDescriptor",
1439
+ { operation: "matrix-plan-finalize", policy: reservationPolicy },
1440
+ );
1441
+ const reserve = (...args) =>
1442
+ Reflect.apply(reserveRaw, options.reservationAuthority, args);
1443
+ const finalize = (...args) =>
1444
+ Reflect.apply(finalizeRaw, options.reservationAuthority, args);
1445
+ Object.freeze(reserve);
1446
+ Object.freeze(finalize);
1447
+ Object.freeze(options.reservationAuthority);
1448
+ const supervisor = capturePort(
1449
+ options.matrixSupervisor,
1450
+ SUPERVISOR_PORT_KEYS,
1451
+ "run",
1452
+ "matrixSupervisor",
1453
+ "authorityDescriptor",
1454
+ { operation: "matrix-operation-supervise", policy: supervisorPolicy },
1455
+ );
1456
+ const signer = capturePort(
1457
+ options.matrixReceiptSigner,
1458
+ SIGN_PORT_KEYS,
1459
+ "sign",
1460
+ "matrixReceiptSigner",
1461
+ "authorityDescriptor",
1462
+ { operation: "matrix-receipt-sign" },
1463
+ );
1464
+ const verifier = capturePort(
1465
+ options.matrixReceiptVerifier,
1466
+ VERIFY_PORT_KEYS,
1467
+ "verify",
1468
+ "matrixReceiptVerifier",
1469
+ "authorityDescriptor",
1470
+ { operation: "matrix-receipt-verify" },
1471
+ );
1472
+ const receiptTrust = normalizeTrust(
1473
+ options.matrixReceiptTrust,
1474
+ "matrixReceiptTrust",
1475
+ );
1476
+ if (
1477
+ !sameTrust(signer.descriptor.authority, receiptTrust) ||
1478
+ !sameTrust(verifier.descriptor.authority, receiptTrust)
1479
+ ) {
1480
+ throw matrixError(
1481
+ SKILL_TARGET_MATRIX_EVAL_INVALID_CODE,
1482
+ "matrix signer and verifier must be the exact receipt trust pair",
1483
+ );
1484
+ }
1485
+ const clockPort = capturePort(
1486
+ options.clock,
1487
+ CLOCK_PORT_KEYS,
1488
+ "now",
1489
+ "trustedClock",
1490
+ "authorityDescriptor",
1491
+ { operation: "trusted-time-read", policy: clockPolicy },
1492
+ );
1493
+ const clock = () => clockPort.callable();
1494
+ const supervisionClock = () => normalizeClockResult(clock(), "trusted clock");
1495
+ Object.freeze(clock);
1496
+ Object.freeze(supervisionClock);
1497
+ ensureUniqueCallables([
1498
+ { role: "planResolver.resolve", raw: planResolver.raw },
1499
+ { role: "evidenceVerifier.verify", raw: evidenceVerifier.raw },
1500
+ { role: "reservationAuthority.reserve", raw: reserveRaw },
1501
+ { role: "reservationAuthority.finalize", raw: finalizeRaw },
1502
+ { role: "matrixSupervisor.run", raw: supervisor.raw },
1503
+ { role: "matrixReceiptSigner.sign", raw: signer.raw },
1504
+ { role: "matrixReceiptVerifier.verify", raw: verifier.raw },
1505
+ { role: "trustedClock.now", raw: clockPort.raw },
1506
+ ]);
1507
+ return Object.freeze({
1508
+ planResolver,
1509
+ planResolverPolicy,
1510
+ planTrust: normalizeTrust(options.planTrust, "planTrust"),
1511
+ evidenceVerifier,
1512
+ evidenceVerifierPolicy,
1513
+ reservation: Object.freeze({
1514
+ reserve,
1515
+ finalize,
1516
+ reserveRaw,
1517
+ finalizeRaw,
1518
+ reservationDescriptor,
1519
+ finalizationDescriptor,
1520
+ policy: reservationPolicy,
1521
+ }),
1522
+ supervision: Object.freeze({
1523
+ run: supervisor.callable,
1524
+ descriptor: supervisor.descriptor,
1525
+ policy: supervisorPolicy,
1526
+ clock: supervisionClock,
1527
+ }),
1528
+ signer,
1529
+ verifier,
1530
+ receiptTrust,
1531
+ clock,
1532
+ clockDescriptor: clockPort.descriptor,
1533
+ clockPolicy,
1534
+ });
1535
+ }
1536
+
1537
+ function captureCellRuntimes(value) {
1538
+ rejectProxy(value, "cellRuntimes");
1539
+ if (
1540
+ !(value instanceof Map) ||
1541
+ Object.getPrototypeOf(value) !== Map.prototype
1542
+ ) {
1543
+ throw matrixError(
1544
+ SKILL_TARGET_MATRIX_EVAL_INVALID_CODE,
1545
+ "cellRuntimes must be a standard Map",
1546
+ );
1547
+ }
1548
+ if (value.size < 1 || value.size > MAX_CELLS) {
1549
+ throw matrixError(
1550
+ SKILL_TARGET_MATRIX_EVAL_INVALID_CODE,
1551
+ "cellRuntimes size is invalid",
1552
+ );
1553
+ }
1554
+ const captured = new Map();
1555
+ const authorities = [];
1556
+ for (const [rawCellId, rawConfig] of Map.prototype.entries.call(value)) {
1557
+ const cellId = normalizeId(rawCellId, "cellRuntimes cellId");
1558
+ const label = `cellRuntimes.${cellId}`;
1559
+ assertExactRecord(rawConfig, CELL_RUNTIME_KEYS, label);
1560
+ const gate = ownData(rawConfig, "gate", label);
1561
+ const receiptVerifier = ownData(rawConfig, "receiptVerifier", label);
1562
+ rejectProxy(gate, `${label}.gate`);
1563
+ rejectProxy(receiptVerifier, `${label}.receiptVerifier`);
1564
+ if (!(gate instanceof EvolutionEvalGate)) {
1565
+ throw matrixError(
1566
+ SKILL_TARGET_MATRIX_EVAL_INVALID_CODE,
1567
+ `${label}.gate must be a branded EvolutionEvalGate`,
1568
+ );
1569
+ }
1570
+ if (!(receiptVerifier instanceof EvolutionEvalReceiptVerifier)) {
1571
+ throw matrixError(
1572
+ SKILL_TARGET_MATRIX_EVAL_INVALID_CODE,
1573
+ `${label}.receiptVerifier must be a branded EvolutionEvalReceiptVerifier`,
1574
+ );
1575
+ }
1576
+ const gateDescriptor = normalizeDescriptor(
1577
+ ownData(rawConfig, "gateDescriptor", label),
1578
+ `${label}.gateDescriptor`,
1579
+ { operation: "cell-eval-run" },
1580
+ );
1581
+ const receiptVerifierDescriptor = normalizeDescriptor(
1582
+ ownData(rawConfig, "receiptVerifierDescriptor", label),
1583
+ `${label}.receiptVerifierDescriptor`,
1584
+ { operation: "cell-eval-receipt-verify" },
1585
+ );
1586
+ const config = Object.freeze({
1587
+ gate,
1588
+ receiptVerifier,
1589
+ suiteRef: normalizeId(rawConfig.suiteRef, `${label}.suiteRef`),
1590
+ suiteDigest: normalizeDigest(
1591
+ rawConfig.suiteDigest,
1592
+ `${label}.suiteDigest`,
1593
+ ),
1594
+ policyDigest: normalizeDigest(
1595
+ rawConfig.policyDigest,
1596
+ `${label}.policyDigest`,
1597
+ ),
1598
+ evaluationAuthorityRoot: normalizeDigest(
1599
+ rawConfig.evaluationAuthorityRoot,
1600
+ `${label}.evaluationAuthorityRoot`,
1601
+ ),
1602
+ provenanceAudience: normalizeId(
1603
+ rawConfig.provenanceAudience,
1604
+ `${label}.provenanceAudience`,
1605
+ ),
1606
+ trainerAuthority: normalizeId(
1607
+ rawConfig.trainerAuthority,
1608
+ `${label}.trainerAuthority`,
1609
+ ),
1610
+ trainerRevision: normalizeId(
1611
+ rawConfig.trainerRevision,
1612
+ `${label}.trainerRevision`,
1613
+ ),
1614
+ maximumCellSettlementMs: normalizeInteger(
1615
+ rawConfig.maximumCellSettlementMs,
1616
+ `${label}.maximumCellSettlementMs`,
1617
+ { minimum: 100, maximum: 600_000 },
1618
+ ),
1619
+ gateDescriptor,
1620
+ receiptVerifierDescriptor,
1621
+ });
1622
+ if (captured.has(cellId)) {
1623
+ throw matrixError(
1624
+ SKILL_TARGET_MATRIX_EVAL_INVALID_CODE,
1625
+ `duplicate cell runtime: ${cellId}`,
1626
+ );
1627
+ }
1628
+ captured.set(cellId, config);
1629
+ authorities.push({
1630
+ cellId,
1631
+ gateDescriptor,
1632
+ receiptVerifierDescriptor,
1633
+ policyDigest: config.policyDigest,
1634
+ evaluationAuthorityRoot: config.evaluationAuthorityRoot,
1635
+ maximumCellSettlementMs: config.maximumCellSettlementMs,
1636
+ });
1637
+ }
1638
+ return Object.freeze({ runtimes: captured, authorities });
1639
+ }
1640
+
1641
+ function assertPlanMatchesComposition(plan, state) {
1642
+ if (
1643
+ plan.tenantId !== state.tenantId ||
1644
+ plan.dependencyLockDigest !== state.dependencyLock.dependencyLockDigest ||
1645
+ plan.runtimeManifestDigest !==
1646
+ state.runtimeManifest.runtimeManifestDigest ||
1647
+ plan.targetMatrixRoot !== state.targetMatrix.targetMatrixRoot ||
1648
+ plan.matrixAuthorityRoot !== state.matrixAuthorityRoot ||
1649
+ plan.maxTotalWallClockMs > state.maximumMatrixWallClockMs ||
1650
+ plan.cells.length !== state.targetMatrix.cells.length
1651
+ ) {
1652
+ throw matrixError(
1653
+ SKILL_TARGET_MATRIX_EVAL_AUTHORITY_FAILED_CODE,
1654
+ "signed matrix plan differs from the captured tenant, manifests, matrix, authority root, or budget",
1655
+ );
1656
+ }
1657
+ for (let index = 0; index < plan.cells.length; index += 1) {
1658
+ const planCell = plan.cells[index];
1659
+ const matrixCell = state.targetMatrix.cells[index];
1660
+ const runtime = state.cellRuntimes.get(planCell.cellId);
1661
+ if (
1662
+ !runtime ||
1663
+ planCell.cellId !== matrixCell.cellId ||
1664
+ planCell.runtimeId !== matrixCell.runtimeId ||
1665
+ planCell.targetEnvironmentRef !== matrixCell.targetEnvironmentRef ||
1666
+ planCell.environmentDigest !== matrixCell.environmentDigest ||
1667
+ planCell.suiteRef !== runtime.suiteRef ||
1668
+ planCell.suiteDigest !== runtime.suiteDigest ||
1669
+ planCell.policyDigest !== runtime.policyDigest ||
1670
+ planCell.evaluationAuthorityRoot !== runtime.evaluationAuthorityRoot ||
1671
+ planCell.provenanceAudience !== runtime.provenanceAudience ||
1672
+ planCell.trainerAuthority !== runtime.trainerAuthority ||
1673
+ planCell.trainerRevision !== runtime.trainerRevision ||
1674
+ planCell.maximumCellSettlementMs !== runtime.maximumCellSettlementMs
1675
+ ) {
1676
+ throw matrixError(
1677
+ SKILL_TARGET_MATRIX_EVAL_AUTHORITY_FAILED_CODE,
1678
+ `signed matrix plan cell differs from captured composition: ${planCell.cellId}`,
1679
+ );
1680
+ }
1681
+ }
1682
+ }
1683
+
1684
+ function reservationCore(snapshot) {
1685
+ return deepFreeze(
1686
+ Object.fromEntries(
1687
+ [...RESERVATION_KEYS]
1688
+ .filter((key) => key !== "attestation" && key !== "receiptDigest")
1689
+ .map((key) => [key, snapshot[key]]),
1690
+ ),
1691
+ );
1692
+ }
1693
+
1694
+ function finalizationCore(snapshot) {
1695
+ return deepFreeze(
1696
+ Object.fromEntries(
1697
+ [...FINALIZATION_KEYS]
1698
+ .filter((key) => key !== "attestation" && key !== "receiptDigest")
1699
+ .map((key) => [key, snapshot[key]]),
1700
+ ),
1701
+ );
1702
+ }
1703
+
1704
+ function validateReservationStructure(value, expected) {
1705
+ const snapshot = canonicalClone(value, "matrix reservation receipt");
1706
+ assertExactRecord(snapshot, RESERVATION_KEYS, "matrix reservation receipt");
1707
+ const core = reservationCore(snapshot);
1708
+ const receiptDigest = domainDigest(
1709
+ SKILL_TARGET_MATRIX_EVAL_RESERVATION_SCHEMA,
1710
+ core,
1711
+ "matrix reservation receipt core",
1712
+ );
1713
+ if (
1714
+ snapshot.schema !== SKILL_TARGET_MATRIX_EVAL_RESERVATION_SCHEMA ||
1715
+ snapshot.receiptDigest !== receiptDigest ||
1716
+ snapshot.tenantId !== expected.plan.tenantId ||
1717
+ snapshot.matrixEvalId !== expected.plan.matrixEvalId ||
1718
+ snapshot.planDigest !== expected.plan.planDigest ||
1719
+ snapshot.planNonce !== expected.plan.nonce ||
1720
+ snapshot.matrixAuthorityRoot !== expected.plan.matrixAuthorityRoot ||
1721
+ snapshot.requestDigest !== expected.requestDigest ||
1722
+ snapshot.expiresAt !== expected.plan.expiresAt ||
1723
+ snapshot.authorityRevision !== expected.policy.revision
1724
+ ) {
1725
+ throw matrixError(
1726
+ SKILL_TARGET_MATRIX_EVAL_AUTHORITY_FAILED_CODE,
1727
+ "matrix reservation receipt is not exactly bound",
1728
+ );
1729
+ }
1730
+ normalizeId(snapshot.reservationId, "reservation.reservationId");
1731
+ const reserved = normalizeTimestamp(
1732
+ snapshot.reservedAt,
1733
+ "reservation.reservedAt",
1734
+ );
1735
+ const expires = normalizeTimestamp(
1736
+ snapshot.expiresAt,
1737
+ "reservation.expiresAt",
1738
+ );
1739
+ if (
1740
+ reserved.milliseconds < expected.requestedMs - CLOCK_SKEW_MS ||
1741
+ reserved.milliseconds > expected.nowMs + CLOCK_SKEW_MS ||
1742
+ expires.milliseconds <= expected.nowMs
1743
+ ) {
1744
+ throw matrixError(
1745
+ SKILL_TARGET_MATRIX_EVAL_AUTHORITY_FAILED_CODE,
1746
+ "matrix reservation receipt freshness is invalid",
1747
+ );
1748
+ }
1749
+ return deepFreeze({
1750
+ snapshot,
1751
+ receiptDigest,
1752
+ attestation: normalizeAttestation(
1753
+ snapshot.attestation,
1754
+ "matrix reservation attestation",
1755
+ ),
1756
+ });
1757
+ }
1758
+
1759
+ function validateFinalizationStructure(value, expected) {
1760
+ const snapshot = canonicalClone(value, "matrix finalization receipt");
1761
+ assertExactRecord(snapshot, FINALIZATION_KEYS, "matrix finalization receipt");
1762
+ const core = finalizationCore(snapshot);
1763
+ const receiptDigest = domainDigest(
1764
+ SKILL_TARGET_MATRIX_EVAL_FINALIZATION_SCHEMA,
1765
+ core,
1766
+ "matrix finalization receipt core",
1767
+ );
1768
+ if (
1769
+ snapshot.schema !== SKILL_TARGET_MATRIX_EVAL_FINALIZATION_SCHEMA ||
1770
+ snapshot.receiptDigest !== receiptDigest ||
1771
+ snapshot.tenantId !== expected.plan.tenantId ||
1772
+ snapshot.matrixEvalId !== expected.plan.matrixEvalId ||
1773
+ snapshot.planDigest !== expected.plan.planDigest ||
1774
+ snapshot.reservationId !== expected.reservation.reservationId ||
1775
+ snapshot.reservationReceiptDigest !== expected.reservation.receiptDigest ||
1776
+ snapshot.decisionCommitmentDigest !== expected.decisionCommitmentDigest ||
1777
+ snapshot.requestDigest !== expected.requestDigest ||
1778
+ snapshot.authorityRevision !== expected.policy.revision
1779
+ ) {
1780
+ throw matrixError(
1781
+ SKILL_TARGET_MATRIX_EVAL_AUTHORITY_FAILED_CODE,
1782
+ "matrix finalization receipt is not exactly bound",
1783
+ );
1784
+ }
1785
+ const finalized = normalizeTimestamp(
1786
+ snapshot.finalizedAt,
1787
+ "finalization.finalizedAt",
1788
+ );
1789
+ if (
1790
+ finalized.milliseconds < expected.requestedMs - CLOCK_SKEW_MS ||
1791
+ finalized.milliseconds > expected.nowMs + CLOCK_SKEW_MS
1792
+ ) {
1793
+ throw matrixError(
1794
+ SKILL_TARGET_MATRIX_EVAL_AUTHORITY_FAILED_CODE,
1795
+ "matrix finalization receipt freshness is invalid",
1796
+ );
1797
+ }
1798
+ return deepFreeze({
1799
+ snapshot,
1800
+ receiptDigest,
1801
+ attestation: normalizeAttestation(
1802
+ snapshot.attestation,
1803
+ "matrix finalization attestation",
1804
+ ),
1805
+ });
1806
+ }
1807
+
1808
+ function readTrustedClock(clock) {
1809
+ try {
1810
+ const value = clock();
1811
+ rejectProxy(value, "trusted matrix clock result");
1812
+ return normalizeClockResult(value, "trusted matrix clock result");
1813
+ } catch (cause) {
1814
+ if (cause instanceof SkillTargetMatrixEvalError) throw cause;
1815
+ throw matrixError(
1816
+ SKILL_TARGET_MATRIX_EVAL_AUTHORITY_FAILED_CODE,
1817
+ "trusted matrix clock failed",
1818
+ { cause },
1819
+ );
1820
+ }
1821
+ }
1822
+
1823
+ function buildRequest(domain, fields, label) {
1824
+ const core = canonicalClone(fields, `${label} core`);
1825
+ return deepFreeze({
1826
+ ...core,
1827
+ requestDigest: domainDigest(domain, core, `${label} core`),
1828
+ });
1829
+ }
1830
+
1831
+ function normalizePlanAuthentication(value) {
1832
+ assertExactRecord(value, PLAN_AUTH_KEYS, "matrix plan authentication");
1833
+ const core = deepFreeze({
1834
+ planRef: normalizePlanRef(value.planRef),
1835
+ resolverDescriptorDigest: normalizeDigest(
1836
+ value.resolverDescriptorDigest,
1837
+ "matrix plan authentication resolverDescriptorDigest",
1838
+ ),
1839
+ verifierDescriptorDigest: normalizeDigest(
1840
+ value.verifierDescriptorDigest,
1841
+ "matrix plan authentication verifierDescriptorDigest",
1842
+ ),
1843
+ planAttestation: normalizeAttestation(
1844
+ value.planAttestation,
1845
+ "matrix plan authentication planAttestation",
1846
+ ),
1847
+ verifiedAt: normalizeTimestamp(
1848
+ value.verifiedAt,
1849
+ "matrix plan authentication verifiedAt",
1850
+ ).timestamp,
1851
+ });
1852
+ const evidenceDigest = domainDigest(
1853
+ "chainlesschain.skill-target-matrix-eval-plan-authentication/v1",
1854
+ core,
1855
+ "matrix plan authentication",
1856
+ );
1857
+ if (value.evidenceDigest !== evidenceDigest) {
1858
+ throw matrixError(
1859
+ SKILL_TARGET_MATRIX_EVAL_AUTHORITY_FAILED_CODE,
1860
+ "matrix plan authentication digest is invalid",
1861
+ );
1862
+ }
1863
+ return deepFreeze({ ...core, evidenceDigest });
1864
+ }
1865
+
1866
+ async function resolveAndAuthenticatePlan(
1867
+ state,
1868
+ planRef,
1869
+ deadlineMs,
1870
+ wallDeadlineAt,
1871
+ ) {
1872
+ const requested = readTrustedClock(state.composition.clock);
1873
+ const request = buildRequest(
1874
+ "chainlesschain.skill-target-matrix-eval-plan-resolution-request/v1",
1875
+ {
1876
+ schema:
1877
+ "chainlesschain.skill-target-matrix-eval-plan-resolution-request/v1",
1878
+ tenantId: state.tenantId,
1879
+ planRef,
1880
+ requestNonce: randomId("matrix-plan-resolve"),
1881
+ requestedAt: requested.timestamp,
1882
+ deadlineAt: wallDeadlineAt,
1883
+ },
1884
+ "matrix plan resolution request",
1885
+ );
1886
+ const rawResolution = await invokeSupervised(
1887
+ state.composition.supervision,
1888
+ "matrix-plan-resolve",
1889
+ request,
1890
+ (signal) =>
1891
+ state.composition.planResolver.callable(
1892
+ request,
1893
+ Object.freeze({ signal }),
1894
+ ),
1895
+ deadlineMs,
1896
+ wallDeadlineAt,
1897
+ );
1898
+ const resolution = canonicalClone(rawResolution, "matrix plan resolution");
1899
+ assertExactRecord(resolution, PLAN_RESOLUTION_KEYS, "matrix plan resolution");
1900
+ const plan = verifySkillTargetMatrixEvalPlan(resolution.plan);
1901
+ const normalizedResolvedRef = normalizePlanRef(resolution.planRef);
1902
+ const resolvedAt = normalizeTimestamp(
1903
+ resolution.resolvedAt,
1904
+ "matrix plan resolution resolvedAt",
1905
+ );
1906
+ const checked = readTrustedClock(state.composition.clock);
1907
+ if (
1908
+ resolution.schema !== SKILL_TARGET_MATRIX_EVAL_PLAN_RESOLUTION_SCHEMA ||
1909
+ resolution.requestDigest !== request.requestDigest ||
1910
+ resolution.resolverRevision !==
1911
+ state.composition.planResolverPolicy.revision ||
1912
+ !sameCanonical(normalizedResolvedRef, planRef) ||
1913
+ normalizedResolvedRef.digest !== plan.planDigest ||
1914
+ resolvedAt.milliseconds < requested.milliseconds - CLOCK_SKEW_MS ||
1915
+ resolvedAt.milliseconds > checked.milliseconds + CLOCK_SKEW_MS
1916
+ ) {
1917
+ throw matrixError(
1918
+ SKILL_TARGET_MATRIX_EVAL_AUTHORITY_FAILED_CODE,
1919
+ "resolved matrix plan is not exactly bound to its trusted request",
1920
+ );
1921
+ }
1922
+ const attestation = await verifySignature(
1923
+ state.composition,
1924
+ PLAN_SIGNATURE_PURPOSE,
1925
+ plan.planDigest,
1926
+ resolution.planAttestation,
1927
+ state.composition.planTrust,
1928
+ deadlineMs,
1929
+ wallDeadlineAt,
1930
+ "matrix-plan",
1931
+ );
1932
+ const verified = readTrustedClock(state.composition.clock);
1933
+ const issued = normalizeTimestamp(plan.issuedAt, "plan.issuedAt");
1934
+ const expires = normalizeTimestamp(plan.expiresAt, "plan.expiresAt");
1935
+ if (
1936
+ issued.milliseconds > verified.milliseconds + CLOCK_SKEW_MS ||
1937
+ expires.milliseconds <= verified.milliseconds
1938
+ ) {
1939
+ throw matrixError(
1940
+ SKILL_TARGET_MATRIX_EVAL_AUTHORITY_FAILED_CODE,
1941
+ "resolved matrix plan is not fresh",
1942
+ );
1943
+ }
1944
+ const authCore = deepFreeze({
1945
+ planRef,
1946
+ resolverDescriptorDigest: descriptorDigest(
1947
+ state.composition.planResolver.descriptor,
1948
+ ),
1949
+ verifierDescriptorDigest: descriptorDigest(
1950
+ state.composition.evidenceVerifier.descriptor,
1951
+ ),
1952
+ planAttestation: attestation,
1953
+ verifiedAt: verified.timestamp,
1954
+ });
1955
+ const authentication = deepFreeze({
1956
+ ...authCore,
1957
+ evidenceDigest: domainDigest(
1958
+ "chainlesschain.skill-target-matrix-eval-plan-authentication/v1",
1959
+ authCore,
1960
+ "matrix plan authentication",
1961
+ ),
1962
+ });
1963
+ return Object.freeze({ plan, authentication });
1964
+ }
1965
+
1966
+ async function reservePlan(state, plan, deadlineMs, wallDeadlineAt) {
1967
+ const requested = readTrustedClock(state.composition.clock);
1968
+ const request = buildRequest(
1969
+ "chainlesschain.skill-target-matrix-eval-reservation-request/v1",
1970
+ {
1971
+ schema: "chainlesschain.skill-target-matrix-eval-reservation-request/v1",
1972
+ tenantId: plan.tenantId,
1973
+ matrixEvalId: plan.matrixEvalId,
1974
+ planDigest: plan.planDigest,
1975
+ planNonce: plan.nonce,
1976
+ matrixAuthorityRoot: plan.matrixAuthorityRoot,
1977
+ requestNonce: randomId("matrix-plan-reserve"),
1978
+ requestedAt: requested.timestamp,
1979
+ deadlineAt: wallDeadlineAt,
1980
+ },
1981
+ "matrix plan reservation request",
1982
+ );
1983
+ const rawReceipt = await invokeSupervised(
1984
+ state.composition.supervision,
1985
+ "matrix-plan-reserve",
1986
+ request,
1987
+ (signal) =>
1988
+ state.composition.reservation.reserve(request, Object.freeze({ signal })),
1989
+ deadlineMs,
1990
+ wallDeadlineAt,
1991
+ );
1992
+ const checked = readTrustedClock(state.composition.clock);
1993
+ const validated = validateReservationStructure(rawReceipt, {
1994
+ plan,
1995
+ requestDigest: request.requestDigest,
1996
+ policy: state.composition.reservation.policy,
1997
+ requestedMs: requested.milliseconds,
1998
+ nowMs: checked.milliseconds,
1999
+ });
2000
+ await verifySignature(
2001
+ state.composition,
2002
+ RESERVATION_SIGNATURE_PURPOSE,
2003
+ validated.receiptDigest,
2004
+ validated.attestation,
2005
+ state.composition.reservation.policy.trust,
2006
+ deadlineMs,
2007
+ wallDeadlineAt,
2008
+ "matrix-plan-reservation",
2009
+ );
2010
+ const returned = readTrustedClock(state.composition.clock);
2011
+ if (returned.milliseconds >= new Date(plan.expiresAt).getTime()) {
2012
+ throw matrixError(
2013
+ SKILL_TARGET_MATRIX_EVAL_AUTHORITY_FAILED_CODE,
2014
+ "matrix plan expired while its durable reservation was verified",
2015
+ );
2016
+ }
2017
+ return validated.snapshot;
2018
+ }
2019
+
2020
+ function deriveMatrixDecision(cellResults) {
2021
+ let decision = "accepted";
2022
+ let reasonCodes = ["MATRIX_ALL_CELLS_ACCEPTED"];
2023
+ if (cellResults.some((cell) => cell.decision === "rejected")) {
2024
+ decision = "rejected";
2025
+ reasonCodes = ["MATRIX_CELL_REJECTED"];
2026
+ } else if (
2027
+ cellResults.some((cell) => cell.decision === "needs-more-evidence")
2028
+ ) {
2029
+ decision = "needs-more-evidence";
2030
+ reasonCodes = ["MATRIX_CELL_NEEDS_MORE_EVIDENCE"];
2031
+ }
2032
+ return deepFreeze({ decision, reasonCodes: deepFreeze(reasonCodes) });
2033
+ }
2034
+
2035
+ function matrixDecisionCommitment(input) {
2036
+ return deepFreeze({
2037
+ matrixEvalId: input.plan.matrixEvalId,
2038
+ nonce: input.plan.nonce,
2039
+ tenantId: input.plan.tenantId,
2040
+ skillName: input.plan.skillName,
2041
+ candidateId: input.plan.candidateId,
2042
+ candidateContentDigest: input.plan.candidateContentDigest,
2043
+ baselineId: input.plan.baselineId,
2044
+ baselineReleaseDigest: input.plan.baselineReleaseDigest,
2045
+ expectedActiveContentDigest: input.plan.expectedActiveContentDigest,
2046
+ expectedActiveRevision: input.plan.expectedActiveRevision,
2047
+ dependencyLockDigest: input.plan.dependencyLockDigest,
2048
+ runtimeManifestDigest: input.plan.runtimeManifestDigest,
2049
+ targetMatrixRoot: input.plan.targetMatrixRoot,
2050
+ matrixAuthorityRoot: input.plan.matrixAuthorityRoot,
2051
+ planDigest: input.plan.planDigest,
2052
+ planAuthenticationDigest: input.planAuthentication.evidenceDigest,
2053
+ reservationReceiptDigest: input.reservation.receiptDigest,
2054
+ cellCount: input.cellResults.length,
2055
+ cellResults: input.cellResults,
2056
+ childReceiptRoot: input.childReceiptRoot,
2057
+ decision: input.decision,
2058
+ reasonCodes: input.reasonCodes,
2059
+ });
2060
+ }
2061
+
2062
+ async function finalizePlan(
2063
+ state,
2064
+ plan,
2065
+ reservation,
2066
+ decisionCommitmentDigest,
2067
+ deadlineMs,
2068
+ wallDeadlineAt,
2069
+ ) {
2070
+ const requested = readTrustedClock(state.composition.clock);
2071
+ const request = buildRequest(
2072
+ "chainlesschain.skill-target-matrix-eval-finalization-request/v1",
2073
+ {
2074
+ schema: "chainlesschain.skill-target-matrix-eval-finalization-request/v1",
2075
+ tenantId: plan.tenantId,
2076
+ matrixEvalId: plan.matrixEvalId,
2077
+ planDigest: plan.planDigest,
2078
+ reservationId: reservation.reservationId,
2079
+ reservationReceiptDigest: reservation.receiptDigest,
2080
+ decisionCommitmentDigest,
2081
+ requestNonce: randomId("matrix-plan-finalize"),
2082
+ requestedAt: requested.timestamp,
2083
+ deadlineAt: wallDeadlineAt,
2084
+ },
2085
+ "matrix plan finalization request",
2086
+ );
2087
+ const rawReceipt = await invokeSupervised(
2088
+ state.composition.supervision,
2089
+ "matrix-plan-finalize",
2090
+ request,
2091
+ (signal) =>
2092
+ state.composition.reservation.finalize(
2093
+ request,
2094
+ Object.freeze({ signal }),
2095
+ ),
2096
+ deadlineMs,
2097
+ wallDeadlineAt,
2098
+ );
2099
+ const checked = readTrustedClock(state.composition.clock);
2100
+ const validated = validateFinalizationStructure(rawReceipt, {
2101
+ plan,
2102
+ reservation,
2103
+ decisionCommitmentDigest,
2104
+ requestDigest: request.requestDigest,
2105
+ policy: state.composition.reservation.policy,
2106
+ requestedMs: requested.milliseconds,
2107
+ nowMs: checked.milliseconds,
2108
+ });
2109
+ await verifySignature(
2110
+ state.composition,
2111
+ FINALIZATION_SIGNATURE_PURPOSE,
2112
+ validated.receiptDigest,
2113
+ validated.attestation,
2114
+ state.composition.reservation.policy.trust,
2115
+ deadlineMs,
2116
+ wallDeadlineAt,
2117
+ "matrix-plan-finalization",
2118
+ );
2119
+ return validated.snapshot;
2120
+ }
2121
+
2122
+ function normalizeStandaloneReservation(value) {
2123
+ const snapshot = canonicalClone(value, "matrix reservation receipt");
2124
+ assertExactRecord(snapshot, RESERVATION_KEYS, "matrix reservation receipt");
2125
+ if (snapshot.schema !== SKILL_TARGET_MATRIX_EVAL_RESERVATION_SCHEMA) {
2126
+ throw matrixError(
2127
+ SKILL_TARGET_MATRIX_EVAL_INVALID_CODE,
2128
+ "matrix reservation receipt schema is invalid",
2129
+ );
2130
+ }
2131
+ const core = reservationCore(snapshot);
2132
+ const receiptDigest = domainDigest(
2133
+ SKILL_TARGET_MATRIX_EVAL_RESERVATION_SCHEMA,
2134
+ core,
2135
+ "matrix reservation receipt core",
2136
+ );
2137
+ if (snapshot.receiptDigest !== receiptDigest) {
2138
+ throw matrixError(
2139
+ SKILL_TARGET_MATRIX_EVAL_INVALID_CODE,
2140
+ "matrix reservation receipt digest is invalid",
2141
+ );
2142
+ }
2143
+ normalizeId(snapshot.tenantId, "reservation.tenantId");
2144
+ normalizeId(snapshot.matrixEvalId, "reservation.matrixEvalId");
2145
+ normalizeDigest(snapshot.planDigest, "reservation.planDigest");
2146
+ normalizeId(snapshot.planNonce, "reservation.planNonce");
2147
+ normalizeDigest(
2148
+ snapshot.matrixAuthorityRoot,
2149
+ "reservation.matrixAuthorityRoot",
2150
+ );
2151
+ normalizeDigest(snapshot.requestDigest, "reservation.requestDigest");
2152
+ normalizeId(snapshot.reservationId, "reservation.reservationId");
2153
+ normalizeTimestamp(snapshot.reservedAt, "reservation.reservedAt");
2154
+ normalizeTimestamp(snapshot.expiresAt, "reservation.expiresAt");
2155
+ normalizeId(snapshot.authorityRevision, "reservation.authorityRevision");
2156
+ normalizeAttestation(snapshot.attestation, "reservation.attestation");
2157
+ return snapshot;
2158
+ }
2159
+
2160
+ function normalizeStandaloneFinalization(value) {
2161
+ const snapshot = canonicalClone(value, "matrix finalization receipt");
2162
+ assertExactRecord(snapshot, FINALIZATION_KEYS, "matrix finalization receipt");
2163
+ if (snapshot.schema !== SKILL_TARGET_MATRIX_EVAL_FINALIZATION_SCHEMA) {
2164
+ throw matrixError(
2165
+ SKILL_TARGET_MATRIX_EVAL_INVALID_CODE,
2166
+ "matrix finalization receipt schema is invalid",
2167
+ );
2168
+ }
2169
+ const core = finalizationCore(snapshot);
2170
+ const receiptDigest = domainDigest(
2171
+ SKILL_TARGET_MATRIX_EVAL_FINALIZATION_SCHEMA,
2172
+ core,
2173
+ "matrix finalization receipt core",
2174
+ );
2175
+ if (snapshot.receiptDigest !== receiptDigest) {
2176
+ throw matrixError(
2177
+ SKILL_TARGET_MATRIX_EVAL_INVALID_CODE,
2178
+ "matrix finalization receipt digest is invalid",
2179
+ );
2180
+ }
2181
+ normalizeId(snapshot.tenantId, "finalization.tenantId");
2182
+ normalizeId(snapshot.matrixEvalId, "finalization.matrixEvalId");
2183
+ normalizeDigest(snapshot.planDigest, "finalization.planDigest");
2184
+ normalizeId(snapshot.reservationId, "finalization.reservationId");
2185
+ normalizeDigest(
2186
+ snapshot.reservationReceiptDigest,
2187
+ "finalization.reservationReceiptDigest",
2188
+ );
2189
+ normalizeDigest(
2190
+ snapshot.decisionCommitmentDigest,
2191
+ "finalization.decisionCommitmentDigest",
2192
+ );
2193
+ normalizeDigest(snapshot.requestDigest, "finalization.requestDigest");
2194
+ normalizeTimestamp(snapshot.finalizedAt, "finalization.finalizedAt");
2195
+ normalizeId(snapshot.authorityRevision, "finalization.authorityRevision");
2196
+ normalizeAttestation(snapshot.attestation, "finalization.attestation");
2197
+ return snapshot;
2198
+ }
2199
+
2200
+ function normalizeCellResult(value, label) {
2201
+ assertExactRecord(value, CELL_RESULT_KEYS, label);
2202
+ const planCell = normalizePlanCell(
2203
+ Object.fromEntries([...PLAN_CELL_KEYS].map((key) => [key, value[key]])),
2204
+ label,
2205
+ );
2206
+ return deepFreeze({
2207
+ ...planCell,
2208
+ runId: normalizeId(value.runId, `${label}.runId`),
2209
+ runNonce: normalizeId(value.runNonce, `${label}.runNonce`),
2210
+ evaluationContextDigest: normalizeDigest(
2211
+ value.evaluationContextDigest,
2212
+ `${label}.evaluationContextDigest`,
2213
+ ),
2214
+ childReceiptDigest: normalizeDigest(
2215
+ value.childReceiptDigest,
2216
+ `${label}.childReceiptDigest`,
2217
+ ),
2218
+ childFullDigest: normalizeDigest(
2219
+ value.childFullDigest,
2220
+ `${label}.childFullDigest`,
2221
+ ),
2222
+ decision: normalizeDecision(value.decision, `${label}.decision`),
2223
+ reasonCodes: normalizeReasonCodes(
2224
+ value.reasonCodes,
2225
+ `${label}.reasonCodes`,
2226
+ ),
2227
+ issuedAt: normalizeTimestamp(value.issuedAt, `${label}.issuedAt`).timestamp,
2228
+ expiresAt: normalizeTimestamp(value.expiresAt, `${label}.expiresAt`)
2229
+ .timestamp,
2230
+ });
2231
+ }
2232
+
2233
+ function normalizeCellResults(value) {
2234
+ const results = assertDenseStandardArray(value, "matrix cell results", {
2235
+ minimum: 1,
2236
+ maximum: MAX_CELLS,
2237
+ }).map((entry, index) =>
2238
+ normalizeCellResult(entry, `matrix cell results[${index}]`),
2239
+ );
2240
+ for (const key of [
2241
+ "cellId",
2242
+ "invocationId",
2243
+ "invocationNonce",
2244
+ "runId",
2245
+ "runNonce",
2246
+ "evaluationContextDigest",
2247
+ "childReceiptDigest",
2248
+ "childFullDigest",
2249
+ ]) {
2250
+ if (new Set(results.map((entry) => entry[key])).size !== results.length) {
2251
+ throw matrixError(
2252
+ SKILL_TARGET_MATRIX_EVAL_INVALID_CODE,
2253
+ `matrix cell result ${key} values must be unique`,
2254
+ );
2255
+ }
2256
+ }
2257
+ const ordered = [...results].sort((left, right) =>
2258
+ left.cellId < right.cellId ? -1 : left.cellId > right.cellId ? 1 : 0,
2259
+ );
2260
+ if (!sameCanonical(results, ordered)) {
2261
+ throw matrixError(
2262
+ SKILL_TARGET_MATRIX_EVAL_INVALID_CODE,
2263
+ "matrix cell results are not in canonical cell order",
2264
+ );
2265
+ }
2266
+ return deepFreeze(ordered);
2267
+ }
2268
+
2269
+ function childReceiptRoot(cellResults) {
2270
+ return domainDigest(
2271
+ "chainlesschain.skill-target-matrix-eval-child-receipt-root/v1",
2272
+ cellResults.map((cell) =>
2273
+ deepFreeze({
2274
+ cellId: cell.cellId,
2275
+ childFullDigest: cell.childFullDigest,
2276
+ }),
2277
+ ),
2278
+ "matrix child receipt root",
2279
+ );
2280
+ }
2281
+
2282
+ function receiptCore(receipt) {
2283
+ return deepFreeze(
2284
+ Object.fromEntries(
2285
+ [...RECEIPT_KEYS]
2286
+ .filter((key) => key !== "receiptDigest" && key !== "attestation")
2287
+ .map((key) => [key, receipt[key]]),
2288
+ ),
2289
+ );
2290
+ }
2291
+
2292
+ function normalizeExpectedReceipt(value) {
2293
+ const snapshot = canonicalClone(value, "expected matrix receipt context");
2294
+ assertExactRecord(
2295
+ snapshot,
2296
+ EXPECTED_RECEIPT_KEYS,
2297
+ "expected matrix receipt context",
2298
+ );
2299
+ return deepFreeze({
2300
+ matrixEvalId: normalizeId(snapshot.matrixEvalId, "expected.matrixEvalId"),
2301
+ tenantId: normalizeId(snapshot.tenantId, "expected.tenantId"),
2302
+ skillName: normalizeId(snapshot.skillName, "expected.skillName", 128),
2303
+ candidateId: normalizeDigest(snapshot.candidateId, "expected.candidateId"),
2304
+ candidateContentDigest: normalizeDigest(
2305
+ snapshot.candidateContentDigest,
2306
+ "expected.candidateContentDigest",
2307
+ ),
2308
+ baselineId: normalizeDigest(snapshot.baselineId, "expected.baselineId"),
2309
+ baselineReleaseDigest: normalizeNullableDigest(
2310
+ snapshot.baselineReleaseDigest,
2311
+ "expected.baselineReleaseDigest",
2312
+ ),
2313
+ expectedActiveContentDigest: normalizeDigest(
2314
+ snapshot.expectedActiveContentDigest,
2315
+ "expected.expectedActiveContentDigest",
2316
+ ),
2317
+ expectedActiveRevision: normalizeInteger(
2318
+ snapshot.expectedActiveRevision,
2319
+ "expected.expectedActiveRevision",
2320
+ ),
2321
+ dependencyLockDigest: normalizeDigest(
2322
+ snapshot.dependencyLockDigest,
2323
+ "expected.dependencyLockDigest",
2324
+ ),
2325
+ runtimeManifestDigest: normalizeDigest(
2326
+ snapshot.runtimeManifestDigest,
2327
+ "expected.runtimeManifestDigest",
2328
+ ),
2329
+ targetMatrixRoot: normalizeDigest(
2330
+ snapshot.targetMatrixRoot,
2331
+ "expected.targetMatrixRoot",
2332
+ ),
2333
+ matrixAuthorityRoot: normalizeDigest(
2334
+ snapshot.matrixAuthorityRoot,
2335
+ "expected.matrixAuthorityRoot",
2336
+ ),
2337
+ planDigest: normalizeDigest(snapshot.planDigest, "expected.planDigest"),
2338
+ decision: normalizeDecision(snapshot.decision, "expected.decision"),
2339
+ });
2340
+ }
2341
+
2342
+ function verifyMatrixReceiptStructure(
2343
+ value,
2344
+ receiptTrust,
2345
+ maximumReceiptTtlMs,
2346
+ ) {
2347
+ const snapshot = canonicalClone(value, "matrix evaluation receipt");
2348
+ assertExactRecord(snapshot, RECEIPT_KEYS, "matrix evaluation receipt");
2349
+ if (snapshot.schema !== SKILL_TARGET_MATRIX_EVAL_RECEIPT_SCHEMA) {
2350
+ throw matrixError(
2351
+ SKILL_TARGET_MATRIX_EVAL_INVALID_CODE,
2352
+ "matrix evaluation receipt schema is invalid",
2353
+ );
2354
+ }
2355
+ const planAuthentication = normalizePlanAuthentication(
2356
+ snapshot.planAuthentication,
2357
+ );
2358
+ const reservation = normalizeStandaloneReservation(snapshot.reservation);
2359
+ const finalization = normalizeStandaloneFinalization(snapshot.finalization);
2360
+ const cellResults = normalizeCellResults(snapshot.cellResults);
2361
+ const decision = deriveMatrixDecision(cellResults);
2362
+ const normalized = deepFreeze({
2363
+ schema: SKILL_TARGET_MATRIX_EVAL_RECEIPT_SCHEMA,
2364
+ matrixEvalId: normalizeId(snapshot.matrixEvalId, "receipt.matrixEvalId"),
2365
+ nonce: normalizeId(snapshot.nonce, "receipt.nonce"),
2366
+ tenantId: normalizeId(snapshot.tenantId, "receipt.tenantId"),
2367
+ skillName: normalizeId(snapshot.skillName, "receipt.skillName", 128),
2368
+ candidateId: normalizeDigest(snapshot.candidateId, "receipt.candidateId"),
2369
+ candidateContentDigest: normalizeDigest(
2370
+ snapshot.candidateContentDigest,
2371
+ "receipt.candidateContentDigest",
2372
+ ),
2373
+ baselineId: normalizeDigest(snapshot.baselineId, "receipt.baselineId"),
2374
+ baselineReleaseDigest: normalizeNullableDigest(
2375
+ snapshot.baselineReleaseDigest,
2376
+ "receipt.baselineReleaseDigest",
2377
+ ),
2378
+ expectedActiveContentDigest: normalizeDigest(
2379
+ snapshot.expectedActiveContentDigest,
2380
+ "receipt.expectedActiveContentDigest",
2381
+ ),
2382
+ expectedActiveRevision: normalizeInteger(
2383
+ snapshot.expectedActiveRevision,
2384
+ "receipt.expectedActiveRevision",
2385
+ ),
2386
+ dependencyLockDigest: normalizeDigest(
2387
+ snapshot.dependencyLockDigest,
2388
+ "receipt.dependencyLockDigest",
2389
+ ),
2390
+ runtimeManifestDigest: normalizeDigest(
2391
+ snapshot.runtimeManifestDigest,
2392
+ "receipt.runtimeManifestDigest",
2393
+ ),
2394
+ targetMatrixRoot: normalizeDigest(
2395
+ snapshot.targetMatrixRoot,
2396
+ "receipt.targetMatrixRoot",
2397
+ ),
2398
+ matrixAuthorityRoot: normalizeDigest(
2399
+ snapshot.matrixAuthorityRoot,
2400
+ "receipt.matrixAuthorityRoot",
2401
+ ),
2402
+ planDigest: normalizeDigest(snapshot.planDigest, "receipt.planDigest"),
2403
+ planIssuedAt: normalizeTimestamp(
2404
+ snapshot.planIssuedAt,
2405
+ "receipt.planIssuedAt",
2406
+ ).timestamp,
2407
+ planExpiresAt: normalizeTimestamp(
2408
+ snapshot.planExpiresAt,
2409
+ "receipt.planExpiresAt",
2410
+ ).timestamp,
2411
+ aggregateReceiptTtlMs: normalizeInteger(
2412
+ snapshot.aggregateReceiptTtlMs,
2413
+ "receipt.aggregateReceiptTtlMs",
2414
+ { minimum: 1_000, maximum: MAX_RECEIPT_TTL_MS },
2415
+ ),
2416
+ planAuthentication,
2417
+ reservation,
2418
+ finalization,
2419
+ cellCount: normalizeInteger(snapshot.cellCount, "receipt.cellCount", {
2420
+ minimum: 1,
2421
+ maximum: MAX_CELLS,
2422
+ }),
2423
+ cellResults,
2424
+ childReceiptRoot: normalizeDigest(
2425
+ snapshot.childReceiptRoot,
2426
+ "receipt.childReceiptRoot",
2427
+ ),
2428
+ decisionCommitmentDigest: normalizeDigest(
2429
+ snapshot.decisionCommitmentDigest,
2430
+ "receipt.decisionCommitmentDigest",
2431
+ ),
2432
+ decision: normalizeDecision(snapshot.decision, "receipt.decision"),
2433
+ reasonCodes: normalizeReasonCodes(
2434
+ snapshot.reasonCodes,
2435
+ "receipt.reasonCodes",
2436
+ ),
2437
+ issuedAt: normalizeTimestamp(snapshot.issuedAt, "receipt.issuedAt")
2438
+ .timestamp,
2439
+ expiresAt: normalizeTimestamp(snapshot.expiresAt, "receipt.expiresAt")
2440
+ .timestamp,
2441
+ receiptDigest: normalizeDigest(
2442
+ snapshot.receiptDigest,
2443
+ "receipt.receiptDigest",
2444
+ ),
2445
+ attestation: normalizeAttestation(
2446
+ snapshot.attestation,
2447
+ "receipt.attestation",
2448
+ ),
2449
+ });
2450
+ const planShape = normalized;
2451
+ const expectedRoot = childReceiptRoot(cellResults);
2452
+ const expectedCommitment = matrixDecisionCommitment({
2453
+ plan: planShape,
2454
+ planAuthentication,
2455
+ reservation,
2456
+ cellResults,
2457
+ childReceiptRoot: expectedRoot,
2458
+ decision: decision.decision,
2459
+ reasonCodes: decision.reasonCodes,
2460
+ });
2461
+ const expectedCommitmentDigest = domainDigest(
2462
+ "chainlesschain.skill-target-matrix-eval-decision-commitment/v1",
2463
+ expectedCommitment,
2464
+ "matrix decision commitment",
2465
+ );
2466
+ const expectedReceiptDigest = domainDigest(
2467
+ SKILL_TARGET_MATRIX_EVAL_RECEIPT_SCHEMA,
2468
+ receiptCore(normalized),
2469
+ "matrix evaluation receipt core",
2470
+ );
2471
+ const issuedMs = new Date(normalized.issuedAt).getTime();
2472
+ const expiresMs = new Date(normalized.expiresAt).getTime();
2473
+ const planIssuedMs = new Date(normalized.planIssuedAt).getTime();
2474
+ const planExpiresMs = new Date(normalized.planExpiresAt).getTime();
2475
+ const planVerifiedMs = new Date(
2476
+ normalized.planAuthentication.verifiedAt,
2477
+ ).getTime();
2478
+ const reservedMs = new Date(normalized.reservation.reservedAt).getTime();
2479
+ const finalizedMs = new Date(normalized.finalization.finalizedAt).getTime();
2480
+ const childIssuedTimes = cellResults.map((cell) =>
2481
+ new Date(cell.issuedAt).getTime(),
2482
+ );
2483
+ const latestChildIssuedMs = Math.max(...childIssuedTimes);
2484
+ const childTimelineInvalid = cellResults.some((cell, index) => {
2485
+ const childIssuedMs = childIssuedTimes[index];
2486
+ const childExpiresAtMs = new Date(cell.expiresAt).getTime();
2487
+ return (
2488
+ childExpiresAtMs <= childIssuedMs ||
2489
+ childIssuedMs < planIssuedMs - CLOCK_SKEW_MS ||
2490
+ childIssuedMs < reservedMs - CLOCK_SKEW_MS ||
2491
+ childIssuedMs > issuedMs + CLOCK_SKEW_MS ||
2492
+ childIssuedMs >= planExpiresMs
2493
+ );
2494
+ });
2495
+ const childExpiresMs = Math.min(
2496
+ ...cellResults.map((cell) => new Date(cell.expiresAt).getTime()),
2497
+ );
2498
+ const exactExpiresMs = Math.min(
2499
+ planExpiresMs,
2500
+ childExpiresMs,
2501
+ issuedMs + normalized.aggregateReceiptTtlMs,
2502
+ );
2503
+ if (
2504
+ normalized.cellCount !== cellResults.length ||
2505
+ normalized.childReceiptRoot !== expectedRoot ||
2506
+ normalized.decision !== decision.decision ||
2507
+ !sameCanonical(normalized.reasonCodes, decision.reasonCodes) ||
2508
+ normalized.decisionCommitmentDigest !== expectedCommitmentDigest ||
2509
+ normalized.finalization.decisionCommitmentDigest !==
2510
+ expectedCommitmentDigest ||
2511
+ normalized.reservation.tenantId !== normalized.tenantId ||
2512
+ normalized.reservation.matrixEvalId !== normalized.matrixEvalId ||
2513
+ normalized.reservation.planDigest !== normalized.planDigest ||
2514
+ normalized.reservation.planNonce !== normalized.nonce ||
2515
+ normalized.reservation.matrixAuthorityRoot !==
2516
+ normalized.matrixAuthorityRoot ||
2517
+ normalized.reservation.expiresAt !== normalized.planExpiresAt ||
2518
+ normalized.finalization.tenantId !== normalized.tenantId ||
2519
+ normalized.finalization.matrixEvalId !== normalized.matrixEvalId ||
2520
+ normalized.finalization.planDigest !== normalized.planDigest ||
2521
+ normalized.finalization.reservationId !==
2522
+ normalized.reservation.reservationId ||
2523
+ normalized.finalization.reservationReceiptDigest !==
2524
+ normalized.reservation.receiptDigest ||
2525
+ normalized.planAuthentication.planRef.digest !== normalized.planDigest ||
2526
+ normalized.receiptDigest !== expectedReceiptDigest ||
2527
+ !sameTrust(normalized.attestation, receiptTrust) ||
2528
+ expiresMs !== exactExpiresMs ||
2529
+ expiresMs <= issuedMs ||
2530
+ expiresMs - issuedMs > maximumReceiptTtlMs ||
2531
+ planExpiresMs <= planIssuedMs ||
2532
+ planExpiresMs - planIssuedMs > MAX_PLAN_TTL_MS ||
2533
+ issuedMs < planIssuedMs - CLOCK_SKEW_MS ||
2534
+ issuedMs >= planExpiresMs ||
2535
+ planVerifiedMs < planIssuedMs - CLOCK_SKEW_MS ||
2536
+ planVerifiedMs > issuedMs + CLOCK_SKEW_MS ||
2537
+ planVerifiedMs >= planExpiresMs ||
2538
+ reservedMs < planIssuedMs - CLOCK_SKEW_MS ||
2539
+ reservedMs < planVerifiedMs - CLOCK_SKEW_MS ||
2540
+ reservedMs > finalizedMs + CLOCK_SKEW_MS ||
2541
+ reservedMs > issuedMs + CLOCK_SKEW_MS ||
2542
+ finalizedMs < reservedMs - CLOCK_SKEW_MS ||
2543
+ finalizedMs < latestChildIssuedMs - CLOCK_SKEW_MS ||
2544
+ finalizedMs > issuedMs + CLOCK_SKEW_MS ||
2545
+ finalizedMs >= planExpiresMs ||
2546
+ childTimelineInvalid
2547
+ ) {
2548
+ throw matrixError(
2549
+ SKILL_TARGET_MATRIX_EVAL_AUTHORITY_FAILED_CODE,
2550
+ "matrix evaluation receipt binding, decision, expiry, or signature trust is invalid",
2551
+ );
2552
+ }
2553
+ return normalized;
2554
+ }
2555
+
2556
+ async function verifyReceiptSignature(
2557
+ composition,
2558
+ receiptDigest,
2559
+ attestation,
2560
+ deadlineMs,
2561
+ wallDeadlineAt,
2562
+ label,
2563
+ ) {
2564
+ const verified = await invokeSupervised(
2565
+ composition.supervision,
2566
+ label,
2567
+ { purpose: RECEIPT_SIGNATURE_PURPOSE, receiptDigest, attestation },
2568
+ (signal) =>
2569
+ composition.verifier.callable(
2570
+ signaturePayload(RECEIPT_SIGNATURE_PURPOSE, receiptDigest, attestation),
2571
+ Object.freeze({ signal }),
2572
+ ),
2573
+ deadlineMs,
2574
+ wallDeadlineAt,
2575
+ );
2576
+ if (verified !== true) {
2577
+ throw matrixError(
2578
+ SKILL_TARGET_MATRIX_EVAL_AUTHORITY_FAILED_CODE,
2579
+ "matrix evaluation receipt signature was rejected",
2580
+ );
2581
+ }
2582
+ }
2583
+
2584
+ function compositionPrincipalEntries(composition, cellAuthorities) {
2585
+ const entries = [
2586
+ { role: "planSigner", trust: composition.planTrust },
2587
+ {
2588
+ role: "planResolver",
2589
+ trust: composition.planResolver.descriptor.authority,
2590
+ },
2591
+ {
2592
+ role: "evidenceVerifier",
2593
+ trust: composition.evidenceVerifier.descriptor.authority,
2594
+ },
2595
+ {
2596
+ role: "reservationAuthority",
2597
+ trust: composition.reservation.reservationDescriptor.authority,
2598
+ },
2599
+ {
2600
+ role: "matrixSupervisor",
2601
+ trust: composition.supervision.descriptor.authority,
2602
+ },
2603
+ { role: "matrixSigner", trust: composition.signer.descriptor.authority },
2604
+ {
2605
+ role: "matrixVerifier",
2606
+ trust: composition.verifier.descriptor.authority,
2607
+ },
2608
+ { role: "trustedClock", trust: composition.clockDescriptor.authority },
2609
+ ];
2610
+ for (const cell of cellAuthorities) {
2611
+ entries.push(
2612
+ { role: `cellGate:${cell.cellId}`, trust: cell.gateDescriptor.authority },
2613
+ {
2614
+ role: `cellReceiptVerifier:${cell.cellId}`,
2615
+ trust: cell.receiptVerifierDescriptor.authority,
2616
+ },
2617
+ );
2618
+ }
2619
+ return entries;
2620
+ }
2621
+
2622
+ export class SkillTargetMatrixEvalAggregator {
2623
+ #state;
2624
+ #used = false;
2625
+
2626
+ constructor(options) {
2627
+ assertExactRecord(
2628
+ options,
2629
+ AGGREGATOR_OPTION_KEYS,
2630
+ "matrix aggregator options",
2631
+ );
2632
+ const tenantId = normalizeId(
2633
+ options.tenantId,
2634
+ "matrix aggregator tenantId",
2635
+ );
2636
+ const dependencyLock = verifySkillDependencyLock(options.dependencyLock);
2637
+ const runtimeManifest = verifySkillRuntimeManifest(options.runtimeManifest);
2638
+ const targetMatrix = verifySkillTargetMatrix(options.targetMatrix, {
2639
+ dependencyLock,
2640
+ runtimeManifest,
2641
+ expectedEnvironmentBindings: options.expectedEnvironmentBindings,
2642
+ expectedTargetMatrixRoot: options.expectedTargetMatrixRoot,
2643
+ });
2644
+ if (
2645
+ dependencyLock.tenantId !== tenantId ||
2646
+ runtimeManifest.tenantId !== tenantId ||
2647
+ targetMatrix.tenantId !== tenantId
2648
+ ) {
2649
+ throw matrixError(
2650
+ SKILL_TARGET_MATRIX_EVAL_INVALID_CODE,
2651
+ "matrix composition artifacts must belong to the captured tenant",
2652
+ );
2653
+ }
2654
+ const cells = captureCellRuntimes(options.cellRuntimes);
2655
+ const matrixCellIds = targetMatrix.cells.map((cell) => cell.cellId);
2656
+ const runtimeCellIds = [...cells.runtimes.keys()].sort();
2657
+ if (!sameCanonical(matrixCellIds, runtimeCellIds)) {
2658
+ throw matrixError(
2659
+ SKILL_TARGET_MATRIX_EVAL_INVALID_CODE,
2660
+ "cellRuntimes must exactly cover the canonical target matrix",
2661
+ );
2662
+ }
2663
+ const composition = captureComposition(options);
2664
+ validatePrincipalMatrix(
2665
+ compositionPrincipalEntries(composition, cells.authorities),
2666
+ );
2667
+ const matrixAuthorityRoot = computeSkillTargetMatrixEvalAuthorityRoot({
2668
+ planResolverDescriptor: composition.planResolver.descriptor,
2669
+ evidenceVerifierDescriptor: composition.evidenceVerifier.descriptor,
2670
+ reservationDescriptor: composition.reservation.reservationDescriptor,
2671
+ finalizationDescriptor: composition.reservation.finalizationDescriptor,
2672
+ supervisorDescriptor: composition.supervision.descriptor,
2673
+ matrixSignerDescriptor: composition.signer.descriptor,
2674
+ matrixVerifierDescriptor: composition.verifier.descriptor,
2675
+ clockDescriptor: composition.clockDescriptor,
2676
+ planTrust: composition.planTrust,
2677
+ matrixReceiptTrust: composition.receiptTrust,
2678
+ cellAuthorities: cells.authorities,
2679
+ });
2680
+ const maximumMatrixWallClockMs = normalizeInteger(
2681
+ options.maximumMatrixWallClockMs,
2682
+ "maximumMatrixWallClockMs",
2683
+ { minimum: 100, maximum: 3_600_000 },
2684
+ );
2685
+ readTrustedClock(composition.clock);
2686
+ this.#state = Object.freeze({
2687
+ tenantId,
2688
+ dependencyLock,
2689
+ runtimeManifest,
2690
+ targetMatrix,
2691
+ cellRuntimes: cells.runtimes,
2692
+ composition,
2693
+ matrixAuthorityRoot,
2694
+ maximumMatrixWallClockMs,
2695
+ });
2696
+ AGGREGATOR_INSTANCES.add(this);
2697
+ Object.freeze(this);
2698
+ }
2699
+
2700
+ async evaluate(planRefInput) {
2701
+ if (this.#used) {
2702
+ throw matrixError(
2703
+ SKILL_TARGET_MATRIX_EVAL_REPLAYED_CODE,
2704
+ "matrix aggregator instances are one-shot",
2705
+ );
2706
+ }
2707
+ this.#used = true;
2708
+ const entryMonotonicMs = NATIVE_MONOTONIC_NOW();
2709
+ const state = this.#state;
2710
+ const planRef = normalizePlanRef(
2711
+ canonicalClone(planRefInput, "matrix evaluation planRef"),
2712
+ );
2713
+ const entryClock = readTrustedClock(state.composition.clock);
2714
+ const configuredDeadlineMs =
2715
+ entryMonotonicMs + state.maximumMatrixWallClockMs;
2716
+ const configuredWallDeadlineMs =
2717
+ entryClock.milliseconds + state.maximumMatrixWallClockMs;
2718
+ const configuredWallDeadlineAt = new Date(
2719
+ configuredWallDeadlineMs,
2720
+ ).toISOString();
2721
+ const resolved = await resolveAndAuthenticatePlan(
2722
+ state,
2723
+ planRef,
2724
+ configuredDeadlineMs,
2725
+ configuredWallDeadlineAt,
2726
+ );
2727
+ const plan = resolved.plan;
2728
+ assertPlanMatchesComposition(plan, state);
2729
+ const planExpiresMs = new Date(plan.expiresAt).getTime();
2730
+ const deadlineMs = Math.min(
2731
+ configuredDeadlineMs,
2732
+ entryMonotonicMs + plan.maxTotalWallClockMs,
2733
+ entryMonotonicMs + (planExpiresMs - entryClock.milliseconds),
2734
+ );
2735
+ const wallDeadlineAt = new Date(
2736
+ Math.min(
2737
+ configuredWallDeadlineMs,
2738
+ entryClock.milliseconds + plan.maxTotalWallClockMs,
2739
+ planExpiresMs,
2740
+ ),
2741
+ ).toISOString();
2742
+ assertRootDeadline(deadlineMs, "matrix evaluation plan resolution");
2743
+ const reservation = await reservePlan(
2744
+ state,
2745
+ plan,
2746
+ deadlineMs,
2747
+ wallDeadlineAt,
2748
+ );
2749
+ const cellResults = [];
2750
+ for (const planCell of plan.cells) {
2751
+ assertRootDeadline(deadlineMs, `matrix cell ${planCell.cellId}`);
2752
+ // This authority-root and signed-plan commitment is the trusted
2753
+ // composition's bound for the branded Gate's complete API settlement,
2754
+ // including its own hard-deadline termination grace. An attested loader
2755
+ // must bind it to the captured policyDigest and actual Gate instance.
2756
+ if (
2757
+ remainingMilliseconds(deadlineMs) <= planCell.maximumCellSettlementMs
2758
+ ) {
2759
+ throw matrixError(
2760
+ SKILL_TARGET_MATRIX_EVAL_DEADLINE_CODE,
2761
+ `matrix cell ${planCell.cellId} cannot start without its preregistered settlement window`,
2762
+ );
2763
+ }
2764
+ const runtime = state.cellRuntimes.get(planCell.cellId);
2765
+ const gateRequest = deepFreeze({
2766
+ suiteRef: planCell.suiteRef,
2767
+ candidateId: plan.candidateId,
2768
+ baselineId: plan.baselineId,
2769
+ targetEnvironmentRef: planCell.targetEnvironmentRef,
2770
+ evaluationContext: deepFreeze({
2771
+ planDigest: plan.planDigest,
2772
+ targetMatrixRoot: plan.targetMatrixRoot,
2773
+ cellId: planCell.cellId,
2774
+ runtimeId: planCell.runtimeId,
2775
+ }),
2776
+ });
2777
+ // The preregistered invocation identity is the signed plan cell plus the
2778
+ // durable reservation. Gate-generated runId/runNonce are only exact
2779
+ // child-verifier parameters read from this captured Promise result; they
2780
+ // are not treated as an independent replay boundary.
2781
+ const childFromGate = await invokeSupervised(
2782
+ state.composition.supervision,
2783
+ `cell-gate-${planCell.cellId}`,
2784
+ {
2785
+ invocationId: planCell.invocationId,
2786
+ invocationNonce: planCell.invocationNonce,
2787
+ gateRequest,
2788
+ },
2789
+ () => runEvolutionEvalGate(runtime.gate, gateRequest),
2790
+ deadlineMs,
2791
+ wallDeadlineAt,
2792
+ );
2793
+ const expectedContextDigest = computeEvolutionEvalContextDigest({
2794
+ planDigest: plan.planDigest,
2795
+ tenantId: plan.tenantId,
2796
+ targetMatrixRoot: plan.targetMatrixRoot,
2797
+ cellId: planCell.cellId,
2798
+ runtimeId: planCell.runtimeId,
2799
+ targetEnvironmentRef: planCell.targetEnvironmentRef,
2800
+ environmentDigest: planCell.environmentDigest,
2801
+ candidateId: plan.candidateId,
2802
+ baselineId: plan.baselineId,
2803
+ suiteDigest: planCell.suiteDigest,
2804
+ policyDigest: planCell.policyDigest,
2805
+ evaluationAuthorityRoot: planCell.evaluationAuthorityRoot,
2806
+ });
2807
+ const expectedChild = deepFreeze({
2808
+ runId: normalizeId(childFromGate.runId, "child receipt runId"),
2809
+ runNonce: normalizeId(childFromGate.runNonce, "child receipt runNonce"),
2810
+ suiteDigest: planCell.suiteDigest,
2811
+ policyDigest: planCell.policyDigest,
2812
+ evaluationAuthorityRoot: planCell.evaluationAuthorityRoot,
2813
+ targetEnvironmentRef: planCell.targetEnvironmentRef,
2814
+ evaluationContextDigest: expectedContextDigest,
2815
+ candidateId: plan.candidateId,
2816
+ baselineId: plan.baselineId,
2817
+ environmentDigest: planCell.environmentDigest,
2818
+ tenantId: plan.tenantId,
2819
+ provenanceAudience: planCell.provenanceAudience,
2820
+ trainerAuthority: planCell.trainerAuthority,
2821
+ trainerRevision: planCell.trainerRevision,
2822
+ });
2823
+ const verifiedChild = await invokeSupervised(
2824
+ state.composition.supervision,
2825
+ `cell-receipt-verify-${planCell.cellId}`,
2826
+ {
2827
+ invocationId: planCell.invocationId,
2828
+ invocationNonce: planCell.invocationNonce,
2829
+ childFullDigest: domainDigest(
2830
+ "chainlesschain.skill-target-matrix-eval-child-receipt/v1",
2831
+ childFromGate,
2832
+ `matrix cell ${planCell.cellId} child receipt`,
2833
+ ),
2834
+ expectedChild,
2835
+ },
2836
+ () =>
2837
+ verifyEvolutionEvalReceipt(
2838
+ runtime.receiptVerifier,
2839
+ childFromGate,
2840
+ expectedChild,
2841
+ ),
2842
+ deadlineMs,
2843
+ wallDeadlineAt,
2844
+ );
2845
+ const verifiedSnapshot = canonicalClone(
2846
+ verifiedChild,
2847
+ `matrix cell ${planCell.cellId} verified receipt`,
2848
+ );
2849
+ if (
2850
+ verifiedSnapshot.runId !== expectedChild.runId ||
2851
+ verifiedSnapshot.runNonce !== expectedChild.runNonce ||
2852
+ verifiedSnapshot.evaluationContextDigest !== expectedContextDigest ||
2853
+ verifiedSnapshot.receiptDigest !== childFromGate.receiptDigest
2854
+ ) {
2855
+ throw matrixError(
2856
+ SKILL_TARGET_MATRIX_EVAL_AUTHORITY_FAILED_CODE,
2857
+ `matrix cell verifier returned a different receipt: ${planCell.cellId}`,
2858
+ );
2859
+ }
2860
+ const issuedAt = normalizeTimestamp(
2861
+ verifiedSnapshot.issuedAt,
2862
+ `matrix cell ${planCell.cellId} issuedAt`,
2863
+ ).timestamp;
2864
+ const expiresAt = normalizeTimestamp(
2865
+ verifiedSnapshot.expiresAt,
2866
+ `matrix cell ${planCell.cellId} expiresAt`,
2867
+ ).timestamp;
2868
+ cellResults.push(
2869
+ deepFreeze({
2870
+ ...planCell,
2871
+ runId: expectedChild.runId,
2872
+ runNonce: expectedChild.runNonce,
2873
+ evaluationContextDigest: expectedContextDigest,
2874
+ childReceiptDigest: normalizeDigest(
2875
+ verifiedSnapshot.receiptDigest,
2876
+ `matrix cell ${planCell.cellId} receiptDigest`,
2877
+ ),
2878
+ childFullDigest: domainDigest(
2879
+ "chainlesschain.skill-target-matrix-eval-child-receipt/v1",
2880
+ verifiedSnapshot,
2881
+ `matrix cell ${planCell.cellId} verified full receipt`,
2882
+ ),
2883
+ decision: normalizeDecision(
2884
+ verifiedSnapshot.decision,
2885
+ `matrix cell ${planCell.cellId} decision`,
2886
+ ),
2887
+ reasonCodes: normalizeReasonCodes(
2888
+ verifiedSnapshot.reasonCodes,
2889
+ `matrix cell ${planCell.cellId} reasonCodes`,
2890
+ ),
2891
+ issuedAt,
2892
+ expiresAt,
2893
+ }),
2894
+ );
2895
+ }
2896
+ const normalizedCells = normalizeCellResults(cellResults);
2897
+ const root = childReceiptRoot(normalizedCells);
2898
+ const derived = deriveMatrixDecision(normalizedCells);
2899
+ const commitment = matrixDecisionCommitment({
2900
+ plan,
2901
+ planAuthentication: resolved.authentication,
2902
+ reservation,
2903
+ cellResults: normalizedCells,
2904
+ childReceiptRoot: root,
2905
+ decision: derived.decision,
2906
+ reasonCodes: derived.reasonCodes,
2907
+ });
2908
+ const decisionCommitmentDigest = domainDigest(
2909
+ "chainlesschain.skill-target-matrix-eval-decision-commitment/v1",
2910
+ commitment,
2911
+ "matrix decision commitment",
2912
+ );
2913
+ const finalization = await finalizePlan(
2914
+ state,
2915
+ plan,
2916
+ reservation,
2917
+ decisionCommitmentDigest,
2918
+ deadlineMs,
2919
+ wallDeadlineAt,
2920
+ );
2921
+ const issued = readTrustedClock(state.composition.clock);
2922
+ const childExpiresMs = Math.min(
2923
+ ...normalizedCells.map((cell) => new Date(cell.expiresAt).getTime()),
2924
+ );
2925
+ const expiresMs = Math.min(
2926
+ planExpiresMs,
2927
+ childExpiresMs,
2928
+ issued.milliseconds + plan.aggregateReceiptTtlMs,
2929
+ );
2930
+ if (expiresMs <= issued.milliseconds) {
2931
+ throw matrixError(
2932
+ SKILL_TARGET_MATRIX_EVAL_AUTHORITY_FAILED_CODE,
2933
+ "matrix receipt inputs expired before aggregation completed",
2934
+ );
2935
+ }
2936
+ const core = deepFreeze({
2937
+ schema: SKILL_TARGET_MATRIX_EVAL_RECEIPT_SCHEMA,
2938
+ matrixEvalId: plan.matrixEvalId,
2939
+ nonce: plan.nonce,
2940
+ tenantId: plan.tenantId,
2941
+ skillName: plan.skillName,
2942
+ candidateId: plan.candidateId,
2943
+ candidateContentDigest: plan.candidateContentDigest,
2944
+ baselineId: plan.baselineId,
2945
+ baselineReleaseDigest: plan.baselineReleaseDigest,
2946
+ expectedActiveContentDigest: plan.expectedActiveContentDigest,
2947
+ expectedActiveRevision: plan.expectedActiveRevision,
2948
+ dependencyLockDigest: plan.dependencyLockDigest,
2949
+ runtimeManifestDigest: plan.runtimeManifestDigest,
2950
+ targetMatrixRoot: plan.targetMatrixRoot,
2951
+ matrixAuthorityRoot: plan.matrixAuthorityRoot,
2952
+ planDigest: plan.planDigest,
2953
+ planIssuedAt: plan.issuedAt,
2954
+ planExpiresAt: plan.expiresAt,
2955
+ aggregateReceiptTtlMs: plan.aggregateReceiptTtlMs,
2956
+ planAuthentication: resolved.authentication,
2957
+ reservation,
2958
+ finalization,
2959
+ cellCount: normalizedCells.length,
2960
+ cellResults: normalizedCells,
2961
+ childReceiptRoot: root,
2962
+ decisionCommitmentDigest,
2963
+ decision: derived.decision,
2964
+ reasonCodes: derived.reasonCodes,
2965
+ issuedAt: issued.timestamp,
2966
+ expiresAt: new Date(expiresMs).toISOString(),
2967
+ });
2968
+ const receiptDigest = domainDigest(
2969
+ SKILL_TARGET_MATRIX_EVAL_RECEIPT_SCHEMA,
2970
+ core,
2971
+ "matrix evaluation receipt core",
2972
+ );
2973
+ const rawAttestation = await invokeSupervised(
2974
+ state.composition.supervision,
2975
+ "matrix-receipt-sign",
2976
+ { purpose: RECEIPT_SIGNATURE_PURPOSE, receiptDigest },
2977
+ (signal) =>
2978
+ state.composition.signer.callable(
2979
+ deepFreeze({
2980
+ purpose: RECEIPT_SIGNATURE_PURPOSE,
2981
+ payloadDigest: receiptDigest,
2982
+ }),
2983
+ Object.freeze({ signal }),
2984
+ ),
2985
+ deadlineMs,
2986
+ wallDeadlineAt,
2987
+ );
2988
+ const attestation = normalizeAttestation(
2989
+ rawAttestation,
2990
+ "matrix receipt signer attestation",
2991
+ );
2992
+ if (!sameTrust(attestation, state.composition.receiptTrust)) {
2993
+ throw matrixError(
2994
+ SKILL_TARGET_MATRIX_EVAL_AUTHORITY_FAILED_CODE,
2995
+ "matrix receipt signer used an unexpected trust identity",
2996
+ );
2997
+ }
2998
+ const receipt = verifyMatrixReceiptStructure(
2999
+ deepFreeze({ ...core, receiptDigest, attestation }),
3000
+ state.composition.receiptTrust,
3001
+ MAX_RECEIPT_TTL_MS,
3002
+ );
3003
+ await verifyReceiptSignature(
3004
+ state.composition,
3005
+ receipt.receiptDigest,
3006
+ receipt.attestation,
3007
+ deadlineMs,
3008
+ wallDeadlineAt,
3009
+ "matrix-receipt-post-sign-verify",
3010
+ );
3011
+ const returned = readTrustedClock(state.composition.clock);
3012
+ if (
3013
+ returned.milliseconds >= expiresMs ||
3014
+ NATIVE_MONOTONIC_NOW() >= deadlineMs
3015
+ ) {
3016
+ throw matrixError(
3017
+ SKILL_TARGET_MATRIX_EVAL_DEADLINE_CODE,
3018
+ "matrix receipt expired before its verified snapshot could be returned",
3019
+ );
3020
+ }
3021
+ return receipt;
3022
+ }
3023
+ }
3024
+
3025
+ function captureReceiptVerificationComposition(options) {
3026
+ const receiptTrust = normalizeTrust(
3027
+ options.matrixReceiptTrust,
3028
+ "matrixReceiptTrust",
3029
+ );
3030
+ const signerDescriptor = normalizeDescriptor(
3031
+ options.matrixReceiptSignerDescriptor,
3032
+ "matrixReceiptSignerDescriptor",
3033
+ { operation: "matrix-receipt-sign" },
3034
+ );
3035
+ const verifier = capturePort(
3036
+ options.matrixReceiptVerifier,
3037
+ VERIFY_PORT_KEYS,
3038
+ "verify",
3039
+ "matrixReceiptVerifier",
3040
+ "authorityDescriptor",
3041
+ { operation: "matrix-receipt-verify" },
3042
+ );
3043
+ if (
3044
+ !sameTrust(signerDescriptor.authority, receiptTrust) ||
3045
+ !sameTrust(verifier.descriptor.authority, receiptTrust)
3046
+ ) {
3047
+ throw matrixError(
3048
+ SKILL_TARGET_MATRIX_EVAL_INVALID_CODE,
3049
+ "matrix receipt signer descriptor and verifier must be the exact trust pair",
3050
+ );
3051
+ }
3052
+ const supervisorPolicy = normalizePolicy(
3053
+ options.supervisorPolicy,
3054
+ "supervisorPolicy",
3055
+ );
3056
+ const supervisor = capturePort(
3057
+ options.matrixSupervisor,
3058
+ SUPERVISOR_PORT_KEYS,
3059
+ "run",
3060
+ "matrixSupervisor",
3061
+ "authorityDescriptor",
3062
+ { operation: "matrix-operation-supervise", policy: supervisorPolicy },
3063
+ );
3064
+ const clockPolicy = normalizePolicy(options.clockPolicy, "clockPolicy");
3065
+ const clockPort = capturePort(
3066
+ options.clock,
3067
+ CLOCK_PORT_KEYS,
3068
+ "now",
3069
+ "trustedClock",
3070
+ "authorityDescriptor",
3071
+ { operation: "trusted-time-read", policy: clockPolicy },
3072
+ );
3073
+ const clock = () => clockPort.callable();
3074
+ const supervisionClock = () => normalizeClockResult(clock(), "trusted clock");
3075
+ Object.freeze(clock);
3076
+ Object.freeze(supervisionClock);
3077
+ ensureUniqueCallables([
3078
+ { role: "matrixReceiptVerifier.verify", raw: verifier.raw },
3079
+ { role: "matrixSupervisor.run", raw: supervisor.raw },
3080
+ { role: "trustedClock.now", raw: clockPort.raw },
3081
+ ]);
3082
+ validatePrincipalMatrix([
3083
+ { role: "matrixSigner", trust: signerDescriptor.authority },
3084
+ { role: "matrixVerifier", trust: verifier.descriptor.authority },
3085
+ { role: "matrixSupervisor", trust: supervisor.descriptor.authority },
3086
+ { role: "trustedClock", trust: clockPort.descriptor.authority },
3087
+ ]);
3088
+ const supervision = Object.freeze({
3089
+ run: supervisor.callable,
3090
+ descriptor: supervisor.descriptor,
3091
+ policy: supervisorPolicy,
3092
+ clock: supervisionClock,
3093
+ });
3094
+ return Object.freeze({
3095
+ signerDescriptor,
3096
+ verifier,
3097
+ receiptTrust,
3098
+ clock,
3099
+ clockDescriptor: clockPort.descriptor,
3100
+ supervision,
3101
+ });
3102
+ }
3103
+
3104
+ export class SkillTargetMatrixEvalReceiptVerifier {
3105
+ #state;
3106
+
3107
+ constructor(options) {
3108
+ assertExactRecord(
3109
+ options,
3110
+ RECEIPT_VERIFIER_OPTION_KEYS,
3111
+ "matrix receipt verifier options",
3112
+ );
3113
+ const composition = captureReceiptVerificationComposition(options);
3114
+ const maximumReceiptTtlMs = normalizeInteger(
3115
+ options.maximumReceiptTtlMs,
3116
+ "maximumReceiptTtlMs",
3117
+ { minimum: 1_000, maximum: MAX_RECEIPT_TTL_MS },
3118
+ );
3119
+ const maximumVerificationMs = normalizeInteger(
3120
+ options.maximumVerificationMs,
3121
+ "maximumVerificationMs",
3122
+ { minimum: 100, maximum: 60_000 },
3123
+ );
3124
+ readTrustedClock(composition.clock);
3125
+ this.#state = Object.freeze({
3126
+ composition,
3127
+ maximumReceiptTtlMs,
3128
+ maximumVerificationMs,
3129
+ });
3130
+ RECEIPT_VERIFIER_INSTANCES.add(this);
3131
+ Object.freeze(this);
3132
+ }
3133
+
3134
+ async verify(value, expected) {
3135
+ const entryMonotonicMs = NATIVE_MONOTONIC_NOW();
3136
+ const entryClock = readTrustedClock(this.#state.composition.clock);
3137
+ const maximumDeadlineMs =
3138
+ entryMonotonicMs + this.#state.maximumVerificationMs;
3139
+ // Both attacker-controlled graphs are uniquely snapshotted before the
3140
+ // first await; no later decision reads the caller's mutable objects.
3141
+ const receiptInput = canonicalClone(value, "matrix evaluation receipt");
3142
+ const normalizedExpected = normalizeExpectedReceipt(expected);
3143
+ const receipt = verifyMatrixReceiptStructure(
3144
+ receiptInput,
3145
+ this.#state.composition.receiptTrust,
3146
+ this.#state.maximumReceiptTtlMs,
3147
+ );
3148
+ for (const [key, expectedValue] of Object.entries(normalizedExpected)) {
3149
+ if (receipt[key] !== expectedValue) {
3150
+ throw matrixError(
3151
+ SKILL_TARGET_MATRIX_EVAL_AUTHORITY_FAILED_CODE,
3152
+ `matrix evaluation receipt differs from expected ${key}`,
3153
+ );
3154
+ }
3155
+ }
3156
+ const now = readTrustedClock(this.#state.composition.clock);
3157
+ const issuedMs = new Date(receipt.issuedAt).getTime();
3158
+ const expiresMs = new Date(receipt.expiresAt).getTime();
3159
+ const deadlineMs = Math.min(
3160
+ maximumDeadlineMs,
3161
+ entryMonotonicMs + (expiresMs - entryClock.milliseconds),
3162
+ );
3163
+ if (
3164
+ issuedMs > now.milliseconds + CLOCK_SKEW_MS ||
3165
+ expiresMs <= now.milliseconds
3166
+ ) {
3167
+ throw matrixError(
3168
+ SKILL_TARGET_MATRIX_EVAL_AUTHORITY_FAILED_CODE,
3169
+ "matrix evaluation receipt is stale or future-dated",
3170
+ );
3171
+ }
3172
+ const wallDeadlineAt = new Date(
3173
+ Math.min(
3174
+ expiresMs,
3175
+ entryClock.milliseconds + this.#state.maximumVerificationMs,
3176
+ ),
3177
+ ).toISOString();
3178
+ assertRootDeadline(deadlineMs, "matrix receipt verification");
3179
+ await verifyReceiptSignature(
3180
+ this.#state.composition,
3181
+ receipt.receiptDigest,
3182
+ receipt.attestation,
3183
+ deadlineMs,
3184
+ wallDeadlineAt,
3185
+ "matrix-receipt-external-verify",
3186
+ );
3187
+ const returned = readTrustedClock(this.#state.composition.clock);
3188
+ if (
3189
+ returned.milliseconds >= expiresMs ||
3190
+ NATIVE_MONOTONIC_NOW() >= deadlineMs
3191
+ ) {
3192
+ throw matrixError(
3193
+ SKILL_TARGET_MATRIX_EVAL_DEADLINE_CODE,
3194
+ "matrix receipt expired during verification",
3195
+ );
3196
+ }
3197
+ return receipt;
3198
+ }
3199
+ }
3200
+
3201
+ Object.freeze(SkillTargetMatrixEvalAggregator.prototype);
3202
+ Object.freeze(SkillTargetMatrixEvalReceiptVerifier.prototype);
3203
+
3204
+ export async function evaluateSkillTargetMatrix(aggregator, planRef) {
3205
+ if (!AGGREGATOR_INSTANCES.has(aggregator)) {
3206
+ throw matrixError(
3207
+ SKILL_TARGET_MATRIX_EVAL_INVALID_CODE,
3208
+ "evaluateSkillTargetMatrix requires a branded trusted aggregator",
3209
+ );
3210
+ }
3211
+ return SkillTargetMatrixEvalAggregator.prototype.evaluate.call(
3212
+ aggregator,
3213
+ planRef,
3214
+ );
3215
+ }
3216
+
3217
+ export async function verifySkillTargetMatrixEvalReceipt(
3218
+ verifier,
3219
+ value,
3220
+ expected,
3221
+ ) {
3222
+ if (!RECEIPT_VERIFIER_INSTANCES.has(verifier)) {
3223
+ throw matrixError(
3224
+ SKILL_TARGET_MATRIX_EVAL_INVALID_CODE,
3225
+ "verifySkillTargetMatrixEvalReceipt requires a branded read-only verifier",
3226
+ );
3227
+ }
3228
+ return SkillTargetMatrixEvalReceiptVerifier.prototype.verify.call(
3229
+ verifier,
3230
+ value,
3231
+ expected,
3232
+ );
3233
+ }