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,97 @@
1
+ /**
2
+ * §11 causal strategy evaluation + §15 outcome metrics.
3
+ *
4
+ * Doubly Robust estimation is a second-stage offline tool over logged
5
+ * single-checkpoint decisions: it needs real logged propensities, action
6
+ * support, and rewards — never probabilities invented after the fact.
7
+ * Completion metrics report false-completion alongside success/abstain rates,
8
+ * because a policy that never completes can trivially zero false completions.
9
+ */
10
+ import { ensure, finite, integer, probability, text } from "./validation.js";
11
+ /**
12
+ * Single-decision Doubly Robust estimate:
13
+ * V̂_DR(π) = 1/n Σ [ Σ_a π(a|x_i)r̂(x_i,a) + (π(a_i|x_i)/μ(a_i|x_i))(r_i - r̂(x_i,a_i)) ].
14
+ * Deterministic logging policies that never tried an action cannot evaluate
15
+ * that action post-hoc — those rows are excluded and counted.
16
+ */
17
+ export function doublyRobustEstimate(input, maxWeight = 50) {
18
+ const { decisions, evaluatedActions, rewardModel } = input;
19
+ integer(decisions.length, "decisions", 1_000_000);
20
+ ensure(decisions.length > 0, "no logged decisions");
21
+ ensure(evaluatedActions.length === decisions.length, "evaluated action count mismatch");
22
+ ensure(rewardModel.length === decisions.length, "reward model row mismatch");
23
+ finite(maxWeight, "maxWeight", 1e9);
24
+ let sum = 0, clipped = 0, unsupported = 0, usable = 0;
25
+ for (let i = 0; i < decisions.length; i++) {
26
+ const d = decisions[i];
27
+ text(d.contextHash, "contextHash", 256);
28
+ text(d.action, "action", 128);
29
+ finite(d.reward, "reward");
30
+ probability(d.propensity, "propensity");
31
+ text(evaluatedActions[i], "evaluated action", 128);
32
+ const rewards = rewardModel[i];
33
+ ensure(rewards.length > 0, "reward model row empty");
34
+ for (const r of rewards)
35
+ finite(r, "reward model value");
36
+ // Contexts may carry several logged actions; μ is per recorded decision.
37
+ const modelMean = rewards.reduce((a, b) => a + b, 0) / rewards.length;
38
+ if (d.propensity === 0 && d.action === evaluatedActions[i]) {
39
+ unsupported++;
40
+ continue;
41
+ }
42
+ usable++;
43
+ const weight = d.action === evaluatedActions[i] ? Math.min(maxWeight, 1 / d.propensity) : 0;
44
+ if (weight === maxWeight)
45
+ clipped++;
46
+ sum += modelMean + weight * (d.reward - modelMean);
47
+ }
48
+ ensure(usable > 0, "no decisions with logged support for the evaluated policy");
49
+ return { value: sum / usable, n: usable, clipped, unsupported };
50
+ }
51
+ export function validateExperienceRecord(r) {
52
+ text(r.recordId, "recordId", 128);
53
+ text(r.failureMechanism, "failureMechanism", 2048);
54
+ text(r.firstWrongExpectation, "firstWrongExpectation", 2048);
55
+ text(r.discriminatingObservation, "discriminatingObservation", 2048);
56
+ text(r.appliedFixOrStrategy, "appliedFixOrStrategy", 2048);
57
+ text(r.policyVersion, "policyVersion", 64);
58
+ for (const list of [
59
+ r.checksBefore,
60
+ r.checksAfter,
61
+ r.knownCounterexamples,
62
+ r.applicabilityConditions,
63
+ r.evidenceRefs,
64
+ r.skillHashes,
65
+ ]) {
66
+ ensure(Array.isArray(list) && list.length <= 128, "experience record list bound");
67
+ }
68
+ }
69
+ export function completionMetrics(c) {
70
+ integer(c.declaredComplete, "declaredComplete");
71
+ integer(c.independentFailAmongDeclared, "independentFail");
72
+ integer(c.allTasks, "allTasks");
73
+ integer(c.succeeded, "succeeded");
74
+ integer(c.abstained, "abstained");
75
+ finite(c.totalCost, "totalCost");
76
+ ensure(c.independentFailAmongDeclared <= c.declaredComplete, "fail count exceeds declared");
77
+ ensure(c.declaredComplete <= c.allTasks && c.succeeded <= c.allTasks && c.abstained <= c.allTasks, "counts exceed task total");
78
+ return {
79
+ falseCompletionDeclared: c.declaredComplete > 0 ? c.independentFailAmongDeclared / c.declaredComplete : undefined,
80
+ falseCompletionAll: c.allTasks > 0 ? c.independentFailAmongDeclared / c.allTasks : undefined,
81
+ successRate: c.allTasks > 0 ? c.succeeded / c.allTasks : undefined,
82
+ abstainRate: c.allTasks > 0 ? c.abstained / c.allTasks : undefined,
83
+ meanCost: c.allTasks > 0 ? c.totalCost / c.allTasks : undefined,
84
+ };
85
+ }
86
+ /** §15.3 hidden-obligation detection with false alarms, for held-out requirements. */
87
+ export function hiddenObligationMetrics(detected, totalHidden, falseAlarms) {
88
+ integer(detected, "detected");
89
+ integer(totalHidden, "totalHidden");
90
+ integer(falseAlarms, "falseAlarms");
91
+ ensure(detected <= totalHidden, "detected exceeds hidden total");
92
+ return {
93
+ detectionRate: totalHidden > 0 ? detected / totalHidden : undefined,
94
+ falseAlarms,
95
+ };
96
+ }
97
+ //# sourceMappingURL=evaluation.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"evaluation.js","sourceRoot":"","sources":["../../src/metacognition/evaluation.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,WAAW,EAAE,IAAI,EAAE,MAAM,iBAAiB,CAAC;AAyB7E;;;;;GAKG;AACH,MAAM,UAAU,oBAAoB,CAAC,KAAc,EAAE,SAAS,GAAG,EAAE,EAAc;IAChF,MAAM,EAAE,SAAS,EAAE,gBAAgB,EAAE,WAAW,EAAE,GAAG,KAAK,CAAC;IAC3D,OAAO,CAAC,SAAS,CAAC,MAAM,EAAE,WAAW,EAAE,SAAS,CA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AgB,CAAC,CAAC,CAAC,SAAS;QACjH,kBAAkB,EAAE,CAAC,CAAC,QAAQ,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,4BAA4B,GAAG,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,SAAS;QAC5F,WAAW,EAAE,CAAC,CAAC,QAAQ,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,GAAG,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,SAAS;QAClE,WAAW,EAAE,CAAC,CAAC,QAAQ,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,GAAG,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,SAAS;QAClE,QAAQ,EAAE,CAAC,CAAC,QAAQ,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,SAAS,GAAG,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,SAAS;KAC/D,CAAC;AAAA,CACF;AAED,uFAAsF;AACtF,MAAM,UAAU,uBAAuB,CACtC,QAAgB,EAChB,WAAmB,EACnB,WAAmB,EAIlB;IACD,OAAO,CAAC,QAAQ,EAAE,UAAU,CAAC,CAAC;IAC9B,OAAO,CAAC,WAAW,EAAE,aAAa,CAAC,CAAC;IACpC,OAAO,CAAC,WAAW,EAAE,aAAa,CAAC,CAAC;IACpC,MAAM,CAAC,QAAQ,IAAI,WAAW,EAAE,+BAA+B,CAAC,CAAC;IACjE,OAAO;QACN,aAAa,EAAE,WAAW,GAAG,CAAC,CAAC,CAAC,CAAC,QAAQ,GAAG,WAAW,CAAC,CAAC,CAAC,SAAS;QACnE,WAAW;KACX,CAAC;AAAA,CACF","sourcesContent":["/**\n * §11 causal strategy evaluation + §15 outcome metrics.\n *\n * Doubly Robust estimation is a second-stage offline tool over logged\n * single-checkpoint decisions: it needs real logged propensities, action\n * support, and rewards — never probabilities invented after the fact.\n * Completion metrics report false-completion alongside success/abstain rates,\n * because a policy that never completes can trivially zero false completions.\n */\nimport { ensure, finite, integer, probability, text } from \"./validation.ts\";\n\n/** One logged decision for DR evaluation. Single checkpoint, not a trajectory. */\nexport interface LoggedDecision {\n\treadonly contextHash: string;\n\treadonly action: string;\n\treadonly reward: number;\n\t/** Logged selection probability under the recording policy. Required, never imputed. */\n\treadonly propensity: number;\n}\nexport interface DRInput {\n\treadonly decisions: readonly LoggedDecision[];\n\t/** π(a|x): the evaluated policy's action for each logged context. */\n\treadonly evaluatedActions: readonly string[];\n\t/** r̂(x,a): reward model per context-action pair. */\n\treadonly rewardModel: readonly (readonly number[])[];\n}\nexport interface DREstimate {\n\treadonly value: number;\n\treadonly n: number;\n\treadonly clipped: number;\n\t/** Contexts where the evaluated action had zero logged support — excluded, never imputed. */\n\treadonly unsupported: number;\n}\n\n/**\n * Single-decision Doubly Robust estimate:\n * V̂_DR(π) = 1/n Σ [ Σ_a π(a|x_i)r̂(x_i,a) + (π(a_i|x_i)/μ(a_i|x_i))(r_i - r̂(x_i,a_i)) ].\n * Deterministic logging policies that never tried an action cannot evaluate\n * that action post-hoc — those rows are excluded and counted.\n */\nexport function doublyRobustEstimate(input: DRInput, maxWeight = 50): DREstimate {\n\tconst { decisions, evaluatedActions, rewardModel } = input;\n\tinteger(decisions.length, \"decisions\", 1_000_000);\n\tensure(decisions.length > 0, \"no logged decisions\");\n\tensure(evaluatedActions.length === decisions.length, \"evaluated action count mismatch\");\n\tensure(rewardModel.length === decisions.length, \"reward model row mismatch\");\n\tfinite(maxWeight, \"maxWeight\", 1e9);\n\tlet sum = 0,\n\t\tclipped = 0,\n\t\tunsupported = 0,\n\t\tusable = 0;\n\tfor (let i = 0; i < decisions.length; i++) {\n\t\tconst d = decisions[i]!;\n\t\ttext(d.contextHash, \"contextHash\", 256);\n\t\ttext(d.action, \"action\", 128);\n\t\tfinite(d.reward, \"reward\");\n\t\tprobability(d.propensity, \"propensity\");\n\t\ttext(evaluatedActions[i]!, \"evaluated action\", 128);\n\t\tconst rewards = rewardModel[i]!;\n\t\tensure(rewards.length > 0, \"reward model row empty\");\n\t\tfor (const r of rewards) finite(r, \"reward model value\");\n\t\t// Contexts may carry several logged actions; μ is per recorded decision.\n\t\tconst modelMean = rewards.reduce((a, b) => a + b, 0) / rewards.length;\n\t\tif (d.propensity === 0 && d.action === evaluatedActions[i]) {\n\t\t\tunsupported++;\n\t\t\tcontinue;\n\t\t}\n\t\tusable++;\n\t\tconst weight = d.action === evaluatedActions[i] ? Math.min(maxWeight, 1 / d.propensity) : 0;\n\t\tif (weight === maxWeight) clipped++;\n\t\tsum += modelMean + weight * (d.reward - modelMean);\n\t}\n\tensure(usable > 0, \"no decisions with logged support for the evaluated policy\");\n\treturn { value: sum / usable, n: usable, clipped, unsupported };\n}\n\n/** §11.3 experience memory — failure mechanism and discrimination, not essays. */\nexport interface ExperienceRecord {\n\treadonly recordId: string;\n\treadonly conditions: {\n\t\treadonly modelRevision: string;\n\t\treadonly toolchain: string;\n\t\treadonly environmentHash: string;\n\t\treadonly taskBand: string;\n\t};\n\treadonly failureMechanism: string;\n\treadonly firstWrongExpectation: string;\n\treadonly discriminatingObservation: string;\n\treadonly appliedFixOrStrategy: string;\n\treadonly checksBefore: readonly string[];\n\treadonly checksAfter: readonly string[];\n\treadonly knownCounterexamples: readonly string[];\n\treadonly applicabilityConditions: readonly string[];\n\treadonly evidenceRefs: readonly string[];\n\treadonly policyVersion: string;\n\treadonly skillHashes: readonly string[];\n}\nexport function validateExperienceRecord(r: ExperienceRecord): void {\n\ttext(r.recordId, \"recordId\", 128);\n\ttext(r.failureMechanism, \"failureMechanism\", 2048);\n\ttext(r.firstWrongExpectation, \"firstWrongExpectation\", 2048);\n\ttext(r.discriminatingObservation, \"discriminatingObservation\", 2048);\n\ttext(r.appliedFixOrStrategy, \"appliedFixOrStrategy\", 2048);\n\ttext(r.policyVersion, \"policyVersion\", 64);\n\tfor (const list of [\n\t\tr.checksBefore,\n\t\tr.checksAfter,\n\t\tr.knownCounterexamples,\n\t\tr.applicabilityConditions,\n\t\tr.evidenceRefs,\n\t\tr.skillHashes,\n\t]) {\n\t\tensure(Array.isArray(list) && list.length <= 128, \"experience record list bound\");\n\t}\n}\n\n/** §15.3 completion metrics. Zero denominators are `undefined`, never 0 or 1. */\nexport interface OutcomeCounts {\n\treadonly declaredComplete: number;\n\treadonly independentFailAmongDeclared: number;\n\treadonly allTasks: number;\n\treadonly succeeded: number;\n\treadonly abstained: number;\n\treadonly totalCost: number;\n}\nexport function completionMetrics(c: OutcomeCounts): {\n\treadonly falseCompletionDeclared?: number;\n\treadonly falseCompletionAll?: number;\n\treadonly successRate?: number;\n\treadonly abstainRate?: number;\n\treadonly meanCost?: number;\n} {\n\tinteger(c.declaredComplete, \"declaredComplete\");\n\tinteger(c.independentFailAmongDeclared, \"independentFail\");\n\tinteger(c.allTasks, \"allTasks\");\n\tinteger(c.succeeded, \"succeeded\");\n\tinteger(c.abstained, \"abstained\");\n\tfinite(c.totalCost, \"totalCost\");\n\tensure(c.independentFailAmongDeclared <= c.declaredComplete, \"fail count exceeds declared\");\n\tensure(\n\t\tc.declaredComplete <= c.allTasks && c.succeeded <= c.allTasks && c.abstained <= c.allTasks,\n\t\t\"counts exceed task total\",\n\t);\n\treturn {\n\t\tfalseCompletionDeclared: c.declaredComplete > 0 ? c.independentFailAmongDeclared / c.declaredComplete : undefined,\n\t\tfalseCompletionAll: c.allTasks > 0 ? c.independentFailAmongDeclared / c.allTasks : undefined,\n\t\tsuccessRate: c.allTasks > 0 ? c.succeeded / c.allTasks : undefined,\n\t\tabstainRate: c.allTasks > 0 ? c.abstained / c.allTasks : undefined,\n\t\tmeanCost: c.allTasks > 0 ? c.totalCost / c.allTasks : undefined,\n\t};\n}\n\n/** §15.3 hidden-obligation detection with false alarms, for held-out requirements. */\nexport function hiddenObligationMetrics(\n\tdetected: number,\n\ttotalHidden: number,\n\tfalseAlarms: number,\n): {\n\treadonly detectionRate?: number;\n\treadonly falseAlarms: number;\n} {\n\tinteger(detected, \"detected\");\n\tinteger(totalHidden, \"totalHidden\");\n\tinteger(falseAlarms, \"falseAlarms\");\n\tensure(detected <= totalHidden, \"detected exceeds hidden total\");\n\treturn {\n\t\tdetectionRate: totalHidden > 0 ? detected / totalHidden : undefined,\n\t\tfalseAlarms,\n\t};\n}\n"]}
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Metacognitive control kernel for OMK.
3
+ *
4
+ * Pure, deterministic, bounded modules implementing the observation /
5
+ * control / evaluation loop of OMK_metacognitive_control_algorithms_2026-09-19.
6
+ * Host-owned state only; no model output is ever treated as runner truth,
7
+ * and learned scores never relax a required approval or check.
8
+ */
9
+ export * from "./calibration.ts";
10
+ export * from "./calibration-selective.ts";
11
+ export * from "./checkpoint.ts";
12
+ export * from "./context7.ts";
13
+ export * from "./decision.ts";
14
+ export * from "./evaluation.ts";
15
+ export * from "./knowledge.ts";
16
+ export * from "./knowledge-action.ts";
17
+ export * from "./obligations.ts";
18
+ export * from "./observation-validity.ts";
19
+ export * from "./observe.ts";
20
+ export * from "./policy.ts";
21
+ export * from "./predictions.ts";
22
+ export * from "./retrieval.ts";
23
+ export * from "./risk.ts";
24
+ export * from "./route-economics.ts";
25
+ export * from "./runtime-bridge.ts";
26
+ export * from "./skills.ts";
27
+ export * from "./state.ts";
28
+ export * from "./validation.ts";
29
+ export * from "./verification.ts";
30
+ export * from "./verifier.ts";
31
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/metacognition/index.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,cAAc,kBAAkB,CAAC;AACjC,cAAc,4BAA4B,CAAC;AAC3C,cAAc,iBAAiB,CAAC;AAChC,cAAc,eAAe,CAAC;AAC9B,cAAc,eAAe,CAAC;AAC9B,cAAc,iBAAiB,CAAC;AAChC,cAAc,gBAAgB,CAAC;AAC/B,cAAc,uBAAuB,CAAC;AACtC,cAAc,kBAAkB,CAAC;AACjC,cAAc,2BAA2B,CAAC;AAC1C,cAAc,cAAc,CAAC;AAC7B,cAAc,aAAa,CAAC;AAC5B,cAAc,kBAAkB,CAAC;AACjC,cAAc,gBAAgB,CAAC;AAC/B,cAAc,WAAW,CAAC;AAC1B,cAAc,sBAAsB,CAAC;AACrC,cAAc,qBAAqB,CAAC;AACpC,cAAc,aAAa,CAAC;AAC5B,cAAc,YAAY,CAAC;AAC3B,cAAc,iBAAiB,CAAC;AAChC,cAAc,mBAAmB,CAAC;AAClC,cAAc,eAAe,CAAC","sourcesContent":["/**\n * Metacognitive control kernel for OMK.\n *\n * Pure, deterministic, bounded modules implementing the observation /\n * control / evaluation loop of OMK_metacognitive_control_algorithms_2026-09-19.\n * Host-owned state only; no model output is ever treated as runner truth,\n * and learned scores never relax a required approval or check.\n */\n\nexport * from \"./calibration.ts\";\nexport * from \"./calibration-selective.ts\";\nexport * from \"./checkpoint.ts\";\nexport * from \"./context7.ts\";\nexport * from \"./decision.ts\";\nexport * from \"./evaluation.ts\";\nexport * from \"./knowledge.ts\";\nexport * from \"./knowledge-action.ts\";\nexport * from \"./obligations.ts\";\nexport * from \"./observation-validity.ts\";\nexport * from \"./observe.ts\";\nexport * from \"./policy.ts\";\nexport * from \"./predictions.ts\";\nexport * from \"./retrieval.ts\";\nexport * from \"./risk.ts\";\nexport * from \"./route-economics.ts\";\nexport * from \"./runtime-bridge.ts\";\nexport * from \"./skills.ts\";\nexport * from \"./state.ts\";\nexport * from \"./validation.ts\";\nexport * from \"./verification.ts\";\nexport * from \"./verifier.ts\";\n"]}
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Metacognitive control kernel for OMK.
3
+ *
4
+ * Pure, deterministic, bounded modules implementing the observation /
5
+ * control / evaluation loop of OMK_metacognitive_control_algorithms_2026-09-19.
6
+ * Host-owned state only; no model output is ever treated as runner truth,
7
+ * and learned scores never relax a required approval or check.
8
+ */
9
+ export * from "./calibration.js";
10
+ export * from "./calibration-selective.js";
11
+ export * from "./checkpoint.js";
12
+ export * from "./context7.js";
13
+ export * from "./decision.js";
14
+ export * from "./evaluation.js";
15
+ export * from "./knowledge.js";
16
+ export * from "./knowledge-action.js";
17
+ export * from "./obligations.js";
18
+ export * from "./observation-validity.js";
19
+ export * from "./observe.js";
20
+ export * from "./policy.js";
21
+ export * from "./predictions.js";
22
+ export * from "./retrieval.js";
23
+ export * from "./risk.js";
24
+ export * from "./route-economics.js";
25
+ export * from "./runtime-bridge.js";
26
+ export * from "./skills.js";
27
+ export * from "./state.js";
28
+ export * from "./validation.js";
29
+ export * from "./verification.js";
30
+ export * from "./verifier.js";
31
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/metacognition/index.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,cAAc,kBAAkB,CAAC;AACjC,cAAc,4BAA4B,CAAC;AAC3C,cAAc,iBAAiB,CAAC;AAChC,cAAc,eAAe,CAAC;AAC9B,cAAc,eAAe,CAAC;AAC9B,cAAc,iBAAiB,CAAC;AAChC,cAAc,gBAAgB,CAAC;AAC/B,cAAc,uBAAuB,CAAC;AACtC,cAAc,kBAAkB,CAAC;AACjC,cAAc,2BAA2B,CAAC;AAC1C,cAAc,cAAc,CAAC;AAC7B,cAAc,aAAa,CAAC;AAC5B,cAAc,kBAAkB,CAAC;AACjC,cAAc,gBAAgB,CAAC;AAC/B,cAAc,WAAW,CAAC;AAC1B,cAAc,sBAAsB,CAAC;AACrC,cAAc,qBAAqB,CAAC;AACpC,cAAc,aAAa,CAAC;AAC5B,cAAc,YAAY,CAAC;AAC3B,cAAc,iBAAiB,CAAC;AAChC,cAAc,mBAAmB,CAAC;AAClC,cAAc,eAAe,CAAC","sourcesContent":["/**\n * Metacognitive control kernel for OMK.\n *\n * Pure, deterministic, bounded modules implementing the observation /\n * control / evaluation loop of OMK_metacognitive_control_algorithms_2026-09-19.\n * Host-owned state only; no model output is ever treated as runner truth,\n * and learned scores never relax a required approval or check.\n */\n\nexport * from \"./calibration.ts\";\nexport * from \"./calibration-selective.ts\";\nexport * from \"./checkpoint.ts\";\nexport * from \"./context7.ts\";\nexport * from \"./decision.ts\";\nexport * from \"./evaluation.ts\";\nexport * from \"./knowledge.ts\";\nexport * from \"./knowledge-action.ts\";\nexport * from \"./obligations.ts\";\nexport * from \"./observation-validity.ts\";\nexport * from \"./observe.ts\";\nexport * from \"./policy.ts\";\nexport * from \"./predictions.ts\";\nexport * from \"./retrieval.ts\";\nexport * from \"./risk.ts\";\nexport * from \"./route-economics.ts\";\nexport * from \"./runtime-bridge.ts\";\nexport * from \"./skills.ts\";\nexport * from \"./state.ts\";\nexport * from \"./validation.ts\";\nexport * from \"./verification.ts\";\nexport * from \"./verifier.ts\";\n"]}
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Bounded next-action selector for knowledge gaps.
3
+ *
4
+ * Split from knowledge.ts to keep each module under the repository's
5
+ * 250-line module-size ratchet. Same behavior as the reference port.
6
+ */
7
+ import type { Claim, KnowledgeReport } from "./knowledge.ts";
8
+ export type SearchChannel = "local" | "official" | "web";
9
+ export interface SearchAttempt {
10
+ readonly claimId: string;
11
+ readonly binding: string;
12
+ readonly channel: SearchChannel;
13
+ readonly result: "empty" | "failed" | "candidates" | "in-flight";
14
+ }
15
+ export interface ActionPolicy {
16
+ readonly availableChannels: readonly SearchChannel[];
17
+ readonly remoteQueryApprovedClaimIds: readonly string[];
18
+ readonly remainingRequests: number;
19
+ readonly remainingMs: number;
20
+ }
21
+ export type KnowledgeAction = {
22
+ readonly kind: "proceed";
23
+ readonly meaning: "evidence-predicates-satisfied-not-general-correctness";
24
+ } | {
25
+ readonly kind: "search";
26
+ readonly claimId: string;
27
+ readonly channel: SearchChannel;
28
+ readonly query: string;
29
+ } | {
30
+ readonly kind: "run-check";
31
+ readonly claimId: string;
32
+ readonly checkId: string;
33
+ } | {
34
+ readonly kind: "inspect-local" | "repair" | "review-candidates" | "await-owned-work" | "ask-user" | "form-obligations";
35
+ readonly claimId: string;
36
+ } | {
37
+ readonly kind: "blocked";
38
+ readonly claimId: string;
39
+ readonly reason: string;
40
+ };
41
+ /** One bounded next action, not an autonomous recursion that can spend unbounded API calls. */
42
+ export declare function nextKnowledgeAction(report: KnowledgeReport, claims: readonly Claim[], attempts: readonly SearchAttempt[], policy: ActionPolicy): KnowledgeAction;
43
+ //# sourceMappingURL=knowledge-action.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"knowledge-action.d.ts","sourceRoot":"","sources":["../../src/metacognition/knowledge-action.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAAE,KAAK,EAAE,eAAe,EAAE,MAAM,gBAAgB,CAAC;AAG7D,MAAM,MAAM,aAAa,GAAG,OAAO,GAAG,UAAU,GAAG,KAAK,CAAC;AACzD,MAAM,WAAW,aAAa;IAC7B,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,OAAO,EAAE,aAAa,CAAC;IAChC,QAAQ,CAAC,MAAM,EAAE,OAAO,GAAG,QAAQ,GAAG,YAAY,GAAG,WAAW,CAAC;CACjE;AACD,MAAM,WAAW,YAAY;IAC5B,QAAQ,CAAC,iBAAiB,EAAE,SAAS,aAAa,EAAE,CAAC;IACrD,QAAQ,CAAC,2BAA2B,EAAE,SAAS,MAAM,EAAE,CAAC;IACxD,QAAQ,CAAC,iBAAiB,EAAE,MAAM,CAAC;IACnC,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;CAC7B;AACD,MAAM,MAAM,eAAe,GACxB;IAAE,QAAQ,CAAC,IAAI,EAAE,SAAS,CAAC;IAAC,QAAQ,CAAC,OAAO,EAAE,uDAAuD,CAAA;CAAE,GACvG;IAAE,QAAQ,CAAC,IAAI,EAAE,QAAQ,CAAC;IAAC,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,OAAO,EAAE,aAAa,CAAC;IAAC,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAA;CAAE,GAC9G;IAAE,QAAQ,CAAC,IAAI,EAAE,WAAW,CAAC;IAAC,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAA;CAAE,GAClF;IACA,QAAQ,CAAC,IAAI,EACV,eAAe,GACf,QAAQ,GACR,mBAAmB,GACnB,kBAAkB,GAClB,UAAU,GACV,kBAAkB,CAAC;IACtB,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;CACxB,GACD;IAAE,QAAQ,CAAC,IAAI,EAAE,SAAS,CAAC;IAAC,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAAC;AAEnF,+FAA+F;AAC/F,wBAAgB,mBAAmB,CAClC,MAAM,EAAE,eAAe,EACvB,MAAM,EAAE,SAAS,KAAK,EAAE,EACxB,QAAQ,EAAE,SAAS,aAAa,EAAE,EAClC,MAAM,EAAE,YAAY,GAClB,eAAe,CAwCjB","sourcesContent":["/**\n * Bounded next-action selector for knowledge gaps.\n *\n * Split from knowledge.ts to keep each module under the repository's\n * 250-line module-size ratchet. Same behavior as the reference port.\n */\n\nimport type { Claim, KnowledgeReport } from \"./knowledge.ts\";\nimport { ensure, integer, member, text, unique } from \"./validation.ts\";\n\nexport type SearchChannel = \"local\" | \"official\" | \"web\";\nexport interface SearchAttempt {\n\treadonly claimId: string;\n\treadonly binding: string;\n\treadonly channel: SearchChannel;\n\treadonly result: \"empty\" | \"failed\" | \"candidates\" | \"in-flight\";\n}\nexport interface ActionPolicy {\n\treadonly availableChannels: readonly SearchChannel[];\n\treadonly remoteQueryApprovedClaimIds: readonly string[];\n\treadonly remainingRequests: number;\n\treadonly remainingMs: number;\n}\nexport type KnowledgeAction =\n\t| { readonly kind: \"proceed\"; readonly meaning: \"evidence-predicates-satisfied-not-general-correctness\" }\n\t| { readonly kind: \"search\"; readonly claimId: string; readonly channel: SearchChannel; readonly query: string }\n\t| { readonly kind: \"run-check\"; readonly claimId: string; readonly checkId: string }\n\t| {\n\t\t\treadonly kind:\n\t\t\t\t| \"inspect-local\"\n\t\t\t\t| \"repair\"\n\t\t\t\t| \"review-candidates\"\n\t\t\t\t| \"await-owned-work\"\n\t\t\t\t| \"ask-user\"\n\t\t\t\t| \"form-obligations\";\n\t\t\treadonly claimId: string;\n\t }\n\t| { readonly kind: \"blocked\"; readonly claimId: string; readonly reason: string };\n\n/** One bounded next action, not an autonomous recursion that can spend unbounded API calls. */\nexport function nextKnowledgeAction(\n\treport: KnowledgeReport,\n\tclaims: readonly Claim[],\n\tattempts: readonly SearchAttempt[],\n\tpolicy: ActionPolicy,\n): KnowledgeAction {\n\tinteger(policy.remainingRequests, \"remainingRequests\");\n\tinteger(policy.remainingMs, \"remainingMs\");\n\tunique(policy.availableChannels, \"availableChannels\", 3);\n\tfor (const channel of policy.availableChannels) member(channel, [\"local\", \"official\", \"web\"], \"search channel\");\n\tunique(policy.remoteQueryApprovedClaimIds, \"remote approvals\", 128);\n\tensure(attempts.length <= 4096, \"too many search attempts\");\n\tfor (const attempt of attempts) {\n\t\ttext(attempt.claimId, \"attempt claim\");\n\t\ttext(attempt.binding, \"attempt binding\");\n\t\tmember(attempt.channel, [\"local\", \"official\", \"web\"], \"attempt channel\");\n\t\tmember(attempt.result, [\"empty\", \"failed\", \"candidates\", \"in-flight\"], \"attempt result\");\n\t}\n\tconst gap = report.gaps.find((g) => g.required);\n\tif (!gap) return { kind: \"proceed\", meaning: \"evidence-predicates-satisfied-not-general-correctness\" };\n\tconst claimId = gap.claimId;\n\tif (gap.reason === \"unassessed-step\") return { kind: \"form-obligations\", claimId };\n\tif (gap.reason === \"missing-user-decision\") return { kind: \"ask-user\", claimId };\n\tif (gap.reason === \"unknown-version\") return { kind: \"inspect-local\", claimId };\n\tif (gap.reason === \"failed-check\") return { kind: \"repair\", claimId };\n\tif (gap.reason === \"pending-check\") return { kind: \"await-owned-work\", claimId };\n\tif (gap.reason === \"missing-check\") {\n\t\tensure(gap.checkId !== null, \"missing checkId\");\n\t\treturn { kind: \"run-check\", claimId, checkId: gap.checkId };\n\t}\n\tconst claim = claims.find((c) => c.id === claimId && c.binding === gap.binding);\n\tensure(claim !== undefined, \"report has stale or unknown claim\");\n\tconst history = attempts.filter((a) => a.claimId === claimId && a.binding === gap.binding);\n\tif (history.some((a) => a.result === \"in-flight\")) return { kind: \"await-owned-work\", claimId };\n\tif (history.some((a) => a.result === \"candidates\")) return { kind: \"review-candidates\", claimId };\n\tif (policy.remainingRequests === 0 || policy.remainingMs === 0) {\n\t\treturn { kind: \"blocked\", claimId, reason: \"acquisition-budget-exhausted\" };\n\t}\n\tfor (const channel of [\"local\", \"official\", \"web\"] as const) {\n\t\tif (!policy.availableChannels.includes(channel) || history.some((a) => a.channel === channel)) continue;\n\t\tif (channel !== \"local\" && (!policy.remoteQueryApprovedClaimIds.includes(claimId) || claim.publicQuery === null))\n\t\t\tcontinue;\n\t\treturn { kind: \"search\", claimId, channel, query: channel === \"local\" ? claim.statement : claim.publicQuery! };\n\t}\n\treturn { kind: \"blocked\", claimId, reason: \"no-approved-untried-source\" };\n}\n"]}
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Bounded next-action selector for knowledge gaps.
3
+ *
4
+ * Split from knowledge.ts to keep each module under the repository's
5
+ * 250-line module-size ratchet. Same behavior as the reference port.
6
+ */
7
+ import { ensure, integer, member, text, unique } from "./validation.js";
8
+ /** One bounded next action, not an autonomous recursion that can spend unbounded API calls. */
9
+ export function nextKnowledgeAction(report, claims, attempts, policy) {
10
+ integer(policy.remainingRequests, "remainingRequests");
11
+ integer(policy.remainingMs, "remainingMs");
12
+ unique(policy.availableChannels, "availableChannels", 3);
13
+ for (const channel of policy.availableChannels)
14
+ member(channel, ["local", "official", "web"], "search channel");
15
+ unique(policy.remoteQueryApprovedClaimIds, "remote approvals", 128);
16
+ ensure(attempts.length <= 4096, "too many search attempts");
17
+ for (const attempt of attempts) {
18
+ text(attempt.claimId, "attempt claim");
19
+ text(attempt.binding, "attempt binding");
20
+ member(attempt.channel, ["local", "official", "web"], "attempt channel");
21
+ member(attempt.result, ["empty", "failed", "candidates", "in-flight"], "attempt result");
22
+ }
23
+ const gap = report.gaps.find((g) => g.required);
24
+ if (!gap)
25
+ return { kind: "proceed", meaning: "evidence-predicates-satisfied-not-general-correctness" };
26
+ const claimId = gap.claimId;
27
+ if (gap.reason === "unassessed-step")
28
+ return { kind: "form-obligations", claimId };
29
+ if (gap.reason === "missing-user-decision")
30
+ return { kind: "ask-user", claimId };
31
+ if (gap.reason === "unknown-version")
32
+ return { kind: "inspect-local", claimId };
33
+ if (gap.reason === "failed-check")
34
+ return { kind: "repair", claimId };
35
+ if (gap.reason === "pending-check")
36
+ return { kind: "await-owned-work", claimId };
37
+ if (gap.reason === "missing-check") {
38
+ ensure(gap.checkId !== null, "missing checkId");
39
+ return { kind: "run-check", claimId, checkId: gap.checkId };
40
+ }
41
+ const claim = claims.find((c) => c.id === claimId && c.binding === gap.binding);
42
+ ensure(claim !== undefined, "report has stale or unknown claim");
43
+ const history = attempts.filter((a) => a.claimId === claimId && a.binding === gap.binding);
44
+ if (history.some((a) => a.result === "in-flight"))
45
+ return { kind: "await-owned-work", claimId };
46
+ if (history.some((a) => a.result === "candidates"))
47
+ return { kind: "review-candidates", claimId };
48
+ if (policy.remainingRequests === 0 || policy.remainingMs === 0) {
49
+ return { kind: "blocked", claimId, reason: "acquisition-budget-exhausted" };
50
+ }
51
+ for (const channel of ["local", "official", "web"]) {
52
+ if (!policy.availableChannels.includes(channel) || history.some((a) => a.channel === channel))
53
+ continue;
54
+ if (channel !== "local" && (!policy.remoteQueryApprovedClaimIds.includes(claimId) || claim.publicQuery === null))
55
+ continue;
56
+ return { kind: "search", claimId, channel, query: channel === "local" ? claim.statement : claim.publicQuery };
57
+ }
58
+ return { kind: "blocked", claimId, reason: "no-approved-untried-source" };
59
+ }
60
+ //# sourceMappingURL=knowledge-action.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"knowledge-action.js","sourceRoot":"","sources":["../../src/metacognition/knowledge-action.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAGH,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAC;AA+BxE,+FAA+F;AAC/F,MAAM,UAAU,mBAAmB,CAClC,MAAuB,EACvB,MAAwB,EACxB,QAAkC,EAClC,MAAoB,EACF;IAClB,OAAO,CAAC,MAAM,CAAC,iBAAiB,EAAE,mBAAmB,CAAC,CAAC;IACvD,OAAO,CAAC,MAAM,CAAC,WAAW,EAAE,aAAa,CAAC,CAAC;IAC3C,MAAM,CAAC,MAAM,CAAC,iBAAiB,EAAE,mBAAmB,EAAE,CAAC,CAAC,CAAC;IACzD,KAAK,MAAM,OAAO,IAAI,MAAM,CAAC,iBAAiB;QAAE,MAAM,CAAC,OAAO,EAAE,CAAC,OAAO,EAAE,UAAU,EAAE,KAAK,CAAC,EAAE,gBAAgB,CAAC,CAAC;IAChH,MAAM,CAAC,MAAM,CAAC,2BAA2B,EAAE,kBAAkB,EAAE,GAAG,CAAC,CAAC;IACpE,MAAM,CAAC,QAAQ,CAAC,MAAM,IAAI,IAAI,EAAE,0BAA0B,CAAC,CAAC;IAC5D,KAAK,MAAM,OAAO,IAAI,QAAQ,EAAE,CAAC;QAChC,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE,eAAe,CAAC,CAAC;QACvC,IAAI,CAAC,OAAO,CAAC,OAAO,EAAE,iBAAiB,CAAC,CAAC;QACzC,MAAM,CAAC,OAAO,CAAC,OAAO,EAAE,CAAC,OAAO,EAAE,UAAU,EAAE,KAAK,CAAC,EAAE,iBAAiB,CAAC,CAAC;QACzE,MAAM,CAAC,OAAO,CAAC,MAAM,EAAE,CAAC,OAAO,EAAE,QAAQ,EAAE,YAAY,EAAE,WAA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AO,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,KAAK,OAAO,CAAC,CAAC,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC,CAAC,KAAK,CAAC,WAAY,EAAE,CAAC;IAChH,CAAC;IACD,OAAO,EAAE,IAAI,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,EAAE,4BAA4B,EAAE,CAAC;AAAA,CAC1E","sourcesContent":["/**\n * Bounded next-action selector for knowledge gaps.\n *\n * Split from knowledge.ts to keep each module under the repository's\n * 250-line module-size ratchet. Same behavior as the reference port.\n */\n\nimport type { Claim, KnowledgeReport } from \"./knowledge.ts\";\nimport { ensure, integer, member, text, unique } from \"./validation.ts\";\n\nexport type SearchChannel = \"local\" | \"official\" | \"web\";\nexport interface SearchAttempt {\n\treadonly claimId: string;\n\treadonly binding: string;\n\treadonly channel: SearchChannel;\n\treadonly result: \"empty\" | \"failed\" | \"candidates\" | \"in-flight\";\n}\nexport interface ActionPolicy {\n\treadonly availableChannels: readonly SearchChannel[];\n\treadonly remoteQueryApprovedClaimIds: readonly string[];\n\treadonly remainingRequests: number;\n\treadonly remainingMs: number;\n}\nexport type KnowledgeAction =\n\t| { readonly kind: \"proceed\"; readonly meaning: \"evidence-predicates-satisfied-not-general-correctness\" }\n\t| { readonly kind: \"search\"; readonly claimId: string; readonly channel: SearchChannel; readonly query: string }\n\t| { readonly kind: \"run-check\"; readonly claimId: string; readonly checkId: string }\n\t| {\n\t\t\treadonly kind:\n\t\t\t\t| \"inspect-local\"\n\t\t\t\t| \"repair\"\n\t\t\t\t| \"review-candidates\"\n\t\t\t\t| \"await-owned-work\"\n\t\t\t\t| \"ask-user\"\n\t\t\t\t| \"form-obligations\";\n\t\t\treadonly claimId: string;\n\t }\n\t| { readonly kind: \"blocked\"; readonly claimId: string; readonly reason: string };\n\n/** One bounded next action, not an autonomous recursion that can spend unbounded API calls. */\nexport function nextKnowledgeAction(\n\treport: KnowledgeReport,\n\tclaims: readonly Claim[],\n\tattempts: readonly SearchAttempt[],\n\tpolicy: ActionPolicy,\n): KnowledgeAction {\n\tinteger(policy.remainingRequests, \"remainingRequests\");\n\tinteger(policy.remainingMs, \"remainingMs\");\n\tunique(policy.availableChannels, \"availableChannels\", 3);\n\tfor (const channel of policy.availableChannels) member(channel, [\"local\", \"official\", \"web\"], \"search channel\");\n\tunique(policy.remoteQueryApprovedClaimIds, \"remote approvals\", 128);\n\tensure(attempts.length <= 4096, \"too many search attempts\");\n\tfor (const attempt of attempts) {\n\t\ttext(attempt.claimId, \"attempt claim\");\n\t\ttext(attempt.binding, \"attempt binding\");\n\t\tmember(attempt.channel, [\"local\", \"official\", \"web\"], \"attempt channel\");\n\t\tmember(attempt.result, [\"empty\", \"failed\", \"candidates\", \"in-flight\"], \"attempt result\");\n\t}\n\tconst gap = report.gaps.find((g) => g.required);\n\tif (!gap) return { kind: \"proceed\", meaning: \"evidence-predicates-satisfied-not-general-correctness\" };\n\tconst claimId = gap.claimId;\n\tif (gap.reason === \"unassessed-step\") return { kind: \"form-obligations\", claimId };\n\tif (gap.reason === \"missing-user-decision\") return { kind: \"ask-user\", claimId };\n\tif (gap.reason === \"unknown-version\") return { kind: \"inspect-local\", claimId };\n\tif (gap.reason === \"failed-check\") return { kind: \"repair\", claimId };\n\tif (gap.reason === \"pending-check\") return { kind: \"await-owned-work\", claimId };\n\tif (gap.reason === \"missing-check\") {\n\t\tensure(gap.checkId !== null, \"missing checkId\");\n\t\treturn { kind: \"run-check\", claimId, checkId: gap.checkId };\n\t}\n\tconst claim = claims.find((c) => c.id === claimId && c.binding === gap.binding);\n\tensure(claim !== undefined, \"report has stale or unknown claim\");\n\tconst history = attempts.filter((a) => a.claimId === claimId && a.binding === gap.binding);\n\tif (history.some((a) => a.result === \"in-flight\")) return { kind: \"await-owned-work\", claimId };\n\tif (history.some((a) => a.result === \"candidates\")) return { kind: \"review-candidates\", claimId };\n\tif (policy.remainingRequests === 0 || policy.remainingMs === 0) {\n\t\treturn { kind: \"blocked\", claimId, reason: \"acquisition-budget-exhausted\" };\n\t}\n\tfor (const channel of [\"local\", \"official\", \"web\"] as const) {\n\t\tif (!policy.availableChannels.includes(channel) || history.some((a) => a.channel === channel)) continue;\n\t\tif (channel !== \"local\" && (!policy.remoteQueryApprovedClaimIds.includes(claimId) || claim.publicQuery === null))\n\t\t\tcontinue;\n\t\treturn { kind: \"search\", claimId, channel, query: channel === \"local\" ? claim.statement : claim.publicQuery! };\n\t}\n\treturn { kind: \"blocked\", claimId, reason: \"no-approved-untried-source\" };\n}\n"]}
@@ -0,0 +1,84 @@
1
+ export type Stage = "before-change" | "after-change";
2
+ export interface Claim {
3
+ readonly id: string;
4
+ /** Hash/fingerprint computed by the host over the relevant subject and environment. */
5
+ readonly binding: string;
6
+ readonly phase: "precondition" | "postcondition";
7
+ readonly statement: string;
8
+ readonly required: boolean;
9
+ readonly impact: number;
10
+ readonly needsReference: boolean;
11
+ readonly requiresVersion: boolean;
12
+ readonly version: string | null;
13
+ readonly minSourceFamilies: number;
14
+ readonly requiredCheckIds: readonly string[];
15
+ readonly needsUserDecision: boolean;
16
+ /** Only explicit, host-approved public text can leave the repository. */
17
+ readonly publicQuery: string | null;
18
+ }
19
+ export interface SourceIdentity {
20
+ readonly id: string;
21
+ readonly family: string;
22
+ readonly kind: "repository" | "official" | "community" | "model";
23
+ }
24
+ interface ObservationBase {
25
+ readonly id: string;
26
+ readonly claimId: string;
27
+ readonly binding: string;
28
+ readonly observedAtMs: number;
29
+ readonly expiresAtMs: number;
30
+ }
31
+ export interface ReferenceObservation extends ObservationBase {
32
+ readonly kind: "reference";
33
+ readonly sourceId: string;
34
+ readonly version: string | null;
35
+ readonly stance: "support" | "refute";
36
+ readonly documentDigest: string;
37
+ readonly locator: string;
38
+ }
39
+ export interface CheckObservation extends ObservationBase {
40
+ readonly kind: "check";
41
+ readonly runnerId: string;
42
+ readonly checkId: string;
43
+ /** Host-ordered snapshot. In OMK, project the existing strict evidence ledger here. */
44
+ readonly sequence: number;
45
+ readonly verdict: "pass" | "fail" | "pending";
46
+ }
47
+ export interface DecisionObservation extends ObservationBase {
48
+ readonly kind: "decision";
49
+ readonly actorId: string;
50
+ readonly accepted: boolean;
51
+ }
52
+ export type Observation = ReferenceObservation | CheckObservation | DecisionObservation;
53
+ export type GapReason = "unassessed-step" | "unknown-version" | "unsupported-reference" | "contradictory-reference" | "missing-check" | "failed-check" | "pending-check" | "missing-user-decision";
54
+ export interface KnowledgeGap {
55
+ readonly claimId: string;
56
+ readonly binding: string;
57
+ readonly reason: GapReason;
58
+ readonly required: boolean;
59
+ readonly impact: number;
60
+ readonly checkId: string | null;
61
+ }
62
+ export interface KnowledgeReport {
63
+ readonly state: "supported" | "gaps";
64
+ readonly gaps: readonly KnowledgeGap[];
65
+ readonly supportedClaimIds: readonly string[];
66
+ readonly rejectedObservations: readonly {
67
+ id: string;
68
+ reason: string;
69
+ }[];
70
+ }
71
+ export interface KnowledgeInput {
72
+ readonly stage: Stage;
73
+ readonly requiresAssessment: boolean;
74
+ readonly nowMs: number;
75
+ readonly claims: readonly Claim[];
76
+ /** Admitted host observations only. Never pass a model's JSON here as runner truth. */
77
+ readonly observations: readonly Observation[];
78
+ readonly sources: readonly SourceIdentity[];
79
+ readonly trustedRunnerIds: readonly string[];
80
+ readonly decisionActorIds: readonly string[];
81
+ }
82
+ export declare function inspectKnowledge(input: KnowledgeInput): KnowledgeReport;
83
+ export {};
84
+ //# sourceMappingURL=knowledge.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"knowledge.d.ts","sourceRoot":"","sources":["../../src/metacognition/knowledge.ts"],"names":[],"mappings":"AASA,MAAM,MAAM,KAAK,GAAG,eAAe,GAAG,cAAc,CAAC;AACrD,MAAM,WAAW,KAAK;IACrB,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,uFAAuF;IACvF,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,KAAK,EAAE,cAAc,GAAG,eAAe,CAAC;I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;IAC9C,QAAQ,CAAC,oBAAoB,EAAE,SAAS;QAAE,EAAE,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,EAAE,CAAC;CACzE;AACD,MAAM,WAAW,cAAc;IAC9B,QAAQ,CAAC,KAAK,EAAE,KAAK,CAAC;IACtB,QAAQ,CAAC,kBAAkB,EAAE,OAAO,CAAC;IACrC,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,QAAQ,CAAC,MAAM,EAAE,SAAS,KAAK,EAAE,CAAC;IAClC,uFAAuF;IACvF,QAAQ,CAAC,YAAY,EAAE,SAAS,WAAW,EAAE,CAAC;IAC9C,QAAQ,CAAC,OAAO,EAAE,SAAS,cAAc,EAAE,CAAC;IAC5C,QAAQ,CAAC,gBAAgB,EAAE,SAAS,MAAM,EAAE,CAAC;IAC7C,QAAQ,CAAC,gBAAgB,EAAE,SAAS,MAAM,EAAE,CAAC;CAC7C;AAED,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,cAAc,GAAG,eAAe,CAuJvE","sourcesContent":["/**\n * Claim/evidence gap inspection and the bounded next-action selector.\n *\n * Ported from docs/OMK_skill_knowledge_control_2026-09-19.zip\n * (src/knowledge.ts). Host-owned observations only; a model's JSON is never\n * runner truth. See OMK_metacognitive_control_algorithms_2026-09-19.md §13.\n */\nimport { canonical, ensure, integer, lexical, member, text, unique } from \"./validation.ts\";\n\nexport type Stage = \"before-change\" | \"after-change\";\nexport interface Claim {\n\treadonly id: string;\n\t/** Hash/fingerprint computed by the host over the relevant subject and environment. */\n\treadonly binding: string;\n\treadonly phase: \"precondition\" | \"postcondition\";\n\treadonly statement: string;\n\treadonly required: boolean;\n\treadonly impact: number;\n\treadonly needsReference: boolean;\n\treadonly requiresVersion: boolean;\n\treadonly version: string | null;\n\treadonly minSourceFamilies: number;\n\treadonly requiredCheckIds: readonly string[];\n\treadonly needsUserDecision: boolean;\n\t/** Only explicit, host-approved public text can leave the repository. */\n\treadonly publicQuery: string | null;\n}\nexport interface SourceIdentity {\n\treadonly id: string;\n\treadonly family: string;\n\treadonly kind: \"repository\" | \"official\" | \"community\" | \"model\";\n}\ninterface ObservationBase {\n\treadonly id: string;\n\treadonly claimId: string;\n\treadonly binding: string;\n\treadonly observedAtMs: number;\n\treadonly expiresAtMs: number;\n}\nexport interface ReferenceObservation extends ObservationBase {\n\treadonly kind: \"reference\";\n\treadonly sourceId: string;\n\treadonly version: string | null;\n\treadonly stance: \"support\" | \"refute\";\n\treadonly documentDigest: string;\n\treadonly locator: string;\n}\nexport interface CheckObservation extends ObservationBase {\n\treadonly kind: \"check\";\n\treadonly runnerId: string;\n\treadonly checkId: string;\n\t/** Host-ordered snapshot. In OMK, project the existing strict evidence ledger here. */\n\treadonly sequence: number;\n\treadonly verdict: \"pass\" | \"fail\" | \"pending\";\n}\nexport interface DecisionObservation extends ObservationBase {\n\treadonly kind: \"decision\";\n\treadonly actorId: string;\n\treadonly accepted: boolean;\n}\nexport type Observation = ReferenceObservation | CheckObservation | DecisionObservation;\nexport type GapReason =\n\t| \"unassessed-step\"\n\t| \"unknown-version\"\n\t| \"unsupported-reference\"\n\t| \"contradictory-reference\"\n\t| \"missing-check\"\n\t| \"failed-check\"\n\t| \"pending-check\"\n\t| \"missing-user-decision\";\nexport interface KnowledgeGap {\n\treadonly claimId: string;\n\treadonly binding: string;\n\treadonly reason: GapReason;\n\treadonly required: boolean;\n\treadonly impact: number;\n\treadonly checkId: string | null;\n}\nexport interface KnowledgeReport {\n\treadonly state: \"supported\" | \"gaps\";\n\treadonly gaps: readonly KnowledgeGap[];\n\treadonly supportedClaimIds: readonly string[];\n\treadonly rejectedObservations: readonly { id: string; reason: string }[];\n}\nexport interface KnowledgeInput {\n\treadonly stage: Stage;\n\treadonly requiresAssessment: boolean;\n\treadonly nowMs: number;\n\treadonly claims: readonly Claim[];\n\t/** Admitted host observations only. Never pass a model's JSON here as runner truth. */\n\treadonly observations: readonly Observation[];\n\treadonly sources: readonly SourceIdentity[];\n\treadonly trustedRunnerIds: readonly string[];\n\treadonly decisionActorIds: readonly string[];\n}\n\nexport function inspectKnowledge(input: KnowledgeInput): KnowledgeReport {\n\tmember(input.stage, [\"before-change\", \"after-change\"], \"stage\");\n\tinteger(input.nowMs, \"nowMs\");\n\tensure(typeof input.requiresAssessment === \"boolean\", \"requiresAssessment must be boolean\");\n\tensure(input.claims.length <= 128 && input.observations.length <= 4096, \"knowledge input too large\");\n\tunique(\n\t\tinput.claims.map((c) => c.id),\n\t\t\"claim ids\",\n\t\t128,\n\t);\n\tunique(\n\t\tinput.sources.map((s) => s.id),\n\t\t\"source ids\",\n\t\t512,\n\t);\n\tunique(input.trustedRunnerIds, \"runner ids\");\n\tunique(input.decisionActorIds, \"decision actor ids\");\n\tfor (const c of input.claims) {\n\t\ttext(c.binding, \"binding\");\n\t\ttext(c.statement, \"statement\");\n\t\tmember(c.phase, [\"precondition\", \"postcondition\"], \"claim phase\");\n\t\tfor (const v of [c.required, c.needsReference, c.requiresVersion, c.needsUserDecision]) {\n\t\t\tensure(typeof v === \"boolean\", \"invalid claim flag\");\n\t\t}\n\t\tensure(Number.isFinite(c.impact) && c.impact >= 0 && c.impact <= 1_000_000, \"invalid impact\");\n\t\tinteger(c.minSourceFamilies, \"minSourceFamilies\", 16);\n\t\tensure(!c.needsReference || c.minSourceFamilies > 0, \"reference needs at least one source family\");\n\t\tif (c.version !== null) text(c.version, \"version\", 128);\n\t\tif (c.publicQuery !== null) text(c.publicQuery, \"publicQuery\", 500);\n\t\tunique(c.requiredCheckIds, \"check ids\", 128);\n\t\tensure(\n\t\t\tc.needsReference || c.requiredCheckIds.length > 0 || c.needsUserDecision,\n\t\t\t\"claim has no evidence predicate\",\n\t\t);\n\t}\n\tconst sources = new Map(\n\t\tinput.sources.map((s) => {\n\t\t\ttext(s.family, \"source family\");\n\t\t\tmember(s.kind, [\"repository\", \"official\", \"community\", \"model\"], \"source kind\");\n\t\t\treturn [s.id, s] as const;\n\t\t}),\n\t);\n\tconst observations = new Map<string, Observation>();\n\tconst sequences = new Map<string, string>();\n\tfor (const obs of input.observations) {\n\t\ttext(obs.id, \"observation id\");\n\t\ttext(obs.claimId, \"observation claim\");\n\t\ttext(obs.binding, \"observation binding\");\n\t\tinteger(obs.observedAtMs, \"observedAtMs\");\n\t\tinteger(obs.expiresAtMs, \"expiresAtMs\");\n\t\tensure(obs.expiresAtMs >= obs.observedAtMs, \"invalid observation validity interval\");\n\t\tmember(obs.kind, [\"reference\", \"check\", \"decision\"], \"observation kind\");\n\t\tif (obs.kind === \"reference\") {\n\t\t\ttext(obs.sourceId, \"sourceId\");\n\t\t\ttext(obs.documentDigest, \"documentDigest\");\n\t\t\ttext(obs.locator, \"locator\");\n\t\t\tif (obs.version !== null) text(obs.version, \"observation version\", 128);\n\t\t\tmember(obs.stance, [\"support\", \"refute\"], \"stance\");\n\t\t} else if (obs.kind === \"check\") {\n\t\t\ttext(obs.runnerId, \"runnerId\");\n\t\t\ttext(obs.checkId, \"checkId\");\n\t\t\tinteger(obs.sequence, \"sequence\");\n\t\t\tmember(obs.verdict, [\"pass\", \"fail\", \"pending\"], \"check verdict\");\n\t\t\tconst key = canonical([obs.claimId, obs.binding, obs.checkId, obs.sequence]);\n\t\t\tconst previous = sequences.get(key);\n\t\t\tensure(previous === undefined || previous === canonical(obs), \"conflicting check sequence\");\n\t\t\tsequences.set(key, canonical(obs));\n\t\t} else {\n\t\t\ttext(obs.actorId, \"actorId\");\n\t\t\tensure(typeof obs.accepted === \"boolean\", \"invalid decision\");\n\t\t}\n\t\tconst previous = observations.get(obs.id);\n\t\tensure(previous === undefined || canonical(previous) === canonical(obs), \"conflicting observation id\");\n\t\tobservations.set(obs.id, obs);\n\t}\n\tconst relevantClaims = input.claims.filter((c) => input.stage === \"after-change\" || c.phase === \"precondition\");\n\tconst rejectedObservations: { id: string; reason: string }[] = [];\n\tconst admissible = new Map<string, Observation[]>();\n\tconst claimMap = new Map(relevantClaims.map((c) => [c.id, c]));\n\tfor (const obs of observations.values()) {\n\t\tconst c = claimMap.get(obs.claimId);\n\t\tlet reason: string | undefined;\n\t\tif (!c) reason = \"irrelevant-claim-or-stage\";\n\t\telse if (obs.binding !== c.binding) reason = \"stale-binding\";\n\t\telse if (obs.observedAtMs > input.nowMs || obs.expiresAtMs <= input.nowMs) reason = \"expired-or-future\";\n\t\telse if (obs.kind === \"reference\") {\n\t\t\tconst source = sources.get(obs.sourceId);\n\t\t\tif (!source || (source.kind !== \"repository\" && source.kind !== \"official\")) reason = \"inadmissible-source\";\n\t\t\telse if (c.requiresVersion && (c.version === null || obs.version !== c.version)) reason = \"version-mismatch\";\n\t\t} else if (obs.kind === \"check\" && !input.trustedRunnerIds.includes(obs.runnerId)) reason = \"untrusted-runner\";\n\t\telse if (obs.kind === \"decision\" && !input.decisionActorIds.includes(obs.actorId)) {\n\t\t\treason = \"untrusted-decision-actor\";\n\t\t}\n\t\tif (reason) rejectedObservations.push({ id: obs.id, reason });\n\t\telse admissible.set(obs.claimId, [...(admissible.get(obs.claimId) ?? []), obs]);\n\t}\n\tconst gaps: KnowledgeGap[] = [];\n\tconst supportedClaimIds: string[] = [];\n\tif (input.requiresAssessment && relevantClaims.filter((c) => c.required).length === 0) {\n\t\tgaps.push({\n\t\t\tclaimId: \"$step\",\n\t\t\tbinding: \"unassessed\",\n\t\t\treason: \"unassessed-step\",\n\t\t\trequired: true,\n\t\t\timpact: 1_000_000,\n\t\t\tcheckId: null,\n\t\t});\n\t}\n\tfor (const c of relevantClaims) {\n\t\tconst before = gaps.length;\n\t\tconst evidence = admissible.get(c.id) ?? [];\n\t\tconst add = (reason: GapReason, checkId: string | null = null): void => {\n\t\t\tgaps.push({ claimId: c.id, binding: c.binding, reason, required: c.required, impact: c.impact, checkId });\n\t\t};\n\t\tif (c.requiresVersion && c.version === null) add(\"unknown-version\");\n\t\tif (c.needsReference) {\n\t\t\tconst refs = evidence.filter((obs): obs is ReferenceObservation => obs.kind === \"reference\");\n\t\t\tconst support = new Set(\n\t\t\t\trefs.filter((r) => r.stance === \"support\").map((r) => sources.get(r.sourceId)!.family),\n\t\t\t);\n\t\t\tif (refs.some((r) => r.stance === \"refute\")) add(\"contradictory-reference\");\n\t\t\telse if (support.size < c.minSourceFamilies) add(\"unsupported-reference\");\n\t\t}\n\t\tfor (const checkId of c.requiredCheckIds) {\n\t\t\tconst records = evidence\n\t\t\t\t.filter((obs): obs is CheckObservation => obs.kind === \"check\" && obs.checkId === checkId)\n\t\t\t\t.sort((a, b) => a.sequence - b.sequence);\n\t\t\tconst latest = records.at(-1);\n\t\t\tif (!latest) add(\"missing-check\", checkId);\n\t\t\telse if (latest.verdict === \"fail\") add(\"failed-check\", checkId);\n\t\t\telse if (latest.verdict === \"pending\") add(\"pending-check\", checkId);\n\t\t}\n\t\tif (c.needsUserDecision) {\n\t\t\tconst decisions = evidence.filter((obs): obs is DecisionObservation => obs.kind === \"decision\");\n\t\t\tif (!decisions.some((d) => d.accepted) || decisions.some((d) => !d.accepted)) add(\"missing-user-decision\");\n\t\t}\n\t\tif (before === gaps.length) supportedClaimIds.push(c.id);\n\t}\n\tgaps.sort(\n\t\t(a, b) =>\n\t\t\tNumber(b.required) - Number(a.required) ||\n\t\t\tb.impact - a.impact ||\n\t\t\tlexical(a.claimId, b.claimId) ||\n\t\t\tlexical(a.reason, b.reason),\n\t);\n\treturn {\n\t\tstate: gaps.some((g) => g.required) ? \"gaps\" : \"supported\",\n\t\tgaps,\n\t\tsupportedClaimIds: supportedClaimIds.sort(lexical),\n\t\trejectedObservations,\n\t};\n}\n"]}
@@ -0,0 +1,165 @@
1
+ /**
2
+ * Claim/evidence gap inspection and the bounded next-action selector.
3
+ *
4
+ * Ported from docs/OMK_skill_knowledge_control_2026-09-19.zip
5
+ * (src/knowledge.ts). Host-owned observations only; a model's JSON is never
6
+ * runner truth. See OMK_metacognitive_control_algorithms_2026-09-19.md §13.
7
+ */
8
+ import { canonical, ensure, integer, lexical, member, text, unique } from "./validation.js";
9
+ export function inspectKnowledge(input) {
10
+ member(input.stage, ["before-change", "after-change"], "stage");
11
+ integer(input.nowMs, "nowMs");
12
+ ensure(typeof input.requiresAssessment === "boolean", "requiresAssessment must be boolean");
13
+ ensure(input.claims.length <= 128 && input.observations.length <= 4096, "knowledge input too large");
14
+ unique(input.claims.map((c) => c.id), "claim ids", 128);
15
+ unique(input.sources.map((s) => s.id), "source ids", 512);
16
+ unique(input.trustedRunnerIds, "runner ids");
17
+ unique(input.decisionActorIds, "decision actor ids");
18
+ for (const c of input.claims) {
19
+ text(c.binding, "binding");
20
+ text(c.statement, "statement");
21
+ member(c.phase, ["precondition", "postcondition"], "claim phase");
22
+ for (const v of [c.required, c.needsReference, c.requiresVersion, c.needsUserDecision]) {
23
+ ensure(typeof v === "boolean", "invalid claim flag");
24
+ }
25
+ ensure(Number.isFinite(c.impact) && c.impact >= 0 && c.impact <= 1_000_000, "invalid impact");
26
+ integer(c.minSourceFamilies, "minSourceFamilies", 16);
27
+ ensure(!c.needsReference || c.minSourceFamilies > 0, "reference needs at least one source family");
28
+ if (c.version !== null)
29
+ text(c.version, "version", 128);
30
+ if (c.publicQuery !== null)
31
+ text(c.publicQuery, "publicQuery", 500);
32
+ unique(c.requiredCheckIds, "check ids", 128);
33
+ ensure(c.needsReference || c.requiredCheckIds.length > 0 || c.needsUserDecision, "claim has no evidence predicate");
34
+ }
35
+ const sources = new Map(input.sources.map((s) => {
36
+ text(s.family, "source family");
37
+ member(s.kind, ["repository", "official", "community", "model"], "source kind");
38
+ return [s.id, s];
39
+ }));
40
+ const observations = new Map();
41
+ const sequences = new Map();
42
+ for (const obs of input.observations) {
43
+ text(obs.id, "observation id");
44
+ text(obs.claimId, "observation claim");
45
+ text(obs.binding, "observation binding");
46
+ integer(obs.observedAtMs, "observedAtMs");
47
+ integer(obs.expiresAtMs, "expiresAtMs");
48
+ ensure(obs.expiresAtMs >= obs.observedAtMs, "invalid observation validity interval");
49
+ member(obs.kind, ["reference", "check", "decision"], "observation kind");
50
+ if (obs.kind === "reference") {
51
+ text(obs.sourceId, "sourceId");
52
+ text(obs.documentDigest, "documentDigest");
53
+ text(obs.locator, "locator");
54
+ if (obs.version !== null)
55
+ text(obs.version, "observation version", 128);
56
+ member(obs.stance, ["support", "refute"], "stance");
57
+ }
58
+ else if (obs.kind === "check") {
59
+ text(obs.runnerId, "runnerId");
60
+ text(obs.checkId, "checkId");
61
+ integer(obs.sequence, "sequence");
62
+ member(obs.verdict, ["pass", "fail", "pending"], "check verdict");
63
+ const key = canonical([obs.claimId, obs.binding, obs.checkId, obs.sequence]);
64
+ const previous = sequences.get(key);
65
+ ensure(previous === undefined || previous === canonical(obs), "conflicting check sequence");
66
+ sequences.set(key, canonical(obs));
67
+ }
68
+ else {
69
+ text(obs.actorId, "actorId");
70
+ ensure(typeof obs.accepted === "boolean", "invalid decision");
71
+ }
72
+ const previous = observations.get(obs.id);
73
+ ensure(previous === undefined || canonical(previous) === canonical(obs), "conflicting observation id");
74
+ observations.set(obs.id, obs);
75
+ }
76
+ const relevantClaims = input.claims.filter((c) => input.stage === "after-change" || c.phase === "precondition");
77
+ const rejectedObservations = [];
78
+ const admissible = new Map();
79
+ const claimMap = new Map(relevantClaims.map((c) => [c.id, c]));
80
+ for (const obs of observations.values()) {
81
+ const c = claimMap.get(obs.claimId);
82
+ let reason;
83
+ if (!c)
84
+ reason = "irrelevant-claim-or-stage";
85
+ else if (obs.binding !== c.binding)
86
+ reason = "stale-binding";
87
+ else if (obs.observedAtMs > input.nowMs || obs.expiresAtMs <= input.nowMs)
88
+ reason = "expired-or-future";
89
+ else if (obs.kind === "reference") {
90
+ const source = sources.get(obs.sourceId);
91
+ if (!source || (source.kind !== "repository" && source.kind !== "official"))
92
+ reason = "inadmissible-source";
93
+ else if (c.requiresVersion && (c.version === null || obs.version !== c.version))
94
+ reason = "version-mismatch";
95
+ }
96
+ else if (obs.kind === "check" && !input.trustedRunnerIds.includes(obs.runnerId))
97
+ reason = "untrusted-runner";
98
+ else if (obs.kind === "decision" && !input.decisionActorIds.includes(obs.actorId)) {
99
+ reason = "untrusted-decision-actor";
100
+ }
101
+ if (reason)
102
+ rejectedObservations.push({ id: obs.id, reason });
103
+ else
104
+ admissible.set(obs.claimId, [...(admissible.get(obs.claimId) ?? []), obs]);
105
+ }
106
+ const gaps = [];
107
+ const supportedClaimIds = [];
108
+ if (input.requiresAssessment && relevantClaims.filter((c) => c.required).length === 0) {
109
+ gaps.push({
110
+ claimId: "$step",
111
+ binding: "unassessed",
112
+ reason: "unassessed-step",
113
+ required: true,
114
+ impact: 1_000_000,
115
+ checkId: null,
116
+ });
117
+ }
118
+ for (const c of relevantClaims) {
119
+ const before = gaps.length;
120
+ const evidence = admissible.get(c.id) ?? [];
121
+ const add = (reason, checkId = null) => {
122
+ gaps.push({ claimId: c.id, binding: c.binding, reason, required: c.required, impact: c.impact, checkId });
123
+ };
124
+ if (c.requiresVersion && c.version === null)
125
+ add("unknown-version");
126
+ if (c.needsReference) {
127
+ const refs = evidence.filter((obs) => obs.kind === "reference");
128
+ const support = new Set(refs.filter((r) => r.stance === "support").map((r) => sources.get(r.sourceId).family));
129
+ if (refs.some((r) => r.stance === "refute"))
130
+ add("contradictory-reference");
131
+ else if (support.size < c.minSourceFamilies)
132
+ add("unsupported-reference");
133
+ }
134
+ for (const checkId of c.requiredCheckIds) {
135
+ const records = evidence
136
+ .filter((obs) => obs.kind === "check" && obs.checkId === checkId)
137
+ .sort((a, b) => a.sequence - b.sequence);
138
+ const latest = records.at(-1);
139
+ if (!latest)
140
+ add("missing-check", checkId);
141
+ else if (latest.verdict === "fail")
142
+ add("failed-check", checkId);
143
+ else if (latest.verdict === "pending")
144
+ add("pending-check", checkId);
145
+ }
146
+ if (c.needsUserDecision) {
147
+ const decisions = evidence.filter((obs) => obs.kind === "decision");
148
+ if (!decisions.some((d) => d.accepted) || decisions.some((d) => !d.accepted))
149
+ add("missing-user-decision");
150
+ }
151
+ if (before === gaps.length)
152
+ supportedClaimIds.push(c.id);
153
+ }
154
+ gaps.sort((a, b) => Number(b.required) - Number(a.required) ||
155
+ b.impact - a.impact ||
156
+ lexical(a.claimId, b.claimId) ||
157
+ lexical(a.reason, b.reason));
158
+ return {
159
+ state: gaps.some((g) => g.required) ? "gaps" : "supported",
160
+ gaps,
161
+ supportedClaimIds: supportedClaimIds.sort(lexical),
162
+ rejectedObservations,
163
+ };
164
+ }
165
+ //# sourceMappingURL=knowledge.js.map