@plurnk/plurnk-service 1.3.11 → 1.4.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 (469) hide show
  1. package/.env.defaults +84 -77
  2. package/INSTALL.md +50 -25
  3. package/README.md +24 -10
  4. package/SPEC.md +2315 -932
  5. package/dist/Paths.d.ts +4 -1
  6. package/dist/Paths.d.ts.map +1 -1
  7. package/dist/Paths.js +23 -21
  8. package/dist/Paths.js.map +1 -1
  9. package/dist/build-info.json +1 -1
  10. package/dist/content/edit-receipt.d.ts +13 -28
  11. package/dist/content/edit-receipt.d.ts.map +1 -1
  12. package/dist/content/edit-receipt.js +285 -104
  13. package/dist/content/edit-receipt.js.map +1 -1
  14. package/dist/content/edited-span.d.ts.map +1 -1
  15. package/dist/content/edited-span.js +2 -5
  16. package/dist/content/edited-span.js.map +1 -1
  17. package/dist/content/index.d.ts +3 -3
  18. package/dist/content/index.d.ts.map +1 -1
  19. package/dist/content/index.js +1 -1
  20. package/dist/content/index.js.map +1 -1
  21. package/dist/content/line-marker.d.ts +6 -9
  22. package/dist/content/line-marker.d.ts.map +1 -1
  23. package/dist/content/line-marker.js +7 -11
  24. package/dist/content/line-marker.js.map +1 -1
  25. package/dist/content/matcher.d.ts +14 -25
  26. package/dist/content/matcher.d.ts.map +1 -1
  27. package/dist/content/matcher.js +77 -107
  28. package/dist/content/matcher.js.map +1 -1
  29. package/dist/content/mimetype-binary.d.ts +2 -2
  30. package/dist/content/mimetype-binary.d.ts.map +1 -1
  31. package/dist/content/mimetype-binary.js +10 -10
  32. package/dist/content/mimetype-binary.js.map +1 -1
  33. package/dist/content/path-mimetype.js +3 -3
  34. package/dist/content/path-mimetype.js.map +1 -1
  35. package/dist/content/read-resolve.d.ts +8 -4
  36. package/dist/content/read-resolve.d.ts.map +1 -1
  37. package/dist/content/read-resolve.js +101 -49
  38. package/dist/content/read-resolve.js.map +1 -1
  39. package/dist/core/BranchReceipt.d.ts +7 -0
  40. package/dist/core/BranchReceipt.d.ts.map +1 -0
  41. package/dist/core/BranchReceipt.js +27 -0
  42. package/dist/core/BranchReceipt.js.map +1 -0
  43. package/dist/core/BudgetOverflow.d.ts +23 -0
  44. package/dist/core/BudgetOverflow.d.ts.map +1 -0
  45. package/dist/core/BudgetOverflow.js +61 -0
  46. package/dist/core/BudgetOverflow.js.map +1 -0
  47. package/dist/core/BudgetReadout.d.ts +8 -0
  48. package/dist/core/BudgetReadout.d.ts.map +1 -0
  49. package/dist/core/BudgetReadout.js +79 -0
  50. package/dist/core/BudgetReadout.js.map +1 -0
  51. package/dist/core/ChannelWrite.d.ts +28 -9
  52. package/dist/core/ChannelWrite.d.ts.map +1 -1
  53. package/dist/core/ChannelWrite.js +28 -21
  54. package/dist/core/ChannelWrite.js.map +1 -1
  55. package/dist/core/ChannelWrite.sql +11 -10
  56. package/dist/core/CoreSchemeServices.d.ts +10 -4
  57. package/dist/core/CoreSchemeServices.d.ts.map +1 -1
  58. package/dist/core/CoreSchemeServices.js +7 -1
  59. package/dist/core/CoreSchemeServices.js.map +1 -1
  60. package/dist/core/Dispatcher.d.ts +29 -20
  61. package/dist/core/Dispatcher.d.ts.map +1 -1
  62. package/dist/core/Dispatcher.js +1488 -599
  63. package/dist/core/Dispatcher.js.map +1 -1
  64. package/dist/core/DurableStatement.d.ts +6 -0
  65. package/dist/core/DurableStatement.d.ts.map +1 -0
  66. package/dist/core/DurableStatement.js +51 -0
  67. package/dist/core/DurableStatement.js.map +1 -0
  68. package/dist/core/Engine.d.ts +48 -20
  69. package/dist/core/Engine.d.ts.map +1 -1
  70. package/dist/core/Engine.js +1208 -789
  71. package/dist/core/Engine.js.map +1 -1
  72. package/dist/core/Engine.sql +309 -217
  73. package/dist/core/EnvFlags.js +1 -1
  74. package/dist/core/EnvFlags.js.map +1 -1
  75. package/dist/core/ErrorDetail.d.ts +6 -0
  76. package/dist/core/ErrorDetail.d.ts.map +1 -0
  77. package/dist/core/ErrorDetail.js +20 -0
  78. package/dist/core/ErrorDetail.js.map +1 -0
  79. package/dist/core/ExecutorRegistry.d.ts +14 -3
  80. package/dist/core/ExecutorRegistry.d.ts.map +1 -1
  81. package/dist/core/ExecutorRegistry.js +56 -30
  82. package/dist/core/ExecutorRegistry.js.map +1 -1
  83. package/dist/core/GitBranch.d.ts +20 -0
  84. package/dist/core/GitBranch.d.ts.map +1 -0
  85. package/dist/core/GitBranch.js +110 -0
  86. package/dist/core/GitBranch.js.map +1 -0
  87. package/dist/core/JournalTurn.d.ts +9 -0
  88. package/dist/core/JournalTurn.d.ts.map +1 -0
  89. package/dist/core/JournalTurn.js +14 -0
  90. package/dist/core/JournalTurn.js.map +1 -0
  91. package/dist/core/JournalTurn.sql +10 -0
  92. package/dist/core/LogBody.d.ts +17 -0
  93. package/dist/core/LogBody.d.ts.map +1 -0
  94. package/dist/core/LogBody.js +148 -0
  95. package/dist/core/LogBody.js.map +1 -0
  96. package/dist/core/LoopFlagsReader.d.ts +7 -0
  97. package/dist/core/LoopFlagsReader.d.ts.map +1 -0
  98. package/dist/core/LoopFlagsReader.js +33 -0
  99. package/dist/core/LoopFlagsReader.js.map +1 -0
  100. package/dist/core/LoopLifecycle.d.ts +8 -1
  101. package/dist/core/LoopLifecycle.d.ts.map +1 -1
  102. package/dist/core/LoopLifecycle.js +55 -9
  103. package/dist/core/LoopLifecycle.js.map +1 -1
  104. package/dist/core/LoopLifecycle.sql +9 -3
  105. package/dist/core/NoticeChannel.d.ts +13 -0
  106. package/dist/core/NoticeChannel.d.ts.map +1 -0
  107. package/dist/core/NoticeChannel.js +40 -0
  108. package/dist/core/NoticeChannel.js.map +1 -0
  109. package/dist/core/Owner.d.ts +0 -1
  110. package/dist/core/Owner.d.ts.map +1 -1
  111. package/dist/core/Owner.js +2 -5
  112. package/dist/core/Owner.js.map +1 -1
  113. package/dist/core/PacketBuilder.d.ts +25 -24
  114. package/dist/core/PacketBuilder.d.ts.map +1 -1
  115. package/dist/core/PacketBuilder.js +323 -384
  116. package/dist/core/PacketBuilder.js.map +1 -1
  117. package/dist/core/ProblemLog.d.ts +26 -0
  118. package/dist/core/ProblemLog.d.ts.map +1 -0
  119. package/dist/core/ProblemLog.js +58 -0
  120. package/dist/core/ProblemLog.js.map +1 -0
  121. package/dist/core/ProposalLifecycle.d.ts +15 -21
  122. package/dist/core/ProposalLifecycle.d.ts.map +1 -1
  123. package/dist/core/ProposalLifecycle.js +291 -78
  124. package/dist/core/ProposalLifecycle.js.map +1 -1
  125. package/dist/core/ProviderInstantiate.d.ts.map +1 -1
  126. package/dist/core/ProviderInstantiate.js +51 -48
  127. package/dist/core/ProviderInstantiate.js.map +1 -1
  128. package/dist/core/SchemeRegistry.d.ts +14 -8
  129. package/dist/core/SchemeRegistry.d.ts.map +1 -1
  130. package/dist/core/SchemeRegistry.js +189 -114
  131. package/dist/core/SchemeRegistry.js.map +1 -1
  132. package/dist/core/ServiceTeardown.d.ts +11 -0
  133. package/dist/core/ServiceTeardown.d.ts.map +1 -0
  134. package/dist/core/ServiceTeardown.js +70 -0
  135. package/dist/core/ServiceTeardown.js.map +1 -0
  136. package/dist/core/StoredPacket.d.ts +29 -0
  137. package/dist/core/StoredPacket.d.ts.map +1 -0
  138. package/dist/core/StoredPacket.js +147 -0
  139. package/dist/core/StoredPacket.js.map +1 -0
  140. package/dist/core/StrikeRail.d.ts +1 -2
  141. package/dist/core/StrikeRail.d.ts.map +1 -1
  142. package/dist/core/StrikeRail.js +25 -55
  143. package/dist/core/StrikeRail.js.map +1 -1
  144. package/dist/core/WorkerControlAddress.d.ts +17 -0
  145. package/dist/core/WorkerControlAddress.d.ts.map +1 -0
  146. package/dist/core/WorkerControlAddress.js +44 -0
  147. package/dist/core/WorkerControlAddress.js.map +1 -0
  148. package/dist/core/WorkerName.d.ts +31 -0
  149. package/dist/core/WorkerName.d.ts.map +1 -0
  150. package/dist/core/WorkerName.js +95 -0
  151. package/dist/core/WorkerName.js.map +1 -0
  152. package/dist/core/WorkerName.sql +36 -0
  153. package/dist/core/WorkspaceGate.d.ts +14 -0
  154. package/dist/core/WorkspaceGate.d.ts.map +1 -0
  155. package/dist/core/WorkspaceGate.js +155 -0
  156. package/dist/core/WorkspaceGate.js.map +1 -0
  157. package/dist/core/caps/CapsResolve.d.ts +1 -1
  158. package/dist/core/caps/CapsResolve.d.ts.map +1 -1
  159. package/dist/core/caps/CapsResolve.js.map +1 -1
  160. package/dist/core/caps/DbChannelCaps.d.ts +5 -11
  161. package/dist/core/caps/DbChannelCaps.d.ts.map +1 -1
  162. package/dist/core/caps/DbChannelCaps.js +24 -8
  163. package/dist/core/caps/DbChannelCaps.js.map +1 -1
  164. package/dist/core/caps/DbEntryCaps.d.ts +4 -13
  165. package/dist/core/caps/DbEntryCaps.d.ts.map +1 -1
  166. package/dist/core/caps/DbEntryCaps.js +15 -6
  167. package/dist/core/caps/DbEntryCaps.js.map +1 -1
  168. package/dist/core/caps/DbNotifyCaps.d.ts +1 -1
  169. package/dist/core/caps/DbNotifyCaps.d.ts.map +1 -1
  170. package/dist/core/caps/DbNotifyCaps.js +12 -11
  171. package/dist/core/caps/DbNotifyCaps.js.map +1 -1
  172. package/dist/core/caps/DbProjectionCaps.d.ts +5 -5
  173. package/dist/core/caps/DbProjectionCaps.d.ts.map +1 -1
  174. package/dist/core/caps/DbProjectionCaps.js +21 -4
  175. package/dist/core/caps/DbProjectionCaps.js.map +1 -1
  176. package/dist/core/caps/DbSubscriptionCaps.d.ts +4 -4
  177. package/dist/core/caps/DbSubscriptionCaps.d.ts.map +1 -1
  178. package/dist/core/caps/DbSubscriptionCaps.js +57 -62
  179. package/dist/core/caps/DbSubscriptionCaps.js.map +1 -1
  180. package/dist/core/caps/DbTagCaps.d.ts +5 -12
  181. package/dist/core/caps/DbTagCaps.d.ts.map +1 -1
  182. package/dist/core/caps/DbTagCaps.js +14 -7
  183. package/dist/core/caps/DbTagCaps.js.map +1 -1
  184. package/dist/core/content-hash.js +1 -1
  185. package/dist/core/content-hash.js.map +1 -1
  186. package/dist/core/env-defaults.d.ts.map +1 -1
  187. package/dist/core/env-defaults.js.map +1 -1
  188. package/dist/core/fork.d.ts.map +1 -1
  189. package/dist/core/fork.js +55 -30
  190. package/dist/core/fork.js.map +1 -1
  191. package/dist/core/fork.sql +41 -27
  192. package/dist/core/git-env.d.ts +2 -0
  193. package/dist/core/git-env.d.ts.map +1 -1
  194. package/dist/core/git-env.js +13 -18
  195. package/dist/core/git-env.js.map +1 -1
  196. package/dist/core/git-iso.d.ts.map +1 -1
  197. package/dist/core/git-iso.js +9 -15
  198. package/dist/core/git-iso.js.map +1 -1
  199. package/dist/core/git-membership.d.ts +1 -1
  200. package/dist/core/git-membership.d.ts.map +1 -1
  201. package/dist/core/git-membership.js +198 -146
  202. package/dist/core/git-membership.js.map +1 -1
  203. package/dist/core/git-state.d.ts.map +1 -1
  204. package/dist/core/git-state.js +10 -11
  205. package/dist/core/git-state.js.map +1 -1
  206. package/dist/core/owner.sql +1 -1
  207. package/dist/core/packet-inject.d.ts.map +1 -1
  208. package/dist/core/packet-inject.js +7 -11
  209. package/dist/core/packet-inject.js.map +1 -1
  210. package/dist/core/packet-wire.d.ts +2 -20
  211. package/dist/core/packet-wire.d.ts.map +1 -1
  212. package/dist/core/packet-wire.js +242 -368
  213. package/dist/core/packet-wire.js.map +1 -1
  214. package/dist/core/plurnk-uri.d.ts +12 -1
  215. package/dist/core/plurnk-uri.d.ts.map +1 -1
  216. package/dist/core/plurnk-uri.js +49 -29
  217. package/dist/core/plurnk-uri.js.map +1 -1
  218. package/dist/core/results.d.ts +16 -5
  219. package/dist/core/results.d.ts.map +1 -1
  220. package/dist/core/results.js +27 -18
  221. package/dist/core/results.js.map +1 -1
  222. package/dist/core/ruler_count.d.ts +4 -0
  223. package/dist/core/ruler_count.d.ts.map +1 -0
  224. package/dist/core/ruler_count.js +7 -0
  225. package/dist/core/ruler_count.js.map +1 -0
  226. package/dist/core/scheme-types.d.ts +9 -11
  227. package/dist/core/scheme-types.d.ts.map +1 -1
  228. package/dist/core/scheme-types.js.map +1 -1
  229. package/dist/core/search-gate.d.ts.map +1 -1
  230. package/dist/core/search-gate.js +3 -11
  231. package/dist/core/search-gate.js.map +1 -1
  232. package/dist/core/teaching-corpus.d.ts +6 -0
  233. package/dist/core/teaching-corpus.d.ts.map +1 -0
  234. package/dist/core/teaching-corpus.js +23 -0
  235. package/dist/core/teaching-corpus.js.map +1 -0
  236. package/dist/core/teaching.d.ts +0 -1
  237. package/dist/core/teaching.d.ts.map +1 -1
  238. package/dist/core/teaching.js +2 -8
  239. package/dist/core/teaching.js.map +1 -1
  240. package/dist/core/token-ruler.d.ts.map +1 -1
  241. package/dist/core/token-ruler.js +3 -16
  242. package/dist/core/token-ruler.js.map +1 -1
  243. package/dist/core/turn-scheduler.d.ts +1 -1
  244. package/dist/core/turn-scheduler.d.ts.map +1 -1
  245. package/dist/core/turn-scheduler.js +1 -1
  246. package/dist/core/turn-scheduler.js.map +1 -1
  247. package/dist/core/worker-cap.d.ts +2 -4
  248. package/dist/core/worker-cap.d.ts.map +1 -1
  249. package/dist/core/worker-cap.js +13 -4
  250. package/dist/core/worker-cap.js.map +1 -1
  251. package/dist/core/{run-ops.sql → worker-ops.sql} +11 -11
  252. package/dist/core/workspace-settings.d.ts.map +1 -1
  253. package/dist/core/workspace-settings.js +17 -9
  254. package/dist/core/workspace-settings.js.map +1 -1
  255. package/dist/digest/Digest.d.ts +2 -1
  256. package/dist/digest/Digest.d.ts.map +1 -1
  257. package/dist/digest/Digest.js +339 -139
  258. package/dist/digest/Digest.js.map +1 -1
  259. package/dist/digest/digest.sql +19 -10
  260. package/dist/index.d.ts.map +1 -1
  261. package/dist/index.js +3 -5
  262. package/dist/index.js.map +1 -1
  263. package/dist/matrix/live-specimen.d.ts +9 -0
  264. package/dist/matrix/live-specimen.d.ts.map +1 -0
  265. package/dist/matrix/live-specimen.js +37 -0
  266. package/dist/matrix/live-specimen.js.map +1 -0
  267. package/dist/observe/api.d.ts +6 -0
  268. package/dist/observe/api.d.ts.map +1 -0
  269. package/dist/observe/api.js +11 -0
  270. package/dist/observe/api.js.map +1 -0
  271. package/dist/observe/init.d.ts +7 -0
  272. package/dist/observe/init.d.ts.map +1 -0
  273. package/dist/observe/init.js +159 -0
  274. package/dist/observe/init.js.map +1 -0
  275. package/dist/observe/metrics.d.ts +6 -0
  276. package/dist/observe/metrics.d.ts.map +1 -0
  277. package/dist/observe/metrics.js +15 -0
  278. package/dist/observe/metrics.js.map +1 -0
  279. package/dist/observe/spans.d.ts +4 -0
  280. package/dist/observe/spans.d.ts.map +1 -0
  281. package/dist/observe/spans.js +51 -0
  282. package/dist/observe/spans.js.map +1 -0
  283. package/dist/schemes/EffectPolicy.d.ts +1 -0
  284. package/dist/schemes/EffectPolicy.d.ts.map +1 -1
  285. package/dist/schemes/EffectPolicy.js +5 -2
  286. package/dist/schemes/EffectPolicy.js.map +1 -1
  287. package/dist/schemes/Exec.d.ts +6 -11
  288. package/dist/schemes/Exec.d.ts.map +1 -1
  289. package/dist/schemes/Exec.js +371 -263
  290. package/dist/schemes/Exec.js.map +1 -1
  291. package/dist/schemes/ExecOutputScheme.d.ts +8 -7
  292. package/dist/schemes/ExecOutputScheme.d.ts.map +1 -1
  293. package/dist/schemes/ExecOutputScheme.js +48 -9
  294. package/dist/schemes/ExecOutputScheme.js.map +1 -1
  295. package/dist/schemes/File.d.ts +7 -11
  296. package/dist/schemes/File.d.ts.map +1 -1
  297. package/dist/schemes/File.js +280 -141
  298. package/dist/schemes/File.js.map +1 -1
  299. package/dist/schemes/Log.d.ts +4 -8
  300. package/dist/schemes/Log.d.ts.map +1 -1
  301. package/dist/schemes/Log.js +475 -208
  302. package/dist/schemes/Log.js.map +1 -1
  303. package/dist/schemes/Log.sql +62 -30
  304. package/dist/schemes/Prompt.d.ts +3 -2
  305. package/dist/schemes/Prompt.d.ts.map +1 -1
  306. package/dist/schemes/Prompt.js +9 -6
  307. package/dist/schemes/Prompt.js.map +1 -1
  308. package/dist/schemes/Skill.d.ts +1 -1
  309. package/dist/schemes/Skill.d.ts.map +1 -1
  310. package/dist/schemes/Skill.js +2 -3
  311. package/dist/schemes/Skill.js.map +1 -1
  312. package/dist/schemes/Worker.d.ts +8 -16
  313. package/dist/schemes/Worker.d.ts.map +1 -1
  314. package/dist/schemes/Worker.js +179 -69
  315. package/dist/schemes/Worker.js.map +1 -1
  316. package/dist/schemes/_entry-chunk.d.ts.map +1 -1
  317. package/dist/schemes/_entry-chunk.js +12 -5
  318. package/dist/schemes/_entry-chunk.js.map +1 -1
  319. package/dist/schemes/_entry-crud.d.ts +10 -9
  320. package/dist/schemes/_entry-crud.d.ts.map +1 -1
  321. package/dist/schemes/_entry-crud.js +59 -13
  322. package/dist/schemes/_entry-crud.js.map +1 -1
  323. package/dist/schemes/_entry-crud.sql +20 -8
  324. package/dist/schemes/_entry-find.d.ts +20 -15
  325. package/dist/schemes/_entry-find.d.ts.map +1 -1
  326. package/dist/schemes/_entry-find.js +339 -174
  327. package/dist/schemes/_entry-find.js.map +1 -1
  328. package/dist/schemes/_entry-find.sql +20 -8
  329. package/dist/schemes/_entry-graph.d.ts +4 -2
  330. package/dist/schemes/_entry-graph.d.ts.map +1 -1
  331. package/dist/schemes/_entry-graph.js +55 -31
  332. package/dist/schemes/_entry-graph.js.map +1 -1
  333. package/dist/schemes/_entry-graph.sql +37 -22
  334. package/dist/schemes/_entry-manifest.d.ts +10 -15
  335. package/dist/schemes/_entry-manifest.d.ts.map +1 -1
  336. package/dist/schemes/_entry-manifest.js +50 -268
  337. package/dist/schemes/_entry-manifest.js.map +1 -1
  338. package/dist/schemes/_entry-ops.d.ts +9 -14
  339. package/dist/schemes/_entry-ops.d.ts.map +1 -1
  340. package/dist/schemes/_entry-ops.js +149 -77
  341. package/dist/schemes/_entry-ops.js.map +1 -1
  342. package/dist/schemes/_entry-ops.sql +1 -1
  343. package/dist/schemes/_entry-semantic.d.ts +23 -8
  344. package/dist/schemes/_entry-semantic.d.ts.map +1 -1
  345. package/dist/schemes/_entry-semantic.js +141 -60
  346. package/dist/schemes/_entry-semantic.js.map +1 -1
  347. package/dist/schemes/_entry-semantic.sql +63 -45
  348. package/dist/schemes/_entry-send.d.ts +3 -4
  349. package/dist/schemes/_entry-send.d.ts.map +1 -1
  350. package/dist/schemes/_entry-send.js +48 -23
  351. package/dist/schemes/_entry-send.js.map +1 -1
  352. package/dist/schemes/_path-scope.d.ts +23 -0
  353. package/dist/schemes/_path-scope.d.ts.map +1 -0
  354. package/dist/schemes/_path-scope.js +61 -0
  355. package/dist/schemes/_path-scope.js.map +1 -0
  356. package/dist/schemes/_search-candidate.d.ts +20 -0
  357. package/dist/schemes/_search-candidate.d.ts.map +1 -0
  358. package/dist/schemes/_search-candidate.js +19 -0
  359. package/dist/schemes/_search-candidate.js.map +1 -0
  360. package/dist/schemes/_search-exclusion.d.ts +7 -0
  361. package/dist/schemes/_search-exclusion.d.ts.map +1 -0
  362. package/dist/schemes/_search-exclusion.js +23 -0
  363. package/dist/schemes/_search-exclusion.js.map +1 -0
  364. package/dist/schemes/_search-index.d.ts +6 -0
  365. package/dist/schemes/_search-index.d.ts.map +1 -0
  366. package/dist/schemes/_search-index.js +326 -0
  367. package/dist/schemes/_search-index.js.map +1 -0
  368. package/dist/schemes/cosine.js +1 -1
  369. package/dist/schemes/cosine.js.map +1 -1
  370. package/dist/schemes/exec-abort.js +3 -3
  371. package/dist/schemes/exec-abort.js.map +1 -1
  372. package/dist/schemes/exec-env.js +3 -3
  373. package/dist/schemes/exec-env.js.map +1 -1
  374. package/dist/server/BranchBatches.d.ts +48 -0
  375. package/dist/server/BranchBatches.d.ts.map +1 -0
  376. package/dist/server/BranchBatches.js +591 -0
  377. package/dist/server/BranchBatches.js.map +1 -0
  378. package/dist/server/Daemon.d.ts +36 -66
  379. package/dist/server/Daemon.d.ts.map +1 -1
  380. package/dist/server/Daemon.js +920 -446
  381. package/dist/server/Daemon.js.map +1 -1
  382. package/dist/server/DaemonModule.d.ts +31 -0
  383. package/dist/server/DaemonModule.d.ts.map +1 -0
  384. package/dist/server/DaemonModule.js +2 -0
  385. package/dist/server/DaemonModule.js.map +1 -0
  386. package/dist/server/branch-batch.sql +152 -0
  387. package/dist/server/client-input.d.ts +12 -0
  388. package/dist/server/client-input.d.ts.map +1 -1
  389. package/dist/server/client-input.js +262 -57
  390. package/dist/server/client-input.js.map +1 -1
  391. package/dist/server/dispatch-as-plurnk.d.ts +1 -1
  392. package/dist/server/dispatch-as-plurnk.d.ts.map +1 -1
  393. package/dist/server/dispatch-as-plurnk.js +15 -7
  394. package/dist/server/dispatch-as-plurnk.js.map +1 -1
  395. package/dist/server/drain.sql +92 -62
  396. package/dist/server/envelope.d.ts +2 -5
  397. package/dist/server/envelope.d.ts.map +1 -1
  398. package/dist/server/envelope.js +119 -95
  399. package/dist/server/envelope.js.map +1 -1
  400. package/dist/server/envelope.sql +19 -23
  401. package/dist/server/exec-poll-backoff.js +1 -1
  402. package/dist/server/exec-poll-backoff.js.map +1 -1
  403. package/dist/server/lifecycle-recovery.sql +79 -2
  404. package/dist/server/logEntry.d.ts +3 -1
  405. package/dist/server/logEntry.d.ts.map +1 -1
  406. package/dist/server/logEntry.js +4 -2
  407. package/dist/server/logEntry.js.map +1 -1
  408. package/dist/server/logEntry.sql +1 -1
  409. package/dist/server/loop-model.d.ts.map +1 -1
  410. package/dist/server/loop-model.js +22 -9
  411. package/dist/server/loop-model.js.map +1 -1
  412. package/dist/server/loopDocs.d.ts.map +1 -1
  413. package/dist/server/loopDocs.js +5 -4
  414. package/dist/server/loopDocs.js.map +1 -1
  415. package/dist/server/seam-entry-read.sql +15 -10
  416. package/dist/server/seam-log-read.sql +2 -2
  417. package/dist/server/seam-loop.sql +1 -1
  418. package/dist/server/seam-proposal-list.sql +17 -7
  419. package/dist/service.d.ts.map +1 -1
  420. package/dist/service.js +66 -60
  421. package/dist/service.js.map +1 -1
  422. package/migrations/001_schema.sql +897 -0
  423. package/package.json +57 -26
  424. package/dist/core/PluginLoader.d.ts +0 -20
  425. package/dist/core/PluginLoader.d.ts.map +0 -1
  426. package/dist/core/PluginLoader.js +0 -142
  427. package/dist/core/PluginLoader.js.map +0 -1
  428. package/dist/core/TelemetryChannel.d.ts +0 -37
  429. package/dist/core/TelemetryChannel.d.ts.map +0 -1
  430. package/dist/core/TelemetryChannel.js +0 -80
  431. package/dist/core/TelemetryChannel.js.map +0 -1
  432. package/dist/core/path-decode.d.ts +0 -3
  433. package/dist/core/path-decode.d.ts.map +0 -1
  434. package/dist/core/path-decode.js +0 -9
  435. package/dist/core/path-decode.js.map +0 -1
  436. package/dist/core/plugin-attribution.d.ts +0 -5
  437. package/dist/core/plugin-attribution.d.ts.map +0 -1
  438. package/dist/core/plugin-attribution.js +0 -39
  439. package/dist/core/plugin-attribution.js.map +0 -1
  440. package/dist/core/world-state.d.ts +0 -10
  441. package/dist/core/world-state.d.ts.map +0 -1
  442. package/dist/core/world-state.js +0 -35
  443. package/dist/core/world-state.js.map +0 -1
  444. package/dist/core/world-state.sql +0 -35
  445. package/dist/core/zero-pin.d.ts +0 -3
  446. package/dist/core/zero-pin.d.ts.map +0 -1
  447. package/dist/core/zero-pin.js +0 -16
  448. package/dist/core/zero-pin.js.map +0 -1
  449. package/dist/server/auto.d.ts +0 -6
  450. package/dist/server/auto.d.ts.map +0 -1
  451. package/dist/server/auto.js +0 -63
  452. package/dist/server/auto.js.map +0 -1
  453. package/dist/server/clientTurn.d.ts +0 -6
  454. package/dist/server/clientTurn.d.ts.map +0 -1
  455. package/dist/server/clientTurn.js +0 -22
  456. package/dist/server/clientTurn.js.map +0 -1
  457. package/dist/server/clientTurn.sql +0 -10
  458. package/dist/server/noProposals.d.ts +0 -6
  459. package/dist/server/noProposals.d.ts.map +0 -1
  460. package/dist/server/noProposals.js +0 -37
  461. package/dist/server/noProposals.js.map +0 -1
  462. package/dist/server/version-info.d.ts +0 -14
  463. package/dist/server/version-info.d.ts.map +0 -1
  464. package/dist/server/version-info.js +0 -69
  465. package/dist/server/version-info.js.map +0 -1
  466. package/migrations/0000-00-00.01_schema.sql +0 -536
  467. package/migrations/0004_loop-provider.sql +0 -3
  468. package/migrations/0005_subscription-published-channel.sql +0 -3
  469. package/migrations/0006_loop-max-turns.sql +0 -3
