@agentplat/mesh-sim 0.3.0-beta.2 → 0.3.0-beta.4

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 (185) hide show
  1. package/README.md +447 -2
  2. package/dist/collective-closed-loop-action.d.ts +80 -0
  3. package/dist/collective-closed-loop-action.d.ts.map +1 -0
  4. package/dist/collective-closed-loop-action.js +471 -0
  5. package/dist/collective-closed-loop-action.js.map +1 -0
  6. package/dist/collective-closed-loop-contracts.d.ts +75 -0
  7. package/dist/collective-closed-loop-contracts.d.ts.map +1 -0
  8. package/dist/collective-closed-loop-contracts.js +420 -0
  9. package/dist/collective-closed-loop-contracts.js.map +1 -0
  10. package/dist/collective-closed-loop-fault-matrix.d.ts +101 -0
  11. package/dist/collective-closed-loop-fault-matrix.d.ts.map +1 -0
  12. package/dist/collective-closed-loop-fault-matrix.js +253 -0
  13. package/dist/collective-closed-loop-fault-matrix.js.map +1 -0
  14. package/dist/collective-closed-loop-recovery.d.ts +70 -0
  15. package/dist/collective-closed-loop-recovery.d.ts.map +1 -0
  16. package/dist/collective-closed-loop-recovery.js +823 -0
  17. package/dist/collective-closed-loop-recovery.js.map +1 -0
  18. package/dist/collective-closed-loop-reference.d.ts +54 -0
  19. package/dist/collective-closed-loop-reference.d.ts.map +1 -0
  20. package/dist/collective-closed-loop-reference.js +1696 -0
  21. package/dist/collective-closed-loop-reference.js.map +1 -0
  22. package/dist/collective-closed-loop-replanning.d.ts +27 -0
  23. package/dist/collective-closed-loop-replanning.d.ts.map +1 -0
  24. package/dist/collective-closed-loop-replanning.js +151 -0
  25. package/dist/collective-closed-loop-replanning.js.map +1 -0
  26. package/dist/collective-closed-loop-resilience-campaign.d.ts +22 -0
  27. package/dist/collective-closed-loop-resilience-campaign.d.ts.map +1 -0
  28. package/dist/collective-closed-loop-resilience-campaign.js +196 -0
  29. package/dist/collective-closed-loop-resilience-campaign.js.map +1 -0
  30. package/dist/collective-closed-loop-resilience-contracts.d.ts +138 -0
  31. package/dist/collective-closed-loop-resilience-contracts.d.ts.map +1 -0
  32. package/dist/collective-closed-loop-resilience-contracts.js +677 -0
  33. package/dist/collective-closed-loop-resilience-contracts.js.map +1 -0
  34. package/dist/collective-closed-loop-runner.d.ts +133 -0
  35. package/dist/collective-closed-loop-runner.d.ts.map +1 -0
  36. package/dist/collective-closed-loop-runner.js +1429 -0
  37. package/dist/collective-closed-loop-runner.js.map +1 -0
  38. package/dist/collective-closed-loop-runtime.d.ts +95 -0
  39. package/dist/collective-closed-loop-runtime.d.ts.map +1 -0
  40. package/dist/collective-closed-loop-runtime.js +1192 -0
  41. package/dist/collective-closed-loop-runtime.js.map +1 -0
  42. package/dist/collective-effect-provenance.d.ts +5 -0
  43. package/dist/collective-effect-provenance.d.ts.map +1 -0
  44. package/dist/collective-effect-provenance.js +32 -0
  45. package/dist/collective-effect-provenance.js.map +1 -0
  46. package/dist/collective-environment.d.ts +49 -0
  47. package/dist/collective-environment.d.ts.map +1 -0
  48. package/dist/collective-environment.js +907 -0
  49. package/dist/collective-environment.js.map +1 -0
  50. package/dist/collective-progressive-scale-overlay.d.ts +39 -0
  51. package/dist/collective-progressive-scale-overlay.d.ts.map +1 -0
  52. package/dist/collective-progressive-scale-overlay.js +147 -0
  53. package/dist/collective-progressive-scale-overlay.js.map +1 -0
  54. package/dist/collective-progressive-scale.d.ts +202 -0
  55. package/dist/collective-progressive-scale.d.ts.map +1 -0
  56. package/dist/collective-progressive-scale.js +755 -0
  57. package/dist/collective-progressive-scale.js.map +1 -0
  58. package/dist/collective-statistical-campaign-aggregation.d.ts +97 -0
  59. package/dist/collective-statistical-campaign-aggregation.d.ts.map +1 -0
  60. package/dist/collective-statistical-campaign-aggregation.js +446 -0
  61. package/dist/collective-statistical-campaign-aggregation.js.map +1 -0
  62. package/dist/collective-statistical-campaign-artifact-stream.d.ts +66 -0
  63. package/dist/collective-statistical-campaign-artifact-stream.d.ts.map +1 -0
  64. package/dist/collective-statistical-campaign-artifact-stream.js +207 -0
  65. package/dist/collective-statistical-campaign-artifact-stream.js.map +1 -0
  66. package/dist/collective-statistical-campaign-bundle.d.ts +151 -0
  67. package/dist/collective-statistical-campaign-bundle.d.ts.map +1 -0
  68. package/dist/collective-statistical-campaign-bundle.js +885 -0
  69. package/dist/collective-statistical-campaign-bundle.js.map +1 -0
  70. package/dist/collective-statistical-campaign-executor.d.ts +131 -0
  71. package/dist/collective-statistical-campaign-executor.d.ts.map +1 -0
  72. package/dist/collective-statistical-campaign-executor.js +856 -0
  73. package/dist/collective-statistical-campaign-executor.js.map +1 -0
  74. package/dist/collective-statistical-campaign-normative-analysis.d.ts +85 -0
  75. package/dist/collective-statistical-campaign-normative-analysis.d.ts.map +1 -0
  76. package/dist/collective-statistical-campaign-normative-analysis.js +483 -0
  77. package/dist/collective-statistical-campaign-normative-analysis.js.map +1 -0
  78. package/dist/collective-statistical-campaign-normative-operation.d.ts +89 -0
  79. package/dist/collective-statistical-campaign-normative-operation.d.ts.map +1 -0
  80. package/dist/collective-statistical-campaign-normative-operation.js +266 -0
  81. package/dist/collective-statistical-campaign-normative-operation.js.map +1 -0
  82. package/dist/collective-statistical-campaign-normative-registry.d.ts +24 -0
  83. package/dist/collective-statistical-campaign-normative-registry.d.ts.map +1 -0
  84. package/dist/collective-statistical-campaign-normative-registry.js +163 -0
  85. package/dist/collective-statistical-campaign-normative-registry.js.map +1 -0
  86. package/dist/collective-statistical-campaign-registered-adapter.d.ts +16 -0
  87. package/dist/collective-statistical-campaign-registered-adapter.d.ts.map +1 -0
  88. package/dist/collective-statistical-campaign-registered-adapter.js +518 -0
  89. package/dist/collective-statistical-campaign-registered-adapter.js.map +1 -0
  90. package/dist/collective-statistical-campaign-scale.d.ts +85 -0
  91. package/dist/collective-statistical-campaign-scale.d.ts.map +1 -0
  92. package/dist/collective-statistical-campaign-scale.js +349 -0
  93. package/dist/collective-statistical-campaign-scale.js.map +1 -0
  94. package/dist/collective-trace-journal.d.ts +20 -0
  95. package/dist/collective-trace-journal.d.ts.map +1 -0
  96. package/dist/collective-trace-journal.js +105 -0
  97. package/dist/collective-trace-journal.js.map +1 -0
  98. package/dist/index.d.ts +25 -0
  99. package/dist/index.d.ts.map +1 -1
  100. package/dist/index.js +25 -0
  101. package/dist/index.js.map +1 -1
  102. package/dist/multi-domain-environment-contracts.d.ts +122 -0
  103. package/dist/multi-domain-environment-contracts.d.ts.map +1 -0
  104. package/dist/multi-domain-environment-contracts.js +14 -0
  105. package/dist/multi-domain-environment-contracts.js.map +1 -0
  106. package/dist/multi-domain-environment-runtime.d.ts +25 -0
  107. package/dist/multi-domain-environment-runtime.d.ts.map +1 -0
  108. package/dist/multi-domain-environment-runtime.js +493 -0
  109. package/dist/multi-domain-environment-runtime.js.map +1 -0
  110. package/dist/multi-domain-environment-validation.d.ts +33 -0
  111. package/dist/multi-domain-environment-validation.d.ts.map +1 -0
  112. package/dist/multi-domain-environment-validation.js +415 -0
  113. package/dist/multi-domain-environment-validation.js.map +1 -0
  114. package/dist/multi-domain-environment.d.ts +4 -0
  115. package/dist/multi-domain-environment.d.ts.map +1 -0
  116. package/dist/multi-domain-environment.js +4 -0
  117. package/dist/multi-domain-environment.js.map +1 -0
  118. package/dist/reducer-scenario.d.ts.map +1 -1
  119. package/dist/reducer-scenario.js +67 -19
  120. package/dist/reducer-scenario.js.map +1 -1
  121. package/dist/scalable-evaluation-contracts.d.ts +835 -0
  122. package/dist/scalable-evaluation-contracts.d.ts.map +1 -0
  123. package/dist/scalable-evaluation-contracts.js +22 -0
  124. package/dist/scalable-evaluation-contracts.js.map +1 -0
  125. package/dist/scalable-evaluation-durability.d.ts +16 -0
  126. package/dist/scalable-evaluation-durability.d.ts.map +1 -0
  127. package/dist/scalable-evaluation-durability.js +339 -0
  128. package/dist/scalable-evaluation-durability.js.map +1 -0
  129. package/dist/scalable-evaluation-evidence.d.ts +93 -0
  130. package/dist/scalable-evaluation-evidence.d.ts.map +1 -0
  131. package/dist/scalable-evaluation-evidence.js +470 -0
  132. package/dist/scalable-evaluation-evidence.js.map +1 -0
  133. package/dist/scalable-evaluation-reference-integrated.d.ts +87 -0
  134. package/dist/scalable-evaluation-reference-integrated.d.ts.map +1 -0
  135. package/dist/scalable-evaluation-reference-integrated.js +1318 -0
  136. package/dist/scalable-evaluation-reference-integrated.js.map +1 -0
  137. package/dist/scalable-evaluation-runner.d.ts +8 -0
  138. package/dist/scalable-evaluation-runner.d.ts.map +1 -0
  139. package/dist/scalable-evaluation-runner.js +1810 -0
  140. package/dist/scalable-evaluation-runner.js.map +1 -0
  141. package/dist/scalable-evaluation-runtime.d.ts +86 -0
  142. package/dist/scalable-evaluation-runtime.d.ts.map +1 -0
  143. package/dist/scalable-evaluation-runtime.js +1310 -0
  144. package/dist/scalable-evaluation-runtime.js.map +1 -0
  145. package/dist/scalable-evaluation-validation.d.ts +59 -0
  146. package/dist/scalable-evaluation-validation.d.ts.map +1 -0
  147. package/dist/scalable-evaluation-validation.js +377 -0
  148. package/dist/scalable-evaluation-validation.js.map +1 -0
  149. package/dist/scalable-evaluation.d.ts +8 -0
  150. package/dist/scalable-evaluation.d.ts.map +1 -0
  151. package/dist/scalable-evaluation.js +8 -0
  152. package/dist/scalable-evaluation.js.map +1 -0
  153. package/dist/sharded-simulation-contracts.d.ts +240 -0
  154. package/dist/sharded-simulation-contracts.d.ts.map +1 -0
  155. package/dist/sharded-simulation-contracts.js +199 -0
  156. package/dist/sharded-simulation-contracts.js.map +1 -0
  157. package/dist/sharded-simulation-runtime.d.ts +64 -0
  158. package/dist/sharded-simulation-runtime.d.ts.map +1 -0
  159. package/dist/sharded-simulation-runtime.js +755 -0
  160. package/dist/sharded-simulation-runtime.js.map +1 -0
  161. package/dist/sharded-simulation-validation.d.ts +10 -0
  162. package/dist/sharded-simulation-validation.d.ts.map +1 -0
  163. package/dist/sharded-simulation-validation.js +250 -0
  164. package/dist/sharded-simulation-validation.js.map +1 -0
  165. package/dist/sharded-simulation.d.ts +46 -0
  166. package/dist/sharded-simulation.d.ts.map +1 -0
  167. package/dist/sharded-simulation.js +32 -0
  168. package/dist/sharded-simulation.js.map +1 -0
  169. package/dist/verified-benchmark-contracts.d.ts +132 -0
  170. package/dist/verified-benchmark-contracts.d.ts.map +1 -0
  171. package/dist/verified-benchmark-contracts.js +2 -0
  172. package/dist/verified-benchmark-contracts.js.map +1 -0
  173. package/dist/verified-benchmark-runtime.d.ts +20 -0
  174. package/dist/verified-benchmark-runtime.d.ts.map +1 -0
  175. package/dist/verified-benchmark-runtime.js +199 -0
  176. package/dist/verified-benchmark-runtime.js.map +1 -0
  177. package/dist/verified-benchmark-validation.d.ts +64 -0
  178. package/dist/verified-benchmark-validation.d.ts.map +1 -0
  179. package/dist/verified-benchmark-validation.js +481 -0
  180. package/dist/verified-benchmark-validation.js.map +1 -0
  181. package/dist/verified-benchmark.d.ts +4 -0
  182. package/dist/verified-benchmark.d.ts.map +1 -0
  183. package/dist/verified-benchmark.js +4 -0
  184. package/dist/verified-benchmark.js.map +1 -0
  185. package/package.json +18 -8
