@namzu/sdk 38.1.0 → 39.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 (534) hide show
  1. package/CHANGELOG.md +758 -0
  2. package/dist/advisory/executor.d.ts +10 -1
  3. package/dist/advisory/executor.d.ts.map +1 -1
  4. package/dist/advisory/executor.js +5 -26
  5. package/dist/advisory/executor.js.map +1 -1
  6. package/dist/advisory/history.d.ts +9 -0
  7. package/dist/advisory/history.d.ts.map +1 -0
  8. package/dist/advisory/history.js +120 -0
  9. package/dist/advisory/history.js.map +1 -0
  10. package/dist/advisory/index.d.ts +1 -1
  11. package/dist/advisory/index.d.ts.map +1 -1
  12. package/dist/advisory/index.js.map +1 -1
  13. package/dist/agents/ReactiveAgent.d.ts.map +1 -1
  14. package/dist/agents/ReactiveAgent.js +3 -0
  15. package/dist/agents/ReactiveAgent.js.map +1 -1
  16. package/dist/agents/runAgent.d.ts +10 -0
  17. package/dist/agents/runAgent.d.ts.map +1 -1
  18. package/dist/agents/runAgent.js +3 -0
  19. package/dist/agents/runAgent.js.map +1 -1
  20. package/dist/compaction/manual.d.ts +6 -0
  21. package/dist/compaction/manual.d.ts.map +1 -1
  22. package/dist/compaction/manual.js +21 -2
  23. package/dist/compaction/manual.js.map +1 -1
  24. package/dist/compaction/summary.d.ts.map +1 -1
  25. package/dist/compaction/summary.js +4 -1
  26. package/dist/compaction/summary.js.map +1 -1
  27. package/dist/config/runtime.js +2 -2
  28. package/dist/config/runtime.js.map +1 -1
  29. package/dist/contracts/schemas.js +1 -1
  30. package/dist/contracts/schemas.js.map +1 -1
  31. package/dist/eval/harness-protection.d.ts +18 -0
  32. package/dist/eval/harness-protection.d.ts.map +1 -0
  33. package/dist/eval/harness-protection.js +58 -0
  34. package/dist/eval/harness-protection.js.map +1 -0
  35. package/dist/eval/harness-verification.d.ts +6 -1
  36. package/dist/eval/harness-verification.d.ts.map +1 -1
  37. package/dist/eval/harness-verification.js +19 -2
  38. package/dist/eval/harness-verification.js.map +1 -1
  39. package/dist/eval/index.d.ts +1 -0
  40. package/dist/eval/index.d.ts.map +1 -1
  41. package/dist/eval/index.js.map +1 -1
  42. package/dist/manager/resident/activity.d.ts +50 -0
  43. package/dist/manager/resident/activity.d.ts.map +1 -0
  44. package/dist/manager/resident/activity.js +125 -0
  45. package/dist/manager/resident/activity.js.map +1 -0
  46. package/dist/manager/resident/agenda.d.ts +137 -0
  47. package/dist/manager/resident/agenda.d.ts.map +1 -0
  48. package/dist/manager/resident/agenda.js +586 -0
  49. package/dist/manager/resident/agenda.js.map +1 -0
  50. package/dist/manager/resident/consumption.d.ts +104 -0
  51. package/dist/manager/resident/consumption.d.ts.map +1 -0
  52. package/dist/manager/resident/consumption.js +233 -0
  53. package/dist/manager/resident/consumption.js.map +1 -0
  54. package/dist/manager/resident/delivery-window.d.ts +22 -0
  55. package/dist/manager/resident/delivery-window.d.ts.map +1 -0
  56. package/dist/manager/resident/delivery-window.js +78 -0
  57. package/dist/manager/resident/delivery-window.js.map +1 -0
  58. package/dist/manager/resident/evidence-recall.d.ts +24 -0
  59. package/dist/manager/resident/evidence-recall.d.ts.map +1 -0
  60. package/dist/manager/resident/evidence-recall.js +295 -0
  61. package/dist/manager/resident/evidence-recall.js.map +1 -0
  62. package/dist/manager/resident/history-disk.d.ts +10 -0
  63. package/dist/manager/resident/history-disk.d.ts.map +1 -0
  64. package/dist/manager/resident/history-disk.js +50 -0
  65. package/dist/manager/resident/history-disk.js.map +1 -0
  66. package/dist/manager/resident/history.d.ts +79 -0
  67. package/dist/manager/resident/history.d.ts.map +1 -0
  68. package/dist/manager/resident/history.js +203 -0
  69. package/dist/manager/resident/history.js.map +1 -0
  70. package/dist/manager/resident/host.d.ts +78 -0
  71. package/dist/manager/resident/host.d.ts.map +1 -0
  72. package/dist/manager/resident/host.js +252 -0
  73. package/dist/manager/resident/host.js.map +1 -0
  74. package/dist/manager/resident/initiative.d.ts +111 -0
  75. package/dist/manager/resident/initiative.d.ts.map +1 -0
  76. package/dist/manager/resident/initiative.js +129 -0
  77. package/dist/manager/resident/initiative.js.map +1 -0
  78. package/dist/manager/resident/learning-cycle.d.ts +131 -0
  79. package/dist/manager/resident/learning-cycle.d.ts.map +1 -0
  80. package/dist/manager/resident/learning-cycle.js +306 -0
  81. package/dist/manager/resident/learning-cycle.js.map +1 -0
  82. package/dist/manager/resident/learning-observation.d.ts +80 -0
  83. package/dist/manager/resident/learning-observation.d.ts.map +1 -0
  84. package/dist/manager/resident/learning-observation.js +22 -0
  85. package/dist/manager/resident/learning-observation.js.map +1 -0
  86. package/dist/manager/resident/learning-store.d.ts +106 -0
  87. package/dist/manager/resident/learning-store.d.ts.map +1 -0
  88. package/dist/manager/resident/learning-store.js +598 -0
  89. package/dist/manager/resident/learning-store.js.map +1 -0
  90. package/dist/manager/resident/learning.d.ts +726 -0
  91. package/dist/manager/resident/learning.d.ts.map +1 -0
  92. package/dist/manager/resident/learning.js +353 -0
  93. package/dist/manager/resident/learning.js.map +1 -0
  94. package/dist/manager/resident/loop.d.ts +31 -0
  95. package/dist/manager/resident/loop.d.ts.map +1 -0
  96. package/dist/manager/resident/loop.js +69 -0
  97. package/dist/manager/resident/loop.js.map +1 -0
  98. package/dist/manager/resident/outbox.d.ts +180 -0
  99. package/dist/manager/resident/outbox.d.ts.map +1 -0
  100. package/dist/manager/resident/outbox.js +214 -0
  101. package/dist/manager/resident/outbox.js.map +1 -0
  102. package/dist/manager/resident/proposal.d.ts +91 -0
  103. package/dist/manager/resident/proposal.d.ts.map +1 -0
  104. package/dist/manager/resident/proposal.js +75 -0
  105. package/dist/manager/resident/proposal.js.map +1 -0
  106. package/dist/manager/resident/store.d.ts +182 -0
  107. package/dist/manager/resident/store.d.ts.map +1 -0
  108. package/dist/manager/resident/store.js +199 -0
  109. package/dist/manager/resident/store.js.map +1 -0
  110. package/dist/manager/resident/tool-evidence.d.ts +71 -0
  111. package/dist/manager/resident/tool-evidence.d.ts.map +1 -0
  112. package/dist/manager/resident/tool-evidence.js +285 -0
  113. package/dist/manager/resident/tool-evidence.js.map +1 -0
  114. package/dist/manager/run/persistence.d.ts.map +1 -1
  115. package/dist/manager/run/persistence.js +6 -0
  116. package/dist/manager/run/persistence.js.map +1 -1
  117. package/dist/plugin/loader.d.ts.map +1 -1
  118. package/dist/plugin/loader.js +5 -3
  119. package/dist/plugin/loader.js.map +1 -1
  120. package/dist/prompt/coding-agent-doctrine.d.ts +1 -1
  121. package/dist/prompt/coding-agent-doctrine.d.ts.map +1 -1
  122. package/dist/prompt/coding-agent-doctrine.js +2 -0
  123. package/dist/prompt/coding-agent-doctrine.js.map +1 -1
  124. package/dist/prompt/contributions.d.ts +5 -2
  125. package/dist/prompt/contributions.d.ts.map +1 -1
  126. package/dist/prompt/contributions.js.map +1 -1
  127. package/dist/prompt/index.d.ts +4 -0
  128. package/dist/prompt/index.d.ts.map +1 -1
  129. package/dist/prompt/index.js +2 -0
  130. package/dist/prompt/index.js.map +1 -1
  131. package/dist/prompt/resident-learning.d.ts +19 -0
  132. package/dist/prompt/resident-learning.d.ts.map +1 -0
  133. package/dist/prompt/resident-learning.js +125 -0
  134. package/dist/prompt/resident-learning.js.map +1 -0
  135. package/dist/prompt/resident-step.d.ts +36 -0
  136. package/dist/prompt/resident-step.d.ts.map +1 -0
  137. package/dist/prompt/resident-step.js +135 -0
  138. package/dist/prompt/resident-step.js.map +1 -0
  139. package/dist/provider/collect-chat-completion.d.ts +2 -1
  140. package/dist/provider/collect-chat-completion.d.ts.map +1 -1
  141. package/dist/provider/collect-chat-completion.js +7 -6
  142. package/dist/provider/collect-chat-completion.js.map +1 -1
  143. package/dist/provider/fallback.d.ts.map +1 -1
  144. package/dist/provider/fallback.js +2 -1
  145. package/dist/provider/fallback.js.map +1 -1
  146. package/dist/provider/stream-text.d.ts +16 -0
  147. package/dist/provider/stream-text.d.ts.map +1 -0
  148. package/dist/provider/stream-text.js +51 -0
  149. package/dist/provider/stream-text.js.map +1 -0
  150. package/dist/public-runtime.d.ts +22 -3
  151. package/dist/public-runtime.d.ts.map +1 -1
  152. package/dist/public-runtime.js +21 -3
  153. package/dist/public-runtime.js.map +1 -1
  154. package/dist/public-tools.d.ts +2 -0
  155. package/dist/public-tools.d.ts.map +1 -1
  156. package/dist/public-tools.js +2 -0
  157. package/dist/public-tools.js.map +1 -1
  158. package/dist/public-types.d.ts +29 -3
  159. package/dist/public-types.d.ts.map +1 -1
  160. package/dist/registry/index.d.ts +1 -1
  161. package/dist/registry/index.d.ts.map +1 -1
  162. package/dist/registry/tool/execute.d.ts +18 -0
  163. package/dist/registry/tool/execute.d.ts.map +1 -1
  164. package/dist/registry/tool/execute.js +43 -6
  165. package/dist/registry/tool/execute.js.map +1 -1
  166. package/dist/run/LimitChecker.js +3 -3
  167. package/dist/run/LimitChecker.js.map +1 -1
  168. package/dist/run/evidence-query.d.ts +41 -0
  169. package/dist/run/evidence-query.d.ts.map +1 -0
  170. package/dist/run/evidence-query.js +270 -0
  171. package/dist/run/evidence-query.js.map +1 -0
  172. package/dist/run/evidence-recall.d.ts +99 -0
  173. package/dist/run/evidence-recall.d.ts.map +1 -0
  174. package/dist/run/evidence-recall.js +633 -0
  175. package/dist/run/evidence-recall.js.map +1 -0
  176. package/dist/run/index.d.ts +2 -0
  177. package/dist/run/index.d.ts.map +1 -1
  178. package/dist/run/index.js +1 -0
  179. package/dist/run/index.js.map +1 -1
  180. package/dist/run/json-claim-verifier.d.ts +83 -0
  181. package/dist/run/json-claim-verifier.d.ts.map +1 -0
  182. package/dist/run/json-claim-verifier.js +200 -0
  183. package/dist/run/json-claim-verifier.js.map +1 -0
  184. package/dist/run/preparation-context-error.d.ts +10 -0
  185. package/dist/run/preparation-context-error.d.ts.map +1 -0
  186. package/dist/run/preparation-context-error.js +15 -0
  187. package/dist/run/preparation-context-error.js.map +1 -0
  188. package/dist/run-query/index.d.ts +3 -1
  189. package/dist/run-query/index.d.ts.map +1 -1
  190. package/dist/runtime/query/callback-inference.d.ts +8 -0
  191. package/dist/runtime/query/callback-inference.d.ts.map +1 -0
  192. package/dist/runtime/query/callback-inference.js +89 -0
  193. package/dist/runtime/query/callback-inference.js.map +1 -0
  194. package/dist/runtime/query/checkpoint.d.ts +4 -0
  195. package/dist/runtime/query/checkpoint.d.ts.map +1 -1
  196. package/dist/runtime/query/checkpoint.js +13 -0
  197. package/dist/runtime/query/checkpoint.js.map +1 -1
  198. package/dist/runtime/query/events.d.ts +7 -1
  199. package/dist/runtime/query/events.d.ts.map +1 -1
  200. package/dist/runtime/query/events.js +39 -12
  201. package/dist/runtime/query/events.js.map +1 -1
  202. package/dist/runtime/query/executor.d.ts +7 -1
  203. package/dist/runtime/query/executor.d.ts.map +1 -1
  204. package/dist/runtime/query/executor.js +38 -7
  205. package/dist/runtime/query/executor.js.map +1 -1
  206. package/dist/runtime/query/file-evidence-context.d.ts +5 -0
  207. package/dist/runtime/query/file-evidence-context.d.ts.map +1 -0
  208. package/dist/runtime/query/file-evidence-context.js +64 -0
  209. package/dist/runtime/query/file-evidence-context.js.map +1 -0
  210. package/dist/runtime/query/guard.d.ts.map +1 -1
  211. package/dist/runtime/query/guard.js +4 -0
  212. package/dist/runtime/query/guard.js.map +1 -1
  213. package/dist/runtime/query/index.d.ts +10 -1
  214. package/dist/runtime/query/index.d.ts.map +1 -1
  215. package/dist/runtime/query/index.js +40 -25
  216. package/dist/runtime/query/index.js.map +1 -1
  217. package/dist/runtime/query/iteration/index.d.ts +9 -31
  218. package/dist/runtime/query/iteration/index.d.ts.map +1 -1
  219. package/dist/runtime/query/iteration/index.js +231 -93
  220. package/dist/runtime/query/iteration/index.js.map +1 -1
  221. package/dist/runtime/query/iteration/phases/advisory.d.ts +2 -1
  222. package/dist/runtime/query/iteration/phases/advisory.d.ts.map +1 -1
  223. package/dist/runtime/query/iteration/phases/advisory.js +2 -1
  224. package/dist/runtime/query/iteration/phases/advisory.js.map +1 -1
  225. package/dist/runtime/query/iteration/phases/context.d.ts +2 -1
  226. package/dist/runtime/query/iteration/phases/context.d.ts.map +1 -1
  227. package/dist/runtime/query/iteration/phases/context.js.map +1 -1
  228. package/dist/runtime/query/iteration/phases/tool-review.d.ts.map +1 -1
  229. package/dist/runtime/query/iteration/phases/tool-review.js +3 -0
  230. package/dist/runtime/query/iteration/phases/tool-review.js.map +1 -1
  231. package/dist/runtime/query/iteration/provider-rejected-image.d.ts +2 -1
  232. package/dist/runtime/query/iteration/provider-rejected-image.d.ts.map +1 -1
  233. package/dist/runtime/query/iteration/provider-rejected-image.js +5 -2
  234. package/dist/runtime/query/iteration/provider-rejected-image.js.map +1 -1
  235. package/dist/runtime/query/iteration/stream-turn.d.ts +4 -1
  236. package/dist/runtime/query/iteration/stream-turn.d.ts.map +1 -1
  237. package/dist/runtime/query/iteration/stream-turn.js +22 -8
  238. package/dist/runtime/query/iteration/stream-turn.js.map +1 -1
  239. package/dist/runtime/query/prompt-cache.d.ts.map +1 -1
  240. package/dist/runtime/query/prompt-cache.js +21 -42
  241. package/dist/runtime/query/prompt-cache.js.map +1 -1
  242. package/dist/runtime/query/resume-pending.d.ts +18 -33
  243. package/dist/runtime/query/resume-pending.d.ts.map +1 -1
  244. package/dist/runtime/query/resume-pending.js +59 -42
  245. package/dist/runtime/query/resume-pending.js.map +1 -1
  246. package/dist/runtime/query/review-policy.d.ts +4 -4
  247. package/dist/runtime/query/review-policy.d.ts.map +1 -1
  248. package/dist/runtime/query/review-policy.js +10 -9
  249. package/dist/runtime/query/review-policy.js.map +1 -1
  250. package/dist/runtime/query/sandbox-lifecycle.d.ts.map +1 -1
  251. package/dist/runtime/query/sandbox-lifecycle.js +4 -0
  252. package/dist/runtime/query/sandbox-lifecycle.js.map +1 -1
  253. package/dist/runtime/query/tool-output-budget.d.ts +10 -6
  254. package/dist/runtime/query/tool-output-budget.d.ts.map +1 -1
  255. package/dist/runtime/query/tool-output-budget.js +54 -12
  256. package/dist/runtime/query/tool-output-budget.js.map +1 -1
  257. package/dist/runtime/query/tooling.d.ts +3 -1
  258. package/dist/runtime/query/tooling.d.ts.map +1 -1
  259. package/dist/runtime/query/tooling.js +4 -0
  260. package/dist/runtime/query/tooling.js.map +1 -1
  261. package/dist/scheduler/completion-inbox.d.ts +3 -0
  262. package/dist/scheduler/completion-inbox.d.ts.map +1 -1
  263. package/dist/scheduler/completion-inbox.js +28 -0
  264. package/dist/scheduler/completion-inbox.js.map +1 -1
  265. package/dist/store/evidence/compaction-archive.d.ts +109 -0
  266. package/dist/store/evidence/compaction-archive.d.ts.map +1 -0
  267. package/dist/store/evidence/compaction-archive.js +125 -0
  268. package/dist/store/evidence/compaction-archive.js.map +1 -0
  269. package/dist/store/evidence/compaction-provenance.d.ts +7 -0
  270. package/dist/store/evidence/compaction-provenance.d.ts.map +1 -0
  271. package/dist/store/evidence/compaction-provenance.js +49 -0
  272. package/dist/store/evidence/compaction-provenance.js.map +1 -0
  273. package/dist/store/evidence/compaction-text.d.ts +16 -0
  274. package/dist/store/evidence/compaction-text.d.ts.map +1 -0
  275. package/dist/store/evidence/compaction-text.js +51 -0
  276. package/dist/store/evidence/compaction-text.js.map +1 -0
  277. package/dist/store/evidence/disk.d.ts +11 -0
  278. package/dist/store/evidence/disk.d.ts.map +1 -0
  279. package/dist/store/evidence/disk.js +367 -0
  280. package/dist/store/evidence/disk.js.map +1 -0
  281. package/dist/store/evidence/format.d.ts +25 -0
  282. package/dist/store/evidence/format.d.ts.map +1 -0
  283. package/dist/store/evidence/format.js +115 -0
  284. package/dist/store/evidence/format.js.map +1 -0
  285. package/dist/store/evidence/index-page.d.ts +208 -0
  286. package/dist/store/evidence/index-page.d.ts.map +1 -0
  287. package/dist/store/evidence/index-page.js +262 -0
  288. package/dist/store/evidence/index-page.js.map +1 -0
  289. package/dist/store/evidence/io.d.ts +24 -0
  290. package/dist/store/evidence/io.d.ts.map +1 -0
  291. package/dist/store/evidence/io.js +69 -0
  292. package/dist/store/evidence/io.js.map +1 -0
  293. package/dist/store/evidence/linked.d.ts +9 -0
  294. package/dist/store/evidence/linked.d.ts.map +1 -0
  295. package/dist/store/evidence/linked.js +314 -0
  296. package/dist/store/evidence/linked.js.map +1 -0
  297. package/dist/store/evidence/passages.d.ts +15 -0
  298. package/dist/store/evidence/passages.d.ts.map +1 -0
  299. package/dist/store/evidence/passages.js +72 -0
  300. package/dist/store/evidence/passages.js.map +1 -0
  301. package/dist/store/evidence/record-chain.d.ts +42 -0
  302. package/dist/store/evidence/record-chain.d.ts.map +1 -0
  303. package/dist/store/evidence/record-chain.js +111 -0
  304. package/dist/store/evidence/record-chain.js.map +1 -0
  305. package/dist/store/evidence/search-input.d.ts +21 -0
  306. package/dist/store/evidence/search-input.d.ts.map +1 -0
  307. package/dist/store/evidence/search-input.js +44 -0
  308. package/dist/store/evidence/search-input.js.map +1 -0
  309. package/dist/store/evidence/selection.d.ts +9 -0
  310. package/dist/store/evidence/selection.d.ts.map +1 -0
  311. package/dist/store/evidence/selection.js +17 -0
  312. package/dist/store/evidence/selection.js.map +1 -0
  313. package/dist/store/evidence/source-kind.d.ts +11 -0
  314. package/dist/store/evidence/source-kind.d.ts.map +1 -0
  315. package/dist/store/evidence/source-kind.js +26 -0
  316. package/dist/store/evidence/source-kind.js.map +1 -0
  317. package/dist/store/evidence/source-text.d.ts +51 -0
  318. package/dist/store/evidence/source-text.d.ts.map +1 -0
  319. package/dist/store/evidence/source-text.js +213 -0
  320. package/dist/store/evidence/source-text.js.map +1 -0
  321. package/dist/store/evidence/types.d.ts +162 -0
  322. package/dist/store/evidence/types.d.ts.map +1 -0
  323. package/dist/store/evidence/types.js +2 -0
  324. package/dist/store/evidence/types.js.map +1 -0
  325. package/dist/store/memory/disk.d.ts +2 -0
  326. package/dist/store/memory/disk.d.ts.map +1 -1
  327. package/dist/store/memory/disk.js +2 -1
  328. package/dist/store/memory/disk.js.map +1 -1
  329. package/dist/store/run/disk.d.ts +10 -0
  330. package/dist/store/run/disk.d.ts.map +1 -1
  331. package/dist/store/run/disk.js +87 -7
  332. package/dist/store/run/disk.js.map +1 -1
  333. package/dist/store/run/memory.d.ts +1 -0
  334. package/dist/store/run/memory.d.ts.map +1 -1
  335. package/dist/store/run/memory.js +10 -0
  336. package/dist/store/run/memory.js.map +1 -1
  337. package/dist/store/run/tool-executions.d.ts +13 -0
  338. package/dist/store/run/tool-executions.d.ts.map +1 -0
  339. package/dist/store/run/tool-executions.js +99 -0
  340. package/dist/store/run/tool-executions.js.map +1 -0
  341. package/dist/store/session/index.d.ts +2 -0
  342. package/dist/store/session/index.d.ts.map +1 -1
  343. package/dist/store/session/index.js +1 -0
  344. package/dist/store/session/index.js.map +1 -1
  345. package/dist/store/session/sqlite.d.ts +57 -0
  346. package/dist/store/session/sqlite.d.ts.map +1 -0
  347. package/dist/store/session/sqlite.js +430 -0
  348. package/dist/store/session/sqlite.js.map +1 -0
  349. package/dist/tools/builtins/job.d.ts.map +1 -1
  350. package/dist/tools/builtins/job.js +4 -5
  351. package/dist/tools/builtins/job.js.map +1 -1
  352. package/dist/tools/builtins/write-file.js +2 -2
  353. package/dist/tools/builtins/write-file.js.map +1 -1
  354. package/dist/tools/defineTool.d.ts +2 -1
  355. package/dist/tools/defineTool.d.ts.map +1 -1
  356. package/dist/tools/defineTool.js +1 -1
  357. package/dist/tools/defineTool.js.map +1 -1
  358. package/dist/tools/file-read-tracker.d.ts.map +1 -1
  359. package/dist/tools/file-read-tracker.js +12 -3
  360. package/dist/tools/file-read-tracker.js.map +1 -1
  361. package/dist/tools/resident-history.d.ts +10 -0
  362. package/dist/tools/resident-history.d.ts.map +1 -0
  363. package/dist/tools/resident-history.js +80 -0
  364. package/dist/tools/resident-history.js.map +1 -0
  365. package/dist/tools/resident-tool-evidence.d.ts +5 -0
  366. package/dist/tools/resident-tool-evidence.d.ts.map +1 -0
  367. package/dist/tools/resident-tool-evidence.js +57 -0
  368. package/dist/tools/resident-tool-evidence.js.map +1 -0
  369. package/dist/types/advisory/config.d.ts +7 -0
  370. package/dist/types/advisory/config.d.ts.map +1 -1
  371. package/dist/types/agent/reactive.d.ts +1 -0
  372. package/dist/types/agent/reactive.d.ts.map +1 -1
  373. package/dist/types/authorization/index.d.ts +9 -9
  374. package/dist/types/authorization/index.d.ts.map +1 -1
  375. package/dist/types/authorization/index.js +1 -1
  376. package/dist/types/authorization/index.js.map +1 -1
  377. package/dist/types/hitl/index.d.ts +4 -0
  378. package/dist/types/hitl/index.d.ts.map +1 -1
  379. package/dist/types/hitl/index.js.map +1 -1
  380. package/dist/types/message/index.d.ts +16 -2
  381. package/dist/types/message/index.d.ts.map +1 -1
  382. package/dist/types/message/index.js +8 -1
  383. package/dist/types/message/index.js.map +1 -1
  384. package/dist/types/provider/chat.d.ts +2 -0
  385. package/dist/types/provider/chat.d.ts.map +1 -1
  386. package/dist/types/provider/stream.d.ts +4 -0
  387. package/dist/types/provider/stream.d.ts.map +1 -1
  388. package/dist/types/run/answer-review.d.ts +34 -3
  389. package/dist/types/run/answer-review.d.ts.map +1 -1
  390. package/dist/types/run/config.d.ts +3 -0
  391. package/dist/types/run/config.d.ts.map +1 -1
  392. package/dist/types/run/entity.d.ts +7 -0
  393. package/dist/types/run/entity.d.ts.map +1 -1
  394. package/dist/types/run/events.d.ts +31 -8
  395. package/dist/types/run/events.d.ts.map +1 -1
  396. package/dist/types/run/events.js.map +1 -1
  397. package/dist/types/run/prepare-step.d.ts +53 -8
  398. package/dist/types/run/prepare-step.d.ts.map +1 -1
  399. package/dist/types/run/store.d.ts +29 -4
  400. package/dist/types/run/store.d.ts.map +1 -1
  401. package/dist/types/run/store.js +0 -28
  402. package/dist/types/run/store.js.map +1 -1
  403. package/dist/types/tool/index.d.ts +15 -1
  404. package/dist/types/tool/index.d.ts.map +1 -1
  405. package/dist/types/tool/index.js.map +1 -1
  406. package/dist/utils/await-with-abort.d.ts +8 -0
  407. package/dist/utils/await-with-abort.d.ts.map +1 -0
  408. package/dist/utils/await-with-abort.js +28 -0
  409. package/dist/utils/await-with-abort.js.map +1 -0
  410. package/dist/utils/evidence-time.d.ts +3 -0
  411. package/dist/utils/evidence-time.d.ts.map +1 -0
  412. package/dist/utils/evidence-time.js +10 -0
  413. package/dist/utils/evidence-time.js.map +1 -0
  414. package/dist/utils/evidence-tokens.d.ts +13 -0
  415. package/dist/utils/evidence-tokens.d.ts.map +1 -0
  416. package/dist/utils/evidence-tokens.js +29 -0
  417. package/dist/utils/evidence-tokens.js.map +1 -0
  418. package/package.json +1 -1
  419. package/src/advisory/executor.ts +15 -30
  420. package/src/advisory/history.ts +126 -0
  421. package/src/advisory/index.ts +5 -1
  422. package/src/agents/ReactiveAgent.ts +3 -0
  423. package/src/agents/runAgent.ts +14 -1
  424. package/src/compaction/manual.ts +30 -2
  425. package/src/compaction/summary.ts +4 -1
  426. package/src/config/runtime.ts +2 -2
  427. package/src/contracts/schemas.ts +1 -1
  428. package/src/eval/harness-protection.ts +79 -0
  429. package/src/eval/harness-verification.ts +31 -1
  430. package/src/eval/index.ts +1 -0
  431. package/src/manager/resident/activity.ts +187 -0
  432. package/src/manager/resident/agenda.ts +907 -0
  433. package/src/manager/resident/consumption.ts +311 -0
  434. package/src/manager/resident/delivery-window.ts +93 -0
  435. package/src/manager/resident/evidence-recall.ts +363 -0
  436. package/src/manager/resident/history-disk.ts +63 -0
  437. package/src/manager/resident/history.ts +312 -0
  438. package/src/manager/resident/host.ts +356 -0
  439. package/src/manager/resident/initiative.ts +205 -0
  440. package/src/manager/resident/learning-cycle.ts +499 -0
  441. package/src/manager/resident/learning-observation.ts +39 -0
  442. package/src/manager/resident/learning-store.ts +813 -0
  443. package/src/manager/resident/learning.ts +493 -0
  444. package/src/manager/resident/loop.ts +101 -0
  445. package/src/manager/resident/outbox.ts +307 -0
  446. package/src/manager/resident/proposal.ts +105 -0
  447. package/src/manager/resident/store.ts +257 -0
  448. package/src/manager/resident/tool-evidence.ts +412 -0
  449. package/src/manager/run/persistence.ts +6 -0
  450. package/src/plugin/loader.ts +8 -3
  451. package/src/prompt/coding-agent-doctrine.ts +2 -0
  452. package/src/prompt/contributions.ts +5 -2
  453. package/src/prompt/index.ts +4 -0
  454. package/src/prompt/resident-learning.ts +143 -0
  455. package/src/prompt/resident-step.ts +176 -0
  456. package/src/provider/collect-chat-completion.ts +7 -6
  457. package/src/provider/fallback.ts +2 -1
  458. package/src/provider/stream-text.ts +56 -0
  459. package/src/public-runtime.ts +44 -0
  460. package/src/public-tools.ts +3 -0
  461. package/src/public-types.ts +165 -0
  462. package/src/registry/index.ts +1 -1
  463. package/src/registry/tool/execute.ts +56 -9
  464. package/src/run/LimitChecker.ts +3 -3
  465. package/src/run/evidence-query.ts +333 -0
  466. package/src/run/evidence-recall.ts +854 -0
  467. package/src/run/index.ts +11 -0
  468. package/src/run/json-claim-verifier.ts +298 -0
  469. package/src/run/preparation-context-error.ts +16 -0
  470. package/src/run-query/index.ts +1 -1
  471. package/src/runtime/query/callback-inference.ts +94 -0
  472. package/src/runtime/query/checkpoint.ts +14 -0
  473. package/src/runtime/query/events.ts +46 -14
  474. package/src/runtime/query/executor.ts +51 -9
  475. package/src/runtime/query/file-evidence-context.ts +65 -0
  476. package/src/runtime/query/guard.ts +2 -0
  477. package/src/runtime/query/index.ts +50 -27
  478. package/src/runtime/query/iteration/index.ts +269 -86
  479. package/src/runtime/query/iteration/phases/advisory.ts +3 -0
  480. package/src/runtime/query/iteration/phases/context.ts +2 -0
  481. package/src/runtime/query/iteration/phases/tool-review.ts +3 -0
  482. package/src/runtime/query/iteration/provider-rejected-image.ts +6 -1
  483. package/src/runtime/query/iteration/stream-turn.ts +35 -8
  484. package/src/runtime/query/prompt-cache.ts +24 -47
  485. package/src/runtime/query/resume-pending.ts +65 -40
  486. package/src/runtime/query/review-policy.ts +13 -9
  487. package/src/runtime/query/sandbox-lifecycle.ts +3 -0
  488. package/src/runtime/query/tool-output-budget.ts +65 -13
  489. package/src/runtime/query/tooling.ts +7 -1
  490. package/src/scheduler/completion-inbox.ts +26 -0
  491. package/src/store/evidence/compaction-archive.ts +139 -0
  492. package/src/store/evidence/compaction-provenance.ts +52 -0
  493. package/src/store/evidence/compaction-text.ts +61 -0
  494. package/src/store/evidence/disk.ts +461 -0
  495. package/src/store/evidence/format.ts +126 -0
  496. package/src/store/evidence/index-page.ts +292 -0
  497. package/src/store/evidence/io.ts +95 -0
  498. package/src/store/evidence/linked.ts +365 -0
  499. package/src/store/evidence/passages.ts +88 -0
  500. package/src/store/evidence/record-chain.ts +108 -0
  501. package/src/store/evidence/search-input.ts +62 -0
  502. package/src/store/evidence/selection.ts +25 -0
  503. package/src/store/evidence/source-kind.ts +36 -0
  504. package/src/store/evidence/source-text.ts +285 -0
  505. package/src/store/evidence/types.ts +177 -0
  506. package/src/store/memory/disk.ts +4 -1
  507. package/src/store/run/disk.ts +110 -8
  508. package/src/store/run/memory.ts +10 -0
  509. package/src/store/run/tool-executions.ts +112 -0
  510. package/src/store/session/index.ts +2 -0
  511. package/src/store/session/sqlite.ts +584 -0
  512. package/src/tools/builtins/job.ts +4 -5
  513. package/src/tools/builtins/write-file.ts +2 -2
  514. package/src/tools/defineTool.ts +4 -2
  515. package/src/tools/file-read-tracker.ts +8 -2
  516. package/src/tools/resident-history.ts +86 -0
  517. package/src/tools/resident-tool-evidence.ts +68 -0
  518. package/src/types/advisory/config.ts +7 -0
  519. package/src/types/agent/reactive.ts +1 -0
  520. package/src/types/authorization/index.ts +2 -2
  521. package/src/types/hitl/index.ts +4 -0
  522. package/src/types/message/index.ts +20 -0
  523. package/src/types/provider/chat.ts +2 -0
  524. package/src/types/provider/stream.ts +4 -0
  525. package/src/types/run/answer-review.ts +34 -3
  526. package/src/types/run/config.ts +3 -0
  527. package/src/types/run/entity.ts +7 -0
  528. package/src/types/run/events.ts +31 -8
  529. package/src/types/run/prepare-step.ts +59 -8
  530. package/src/types/run/store.ts +35 -4
  531. package/src/types/tool/index.ts +19 -1
  532. package/src/utils/await-with-abort.ts +26 -0
  533. package/src/utils/evidence-time.ts +9 -0
  534. package/src/utils/evidence-tokens.ts +32 -0