@@ -1,28 +1,31 @@
1
- import { parsePath } from "@plurnk/plurnk-grammar";
1
+ import { parsePath } from "@plurnk/plurnk-contracts";
2
2
  import { Policy } from "@plurnk/plurnk-execs";
3
- import { WebFetcher } from "@plurnk/plurnk-schemes-http";
3
+ import { WebFetcher, WebMaterializationError, } from "@plurnk/plurnk-schemes-http";
4
4
  import WorkspaceSettings from "../core/workspace-settings.js";
5
5
  import EffectPolicy from "./EffectPolicy.js";
6
6
  import EntryOps from "./_entry-ops.js";
7
7
  import EntryCrud from "./_entry-crud.js";
8
8
  import Owner from "../core/Owner.js";
9
- import { foldAuthorityIntoPath } from "../core/plurnk-uri.js";
10
- import { decodePathParens } from "../core/path-decode.js";
11
9
  import EntryFind from "./_entry-find.js";
12
10
  import ChannelWrite from "../core/ChannelWrite.js";
13
11
  import ExecEnv from "./exec-env.js";
14
12
  import ExecAbort from "./exec-abort.js";
15
- import { renderAddress } from "../core/plurnk-uri.js";
13
+ import { entryPathnameOf, renderAddress } from "../core/plurnk-uri.js";
16
14
  import { writeFile, unlink, stat } from "node:fs/promises";
