@narumitw/pi-sync 0.70.7 → 0.71.1

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 (734) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/README.md +33 -106
  3. package/dist/chunks/agent-plan-A6CS3XXA.ts +337 -0
  4. package/dist/chunks/agent-plan-A6CS3XXA.ts.map +7 -0
  5. package/dist/chunks/chunk-2BMTS5OW.ts +229 -0
  6. package/dist/chunks/chunk-2BMTS5OW.ts.map +7 -0
  7. package/dist/chunks/chunk-2G6GTIWW.ts +188 -0
  8. package/dist/chunks/chunk-2G6GTIWW.ts.map +7 -0
  9. package/dist/chunks/chunk-2YHXXWUF.ts +18 -0
  10. package/dist/chunks/chunk-2YHXXWUF.ts.map +7 -0
  11. package/dist/chunks/chunk-3GL7LBNB.ts +3 -0
  12. package/dist/chunks/chunk-3M3KQFSQ.ts +215 -0
  13. package/dist/chunks/chunk-3M3KQFSQ.ts.map +7 -0
  14. package/dist/chunks/chunk-3PFWVSV3.ts +3 -0
  15. package/dist/chunks/chunk-4S5CGN4M.ts +54 -0
  16. package/dist/chunks/chunk-4S5CGN4M.ts.map +7 -0
  17. package/dist/chunks/{chunk-H7VOTY5N.ts → chunk-53AFFVTT.ts} +2 -24
  18. package/dist/chunks/{chunk-H7VOTY5N.ts.map → chunk-53AFFVTT.ts.map} +1 -1
  19. package/dist/chunks/chunk-53IKSWLZ.ts +3 -0
  20. package/dist/chunks/{chunk-ZWP6HAYV.ts → chunk-5ERTMRNE.ts} +1 -1
  21. package/dist/chunks/chunk-5ERTMRNE.ts.map +7 -0
  22. package/dist/chunks/chunk-5WUWHDCJ.ts +12 -0
  23. package/dist/chunks/chunk-5WUWHDCJ.ts.map +7 -0
  24. package/dist/chunks/{chunk-WRS3SUNZ.ts → chunk-6VGQ6THO.ts} +8 -10
  25. package/dist/chunks/{chunk-WRS3SUNZ.ts.map → chunk-6VGQ6THO.ts.map} +1 -1
  26. package/dist/chunks/chunk-6WVJIIXQ.ts +154 -0
  27. package/dist/chunks/chunk-6WVJIIXQ.ts.map +7 -0
  28. package/dist/chunks/chunk-A3NEEVNA.ts +3 -0
  29. package/dist/chunks/chunk-A7KJUFLX.ts +2120 -0
  30. package/dist/chunks/chunk-A7KJUFLX.ts.map +7 -0
  31. package/dist/chunks/{chunk-4A34OGXY.ts → chunk-AA2G3HTW.ts} +12 -16
  32. package/dist/chunks/{chunk-4A34OGXY.ts.map → chunk-AA2G3HTW.ts.map} +1 -1
  33. package/dist/chunks/chunk-AITZUACB.ts +3 -0
  34. package/dist/chunks/chunk-AVLYLWA7.ts +1414 -0
  35. package/dist/chunks/chunk-AVLYLWA7.ts.map +7 -0
  36. package/dist/chunks/chunk-B4JNUYZ2.ts +12 -0
  37. package/dist/chunks/chunk-B4JNUYZ2.ts.map +7 -0
  38. package/dist/chunks/chunk-BEO3THWZ.ts +3 -0
  39. package/dist/chunks/chunk-BEO3THWZ.ts.map +7 -0
  40. package/dist/chunks/chunk-C2YD64T6.ts +167 -0
  41. package/dist/chunks/chunk-C2YD64T6.ts.map +7 -0
  42. package/dist/chunks/chunk-C66HLRRZ.ts +72 -0
  43. package/dist/chunks/chunk-C66HLRRZ.ts.map +7 -0
  44. package/dist/chunks/chunk-CFXAA65U.ts +53 -0
  45. package/dist/chunks/chunk-CFXAA65U.ts.map +7 -0
  46. package/dist/chunks/chunk-D34Y5JSL.ts +152 -0
  47. package/dist/chunks/chunk-D34Y5JSL.ts.map +7 -0
  48. package/dist/chunks/chunk-D3DMJSFU.ts +125 -0
  49. package/dist/chunks/chunk-D3DMJSFU.ts.map +7 -0
  50. package/dist/chunks/chunk-DFC3WJP5.ts +3 -0
  51. package/dist/chunks/chunk-DFC3WJP5.ts.map +7 -0
  52. package/dist/chunks/chunk-DH52CVRD.ts +2499 -0
  53. package/dist/chunks/chunk-DH52CVRD.ts.map +7 -0
  54. package/dist/chunks/chunk-DLA5RPFP.ts +50 -0
  55. package/dist/chunks/chunk-DLA5RPFP.ts.map +7 -0
  56. package/dist/chunks/chunk-ES4FIIHZ.ts +50 -0
  57. package/dist/chunks/chunk-ES4FIIHZ.ts.map +7 -0
  58. package/dist/chunks/chunk-ESUMO4TW.ts +55 -0
  59. package/dist/chunks/chunk-ESUMO4TW.ts.map +7 -0
  60. package/dist/chunks/chunk-FIEW5453.ts +77 -0
  61. package/dist/chunks/chunk-FIEW5453.ts.map +7 -0
  62. package/dist/chunks/chunk-FT45DX6E.ts +163 -0
  63. package/dist/chunks/chunk-FT45DX6E.ts.map +7 -0
  64. package/dist/chunks/chunk-G7U6BPP4.ts +137 -0
  65. package/dist/chunks/chunk-G7U6BPP4.ts.map +7 -0
  66. package/dist/chunks/{chunk-5BE6LBDC.ts → chunk-GC5XDUVA.ts} +25 -34
  67. package/dist/chunks/{chunk-5BE6LBDC.ts.map → chunk-GC5XDUVA.ts.map} +3 -3
  68. package/dist/chunks/{chunk-VERMBZGL.ts → chunk-GDA35HWZ.ts} +12 -14
  69. package/dist/chunks/{chunk-VERMBZGL.ts.map → chunk-GDA35HWZ.ts.map} +1 -1
  70. package/dist/chunks/chunk-HOFEC5FH.ts +54 -0
  71. package/dist/chunks/chunk-HOFEC5FH.ts.map +7 -0
  72. package/dist/chunks/{chunk-WE3KJ7JS.ts → chunk-IFJXUHHC.ts} +7 -7
  73. package/dist/chunks/chunk-INUH2UXN.ts +53 -0
  74. package/dist/chunks/chunk-INUH2UXN.ts.map +7 -0
  75. package/dist/chunks/chunk-JPLT2DG6.ts +122 -0
  76. package/dist/chunks/chunk-JPLT2DG6.ts.map +7 -0
  77. package/dist/chunks/chunk-KDTDGAOM.ts +76 -0
  78. package/dist/chunks/chunk-KDTDGAOM.ts.map +7 -0
  79. package/dist/chunks/chunk-LBDUDSHD.ts +3 -0
  80. package/dist/chunks/chunk-LBDUDSHD.ts.map +7 -0
  81. package/dist/chunks/{chunk-VQTYTUBU.ts → chunk-LHQIQIWL.ts} +4 -22
  82. package/dist/chunks/chunk-LHQIQIWL.ts.map +7 -0
  83. package/dist/chunks/chunk-MHERAG42.ts +150 -0
  84. package/dist/chunks/chunk-MHERAG42.ts.map +7 -0
  85. package/dist/chunks/chunk-MS6HLJFR.ts +61 -0
  86. package/dist/chunks/chunk-MS6HLJFR.ts.map +7 -0
  87. package/dist/chunks/{chunk-AXN3B5KC.ts → chunk-MTUR4H7S.ts} +31 -41
  88. package/dist/chunks/chunk-MTUR4H7S.ts.map +7 -0
  89. package/dist/chunks/chunk-NFW5HLKA.ts +84 -0
  90. package/dist/chunks/chunk-NFW5HLKA.ts.map +7 -0
  91. package/dist/chunks/chunk-NFZMKZ2D.ts +345 -0
  92. package/dist/chunks/chunk-NFZMKZ2D.ts.map +7 -0
  93. package/dist/chunks/chunk-OTI4XVCS.ts +618 -0
  94. package/dist/chunks/chunk-OTI4XVCS.ts.map +7 -0
  95. package/dist/chunks/chunk-QIL27OLJ.ts +28 -0
  96. package/dist/chunks/chunk-QIL27OLJ.ts.map +7 -0
  97. package/dist/chunks/chunk-QJTU5SCJ.ts +27 -0
  98. package/dist/chunks/chunk-QJTU5SCJ.ts.map +7 -0
  99. package/dist/chunks/chunk-QNU4RFCN.ts +225 -0
  100. package/dist/chunks/chunk-QNU4RFCN.ts.map +7 -0
  101. package/dist/chunks/chunk-QRSESWT2.ts +26 -0
  102. package/dist/chunks/chunk-QRSESWT2.ts.map +7 -0
  103. package/dist/chunks/chunk-RFJWUIV5.ts +1622 -0
  104. package/dist/chunks/chunk-RFJWUIV5.ts.map +7 -0
  105. package/dist/chunks/chunk-RRFW2UAD.ts +347 -0
  106. package/dist/chunks/chunk-RRFW2UAD.ts.map +7 -0
  107. package/dist/chunks/chunk-SD3D6BTF.ts +3 -0
  108. package/dist/chunks/chunk-SD3D6BTF.ts.map +7 -0
  109. package/dist/chunks/chunk-SPRHJBJC.ts +17 -0
  110. package/dist/chunks/chunk-SPRHJBJC.ts.map +7 -0
  111. package/dist/chunks/chunk-T22OVZSI.ts +347 -0
  112. package/dist/chunks/chunk-T22OVZSI.ts.map +7 -0
  113. package/dist/chunks/chunk-TAOYC2YG.ts +113 -0
  114. package/dist/chunks/chunk-TAOYC2YG.ts.map +7 -0
  115. package/dist/chunks/chunk-U6CORBHU.ts +205 -0
  116. package/dist/chunks/chunk-U6CORBHU.ts.map +7 -0
  117. package/dist/chunks/chunk-ULNEZ53E.ts +105 -0
  118. package/dist/chunks/chunk-ULNEZ53E.ts.map +7 -0
  119. package/dist/chunks/chunk-UPP54ATP.ts +3 -0
  120. package/dist/chunks/chunk-UPP54ATP.ts.map +7 -0
  121. package/dist/chunks/chunk-V66NV2HZ.ts +70 -0
  122. package/dist/chunks/chunk-V66NV2HZ.ts.map +7 -0
  123. package/dist/chunks/chunk-W3YS4Y2Q.ts +545 -0
  124. package/dist/chunks/chunk-W3YS4Y2Q.ts.map +7 -0
  125. package/dist/chunks/chunk-WETDHZAD.ts +815 -0
  126. package/dist/chunks/chunk-WETDHZAD.ts.map +7 -0
  127. package/dist/chunks/chunk-WT2722L4.ts +61 -0
  128. package/dist/chunks/chunk-WT2722L4.ts.map +7 -0
  129. package/dist/chunks/chunk-XHJ3AVIT.ts +12 -0
  130. package/dist/chunks/chunk-XHJ3AVIT.ts.map +7 -0
  131. package/dist/chunks/{chunk-HFMGK6A6.ts → chunk-YLVRV6NM.ts} +5 -5
  132. package/dist/chunks/chunk-YV776ZPN.ts +49 -0
  133. package/dist/chunks/chunk-YV776ZPN.ts.map +7 -0
  134. package/dist/chunks/chunk-YVHXQZIH.ts +411 -0
  135. package/dist/chunks/chunk-YVHXQZIH.ts.map +7 -0
  136. package/dist/chunks/chunk-ZWJMVLQ3.ts +3 -0
  137. package/dist/chunks/chunk-ZWJMVLQ3.ts.map +7 -0
  138. package/dist/chunks/chunk-ZWOKNJDT.ts +25 -0
  139. package/dist/chunks/chunk-ZWOKNJDT.ts.map +7 -0
  140. package/dist/chunks/{command-handler-DWWFIXSC.ts → command-handler-SMARANCT.ts} +128 -155
  141. package/dist/chunks/command-handler-SMARANCT.ts.map +7 -0
  142. package/dist/chunks/{chunk-LNZRNXNQ.ts → config-PUZS2ZBP.ts} +15 -6
  143. package/dist/chunks/config-PUZS2ZBP.ts.map +7 -0
  144. package/dist/chunks/conflict-artifacts-77PI6IXK.ts +33 -0
  145. package/dist/chunks/conflict-artifacts-77PI6IXK.ts.map +7 -0
  146. package/dist/chunks/conflict-review-HHGVL5TP.ts +188 -0
  147. package/dist/chunks/conflict-review-HHGVL5TP.ts.map +7 -0
  148. package/dist/chunks/conflict-review-OO57TGMR.ts +40 -0
  149. package/dist/chunks/conflict-review-OO57TGMR.ts.map +7 -0
  150. package/dist/chunks/continuous-record-QIIFQNKP.ts +277 -0
  151. package/dist/chunks/continuous-record-QIIFQNKP.ts.map +7 -0
  152. package/dist/chunks/debug-check-ETFFIDW5.ts +14 -0
  153. package/dist/chunks/debug-check-ETFFIDW5.ts.map +7 -0
  154. package/dist/chunks/debug-log-QGBO6XHF.ts +17 -0
  155. package/dist/chunks/debug-log-QGBO6XHF.ts.map +7 -0
  156. package/dist/chunks/debug-tool-execution-AIQAGPMJ.ts +95 -0
  157. package/dist/chunks/debug-tool-execution-AIQAGPMJ.ts.map +7 -0
  158. package/dist/chunks/{diff-review-GB4NO53B.ts → diff-review-QRHOHG5C.ts} +12 -5
  159. package/dist/chunks/diff-review-QRHOHG5C.ts.map +7 -0
  160. package/dist/chunks/{file-selection-DGC5UJVI.ts → file-selection-ZEBPDRHG.ts} +33 -16
  161. package/dist/chunks/{file-selection-DGC5UJVI.ts.map → file-selection-ZEBPDRHG.ts.map} +1 -1
  162. package/dist/chunks/git-backend-I2IJ5ULJ.ts +1151 -0
  163. package/dist/chunks/git-backend-I2IJ5ULJ.ts.map +7 -0
  164. package/dist/chunks/initialization-XGYWRNPQ.ts +106 -0
  165. package/dist/chunks/initialization-XGYWRNPQ.ts.map +7 -0
  166. package/dist/chunks/local-diff-review-OGZM3TA7.ts +525 -0
  167. package/dist/chunks/local-diff-review-OGZM3TA7.ts.map +7 -0
  168. package/dist/chunks/local-fields-PIKOEXWR.ts +31 -0
  169. package/dist/chunks/local-fields-PIKOEXWR.ts.map +7 -0
  170. package/dist/chunks/manager-result-dispatcher-72YGSLHL.ts +42 -0
  171. package/dist/chunks/manager-result-dispatcher-72YGSLHL.ts.map +7 -0
  172. package/dist/chunks/{manager-ui-3CQU37XY.ts → manager-ui-5SXPS4SE.ts} +130 -92
  173. package/dist/chunks/manager-ui-5SXPS4SE.ts.map +7 -0
  174. package/dist/chunks/merge-baseline-store-MI7SHGDH.ts +26 -0
  175. package/dist/chunks/merge-baseline-store-MI7SHGDH.ts.map +7 -0
  176. package/dist/chunks/merge-journal-46QC5N7D.ts +38 -0
  177. package/dist/chunks/merge-journal-46QC5N7D.ts.map +7 -0
  178. package/dist/chunks/{merge-review-DXSERTCK.ts → merge-review-RMDYVNBK.ts} +2 -2
  179. package/dist/chunks/remote-selection-ui-4BXJAZUD.ts +41 -0
  180. package/dist/chunks/remote-selection-ui-4BXJAZUD.ts.map +7 -0
  181. package/dist/chunks/s3-backend-ZRMOWH5R.ts +866 -0
  182. package/dist/chunks/s3-backend-ZRMOWH5R.ts.map +7 -0
  183. package/dist/chunks/session-push-55IV4IW3.ts +101 -0
  184. package/dist/chunks/session-push-55IV4IW3.ts.map +7 -0
  185. package/dist/chunks/setup-switch-DXDUBDQI.ts +43 -0
  186. package/dist/chunks/setup-switch-DXDUBDQI.ts.map +7 -0
  187. package/dist/chunks/{setup-wizard-FRIR2EOR.ts → setup-wizard-ICPQERAE.ts} +34 -18
  188. package/dist/chunks/{setup-wizard-FRIR2EOR.ts.map → setup-wizard-ICPQERAE.ts.map} +1 -1
  189. package/dist/chunks/{snapshot-ZUJJZCFW.ts → snapshot-HDARHOQZ.ts} +14 -8
  190. package/dist/chunks/snapshot-HDARHOQZ.ts.map +7 -0
  191. package/dist/chunks/snapshot-LZ6XKFA4.ts +63 -0
  192. package/dist/chunks/snapshot-LZ6XKFA4.ts.map +7 -0
  193. package/dist/chunks/snapshot-transaction-LYR5OFLR.ts +27 -0
  194. package/dist/chunks/snapshot-transaction-LYR5OFLR.ts.map +7 -0
  195. package/dist/chunks/sync-inspection-N6TELULU.ts +29 -0
  196. package/dist/chunks/sync-inspection-N6TELULU.ts.map +7 -0
  197. package/dist/chunks/sync-inspection-PMEXXLDK.ts +26 -0
  198. package/dist/chunks/sync-inspection-PMEXXLDK.ts.map +7 -0
  199. package/dist/chunks/sync-operations-KKSIS2CI.ts +69 -0
  200. package/dist/chunks/sync-operations-KKSIS2CI.ts.map +7 -0
  201. package/dist/chunks/sync-operations-VSMA5GSA.ts +47 -0
  202. package/dist/chunks/sync-operations-VSMA5GSA.ts.map +7 -0
  203. package/dist/chunks/{sync-state-QIT64TKV.ts → sync-state-72ZDKUQW.ts} +13 -5
  204. package/dist/chunks/sync-state-72ZDKUQW.ts.map +7 -0
  205. package/dist/chunks/{sync-state-store-TZE7XDV5.ts → sync-state-store-YTMAZQ3Z.ts} +8 -2
  206. package/dist/chunks/sync-state-store-YTMAZQ3Z.ts.map +7 -0
  207. package/dist/chunks/webdav-backend-3AZOECVQ.ts +948 -0
  208. package/dist/chunks/webdav-backend-3AZOECVQ.ts.map +7 -0
  209. package/dist/index.ts +271 -478
  210. package/dist/index.ts.map +4 -4
  211. package/docs/agent-continuous-hardening.md +3 -1
  212. package/docs/agent-quality-verification.md +3 -1
  213. package/docs/continuous-sync-verification.md +1 -1
  214. package/docs/daemon-migration.md +3 -1
  215. package/docs/daemon-retirement.md +15 -0
  216. package/docs/merge-implementation-audit.md +2 -0
  217. package/docs/settings-merge-audit.md +1 -1
  218. package/docs/tui-contract.md +12 -14
  219. package/package.json +5 -7
  220. package/skills/configure-pi-sync/SKILL.md +14 -60
  221. package/skills/configure-pi-sync/references/configuration.md +38 -46
  222. package/src/backends/backend-factory.ts +2 -2
  223. package/src/backends/backend-identity.ts +2 -2
  224. package/src/backends/backend-types.ts +1 -1
  225. package/src/backends/git/git-backend.ts +2 -2
  226. package/src/backends/git/git-config.ts +2 -2
  227. package/src/backends/git/git-runner.ts +2 -2
  228. package/src/backends/git/git-storage.ts +2 -2
  229. package/src/backends/s3/s3-backend.ts +2 -2
  230. package/src/backends/s3/s3-client.ts +2 -2
  231. package/src/backends/s3/s3-conditions.ts +2 -2
  232. package/src/backends/snapshot-pointer.ts +2 -2
  233. package/src/backends/sync-backend.ts +2 -2
  234. package/src/backends/webdav/webdav-backend.ts +2 -2
  235. package/src/backends/webdav/webdav-client.ts +2 -2
  236. package/src/backends/webdav/webdav-config.ts +2 -2
  237. package/src/commands/command-execution.ts +66 -62
  238. package/src/commands/command-handler.ts +3 -10
  239. package/src/commands/command-types.ts +1 -0
  240. package/src/commands/command.ts +3 -24
  241. package/src/engine/backends/backend-factory.ts +23 -0
  242. package/src/engine/backends/backend-identity.ts +40 -0
  243. package/src/engine/backends/backend-types.ts +75 -0
  244. package/src/engine/backends/git/git-backend.ts +863 -0
  245. package/src/engine/backends/git/git-config.ts +130 -0
  246. package/src/engine/backends/git/git-runner.ts +260 -0
  247. package/src/engine/backends/git/git-storage.ts +295 -0
  248. package/src/engine/backends/publication-encoding.ts +19 -0
  249. package/src/engine/backends/s3/s3-backend.ts +528 -0
  250. package/src/engine/backends/s3/s3-client.ts +398 -0
  251. package/src/engine/backends/s3/s3-conditions.ts +64 -0
  252. package/src/engine/backends/snapshot-pointer.ts +26 -0
  253. package/src/engine/backends/sync-backend.ts +133 -0
  254. package/src/engine/backends/webdav/webdav-backend.ts +691 -0
  255. package/src/engine/backends/webdav/webdav-client.ts +390 -0
  256. package/src/engine/backends/webdav/webdav-config.ts +82 -0
  257. package/src/engine/commands/command-types.ts +37 -0
  258. package/src/engine/debug-check.ts +83 -0
  259. package/src/engine/debug-log.ts +272 -0
  260. package/src/engine/diff-review-types.ts +16 -0
  261. package/src/engine/foreground-transfer.ts +15 -0
  262. package/src/engine/host.ts +95 -0
  263. package/src/engine/paths.ts +90 -0
  264. package/src/engine/record.ts +3 -0
  265. package/src/engine/settings/config-errors.ts +6 -0
  266. package/src/engine/settings/config-file.ts +907 -0
  267. package/src/engine/settings/config.ts +315 -0
  268. package/src/engine/settings/retired-ignore-policy.ts +15 -0
  269. package/src/engine/settings/retired-ignore-recovery.ts +18 -0
  270. package/src/engine/settings/settings-management.ts +261 -0
  271. package/src/engine/settings/settings-store.ts +48 -0
  272. package/src/engine/settings/settings-types.ts +164 -0
  273. package/src/engine/settings/settings-validation.ts +472 -0
  274. package/src/engine/snapshot/session-paths.ts +179 -0
  275. package/src/engine/snapshot/snapshot-apply.ts +443 -0
  276. package/src/engine/snapshot/snapshot-bounds.ts +23 -0
  277. package/src/engine/snapshot/snapshot-capture-limit.ts +110 -0
  278. package/src/engine/snapshot/snapshot-case-replacement.ts +77 -0
  279. package/src/engine/snapshot/snapshot-codec.ts +69 -0
  280. package/src/engine/snapshot/snapshot-difference.ts +25 -0
  281. package/src/engine/snapshot/snapshot-entry-projection.ts +101 -0
  282. package/src/engine/snapshot/snapshot-exclude-safety.ts +203 -0
  283. package/src/engine/snapshot/snapshot-mutation-queues.ts +152 -0
  284. package/src/engine/snapshot/snapshot-paths.ts +11 -0
  285. package/src/engine/snapshot/snapshot-payload.ts +50 -0
  286. package/src/engine/snapshot/snapshot-reviewed-preimages.ts +68 -0
  287. package/src/engine/snapshot/snapshot-root-transition.ts +170 -0
  288. package/src/engine/snapshot/snapshot-transaction-directory.ts +16 -0
  289. package/src/engine/snapshot/snapshot-transaction-images.ts +424 -0
  290. package/src/engine/snapshot/snapshot-transaction-plan.ts +69 -0
  291. package/src/engine/snapshot/snapshot-transaction-policy.ts +278 -0
  292. package/src/engine/snapshot/snapshot-transaction-stage.ts +342 -0
  293. package/src/engine/snapshot/snapshot-transaction-verification.ts +109 -0
  294. package/src/engine/snapshot/snapshot-transaction.ts +961 -0
  295. package/src/engine/snapshot/snapshot-types.ts +67 -0
  296. package/src/engine/snapshot/snapshot.ts +847 -0
  297. package/src/engine/state/json-file.ts +46 -0
  298. package/src/engine/state/lock.ts +421 -0
  299. package/src/engine/state/lockfile-fs.ts +25 -0
  300. package/src/engine/state/merge-baseline-store.ts +213 -0
  301. package/src/engine/state/mutation-directory-sync.ts +33 -0
  302. package/src/engine/state/operation-availability.ts +59 -0
  303. package/src/engine/state/state-directory.ts +245 -0
  304. package/src/engine/state/state-types.ts +26 -0
  305. package/src/engine/state/sync-state-store.ts +77 -0
  306. package/src/engine/sync/agent-candidate.ts +252 -0
  307. package/src/engine/sync/agent-plan.ts +114 -0
  308. package/{dist/daemon/dist/engine/sync/agent-policy.js → src/engine/sync/agent-policy.ts} +5 -3
  309. package/src/engine/sync/agent-refusal-retry.ts +53 -0
  310. package/src/engine/sync/agent-request.ts +17 -0
  311. package/src/engine/sync/agent-runner.ts +208 -0
  312. package/src/engine/sync/agent-store.ts +175 -0
  313. package/src/engine/sync/agent-sync.ts +145 -0
  314. package/src/engine/sync/apply-review.ts +63 -0
  315. package/src/engine/sync/conflict-artifact-ownership.ts +58 -0
  316. package/src/engine/sync/conflict-artifacts.ts +193 -0
  317. package/src/engine/sync/conflict-groups.ts +67 -0
  318. package/src/engine/sync/conflict-preview.ts +54 -0
  319. package/src/engine/sync/conflict-resolution.ts +93 -0
  320. package/src/engine/sync/conflict-retention.ts +71 -0
  321. package/src/engine/sync/conflict-review.ts +95 -0
  322. package/src/engine/sync/content-conflicts.ts +73 -0
  323. package/src/engine/sync/continuous-errors.ts +91 -0
  324. package/src/engine/sync/continuous-lease.ts +213 -0
  325. package/src/engine/sync/continuous-record.ts +255 -0
  326. package/src/engine/sync/continuous-storage.ts +63 -0
  327. package/src/engine/sync/continuous-sync.ts +646 -0
  328. package/src/engine/sync/continuous-watch.ts +123 -0
  329. package/src/engine/sync/diff-review-capture.ts +259 -0
  330. package/src/engine/sync/diff-review-preview.ts +111 -0
  331. package/src/engine/sync/diff-review-store.ts +72 -0
  332. package/src/engine/sync/directional-action.ts +169 -0
  333. package/src/engine/sync/directional-conflict.ts +53 -0
  334. package/src/engine/sync/exclude-policy.ts +88 -0
  335. package/src/engine/sync/field-migration.ts +39 -0
  336. package/src/engine/sync/file-merge-planner.ts +138 -0
  337. package/src/engine/sync/initialization.ts +81 -0
  338. package/src/engine/sync/json-document.ts +179 -0
  339. package/src/engine/sync/local-field-policy.ts +28 -0
  340. package/src/engine/sync/local-fields.ts +171 -0
  341. package/src/engine/sync/merge-acceptance.ts +56 -0
  342. package/src/engine/sync/merge-apply.ts +585 -0
  343. package/src/engine/sync/merge-journal.ts +259 -0
  344. package/src/engine/sync/merge-transfer-error.ts +68 -0
  345. package/src/engine/sync/merged-sync.ts +912 -0
  346. package/src/engine/sync/mutation-owner.ts +22 -0
  347. package/src/engine/sync/package-merge.ts +81 -0
  348. package/src/engine/sync/partial-progress.ts +56 -0
  349. package/src/engine/sync/pull-outcome.ts +16 -0
  350. package/src/engine/sync/push-review.ts +47 -0
  351. package/src/engine/sync/remote-snapshot.ts +185 -0
  352. package/src/engine/sync/resolver-stream.ts +34 -0
  353. package/src/engine/sync/session-merge.ts +192 -0
  354. package/src/engine/sync/session-push.ts +68 -0
  355. package/src/engine/sync/settings-conflicts.ts +64 -0
  356. package/src/engine/sync/settings-merge.ts +118 -0
  357. package/src/engine/sync/signals.ts +8 -0
  358. package/src/engine/sync/startup-recovery-evidence.ts +37 -0
  359. package/src/engine/sync/startup-timings.ts +135 -0
  360. package/src/engine/sync/sync-decision.ts +134 -0
  361. package/src/engine/sync/sync-error-guidance.ts +56 -0
  362. package/src/engine/sync/sync-errors.ts +50 -0
  363. package/src/engine/sync/sync-inspection.ts +61 -0
  364. package/src/engine/sync/sync-loaders.ts +14 -0
  365. package/src/engine/sync/sync-local.ts +117 -0
  366. package/src/engine/sync/sync-mutations.ts +940 -0
  367. package/src/engine/sync/sync-operations.ts +10 -0
  368. package/src/engine/sync/sync-policy.ts +695 -0
  369. package/src/engine/sync/sync-queries.ts +404 -0
  370. package/src/engine/sync/sync-rollback.ts +245 -0
  371. package/src/engine/sync/sync-state.ts +197 -0
  372. package/src/engine/sync/text-merge.ts +132 -0
  373. package/src/engine/sync/transfer-freshness.ts +151 -0
  374. package/src/engine/sync/transfer-size-limits.ts +100 -0
  375. package/src/engine/types.ts +45 -0
  376. package/src/engine/ui/merge-review.ts +14 -0
  377. package/src/engine/ui/merged-sync-summary.ts +111 -0
  378. package/src/engine/ui/sync-format.ts +222 -0
  379. package/src/engine/ui/sync-status.ts +29 -0
  380. package/src/engine/ui/terminal-text.ts +9 -0
  381. package/src/engine/ui/transfer-changes.ts +32 -0
  382. package/src/engine/ui/transfer-review.ts +28 -0
  383. package/src/paths.ts +2 -2
  384. package/src/runtime/identity.ts +152 -0
  385. package/src/runtime/legacy-owner.ts +223 -0
  386. package/src/runtime/lifecycle.ts +17 -0
  387. package/src/runtime/local-host.ts +157 -0
  388. package/src/{daemon/session-presence.ts → runtime/session-presence-binding.ts} +1 -2
  389. package/src/runtime/session-presence.ts +258 -0
  390. package/src/settings/config-errors.ts +2 -2
  391. package/src/settings/config-file.ts +2 -2
  392. package/src/settings/config.ts +2 -2
  393. package/src/settings/settings-management.ts +2 -2
  394. package/src/settings/settings-store.ts +2 -2
  395. package/src/settings/settings-types.ts +1 -1
  396. package/src/settings/settings-validation.ts +2 -2
  397. package/src/snapshot/session-paths.ts +2 -2
  398. package/src/snapshot/snapshot-apply.ts +2 -2
  399. package/src/snapshot/snapshot-case-replacement.ts +2 -2
  400. package/src/snapshot/snapshot-codec.ts +2 -2
  401. package/src/snapshot/snapshot-exclude-safety.ts +2 -2
  402. package/src/snapshot/snapshot-mutation-queues.ts +2 -2
  403. package/src/snapshot/snapshot-paths.ts +2 -2
  404. package/src/snapshot/snapshot-root-transition.ts +2 -2
  405. package/src/snapshot/snapshot-transaction-directory.ts +2 -2
  406. package/src/snapshot/snapshot-transaction-plan.ts +2 -2
  407. package/src/snapshot/snapshot-transaction.ts +2 -2
  408. package/src/snapshot/snapshot-types.ts +1 -1
  409. package/src/snapshot/snapshot.ts +2 -2
  410. package/src/state/json-file.ts +2 -2
  411. package/src/state/lock-policy.ts +2 -2
  412. package/src/state/lock.ts +2 -2
  413. package/src/state/lockfile-fs.ts +2 -2
  414. package/src/state/merge-baseline-store.ts +2 -2
  415. package/src/state/mutation-directory-sync.ts +2 -2
  416. package/src/state/operation-availability.ts +2 -2
  417. package/src/state/state-directory.ts +2 -2
  418. package/src/state/state-types.ts +1 -1
  419. package/src/state/sync-state-store.ts +2 -2
  420. package/src/sync/agent-candidate.ts +2 -2
  421. package/src/sync/agent-plan.ts +2 -2
  422. package/src/sync/agent-policy.ts +2 -2
  423. package/src/sync/agent-refusal-retry.ts +2 -2
  424. package/src/sync/agent-request.ts +2 -2
  425. package/src/sync/agent-runner.ts +2 -2
  426. package/src/sync/agent-store.ts +2 -2
  427. package/src/sync/agent-sync.ts +2 -2
  428. package/src/sync/apply-review.ts +2 -2
  429. package/src/sync/automatic-sync.ts +58 -120
  430. package/src/sync/conflict-artifact-ownership.ts +2 -2
  431. package/src/sync/conflict-artifacts.ts +2 -2
  432. package/src/sync/conflict-groups.ts +2 -2
  433. package/src/sync/conflict-preview.ts +2 -2
  434. package/src/sync/conflict-resolution.ts +2 -2
  435. package/src/sync/conflict-retention.ts +2 -2
  436. package/src/sync/conflict-review.ts +5 -2
  437. package/src/sync/content-conflicts.ts +2 -2
  438. package/src/sync/continuous-errors.ts +2 -2
  439. package/src/sync/continuous-lease.ts +2 -2
  440. package/src/sync/continuous-record.ts +2 -2
  441. package/src/sync/continuous-storage.ts +2 -2
  442. package/src/sync/continuous-sync.ts +2 -2
  443. package/src/sync/continuous-watch.ts +2 -2
  444. package/src/sync/debug-tool-execution.ts +21 -22
  445. package/src/sync/debug-tool.ts +10 -12
  446. package/src/sync/exclude-policy.ts +2 -2
  447. package/src/sync/field-migration.ts +2 -2
  448. package/src/sync/file-merge-planner.ts +2 -2
  449. package/src/sync/json-document.ts +2 -2
  450. package/src/sync/local-diff-review.ts +115 -0
  451. package/src/sync/local-field-policy.ts +2 -2
  452. package/src/sync/local-fields.ts +2 -2
  453. package/src/sync/local-recovery.ts +53 -0
  454. package/src/sync/merge-apply.ts +2 -2
  455. package/src/sync/merge-journal.ts +2 -2
  456. package/src/sync/merge-transfer-error.ts +2 -2
  457. package/src/sync/merged-sync.ts +2 -2
  458. package/src/sync/mutation-owner.ts +2 -2
  459. package/src/sync/package-merge.ts +2 -2
  460. package/src/sync/partial-progress.ts +2 -2
  461. package/src/sync/remote-snapshot.ts +2 -2
  462. package/src/sync/session-merge.ts +2 -2
  463. package/src/sync/settings-conflicts.ts +2 -2
  464. package/src/sync/settings-merge.ts +2 -2
  465. package/src/sync/signals.ts +2 -2
  466. package/src/sync/startup-timings.ts +2 -2
  467. package/src/sync/sync-decision.ts +2 -2
  468. package/src/sync/sync-error-guidance.ts +2 -2
  469. package/src/sync/sync-errors.ts +2 -2
  470. package/src/sync/sync-inspection.ts +46 -11
  471. package/src/sync/sync-local.ts +2 -2
  472. package/src/sync/sync-mutations.ts +2 -2
  473. package/src/sync/sync-operations.ts +143 -33
  474. package/src/sync/sync-policy.ts +2 -2
  475. package/src/sync/sync-queries.ts +2 -2
  476. package/src/sync/sync-state.ts +2 -2
  477. package/src/sync/text-merge.ts +2 -2
  478. package/src/sync-extension.ts +170 -340
  479. package/src/ui/cancellable-operation.ts +1 -1
  480. package/src/ui/diff-review.ts +4 -3
  481. package/src/ui/manager-ui.ts +2 -22
  482. package/dist/chunks/chunk-6YKOHBSC.ts +0 -18
  483. package/dist/chunks/chunk-6YKOHBSC.ts.map +0 -7
  484. package/dist/chunks/chunk-A43CJYG4.ts +0 -26
  485. package/dist/chunks/chunk-A43CJYG4.ts.map +0 -7
  486. package/dist/chunks/chunk-APZVJAEW.ts +0 -34
  487. package/dist/chunks/chunk-APZVJAEW.ts.map +0 -7
  488. package/dist/chunks/chunk-AXN3B5KC.ts.map +0 -7
  489. package/dist/chunks/chunk-GELYN4UC.ts +0 -14
  490. package/dist/chunks/chunk-GELYN4UC.ts.map +0 -7
  491. package/dist/chunks/chunk-HCXPNKPU.ts +0 -1553
  492. package/dist/chunks/chunk-HCXPNKPU.ts.map +0 -7
  493. package/dist/chunks/chunk-IBXEM35O.ts +0 -34
  494. package/dist/chunks/chunk-IBXEM35O.ts.map +0 -7
  495. package/dist/chunks/chunk-LNZRNXNQ.ts.map +0 -7
  496. package/dist/chunks/chunk-NXWHPVXR.ts +0 -26
  497. package/dist/chunks/chunk-NXWHPVXR.ts.map +0 -7
  498. package/dist/chunks/chunk-P4GI7LTT.ts +0 -20
  499. package/dist/chunks/chunk-P4GI7LTT.ts.map +0 -7
  500. package/dist/chunks/chunk-R3SAMXB6.ts +0 -60
  501. package/dist/chunks/chunk-R3SAMXB6.ts.map +0 -7
  502. package/dist/chunks/chunk-R7PN3KIY.ts +0 -22
  503. package/dist/chunks/chunk-R7PN3KIY.ts.map +0 -7
  504. package/dist/chunks/chunk-T3LABNHF.ts +0 -20
  505. package/dist/chunks/chunk-T3LABNHF.ts.map +0 -7
  506. package/dist/chunks/chunk-UMPA5S7X.ts +0 -11
  507. package/dist/chunks/chunk-UMPA5S7X.ts.map +0 -7
  508. package/dist/chunks/chunk-VQTYTUBU.ts.map +0 -7
  509. package/dist/chunks/chunk-ZO52JM4H.ts +0 -15
  510. package/dist/chunks/chunk-ZO52JM4H.ts.map +0 -7
  511. package/dist/chunks/chunk-ZWP6HAYV.ts.map +0 -7
  512. package/dist/chunks/client-debug-F4WFP2YJ.ts +0 -40
  513. package/dist/chunks/client-debug-F4WFP2YJ.ts.map +0 -7
  514. package/dist/chunks/command-handler-DWWFIXSC.ts.map +0 -7
  515. package/dist/chunks/conflict-review-HSERM245.ts +0 -18
  516. package/dist/chunks/conflict-review-HSERM245.ts.map +0 -7
  517. package/dist/chunks/debug-tool-execution-7N4H6K3X.ts +0 -67
  518. package/dist/chunks/debug-tool-execution-7N4H6K3X.ts.map +0 -7
  519. package/dist/chunks/diff-review-6IUIOYST.ts +0 -68
  520. package/dist/chunks/diff-review-6IUIOYST.ts.map +0 -7
  521. package/dist/chunks/diff-review-GB4NO53B.ts.map +0 -7
  522. package/dist/chunks/manager-result-dispatcher-6MOJPLIS.ts +0 -20
  523. package/dist/chunks/manager-ui-3CQU37XY.ts.map +0 -7
  524. package/dist/chunks/ownership-recovery-5KXAMFSL.ts +0 -59
  525. package/dist/chunks/ownership-recovery-5KXAMFSL.ts.map +0 -7
  526. package/dist/chunks/remote-selection-ui-2V53UBHM.ts +0 -19
  527. package/dist/chunks/setup-switch-WSKVGW7L.ts +0 -27
  528. package/dist/chunks/snapshot-ZUJJZCFW.ts.map +0 -7
  529. package/dist/chunks/snapshot-transaction-directory-F46JWRAU.ts +0 -13
  530. package/dist/chunks/snapshot-transaction-directory-F46JWRAU.ts.map +0 -7
  531. package/dist/chunks/state-directory-CMAIF34J.ts +0 -17
  532. package/dist/chunks/sync-inspection-CQDNC542.ts +0 -23
  533. package/dist/chunks/sync-inspection-CQDNC542.ts.map +0 -7
  534. package/dist/chunks/sync-operations-IF7LMWK6.ts +0 -52
  535. package/dist/chunks/sync-operations-IF7LMWK6.ts.map +0 -7
  536. package/dist/chunks/sync-state-QIT64TKV.ts.map +0 -7
  537. package/dist/daemon/LICENSE +0 -21
  538. package/dist/daemon/dist/build-id.json +0 -1
  539. package/dist/daemon/dist/build-version.js +0 -28
  540. package/dist/daemon/dist/child-sdk.mjs +0 -17
  541. package/dist/daemon/dist/cli.js +0 -156
  542. package/dist/daemon/dist/client-transport.js +0 -77
  543. package/dist/daemon/dist/client.js +0 -950
  544. package/dist/daemon/dist/consent.js +0 -304
  545. package/dist/daemon/dist/daemon-debug.js +0 -40
  546. package/dist/daemon/dist/daemon-recovery.js +0 -160
  547. package/dist/daemon/dist/daemon-startup.js +0 -350
  548. package/dist/daemon/dist/daemon-status.js +0 -57
  549. package/dist/daemon/dist/daemon-upgrade-error.js +0 -14
  550. package/dist/daemon/dist/diff-review-binding.js +0 -11
  551. package/dist/daemon/dist/diff-review-protocol.js +0 -85
  552. package/dist/daemon/dist/diff-review-rpc.js +0 -37
  553. package/dist/daemon/dist/diff-review-store.js +0 -89
  554. package/dist/daemon/dist/document.js +0 -6
  555. package/dist/daemon/dist/endpoint.js +0 -91
  556. package/dist/daemon/dist/engine/backends/backend-factory.js +0 -16
  557. package/dist/daemon/dist/engine/backends/backend-identity.js +0 -38
  558. package/dist/daemon/dist/engine/backends/backend-types.js +0 -1
  559. package/dist/daemon/dist/engine/backends/git/git-backend.js +0 -775
  560. package/dist/daemon/dist/engine/backends/git/git-config.js +0 -118
  561. package/dist/daemon/dist/engine/backends/git/git-runner.js +0 -237
  562. package/dist/daemon/dist/engine/backends/git/git-storage.js +0 -227
  563. package/dist/daemon/dist/engine/backends/publication-encoding.js +0 -19
  564. package/dist/daemon/dist/engine/backends/s3/s3-backend.js +0 -453
  565. package/dist/daemon/dist/engine/backends/s3/s3-client.js +0 -362
  566. package/dist/daemon/dist/engine/backends/s3/s3-conditions.js +0 -66
  567. package/dist/daemon/dist/engine/backends/snapshot-pointer.js +0 -22
  568. package/dist/daemon/dist/engine/backends/sync-backend.js +0 -39
  569. package/dist/daemon/dist/engine/backends/webdav/webdav-backend.js +0 -605
  570. package/dist/daemon/dist/engine/backends/webdav/webdav-client.js +0 -349
  571. package/dist/daemon/dist/engine/backends/webdav/webdav-config.js +0 -73
  572. package/dist/daemon/dist/engine/commands/command-types.js +0 -1
  573. package/dist/daemon/dist/engine/debug-check.js +0 -59
  574. package/dist/daemon/dist/engine/debug-log.js +0 -252
  575. package/dist/daemon/dist/engine/host.js +0 -20
  576. package/dist/daemon/dist/engine/paths.js +0 -77
  577. package/dist/daemon/dist/engine/settings/config-errors.js +0 -4
  578. package/dist/daemon/dist/engine/settings/config-file.js +0 -784
  579. package/dist/daemon/dist/engine/settings/config.js +0 -246
  580. package/dist/daemon/dist/engine/settings/retired-ignore-policy.js +0 -16
  581. package/dist/daemon/dist/engine/settings/retired-ignore-recovery.js +0 -14
  582. package/dist/daemon/dist/engine/settings/settings-management.js +0 -196
  583. package/dist/daemon/dist/engine/settings/settings-store.js +0 -41
  584. package/dist/daemon/dist/engine/settings/settings-types.js +0 -1
  585. package/dist/daemon/dist/engine/settings/settings-validation.js +0 -390
  586. package/dist/daemon/dist/engine/snapshot/session-paths.js +0 -146
  587. package/dist/daemon/dist/engine/snapshot/snapshot-apply.js +0 -347
  588. package/dist/daemon/dist/engine/snapshot/snapshot-bounds.js +0 -20
  589. package/dist/daemon/dist/engine/snapshot/snapshot-capture-limit.js +0 -99
  590. package/dist/daemon/dist/engine/snapshot/snapshot-case-replacement.js +0 -82
  591. package/dist/daemon/dist/engine/snapshot/snapshot-codec.js +0 -62
  592. package/dist/daemon/dist/engine/snapshot/snapshot-difference.js +0 -13
  593. package/dist/daemon/dist/engine/snapshot/snapshot-entry-projection.js +0 -78
  594. package/dist/daemon/dist/engine/snapshot/snapshot-exclude-safety.js +0 -205
  595. package/dist/daemon/dist/engine/snapshot/snapshot-mutation-queues.js +0 -153
  596. package/dist/daemon/dist/engine/snapshot/snapshot-paths.js +0 -11
  597. package/dist/daemon/dist/engine/snapshot/snapshot-payload.js +0 -42
  598. package/dist/daemon/dist/engine/snapshot/snapshot-reviewed-preimages.js +0 -60
  599. package/dist/daemon/dist/engine/snapshot/snapshot-root-transition.js +0 -138
  600. package/dist/daemon/dist/engine/snapshot/snapshot-transaction-directory.js +0 -16
  601. package/dist/daemon/dist/engine/snapshot/snapshot-transaction-images.js +0 -415
  602. package/dist/daemon/dist/engine/snapshot/snapshot-transaction-plan.js +0 -68
  603. package/dist/daemon/dist/engine/snapshot/snapshot-transaction-policy.js +0 -202
  604. package/dist/daemon/dist/engine/snapshot/snapshot-transaction-stage.js +0 -303
  605. package/dist/daemon/dist/engine/snapshot/snapshot-transaction-verification.js +0 -78
  606. package/dist/daemon/dist/engine/snapshot/snapshot-transaction.js +0 -830
  607. package/dist/daemon/dist/engine/snapshot/snapshot-types.js +0 -3
  608. package/dist/daemon/dist/engine/snapshot/snapshot.js +0 -695
  609. package/dist/daemon/dist/engine/state/json-file.js +0 -49
  610. package/dist/daemon/dist/engine/state/lock.js +0 -399
  611. package/dist/daemon/dist/engine/state/lockfile-fs.js +0 -13
  612. package/dist/daemon/dist/engine/state/merge-baseline-store.js +0 -198
  613. package/dist/daemon/dist/engine/state/mutation-directory-sync.js +0 -34
  614. package/dist/daemon/dist/engine/state/operation-availability.js +0 -40
  615. package/dist/daemon/dist/engine/state/state-directory.js +0 -227
  616. package/dist/daemon/dist/engine/state/state-types.js +0 -1
  617. package/dist/daemon/dist/engine/state/sync-state-store.js +0 -58
  618. package/dist/daemon/dist/engine/sync/agent-candidate.js +0 -207
  619. package/dist/daemon/dist/engine/sync/agent-plan.js +0 -84
  620. package/dist/daemon/dist/engine/sync/agent-refusal-retry.js +0 -39
  621. package/dist/daemon/dist/engine/sync/agent-request.js +0 -13
  622. package/dist/daemon/dist/engine/sync/agent-runner.js +0 -183
  623. package/dist/daemon/dist/engine/sync/agent-store.js +0 -177
  624. package/dist/daemon/dist/engine/sync/agent-sync.js +0 -139
  625. package/dist/daemon/dist/engine/sync/apply-review.js +0 -52
  626. package/dist/daemon/dist/engine/sync/conflict-artifact-ownership.js +0 -53
  627. package/dist/daemon/dist/engine/sync/conflict-artifacts.js +0 -158
  628. package/dist/daemon/dist/engine/sync/conflict-groups.js +0 -76
  629. package/dist/daemon/dist/engine/sync/conflict-preview.js +0 -53
  630. package/dist/daemon/dist/engine/sync/conflict-resolution.js +0 -53
  631. package/dist/daemon/dist/engine/sync/conflict-retention.js +0 -61
  632. package/dist/daemon/dist/engine/sync/conflict-review.js +0 -73
  633. package/dist/daemon/dist/engine/sync/content-conflicts.js +0 -70
  634. package/dist/daemon/dist/engine/sync/continuous-errors.js +0 -72
  635. package/dist/daemon/dist/engine/sync/continuous-lease.js +0 -206
  636. package/dist/daemon/dist/engine/sync/continuous-record.js +0 -199
  637. package/dist/daemon/dist/engine/sync/continuous-storage.js +0 -59
  638. package/dist/daemon/dist/engine/sync/continuous-sync.js +0 -549
  639. package/dist/daemon/dist/engine/sync/continuous-watch.js +0 -137
  640. package/dist/daemon/dist/engine/sync/diff-review-capture.js +0 -210
  641. package/dist/daemon/dist/engine/sync/diff-review-preview.js +0 -114
  642. package/dist/daemon/dist/engine/sync/directional-action.js +0 -101
  643. package/dist/daemon/dist/engine/sync/directional-conflict.js +0 -29
  644. package/dist/daemon/dist/engine/sync/exclude-policy.js +0 -86
  645. package/dist/daemon/dist/engine/sync/field-migration.js +0 -20
  646. package/dist/daemon/dist/engine/sync/file-merge-planner.js +0 -123
  647. package/dist/daemon/dist/engine/sync/initialization.js +0 -81
  648. package/dist/daemon/dist/engine/sync/json-document.js +0 -172
  649. package/dist/daemon/dist/engine/sync/local-field-policy.js +0 -26
  650. package/dist/daemon/dist/engine/sync/local-fields.js +0 -161
  651. package/dist/daemon/dist/engine/sync/merge-acceptance.js +0 -29
  652. package/dist/daemon/dist/engine/sync/merge-apply.js +0 -530
  653. package/dist/daemon/dist/engine/sync/merge-journal.js +0 -204
  654. package/dist/daemon/dist/engine/sync/merge-transfer-error.js +0 -64
  655. package/dist/daemon/dist/engine/sync/merged-sync.js +0 -655
  656. package/dist/daemon/dist/engine/sync/mutation-owner.js +0 -18
  657. package/dist/daemon/dist/engine/sync/package-merge.js +0 -82
  658. package/dist/daemon/dist/engine/sync/partial-progress.js +0 -41
  659. package/dist/daemon/dist/engine/sync/push-review.js +0 -18
  660. package/dist/daemon/dist/engine/sync/remote-snapshot.js +0 -119
  661. package/dist/daemon/dist/engine/sync/resolver-stream.js +0 -34
  662. package/dist/daemon/dist/engine/sync/session-merge.js +0 -178
  663. package/dist/daemon/dist/engine/sync/session-push.js +0 -56
  664. package/dist/daemon/dist/engine/sync/settings-conflicts.js +0 -56
  665. package/dist/daemon/dist/engine/sync/settings-merge.js +0 -93
  666. package/dist/daemon/dist/engine/sync/signals.js +0 -8
  667. package/dist/daemon/dist/engine/sync/startup-bootstrap.js +0 -105
  668. package/dist/daemon/dist/engine/sync/startup-recovery-evidence.js +0 -37
  669. package/dist/daemon/dist/engine/sync/startup-timings.js +0 -116
  670. package/dist/daemon/dist/engine/sync/sync-decision.js +0 -81
  671. package/dist/daemon/dist/engine/sync/sync-error-guidance.js +0 -74
  672. package/dist/daemon/dist/engine/sync/sync-errors.js +0 -38
  673. package/dist/daemon/dist/engine/sync/sync-inspection.js +0 -42
  674. package/dist/daemon/dist/engine/sync/sync-loaders.js +0 -8
  675. package/dist/daemon/dist/engine/sync/sync-local.js +0 -96
  676. package/dist/daemon/dist/engine/sync/sync-mutations.js +0 -723
  677. package/dist/daemon/dist/engine/sync/sync-operations.js +0 -3
  678. package/dist/daemon/dist/engine/sync/sync-policy.js +0 -530
  679. package/dist/daemon/dist/engine/sync/sync-queries.js +0 -316
  680. package/dist/daemon/dist/engine/sync/sync-rollback.js +0 -180
  681. package/dist/daemon/dist/engine/sync/sync-state.js +0 -119
  682. package/dist/daemon/dist/engine/sync/text-merge.js +0 -124
  683. package/dist/daemon/dist/engine/sync/transfer-freshness.js +0 -79
  684. package/dist/daemon/dist/engine/sync/transfer-size-limits.js +0 -88
  685. package/dist/daemon/dist/engine/types.js +0 -2
  686. package/dist/daemon/dist/engine/ui/merge-review.js +0 -7
  687. package/dist/daemon/dist/engine/ui/merged-sync-summary.js +0 -86
  688. package/dist/daemon/dist/engine/ui/sync-format.js +0 -123
  689. package/dist/daemon/dist/engine/ui/sync-status.js +0 -30
  690. package/dist/daemon/dist/engine/ui/terminal-text.js +0 -9
  691. package/dist/daemon/dist/engine/ui/transfer-changes.js +0 -24
  692. package/dist/daemon/dist/engine/ui/transfer-review.js +0 -18
  693. package/dist/daemon/dist/engine-service.js +0 -506
  694. package/dist/daemon/dist/foreground-queue-outcome.js +0 -9
  695. package/dist/daemon/dist/foreground-transfer.js +0 -10
  696. package/dist/daemon/dist/identity.js +0 -275
  697. package/dist/daemon/dist/idle-exit.js +0 -77
  698. package/dist/daemon/dist/index.js +0 -27
  699. package/dist/daemon/dist/legacy-consent-guard.js +0 -34
  700. package/dist/daemon/dist/lifecycle-log.js +0 -54
  701. package/dist/daemon/dist/lifecycle.js +0 -21
  702. package/dist/daemon/dist/model-signature.js +0 -7
  703. package/dist/daemon/dist/paged-review.js +0 -177
  704. package/dist/daemon/dist/participant-admission.js +0 -30
  705. package/dist/daemon/dist/participant-ledger.js +0 -149
  706. package/dist/daemon/dist/protocol.js +0 -108
  707. package/dist/daemon/dist/resolver-host.js +0 -78
  708. package/dist/daemon/dist/server.js +0 -1374
  709. package/dist/daemon/dist/service-host.js +0 -260
  710. package/dist/daemon/dist/session-presence.js +0 -207
  711. package/dist/daemon/dist/state-wait-jobs.js +0 -23
  712. package/dist/daemon/dist/state-wait.js +0 -34
  713. package/dist/daemon/dist/upgrade-repair.js +0 -55
  714. package/dist/daemon/package.json +0 -3
  715. package/dist/package.json +0 -6
  716. package/src/daemon/apply-gate.ts +0 -146
  717. package/src/daemon/client-debug.ts +0 -50
  718. package/src/daemon/daemon-status-ui.ts +0 -64
  719. package/src/daemon/diff-review.ts +0 -68
  720. package/src/daemon/directional-recovery.ts +0 -106
  721. package/src/daemon/ownership-recovery.ts +0 -50
  722. package/src/daemon/pi-client.ts +0 -1330
  723. package/src/daemon/queue-release-ui.ts +0 -88
  724. package/src/daemon/recovery.ts +0 -103
  725. package/src/daemon/startup-bootstrap-client.ts +0 -26
  726. /package/dist/chunks/{manager-result-dispatcher-6MOJPLIS.ts.map → chunk-3GL7LBNB.ts.map} +0 -0
  727. /package/dist/chunks/{remote-selection-ui-2V53UBHM.ts.map → chunk-3PFWVSV3.ts.map} +0 -0
  728. /package/dist/chunks/{setup-switch-WSKVGW7L.ts.map → chunk-53IKSWLZ.ts.map} +0 -0
  729. /package/dist/chunks/{state-directory-CMAIF34J.ts.map → chunk-A3NEEVNA.ts.map} +0 -0
  730. /package/dist/chunks/{sync-state-store-TZE7XDV5.ts.map → chunk-AITZUACB.ts.map} +0 -0
  731. /package/dist/chunks/{chunk-WE3KJ7JS.ts.map → chunk-IFJXUHHC.ts.map} +0 -0
  732. /package/dist/chunks/{chunk-HFMGK6A6.ts.map → chunk-YLVRV6NM.ts.map} +0 -0
  733. /package/dist/chunks/{merge-review-DXSERTCK.ts.map → merge-review-RMDYVNBK.ts.map} +0 -0
  734. /package/{dist/daemon/dist/engine/state/lock-policy.js → src/engine/state/lock-policy.ts} +0 -0
