open-multi-agent-kit 1.0.0 → 1.2.0

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 (244) hide show
  1. package/CHANGELOG.md +6 -1
  2. package/README.md +2 -2
  3. package/dist/cli/help.d.ts.map +1 -1
  4. package/dist/cli/help.js +1 -0
  5. package/dist/cli/help.js.map +1 -1
  6. package/dist/coordination/awareness.d.ts +32 -0
  7. package/dist/coordination/awareness.d.ts.map +1 -0
  8. package/dist/coordination/awareness.js +55 -0
  9. package/dist/coordination/awareness.js.map +1 -0
  10. package/dist/coordination/broker.d.ts +79 -0
  11. package/dist/coordination/broker.d.ts.map +1 -0
  12. package/dist/coordination/broker.js +195 -0
  13. package/dist/coordination/broker.js.map +1 -0
  14. package/dist/coordination/index.d.ts +16 -0
  15. package/dist/coordination/index.d.ts.map +1 -0
  16. package/dist/coordination/index.js +16 -0
  17. package/dist/coordination/index.js.map +1 -0
  18. package/dist/coordination/integration.d.ts +59 -0
  19. package/dist/coordination/integration.d.ts.map +1 -0
  20. package/dist/coordination/integration.js +126 -0
  21. package/dist/coordination/integration.js.map +1 -0
  22. package/dist/coordination/operation.d.ts +106 -0
  23. package/dist/coordination/operation.d.ts.map +1 -0
  24. package/dist/coordination/operation.js +179 -0
  25. package/dist/coordination/operation.js.map +1 -0
  26. package/dist/coordination/resource.d.ts +33 -0
  27. package/dist/coordination/resource.d.ts.map +1 -0
  28. package/dist/coordination/resource.js +89 -0
  29. package/dist/coordination/resource.js.map +1 -0
  30. package/dist/coordination/session.d.ts +74 -0
  31. package/dist/coordination/session.d.ts.map +1 -0
  32. package/dist/coordination/session.js +143 -0
  33. package/dist/coordination/session.js.map +1 -0
  34. package/dist/coordination/types.d.ts +68 -0
  35. package/dist/coordination/types.d.ts.map +1 -0
  36. package/dist/coordination/types.js +26 -0
  37. package/dist/coordination/types.js.map +1 -0
  38. package/dist/core/agent-session.d.ts.map +1 -1
  39. package/dist/core/agent-session.js +28 -7
  40. package/dist/core/agent-session.js.map +1 -1
  41. package/dist/core/compaction/control-state.d.ts +41 -0
  42. package/dist/core/compaction/control-state.d.ts.map +1 -0
  43. package/dist/core/compaction/control-state.js +85 -0
  44. package/dist/core/compaction/control-state.js.map +1 -0
  45. package/dist/core/compaction/fallback.d.ts +60 -0
  46. package/dist/core/compaction/fallback.d.ts.map +1 -0
  47. package/dist/core/compaction/fallback.js +117 -0
  48. package/dist/core/compaction/fallback.js.map +1 -0
  49. package/dist/core/compaction/index.d.ts +2 -0
  50. package/dist/core/compaction/index.d.ts.map +1 -1
  51. package/dist/core/compaction/index.js +2 -0
  52. package/dist/core/compaction/index.js.map +1 -1
  53. package/dist/core/context-budget-headroom-candidates.d.ts +16 -1
  54. package/dist/core/context-budget-headroom-candidates.d.ts.map +1 -1
  55. package/dist/core/context-budget-headroom-candidates.js +31 -13
  56. package/dist/core/context-budget-headroom-candidates.js.map +1 -1
  57. package/dist/core/context-budget-headroom-types.d.ts +7 -1
  58. package/dist/core/context-budget-headroom-types.d.ts.map +1 -1
  59. package/dist/core/context-budget-headroom-types.js +0 -1
  60. package/dist/core/context-budget-headroom-types.js.map +1 -1
  61. package/dist/core/context-budget-headroom.d.ts +10 -0
  62. package/dist/core/context-budget-headroom.d.ts.map +1 -1
  63. package/dist/core/context-budget-headroom.js +11 -2
  64. package/dist/core/context-budget-headroom.js.map +1 -1
  65. package/dist/core/context-budget-v2-global-pass.d.ts +21 -0
  66. package/dist/core/context-budget-v2-global-pass.d.ts.map +1 -0
  67. package/dist/core/context-budget-v2-global-pass.js +203 -0
  68. package/dist/core/context-budget-v2-global-pass.js.map +1 -0
  69. package/dist/core/context-budget-v2-planned-items.d.ts +12 -0
  70. package/dist/core/context-budget-v2-planned-items.d.ts.map +1 -1
  71. package/dist/core/context-budget-v2-planned-items.js +21 -2
  72. package/dist/core/context-budget-v2-planned-items.js.map +1 -1
  73. package/dist/core/context-budget-v2-planner.d.ts.map +1 -1
  74. package/dist/core/context-budget-v2-planner.js +18 -19
  75. package/dist/core/context-budget-v2-planner.js.map +1 -1
  76. package/dist/core/context-budget-v2-scoring.d.ts +7 -1
  77. package/dist/core/context-budget-v2-scoring.d.ts.map +1 -1
  78. package/dist/core/context-budget-v2-scoring.js.map +1 -1
  79. package/dist/core/context-budget-v2-selection.d.ts +3 -0
  80. package/dist/core/context-budget-v2-selection.d.ts.map +1 -1
  81. package/dist/core/context-budget-v2-selection.js +6 -2
  82. package/dist/core/context-budget-v2-selection.js.map +1 -1
  83. package/dist/core/context-budget-v2-types.d.ts +6 -1
  84. package/dist/core/context-budget-v2-types.d.ts.map +1 -1
  85. package/dist/core/context-budget-v2-types.js +6 -1
  86. package/dist/core/context-budget-v2-types.js.map +1 -1
  87. package/dist/core/provider-default-models.d.ts +1 -0
  88. package/dist/core/provider-default-models.d.ts.map +1 -1
  89. package/dist/core/provider-default-models.js +1 -0
  90. package/dist/core/provider-default-models.js.map +1 -1
  91. package/dist/core/provider-display-names.d.ts.map +1 -1
  92. package/dist/core/provider-display-names.js +1 -0
  93. package/dist/core/provider-display-names.js.map +1 -1
  94. package/dist/core/reasoning-router-resolver.d.ts +7 -0
  95. package/dist/core/reasoning-router-resolver.d.ts.map +1 -1
  96. package/dist/core/reasoning-router-resolver.js +21 -3
  97. package/dist/core/reasoning-router-resolver.js.map +1 -1
  98. package/dist/core/reasoning-router-v4.d.ts +8 -5
  99. package/dist/core/reasoning-router-v4.d.ts.map +1 -1
  100. package/dist/core/reasoning-router-v4.js +8 -5
  101. package/dist/core/reasoning-router-v4.js.map +1 -1
  102. package/dist/core/session-compaction-service.d.ts +15 -0
  103. package/dist/core/session-compaction-service.d.ts.map +1 -1
  104. package/dist/core/session-compaction-service.js +17 -4
  105. package/dist/core/session-compaction-service.js.map +1 -1
  106. package/dist/core/todo-runtime-state.d.ts +12 -0
  107. package/dist/core/todo-runtime-state.d.ts.map +1 -1
  108. package/dist/core/todo-runtime-state.js +23 -0
  109. package/dist/core/todo-runtime-state.js.map +1 -1
  110. package/dist/index.d.ts +2 -0
  111. package/dist/index.d.ts.map +1 -1
  112. package/dist/index.js +2 -0
  113. package/dist/index.js.map +1 -1
  114. package/dist/metacognition/calibration-selective.d.ts +78 -0
  115. package/dist/metacognition/calibration-selective.d.ts.map +1 -0
  116. package/dist/metacognition/calibration-selective.js +161 -0
  117. package/dist/metacognition/calibration-selective.js.map +1 -0
  118. package/dist/metacognition/calibration.d.ts +62 -0
  119. package/dist/metacognition/calibration.d.ts.map +1 -0
  120. package/dist/metacognition/calibration.js +122 -0
  121. package/dist/metacognition/calibration.js.map +1 -0
  122. package/dist/metacognition/checkpoint.d.ts +60 -0
  123. package/dist/metacognition/checkpoint.d.ts.map +1 -0
  124. package/dist/metacognition/checkpoint.js +57 -0
  125. package/dist/metacognition/checkpoint.js.map +1 -0
  126. package/dist/metacognition/context7.d.ts +48 -0
  127. package/dist/metacognition/context7.d.ts.map +1 -0
  128. package/dist/metacognition/context7.js +154 -0
  129. package/dist/metacognition/context7.js.map +1 -0
  130. package/dist/metacognition/decision.d.ts +44 -0
  131. package/dist/metacognition/decision.d.ts.map +1 -0
  132. package/dist/metacognition/decision.js +111 -0
  133. package/dist/metacognition/decision.js.map +1 -0
  134. package/dist/metacognition/evaluation.d.ts +73 -0
  135. package/dist/metacognition/evaluation.d.ts.map +1 -0
  136. package/dist/metacognition/evaluation.js +97 -0
  137. package/dist/metacognition/evaluation.js.map +1 -0
  138. package/dist/metacognition/index.d.ts +31 -0
  139. package/dist/metacognition/index.d.ts.map +1 -0
  140. package/dist/metacognition/index.js +31 -0
  141. package/dist/metacognition/index.js.map +1 -0
  142. package/dist/metacognition/knowledge-action.d.ts +43 -0
  143. package/dist/metacognition/knowledge-action.d.ts.map +1 -0
  144. package/dist/metacognition/knowledge-action.js +60 -0
  145. package/dist/metacognition/knowledge-action.js.map +1 -0
  146. package/dist/metacognition/knowledge.d.ts +84 -0
  147. package/dist/metacognition/knowledge.d.ts.map +1 -0
  148. package/dist/metacognition/knowledge.js +165 -0
  149. package/dist/metacognition/knowledge.js.map +1 -0
  150. package/dist/metacognition/obligations.d.ts +82 -0
  151. package/dist/metacognition/obligations.d.ts.map +1 -0
  152. package/dist/metacognition/obligations.js +139 -0
  153. package/dist/metacognition/obligations.js.map +1 -0
  154. package/dist/metacognition/observation-validity.d.ts +83 -0
  155. package/dist/metacognition/observation-validity.d.ts.map +1 -0
  156. package/dist/metacognition/observation-validity.js +118 -0
  157. package/dist/metacognition/observation-validity.js.map +1 -0
  158. package/dist/metacognition/observe.d.ts +45 -0
  159. package/dist/metacognition/observe.d.ts.map +1 -0
  160. package/dist/metacognition/observe.js +59 -0
  161. package/dist/metacognition/observe.js.map +1 -0
  162. package/dist/metacognition/policy.d.ts +53 -0
  163. package/dist/metacognition/policy.d.ts.map +1 -0
  164. package/dist/metacognition/policy.js +155 -0
  165. package/dist/metacognition/policy.js.map +1 -0
  166. package/dist/metacognition/predictions.d.ts +78 -0
  167. package/dist/metacognition/predictions.d.ts.map +1 -0
  168. package/dist/metacognition/predictions.js +181 -0
  169. package/dist/metacognition/predictions.js.map +1 -0
  170. package/dist/metacognition/retrieval.d.ts +53 -0
  171. package/dist/metacognition/retrieval.d.ts.map +1 -0
  172. package/dist/metacognition/retrieval.js +170 -0
  173. package/dist/metacognition/retrieval.js.map +1 -0
  174. package/dist/metacognition/risk.d.ts +48 -0
  175. package/dist/metacognition/risk.d.ts.map +1 -0
  176. package/dist/metacognition/risk.js +165 -0
  177. package/dist/metacognition/risk.js.map +1 -0
  178. package/dist/metacognition/route-economics.d.ts +95 -0
  179. package/dist/metacognition/route-economics.d.ts.map +1 -0
  180. package/dist/metacognition/route-economics.js +110 -0
  181. package/dist/metacognition/route-economics.js.map +1 -0
  182. package/dist/metacognition/runtime-bridge.d.ts +54 -0
  183. package/dist/metacognition/runtime-bridge.d.ts.map +1 -0
  184. package/dist/metacognition/runtime-bridge.js +140 -0
  185. package/dist/metacognition/runtime-bridge.js.map +1 -0
  186. package/dist/metacognition/skills.d.ts +42 -0
  187. package/dist/metacognition/skills.d.ts.map +1 -0
  188. package/dist/metacognition/skills.js +220 -0
  189. package/dist/metacognition/skills.js.map +1 -0
  190. package/dist/metacognition/state.d.ts +110 -0
  191. package/dist/metacognition/state.d.ts.map +1 -0
  192. package/dist/metacognition/state.js +52 -0
  193. package/dist/metacognition/state.js.map +1 -0
  194. package/dist/metacognition/validation.d.ts +19 -0
  195. package/dist/metacognition/validation.d.ts.map +1 -0
  196. package/dist/metacognition/validation.js +58 -0
  197. package/dist/metacognition/validation.js.map +1 -0
  198. package/dist/metacognition/verification.d.ts +93 -0
  199. package/dist/metacognition/verification.d.ts.map +1 -0
  200. package/dist/metacognition/verification.js +132 -0
  201. package/dist/metacognition/verification.js.map +1 -0
  202. package/dist/metacognition/verifier.d.ts +49 -0
  203. package/dist/metacognition/verifier.d.ts.map +1 -0
  204. package/dist/metacognition/verifier.js +88 -0
  205. package/dist/metacognition/verifier.js.map +1 -0
  206. package/dist/observation/identity.d.ts +14 -0
  207. package/dist/observation/identity.d.ts.map +1 -0
  208. package/dist/observation/identity.js +29 -0
  209. package/dist/observation/identity.js.map +1 -0
  210. package/dist/observation/index.d.ts +13 -0
  211. package/dist/observation/index.d.ts.map +1 -0
  212. package/dist/observation/index.js +13 -0
  213. package/dist/observation/index.js.map +1 -0
  214. package/dist/observation/observe-mode.d.ts +46 -0
  215. package/dist/observation/observe-mode.d.ts.map +1 -0
  216. package/dist/observation/observe-mode.js +83 -0
  217. package/dist/observation/observe-mode.js.map +1 -0
  218. package/dist/observation/store.d.ts +53 -0
  219. package/dist/observation/store.d.ts.map +1 -0
  220. package/dist/observation/store.js +126 -0
  221. package/dist/observation/store.js.map +1 -0
  222. package/dist/observation/types.d.ts +72 -0
  223. package/dist/observation/types.d.ts.map +1 -0
  224. package/dist/observation/types.js +9 -0
  225. package/dist/observation/types.js.map +1 -0
  226. package/dist/observation/view.d.ts +39 -0
  227. package/dist/observation/view.d.ts.map +1 -0
  228. package/dist/observation/view.js +173 -0
  229. package/dist/observation/view.js.map +1 -0
  230. package/docs/metacognition.md +51 -0
  231. package/docs/model-catalog-refresh.md +59 -0
  232. package/docs/providers.md +53 -0
  233. package/docs/runtime-algorithms.md +107 -3
  234. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  235. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  236. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  237. package/examples/extensions/gondolin/package-lock.json +2 -2
  238. package/examples/extensions/gondolin/package.json +1 -1
  239. package/examples/extensions/sandbox/package-lock.json +2 -2
  240. package/examples/extensions/sandbox/package.json +1 -1
  241. package/examples/extensions/with-deps/package-lock.json +2 -2
  242. package/examples/extensions/with-deps/package.json +1 -1
  243. package/npm-shrinkwrap.json +18 -18
  244. package/package.json +6 -6