17
15
  import { tmpdir } from "node:os";
18
16
  import { join, resolve } from "node:path";
19
17
  import { CoreSchemeAdapterBase } from "../core/CoreSchemeServices.js";
18
+ import ErrorDetail from "../core/ErrorDetail.js";
19
+ import Results, { OperationFailureError } from "../core/results.js";
20
+ import { InvalidOperationResultError, NetworkAddress } from "@plurnk/plurnk-schemes";
21
+ import DbProjectionCaps from "../core/caps/DbProjectionCaps.js";
22
+ import WorkerControlAddress from "../core/WorkerControlAddress.js";
23
+ import JournalTurn from "../core/JournalTurn.js";
20
24
  // Executors are discovered + probed at boot into ExecutorRegistry and reach
21
- // the scheme through ctx.executors (plurnk-service#181). Each runtime tag
25
+ // the scheme through ctx.executors ({§exec-registry-resolves}). Each runtime tag
22
26
  // resolves to its sibling executor; the scheme itself stays runtime-agnostic.
23
- // The local path a subprocess EXEC's `(target)` slot names — a bare local path or a file:/// URL (both
24
- // decode to a filesystem path). Stat-routed at dispatch (#462): a directory becomes cwd, a file is the
25
- // program/data-source. A plurnk-scheme target is NOT local — schemeTargetOf handles that.
27
+ // Extract the local arm of {§exec-target-routing}; non-file schemes are
28
+ // classified separately by schemeSourceOf.
26
29
  const localPathFromTarget = (target) => {
27
30
  if (target === null)
28
31
  return null;
@@ -33,22 +36,31 @@ const localPathFromTarget = (target) => {
33
36
  }
34
37
  return null;
35
38
  };