@@ -0,0 +1,907 @@
1
+ import { randomUUID } from 'node:crypto'
2
+ import { join, resolve } from 'node:path'
3
+ import { isDeepStrictEqual } from 'node:util'
4
+ import { z } from 'zod'
5
+ import { DiskRecordStore } from '../../store/kv/record-store.js'
6
+ import { DiskRevisionRecordStore } from '../../store/kv/revision-record-store.js'
7
+ import { defineSchema, migrate } from '../../store/schema.js'
8
+ import type { TenantId } from '../../types/ids/index.js'
9
+ import { asTenantId } from '../../utils/id.js'
10
+ import {
11
+ ResidentConflictError,
12
+ type ResidentDecision,
13
+ type ResidentExecutionStore,
14
+ type ResidentState,
15
+ claimResidentState,
16
+ residentDecisionSchema,
17
+ residentKeySegment,
18
+ residentStateSchema,
19
+ settleResidentState,
20
+ wakeResidentState,
21
+ } from './store.js'
22
+
23
+ import { type ResidentActivitySource, createResidentActivitySource } from './activity.js'
24
+ import { readResidentHistoryRecord } from './history-disk.js'
25
+ import { type ResidentHistorySource, createResidentHistorySource } from './history.js'
26
+ import {
27
+ type ResidentFeedback,
28
+ type ResidentObservation,
29
+ freezeResidentFeedback,
30
+ observeResidentStep,
31
+ residentFeedbackSchema,
32
+ residentObservationSchema,
33
+ } from './initiative.js'
34
+ import {
35
+ type ResidentLearningEvidence,
36
+ type ResidentLearningState,
37
+ type ResidentProfileUpdate,
38
+ type ResidentSkillCandidate,
39
+ type ResidentSkillEvaluation,
40
+ freezeResidentLearning,
41
+ promoteResidentSkill,
42
+ residentLearningEvidenceSchema,
43
+ residentLearningSchema,
44
+ restoreResidentSkill,
45
+ reviseResidentProfile,
46
+ } from './learning.js'
47
+ import {
48
+ type ResidentDeliveryOutcome,
49
+ type ResidentMessageInput,
50
+ type ResidentOutboxMessage,
51
+ appendResidentMessage,
52
+ claimResidentOutboxMessage,
53
+ residentDeliveryOutcomeSchema,
54
+ residentMessageInputSchema,
55
+ residentOutboxMessageSchema,
56
+ settleResidentOutboxMessage,
57
+ } from './outbox.js'
58
+ import {
59
+ type ResidentProposal,
60
+ type ResidentProposalLimits,
61
+ type ResidentProposalOrigin,
62
+ residentProposalLimitsSchema,
63
+ residentProposalOriginSchema,
64
+ residentProposalSchema,
65
+ validateResidentProposal,
66
+ } from './proposal.js'
67
+
68
+ const agendaSchema = z
69
+ .object({
70
+ tenantId: z.string().uuid(),
71
+ agentKey: z.string().min(1).max(200),
72
+ identity: z.string().trim().min(1).max(8_000),
73
+ revision: z.number().int().positive().safe(),
74
+ paused: z.boolean(),
75
+ pauseGeneration: z.number().int().nonnegative().safe().optional(),
76
+ archiveHead: z.number().int().min(2).safe().optional(),
77
+ learning: residentLearningSchema.optional(),
78
+ outbox: z.array(residentOutboxMessageSchema).max(128).optional(),
79
+ pursuits: z
80
+ .array(
81
+ z.object({
82
+ id: z.string().uuid(),
83
+ state: residentStateSchema,
84
+ feedback: residentFeedbackSchema.optional(),
85
+ origin: residentProposalOriginSchema.optional(),
86
+ retiredChildren: z.number().int().min(0).max(8).optional(),
87
+ }),
88
+ )
89
+ .max(32),
90
+ })
91
+ .superRefine((agenda, context) => {
92
+ const origins = agenda.pursuits.flatMap((p) => (p.origin ? [p.origin] : []))
93
+ const outbox = agenda.outbox ?? []
94
+ const invalid =
95
+ (agenda.archiveHead !== undefined && agenda.archiveHead > agenda.revision) ||
96
+ new Set(outbox.map((message) => message.id)).size !== outbox.length ||
97
+ outbox.filter((message) => message.phase === 'sending').length > 1 ||
98
+ outbox.some(
99
+ (message) =>
100
+ message.tenantId !== agenda.tenantId ||
101
+ message.agentKey !== agenda.agentKey ||
102
+ !agenda.pursuits.some((pursuit) => pursuit.id === message.pursuitId),
103
+ ) ||
104
+ new Set(agenda.pursuits.map((p) => p.id)).size !== agenda.pursuits.length ||
105
+ new Set(origins.map((origin) => origin.proposalId)).size !== origins.length ||
106
+ agenda.pursuits.filter((p) => p.state.phase === 'running').length > 1 ||
107
+ agenda.pursuits.some((p) => {
108
+ if (!p.origin) return false
109
+ const parent = agenda.pursuits.find((candidate) => candidate.id === p.origin?.parentId)
110
+ return (
111
+ !parent ||
112
+ parent.id === p.id ||
113
+ p.origin.parentRevision > parent.state.revision ||
114
+ p.origin.depth !== (parent.origin?.depth ?? 0) + 1
115
+ )
116
+ }) ||
117
+ agenda.pursuits.some((p) =>
118
+ p.feedback?.observations.some(
119
+ (item, index, all) =>
120
+ item.step > p.state.stepsAdmitted ||
121
+ (index > 0 && item.step <= (all[index - 1]?.step ?? 0)),
122
+ ),
123
+ ) ||
124
+ agenda.pursuits.some(
125
+ ({ id, state }) =>
126
+ state.pursuitId !== id ||
127
+ state.tenantId !== agenda.tenantId ||
128
+ state.agentKey !== agenda.agentKey ||
129
+ state.identity !== agenda.identity,
130
+ )
131
+ if (invalid)
132
+ context.addIssue({
133
+ code: z.ZodIssueCode.custom,
134
+ message:
135
+ 'Invalid agenda identity, pursuit ancestry, observation order, outbox or overlapping claims.',
136
+ })
137
+ })
138
+
139
+ /** @experimental One pursuit shares its agent's identity, but has its own lifecycle. */
140
+ export interface ResidentPursuit {
141
+ readonly id: string
142
+ readonly state: ResidentState
143
+ readonly feedback?: ResidentFeedback
144
+ readonly origin?: ResidentProposalOrigin
145
+ /** Archived direct children still consume the parent's lifetime admission bound. */
146
+ readonly retiredChildren?: number
147
+ }
148
+
149
+ /** @experimental Bounded shared admission record; at most one pursuit may be running. */
150
+ export interface ResidentAgendaState {
151
+ readonly tenantId: string
152
+ readonly agentKey: string
153
+ readonly identity: string
154
+ readonly revision: number
155
+ readonly paused: boolean
156
+ /** Durable pause requests; absent means zero. Resuming never resets this generation. */
157
+ readonly pauseGeneration?: number
158
+ readonly pursuits: readonly ResidentPursuit[]
159
+ readonly outbox?: readonly ResidentOutboxMessage[]
160
+ readonly archiveHead?: number
161
+ readonly learning?: ResidentLearningState
162
+ }
163
+
164
+ /** @experimental Explicit terminal entries to retire from active capacity together. */
165
+ export interface ResidentArchiveRequest {
166
+ readonly pursuitIds?: readonly string[]
167
+ readonly messageIds?: readonly string[]
168
+ }
169
+
170
+ /** @experimental A committed removal, whose immutable predecessor preserves the full records. */
171
+ export interface ResidentArchiveEntry {
172
+ readonly revision: number
173
+ readonly pursuits: readonly ResidentPursuit[]
174
+ readonly messages: readonly ResidentOutboxMessage[]
175
+ }
176
+
177
+ /** @experimental Pages count archive events; each event contains at most 32 pursuits and 128 messages. */
178
+ export interface ResidentArchivePage {
179
+ readonly entries: readonly ResidentArchiveEntry[]
180
+ readonly nextBeforeRevision: number | null
181
+ }
182
+
183
+ /** @experimental The cursor is the next archive-event revision returned by a previous page. */
184
+ export interface ResidentArchiveListOptions {
185
+ readonly beforeRevision?: number
186
+ /** Number of archive events to inspect; defaults to 8 and cannot exceed 32. */
187
+ readonly limit?: number
188
+ }
189
+
190
+ const agendaRecordSchema = defineSchema({
191
+ kind: 'resident-agenda',
192
+ current: 6,
193
+ migrations: {
194
+ 1: (record) => record,
195
+ 2: (record) => record,
196
+ 3: (record) => record,
197
+ 4: (record) => record,
198
+ 5: (record) => record,
199
+ },
200
+ })
201
+
202
+ const archiveRequestSchema = z.object({
203
+ pursuitIds: z.array(z.string().uuid()).max(32).default([]),
204
+ messageIds: z.array(z.string().uuid()).max(128).default([]),
205
+ })
206
+
207
+ /** @experimental Atomic whole-agent admission plus independently addressable pursuits. */
208
+ export interface ResidentAgendaStore {
209
+ read(): Promise<ResidentAgendaState | null>
210
+ create(identity: string): Promise<ResidentAgendaState>
211
+ add(expected: ResidentAgendaState, objective: string): Promise<ResidentPursuit>
212
+ /** Each committed true request advances pauseGeneration, even when already paused. */
213
+ setPaused(expected: ResidentAgendaState, paused: boolean): Promise<ResidentAgendaState>
214
+ wake(id: string, expected: ResidentState, reason: string, now: number): Promise<ResidentState>
215
+ execution(id: string): ResidentExecutionStore
216
+ /** Optional atomic extensions required by a configured resident initiative host. */
217
+ executionAt?(id: string, expected: ResidentAgendaState): ResidentExecutionStore
218
+ settleObserved?(
219
+ id: string,
220
+ expected: ResidentState,
221
+ decision: ResidentDecision,
222
+ observation: ResidentObservation,
223
+ now: number,
224
+ ): Promise<ResidentState>
225
+ /** Optional atomic settlement and outbound intent; no transport runs during persistence. */
226
+ settleWithMessage?(
227
+ id: string,
228
+ expected: ResidentState,
229
+ decision: ResidentDecision,
230
+ message: ResidentMessageInput,
231
+ now: number,
232
+ observation?: ResidentObservation,
233
+ ): Promise<ResidentState>
234
+ enqueueMessage?(
235
+ expected: ResidentAgendaState,
236
+ input: ResidentMessageInput,
237
+ ): Promise<ResidentOutboxMessage>
238
+ claimMessage?(
239
+ expected: ResidentAgendaState,
240
+ id: string,
241
+ now: number,
242
+ ): Promise<ResidentOutboxMessage>
243
+ settleMessage?(
244
+ expected: ResidentOutboxMessage,
245
+ outcome: ResidentDeliveryOutcome,
246
+ now: number,
247
+ ): Promise<ResidentOutboxMessage>
248
+ }
249
+
250
+ /**
251
+ * @experimental One immutable revision contains identity, pause state and all
252
+ * pursuits. Admission therefore serializes this agent even across processes
253
+ * choosing different pursuits. Trusted local filesystems only; no lease expiry.
254
+ */
255
+ export class DiskResidentAgenda implements ResidentAgendaStore {
256
+ private readonly records = new DiskRevisionRecordStore<ResidentAgendaState>(
257
+ agendaRecordSchema,
258
+ 'resident agenda',
259
+ (record) => record.revision,
260
+ )
261
+ private readonly historyRecords = new DiskRecordStore<ResidentAgendaState>(agendaRecordSchema)
262
+ private readonly location
263
+ private readonly tenantId: TenantId
264
+ private readonly agentKey: string
265
+ private readonly historyRoot: string
266
+ private readonly historyRevisions: string
267
+
268
+ constructor(root: string, scope: { tenantId: TenantId; agentKey: string }) {
269
+ this.tenantId = asTenantId(scope.tenantId)
270
+ this.agentKey = z.string().min(1).max(200).parse(scope.agentKey)
271
+ const directory = join(root, this.tenantId, residentKeySegment(this.agentKey), 'agenda')
272
+ this.location = {
273
+ legacyPath: join(directory, 'state.json'),
274
+ revisionsDir: join(directory, 'revisions'),
275
+ publishLegacyProjection: false,
276
+ }
277
+ this.historyRoot = resolve(root)
278
+ this.historyRevisions = resolve(this.location.revisionsDir)
279
+ }
280
+
281
+ private checked(record: ResidentAgendaState): ResidentAgendaState {
282
+ const agenda = agendaSchema.parse(record)
283
+ if (agenda.tenantId !== this.tenantId || agenda.agentKey !== this.agentKey)
284
+ throw new Error('Agenda does not match the bound tenant and agent.')
285
+ return Object.freeze({
286
+ ...agenda,
287
+ ...(agenda.learning ? { learning: freezeResidentLearning(agenda.learning) } : {}),
288
+ ...(agenda.outbox
289
+ ? { outbox: Object.freeze(agenda.outbox.map((message) => Object.freeze(message))) }
290
+ : {}),
291
+ pursuits: Object.freeze(
292
+ agenda.pursuits.map((p) =>
293
+ Object.freeze({
294
+ ...p,
295
+ state: Object.freeze(p.state),
296
+ ...(p.feedback ? { feedback: freezeResidentFeedback(p.feedback) } : {}),
297
+ ...(p.origin ? { origin: Object.freeze(p.origin) } : {}),
298
+ }),
299
+ ),
300
+ ),
301
+ })
302
+ }
303
+
304
+ async read(): Promise<ResidentAgendaState | null> {
305
+ const record = await this.records.read(this.location)
306
+ return record === null ? null : this.checked(record)
307
+ }
308
+
309
+ /** Read one authoritative immutable commit, never the compatibility projection. */
310
+ async readRevision(revision: number): Promise<ResidentAgendaState | null> {
311
+ z.number().int().positive().safe().parse(revision)
312
+ const record = await this.historyRecords.read(
313
+ join(this.location.revisionsDir, `${revision}.json`),
314
+ )
315
+ if (record === null) return null
316
+ const state = this.checked(record)
317
+ if (state.revision !== revision) throw new Error('Agenda revision filename and body disagree.')
318
+ return state
319
+ }
320
+
321
+ /**
322
+ * Bind bounded historical reads to this pursuit and a host-selected upper
323
+ * agenda revision (normally ResidentStepContext.agendaRevision). No I/O or
324
+ * inference occurs until search/read; the boundary never advances itself.
325
+ */
326
+ history(pursuit: ResidentState, throughRevision: number): ResidentHistorySource {
327
+ const state = residentStateSchema.parse(pursuit)
328
+ if (state.tenantId !== this.tenantId || state.agentKey !== this.agentKey || !state.pursuitId)
329
+ throw new Error('History requires a pursuit belonging to this resident agenda.')
330
+ z.number().int().positive().safe().parse(throughRevision)
331
+ return createResidentHistorySource(
332
+ {
333
+ tenantId: this.tenantId,
334
+ agentKey: this.agentKey,
335
+ pursuitId: state.pursuitId,
336
+ throughRevision,
337
+ },
338
+ state,
339
+ async (revision, budget) => {
340
+ const raw = await readResidentHistoryRecord(
341
+ this.historyRoot,
342
+ join(this.historyRevisions, `${revision}.json`),
343
+ budget,
344
+ )
345
+ return this.checked(migrate<ResidentAgendaState>(agendaRecordSchema, raw))
346
+ },
347
+ )
348
+ }
349
+
350
+ /** @experimental Bounded admission/settlement history, including archived pursuits. */
351
+ activity(throughRevision: number): ResidentActivitySource {
352
+ return createResidentActivitySource(
353
+ { tenantId: this.tenantId, agentKey: this.agentKey, throughRevision },
354
+ async (revision, budget) => {
355
+ const raw = await readResidentHistoryRecord(
356
+ this.historyRoot,
357
+ join(this.historyRevisions, `${revision}.json`),
358
+ budget,
359
+ )
360
+ return this.checked(migrate<ResidentAgendaState>(agendaRecordSchema, raw))
361
+ },
362
+ )
363
+ }
364
+
365
+ private retire(state: ResidentAgendaState, input: ResidentArchiveRequest): ResidentAgendaState {
366
+ const request = archiveRequestSchema.parse(input)
367
+ const pursuits = new Set(request.pursuitIds)
368
+ const messages = new Set(request.messageIds)
369
+ if (
370
+ pursuits.size + messages.size === 0 ||
371
+ pursuits.size !== request.pursuitIds.length ||
372
+ messages.size !== request.messageIds.length
373
+ )
374
+ throw new Error('Archive requires a nonempty set of unique entry IDs.')
375
+ const removed = state.pursuits.filter((pursuit) => pursuits.has(pursuit.id))
376
+ const removedMessages = (state.outbox ?? []).filter((message) => messages.has(message.id))
377
+ if (removed.length !== pursuits.size || removedMessages.length !== messages.size)
378
+ throw new Error('Unknown active entry in resident archive request.')
379
+ if (removed.some((p) => p.state.phase !== 'complete' && p.state.phase !== 'blocked'))
380
+ throw new Error('Only terminal pursuits can be archived.')
381
+ if (removedMessages.some((m) => m.phase !== 'acknowledged' && m.phase !== 'cancelled'))
382
+ throw new Error('Only terminal messages can be archived.')
383
+ const remaining = state.pursuits.filter((pursuit) => !pursuits.has(pursuit.id))
384
+ const remainingMessages = state.outbox?.filter((message) => !messages.has(message.id))
385
+ if (remaining.some((p) => p.origin && pursuits.has(p.origin.parentId)))
386
+ throw new Error('Archive must retain the parents of remaining pursuits.')
387
+ if (remainingMessages?.some((message) => pursuits.has(message.pursuitId)))
388
+ throw new Error('Archive must retain pursuits referenced by remaining messages.')
389
+ return {
390
+ ...state,
391
+ archiveHead: state.revision + 1,
392
+ pursuits: remaining.map((pursuit) => {
393
+ const retired = removed.filter((child) => child.origin?.parentId === pursuit.id).length
394
+ return retired
395
+ ? { ...pursuit, retiredChildren: (pursuit.retiredChildren ?? 0) + retired }
396
+ : pursuit
397
+ }),
398
+ ...(remainingMessages ? { outbox: remainingMessages } : {}),
399
+ }
400
+ }
401
+
402
+ /** Free active slots while preserving full records in the immutable predecessor commit. */
403
+ async archive(
404
+ expected: ResidentAgendaState,
405
+ input: ResidentArchiveRequest,
406
+ ): Promise<ResidentAgendaState> {
407
+ const request = archiveRequestSchema.parse(input)
408
+ return this.change(expected, (state) => this.retire(state, request))
409
+ }
410
+
411
+ private async archiveEntry(revision: number): Promise<{
412
+ entry: ResidentArchiveEntry
413
+ previous: number | null
414
+ }> {
415
+ const after = await this.readRevision(revision)
416
+ const before = await this.readRevision(revision - 1)
417
+ if (
418
+ !before ||
419
+ !after ||
420
+ after.archiveHead !== revision ||
421
+ (before.archiveHead !== undefined && before.archiveHead >= revision)
422
+ )
423
+ throw new Error('Resident archive history is missing or its chain is invalid.')
424
+ const activePursuits = new Set(after.pursuits.map((p) => p.id))
425
+ const activeMessages = new Set((after.outbox ?? []).map((m) => m.id))
426
+ const pursuits = before.pursuits.filter((p) => !activePursuits.has(p.id))
427
+ const messages = (before.outbox ?? []).filter((m) => !activeMessages.has(m.id))
428
+ const derived = this.checked({
429
+ ...this.retire(before, {
430
+ pursuitIds: pursuits.map((p) => p.id),
431
+ messageIds: messages.map((m) => m.id),
432
+ }),
433
+ revision,
434
+ })
435
+ if (!isDeepStrictEqual(derived, after))
436
+ throw new Error('Resident archive commit does not match its immutable predecessor.')
437
+ return {
438
+ entry: Object.freeze({
439
+ revision,
440
+ pursuits: Object.freeze(pursuits),
441
+ messages: Object.freeze(messages),
442
+ }),
443
+ previous: before.archiveHead ?? null,
444
+ }
445
+ }
446
+
447
+ /** Bounded archive-event pages; exact-ID deduplication may inspect the complete chain. */
448
+ async listArchived(options: ResidentArchiveListOptions = {}): Promise<ResidentArchivePage> {
449
+ const request = z
450
+ .object({
451
+ beforeRevision: z.number().int().min(2).safe().optional(),
452
+ limit: z.number().int().min(1).max(32).default(8),
453
+ })
454
+ .parse(options)
455
+ const state = await this.read()
456
+ if (!state) throw new Error('Create the resident agenda first.')
457
+ let revision = request.beforeRevision ?? state.archiveHead ?? null
458
+ if (revision !== null && (state.archiveHead === undefined || revision > state.archiveHead))
459
+ throw new Error('Archive cursor is ahead of committed archive history.')
460
+ const entries: ResidentArchiveEntry[] = []
461
+ while (revision !== null && entries.length < request.limit) {
462
+ const archived = await this.archiveEntry(revision)
463
+ entries.push(archived.entry)
464
+ revision = archived.previous
465
+ }
466
+ return Object.freeze({ entries: Object.freeze(entries), nextBeforeRevision: revision })
467
+ }
468
+
469
+ private async archivedMatch<T>(
470
+ state: ResidentAgendaState,
471
+ match: (entry: ResidentArchiveEntry) => T | undefined,
472
+ ): Promise<T | undefined> {
473
+ let revision = state.archiveHead ?? null
474
+ while (revision !== null) {
475
+ const archived = await this.archiveEntry(revision)
476
+ const found = match(archived.entry)
477
+ if (found !== undefined) return found
478
+ revision = archived.previous
479
+ }
480
+ return undefined
481
+ }
482
+
483
+ private assertArchivedIntent(
484
+ message: ResidentOutboxMessage,
485
+ input: ResidentMessageInput,
486
+ sourceClaimId: string | null,
487
+ ): void {
488
+ if (
489
+ message.pursuitId !== input.pursuitId ||
490
+ message.destination !== input.destination ||
491
+ message.body !== input.body ||
492
+ message.notBefore !== input.notBefore ||
493
+ message.sourceClaimId !== sourceClaimId
494
+ )
495
+ throw new Error('Outbox message ID already names a different immutable archived intent.')
496
+ }
497
+
498
+ async create(identity: string): Promise<ResidentAgendaState> {
499
+ const record = this.checked({
500
+ tenantId: this.tenantId,
501
+ agentKey: this.agentKey,
502
+ identity,
503
+ revision: 1,
504
+ paused: false,
505
+ pursuits: [],
506
+ })
507
+ return this.records.transact(this.location, (current) => {
508
+ if (current !== null) throw new ResidentConflictError()
509
+ return { record, result: record }
510
+ })
511
+ }
512
+
513
+ private async change(
514
+ expected: ResidentAgendaState,
515
+ update: (state: ResidentAgendaState) => ResidentAgendaState,
516
+ ): Promise<ResidentAgendaState> {
517
+ const snapshot = this.checked(expected)
518
+ return this.records.transact(this.location, (record) => {
519
+ if (record === null) throw new ResidentConflictError()
520
+ const current = this.checked(record)
521
+ if (current.revision !== snapshot.revision) throw new ResidentConflictError()
522
+ const next = this.checked({ ...update(current), revision: current.revision + 1 })
523
+ return { record: next, result: next }
524
+ })
525
+ }
526
+
527
+ private pursuit(identity: string, objective: string): ResidentPursuit {
528
+ const id = randomUUID()
529
+ const pursuit = Object.freeze({
530
+ id,
531
+ state: Object.freeze(
532
+ residentStateSchema.parse({
533
+ tenantId: this.tenantId,
534
+ agentKey: this.agentKey,
535
+ pursuitId: id,
536
+ identity,
537
+ objective,
538
+ revision: 1,
539
+ stepsAdmitted: 0,
540
+ phase: 'waiting',
541
+ wakeAt: 0,
542
+ reason: 'Initial pursuit',
543
+ summary: null,
544
+ claimId: null,
545
+ }),
546
+ ),
547
+ })
548
+ return pursuit
549
+ }
550
+
551
+ async add(expected: ResidentAgendaState, objective: string): Promise<ResidentPursuit> {
552
+ const pursuit = this.pursuit(expected.identity, objective)
553
+ await this.change(expected, (state) => ({ ...state, pursuits: [...state.pursuits, pursuit] }))
554
+ return pursuit
555
+ }
556
+
557
+ /** Host-approved proposal admission is atomic and inert until a future invocation. */
558
+ async admitProposal(
559
+ expected: ResidentAgendaState,
560
+ input: ResidentProposal,
561
+ limits: ResidentProposalLimits,
562
+ ): Promise<ResidentPursuit> {
563
+ const snapshot = this.checked(expected)
564
+ const proposal = residentProposalSchema.parse(input)
565
+ const policy = residentProposalLimitsSchema.parse(limits)
566
+ const current = await this.read()
567
+ if (!current || current.revision !== snapshot.revision) throw new ResidentConflictError()
568
+ validateResidentProposal(current, proposal, policy)
569
+ if (
570
+ await this.archivedMatch(current, (entry) =>
571
+ entry.pursuits.find((p) => p.origin?.proposalId === proposal.id),
572
+ )
573
+ )
574
+ throw new Error('Resident proposal has already been admitted and archived.')
575
+ let admitted: ResidentPursuit | undefined
576
+ await this.change(snapshot, (state) => {
577
+ const origin = validateResidentProposal(state, proposal, policy)
578
+ admitted = Object.freeze({
579
+ ...this.pursuit(state.identity, proposal.objective),
580
+ origin: Object.freeze(origin),
581
+ })
582
+ return { ...state, pursuits: [...state.pursuits, admitted] }
583
+ })
584
+ if (!admitted) throw new Error('Resident proposal was not admitted.')
585
+ return admitted
586
+ }
587
+
588
+ async setPaused(expected: ResidentAgendaState, paused: boolean): Promise<ResidentAgendaState> {
589
+ z.boolean().parse(paused)
590
+ return this.change(expected, (state) => ({
591
+ ...state,
592
+ paused,
593
+ ...(paused ? { pauseGeneration: (state.pauseGeneration ?? 0) + 1 } : {}),
594
+ }))
595
+ }
596
+
597
+ private async learn(
598
+ expected: ResidentAgendaState,
599
+ learning: ResidentLearningState,
600
+ ): Promise<ResidentAgendaState> {
601
+ return this.change(expected, (state) => {
602
+ if (state.pursuits.some((pursuit) => pursuit.state.phase === 'running'))
603
+ throw new Error('Resident learning cannot change while a pursuit is running.')
604
+ if (!isDeepStrictEqual(state.learning, expected.learning)) throw new ResidentConflictError()
605
+ return { ...state, learning }
606
+ })
607
+ }
608
+
609
+ /** Append a host-evidenced correction only while pursuit admission is idle. */
610
+ async updateProfile(
611
+ expected: ResidentAgendaState,
612
+ input: ResidentProfileUpdate,
613
+ ): Promise<ResidentAgendaState> {
614
+ const snapshot = this.checked(expected)
615
+ const learning = reviseResidentProfile(snapshot.learning, input)
616
+ return this.learn(snapshot, learning)
617
+ }
618
+
619
+ /** Bind evaluated guidance to the current learning version and an idle agenda. */
620
+ async promoteSkill(
621
+ expected: ResidentAgendaState,
622
+ candidate: ResidentSkillCandidate,
623
+ evaluation: ResidentSkillEvaluation,
624
+ evidence: ResidentLearningEvidence,
625
+ ): Promise<ResidentAgendaState> {
626
+ const snapshot = this.checked(expected)
627
+ const learning = promoteResidentSkill(snapshot.learning, candidate, evaluation, evidence)
628
+ return this.learn(snapshot, learning)
629
+ }
630
+
631
+ /** Restore one skill from an immutable agenda revision while retaining the current profile. */
632
+ async rollbackSkill(
633
+ expected: ResidentAgendaState,
634
+ name: string,
635
+ fromRevision: number,
636
+ evidence: ResidentLearningEvidence,
637
+ ): Promise<ResidentAgendaState> {
638
+ const snapshot = this.checked(expected)
639
+ const checkedEvidence = residentLearningEvidenceSchema.parse(evidence)
640
+ z.number().int().positive().safe().max(snapshot.revision).parse(fromRevision)
641
+ z.string()
642
+ .regex(/^[a-z0-9][a-z0-9_-]{0,63}$/)
643
+ .parse(name)
644
+ const historical = await this.readRevision(fromRevision)
645
+ if (!historical) throw new Error('Resident skill rollback revision is missing.')
646
+ const learning = restoreResidentSkill(
647
+ snapshot.learning,
648
+ historical.learning,
649
+ name,
650
+ checkedEvidence,
651
+ )
652
+ return this.learn(snapshot, learning)
653
+ }
654
+
655
+ private async updatePursuit(
656
+ id: string,
657
+ expected: ResidentState,
658
+ update: (state: ResidentState) => ResidentState,
659
+ admission = false,
660
+ expectedAgendaRevision?: number,
661
+ observation?: ResidentObservation,
662
+ message?: ResidentMessageInput,
663
+ ): Promise<ResidentState> {
664
+ const validate = (state: ResidentAgendaState): ResidentState => {
665
+ const pursuit = state.pursuits.find((p) => p.id === id)
666
+ if (!pursuit) throw new Error('Unknown resident pursuit.')
667
+ const current = pursuit.state
668
+ if (
669
+ expected.pursuitId !== id ||
670
+ expected.tenantId !== state.tenantId ||
671
+ expected.agentKey !== state.agentKey ||
672
+ current.revision !== expected.revision ||
673
+ current.claimId !== expected.claimId
674
+ )
675
+ throw new ResidentConflictError()
676
+ if (admission && (state.paused || state.pursuits.some((p) => p.state.phase === 'running')))
677
+ throw new ResidentConflictError()
678
+ return current
679
+ }
680
+ // Retry persistence contention only. The caller's exact pursuit revision
681
+ // and claim must survive every retry; a callback is never re-executed here.
682
+ for (let attempt = 0; attempt < 8; attempt++) {
683
+ const agenda = await this.read()
684
+ if (agenda === null) throw new Error('Create the resident agenda first.')
685
+ if (expectedAgendaRevision !== undefined && agenda.revision !== expectedAgendaRevision)
686
+ throw new ResidentConflictError()
687
+ const current = validate(agenda)
688
+ const archived =
689
+ message && !agenda.outbox?.some((item) => item.id === message.id)
690
+ ? await this.archivedMatch(agenda, (entry) =>
691
+ entry.messages.find((item) => item.id === message.id),
692
+ )
693
+ : undefined
694
+ if (message && archived) this.assertArchivedIntent(archived, message, current.claimId)
695
+ try {
696
+ const next = await this.change(agenda, (state) => {
697
+ const current = validate(state)
698
+ const updated = residentStateSchema.parse({
699
+ ...update(current),
700
+ revision: current.revision + 1,
701
+ })
702
+ return {
703
+ ...state,
704
+ ...(message && !archived
705
+ ? { outbox: appendResidentMessage(state, message, current.claimId) }
706
+ : {}),
707
+ pursuits: state.pursuits.map((p) =>
708
+ p.id === id
709
+ ? {
710
+ ...p,
711
+ state: updated,
712
+ ...(observation
713
+ ? {
714
+ feedback: observeResidentStep(
715
+ p.feedback,
716
+ observation,
717
+ current.stepsAdmitted,
718
+ ),
719
+ }
720
+ : {}),
721
+ }
722
+ : p,
723
+ ),
724
+ }
725
+ })
726
+ const result = next.pursuits.find((p) => p.id === id)
727
+ if (!result) throw new Error('Committed pursuit is missing.')
728
+ return result.state
729
+ } catch (error) {
730
+ if (!(error instanceof ResidentConflictError) || attempt === 7) throw error
731
+ }
732
+ }
733
+ throw new ResidentConflictError()
734
+ }
735
+
736
+ async wake(
737
+ id: string,
738
+ expected: ResidentState,
739
+ reason: string,
740
+ now: number,
741
+ ): Promise<ResidentState> {
742
+ return this.updatePursuit(id, expected, (state) => wakeResidentState(state, reason, now))
743
+ }
744
+
745
+ async settleObserved(
746
+ id: string,
747
+ expected: ResidentState,
748
+ decision: ResidentDecision,
749
+ observation: ResidentObservation,
750
+ now: number,
751
+ ): Promise<ResidentState> {
752
+ const checked = residentObservationSchema.parse(observation)
753
+ return this.updatePursuit(
754
+ id,
755
+ expected,
756
+ (state) => settleResidentState(state, decision, now),
757
+ false,
758
+ undefined,
759
+ checked,
760
+ )
761
+ }
762
+
763
+ /** Commit the step, observation and message intent together; delivery is separate. */
764
+ async settleWithMessage(
765
+ id: string,
766
+ expected: ResidentState,
767
+ decision: ResidentDecision,
768
+ message: ResidentMessageInput,
769
+ now: number,
770
+ observation?: ResidentObservation,
771
+ ): Promise<ResidentState> {
772
+ const input = residentMessageInputSchema.parse(message)
773
+ const disposition = residentDecisionSchema.parse(decision)
774
+ if (input.pursuitId !== id) throw new Error('Message must belong to the settling pursuit.')
775
+ const current = residentStateSchema.parse(expected)
776
+ const checked =
777
+ observation === undefined ? undefined : residentObservationSchema.parse(observation)
778
+ return this.updatePursuit(
779
+ id,
780
+ current,
781
+ (state) => settleResidentState(state, disposition, now),
782
+ false,
783
+ undefined,
784
+ checked,
785
+ input,
786
+ )
787
+ }
788
+
789
+ /** Enqueue host-authorized intent without invoking a transport or changing pursuit state. */
790
+ async enqueueMessage(
791
+ expected: ResidentAgendaState,
792
+ input: ResidentMessageInput,
793
+ ): Promise<ResidentOutboxMessage> {
794
+ const snapshot = this.checked(expected)
795
+ const message = residentMessageInputSchema.parse(input)
796
+ const current = await this.read()
797
+ if (!current || current.revision !== snapshot.revision) throw new ResidentConflictError()
798
+ const archived = current.outbox?.some((item) => item.id === message.id)
799
+ ? undefined
800
+ : await this.archivedMatch(current, (entry) =>
801
+ entry.messages.find((item) => item.id === message.id),
802
+ )
803
+ if (archived) this.assertArchivedIntent(archived, message, null)
804
+ const next = await this.change(snapshot, (state) => ({
805
+ ...state,
806
+ ...(!archived ? { outbox: appendResidentMessage(state, message) } : {}),
807
+ }))
808
+ const saved = archived ?? next.outbox?.find((candidate) => candidate.id === message.id)
809
+ if (!saved) throw new Error('Committed resident message is missing.')
810
+ return saved
811
+ }
812
+
813
+ /** Admit one delivery against the same agenda snapshot used by the host's gate. */
814
+ async claimMessage(
815
+ expected: ResidentAgendaState,
816
+ id: string,
817
+ now: number,
818
+ ): Promise<ResidentOutboxMessage> {
819
+ z.string().uuid().parse(id)
820
+ const next = await this.change(expected, (state) => {
821
+ const outbox = state.outbox ?? []
822
+ if (state.paused || outbox.some((message) => message.phase === 'sending'))
823
+ throw new ResidentConflictError()
824
+ const message = outbox.find((candidate) => candidate.id === id)
825
+ if (!message) throw new Error('Unknown resident message.')
826
+ const admitted = claimResidentOutboxMessage(message, now)
827
+ return {
828
+ ...state,
829
+ outbox: outbox.map((candidate) => (candidate.id === id ? admitted : candidate)),
830
+ }
831
+ })
832
+ const claim = next.outbox?.find((message) => message.id === id)
833
+ if (!claim) throw new Error('Claimed resident message is missing.')
834
+ return claim
835
+ }
836
+
837
+ /** Settle the exact delivery claim; unrelated agenda writes never repeat the transport. */
838
+ async settleMessage(
839
+ expected: ResidentOutboxMessage,
840
+ outcome: ResidentDeliveryOutcome,
841
+ now: number,
842
+ ): Promise<ResidentOutboxMessage> {
843
+ const claim = residentOutboxMessageSchema.parse(expected)
844
+ const checked = residentDeliveryOutcomeSchema.parse(outcome)
845
+ if (claim.tenantId !== this.tenantId || claim.agentKey !== this.agentKey)
846
+ throw new ResidentConflictError()
847
+ const validate = (state: ResidentAgendaState): ResidentOutboxMessage => {
848
+ const message = state.outbox?.find((candidate) => candidate.id === claim.id)
849
+ if (!message || message.revision !== claim.revision || message.claimId !== claim.claimId)
850
+ throw new ResidentConflictError()
851
+ return message
852
+ }
853
+ for (let attempt = 0; attempt < 8; attempt++) {
854
+ const agenda = await this.read()
855
+ if (agenda === null) throw new Error('Create the resident agenda first.')
856
+ validate(agenda)
857
+ try {
858
+ const next = await this.change(agenda, (state) => {
859
+ const current = validate(state)
860
+ const settled = settleResidentOutboxMessage(current, checked, now)
861
+ return {
862
+ ...state,
863
+ outbox: (state.outbox ?? []).map((message) =>
864
+ message.id === claim.id ? settled : message,
865
+ ),
866
+ }
867
+ })
868
+ const settled = next.outbox?.find((message) => message.id === claim.id)
869
+ if (!settled) throw new Error('Settled resident message is missing.')
870
+ return settled
871
+ } catch (error) {
872
+ if (!(error instanceof ResidentConflictError) || attempt === 7) throw error
873
+ }
874
+ }
875
+ throw new ResidentConflictError()
876
+ }
877
+
878
+ executionAt(id: string, expected: ResidentAgendaState): ResidentExecutionStore {
879
+ const state = this.checked(expected)
880
+ const pursuit = state.pursuits.find((p) => p.id === id)
881
+ if (!pursuit) throw new Error('Unknown resident pursuit.')
882
+ const execution = this.execution(id)
883
+ return {
884
+ read: async () => pursuit.state,
885
+ settle: (...args) => execution.settle(...args),
886
+ claim: (current, now) =>
887
+ this.updatePursuit(
888
+ id,
889
+ current,
890
+ (saved) => claimResidentState(saved, now),
891
+ true,
892
+ state.revision,
893
+ ),
894
+ }
895
+ }
896
+
897
+ execution(id: string): ResidentExecutionStore {
898
+ z.string().uuid().parse(id)
899
+ return {
900
+ read: async () => (await this.read())?.pursuits.find((p) => p.id === id)?.state ?? null,
901
+ claim: (expected, now) =>
902
+ this.updatePursuit(id, expected, (state) => claimResidentState(state, now), true),
903
+ settle: (expected, decision: ResidentDecision, now) =>
904
+ this.updatePursuit(id, expected, (state) => settleResidentState(state, decision, now)),
905
+ }
906
+ }
907
+ }