@remnic/core 9.69.87 → 9.69.89

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 (416) hide show
  1. package/dist/access-admin-ops-surface.js +56 -49
  2. package/dist/access-authorization-probe.js +57 -50
  3. package/dist/access-boundary.js +56 -49
  4. package/dist/access-citation-namespace.js +2 -2
  5. package/dist/access-cli.js +129 -122
  6. package/dist/access-cli.js.map +1 -1
  7. package/dist/access-extraction-force-flush.js +56 -49
  8. package/dist/access-http-briefing.js +57 -50
  9. package/dist/access-http-offline-stream.d.ts.map +1 -1
  10. package/dist/access-http-offline-stream.js +1 -1
  11. package/dist/access-http-query.js +58 -51
  12. package/dist/access-http.js +78 -71
  13. package/dist/access-identity-continuity-surface.js +56 -49
  14. package/dist/access-lcm-surface.js +56 -49
  15. package/dist/access-mcp-output-schemas.d.ts.map +1 -1
  16. package/dist/access-mcp-output-schemas.js +1 -1
  17. package/dist/access-mcp.js +69 -62
  18. package/dist/access-namespace-preflight.js +56 -49
  19. package/dist/access-observe-write-category.js +20 -13
  20. package/dist/access-observe-write-surface.js +56 -49
  21. package/dist/access-offline-manifest.js +16 -10
  22. package/dist/access-operations-batch.js +60 -53
  23. package/dist/access-operations.js +67 -60
  24. package/dist/access-recall-concurrency.js +56 -49
  25. package/dist/access-recall-response.js +56 -49
  26. package/dist/access-recall-surface.js +56 -49
  27. package/dist/access-schema.js +16 -7
  28. package/dist/access-service.d.ts.map +1 -1
  29. package/dist/access-service.js +56 -49
  30. package/dist/access-surface-catalog.js +58 -51
  31. package/dist/access-surface-catalog.js.map +1 -1
  32. package/dist/active-recall.js +24 -18
  33. package/dist/active-recall.js.map +1 -1
  34. package/dist/{auto-sync-6IPX2BAC.js → auto-sync-U5N3CB5Y.js} +7 -7
  35. package/dist/briefing.js +11 -11
  36. package/dist/buffer.js +7 -7
  37. package/dist/{capsule-crypto-7FJQINUR.js → capsule-crypto-GWVG7LGC.js} +2 -2
  38. package/dist/{capsule-merge-3MNURAQ3.js → capsule-merge-ZCXUPLNJ.js} +2 -2
  39. package/dist/causal-behavior.js +2 -2
  40. package/dist/causal-chain.js +2 -2
  41. package/dist/causal-consolidation.js +14 -14
  42. package/dist/causal-retrieval.js +2 -2
  43. package/dist/causal-trajectory-graph.js +2 -2
  44. package/dist/causal-trajectory.js +1 -1
  45. package/dist/{chunk-JE334SIA.js → chunk-22DYJLFN.js} +2 -2
  46. package/dist/{chunk-YTQGGO3K.js → chunk-22LMCQ5B.js} +85 -82
  47. package/dist/{chunk-YTQGGO3K.js.map → chunk-22LMCQ5B.js.map} +1 -1
  48. package/dist/{chunk-JGSQ6P4D.js → chunk-2FX374UI.js} +2 -2
  49. package/dist/{chunk-SY5KDWGU.js → chunk-2WLMWP2T.js} +2 -2
  50. package/dist/{chunk-6TT6HRE4.js → chunk-3AGHSQPM.js} +2 -2
  51. package/dist/{chunk-P6WFK4ZJ.js → chunk-3O5BB45T.js} +4 -4
  52. package/dist/{chunk-3C3J243X.js → chunk-3QKO4QN7.js} +3 -3
  53. package/dist/{chunk-KFCMMDHH.js → chunk-3YD44CH2.js} +2 -2
  54. package/dist/{chunk-FRCESVV6.js → chunk-4HUCP4R4.js} +18 -18
  55. package/dist/chunk-4HUCP4R4.js.map +1 -0
  56. package/dist/chunk-4NSLQ7EU.js +137 -0
  57. package/dist/chunk-4NSLQ7EU.js.map +1 -0
  58. package/dist/{chunk-7DE2NOON.js → chunk-4O4XCBOS.js} +3 -3
  59. package/dist/{chunk-GDYU6VF4.js → chunk-5AYUHSAU.js} +2 -2
  60. package/dist/{chunk-ICZQG4XE.js → chunk-5FAGCOZD.js} +4 -4
  61. package/dist/{chunk-VKQI47DJ.js → chunk-5FNZ3G6X.js} +4 -4
  62. package/dist/{chunk-CK5KOVHW.js → chunk-5R627MYY.js} +3 -2
  63. package/dist/{chunk-CK5KOVHW.js.map → chunk-5R627MYY.js.map} +1 -1
  64. package/dist/{chunk-VQNONC4E.js → chunk-5STPRPE7.js} +2 -2
  65. package/dist/{chunk-52II7PB6.js → chunk-645WOU5I.js} +4 -4
  66. package/dist/{chunk-SRZW7FNU.js → chunk-64ZUALXK.js} +2 -2
  67. package/dist/{chunk-4BZP2B4U.js → chunk-6MNKDTDI.js} +2 -2
  68. package/dist/{chunk-DUJYRVUD.js → chunk-6O2VUWV6.js} +3 -3
  69. package/dist/chunk-75PT4N7Q.js +75 -0
  70. package/dist/chunk-75PT4N7Q.js.map +1 -0
  71. package/dist/{chunk-HESDNYRB.js → chunk-76M5OK7V.js} +2 -2
  72. package/dist/{chunk-FAN73COB.js → chunk-7D7OUO5W.js} +2 -2
  73. package/dist/{chunk-DZ525SNQ.js → chunk-7QE46QXI.js} +1 -1
  74. package/dist/{chunk-VX6GCKBS.js → chunk-7WBSMXGC.js} +4 -4
  75. package/dist/{chunk-VVDWZRZG.js → chunk-A6RVIHHK.js} +3 -3
  76. package/dist/{chunk-M536WNTQ.js → chunk-AEJ3TE5H.js} +2 -2
  77. package/dist/{chunk-72JNNJJJ.js → chunk-AXC4WSF3.js} +3 -3
  78. package/dist/chunk-AXGJMDBS.js +684 -0
  79. package/dist/chunk-AXGJMDBS.js.map +1 -0
  80. package/dist/{chunk-UA5DX5C3.js → chunk-AZIOEOK4.js} +2 -2
  81. package/dist/{chunk-N4S4NUX5.js → chunk-B3O3IRZN.js} +1 -1
  82. package/dist/{chunk-XTYX6V52.js → chunk-BJVO4H5C.js} +2 -2
  83. package/dist/{chunk-7LCGFUMB.js → chunk-BUKK5SWA.js} +4 -4
  84. package/dist/{chunk-TM3RXL4G.js → chunk-BUQKSQXL.js} +2 -2
  85. package/dist/chunk-C6HPNPNK.js +64 -0
  86. package/dist/chunk-C6HPNPNK.js.map +1 -0
  87. package/dist/{chunk-RB776UH3.js → chunk-C7V3KPKJ.js} +235 -93
  88. package/dist/chunk-C7V3KPKJ.js.map +1 -0
  89. package/dist/{chunk-FOH7AMMI.js → chunk-CALBQ2NG.js} +71 -72
  90. package/dist/chunk-CALBQ2NG.js.map +1 -0
  91. package/dist/{chunk-37S3IMYB.js → chunk-DGS34QSY.js} +2 -2
  92. package/dist/{chunk-4IEOGIPB.js → chunk-DO4C4AXD.js} +2 -2
  93. package/dist/{chunk-SPSRGEDQ.js → chunk-EAQQ2FD3.js} +9 -9
  94. package/dist/{chunk-3BTFBQLO.js → chunk-EFHNFTWB.js} +49 -3
  95. package/dist/chunk-EFHNFTWB.js.map +1 -0
  96. package/dist/{chunk-C3QXITIP.js → chunk-EQUD7FP4.js} +2 -2
  97. package/dist/chunk-ETUZFFPU.js +218 -0
  98. package/dist/chunk-ETUZFFPU.js.map +1 -0
  99. package/dist/{chunk-YNDLCWXS.js → chunk-EZ25VE3G.js} +4 -4
  100. package/dist/{chunk-YITN5WXI.js → chunk-FC52YWAO.js} +2 -2
  101. package/dist/{chunk-ZI7QA4MK.js → chunk-FEIXG5FA.js} +2 -2
  102. package/dist/{chunk-CLXTDOKV.js → chunk-FUNBJQYR.js} +2 -2
  103. package/dist/{chunk-CLSYE5OZ.js → chunk-G2STTRYB.js} +2 -2
  104. package/dist/{chunk-TDYAIXHK.js → chunk-H36X4NRH.js} +5 -5
  105. package/dist/{chunk-3GQC3NMB.js → chunk-H56VY4BY.js} +5 -5
  106. package/dist/{chunk-PUKTBULQ.js → chunk-HWLIMQE2.js} +2 -2
  107. package/dist/{chunk-V2ES4WCZ.js → chunk-IIARQTZ2.js} +2 -2
  108. package/dist/{chunk-QEV26L2F.js → chunk-IKDRGVVJ.js} +2 -2
  109. package/dist/{chunk-WQZZDN5M.js → chunk-IVEHY2VT.js} +254 -377
  110. package/dist/chunk-IVEHY2VT.js.map +1 -0
  111. package/dist/{chunk-LS3XH3UE.js → chunk-IYIBGSHJ.js} +2 -2
  112. package/dist/{chunk-YSJTCOHR.js → chunk-J27JML5O.js} +2 -2
  113. package/dist/{chunk-AQK54Q7O.js → chunk-JB56XYHP.js} +2 -2
  114. package/dist/{chunk-NE6PHPLG.js → chunk-JBH26P62.js} +10 -10
  115. package/dist/{chunk-CWHV574S.js → chunk-JUT3OR2L.js} +6 -6
  116. package/dist/{chunk-6ET2VII7.js → chunk-JYG2334B.js} +2 -2
  117. package/dist/{chunk-LF5IGOOD.js → chunk-JYM4Y6SO.js} +16 -16
  118. package/dist/{chunk-FB64XE3R.js → chunk-JZ4TJHR2.js} +2 -2
  119. package/dist/{chunk-EHS5MJEF.js → chunk-KTKHO3UI.js} +3 -3
  120. package/dist/{chunk-WIKO4SCR.js → chunk-LHRQBMJN.js} +2 -2
  121. package/dist/{chunk-K4J4E7WV.js → chunk-LO4UKPKX.js} +2 -2
  122. package/dist/{chunk-JN72EPOE.js → chunk-MAAL6OZV.js} +7 -7
  123. package/dist/chunk-MAAL6OZV.js.map +1 -0
  124. package/dist/{chunk-MY2PLXSM.js → chunk-MCTM4YPL.js} +2 -1
  125. package/dist/{chunk-MY2PLXSM.js.map → chunk-MCTM4YPL.js.map} +1 -1
  126. package/dist/{chunk-6NQ4LSMS.js → chunk-MGZMC6WN.js} +47 -47
  127. package/dist/chunk-MSAI3Q7D.js +372 -0
  128. package/dist/chunk-MSAI3Q7D.js.map +1 -0
  129. package/dist/{chunk-BMYZTZ5D.js → chunk-MY7B3HYC.js} +2 -2
  130. package/dist/{chunk-NB3LRY4T.js → chunk-N4PYB235.js} +2 -2
  131. package/dist/{chunk-S3YM4SZQ.js → chunk-N7QV3CMX.js} +2 -2
  132. package/dist/{chunk-L6UZEAID.js → chunk-NJVR724O.js} +4 -4
  133. package/dist/{chunk-VLLD4TOB.js → chunk-NMZVDRVP.js} +2 -2
  134. package/dist/{chunk-P2WZHLUF.js → chunk-NOL7SEWN.js} +2 -2
  135. package/dist/{chunk-2NLLXCJG.js → chunk-OWHERGF2.js} +2 -2
  136. package/dist/{chunk-6L3PBSAR.js → chunk-PMNLL2TL.js} +2 -2
  137. package/dist/{chunk-VYCOJKSX.js → chunk-PO7NXNGC.js} +2 -2
  138. package/dist/{chunk-4IIMMZZK.js → chunk-PULDSMCJ.js} +10 -10
  139. package/dist/{chunk-G6SVZWPB.js → chunk-PZX3AQLF.js} +44 -1
  140. package/dist/chunk-PZX3AQLF.js.map +1 -0
  141. package/dist/{chunk-HBBHL4YF.js → chunk-QOXNTKXB.js} +2 -2
  142. package/dist/{chunk-CUCWX3MO.js → chunk-QZLCVO2V.js} +2 -2
  143. package/dist/{chunk-NE7I2RCT.js → chunk-R3X2T2LP.js} +2 -2
  144. package/dist/{chunk-S7GCT7NU.js → chunk-RBITPCMK.js} +8 -8
  145. package/dist/{chunk-EVBI7S4J.js → chunk-RMDGAAZF.js} +4 -4
  146. package/dist/{chunk-BJRAELDH.js → chunk-SCXURCVT.js} +3 -3
  147. package/dist/{chunk-EQ6YOIKO.js → chunk-ST2RQUXC.js} +3 -3
  148. package/dist/{chunk-CS52MFDV.js → chunk-SZG4WFAG.js} +2 -2
  149. package/dist/{chunk-BFO3IR56.js → chunk-TPEZ2SHV.js} +2 -2
  150. package/dist/chunk-TYT4TEQV.js +45 -0
  151. package/dist/chunk-TYT4TEQV.js.map +1 -0
  152. package/dist/{chunk-YRLHEEQT.js → chunk-U6VC6RP3.js} +2 -2
  153. package/dist/chunk-UCPGOUDZ.js +726 -0
  154. package/dist/chunk-UCPGOUDZ.js.map +1 -0
  155. package/dist/{chunk-MOQPEFLN.js → chunk-UP75KL3L.js} +2 -2
  156. package/dist/{chunk-W4AOR52H.js → chunk-UQDC3W77.js} +2 -2
  157. package/dist/{chunk-X7Y7WX73.js → chunk-UVYI6VIX.js} +1 -1
  158. package/dist/{chunk-D5F7TKMH.js → chunk-V4JZCTMK.js} +2 -2
  159. package/dist/{chunk-MQJL6CDZ.js → chunk-VA4O3U7U.js} +4 -4
  160. package/dist/{chunk-4CDYONWO.js → chunk-VDO32NLK.js} +3 -3
  161. package/dist/{chunk-SOZUJCME.js → chunk-VHDKPGMG.js} +6 -6
  162. package/dist/{chunk-QWW2JDDX.js → chunk-WNRTXEWW.js} +6 -6
  163. package/dist/{chunk-NR2ASHBL.js → chunk-XOV7NRY5.js} +2 -2
  164. package/dist/{chunk-KP7SANCF.js → chunk-YPI4RQWV.js} +2 -2
  165. package/dist/{chunk-JKMHZF3Q.js → chunk-YSWJXOOL.js} +2 -2
  166. package/dist/{chunk-LQG5O5EP.js → chunk-Z3O53WZR.js} +2 -2
  167. package/dist/{chunk-QVS22WTO.js → chunk-ZG5DWWKK.js} +2 -2
  168. package/dist/cli.js +99 -92
  169. package/dist/coding/export-okf-codegraph.js +12 -12
  170. package/dist/coding/pre-action-gate.js +2 -2
  171. package/dist/compounding/engine.js +12 -12
  172. package/dist/config.js +24 -18
  173. package/dist/connectors/codex-materialize-runner.js +11 -11
  174. package/dist/connectors/index.js +11 -11
  175. package/dist/console/state.d.ts +30 -0
  176. package/dist/console/state.d.ts.map +1 -1
  177. package/dist/contradiction/index.js +5 -5
  178. package/dist/convergence-refresh.js +13 -13
  179. package/dist/corpus-watermark.js +13 -13
  180. package/dist/dashboard-runtime.js +2 -2
  181. package/dist/deep-recall-http-glue.js +16 -8
  182. package/dist/embedding-fallback.d.ts +41 -31
  183. package/dist/embedding-fallback.d.ts.map +1 -1
  184. package/dist/embedding-fallback.js +9 -1
  185. package/dist/embedding-generation-lock.d.ts +49 -0
  186. package/dist/embedding-generation-lock.d.ts.map +1 -0
  187. package/dist/embedding-generation-lock.js +19 -0
  188. package/dist/embedding-index-storage.d.ts +276 -0
  189. package/dist/embedding-index-storage.d.ts.map +1 -0
  190. package/dist/embedding-index-storage.js +28 -0
  191. package/dist/entity-retrieval.js +12 -12
  192. package/dist/event-order-recall.js +3 -3
  193. package/dist/explicit-capture.js +6 -6
  194. package/dist/external-wiki-access.js +57 -50
  195. package/dist/extraction.js +17 -17
  196. package/dist/{first-start-migration-7OATHJKB.js → first-start-migration-GAT7G733.js} +4 -4
  197. package/dist/{graph-edge-decay-KQGS3L3B.js → graph-edge-decay-MKIRZ762.js} +5 -5
  198. package/dist/graph-jsonl.js +3 -3
  199. package/dist/graph-snapshot.js +3 -3
  200. package/dist/graph.js +2 -2
  201. package/dist/harmonic-retrieval.js +1 -1
  202. package/dist/index.d.ts +2 -0
  203. package/dist/index.d.ts.map +1 -1
  204. package/dist/index.js +195 -164
  205. package/dist/lcm/engine.js +2 -2
  206. package/dist/lcm/index.js +5 -5
  207. package/dist/local-llm.js +2 -2
  208. package/dist/location/index.js +14 -14
  209. package/dist/maintenance/memory-governance.js +11 -11
  210. package/dist/maintenance/rebuild-memory-lifecycle-ledger.js +11 -11
  211. package/dist/maintenance/rebuild-memory-projection.js +12 -12
  212. package/dist/memory-browse-operations.js +57 -50
  213. package/dist/memory-subject.js +3 -3
  214. package/dist/namespaces/migrate.js +12 -12
  215. package/dist/namespaces/storage.js +11 -11
  216. package/dist/offline-sync-changeset-generations.d.ts +82 -0
  217. package/dist/offline-sync-changeset-generations.d.ts.map +1 -0
  218. package/dist/offline-sync-changeset-generations.js +21 -0
  219. package/dist/offline-sync-embedding-generation.d.ts +257 -0
  220. package/dist/offline-sync-embedding-generation.d.ts.map +1 -0
  221. package/dist/offline-sync-embedding-generation.js +44 -0
  222. package/dist/offline-sync-embedding-generation.js.map +1 -0
  223. package/dist/offline-sync-exclude-globs.d.ts +15 -0
  224. package/dist/offline-sync-exclude-globs.d.ts.map +1 -1
  225. package/dist/offline-sync-exclude-globs.js +11 -3
  226. package/dist/offline-sync-file-io.d.ts +7 -0
  227. package/dist/offline-sync-file-io.d.ts.map +1 -1
  228. package/dist/offline-sync-file-io.js +14 -2
  229. package/dist/offline-sync-impression-drain.js +3 -3
  230. package/dist/offline-sync-runtime-state.d.ts +5 -0
  231. package/dist/offline-sync-runtime-state.d.ts.map +1 -0
  232. package/dist/offline-sync-runtime-state.js +14 -0
  233. package/dist/offline-sync-runtime-state.js.map +1 -0
  234. package/dist/offline-sync-snapshot-stream.d.ts +26 -0
  235. package/dist/offline-sync-snapshot-stream.d.ts.map +1 -0
  236. package/dist/offline-sync-snapshot-stream.js +29 -0
  237. package/dist/offline-sync-snapshot-stream.js.map +1 -0
  238. package/dist/offline-sync-upload-staging.d.ts +34 -0
  239. package/dist/offline-sync-upload-staging.d.ts.map +1 -0
  240. package/dist/offline-sync-upload-staging.js +26 -0
  241. package/dist/offline-sync-upload-staging.js.map +1 -0
  242. package/dist/offline-sync.d.ts +58 -28
  243. package/dist/offline-sync.d.ts.map +1 -1
  244. package/dist/offline-sync.js +22 -8
  245. package/dist/operator-doctor-corpus.js +14 -14
  246. package/dist/operator-toolkit.js +35 -29
  247. package/dist/orchestration/maintenance.js +22 -22
  248. package/dist/orchestrator.d.ts.map +1 -1
  249. package/dist/orchestrator.js +129 -122
  250. package/dist/recall-navigation-operations.js +57 -50
  251. package/dist/recall-navigation.js +56 -49
  252. package/dist/reconcile/manifest.js +4 -4
  253. package/dist/{resolution-DNX7FO7A.js → resolution-K4A3VPKZ.js} +6 -6
  254. package/dist/resolution-K4A3VPKZ.js.map +1 -0
  255. package/dist/resume-bundles.js +25 -19
  256. package/dist/salvage-envelope.js +5 -5
  257. package/dist/secure-store/index.js +2 -2
  258. package/dist/secure-store/secure-fs.d.ts +14 -1
  259. package/dist/secure-store/secure-fs.d.ts.map +1 -1
  260. package/dist/semantic-consolidation.js +12 -12
  261. package/dist/semantic-rule-promotion.js +11 -11
  262. package/dist/semantic-rule-verifier.js +11 -11
  263. package/dist/source-agent-qualifier.js +14 -14
  264. package/dist/standup/build.js +11 -11
  265. package/dist/{state-ITXJKXRE.js → state-JB47KHYV.js} +2 -2
  266. package/dist/state-JB47KHYV.js.map +1 -0
  267. package/dist/storage.d.ts +9 -3
  268. package/dist/storage.d.ts.map +1 -1
  269. package/dist/storage.js +10 -10
  270. package/dist/subject-config.js +4 -4
  271. package/dist/summarizer.js +3 -3
  272. package/dist/support-passport/index.js +59 -52
  273. package/dist/support-passport/offline-sync-guard.d.ts +6 -2
  274. package/dist/support-passport/offline-sync-guard.d.ts.map +1 -1
  275. package/dist/{trace-ZFVRH4GO.js → trace-LXXCMZJA.js} +3 -3
  276. package/dist/transfer/backup.js +2 -2
  277. package/dist/transfer/capsule-export.js +2 -2
  278. package/dist/transfer/capsule-import.js +3 -3
  279. package/dist/transfer/export-okf.js +12 -12
  280. package/dist/{tui-55UJMJX7.js → tui-2Z5WOV7L.js} +3 -3
  281. package/dist/tui-2Z5WOV7L.js.map +1 -0
  282. package/dist/verified-recall.js +11 -11
  283. package/dist/who-knows-cli.js +12 -12
  284. package/dist/who-knows.js +11 -11
  285. package/dist/write-envelope.js +4 -4
  286. package/package.json +2 -2
  287. package/src/access-http-offline-stream.ts +3 -0
  288. package/src/access-mcp-output-schemas.ts +1 -0
  289. package/src/access-service.ts +7 -18
  290. package/src/console/state.test.ts +56 -0
  291. package/src/console/state.ts +83 -0
  292. package/src/embedding-fallback.ts +325 -141
  293. package/src/embedding-generation-lock.ts +141 -0
  294. package/src/embedding-index-storage.test.ts +245 -0
  295. package/src/embedding-index-storage.ts +1068 -0
  296. package/src/index.ts +3 -3
  297. package/src/offline-sync-changeset-generations.test.ts +962 -0
  298. package/src/offline-sync-changeset-generations.ts +549 -0
  299. package/src/offline-sync-embedding-generation.test.ts +2173 -0
  300. package/src/offline-sync-embedding-generation.ts +1153 -0
  301. package/src/offline-sync-exclude-globs.ts +112 -0
  302. package/src/offline-sync-file-io.ts +48 -0
  303. package/src/offline-sync-runtime-state.ts +48 -0
  304. package/src/offline-sync-snapshot-stream.ts +99 -0
  305. package/src/offline-sync-upload-staging.ts +291 -0
  306. package/src/offline-sync.test.ts +164 -1
  307. package/src/offline-sync.ts +372 -454
  308. package/src/orchestrator.ts +2 -1
  309. package/src/secure-store/secure-fs.ts +26 -6
  310. package/src/storage.ts +11 -6
  311. package/src/support-passport/offline-sync-guard.ts +16 -2
  312. package/dist/chunk-3BTFBQLO.js.map +0 -1
  313. package/dist/chunk-AREGMX2J.js +0 -50
  314. package/dist/chunk-AREGMX2J.js.map +0 -1
  315. package/dist/chunk-FOH7AMMI.js.map +0 -1
  316. package/dist/chunk-FRCESVV6.js.map +0 -1
  317. package/dist/chunk-G6SVZWPB.js.map +0 -1
  318. package/dist/chunk-JN72EPOE.js.map +0 -1
  319. package/dist/chunk-RB776UH3.js.map +0 -1
  320. package/dist/chunk-WQZZDN5M.js.map +0 -1
  321. /package/dist/{auto-sync-6IPX2BAC.js.map → auto-sync-U5N3CB5Y.js.map} +0 -0
  322. /package/dist/{capsule-crypto-7FJQINUR.js.map → capsule-crypto-GWVG7LGC.js.map} +0 -0
  323. /package/dist/{capsule-merge-3MNURAQ3.js.map → capsule-merge-ZCXUPLNJ.js.map} +0 -0
  324. /package/dist/{chunk-JE334SIA.js.map → chunk-22DYJLFN.js.map} +0 -0
  325. /package/dist/{chunk-JGSQ6P4D.js.map → chunk-2FX374UI.js.map} +0 -0
  326. /package/dist/{chunk-SY5KDWGU.js.map → chunk-2WLMWP2T.js.map} +0 -0
  327. /package/dist/{chunk-6TT6HRE4.js.map → chunk-3AGHSQPM.js.map} +0 -0
  328. /package/dist/{chunk-P6WFK4ZJ.js.map → chunk-3O5BB45T.js.map} +0 -0
  329. /package/dist/{chunk-3C3J243X.js.map → chunk-3QKO4QN7.js.map} +0 -0
  330. /package/dist/{chunk-KFCMMDHH.js.map → chunk-3YD44CH2.js.map} +0 -0
  331. /package/dist/{chunk-7DE2NOON.js.map → chunk-4O4XCBOS.js.map} +0 -0
  332. /package/dist/{chunk-GDYU6VF4.js.map → chunk-5AYUHSAU.js.map} +0 -0
  333. /package/dist/{chunk-ICZQG4XE.js.map → chunk-5FAGCOZD.js.map} +0 -0
  334. /package/dist/{chunk-VKQI47DJ.js.map → chunk-5FNZ3G6X.js.map} +0 -0
  335. /package/dist/{chunk-VQNONC4E.js.map → chunk-5STPRPE7.js.map} +0 -0
  336. /package/dist/{chunk-52II7PB6.js.map → chunk-645WOU5I.js.map} +0 -0
  337. /package/dist/{chunk-SRZW7FNU.js.map → chunk-64ZUALXK.js.map} +0 -0
  338. /package/dist/{chunk-4BZP2B4U.js.map → chunk-6MNKDTDI.js.map} +0 -0
  339. /package/dist/{chunk-DUJYRVUD.js.map → chunk-6O2VUWV6.js.map} +0 -0
  340. /package/dist/{chunk-HESDNYRB.js.map → chunk-76M5OK7V.js.map} +0 -0
  341. /package/dist/{chunk-FAN73COB.js.map → chunk-7D7OUO5W.js.map} +0 -0
  342. /package/dist/{chunk-DZ525SNQ.js.map → chunk-7QE46QXI.js.map} +0 -0
  343. /package/dist/{chunk-VX6GCKBS.js.map → chunk-7WBSMXGC.js.map} +0 -0
  344. /package/dist/{chunk-VVDWZRZG.js.map → chunk-A6RVIHHK.js.map} +0 -0
  345. /package/dist/{chunk-M536WNTQ.js.map → chunk-AEJ3TE5H.js.map} +0 -0
  346. /package/dist/{chunk-72JNNJJJ.js.map → chunk-AXC4WSF3.js.map} +0 -0
  347. /package/dist/{chunk-UA5DX5C3.js.map → chunk-AZIOEOK4.js.map} +0 -0
  348. /package/dist/{chunk-N4S4NUX5.js.map → chunk-B3O3IRZN.js.map} +0 -0
  349. /package/dist/{chunk-XTYX6V52.js.map → chunk-BJVO4H5C.js.map} +0 -0
  350. /package/dist/{chunk-7LCGFUMB.js.map → chunk-BUKK5SWA.js.map} +0 -0
  351. /package/dist/{chunk-TM3RXL4G.js.map → chunk-BUQKSQXL.js.map} +0 -0
  352. /package/dist/{chunk-37S3IMYB.js.map → chunk-DGS34QSY.js.map} +0 -0
  353. /package/dist/{chunk-4IEOGIPB.js.map → chunk-DO4C4AXD.js.map} +0 -0
  354. /package/dist/{chunk-SPSRGEDQ.js.map → chunk-EAQQ2FD3.js.map} +0 -0
  355. /package/dist/{chunk-C3QXITIP.js.map → chunk-EQUD7FP4.js.map} +0 -0
  356. /package/dist/{chunk-YNDLCWXS.js.map → chunk-EZ25VE3G.js.map} +0 -0
  357. /package/dist/{chunk-YITN5WXI.js.map → chunk-FC52YWAO.js.map} +0 -0
  358. /package/dist/{chunk-ZI7QA4MK.js.map → chunk-FEIXG5FA.js.map} +0 -0
  359. /package/dist/{chunk-CLXTDOKV.js.map → chunk-FUNBJQYR.js.map} +0 -0
  360. /package/dist/{chunk-CLSYE5OZ.js.map → chunk-G2STTRYB.js.map} +0 -0
  361. /package/dist/{chunk-TDYAIXHK.js.map → chunk-H36X4NRH.js.map} +0 -0
  362. /package/dist/{chunk-3GQC3NMB.js.map → chunk-H56VY4BY.js.map} +0 -0
  363. /package/dist/{chunk-PUKTBULQ.js.map → chunk-HWLIMQE2.js.map} +0 -0
  364. /package/dist/{chunk-V2ES4WCZ.js.map → chunk-IIARQTZ2.js.map} +0 -0
  365. /package/dist/{chunk-QEV26L2F.js.map → chunk-IKDRGVVJ.js.map} +0 -0
  366. /package/dist/{chunk-LS3XH3UE.js.map → chunk-IYIBGSHJ.js.map} +0 -0
  367. /package/dist/{chunk-YSJTCOHR.js.map → chunk-J27JML5O.js.map} +0 -0
  368. /package/dist/{chunk-AQK54Q7O.js.map → chunk-JB56XYHP.js.map} +0 -0
  369. /package/dist/{chunk-NE6PHPLG.js.map → chunk-JBH26P62.js.map} +0 -0
  370. /package/dist/{chunk-CWHV574S.js.map → chunk-JUT3OR2L.js.map} +0 -0
  371. /package/dist/{chunk-6ET2VII7.js.map → chunk-JYG2334B.js.map} +0 -0
  372. /package/dist/{chunk-LF5IGOOD.js.map → chunk-JYM4Y6SO.js.map} +0 -0
  373. /package/dist/{chunk-FB64XE3R.js.map → chunk-JZ4TJHR2.js.map} +0 -0
  374. /package/dist/{chunk-EHS5MJEF.js.map → chunk-KTKHO3UI.js.map} +0 -0
  375. /package/dist/{chunk-WIKO4SCR.js.map → chunk-LHRQBMJN.js.map} +0 -0
  376. /package/dist/{chunk-K4J4E7WV.js.map → chunk-LO4UKPKX.js.map} +0 -0
  377. /package/dist/{chunk-6NQ4LSMS.js.map → chunk-MGZMC6WN.js.map} +0 -0
  378. /package/dist/{chunk-BMYZTZ5D.js.map → chunk-MY7B3HYC.js.map} +0 -0
  379. /package/dist/{chunk-NB3LRY4T.js.map → chunk-N4PYB235.js.map} +0 -0
  380. /package/dist/{chunk-S3YM4SZQ.js.map → chunk-N7QV3CMX.js.map} +0 -0
  381. /package/dist/{chunk-L6UZEAID.js.map → chunk-NJVR724O.js.map} +0 -0
  382. /package/dist/{chunk-VLLD4TOB.js.map → chunk-NMZVDRVP.js.map} +0 -0
  383. /package/dist/{chunk-P2WZHLUF.js.map → chunk-NOL7SEWN.js.map} +0 -0
  384. /package/dist/{chunk-2NLLXCJG.js.map → chunk-OWHERGF2.js.map} +0 -0
  385. /package/dist/{chunk-6L3PBSAR.js.map → chunk-PMNLL2TL.js.map} +0 -0
  386. /package/dist/{chunk-VYCOJKSX.js.map → chunk-PO7NXNGC.js.map} +0 -0
  387. /package/dist/{chunk-4IIMMZZK.js.map → chunk-PULDSMCJ.js.map} +0 -0
  388. /package/dist/{chunk-HBBHL4YF.js.map → chunk-QOXNTKXB.js.map} +0 -0
  389. /package/dist/{chunk-CUCWX3MO.js.map → chunk-QZLCVO2V.js.map} +0 -0
  390. /package/dist/{chunk-NE7I2RCT.js.map → chunk-R3X2T2LP.js.map} +0 -0
  391. /package/dist/{chunk-S7GCT7NU.js.map → chunk-RBITPCMK.js.map} +0 -0
  392. /package/dist/{chunk-EVBI7S4J.js.map → chunk-RMDGAAZF.js.map} +0 -0
  393. /package/dist/{chunk-BJRAELDH.js.map → chunk-SCXURCVT.js.map} +0 -0
  394. /package/dist/{chunk-EQ6YOIKO.js.map → chunk-ST2RQUXC.js.map} +0 -0
  395. /package/dist/{chunk-CS52MFDV.js.map → chunk-SZG4WFAG.js.map} +0 -0
  396. /package/dist/{chunk-BFO3IR56.js.map → chunk-TPEZ2SHV.js.map} +0 -0
  397. /package/dist/{chunk-YRLHEEQT.js.map → chunk-U6VC6RP3.js.map} +0 -0
  398. /package/dist/{chunk-MOQPEFLN.js.map → chunk-UP75KL3L.js.map} +0 -0
  399. /package/dist/{chunk-W4AOR52H.js.map → chunk-UQDC3W77.js.map} +0 -0
  400. /package/dist/{chunk-X7Y7WX73.js.map → chunk-UVYI6VIX.js.map} +0 -0
  401. /package/dist/{chunk-D5F7TKMH.js.map → chunk-V4JZCTMK.js.map} +0 -0
  402. /package/dist/{chunk-MQJL6CDZ.js.map → chunk-VA4O3U7U.js.map} +0 -0
  403. /package/dist/{chunk-4CDYONWO.js.map → chunk-VDO32NLK.js.map} +0 -0
  404. /package/dist/{chunk-SOZUJCME.js.map → chunk-VHDKPGMG.js.map} +0 -0
  405. /package/dist/{chunk-QWW2JDDX.js.map → chunk-WNRTXEWW.js.map} +0 -0
  406. /package/dist/{chunk-NR2ASHBL.js.map → chunk-XOV7NRY5.js.map} +0 -0
  407. /package/dist/{chunk-KP7SANCF.js.map → chunk-YPI4RQWV.js.map} +0 -0
  408. /package/dist/{chunk-JKMHZF3Q.js.map → chunk-YSWJXOOL.js.map} +0 -0
  409. /package/dist/{chunk-LQG5O5EP.js.map → chunk-Z3O53WZR.js.map} +0 -0
  410. /package/dist/{chunk-QVS22WTO.js.map → chunk-ZG5DWWKK.js.map} +0 -0
  411. /package/dist/{graph-edge-decay-KQGS3L3B.js.map → embedding-generation-lock.js.map} +0 -0
  412. /package/dist/{resolution-DNX7FO7A.js.map → embedding-index-storage.js.map} +0 -0
  413. /package/dist/{first-start-migration-7OATHJKB.js.map → first-start-migration-GAT7G733.js.map} +0 -0
  414. /package/dist/{state-ITXJKXRE.js.map → graph-edge-decay-MKIRZ762.js.map} +0 -0
  415. /package/dist/{tui-55UJMJX7.js.map → offline-sync-changeset-generations.js.map} +0 -0
  416. /package/dist/{trace-ZFVRH4GO.js.map → trace-LXXCMZJA.js.map} +0 -0
