@miller-tech/uap 1.0.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 (660) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +888 -0
  3. package/dist/analyzers/index.d.ts +3 -0
  4. package/dist/analyzers/index.d.ts.map +1 -0
  5. package/dist/analyzers/index.js +684 -0
  6. package/dist/analyzers/index.js.map +1 -0
  7. package/dist/benchmarks/agents/naive-agent.d.ts +60 -0
  8. package/dist/benchmarks/agents/naive-agent.d.ts.map +1 -0
  9. package/dist/benchmarks/agents/naive-agent.js +144 -0
  10. package/dist/benchmarks/agents/naive-agent.js.map +1 -0
  11. package/dist/benchmarks/agents/uap-agent.d.ts +167 -0
  12. package/dist/benchmarks/agents/uap-agent.d.ts.map +1 -0
  13. package/dist/benchmarks/agents/uap-agent.js +437 -0
  14. package/dist/benchmarks/agents/uap-agent.js.map +1 -0
  15. package/dist/benchmarks/benchmark.d.ts +328 -0
  16. package/dist/benchmarks/benchmark.d.ts.map +1 -0
  17. package/dist/benchmarks/benchmark.js +112 -0
  18. package/dist/benchmarks/benchmark.js.map +1 -0
  19. package/dist/benchmarks/execution-verifier.d.ts +41 -0
  20. package/dist/benchmarks/execution-verifier.d.ts.map +1 -0
  21. package/dist/benchmarks/execution-verifier.js +340 -0
  22. package/dist/benchmarks/execution-verifier.js.map +1 -0
  23. package/dist/benchmarks/hierarchical-prompting.d.ts +37 -0
  24. package/dist/benchmarks/hierarchical-prompting.d.ts.map +1 -0
  25. package/dist/benchmarks/hierarchical-prompting.js +246 -0
  26. package/dist/benchmarks/hierarchical-prompting.js.map +1 -0
  27. package/dist/benchmarks/improved-benchmark.d.ts +89 -0
  28. package/dist/benchmarks/improved-benchmark.d.ts.map +1 -0
  29. package/dist/benchmarks/improved-benchmark.js +585 -0
  30. package/dist/benchmarks/improved-benchmark.js.map +1 -0
  31. package/dist/benchmarks/index.d.ts +11 -0
  32. package/dist/benchmarks/index.d.ts.map +1 -0
  33. package/dist/benchmarks/index.js +11 -0
  34. package/dist/benchmarks/index.js.map +1 -0
  35. package/dist/benchmarks/model-integration.d.ts +111 -0
  36. package/dist/benchmarks/model-integration.d.ts.map +1 -0
  37. package/dist/benchmarks/model-integration.js +904 -0
  38. package/dist/benchmarks/model-integration.js.map +1 -0
  39. package/dist/benchmarks/multi-turn-agent.d.ts +44 -0
  40. package/dist/benchmarks/multi-turn-agent.d.ts.map +1 -0
  41. package/dist/benchmarks/multi-turn-agent.js +254 -0
  42. package/dist/benchmarks/multi-turn-agent.js.map +1 -0
  43. package/dist/benchmarks/multi-turn-loop.d.ts +57 -0
  44. package/dist/benchmarks/multi-turn-loop.d.ts.map +1 -0
  45. package/dist/benchmarks/multi-turn-loop.js +167 -0
  46. package/dist/benchmarks/multi-turn-loop.js.map +1 -0
  47. package/dist/benchmarks/tasks.d.ts +19 -0
  48. package/dist/benchmarks/tasks.d.ts.map +1 -0
  49. package/dist/benchmarks/tasks.js +435 -0
  50. package/dist/benchmarks/tasks.js.map +1 -0
  51. package/dist/bin/cli.d.ts +3 -0
  52. package/dist/bin/cli.d.ts.map +1 -0
  53. package/dist/bin/cli.js +546 -0
  54. package/dist/bin/cli.js.map +1 -0
  55. package/dist/bin/llama-server-optimize.d.ts +18 -0
  56. package/dist/bin/llama-server-optimize.d.ts.map +1 -0
  57. package/dist/bin/llama-server-optimize.js +708 -0
  58. package/dist/bin/llama-server-optimize.js.map +1 -0
  59. package/dist/bin/policy.d.ts +3 -0
  60. package/dist/bin/policy.d.ts.map +1 -0
  61. package/dist/bin/policy.js +143 -0
  62. package/dist/bin/policy.js.map +1 -0
  63. package/dist/bin/tool-calls.d.ts +3 -0
  64. package/dist/bin/tool-calls.d.ts.map +1 -0
  65. package/dist/bin/tool-calls.js +4 -0
  66. package/dist/bin/tool-calls.js.map +1 -0
  67. package/dist/browser/index.d.ts +2 -0
  68. package/dist/browser/index.d.ts.map +1 -0
  69. package/dist/browser/index.js +2 -0
  70. package/dist/browser/index.js.map +1 -0
  71. package/dist/browser/web-browser.d.ts +30 -0
  72. package/dist/browser/web-browser.d.ts.map +1 -0
  73. package/dist/browser/web-browser.js +93 -0
  74. package/dist/browser/web-browser.js.map +1 -0
  75. package/dist/cli/agent.d.ts +20 -0
  76. package/dist/cli/agent.d.ts.map +1 -0
  77. package/dist/cli/agent.js +474 -0
  78. package/dist/cli/agent.js.map +1 -0
  79. package/dist/cli/analyze.d.ts +7 -0
  80. package/dist/cli/analyze.d.ts.map +1 -0
  81. package/dist/cli/analyze.js +103 -0
  82. package/dist/cli/analyze.js.map +1 -0
  83. package/dist/cli/completion-gates.d.ts +51 -0
  84. package/dist/cli/completion-gates.d.ts.map +1 -0
  85. package/dist/cli/completion-gates.js +201 -0
  86. package/dist/cli/completion-gates.js.map +1 -0
  87. package/dist/cli/compliance.d.ts +8 -0
  88. package/dist/cli/compliance.d.ts.map +1 -0
  89. package/dist/cli/compliance.js +509 -0
  90. package/dist/cli/compliance.js.map +1 -0
  91. package/dist/cli/coord.d.ts +7 -0
  92. package/dist/cli/coord.d.ts.map +1 -0
  93. package/dist/cli/coord.js +138 -0
  94. package/dist/cli/coord.js.map +1 -0
  95. package/dist/cli/dashboard.d.ts +21 -0
  96. package/dist/cli/dashboard.d.ts.map +1 -0
  97. package/dist/cli/dashboard.js +1508 -0
  98. package/dist/cli/dashboard.js.map +1 -0
  99. package/dist/cli/deploy.d.ts +19 -0
  100. package/dist/cli/deploy.d.ts.map +1 -0
  101. package/dist/cli/deploy.js +387 -0
  102. package/dist/cli/deploy.js.map +1 -0
  103. package/dist/cli/droids.d.ts +9 -0
  104. package/dist/cli/droids.d.ts.map +1 -0
  105. package/dist/cli/droids.js +227 -0
  106. package/dist/cli/droids.js.map +1 -0
  107. package/dist/cli/generate.d.ts +17 -0
  108. package/dist/cli/generate.d.ts.map +1 -0
  109. package/dist/cli/generate.js +432 -0
  110. package/dist/cli/generate.js.map +1 -0
  111. package/dist/cli/hooks.d.ts +9 -0
  112. package/dist/cli/hooks.d.ts.map +1 -0
  113. package/dist/cli/hooks.js +464 -0
  114. package/dist/cli/hooks.js.map +1 -0
  115. package/dist/cli/init.d.ts +12 -0
  116. package/dist/cli/init.d.ts.map +1 -0
  117. package/dist/cli/init.js +364 -0
  118. package/dist/cli/init.js.map +1 -0
  119. package/dist/cli/mcp-router.d.ts +16 -0
  120. package/dist/cli/mcp-router.d.ts.map +1 -0
  121. package/dist/cli/mcp-router.js +143 -0
  122. package/dist/cli/mcp-router.js.map +1 -0
  123. package/dist/cli/memory.d.ts +24 -0
  124. package/dist/cli/memory.d.ts.map +1 -0
  125. package/dist/cli/memory.js +885 -0
  126. package/dist/cli/memory.js.map +1 -0
  127. package/dist/cli/model.d.ts +15 -0
  128. package/dist/cli/model.d.ts.map +1 -0
  129. package/dist/cli/model.js +290 -0
  130. package/dist/cli/model.js.map +1 -0
  131. package/dist/cli/patterns.d.ts +26 -0
  132. package/dist/cli/patterns.d.ts.map +1 -0
  133. package/dist/cli/patterns.js +862 -0
  134. package/dist/cli/patterns.js.map +1 -0
  135. package/dist/cli/rtk-validation.d.ts +9 -0
  136. package/dist/cli/rtk-validation.d.ts.map +1 -0
  137. package/dist/cli/rtk-validation.js +9 -0
  138. package/dist/cli/rtk-validation.js.map +1 -0
  139. package/dist/cli/rtk.d.ts +34 -0
  140. package/dist/cli/rtk.d.ts.map +1 -0
  141. package/dist/cli/rtk.js +401 -0
  142. package/dist/cli/rtk.js.map +1 -0
  143. package/dist/cli/schema-diff.d.ts +7 -0
  144. package/dist/cli/schema-diff.d.ts.map +1 -0
  145. package/dist/cli/schema-diff.js +11 -0
  146. package/dist/cli/schema-diff.js.map +1 -0
  147. package/dist/cli/setup-mcp-router.d.ts +8 -0
  148. package/dist/cli/setup-mcp-router.d.ts.map +1 -0
  149. package/dist/cli/setup-mcp-router.js +163 -0
  150. package/dist/cli/setup-mcp-router.js.map +1 -0
  151. package/dist/cli/setup-wizard.d.ts +2 -0
  152. package/dist/cli/setup-wizard.d.ts.map +1 -0
  153. package/dist/cli/setup-wizard.js +806 -0
  154. package/dist/cli/setup-wizard.js.map +1 -0
  155. package/dist/cli/setup.d.ts +15 -0
  156. package/dist/cli/setup.d.ts.map +1 -0
  157. package/dist/cli/setup.js +154 -0
  158. package/dist/cli/setup.js.map +1 -0
  159. package/dist/cli/sync.d.ts +8 -0
  160. package/dist/cli/sync.d.ts.map +1 -0
  161. package/dist/cli/sync.js +395 -0
  162. package/dist/cli/sync.js.map +1 -0
  163. package/dist/cli/task.d.ts +33 -0
  164. package/dist/cli/task.d.ts.map +1 -0
  165. package/dist/cli/task.js +672 -0
  166. package/dist/cli/task.js.map +1 -0
  167. package/dist/cli/tool-calls.d.ts +20 -0
  168. package/dist/cli/tool-calls.d.ts.map +1 -0
  169. package/dist/cli/tool-calls.js +605 -0
  170. package/dist/cli/tool-calls.js.map +1 -0
  171. package/dist/cli/uap.d.ts +10 -0
  172. package/dist/cli/uap.d.ts.map +1 -0
  173. package/dist/cli/uap.js +398 -0
  174. package/dist/cli/uap.js.map +1 -0
  175. package/dist/cli/update.d.ts +10 -0
  176. package/dist/cli/update.d.ts.map +1 -0
  177. package/dist/cli/update.js +300 -0
  178. package/dist/cli/update.js.map +1 -0
  179. package/dist/cli/visualize.d.ts +77 -0
  180. package/dist/cli/visualize.d.ts.map +1 -0
  181. package/dist/cli/visualize.js +287 -0
  182. package/dist/cli/visualize.js.map +1 -0
  183. package/dist/cli/worktree.d.ts +9 -0
  184. package/dist/cli/worktree.d.ts.map +1 -0
  185. package/dist/cli/worktree.js +213 -0
  186. package/dist/cli/worktree.js.map +1 -0
  187. package/dist/coordination/adaptive-patterns.d.ts +65 -0
  188. package/dist/coordination/adaptive-patterns.d.ts.map +1 -0
  189. package/dist/coordination/adaptive-patterns.js +108 -0
  190. package/dist/coordination/adaptive-patterns.js.map +1 -0
  191. package/dist/coordination/auto-agent.d.ts +82 -0
  192. package/dist/coordination/auto-agent.d.ts.map +1 -0
  193. package/dist/coordination/auto-agent.js +145 -0
  194. package/dist/coordination/auto-agent.js.map +1 -0
  195. package/dist/coordination/capability-router.d.ts +79 -0
  196. package/dist/coordination/capability-router.d.ts.map +1 -0
  197. package/dist/coordination/capability-router.js +334 -0
  198. package/dist/coordination/capability-router.js.map +1 -0
  199. package/dist/coordination/database.d.ts +13 -0
  200. package/dist/coordination/database.d.ts.map +1 -0
  201. package/dist/coordination/database.js +136 -0
  202. package/dist/coordination/database.js.map +1 -0
  203. package/dist/coordination/deploy-batcher.d.ts +122 -0
  204. package/dist/coordination/deploy-batcher.d.ts.map +1 -0
  205. package/dist/coordination/deploy-batcher.js +718 -0
  206. package/dist/coordination/deploy-batcher.js.map +1 -0
  207. package/dist/coordination/droid-validator.d.ts +59 -0
  208. package/dist/coordination/droid-validator.d.ts.map +1 -0
  209. package/dist/coordination/droid-validator.js +142 -0
  210. package/dist/coordination/droid-validator.js.map +1 -0
  211. package/dist/coordination/index.d.ts +10 -0
  212. package/dist/coordination/index.d.ts.map +1 -0
  213. package/dist/coordination/index.js +10 -0
  214. package/dist/coordination/index.js.map +1 -0
  215. package/dist/coordination/pattern-router.d.ts +50 -0
  216. package/dist/coordination/pattern-router.d.ts.map +1 -0
  217. package/dist/coordination/pattern-router.js +118 -0
  218. package/dist/coordination/pattern-router.js.map +1 -0
  219. package/dist/coordination/service.d.ts +81 -0
  220. package/dist/coordination/service.d.ts.map +1 -0
  221. package/dist/coordination/service.js +619 -0
  222. package/dist/coordination/service.js.map +1 -0
  223. package/dist/coordination/worktree-enforcer.d.ts +22 -0
  224. package/dist/coordination/worktree-enforcer.d.ts.map +1 -0
  225. package/dist/coordination/worktree-enforcer.js +71 -0
  226. package/dist/coordination/worktree-enforcer.js.map +1 -0
  227. package/dist/generators/claude-md.d.ts +3 -0
  228. package/dist/generators/claude-md.d.ts.map +1 -0
  229. package/dist/generators/claude-md.js +1020 -0
  230. package/dist/generators/claude-md.js.map +1 -0
  231. package/dist/generators/template-loader.d.ts +105 -0
  232. package/dist/generators/template-loader.d.ts.map +1 -0
  233. package/dist/generators/template-loader.js +291 -0
  234. package/dist/generators/template-loader.js.map +1 -0
  235. package/dist/index.d.ts +49 -0
  236. package/dist/index.d.ts.map +1 -0
  237. package/dist/index.js +63 -0
  238. package/dist/index.js.map +1 -0
  239. package/dist/mcp-router/config/parser.d.ts +9 -0
  240. package/dist/mcp-router/config/parser.d.ts.map +1 -0
  241. package/dist/mcp-router/config/parser.js +174 -0
  242. package/dist/mcp-router/config/parser.js.map +1 -0
  243. package/dist/mcp-router/executor/client.d.ts +31 -0
  244. package/dist/mcp-router/executor/client.d.ts.map +1 -0
  245. package/dist/mcp-router/executor/client.js +189 -0
  246. package/dist/mcp-router/executor/client.js.map +1 -0
  247. package/dist/mcp-router/index.d.ts +22 -0
  248. package/dist/mcp-router/index.d.ts.map +1 -0
  249. package/dist/mcp-router/index.js +18 -0
  250. package/dist/mcp-router/index.js.map +1 -0
  251. package/dist/mcp-router/output-compressor.d.ts +26 -0
  252. package/dist/mcp-router/output-compressor.d.ts.map +1 -0
  253. package/dist/mcp-router/output-compressor.js +236 -0
  254. package/dist/mcp-router/output-compressor.js.map +1 -0
  255. package/dist/mcp-router/search/fuzzy.d.ts +26 -0
  256. package/dist/mcp-router/search/fuzzy.d.ts.map +1 -0
  257. package/dist/mcp-router/search/fuzzy.js +94 -0
  258. package/dist/mcp-router/search/fuzzy.js.map +1 -0
  259. package/dist/mcp-router/server.d.ts +50 -0
  260. package/dist/mcp-router/server.d.ts.map +1 -0
  261. package/dist/mcp-router/server.js +229 -0
  262. package/dist/mcp-router/server.js.map +1 -0
  263. package/dist/mcp-router/session-stats.d.ts +37 -0
  264. package/dist/mcp-router/session-stats.d.ts.map +1 -0
  265. package/dist/mcp-router/session-stats.js +56 -0
  266. package/dist/mcp-router/session-stats.js.map +1 -0
  267. package/dist/mcp-router/tools/discover.d.ts +37 -0
  268. package/dist/mcp-router/tools/discover.d.ts.map +1 -0
  269. package/dist/mcp-router/tools/discover.js +65 -0
  270. package/dist/mcp-router/tools/discover.js.map +1 -0
  271. package/dist/mcp-router/tools/execute.d.ts +43 -0
  272. package/dist/mcp-router/tools/execute.d.ts.map +1 -0
  273. package/dist/mcp-router/tools/execute.js +144 -0
  274. package/dist/mcp-router/tools/execute.js.map +1 -0
  275. package/dist/mcp-router/types.d.ts +62 -0
  276. package/dist/mcp-router/types.d.ts.map +1 -0
  277. package/dist/mcp-router/types.js +6 -0
  278. package/dist/mcp-router/types.js.map +1 -0
  279. package/dist/memory/adaptive-context.d.ts +149 -0
  280. package/dist/memory/adaptive-context.d.ts.map +1 -0
  281. package/dist/memory/adaptive-context.js +1095 -0
  282. package/dist/memory/adaptive-context.js.map +1 -0
  283. package/dist/memory/agent-scoped-memory.d.ts +67 -0
  284. package/dist/memory/agent-scoped-memory.d.ts.map +1 -0
  285. package/dist/memory/agent-scoped-memory.js +126 -0
  286. package/dist/memory/agent-scoped-memory.js.map +1 -0
  287. package/dist/memory/ambiguity-detector.d.ts +54 -0
  288. package/dist/memory/ambiguity-detector.d.ts.map +1 -0
  289. package/dist/memory/ambiguity-detector.js +401 -0
  290. package/dist/memory/ambiguity-detector.js.map +1 -0
  291. package/dist/memory/backends/base.d.ts +18 -0
  292. package/dist/memory/backends/base.d.ts.map +1 -0
  293. package/dist/memory/backends/base.js +2 -0
  294. package/dist/memory/backends/base.js.map +1 -0
  295. package/dist/memory/backends/factory.d.ts +4 -0
  296. package/dist/memory/backends/factory.d.ts.map +1 -0
  297. package/dist/memory/backends/factory.js +53 -0
  298. package/dist/memory/backends/factory.js.map +1 -0
  299. package/dist/memory/backends/github.d.ts +27 -0
  300. package/dist/memory/backends/github.d.ts.map +1 -0
  301. package/dist/memory/backends/github.js +134 -0
  302. package/dist/memory/backends/github.js.map +1 -0
  303. package/dist/memory/backends/qdrant-cloud.d.ts +32 -0
  304. package/dist/memory/backends/qdrant-cloud.d.ts.map +1 -0
  305. package/dist/memory/backends/qdrant-cloud.js +167 -0
  306. package/dist/memory/backends/qdrant-cloud.js.map +1 -0
  307. package/dist/memory/context-compressor.d.ts +116 -0
  308. package/dist/memory/context-compressor.d.ts.map +1 -0
  309. package/dist/memory/context-compressor.js +430 -0
  310. package/dist/memory/context-compressor.js.map +1 -0
  311. package/dist/memory/context-pruner.d.ts +55 -0
  312. package/dist/memory/context-pruner.d.ts.map +1 -0
  313. package/dist/memory/context-pruner.js +85 -0
  314. package/dist/memory/context-pruner.js.map +1 -0
  315. package/dist/memory/correction-propagator.d.ts +44 -0
  316. package/dist/memory/correction-propagator.d.ts.map +1 -0
  317. package/dist/memory/correction-propagator.js +156 -0
  318. package/dist/memory/correction-propagator.js.map +1 -0
  319. package/dist/memory/daily-log.d.ts +67 -0
  320. package/dist/memory/daily-log.d.ts.map +1 -0
  321. package/dist/memory/daily-log.js +143 -0
  322. package/dist/memory/daily-log.js.map +1 -0
  323. package/dist/memory/dynamic-retrieval.d.ts +112 -0
  324. package/dist/memory/dynamic-retrieval.d.ts.map +1 -0
  325. package/dist/memory/dynamic-retrieval.js +908 -0
  326. package/dist/memory/dynamic-retrieval.js.map +1 -0
  327. package/dist/memory/embeddings.d.ts +172 -0
  328. package/dist/memory/embeddings.d.ts.map +1 -0
  329. package/dist/memory/embeddings.js +780 -0
  330. package/dist/memory/embeddings.js.map +1 -0
  331. package/dist/memory/generic-uap-patterns.d.ts +7 -0
  332. package/dist/memory/generic-uap-patterns.d.ts.map +1 -0
  333. package/dist/memory/generic-uap-patterns.js +43 -0
  334. package/dist/memory/generic-uap-patterns.js.map +1 -0
  335. package/dist/memory/hierarchical-memory.d.ts +141 -0
  336. package/dist/memory/hierarchical-memory.d.ts.map +1 -0
  337. package/dist/memory/hierarchical-memory.js +485 -0
  338. package/dist/memory/hierarchical-memory.js.map +1 -0
  339. package/dist/memory/knowledge-graph.d.ts +98 -0
  340. package/dist/memory/knowledge-graph.d.ts.map +1 -0
  341. package/dist/memory/knowledge-graph.js +275 -0
  342. package/dist/memory/knowledge-graph.js.map +1 -0
  343. package/dist/memory/memory-consolidator.d.ts +124 -0
  344. package/dist/memory/memory-consolidator.d.ts.map +1 -0
  345. package/dist/memory/memory-consolidator.js +514 -0
  346. package/dist/memory/memory-consolidator.js.map +1 -0
  347. package/dist/memory/memory-maintenance.d.ts +39 -0
  348. package/dist/memory/memory-maintenance.d.ts.map +1 -0
  349. package/dist/memory/memory-maintenance.js +336 -0
  350. package/dist/memory/memory-maintenance.js.map +1 -0
  351. package/dist/memory/model-router.d.ts +105 -0
  352. package/dist/memory/model-router.d.ts.map +1 -0
  353. package/dist/memory/model-router.js +474 -0
  354. package/dist/memory/model-router.js.map +1 -0
  355. package/dist/memory/multi-view-memory.d.ts +134 -0
  356. package/dist/memory/multi-view-memory.d.ts.map +1 -0
  357. package/dist/memory/multi-view-memory.js +430 -0
  358. package/dist/memory/multi-view-memory.js.map +1 -0
  359. package/dist/memory/predictive-memory.d.ts +79 -0
  360. package/dist/memory/predictive-memory.d.ts.map +1 -0
  361. package/dist/memory/predictive-memory.js +294 -0
  362. package/dist/memory/predictive-memory.js.map +1 -0
  363. package/dist/memory/prepopulate.d.ts +76 -0
  364. package/dist/memory/prepopulate.d.ts.map +1 -0
  365. package/dist/memory/prepopulate.js +832 -0
  366. package/dist/memory/prepopulate.js.map +1 -0
  367. package/dist/memory/semantic-compression.d.ts +77 -0
  368. package/dist/memory/semantic-compression.d.ts.map +1 -0
  369. package/dist/memory/semantic-compression.js +359 -0
  370. package/dist/memory/semantic-compression.js.map +1 -0
  371. package/dist/memory/serverless-qdrant.d.ts +102 -0
  372. package/dist/memory/serverless-qdrant.d.ts.map +1 -0
  373. package/dist/memory/serverless-qdrant.js +369 -0
  374. package/dist/memory/serverless-qdrant.js.map +1 -0
  375. package/dist/memory/short-term/factory.d.ts +26 -0
  376. package/dist/memory/short-term/factory.d.ts.map +1 -0
  377. package/dist/memory/short-term/factory.js +28 -0
  378. package/dist/memory/short-term/factory.js.map +1 -0
  379. package/dist/memory/short-term/indexeddb.d.ts +25 -0
  380. package/dist/memory/short-term/indexeddb.d.ts.map +1 -0
  381. package/dist/memory/short-term/indexeddb.js +64 -0
  382. package/dist/memory/short-term/indexeddb.js.map +1 -0
  383. package/dist/memory/short-term/schema.d.ts +6 -0
  384. package/dist/memory/short-term/schema.d.ts.map +1 -0
  385. package/dist/memory/short-term/schema.js +141 -0
  386. package/dist/memory/short-term/schema.js.map +1 -0
  387. package/dist/memory/short-term/sqlite.d.ts +64 -0
  388. package/dist/memory/short-term/sqlite.d.ts.map +1 -0
  389. package/dist/memory/short-term/sqlite.js +274 -0
  390. package/dist/memory/short-term/sqlite.js.map +1 -0
  391. package/dist/memory/speculative-cache.d.ts +111 -0
  392. package/dist/memory/speculative-cache.d.ts.map +1 -0
  393. package/dist/memory/speculative-cache.js +457 -0
  394. package/dist/memory/speculative-cache.js.map +1 -0
  395. package/dist/memory/task-classifier.d.ts +40 -0
  396. package/dist/memory/task-classifier.d.ts.map +1 -0
  397. package/dist/memory/task-classifier.js +342 -0
  398. package/dist/memory/task-classifier.js.map +1 -0
  399. package/dist/memory/terminal-bench-knowledge.d.ts +48 -0
  400. package/dist/memory/terminal-bench-knowledge.d.ts.map +1 -0
  401. package/dist/memory/terminal-bench-knowledge.js +622 -0
  402. package/dist/memory/terminal-bench-knowledge.js.map +1 -0
  403. package/dist/memory/write-gate.d.ts +39 -0
  404. package/dist/memory/write-gate.d.ts.map +1 -0
  405. package/dist/memory/write-gate.js +190 -0
  406. package/dist/memory/write-gate.js.map +1 -0
  407. package/dist/models/api-client.d.ts +46 -0
  408. package/dist/models/api-client.d.ts.map +1 -0
  409. package/dist/models/api-client.js +182 -0
  410. package/dist/models/api-client.js.map +1 -0
  411. package/dist/models/execution-profiles.d.ts +64 -0
  412. package/dist/models/execution-profiles.d.ts.map +1 -0
  413. package/dist/models/execution-profiles.js +403 -0
  414. package/dist/models/execution-profiles.js.map +1 -0
  415. package/dist/models/executor.d.ts +130 -0
  416. package/dist/models/executor.d.ts.map +1 -0
  417. package/dist/models/executor.js +382 -0
  418. package/dist/models/executor.js.map +1 -0
  419. package/dist/models/index.d.ts +19 -0
  420. package/dist/models/index.d.ts.map +1 -0
  421. package/dist/models/index.js +23 -0
  422. package/dist/models/index.js.map +1 -0
  423. package/dist/models/plan-validator.d.ts +37 -0
  424. package/dist/models/plan-validator.d.ts.map +1 -0
  425. package/dist/models/plan-validator.js +179 -0
  426. package/dist/models/plan-validator.js.map +1 -0
  427. package/dist/models/planner.d.ts +73 -0
  428. package/dist/models/planner.d.ts.map +1 -0
  429. package/dist/models/planner.js +375 -0
  430. package/dist/models/planner.js.map +1 -0
  431. package/dist/models/router.d.ts +96 -0
  432. package/dist/models/router.d.ts.map +1 -0
  433. package/dist/models/router.js +523 -0
  434. package/dist/models/router.js.map +1 -0
  435. package/dist/models/types.d.ts +370 -0
  436. package/dist/models/types.d.ts.map +1 -0
  437. package/dist/models/types.js +232 -0
  438. package/dist/models/types.js.map +1 -0
  439. package/dist/models/unified-router.d.ts +152 -0
  440. package/dist/models/unified-router.d.ts.map +1 -0
  441. package/dist/models/unified-router.js +313 -0
  442. package/dist/models/unified-router.js.map +1 -0
  443. package/dist/policies/convert-policy-to-claude.d.ts +3 -0
  444. package/dist/policies/convert-policy-to-claude.d.ts.map +1 -0
  445. package/dist/policies/convert-policy-to-claude.js +87 -0
  446. package/dist/policies/convert-policy-to-claude.js.map +1 -0
  447. package/dist/policies/database-manager.d.ts +27 -0
  448. package/dist/policies/database-manager.d.ts.map +1 -0
  449. package/dist/policies/database-manager.js +198 -0
  450. package/dist/policies/database-manager.js.map +1 -0
  451. package/dist/policies/enforced-tool-router.d.ts +53 -0
  452. package/dist/policies/enforced-tool-router.d.ts.map +1 -0
  453. package/dist/policies/enforced-tool-router.js +80 -0
  454. package/dist/policies/enforced-tool-router.js.map +1 -0
  455. package/dist/policies/index.d.ts +10 -0
  456. package/dist/policies/index.d.ts.map +1 -0
  457. package/dist/policies/index.js +8 -0
  458. package/dist/policies/index.js.map +1 -0
  459. package/dist/policies/policy-gate.d.ts +59 -0
  460. package/dist/policies/policy-gate.d.ts.map +1 -0
  461. package/dist/policies/policy-gate.js +171 -0
  462. package/dist/policies/policy-gate.js.map +1 -0
  463. package/dist/policies/policy-memory.d.ts +18 -0
  464. package/dist/policies/policy-memory.d.ts.map +1 -0
  465. package/dist/policies/policy-memory.js +126 -0
  466. package/dist/policies/policy-memory.js.map +1 -0
  467. package/dist/policies/policy-tools.d.ts +11 -0
  468. package/dist/policies/policy-tools.d.ts.map +1 -0
  469. package/dist/policies/policy-tools.js +66 -0
  470. package/dist/policies/policy-tools.js.map +1 -0
  471. package/dist/policies/schemas/policy.d.ts +69 -0
  472. package/dist/policies/schemas/policy.d.ts.map +1 -0
  473. package/dist/policies/schemas/policy.js +31 -0
  474. package/dist/policies/schemas/policy.js.map +1 -0
  475. package/dist/tasks/coordination.d.ts +83 -0
  476. package/dist/tasks/coordination.d.ts.map +1 -0
  477. package/dist/tasks/coordination.js +291 -0
  478. package/dist/tasks/coordination.js.map +1 -0
  479. package/dist/tasks/database.d.ts +19 -0
  480. package/dist/tasks/database.d.ts.map +1 -0
  481. package/dist/tasks/database.js +149 -0
  482. package/dist/tasks/database.js.map +1 -0
  483. package/dist/tasks/decoder-gate.d.ts +64 -0
  484. package/dist/tasks/decoder-gate.d.ts.map +1 -0
  485. package/dist/tasks/decoder-gate.js +268 -0
  486. package/dist/tasks/decoder-gate.js.map +1 -0
  487. package/dist/tasks/index.d.ts +6 -0
  488. package/dist/tasks/index.d.ts.map +1 -0
  489. package/dist/tasks/index.js +6 -0
  490. package/dist/tasks/index.js.map +1 -0
  491. package/dist/tasks/service.d.ts +40 -0
  492. package/dist/tasks/service.d.ts.map +1 -0
  493. package/dist/tasks/service.js +671 -0
  494. package/dist/tasks/service.js.map +1 -0
  495. package/dist/tasks/types.d.ts +238 -0
  496. package/dist/tasks/types.d.ts.map +1 -0
  497. package/dist/tasks/types.js +74 -0
  498. package/dist/tasks/types.js.map +1 -0
  499. package/dist/telemetry/index.d.ts +2 -0
  500. package/dist/telemetry/index.d.ts.map +1 -0
  501. package/dist/telemetry/index.js +2 -0
  502. package/dist/telemetry/index.js.map +1 -0
  503. package/dist/telemetry/session-telemetry.d.ts +56 -0
  504. package/dist/telemetry/session-telemetry.d.ts.map +1 -0
  505. package/dist/telemetry/session-telemetry.js +807 -0
  506. package/dist/telemetry/session-telemetry.js.map +1 -0
  507. package/dist/types/analysis.d.ts +82 -0
  508. package/dist/types/analysis.d.ts.map +1 -0
  509. package/dist/types/analysis.js +2 -0
  510. package/dist/types/analysis.js.map +1 -0
  511. package/dist/types/config.d.ts +3324 -0
  512. package/dist/types/config.d.ts.map +1 -0
  513. package/dist/types/config.js +418 -0
  514. package/dist/types/config.js.map +1 -0
  515. package/dist/types/coordination.d.ts +240 -0
  516. package/dist/types/coordination.d.ts.map +1 -0
  517. package/dist/types/coordination.js +43 -0
  518. package/dist/types/coordination.js.map +1 -0
  519. package/dist/types/index.d.ts +4 -0
  520. package/dist/types/index.d.ts.map +1 -0
  521. package/dist/types/index.js +4 -0
  522. package/dist/types/index.js.map +1 -0
  523. package/dist/uap-droids-strict.d.ts +59 -0
  524. package/dist/uap-droids-strict.d.ts.map +1 -0
  525. package/dist/uap-droids-strict.js +200 -0
  526. package/dist/uap-droids-strict.js.map +1 -0
  527. package/dist/utils/config-manager.d.ts +30 -0
  528. package/dist/utils/config-manager.d.ts.map +1 -0
  529. package/dist/utils/config-manager.js +41 -0
  530. package/dist/utils/config-manager.js.map +1 -0
  531. package/dist/utils/fetch-with-retry.d.ts +5 -0
  532. package/dist/utils/fetch-with-retry.d.ts.map +1 -0
  533. package/dist/utils/fetch-with-retry.js +61 -0
  534. package/dist/utils/fetch-with-retry.js.map +1 -0
  535. package/dist/utils/merge-claude-md.d.ts +28 -0
  536. package/dist/utils/merge-claude-md.d.ts.map +1 -0
  537. package/dist/utils/merge-claude-md.js +342 -0
  538. package/dist/utils/merge-claude-md.js.map +1 -0
  539. package/dist/utils/rate-limiter.d.ts +58 -0
  540. package/dist/utils/rate-limiter.d.ts.map +1 -0
  541. package/dist/utils/rate-limiter.js +100 -0
  542. package/dist/utils/rate-limiter.js.map +1 -0
  543. package/dist/utils/string-similarity.d.ts +37 -0
  544. package/dist/utils/string-similarity.d.ts.map +1 -0
  545. package/dist/utils/string-similarity.js +114 -0
  546. package/dist/utils/string-similarity.js.map +1 -0
  547. package/dist/utils/validate-json.d.ts +51 -0
  548. package/dist/utils/validate-json.d.ts.map +1 -0
  549. package/dist/utils/validate-json.js +94 -0
  550. package/dist/utils/validate-json.js.map +1 -0
  551. package/docs/INDEX.md +66 -0
  552. package/docs/architecture/MULTI_MODEL.md +224 -0
  553. package/docs/architecture/SYSTEM_ANALYSIS.md +1117 -0
  554. package/docs/architecture/UAP_COMPLIANCE.md +217 -0
  555. package/docs/architecture/UAP_PROTOCOL.md +339 -0
  556. package/docs/architecture/UAP_STRICT_DROIDS.md +172 -0
  557. package/docs/archive/BALLS_MODE_SELF_ANALYSIS.md +260 -0
  558. package/docs/archive/FAILING_TASKS_SOLUTION_PLAN.md +668 -0
  559. package/docs/archive/JINJA2-SYSTEM-MESSAGE-FIX.md +209 -0
  560. package/docs/archive/NPM-PUBLISH-V0.9.1.md +240 -0
  561. package/docs/archive/OPTIMIZATION_OPTIONS.md +334 -0
  562. package/docs/archive/SETUP_IMPROVEMENTS.md +213 -0
  563. package/docs/archive/UAP_GENERIC_OPTIMIZATION_PLAN.md +270 -0
  564. package/docs/archive/UAP_V103_PATTERN_DESIGN.md +315 -0
  565. package/docs/archive/UAP_V104_COMPLIANCE_DESIGN.md +223 -0
  566. package/docs/archive/changelog/2026-03-10_uap-100-compliance.md +77 -0
  567. package/docs/archive/changelog/2026-03-10_uap-full-system-verification.md +109 -0
  568. package/docs/benchmarks/ACCURACY_ANALYSIS.md +471 -0
  569. package/docs/benchmarks/TOKEN_OPTIMIZATION.md +572 -0
  570. package/docs/benchmarks/VALIDATION_PLAN.md +568 -0
  571. package/docs/benchmarks/VALIDATION_RESULTS.md +161 -0
  572. package/docs/deployment/DEPLOYMENT.md +895 -0
  573. package/docs/deployment/DEPLOYMENT_STRATEGIES.md +518 -0
  574. package/docs/deployment/DEPLOY_BATCHER_ANALYSIS.md +856 -0
  575. package/docs/deployment/DEPLOY_BATCHING.md +273 -0
  576. package/docs/deployment/DEPLOY_BUCKETING_ANALYSIS.md +420 -0
  577. package/docs/deployment/QWEN35_LLAMA_CPP.md +265 -0
  578. package/docs/getting-started/INTEGRATION.md +449 -0
  579. package/docs/getting-started/OVERVIEW.md +344 -0
  580. package/docs/getting-started/SETUP.md +203 -0
  581. package/docs/integrations/MCP_ROUTER_SETUP.md +445 -0
  582. package/docs/integrations/RTK_INTEGRATION.md +468 -0
  583. package/docs/operations/TROUBLESHOOTING.md +660 -0
  584. package/docs/reference/API_REFERENCE.md +903 -0
  585. package/docs/reference/FEATURES.md +472 -0
  586. package/docs/reference/HARNESS-MATRIX.md +318 -0
  587. package/docs/reference/UAP_CLI_REFERENCE.md +600 -0
  588. package/docs/research/BEHAVIORAL_PATTERNS.md +228 -0
  589. package/docs/research/DOMAIN_STRATEGIES.md +316 -0
  590. package/docs/research/MEMORY_SYSTEMS_COMPARISON.md +812 -0
  591. package/docs/research/PATTERN_ANALYSIS_2026-01-18.md +436 -0
  592. package/docs/research/PERFORMANCE_ANALYSIS_2026-01-18.md +209 -0
  593. package/docs/research/PERFORMANCE_TEST_PLAN.md +383 -0
  594. package/docs/research/TERMINAL_BENCH_LEARNINGS.md +217 -0
  595. package/package.json +113 -0
  596. package/scripts/README.md +161 -0
  597. package/templates/CLAUDE.template.md +10 -0
  598. package/templates/CLAUDE_ARCHITECTURE.template.md +103 -0
  599. package/templates/CLAUDE_CODING.template.md +127 -0
  600. package/templates/CLAUDE_DROIDS.template.md +109 -0
  601. package/templates/CLAUDE_MEMORY.template.md +131 -0
  602. package/templates/CLAUDE_WORKFLOWS.template.md +139 -0
  603. package/templates/PROJECT.template.md +209 -0
  604. package/templates/SCHEMA.md +57 -0
  605. package/templates/archive/CLAUDE.template.root-v6.md +534 -0
  606. package/templates/archive/CLAUDE.template.v6.md +534 -0
  607. package/templates/hooks/forgecode/pre-compact.sh +68 -0
  608. package/templates/hooks/forgecode/session-start.sh +169 -0
  609. package/templates/hooks/forgecode.plugin.sh +128 -0
  610. package/templates/hooks/pre-compact.sh +74 -0
  611. package/templates/hooks/session-start.sh +366 -0
  612. package/tools/agents/README.md +224 -0
  613. package/tools/agents/UAP/README.md +386 -0
  614. package/tools/agents/UAP/__init__.py +9 -0
  615. package/tools/agents/UAP/cli.py +901 -0
  616. package/tools/agents/UAP/compliance_verify.sh +108 -0
  617. package/tools/agents/UAP/full_verification.sh +126 -0
  618. package/tools/agents/UAP/version.py +32 -0
  619. package/tools/agents/benchmarks/benchmark_memory_systems.py +730 -0
  620. package/tools/agents/benchmarks/results/benchmark_20260106_064817.json +170 -0
  621. package/tools/agents/benchmarks/results/benchmark_20260106_064817.md +51 -0
  622. package/tools/agents/config/chat_template.jinja +77 -0
  623. package/tools/agents/config/tool-call-schema.json +19 -0
  624. package/tools/agents/config/tool-call.gbnf +58 -0
  625. package/tools/agents/docker/Dockerfile.python +52 -0
  626. package/tools/agents/docker/Dockerfile.ubuntu +55 -0
  627. package/tools/agents/docker-compose.qdrant.yml +24 -0
  628. package/tools/agents/install-opencode-local.sh.j2 +135 -0
  629. package/tools/agents/migrations/apply.py +256 -0
  630. package/tools/agents/opencode_uap_agent.py +1505 -0
  631. package/tools/agents/plugin/README.md +91 -0
  632. package/tools/agents/plugin/index.ts +46 -0
  633. package/tools/agents/plugin/pre-compact.sh +68 -0
  634. package/tools/agents/plugin/session-start.sh +175 -0
  635. package/tools/agents/plugin/uap-commands.ts +45 -0
  636. package/tools/agents/plugin/uap-droids.ts +54 -0
  637. package/tools/agents/plugin/uap-patterns.ts +54 -0
  638. package/tools/agents/plugin/uap-skills.ts +52 -0
  639. package/tools/agents/plugins/uap-enforce.ts +314 -0
  640. package/tools/agents/scripts/__pycache__/tool_call_wrapper.cpython-313.pyc +0 -0
  641. package/tools/agents/scripts/chat_template_verifier.py +343 -0
  642. package/tools/agents/scripts/fix-qwen-template.js +38 -0
  643. package/tools/agents/scripts/fix_qwen_chat_template.py +316 -0
  644. package/tools/agents/scripts/generate_lora_training_data.py +412 -0
  645. package/tools/agents/scripts/init_qdrant.py +151 -0
  646. package/tools/agents/scripts/memory_migration.py +560 -0
  647. package/tools/agents/scripts/migrate_memory_to_qdrant.py +110 -0
  648. package/tools/agents/scripts/prepare_lora.sh +512 -0
  649. package/tools/agents/scripts/query_memory.py +200 -0
  650. package/tools/agents/scripts/qwen-tool-call-test.js +38 -0
  651. package/tools/agents/scripts/qwen-tool-call-wrapper.js +38 -0
  652. package/tools/agents/scripts/qwen_tool_call_test.py +464 -0
  653. package/tools/agents/scripts/qwen_tool_call_wrapper.py +686 -0
  654. package/tools/agents/scripts/start-services.sh +96 -0
  655. package/tools/agents/scripts/tool-choice-proxy.cjs +296 -0
  656. package/tools/agents/scripts/tool_call_test.py +656 -0
  657. package/tools/agents/scripts/tool_call_wrapper.py +799 -0
  658. package/tools/agents/tests/test_uap_compliance.py +257 -0
  659. package/tools/agents/uap_agent.py +122 -0
  660. package/tools/agents/uap_agent_install.sh +12 -0