36
- // #201 — a plurnk-scheme target (known/exec/log/…), distinct from file/local
37
- // (which localPathFromTarget handles as a path). Its content is resolved at apply-time;
38
- // executors stay scheme-blind (SPEC §5), so the scheme — not the executor — reads it.
39
- const schemeTargetOf = (target) => {
39
+ // A non-file scheme target is distinct from the local path handled above. The
40
+ // consumer resolves its content at apply time; executors stay scheme-blind
41
+ // ({§executor-role}).
42
+ const schemeSourceOf = (target) => {
40
43
  if (target === null || target.kind !== "url")
41
44
  return null;
42
45
  if (target.scheme === null || target.scheme === "file")
43
46
  return null;
44
- return { scheme: target.scheme, pathname: target.pathname, fragment: target.fragment };
47
+ return target.raw;
45
48
  };
49
+ // {§exec-target-routing} — effect classifies the invocation core is admitting,
50
+ // before a scheme-backed source can be materialized. A scheme target with no
51
+ // body becomes the command, so the executor has no target. With a body, the
52
+ // scheme content becomes a target at run time; its authored address is the
53
+ // stable, opaque target-present identity used only for the one effect call.
54
+ const effectTargetOf = (authoredTarget, routedTarget, schemeSource, command) => schemeSource !== null && command.length > 0
55
+ ? authoredTarget?.raw ?? null
56
+ : routedTarget;
46
57
  // EXEC's pathname is <runtime>/<loop_seq>/<turn_seq>/<sequence> (stamped by
47
58
  // Dispatcher.#writeLog). Exec owns this convention, so it — not the client — turns
48
59
  // the pathname into the entry's coordinate, mirrored onto stream payloads so
49
- // waterfall clients read fields instead of parsing the URI (#224). The
60
+ // clients read fields instead of parsing the URI. The
50
61
  // coordinate is the trailing three segments (runtime-agnostic); a pathname that
51
62
  // isn't a numeric triple yields undefined (no coordinate on the wire).
63
+ // {§notifications-stream-event-on-channel-change}, {§notifications-stream-concluded}
52
64
  const coordinateFromPathname = (pathname) => {
53
65
  const seg = pathname.split("/").filter(Boolean);
54
66
  if (seg.length < 3)
@@ -61,7 +73,8 @@ const coordinateFromPathname = (pathname) => {
61
73
  // {§stream-owner-scoped} — resolve a stream statement's authority to the owning worker and hand
62
74
  // back the statement authority-stripped (the storage path is the bare loop coordinate; the owner
63
75
  // rides the owner_id column, never the pathname). Empty authority = the CALLING worker — your own
64
- // streams need no qualifier, so a fan-out sibling's identical coordinate can never be yours (#526).
76
+ // streams need no qualifier, so a fan-out sibling's identical coordinate can never be yours
77
+ // ({§stream-owner-scoped}).
65
78
  // A named authority = that worker's streams, ancestry-gated (reader must be the owner or an
66
79
  // ancestor); an unknown name or unpermitted reader resolves null → the face 404s, no existence leak.
67
80
  export const resolveStreamStatement = async (statement, ctx) => {
@@ -80,18 +93,17 @@ export default class Exec extends CoreSchemeAdapterBase {
80
93
  channels: { stdout: "text/stream", stderr: "text/stream" },
81
94
  defaultChannel: "stdout",
82
95
  category: "data",
83
- scope: "workspace",
84
96
  writableBy: ["model", "client"],
85
97
  volatile: true,
86
98
  modelVisible: true,
87
99
  example: "<<EXEC[sqlite]:SELECT 22.0 / 7.0:EXEC",
88
- documentation: "Runs a command in a runtime — `<<EXEC[runtime](cwd):command:EXEC` — output streams into the worker's `<runtime>:///<loop>/<turn>/<seq>` entry on the runtime's own channels (a subprocess → stdout/stderr; a computational runtime like sqlite/jq → a JSON `results` channel). A host-effecting command proposes for review before it runs; a read-only/pure one runs ungated. Either way you never fetch the output: the engine surfaces each turn's new stream bytes to you automatically — folded while the command runs, opened when it finishes.",
100
+ documentation: "Runs a command in a runtime — `<<EXEC[runtime](target):command:EXEC` — output streams into the worker's `<runtime>:///<loop>/<turn>/<seq>` entry on the runtime's own channels (a subprocess → stdout/stderr; a computational runtime like sqlite/jq → a JSON `results` channel). A host-effecting command proposes for review before it runs; a read-only/pure one runs ungated. Either way you never fetch the output: the engine surfaces each turn's new stream bytes to you automatically — folded while the command runs, opened when it finishes.",
89
101
  flags: {
90
102
  excludedInAsk: true,
91
103
  },
92
104
  };
93
- // The web-fetch the entry sink calls on content:null (§exec-entry-sink / #455). Default = schemes-http's
94
- // guarded WebFetcher over one warm-Chromium pool shared across this handler's
105
+ // The web-fetch the entry sink calls on content:null ({§exec-entry-sink}). Default = schemes-http's
106
+ // checked WebFetcher over one warm-Chromium pool shared across this handler's
95
107
  // fallback renders; injectable so tests substitute the network.
96
108
  #fetchWeb;
97
109
  #closeWebFetcher;
@@ -111,6 +123,11 @@ export default class Exec extends CoreSchemeAdapterBase {
111
123
  #activeSpawns = new Map();
112
124
  async idle() {
113
125
  await Promise.allSettled([...this.#activeSpawns.values()]);
126
+ }
127
+ // {§handler-lifecycle} — idle is the streaming drain barrier; the handler
128
+ // hook owns release of its separate checked-fetch browser pool.
129
+ async close() {
130
+ await this.idle();
114
131
  await this.#closeWebFetcher();
115
132
  }
116
133
  // Whether the worker has an in-flight spawn (a background exec). The daemon
@@ -123,23 +140,16 @@ export default class Exec extends CoreSchemeAdapterBase {
123
140
  return true;
124
141
  return false;
125
142
  }
126
- // §exec-hold-until-concluded — does the worker hold an in-flight spawn whose RUNTIME is in the
127
- // operator's hold set? The turn-hold exception (owner ruling): for streams we know and
128
- // control (the search family — one final JSON digest, seconds-bounded), the engine holds
129
- // the next packet until conclusion instead of giving the model a turn it can only waste.
143
+ // {§exec-hold-until-concluded} — match active spawns against the
144
+ // operator's runtime or runtime:effect hold selectors.
130
145
  hasActiveHoldSpawns(workerId, holdSet) {
131
146
  for (const { workerId: r, runtime, effect } of this.#activeAborts.values())
132
147
  if (r === workerId && (holdSet.has(runtime) || holdSet.has(`${runtime}:${effect}`)))
133
148
  return true;
134
149
  return false;
135
150
  }
136
- // Process-KILL (plurnk-service#203). A running (host/background) exec is
137
- // addressable by its coordinate pathname; KILL aborts that spawn's controller with
138
- // the model's signal — KILL[code] → exactly that signal once (KILL[9] = SIGKILL), a
139
- // bare KILL → the executor's SIGHUP default. The model owns escalation, so there
140
- // is no auto-escalation here. The full #203 status matrix: 200 killed (in-flight) · 410
141
- // killed-earlier (a prior abort closed the stream 499) · 304 already-exited (closed
142
- // with any other terminal status) · 404 unknown (no subscription for that coordinate).
151
+ // {§stream-control} — active KILL routes through the live controller;
152
+ // terminal and missing outcomes resolve from the durable subscription.
143
153
  async kill(pathname, signal, ctx, scheme = "exec") {
144
154
  const core = this.coreContext(ctx);
145
155
  for (const entry of this.#activeAborts.values()) {
@@ -151,32 +161,44 @@ export default class Exec extends CoreSchemeAdapterBase {
151
161
  // Not running — settle the outcome from the closed subscription's status, scoped to the
152
162
  // caller's own subscription (coordinates duplicate across workers, {§stream-owner-scoped}).
153
163
  // The error answers in the model's OWN runtime-tag address (sh:///…), never the retired
154
- // internal `exec` scheme (#527, {§fs-answer-in-canon}) — the model KILLs what it addressed.
155
- const terminal = await ChannelWrite.execTerminalStatus(core.db, { workspaceId: core.workspaceId, workerId: core.workerId, pathname });
156
- if (terminal === null)
157
- return { status: 404, error: `no active stream at ${scheme}://${pathname}` };
158
- if (terminal === 499)
159
- return { status: 410, error: `${scheme}://${pathname} was killed earlier` };
160
- return { status: 304 };
164
+ // internal `exec` machinery ({§fs-answer-in-canon}) — the model KILLs what it addressed.
165
+ const terminal = await ChannelWrite.execTerminalStatus(core.db, {
166
+ workspaceId: core.workspaceId,
167
+ workerId: core.workerId,
168
+ scheme,
169
+ pathname,
170
+ });
171
+ const target = renderAddress(scheme, pathname);
172
+ if (terminal === null) {
173
+ return Results.failure("scheme:exec", "stream-not-found", 404, `No stream exists at ${target}.`, {}, { target });
174
+ }
175
+ if (terminal === 499) {
176
+ return Results.failure("scheme:exec", "stream-already-killed", 410, `Stream ${target} was already killed.`, {}, {
177
+ target,
178
+ retryable: false,
179
+ });
180
+ }
181
+ return Results.failure("scheme:exec", "stream-already-terminal", 409, `${target} already concluded with status ${terminal}.`, {}, {
182
+ target,
183
+ terminalStatus: terminal,
184
+ retryable: false,
185
+ });
161
186
  }
162
187
  // EXEC op handler — the actual model-facing entry point per plurnk.md.
163
- // `<<EXEC[runtime](cwd):command:EXEC` →
164
- // signal=runtime, target=cwd (ParsedPath local/file or null), body=command.
188
+ // `<<EXEC[runtime](target):command:EXEC` →
189
+ // signal=runtime, target=optional source/program/cwd, body=command.
165
190
  //
166
191
  // Proposes (status=202) with attrs={runtime, cwd, command, pathname}.
167
192
  // applyResolution spawns the subprocess; output streams into the
168
193
  // coordinate-stamped <runtime>:///<pathname> entry's stdout/stderr channels
169
- // (e.g. sh:///1/1/2, §exec/#240). The model READs that entry on a subsequent turn.
194
+ // (e.g. sh:///1/1/2, {§exec}). The model READs that entry on a subsequent turn.
170
195
  async exec(statement, ctx) {
171
196
  const core = this.coreContext(ctx);
172
197
  let command = statement.body ?? "";
173
- // #201 — a plurnk-scheme target carries content the scheme resolves at
174
- // apply-time; an empty body is then legal (the target IS the script).
175
- const schemeTarget = schemeTargetOf(statement.target);
176
- // #462 — stat-route the local (target): a DIRECTORY overrides cwd (run the body IN it); a FILE is
177
- // the program/data-source the executor runs (body = stdin). A stat-miss falls to the file arm so the
178
- // runtime reports its own not-found, never a dispatch 400. cwd otherwise = the workspace workspace
179
- // (project_root) — the directory File writes to, and what a data-source target resolves against.
198
+ // Non-file data sources resolve after acceptance. {§exec-target-routing}
199
+ const schemeSource = schemeSourceOf(statement.target);
200
+ // A local directory overrides cwd; every other local path remains the
201
+ // executor target. {§exec-target-routing}
180
202
  const workspaceRow = await core.db.envelope_get_workspace.get({ id: core.workspaceId });
181
203
  const projectRoot = workspaceRow?.project_root ?? null;
182
204
  const localTarget = localPathFromTarget(statement.target);
@@ -190,75 +212,96 @@ export default class Exec extends CoreSchemeAdapterBase {
190
212
  routedTarget = null;
191
213
  }
192
214
  }
193
- catch { /* stat-miss → file arm; the runtime reports its own not-found */ }
215
+ catch (cause) {
216
+ if (cause?.code !== "ENOENT") {
217
+ console.error(`EXEC target classification failed for '${abs}':`, cause);
218
+ return Results.failure("scheme:exec", "target-classification-failed", 500, `EXEC target '${localTarget}' could not be inspected: ${ErrorDetail.preview(cause)}`, {}, {
219
+ target: localTarget,
220
+ stage: "target-classification",
221
+ });
222
+ }
223
+ }
194
224
  }
195
- // Empty body is legal when the target IS the program: a #201 scheme target (the target is the
196
- // script) or a #462 FILE target (run it, no stdin). Empty body with a directory target (nothing
197
- // to run) or no target at all → 400.
198
- if (command.length === 0 && schemeTarget === null && routedTarget === null) {
199
- return { status: 400, error: "EXEC requires a command body (or a scheme target to run)" };
225
+ // An empty body requires a file/program or scheme command source.
226
+ // {§exec-target-routing}
227
+ if (command.length === 0 && schemeSource === null && routedTarget === null) {
228
+ return Results.failure("scheme:exec", "command-required", 400, "EXEC requires a command body or an executable target.", {}, {
229
+ recovery: "Provide a command body or executable target.",
230
+ retryable: false,
231
+ });
200
232
  }
201
233
  const requested = typeof statement.signal === "string" ? statement.signal : "";
202
- let runtime = requested === "" ? "sh" : requested; // empty signal = default shell
234
+ const runtime = requested === "" ? "sh" : requested; // empty signal = default shell
203
235
  if (core.executors === undefined)
204
236
  throw new Error("exec dispatched without an executor registry");
205
- // §exec-runtime-fallthrough (#350, the execs architect's resolution to the go-501 saga):
206
- // an UNREGISTERED tag falls through to the shell with the tag as the command word —
207
- // EXEC[go]:test ./... runs as sh: `go test ./...`. Per-tool runtimes (go/cargo/make/npm)
208
- // never earn tags (owner, execs#21); this automates the principle. The output entry lands
209
- // under sh:// (it ran on sh), telemetry records what models reach FOR (the promotion
210
- // signal is data, not guesswork), and a typo'd tag becomes the shell's own clear 127.
211
- // No new surface: anything expressible as EXEC[foo]:bar was expressible as EXEC[sh]:foo bar.
212
- let fellThroughFrom = null;
213
- if (requested !== "" && core.executors.entry(runtime) === undefined && core.executors.entry("sh") !== undefined) {
214
- fellThroughFrom = runtime;
215
- command = command.length > 0 ? `${runtime} ${command}` : runtime;
216
- runtime = "sh";
217
- }
218
- // #328 — per-workspace client policy narrows the boot-registered set (subtractive). A tag the
219
- // workspace's client layer disables is ABSENT for this workspace — refused like an unavailable
220
- // runtime. Checked on the EFFECTIVE runtime: a fall-through rides sh's gate, so a workspace
221
- // that disabled sh gets the refusal, never a side door.
222
237
  const workspaceExecs = (await WorkspaceSettings.read(core.db, core.workspaceId)).execs;
223
- if (workspaceExecs !== null && !Policy.isEnabled(runtime, workspaceExecs)) {
224
- return { status: 501, error: `\`${runtime}\` is disabled for this workspace by client policy (PLURNK_EXECS_*)` };
225
- }
226
- const resolved = core.executors.entry(runtime); // registry resolves the runtime tag; unknown/unavailable → 501 — §exec-registry-resolves
238
+ // {§exec-registry-resolves} — a non-empty tag selects exactly one registered executable
239
+ // tool. Unknown tags are not reinterpreted as shell command words: that would make the
240
+ // executed command differ from the authored body. Bare EXEC remains the default-shell form.
241
+ const resolved = core.executors.entry(runtime);
227
242
  if (resolved === undefined) {
228
- return { status: 501, error: `\`${runtime}\` is not a configured runtime. available: ${core.executors.availableRuntimes().join(", ")}` };
243
+ const available = core.executors.availableRuntimes()
244
+ .filter((tag) => workspaceExecs === null || Policy.isEnabled(tag, workspaceExecs));
245
+ return Results.failure("scheme:exec", "runtime-not-registered", 501, `Executable tool '${runtime}' is not registered in this workspace.`, {}, {
246
+ requestedRuntime: runtime,
247
+ availableRuntimes: available,
248
+ ...(available.length > 0
249
+ ? {
250
+ recovery: available.includes("sh")
251
+ ? `Use bare EXEC for a shell command or select a registered executable tool: ${available.join(", ")}.`
252
+ : `Select a registered executable tool: ${available.join(", ")}.`,
253
+ }
254
+ : {}),
255
+ retryable: false,
256
+ });
229
257
  }
230
- if (fellThroughFrom !== null) {
231
- core.pushTelemetry?.({ source: "exec:dispatch", kind: "exec_runtime_fallthrough", message: `EXEC[${fellThroughFrom}] fell through to sh`, requested: fellThroughFrom, level: "info" });
258
+ // {§operator-config-workspace-execs} — the workspace layer only narrows
259
+ // the registered set. Bare EXEC resolves to sh before the same gate.
260
+ if (workspaceExecs !== null && !Policy.isEnabled(runtime, workspaceExecs)) {
261
+ const available = core.executors.availableRuntimes()
262
+ .filter((tag) => Policy.isEnabled(tag, workspaceExecs));
263
+ return Results.failure("scheme:exec", "runtime-disabled", 501, `Executable tool '${runtime}' is disabled by workspace policy.`, {}, {
264
+ requestedRuntime: runtime,
265
+ availableRuntimes: available,
266
+ recovery: available.length > 0
267
+ ? `Use an enabled executable tool: ${available.join(", ")}.`
268
+ : "Continue without executing a tool in this workspace.",
269
+ retryable: false,
270
+ });
232
271
  }
233
272
  if (!resolved.available) {
234
- const why = resolved.detail === undefined ? "" : `: ${resolved.detail}`;
235
- return { status: 501, error: `\`${runtime}\` is unavailable${why}` };
273
+ const why = resolved.detail === undefined ? "" : `: ${ErrorDetail.preview(resolved.detail)}`;
274
+ return Results.failure("scheme:exec", "runtime-unavailable", 501, `Executable tool '${runtime}' is unavailable${why}.`, {}, {
275
+ requestedRuntime: runtime,
276
+ retryable: false,
277
+ });
236
278
  }
237
- // The (target) slot the executor receives — its DATA SOURCE / program (jq input, sqlite db, or a
238
- // subprocess program run with the body as stdin; #15). A #462 directory target routed to cwd above
239
- // leaves this null (the body is the command, run in that directory).
279
+ // The local (target) realization the executor receives — its data source
280
+ // or program. A directory routes to cwd and a scheme source is resolved
281
+ // only after acceptance, so either is null here.
240
282
  const target = routedTarget;
241
- // Effect classifies by the target only, never by parsing the command (#289): host → propose,
242
- // read/pure → auto-run inline (plurnk-service#182).
243
- const policy = EffectPolicy.decide(resolved.executor.effect(target, command));
244
- // cwd is the workspace WORKSPACE (project_root) — the directory File writes to and a relative
245
- // data-source target resolves against (execs 0.4.26 §2) — UNLESS a #462 directory target overrode
246
- // it above, in which case the body runs in that directory. A file/data-source target never moves cwd.
283
+ // Derive one effect from the canonical logical target before any policy
284
+ // consumes it, then preserve that fact with the invocation (#107,
285
+ // {§executor-effect}). Leaves never receive authored command text.
286
+ const effectTarget = effectTargetOf(statement.target, target, schemeSource, command);
287
+ const effect = resolved.executor.effect(effectTarget);
288
+ // cwd is the workspace project_root unless target routing selected a
289
+ // directory override. {§exec-target-routing}, {§executor-sinks}
247
290
  // Pathname is assigned by Dispatcher.#writeLog as <runtime>/<loop_seq>/
248
291
  // <turn_seq>/<sequence> (executor-domain + coordinate, e.g. sh/1/1/2).
249
292
  // `pathname` is stamped into attrs at log-write time; applyResolution
250
293
  // reads it back here.
251
294
  // EXEC repurposes the `<L>` slot as `<timeout, poll>` (seconds): mark[0] caps the spawn's
252
- // lifetime, mark[1] sets the hibernation poll-wake cadence (§exec-poll). N>0 → deadline (504);
295
+ // lifetime, mark[1] sets the hibernation poll-wake cadence ({§exec-poll}). N>0 → deadline (504);
253
296
  // -1 / absent → unbounded (loop-life bounded); 0 → turn-scoped (reaped at the next pre-turn,
254
297
  // never surviving into the subsequent turn).
255
298
  const marks = statement.lineMarker?.marks;
256
299
  const timeoutSec = typeof marks?.[0] === "number" && marks[0] > 0 ? Math.floor(marks[0]) : undefined;
257
300
  const turnScoped = typeof marks?.[0] === "number" && marks[0] === 0;
258
- const pollSec = typeof marks?.[1] === "number" && marks[1] > 0 ? Math.floor(marks[1]) : undefined;
301
+ const pollSec = typeof marks?.[1] === "number" && marks[1] >= 0 ? Math.floor(marks[1]) : undefined;
259
302
  const attrs = {
260
- runtime, cwd, command, target, pathname: "", inline: policy === "auto",
261
- ...(schemeTarget !== null ? { schemeTarget } : {}),
303
+ runtime, cwd, command, target, pathname: "", effect,
304
+ ...(schemeSource !== null ? { schemeSource } : {}),
262
305
  ...(timeoutSec !== undefined ? { timeoutSec } : {}),
263
306
  ...(turnScoped ? { turnScoped: true } : {}),
264
307
  ...(pollSec !== undefined ? { pollSec } : {}),
@@ -266,7 +309,7 @@ export default class Exec extends CoreSchemeAdapterBase {
266
309
  // Body shown to client during proposal review — `$ command` is the
267
310
  // most-readable summary regardless of runtime.
268
311
  const preview = runtime !== "" ? `[${runtime}] ${command}` : `$ ${command}`;
269
- return { status: 202, body: preview, attrs }; // host runtime proposes with 202 — §exec-host-proposes
312
+ return { status: 202, body: preview, attrs }; // host runtime proposes with 202 — {§exec-host-proposes}
270
313
  }
271
314
  async applyResolution(args, ctx) {
272
315
  const core = this.coreContext(ctx);
@@ -276,25 +319,42 @@ export default class Exec extends CoreSchemeAdapterBase {
276
319
  const runtime = (typeof attrs.runtime === "string" && attrs.runtime !== "") ? attrs.runtime : "sh";
277
320
  const cwd = (typeof attrs.cwd === "string" && attrs.cwd.length > 0) ? attrs.cwd : null;
278
321
  let target = (typeof attrs.target === "string" && attrs.target.length > 0) ? attrs.target : null;
322
+ const effect = attrs.effect;
279
323
  if (typeof pathname !== "string" || pathname.length === 0) {
280
- return { status: 500, outcome: "missing_pathname" };
324
+ throw new InvalidOperationResultError("The accepted EXEC proposal is missing its stream pathname.");
325
+ }
326
+ if (!EffectPolicy.isEffect(effect)) {
327
+ throw new InvalidOperationResultError("The accepted EXEC proposal is missing its canonical effect fact.");
281
328
  }
282
- // #201 — resolve a scheme-URI target to content (executors stay scheme-blind).
283
- // Empty body → the resolved content IS the command (run a stored script).
284
- // Non-empty body → materialize the content to a temp file whose path becomes
285
- // the runtime's data-source TARGET (the input for filters/sqlite/wasm).
329
+ // Resolve a scheme target after acceptance: empty body uses the content
330
+ // as the command; otherwise a temporary file becomes the data target.
331
+ // {§exec-target-routing}
286
332
  let tempPath = null;
287
- if (attrs.schemeTarget !== undefined) {
288
- const { scheme, pathname: tPath, fragment } = attrs.schemeTarget;
289
- const read = await EntryCrud.readEntry(tPath, core, scheme);
290
- if (read.entry === null)
291
- return { status: 404, outcome: "scheme_target_not_found" };
292
- const channels = read.entry.channels;
293
- const channelName = fragment ?? (channels.body !== undefined ? "body" : Object.keys(channels)[0]);
294
- const content = channelName === undefined ? undefined : channels[channelName]?.content;
295
- // §channel-selection-unknown-channel-400 sibling fact — the miss names what exists.
296
- if (content === undefined)
297
- return { status: 404, outcome: "scheme_target_channel_not_found", error: `no channel #${channelName ?? fragment} at ${scheme}:///${tPath.replace(/^\//, "")}; channels: ${Object.keys(channels).join(", ")}` };
333
+ if (attrs.schemeSource !== undefined) {
334
+ const sourceTarget = parsePath(attrs.schemeSource);
335
+ if (sourceTarget?.kind !== "url" || sourceTarget.scheme === null || sourceTarget.scheme === "file") {
336
+ throw new InvalidOperationResultError("The accepted EXEC proposal has an invalid scheme source address.");
337
+ }
338
+ const read = await this.readExecSource({
339
+ op: "READ",
340
+ suffix: "",
341
+ signal: null,
342
+ target: sourceTarget,
343
+ lineMarker: null,
344
+ body: null,
345
+ position: { line: 0, column: 0 },
346
+ }, core);
347
+ if (read.status >= 400) {
348
+ return Results.assert({ ...read, outcome: "scheme_source_read_failed" });
349
+ }
350
+ const content = read.content;
351
+ if (typeof content !== "string") {
352
+ return Results.failure("scheme:exec", "source-content-unavailable", 422, `Scheme '${sourceTarget.scheme}' did not supply content for the EXEC source.`, { outcome: "scheme_source_content_unavailable" }, {
353
+ scheme: sourceTarget.scheme,
354
+ sourceStatus: read.status,
355
+ retryable: false,
356
+ });
357
+ }
298
358
  if (command.length === 0) {
299
359
  command = content;
300
360
  }
@@ -304,25 +364,26 @@ export default class Exec extends CoreSchemeAdapterBase {
304
364
  target = tempPath;
305
365
  }
306
366
  }
307
- // #500 — the accept-half mirrors the propose-half's #462 stat-route: an empty body with a
308
- // LOCAL FILE target is legal (the target IS the program — the executor runs it as its script
309
- // positional, transient exec per the owner ruling). Empty body with no target of any kind
310
- // remains the contradiction.
367
+ // {§exec-target-routing} — a local file target is itself the program, so
368
+ // its body may be empty; no target and no command remains invalid.
311
369
  if (command.length === 0 && target === null) {
312
- return { status: 500, outcome: "missing_command" };
370
+ if (attrs.schemeSource !== undefined) {
371
+ return Results.failure("scheme:exec", "source-command-empty", 422, "The EXEC source resolved to an empty command.", { outcome: "scheme_source_command_empty" }, { retryable: false });
372
+ }
373
+ throw new InvalidOperationResultError("The accepted EXEC proposal has neither a command nor a target.");
313
374
  }
314
375
  // Resolve the runtime's executor from the boot registry, then seed
315
- // channels from its declared topology (Q1(b) in plurnk-service#174 —
316
- // executor declares, scheme honors). Each executor declares its own
376
+ // channels from its declared topology ({§executor-channels}). Each executor declares its own
317
377
  // shape (subprocess → stdout/stderr; search → results; etc.).
318
- if (core.executors === undefined)
319
- return { status: 500, outcome: "no_executor_registry" };
378
+ if (core.executors === undefined) {
379
+ throw new InvalidOperationResultError("An accepted EXEC proposal has no executor registry.");
380
+ }
320
381
  const resolved = core.executors.entry(runtime);
321
- if (resolved === undefined)
322
- return { status: 500, outcome: "no_executor" };
323
- // #485 — the per-tool effect (execs Effect: read/host/pure) rides the hold predicate so a
324
- // suffixed PLURNK_SERVICE_EXEC_HOLD entry (`github:read`) can hold one tool-class and not another.
325
- const effect = resolved.executor.effect(target, command);
382
+ if (resolved === undefined) {
383
+ throw new InvalidOperationResultError(`The '${runtime}' executor disappeared after its EXEC proposal.`);
384
+ }
385
+ // {§executor-effect}, {§exec-hold-until-concluded}, #107: the admitted
386
+ // effect fact rides the hold predicate unchanged through application.
326
387
  const seedChannels = {};
327
388
  for (const [name, decl] of Object.entries(resolved.executor.channels)) {
328
389
  seedChannels[name] = {
@@ -332,16 +393,23 @@ export default class Exec extends CoreSchemeAdapterBase {
332
393
  };
333
394
  }
334
395
  const seed = { channels: seedChannels, tags: [] };
335
- // §exec — the stream entry's scheme IS the runtime tag (sh/node), so it addresses by
396
+ // {§exec} — the stream entry's scheme IS the runtime tag (sh/node), so it addresses by
336
397
  // tag authority (sh:///l/t/s). The engine registers each runtime tag → this handler.
337
398
  const { entryId } = await EntryCrud.writeEntry(pathname, seed, core, runtime, core.workerId);
338
- if (entryId === null)
339
- return { status: 500, outcome: "entry_write_failed" };
399
+ if (entryId === null) {
400
+ return Results.failure("scheme:exec", "stream-entry-write-failed", 500, `The ${runtime} stream entry could not be created.`, {
401
+ outcome: "entry_write_failed",
402
+ }, {
403
+ runtime,
404
+ stage: "stream-creation",
405
+ retryable: false,
406
+ });
407
+ }
340
408
  const subscriptionId = await ChannelWrite.openSubscription(core.db, {
341
409
  workerId: core.workerId, entryId, scheme: runtime,
342
410
  handle: runtime !== "" ? `${runtime}: ${command}` : command,
343
- pollSeconds: typeof attrs.pollSec === "number" ? attrs.pollSec : null, // §exec-poll — hibernation wake cadence
344
- turnScoped: attrs.turnScoped === true, // §exec-poll — `<0>` reaped at the next pre-turn
411
+ pollSeconds: typeof attrs.pollSec === "number" ? attrs.pollSec : null, // {§exec-poll} — hibernation wake cadence
412
+ turnScoped: attrs.turnScoped === true, // {§exec-poll} — `<0>` reaped at the next pre-turn
345
413
  });
346
414
  const controller = new AbortController();
347
415
  let unlink = () => { };
@@ -354,7 +422,7 @@ export default class Exec extends CoreSchemeAdapterBase {
354
422
  // then re-check `aborted`: a listener added to an already-aborted signal never
355
423
  // fires, so a check-then-attach order LOSES an abort that lands in the gap (R1's
356
424
  // TOCTOU leak). Attach-then-check closes it; controller.abort is idempotent, so a
357
- // doubled fire is harmless. §exec-timeout
425
+ // doubled fire is harmless. {§exec-timeout}
358
426
  const onParentAbort = () => controller.abort(ExecAbort.teardownReason());
359
427
  parent.addEventListener("abort", onParentAbort, { once: true });
360
428
  unlink = () => parent.removeEventListener("abort", onParentAbort);
@@ -371,18 +439,19 @@ export default class Exec extends CoreSchemeAdapterBase {
371
439
  entryId, subscriptionId, signal: controller.signal, controller, tempPath,
372
440
  timeoutSec: typeof attrs.timeoutSec === "number" ? attrs.timeoutSec : null,
373
441
  });
374
- // Every exec backgrounds + streams (§exec-stream): no same-turn receipt — the output
442
+ // Every exec backgrounds + streams ({§exec-stream}): no same-turn receipt — the output
375
443
  // surfaces as the environment-observation injector's delta on the next turn (folded while
376
- // it runs, opened when it finishes). Pure/read commands still auto-accept (attrs.inline =
377
- // no human gate); they just resolve a turn later, uniformly with host streams.
444
+ // it runs, opened when it finishes). Pure/read commands still auto-accept
445
+ // from the preserved effect fact; they resolve a turn later, uniformly
446
+ // with host streams.
378
447
  this.#activeSpawns.set(subscriptionId, tail);
379
448
  return { status: 200, outcome: "started" };
380
449
  }
381
450
  // Bridge the executor's sink-style contract (write/setState/emit)
382
451
  // onto plurnk-service's storage primitives (appendToChannel,
383
- // setChannelState, ctx.pushTelemetry). Per plurnk-service#174 Q3,
384
- // executor TelemetryEvents flow through the same engine path as
385
- // grammar parse_errors — emit → buffer → next packet + live notify.
452
+ // setChannelState, ctx.pushNotice). Under {§executor-results},
453
+ // executor Notices flow through the same engine path as
454
+ // grammar parse advisories: emit, buffer, next packet, and live notify.
386
455
  //
387
456
  // write() and setState() callbacks must run in emission order:
388
457
  // appendToChannel reads channel state AFTER the append commits, so
@@ -392,7 +461,7 @@ export default class Exec extends CoreSchemeAdapterBase {
392
461
  async #runExecutor(opts) {
393
462
  const { executor, runtime, command, cwd, target, ctx, pathname, entryId, subscriptionId, signal, controller, timeoutSec, tempPath } = opts;
394
463
  const db = ctx.db;
395
- const coordinate = coordinateFromPathname(pathname); // #224 — stamped on stream/event + stream/concluded
464
+ const coordinate = coordinateFromPathname(pathname);
396
465
  // grammar 0.74.20 EXEC `<T>` — kill the spawn after T seconds. unref'd so a pending timer never
397
466
  // holds the process open; cleared in finally so a spawn that finishes first leaves no timer.
398
467
  let timedOut = false;
@@ -404,216 +473,255 @@ export default class Exec extends CoreSchemeAdapterBase {
404
473
  const enqueue = (op) => {
405
474
  queue = queue.then(op, op);
406
475
  };
407
- let closeStatus = 500;
408
- let exitLabel = "spawn_failed";
476
+ let result = Results.failure("scheme:exec", "executor-did-not-conclude", 500, `The '${runtime}' executor did not produce a terminal result.`, {}, {
477
+ runtime,
478
+ stage: "execution",
479
+ retryable: false,
480
+ });
481
+ let exitLabel = "did not conclude";
409
482
  let stdoutLength = 0;
410
483
  let stderrLength = 0;
411
- // §exec-entry-sink (#340) — the executor's entry() materialization request. The executor
412
- // owns zero substrate: it hands us (path, content, {tags, mimetype}) and WE create/update
413
- // the entry (writeEntry upsert; tags UNIONED — writeEntry alone replaces), then narrate ONE
414
- // EDIT row in the reserved plurnk worker's log (the fs-fiction pattern, source = the calling
415
- // run) — the existing env-delta ambience folds it into every worker's next packet. The row is a
416
- // FULL fiction: tx carries the statement (body = the written content — the journal records
417
- // the write, replay/fork-complete), rx carries the span (§edit-result-render, the whole
418
- // content numbered — a wholesale write's span IS the content; no diff, which would be a
419
- // pathological cost against a rewritten multi-MB page). Rendered folded by default, so no
420
- // body rides a packet uninvited — the meta line carries the honest OPEN weight.
421
- // Serialized: parallel entry() calls (allSettled) write in order; a rejection prunes that
422
- // survivor executor-side without breaking the chain. Lazy narration context: one plurnk-run
423
- // turn per spawn, not per entry.
484
+ // {§exec-entry-sink} {§env-delta-entry-materialization} — serialize
485
+ // executor entry() materializations and narrate them through the one
486
+ // reserved-worker turn owned by this spawn.
424
487
  let entryChain = Promise.resolve();
425
488
  let narration = null;
489
+ let callerSource;
490
+ const resolveCallerSource = async () => {
491
+ if (callerSource !== undefined)
492
+ return callerSource;
493
+ const caller = await db.worker_name_by_id.get({ worker_id: ctx.workerId });
494
+ if (caller === undefined)
495
+ throw new Error(`entry(): calling worker ${ctx.workerId} does not exist`);
496
+ callerSource = WorkerControlAddress.render(caller.name);
497
+ return callerSource;
498
+ };
426
499
  const entrySink = (path, content, opts) => {
427
500
  const parsed = parsePath(path);
428
- if (parsed === null || parsed.kind !== "url" || parsed.scheme === null)
501
+ if (parsed === null || parsed.kind !== "url")
429
502
  return Promise.reject(new Error(`entry(): '${path.slice(0, 80)}' is not a URL`));
430
503
  if (content !== null && opts.mimetype === undefined)
431
504
  return Promise.reject(new Error("entry(): mimetype is required when content is provided"));
432
- // §exec-entry-sink / #455 — content:null ⇒ core fetches the page through schemes-http's guarded
433
- // primitive. The fetch STARTS HERE, OFF the write-serialization chain, so concurrent entry() calls
434
- // fetch in PARALLEL (owner ruling: search fetches must not freeze the agent); only the entry WRITE
435
- // serializes on entryChain (db-write ordering). A null fetch is dead (guard-refused / unreachable /
436
- // non-2xx / non-textual / empty) and REJECTS, so the executor prunes that survivor. Non-null content
437
- // is the materialize-given-body path — the caller already holds the bytes and states their mimetype.
438
- const materialized = content === null
439
- ? this.#fetchWeb(path, { signal })
440
- : Promise.resolve({ body: content, mimetype: opts.mimetype });
505
+ const address = NetworkAddress.supports(parsed.scheme) ? NetworkAddress.from(parsed) : null;
506
+ if (address?.hasCredentials === true)
507
+ return Promise.reject(new Error("entry(): network URL userinfo is not allowed"));
508
+ const fetchAddress = address !== null && (address.scheme === "http" || address.scheme === "https")
509
+ ? address
510
+ : null;
511
+ const pathname = address?.pathname ?? entryPathnameOf(parsed);
512
+ const scheme = address?.scheme ?? parsed.scheme;
513
+ // {§exec-entry-sink}/{§web-search-retrieval} — start content:null
514
+ // acquisition before the write chain so fetches run in parallel;
515
+ // only durable entry writes serialize. A null result rejects the sink.
516
+ let materialized;
517
+ if (content === null) {
518
+ if (fetchAddress === null)
519
+ return Promise.reject(new Error("entry(): content:null requires an http(s):// URL"));
520
+ materialized = this.#fetchWeb(fetchAddress.url, { signal });
521
+ }
522
+ else {
523
+ materialized = Promise.resolve({ body: content, mimetype: opts.mimetype });
524
+ }
441
525
  const op = async () => {
442
526
  const fetched = await materialized;
443
527
  if (fetched === null)
444
528
  throw new Error(`entry(): '${path.slice(0, 80)}' is dead`);
445
- let { body, mimetype } = fetched;
446
- // External URLs arrive in transport-safe spelling, while entry identity uses
447
- // the grammar's canonical resolved path. Store the decoded identity; renderers
448
- // encode parentheses again when the address returns to the model.
449
- const pathname = decodePathParens(foldAuthorityIntoPath(parsed.hostname, parsed.pathname));
450
- const prior = await EntryCrud.readEntry(pathname, ctx, parsed.scheme);
451
- const tags = [...new Set([...(prior.entry?.tags ?? []), ...opts.tags])];
452
- // The web-fetch entry point: a fetched html page stores the handler's readable
453
- // projection as the decisive `body` (text/markdown — what READ serves, FIND matches,
454
- // FTS indexes, every weight reports) with the raw page under `html` (xpath + archive).
455
- // Scoped HERE, not writeEntry: only auto-fetched web content projects; authored files
456
- // stay verbatim (a `<user email=…>` roster's attribute data must survive a default READ).
457
- let channels = { body: { content: body, mimetype } };
458
- if (fetched.header !== undefined)
459
- channels.header = { content: fetched.header, mimetype: "text/plain" };
460
- let decisive = body;
461
- if (mimetype === "text/html") {
462
- if (ctx.mimetypes === undefined)
463
- throw new Error("entry(): HTML materialization requires the mimetype registry");
464
- let projected = (await ctx.mimetypes.process({ content: body, hint: "text/html" }, { channels: ["content"] })).content;
465
- if ((typeof projected !== "string" || projected.length === 0) && fetched.render !== undefined) {
466
- const rendered = await fetched.render();
467
- if (rendered !== null) {
468
- body = rendered.body;
469
- mimetype = rendered.mimetype;
470
- projected = (await ctx.mimetypes.process({ content: body, hint: "text/html" }, { channels: ["content"] })).content;
471
- }
472
- }
473
- if (typeof projected !== "string" || projected.length === 0) {
474
- throw new Error(`entry(): '${path.slice(0, 80)}' has no readable HTML projection`);
529
+ let web;
530
+ try {
531
+ web = await WebFetcher.materialize(fetched, new DbProjectionCaps(ctx));
532
+ }
533
+ catch (error) {
534
+ if (!signal.aborted && error instanceof WebMaterializationError) {
535
+ console.error("entry() web materialization failed", { path, error });
475
536
  }
476
- channels = {
477
- body: { content: projected, mimetype: "text/markdown" },
478
- html: { content: body, mimetype },
479
- ...(fetched.header === undefined ? {} : { header: { content: fetched.header, mimetype: "text/plain" } }),
480
- };
481
- decisive = projected;
537
+ throw error;
482
538
  }
483
- const written = await EntryCrud.writeEntry(pathname, { channels, tags }, ctx, parsed.scheme);
539
+ if (web === null)
540
+ throw new Error(`entry(): '${path.slice(0, 80)}' has no readable projection`);
541
+ const prior = await EntryCrud.readEntry(pathname, ctx, scheme);
542
+ const tags = [...new Set([...(prior.entry?.tags ?? []), ...opts.tags])];
543
+ // {§exec-entry-sink}/{§html-materialization} The shared
544
+ // materializer owns the decisive projection and its provenance.
545
+ const channels = {
546
+ body: web.body,
547
+ ...(web.html === undefined ? {} : { html: web.html }),
548
+ ...(web.header === undefined ? {} : { header: { content: web.header, mimetype: "text/plain" } }),
549
+ };
550
+ const decisive = web.body.content;
551
+ const source = web.html?.content ?? decisive;
552
+ const causalSource = await resolveCallerSource();
553
+ const written = Results.assert(await EntryCrud.writeEntry(pathname, { channels, tags }, ctx, scheme));
484
554
  if (narration === null) {
485
- const run = await db.envelope_get_worker_by_name.get({ workspace_id: ctx.workspaceId, name: "plurnk" })
555
+ const worker = await db.envelope_get_worker_by_name.get({ workspace_id: ctx.workspaceId, name: "plurnk" })
486
556
  ?? await db.envelope_insert_worker.get({ workspace_id: ctx.workspaceId, name: "plurnk", origin: "plurnk" });
487
- if (run === undefined)
557
+ if (worker === undefined)
488
558
  throw new Error("entry(): plurnk worker resolution returned no row");
489
- const loop = await db.envelope_insert_client_loop.get({ worker_id: run.id });
559
+ const loop = await db.envelope_insert_client_loop.get({ worker_id: worker.id });
490
560
  if (loop === undefined)
491
561
  throw new Error("entry(): loop insert returned no row");
492
- const seqRow = await db.client_turn_next_sequence.get({ loop_id: loop.id });
493
- const turn = await db.client_turn_insert.get({ loop_id: loop.id, sequence: seqRow?.next ?? 1, packet: "{}" });
494
- if (turn === undefined)
495
- throw new Error("entry(): turn insert returned no row");
496
- narration = { workerId: run.id, loopId: loop.id, turnId: turn.id, seq: 1 };
562
+ const turn = await JournalTurn.insert(db, loop.id);
563
+ narration = {
564
+ workerId: worker.id,
565
+ loopId: loop.id,
566
+ loopSeq: loop.sequence,
567
+ turnId: turn.id,
568
+ turnSeq: turn.sequence,
569
+ seq: 1,
570
+ };
571
+ }
572
+ const sequence = narration.seq++;
573
+ if (written.problem !== undefined) {
574
+ Results.attachInstance(written, `log:///${narration.loopSeq}/${narration.turnSeq}/${sequence}/EDIT`);
497
575
  }
498
576
  await db.engine_insert_log_entry.get({
499
- worker_id: narration.workerId, loop_id: narration.loopId, turn_id: narration.turnId, sequence: narration.seq++,
577
+ worker_id: narration.workerId, loop_id: narration.loopId, turn_id: narration.turnId, sequence,
500
578
  // signal carries the tags — the SAME slot a model's EDIT[tags] uses, so the
501
579
  // ambient row renders its tags natively everywhere (packet meta line, digest).
502
- origin: "plurnk", source: String(ctx.workerId), op: "EDIT", suffix: "", signal: JSON.stringify(tags),
503
- scheme: parsed.scheme, username: null, password: null, hostname: null, port: null,
504
- pathname, params: null, fragment: null, lineMarker: null,
505
- tx: JSON.stringify({ op: "EDIT", body }), mimetype_tx: "application/json",
506
- rx: JSON.stringify({
507
- status: written.status, entryId: written.entryId, tags,
508
- span: decisive.split("\n").map((l, n) => `${n + 1}:${l}`).join("\n"),
509
- }), mimetype_rx: "application/json",
580
+ origin: "plurnk", source: causalSource, op: "EDIT", suffix: "", signal: JSON.stringify(tags),
581
+ scheme, username: null, password: null, hostname: null, port: null,
582
+ pathname, query: null, fragment: null, lineMarker: null,
583
+ tx: JSON.stringify({ op: "EDIT", body: source }), mimetype_tx: "application/json",
584
+ rx: JSON.stringify(written.problem === undefined
585
+ ? {
586
+ ...written,
587
+ tags,
588
+ span: decisive.split("\n").map((l, n) => `${n + 1}:${l}`).join("\n"),
589
+ }
590
+ : written),
591
+ mimetype_rx: "application/json",
510
592
  status_rx: written.status, tokens: ctx.tokenize?.(decisive) ?? 0, state: "resolved", outcome: null,
511
593
  // Durable provenance for clients/forensics. This is machine
512
594
  // ambience, not a human/model action waterfall item.
513
595
  attrs: JSON.stringify({ tags, kind: "entry_materialized" }),
514
596
  });
515
- return renderAddress(parsed.scheme, pathname);
597
+ if (written.problem !== undefined)
598
+ throw new OperationFailureError(written);
599
+ return renderAddress(scheme, pathname);
516
600
  };
517
601
  const run = entryChain.then(op, op);
518
602
  entryChain = run.then(() => undefined, () => undefined);
519
603
  return run;
520
604
  };
521
605
  try {
522
- let result = null;
523
606
  try {
524
- result = await executor.run({
607
+ const reported = await executor.run({
525
608
  runtime, command, cwd, target, signal,
526
609
  entry: entrySink,
527
- env: ExecEnv.scoped(), // SPEC §exec {§exec-env-scoped} — never plurnk's own secrets
610
+ env: ExecEnv.scoped(), // SPEC {§exec} {§exec-env-scoped} — never plurnk's own secrets
528
611
  write: (channel, chunk) => enqueue(() => ChannelWrite.appendToChannel(db, {
529
612
  entryId, channel, chunk, notify: ctx.streamEventNotify, coordinate,
530
613
  })),
531
614
  setState: (channel, state) => enqueue(() => ChannelWrite.setChannelState(db, {
532
615
  entryId, channel, state, notify: ctx.streamEventNotify, coordinate,
533
616
  })),
534
- emit: (event) => {
535
- // The executor plugin's TelemetryEvent predates grammar's required `level`;
536
- // inject a default (forwarding the producer's own severity when it supplies one). #276
537
- const level = event.level ?? "info";
538
- ctx.pushTelemetry?.({ ...event, level });
539
- },
617
+ emit: (event) => ctx.pushNotice?.(event),
540
618
  });
541
619
  // Drain the queue so the subscription doesn't close before
542
620
  // final chunk events / state transitions have committed.
543
621
  await queue;
622
+ try {
623
+ result = Results.assert(reported);
624
+ }
625
+ catch (cause) {
626
+ console.error(`Executor '${runtime}' returned an invalid operation result:`, cause);
627
+ result = Results.failure("scheme:exec", "executor-invalid-result", 500, `The '${runtime}' executor returned an invalid operation result.`, {}, {
628
+ runtime,
629
+ stage: "result-validation",
630
+ retryable: false,
631
+ });
632
+ }
544
633
  }
545
634
  catch (cause) {
546
635
  // A rejecting driver must still CONCLUDE its stream — uncaught, the subscription sat
547
636
  // open forever and the floating spawn promise was an unhandled rejection.
548
- exitLabel = `driver_crashed: ${cause instanceof Error ? cause.message : String(cause)}`;
637
+ console.error(`Executor '${runtime}' threw outside its operation result contract:`, cause);
638
+ result = Results.failure("scheme:exec", "executor-threw", 500, `The '${runtime}' executor failed outside its operation result contract.`, {}, {
639
+ runtime,
640
+ stage: "execution",
641
+ retryable: false,
642
+ });
549
643
  }
550
- if (result !== null) {
551
- const exitCode = result.exitCode ?? -1;
552
- closeStatus = result.status;
553
- // A timeout aborts the spawn → the executor reports 499; restamp it 504 so the model
554
- // sees "ran out of time" distinct from a deliberate kill/cancel (§exec-timeout).
555
- if (timedOut && closeStatus === 499)
556
- closeStatus = 504;
557
- // The service's own abort knowledge outranks a driver's claim: a spawn we reaped
558
- // (teardown/kill/cancel) did not succeed, whatever status it resolved under abort.
559
- if (signal.aborted && !timedOut && closeStatus < 400) {
560
- closeStatus = 499;
561
- exitLabel = "reaped";
562
- }
563
- else
564
- exitLabel = closeStatus === 504 ? `timed out after ${timeoutSec}s`
565
- : closeStatus === 499 ? "aborted"
566
- : closeStatus === 500 && exitCode === -1 ? "spawn_failed"
567
- : `exit ${exitCode}`;
644
+ const exitCode = typeof result.exitCode === "number" ? result.exitCode : null;
645
+ // A timeout aborts the spawn → the executor reports 499; replace the
646
+ // complete result so status and Problem remain one valid truth.
647
+ if (timedOut) {
648
+ result = Results.failure("scheme:exec", "execution-timeout", 504, `Execution of '${runtime}' exceeded its ${timeoutSec}-second deadline.`, exitCode === null ? {} : { exitCode }, {
649
+ runtime,
650
+ timeoutSeconds: timeoutSec,
651
+ stage: "execution",
652
+ retryable: false,
653
+ });
654
+ // The service's own abort knowledge outranks a driver's claim: a
655
+ // spawn we reaped did not succeed, whatever it resolved under abort.
568
656
  }
569
- await ChannelWrite.closeSubscription(db, { subscriptionId, status: closeStatus });
657
+ else if (signal.aborted && result.status < 400) {
658
+ result = Results.failure("scheme:exec", "execution-cancelled", 499, `Execution of '${runtime}' was cancelled by the service.`, exitCode === null ? {} : { exitCode }, {
659
+ runtime,
660
+ stage: "execution",
661
+ retryable: false,
662
+ });
663
+ }
664
+ exitLabel = timedOut
665
+ ? `timed out after ${timeoutSec}s`
666
+ : result.status === 499
667
+ ? "aborted"
668
+ : exitCode !== null
669
+ ? `exit ${exitCode}`
670
+ : result.problem?.title.toLowerCase() ?? "completed";
671
+ await ChannelWrite.closeSubscription(db, { subscriptionId, result });
570
672
  const stdoutMeta = await db.channel_meta.get({ entry_id: entryId, channel: "stdout" });
571
673
  const stderrMeta = await db.channel_meta.get({ entry_id: entryId, channel: "stderr" });
572
674
  stdoutLength = stdoutMeta?.contentLength ?? 0;
573
675
  stderrLength = stderrMeta?.contentLength ?? 0;
574
676
  }
575
677
  finally {
576
- // §exec-entry-sink — drain the entry()/narration writes so the tail (hence idle()) is a
577
- // COMPLETE quiescence barrier: a consumer woken below, or a teardown awaiting idle(), must
578
- // not race an in-flight entry() write into a closing db (#432 teardown race). Each op is
579
- // enqueued as `.then(op, op)`, so entryChain never rejects — awaiting it in finally is safe.
678
+ // {§exec-entry-sink} — the spawn tail owns every serialized entry/narration write.
580
679
  await entryChain;
581
680
  if (timeoutTimer !== null)
582
681
  clearTimeout(timeoutTimer); // a finished spawn leaves no pending timer
583
- // #201 — a materialized data-source temp file outlives the spawn it fed;
584
- // unlink it once the worker settles (open-unlink is safe on Linux).
585
- if (tempPath !== null)
586
- await unlink(tempPath).catch(() => { });
682
+ // {§exec-source-temporary} — cleanup cannot rewrite the settled
683
+ // executor result, but an exceptional failure remains observable.
684
+ if (tempPath !== null) {
685
+ await unlink(tempPath).catch((cause) => {
686
+ console.error(`EXEC source temporary cleanup failed for '${tempPath}':`, cause);
687
+ });
688
+ }
587
689
  this.#activeAborts.get(subscriptionId)?.unlink();
588
690
  this.#activeAborts.delete(subscriptionId);
589
691
  this.liveSubscriptions().unregister(subscriptionId);
590
692
  this.#activeSpawns.delete(subscriptionId);
591
- // Every worker backgrounds now (§exec-stream) — wake a parked loop on completion so the
592
- // run resumes to the turn where the stream's terminal delta surfaces.
693
+ // Every worker backgrounds now ({§exec-stream}) — wake a parked loop on completion so the
694
+ // worker resumes to the turn where the stream's terminal delta surfaces.
593
695
  if (ctx.wakeWorkerNotify !== undefined) {
594
696
  ctx.wakeWorkerNotify({
595
697
  workspaceId: ctx.workspaceId, workerId: ctx.workerId,
596
- entryId, target: `${runtime}://${pathname}`, subscriptionId, closeStatus,
698
+ entryId, target: `${runtime}://${pathname}`, subscriptionId, result,
597
699
  scheme: runtime,
598
700
  summary: `${runtime}://${pathname} completed (${exitLabel}); stdout=${stdoutLength} bytes, stderr=${stderrLength} bytes`,
599
701
  ...coordinate,
600
702
  });
601
703
  }
602
704
  }
603
- return closeStatus;
705
+ return result;
604
706
  }
605
707
  async read(statement, ctx) {
606
708
  const core = this.coreContext(ctx);
607
709
  const owner = await resolveStreamStatement(statement, core);
608
- if (owner === null)
609
- return { status: 404, content: null, mimetype: null, channel: null };
710
+ if (owner === null) {
711
+ return Results.failure("scheme:exec", "stream-not-found", 404, "No visible stream exists at the requested address.", {
712
+ content: null, mimetype: null, channel: null,
713
+ });
714
+ }
610
715
  return EntryOps.readWorkspaceEntry(owner.statement, core, Exec.manifest, owner.ownerId);
611
716
  }
612
717
  async find(statement, ctx) {
613
718
  const core = this.coreContext(ctx);
614
719
  const owner = await resolveStreamStatement(statement, core);
615
- if (owner === null)
616
- return { status: 404, content: null, mimetype: null, results: [], itemsTokenTotal: 0, pathnames: [], matches: [] };
720
+ if (owner === null) {
721
+ return Results.failure("scheme:exec", "stream-not-found", 404, "No visible stream exists at the requested address.", {
722
+ content: null, mimetype: null, results: [], itemsTokenTotal: 0, pathnames: [], matches: [],
723
+ });
724
+ }
617
725
  return EntryFind.findWorkspaceEntries(owner.statement, core, Exec.manifest, owner.ownerId);
618
726
  }
619
727
  async readEntry(pathname, ctx) {