@@ -1,1374 +0,0 @@
1
- import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
2
- import { addAbortListener } from "node:events";
3
- import { lstatSync } from "node:fs";
4
- import fs from "node:fs/promises";
5
- import { createServer } from "node:http";
6
- import lockfile from "proper-lockfile";
7
- import { DAEMON_BUILD_ID, DAEMON_BUILD_VERSION } from "./build-version.js";
8
- import { ConsentPublicationError, readConsent } from "./consent.js";
9
- import { sameDiffReviewBinding } from "./diff-review-binding.js";
10
- import { handleDiffReviewRequest } from "./diff-review-rpc.js";
11
- import { createDiffReviewStore } from "./diff-review-store.js";
12
- import { endpointOwner } from "./endpoint.js";
13
- import { debugJobResult, debugOperation } from "./engine/debug-log.js";
14
- import { SyncDecisionRequiredError } from "./engine/sync/sync-errors.js";
15
- import { isForegroundDirection, isForegroundQueueOutcome } from "./foreground-queue-outcome.js";
16
- import { canonicalRootGuard, daemonPaths, matchesPublishedIdentity, privateDirectory, processExists, publishIdentity, readIdentity, readJsonBody, readUpgradeOwner, runtimePaths, } from "./identity.js";
17
- import { createIdleExit } from "./idle-exit.js";
18
- import { withCleanup } from "./lifecycle.js";
19
- import { createPagedReviewOffer, reviewScope } from "./paged-review.js";
20
- import { ParticipantAdmission } from "./participant-admission.js";
21
- import { createParticipantLedger } from "./participant-ledger.js";
22
- import { ClientContactExpiredError, DAEMON_JOB_CAPACITY, DaemonStoppingError, MAX_MESSAGE_BYTES, MAX_REVIEW_BYTES, OWNERSHIP_CLEANUP_REQUIRED, operationPrefix, PROTOCOL_VERSION, REVIEW_PAGE_CHARS, record, remoteError, UNKNOWN_JOB_RESULT, validateFacts, validateHandoff, validId, } from "./protocol.js";
23
- import { ParticipantStateWait } from "./state-wait.js";
24
- export async function startServer(root, execute, hooks = {}) {
25
- const base = await runtimePaths(root);
26
- const identity = {
27
- version: 1,
28
- root: base.root,
29
- instance: randomUUID(),
30
- pid: process.pid,
31
- token: randomBytes(32).toString("hex"),
32
- };
33
- const paths = daemonPaths(base, identity.instance);
34
- const assertRoot = canonicalRootGuard(paths.root);
35
- assertRoot();
36
- await privateDirectory(paths.directory);
37
- const previous = await readIdentity(paths);
38
- if (previous && processExists(previous.pid))
39
- throw new Error("A daemon owner is still alive; refusing replacement.");
40
- let compromised = false;
41
- let published = false;
42
- let released = false;
43
- const release = await lockfile.lock(paths.directory, {
44
- realpath: false,
45
- lockfilePath: paths.owner,
46
- stale: 30_000,
47
- update: 5_000,
48
- onCompromised: () => {
49
- compromised = true;
50
- if (published)
51
- void close().catch(() => { });
52
- },
53
- });
54
- const diagnostic = hooks.diagnostic;
55
- const ownsLog = () => {
56
- if (!published || compromised || released)
57
- return false;
58
- assertRoot();
59
- return (lstatSync(paths.owner, { throwIfNoEntry: false })?.isDirectory() === true &&
60
- matchesPublishedIdentity(paths, identity));
61
- };
62
- const debug = diagnostic
63
- ? (event, current) => {
64
- try {
65
- return diagnostic(event, () => ownsLog() && (current?.() ?? true))?.catch(() => { });
66
- }
67
- catch { }
68
- }
69
- : undefined;
70
- const failure = () => {
71
- debug?.({ event: "lifecycle", outcome: "failed" });
72
- hooks.failure?.();
73
- };
74
- const participants = new Map();
75
- const diffReviews = createDiffReviewStore();
76
- const invalidateDiffReview = (peer) => {
77
- const owner = peer.diffReviewOwner;
78
- if (!owner)
79
- return;
80
- peer.diffReviewOwner = undefined;
81
- diffReviews.release(owner);
82
- owner.abort(new DOMException("File review owner changed", "AbortError"));
83
- };
84
- const waiters = new WeakMap();
85
- const admission = new ParticipantAdmission();
86
- const jobs = new Map();
87
- const backgroundJobs = new Set();
88
- const cancelled = new Set();
89
- const closedClients = new Set();
90
- // Retain tombstones after result eviction; replay must never dispatch a second write.
91
- const retired = new Set();
92
- const pending = new Map();
93
- const ledger = createParticipantLedger(paths, () => participants.values(), failure);
94
- let sequence = 0;
95
- let participantGeneration = 0;
96
- let closed = false;
97
- let stopRequested = false;
98
- let foregroundRecoveryJob;
99
- let consentPublicationFailed = false;
100
- let automaticClosing = false;
101
- let idleExit;
102
- let expiring;
103
- const peerOperations = new Set();
104
- let queue = Promise.resolve();
105
- let closing;
106
- let heartbeat;
107
- function participantsChanged() {
108
- participantGeneration++;
109
- for (const peer of participants.values())
110
- waiters.get(peer)?.changed();
111
- for (const job of [...jobs.values(), ...backgroundJobs]) {
112
- if (job.participantGeneration !== undefined &&
113
- !job.committed &&
114
- (job.view.phase === "queued" || job.view.phase === "running"))
115
- job.controller.abort(new DOMException("Daemon participants changed before automatic work completed.", "AbortError"));
116
- }
117
- }
118
- function savePeers(candidate, allowNoop = false) {
119
- idleExit?.changed();
120
- return ledger.save(candidate, allowNoop);
121
- }
122
- try {
123
- for (const { facts, handoff } of await ledger.restore()) {
124
- if (!processExists(facts.pid))
125
- continue;
126
- if (handoff?.kind === "exit")
127
- closedClients.add(facts.id);
128
- participants.set(facts.id, {
129
- facts,
130
- handoff,
131
- callbacks: new Map(),
132
- events: [],
133
- connected: false,
134
- closing: false,
135
- suspected: handoff?.kind !== "exit",
136
- seen: 0,
137
- });
138
- }
139
- }
140
- catch (error) {
141
- await release();
142
- throw error;
143
- }
144
- const known = async () => {
145
- const current = await readIdentity(paths);
146
- return current?.instance === identity.instance && current.pid === process.pid && current.token === identity.token;
147
- };
148
- const emit = (kind, payload, target) => {
149
- const event = { id: ++sequence, kind, payload };
150
- if (Buffer.byteLength(JSON.stringify(event)) > MAX_MESSAGE_BYTES / 8)
151
- throw new Error("Notification exceeds the local API limit; use bounded diagnostics. No review was truncated.");
152
- for (const [id, peer] of participants) {
153
- if (target && id !== target)
154
- continue;
155
- peer.events.push(event);
156
- while (peer.events.length > 128 || Buffer.byteLength(JSON.stringify(peer.events)) > MAX_MESSAGE_BYTES / 8)
157
- peer.events.shift();
158
- waiters.get(peer)?.changed();
159
- }
160
- };
161
- const assertOwner = () => {
162
- if (automaticClosing && !compromised)
163
- throw new DaemonStoppingError();
164
- if (stopRequested)
165
- throw new DaemonStoppingError();
166
- if (closed || compromised)
167
- throw new Error("Daemon ownership is no longer valid.");
168
- assertRoot();
169
- };
170
- const requireParticipant = (id, cleanup = false) => {
171
- if (!validId(id))
172
- throw new Error("Invalid client identity.");
173
- const peer = participants.get(id);
174
- if (!peer ||
175
- (!cleanup &&
176
- (peer.publishing ||
177
- !peer.connected ||
178
- peer.closing ||
179
- Date.now() - peer.seen > 5_000 ||
180
- !processExists(peer.facts.pid))))
181
- throw new Error("Client is not attached or is closing.");
182
- return peer;
183
- };
184
- const liveClientFacts = () => [...participants.values()].filter((peer) => processExists(peer.facts.pid)).map((peer) => peer.facts);
185
- const participates = (peer) => !peer.publishing && (peer.connected || peer.suspected);
186
- const participantFacts = () => [...participants.values()]
187
- .filter((peer) => participates(peer) && processExists(peer.facts.pid))
188
- .map((peer) => peer.closing || peer.suspected || Date.now() - peer.seen > 5_000
189
- ? { ...(peer.resumeFacts ?? peer.facts), idle: false }
190
- : peer.facts);
191
- const contactState = (peer) => {
192
- if (closed || stopRequested || compromised || peer.publishing || peer.closing || !processExists(peer.facts.pid))
193
- return "inactive";
194
- if (peer.connected)
195
- return "active";
196
- return peer.expiry ? "expired" : "inactive";
197
- };
198
- const poll = (peer, cursor, job) => ({
199
- contact: contactState(peer),
200
- cursor: sequence,
201
- callbacks: [...peer.callbacks.values()],
202
- events: peer.events.filter((event) => event.id > (typeof cursor === "number" && Number.isSafeInteger(cursor) ? cursor : 0)),
203
- job: job?.view,
204
- });
205
- function makeExecution(job, diffReviewOwner) {
206
- const signal = diffReviewOwner
207
- ? AbortSignal.any([job.controller.signal, diffReviewOwner.signal])
208
- : job.controller.signal;
209
- const validate = () => {
210
- if (compromised)
211
- throw new Error("Daemon ownership is no longer valid.");
212
- // Finish journal/publication bookkeeping after commit even if a UI detaches or stop begins.
213
- if (job.committed) {
214
- assertRoot();
215
- return;
216
- }
217
- assertOwner();
218
- signal.throwIfAborted();
219
- if (job.participantGeneration !== undefined && job.participantGeneration !== participantGeneration)
220
- throw new Error("Daemon participants changed before automatic work completed.");
221
- if (job.client) {
222
- const peer = requireParticipant(job.client);
223
- if (peer.facts.generation !== job.generation || (diffReviewOwner && peer.diffReviewOwner !== diffReviewOwner))
224
- throw new Error("Client session generation changed.");
225
- }
226
- };
227
- const request = (kind, data, target = job.client, requestSignal = signal) => {
228
- const cleanup = kind === "queue-release";
229
- if (!cleanup)
230
- validate();
231
- if (!target)
232
- throw new Error("This operation requires an attached UI client.");
233
- const peer = requireParticipant(target, cleanup);
234
- const callback = { id: randomUUID(), job: job.view.id, kind, payload: data };
235
- let review;
236
- let pagedReview;
237
- if (kind === "merge-review" && record(data) && typeof data.content === "string") {
238
- const bytes = Buffer.byteLength(data.content);
239
- if (bytes > MAX_REVIEW_BYTES)
240
- throw new Error("Exact review exceeds its byte limit; no truncated review was approved.");
241
- if (bytes > REVIEW_PAGE_CHARS) {
242
- if (peer.reviewDetails)
243
- pagedReview = createPagedReviewOffer(reviewScope(identity, peer.facts, callback), data, data.content, bytes);
244
- if (pagedReview) {
245
- callback.payload = pagedReview.summary;
246
- callback.review = pagedReview.reference;
247
- }
248
- else {
249
- review = data.content;
250
- callback.payload = { ...data, content: undefined };
251
- callback.review = {
252
- pages: Math.ceil(review.length / REVIEW_PAGE_CHARS),
253
- bytes,
254
- sha256: createHash("sha256").update(review).digest("hex"),
255
- };
256
- }
257
- }
258
- }
259
- if (peer.callbacks.size >= 64 ||
260
- Buffer.byteLength(JSON.stringify([...peer.callbacks.values(), callback])) > MAX_MESSAGE_BYTES / 8)
261
- throw new Error("Callback exceeds its byte limit; no review was approved.");
262
- job.peers.add(target);
263
- const reservation = record(data) && typeof data.reservation === "string" ? data.reservation : undefined;
264
- if (kind === "queue-acquire" || cleanup) {
265
- // A lost acquire response is not proof that Pi never acquired the queue.
266
- // Bound retained evidence even if a failing or malformed executor keeps requesting grants.
267
- peer.reservations ??= new Set();
268
- if (!reservation)
269
- peer.resumeUnsafe = true;
270
- else if (peer.reservations.size < 64)
271
- peer.reservations.add(reservation);
272
- else if (!peer.reservations.has(reservation))
273
- peer.resumeUnsafe = true;
274
- }
275
- return new Promise((resolve, reject) => {
276
- let timer;
277
- const effectiveSignal = cleanup ? undefined : requestSignal;
278
- const abort = () => finish(undefined, effectiveSignal?.reason);
279
- const finish = (value, error) => {
280
- if (timer)
281
- clearTimeout(timer);
282
- effectiveSignal?.removeEventListener("abort", abort);
283
- if (!pending.delete(callback.id))
284
- return;
285
- peer.callbacks.delete(callback.id);
286
- if (cleanup && reservation && error === undefined && value === true)
287
- peer.reservations?.delete(reservation);
288
- sequence++;
289
- waiters.get(peer)?.changed();
290
- if (error)
291
- reject(error);
292
- else
293
- resolve(value);
294
- };
295
- let startupReviewLock;
296
- if (!job.committed && ["confirm", "select", "merge-review"].includes(kind)) {
297
- try {
298
- startupReviewLock = hooks.startup?.captureReviewLock();
299
- }
300
- catch {
301
- startupReviewLock = undefined;
302
- }
303
- }
304
- pending.set(callback.id, {
305
- callback,
306
- startupReviewLock,
307
- review,
308
- pagedReview,
309
- target,
310
- resolve: (value) => finish(value),
311
- reject: (error) => finish(undefined, error),
312
- });
313
- peer.callbacks.set(callback.id, callback);
314
- sequence++;
315
- waiters.get(peer)?.changed();
316
- effectiveSignal?.addEventListener("abort", abort, { once: true });
317
- if (kind.startsWith("queue-")) {
318
- timer = setTimeout(() => finish(undefined, new Error("Client file-queue acknowledgement timed out; work was stopped.")), 30_000);
319
- timer.unref?.();
320
- }
321
- if (effectiveSignal?.aborted)
322
- abort();
323
- });
324
- };
325
- return {
326
- root: paths.root,
327
- clientId: job.client,
328
- signal,
329
- facts: () => (job.client ? participants.get(job.client)?.facts : undefined),
330
- participants: participantFacts,
331
- liveClients: liveClientFacts,
332
- withParticipants: (action) => admission.run(async () => {
333
- validate();
334
- return action(participantFacts());
335
- }, job.committed ? undefined : signal),
336
- validate,
337
- ...(diffReviewOwner && {
338
- diffReview: {
339
- clear() {
340
- validate();
341
- diffReviews.release(diffReviewOwner);
342
- },
343
- retain(prepared) {
344
- validate();
345
- return diffReviews.retain(diffReviewOwner, prepared, signal);
346
- },
347
- },
348
- }),
349
- request,
350
- emit: (kind, data, target = job.client) => emit(kind, data, target),
351
- debug: debug &&
352
- ((event, current) => debug(event.event === "check" ? { ...event, operationId: job.view.id } : event, current)),
353
- noteDebugOutcome(outcome) {
354
- job.debugOutcome = outcome;
355
- },
356
- committed: () => {
357
- job.committed = true;
358
- emit("commit", { job: job.view.id }, job.client);
359
- },
360
- };
361
- }
362
- function assertForegroundQueueReady() {
363
- if (foregroundRecoveryJob)
364
- throw Object.assign(new Error("File-queue cleanup is pending; no new daemon work can start."), {
365
- code: OWNERSHIP_CLEANUP_REQUIRED,
366
- });
367
- }
368
- function enqueue(id, client, operation, payload) {
369
- const peer = requireParticipant(client);
370
- if (!id.startsWith(operationPrefix(identity)))
371
- throw new Error("Operation belongs to another daemon instance; reconcile journals instead of replaying.");
372
- const digest = createHash("sha256").update(JSON.stringify({ client, operation, payload })).digest("hex");
373
- const duplicate = jobs.get(id);
374
- if (duplicate) {
375
- if (duplicate.digest !== digest || duplicate.client !== client)
376
- throw new Error("Operation ID was reused with different input.");
377
- return duplicate;
378
- }
379
- assertForegroundQueueReady();
380
- if (retired.has(id))
381
- throw new Error("Operation result expired; reconcile the existing journal before starting new work.");
382
- if (retired.size + jobs.size >= 4096)
383
- throw new Error("Daemon operation ledger is full; drain and restart explicitly.");
384
- if (jobs.size >= DAEMON_JOB_CAPACITY) {
385
- for (const [key, job] of jobs)
386
- if (job.view.phase === "done" || job.view.phase === "failed") {
387
- retired.add(key);
388
- jobs.delete(key);
389
- const owner = job.client ? participants.get(job.client) : undefined;
390
- if (owner)
391
- waiters.get(owner)?.changed();
392
- break;
393
- }
394
- if (jobs.size >= DAEMON_JOB_CAPACITY)
395
- throw new Error("Daemon job capacity reached.");
396
- }
397
- const job = {
398
- view: { id, phase: "queued" },
399
- digest,
400
- client,
401
- generation: peer.facts.generation,
402
- participantGeneration: ["startup-transfer", "shutdown", "daemon.authorize"].includes(operation)
403
- ? participantGeneration
404
- : undefined,
405
- controller: new AbortController(),
406
- committed: false,
407
- promise: Promise.resolve(),
408
- peers: new Set(),
409
- };
410
- if (cancelled.has(`${client}:${id}`))
411
- job.controller.abort(new DOMException("Operation cancelled before dispatch", "AbortError"));
412
- let diffReviewOwner;
413
- if (operation === "diff.review" && peer.facts.mode === "tui" && peer.facts.hasUI) {
414
- peer.diffReviewOwner ??= new AbortController();
415
- diffReviewOwner = peer.diffReviewOwner;
416
- }
417
- const execution = makeExecution(job, diffReviewOwner);
418
- const kind = debug && debugOperation(operation);
419
- const waitForInspectionLog = kind === "inspect";
420
- const note = (outcome, current) => {
421
- if (kind)
422
- return debug?.({ event: "job", operation: kind, outcome, operationId: id }, current);
423
- };
424
- job.promise = queue
425
- .then(async () => {
426
- execution.validate();
427
- assertForegroundQueueReady();
428
- job.view.phase = "running";
429
- note("started");
430
- const result = await execute(operation, payload, execution);
431
- if (Buffer.byteLength(JSON.stringify(result ?? null)) > MAX_MESSAGE_BYTES / 2)
432
- throw new Error("Operation result exceeds its byte limit; use bounded inspection.");
433
- if (isForegroundDirection(operation) && isForegroundQueueOutcome(result)) {
434
- if (result.foregroundQueueCleanup === "before-mutation" && job.committed)
435
- throw Object.assign(new Error("File-queue release and transfer outcome could not be verified."), {
436
- code: OWNERSHIP_CLEANUP_REQUIRED,
437
- });
438
- foregroundRecoveryJob ??= job;
439
- }
440
- const logged = note(debugJobResult(operation, result) ?? job.debugOutcome ?? "completed", waitForInspectionLog ? () => !execution.signal.aborted : undefined);
441
- if (waitForInspectionLog && logged) {
442
- await logged;
443
- execution.validate();
444
- }
445
- job.view.result = result;
446
- job.view.phase = "done";
447
- })
448
- .catch(async (error) => {
449
- if (error instanceof ConsentPublicationError)
450
- consentPublicationFailed = true;
451
- const logged = note(!job.committed && (job.controller.signal.aborted || (error instanceof Error && error.name === "AbortError"))
452
- ? "cancelled"
453
- : (job.debugOutcome ??
454
- (error instanceof SyncDecisionRequiredError || error instanceof DaemonStoppingError
455
- ? "blocked"
456
- : "failed")));
457
- if (waitForInspectionLog && logged)
458
- await logged;
459
- job.view.phase = "failed";
460
- job.view.error = remoteError(error);
461
- if (diffReviewOwner)
462
- job.controller.abort();
463
- if (job.committed)
464
- for (const id of new Set([client, ...job.peers])) {
465
- const affected = participants.get(id);
466
- if (affected)
467
- affected.resumeUnsafe = true;
468
- }
469
- })
470
- .finally(() => {
471
- for (const waiting of [...pending.values()])
472
- if (waiting.callback.job === id)
473
- waiting.reject(new Error("Operation finished."));
474
- const owner = participants.get(client);
475
- if (owner)
476
- waiters.get(owner)?.changed();
477
- hooks.idle?.();
478
- });
479
- queue = job.promise;
480
- jobs.set(id, job);
481
- return job;
482
- }
483
- function invalidateExpiry(peer) {
484
- peer.expiry?.abort(new DOMException("Client is no longer eligible to resume contact", "AbortError"));
485
- peer.expiry = undefined;
486
- peer.resumeFacts = undefined;
487
- }
488
- async function bootstrapStartup(client, generation, fingerprint, debug, signal, startup) {
489
- const peer = requireParticipant(client);
490
- const before = peer.facts;
491
- const currentParticipant = () => {
492
- assertOwner();
493
- signal.throwIfAborted();
494
- return !ledger.failed && requireParticipant(client) === peer && peer.facts === before;
495
- };
496
- if (before.generation !== generation || !before.hasUI || !["tui", "rpc"].includes(before.mode)) {
497
- throw new Error("Only the attached interactive session can finish startup.");
498
- }
499
- const reviewState = () => {
500
- if (backgroundJobs.size ||
501
- [...participants.values()].some((item) => item.resumeUnsafe || item.reservations?.size))
502
- return;
503
- const running = [...jobs.values()].filter((job) => job.view.phase === "running" || job.view.phase === "queued");
504
- if (!running.length && !pending.size)
505
- return null;
506
- if (running.length !== 1 || pending.size !== 1)
507
- return;
508
- const [job] = running;
509
- const review = pending.values().next().value;
510
- if (job.view.phase === "running" &&
511
- !job.committed &&
512
- !job.controller.signal.aborted &&
513
- job.participantGeneration === undefined &&
514
- review?.startupReviewLock &&
515
- review.callback.job === job.view.id &&
516
- review.target !== client)
517
- return review;
518
- };
519
- if (before.ready || !currentParticipant() || reviewState() === undefined)
520
- return false;
521
- await hooks.factsChanged?.();
522
- return admission.run(async () => {
523
- const review = reviewState();
524
- if (review === undefined || !currentParticipant())
525
- return false;
526
- const validateEvidence = await startup.probe(fingerprint, signal, review?.startupReviewLock);
527
- const recheck = () => currentParticipant() && reviewState() === review;
528
- if (!validateEvidence || !recheck())
529
- return false;
530
- const ready = { ...before, ready: true, startupDebug: debug };
531
- await savePeers({ peer, facts: ready });
532
- let accepted = false;
533
- try {
534
- if (!recheck() || !validateEvidence())
535
- return false;
536
- peer.facts = ready;
537
- accepted = true;
538
- participantsChanged();
539
- hooks.idle?.();
540
- return true;
541
- }
542
- finally {
543
- if (!accepted)
544
- await savePeers();
545
- }
546
- }, signal);
547
- }
548
- async function resumeContact(facts, disconnect) {
549
- const peer = requireParticipant(facts.id, true);
550
- const expiry = peer.expiry;
551
- const matchesSession = (old) => sameDiffReviewBinding(old, facts);
552
- if (!expiry || contactState(peer) !== "expired" || peer.resumeFacts || !matchesSession(peer.facts))
553
- throw new Error("Client is not eligible to resume contact for this session.");
554
- const signal = disconnect ? AbortSignal.any([disconnect, expiry.signal]) : expiry.signal;
555
- const candidate = structuredClone(facts);
556
- const recheck = () => {
557
- assertOwner();
558
- signal.throwIfAborted();
559
- if (ledger.failed)
560
- throw new Error("Daemon client ledger persistence is uncertain; reconcile with the existing owner before reconnecting.");
561
- if (participants.get(facts.id) !== peer ||
562
- peer.expiry !== expiry ||
563
- contactState(peer) !== "expired" ||
564
- !matchesSession(peer.facts))
565
- throw new Error("Client is no longer eligible to resume contact.");
566
- };
567
- const affected = (job) => job.client === facts.id || job.peers.has(facts.id);
568
- const running = (job) => affected(job) && job.view.phase === "running";
569
- const stopped = Promise.withResolvers();
570
- const abort = addAbortListener(signal, () => stopped.reject(signal.reason));
571
- try {
572
- recheck();
573
- // Expose the new binding to the monitor, but only as a non-ready, busy suspect.
574
- peer.resumeFacts = { ...candidate, ready: false };
575
- participantsChanged();
576
- // Never wait for jobs or monitor transitions inside admission: they can need the fence.
577
- await Promise.race([
578
- Promise.all([hooks.factsChanged?.(), ...[...jobs.values()].filter(running).map((job) => job.promise)]),
579
- stopped.promise,
580
- ]);
581
- recheck();
582
- return await admission.run(async () => {
583
- const safe = () => {
584
- recheck();
585
- if (peer.resumeUnsafe ||
586
- peer.reservations?.size ||
587
- peer.callbacks.size ||
588
- [...jobs.values()].some(running) ||
589
- [...backgroundJobs].some((job) => job.committed && affected(job)))
590
- throw new Error("Client work or file-queue cleanup is uncertain; reconcile with the existing owner before reconnecting.");
591
- };
592
- safe();
593
- // The staged facts have the same location and identity. Even if cancelled mid-write,
594
- // the on-disk record does not authorize work or confer expiry eligibility on restart.
595
- await savePeers({ peer, facts: candidate });
596
- safe();
597
- peer.facts = candidate;
598
- peer.seen = Date.now();
599
- peer.expiry = undefined;
600
- peer.resumeFacts = undefined;
601
- peer.suspected = false;
602
- peer.connected = true;
603
- participantsChanged();
604
- hooks.idle?.();
605
- return poll(peer, 0);
606
- }, signal);
607
- }
608
- finally {
609
- abort[Symbol.dispose]();
610
- if (peer.expiry === expiry)
611
- peer.resumeFacts = undefined;
612
- }
613
- }
614
- async function detach(id, retain = false, handoff) {
615
- const peer = participants.get(id);
616
- if (!peer) {
617
- if (closedClients.size < 10_000)
618
- closedClients.add(id);
619
- return { contact: "inactive", cursor: sequence, callbacks: [], events: [] };
620
- }
621
- if (closedClients.has(id))
622
- return poll(peer, 0);
623
- peer.closing = true;
624
- invalidateDiffReview(peer);
625
- participantsChanged();
626
- invalidateExpiry(peer);
627
- for (const waiting of [...pending.values()])
628
- if (waiting.target === id && !waiting.callback.kind.startsWith("queue-"))
629
- waiting.reject(new Error("Client detaching."));
630
- await hooks.factsChanged?.();
631
- const affected = [...jobs.values(), ...backgroundJobs].filter((job) => job.client === id || job.peers.has(id));
632
- for (const job of affected)
633
- if (!job.committed)
634
- job.controller.abort(new DOMException("Client detached", "AbortError"));
635
- await Promise.allSettled(affected.map((job) => job.promise));
636
- peer.connected = false;
637
- participantsChanged();
638
- // Orderly exit remains protected by PID, but is not an ambiguous active participant.
639
- peer.suspected = retain && handoff?.kind !== "exit";
640
- peer.closing = false;
641
- peer.handoff = handoff ?? (retain ? undefined : { kind: "exit" });
642
- if (!retain || handoff?.kind === "exit")
643
- closedClients.add(id);
644
- await savePeers();
645
- const result = poll(peer, 0);
646
- hooks.idle?.();
647
- return result;
648
- }
649
- function stop() {
650
- stopRequested = true;
651
- for (const peer of participants.values())
652
- waiters.get(peer)?.changed();
653
- setImmediate(() => {
654
- void close().catch(() => { });
655
- });
656
- return { stopping: true };
657
- }
658
- function upgradeBlocker() {
659
- if (ledger.failed ||
660
- foregroundRecoveryJob ||
661
- consentPublicationFailed ||
662
- hooks.upgradeAllowed?.() === false ||
663
- [...participants.values()].some((peer) => peer.resumeUnsafe))
664
- return "repair";
665
- if (peerOperations.size ||
666
- expiring ||
667
- backgroundJobs.size ||
668
- pending.size ||
669
- [...jobs.values()].some(({ view }) => view.phase === "queued" || view.phase === "running"))
670
- return "busy";
671
- if ([...participants.values()].some((peer) => peer.reservations?.size))
672
- return "repair";
673
- }
674
- async function stopForUpgrade(params, signal) {
675
- if (!record(params) || Object.keys(params).length !== 0)
676
- throw new Error("Invalid upgrade stop request.");
677
- const checkBarrier = (barrier) => {
678
- signal?.throwIfAborted();
679
- assertOwner();
680
- if (barrier?.purpose || barrier?.instance !== identity.instance || barrier.pid !== identity.pid || !ownsLog())
681
- throw new Error("Daemon owner or upgrade record changed; no stop was accepted.");
682
- };
683
- checkBarrier(await readUpgradeOwner(paths));
684
- const deferred = upgradeBlocker();
685
- if (deferred)
686
- return { deferred };
687
- return admission.run(async () => {
688
- checkBarrier(await readUpgradeOwner(paths));
689
- const deferred = upgradeBlocker();
690
- if (deferred)
691
- return { deferred };
692
- if (Object.values(readConsent(paths.root)?.setups ?? {}).some((setup) => setup.afterExit))
693
- return { deferred: "unattended" };
694
- return stop();
695
- }, signal);
696
- }
697
- async function stopForeground(params, signal) {
698
- if (params.check !== undefined && params.check !== true)
699
- throw new Error("Invalid foreground stop request.");
700
- const barrier = await readUpgradeOwner(paths);
701
- signal?.throwIfAborted();
702
- assertOwner();
703
- if (params.check === true
704
- ? barrier !== undefined
705
- : barrier?.purpose !== "cleanup" || barrier.instance !== identity.instance || barrier.pid !== identity.pid)
706
- return { blocked: "A daemon upgrade or recovery is already pending." };
707
- if (!published || !matchesPublishedIdentity(paths, identity))
708
- return { blocked: "Daemon owner changed during queue cleanup." };
709
- const job = foregroundRecoveryJob;
710
- const requester = validId(params.client) ? participants.get(params.client) : undefined;
711
- if (job?.view.phase !== "done" ||
712
- job.view.id !== params.job ||
713
- !requester ||
714
- requester.facts.id !== job.client ||
715
- requester.facts.generation !== params.generation ||
716
- requester.facts.generation !== job.generation ||
717
- contactState(requester) !== "active")
718
- return { blocked: "The completed transfer is not owned by the current Pi session." };
719
- if (ledger.failed ||
720
- consentPublicationFailed ||
721
- hooks.foregroundRecoveryAllowed?.() !== true ||
722
- Object.values(readConsent(paths.root)?.setups ?? {}).some((setup) => setup.afterExit))
723
- return { blocked: "Daemon authorization or ownership evidence needs repair before a restart." };
724
- if (peerOperations.size ||
725
- expiring ||
726
- backgroundJobs.size ||
727
- pending.size ||
728
- [...jobs.values()].some(({ view }) => view.phase === "queued" || view.phase === "running"))
729
- return { blocked: "Another daemon operation may still be running; no restart was attempted." };
730
- if ([...participants.values()].some((peer) => peer !== requester && participates(peer) && processExists(peer.facts.pid)))
731
- return { blocked: "Another live Pi session still uses this daemon; no restart was attempted." };
732
- return params.check === true ? { eligible: true } : stop();
733
- }
734
- async function handle(method, params, signal, reviewDetails = false) {
735
- if (automaticClosing && method !== "stop")
736
- throw new DaemonStoppingError();
737
- const cleanup = ["answer", "poll", "state-wait", "cancel", "detach", "pause", "handoff", "stop"].includes(method);
738
- if (!published && !cleanup)
739
- throw new Error("Daemon readiness is not published.");
740
- if (!cleanup)
741
- assertOwner();
742
- if (method === "hello")
743
- return {
744
- version: PROTOCOL_VERSION,
745
- ignoreFilesRetired: true,
746
- autonomousSyncRetired: true,
747
- buildVersion: DAEMON_BUILD_VERSION,
748
- ...(DAEMON_BUILD_ID && { buildId: DAEMON_BUILD_ID }),
749
- upgradeStop: 1,
750
- prefixedLifecycleLog: true,
751
- root: identity.root,
752
- instance: identity.instance,
753
- pid: identity.pid,
754
- };
755
- if (method === "upgrade-stop")
756
- return stopForUpgrade(params, signal);
757
- if (method === "protect-session") {
758
- validateFacts(params);
759
- const { pid, cwd, mode, sessionFile } = params;
760
- if (!sessionFile)
761
- throw new Error("A session file is required for protection.");
762
- return admission.run(async () => {
763
- assertOwner();
764
- if (!processExists(pid))
765
- throw new Error("Client process is not alive.");
766
- const recorded = [...participants.values()].some((peer) => peer.handoff?.kind === "exit" && peer.facts.pid === pid && peer.facts.sessionFile === sessionFile);
767
- if (!recorded) {
768
- if (participants.size >= 64 || closedClients.size >= 10_000)
769
- throw new Error("Daemon client capacity reached.");
770
- const id = randomUUID();
771
- participants.set(id, {
772
- facts: { id, pid, generation: id, cwd, mode, sessionFile, hasUI: false, idle: false },
773
- handoff: { kind: "exit" },
774
- callbacks: new Map(),
775
- events: [],
776
- connected: false,
777
- closing: false,
778
- suspected: false,
779
- seen: 0,
780
- });
781
- closedClients.add(id);
782
- }
783
- await savePeers(undefined, recorded);
784
- signal?.throwIfAborted();
785
- assertOwner();
786
- return { protected: true };
787
- }, signal);
788
- }
789
- if (method === "attach") {
790
- const attached = await admission.run(async () => {
791
- assertOwner();
792
- validateFacts(params);
793
- if (closedClients.has(params.id))
794
- throw new Error("Client was retired; attach a new client identity.");
795
- if (closedClients.size >= 10_000)
796
- throw new Error("Client retirement ledger is full; stop and restart the service.");
797
- if (!processExists(params.pid))
798
- throw new Error("Client process is not alive.");
799
- for (const [id, peer] of participants) {
800
- if (!processExists(peer.facts.pid) && !peer.callbacks.size) {
801
- invalidateDiffReview(peer);
802
- participants.delete(id);
803
- }
804
- }
805
- if (!participants.has(params.id) && participants.size >= 64)
806
- throw new Error("Daemon client capacity reached.");
807
- const old = participants.get(params.id);
808
- if (old &&
809
- (old.facts.pid !== params.pid ||
810
- ((old.connected || old.suspected) && old.facts.generation !== params.generation)))
811
- throw new Error("Client identity collision.");
812
- if (old) {
813
- invalidateExpiry(old);
814
- invalidateDiffReview(old);
815
- }
816
- participantsChanged();
817
- const replacement = {
818
- facts: structuredClone(params),
819
- reviewDetails,
820
- reservations: old?.reservations,
821
- resumeUnsafe: old?.resumeUnsafe,
822
- callbacks: old?.callbacks ?? new Map(),
823
- events: old?.events ?? [],
824
- connected: true,
825
- closing: false,
826
- suspected: false,
827
- seen: Date.now(),
828
- publishing: !old,
829
- };
830
- participants.set(params.id, replacement);
831
- try {
832
- await savePeers();
833
- assertOwner();
834
- }
835
- catch (error) {
836
- if (participants.get(params.id) === replacement) {
837
- invalidateDiffReview(replacement);
838
- if (old)
839
- participants.set(params.id, old);
840
- else
841
- participants.delete(params.id);
842
- }
843
- throw error;
844
- }
845
- const attached = requireParticipant(params.id, true);
846
- attached.publishing = false;
847
- participantsChanged();
848
- // A shutdown-confirmed handoff keeps protection across SDK invalidation.
849
- // Publish the replacement first, then retire only the matching closed scope.
850
- for (const [id, peer] of participants) {
851
- const next = peer.handoff;
852
- if (id === params.id || peer.facts.pid !== params.pid || next?.kind !== "replace")
853
- continue;
854
- const matches = next.file !== undefined
855
- ? next.file === params.sessionFile
856
- : next.sessionId !== undefined
857
- ? next.sessionId === params.sessionId
858
- : params.sessionFile === undefined && next.cwd === params.cwd;
859
- if (matches) {
860
- invalidateDiffReview(peer);
861
- participants.delete(id);
862
- closedClients.add(id);
863
- }
864
- }
865
- await savePeers();
866
- assertOwner();
867
- return attached;
868
- }, signal);
869
- // Monitoring can await a queued reservation; never call it while admission is held.
870
- await hooks.factsChanged?.();
871
- assertOwner();
872
- return { ...poll(attached, 0), stateWait: 1 };
873
- }
874
- if (method === "resume-contact") {
875
- validateFacts(params);
876
- return resumeContact(params, signal);
877
- }
878
- if (method === "startup.bootstrap" && hooks.startup) {
879
- if (foregroundRecoveryJob)
880
- throw new Error("File-queue cleanup is pending; startup work did not begin.");
881
- if (!record(params) ||
882
- Object.keys(params).length !== 4 ||
883
- !validId(params.client) ||
884
- !validId(params.generation) ||
885
- typeof params.fingerprint !== "string" ||
886
- !/^[a-f0-9]{64}$/u.test(params.fingerprint) ||
887
- typeof params.debug !== "boolean" ||
888
- !signal)
889
- throw new Error("Invalid startup bootstrap request.");
890
- const peer = requireParticipant(params.client);
891
- peer.seen = Date.now();
892
- return bootstrapStartup(params.client, params.generation, params.fingerprint, params.debug, signal, hooks.startup);
893
- }
894
- if (!record(params))
895
- throw new Error("Invalid request parameters.");
896
- const contact = typeof params.client === "string" ? participants.get(params.client) : undefined;
897
- if (contact)
898
- contact.seen = Date.now();
899
- if (method === "update" && record(params.facts) && typeof params.facts.id === "string") {
900
- const peer = participants.get(params.facts.id);
901
- if (peer)
902
- peer.seen = Date.now();
903
- }
904
- if (method === "update") {
905
- validateFacts(params.facts);
906
- const peer = requireParticipant(params.facts.id, true);
907
- const old = peer.facts;
908
- if (old.pid !== params.facts.pid || old.generation !== params.facts.generation)
909
- throw new Error("Client generation mismatch.");
910
- if (contactState(peer) === "expired")
911
- throw new ClientContactExpiredError();
912
- requireParticipant(params.facts.id);
913
- const published = structuredClone(params.facts);
914
- const bindingChanged = !sameDiffReviewBinding(old, published);
915
- if (bindingChanged)
916
- invalidateDiffReview(peer);
917
- peer.facts = published;
918
- const unchanged = JSON.stringify(old) === JSON.stringify(published);
919
- if (!unchanged)
920
- participantsChanged();
921
- try {
922
- await savePeers(undefined, unchanged);
923
- }
924
- catch (error) {
925
- if (participants.get(published.id) === peer && peer.facts === published) {
926
- peer.facts = old;
927
- if (bindingChanged)
928
- invalidateDiffReview(peer);
929
- }
930
- throw error;
931
- }
932
- await hooks.factsChanged?.();
933
- assertOwner();
934
- if (participants.get(params.facts.id) !== peer)
935
- throw new Error("Client changed during update.");
936
- const reply = poll(peer, 0);
937
- if (reply.contact === "expired")
938
- throw new ClientContactExpiredError();
939
- if (reply.contact !== "active")
940
- throw new Error("Client is not attached or is closing.");
941
- return reply;
942
- }
943
- if (["detach", "pause", "handoff"].includes(method)) {
944
- if (!validId(params.client))
945
- throw new Error("Invalid client.");
946
- const peer = participants.get(params.client);
947
- if (peer &&
948
- ((params.generation !== undefined && params.generation !== peer.facts.generation) ||
949
- (params.pid !== undefined && params.pid !== peer.facts.pid)))
950
- throw new Error("Stale client cleanup cannot detach a replacement generation.");
951
- if (method === "handoff")
952
- validateHandoff(params.handoff);
953
- return detach(params.client, method !== "detach", method === "handoff" ? params.handoff : undefined);
954
- }
955
- if (method === "submit") {
956
- if (!validId(params.id) ||
957
- !validId(params.client) ||
958
- typeof params.operation !== "string" ||
959
- params.operation.length > 64)
960
- throw new Error("Invalid operation envelope.");
961
- return enqueue(params.id, params.client, params.operation, params.payload).view;
962
- }
963
- if (method === "state-wait") {
964
- const peer = requireParticipant(params.client, true);
965
- const client = peer.facts.id;
966
- const generation = peer.facts.generation;
967
- const requested = params.jobs;
968
- if (params.generation !== generation ||
969
- !Array.isArray(requested) ||
970
- requested.length > DAEMON_JOB_CAPACITY ||
971
- !requested.every(validId))
972
- throw new Error("Invalid state wait.");
973
- let mailbox = waiters.get(peer);
974
- if (!mailbox) {
975
- mailbox = new ParticipantStateWait();
976
- waiters.set(peer, mailbox);
977
- }
978
- await mailbox.wait(params.revision, signal);
979
- signal?.throwIfAborted();
980
- if (participants.get(client) !== peer || peer.facts.generation !== generation)
981
- throw new Error("Client changed during state wait.");
982
- const finished = [...jobs.values()]
983
- .filter((job) => job.client === client && (job.view.phase === "done" || job.view.phase === "failed"))
984
- .map((job) => job.view.id);
985
- return {
986
- ...poll(peer, params.cursor),
987
- stateRevision: mailbox.version,
988
- finished,
989
- missing: requested.filter((id) => jobs.get(id)?.client !== client),
990
- };
991
- }
992
- if (method === "poll") {
993
- const peer = requireParticipant(params.client, true);
994
- const job = typeof params.job === "string" ? jobs.get(params.job) : undefined;
995
- if (params.job !== undefined && !job)
996
- throw new Error(UNKNOWN_JOB_RESULT);
997
- if (job && job.client !== params.client)
998
- throw new Error("Operation belongs to another client.");
999
- return poll(peer, params.cursor, job);
1000
- }
1001
- if (method === "review-page") {
1002
- const peer = requireParticipant(params.client);
1003
- const waiting = typeof params.id === "string" ? pending.get(params.id) : undefined;
1004
- if (waiting?.pagedReview) {
1005
- if (waiting.pagedReview.generation !== peer.facts.generation)
1006
- throw new Error("Stale, foreign, or invalid review page.");
1007
- return waiting.pagedReview.page(params);
1008
- }
1009
- if (!waiting?.review ||
1010
- waiting.target !== params.client ||
1011
- !Number.isSafeInteger(params.index) ||
1012
- Number(params.index) < 0 ||
1013
- Number(params.index) >= Math.ceil(waiting.review.length / REVIEW_PAGE_CHARS))
1014
- throw new Error("Stale, foreign, or invalid review page.");
1015
- const start = Number(params.index) * REVIEW_PAGE_CHARS;
1016
- return { id: params.id, index: params.index, content: waiting.review.slice(start, start + REVIEW_PAGE_CHARS) };
1017
- }
1018
- if (method === "answer") {
1019
- const peer = requireParticipant(params.client, true);
1020
- const waiting = typeof params.id === "string" ? pending.get(params.id) : undefined;
1021
- const offer = waiting?.pagedReview;
1022
- if (!waiting ||
1023
- waiting.target !== params.client ||
1024
- (offer && (offer.generation !== peer.facts.generation || params.generation !== offer.generation)))
1025
- throw new Error("Stale or foreign callback response.");
1026
- if (typeof params.error === "string")
1027
- waiting.reject(new Error(params.error.slice(0, 1024)));
1028
- else if (offer && params.value !== false) {
1029
- assertOwner();
1030
- requireParticipant(params.client);
1031
- waiting.resolve(offer.approved(params.value));
1032
- }
1033
- else
1034
- waiting.resolve(params.value);
1035
- return {};
1036
- }
1037
- if (method === "cancel") {
1038
- requireParticipant(params.client, true);
1039
- if (!validId(params.id))
1040
- throw new Error("Invalid operation identity.");
1041
- const job = jobs.get(params.id);
1042
- if (!job) {
1043
- if (cancelled.size >= 128)
1044
- throw new Error("Cancellation capacity reached.");
1045
- cancelled.add(`${params.client}:${params.id}`);
1046
- return { cancelled: true };
1047
- }
1048
- if (job.client !== params.client)
1049
- throw new Error("Operation belongs to another client.");
1050
- if (!job.committed)
1051
- job.controller.abort(new DOMException("Operation cancelled", "AbortError"));
1052
- await job.promise;
1053
- return job.view;
1054
- }
1055
- if (method === "foreground-stop")
1056
- return stopForeground(params, signal);
1057
- if (method === "stop")
1058
- return stop();
1059
- throw new Error("Unknown daemon method.");
1060
- }
1061
- const diffReviewOwner = (client, generation) => {
1062
- const peer = participants.get(client);
1063
- if (peer &&
1064
- peer.facts.generation === generation &&
1065
- peer.facts.mode === "tui" &&
1066
- peer.facts.hasUI &&
1067
- contactState(peer) === "active" &&
1068
- Date.now() - peer.seen <= 5_000)
1069
- return peer.diffReviewOwner;
1070
- };
1071
- const respond = (response, status, value) => {
1072
- let encoded = JSON.stringify(value);
1073
- if (Buffer.byteLength(encoded) > MAX_MESSAGE_BYTES) {
1074
- status = 413;
1075
- encoded = JSON.stringify({ error: { name: "Error", message: "Daemon response exceeds its byte limit." } });
1076
- }
1077
- response.writeHead(status, { "content-type": "application/json", "cache-control": "no-store" });
1078
- response.end(encoded);
1079
- };
1080
- const server = createServer(async (request, response) => {
1081
- let admissionController;
1082
- const disconnect = () => admissionController?.abort(new DOMException("Client disconnected", "AbortError"));
1083
- try {
1084
- if (request.method !== "POST" || request.url !== "/v1") {
1085
- respond(response, 404, { error: { message: "Not found." } });
1086
- return;
1087
- }
1088
- const body = await readJsonBody(request);
1089
- if (!record(body) ||
1090
- body.version !== 1 ||
1091
- body.root !== identity.root ||
1092
- body.instance !== identity.instance ||
1093
- typeof body.token !== "string" ||
1094
- !/^[a-f0-9]{64}$/u.test(body.token) ||
1095
- !timingSafeEqual(Buffer.from(body.token), Buffer.from(identity.token)) ||
1096
- typeof body.method !== "string") {
1097
- respond(response, 403, { error: { name: "Error", message: "Invalid daemon identity or protocol." } });
1098
- return;
1099
- }
1100
- if ([
1101
- "attach",
1102
- "protect-session",
1103
- "resume-contact",
1104
- "startup.bootstrap",
1105
- "state-wait",
1106
- "diff-review-read",
1107
- "foreground-stop",
1108
- "upgrade-stop",
1109
- ].includes(body.method)) {
1110
- admissionController = new AbortController();
1111
- response.once("close", disconnect);
1112
- if (response.destroyed)
1113
- disconnect();
1114
- }
1115
- if (body.method === "diff-review-read" || body.method === "diff-review-close") {
1116
- if (!published)
1117
- throw new Error("Daemon readiness is not published.");
1118
- assertOwner();
1119
- if (!record(body.params))
1120
- throw new Error("Invalid diff review request.");
1121
- await handleDiffReviewRequest(body.method, body.params, admissionController?.signal, diffReviews, diffReviewOwner, assertOwner, (result) => {
1122
- if (!response.destroyed)
1123
- respond(response, 200, { result });
1124
- });
1125
- return;
1126
- }
1127
- const operation = handle(body.method, body.params, admissionController?.signal, body.reviewDetails === 1);
1128
- if ([
1129
- "attach",
1130
- "protect-session",
1131
- "resume-contact",
1132
- "startup.bootstrap",
1133
- "update",
1134
- "detach",
1135
- "pause",
1136
- "handoff",
1137
- ].includes(body.method)) {
1138
- peerOperations.add(operation);
1139
- void operation.finally(() => peerOperations.delete(operation)).catch(() => { });
1140
- }
1141
- respond(response, 200, { result: await operation });
1142
- }
1143
- catch (error) {
1144
- if (!response.destroyed)
1145
- respond(response, 400, { error: remoteError(error) });
1146
- }
1147
- finally {
1148
- response.removeListener("close", disconnect);
1149
- }
1150
- });
1151
- server.requestTimeout = 30_000;
1152
- server.headersTimeout = 10_000;
1153
- const endpoint = endpointOwner(server, paths);
1154
- try {
1155
- assertOwner();
1156
- if (await readUpgradeOwner(paths))
1157
- throw new Error("A daemon upgrade is pending; use normal startup to verify the previous owner.");
1158
- assertOwner();
1159
- await endpoint.listen();
1160
- assertOwner();
1161
- await publishIdentity(paths, identity);
1162
- assertOwner();
1163
- published = true;
1164
- debug?.({ event: "lifecycle", outcome: "starting" });
1165
- }
1166
- catch (error) {
1167
- closed = true;
1168
- return withCleanup(async () => {
1169
- throw error;
1170
- }, () => withCleanup(() => endpoint.close(), release));
1171
- }
1172
- function expireClients() {
1173
- expiring ??= expire().finally(() => {
1174
- expiring = undefined;
1175
- });
1176
- return expiring;
1177
- }
1178
- async function expire() {
1179
- if (closed)
1180
- return;
1181
- let changed = false;
1182
- let participationChanged = false;
1183
- for (const [id, peer] of participants) {
1184
- const exited = !processExists(peer.facts.pid);
1185
- if (!exited && (!peer.connected || Date.now() - peer.seen <= 5_000))
1186
- continue;
1187
- participationChanged ||= participates(peer);
1188
- invalidateDiffReview(peer);
1189
- peer.connected = false;
1190
- peer.suspected = !exited;
1191
- if (exited)
1192
- invalidateExpiry(peer);
1193
- else if (!peer.closing && !peer.publishing)
1194
- peer.expiry = new AbortController();
1195
- waiters.get(peer)?.changed();
1196
- changed = true;
1197
- for (const job of [...jobs.values(), ...backgroundJobs])
1198
- if (!job.committed && (job.client === id || job.peers.has(id)))
1199
- job.controller.abort(new DOMException(exited ? "Client exited" : "Client contact expired", "AbortError"));
1200
- if (exited) {
1201
- for (const waiting of [...pending.values()])
1202
- if (waiting.target === id) {
1203
- if (waiting.callback.kind === "queue-release")
1204
- waiting.resolve(true);
1205
- else
1206
- waiting.reject(new Error("Client process exited."));
1207
- }
1208
- participants.delete(id);
1209
- }
1210
- // Contact expiry alone retains the live session and its uncertain grants.
1211
- }
1212
- if (participationChanged)
1213
- participantsChanged();
1214
- if (changed)
1215
- await savePeers();
1216
- if (participationChanged)
1217
- await hooks.factsChanged?.();
1218
- }
1219
- const lifetime = async () => closed || compromised || ledger.failed ? "pause" : ((await hooks.lifetime?.()) ?? "pause");
1220
- if (hooks.lifetime) {
1221
- idleExit = createIdleExit({
1222
- live: () => liveClientFacts().length > 0,
1223
- policy: lifetime,
1224
- quiesce: async () => {
1225
- for (const job of [...jobs.values(), ...backgroundJobs])
1226
- if (!job.committed)
1227
- job.controller.abort(new DOMException("Daemon idle shutdown", "AbortError"));
1228
- await hooks.quiesce?.();
1229
- await Promise.allSettled([...jobs.values()].map((job) => job.promise));
1230
- await Promise.allSettled([...peerOperations]);
1231
- await expiring;
1232
- await ledger.drain();
1233
- },
1234
- close: (current) => admission.run(async () => {
1235
- if (!current() || closed || ledger.failed || peerOperations.size)
1236
- return false;
1237
- await ledger.drain();
1238
- const owned = await known();
1239
- const policy = await lifetime();
1240
- if (!owned ||
1241
- policy !== "exit" ||
1242
- !current() ||
1243
- closed ||
1244
- compromised ||
1245
- ledger.failed ||
1246
- peerOperations.size ||
1247
- backgroundJobs.size ||
1248
- pending.size ||
1249
- [...jobs.values()].some((job) => job.view.phase === "queued" || job.view.phase === "running"))
1250
- return false;
1251
- assertRoot();
1252
- // Fence new admissions synchronously, then close outside the gate and monitor transition.
1253
- automaticClosing = true;
1254
- closed = true;
1255
- setImmediate(() => {
1256
- void close().catch(() => { });
1257
- });
1258
- return true;
1259
- }),
1260
- resume: () => hooks.idle?.(),
1261
- failed: failure,
1262
- });
1263
- void idleExit.tick();
1264
- }
1265
- heartbeat = setInterval(() => {
1266
- void expireClients()
1267
- .then(() => idleExit?.tick())
1268
- .catch(() => { });
1269
- }, 1_000);
1270
- heartbeat.unref();
1271
- async function close() {
1272
- if (closing)
1273
- return closing;
1274
- closing = (async () => {
1275
- closed = true;
1276
- diffReviews.close();
1277
- for (const peer of participants.values()) {
1278
- invalidateExpiry(peer);
1279
- waiters.get(peer)?.changed();
1280
- }
1281
- clearInterval(heartbeat);
1282
- for (const waiting of [...pending.values()])
1283
- if (!waiting.callback.kind.startsWith("queue-"))
1284
- waiting.reject(new Error("Daemon stopping."));
1285
- for (const job of [...jobs.values(), ...backgroundJobs])
1286
- if (!job.committed)
1287
- job.controller.abort(new DOMException("Daemon stopping", "AbortError"));
1288
- await idleExit?.dispose();
1289
- let closeError;
1290
- try {
1291
- await hooks.close?.();
1292
- }
1293
- catch (error) {
1294
- closeError = error;
1295
- }
1296
- await Promise.allSettled([...jobs.values()].map((job) => job.promise));
1297
- await admission.run(async () => { });
1298
- await Promise.allSettled([...peerOperations]);
1299
- await expiring;
1300
- await ledger.drain();
1301
- for (const waiting of [...pending.values()])
1302
- waiting.reject(new Error("Daemon stopping."));
1303
- // A failed engine drain must retain the live owner, not permit an implicit restart.
1304
- if (closeError)
1305
- throw closeError;
1306
- await endpoint.close();
1307
- const owned = await known();
1308
- if (owned)
1309
- await fs.rm(paths.identity, { force: true });
1310
- await release();
1311
- released = true;
1312
- if (owned && !compromised) {
1313
- try {
1314
- diagnostic?.({ event: "lifecycle", outcome: "drained" }, () => {
1315
- assertRoot();
1316
- return (!lstatSync(paths.owner, { throwIfNoEntry: false }) &&
1317
- !lstatSync(paths.identity, { throwIfNoEntry: false }));
1318
- });
1319
- }
1320
- catch { }
1321
- }
1322
- hooks.stopped?.();
1323
- })().catch((error) => {
1324
- failure();
1325
- closing = undefined;
1326
- throw error;
1327
- });
1328
- return closing;
1329
- }
1330
- function backgroundExecution(signal) {
1331
- assertOwner();
1332
- const job = {
1333
- view: { id: randomUUID(), phase: "running" },
1334
- digest: "",
1335
- participantGeneration,
1336
- controller: new AbortController(),
1337
- committed: false,
1338
- promise: Promise.resolve(),
1339
- peers: new Set(),
1340
- };
1341
- const abort = () => {
1342
- job.controller.abort(signal.reason);
1343
- backgroundJobs.delete(job);
1344
- };
1345
- signal.addEventListener("abort", abort, { once: true });
1346
- backgroundJobs.add(job);
1347
- if (signal.aborted)
1348
- abort();
1349
- return makeExecution(job);
1350
- }
1351
- return {
1352
- identity,
1353
- paths,
1354
- close,
1355
- recordBootOutcome: (outcome) => debug?.({ event: "lifecycle", outcome }),
1356
- backgroundExecution,
1357
- get retainedEndpoint() {
1358
- return endpoint.retainedDirectory;
1359
- },
1360
- participants: participantFacts,
1361
- participantGeneration: () => participantGeneration,
1362
- liveClients: liveClientFacts,
1363
- expireClients,
1364
- // The heartbeat and deterministic lifecycle tests use the same evaluation boundary.
1365
- checkLifetime: () => idleExit?.tick() ?? Promise.resolve(),
1366
- isIdle: () => !closed &&
1367
- !stopRequested &&
1368
- !foregroundRecoveryJob &&
1369
- [...jobs.values()].every((job) => job.view.phase !== "queued" && job.view.phase !== "running"),
1370
- get closed() {
1371
- return closed;
1372
- },
1373
- };
1374
- }