@@ -0,0 +1,1153 @@
1
+ // Embedding-index generation semantics for offline sync (issue #3146, PR
2
+ // #3148). Extracted from offline-sync.ts so the god-file line-count ratchet
3
+ // does not grow when the rules gain behavior. The snapshot walker treats
4
+ // every `state/embeddings/` shard set — or a legacy `state/embeddings.json`
5
+ // marker — as ONE generation, in both directions:
6
+ //
7
+ // 1. Atomic replacement (apply side): an incoming generation is staged
8
+ // complete, verified byte-for-byte, and published through the store's
9
+ // single backup-swap state machine. A crash or write failure can never
10
+ // leave a mix of the local and incoming generation on disk, and a
11
+ // local-only shard of a replaced generation is removed by the swap, not
12
+ // merged into the incoming set.
13
+ // 2. Filter-to-omit, never filter-to-delete (push side): when an exclusion
14
+ // filter removes ANY member of a local generation from a push, the
15
+ // WHOLE generation is omitted — files and deletion metadata — and the
16
+ // receiver keeps its copy. A filtered generation must never look
17
+ // deleted, and a partially filtered snapshot must never look like a
18
+ // complete generation.
19
+ import { createHash, randomBytes } from "node:crypto";
20
+ import { lstat, mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises";
21
+ import path from "node:path";
22
+ import {
23
+ type EmbeddingIndexFile,
24
+ EmbeddingIndexFileStore,
25
+ type EmbeddingIndexIdentity,
26
+ type EmbeddingIndexStoreIo,
27
+ EmbeddingIndexStorageError,
28
+ parseEmbeddingIndexDocument,
29
+ serializeEmbeddingShard,
30
+ shardEntriesForIndex,
31
+ validateShardMembership,
32
+ } from "./embedding-index-storage.js";
33
+ import {
34
+ assertEmbeddingGenerationLockHeld,
35
+ type EmbeddingGenerationFence,
36
+ embeddingGenerationLockPath,
37
+ withEmbeddingGenerationLock,
38
+ } from "./embedding-generation-lock.js";
39
+ import type { OfflineSyncExcludeFile, OfflineSyncFileTarget } from "./offline-sync-file-io.js";
40
+ import { EMBEDDING_SHARD_FILE_PATTERN } from "./offline-sync-runtime-state.js";
41
+ import { log } from "./logger.js";
42
+ import type {
43
+ OfflineSyncFileDeleteTarget,
44
+ OfflineSyncFileStagingReadTarget,
45
+ OfflineSyncFileStagingWriteTarget,
46
+ OfflineSyncFileState,
47
+ } from "./offline-sync.js";
48
+ import { type SafeArchiveRoot, resolveSafeArchiveTarget } from "./transfer/fs-utils.js";
49
+
50
+ const EMBEDDING_MARKER_BASENAME = "embeddings.json";
51
+ export const EMBEDDING_SHARD_DIR_BASENAME = "embeddings";
52
+
53
+ /**
54
+ * Canonical `state` dir prefix ("state" or "namespaces/<ns>/state") for a
55
+ * path's segments, or null when the path is not canonical runtime state.
56
+ */
57
+ function canonicalStateDirPrefix(parts: string[]): string | null {
58
+ if (parts[0] === "state") return "state";
59
+ if (parts[0] === "namespaces" && parts.length >= 4 && parts[2] === "state") {
60
+ return `namespaces/${parts[1]}/state`;
61
+ }
62
+ return null;
63
+ }
64
+
65
+ /** The sharded-generation directory when `relPath` is one of its shards. */
66
+ export function embeddingShardDirOf(relPath: string): string | null {
67
+ const parts = relPath.split("/");
68
+ if (parts.length < 3) return null;
69
+ if (!EMBEDDING_SHARD_FILE_PATTERN.test(parts[parts.length - 1] ?? "")) return null;
70
+ if (parts[parts.length - 2] !== EMBEDDING_SHARD_DIR_BASENAME) return null;
71
+ if (canonicalStateDirPrefix(parts) === null) return null;
72
+ return parts.slice(0, -1).join("/");
73
+ }
74
+
75
+ /**
76
+ * True when `dirPath` is a canonical embeddings generation dir
77
+ * (`state/embeddings` or `namespaces/<ns>/state/embeddings`). Encodes the
78
+ * snapshot-field shape contract without a ReDoS-shaped literal (issue #2439).
79
+ */
80
+ export function isEmbeddingGenerationDirPath(dirPath: string): boolean {
81
+ const membership = embeddingGenerationMembership(`${dirPath}/shard-0000.json`);
82
+ return membership !== null && membership.shardDir === dirPath;
83
+ }
84
+
85
+ /** The state dir when `relPath` is the legacy single-file marker. */
86
+ export function embeddingMarkerDirOf(relPath: string): string | null {
87
+ const parts = relPath.split("/");
88
+ if ((parts[parts.length - 1] ?? "") !== EMBEDDING_MARKER_BASENAME) return null;
89
+ if (canonicalStateDirPrefix(parts) === null) return null;
90
+ return parts.slice(0, -1).join("/");
91
+ }
92
+
93
+ /**
94
+ * Membership of `relPath` in an embedding generation: shards belong to their
95
+ * `.../embeddings` directory, the legacy marker belongs to the sibling
96
+ * `.../embeddings` directory of its state dir.
97
+ */
98
+ export function embeddingGenerationMembership(relPath: string): { kind: "shard" | "marker"; shardDir: string } | null {
99
+ const shardDir = embeddingShardDirOf(relPath);
100
+ if (shardDir) return { kind: "shard", shardDir };
101
+ const markerDir = embeddingMarkerDirOf(relPath);
102
+ if (markerDir) return { kind: "marker", shardDir: `${markerDir}/${EMBEDDING_SHARD_DIR_BASENAME}` };
103
+ return null;
104
+ }
105
+
106
+ export interface IncomingEmbeddingGenerations {
107
+ /** Generation dirs with at least one incoming shard. */
108
+ shardDirs: Set<string>;
109
+ /** State dirs whose incoming snapshot carries the legacy marker. */
110
+ legacyMarkerDirs: Set<string>;
111
+ }
112
+
113
+ /** Classify incoming snapshot paths into embedding generations. */
114
+ export function detectIncomingEmbeddingGenerations(incomingPaths: Iterable<string>): IncomingEmbeddingGenerations {
115
+ const shardDirs = new Set<string>();
116
+ const legacyMarkerDirs = new Set<string>();
117
+ for (const relPath of incomingPaths) {
118
+ const membership = embeddingGenerationMembership(relPath);
119
+ if (!membership) continue;
120
+ if (membership.kind === "shard") shardDirs.add(membership.shardDir);
121
+ else legacyMarkerDirs.add(membership.shardDir);
122
+ }
123
+ return { shardDirs, legacyMarkerDirs };
124
+ }
125
+
126
+ function shardRelPath(shardDirRel: string, shardIndex: number): string {
127
+ return `${shardDirRel}/shard-${String(shardIndex).padStart(4, "0")}.json`;
128
+ }
129
+
130
+ function describeIndexReadFailure(
131
+ read: { outcome: "absent" } | { outcome: "foreign" } | { outcome: "unreadable"; reason: string }
132
+ ): string {
133
+ if (read.outcome === "unreadable") return read.reason;
134
+ if (read.outcome === "foreign") return "unrecognized index format";
135
+ return "generation document is absent";
136
+ }
137
+
138
+ function sha256Hex(buffer: Buffer): string {
139
+ return createHash("sha256").update(buffer).digest("hex");
140
+ }
141
+
142
+ async function pathExists(absPath: string): Promise<boolean> {
143
+ try {
144
+ await lstat(absPath);
145
+ return true;
146
+ } catch (err) {
147
+ if ((err as NodeJS.ErrnoException).code === "ENOENT") return false;
148
+ throw err;
149
+ }
150
+ }
151
+
152
+ export interface EmbeddingGenerationTransactionIo {
153
+ /** Storage-backed local read: hydrates unchanged shards (metadata-only
154
+ * pulls skip their content) and decrypts secure-store files. */
155
+ readFile?: (target: OfflineSyncFileTarget) => Promise<Buffer>;
156
+ writeStagingFile?: (target: OfflineSyncFileStagingWriteTarget) => Promise<void>;
157
+ readStagingFile?: (target: OfflineSyncFileStagingReadTarget) => Promise<Buffer>;
158
+ deleteFile?: (target: OfflineSyncFileDeleteTarget) => Promise<void>;
159
+ }
160
+
161
+ export interface EmbeddingGenerationTransactionInput {
162
+ root: SafeArchiveRoot;
163
+ /** The generation dir, e.g. `state/embeddings`. */
164
+ shardDirRel: string;
165
+ /** Incoming shard rel paths — the complete incoming sharded generation. */
166
+ incomingShardPaths: string[];
167
+ /** Incoming legacy marker (rel path + verified content), when the
168
+ * incoming generation is legacy-layout. Mutually exclusive with
169
+ * `incomingShardPaths`. */
170
+ incomingMarker: { path: string; sha256: string; buffer: Buffer | null } | null;
171
+ /** True when the incoming snapshot ALSO carries the legacy marker while
172
+ * shards form the generation (mixed remote): the per-file loop then writes
173
+ * the marker as the inert remote artifact, so this transaction must NOT
174
+ * remove a local marker. */
175
+ incomingMarkerPresent: boolean;
176
+ /** Incoming shard records (sha256 for local hydration of unchanged
177
+ * metadata-only pulls). */
178
+ incomingShardStates: ReadonlyMap<string, OfflineSyncFileState>;
179
+ /** Verified incoming content by rel path (absent for shards the metadata
180
+ * hydration skipped because the local hash already matches). */
181
+ incomingBuffers: ReadonlyMap<string, Buffer>;
182
+ /**
183
+ * Shared-base states (pre-census): lets the transaction re-evaluate
184
+ * divergence against ACTUAL disk contents while holding the mutation
185
+ * lock, instead of trusting the census taken before the lock
186
+ * (codex P1: a daemon mutation between census and lock was discarded).
187
+ */
188
+ baseStates?: ReadonlyMap<string, { sha256: string }>;
189
+ /**
190
+ * Paths this apply is pre-authorized to remove (changeset deletes / remote
191
+ * tombstones). A base member absent from the under-lock census is
192
+ * divergence UNLESS it is pre-authorized — the retry after a response loss
193
+ * must re-apply idempotently instead of failing as diverged (#3150
194
+ * review). A pre-authorized member still present with a changed digest
195
+ * defers as before, so a daemon rewrite is never silently swept.
196
+ */
197
+ justifiedRemovals?: ReadonlySet<string>;
198
+ /**
199
+ * Deletion revisions (mtimeMs by path) to record through the delete hook
200
+ * AFTER the swap publishes. Swept members bypass the per-file delete path,
201
+ * so without this their tombstones are lost and a later peer without
202
+ * shared-base evidence can reintroduce the removed shards (codex P1).
203
+ */
204
+ deletionMtimeByPath?: ReadonlyMap<string, number>;
205
+ /**
206
+ * True when the incoming set claims to be a FRESH creation but carries no
207
+ * base evidence (manifested changeset members are all base-less upserts):
208
+ * a non-empty local generation must match the incoming set exactly or the
209
+ * apply defers as diverged, because the empty-base divergence skip would
210
+ * otherwise silently replace it (#3150 review).
211
+ */
212
+ freshCreateClaim?: boolean;
213
+ io: EmbeddingGenerationTransactionIo;
214
+ now: number;
215
+ }
216
+
217
+ export interface EmbeddingGenerationTransactionResult {
218
+ shardDirRel: string;
219
+ upserted: number;
220
+ deleted: number;
221
+ /** nextBase states for files the transaction published. */
222
+ writtenStates: Map<string, OfflineSyncFileState>;
223
+ /** nextBase paths the transaction removed (stale shards, demoted marker). */
224
+ removedPaths: Set<string>;
225
+ /** Paths the per-file apply loop must skip — all handled here. */
226
+ handledPaths: Set<string>;
227
+ /** True when the generation was deferred (not published) because the disk
228
+ * diverged from the shared base while the lock was held. */
229
+ deferredLocalDivergence?: boolean;
230
+ }
231
+
232
+ /**
233
+ * Content for ONE incoming generation member: the verified incoming buffer,
234
+ * or the LOCAL file hash-verified against the incoming record (metadata-only
235
+ * pulls skip content whose local hash already matches — the local bytes ARE
236
+ * the incoming content). Shared by the shard and legacy-marker branches.
237
+ */
238
+ async function hydratedIncomingBuffer(
239
+ io: EmbeddingGenerationTransactionIo,
240
+ root: SafeArchiveRoot,
241
+ relPath: string,
242
+ expectedSha256: string,
243
+ incoming: Buffer | null | undefined,
244
+ ): Promise<Buffer> {
245
+ if (incoming) return incoming;
246
+ const filePath = await resolveSafeArchiveTarget(root, relPath);
247
+ const local = io.readFile
248
+ ? await io.readFile({ root: root.abs, path: relPath, filePath })
249
+ : await readFile(filePath);
250
+ if (sha256Hex(local) !== expectedSha256) {
251
+ throw new EmbeddingIndexStorageError(
252
+ `cannot hydrate unchanged embedding index file ${relPath}: local digest does not match the incoming record; local generation preserved`,
253
+ );
254
+ }
255
+ return local;
256
+ }
257
+
258
+ /**
259
+ * Apply ONE incoming embedding generation atomically (issue #3148, round 4):
260
+ * recover an interrupted replacement, validate the complete incoming
261
+ * generation (legacy markers are converted to the sharded layout so the
262
+ * one-way layout is preserved), stage it, verify the staged bytes, then
263
+ * publish through the shared backup-swap. Any failure before the swap leaves
264
+ * the local generation untouched; a crash in the swap gap is rolled back by
265
+ * the store's recovery on next use.
266
+ */
267
+ /**
268
+ * Enumerate and hash the ACTUAL local generation on disk (legacy marker +
269
+ * every shard) through the configured secure IO — the fresh in-lock census
270
+ * the stale pre-lock apply census cannot be trusted for (codex P1).
271
+ */
272
+ /** Scope the shared vault base to this physical embedding generation. */
273
+ function baseStatesForGeneration(
274
+ base: ReadonlyMap<string, { sha256: string }> | undefined,
275
+ shardDirRel: string,
276
+ ): Map<string, { sha256: string }> {
277
+ return new Map([...base ?? []].filter(([relPath]) => embeddingGenerationMembership(relPath)?.shardDir === shardDirRel));
278
+ }
279
+
280
+ async function censusGenerationState(
281
+ io: EmbeddingGenerationTransactionIo,
282
+ root: SafeArchiveRoot,
283
+ markerRel: string,
284
+ markerAbs: string,
285
+ shardDirAbs: string,
286
+ shardDirRel: string,
287
+ ): Promise<Map<string, string>> {
288
+ const census = new Map<string, string>();
289
+ const readSha = async (relPath: string, filePath: string) =>
290
+ sha256Hex(io.readFile ? await io.readFile({ root: root.abs, path: relPath, filePath }) : await readFile(filePath));
291
+ if (await pathExists(markerAbs)) census.set(markerRel, await readSha(markerRel, markerAbs));
292
+ const names = await readdir(shardDirAbs).catch((err: NodeJS.ErrnoException) => {
293
+ if (err.code === "ENOENT") return [] as string[];
294
+ throw err;
295
+ });
296
+ for (const name of names.filter((candidate) => EMBEDDING_SHARD_FILE_PATTERN.test(candidate)).sort()) {
297
+ const relPath = `${shardDirRel}/${name}`;
298
+ census.set(relPath, await readSha(relPath, path.join(shardDirAbs, name)));
299
+ }
300
+ return census;
301
+ }
302
+
303
+ /** Incoming member states for the divergence helper (digests as fallback). */
304
+ function incomingGenerationStates(input: EmbeddingGenerationTransactionInput): { path: string; sha256: string }[] {
305
+ const states = input.incomingShardPaths.map((relPath) => ({
306
+ path: relPath,
307
+ sha256: input.incomingShardStates.get(relPath)?.sha256 ?? sha256Hex(input.incomingBuffers.get(relPath) ?? Buffer.alloc(0)),
308
+ }));
309
+ if (input.incomingMarker) {
310
+ states.push({ path: input.incomingMarker.path, sha256: input.incomingMarker.sha256 });
311
+ }
312
+ return states;
313
+ }
314
+
315
+ export async function applyEmbeddingGenerationTransaction(
316
+ input: EmbeddingGenerationTransactionInput
317
+ ): Promise<EmbeddingGenerationTransactionResult> {
318
+ const { root, shardDirRel, io } = input;
319
+ const stateDirRel = shardDirRel.slice(0, -`/${EMBEDDING_SHARD_DIR_BASENAME}`.length);
320
+ const stateDirAbs = await resolveSafeArchiveTarget(root, stateDirRel);
321
+ return await withEmbeddingGenerationLock(stateDirAbs, async (section) => {
322
+ const lockPath = embeddingGenerationLockPath(stateDirAbs);
323
+ const fence: EmbeddingGenerationFence = () => assertEmbeddingGenerationLockHeld(lockPath, section);
324
+ const markerRel = `${stateDirRel}/${EMBEDDING_MARKER_BASENAME}`;
325
+ const shardDirAbs = await resolveSafeArchiveTarget(root, shardDirRel);
326
+ const markerAbs = await resolveSafeArchiveTarget(root, markerRel);
327
+ const store = new EmbeddingIndexFileStore(
328
+ markerAbs,
329
+ shardDirAbs,
330
+ await resolveSafeArchiveTarget(root, `${stateDirRel}/embedding-fallback-status.json`)
331
+ );
332
+
333
+ // 1. Close a pending rename gap (old generation restored) before staging:
334
+ // the swap below must never build on a half-replaced generation. The
335
+ // fixed backup path is validated first: a planted symlink (or any
336
+ // escape) must fail closed instead of being renamed into the published
337
+ // position or removed through. The restored target is re-resolved so a
338
+ // symlinked restoration cannot slip past the subsequent IO.
339
+ const backupRel = `${stateDirRel}/embeddings.pre-replace.tmp`;
340
+ await resolveSafeArchiveTarget(root, backupRel);
341
+ if (await store.recoverIfInterrupted(fence)) {
342
+ await resolveSafeArchiveTarget(root, shardDirRel);
343
+ }
344
+
345
+ // Codex P1: the apply census was taken BEFORE this lock, so it may be
346
+ // stale. Re-enumerate and hash the ACTUAL local generation through the
347
+ // secure IO and defer the WHOLE generation when the disk no longer
348
+ // matches the shared base — a concurrent daemon mutation must never be
349
+ // silently discarded by the swap.
350
+ // No shared base (fresh catch-up) = no divergence semantics to protect,
351
+ // UNLESS the apply claims a fresh creation (manifested base-less
352
+ // upserts): an existing local generation must then match the incoming
353
+ // set exactly or defer, instead of being silently replaced.
354
+ const justifiedRemovals = input.justifiedRemovals ?? new Set<string>();
355
+ const baseStates = baseStatesForGeneration(input.baseStates, shardDirRel);
356
+ if (baseStates.size > 0) {
357
+ const localCensus = await censusGenerationState(io, root, markerRel, markerAbs, shardDirAbs, shardDirRel);
358
+ const baseArr = [...baseStates].map(([relPath, state]) => ({ path: relPath, sha256: state.sha256 }));
359
+ const censusArr = [...localCensus].map(([relPath, sha256]) => ({ path: relPath, sha256 }));
360
+ const deferrals = divergedEmbeddingGenerationDeferrals({
361
+ incomingFiles: incomingGenerationStates(input),
362
+ // A pre-authorized removal keeps its base entry only while still on
363
+ // disk (digest auth): present members are compared normally — a
364
+ // daemon rewrite still defers — while an absent member is already
365
+ // applied and must not diverge the retry (#3150 review).
366
+ baseFiles: baseArr.filter((member) => !justifiedRemovals.has(member.path) || localCensus.has(member.path)),
367
+ currentFiles: censusArr,
368
+ });
369
+ const incomingShardPaths = new Set(input.incomingShardPaths);
370
+ const addedOrRemovedSinceBase =
371
+ censusArr.some((member) =>
372
+ !baseStates.has(member.path) &&
373
+ !justifiedRemovals.has(member.path) &&
374
+ // An incoming member found in the census is the apply's own
375
+ // already-published work (response-loss retry), not a local
376
+ // addition; its bytes were verified above.
377
+ !incomingShardPaths.has(member.path)) ||
378
+ baseArr.some((member) => !localCensus.has(member.path) && !justifiedRemovals.has(member.path));
379
+ if (deferrals.length > 0 || addedOrRemovedSinceBase) {
380
+ const handled = new Set<string>(input.incomingShardPaths);
381
+ if (input.incomingMarker) handled.add(input.incomingMarker.path);
382
+ if (input.incomingMarkerPresent) handled.add(markerRel);
383
+ for (const relPath of localCensus.keys()) handled.add(relPath);
384
+ log.warn(
385
+ `embedding generation ${shardDirRel} deferred: disk diverged from the shared base under the mutation lock (${deferrals.length > 0 ? deferrals.join(", ") : "generation membership changed since base"}); nothing published, nothing removed`,
386
+ );
387
+ return {
388
+ shardDirRel,
389
+ upserted: 0,
390
+ deleted: 0,
391
+ writtenStates: new Map<string, OfflineSyncFileState>(),
392
+ removedPaths: new Set<string>(),
393
+ handledPaths: handled,
394
+ deferredLocalDivergence: true,
395
+ };
396
+ }
397
+ } else if (input.freshCreateClaim) {
398
+ const localCensus = await censusGenerationState(io, root, markerRel, markerAbs, shardDirAbs, shardDirRel);
399
+ if (localCensus.size > 0) {
400
+ const incomingArr = incomingGenerationStates(input).sort((left, right) => left.path.localeCompare(right.path));
401
+ const censusArr = [...localCensus]
402
+ .map(([relPath, sha256]) => ({ path: relPath, sha256 }))
403
+ .sort((left, right) => left.path.localeCompare(right.path));
404
+ const identical =
405
+ censusArr.length === incomingArr.length &&
406
+ censusArr.every((member, index) => member.path === incomingArr[index]?.path && member.sha256 === incomingArr[index]?.sha256);
407
+ if (!identical) {
408
+ const handled = new Set<string>(input.incomingShardPaths);
409
+ if (input.incomingMarker) handled.add(input.incomingMarker.path);
410
+ if (input.incomingMarkerPresent) handled.add(markerRel);
411
+ for (const relPath of localCensus.keys()) handled.add(relPath);
412
+ log.warn(
413
+ `embedding generation ${shardDirRel} deferred: base-less creation does not match the existing local generation under the mutation lock; nothing published, nothing removed`,
414
+ );
415
+ return {
416
+ shardDirRel,
417
+ upserted: 0,
418
+ deleted: 0,
419
+ writtenStates: new Map<string, OfflineSyncFileState>(),
420
+ removedPaths: new Set<string>(),
421
+ handledPaths: handled,
422
+ deferredLocalDivergence: true,
423
+ };
424
+ }
425
+ }
426
+ }
427
+
428
+ const published = new Map<string, Buffer>();
429
+ let identity: EmbeddingIndexIdentity | null = null;
430
+ // Divergence re-evaluation happens HERE, under the lock, against real
431
+ // disk bytes: the apply-side census may already be stale.
432
+ // 2. Build the complete incoming generation (final rel path → plaintext
433
+ // bytes) and validate every document BEFORE touching local state.
434
+ if (input.incomingMarker) {
435
+ const markerBuffer = await hydratedIncomingBuffer(
436
+ io,
437
+ root,
438
+ input.incomingMarker.path,
439
+ input.incomingMarker.sha256,
440
+ input.incomingMarker.buffer,
441
+ );
442
+ const read = parseEmbeddingIndexDocument(markerBuffer.toString("utf-8"));
443
+ if (read.outcome !== "ok") {
444
+ throw new EmbeddingIndexStorageError(
445
+ `refusing incoming embedding index generation ${markerRel}: ${describeIndexReadFailure(read)}; local generation preserved`
446
+ );
447
+ }
448
+ identity = { provider: read.file.provider, model: read.file.model };
449
+ const groups = shardEntriesForIndex(read.file);
450
+ for (const [shardIndex, entries] of groups) {
451
+ if (Object.keys(entries).length === 0) continue;
452
+ published.set(
453
+ shardRelPath(shardDirRel, shardIndex),
454
+ Buffer.from(serializeEmbeddingShard(read.file, shardIndex, entries), "utf-8")
455
+ );
456
+ }
457
+ } else {
458
+ for (const relPath of input.incomingShardPaths) {
459
+ // Metadata-only pulls skip content whose local hash already matches
460
+ // the incoming record: the LOCAL bytes ARE the incoming content, so
461
+ // read and hash-verify them instead of failing (codex rounds 5-6).
462
+ const state = input.incomingShardStates.get(relPath);
463
+ const buffer = await hydratedIncomingBuffer(
464
+ io,
465
+ root,
466
+ relPath,
467
+ state?.sha256 ?? "",
468
+ input.incomingBuffers.get(relPath),
469
+ );
470
+ const read = parseEmbeddingIndexDocument(buffer.toString("utf-8"));
471
+ if (read.outcome !== "ok") {
472
+ throw new EmbeddingIndexStorageError(
473
+ `refusing incoming embedding index shard ${relPath}: ${describeIndexReadFailure(read)}; local generation preserved`
474
+ );
475
+ }
476
+ validateShardMembership(relPath.split("/").pop() ?? "", read.file);
477
+ const shardIdentity = { provider: read.file.provider, model: read.file.model };
478
+ if (!identity) identity = shardIdentity;
479
+ if (identity.provider !== shardIdentity.provider || identity.model !== shardIdentity.model) {
480
+ throw new EmbeddingIndexStorageError(
481
+ `refusing mixed-identity incoming embedding index generation in ${shardDirRel}: ${relPath} is ${shardIdentity.provider}/${shardIdentity.model} but the generation is ${identity.provider}/${identity.model}; local generation preserved`
482
+ );
483
+ }
484
+ published.set(relPath, buffer);
485
+ }
486
+ if (published.size === 0) {
487
+ throw new EmbeddingIndexStorageError(
488
+ `incoming embedding index generation ${shardDirRel} is empty; local generation preserved`
489
+ );
490
+ }
491
+ }
492
+
493
+ const stagingRel = `${stateDirRel}/embeddings.staging.tmp-sync-${process.pid}-${input.now}-${randomBytes(8).toString("hex")}`;
494
+ const stagingAbs = await resolveSafeArchiveTarget(root, stagingRel);
495
+ try {
496
+ await mkdir(stagingAbs, { recursive: true });
497
+
498
+ // 3. Stage the complete generation. With storage-backed IO the staged
499
+ // ciphertext binds its FINAL canonical path (`aadRelPath`), so after
500
+ // the directory swap it decrypts at the published path — a physical
501
+ // staging-path AAD would make the published generation unreadable.
502
+ for (const [relPath, buffer] of published) {
503
+ const stagedRel = `${stagingRel}/${path.basename(relPath)}`;
504
+ const stagedAbs = await resolveSafeArchiveTarget(root, stagedRel);
505
+ const finalAbs = await resolveSafeArchiveTarget(root, relPath);
506
+ if (io.writeStagingFile) {
507
+ await io.writeStagingFile({
508
+ root: root.abs,
509
+ path: stagedRel,
510
+ filePath: stagedAbs,
511
+ content: buffer,
512
+ finalAadFilePath: finalAbs,
513
+ });
514
+ } else {
515
+ await writeFile(stagedAbs, buffer, { mode: 0o600 });
516
+ }
517
+ }
518
+
519
+ // 4. Verify the staged bytes against the incoming content before the
520
+ // published generation is touched at all.
521
+ for (const [relPath, buffer] of published) {
522
+ const stagedRel = `${stagingRel}/${path.basename(relPath)}`;
523
+ const stagedAbs = await resolveSafeArchiveTarget(root, stagedRel);
524
+ const staged = io.readStagingFile
525
+ ? await io.readStagingFile({
526
+ root: root.abs,
527
+ path: stagedRel,
528
+ filePath: stagedAbs,
529
+ finalAadFilePath: await resolveSafeArchiveTarget(root, relPath),
530
+ })
531
+ : await readFile(stagedAbs);
532
+ if (!staged.equals(buffer)) {
533
+ throw new EmbeddingIndexStorageError(
534
+ `staged embedding index file ${stagedRel} does not match the incoming content; local generation preserved`
535
+ );
536
+ }
537
+ }
538
+
539
+ // 5. Publish with the ONE swap state machine shared with persist(). The
540
+ // old directory moves aside wholesale, so local shards absent from
541
+ // the incoming generation are removed by the swap — never merged.
542
+ const localShardRels = (
543
+ await readdir(shardDirAbs).catch((err) => {
544
+ if ((err as NodeJS.ErrnoException).code === "ENOENT") return [] as string[];
545
+ throw err;
546
+ })
547
+ )
548
+ .filter((name) => EMBEDDING_SHARD_FILE_PATTERN.test(name))
549
+ .map((name) => `${shardDirRel}/${name}`)
550
+ .sort();
551
+ await store.publishSwappedGeneration(stagingAbs, fence);
552
+
553
+ const writtenStates = new Map<string, OfflineSyncFileState>();
554
+ for (const [relPath, buffer] of published) {
555
+ writtenStates.set(relPath, {
556
+ path: relPath,
557
+ sha256: sha256Hex(buffer),
558
+ bytes: buffer.length,
559
+ mtimeMs: input.now,
560
+ });
561
+ }
562
+ const removedPaths = new Set<string>(localShardRels.filter((rel) => !published.has(rel)));
563
+ let deleted = removedPaths.size;
564
+ let markerCleanupFailed = false;
565
+ if ((await pathExists(markerAbs)) && !input.incomingMarker && !input.incomingMarkerPresent) {
566
+ // Publication is already committed. Keep its base advancement even if
567
+ // marker cleanup fails, retaining the marker in base for a retry.
568
+ try {
569
+ if (io.deleteFile) await io.deleteFile({ root: root.abs, path: markerRel, filePath: markerAbs });
570
+ else await rm(markerAbs, { force: true });
571
+ removedPaths.add(markerRel);
572
+ deleted += 1;
573
+ } catch (err) {
574
+ markerCleanupFailed = true;
575
+ log.warn(`embedding generation ${shardDirRel}: marker cleanup deferred after publish: ${err}`);
576
+ }
577
+ }
578
+ // Swept members bypass the per-file delete path, so record their
579
+ // deletion revisions here — mirroring the whole-generation removal
580
+ // path — or a later peer without shared-base evidence can reintroduce
581
+ // the removed shards (codex P1). An empty map still records (with
582
+ // `now`) when the caller declared a deletion context, so tombstones
583
+ // whose changeset deletes omit mtimeMs are not lost. Every member
584
+ // gets an attempt before the failure propagates: the push side then
585
+ // retries a fully-recorded apply or nothing, and the
586
+ // justified-removals exemption keeps that retry idempotent.
587
+ if (input.deletionMtimeByPath !== undefined && io.deleteFile) {
588
+ let firstTombstoneError: unknown = null;
589
+ for (const relPath of removedPaths) {
590
+ try {
591
+ await io.deleteFile({
592
+ root: root.abs,
593
+ path: relPath,
594
+ filePath: await resolveSafeArchiveTarget(root, relPath),
595
+ mtimeMs: input.deletionMtimeByPath.get(relPath) ?? input.now,
596
+ });
597
+ } catch (err) {
598
+ firstTombstoneError ??= err;
599
+ log.warn(`embedding generation ${shardDirRel}: tombstone recording failed for ${relPath}: ${err instanceof Error ? err.message : String(err)}`);
600
+ }
601
+ }
602
+ if (firstTombstoneError) throw firstTombstoneError;
603
+ }
604
+ return {
605
+ shardDirRel,
606
+ upserted: published.size,
607
+ deleted,
608
+ writtenStates,
609
+ removedPaths,
610
+ handledPaths: new Set([...published.keys(), ...removedPaths, ...(markerCleanupFailed ? [markerRel] : [])]),
611
+ };
612
+ } catch (err) {
613
+ await rm(stagingAbs, { recursive: true, force: true }).catch(() => undefined);
614
+ throw err;
615
+ }
616
+ });
617
+ }
618
+
619
+ // ---------------------------------------------------------------------------
620
+ // Push-side whole-generation omission
621
+ // ---------------------------------------------------------------------------
622
+
623
+ export interface EmbeddingGenerationOmissionOptions {
624
+ rootAbs: string;
625
+ userExcludeRegexps?: readonly RegExp[];
626
+ excludeFile?: OfflineSyncExcludeFile;
627
+ /** Recorded deletion-revision paths: a tombstoned member counts as a
628
+ * generation member for omission detection even though it is absent on
629
+ * disk (its exclusion must omit the WHOLE generation). */
630
+ tombstonedPaths?: readonly string[];
631
+ /**
632
+ * Per-path push exclusion predicate (structural + node-local defaults +
633
+ * user regexps). Defaults to the built-in default excludes + the supplied
634
+ * user regexps, matching the walk that consumes the result.
635
+ */
636
+ isExcludedRelPath?: (relPath: string) => boolean;
637
+ }
638
+
639
+ export interface EmbeddingGenerationOmission {
640
+ /** Existing member paths omitted because their generation is partial. */
641
+ omittedPaths: Set<string>;
642
+ /** Generation dirs whose members are omitted (snapshot field value). */
643
+ omittedDirs: string[];
644
+ }
645
+
646
+ /**
647
+ * Compute the push-side whole-generation omission set: when ANY on-disk
648
+ * member of an embedding generation is excluded by a push filter, EVERY
649
+ * member of that generation is omitted (issue #3148, round 4).
650
+ */
651
+ export async function computeOmittedEmbeddingGenerationPaths(
652
+ options: EmbeddingGenerationOmissionOptions
653
+ ): Promise<EmbeddingGenerationOmission> {
654
+ const omittedPaths = new Set<string>();
655
+ const omittedDirs: string[] = [];
656
+ const stateDirs = ["state"];
657
+ let namespaceNames: string[] = [];
658
+ try {
659
+ namespaceNames = (await readdir(path.join(options.rootAbs, "namespaces"), { withFileTypes: true }))
660
+ .filter((entry) => entry.isDirectory())
661
+ .map((entry) => entry.name);
662
+ } catch {
663
+ // no namespaces
664
+ }
665
+ for (const ns of namespaceNames) stateDirs.push(`namespaces/${ns}/state`);
666
+ const isExcluded = options.isExcludedRelPath ??
667
+ ((relPath: string) =>
668
+ matchesOfflineSyncDefaultExclude(relPath) ||
669
+ Boolean(options.userExcludeRegexps?.some((re) => re.test(relPath))));
670
+
671
+ for (const stateDir of stateDirs) {
672
+ const markerRel = `${stateDir}/${EMBEDDING_MARKER_BASENAME}`;
673
+ const shardDirRel = `${stateDir}/${EMBEDDING_SHARD_DIR_BASENAME}`;
674
+ const shardDirAbs = path.join(options.rootAbs, ...shardDirRel.split("/"));
675
+ const memberRels: string[] = [];
676
+ if (await pathExists(path.join(options.rootAbs, ...markerRel.split("/")))) {
677
+ memberRels.push(markerRel);
678
+ }
679
+ let shardNames: string[] = [];
680
+ try {
681
+ shardNames = (await readdir(shardDirAbs, { withFileTypes: true }))
682
+ .filter((entry) => entry.isFile() && EMBEDDING_SHARD_FILE_PATTERN.test(entry.name))
683
+ .map((entry) => entry.name);
684
+ } catch (err) {
685
+ if ((err as NodeJS.ErrnoException).code !== "ENOENT") throw err;
686
+ }
687
+ for (const name of shardNames) memberRels.push(`${shardDirRel}/${name}`);
688
+ // A tombstoned member is part of the generation even though it is
689
+ // already absent on disk: its exclusion must omit the WHOLE generation,
690
+ // not just drop its revision individually (codex round 6, XkFf).
691
+ for (const tombstoned of options.tombstonedPaths ?? []) {
692
+ const membership = embeddingGenerationMembership(tombstoned);
693
+ if (membership?.shardDir === shardDirRel && !memberRels.includes(tombstoned)) {
694
+ memberRels.push(tombstoned);
695
+ }
696
+ }
697
+ if (memberRels.length === 0) continue;
698
+
699
+ const excludedMembers: string[] = [];
700
+ for (const relPath of memberRels) {
701
+ let excluded = isExcluded(relPath);
702
+ if (!excluded && options.excludeFile) {
703
+ excluded = await options.excludeFile({
704
+ root: options.rootAbs,
705
+ path: relPath,
706
+ filePath: path.join(options.rootAbs, ...relPath.split("/")),
707
+ });
708
+ }
709
+ if (excluded) excludedMembers.push(relPath);
710
+ }
711
+ if (excludedMembers.length === 0) continue;
712
+ omittedDirs.push(shardDirRel);
713
+ omittedPaths.add(shardDirRel); // skip new shards after the omission header
714
+ for (const relPath of memberRels) omittedPaths.add(relPath);
715
+ }
716
+ return { omittedPaths, omittedDirs };
717
+ }
718
+
719
+ /** Reject an exclusion introduced after the snapshot header was computed. */
720
+ export async function assertEmbeddingGenerationStillIncluded(
721
+ rootAbs: string, shardDirRel: string, excludeFile: OfflineSyncExcludeFile | undefined,
722
+ isExcludedRelPath: (relPath: string) => boolean, tombstonedPaths: readonly string[],
723
+ ): Promise<void> {
724
+ const current = await computeOmittedEmbeddingGenerationPaths({ rootAbs, excludeFile, isExcludedRelPath, tombstonedPaths });
725
+ if (current.omittedDirs.includes(shardDirRel)) {
726
+ throw new EmbeddingIndexStorageError(
727
+ `embedding generation ${shardDirRel} became partially excluded during snapshot capture; retry with a fresh omission header`,
728
+ );
729
+ }
730
+ }
731
+
732
+ /** True when a path belongs to a generation the push omitted. */
733
+ export function isPathInOmittedEmbeddingGeneration(relPath: string, omittedDirs: ReadonlySet<string>): boolean {
734
+ const membership = embeddingGenerationMembership(relPath);
735
+ return membership !== null && omittedDirs.has(membership.shardDir);
736
+ }
737
+
738
+ export type { EmbeddingIndexFile };
739
+
740
+ import { matchesOfflineSyncDefaultExclude } from "./offline-sync-exclude-globs.js";
741
+ import type { OfflineSyncDeletionRevision } from "./offline-sync.js";
742
+
743
+ export interface PushEmbeddingGenerationState {
744
+ /** Generation dirs omitted by the push filters (snapshot header value). */
745
+ omittedDirs: string[];
746
+ /** All omitted member paths (walk skip set). */
747
+ omittedPaths: Set<string>;
748
+ /** Deletions with whole-generation suppression applied. */
749
+ deletions: OfflineSyncDeletionRevision[];
750
+ }
751
+
752
+ /**
753
+ * One-call push-side generation state for streaming snapshot builders: the
754
+ * whole-generation omission set (from user regexps, excludeFile, and default
755
+ * excludes) plus the deletion list with omitted-generation revisions
756
+ * suppressed — including revisions for members that are already absent, so a
757
+ * filtered generation can never be announced as deleted.
758
+ */
759
+ export async function resolvePushEmbeddingGenerationState(options: {
760
+ rootAbs: string;
761
+ includeTranscripts: boolean;
762
+ userExcludeRegexps?: readonly RegExp[];
763
+ excludeFile?: OfflineSyncExcludeFile;
764
+ deletions: readonly OfflineSyncDeletionRevision[];
765
+ }): Promise<PushEmbeddingGenerationState> {
766
+ const omission = await computeOmittedEmbeddingGenerationPaths({
767
+ rootAbs: options.rootAbs,
768
+ userExcludeRegexps: options.userExcludeRegexps,
769
+ excludeFile: options.excludeFile,
770
+ // RAW pre-filter tombstones: a deleted member's exclusion must omit the
771
+ // whole generation even though the member is already absent on disk.
772
+ tombstonedPaths: options.deletions.map((deletion) => deletion.path),
773
+ isExcludedRelPath: (relPath) =>
774
+ matchesOfflineSyncDefaultExclude(relPath) ||
775
+ Boolean(options.userExcludeRegexps?.some((re) => re.test(relPath))),
776
+ });
777
+ const omittedDirs = new Set(omission.omittedDirs);
778
+ const deletions = options.deletions.filter((deletion) => {
779
+ if (matchesOfflineSyncDefaultExclude(deletion.path)) return false;
780
+ if (options.userExcludeRegexps?.some((re) => re.test(deletion.path))) return false;
781
+ const membership = embeddingGenerationMembership(deletion.path);
782
+ if (membership && omittedDirs.has(membership.shardDir)) return false;
783
+ return true;
784
+ });
785
+ return { omittedDirs: omission.omittedDirs, omittedPaths: omission.omittedPaths, deletions };
786
+ }
787
+
788
+
789
+ interface StorageBackedIndexIoHost {
790
+ readOfflineSyncFile(filePath: string, opts?: { aadFilePath?: string }): Promise<Buffer>;
791
+ writeOfflineSyncStagingFile(
792
+ filePath: string,
793
+ content: Buffer,
794
+ opts?: { aadFilePath?: string },
795
+ ): Promise<void>;
796
+ }
797
+
798
+ /**
799
+ * Daemon wiring for the index store IO backed by a StorageManager:
800
+ * canonical-path secure reads/writes, so sync-published encrypted shards
801
+ * decrypt in the daemon and daemon-written shards decrypt on sync. Shard
802
+ * STAGING writes bind the FINAL published path.
803
+ */
804
+ export function storageBackedIndexStoreIo(storage: StorageBackedIndexIoHost): EmbeddingIndexStoreIo {
805
+ return {
806
+ readUtf8: async (filePath) => (await storage.readOfflineSyncFile(filePath)).toString("utf-8"),
807
+ writeUtf8: (filePath, contents, opts) =>
808
+ storage.writeOfflineSyncStagingFile(
809
+ filePath,
810
+ Buffer.from(contents, "utf-8"),
811
+ opts?.finalAadFilePath === undefined ? undefined : { aadFilePath: opts.finalAadFilePath },
812
+ ),
813
+ };
814
+ }
815
+
816
+ export interface EmbeddingGenerationRemovalInput {
817
+ root: SafeArchiveRoot;
818
+ /** The generation dir, e.g. `state/embeddings`. */
819
+ shardDirRel: string;
820
+ io: Pick<EmbeddingGenerationTransactionIo, "deleteFile" | "readFile">;
821
+ /** Incoming deletion revisions by path, threaded so each removed member's
822
+ * tombstone is recorded through the configured delete hook AFTER the
823
+ * atomic empty publication (round 6: raw removal must not lose them). */
824
+ deletionMtimeByPath?: ReadonlyMap<string, number>;
825
+ now: number;
826
+ /**
827
+ * Shared-base states: when the live generation diverged from the base
828
+ * (daemon indexed, added, or removed members after the census), the
829
+ * removal DEFERS instead of erasing the local work (codex P1).
830
+ */
831
+ baseStates?: ReadonlyMap<string, { sha256: string }>;
832
+ }
833
+
834
+ /**
835
+ * Remove a LOCAL embedding generation atomically because the remote deleted
836
+ * it wholesale (every member has a deletion revision): recover first, then
837
+ * demote the published directory through the store's single swap state
838
+ * machine and delete the backup — a crash or delete failure can never leave
839
+ * a partial same-identity generation serving silently missing memories.
840
+ * The local legacy marker, when present, is removed through the same delete
841
+ * hook the per-file path uses.
842
+ */
843
+ export async function applyEmbeddingGenerationRemoval(
844
+ input: EmbeddingGenerationRemovalInput,
845
+ ): Promise<EmbeddingGenerationTransactionResult> {
846
+ const { root, shardDirRel, io } = input;
847
+ const stateDirRel = shardDirRel.slice(0, -(`/${EMBEDDING_SHARD_DIR_BASENAME}`.length));
848
+ const stateDirAbs = await resolveSafeArchiveTarget(root, stateDirRel);
849
+ return await withEmbeddingGenerationLock(stateDirAbs, async (section) => {
850
+ const lockPath = embeddingGenerationLockPath(stateDirAbs);
851
+ const fence: EmbeddingGenerationFence = () => assertEmbeddingGenerationLockHeld(lockPath, section);
852
+ const markerRel = `${stateDirRel}/${EMBEDDING_MARKER_BASENAME}`;
853
+ const shardDirAbs = await resolveSafeArchiveTarget(root, shardDirRel);
854
+ const markerAbs = await resolveSafeArchiveTarget(root, markerRel);
855
+ const store = new EmbeddingIndexFileStore(
856
+ markerAbs,
857
+ shardDirAbs,
858
+ await resolveSafeArchiveTarget(root, `${stateDirRel}/embedding-fallback-status.json`),
859
+ );
860
+ await store.recoverIfInterrupted(fence);
861
+
862
+ // Codex P1: the deletion census is stale by the time the lock is held.
863
+ // When the live generation no longer matches the shared base (daemon
864
+ // indexed, added, or removed members), DEFER the removal — the local
865
+ // work survives and a later sync re-evaluates with a fresh base.
866
+ // No shared base (fresh catch-up) = no divergence semantics to protect.
867
+ const baseStates = baseStatesForGeneration(input.baseStates, shardDirRel);
868
+ if (baseStates.size > 0) {
869
+ const localCensus = await censusGenerationState(io, root, markerRel, markerAbs, shardDirAbs, shardDirRel);
870
+ const baseArr = [...baseStates].map(([relPath, state]) => ({ path: relPath, sha256: state.sha256 }));
871
+ const censusArr = [...localCensus].map(([relPath, sha256]) => ({ path: relPath, sha256 }));
872
+ const changedSinceBase =
873
+ censusArr.some((member) => {
874
+ // A MODIFIED member must also defer: removing the generation would
875
+ // erase the daemon's rewrite, not just the remote's stale copy.
876
+ const baseSha = baseStates.get(member.path)?.sha256;
877
+ return baseSha === undefined || baseSha !== member.sha256;
878
+ }) || baseArr.some((member) => !localCensus.has(member.path));
879
+ if (changedSinceBase) {
880
+ const removedPaths = new Set<string>([...localCensus.keys()]);
881
+ log.warn(
882
+ `embedding generation removal ${shardDirRel} deferred: disk diverged from the shared base under the mutation lock; local generation preserved`,
883
+ );
884
+ return {
885
+ shardDirRel,
886
+ upserted: 0,
887
+ deleted: 0,
888
+ writtenStates: new Map<string, OfflineSyncFileState>(),
889
+ removedPaths,
890
+ handledPaths: new Set(removedPaths),
891
+ deferredLocalDivergence: true,
892
+ };
893
+ }
894
+ }
895
+ const localShardRels = (await readdir(shardDirAbs).catch((err) => {
896
+ if ((err as NodeJS.ErrnoException).code === "ENOENT") return [] as string[];
897
+ throw err;
898
+ }))
899
+ .filter((name) => EMBEDDING_SHARD_FILE_PATTERN.test(name))
900
+ .map((name) => `${shardDirRel}/${name}`)
901
+ .sort();
902
+ await store.removePublishedGeneration(fence);
903
+ const removedPaths = new Set(localShardRels);
904
+ let deleted = removedPaths.size;
905
+ const markerPresent = await pathExists(markerAbs);
906
+ if (markerPresent) {
907
+ removedPaths.add(markerRel);
908
+ deleted += 1;
909
+ }
910
+ // Preserve the replicated tombstones through the configured hooks AFTER
911
+ // the atomic publication: raw removal must not lose the deletion
912
+ // revisions, or a downstream sync without base evidence retains stale
913
+ // entries. EVERY member (shards and marker) is recorded exactly ONCE with
914
+ // the remote revision when known, so a first hook call without a revision
915
+ // is never overwritten by an older replicated one. The storage hook
916
+ // tolerates already-absent paths.
917
+ let firstError: unknown = null;
918
+ for (const relPath of removedPaths) {
919
+ const memberAbs = relPath === markerRel ? markerAbs : await resolveSafeArchiveTarget(root, relPath);
920
+ const mtimeMs = input.deletionMtimeByPath?.get(relPath) ?? input.now;
921
+ if (io.deleteFile) {
922
+ try {
923
+ await io.deleteFile({
924
+ root: root.abs,
925
+ path: relPath,
926
+ filePath: await resolveSafeArchiveTarget(root, relPath),
927
+ mtimeMs,
928
+ });
929
+ } catch (err) {
930
+ firstError ??= err;
931
+ log.warn(`embedding generation removal: tombstone recording failed for ${relPath}: ${err instanceof Error ? err.message : String(err)}`);
932
+ }
933
+ } else if (relPath === markerRel && markerPresent) {
934
+ await rm(markerAbs, { force: true });
935
+ }
936
+ }
937
+ if (firstError) throw firstError;
938
+ return {
939
+ shardDirRel,
940
+ upserted: 0,
941
+ deleted,
942
+ writtenStates: new Map(),
943
+ removedPaths,
944
+ handledPaths: new Set(removedPaths),
945
+ };
946
+ });
947
+ }
948
+
949
+ /** Defer a whole generation when the shared remote base would erase a local change. */
950
+ export function divergedEmbeddingGenerationDeferrals(options: {
951
+ incomingFiles: readonly { path: string; sha256: string }[];
952
+ baseFiles: readonly { path: string; sha256: string }[];
953
+ currentFiles: readonly { path: string; sha256: string }[];
954
+ }): string[] {
955
+ const base = new Map(options.baseFiles.map((f) => [f.path, f.sha256]));
956
+ const current = new Map(options.currentFiles.map((f) => [f.path, f.sha256]));
957
+ const incomingByPath = new Map(options.incomingFiles.map((f) => [f.path, f.sha256]));
958
+ const sharedDirs = new Set(options.baseFiles.map((f) => embeddingGenerationMembership(f.path)?.shardDir));
959
+ const conflictedDirs = new Set<string>();
960
+ for (const relPath of new Set([...base.keys(), ...current.keys(), ...incomingByPath.keys()])) {
961
+ const membership = embeddingGenerationMembership(relPath);
962
+ // Without a shared generation base this is an initial remote-authoritative
963
+ // import, not evidence of local indexing after a synchronized snapshot.
964
+ if (!membership || !sharedDirs.has(membership.shardDir)) continue;
965
+ const currentSha = current.get(relPath);
966
+ if (currentSha !== base.get(relPath) && currentSha !== incomingByPath.get(relPath)) {
967
+ conflictedDirs.add(membership.shardDir);
968
+ }
969
+ }
970
+ if (conflictedDirs.size === 0) return [];
971
+ const deferred: string[] = [];
972
+ // Include local/base members too: an all-absent remote generation still
973
+ // needs a concrete deferral so its removal cannot erase a local change.
974
+ for (const relPath of new Set([...base.keys(), ...current.keys(), ...incomingByPath.keys()])) {
975
+ const membership = embeddingGenerationMembership(relPath);
976
+ if (membership && conflictedDirs.has(membership.shardDir)) deferred.push(relPath);
977
+ }
978
+ return deferred.sort((left, right) => left.localeCompare(right));
979
+ }
980
+
981
+ // ---------------------------------------------------------------------------
982
+ // Snapshot-side generation routing, extracted from applyOfflineSyncSnapshot
983
+ // for issue #3150 so the changeset path could share the machinery without
984
+ // growing the offline-sync.ts ratchet ceiling. Behavior-preserving.
985
+ // ---------------------------------------------------------------------------
986
+
987
+ export interface IncomingEmbeddingGenerationApply {
988
+ transactionResults: EmbeddingGenerationTransactionResult[];
989
+ deferredGenerationDirs: Set<string>;
990
+ }
991
+
992
+ export interface IncomingEmbeddingGenerationApplyOptions {
993
+ root: SafeArchiveRoot;
994
+ incomingMap: ReadonlyMap<string, OfflineSyncFileState>;
995
+ incomingBuffers: ReadonlyMap<string, Buffer>;
996
+ baseMap: ReadonlyMap<string, OfflineSyncFileState>;
997
+ currentMap: ReadonlyMap<string, OfflineSyncFileState>;
998
+ deferredPaths: ReadonlySet<string>;
999
+ omittedGenerationDirs: ReadonlySet<string>;
1000
+ deletionMtimeByPath?: ReadonlyMap<string, number>;
1001
+ io: EmbeddingGenerationTransactionIo;
1002
+ /** True when the caller supplied ANY custom storage IO. */
1003
+ customIoPresent: boolean;
1004
+ now: number;
1005
+ }
1006
+
1007
+ /**
1008
+ * Snapshot-side generation routing, extracted from applyOfflineSyncSnapshot
1009
+ * for issue #3150 (the changeset path needed the same machinery and the
1010
+ * offline-sync.ts line ratchet had no headroom). Incoming generations replace
1011
+ * as ONE unit through the shared locked transaction. Behavior-preserving —
1012
+ * the #3148 regression suites own this contract.
1013
+ */
1014
+ export async function applyIncomingEmbeddingGenerations(
1015
+ options: IncomingEmbeddingGenerationApplyOptions,
1016
+ ): Promise<IncomingEmbeddingGenerationApply> {
1017
+ const incomingGenerations = detectIncomingEmbeddingGenerations(options.incomingMap.keys());
1018
+ const generationDirs = new Set<string>([
1019
+ ...incomingGenerations.shardDirs,
1020
+ ...incomingGenerations.legacyMarkerDirs,
1021
+ ]);
1022
+ const deferredGenerationDirs = new Set<string>();
1023
+ for (const deferredPath of options.deferredPaths) {
1024
+ const membership = embeddingGenerationMembership(deferredPath);
1025
+ if (membership) deferredGenerationDirs.add(membership.shardDir);
1026
+ }
1027
+ const transactionResults: EmbeddingGenerationTransactionResult[] = [];
1028
+ // Included and omitted cannot describe the same generation.
1029
+ for (const shardDir of generationDirs) {
1030
+ if (options.omittedGenerationDirs.has(shardDir)) {
1031
+ throw new EmbeddingIndexStorageError(
1032
+ `offline sync snapshot both includes and omits embedding generation ${shardDir}; refusing to apply`,
1033
+ );
1034
+ }
1035
+ }
1036
+ // Fail closed BEFORE any publication: custom storage IO (encrypted or
1037
+ // otherwise) without the staging pair would make the generation transaction
1038
+ // fall back to unencrypted raw writes — a plaintext downgrade of the staged
1039
+ // generation. Callers must wire both staging hooks (the CLI does).
1040
+ if (
1041
+ generationDirs.size > 0 &&
1042
+ options.customIoPresent &&
1043
+ !(options.io.writeStagingFile && options.io.readStagingFile)
1044
+ ) {
1045
+ throw new EmbeddingIndexStorageError(
1046
+ "refusing to replace embedding generation: custom storage IO requires both writeStagingFile and readStagingFile hooks; unencrypted raw staging would plaintext-downgrade the index",
1047
+ );
1048
+ }
1049
+ for (const shardDir of generationDirs) {
1050
+ if (deferredGenerationDirs.has(shardDir)) continue;
1051
+ if (
1052
+ incomingGenerations.legacyMarkerDirs.has(shardDir) &&
1053
+ !incomingGenerations.shardDirs.has(shardDir)
1054
+ ) {
1055
+ // Cross-layout: an incoming legacy marker replaces a local sharded
1056
+ // generation as a whole (codex round 4). When shards are ALSO
1057
+ // incoming, the sharded set is the generation and the marker is
1058
+ // written as an inert artifact by the per-file loop below.
1059
+ const markerRel = [...options.incomingMap.keys()].find(
1060
+ (relPath) => embeddingMarkerDirOf(relPath) === shardDir.slice(0, -`/${EMBEDDING_SHARD_DIR_BASENAME}`.length),
1061
+ );
1062
+ if (!markerRel) continue;
1063
+ transactionResults.push(await applyEmbeddingGenerationTransaction({
1064
+ root: options.root,
1065
+ shardDirRel: shardDir,
1066
+ incomingShardPaths: [],
1067
+ incomingMarker: {
1068
+ path: markerRel,
1069
+ sha256: options.incomingMap.get(markerRel)!.sha256,
1070
+ buffer: options.incomingBuffers.get(markerRel) ?? null,
1071
+ },
1072
+ incomingMarkerPresent: false,
1073
+ incomingShardStates: new Map(),
1074
+ incomingBuffers: options.incomingBuffers,
1075
+ baseStates: options.baseMap,
1076
+ io: options.io,
1077
+ now: options.now,
1078
+ }));
1079
+ continue;
1080
+ }
1081
+ transactionResults.push(await applyEmbeddingGenerationTransaction({
1082
+ root: options.root,
1083
+ shardDirRel: shardDir,
1084
+ incomingShardPaths: [...options.incomingMap.keys()]
1085
+ .filter((relPath) => embeddingShardDirOf(relPath) === shardDir)
1086
+ .sort(),
1087
+ incomingMarker: null,
1088
+ incomingMarkerPresent: Boolean(
1089
+ incomingGenerations.legacyMarkerDirs.has(shardDir),
1090
+ ),
1091
+ incomingShardStates: new Map(
1092
+ [...options.incomingMap.values()]
1093
+ .filter((state) => embeddingShardDirOf(state.path) === shardDir)
1094
+ .map((state) => [state.path, state]),
1095
+ ),
1096
+ incomingBuffers: options.incomingBuffers,
1097
+ baseStates: options.baseMap,
1098
+ io: options.io,
1099
+ now: options.now,
1100
+ }));
1101
+ }
1102
+ // Whole-generation removal (codex round 6 P1): when the remote deleted a
1103
+ // previously shared sharded index, the deletion revisions cover EVERY
1104
+ // local member. Remove that generation as ONE atomic swap instead of
1105
+ // deleting shards one-by-one, so a crash or delete failure can never
1106
+ // expose a partial same-identity generation serving missing memories.
1107
+ const localGenerationDirs = new Set<string>();
1108
+ for (const relPath of options.currentMap.keys()) {
1109
+ const membership = embeddingGenerationMembership(relPath);
1110
+ if (membership?.kind === "shard") localGenerationDirs.add(membership.shardDir);
1111
+ }
1112
+ for (const shardDir of localGenerationDirs) {
1113
+ if (
1114
+ generationDirs.has(shardDir) ||
1115
+ deferredGenerationDirs.has(shardDir) ||
1116
+ options.omittedGenerationDirs.has(shardDir)
1117
+ ) {
1118
+ continue;
1119
+ }
1120
+ const localMembers = [...options.currentMap.keys()].filter(
1121
+ (relPath) => embeddingGenerationMembership(relPath)?.shardDir === shardDir,
1122
+ );
1123
+ if (localMembers.length === 0) continue;
1124
+ // Tombstone or shared-base absence authorizes whole-generation removal.
1125
+ const baseMembers = localMembers.filter((relPath) => options.baseMap.has(relPath));
1126
+ // Tombstone evidence is satisfied by the members the REMOTE knew: the
1127
+ // remote cannot tombstone local-only extras or an inert legacy marker,
1128
+ // and the removal sweeps those once the remote deletion is established.
1129
+ // Non-empty same-generation tombstones establish remote absence on
1130
+ // their own: they may name shards already absent locally (removed in an
1131
+ // earlier round), so the set is NOT required to intersect localMembers
1132
+ // (codex round 6, XiOb).
1133
+ const tombstonedMembers =
1134
+ options.deletionMtimeByPath === undefined
1135
+ ? []
1136
+ : [...options.deletionMtimeByPath.keys()].filter(
1137
+ (relPath) => embeddingGenerationMembership(relPath)?.shardDir === shardDir,
1138
+ );
1139
+ const tombstoneCovered = tombstonedMembers.length > 0;
1140
+ const baseEvidenced =
1141
+ baseMembers.length > 0 && baseMembers.every((relPath) => !options.incomingMap.has(relPath));
1142
+ if (!tombstoneCovered && !baseEvidenced) continue;
1143
+ transactionResults.push(await applyEmbeddingGenerationRemoval({
1144
+ root: options.root,
1145
+ shardDirRel: shardDir,
1146
+ io: { deleteFile: options.io.deleteFile, readFile: options.io.readFile },
1147
+ deletionMtimeByPath: options.deletionMtimeByPath,
1148
+ baseStates: options.baseMap,
1149
+ now: options.now,
1150
+ }));
1151
+ }
1152
+ return { transactionResults, deferredGenerationDirs };
1153
+ }