@@ -0,0 +1,1696 @@
1
+ import { createMissionIntentV1, createMissionObservationV1, createPlanFragmentProposalV1, createPlanSelectionPolicyV1, digestPlanningJsonV1, } from '@agentplat/collective-planning';
2
+ import { createDelegationMandateV1, delegationMandateDigestV1, } from '@agentplat/collective-control';
3
+ import { DEFAULT_COLLECTIVE_EVALUATION_LIMITS_V1, createCollectiveEvaluationRegistrationBindingV1, createCollectiveInvariantMonitorPolicyV1, } from '@agentplat/collective-planning/evaluation';
4
+ import { DEFAULT_MESH_CRYPTO_POLICY, createStaticMeshKeyResolver, } from '@agentplat/mesh-crypto';
5
+ import { MESH_SIGNATURE_ALGORITHM } from '@agentplat/mesh-protocol';
6
+ import { CapabilityRegistryV1, INFERENCE_CONTROL_LIMITS_V1, createInferenceControlStateV1, createPolicyRecordV1, negotiateCapabilitiesV1, reduceInferenceControlStateV1, } from '@agentplat/inference-control';
7
+ import { actionDigest, actionInputDigest, controlDigest, scopeDigest, } from '@agentplat/inference-control/tools';
8
+ import { EVIDENCE_TRUST_LIMITS_V1, createEvidenceFusionPolicyV1, createEvidenceTrustStateV1, createTrustEligibilityRequestV1, digestEvidenceFusionPolicyV1, digestScopeV1, digestSubjectV1, reduceEvidenceTrustStateV1, } from '@agentplat/trust';
9
+ import { collectiveDeterministicEnvironmentDigestV1, collectiveHiddenCanaryDigestV1, } from './collective-environment.js';
10
+ import { createCollectiveClosedLoopDefinitionV1 } from './collective-closed-loop-contracts.js';
11
+ import { createCollectiveClosedLoopFaultPlanV1, createCollectiveClosedLoopResilienceDefinitionV1, } from './collective-closed-loop-resilience-contracts.js';
12
+ import { recoverCollectiveClosedLoopAssignmentV1 } from './collective-closed-loop-recovery.js';
13
+ import { createCollectiveClosedLoopRuntimeRunnerV1, runCollectiveClosedLoopMeshRuntimeV1, } from './collective-closed-loop-runtime.js';
14
+ import { createCollectiveClosedLoopEvaluatorV1, createCollectiveClosedLoopFaultMatrixMissionBindingV1, createCollectiveClosedLoopFaultMatrixPortV1, } from './collective-closed-loop-runner.js';
15
+ const MINIMUM_PEERS = 3;
16
+ const MAXIMUM_PEERS = 500;
17
+ const SEED = 11;
18
+ const MAXIMUM_LOGICAL_TIME_MS = 5_000;
19
+ // The reference mandate remains inside its two-day validity window. Recovery
20
+ // derives the safe takeover point from the issued lease, whose logical expiry
21
+ // can be far beyond the compact nominal planning window.
22
+ const MAXIMUM_RESILIENCE_LOGICAL_TIME_MS = 86_400_000;
23
+ const VALID_FROM = '2026-08-01T00:00:00.000Z';
24
+ const VALID_UNTIL = '2026-08-03T00:00:00.000Z';
25
+ const ACTION_CLASS = 'publish-result';
26
+ const HIDDEN_CANARY = 'closed-loop-reference-private-canary-v1';
27
+ const ACTION_INPUT = Object.freeze({
28
+ resourceId: 'resource:closed-loop-reference',
29
+ });
30
+ const referenceDecisionPolicies = new WeakMap();
31
+ const referenceRuntimeCache = new Map();
32
+ /**
33
+ * Generates reusable signing handles for deterministic closed-loop replay.
34
+ * Reuse the returned value across scenario factories to retain the same keys.
35
+ */
36
+ export async function createCollectiveClosedLoopReferenceRuntimeV1(peerCount) {
37
+ assertPeerCount(peerCount);
38
+ const cached = referenceRuntimeCache.get(peerCount);
39
+ if (cached !== undefined)
40
+ return cached;
41
+ const pending = createReferenceRuntime(peerCount);
42
+ referenceRuntimeCache.set(peerCount, pending);
43
+ return pending;
44
+ }
45
+ async function createReferenceRuntime(peerCount) {
46
+ const crypto = globalThis.crypto;
47
+ if (!crypto?.subtle)
48
+ throw new TypeError('closed_loop_crypto_unavailable');
49
+ const peerIds = peerIdsFor(peerCount);
50
+ const keyPairs = await Promise.all(peerIds.map(async (peerId) => {
51
+ const keyPair = await crypto.subtle.generateKey(MESH_SIGNATURE_ALGORITHM, true, ['sign', 'verify']);
52
+ if (!('privateKey' in keyPair) || !('publicKey' in keyPair))
53
+ throw new TypeError('closed_loop_key_generation_failed');
54
+ return Object.freeze({ peerId, keyPair });
55
+ }));
56
+ const resolver = createStaticMeshKeyResolver(keyPairs.map(({ peerId, keyPair }) => ({
57
+ tenantId: 'tenant:closed-loop-reference',
58
+ meshId: 'mesh:closed-loop-reference',
59
+ peerId,
60
+ keyId: `key:${peerId}`,
61
+ algorithm: MESH_SIGNATURE_ALGORITHM,
62
+ publicKey: keyPair.publicKey,
63
+ validFrom: VALID_FROM,
64
+ validUntil: VALID_UNTIL,
65
+ status: 'active',
66
+ })));
67
+ const runner = createCollectiveClosedLoopRuntimeRunnerV1({
68
+ resolver,
69
+ privateKeys: Object.fromEntries(keyPairs.map(({ peerId, keyPair }) => [peerId, keyPair.privateKey])),
70
+ crypto,
71
+ cryptoPolicy: DEFAULT_MESH_CRYPTO_POLICY,
72
+ mandateVerification: {
73
+ schemaVersion: 1,
74
+ verifierId: 'verifier:closed-loop-reference',
75
+ verifierVersion: 1,
76
+ issuerId: peerIds[0],
77
+ signedDigest: zeroDigest(),
78
+ verifiedAt: VALID_FROM,
79
+ status: 'verified',
80
+ },
81
+ });
82
+ return Object.freeze({ schemaVersion: 1, peerCount, runner });
83
+ }
84
+ /**
85
+ * Compiles a complete nominal Increment 5 execution from a real Mesh
86
+ * allocation preflight. The measured run receives the same public planning
87
+ * inputs and construction-bound crypto handles, so its contract must match the
88
+ * evaluator's exact fenced effect rule.
89
+ */
90
+ export async function createCollectiveClosedLoopReferenceScenarioV1(input) {
91
+ assertRunner(input.runner);
92
+ assertPeerCount(input.peerCount);
93
+ const seed = referenceSeed(input.seed);
94
+ const stratum = referenceStratum(input.stratum);
95
+ const runtimeHandles = input.runtime ??
96
+ (await createCollectiveClosedLoopReferenceRuntimeV1(input.peerCount));
97
+ if (runtimeHandles.schemaVersion !== 1 ||
98
+ runtimeHandles.peerCount !== input.peerCount)
99
+ throw new TypeError('closed_loop_reference_runtime_mismatch');
100
+ const peerIds = peerIdsFor(input.peerCount);
101
+ const peers = peersFor(peerIds);
102
+ const selectionPolicy = selectionPolicyFor();
103
+ const mandate = mandateFor(peerIds);
104
+ const runtime = createCollectiveClosedLoopRuntimeRunnerV1({
105
+ resolver: runtimeHandles.runner.resolver,
106
+ privateKeys: runtimeHandles.runner.privateKeys,
107
+ signer: runtimeHandles.runner.signer,
108
+ crypto: runtimeHandles.runner.crypto,
109
+ cryptoPolicy: runtimeHandles.runner.cryptoPolicy,
110
+ mandateVerification: {
111
+ ...runtimeHandles.runner.mandateVerification,
112
+ issuerId: peerIds[0],
113
+ signedDigest: mandate.mandateDigest,
114
+ verifiedAt: VALID_FROM,
115
+ status: 'verified',
116
+ },
117
+ });
118
+ const missionIntent = missionIntentFor(selectionPolicy.policyDigest, mandate);
119
+ const initialObservations = peerIds.map((peerId, index) => observationFor({
120
+ missionIntent,
121
+ peerId,
122
+ peerInstanceId: peerInstanceId(index),
123
+ cursor: 0,
124
+ phase: 'initial',
125
+ logicalTimeMs: 0,
126
+ }));
127
+ const ownerObservation = initialObservations[0];
128
+ const planningProposal = proposalFor(missionIntent, peerIds[0], peerInstanceId(0), [ownerObservation]);
129
+ const preflight = await runCollectiveClosedLoopMeshRuntimeV1({
130
+ schemaVersion: 1,
131
+ missionIntent,
132
+ selectionPolicy,
133
+ mandate,
134
+ peers,
135
+ observations: initialObservations,
136
+ planningProposal,
137
+ planningMode: input.runner,
138
+ runner: runtime,
139
+ seed,
140
+ maximumLogicalTimeMs: MAXIMUM_LOGICAL_TIME_MS,
141
+ });
142
+ const actionLogicalTimeMs = preflight.logicalTimeMs + 1;
143
+ const checkpointObservations = peerIds.map((peerId, index) => observationFor({
144
+ missionIntent,
145
+ peerId,
146
+ peerInstanceId: peerInstanceId(index),
147
+ cursor: 1,
148
+ phase: 'checkpoint',
149
+ logicalTimeMs: preflight.logicalTimeMs,
150
+ }));
151
+ const outcomeObservations = peerIds.map((peerId, index) => observationFor({
152
+ missionIntent,
153
+ peerId,
154
+ peerInstanceId: peerInstanceId(index),
155
+ cursor: 2,
156
+ phase: 'outcome',
157
+ logicalTimeMs: actionLogicalTimeMs,
158
+ }));
159
+ const resultDigest = digest({ result: 'closed-loop-reference-committed' });
160
+ const inputDigest = asPlanningDigest(actionInputDigest(ACTION_INPUT));
161
+ const effectId = 'effect:closed-loop-reference';
162
+ const environmentDefinition = {
163
+ schemaVersion: 1,
164
+ environmentId: 'environment:closed-loop-reference',
165
+ observations: [
166
+ ...initialObservations,
167
+ ...checkpointObservations,
168
+ ...outcomeObservations,
169
+ ],
170
+ effectRules: [
171
+ {
172
+ schemaVersion: 1,
173
+ effectId,
174
+ workItemId: preflight.workContract.assignment.workItemId,
175
+ workItemRevision: preflight.workContract.assignment.workItemRevision,
176
+ workContractId: preflight.workContract.workContractId,
177
+ workContractDigest: preflight.workContract.workContractDigest,
178
+ peerId: preflight.workContract.assignment.assignedPeerId,
179
+ peerInstanceId: preflight.workContract.assignment.assignedInstanceId,
180
+ assignmentEpoch: preflight.workContract.assignment.assignmentEpoch,
181
+ authorityGeneration: preflight.workContract.assignment.authorityGeneration,
182
+ fencingToken: preflight.workContract.assignment.fencingToken,
183
+ actionClass: ACTION_CLASS,
184
+ inputDigest,
185
+ outputDigest: resultDigest,
186
+ behavior: 'commit',
187
+ rejectionCode: null,
188
+ },
189
+ ],
190
+ hiddenCanary: HIDDEN_CANARY,
191
+ };
192
+ const registrationDigest = digest({
193
+ registration: 'closed-loop-reference',
194
+ runner: input.runner,
195
+ peerCount: input.peerCount,
196
+ seed,
197
+ stratum,
198
+ });
199
+ const monitorPolicy = createCollectiveInvariantMonitorPolicyV1({
200
+ schemaVersion: 1,
201
+ policyId: `monitor:closed-loop-reference:${input.runner}`,
202
+ registrationDigest,
203
+ requiredEffects: [
204
+ { schemaVersion: 1, effectId, outcomeUnits: 1, objectiveValue: 1 },
205
+ ],
206
+ hiddenCanaryDigest: collectiveHiddenCanaryDigestV1(HIDDEN_CANARY),
207
+ });
208
+ const observationPolicyDigest = digest({
209
+ observationPolicy: 'peer-local-cursor-v1',
210
+ });
211
+ const registration = createCollectiveEvaluationRegistrationBindingV1({
212
+ schemaVersion: 1,
213
+ registrationId: `registration:closed-loop-reference:${input.runner}`,
214
+ registrationDigest,
215
+ tenantId: missionIntent.tenantId,
216
+ missionIntentId: missionIntent.missionIntentId,
217
+ intentRevision: missionIntent.revision,
218
+ intentDigest: missionIntent.intentDigest,
219
+ runner: input.runner,
220
+ stratum,
221
+ seed,
222
+ environmentDigest: collectiveDeterministicEnvironmentDigestV1(environmentDefinition),
223
+ observationPolicyDigest,
224
+ monitorDigest: monitorPolicy.policyDigest,
225
+ hiddenCanaryDigest: collectiveHiddenCanaryDigestV1(HIDDEN_CANARY),
226
+ limits: DEFAULT_COLLECTIVE_EVALUATION_LIMITS_V1,
227
+ });
228
+ const definition = createCollectiveClosedLoopDefinitionV1({
229
+ schemaVersion: 1,
230
+ registration,
231
+ missionIntent,
232
+ selectionPolicy,
233
+ mandate,
234
+ peers,
235
+ maximumLogicalTimeMs: MAXIMUM_LOGICAL_TIME_MS,
236
+ });
237
+ const evaluator = createCollectiveClosedLoopEvaluatorV1({
238
+ schemaVersion: 1,
239
+ registration,
240
+ monitorPolicy,
241
+ definition: environmentDefinition,
242
+ });
243
+ const decisionPolicy = decisionPolicyFor(observationPolicyDigest, peerIds, missionIntent.planningLimits.maximumCandidateFragments);
244
+ const expectedWorkContractDigest = preflight.workContract.workContractDigest;
245
+ return Object.freeze({
246
+ schemaVersion: 1,
247
+ definition,
248
+ evaluator,
249
+ runtime,
250
+ decisionPolicy,
251
+ actionClass: ACTION_CLASS,
252
+ resultDigest,
253
+ resultSummary: 'The protected reference effect committed successfully.',
254
+ async prepareAction(context) {
255
+ if (context.workContract.workContractDigest !==
256
+ expectedWorkContractDigest ||
257
+ context.winnerPeerId !==
258
+ context.workContract.assignment.assignedPeerId ||
259
+ context.logicalTimeMs !== actionLogicalTimeMs)
260
+ throw new Error('closed_loop_reference_preflight_mismatch');
261
+ return prepareCollectiveClosedLoopReferenceActionV1(context);
262
+ },
263
+ });
264
+ }
265
+ /**
266
+ * Compiles a bounded six-fault reference campaign without issuing an external
267
+ * effect during construction. The Mesh preflight and certificate recovery are
268
+ * deterministic, construction-bound preparation steps; only the runner can
269
+ * subsequently execute the evaluator-owned protected effect.
270
+ */
271
+ export async function createCollectiveClosedLoopResilienceReferenceScenarioV1(input) {
272
+ assertRunner(input.runner);
273
+ assertPeerCount(input.peerCount);
274
+ const seed = referenceSeed(input.seed);
275
+ const stratum = referenceStratum(input.stratum);
276
+ const nominal = await createCollectiveClosedLoopReferenceScenarioV1({
277
+ ...input,
278
+ stratum: 'nominal',
279
+ });
280
+ const nominalDefinition = nominal.definition;
281
+ const peerIds = nominalDefinition.peers.map((peer) => peer.peerId);
282
+ const owner = nominalDefinition.peers[0];
283
+ if (!owner)
284
+ throw new Error('closed_loop_resilience_owner_missing');
285
+ // The runtime's planning round is intentionally bounded to the owner and
286
+ // its direct neighbours. Construct the preflight from that exact observer
287
+ // set as well: the fault-matrix port is cryptographically bound to the
288
+ // pre-effect state later reconstructed by the runner.
289
+ const planningPeerIds = new Set([owner.peerId, ...owner.neighborPeerIds]);
290
+ const planningPeers = nominalDefinition.peers.filter((peer) => planningPeerIds.has(peer.peerId));
291
+ const initialObservations = planningPeers.map((peer) => observationFor({
292
+ missionIntent: nominalDefinition.missionIntent,
293
+ peerId: peer.peerId,
294
+ peerInstanceId: peer.peerInstanceId,
295
+ cursor: 0,
296
+ phase: 'initial',
297
+ logicalTimeMs: 0,
298
+ }));
299
+ const planningProposal = proposalFor(nominalDefinition.missionIntent, owner.peerId, owner.peerInstanceId, [initialObservations[0]]);
300
+ const preflight = await runCollectiveClosedLoopMeshRuntimeV1({
301
+ schemaVersion: 1,
302
+ missionIntent: nominalDefinition.missionIntent,
303
+ selectionPolicy: nominalDefinition.selectionPolicy,
304
+ mandate: nominalDefinition.mandate,
305
+ peers: nominalDefinition.peers,
306
+ observations: initialObservations,
307
+ planningProposal,
308
+ planningMode: input.runner,
309
+ runner: nominal.runtime,
310
+ seed,
311
+ maximumLogicalTimeMs: MAXIMUM_LOGICAL_TIME_MS,
312
+ });
313
+ // A recovery award must bind to a bid that the owner has already recorded.
314
+ // Choosing the next topology member works only when that peer happened to
315
+ // bid; select a distinct registered bidder instead.
316
+ const ownerState = preflight.meshStates[owner.peerId];
317
+ const eligibleBidders = new Set(Object.values(ownerState?.allocation.bidHeads ?? {}).map((bid) => bid.bidderPeerId));
318
+ const replacementPeerId = ownerState?.objectives.objectives[nominalDefinition.missionIntent.objective.objectiveId]
319
+ ?.recoveryWitnessPeerIds
320
+ .filter((peerId) => eligibleBidders.has(peerId) &&
321
+ peerId !== preflight.winnerPeerId &&
322
+ peerId !== owner.peerId)
323
+ .sort()[0];
324
+ if (!replacementPeerId)
325
+ throw new RangeError('closed_loop_resilience_replacement_unavailable');
326
+ // Recovery requires a lease-expiry observation. Keep this value in the
327
+ // publicly auditable plan, rather than deriving a hidden future schedule.
328
+ const crashLogicalTimeMs = Math.max(preflight.logicalTimeMs + 4, preflight.execution.leaseExpiresAtLogical + 60_000);
329
+ const faultSchedule = resilienceFaultPlanFor({
330
+ ownerPeerId: owner.peerId,
331
+ failedWinnerPeerId: preflight.winnerPeerId,
332
+ replacementPeerId,
333
+ firstLogicalTimeMs: preflight.logicalTimeMs + 1,
334
+ crashLogicalTimeMs,
335
+ });
336
+ const finalPlannedFault = faultSchedule[faultSchedule.length - 1];
337
+ if (!finalPlannedFault)
338
+ throw new Error('closed_loop_resilience_fault_schedule_missing');
339
+ const recovery = await recoverCollectiveClosedLoopAssignmentV1({
340
+ schemaVersion: 1,
341
+ preEffect: preflight,
342
+ peers: nominalDefinition.peers,
343
+ runner: nominal.runtime,
344
+ missionIntent: nominalDefinition.missionIntent,
345
+ mandate: nominalDefinition.mandate,
346
+ failedWinnerPeerId: preflight.winnerPeerId,
347
+ replacementPeerId,
348
+ // Keep construction in lockstep with the public runner: every scheduled
349
+ // fault is observed before the certificate-backed reassignment begins.
350
+ faultLogicalTimeMs: finalPlannedFault.trigger.logicalTimeMs + 1,
351
+ });
352
+ const actionLogicalTimeMs = recovery.recoveryLogicalTimeMs + 1;
353
+ if (actionLogicalTimeMs > MAXIMUM_RESILIENCE_LOGICAL_TIME_MS)
354
+ throw new RangeError('closed_loop_resilience_logical_time_exceeded');
355
+ const checkpointObservations = planningPeers.map((peer) => observationFor({
356
+ missionIntent: nominalDefinition.missionIntent,
357
+ peerId: peer.peerId,
358
+ peerInstanceId: peer.peerInstanceId,
359
+ cursor: 1,
360
+ phase: 'checkpoint',
361
+ logicalTimeMs: preflight.logicalTimeMs,
362
+ }));
363
+ const outcomeObservations = planningPeers.map((peer) => observationFor({
364
+ missionIntent: nominalDefinition.missionIntent,
365
+ peerId: peer.peerId,
366
+ peerInstanceId: peer.peerInstanceId,
367
+ cursor: 2,
368
+ phase: 'outcome',
369
+ logicalTimeMs: actionLogicalTimeMs,
370
+ }));
371
+ const resultDigest = digest({ result: 'closed-loop-reference-committed' });
372
+ const inputDigest = asPlanningDigest(actionInputDigest(ACTION_INPUT));
373
+ const effectId = 'effect:closed-loop-resilience-reference';
374
+ const environmentDefinition = {
375
+ schemaVersion: 1,
376
+ environmentId: 'environment:closed-loop-resilience-reference',
377
+ observations: [
378
+ ...initialObservations,
379
+ ...checkpointObservations,
380
+ ...outcomeObservations,
381
+ ],
382
+ effectRules: [
383
+ {
384
+ schemaVersion: 1,
385
+ effectId,
386
+ workItemId: recovery.workContract.assignment.workItemId,
387
+ workItemRevision: recovery.workContract.assignment.workItemRevision,
388
+ workContractId: recovery.workContract.workContractId,
389
+ workContractDigest: recovery.workContract.workContractDigest,
390
+ peerId: recovery.workContract.assignment.assignedPeerId,
391
+ peerInstanceId: recovery.workContract.assignment.assignedInstanceId,
392
+ assignmentEpoch: recovery.workContract.assignment.assignmentEpoch,
393
+ authorityGeneration: recovery.workContract.assignment.authorityGeneration,
394
+ fencingToken: recovery.workContract.assignment.fencingToken,
395
+ actionClass: ACTION_CLASS,
396
+ inputDigest,
397
+ outputDigest: resultDigest,
398
+ behavior: 'commit',
399
+ rejectionCode: null,
400
+ },
401
+ ],
402
+ hiddenCanary: HIDDEN_CANARY,
403
+ };
404
+ const registrationDigest = digest({
405
+ registration: 'closed-loop-resilience-reference',
406
+ campaign: 'paired-reference-v1',
407
+ peerCount: input.peerCount,
408
+ seed,
409
+ stratum,
410
+ });
411
+ const monitorPolicy = createCollectiveInvariantMonitorPolicyV1({
412
+ schemaVersion: 1,
413
+ policyId: 'monitor:closed-loop-resilience-reference',
414
+ registrationDigest,
415
+ requiredEffects: [
416
+ { schemaVersion: 1, effectId, outcomeUnits: 1, objectiveValue: 1 },
417
+ ],
418
+ hiddenCanaryDigest: collectiveHiddenCanaryDigestV1(HIDDEN_CANARY),
419
+ });
420
+ const observationPolicyDigest = digest({
421
+ observationPolicy: 'peer-local-cursor-v1',
422
+ });
423
+ const registration = createCollectiveEvaluationRegistrationBindingV1({
424
+ schemaVersion: 1,
425
+ registrationId: `registration:closed-loop-resilience-reference:${input.runner}`,
426
+ registrationDigest,
427
+ tenantId: nominalDefinition.missionIntent.tenantId,
428
+ missionIntentId: nominalDefinition.missionIntent.missionIntentId,
429
+ intentRevision: nominalDefinition.missionIntent.revision,
430
+ intentDigest: nominalDefinition.missionIntent.intentDigest,
431
+ runner: input.runner,
432
+ // The resilience definition wraps a nominal closed-loop definition. The
433
+ // target statistical stratum remains bound by registrationDigest, the
434
+ // fault plan and the outer campaign cell.
435
+ stratum: 'nominal',
436
+ seed,
437
+ environmentDigest: collectiveDeterministicEnvironmentDigestV1(environmentDefinition),
438
+ observationPolicyDigest,
439
+ monitorDigest: monitorPolicy.policyDigest,
440
+ hiddenCanaryDigest: collectiveHiddenCanaryDigestV1(HIDDEN_CANARY),
441
+ limits: DEFAULT_COLLECTIVE_EVALUATION_LIMITS_V1,
442
+ });
443
+ const rebuiltNominalDefinition = createCollectiveClosedLoopDefinitionV1({
444
+ schemaVersion: 1,
445
+ registration,
446
+ missionIntent: nominalDefinition.missionIntent,
447
+ selectionPolicy: nominalDefinition.selectionPolicy,
448
+ mandate: nominalDefinition.mandate,
449
+ peers: nominalDefinition.peers,
450
+ maximumLogicalTimeMs: MAXIMUM_RESILIENCE_LOGICAL_TIME_MS,
451
+ });
452
+ const faultPlan = createCollectiveClosedLoopFaultPlanV1({
453
+ schemaVersion: 1,
454
+ nominalDefinitionDigest: rebuiltNominalDefinition.definitionDigest,
455
+ faults: faultSchedule,
456
+ });
457
+ const definition = createCollectiveClosedLoopResilienceDefinitionV1({
458
+ schemaVersion: 1,
459
+ nominalDefinition: rebuiltNominalDefinition,
460
+ faultPlan,
461
+ maximumEpochs: 2,
462
+ });
463
+ const evaluator = createCollectiveClosedLoopEvaluatorV1({
464
+ schemaVersion: 1,
465
+ registration,
466
+ monitorPolicy,
467
+ definition: environmentDefinition,
468
+ });
469
+ const decisionPolicy = sharedDecisionPolicyFor(input.runtime ?? nominal.runtime, observationPolicyDigest, peerIds, nominalDefinition.missionIntent.planningLimits.maximumCandidateFragments);
470
+ const expectedWorkContractDigest = recovery.workContract.workContractDigest;
471
+ const faultMatrix = resilienceFaultMatrixPortFor({
472
+ preEffect: preflight,
473
+ peerIds,
474
+ ownerPeerId: owner.peerId,
475
+ failedWinnerPeerId: preflight.winnerPeerId,
476
+ replacementPeerId,
477
+ faultPlan: definition.faultPlan.faults,
478
+ seed,
479
+ });
480
+ return Object.freeze({
481
+ schemaVersion: 1,
482
+ definition,
483
+ evaluator,
484
+ runtime: nominal.runtime,
485
+ decisionPolicy,
486
+ faultMatrix,
487
+ replacementPeerId,
488
+ actionClass: ACTION_CLASS,
489
+ resultDigest,
490
+ resultSummary: 'The recovered protected reference effect committed successfully.',
491
+ async prepareAction(context) {
492
+ if (context.workContract.workContractDigest !==
493
+ expectedWorkContractDigest ||
494
+ context.winnerPeerId !==
495
+ recovery.workContract.assignment.assignedPeerId ||
496
+ context.logicalTimeMs !== actionLogicalTimeMs)
497
+ throw new Error('closed_loop_resilience_reference_recovery_mismatch');
498
+ return prepareCollectiveClosedLoopReferenceActionV1(context);
499
+ },
500
+ });
501
+ }
502
+ function resilienceFaultPlanFor(input) {
503
+ const withdrawalAt = input.firstLogicalTimeMs;
504
+ const declineAt = withdrawalAt + 1;
505
+ const crashAt = Math.max(input.crashLogicalTimeMs, declineAt + 2);
506
+ const restartAt = crashAt + 1;
507
+ const partitionAt = restartAt + 1;
508
+ const healAt = partitionAt + 1;
509
+ return Object.freeze([
510
+ {
511
+ schemaVersion: 1,
512
+ faultId: '01-capability-withdrawal',
513
+ family: 'capability.withdraw',
514
+ trigger: {
515
+ schemaVersion: 1,
516
+ kind: 'logical_time',
517
+ logicalTimeMs: withdrawalAt,
518
+ causalEventDigest: null,
519
+ },
520
+ causalPredecessorFaultIds: [],
521
+ links: [],
522
+ targets: [{ schemaVersion: 1, peerId: input.replacementPeerId }],
523
+ },
524
+ {
525
+ schemaVersion: 1,
526
+ faultId: '02-assignment-decline',
527
+ family: 'assignment.decline',
528
+ trigger: {
529
+ schemaVersion: 1,
530
+ kind: 'logical_time',
531
+ logicalTimeMs: declineAt,
532
+ causalEventDigest: null,
533
+ },
534
+ causalPredecessorFaultIds: [],
535
+ links: [],
536
+ targets: [{ schemaVersion: 1, peerId: input.ownerPeerId }],
537
+ },
538
+ {
539
+ schemaVersion: 1,
540
+ faultId: '03-peer-crash',
541
+ family: 'peer.crash',
542
+ trigger: {
543
+ schemaVersion: 1,
544
+ kind: 'logical_time',
545
+ logicalTimeMs: crashAt,
546
+ causalEventDigest: null,
547
+ },
548
+ causalPredecessorFaultIds: [],
549
+ links: [],
550
+ targets: [
551
+ { schemaVersion: 1, peerId: input.failedWinnerPeerId },
552
+ ],
553
+ },
554
+ {
555
+ schemaVersion: 1,
556
+ faultId: '04-peer-restart',
557
+ family: 'peer.restart',
558
+ trigger: {
559
+ schemaVersion: 1,
560
+ kind: 'logical_time',
561
+ logicalTimeMs: restartAt,
562
+ causalEventDigest: null,
563
+ },
564
+ causalPredecessorFaultIds: ['03-peer-crash'],
565
+ links: [],
566
+ targets: [
567
+ { schemaVersion: 1, peerId: input.failedWinnerPeerId },
568
+ ],
569
+ },
570
+ {
571
+ schemaVersion: 1,
572
+ faultId: '05-network-partition',
573
+ family: 'network.partition',
574
+ trigger: {
575
+ schemaVersion: 1,
576
+ kind: 'logical_time',
577
+ logicalTimeMs: partitionAt,
578
+ causalEventDigest: null,
579
+ },
580
+ causalPredecessorFaultIds: [],
581
+ links: [
582
+ {
583
+ schemaVersion: 1,
584
+ fromPeerId: input.ownerPeerId,
585
+ toPeerId: input.replacementPeerId,
586
+ },
587
+ ],
588
+ targets: [],
589
+ },
590
+ {
591
+ schemaVersion: 1,
592
+ faultId: '06-network-heal',
593
+ family: 'network.heal',
594
+ trigger: {
595
+ schemaVersion: 1,
596
+ kind: 'logical_time',
597
+ logicalTimeMs: healAt,
598
+ causalEventDigest: null,
599
+ },
600
+ causalPredecessorFaultIds: ['05-network-partition'],
601
+ links: [
602
+ {
603
+ schemaVersion: 1,
604
+ fromPeerId: input.ownerPeerId,
605
+ toPeerId: input.replacementPeerId,
606
+ },
607
+ ],
608
+ targets: [],
609
+ },
610
+ ]);
611
+ }
612
+ /**
613
+ * The Matrix is a deterministic driver campaign. It proves each scheduled
614
+ * fault was applied and observed without exposing its future schedule to a
615
+ * planning decision context.
616
+ */
617
+ function resilienceFaultMatrixPortFor(input) {
618
+ const fault = (faultId) => {
619
+ const value = input.faultPlan.find((candidate) => candidate.faultId === faultId);
620
+ if (!value)
621
+ throw new Error(`closed_loop_resilience_fault_missing:${faultId}`);
622
+ return value;
623
+ };
624
+ const withdrawal = fault('01-capability-withdrawal');
625
+ const decline = fault('02-assignment-decline');
626
+ const crash = fault('03-peer-crash');
627
+ const restart = fault('04-peer-restart');
628
+ const partition = fault('05-network-partition');
629
+ const heal = fault('06-network-heal');
630
+ const afterRestart = restart.trigger.logicalTimeMs + 1;
631
+ const afterHeal = heal.trigger.logicalTimeMs + 1;
632
+ const maximumLogicalTime = afterHeal;
633
+ const healthyDriverPeerId = input.peerIds.find((peerId) => peerId !== input.failedWinnerPeerId);
634
+ if (!healthyDriverPeerId)
635
+ throw new Error('closed_loop_resilience_fault_driver_missing');
636
+ const event = (eventId, targetPeerId, logicalTime, action, sourcePeerId) => Object.freeze({
637
+ eventId,
638
+ targetPeerId,
639
+ ...(sourcePeerId === undefined
640
+ ? {}
641
+ : { sourcePeerId, scheduledAt: logicalTime }),
642
+ logicalTime,
643
+ priority: 10,
644
+ action,
645
+ });
646
+ const matrixInput = Object.freeze({
647
+ schemaVersion: 1,
648
+ scenario: {
649
+ schemaVersion: 1,
650
+ scenarioId: 'closed-loop-resilience-reference-fault-matrix-v1',
651
+ seed: input.seed,
652
+ prngVersion: 'xorshift32-v1',
653
+ peers: input.peerIds.map((peerId) => ({
654
+ peerId,
655
+ state: {
656
+ capabilityAvailable: true,
657
+ assignmentDeclined: false,
658
+ offerAttempt: 1,
659
+ deliveryCount: 0,
660
+ },
661
+ })),
662
+ links: [
663
+ {
664
+ fromPeerId: input.ownerPeerId,
665
+ toPeerId: input.replacementPeerId,
666
+ latency: 0,
667
+ enabled: true,
668
+ },
669
+ {
670
+ fromPeerId: input.replacementPeerId,
671
+ toPeerId: input.ownerPeerId,
672
+ latency: 0,
673
+ enabled: true,
674
+ },
675
+ {
676
+ fromPeerId: healthyDriverPeerId,
677
+ toPeerId: input.failedWinnerPeerId,
678
+ latency: 0,
679
+ enabled: true,
680
+ },
681
+ ],
682
+ events: [
683
+ event('fault-event:01-capability-withdrawal', input.replacementPeerId, withdrawal.trigger.logicalTimeMs, { kind: 'capability.withdraw' }),
684
+ event('fault-event:02-assignment-decline', input.ownerPeerId, decline.trigger.logicalTimeMs, { kind: 'assignment.decline' }),
685
+ event('reoffer-after-decline', input.ownerPeerId, decline.trigger.logicalTimeMs + 1, {
686
+ kind: 'assignment.reoffer',
687
+ attempt: 2,
688
+ }),
689
+ event('delivery-during-crash', input.failedWinnerPeerId, crash.trigger.logicalTimeMs, { kind: 'delivery' }, healthyDriverPeerId),
690
+ event('delivery-after-restart', input.failedWinnerPeerId, afterRestart, { kind: 'delivery' }, healthyDriverPeerId),
691
+ event('delivery-during-partition', input.replacementPeerId, partition.trigger.logicalTimeMs, { kind: 'delivery' }, input.ownerPeerId),
692
+ event('delivery-after-heal', input.replacementPeerId, afterHeal, { kind: 'delivery' }, input.ownerPeerId),
693
+ ],
694
+ faultPlan: {
695
+ schemaVersion: 1,
696
+ faults: [
697
+ {
698
+ faultId: crash.faultId,
699
+ kind: 'peer.crash',
700
+ peerId: input.failedWinnerPeerId,
701
+ logicalTime: crash.trigger.logicalTimeMs,
702
+ priority: -10,
703
+ },
704
+ {
705
+ faultId: restart.faultId,
706
+ kind: 'peer.resume',
707
+ peerId: input.failedWinnerPeerId,
708
+ logicalTime: restart.trigger.logicalTimeMs,
709
+ priority: -10,
710
+ },
711
+ {
712
+ faultId: partition.faultId,
713
+ kind: 'network.partition',
714
+ links: [
715
+ {
716
+ fromPeerId: input.ownerPeerId,
717
+ toPeerId: input.replacementPeerId,
718
+ },
719
+ ],
720
+ logicalTime: partition.trigger.logicalTimeMs,
721
+ priority: -10,
722
+ },
723
+ {
724
+ faultId: heal.faultId,
725
+ kind: 'network.heal',
726
+ links: [
727
+ {
728
+ fromPeerId: input.ownerPeerId,
729
+ toPeerId: input.replacementPeerId,
730
+ },
731
+ ],
732
+ logicalTime: heal.trigger.logicalTimeMs,
733
+ priority: -10,
734
+ },
735
+ ],
736
+ },
737
+ limits: {
738
+ maximumEvents: 32,
739
+ maximumLogicalTime,
740
+ maximumQueuedEvents: 32,
741
+ maximumStateBytes: 64 * 1024,
742
+ },
743
+ },
744
+ runtime: {
745
+ driverId: 'closed-loop-resilience-reference-domain-v1',
746
+ projectionId: 'closed-loop-resilience-reference-projection-v1',
747
+ reduce({ state, action, }) {
748
+ if (action.kind === 'capability.withdraw')
749
+ return {
750
+ accepted: true,
751
+ state: { ...state, capabilityAvailable: false },
752
+ };
753
+ if (action.kind === 'assignment.decline')
754
+ return {
755
+ accepted: true,
756
+ state: { ...state, assignmentDeclined: true },
757
+ };
758
+ if (action.kind === 'assignment.reoffer')
759
+ return state.assignmentDeclined &&
760
+ action.attempt === state.offerAttempt + 1
761
+ ? {
762
+ accepted: true,
763
+ state: { ...state, offerAttempt: action.attempt },
764
+ }
765
+ : { accepted: false, rejectionCode: 'reoffer_not_causal', state };
766
+ if (action.kind === 'delivery')
767
+ return {
768
+ accepted: true,
769
+ state: { ...state, deliveryCount: state.deliveryCount + 1 },
770
+ };
771
+ throw new TypeError('closed_loop_resilience_unknown_fault_action');
772
+ },
773
+ project(state) {
774
+ return state;
775
+ },
776
+ },
777
+ faults: [
778
+ {
779
+ schemaVersion: 1,
780
+ faultId: withdrawal.faultId,
781
+ family: 'capability.withdraw',
782
+ logicalTime: withdrawal.trigger.logicalTimeMs,
783
+ injection: {
784
+ schemaVersion: 1,
785
+ kind: 'reducer_event',
786
+ eventId: 'fault-event:01-capability-withdrawal',
787
+ },
788
+ causalPredecessorFaultId: null,
789
+ },
790
+ {
791
+ schemaVersion: 1,
792
+ faultId: decline.faultId,
793
+ family: 'assignment.decline',
794
+ logicalTime: decline.trigger.logicalTimeMs,
795
+ injection: {
796
+ schemaVersion: 1,
797
+ kind: 'reducer_event',
798
+ eventId: 'fault-event:02-assignment-decline',
799
+ },
800
+ causalPredecessorFaultId: null,
801
+ reofferEventId: 'reoffer-after-decline',
802
+ declinedOfferAttempt: 1,
803
+ reofferAttempt: 2,
804
+ },
805
+ {
806
+ schemaVersion: 1,
807
+ faultId: crash.faultId,
808
+ family: 'peer.crash',
809
+ logicalTime: crash.trigger.logicalTimeMs,
810
+ injection: {
811
+ schemaVersion: 1,
812
+ kind: 'driver_fault',
813
+ simulationFaultId: crash.faultId,
814
+ },
815
+ causalPredecessorFaultId: null,
816
+ },
817
+ {
818
+ schemaVersion: 1,
819
+ faultId: restart.faultId,
820
+ family: 'peer.restart',
821
+ logicalTime: restart.trigger.logicalTimeMs,
822
+ injection: {
823
+ schemaVersion: 1,
824
+ kind: 'driver_fault',
825
+ simulationFaultId: restart.faultId,
826
+ },
827
+ causalPredecessorFaultId: crash.faultId,
828
+ },
829
+ {
830
+ schemaVersion: 1,
831
+ faultId: partition.faultId,
832
+ family: 'network.partition',
833
+ logicalTime: partition.trigger.logicalTimeMs,
834
+ injection: {
835
+ schemaVersion: 1,
836
+ kind: 'driver_fault',
837
+ simulationFaultId: partition.faultId,
838
+ },
839
+ causalPredecessorFaultId: null,
840
+ },
841
+ {
842
+ schemaVersion: 1,
843
+ faultId: heal.faultId,
844
+ family: 'network.heal',
845
+ logicalTime: heal.trigger.logicalTimeMs,
846
+ injection: {
847
+ schemaVersion: 1,
848
+ kind: 'driver_fault',
849
+ simulationFaultId: heal.faultId,
850
+ },
851
+ causalPredecessorFaultId: partition.faultId,
852
+ },
853
+ ],
854
+ observations: [
855
+ {
856
+ faultId: withdrawal.faultId,
857
+ observe({ trace, }) {
858
+ return (trace.peerStates[input.replacementPeerId]?.capabilityAvailable ===
859
+ false);
860
+ },
861
+ },
862
+ {
863
+ faultId: decline.faultId,
864
+ observe({ trace, }) {
865
+ return trace.peerStates[input.ownerPeerId]?.offerAttempt === 2;
866
+ },
867
+ },
868
+ {
869
+ faultId: crash.faultId,
870
+ observe({ trace, }) {
871
+ return trace.faults.some((record) => record.faultId === crash.faultId &&
872
+ record.affectedEventIds.includes('delivery-during-crash'));
873
+ },
874
+ },
875
+ {
876
+ faultId: restart.faultId,
877
+ observe({ trace, }) {
878
+ return trace.records.some((record) => record.eventId === 'delivery-after-restart' && record.accepted);
879
+ },
880
+ },
881
+ {
882
+ faultId: partition.faultId,
883
+ observe({ trace, }) {
884
+ return trace.faults.some((record) => record.faultId === partition.faultId &&
885
+ record.affectedEventIds.includes('delivery-during-partition'));
886
+ },
887
+ },
888
+ {
889
+ faultId: heal.faultId,
890
+ observe({ trace, }) {
891
+ return trace.records.some((record) => record.eventId === 'delivery-after-heal' && record.accepted);
892
+ },
893
+ },
894
+ ],
895
+ });
896
+ return createCollectiveClosedLoopFaultMatrixPortV1(matrixInput, createCollectiveClosedLoopFaultMatrixMissionBindingV1({
897
+ preEffect: input.preEffect,
898
+ replacementPeerId: input.replacementPeerId,
899
+ }));
900
+ }
901
+ function assertRunner(value) {
902
+ if (value !== 'adaptive_collective' && value !== 'centralized_planner')
903
+ throw new TypeError('closed_loop_reference_runner_invalid');
904
+ }
905
+ function assertPeerCount(value) {
906
+ if (!Number.isSafeInteger(value) ||
907
+ value < MINIMUM_PEERS ||
908
+ value > MAXIMUM_PEERS)
909
+ throw new RangeError('closed_loop_reference_peer_count_invalid');
910
+ }
911
+ function referenceSeed(value) {
912
+ const seed = value ?? SEED;
913
+ if (!Number.isSafeInteger(seed) || seed < 0)
914
+ throw new TypeError('closed_loop_reference_seed_invalid');
915
+ return seed;
916
+ }
917
+ function referenceStratum(value) {
918
+ const stratum = value ?? 'nominal';
919
+ if (!['nominal', 'benign', 'adversarial', 'mixed'].includes(stratum))
920
+ throw new TypeError('closed_loop_reference_stratum_invalid');
921
+ return stratum;
922
+ }
923
+ function peerIdsFor(peerCount) {
924
+ return Object.freeze(Array.from({ length: peerCount }, (_, index) => `peer:${String(index).padStart(3, '0')}`));
925
+ }
926
+ function peerInstanceId(index) {
927
+ return `instance:${String(index).padStart(3, '0')}`;
928
+ }
929
+ function peersFor(peerIds) {
930
+ // The registered 500-peer scale models a sparse mesh, not a 499-way
931
+ // broadcast fanout. The runtime itself accepts at most 32 work recipients,
932
+ // so retaining more discovery neighbors cannot affect the selected set.
933
+ const ownerNeighbors = peerIds.slice(1, 33);
934
+ return Object.freeze(peerIds.map((peerId, index) => Object.freeze({
935
+ schemaVersion: 1,
936
+ peerId,
937
+ peerInstanceId: peerInstanceId(index),
938
+ capabilityKeys: Object.freeze(['capability.execute']),
939
+ neighborPeerIds: Object.freeze(index === 0
940
+ ? [...ownerNeighbors]
941
+ : ownerNeighbors.includes(peerId)
942
+ ? [peerIds[0]]
943
+ : []),
944
+ })));
945
+ }
946
+ function selectionPolicyFor() {
947
+ return createPlanSelectionPolicyV1({
948
+ schemaVersion: 1,
949
+ selectionPolicyId: 'selection:closed-loop-reference',
950
+ revision: 1,
951
+ scoringDimensions: [
952
+ {
953
+ schemaVersion: 1,
954
+ dimension: 'outcome_coverage',
955
+ weight: 1,
956
+ direction: 'maximize',
957
+ },
958
+ ],
959
+ hardConstraintKeys: ['budget'],
960
+ acceptanceScoreThreshold: 1,
961
+ challengeScoreThreshold: 0,
962
+ tieBreakOrder: [
963
+ 'score',
964
+ 'requested_budget_units',
965
+ 'work_deadline',
966
+ 'proposed_at_logical_ms',
967
+ 'proposal_digest',
968
+ ],
969
+ });
970
+ }
971
+ function mandateFor(peerIds) {
972
+ const statement = {
973
+ schemaVersion: 1,
974
+ mandateId: 'mandate:closed-loop-reference',
975
+ tenantId: 'tenant:closed-loop-reference',
976
+ policyDomainId: 'policy-domain:closed-loop-reference',
977
+ issuerId: peerIds[0],
978
+ revision: 1,
979
+ predecessorDigest: null,
980
+ subjectPeerIds: [...peerIds],
981
+ objective: {
982
+ schemaVersion: 1,
983
+ meshId: 'mesh:closed-loop-reference',
984
+ objectiveId: 'objective:closed-loop-reference',
985
+ objectiveDocumentId: 'objective-document:closed-loop-reference',
986
+ minimumObjectiveRevision: 1,
987
+ maximumObjectiveRevision: 1,
988
+ },
989
+ work: {
990
+ schemaVersion: 1,
991
+ workItemIds: [],
992
+ permittedRoleKeys: ['executor'],
993
+ maximumWorkItemRevision: 1,
994
+ },
995
+ permittedCapabilityKeys: ['capability.execute'],
996
+ permittedActions: [
997
+ {
998
+ schemaVersion: 1,
999
+ namespace: 'resources',
1000
+ toolId: 'allocator',
1001
+ operation: 'commit',
1002
+ },
1003
+ ],
1004
+ budget: {
1005
+ schemaVersion: 1,
1006
+ totalBudgetUnits: 10_000,
1007
+ maximumWorkBudgetUnits: 100,
1008
+ maximumActionBudgetUnits: 10,
1009
+ maximumConcurrentWorkReservations: 500,
1010
+ maximumConcurrentActionReservations: 500,
1011
+ reservationLifetimeMs: 60_000,
1012
+ },
1013
+ validFrom: VALID_FROM,
1014
+ validUntil: VALID_UNTIL,
1015
+ roomProvenance: null,
1016
+ evidence: {
1017
+ schemaVersion: 1,
1018
+ redactionPolicyId: 'redaction:closed-loop-reference',
1019
+ retentionClass: 'evaluation',
1020
+ requireDurablePreDispatchEvidence: true,
1021
+ },
1022
+ };
1023
+ const mandateDigest = delegationMandateDigestV1(statement);
1024
+ return createDelegationMandateV1({
1025
+ statement,
1026
+ proof: {
1027
+ schemaVersion: 1,
1028
+ kind: 'local_attestation',
1029
+ issuerId: statement.issuerId,
1030
+ attestorId: 'attestor:closed-loop-reference',
1031
+ attestationId: 'attestation:closed-loop-reference',
1032
+ signedDigest: mandateDigest,
1033
+ },
1034
+ });
1035
+ }
1036
+ function missionIntentFor(selectionPolicyDigest, mandate) {
1037
+ return createMissionIntentV1({
1038
+ schemaVersion: 1,
1039
+ missionIntentId: 'mission:closed-loop-reference',
1040
+ revision: 1,
1041
+ predecessorDigest: null,
1042
+ tenantId: mandate.statement.tenantId,
1043
+ policyDomainId: mandate.statement.policyDomainId,
1044
+ objective: {
1045
+ schemaVersion: 1,
1046
+ meshId: mandate.statement.objective.meshId,
1047
+ objectiveId: mandate.statement.objective.objectiveId,
1048
+ objectiveDocumentId: mandate.statement.objective.objectiveDocumentId,
1049
+ objectiveRevision: 1,
1050
+ acceptedPolicyDigest: digest({ objective: 'closed-loop-reference' }),
1051
+ },
1052
+ mandateDigest: mandate.mandateDigest,
1053
+ outcomeStatements: ['outcome.complete'],
1054
+ permittedResourceClasses: ['resource.compute'],
1055
+ permittedCapabilityKeys: ['capability.execute'],
1056
+ planningLimits: {
1057
+ schemaVersion: 1,
1058
+ maximumCandidateFragments: 32,
1059
+ maximumActiveFragments: 4,
1060
+ maximumFragmentsPerPeer: 4,
1061
+ maximumRevisionsPerSemanticSlot: 8,
1062
+ maximumDependencyDepth: 4,
1063
+ maximumDependencyFanout: 2,
1064
+ maximumCapabilityTerms: 4,
1065
+ maximumOutcomeTerms: 4,
1066
+ maximumProposalBytes: 16_384,
1067
+ maximumSnapshotBytes: 131_072,
1068
+ maximumTraceBytes: 131_072,
1069
+ // The equal-subject shard policy must fund the fixed 10-unit proposal
1070
+ // for every supported peer at the largest registered scale.
1071
+ maximumTotalPlanningBudgetUnits: MAXIMUM_PEERS * 10,
1072
+ maximumFragmentBudgetUnits: 100,
1073
+ budgetShardPolicy: 'equal_mandate_subjects',
1074
+ maximumConcurrentProposals: 4,
1075
+ maximumActiveRoles: 4,
1076
+ proposalLogicalWindowMs: 20,
1077
+ observationLogicalWindowMs: 20,
1078
+ replanningLogicalWindowMs: 20,
1079
+ },
1080
+ selectionPolicyDigest,
1081
+ validFrom: mandate.statement.validFrom,
1082
+ validUntil: mandate.statement.validUntil,
1083
+ });
1084
+ }
1085
+ function observationFor(input) {
1086
+ return createMissionObservationV1({
1087
+ schemaVersion: 1,
1088
+ observationId: `observation:${input.peerId}:${input.phase}:1`,
1089
+ missionIntentId: input.missionIntent.missionIntentId,
1090
+ intentRevision: input.missionIntent.revision,
1091
+ intentDigest: input.missionIntent.intentDigest,
1092
+ observerPeerId: input.peerId,
1093
+ observerInstanceId: input.peerInstanceId,
1094
+ environmentCursor: `cursor:${input.cursor}`,
1095
+ logicalTimeMs: input.logicalTimeMs,
1096
+ visibility: 'public',
1097
+ observationKind: `execution.${input.phase}`,
1098
+ publicValue: {
1099
+ phase: input.phase,
1100
+ available: true,
1101
+ },
1102
+ contentReferenceDigest: null,
1103
+ });
1104
+ }
1105
+ function proposalFor(missionIntent, peerId, peerInstanceId, observations) {
1106
+ return createPlanFragmentProposalV1({
1107
+ schemaVersion: 1,
1108
+ proposalRevision: 1,
1109
+ missionIntentId: missionIntent.missionIntentId,
1110
+ intentRevision: missionIntent.revision,
1111
+ intentDigest: missionIntent.intentDigest,
1112
+ proposerPeerId: peerId,
1113
+ proposerInstanceId: peerInstanceId,
1114
+ semanticSlotKey: 'slot:closed-loop-reference',
1115
+ predecessorFragmentDigest: null,
1116
+ parentFragmentDigests: [],
1117
+ dependencyFragmentDigests: [],
1118
+ outcomeStatements: ['outcome.complete'],
1119
+ roleKey: 'executor',
1120
+ requiredCapabilityKeys: ['capability.execute'],
1121
+ inputReferenceDigest: digest({ input: 'closed-loop-reference' }),
1122
+ basisObservationDigests: observations
1123
+ .map((observation) => observation.observationDigest)
1124
+ .sort(),
1125
+ requestedBudgetUnits: 10,
1126
+ workDeadline: '2026-08-01T02:00:00.000Z',
1127
+ proposedAtLogicalMs: 0,
1128
+ });
1129
+ }
1130
+ function decisionPolicyFor(policyDigest, peerIds, maximumCentralizedObservations) {
1131
+ return Object.freeze({
1132
+ policyId: 'decision-policy:peer-local-reference',
1133
+ policyVersion: 1,
1134
+ policyDigest,
1135
+ decide(context) {
1136
+ if (context.peerId !== 'peer:000')
1137
+ return Object.freeze({
1138
+ schemaVersion: 1,
1139
+ kind: 'abstain',
1140
+ reasonCode: 'local_no_proposal',
1141
+ });
1142
+ const observation = context.observations[0];
1143
+ if (!observation)
1144
+ return Object.freeze({
1145
+ schemaVersion: 1,
1146
+ kind: 'abstain',
1147
+ reasonCode: 'local_observation_missing',
1148
+ });
1149
+ return Object.freeze({
1150
+ schemaVersion: 1,
1151
+ kind: 'proposal',
1152
+ proposal: proposalFor(context.missionIntent, context.peerId, context.peerInstanceId, [observation]),
1153
+ });
1154
+ },
1155
+ decideCentralized(context) {
1156
+ const observedPeers = new Set(context.observations.map((observation) => observation.observerPeerId));
1157
+ if (observedPeers.size !==
1158
+ Math.min(peerIds.length, maximumCentralizedObservations) ||
1159
+ peerIds
1160
+ .slice(0, maximumCentralizedObservations)
1161
+ .some((peerId) => !observedPeers.has(peerId)))
1162
+ return Object.freeze({
1163
+ schemaVersion: 1,
1164
+ kind: 'abstain',
1165
+ reasonCode: 'central_observation_set_incomplete',
1166
+ });
1167
+ const ownerObservation = context.observations.find((observation) => observation.observerPeerId === context.ownerPeerId &&
1168
+ observation.observerInstanceId === context.ownerPeerInstanceId);
1169
+ if (!ownerObservation)
1170
+ return Object.freeze({
1171
+ schemaVersion: 1,
1172
+ kind: 'abstain',
1173
+ reasonCode: 'central_owner_observation_missing',
1174
+ });
1175
+ return Object.freeze({
1176
+ schemaVersion: 1,
1177
+ kind: 'proposal',
1178
+ proposal: proposalFor(context.missionIntent, context.ownerPeerId, context.ownerPeerInstanceId, [ownerObservation]),
1179
+ });
1180
+ },
1181
+ });
1182
+ }
1183
+ function sharedDecisionPolicyFor(runtime, policyDigest, peerIds, maximumCentralizedObservations) {
1184
+ let policies = referenceDecisionPolicies.get(runtime);
1185
+ if (!policies) {
1186
+ policies = new Map();
1187
+ referenceDecisionPolicies.set(runtime, policies);
1188
+ }
1189
+ const key = `${policyDigest}\u0000${peerIds.join('\u0000')}\u0000${maximumCentralizedObservations}`;
1190
+ const existing = policies.get(key);
1191
+ if (existing)
1192
+ return existing;
1193
+ const created = decisionPolicyFor(policyDigest, peerIds, maximumCentralizedObservations);
1194
+ policies.set(key, created);
1195
+ return created;
1196
+ }
1197
+ /** Builds the deterministic governed-action inputs for a current Work Contract. */
1198
+ export function prepareCollectiveClosedLoopReferenceActionV1(context) {
1199
+ const actionBinding = actionBindingFor();
1200
+ const mesh = meshScopeFor(context.workContract);
1201
+ const trust = trustFor(context.workContract, context.logicalTimeMs);
1202
+ const inference = inferenceFor(context.workContract, mesh, actionBinding, context.logicalTimeMs);
1203
+ return Object.freeze({
1204
+ actionBinding,
1205
+ actionInput: ACTION_INPUT,
1206
+ trustState: trust.state,
1207
+ trustRequest: trust.request,
1208
+ inferenceState: inference.state,
1209
+ assessmentRequest: inference.assessmentRequest,
1210
+ assessment: inference.assessment,
1211
+ actionGrant: inference.actionGrant,
1212
+ gatewayId: 'gateway:closed-loop-reference',
1213
+ reservationId: 'reservation:closed-loop-reference',
1214
+ permitId: 'permit:closed-loop-reference',
1215
+ decisionId: 'decision:closed-loop-reference',
1216
+ });
1217
+ }
1218
+ /** Detached public action input used by reference effect rules. */
1219
+ export function collectiveClosedLoopReferenceActionInputV1() {
1220
+ return ACTION_INPUT;
1221
+ }
1222
+ function actionBindingFor() {
1223
+ return Object.freeze({
1224
+ schemaVersion: 1,
1225
+ actionBindingId: 'binding:closed-loop-reference',
1226
+ actionBindingVersion: 1,
1227
+ namespace: 'resources',
1228
+ toolId: 'allocator',
1229
+ operation: 'commit',
1230
+ dispatcherId: 'dispatcher:closed-loop-reference',
1231
+ dispatcherVersion: 1,
1232
+ contextResolverId: 'context:closed-loop-reference',
1233
+ contextResolverVersion: 1,
1234
+ fencingMode: 'downstream_atomic',
1235
+ handlerDigest: controlDigest('handler-binding', {
1236
+ handler: 'closed-loop-reference',
1237
+ }),
1238
+ });
1239
+ }
1240
+ function meshScopeFor(work) {
1241
+ return Object.freeze({
1242
+ schemaVersion: 1,
1243
+ kind: 'coordinated',
1244
+ tenantId: work.tenantId,
1245
+ runId: 'run:closed-loop-reference',
1246
+ agentId: `agent:${work.assignment.assignedPeerId}`,
1247
+ policyId: work.inferencePolicyId,
1248
+ policyVersion: 1,
1249
+ meshId: work.objective.meshId,
1250
+ objectiveId: work.objective.objectiveId,
1251
+ objectiveRevision: work.objective.objectiveRevision,
1252
+ workItemId: work.assignment.workItemId,
1253
+ workItemRevision: work.assignment.workItemRevision,
1254
+ peerId: work.assignment.assignedPeerId,
1255
+ instanceId: work.assignment.assignedInstanceId,
1256
+ assignmentAuthorityId: work.assignment.assignmentAuthorityId,
1257
+ assignmentEpoch: work.assignment.assignmentEpoch,
1258
+ fencingToken: work.assignment.fencingToken,
1259
+ leaseExpiresAtLogicalMs: work.assignment.leaseExpiresAtLogicalMs,
1260
+ authorityGeneration: work.assignment.authorityGeneration,
1261
+ objectiveTerminal: false,
1262
+ workTerminal: false,
1263
+ });
1264
+ }
1265
+ function trustFor(work, logicalTimeMs) {
1266
+ const subject = {
1267
+ schemaVersion: 1,
1268
+ kind: 'peer',
1269
+ peerId: work.assignment.assignedPeerId,
1270
+ };
1271
+ const trustScope = {
1272
+ schemaVersion: 1,
1273
+ kind: 'work',
1274
+ tenantId: work.tenantId,
1275
+ meshId: work.objective.meshId,
1276
+ objectiveId: work.objective.objectiveId,
1277
+ objectiveRevision: work.objective.objectiveRevision,
1278
+ workItemId: work.assignment.workItemId,
1279
+ workItemRevision: work.assignment.workItemRevision,
1280
+ assignmentEpoch: work.assignment.assignmentEpoch,
1281
+ assignmentAuthorityId: work.assignment.assignmentAuthorityId,
1282
+ fencingToken: work.assignment.fencingToken,
1283
+ };
1284
+ const policy = createEvidenceFusionPolicyV1({
1285
+ schemaVersion: 1,
1286
+ policyId: work.trustPolicyId,
1287
+ policyVersion: 1,
1288
+ parentPolicyDigest: null,
1289
+ mode: 'restrict',
1290
+ dimensions: [
1291
+ {
1292
+ dimensionId: 'integrity',
1293
+ priorScoreBasisPoints: 5000,
1294
+ priorWeightBasisPoints: 1,
1295
+ minimumUncertaintyBasisPoints: 0,
1296
+ coverageTargetBasisPoints: 1,
1297
+ decayIntervalMs: 1,
1298
+ decayBasisPointsPerInterval: 1,
1299
+ uncertaintyGrowthBasisPointsPerInterval: 1,
1300
+ minimumRetainedWeightBasisPoints: 1,
1301
+ contradictionUncertaintyBasisPointsPerClaim: 1,
1302
+ maximumContradictionUncertaintyBasisPoints: 1000,
1303
+ degradedScoreAtOrBelowBasisPoints: 2000,
1304
+ degradedUncertaintyAtOrAboveBasisPoints: 8000,
1305
+ },
1306
+ ],
1307
+ criteria: [
1308
+ {
1309
+ criterionId: 'criterion:integrity',
1310
+ dimensionId: 'integrity',
1311
+ satisfiedValueBasisPoints: 10000,
1312
+ violatedValueBasisPoints: 0,
1313
+ inconclusiveValueBasisPoints: null,
1314
+ baseWeightBasisPoints: 1000,
1315
+ maximumClaimWeightBasisPoints: 1000,
1316
+ maximumSourceGroupContributionWeightBasisPoints: 1000,
1317
+ minimumSupportGroups: 1,
1318
+ minimumSupportWeightBasisPoints: 1,
1319
+ minimumContradictionGroups: 1,
1320
+ minimumContradictionWeightBasisPoints: 1,
1321
+ allowClaimSourceAttestation: false,
1322
+ contentRequired: false,
1323
+ quarantineEligible: false,
1324
+ recoveryEligible: false,
1325
+ maximumAgeMs: 10_000,
1326
+ claimAuthority: {
1327
+ allowedSourceRelations: ['subject_self'],
1328
+ allowedBasisReferences: [
1329
+ {
1330
+ kind: 'external',
1331
+ referenceType: 'root',
1332
+ minimumCount: 1,
1333
+ maximumCount: 1,
1334
+ },
1335
+ ],
1336
+ },
1337
+ challengeAuthority: {
1338
+ allowedSourceRelations: ['target_author'],
1339
+ allowedBasisReferences: [
1340
+ {
1341
+ kind: 'external',
1342
+ referenceType: 'root',
1343
+ minimumCount: 1,
1344
+ maximumCount: 1,
1345
+ },
1346
+ ],
1347
+ requireResolvedBasis: true,
1348
+ },
1349
+ challengeResolution: {
1350
+ minimumCorroboratingGroups: 1,
1351
+ minimumCorroboratingWeightBasisPoints: 1,
1352
+ minimumOpposingGroups: 1,
1353
+ minimumOpposingWeightBasisPoints: 1,
1354
+ },
1355
+ },
1356
+ ],
1357
+ sourceBindings: [
1358
+ {
1359
+ sourceId: work.assignment.assignedPeerId,
1360
+ sourceKind: 'peer',
1361
+ dependencyGroupId: 'group:closed-loop-reference',
1362
+ roles: ['challenge', 'claim'],
1363
+ maximumWeightBasisPoints: 1000,
1364
+ validFromLogicalMs: 0,
1365
+ validUntilLogicalMs: MAXIMUM_RESILIENCE_LOGICAL_TIME_MS,
1366
+ },
1367
+ ],
1368
+ dependencyGroups: [
1369
+ {
1370
+ dependencyGroupId: 'group:closed-loop-reference',
1371
+ maximumAttestationWeightPerClaimBasisPoints: 1000,
1372
+ maximumProfileWeightPerDimensionCriterionBasisPoints: 1000,
1373
+ },
1374
+ ],
1375
+ eligibilityRules: [
1376
+ {
1377
+ ruleId: 'permit',
1378
+ maximumProfileAgeMs: MAXIMUM_RESILIENCE_LOGICAL_TIME_MS,
1379
+ requirements: [
1380
+ {
1381
+ dimensionId: 'integrity',
1382
+ minimumScoreBasisPoints: 4000,
1383
+ maximumUncertaintyBasisPoints: 10000,
1384
+ },
1385
+ ],
1386
+ },
1387
+ ],
1388
+ quarantinePolicy: {
1389
+ enabled: false,
1390
+ rules: [],
1391
+ maximumActiveRecords: 1,
1392
+ },
1393
+ recoveryPolicy: { rules: [] },
1394
+ limits: EVIDENCE_TRUST_LIMITS_V1,
1395
+ diagnosticsPolicyId: 'diagnostics:closed-loop-reference',
1396
+ redactionPolicyId: 'redaction:closed-loop-reference',
1397
+ });
1398
+ const policyDigest = digestEvidenceFusionPolicyV1(policy);
1399
+ let state = reduceEvidenceTrustStateV1(createEvidenceTrustStateV1({ stateId: 'trust:closed-loop-reference' }), { schemaVersion: 1, kind: 'policy_registered', policy, logicalTimeMs: 0 }).state;
1400
+ state = reduceEvidenceTrustStateV1(state, {
1401
+ schemaVersion: 1,
1402
+ kind: 'fusion_evaluated',
1403
+ request: {
1404
+ tenantId: trustScope.tenantId,
1405
+ subject,
1406
+ scope: trustScope,
1407
+ policyId: policy.policyId,
1408
+ policyVersion: policy.policyVersion,
1409
+ policyDigest,
1410
+ dependencyBindingDigests: [],
1411
+ },
1412
+ logicalTimeMs: 0,
1413
+ }).state;
1414
+ const fusion = state.fusionDecisions[0];
1415
+ if (!fusion)
1416
+ throw new Error('closed_loop_reference_trust_fusion_missing');
1417
+ state = reduceEvidenceTrustStateV1(state, {
1418
+ schemaVersion: 1,
1419
+ kind: 'profile_evaluated',
1420
+ fusionDecisionId: fusion.fusionDecisionId,
1421
+ fusionDecisionDigest: fusion.fusionDecisionDigest,
1422
+ logicalTimeMs: 0,
1423
+ }).state;
1424
+ const profile = state.profiles[0];
1425
+ const rule = policy.eligibilityRules[0];
1426
+ if (!profile || !rule)
1427
+ throw new Error('closed_loop_reference_trust_profile_missing');
1428
+ if (logicalTimeMs >= rule.maximumProfileAgeMs)
1429
+ throw new RangeError('closed_loop_reference_trust_expired');
1430
+ return {
1431
+ state,
1432
+ request: createTrustEligibilityRequestV1({
1433
+ schemaVersion: 1,
1434
+ tenantId: profile.tenantId,
1435
+ subject: profile.subject,
1436
+ subjectDigest: digestSubjectV1(profile.subject),
1437
+ scope: profile.scope,
1438
+ scopeDigest: digestScopeV1(profile.scope),
1439
+ policyId: profile.policyId,
1440
+ policyVersion: profile.policyVersion,
1441
+ policyDigest: profile.policyDigest,
1442
+ profileId: profile.profileId,
1443
+ profileDigest: profile.profileDigest,
1444
+ maximumProfileAgeMs: rule.maximumProfileAgeMs,
1445
+ requirements: rule.requirements,
1446
+ }),
1447
+ };
1448
+ }
1449
+ function inferenceFor(work, controlScope, actionBinding, logicalTimeMs) {
1450
+ if (controlScope.kind !== 'coordinated')
1451
+ throw new Error('closed_loop_reference_scope_invalid');
1452
+ const registry = new CapabilityRegistryV1();
1453
+ const descriptor = {
1454
+ schemaVersion: 1,
1455
+ capabilityId: 'capability:closed-loop-reference',
1456
+ descriptorVersion: 1,
1457
+ inputInspection: 'full',
1458
+ finalOutputAssessment: 'full',
1459
+ incrementalOutputAssessment: 'none',
1460
+ releaseInterruption: 'local',
1461
+ toolInterception: 'all',
1462
+ messageInterception: 'none',
1463
+ representationAccess: 'opaque',
1464
+ declarationSource: 'wrapper',
1465
+ assurance: 'reference_tested',
1466
+ wrapperId: 'wrapper:closed-loop-reference',
1467
+ wrapperVersion: 1,
1468
+ };
1469
+ const handle = registry.register({
1470
+ descriptor,
1471
+ wrapperInstanceId: 'instance:closed-loop-reference',
1472
+ });
1473
+ const policy = {
1474
+ schemaVersion: 1,
1475
+ policyId: work.inferencePolicyId,
1476
+ policyVersion: 1,
1477
+ parentPolicyDigest: null,
1478
+ mode: 'observe',
1479
+ outputRisk: 'low',
1480
+ checkpoints: ['pre_tool'],
1481
+ requiredCapabilities: [
1482
+ { kind: 'tool_interception', value: 'all' },
1483
+ ],
1484
+ minimumCapabilityAssurance: 'verified',
1485
+ allowedCapabilityBindings: [
1486
+ {
1487
+ schemaVersion: 1,
1488
+ capabilityId: descriptor.capabilityId,
1489
+ descriptorVersion: 1,
1490
+ wrapperId: descriptor.wrapperId,
1491
+ wrapperVersion: 1,
1492
+ descriptorDigest: handle.descriptorDigest,
1493
+ requiredAssurance: 'reference_tested',
1494
+ },
1495
+ ],
1496
+ allowedContextZones: ['user_untrusted'],
1497
+ allowedTransformerBindings: [],
1498
+ allowedActions: [
1499
+ {
1500
+ schemaVersion: 1,
1501
+ namespace: actionBinding.namespace,
1502
+ toolId: actionBinding.toolId,
1503
+ operation: actionBinding.operation,
1504
+ actionBindingId: actionBinding.actionBindingId,
1505
+ minimumActionBindingVersion: 1,
1506
+ },
1507
+ ],
1508
+ allowedMessageChannels: [],
1509
+ assessmentBindings: [
1510
+ {
1511
+ schemaVersion: 1,
1512
+ checkpoint: 'pre_tool',
1513
+ assessorId: 'assessor:closed-loop-reference',
1514
+ assessorVersion: 1,
1515
+ assessorBindingDigest: `sha256:${'1'.repeat(64)}`,
1516
+ maximumResponseBytes: 2048,
1517
+ maximumEvidenceReferences: 1,
1518
+ timeoutMs: 1_000,
1519
+ },
1520
+ ],
1521
+ budgets: { revisions: 0, retries: 0, challenges: 0 },
1522
+ limits: INFERENCE_CONTROL_LIMITS_V1,
1523
+ maximumRunDurationMs: MAXIMUM_RESILIENCE_LOGICAL_TIME_MS,
1524
+ maximumAssessmentTtlMs: 1_000,
1525
+ maximumGrantTtlMs: 1_000,
1526
+ maximumMessagePermitTtlMs: 1_000,
1527
+ exhaustedDisposition: 'deny',
1528
+ coordinatedActionsRequired: true,
1529
+ diagnosticsPolicyId: 'diagnostics:closed-loop-reference',
1530
+ redactionPolicyId: 'redaction:closed-loop-reference',
1531
+ };
1532
+ const policyRecord = createPolicyRecordV1(policy);
1533
+ let state = createInferenceControlStateV1({
1534
+ stateId: 'inference:closed-loop-reference',
1535
+ tenantId: work.tenantId,
1536
+ });
1537
+ const reduce = (value, withRegistry = false) => {
1538
+ const result = reduceInferenceControlStateV1(state, {
1539
+ schemaVersion: 1,
1540
+ expectedStateGeneration: state.stateGeneration,
1541
+ ...value,
1542
+ }, withRegistry ? { capabilityRegistry: registry } : undefined);
1543
+ if (!result.accepted)
1544
+ throw new Error(`closed_loop_reference_inference_${result.reasonCode}`);
1545
+ state = result.state;
1546
+ };
1547
+ reduce({
1548
+ inputId: 'inference:policy:closed-loop-reference',
1549
+ type: 'policy_registered',
1550
+ policy,
1551
+ policyDigest: policyRecord.policyDigest,
1552
+ logicalTimeMs: 0,
1553
+ });
1554
+ const run = {
1555
+ schemaVersion: 1,
1556
+ runId: controlScope.runId,
1557
+ tenantId: controlScope.tenantId,
1558
+ policyDigest: policyRecord.policyDigest,
1559
+ capabilityDescriptorDigest: handle.descriptorDigest,
1560
+ capabilityHandleId: null,
1561
+ scope: controlScope,
1562
+ generation: 1,
1563
+ phase: 'created',
1564
+ createdAtLogicalMs: 0,
1565
+ deadlineAtLogicalMs: logicalTimeMs + 1_000,
1566
+ dispositionCounts: { revisions: 0, retries: 0, challenges: 0 },
1567
+ contextEntryIds: [],
1568
+ assessmentRequestIds: [],
1569
+ assessmentIds: [],
1570
+ streamIds: [],
1571
+ grantIds: [],
1572
+ messageAttemptIds: [],
1573
+ outputDigest: null,
1574
+ releasedBytes: 0,
1575
+ terminalReasonCode: null,
1576
+ };
1577
+ reduce({
1578
+ inputId: 'inference:run:closed-loop-reference',
1579
+ type: 'run_created',
1580
+ run,
1581
+ logicalTimeMs: 0,
1582
+ });
1583
+ const negotiation = negotiateCapabilitiesV1(descriptor, {
1584
+ policyDigest: policyRecord.policyDigest,
1585
+ descriptorDigest: handle.descriptorDigest,
1586
+ mode: policy.mode,
1587
+ checkpoints: policy.checkpoints,
1588
+ requiredCapabilities: policy.requiredCapabilities,
1589
+ minimumCapabilityAssurance: policy.minimumCapabilityAssurance,
1590
+ allowedCapabilityBindings: policy.allowedCapabilityBindings,
1591
+ });
1592
+ reduce({
1593
+ inputId: 'inference:capability:closed-loop-reference',
1594
+ type: 'capability_negotiated',
1595
+ runId: run.runId,
1596
+ capabilityHandleId: handle.capabilityHandleId,
1597
+ descriptorDigest: handle.descriptorDigest,
1598
+ result: negotiation,
1599
+ logicalTimeMs: 0,
1600
+ }, true);
1601
+ const targetDigest = digest({ target: 'action:closed-loop-reference' });
1602
+ const expiresAtLogicalMs = logicalTimeMs + 500;
1603
+ const assessmentRequest = {
1604
+ schemaVersion: 1,
1605
+ assessmentRequestId: 'assessment-request:closed-loop-reference',
1606
+ requestGeneration: 1,
1607
+ runId: run.runId,
1608
+ tenantId: run.tenantId,
1609
+ policyId: policy.policyId,
1610
+ policyVersion: 1,
1611
+ checkpoint: 'pre_tool',
1612
+ assessorId: 'assessor:closed-loop-reference',
1613
+ assessorVersion: 1,
1614
+ targetKind: 'action',
1615
+ targetDigest,
1616
+ contextEntryIds: [],
1617
+ zoneDigest: digest({ zone: 'closed-loop-reference' }),
1618
+ provenanceDigest: digest({ provenance: 'closed-loop-reference' }),
1619
+ scope: controlScope,
1620
+ createdAtLogicalMs: logicalTimeMs,
1621
+ expiresAtLogicalMs,
1622
+ status: 'pending',
1623
+ };
1624
+ const assessment = {
1625
+ schemaVersion: 1,
1626
+ assessmentId: 'assessment:closed-loop-reference',
1627
+ assessmentRequestId: assessmentRequest.assessmentRequestId,
1628
+ requestGeneration: 1,
1629
+ runId: run.runId,
1630
+ tenantId: run.tenantId,
1631
+ policyId: policy.policyId,
1632
+ policyVersion: 1,
1633
+ checkpoint: 'pre_tool',
1634
+ assessorId: assessmentRequest.assessorId,
1635
+ assessorVersion: assessmentRequest.assessorVersion,
1636
+ targetKind: 'action',
1637
+ targetDigest,
1638
+ zoneDigest: assessmentRequest.zoneDigest,
1639
+ provenanceDigest: assessmentRequest.provenanceDigest,
1640
+ scope: controlScope,
1641
+ disposition: 'allow',
1642
+ reasonCodes: ['assessment_required'],
1643
+ uncertaintyBasisPoints: 0,
1644
+ evidenceReferences: [],
1645
+ revisedContent: null,
1646
+ challenge: null,
1647
+ assessedAtLogicalMs: logicalTimeMs,
1648
+ expiresAtLogicalMs,
1649
+ };
1650
+ const provisional = {
1651
+ schemaVersion: 1,
1652
+ grantId: 'grant:closed-loop-reference',
1653
+ runId: run.runId,
1654
+ stateGeneration: state.stateGeneration + 2,
1655
+ scope: controlScope,
1656
+ scopeDigest: scopeDigest(controlScope),
1657
+ namespace: actionBinding.namespace,
1658
+ toolId: actionBinding.toolId,
1659
+ operation: actionBinding.operation,
1660
+ actionBindingId: actionBinding.actionBindingId,
1661
+ actionBindingVersion: actionBinding.actionBindingVersion,
1662
+ handlerDigest: actionBinding.handlerDigest,
1663
+ inputDigest: actionInputDigest(ACTION_INPUT),
1664
+ actionDigest: '',
1665
+ assessmentRequestId: assessmentRequest.assessmentRequestId,
1666
+ assessmentId: assessment.assessmentId,
1667
+ assessmentTargetDigest: targetDigest,
1668
+ idempotencyKey: 'effect:closed-loop-reference',
1669
+ issuedAtLogicalMs: logicalTimeMs,
1670
+ expiresAtLogicalMs,
1671
+ singleUse: true,
1672
+ status: 'issued',
1673
+ reservation: null,
1674
+ };
1675
+ return {
1676
+ state,
1677
+ assessmentRequest,
1678
+ assessment,
1679
+ actionGrant: {
1680
+ ...provisional,
1681
+ actionDigest: actionDigest(provisional, actionBinding),
1682
+ },
1683
+ };
1684
+ }
1685
+ function digest(value) {
1686
+ return digestPlanningJsonV1('environment-state-v1', value);
1687
+ }
1688
+ function asPlanningDigest(value) {
1689
+ if (!/^sha256:[0-9a-f]{64}$/u.test(value))
1690
+ throw new TypeError('closed_loop_reference_digest_invalid');
1691
+ return value;
1692
+ }
1693
+ function zeroDigest() {
1694
+ return `sha256:${'0'.repeat(64)}`;
1695
+ }
1696
+ //# sourceMappingURL=collective-closed-loop-reference.js.map