@@ -0,0 +1,165 @@
1
+ /**
2
+ * Finite-sample risk bounds for automation gating (Jev audit algorithm A4).
3
+ *
4
+ * A point estimate must never widen automation scope. Two failures in a
5
+ * hundred is not "a 2% error rate" — its one-sided 95% Clopper–Pearson upper
6
+ * bound is about 6.2%, and that bound is what a gate reads.
7
+ *
8
+ * Scope: this bounds the failure probability of samples drawn under the stated
9
+ * conditions. It is not a safety guarantee for the next action, and it assumes
10
+ * a fixed policy, a consistent failure event, and adequately independent
11
+ * samples. Three hundred repeated clicks inside one task are not three hundred
12
+ * independent trials; cluster by task or environment instance before using it.
13
+ */
14
+ import { ensure } from "./validation.js";
15
+ const LANCZOS_G = 7;
16
+ const LANCZOS_COEFFICIENTS = [
17
+ 0.999_999_999_999_809_93, 676.520_368_121_885_1, -1259.139_216_722_402_8, 771.323_428_777_653_13,
18
+ -176.615_029_162_140_59, 12.507_343_278_686_905, -0.138_571_095_265_720_12, 9.984_369_578_019_571_6e-6,
19
+ 1.505_632_735_149_311_6e-7,
20
+ ];
21
+ function logGamma(x) {
22
+ if (x < 0.5)
23
+ return Math.log(Math.PI / Math.sin(Math.PI * x)) - logGamma(1 - x);
24
+ const z = x - 1;
25
+ let a = LANCZOS_COEFFICIENTS[0];
26
+ const t = z + LANCZOS_G + 0.5;
27
+ for (const [index, coefficient] of LANCZOS_COEFFICIENTS.entries()) {
28
+ if (index > 0)
29
+ a += coefficient / (z + index);
30
+ }
31
+ return 0.5 * Math.log(2 * Math.PI) + (z + 0.5) * Math.log(t) - t + Math.log(a);
32
+ }
33
+ /** Continued-fraction expansion for the incomplete beta (Lentz's method). */
34
+ function betaContinuedFraction(a, b, x) {
35
+ const maxIterations = 300;
36
+ const epsilon = 3e-16;
37
+ const tiny = 1e-300;
38
+ const qab = a + b;
39
+ const qap = a + 1;
40
+ const qam = a - 1;
41
+ let c = 1;
42
+ let d = 1 - (qab * x) / qap;
43
+ if (Math.abs(d) < tiny)
44
+ d = tiny;
45
+ d = 1 / d;
46
+ let h = d;
47
+ for (let m = 1; m <= maxIterations; m += 1) {
48
+ const m2 = 2 * m;
49
+ let aa = (m * (b - m) * x) / ((qam + m2) * (a + m2));
50
+ d = 1 + aa * d;
51
+ if (Math.abs(d) < tiny)
52
+ d = tiny;
53
+ c = 1 + aa / c;
54
+ if (Math.abs(c) < tiny)
55
+ c = tiny;
56
+ d = 1 / d;
57
+ h *= d * c;
58
+ aa = (-(a + m) * (qab + m) * x) / ((a + m2) * (qap + m2));
59
+ d = 1 + aa * d;
60
+ if (Math.abs(d) < tiny)
61
+ d = tiny;
62
+ c = 1 + aa / c;
63
+ if (Math.abs(c) < tiny)
64
+ c = tiny;
65
+ d = 1 / d;
66
+ const delta = d * c;
67
+ h *= delta;
68
+ if (Math.abs(delta - 1) < epsilon)
69
+ break;
70
+ }
71
+ return h;
72
+ }
73
+ /** Regularized incomplete beta I_x(a,b). */
74
+ export function regularizedIncompleteBeta(a, b, x) {
75
+ if (x <= 0)
76
+ return 0;
77
+ if (x >= 1)
78
+ return 1;
79
+ const front = Math.exp(logGamma(a + b) - logGamma(a) - logGamma(b) + a * Math.log(x) + b * Math.log1p(-x));
80
+ return x < (a + 1) / (a + b + 2)
81
+ ? (front * betaContinuedFraction(a, b, x)) / a
82
+ : 1 - (front * betaContinuedFraction(b, a, 1 - x)) / b;
83
+ }
84
+ /** Inverse of {@link regularizedIncompleteBeta} by bisection; I_x is monotone in x. */
85
+ function betaQuantile(p, a, b) {
86
+ let low = 0;
87
+ let high = 1;
88
+ for (let i = 0; i < 200 && high - low > 1e-15; i += 1) {
89
+ const mid = (low + high) / 2;
90
+ if (regularizedIncompleteBeta(a, b, mid) < p)
91
+ low = mid;
92
+ else
93
+ high = mid;
94
+ }
95
+ return (low + high) / 2;
96
+ }
97
+ function assertAlpha(alpha) {
98
+ ensure(typeof alpha === "number" && Number.isFinite(alpha) && alpha > 0 && alpha < 1, "alpha must be a probability strictly between 0 and 1");
99
+ }
100
+ /**
101
+ * One-sided Clopper–Pearson upper bound on the failure probability.
102
+ *
103
+ * `U(k,n) = Beta⁻¹(1−α; k+1, n−k)` for `0 ≤ k < n`, and `1` when every trial
104
+ * failed. Zero trials is not zero risk: it is absent evidence, so it throws.
105
+ */
106
+ export function clopperPearsonUpperBound(failures, trials, alpha) {
107
+ ensure(Number.isSafeInteger(trials) && trials > 0, "insufficient evidence: trials must be a positive integer");
108
+ ensure(Number.isSafeInteger(failures) && failures >= 0 && failures <= trials, "failures must be an integer in [0, trials]");
109
+ assertAlpha(alpha);
110
+ if (failures === trials)
111
+ return 1;
112
+ return betaQuantile(1 - alpha, failures + 1, trials - failures);
113
+ }
114
+ /** Closed form of {@link clopperPearsonUpperBound} when no trial failed. */
115
+ export function zeroFailureUpperBound(trials, alpha) {
116
+ ensure(Number.isSafeInteger(trials) && trials > 0, "insufficient evidence: trials must be a positive integer");
117
+ assertAlpha(alpha);
118
+ return -Math.expm1(Math.log(alpha) / trials);
119
+ }
120
+ /**
121
+ * Smallest failure-free sample size whose upper bound meets `targetEpsilon`.
122
+ *
123
+ * `n ≥ ⌈log α / log(1−ε)⌉`, then nudged against the bound itself so a
124
+ * floating-point boundary cannot return a sample size that misses the target.
125
+ */
126
+ export function minimumZeroFailureSamples(targetEpsilon, alpha) {
127
+ ensure(typeof targetEpsilon === "number" && Number.isFinite(targetEpsilon) && targetEpsilon > 0 && targetEpsilon < 1, "targetEpsilon must be strictly between 0 and 1");
128
+ assertAlpha(alpha);
129
+ let n = Math.max(1, Math.ceil(Math.log(alpha) / Math.log1p(-targetEpsilon)));
130
+ while (zeroFailureUpperBound(n, alpha) > targetEpsilon)
131
+ n += 1;
132
+ while (n > 1 && zeroFailureUpperBound(n - 1, alpha) <= targetEpsilon)
133
+ n -= 1;
134
+ return n;
135
+ }
136
+ /**
137
+ * Bonferroni split for `thresholds × groups` comparisons on one validation set.
138
+ *
139
+ * Searching many thresholds and reporting the best keeps none of a single
140
+ * interval's nominal guarantee; this is the conservative correction, and it
141
+ * raises the required sample size on purpose.
142
+ */
143
+ export function bonferroniAlpha(alpha, thresholds, groups) {
144
+ assertAlpha(alpha);
145
+ ensure(Number.isSafeInteger(thresholds) && thresholds > 0, "thresholds must be a positive integer");
146
+ ensure(Number.isSafeInteger(groups) && groups > 0, "groups must be a positive integer");
147
+ return alpha / (thresholds * groups);
148
+ }
149
+ /**
150
+ * Union bound over per-step failure risks.
151
+ *
152
+ * Holds without any independence assumption, which is the point: step risks in
153
+ * one task are usually correlated, so multiplying them would understate the
154
+ * whole-task risk.
155
+ */
156
+ export function unionBoundRisk(stepRisks) {
157
+ ensure(Array.isArray(stepRisks) && stepRisks.length > 0, "stepRisks must be a non-empty array");
158
+ let total = 0;
159
+ for (const risk of stepRisks) {
160
+ ensure(typeof risk === "number" && Number.isFinite(risk) && risk >= 0 && risk <= 1, "each step risk must be a probability in [0, 1]");
161
+ total += risk;
162
+ }
163
+ return Math.min(1, total);
164
+ }
165
+ //# sourceMappingURL=risk.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"risk.js","sourceRoot":"","sources":["../../src/metacognition/risk.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,EAAE,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AAC;IAC/D,OAAO,CAAC,GAAG,CAAC,IAAI,qBAAqB,CAAC,CAAC,GAAG,CAAC,EAAE,KAAK,CAAC,IAAI,aAAa;QAAE,CAAC,IAAI,CAAC,CAAC;IAC7E,OAAO,CAAC,CAAC;AAAA,CACT;AAED;;;;;;GAMG;AACH,MAAM,UAAU,eAAe,CAAC,KAAa,EAAE,UAAkB,EAAE,MAAc,EAAU;IAC1F,WAAW,CAAC,KAAK,CAAC,CAAC;IACnB,MAAM,CAAC,MAAM,CAAC,aAAa,CAAC,UAAU,CAAC,IAAI,UAAU,GAAG,CAAC,EAAE,uCAAuC,CAAC,CAAC;IACpG,MAAM,CAAC,MAAM,CAAC,aAAa,CAAC,MAAM,CAAC,IAAI,MAAM,GAAG,CAAC,EAAE,mCAAmC,CAAC,CAAC;IACxF,OAAO,KAAK,GAAG,CAAC,UAAU,GAAG,MAAM,CAAC,CAAC;AAAA,CACrC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,cAAc,CAAC,SAA4B,EAAU;IACpE,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,SAAS,CAAC,IAAI,SAAS,CAAC,MAAM,GAAG,CAAC,EAAE,qCAAqC,CAAC,CAAC;IAChG,IAAI,KAAK,GAAG,CAAC,CAAC;IACd,KAAK,MAAM,IAAI,IAAI,SAAS,EAAE,CAAC;QAC9B,MAAM,CACL,OAAO,IAAI,KAAK,QAAQ,IAAI,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC,IAAI,IAAI,IAAI,CAAC,EAC3E,gDAAgD,CAChD,CAAC;QACF,KAAK,IAAI,IAAI,CAAC;IACf,CAAC;IACD,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC;AAAA,CAC1B","sourcesContent":["/**\n * Finite-sample risk bounds for automation gating (Jev audit algorithm A4).\n *\n * A point estimate must never widen automation scope. Two failures in a\n * hundred is not \"a 2% error rate\" — its one-sided 95% Clopper–Pearson upper\n * bound is about 6.2%, and that bound is what a gate reads.\n *\n * Scope: this bounds the failure probability of samples drawn under the stated\n * conditions. It is not a safety guarantee for the next action, and it assumes\n * a fixed policy, a consistent failure event, and adequately independent\n * samples. Three hundred repeated clicks inside one task are not three hundred\n * independent trials; cluster by task or environment instance before using it.\n */\n\nimport { ensure } from \"./validation.ts\";\n\nconst LANCZOS_G = 7;\nconst LANCZOS_COEFFICIENTS = [\n\t0.999_999_999_999_809_93, 676.520_368_121_885_1, -1259.139_216_722_402_8, 771.323_428_777_653_13,\n\t-176.615_029_162_140_59, 12.507_343_278_686_905, -0.138_571_095_265_720_12, 9.984_369_578_019_571_6e-6,\n\t1.505_632_735_149_311_6e-7,\n] as const;\n\nfunction logGamma(x: number): number {\n\tif (x < 0.5) return Math.log(Math.PI / Math.sin(Math.PI * x)) - logGamma(1 - x);\n\tconst z = x - 1;\n\tlet a = LANCZOS_COEFFICIENTS[0];\n\tconst t = z + LANCZOS_G + 0.5;\n\tfor (const [index, coefficient] of LANCZOS_COEFFICIENTS.entries()) {\n\t\tif (index > 0) a += coefficient / (z + index);\n\t}\n\treturn 0.5 * Math.log(2 * Math.PI) + (z + 0.5) * Math.log(t) - t + Math.log(a);\n}\n\n/** Continued-fraction expansion for the incomplete beta (Lentz's method). */\nfunction betaContinuedFraction(a: number, b: number, x: number): number {\n\tconst maxIterations = 300;\n\tconst epsilon = 3e-16;\n\tconst tiny = 1e-300;\n\tconst qab = a + b;\n\tconst qap = a + 1;\n\tconst qam = a - 1;\n\tlet c = 1;\n\tlet d = 1 - (qab * x) / qap;\n\tif (Math.abs(d) < tiny) d = tiny;\n\td = 1 / d;\n\tlet h = d;\n\tfor (let m = 1; m <= maxIterations; m += 1) {\n\t\tconst m2 = 2 * m;\n\t\tlet aa = (m * (b - m) * x) / ((qam + m2) * (a + m2));\n\t\td = 1 + aa * d;\n\t\tif (Math.abs(d) < tiny) d = tiny;\n\t\tc = 1 + aa / c;\n\t\tif (Math.abs(c) < tiny) c = tiny;\n\t\td = 1 / d;\n\t\th *= d * c;\n\t\taa = (-(a + m) * (qab + m) * x) / ((a + m2) * (qap + m2));\n\t\td = 1 + aa * d;\n\t\tif (Math.abs(d) < tiny) d = tiny;\n\t\tc = 1 + aa / c;\n\t\tif (Math.abs(c) < tiny) c = tiny;\n\t\td = 1 / d;\n\t\tconst delta = d * c;\n\t\th *= delta;\n\t\tif (Math.abs(delta - 1) < epsilon) break;\n\t}\n\treturn h;\n}\n\n/** Regularized incomplete beta I_x(a,b). */\nexport function regularizedIncompleteBeta(a: number, b: number, x: number): number {\n\tif (x <= 0) return 0;\n\tif (x >= 1) return 1;\n\tconst front = Math.exp(logGamma(a + b) - logGamma(a) - logGamma(b) + a * Math.log(x) + b * Math.log1p(-x));\n\treturn x < (a + 1) / (a + b + 2)\n\t\t? (front * betaContinuedFraction(a, b, x)) / a\n\t\t: 1 - (front * betaContinuedFraction(b, a, 1 - x)) / b;\n}\n\n/** Inverse of {@link regularizedIncompleteBeta} by bisection; I_x is monotone in x. */\nfunction betaQuantile(p: number, a: number, b: number): number {\n\tlet low = 0;\n\tlet high = 1;\n\tfor (let i = 0; i < 200 && high - low > 1e-15; i += 1) {\n\t\tconst mid = (low + high) / 2;\n\t\tif (regularizedIncompleteBeta(a, b, mid) < p) low = mid;\n\t\telse high = mid;\n\t}\n\treturn (low + high) / 2;\n}\n\nfunction assertAlpha(alpha: number): void {\n\tensure(\n\t\ttypeof alpha === \"number\" && Number.isFinite(alpha) && alpha > 0 && alpha < 1,\n\t\t\"alpha must be a probability strictly between 0 and 1\",\n\t);\n}\n\n/**\n * One-sided Clopper–Pearson upper bound on the failure probability.\n *\n * `U(k,n) = Beta⁻¹(1−α; k+1, n−k)` for `0 ≤ k < n`, and `1` when every trial\n * failed. Zero trials is not zero risk: it is absent evidence, so it throws.\n */\nexport function clopperPearsonUpperBound(failures: number, trials: number, alpha: number): number {\n\tensure(Number.isSafeInteger(trials) && trials > 0, \"insufficient evidence: trials must be a positive integer\");\n\tensure(\n\t\tNumber.isSafeInteger(failures) && failures >= 0 && failures <= trials,\n\t\t\"failures must be an integer in [0, trials]\",\n\t);\n\tassertAlpha(alpha);\n\tif (failures === trials) return 1;\n\treturn betaQuantile(1 - alpha, failures + 1, trials - failures);\n}\n\n/** Closed form of {@link clopperPearsonUpperBound} when no trial failed. */\nexport function zeroFailureUpperBound(trials: number, alpha: number): number {\n\tensure(Number.isSafeInteger(trials) && trials > 0, \"insufficient evidence: trials must be a positive integer\");\n\tassertAlpha(alpha);\n\treturn -Math.expm1(Math.log(alpha) / trials);\n}\n\n/**\n * Smallest failure-free sample size whose upper bound meets `targetEpsilon`.\n *\n * `n ≥ ⌈log α / log(1−ε)⌉`, then nudged against the bound itself so a\n * floating-point boundary cannot return a sample size that misses the target.\n */\nexport function minimumZeroFailureSamples(targetEpsilon: number, alpha: number): number {\n\tensure(\n\t\ttypeof targetEpsilon === \"number\" && Number.isFinite(targetEpsilon) && targetEpsilon > 0 && targetEpsilon < 1,\n\t\t\"targetEpsilon must be strictly between 0 and 1\",\n\t);\n\tassertAlpha(alpha);\n\tlet n = Math.max(1, Math.ceil(Math.log(alpha) / Math.log1p(-targetEpsilon)));\n\twhile (zeroFailureUpperBound(n, alpha) > targetEpsilon) n += 1;\n\twhile (n > 1 && zeroFailureUpperBound(n - 1, alpha) <= targetEpsilon) n -= 1;\n\treturn n;\n}\n\n/**\n * Bonferroni split for `thresholds × groups` comparisons on one validation set.\n *\n * Searching many thresholds and reporting the best keeps none of a single\n * interval's nominal guarantee; this is the conservative correction, and it\n * raises the required sample size on purpose.\n */\nexport function bonferroniAlpha(alpha: number, thresholds: number, groups: number): number {\n\tassertAlpha(alpha);\n\tensure(Number.isSafeInteger(thresholds) && thresholds > 0, \"thresholds must be a positive integer\");\n\tensure(Number.isSafeInteger(groups) && groups > 0, \"groups must be a positive integer\");\n\treturn alpha / (thresholds * groups);\n}\n\n/**\n * Union bound over per-step failure risks.\n *\n * Holds without any independence assumption, which is the point: step risks in\n * one task are usually correlated, so multiplying them would understate the\n * whole-task risk.\n */\nexport function unionBoundRisk(stepRisks: readonly number[]): number {\n\tensure(Array.isArray(stepRisks) && stepRisks.length > 0, \"stepRisks must be a non-empty array\");\n\tlet total = 0;\n\tfor (const risk of stepRisks) {\n\t\tensure(\n\t\t\ttypeof risk === \"number\" && Number.isFinite(risk) && risk >= 0 && risk <= 1,\n\t\t\t\"each step risk must be a probability in [0, 1]\",\n\t\t);\n\t\ttotal += risk;\n\t}\n\treturn Math.min(1, total);\n}\n"]}
@@ -0,0 +1,95 @@
1
+ /**
2
+ * Cost- and latency-aware route selection (Jev audit algorithm A5).
3
+ *
4
+ * Adding a selector call only pays if it *replaces* work. Inserting one in
5
+ * front of an existing free-text step adds a semantic inference instead of
6
+ * removing one, so routes are compared on a single utility:
7
+ *
8
+ * U_r = q_r − λ_C·(C_r/C_0) − λ_L·(L_r/L_0)
9
+ *
10
+ * Safety and permission are deliberately not terms in that utility. They are a
11
+ * hard filter, because a cheap unsafe route must never win on weights.
12
+ *
13
+ * Latency is measured over the whole step, not the model call: when operator
14
+ * approval dominates, a faster decision step barely moves the total. Amdahl's
15
+ * bound is included so that limit is explicit rather than assumed away.
16
+ */
17
+ export interface RouteCandidate {
18
+ readonly id: string;
19
+ /** Probability this route completes the step correctly. */
20
+ readonly completionProbability: number;
21
+ readonly costUsd: number;
22
+ readonly latencyMs: number;
23
+ /** Policy and permission verdict. A false value is a veto, not a penalty. */
24
+ readonly approved: boolean;
25
+ }
26
+ export interface RouteUnits {
27
+ readonly costUnit: number;
28
+ readonly latencyUnit: number;
29
+ readonly costWeight: number;
30
+ readonly latencyWeight: number;
31
+ }
32
+ /** Dimensionless utility; cost and latency are normalized before weighting. */
33
+ export declare function routeUtility(route: RouteCandidate, units: RouteUnits): number;
34
+ /**
35
+ * Highest-utility approved route, or null when nothing is approved.
36
+ *
37
+ * Returning null rather than the best unapproved route keeps "we may not do
38
+ * this" distinct from "this is expensive".
39
+ */
40
+ export declare function selectRoute(routes: readonly RouteCandidate[], units: RouteUnits): RouteCandidate | null;
41
+ export interface StepPhases {
42
+ readonly queueMs: number;
43
+ readonly observeMs: number;
44
+ readonly packMs: number;
45
+ readonly decideMs: number;
46
+ readonly approvalMs: number;
47
+ readonly executeMs: number;
48
+ readonly verifyMs: number;
49
+ readonly recoveryMs: number;
50
+ }
51
+ /** Whole-step duration. Model response time is one term among eight. */
52
+ export declare function stepDuration(phases: StepPhases): number;
53
+ /**
54
+ * Amdahl bound: S = 1 / ((1−f) + f/s).
55
+ *
56
+ * `speedup` may be Infinity to ask what an instantaneous step would buy — the
57
+ * answer is still capped by the fraction it occupies, which is the point.
58
+ */
59
+ export declare function overallSpeedup(improvableFraction: number, speedup: number): number;
60
+ export interface FallbackCosts {
61
+ readonly selectorCost: number;
62
+ readonly verificationCost: number;
63
+ readonly fallbackProbability: number;
64
+ readonly fallbackCost: number;
65
+ }
66
+ /**
67
+ * E[C] = c_J + c_V + p_F·c_L.
68
+ *
69
+ * A cost decomposition, not an independence claim. Compare it against the
70
+ * incumbent path's cost under the same success and safety conditions; if it is
71
+ * larger, the cheap path is not cheap.
72
+ */
73
+ export declare function fallbackExpectedCost(costs: FallbackCosts): number;
74
+ export interface ReselectionInput {
75
+ /** Attempts already spent on this observation fingerprint. */
76
+ readonly attemptsForFingerprint: number;
77
+ readonly maxAttempts: number;
78
+ /** True when recovery changed the cause, not merely retried the same question. */
79
+ readonly causeChanged: boolean;
80
+ }
81
+ export type ReselectionDecision = {
82
+ readonly allowed: true;
83
+ } | {
84
+ readonly allowed: false;
85
+ readonly reason: "attempt-budget-exhausted";
86
+ };
87
+ /**
88
+ * Damp selector/model ping-pong on one observation generation.
89
+ *
90
+ * Re-asking the same question about the same state only adds calls. A further
91
+ * attempt is admitted when the budget remains, or when recovery genuinely
92
+ * changed the cause. The budget is a configured value, not a claimed optimum.
93
+ */
94
+ export declare function reselectionAllowed(input: ReselectionInput): ReselectionDecision;
95
+ //# sourceMappingURL=route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M,CAAC;CAC5B;AAED,wEAAwE;AACxE,wBAAgB,YAAY,CAAC,MAAM,EAAE,UAAU,GAAG,MAAM,CAOvD;AAED;;;;;GAKG;AACH,wBAAgB,cAAc,CAAC,kBAAkB,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,MAAM,CASlF;AAED,MAAM,WAAW,aAAa;IAC7B,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAC;IAC9B,QAAQ,CAAC,gBAAgB,EAAE,MAAM,CAAC;IAClC,QAAQ,CAAC,mBAAmB,EAAE,MAAM,CAAC;IACrC,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAC;CAC9B;AAED;;;;;;GAMG;AACH,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,aAAa,GAAG,MAAM,CAYjE;AAED,MAAM,WAAW,gBAAgB;IAChC,8DAA8D;IAC9D,QAAQ,CAAC,sBAAsB,EAAE,MAAM,CAAC;IACxC,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B,kFAAkF;IAClF,QAAQ,CAAC,YAAY,EAAE,OAAO,CAAC;CAC/B;AAED,MAAM,MAAM,mBAAmB,GAC5B;IAAE,QAAQ,CAAC,OAAO,EAAE,IAAI,CAAA;CAAE,GAC1B;IAAE,QAAQ,CAAC,OAAO,EAAE,KAAK,CAAC;IAAC,QAAQ,CAAC,MAAM,EAAE,0BAA0B,CAAA;CAAE,CAAC;AAE5E;;;;;;GAMG;AACH,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,gBAAgB,GAAG,mBAAmB,CAS/E","sourcesContent":["/**\n * Cost- and latency-aware route selection (Jev audit algorithm A5).\n *\n * Adding a selector call only pays if it *replaces* work. Inserting one in\n * front of an existing free-text step adds a semantic inference instead of\n * removing one, so routes are compared on a single utility:\n *\n * U_r = q_r − λ_C·(C_r/C_0) − λ_L·(L_r/L_0)\n *\n * Safety and permission are deliberately not terms in that utility. They are a\n * hard filter, because a cheap unsafe route must never win on weights.\n *\n * Latency is measured over the whole step, not the model call: when operator\n * approval dominates, a faster decision step barely moves the total. Amdahl's\n * bound is included so that limit is explicit rather than assumed away.\n */\n\nimport { ensure } from \"./validation.ts\";\n\nexport interface RouteCandidate {\n\treadonly id: string;\n\t/** Probability this route completes the step correctly. */\n\treadonly completionProbability: number;\n\treadonly costUsd: number;\n\treadonly latencyMs: number;\n\t/** Policy and permission verdict. A false value is a veto, not a penalty. */\n\treadonly approved: boolean;\n}\n\nexport interface RouteUnits {\n\treadonly costUnit: number;\n\treadonly latencyUnit: number;\n\treadonly costWeight: number;\n\treadonly latencyWeight: number;\n}\n\nfunction assertUnits(units: RouteUnits): void {\n\tensure(Number.isFinite(units.costUnit) && units.costUnit > 0, \"costUnit must be positive\");\n\tensure(Number.isFinite(units.latencyUnit) && units.latencyUnit > 0, \"latencyUnit must be positive\");\n\tensure(Number.isFinite(units.costWeight) && units.costWeight >= 0, \"costWeight must be nonnegative\");\n\tensure(Number.isFinite(units.latencyWeight) && units.latencyWeight >= 0, \"latencyWeight must be nonnegative\");\n}\n\n/** Dimensionless utility; cost and latency are normalized before weighting. */\nexport function routeUtility(route: RouteCandidate, units: RouteUnits): number {\n\tensure(\n\t\tNumber.isFinite(route.completionProbability) &&\n\t\t\troute.completionProbability >= 0 &&\n\t\t\troute.completionProbability <= 1,\n\t\t\"completionProbability must be in [0,1]\",\n\t);\n\tensure(Number.isFinite(route.costUsd) && route.costUsd >= 0, \"costUsd must be nonnegative\");\n\tensure(Number.isFinite(route.latencyMs) && route.latencyMs >= 0, \"latencyMs must be nonnegative\");\n\tassertUnits(units);\n\treturn (\n\t\troute.completionProbability -\n\t\tunits.costWeight * (route.costUsd / units.costUnit) -\n\t\tunits.latencyWeight * (route.latencyMs / units.latencyUnit)\n\t);\n}\n\n/**\n * Highest-utility approved route, or null when nothing is approved.\n *\n * Returning null rather than the best unapproved route keeps \"we may not do\n * this\" distinct from \"this is expensive\".\n */\nexport function selectRoute(routes: readonly RouteCandidate[], units: RouteUnits): RouteCandidate | null {\n\tensure(Array.isArray(routes) && routes.length > 0, \"routes must be a non-empty array\");\n\tlet best: RouteCandidate | undefined;\n\tlet bestUtility = Number.NEGATIVE_INFINITY;\n\tfor (const route of routes) {\n\t\tif (!route.approved) continue;\n\t\tconst utility = routeUtility(route, units);\n\t\tconst better = utility > bestUtility || (utility === bestUtility && best !== undefined && route.id < best.id);\n\t\tif (best === undefined || better) {\n\t\t\tbest = route;\n\t\t\tbestUtility = utility;\n\t\t}\n\t}\n\treturn best ?? null;\n}\n\nexport interface StepPhases {\n\treadonly queueMs: number;\n\treadonly observeMs: number;\n\treadonly packMs: number;\n\treadonly decideMs: number;\n\treadonly approvalMs: number;\n\treadonly executeMs: number;\n\treadonly verifyMs: number;\n\treadonly recoveryMs: number;\n}\n\n/** Whole-step duration. Model response time is one term among eight. */\nexport function stepDuration(phases: StepPhases): number {\n\tlet total = 0;\n\tfor (const [label, value] of Object.entries(phases)) {\n\t\tensure(Number.isFinite(value) && value >= 0, `${label} must be a nonnegative finite number`);\n\t\ttotal += value;\n\t}\n\treturn total;\n}\n\n/**\n * Amdahl bound: S = 1 / ((1−f) + f/s).\n *\n * `speedup` may be Infinity to ask what an instantaneous step would buy — the\n * answer is still capped by the fraction it occupies, which is the point.\n */\nexport function overallSpeedup(improvableFraction: number, speedup: number): number {\n\tensure(\n\t\tNumber.isFinite(improvableFraction) && improvableFraction >= 0 && improvableFraction <= 1,\n\t\t\"improvableFraction must be in [0,1]\",\n\t);\n\tensure(typeof speedup === \"number\" && !Number.isNaN(speedup) && speedup >= 1, \"speedup must be at least 1\");\n\tconst remaining = 1 - improvableFraction;\n\tconst improved = speedup === Number.POSITIVE_INFINITY ? 0 : improvableFraction / speedup;\n\treturn 1 / (remaining + improved);\n}\n\nexport interface FallbackCosts {\n\treadonly selectorCost: number;\n\treadonly verificationCost: number;\n\treadonly fallbackProbability: number;\n\treadonly fallbackCost: number;\n}\n\n/**\n * E[C] = c_J + c_V + p_F·c_L.\n *\n * A cost decomposition, not an independence claim. Compare it against the\n * incumbent path's cost under the same success and safety conditions; if it is\n * larger, the cheap path is not cheap.\n */\nexport function fallbackExpectedCost(costs: FallbackCosts): number {\n\tensure(Number.isFinite(costs.selectorCost) && costs.selectorCost >= 0, \"selectorCost must be nonnegative\");\n\tensure(\n\t\tNumber.isFinite(costs.verificationCost) && costs.verificationCost >= 0,\n\t\t\"verificationCost must be nonnegative\",\n\t);\n\tensure(Number.isFinite(costs.fallbackCost) && costs.fallbackCost >= 0, \"fallbackCost must be nonnegative\");\n\tensure(\n\t\tNumber.isFinite(costs.fallbackProbability) && costs.fallbackProbability >= 0 && costs.fallbackProbability <= 1,\n\t\t\"fallbackProbability must be in [0,1]\",\n\t);\n\treturn costs.selectorCost + costs.verificationCost + costs.fallbackProbability * costs.fallbackCost;\n}\n\nexport interface ReselectionInput {\n\t/** Attempts already spent on this observation fingerprint. */\n\treadonly attemptsForFingerprint: number;\n\treadonly maxAttempts: number;\n\t/** True when recovery changed the cause, not merely retried the same question. */\n\treadonly causeChanged: boolean;\n}\n\nexport type ReselectionDecision =\n\t| { readonly allowed: true }\n\t| { readonly allowed: false; readonly reason: \"attempt-budget-exhausted\" };\n\n/**\n * Damp selector/model ping-pong on one observation generation.\n *\n * Re-asking the same question about the same state only adds calls. A further\n * attempt is admitted when the budget remains, or when recovery genuinely\n * changed the cause. The budget is a configured value, not a claimed optimum.\n */\nexport function reselectionAllowed(input: ReselectionInput): ReselectionDecision {\n\tensure(\n\t\tNumber.isSafeInteger(input.attemptsForFingerprint) && input.attemptsForFingerprint >= 0,\n\t\t\"attemptsForFingerprint must be a nonnegative integer\",\n\t);\n\tensure(Number.isSafeInteger(input.maxAttempts) && input.maxAttempts > 0, \"maxAttempts must be a positive integer\");\n\tif (input.causeChanged) return { allowed: true };\n\tif (input.attemptsForFingerprint < input.maxAttempts) return { allowed: true };\n\treturn { allowed: false, reason: \"attempt-budget-exhausted\" };\n}\n"]}
@@ -0,0 +1,110 @@
1
+ /**
2
+ * Cost- and latency-aware route selection (Jev audit algorithm A5).
3
+ *
4
+ * Adding a selector call only pays if it *replaces* work. Inserting one in
5
+ * front of an existing free-text step adds a semantic inference instead of
6
+ * removing one, so routes are compared on a single utility:
7
+ *
8
+ * U_r = q_r − λ_C·(C_r/C_0) − λ_L·(L_r/L_0)
9
+ *
10
+ * Safety and permission are deliberately not terms in that utility. They are a
11
+ * hard filter, because a cheap unsafe route must never win on weights.
12
+ *
13
+ * Latency is measured over the whole step, not the model call: when operator
14
+ * approval dominates, a faster decision step barely moves the total. Amdahl's
15
+ * bound is included so that limit is explicit rather than assumed away.
16
+ */
17
+ import { ensure } from "./validation.js";
18
+ function assertUnits(units) {
19
+ ensure(Number.isFinite(units.costUnit) && units.costUnit > 0, "costUnit must be positive");
20
+ ensure(Number.isFinite(units.latencyUnit) && units.latencyUnit > 0, "latencyUnit must be positive");
21
+ ensure(Number.isFinite(units.costWeight) && units.costWeight >= 0, "costWeight must be nonnegative");
22
+ ensure(Number.isFinite(units.latencyWeight) && units.latencyWeight >= 0, "latencyWeight must be nonnegative");
23
+ }
24
+ /** Dimensionless utility; cost and latency are normalized before weighting. */
25
+ export function routeUtility(route, units) {
26
+ ensure(Number.isFinite(route.completionProbability) &&
27
+ route.completionProbability >= 0 &&
28
+ route.completionProbability <= 1, "completionProbability must be in [0,1]");
29
+ ensure(Number.isFinite(route.costUsd) && route.costUsd >= 0, "costUsd must be nonnegative");
30
+ ensure(Number.isFinite(route.latencyMs) && route.latencyMs >= 0, "latencyMs must be nonnegative");
31
+ assertUnits(units);
32
+ return (route.completionProbability -
33
+ units.costWeight * (route.costUsd / units.costUnit) -
34
+ units.latencyWeight * (route.latencyMs / units.latencyUnit));
35
+ }
36
+ /**
37
+ * Highest-utility approved route, or null when nothing is approved.
38
+ *
39
+ * Returning null rather than the best unapproved route keeps "we may not do
40
+ * this" distinct from "this is expensive".
41
+ */
42
+ export function selectRoute(routes, units) {
43
+ ensure(Array.isArray(routes) && routes.length > 0, "routes must be a non-empty array");
44
+ let best;
45
+ let bestUtility = Number.NEGATIVE_INFINITY;
46
+ for (const route of routes) {
47
+ if (!route.approved)
48
+ continue;
49
+ const utility = routeUtility(route, units);
50
+ const better = utility > bestUtility || (utility === bestUtility && best !== undefined && route.id < best.id);
51
+ if (best === undefined || better) {
52
+ best = route;
53
+ bestUtility = utility;
54
+ }
55
+ }
56
+ return best ?? null;
57
+ }
58
+ /** Whole-step duration. Model response time is one term among eight. */
59
+ export function stepDuration(phases) {
60
+ let total = 0;
61
+ for (const [label, value] of Object.entries(phases)) {
62
+ ensure(Number.isFinite(value) && value >= 0, `${label} must be a nonnegative finite number`);
63
+ total += value;
64
+ }
65
+ return total;
66
+ }
67
+ /**
68
+ * Amdahl bound: S = 1 / ((1−f) + f/s).
69
+ *
70
+ * `speedup` may be Infinity to ask what an instantaneous step would buy — the
71
+ * answer is still capped by the fraction it occupies, which is the point.
72
+ */
73
+ export function overallSpeedup(improvableFraction, speedup) {
74
+ ensure(Number.isFinite(improvableFraction) && improvableFraction >= 0 && improvableFraction <= 1, "improvableFraction must be in [0,1]");
75
+ ensure(typeof speedup === "number" && !Number.isNaN(speedup) && speedup >= 1, "speedup must be at least 1");
76
+ const remaining = 1 - improvableFraction;
77
+ const improved = speedup === Number.POSITIVE_INFINITY ? 0 : improvableFraction / speedup;
78
+ return 1 / (remaining + improved);
79
+ }
80
+ /**
81
+ * E[C] = c_J + c_V + p_F·c_L.
82
+ *
83
+ * A cost decomposition, not an independence claim. Compare it against the
84
+ * incumbent path's cost under the same success and safety conditions; if it is
85
+ * larger, the cheap path is not cheap.
86
+ */
87
+ export function fallbackExpectedCost(costs) {
88
+ ensure(Number.isFinite(costs.selectorCost) && costs.selectorCost >= 0, "selectorCost must be nonnegative");
89
+ ensure(Number.isFinite(costs.verificationCost) && costs.verificationCost >= 0, "verificationCost must be nonnegative");
90
+ ensure(Number.isFinite(costs.fallbackCost) && costs.fallbackCost >= 0, "fallbackCost must be nonnegative");
91
+ ensure(Number.isFinite(costs.fallbackProbability) && costs.fallbackProbability >= 0 && costs.fallbackProbability <= 1, "fallbackProbability must be in [0,1]");
92
+ return costs.selectorCost + costs.verificationCost + costs.fallbackProbability * costs.fallbackCost;
93
+ }
94
+ /**
95
+ * Damp selector/model ping-pong on one observation generation.
96
+ *
97
+ * Re-asking the same question about the same state only adds calls. A further
98
+ * attempt is admitted when the budget remains, or when recovery genuinely
99
+ * changed the cause. The budget is a configured value, not a claimed optimum.
100
+ */
101
+ export function reselectionAllowed(input) {
102
+ ensure(Number.isSafeInteger(input.attemptsForFingerprint) && input.attemptsForFingerprint >= 0, "attemptsForFingerprint must be a nonnegative integer");
103
+ ensure(Number.isSafeInteger(input.maxAttempts) && input.maxAttempts > 0, "maxAttempts must be a positive integer");
104
+ if (input.causeChanged)
105
+ return { allowed: true };
106
+ if (input.attemptsForFingerprint < input.maxAttempts)
107
+ return { allowed: true };
108
+ return { allowed: false, reason: "attempt-budget-exhausted" };
109
+ }
110
+ //# sourceMappingURL=route-economics.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"route-economics.js","sourceRoot":"","sources":["../../src/metacognition/route-economics.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH,OAAO,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAC;AAmBzC,SAAS,WAAW,CAAC,KAAiB,EAAQ;IAC7C,MAAM,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,QAAQ,CAAC,IAAI,KAAK,CAAC,QAAQ,GAAG,CAAC,EAAE,2BAA2B,CAAC,CAAC;IAC3F,MAAM,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,WAAW,CAAC,IAAI,KAAK,CAAC,WAAW,GAAG,CAAC,EAAE,8BAA8B,CAAC,CAAC;IACpG,MAAM,CAAC,MAAM,CAAC,QAAQ,CAAC,KAAK,CAAC,UAAU,CAAC,IAAI,KAAK,CAAC,UAAU,IAAI,CAAC,EAAE,gCAAgC,CAAC,CAA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IAAI,KAAK,CAAC,WAAW,GAAG,CAAC,EAAE,wCAAwC,CAAC,CAAC;IACnH,IAAI,KAAK,CAAC,YAAY;QAAE,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;IACjD,IAAI,KAAK,CAAC,sBAAsB,GAAG,KAAK,CAAC,WAAW;QAAE,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC;IAC/E,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,EAAE,0BAA0B,EAAE,CAAC;AAAA,CAC9D","sourcesContent":["/**\n * Cost- and latency-aware route selection (Jev audit algorithm A5).\n *\n * Adding a selector call only pays if it *replaces* work. Inserting one in\n * front of an existing free-text step adds a semantic inference instead of\n * removing one, so routes are compared on a single utility:\n *\n * U_r = q_r − λ_C·(C_r/C_0) − λ_L·(L_r/L_0)\n *\n * Safety and permission are deliberately not terms in that utility. They are a\n * hard filter, because a cheap unsafe route must never win on weights.\n *\n * Latency is measured over the whole step, not the model call: when operator\n * approval dominates, a faster decision step barely moves the total. Amdahl's\n * bound is included so that limit is explicit rather than assumed away.\n */\n\nimport { ensure } from \"./validation.ts\";\n\nexport interface RouteCandidate {\n\treadonly id: string;\n\t/** Probability this route completes the step correctly. */\n\treadonly completionProbability: number;\n\treadonly costUsd: number;\n\treadonly latencyMs: number;\n\t/** Policy and permission verdict. A false value is a veto, not a penalty. */\n\treadonly approved: boolean;\n}\n\nexport interface RouteUnits {\n\treadonly costUnit: number;\n\treadonly latencyUnit: number;\n\treadonly costWeight: number;\n\treadonly latencyWeight: number;\n}\n\nfunction assertUnits(units: RouteUnits): void {\n\tensure(Number.isFinite(units.costUnit) && units.costUnit > 0, \"costUnit must be positive\");\n\tensure(Number.isFinite(units.latencyUnit) && units.latencyUnit > 0, \"latencyUnit must be positive\");\n\tensure(Number.isFinite(units.costWeight) && units.costWeight >= 0, \"costWeight must be nonnegative\");\n\tensure(Number.isFinite(units.latencyWeight) && units.latencyWeight >= 0, \"latencyWeight must be nonnegative\");\n}\n\n/** Dimensionless utility; cost and latency are normalized before weighting. */\nexport function routeUtility(route: RouteCandidate, units: RouteUnits): number {\n\tensure(\n\t\tNumber.isFinite(route.completionProbability) &&\n\t\t\troute.completionProbability >= 0 &&\n\t\t\troute.completionProbability <= 1,\n\t\t\"completionProbability must be in [0,1]\",\n\t);\n\tensure(Number.isFinite(route.costUsd) && route.costUsd >= 0, \"costUsd must be nonnegative\");\n\tensure(Number.isFinite(route.latencyMs) && route.latencyMs >= 0, \"latencyMs must be nonnegative\");\n\tassertUnits(units);\n\treturn (\n\t\troute.completionProbability -\n\t\tunits.costWeight * (route.costUsd / units.costUnit) -\n\t\tunits.latencyWeight * (route.latencyMs / units.latencyUnit)\n\t);\n}\n\n/**\n * Highest-utility approved route, or null when nothing is approved.\n *\n * Returning null rather than the best unapproved route keeps \"we may not do\n * this\" distinct from \"this is expensive\".\n */\nexport function selectRoute(routes: readonly RouteCandidate[], units: RouteUnits): RouteCandidate | null {\n\tensure(Array.isArray(routes) && routes.length > 0, \"routes must be a non-empty array\");\n\tlet best: RouteCandidate | undefined;\n\tlet bestUtility = Number.NEGATIVE_INFINITY;\n\tfor (const route of routes) {\n\t\tif (!route.approved) continue;\n\t\tconst utility = routeUtility(route, units);\n\t\tconst better = utility > bestUtility || (utility === bestUtility && best !== undefined && route.id < best.id);\n\t\tif (best === undefined || better) {\n\t\t\tbest = route;\n\t\t\tbestUtility = utility;\n\t\t}\n\t}\n\treturn best ?? null;\n}\n\nexport interface StepPhases {\n\treadonly queueMs: number;\n\treadonly observeMs: number;\n\treadonly packMs: number;\n\treadonly decideMs: number;\n\treadonly approvalMs: number;\n\treadonly executeMs: number;\n\treadonly verifyMs: number;\n\treadonly recoveryMs: number;\n}\n\n/** Whole-step duration. Model response time is one term among eight. */\nexport function stepDuration(phases: StepPhases): number {\n\tlet total = 0;\n\tfor (const [label, value] of Object.entries(phases)) {\n\t\tensure(Number.isFinite(value) && value >= 0, `${label} must be a nonnegative finite number`);\n\t\ttotal += value;\n\t}\n\treturn total;\n}\n\n/**\n * Amdahl bound: S = 1 / ((1−f) + f/s).\n *\n * `speedup` may be Infinity to ask what an instantaneous step would buy — the\n * answer is still capped by the fraction it occupies, which is the point.\n */\nexport function overallSpeedup(improvableFraction: number, speedup: number): number {\n\tensure(\n\t\tNumber.isFinite(improvableFraction) && improvableFraction >= 0 && improvableFraction <= 1,\n\t\t\"improvableFraction must be in [0,1]\",\n\t);\n\tensure(typeof speedup === \"number\" && !Number.isNaN(speedup) && speedup >= 1, \"speedup must be at least 1\");\n\tconst remaining = 1 - improvableFraction;\n\tconst improved = speedup === Number.POSITIVE_INFINITY ? 0 : improvableFraction / speedup;\n\treturn 1 / (remaining + improved);\n}\n\nexport interface FallbackCosts {\n\treadonly selectorCost: number;\n\treadonly verificationCost: number;\n\treadonly fallbackProbability: number;\n\treadonly fallbackCost: number;\n}\n\n/**\n * E[C] = c_J + c_V + p_F·c_L.\n *\n * A cost decomposition, not an independence claim. Compare it against the\n * incumbent path's cost under the same success and safety conditions; if it is\n * larger, the cheap path is not cheap.\n */\nexport function fallbackExpectedCost(costs: FallbackCosts): number {\n\tensure(Number.isFinite(costs.selectorCost) && costs.selectorCost >= 0, \"selectorCost must be nonnegative\");\n\tensure(\n\t\tNumber.isFinite(costs.verificationCost) && costs.verificationCost >= 0,\n\t\t\"verificationCost must be nonnegative\",\n\t);\n\tensure(Number.isFinite(costs.fallbackCost) && costs.fallbackCost >= 0, \"fallbackCost must be nonnegative\");\n\tensure(\n\t\tNumber.isFinite(costs.fallbackProbability) && costs.fallbackProbability >= 0 && costs.fallbackProbability <= 1,\n\t\t\"fallbackProbability must be in [0,1]\",\n\t);\n\treturn costs.selectorCost + costs.verificationCost + costs.fallbackProbability * costs.fallbackCost;\n}\n\nexport interface ReselectionInput {\n\t/** Attempts already spent on this observation fingerprint. */\n\treadonly attemptsForFingerprint: number;\n\treadonly maxAttempts: number;\n\t/** True when recovery changed the cause, not merely retried the same question. */\n\treadonly causeChanged: boolean;\n}\n\nexport type ReselectionDecision =\n\t| { readonly allowed: true }\n\t| { readonly allowed: false; readonly reason: \"attempt-budget-exhausted\" };\n\n/**\n * Damp selector/model ping-pong on one observation generation.\n *\n * Re-asking the same question about the same state only adds calls. A further\n * attempt is admitted when the budget remains, or when recovery genuinely\n * changed the cause. The budget is a configured value, not a claimed optimum.\n */\nexport function reselectionAllowed(input: ReselectionInput): ReselectionDecision {\n\tensure(\n\t\tNumber.isSafeInteger(input.attemptsForFingerprint) && input.attemptsForFingerprint >= 0,\n\t\t\"attemptsForFingerprint must be a nonnegative integer\",\n\t);\n\tensure(Number.isSafeInteger(input.maxAttempts) && input.maxAttempts > 0, \"maxAttempts must be a positive integer\");\n\tif (input.causeChanged) return { allowed: true };\n\tif (input.attemptsForFingerprint < input.maxAttempts) return { allowed: true };\n\treturn { allowed: false, reason: \"attempt-budget-exhausted\" };\n}\n"]}
@@ -0,0 +1,54 @@
1
+ /**
2
+ * Runtime bridge — §13 "기존 완료 판정 호출부": projects host-owned OMK
3
+ * runtime artifacts (protocol ClaimGraph claims, ObservationNodes, waiver
4
+ * records, workspace/session facts) onto the metacognition kernel's input
5
+ * types. It only translates; it never relaxes trust floors, never admits a
6
+ * model's JSON as runner truth, and never fabricates completion.
7
+ */
8
+ import type { ClaimNode, ObservationNode } from "omk-protocol";
9
+ import type { CheckObservation, Claim, DecisionObservation, ReferenceObservation, SourceIdentity, Stage } from "./knowledge.ts";
10
+ import type { MetaState } from "./state.ts";
11
+ /** ClaimNode → kernel Claim. Severity maps to impact; leaves keep their check demands. */
12
+ export declare function toKernelClaim(node: ClaimNode, stage: Stage, binding: string): Claim;
13
+ /** ObservationNode → kernel observation. Trust floor rank maps to source admissibility. */
14
+ export declare function toKernelObservation(node: ObservationNode, binding: string, nowMs: number, claimById?: ReadonlyMap<string, Claim>): CheckObservation | ReferenceObservation | DecisionObservation;
15
+ export interface RuntimeBridgeOutput {
16
+ readonly state: MetaState;
17
+ readonly claims: readonly Claim[];
18
+ readonly observations: readonly (CheckObservation | ReferenceObservation | DecisionObservation)[];
19
+ }
20
+ export interface RuntimeBridgeInput {
21
+ readonly taskId: string;
22
+ readonly stageId: string;
23
+ readonly goalScope: string;
24
+ readonly targetArtifact: string;
25
+ readonly candidateHash: string;
26
+ readonly environmentHash: string;
27
+ readonly claims: readonly ClaimNode[];
28
+ readonly observations: readonly ObservationNode[];
29
+ readonly trustedRunnerIds: readonly string[];
30
+ readonly decisionActorIds: readonly string[];
31
+ readonly authorizedActions: readonly string[];
32
+ readonly budget: {
33
+ remainingMs: number;
34
+ remainingRequests: number;
35
+ remainingTokens: number;
36
+ remainingConcurrent: number;
37
+ };
38
+ readonly policyVersion: string;
39
+ readonly modelRevision: string;
40
+ readonly interruptionReason?: string | null;
41
+ readonly stage: Stage;
42
+ readonly nowMs: number;
43
+ readonly progressHistory?: readonly {
44
+ key: string;
45
+ newEvidence: boolean;
46
+ resolvedObligations: number;
47
+ newValidChecks: number;
48
+ }[];
49
+ }
50
+ /** Build kernel inputs plus a MetaState for one safe checkpoint. Host-owned inputs only. */
51
+ export declare function toMetaState(input: RuntimeBridgeInput): RuntimeBridgeOutput;
52
+ /** Sources admitted for reference evidence: only repository/official qualify. */
53
+ export declare function sourceIdentities(overrides?: readonly SourceIdentity[]): readonly SourceIdentity[];
54
+ //# sourceMappingURL=runtime-bridge.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runtime-bridge.d.ts","sourceRoot":"","sources":["../../src/metacognition/runtime-bridge.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,KAAK,EAAE,SAAS,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AAE/D,OAAO,KAAK,EACX,gBAAgB,EAChB,KAAK,EACL,mBAAmB,EACnB,oBAAoB,EACpB,cAAc,EACd,KAAK,EACL,MAAM,gBAAgB,CAAC;AACxB,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAS5C,4FAA0F;AAC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1B,eAAe,EAAE,MAAM,CAAC;QACxB,mBAAmB,EAAE,MAAM,CAAC;KAC5B,CAAC;IACF,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAC;IAC/B,QAAQ,CAAC,aAAa,EAAE,MAAM,CAAC;IAC/B,QAAQ,CAAC,kBAAkB,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC5C,QAAQ,CAAC,KAAK,EAAE,KAAK,CAAC;IACtB,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,eAAe,CAAC,EAAE,SAAS;QACnC,GAAG,EAAE,MAAM,CAAC;QACZ,WAAW,EAAE,OAAO,CAAC;QACrB,mBAAmB,EAAE,MAAM,CAAC;QAC5B,cAAc,EAAE,MAAM,CAAC;KACvB,EAAE,CAAC;CACJ;AAED,4FAA4F;AAC5F,wBAAgB,WAAW,CAAC,KAAK,EAAE,kBAAkB,GAAG,mBAAmB,CAwD1E;AAED,iFAAiF;AACjF,wBAAgB,gBAAgB,CAAC,SAAS,GAAE,SAAS,cAAc,EAAO,GAAG,SAAS,cAAc,EAAE,CAWrG","sourcesContent":["/**\n * Runtime bridge — §13 \"기존 완료 판정 호출부\": projects host-owned OMK\n * runtime artifacts (protocol ClaimGraph claims, ObservationNodes, waiver\n * records, workspace/session facts) onto the metacognition kernel's input\n * types. It only translates; it never relaxes trust floors, never admits a\n * model's JSON as runner truth, and never fabricates completion.\n */\nimport type { ClaimNode, ObservationNode } from \"omk-protocol\";\nimport { createCalibrationStore } from \"./calibration.ts\";\nimport type {\n\tCheckObservation,\n\tClaim,\n\tDecisionObservation,\n\tReferenceObservation,\n\tSourceIdentity,\n\tStage,\n} from \"./knowledge.ts\";\nimport type { MetaState } from \"./state.ts\";\nimport { ensure, integer, lexical, member, text } from \"./validation.ts\";\n\nconst ISO_MS = (iso: string): number => {\n\tconst ms = Date.parse(iso);\n\tensure(Number.isFinite(ms), `invalid ISO timestamp: ${iso}`);\n\treturn ms;\n};\n\n/** ClaimNode → kernel Claim. Severity maps to impact; leaves keep their check demands. */\nexport function toKernelClaim(node: ClaimNode, stage: Stage, binding: string): Claim {\n\ttext(node.claimId, \"claimId\", 256);\n\ttext(node.statement, \"statement\", 2048);\n\tmember(stage, [\"before-change\", \"after-change\"], \"stage\");\n\tlet impact = 100;\n\tif (node.kind === \"safety\") impact = 1_000;\n\telse if (node.severity === \"required\") impact = 500;\n\treturn {\n\t\tid: node.claimId,\n\t\tbinding,\n\t\tphase: node.kind === \"requirement\" || node.kind === \"safety\" ? \"precondition\" : \"postcondition\",\n\t\tstatement: node.statement,\n\t\trequired: node.severity === \"required\",\n\t\timpact,\n\t\tneedsReference: false,\n\t\trequiresVersion: false,\n\t\tversion: null,\n\t\tminSourceFamilies: node.requiredWitnesses ?? 1,\n\t\trequiredCheckIds: node.invalidationKeys,\n\t\tneedsUserDecision: node.trustFloor === \"model_narrative\",\n\t\tpublicQuery: null,\n\t};\n}\n\n/** ObservationNode → kernel observation. Trust floor rank maps to source admissibility. */\nexport function toKernelObservation(\n\tnode: ObservationNode,\n\tbinding: string,\n\tnowMs: number,\n\tclaimById?: ReadonlyMap<string, Claim>,\n): CheckObservation | ReferenceObservation | DecisionObservation {\n\ttext(node.observationId, \"observationId\", 256);\n\ttext(binding, \"binding\", 512);\n\tinteger(nowMs, \"nowMs\");\n\tconst observedAtMs = nowMs;\n\tconst expiresAtMs = node.validUntil !== undefined ? ISO_MS(node.validUntil) : nowMs + 1;\n\tconst claimId = node.claimIds[0] ?? \"\";\n\tconst base = { id: node.observationId, claimId, binding, observedAtMs, expiresAtMs };\n\tif (node.receiptId !== undefined) {\n\t\t// checkId is the claim's required check predicate (its invalidation key),\n\t\t// not the receipt id — receipts are evidence artifacts, checkIds are obligations.\n\t\tconst checkId = claimById?.get(claimId)?.requiredCheckIds[0] ?? node.receiptId;\n\t\treturn {\n\t\t\t...base,\n\t\t\tkind: \"check\",\n\t\t\trunnerId: node.source,\n\t\t\tcheckId,\n\t\t\tsequence: 0,\n\t\t\tverdict: node.polarity === \"supports\" ? \"pass\" : \"fail\",\n\t\t};\n\t}\n\tif (node.source === \"model_narrative\") {\n\t\treturn { ...base, kind: \"decision\", actorId: \"model\", accepted: node.polarity === \"supports\" };\n\t}\n\treturn {\n\t\t...base,\n\t\tkind: \"reference\",\n\t\tsourceId: node.source,\n\t\tversion: null,\n\t\tstance: node.polarity === \"supports\" ? \"support\" : \"refute\",\n\t\tdocumentDigest: node.environmentDigest,\n\t\tlocator: node.sourceRoot,\n\t};\n}\n\nexport interface RuntimeBridgeOutput {\n\treadonly state: MetaState;\n\treadonly claims: readonly Claim[];\n\treadonly observations: readonly (CheckObservation | ReferenceObservation | DecisionObservation)[];\n}\nexport interface RuntimeBridgeInput {\n\treadonly taskId: string;\n\treadonly stageId: string;\n\treadonly goalScope: string;\n\treadonly targetArtifact: string;\n\treadonly candidateHash: string;\n\treadonly environmentHash: string;\n\treadonly claims: readonly ClaimNode[];\n\treadonly observations: readonly ObservationNode[];\n\treadonly trustedRunnerIds: readonly string[];\n\treadonly decisionActorIds: readonly string[];\n\treadonly authorizedActions: readonly string[];\n\treadonly budget: {\n\t\tremainingMs: number;\n\t\tremainingRequests: number;\n\t\tremainingTokens: number;\n\t\tremainingConcurrent: number;\n\t};\n\treadonly policyVersion: string;\n\treadonly modelRevision: string;\n\treadonly interruptionReason?: string | null;\n\treadonly stage: Stage;\n\treadonly nowMs: number;\n\treadonly progressHistory?: readonly {\n\t\tkey: string;\n\t\tnewEvidence: boolean;\n\t\tresolvedObligations: number;\n\t\tnewValidChecks: number;\n\t}[];\n}\n\n/** Build kernel inputs plus a MetaState for one safe checkpoint. Host-owned inputs only. */\nexport function toMetaState(input: RuntimeBridgeInput): RuntimeBridgeOutput {\n\ttext(input.taskId, \"taskId\", 128);\n\ttext(input.stageId, \"stageId\", 128);\n\ttext(input.goalScope, \"goalScope\", 256);\n\ttext(input.targetArtifact, \"targetArtifact\", 512);\n\ttext(input.candidateHash, \"candidateHash\", 128);\n\ttext(input.environmentHash, \"environmentHash\", 128);\n\ttext(input.policyVersion, \"policyVersion\", 64);\n\ttext(input.modelRevision, \"modelRevision\", 128);\n\tinteger(input.nowMs, \"nowMs\");\n\tensure(input.claims.length <= 128 && input.observations.length <= 4096, \"runtime bridge input too large\");\n\t// Only leaf claims map to kernel claims — compound satisfaction is the\n\t// protocol layer's job, not a kernel evidence predicate.\n\tconst binding = `${input.candidateHash}@${input.environmentHash}`;\n\tconst leafClaims = input.claims.filter((c) => c.satisfaction.inputs.length === 0);\n\tconst claimById = new Map(leafClaims.map((c) => [c.claimId, toKernelClaim(c, input.stage, binding)]));\n\tconst kernelClaims = [...claimById.values()].sort((a, b) => lexical(a.id, b.id));\n\tconst kernelObservations = input.observations.map((o) => toKernelObservation(o, binding, input.nowMs, claimById));\n\tconst state: MetaState = {\n\t\tgoal: {\n\t\t\ttaskId: input.taskId,\n\t\t\tstageId: input.stageId,\n\t\t\ttargetArtifact: input.targetArtifact,\n\t\t\tgoalScope: input.goalScope,\n\t\t},\n\t\tfacts: {\n\t\t\tcandidateHash: input.candidateHash,\n\t\t\tenvironmentHash: input.environmentHash,\n\t\t\tchangeScope: [input.targetArtifact],\n\t\t\tanalyzerCoverage: \"unknown\",\n\t\t},\n\t\tobligations: [],\n\t\tevidence: { report: null, adoptedSourceIds: [] },\n\t\tpredictions: [],\n\t\thypotheses: { open: [], discriminatorCandidates: [], modelMismatch: false },\n\t\tcalibration: createCalibrationStore({\n\t\t\tminSamples: 5,\n\t\t\tpriorAlpha: 1,\n\t\t\tpriorBeta: 1,\n\t\t\treferenceMean: 0.3,\n\t\t\tslack: 0.15,\n\t\t\tthreshold: 3,\n\t\t}),\n\t\tverifier: { evaluations: [], runnerHealth: \"unverified\" },\n\t\tbudget: input.budget,\n\t\tpolicy: {\n\t\t\tpolicyVersion: input.policyVersion,\n\t\t\tauthorizedActions: input.authorizedActions,\n\t\t\trequiredApprovals: [],\n\t\t\tinterruptionReason: input.interruptionReason ?? null,\n\t\t},\n\t\thostSequence: 0,\n\t\tprogressHistory: input.progressHistory ?? [],\n\t\tcheckpointCount: 0,\n\t};\n\treturn { state, claims: kernelClaims, observations: kernelObservations };\n}\n\n/** Sources admitted for reference evidence: only repository/official qualify. */\nexport function sourceIdentities(overrides: readonly SourceIdentity[] = []): readonly SourceIdentity[] {\n\treturn [\n\t\t{ id: \"deterministic_validator\", family: \"host\", kind: \"repository\" },\n\t\t{ id: \"workspace_witness\", family: \"host\", kind: \"repository\" },\n\t\t{ id: \"trusted_attestation\", family: \"attestation\", kind: \"official\" },\n\t\t{ id: \"effect_reconciliation\", family: \"host\", kind: \"repository\" },\n\t\t{ id: \"independent_review\", family: \"review\", kind: \"official\" },\n\t\t{ id: \"self_review\", family: \"model\", kind: \"model\" },\n\t\t{ id: \"model_narrative\", family: \"model\", kind: \"model\" },\n\t\t...overrides,\n\t];\n}\n"]}