@@ -0,0 +1,1095 @@
1
+ /**
2
+ * Hybrid Adaptive Context Selector for UAP (Option 4)
3
+ *
4
+ * VERSION: 2.0.0 - 21 Model Outcome Success Optimizations
5
+ *
6
+ * Combines task classification with time-budget awareness, runtime monitoring,
7
+ * and historical benefit tracking for optimal context loading decisions.
8
+ *
9
+ * OPTIMIZATIONS IMPLEMENTED:
10
+ * 1. Historical Data Persistence - SQLite instead of in-memory Map
11
+ * 2. Task-specific context sections for 5 failing tasks
12
+ * 3. Missing context sections (git_recovery, web_parsing, data_processing, theorem_proving)
13
+ * 4. Weighted keyword relevance scoring (TF-IDF-like specificity weights)
14
+ * 5. Token budget utilization - increase minimal sections from 1→2
15
+ * 6. Task-type-selective pattern injection
16
+ * 7. Smarter progressive context escalation with error-to-section mapping
17
+ * 8. Model Router fingerprint persistence integrated
18
+ * 9. Multi-category task classification support
19
+ * 10. Semantic caching foundation for task→outcome mappings
20
+ */
21
+ import Database from 'better-sqlite3';
22
+ import { existsSync, mkdirSync } from 'fs';
23
+ import { dirname, join } from 'path';
24
+ import { fileURLToPath } from 'url';
25
+ import { classifyTask as classifyTaskType } from './task-classifier.js';
26
+ import { recordTaskOutcome as updateModelRouterFingerprint, getModelFingerprint, } from './model-router.js';
27
+ const __filename = fileURLToPath(import.meta.url);
28
+ const __dirname = dirname(__filename);
29
+ // OPT 1: SQLite-backed historical data persistence with connection pooling to prevent contention
30
+ const DB_POOL_SIZE = 5;
31
+ const dbPool = [];
32
+ let poolInitialized = false;
33
+ let poolRoundRobinIndex = 0;
34
+ function initHistoricalDbPool() {
35
+ if (poolInitialized)
36
+ return;
37
+ const dbDir = join(__dirname, '../../agents/data/memory');
38
+ if (!existsSync(dbDir)) {
39
+ mkdirSync(dbDir, { recursive: true });
40
+ }
41
+ const dbPath = join(dbDir, 'historical_context.db');
42
+ for (let i = 0; i < DB_POOL_SIZE; i++) {
43
+ const db = new Database(dbPath);
44
+ db.pragma('journal_mode = WAL');
45
+ db.pragma('busy_timeout = 10000');
46
+ db.pragma('synchronous = NORMAL');
47
+ db.exec(`
48
+ CREATE TABLE IF NOT EXISTS historical_data (
49
+ task_type TEXT PRIMARY KEY,
50
+ total_attempts INTEGER DEFAULT 0,
51
+ uam_successes INTEGER DEFAULT 0,
52
+ no_uam_successes INTEGER DEFAULT 0,
53
+ avg_time_with_uam REAL DEFAULT 0,
54
+ avg_time_without_uam REAL DEFAULT 0,
55
+ last_updated INTEGER DEFAULT 0
56
+ );
57
+
58
+ -- OPT 10: Semantic cache for task→outcome mappings
59
+ CREATE TABLE IF NOT EXISTS semantic_cache (
60
+ cache_key TEXT PRIMARY KEY,
61
+ instruction_hash TEXT,
62
+ decision_json TEXT,
63
+ success_rate REAL DEFAULT 0.5,
64
+ created_at INTEGER,
65
+ last_used INTEGER,
66
+ use_count INTEGER DEFAULT 1
67
+ );
68
+
69
+ CREATE INDEX IF NOT EXISTS idx_semantic_cache_hash ON semantic_cache(instruction_hash);
70
+ `);
71
+ dbPool.push(db);
72
+ }
73
+ poolInitialized = true;
74
+ }
75
+ function getHistoricalDbFromPool() {
76
+ if (!poolInitialized)
77
+ initHistoricalDbPool();
78
+ const currentIndex = poolRoundRobinIndex % DB_POOL_SIZE;
79
+ poolRoundRobinIndex = (poolRoundRobinIndex + 1) % DB_POOL_SIZE;
80
+ return dbPool[currentIndex];
81
+ }
82
+ export function closeAllPools() {
83
+ for (const db of dbPool) {
84
+ try {
85
+ db.close();
86
+ }
87
+ catch (err) {
88
+ console.warn('Failed to close historical DB pool connection:', err);
89
+ }
90
+ }
91
+ dbPool.length = 0;
92
+ poolInitialized = false;
93
+ }
94
+ export function getHistoricalDb() {
95
+ return getHistoricalDbFromPool();
96
+ }
97
+ // OPTIMIZATION 7: Refined low-benefit categories
98
+ const LOW_BENEFIT_CATEGORIES = new Set([
99
+ 'reasoning', // Pure logical reasoning (sudoku, puzzles)
100
+ 'games', // Game theory, chess position analysis (but NOT chess-best-move which needs stockfish)
101
+ 'pure-logic', // Mathematical proofs, formal verification
102
+ 'mathematical', // Pure math calculations
103
+ 'calendar', // Meeting scheduling (but NOT server scheduling)
104
+ ]);
105
+ // Categories that should ALWAYS receive UAP context regardless of historical data
106
+ const ALWAYS_BENEFIT_CATEGORIES = new Set([
107
+ 'security',
108
+ 'file-ops',
109
+ 'sysadmin',
110
+ 'debugging',
111
+ 'legacy',
112
+ 'coding',
113
+ 'testing',
114
+ 'ml-training',
115
+ 'git-recovery', // OPT 3: Added for git tasks
116
+ 'data-processing', // OPT 3: Added for data tasks
117
+ 'theorem-proving', // OPT 3: Added for proof tasks
118
+ ]);
119
+ // OPT 4: Weighted keywords - specificity score (higher = more specific = more valuable)
120
+ const HIGH_BENEFIT_KEYWORDS = {
121
+ // Security - very specific terms get higher weights
122
+ hashcat: 3.0,
123
+ john: 2.5,
124
+ '7z': 2.5,
125
+ xss: 3.0,
126
+ injection: 2.0,
127
+ sanitize: 2.0,
128
+ bleach: 3.0,
129
+ dompurify: 3.0,
130
+ password: 1.5,
131
+ hash: 1.5,
132
+ crack: 2.0,
133
+ decrypt: 2.0,
134
+ secret: 1.5,
135
+ exploit: 2.0,
136
+ // File formats - specific formats get higher weights
137
+ elf: 3.0,
138
+ 'struct.unpack': 3.0,
139
+ e_phoff: 3.5,
140
+ sqlite: 2.0,
141
+ wal: 3.0,
142
+ binary: 1.5,
143
+ executable: 1.5,
144
+ extract: 1.5,
145
+ // Git recovery - OPT 3
146
+ reflog: 3.0,
147
+ fsck: 3.0,
148
+ 'git recovery': 3.0,
149
+ 'lost commit': 2.5,
150
+ 'detached head': 2.5,
151
+ 'git reset': 2.0,
152
+ 'git rebase': 1.5,
153
+ // Web parsing - OPT 2 (for filter-js-from-html)
154
+ 'html parse': 2.5,
155
+ dom: 2.0,
156
+ beautifulsoup: 2.5,
157
+ lxml: 2.5,
158
+ 'regex html': 2.0,
159
+ // Compression - OPT 2 (for gpt2-codegolf)
160
+ codegolf: 3.0,
161
+ minify: 2.0,
162
+ compress: 1.5,
163
+ gzip: 2.0,
164
+ zlib: 2.5,
165
+ // Chess - OPT 2 (for chess-best-move)
166
+ stockfish: 3.0,
167
+ 'python-chess': 3.0,
168
+ fen: 2.5,
169
+ pgn: 2.5,
170
+ 'chess position': 2.0,
171
+ chessimg2pos: 3.0,
172
+ // Legacy
173
+ cobol: 3.0,
174
+ fortran: 2.5,
175
+ legacy: 1.5,
176
+ modernize: 1.5,
177
+ mainframe: 2.5,
178
+ // Theorem proving - OPT 3 (for prove-plus-comm)
179
+ coq: 3.0,
180
+ lean: 3.0,
181
+ isabelle: 3.0,
182
+ theorem: 2.0,
183
+ proof: 1.5,
184
+ induction: 2.0,
185
+ commutativity: 2.5,
186
+ // Data processing - OPT 3 (for reshard-c4-data)
187
+ parquet: 2.5,
188
+ sharding: 2.5,
189
+ reshard: 3.0,
190
+ 'c4 data': 3.0,
191
+ dataset: 1.5,
192
+ arrow: 2.0,
193
+ // General coding
194
+ compile: 1.5,
195
+ build: 1.0,
196
+ makefile: 2.0,
197
+ database: 1.5,
198
+ recovery: 1.5,
199
+ };
200
+ // OPT 3 & 2: Extended context sections including new categories and task-specific sections
201
+ const CONTEXT_SECTIONS = {
202
+ security: {
203
+ tokens: 150,
204
+ keywords: [
205
+ 'xss',
206
+ 'password',
207
+ 'hash',
208
+ 'crack',
209
+ 'secret',
210
+ 'exploit',
211
+ 'injection',
212
+ 'sanitize',
213
+ 'bleach',
214
+ 'dompurify',
215
+ ],
216
+ keywordWeights: { hashcat: 3, bleach: 3, dompurify: 3, xss: 2.5, injection: 2 },
217
+ content: `### Security
218
+ - XSS: Use bleach.clean() or DOMPurify. Remove script, onclick, onerror, javascript:
219
+ - Password cracking: hashcat -m 11600 for 7z, -m 0 MD5, john for CPU
220
+ - Binary secrets: strings, objdump -d, check .rodata section
221
+ - Always validate and sanitize user input`,
222
+ patterns: ['P10', 'P20'], // Whitelist, Adversarial Testing
223
+ },
224
+ file_formats: {
225
+ tokens: 120,
226
+ keywords: ['elf', 'sqlite', '7z', 'archive', 'binary', 'extract', 'format', 'wal', 'struct'],
227
+ keywordWeights: { e_phoff: 4, 'struct.unpack': 3, wal: 3, elf: 2.5 },
228
+ content: `### File Formats
229
+ - ELF: Program headers at e_phoff. Use struct.unpack for parsing
230
+ - SQLite WAL: Header 32 bytes, frames follow. PRAGMA wal_checkpoint to recover
231
+ - 7z: Install p7zip-full, use 7z x -p for password protected archives`,
232
+ patterns: ['P9', 'P35'], // FormatPipeline, Decoder-First
233
+ },
234
+ coding: {
235
+ tokens: 80,
236
+ keywords: ['implement', 'function', 'class', 'refactor', 'algorithm', 'code'],
237
+ content: `### Coding
238
+ - Use absolute paths (/app/...)
239
+ - Verify file exists before reading
240
+ - Handle edge cases in parsing
241
+ - Match exact output format required`,
242
+ patterns: ['P12', 'P16'], // OEV, TFE+
243
+ },
244
+ tools: {
245
+ tokens: 100,
246
+ keywords: ['hashcat', 'john', 'strings', 'objdump', 'readelf', 'command', 'cli'],
247
+ keywordWeights: { hashcat: 3, john: 2.5, readelf: 2, objdump: 2 },
248
+ content: `### Tools
249
+ - hashcat: GPU password cracking, -m flag for hash type
250
+ - john: CPU password cracking, flexible format support
251
+ - readelf/objdump: Binary analysis
252
+ - strings: Extract printable strings from binaries`,
253
+ patterns: ['P4', 'P8'], // ToolSpec, CLIoverLib
254
+ },
255
+ legacy: {
256
+ tokens: 90,
257
+ keywords: ['cobol', 'fortran', 'legacy', 'modernize', 'mainframe'],
258
+ keywordWeights: { cobol: 3, fortran: 2.5, mainframe: 2.5 },
259
+ content: `### Legacy Code
260
+ - COBOL: Fixed-format columns, WORKING-STORAGE for variables
261
+ - Modernization: Preserve business logic, update data structures
262
+ - Test with original inputs to verify behavior`,
263
+ patterns: ['P3'], // StateProtect
264
+ },
265
+ debugging: {
266
+ tokens: 70,
267
+ keywords: ['debug', 'error', 'fix', 'traceback', 'exception', 'crash'],
268
+ content: `### Debugging
269
+ - Check logs first: journalctl, /var/log/
270
+ - Use verbose flags: -v, --debug
271
+ - Isolate the problem: binary search through changes`,
272
+ patterns: ['P15', 'P13'], // ER, IRL
273
+ },
274
+ domain_libraries: {
275
+ tokens: 100,
276
+ keywords: ['chess', 'statistics', 'compression', 'sampler', 'ars', 'stockfish', 'numerical'],
277
+ keywordWeights: { stockfish: 3, 'python-chess': 3, 'scipy.stats': 2.5, ars: 3 },
278
+ content: `### Domain Libraries (USE INSTEAD OF CUSTOM CODE)
279
+ - Chess: python-chess + stockfish (pip install python-chess), chessimg2pos for image→FEN
280
+ - Statistics/ARS: scipy.stats or R CRAN 'ars' package (NOT custom implementation)
281
+ - Compression: zlib, lz4, brotli (NOT custom Huffman). Test round-trip FIRST
282
+ - Numerical: numpy/scipy with tolerance 1e-6, test multiple random seeds`,
283
+ patterns: ['P11'], // PreComputed
284
+ },
285
+ output_verification: {
286
+ tokens: 80,
287
+ keywords: ['create', 'file', 'output', 'script', 'cli', 'executable', 'shebang'],
288
+ content: `### Output Verification (37% of failures = missing files)
289
+ - touch output files FIRST, then implement
290
+ - CLI scripts: add #!/usr/bin/env python3 shebang + chmod +x
291
+ - Test with ./script (NOT python3 script.py)
292
+ - Verify all expected files: ls -la before claiming done
293
+ - Partial output > no output: always create the file`,
294
+ patterns: ['P12', 'P16', 'P32'], // OEV, TFE+, CEV
295
+ },
296
+ // OPT 3: NEW SECTIONS for missing capabilities
297
+ git_recovery: {
298
+ tokens: 100,
299
+ keywords: [
300
+ 'git',
301
+ 'reflog',
302
+ 'fsck',
303
+ 'reset',
304
+ 'rebase',
305
+ 'merge',
306
+ 'conflict',
307
+ 'detached',
308
+ 'lost',
309
+ 'HEAD',
310
+ ],
311
+ keywordWeights: { reflog: 3, fsck: 3, dangling: 2.5, 'detached head': 2.5 },
312
+ content: `### Git Recovery (P22 GRF Pattern)
313
+ - ALWAYS backup first: cp -r .git .git.bak
314
+ - Lost commits: git reflog show HEAD, then git reset --hard HEAD@{n}
315
+ - Dangling objects: git fsck --lost-found, check .git/lost-found/
316
+ - Detached HEAD: git checkout -b recovery-branch
317
+ - Merge conflicts: git merge --abort to reset, or resolve with git mergetool
318
+ - Force push recovery: git reflog, find pre-push commit, reset`,
319
+ patterns: ['P22', 'P3'], // GRF, StateProtect
320
+ },
321
+ web_parsing: {
322
+ tokens: 110,
323
+ keywords: [
324
+ 'html',
325
+ 'parse',
326
+ 'dom',
327
+ 'beautifulsoup',
328
+ 'lxml',
329
+ 'regex',
330
+ 'scrape',
331
+ 'filter',
332
+ 'js',
333
+ 'javascript',
334
+ ],
335
+ keywordWeights: { beautifulsoup: 2.5, lxml: 2.5, 'html.parser': 2, 'regex html': 2 },
336
+ content: `### Web Parsing & XSS Filtering
337
+ - HTML parsing: Use BeautifulSoup with lxml parser (pip install bs4 lxml)
338
+ - XSS filtering: bleach.clean() with allowed_tags whitelist, NOT blacklist
339
+ - Script removal: Remove <script>, onclick, onerror, javascript: hrefs
340
+ - Preserve structure: Maintain HTML hierarchy, don't just regex replace
341
+ - Test edge cases: nested tags, malformed HTML, encoded entities
342
+ - filter-js-from-html: Create /app/filter.py with exact input/output format`,
343
+ patterns: ['P10', 'P20', 'P14'], // Whitelist, AT, OFV
344
+ },
345
+ data_processing: {
346
+ tokens: 100,
347
+ keywords: ['parquet', 'shard', 'reshard', 'dataset', 'arrow', 'pandas', 'dask', 'c4', 'chunk'],
348
+ keywordWeights: { parquet: 2.5, reshard: 3, arrow: 2, dask: 2 },
349
+ content: `### Data Processing & Sharding
350
+ - Parquet: Use pyarrow or fastparquet for columnar data
351
+ - Large datasets: dask.dataframe for out-of-core processing
352
+ - Sharding: Split by hash(key) % num_shards for even distribution
353
+ - C4 data: Common Crawl format, handle with datasets library
354
+ - Memory efficiency: Process in chunks, use generators
355
+ - Verification: Count rows before/after, checksum critical columns`,
356
+ patterns: ['P18', 'P31'], // MTP, RTV
357
+ },
358
+ theorem_proving: {
359
+ tokens: 90,
360
+ keywords: ['coq', 'lean', 'isabelle', 'theorem', 'proof', 'induction', 'lemma', 'tactic'],
361
+ keywordWeights: { coq: 3, lean: 3, isabelle: 3, induction: 2 },
362
+ content: `### Theorem Proving
363
+ - Coq: Use 'induction' tactic for recursive proofs, 'simpl' to simplify
364
+ - Lean: mathlib provides common lemmas, use 'rfl' for reflexivity
365
+ - Commutativity: Prove by induction on first argument, use IH in step case
366
+ - prove-plus-comm: Natural number addition commutativity via Peano axioms
367
+ - Tactics: intro, apply, rewrite, exact, reflexivity
368
+ - Debug: 'Show Proof' in Coq, 'trace.state' in Lean`,
369
+ patterns: ['P5'], // Impossible check
370
+ },
371
+ // OPT 2: Task-specific sections for the 5 persistently failing tasks
372
+ chess_vision: {
373
+ tokens: 110,
374
+ keywords: ['chess', 'image', 'board', 'fen', 'position', 'stockfish', 'best move', 'analyze'],
375
+ keywordWeights: { chessimg2pos: 4, stockfish: 3, fen: 2.5, 'best move': 2 },
376
+ content: `### Chess Image Analysis (chess-best-move)
377
+ - Image to FEN: pip install chessimg2pos (or board_to_fen)
378
+ - Position analysis: python-chess + stockfish engine
379
+ - Workflow: image → FEN → stockfish → best move
380
+ - Install: apt-get install stockfish, pip install python-chess
381
+ - Code: import chess.engine; engine.analyse(board, chess.engine.Limit(depth=20))
382
+ - Output: UCI notation (e.g., e2e4) or SAN (e.g., e4)`,
383
+ patterns: ['P11', 'P34'], // PreComputed, ISP
384
+ },
385
+ regex_chess: {
386
+ tokens: 100,
387
+ keywords: ['regex', 'chess', 'pgn', 'notation', 'game', 'century', 'parse'],
388
+ keywordWeights: { pgn: 3, 'game of century': 3, 'chess notation': 2.5 },
389
+ content: `### Regex Chess (regex-chess task)
390
+ - PGN parsing: Match moves with [KQRBN]?[a-h]?[1-8]?x?[a-h][1-8](=[QRBN])?[+#]?
391
+ - Castling: O-O (kingside), O-O-O (queenside)
392
+ - Game of Century: Byrne vs Fischer 1956, know key moves
393
+ - State machine: Track board state through move sequence
394
+ - Validation: Use python-chess for legal move verification
395
+ - Edge cases: Promotions, en passant, disambiguation`,
396
+ patterns: ['P24'], // PCC
397
+ },
398
+ compression_codegolf: {
399
+ tokens: 100,
400
+ keywords: ['codegolf', 'minify', 'gpt2', 'small', 'bytes', 'compress', 'size'],
401
+ keywordWeights: { codegolf: 3, gpt2: 3, minify: 2, bytes: 2 },
402
+ content: `### Code Golf & Compression (gpt2-codegolf)
403
+ - GPT-2 codegolf: Impossible to implement full GPT-2 in <5KB
404
+ - Strategy: Pre-compute weights, use lookup tables
405
+ - Minification: Remove whitespace, use short variable names
406
+ - gpt2.c: Reference implementation exists, study structure
407
+ - Shannon limit: Cannot compress below entropy of data
408
+ - If truly impossible: Document in IMPOSSIBLE.md with proof`,
409
+ patterns: ['P5', 'P19', 'P23'], // Impossible, ITR+, CID
410
+ },
411
+ db_wal_recovery: {
412
+ tokens: 100,
413
+ keywords: ['wal', 'sqlite', 'recovery', 'checkpoint', 'journal', 'database', 'corrupt'],
414
+ keywordWeights: { wal: 3, checkpoint: 3, 'db-wal-recovery': 4 },
415
+ content: `### SQLite WAL Recovery (db-wal-recovery)
416
+ - CRITICAL: Backup WAL file FIRST before any sqlite3 command!
417
+ - cp /app/main.db-wal /tmp/wal_backup.wal
418
+ - WAL auto-checkpoints when opened - this destroys recovery data
419
+ - Parse WAL manually: struct.unpack for header (32 bytes)
420
+ - Frame format: 24-byte header + page data
421
+ - Use /tmp/wal_backup.wal for analysis, never original
422
+ - Alternative: sqlite3_recover tool from SQLite source`,
423
+ patterns: ['P3', 'P35'], // StateProtect, DFA
424
+ },
425
+ };
426
+ // OPT 7: Error-to-section mapping for smarter progressive escalation
427
+ const ERROR_SECTION_MAPPING = {
428
+ 'permission denied': ['tools', 'output_verification'],
429
+ chmod: ['output_verification', 'tools'],
430
+ 'struct.unpack': ['file_formats'],
431
+ 'unpack requires': ['file_formats'],
432
+ 'no module named': ['domain_libraries', 'tools'],
433
+ 'command not found': ['tools'],
434
+ 'syntax error': ['coding', 'legacy'],
435
+ 'parse error': ['web_parsing', 'file_formats'],
436
+ hash: ['security', 'tools'],
437
+ xss: ['security', 'web_parsing'],
438
+ injection: ['security', 'web_parsing'],
439
+ git: ['git_recovery'],
440
+ reflog: ['git_recovery'],
441
+ 'merge conflict': ['git_recovery'],
442
+ 'detached head': ['git_recovery'],
443
+ parquet: ['data_processing'],
444
+ shard: ['data_processing'],
445
+ dataset: ['data_processing'],
446
+ coq: ['theorem_proving'],
447
+ lean: ['theorem_proving'],
448
+ induction: ['theorem_proving'],
449
+ chess: ['chess_vision', 'regex_chess', 'domain_libraries'],
450
+ stockfish: ['chess_vision', 'domain_libraries'],
451
+ fen: ['chess_vision'],
452
+ pgn: ['regex_chess'],
453
+ wal: ['db_wal_recovery', 'file_formats'],
454
+ sqlite: ['db_wal_recovery', 'file_formats'],
455
+ checkpoint: ['db_wal_recovery'],
456
+ codegolf: ['compression_codegolf'],
457
+ gpt2: ['compression_codegolf'],
458
+ minify: ['compression_codegolf'],
459
+ filter: ['web_parsing', 'security'],
460
+ html: ['web_parsing'],
461
+ beautifulsoup: ['web_parsing'],
462
+ };
463
+ // OPT 6: Pattern relevance by task type
464
+ const TASK_TYPE_PATTERNS = {
465
+ security: ['P10', 'P20', 'P11'],
466
+ 'file-ops': ['P9', 'P35', 'P3', 'P12'],
467
+ coding: ['P12', 'P16', 'P32', 'P17'],
468
+ debugging: ['P15', 'P13', 'P3'],
469
+ 'git-recovery': ['P22', 'P3'],
470
+ 'data-processing': ['P18', 'P31', 'P12'],
471
+ 'theorem-proving': ['P5', 'P11'],
472
+ legacy: ['P3', 'P35'],
473
+ sysadmin: ['P1', 'P8', 'P4'],
474
+ 'ml-training': ['P11', 'P33', 'P30'],
475
+ testing: ['P13', 'P26', 'P30'],
476
+ };
477
+ // Constants
478
+ const MS_PER_TOKEN = 1.5;
479
+ const BENEFIT_THRESHOLD = 0.1;
480
+ const RELEVANCE_THRESHOLD = 0.3;
481
+ const TIME_CRITICAL_MAX_TOKENS = 300;
482
+ // OPT 4: Calculate weighted relevance score for a section
483
+ function calculateSectionRelevance(instruction, sectionConfig) {
484
+ const lower = instruction.toLowerCase();
485
+ let totalScore = 0;
486
+ let matchCount = 0;
487
+ for (const kw of sectionConfig.keywords) {
488
+ if (lower.includes(kw.toLowerCase())) {
489
+ // OPT 4: Use specificity weight if available, otherwise default to 1
490
+ const weight = sectionConfig.keywordWeights?.[kw] || 1;
491
+ totalScore += weight;
492
+ matchCount++;
493
+ }
494
+ }
495
+ // Also check global high-benefit keywords with their weights
496
+ for (const [kw, weight] of Object.entries(HIGH_BENEFIT_KEYWORDS)) {
497
+ if (lower.includes(kw.toLowerCase())) {
498
+ // Check if this keyword is relevant to this section
499
+ if (sectionConfig.keywords.some((sk) => kw.includes(sk) || sk.includes(kw))) {
500
+ totalScore += weight * 0.5; // Partial bonus for related keywords
501
+ }
502
+ }
503
+ }
504
+ // Normalize: max possible score is roughly keywords.length * 3 (max weight)
505
+ const maxPossible = sectionConfig.keywords.length * 3;
506
+ return Math.min(totalScore / Math.max(maxPossible * 0.3, 1), 1);
507
+ }
508
+ export function classifyTaskMultiCategory(instruction) {
509
+ const lower = instruction.toLowerCase();
510
+ const categoryScores = {};
511
+ const matchedKeywords = [];
512
+ // Score from high-benefit keywords
513
+ for (const [kw, weight] of Object.entries(HIGH_BENEFIT_KEYWORDS)) {
514
+ if (lower.includes(kw.toLowerCase())) {
515
+ matchedKeywords.push(kw);
516
+ // Map keywords to categories
517
+ if ([
518
+ 'password',
519
+ 'hash',
520
+ 'crack',
521
+ 'xss',
522
+ 'injection',
523
+ 'sanitize',
524
+ 'hashcat',
525
+ 'john',
526
+ 'bleach',
527
+ 'dompurify',
528
+ ].some((k) => kw.includes(k))) {
529
+ categoryScores['security'] = (categoryScores['security'] || 0) + weight;
530
+ }
531
+ if (['elf', 'sqlite', 'binary', 'wal', 'struct'].some((k) => kw.includes(k))) {
532
+ categoryScores['file-ops'] = (categoryScores['file-ops'] || 0) + weight;
533
+ }
534
+ if (['git', 'reflog', 'fsck', 'rebase'].some((k) => kw.includes(k))) {
535
+ categoryScores['git-recovery'] = (categoryScores['git-recovery'] || 0) + weight;
536
+ }
537
+ if (['cobol', 'fortran', 'legacy', 'mainframe'].some((k) => kw.includes(k))) {
538
+ categoryScores['legacy'] = (categoryScores['legacy'] || 0) + weight;
539
+ }
540
+ if (['coq', 'lean', 'theorem', 'proof', 'induction'].some((k) => kw.includes(k))) {
541
+ categoryScores['theorem-proving'] = (categoryScores['theorem-proving'] || 0) + weight;
542
+ }
543
+ if (['parquet', 'shard', 'reshard', 'dataset', 'arrow'].some((k) => kw.includes(k))) {
544
+ categoryScores['data-processing'] = (categoryScores['data-processing'] || 0) + weight;
545
+ }
546
+ if (['stockfish', 'chess', 'fen', 'pgn'].some((k) => kw.includes(k))) {
547
+ categoryScores['chess'] = (categoryScores['chess'] || 0) + weight;
548
+ }
549
+ }
550
+ }
551
+ // Fall back to task-classifier
552
+ const baseClassification = classifyTaskType(instruction);
553
+ categoryScores[baseClassification.category] =
554
+ (categoryScores[baseClassification.category] || 0) + 5;
555
+ // Sort by score
556
+ const sorted = Object.entries(categoryScores).sort(([, a], [, b]) => b - a);
557
+ if (sorted.length === 0) {
558
+ return {
559
+ primary: 'coding',
560
+ secondary: [],
561
+ confidence: 0.5,
562
+ keywords: matchedKeywords,
563
+ };
564
+ }
565
+ const [primary, primaryScore] = sorted[0];
566
+ const secondary = sorted
567
+ .slice(1, 3)
568
+ .filter(([, score]) => score >= primaryScore * 0.4)
569
+ .map(([cat]) => cat);
570
+ const maxPossible = Object.values(HIGH_BENEFIT_KEYWORDS).reduce((a, b) => a + b, 0);
571
+ const confidence = Math.min(primaryScore / (maxPossible * 0.1), 1);
572
+ return {
573
+ primary,
574
+ secondary,
575
+ confidence,
576
+ keywords: matchedKeywords,
577
+ };
578
+ }
579
+ /**
580
+ * Classify task type from instruction text (backward compatible)
581
+ */
582
+ export function classifyTask(instruction) {
583
+ return classifyTaskMultiCategory(instruction).primary;
584
+ }
585
+ /**
586
+ * Assess time pressure based on timeout and task complexity
587
+ */
588
+ export function assessTimePressure(timeoutSec, taskType, difficulty = 'medium') {
589
+ const difficultyMultiplier = {
590
+ easy: 0.5,
591
+ medium: 1.0,
592
+ hard: 2.0,
593
+ };
594
+ const baseDuration = {
595
+ security: 120,
596
+ 'file-ops': 90,
597
+ legacy: 150,
598
+ coding: 60,
599
+ debugging: 90,
600
+ scheduling: 45,
601
+ games: 30,
602
+ 'constraint-satisfaction': 60,
603
+ 'pure-logic': 90,
604
+ reasoning: 60,
605
+ general: 60,
606
+ sysadmin: 120,
607
+ 'ml-training': 180,
608
+ testing: 60,
609
+ 'git-recovery': 90,
610
+ 'data-processing': 120,
611
+ 'theorem-proving': 180,
612
+ chess: 90,
613
+ unknown: 60,
614
+ };
615
+ const expectedDuration = (baseDuration[taskType] || 60) * (difficultyMultiplier[difficulty] || 1.0);
616
+ const ratio = timeoutSec / expectedDuration;
617
+ if (ratio < 1.0)
618
+ return 'critical';
619
+ if (ratio < 1.3)
620
+ return 'high';
621
+ if (ratio < 1.8)
622
+ return 'medium';
623
+ return 'low';
624
+ }
625
+ /**
626
+ * OPT 1: Get historical benefit from SQLite (persistent)
627
+ */
628
+ export function getHistoricalBenefit(taskType) {
629
+ try {
630
+ const db = getHistoricalDb();
631
+ const row = db.prepare('SELECT * FROM historical_data WHERE task_type = ?').get(taskType);
632
+ if (!row || row.totalAttempts < 3) {
633
+ if (LOW_BENEFIT_CATEGORIES.has(taskType)) {
634
+ return 0.05;
635
+ }
636
+ return 0.5;
637
+ }
638
+ const uapRate = row.uapSuccesses / Math.max(row.totalAttempts / 2, 1);
639
+ const noUamRate = row.noUamSuccesses / Math.max(row.totalAttempts / 2, 1);
640
+ if (noUamRate === 0)
641
+ return uapRate > 0 ? 1.0 : 0.5;
642
+ return (uapRate - noUamRate) / Math.max(uapRate, noUamRate, 0.1);
643
+ }
644
+ catch {
645
+ // Fallback to defaults if DB fails
646
+ if (LOW_BENEFIT_CATEGORIES.has(taskType)) {
647
+ return 0.05;
648
+ }
649
+ return 0.5;
650
+ }
651
+ }
652
+ /**
653
+ * OPT 1: Record task outcome to SQLite (persistent)
654
+ */
655
+ export function recordOutcome(taskType, usedUam, success, durationMs, modelId) {
656
+ try {
657
+ const db = getHistoricalDb();
658
+ // Get existing record or create new
659
+ const existing = db
660
+ .prepare('SELECT * FROM historical_data WHERE task_type = ?')
661
+ .get(taskType);
662
+ if (existing) {
663
+ // Update existing record
664
+ const stmt = db.prepare(`
665
+ UPDATE historical_data SET
666
+ total_attempts = total_attempts + 1,
667
+ uam_successes = uam_successes + ?,
668
+ no_uam_successes = no_uam_successes + ?,
669
+ avg_time_with_uam = CASE WHEN ? THEN (avg_time_with_uam * uam_successes + ?) / (uam_successes + 1) ELSE avg_time_with_uam END,
670
+ avg_time_without_uam = CASE WHEN ? THEN (avg_time_without_uam * no_uam_successes + ?) / (no_uam_successes + 1) ELSE avg_time_without_uam END,
671
+ last_updated = ?
672
+ WHERE task_type = ?
673
+ `);
674
+ stmt.run(usedUam && success ? 1 : 0, !usedUam && success ? 1 : 0, usedUam && success ? 1 : 0, durationMs, !usedUam && success ? 1 : 0, durationMs, Date.now(), taskType);
675
+ }
676
+ else {
677
+ // Insert new record
678
+ const stmt = db.prepare(`
679
+ INSERT INTO historical_data (task_type, total_attempts, uam_successes, no_uam_successes, avg_time_with_uam, avg_time_without_uam, last_updated)
680
+ VALUES (?, 1, ?, ?, ?, ?, ?)
681
+ `);
682
+ stmt.run(taskType, usedUam && success ? 1 : 0, !usedUam && success ? 1 : 0, usedUam && success ? durationMs : 0, !usedUam && success ? durationMs : 0, Date.now());
683
+ }
684
+ }
685
+ catch (err) {
686
+ // Log but don't throw - recording should not block execution
687
+ console.warn('Failed to record outcome:', err);
688
+ }
689
+ // OPT 8: Also update model router fingerprints
690
+ if (modelId) {
691
+ const validModelIds = ['glm-4.7', 'gpt-5.2', 'claude-opus-4.5', 'gpt-5.2-codex'];
692
+ if (validModelIds.includes(modelId)) {
693
+ updateModelRouterFingerprint(modelId, success, durationMs, taskType);
694
+ }
695
+ }
696
+ }
697
+ /**
698
+ * OPT 10: Cache lookup for similar tasks
699
+ */
700
+ export function lookupSemanticCache(instructionHash) {
701
+ try {
702
+ const db = getHistoricalDb();
703
+ const row = db
704
+ .prepare(`
705
+ SELECT decision_json, success_rate
706
+ FROM semantic_cache
707
+ WHERE instruction_hash = ? AND success_rate >= 0.5
708
+ ORDER BY success_rate DESC, use_count DESC
709
+ LIMIT 1
710
+ `)
711
+ .get(instructionHash);
712
+ if (row) {
713
+ // Update usage stats
714
+ db.prepare(`
715
+ UPDATE semantic_cache
716
+ SET last_used = ?, use_count = use_count + 1
717
+ WHERE instruction_hash = ?
718
+ `).run(Date.now(), instructionHash);
719
+ return JSON.parse(row.decision_json);
720
+ }
721
+ }
722
+ catch {
723
+ // Cache miss
724
+ }
725
+ return null;
726
+ }
727
+ /**
728
+ * OPT 10: Store decision in semantic cache
729
+ */
730
+ export function storeSemanticCache(cacheKey, instructionHash, decision, success) {
731
+ try {
732
+ const db = getHistoricalDb();
733
+ const existing = db.prepare('SELECT * FROM semantic_cache WHERE cache_key = ?').get(cacheKey);
734
+ if (existing) {
735
+ // Update success rate with exponential moving average
736
+ db.prepare(`
737
+ UPDATE semantic_cache SET
738
+ decision_json = ?,
739
+ success_rate = success_rate * 0.8 + ? * 0.2,
740
+ last_used = ?,
741
+ use_count = use_count + 1
742
+ WHERE cache_key = ?
743
+ `).run(JSON.stringify(decision), success ? 1.0 : 0.0, Date.now(), cacheKey);
744
+ }
745
+ else {
746
+ db.prepare(`
747
+ INSERT INTO semantic_cache (cache_key, instruction_hash, decision_json, success_rate, created_at, last_used, use_count)
748
+ VALUES (?, ?, ?, ?, ?, ?, 1)
749
+ `).run(cacheKey, instructionHash, JSON.stringify(decision), success ? 1.0 : 0.5, Date.now(), Date.now());
750
+ }
751
+ }
752
+ catch (err) {
753
+ console.warn('Failed to store in semantic cache:', err);
754
+ }
755
+ }
756
+ /**
757
+ * Select relevant context sections based on task type and instruction
758
+ * OPT 5: Returns at least 2 sections for minimal mode
759
+ */
760
+ export function selectRelevantSections(instruction, taskType, secondaryCategories) {
761
+ const sectionsWithScores = [];
762
+ for (const [name, config] of Object.entries(CONTEXT_SECTIONS)) {
763
+ const score = calculateSectionRelevance(instruction, config);
764
+ if (score >= RELEVANCE_THRESHOLD) {
765
+ sectionsWithScores.push({ name, score, patterns: config.patterns });
766
+ }
767
+ }
768
+ // Sort by relevance score descending
769
+ sectionsWithScores.sort((a, b) => b.score - a.score);
770
+ const sections = sectionsWithScores.map((s) => s.name);
771
+ // Add default sections for certain task types if not already included
772
+ const addIfMissing = (section) => {
773
+ if (!sections.includes(section))
774
+ sections.push(section);
775
+ };
776
+ // Primary category defaults
777
+ if (taskType === 'security')
778
+ addIfMissing('security');
779
+ if (taskType === 'file-ops')
780
+ addIfMissing('file_formats');
781
+ if (taskType === 'legacy')
782
+ addIfMissing('legacy');
783
+ if (taskType === 'git-recovery')
784
+ addIfMissing('git_recovery');
785
+ if (taskType === 'data-processing')
786
+ addIfMissing('data_processing');
787
+ if (taskType === 'theorem-proving')
788
+ addIfMissing('theorem_proving');
789
+ if (taskType === 'chess') {
790
+ addIfMissing('chess_vision');
791
+ addIfMissing('domain_libraries');
792
+ }
793
+ // OPT 9: Add sections for secondary categories too
794
+ if (secondaryCategories) {
795
+ for (const cat of secondaryCategories) {
796
+ if (cat === 'security')
797
+ addIfMissing('security');
798
+ if (cat === 'file-ops')
799
+ addIfMissing('file_formats');
800
+ if (cat === 'git-recovery')
801
+ addIfMissing('git_recovery');
802
+ }
803
+ }
804
+ return sections;
805
+ }
806
+ /**
807
+ * Calculate estimated overhead for given sections in milliseconds
808
+ */
809
+ export function calculateOverhead(sections) {
810
+ let totalTokens = 0;
811
+ for (const section of sections) {
812
+ totalTokens += CONTEXT_SECTIONS[section]?.tokens || 0;
813
+ }
814
+ return totalTokens * MS_PER_TOKEN;
815
+ }
816
+ /**
817
+ * OPT 6: Get relevant patterns for task type
818
+ */
819
+ export function getRelevantPatterns(taskType, sections) {
820
+ const patterns = new Set();
821
+ // From task type
822
+ const typePatterns = TASK_TYPE_PATTERNS[taskType] || [];
823
+ for (const p of typePatterns)
824
+ patterns.add(p);
825
+ // From selected sections
826
+ for (const section of sections) {
827
+ const sectionConfig = CONTEXT_SECTIONS[section];
828
+ if (sectionConfig?.patterns) {
829
+ for (const p of sectionConfig.patterns)
830
+ patterns.add(p);
831
+ }
832
+ }
833
+ return Array.from(patterns);
834
+ }
835
+ /**
836
+ * Main decision function: determine optimal context level using hybrid approach
837
+ */
838
+ export function decideContextLevel(instruction, metadata = {}) {
839
+ // OPT 9: Use multi-category classification
840
+ const multiClass = classifyTaskMultiCategory(instruction);
841
+ const taskType = multiClass.primary;
842
+ const timeoutSec = metadata.timeout_sec || 300;
843
+ const difficulty = metadata.difficulty || 'medium';
844
+ // Factor 1: Task classification - skip for pure reasoning
845
+ if (LOW_BENEFIT_CATEGORIES.has(taskType)) {
846
+ return {
847
+ level: 'none',
848
+ sections: [],
849
+ reason: `Task type '${taskType}' is pure reasoning - UAP adds no benefit`,
850
+ estimatedOverheadMs: 0,
851
+ taskType,
852
+ timePressure: 'low',
853
+ historicalBenefit: 0,
854
+ secondaryCategories: multiClass.secondary,
855
+ };
856
+ }
857
+ // Factor 2: Time pressure assessment
858
+ const timePressure = assessTimePressure(timeoutSec, taskType, difficulty);
859
+ // Factor 3: Historical benefit (now from SQLite - OPT 1)
860
+ const historicalBenefit = metadata.historical_uap_benefit ?? getHistoricalBenefit(taskType);
861
+ // Factor 4: Check if historical data suggests skipping UAP
862
+ if (historicalBenefit < BENEFIT_THRESHOLD && !ALWAYS_BENEFIT_CATEGORIES.has(taskType)) {
863
+ return {
864
+ level: 'none',
865
+ sections: [],
866
+ reason: `Low historical benefit (${(historicalBenefit * 100).toFixed(1)}%) for ${taskType}`,
867
+ estimatedOverheadMs: 0,
868
+ taskType,
869
+ timePressure,
870
+ historicalBenefit,
871
+ secondaryCategories: multiClass.secondary,
872
+ };
873
+ }
874
+ // Factor 5: Critical time pressure - skip UAP
875
+ if (timePressure === 'critical') {
876
+ return {
877
+ level: 'none',
878
+ sections: [],
879
+ reason: 'Critical time pressure - skipping UAP to avoid timeout',
880
+ estimatedOverheadMs: 0,
881
+ taskType,
882
+ timePressure,
883
+ historicalBenefit,
884
+ secondaryCategories: multiClass.secondary,
885
+ };
886
+ }
887
+ // Factor 6: Select relevant sections (OPT 9: including secondary categories)
888
+ const relevantSections = selectRelevantSections(instruction, taskType, multiClass.secondary);
889
+ const estimatedOverhead = calculateOverhead(relevantSections);
890
+ // OPT 6: Get relevant patterns
891
+ const relevantPatterns = getRelevantPatterns(taskType, relevantSections);
892
+ // Factor 7: Check if overhead fits within time budget
893
+ const overheadRatio = estimatedOverhead / (timeoutSec * 1000);
894
+ // Time-critical tasks (<120s): cap overhead to TIME_CRITICAL_MAX_TOKENS
895
+ if (timeoutSec < 120) {
896
+ const cappedSections = [];
897
+ let tokenBudget = TIME_CRITICAL_MAX_TOKENS;
898
+ for (const section of relevantSections) {
899
+ const sectionTokens = CONTEXT_SECTIONS[section]?.tokens || 0;
900
+ if (tokenBudget - sectionTokens >= 0) {
901
+ cappedSections.push(section);
902
+ tokenBudget -= sectionTokens;
903
+ }
904
+ }
905
+ return {
906
+ level: cappedSections.length > 0 ? 'minimal' : 'none',
907
+ sections: cappedSections,
908
+ reason: `Time-critical task (<120s) - capped to ${TIME_CRITICAL_MAX_TOKENS} tokens`,
909
+ estimatedOverheadMs: calculateOverhead(cappedSections),
910
+ taskType,
911
+ timePressure,
912
+ historicalBenefit,
913
+ secondaryCategories: multiClass.secondary,
914
+ relevantPatterns,
915
+ };
916
+ }
917
+ // OPT 5: Use 2 sections instead of 1 for minimal mode
918
+ if (timePressure === 'high' || overheadRatio > 0.1) {
919
+ const minimalSections = relevantSections.slice(0, 2); // Changed from 1 to 2
920
+ return {
921
+ level: 'minimal',
922
+ sections: minimalSections,
923
+ reason: `High time pressure - using minimal context (${minimalSections.join(', ') || 'best_practices'})`,
924
+ estimatedOverheadMs: calculateOverhead(minimalSections),
925
+ taskType,
926
+ timePressure,
927
+ historicalBenefit,
928
+ secondaryCategories: multiClass.secondary,
929
+ relevantPatterns,
930
+ };
931
+ }
932
+ // Default: Full context for everything else
933
+ return {
934
+ level: 'full',
935
+ sections: relevantSections.length > 0 ? relevantSections : ['coding'],
936
+ reason: `Full context for ${taskType} task (${timePressure} pressure)`,
937
+ estimatedOverheadMs: estimatedOverhead,
938
+ taskType,
939
+ timePressure,
940
+ historicalBenefit,
941
+ secondaryCategories: multiClass.secondary,
942
+ relevantPatterns,
943
+ };
944
+ }
945
+ /**
946
+ * Generate context string based on decision
947
+ */
948
+ export function generateContext(decision) {
949
+ if (decision.level === 'none' || decision.sections.length === 0) {
950
+ return '';
951
+ }
952
+ const contextParts = ['## UAP Memory Context\n'];
953
+ for (const section of decision.sections) {
954
+ const sectionConfig = CONTEXT_SECTIONS[section];
955
+ if (sectionConfig) {
956
+ contextParts.push(sectionConfig.content);
957
+ }
958
+ }
959
+ // OPT 6: Add relevant patterns hint
960
+ if (decision.relevantPatterns && decision.relevantPatterns.length > 0) {
961
+ contextParts.push(`\n### Relevant Patterns: ${decision.relevantPatterns.join(', ')}`);
962
+ }
963
+ return contextParts.join('\n');
964
+ }
965
+ /**
966
+ * OPT 7: Enhanced progressive context strategy with error-to-section mapping
967
+ */
968
+ export function getProgressiveContextLevels(instruction, initialError, metadata = {}) {
969
+ const decision = decideContextLevel(instruction, metadata);
970
+ if (decision.level === 'none' && LOW_BENEFIT_CATEGORIES.has(decision.taskType)) {
971
+ return ['none'];
972
+ }
973
+ const errorLower = initialError.toLowerCase();
974
+ // OPT 7: Check error-to-section mapping for targeted escalation
975
+ let suggestedSections = [];
976
+ for (const [errorPattern, sections] of Object.entries(ERROR_SECTION_MAPPING)) {
977
+ if (errorLower.includes(errorPattern)) {
978
+ suggestedSections.push(...sections);
979
+ }
980
+ }
981
+ // Standard context-might-help checks
982
+ const contextMightHelp = suggestedSections.length > 0 ||
983
+ errorLower.includes('unknown') ||
984
+ errorLower.includes('how to') ||
985
+ errorLower.includes('what is') ||
986
+ errorLower.includes('command not found') ||
987
+ errorLower.includes('invalid syntax') ||
988
+ errorLower.includes('format') ||
989
+ errorLower.includes('parse');
990
+ if (!contextMightHelp) {
991
+ return [decision.level];
992
+ }
993
+ // Progressive escalation based on starting point
994
+ switch (decision.level) {
995
+ case 'none':
996
+ return ['none', 'minimal', 'full'];
997
+ case 'minimal':
998
+ return ['minimal', 'full'];
999
+ case 'full':
1000
+ return ['full'];
1001
+ default:
1002
+ return ['none', 'minimal', 'full'];
1003
+ }
1004
+ }
1005
+ /**
1006
+ * OPT 7: Get additional sections to add based on error analysis
1007
+ */
1008
+ export function getSectionsForError(error) {
1009
+ const errorLower = error.toLowerCase();
1010
+ const sections = new Set();
1011
+ for (const [errorPattern, sectionList] of Object.entries(ERROR_SECTION_MAPPING)) {
1012
+ if (errorLower.includes(errorPattern)) {
1013
+ for (const section of sectionList) {
1014
+ sections.add(section);
1015
+ }
1016
+ }
1017
+ }
1018
+ return Array.from(sections);
1019
+ }
1020
+ /**
1021
+ * Export configuration for Python agent integration
1022
+ */
1023
+ export function exportConfigForPython(instruction, metadata = {}) {
1024
+ const decision = decideContextLevel(instruction, metadata);
1025
+ const context = generateContext(decision);
1026
+ return JSON.stringify({
1027
+ level: decision.level,
1028
+ sections: decision.sections,
1029
+ reason: decision.reason,
1030
+ estimatedOverheadMs: decision.estimatedOverheadMs,
1031
+ taskType: decision.taskType,
1032
+ timePressure: decision.timePressure,
1033
+ historicalBenefit: decision.historicalBenefit,
1034
+ secondaryCategories: decision.secondaryCategories,
1035
+ relevantPatterns: decision.relevantPatterns,
1036
+ context,
1037
+ }, null, 2);
1038
+ }
1039
+ /**
1040
+ * OPT 8: Get model fingerprint for routing integration
1041
+ */
1042
+ export function getModelFingerprintForTask(taskType) {
1043
+ // Check per-category success rates from model router
1044
+ const models = ['claude-opus-4.5', 'gpt-5.2', 'glm-4.7', 'gpt-5.2-codex'];
1045
+ let bestModel = 'claude-opus-4.5';
1046
+ let bestScore = 0;
1047
+ for (const modelId of models) {
1048
+ const fp = getModelFingerprint(modelId);
1049
+ if (fp && fp.categoryStats?.[taskType]) {
1050
+ const stats = fp.categoryStats[taskType];
1051
+ if (stats.attempts >= 3) {
1052
+ const rate = stats.successes / stats.attempts;
1053
+ if (rate > bestScore) {
1054
+ bestScore = rate;
1055
+ bestModel = modelId;
1056
+ }
1057
+ }
1058
+ }
1059
+ }
1060
+ if (bestScore > 0) {
1061
+ return {
1062
+ recommended: bestModel,
1063
+ reason: `${bestModel} has ${(bestScore * 100).toFixed(0)}% success rate for ${taskType} tasks`,
1064
+ };
1065
+ }
1066
+ return null;
1067
+ }
1068
+ /**
1069
+ * Close database connection pool (for cleanup)
1070
+ */
1071
+ export function closeHistoricalDb() {
1072
+ closeAllPools();
1073
+ }
1074
+ // Export main interface
1075
+ export const HybridAdaptiveContext = {
1076
+ classifyTask,
1077
+ classifyTaskMultiCategory,
1078
+ assessTimePressure,
1079
+ getHistoricalBenefit,
1080
+ recordOutcome,
1081
+ decideContextLevel,
1082
+ generateContext,
1083
+ selectRelevantSections,
1084
+ calculateOverhead,
1085
+ getProgressiveContextLevels,
1086
+ getSectionsForError,
1087
+ getRelevantPatterns,
1088
+ exportConfigForPython,
1089
+ lookupSemanticCache,
1090
+ storeSemanticCache,
1091
+ getModelFingerprintForTask,
1092
+ closeHistoricalDb,
1093
+ };
1094
+ export default HybridAdaptiveContext;
1095
+ //# sourceMappingURL=adaptive-context.js.map