@quolu/lattice 0.1.0 → 0.12.2

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 (370) hide show
  1. package/README.md +87 -4
  2. package/bin/lattice-bridge.mjs +87 -0
  3. package/bin/lattice-dashboard.mjs +70 -0
  4. package/bin/lattice-mcp.mjs +9 -9
  5. package/bin/lattice.mjs +61 -8
  6. package/docs/bridge-setup.md +87 -0
  7. package/docs/schemas/lattice.plan_create_input.v1.schema.json +56 -0
  8. package/docs/schemas/lattice.plan_create_input.v2.schema.json +72 -0
  9. package/docs/schemas/lattice.plan_create_input.v3.schema.json +81 -0
  10. package/package.json +19 -7
  11. package/sensor/dist/bin/command-supervision.d.ts +1 -1
  12. package/sensor/dist/bin/command-supervision.js +4 -4
  13. package/sensor/dist/bin/command-supervision.js.map +1 -1
  14. package/sensor/dist/bin/fatal-handler.js +2 -2
  15. package/sensor/dist/bin/fatal-handler.js.map +1 -1
  16. package/sensor/dist/bin/{codegraph.js → lattice-sensor.js} +207 -328
  17. package/sensor/dist/bin/node-version-check.d.ts +7 -5
  18. package/sensor/dist/bin/node-version-check.d.ts.map +1 -1
  19. package/sensor/dist/bin/node-version-check.js +19 -14
  20. package/sensor/dist/bin/node-version-check.js.map +1 -1
  21. package/sensor/dist/context/index.d.ts +1 -1
  22. package/sensor/dist/context/index.js +6 -6
  23. package/sensor/dist/context/index.js.map +1 -1
  24. package/sensor/dist/db/index.d.ts +5 -5
  25. package/sensor/dist/db/index.d.ts.map +1 -1
  26. package/sensor/dist/db/index.js +7 -7
  27. package/sensor/dist/db/index.js.map +1 -1
  28. package/sensor/dist/db/migrations.js +1 -1
  29. package/sensor/dist/db/migrations.js.map +1 -1
  30. package/sensor/dist/db/queries.d.ts +1 -1
  31. package/sensor/dist/db/queries.js +5 -5
  32. package/sensor/dist/db/queries.js.map +1 -1
  33. package/sensor/dist/db/schema.sql +2 -2
  34. package/sensor/dist/db/sqlite-adapter.d.ts +2 -2
  35. package/sensor/dist/db/sqlite-adapter.js +3 -3
  36. package/sensor/dist/db/sqlite-adapter.js.map +1 -1
  37. package/sensor/dist/db/wal-valve.d.ts +1 -1
  38. package/sensor/dist/db/wal-valve.d.ts.map +1 -1
  39. package/sensor/dist/db/wal-valve.js +2 -2
  40. package/sensor/dist/db/wal-valve.js.map +1 -1
  41. package/sensor/dist/directory.d.ts +27 -63
  42. package/sensor/dist/directory.d.ts.map +1 -1
  43. package/sensor/dist/directory.js +78 -134
  44. package/sensor/dist/directory.js.map +1 -1
  45. package/sensor/dist/errors.d.ts +15 -15
  46. package/sensor/dist/errors.d.ts.map +1 -1
  47. package/sensor/dist/errors.js +21 -21
  48. package/sensor/dist/errors.js.map +1 -1
  49. package/sensor/dist/extraction/dynamic-import.d.ts +1 -1
  50. package/sensor/dist/extraction/dynamic-import.js +1 -1
  51. package/sensor/dist/extraction/extraction-version.d.ts +1 -1
  52. package/sensor/dist/extraction/extraction-version.js +1 -1
  53. package/sensor/dist/extraction/generated-detection.d.ts +1 -1
  54. package/sensor/dist/extraction/generated-detection.js +1 -1
  55. package/sensor/dist/extraction/grammars.d.ts +3 -3
  56. package/sensor/dist/extraction/grammars.js +5 -5
  57. package/sensor/dist/extraction/grammars.js.map +1 -1
  58. package/sensor/dist/extraction/index.d.ts +6 -6
  59. package/sensor/dist/extraction/index.js +50 -50
  60. package/sensor/dist/extraction/index.js.map +1 -1
  61. package/sensor/dist/extraction/kernel/decode.d.ts +1 -1
  62. package/sensor/dist/extraction/kernel/decode.js +1 -1
  63. package/sensor/dist/extraction/kernel/index.d.ts +3 -3
  64. package/sensor/dist/extraction/kernel/index.js +6 -6
  65. package/sensor/dist/extraction/kernel/index.js.map +1 -1
  66. package/sensor/dist/extraction/kernel/layout.d.ts +1 -1
  67. package/sensor/dist/extraction/kernel/layout.js +1 -1
  68. package/sensor/dist/extraction/kernel/loader.d.ts +6 -6
  69. package/sensor/dist/extraction/kernel/loader.js +13 -13
  70. package/sensor/dist/extraction/kernel/loader.js.map +1 -1
  71. package/sensor/dist/extraction/languages/cfquery.d.ts +1 -1
  72. package/sensor/dist/extraction/languages/cfquery.js +1 -1
  73. package/sensor/dist/extraction/languages/lua.d.ts +11 -0
  74. package/sensor/dist/extraction/languages/lua.d.ts.map +1 -1
  75. package/sensor/dist/extraction/languages/lua.js +1 -0
  76. package/sensor/dist/extraction/languages/lua.js.map +1 -1
  77. package/sensor/dist/extraction/parse-pool.d.ts +5 -5
  78. package/sensor/dist/extraction/parse-pool.d.ts.map +1 -1
  79. package/sensor/dist/extraction/parse-pool.js +4 -4
  80. package/sensor/dist/extraction/parse-worker.js +1 -1
  81. package/sensor/dist/extraction/parse-worker.js.map +1 -1
  82. package/sensor/dist/extraction/store-writer.d.ts +1 -1
  83. package/sensor/dist/extraction/store-writer.js +1 -1
  84. package/sensor/dist/extraction/svelte-extractor.d.ts +1 -1
  85. package/sensor/dist/extraction/svelte-extractor.js +1 -1
  86. package/sensor/dist/extraction/tree-sitter-helpers.js +1 -1
  87. package/sensor/dist/extraction/tree-sitter.d.ts +2 -2
  88. package/sensor/dist/extraction/tree-sitter.d.ts.map +1 -1
  89. package/sensor/dist/extraction/tree-sitter.js +71 -4
  90. package/sensor/dist/extraction/tree-sitter.js.map +1 -1
  91. package/sensor/dist/extraction/wasm-runtime-flags.d.ts +2 -2
  92. package/sensor/dist/extraction/wasm-runtime-flags.d.ts.map +1 -1
  93. package/sensor/dist/extraction/wasm-runtime-flags.js +5 -5
  94. package/sensor/dist/extraction/wasm-runtime-flags.js.map +1 -1
  95. package/sensor/dist/index.d.ts +36 -36
  96. package/sensor/dist/index.d.ts.map +1 -1
  97. package/sensor/dist/index.js +71 -71
  98. package/sensor/dist/index.js.map +1 -1
  99. package/sensor/dist/mcp/daemon-manager.js +1 -1
  100. package/sensor/dist/mcp/daemon-paths.d.ts +3 -3
  101. package/sensor/dist/mcp/daemon-paths.js +7 -7
  102. package/sensor/dist/mcp/daemon-paths.js.map +1 -1
  103. package/sensor/dist/mcp/daemon-registry.d.ts +2 -2
  104. package/sensor/dist/mcp/daemon-registry.js +5 -5
  105. package/sensor/dist/mcp/daemon.d.ts +7 -7
  106. package/sensor/dist/mcp/daemon.d.ts.map +1 -1
  107. package/sensor/dist/mcp/daemon.js +21 -21
  108. package/sensor/dist/mcp/daemon.js.map +1 -1
  109. package/sensor/dist/mcp/dynamic-boundaries.js +1 -1
  110. package/sensor/dist/mcp/engine.d.ts +9 -9
  111. package/sensor/dist/mcp/engine.d.ts.map +1 -1
  112. package/sensor/dist/mcp/engine.js +44 -44
  113. package/sensor/dist/mcp/engine.js.map +1 -1
  114. package/sensor/dist/mcp/index.d.ts +14 -14
  115. package/sensor/dist/mcp/index.d.ts.map +1 -1
  116. package/sensor/dist/mcp/index.js +41 -41
  117. package/sensor/dist/mcp/index.js.map +1 -1
  118. package/sensor/dist/mcp/liveness-watchdog.js +7 -7
  119. package/sensor/dist/mcp/liveness-watchdog.js.map +1 -1
  120. package/sensor/dist/mcp/ppid-watchdog.d.ts +3 -3
  121. package/sensor/dist/mcp/ppid-watchdog.js +2 -2
  122. package/sensor/dist/mcp/proxy.d.ts.map +1 -1
  123. package/sensor/dist/mcp/proxy.js +37 -37
  124. package/sensor/dist/mcp/proxy.js.map +1 -1
  125. package/sensor/dist/mcp/query-pool.d.ts +3 -3
  126. package/sensor/dist/mcp/query-pool.js +7 -7
  127. package/sensor/dist/mcp/query-pool.js.map +1 -1
  128. package/sensor/dist/mcp/query-worker.d.ts +2 -2
  129. package/sensor/dist/mcp/query-worker.js +7 -7
  130. package/sensor/dist/mcp/query-worker.js.map +1 -1
  131. package/sensor/dist/mcp/server-instructions.d.ts +10 -12
  132. package/sensor/dist/mcp/server-instructions.d.ts.map +1 -1
  133. package/sensor/dist/mcp/server-instructions.js +39 -37
  134. package/sensor/dist/mcp/server-instructions.js.map +1 -1
  135. package/sensor/dist/mcp/session.d.ts +2 -2
  136. package/sensor/dist/mcp/session.js +18 -18
  137. package/sensor/dist/mcp/session.js.map +1 -1
  138. package/sensor/dist/mcp/startup-handshake.d.ts +3 -3
  139. package/sensor/dist/mcp/startup-handshake.d.ts.map +1 -1
  140. package/sensor/dist/mcp/startup-handshake.js +3 -3
  141. package/sensor/dist/mcp/startup-handshake.js.map +1 -1
  142. package/sensor/dist/mcp/tools.d.ts +53 -53
  143. package/sensor/dist/mcp/tools.d.ts.map +1 -1
  144. package/sensor/dist/mcp/tools.js +180 -216
  145. package/sensor/dist/mcp/tools.js.map +1 -1
  146. package/sensor/dist/mcp/transport.d.ts +1 -1
  147. package/sensor/dist/mcp/transport.js +6 -6
  148. package/sensor/dist/mcp/transport.js.map +1 -1
  149. package/sensor/dist/mcp/version.d.ts +2 -2
  150. package/sensor/dist/mcp/version.d.ts.map +1 -1
  151. package/sensor/dist/mcp/version.js +3 -3
  152. package/sensor/dist/mcp/version.js.map +1 -1
  153. package/sensor/dist/project-config.d.ts +6 -6
  154. package/sensor/dist/project-config.d.ts.map +1 -1
  155. package/sensor/dist/project-config.js +10 -10
  156. package/sensor/dist/project-config.js.map +1 -1
  157. package/sensor/dist/resolution/callback-synthesizer.js +4 -4
  158. package/sensor/dist/resolution/callback-synthesizer.js.map +1 -1
  159. package/sensor/dist/resolution/frameworks/drupal.d.ts +3 -3
  160. package/sensor/dist/resolution/frameworks/drupal.js +3 -3
  161. package/sensor/dist/resolution/frameworks/fabric.js +1 -1
  162. package/sensor/dist/resolution/frameworks/fabric.js.map +1 -1
  163. package/sensor/dist/resolution/frameworks/java.js +1 -1
  164. package/sensor/dist/resolution/frameworks/java.js.map +1 -1
  165. package/sensor/dist/resolution/frameworks/svelte.js +1 -1
  166. package/sensor/dist/resolution/frameworks/svelte.js.map +1 -1
  167. package/sensor/dist/resolution/goframe-synthesizer.d.ts +1 -1
  168. package/sensor/dist/resolution/goframe-synthesizer.js +1 -1
  169. package/sensor/dist/resolution/index.d.ts +1 -1
  170. package/sensor/dist/resolution/index.js +9 -9
  171. package/sensor/dist/resolution/index.js.map +1 -1
  172. package/sensor/dist/resolution/name-matcher.js +2 -2
  173. package/sensor/dist/resolution/name-matcher.js.map +1 -1
  174. package/sensor/dist/resolution/resolver-pool.d.ts +2 -2
  175. package/sensor/dist/resolution/resolver-pool.js +4 -4
  176. package/sensor/dist/resolution/resolver-pool.js.map +1 -1
  177. package/sensor/dist/resolution/resolver-worker.js +2 -2
  178. package/sensor/dist/resolution/resolver-worker.js.map +1 -1
  179. package/sensor/dist/resolution/workspace-packages.js +1 -1
  180. package/sensor/dist/resolution/workspace-packages.js.map +1 -1
  181. package/sensor/dist/search/identifier-segments.d.ts +1 -1
  182. package/sensor/dist/search/identifier-segments.js +1 -1
  183. package/sensor/dist/search/query-utils.d.ts +1 -0
  184. package/sensor/dist/search/query-utils.d.ts.map +1 -1
  185. package/sensor/dist/search/query-utils.js +10 -3
  186. package/sensor/dist/search/query-utils.js.map +1 -1
  187. package/sensor/dist/sync/git-hooks.d.ts +9 -9
  188. package/sensor/dist/sync/git-hooks.d.ts.map +1 -1
  189. package/sensor/dist/sync/git-hooks.js +15 -15
  190. package/sensor/dist/sync/git-hooks.js.map +1 -1
  191. package/sensor/dist/sync/watch-policy.d.ts +2 -2
  192. package/sensor/dist/sync/watch-policy.js +5 -5
  193. package/sensor/dist/sync/watch-policy.js.map +1 -1
  194. package/sensor/dist/sync/watcher.d.ts +2 -2
  195. package/sensor/dist/sync/watcher.d.ts.map +1 -1
  196. package/sensor/dist/sync/watcher.js +16 -16
  197. package/sensor/dist/sync/watcher.js.map +1 -1
  198. package/sensor/dist/sync/worktree.d.ts +5 -5
  199. package/sensor/dist/sync/worktree.d.ts.map +1 -1
  200. package/sensor/dist/sync/worktree.js +9 -9
  201. package/sensor/dist/sync/worktree.js.map +1 -1
  202. package/sensor/dist/telemetry/index.d.ts +8 -8
  203. package/sensor/dist/telemetry/index.d.ts.map +1 -1
  204. package/sensor/dist/telemetry/index.js +16 -16
  205. package/sensor/dist/telemetry/index.js.map +1 -1
  206. package/sensor/dist/types.d.ts +2 -2
  207. package/sensor/dist/types.js +1 -1
  208. package/sensor/dist/ui/color.d.ts +2 -2
  209. package/sensor/dist/ui/color.js +2 -2
  210. package/sensor/dist/ui/glyphs.d.ts +3 -3
  211. package/sensor/dist/ui/glyphs.js +7 -7
  212. package/sensor/dist/ui/glyphs.js.map +1 -1
  213. package/sensor/dist/utils.d.ts +4 -4
  214. package/sensor/dist/utils.js +8 -8
  215. package/sensor/dist/utils.js.map +1 -1
  216. package/sensor/package.json +8 -13
  217. package/src/artifact-contracts.mjs +2 -2
  218. package/src/boundary-compiler.mjs +28 -28
  219. package/src/boundary-observation-compiler-v2.mjs +10 -10
  220. package/src/bounded-seam.mjs +144 -0
  221. package/src/bridge-cli.mjs +227 -0
  222. package/src/bridge-config.mjs +346 -0
  223. package/src/bridge-daemon.mjs +328 -0
  224. package/src/bridge-launch-agent.mjs +311 -0
  225. package/src/bridge-server.mjs +309 -0
  226. package/src/cli-help.mjs +163 -0
  227. package/src/control-compiler.mjs +30 -30
  228. package/src/dag-chain.mjs +261 -0
  229. package/src/factory-diagnostics.mjs +8 -7
  230. package/src/hash-chain.mjs +76 -0
  231. package/src/node-version-guard.mjs +5 -4
  232. package/src/project-cli.mjs +392 -0
  233. package/src/project-identity.mjs +71 -0
  234. package/src/rc1-evidence-bundle.mjs +16 -16
  235. package/src/rc1-v4-campaign.mjs +15 -14
  236. package/src/rc1-v5-artifact-set.mjs +2 -2
  237. package/src/rc1-v5-campaign.mjs +15 -14
  238. package/src/rc1-v6-artifact-set.mjs +18 -18
  239. package/src/rc1-v6-campaign.mjs +16 -16
  240. package/src/rc1-v6-causal-binding.mjs +16 -14
  241. package/src/rc1-v6-measurement.mjs +20 -38
  242. package/src/rc2-artifact-set.mjs +45 -40
  243. package/src/rc2-campaign.mjs +48 -66
  244. package/src/rc2-delivery-policy-front-end.mjs +30 -30
  245. package/src/rc2-rc1-transfer-front-end.mjs +5 -5
  246. package/src/rc3-actual-dogfood.mjs +6 -6
  247. package/src/rc3-dogfood-scaffold.mjs +12 -7
  248. package/src/rc3-scripted-campaign.mjs +75 -21
  249. package/src/rc4-stage1-dogfood.mjs +24 -7
  250. package/src/runtime-cli.mjs +2424 -45
  251. package/src/runtime-contracts.mjs +7 -7
  252. package/src/runtime-control-store.mjs +547 -0
  253. package/src/runtime-controller-protocol.mjs +517 -0
  254. package/src/runtime-direct-os-observer.mjs +284 -0
  255. package/src/runtime-engine.mjs +2 -2
  256. package/src/runtime-errors.mjs +1 -1
  257. package/src/runtime-event-store.mjs +15 -43
  258. package/src/runtime-front-end.mjs +26 -26
  259. package/src/runtime-gate-store.mjs +477 -0
  260. package/src/runtime-hold-recompile.mjs +214 -23
  261. package/src/runtime-lifecycle-lock.mjs +290 -0
  262. package/src/runtime-managed-supervisor.mjs +1276 -0
  263. package/src/runtime-multi-epoch-store.mjs +761 -0
  264. package/src/runtime-projection.mjs +62 -0
  265. package/src/seam-transform.mjs +38 -38
  266. package/src/{codegraph-adapter.mjs → sensor-adapter.mjs} +7 -7
  267. package/src/sensor-cli.mjs +107 -0
  268. package/src/sensor-runtime.mjs +48 -0
  269. package/src/timestamp-contract.mjs +8 -0
  270. package/src/todo-chain.mjs +178 -0
  271. package/src/todo-cli.mjs +1032 -0
  272. package/src/todo-contracts.mjs +501 -0
  273. package/src/todo-dashboard-registry.mjs +318 -0
  274. package/src/todo-gantt-html.mjs +416 -0
  275. package/src/todo-gantt-layout.mjs +603 -0
  276. package/src/todo-gantt-live.mjs +269 -0
  277. package/src/todo-gantt-presentation.mjs +217 -0
  278. package/src/todo-gantt-svg.mjs +249 -0
  279. package/src/todo-markdown-renderer.mjs +260 -0
  280. package/src/todo-migration.mjs +260 -0
  281. package/src/todo-narrative-anchor.mjs +130 -0
  282. package/src/todo-revision.mjs +425 -0
  283. package/src/todo-status.mjs +340 -0
  284. package/src/todo-store.mjs +3451 -0
  285. package/src/treatment-compiler.mjs +28 -28
  286. package/src/treatment-runner.mjs +42 -44
  287. package/sensor/dist/bin/codegraph.d.ts +0 -26
  288. package/sensor/dist/bin/codegraph.d.ts.map +0 -1
  289. package/sensor/dist/bin/codegraph.js.map +0 -1
  290. package/sensor/dist/bin/uninstall.d.ts +0 -14
  291. package/sensor/dist/bin/uninstall.d.ts.map +0 -1
  292. package/sensor/dist/bin/uninstall.js +0 -36
  293. package/sensor/dist/bin/uninstall.js.map +0 -1
  294. package/sensor/dist/installer/beta-signup.d.ts +0 -54
  295. package/sensor/dist/installer/beta-signup.d.ts.map +0 -1
  296. package/sensor/dist/installer/beta-signup.js +0 -178
  297. package/sensor/dist/installer/beta-signup.js.map +0 -1
  298. package/sensor/dist/installer/config-writer.d.ts +0 -28
  299. package/sensor/dist/installer/config-writer.d.ts.map +0 -1
  300. package/sensor/dist/installer/config-writer.js +0 -91
  301. package/sensor/dist/installer/config-writer.js.map +0 -1
  302. package/sensor/dist/installer/index.d.ts +0 -142
  303. package/sensor/dist/installer/index.d.ts.map +0 -1
  304. package/sensor/dist/installer/index.js +0 -622
  305. package/sensor/dist/installer/index.js.map +0 -1
  306. package/sensor/dist/installer/instructions-template.d.ts +0 -41
  307. package/sensor/dist/installer/instructions-template.d.ts.map +0 -1
  308. package/sensor/dist/installer/instructions-template.js +0 -53
  309. package/sensor/dist/installer/instructions-template.js.map +0 -1
  310. package/sensor/dist/installer/targets/antigravity.d.ts +0 -57
  311. package/sensor/dist/installer/targets/antigravity.d.ts.map +0 -1
  312. package/sensor/dist/installer/targets/antigravity.js +0 -308
  313. package/sensor/dist/installer/targets/antigravity.js.map +0 -1
  314. package/sensor/dist/installer/targets/claude.d.ts +0 -62
  315. package/sensor/dist/installer/targets/claude.d.ts.map +0 -1
  316. package/sensor/dist/installer/targets/claude.js +0 -454
  317. package/sensor/dist/installer/targets/claude.js.map +0 -1
  318. package/sensor/dist/installer/targets/codex.d.ts +0 -18
  319. package/sensor/dist/installer/targets/codex.d.ts.map +0 -1
  320. package/sensor/dist/installer/targets/codex.js +0 -185
  321. package/sensor/dist/installer/targets/codex.js.map +0 -1
  322. package/sensor/dist/installer/targets/cursor.d.ts +0 -35
  323. package/sensor/dist/installer/targets/cursor.d.ts.map +0 -1
  324. package/sensor/dist/installer/targets/cursor.js +0 -254
  325. package/sensor/dist/installer/targets/cursor.js.map +0 -1
  326. package/sensor/dist/installer/targets/gemini.d.ts +0 -26
  327. package/sensor/dist/installer/targets/gemini.d.ts.map +0 -1
  328. package/sensor/dist/installer/targets/gemini.js +0 -165
  329. package/sensor/dist/installer/targets/gemini.js.map +0 -1
  330. package/sensor/dist/installer/targets/hermes.d.ts +0 -18
  331. package/sensor/dist/installer/targets/hermes.d.ts.map +0 -1
  332. package/sensor/dist/installer/targets/hermes.js +0 -359
  333. package/sensor/dist/installer/targets/hermes.js.map +0 -1
  334. package/sensor/dist/installer/targets/kiro.d.ts +0 -27
  335. package/sensor/dist/installer/targets/kiro.d.ts.map +0 -1
  336. package/sensor/dist/installer/targets/kiro.js +0 -178
  337. package/sensor/dist/installer/targets/kiro.js.map +0 -1
  338. package/sensor/dist/installer/targets/opencode.d.ts +0 -38
  339. package/sensor/dist/installer/targets/opencode.d.ts.map +0 -1
  340. package/sensor/dist/installer/targets/opencode.js +0 -288
  341. package/sensor/dist/installer/targets/opencode.js.map +0 -1
  342. package/sensor/dist/installer/targets/registry.d.ts +0 -35
  343. package/sensor/dist/installer/targets/registry.d.ts.map +0 -1
  344. package/sensor/dist/installer/targets/registry.js +0 -91
  345. package/sensor/dist/installer/targets/registry.js.map +0 -1
  346. package/sensor/dist/installer/targets/shared.d.ts +0 -101
  347. package/sensor/dist/installer/targets/shared.d.ts.map +0 -1
  348. package/sensor/dist/installer/targets/shared.js +0 -264
  349. package/sensor/dist/installer/targets/shared.js.map +0 -1
  350. package/sensor/dist/installer/targets/toml.d.ts +0 -52
  351. package/sensor/dist/installer/targets/toml.d.ts.map +0 -1
  352. package/sensor/dist/installer/targets/toml.js +0 -147
  353. package/sensor/dist/installer/targets/toml.js.map +0 -1
  354. package/sensor/dist/installer/targets/types.d.ts +0 -108
  355. package/sensor/dist/installer/targets/types.d.ts.map +0 -1
  356. package/sensor/dist/installer/targets/types.js +0 -16
  357. package/sensor/dist/installer/targets/types.js.map +0 -1
  358. package/sensor/dist/upgrade/index.d.ts +0 -171
  359. package/sensor/dist/upgrade/index.d.ts.map +0 -1
  360. package/sensor/dist/upgrade/index.js +0 -659
  361. package/sensor/dist/upgrade/index.js.map +0 -1
  362. package/sensor/dist/upgrade/remove-binary.d.ts +0 -87
  363. package/sensor/dist/upgrade/remove-binary.d.ts.map +0 -1
  364. package/sensor/dist/upgrade/remove-binary.js +0 -289
  365. package/sensor/dist/upgrade/remove-binary.js.map +0 -1
  366. package/sensor/dist/upgrade/update-check.d.ts +0 -92
  367. package/sensor/dist/upgrade/update-check.d.ts.map +0 -1
  368. package/sensor/dist/upgrade/update-check.js +0 -258
  369. package/sensor/dist/upgrade/update-check.js.map +0 -1
  370. package/src/bootstrap.mjs +0 -88
@@ -1,4 +1,4 @@
1
- import { digestArtifact } from './artifact-contracts.mjs';
1
+ import { canonicalizeArtifact, digestArtifact } from './artifact-contracts.mjs';
2
2
  import { buildNextRunEvent, buildExecutorPackets } from './runtime-engine.mjs';
3
3
  import { projectRuntimeState } from './runtime-projection.mjs';
4
4
  import {
@@ -63,6 +63,173 @@ function sha16(value) {
63
63
  }
64
64
 
65
65
  const WITNESS_KINDS = Object.freeze(['state', 'schema', 'invariant', 'effect', 'external_effect']);
66
+ const HEX_DIGEST = /^[0-9a-f]{64}$/u;
67
+ const IDENTIFIER = /^[0-9A-Za-z](?:[0-9A-Za-z._-]{0,127})$/u;
68
+
69
+ function selfDigestValid(value, field) {
70
+ return plainRecord(value) && HEX_DIGEST.test(value[field] ?? '')
71
+ && selfDigest(value, field) === value[field];
72
+ }
73
+
74
+ function sortedUnique(values, predicate) {
75
+ return Array.isArray(values) && values.every(predicate)
76
+ && values.every((value, index) => index === 0
77
+ || canonicalizeArtifact(values[index - 1]) < canonicalizeArtifact(value));
78
+ }
79
+
80
+ /** ADR 0064 Decision 5のfull predecessor→successor mapping。 */
81
+ export function validateRuntimeTaskMigration(value, { predecessorTaskIds = null,
82
+ successorTaskIds = null } = {}) {
83
+ if (!exactRecord(value, ['schema', 'entries', 'migration_digest'])
84
+ || value.schema !== 'lattice.runtime_task_migration.v1'
85
+ || !Array.isArray(value.entries) || value.entries.length > 10_000
86
+ || !selfDigestValid(value, 'migration_digest')) return false;
87
+ const predecessor = [];
88
+ const successorOwners = new Map();
89
+ for (const entry of value.entries) {
90
+ if (!exactRecord(entry, ['predecessor_task_id', 'disposition', 'successor_task_ids',
91
+ 'reason', 'evidence_digests'])
92
+ || !IDENTIFIER.test(entry.predecessor_task_id ?? '')
93
+ || !['carry', 'replace', 'split', 'retire', 'stay'].includes(entry.disposition)
94
+ || typeof entry.reason !== 'string' || entry.reason.length === 0
95
+ || !sortedUnique(entry.successor_task_ids, (id) => IDENTIFIER.test(id))
96
+ || !sortedUnique(entry.evidence_digests, (digest) => HEX_DIGEST.test(digest))) return false;
97
+ if (['carry', 'stay'].includes(entry.disposition)
98
+ && canonicalizeArtifact(entry.successor_task_ids) !== canonicalizeArtifact([entry.predecessor_task_id])) return false;
99
+ if (entry.disposition === 'retire' && entry.successor_task_ids.length !== 0) return false;
100
+ if (['replace', 'split'].includes(entry.disposition) && entry.successor_task_ids.length === 0) return false;
101
+ predecessor.push(entry.predecessor_task_id);
102
+ for (const id of entry.successor_task_ids) {
103
+ const owners = successorOwners.get(id) ?? [];
104
+ owners.push(entry.predecessor_task_id);
105
+ successorOwners.set(id, owners);
106
+ }
107
+ }
108
+ if (!sortedUnique(predecessor, (id) => IDENTIFIER.test(id))) return false;
109
+ if ([...successorOwners.values()].some((owners) => owners.length !== 1)) return false;
110
+ if (predecessorTaskIds !== null
111
+ && canonicalizeArtifact(predecessor) !== canonicalizeArtifact(sorted(predecessorTaskIds))) return false;
112
+ if (successorTaskIds !== null) {
113
+ const mapped = sorted(successorOwners.keys());
114
+ if (canonicalizeArtifact(mapped) !== canonicalizeArtifact(sorted(successorTaskIds))) return false;
115
+ }
116
+ return true;
117
+ }
118
+
119
+ export function validateRunRequestV2(value) {
120
+ if (!exactRecord(value, ['schema', 'request_id', 'repo', 'capacity', 'todos', 'manual_witness',
121
+ 'sensor_query_set', 'executor_capability', 'claim_mode', 'predecessor_request_digest',
122
+ 'task_migration_digest', 'request_digest'])
123
+ || value.schema !== 'lattice.run_request.v2'
124
+ || !HEX_DIGEST.test(value.predecessor_request_digest ?? '')
125
+ || !HEX_DIGEST.test(value.task_migration_digest ?? '')
126
+ || !selfDigestValid(value, 'request_digest')) return false;
127
+ const projected = {
128
+ schema: 'lattice.run_request.v1', request_id: value.request_id, repo: value.repo,
129
+ capacity: value.capacity, todos: value.todos, manual_witness: value.manual_witness,
130
+ sensor_query_set: value.sensor_query_set, executor_capability: value.executor_capability,
131
+ claim_mode: value.claim_mode, request_digest: '',
132
+ };
133
+ projected.request_digest = selfDigest(projected, 'request_digest');
134
+ return validateRunRequest(projected);
135
+ }
136
+
137
+ export function validateRuntimeRecompileRequest(value, { predecessorBundle = null,
138
+ frozenEventDigest = null, holdDecisionDigest = null, validatePhaseRevision = null } = {}) {
139
+ if (!exactRecord(value, ['schema', 'request_id', 'run_id', 'predecessor_epoch',
140
+ 'frozen_event_digest', 'hold_decision_digest', 'mode', 'reason', 'successor_request',
141
+ 'task_migration', 'phase_revision', 'seam_split', 'intentional_serial', 'request_digest'])
142
+ || value.schema !== 'lattice.runtime_recompile_request.v1'
143
+ || !IDENTIFIER.test(value.request_id ?? '') || !IDENTIFIER.test(value.run_id ?? '')
144
+ || !Number.isSafeInteger(value.predecessor_epoch) || value.predecessor_epoch < 1
145
+ || !HEX_DIGEST.test(value.frozen_event_digest ?? '')
146
+ || !HEX_DIGEST.test(value.hold_decision_digest ?? '')
147
+ || !['seam_split', 'intentional_serial'].includes(value.mode)
148
+ || typeof value.reason !== 'string' || value.reason.length === 0
149
+ || !validateRunRequestV2(value.successor_request)
150
+ || !validateRuntimeTaskMigration(value.task_migration, {
151
+ predecessorTaskIds: predecessorBundle?.plan?.nodes?.map(({ todo_id: id }) => id) ?? null,
152
+ successorTaskIds: value.successor_request.todos?.map(({ todo_id: id }) => id) ?? null,
153
+ })
154
+ || value.successor_request.request_id !== value.run_id
155
+ || value.successor_request.task_migration_digest !== value.task_migration.migration_digest
156
+ || !selfDigestValid(value, 'request_digest')) return false;
157
+ if (predecessorBundle !== null
158
+ && (value.predecessor_epoch !== predecessorBundle.plan_epoch
159
+ || value.successor_request.predecessor_request_digest !== predecessorBundle.request.request_digest)) return false;
160
+ if (frozenEventDigest !== null && value.frozen_event_digest !== frozenEventDigest) return false;
161
+ if (holdDecisionDigest !== null && value.hold_decision_digest !== holdDecisionDigest) return false;
162
+ if (value.phase_revision === null) {
163
+ // phase revisionを省略できるのは、TODO/source/edge入力とtask identityが完全に不変な時だけ。
164
+ // intentional_serialのruntime conflict edgeはplan overlayでありTODO工程revisionではない。
165
+ if (predecessorBundle !== null) {
166
+ const predecessorRequest = predecessorBundle.request;
167
+ const stableInputs = ['todos', 'manual_witness', 'sensor_query_set'];
168
+ if (stableInputs.some((key) => canonicalizeArtifact(value.successor_request[key])
169
+ !== canonicalizeArtifact(predecessorRequest[key]))) return false;
170
+ if (value.task_migration.entries.some((entry) => !['stay', 'carry'].includes(entry.disposition)
171
+ || entry.successor_task_ids.length !== 1
172
+ || entry.successor_task_ids[0] !== entry.predecessor_task_id)) return false;
173
+ }
174
+ } else if (typeof validatePhaseRevision !== 'function'
175
+ || validatePhaseRevision(structuredClone(value.phase_revision)) !== true
176
+ || canonicalizeArtifact(value.phase_revision.runtime_task_migration)
177
+ !== canonicalizeArtifact(value.task_migration)) return false;
178
+ if (value.mode === 'seam_split') {
179
+ if (value.intentional_serial !== null || !validateRuntimeSeamSplit(value.seam_split, value)) return false;
180
+ if (value.phase_revision === null && [
181
+ value.seam_split.ownership_diff.added, value.seam_split.ownership_diff.removed,
182
+ value.seam_split.edge_diff.added, value.seam_split.edge_diff.removed,
183
+ ].some((entries) => entries.length > 0)) return false;
184
+ } else if (value.seam_split !== null || !validateRuntimeIntentionalSerial(value.intentional_serial, value)) return false;
185
+ return true;
186
+ }
187
+
188
+ function validateRuntimeSeamSplit(value, request) {
189
+ return exactRecord(value, ['schema', 'finding_digest', 'predecessor_task_ids',
190
+ 'task_migration_digest', 'ownership_diff', 'edge_diff', 'verifier_refs', 'split_digest'])
191
+ && value.schema === 'lattice.runtime_seam_split.v1'
192
+ && HEX_DIGEST.test(value.finding_digest ?? '')
193
+ && sortedUnique(value.predecessor_task_ids, (id) => IDENTIFIER.test(id))
194
+ && value.task_migration_digest === request.task_migration.migration_digest
195
+ && validateOwnershipDiff(value.ownership_diff) && validateEdgeDiff(value.edge_diff)
196
+ && sortedUnique(value.verifier_refs, (ref) => typeof ref === 'string' && ref.length > 0)
197
+ && selfDigestValid(value, 'split_digest');
198
+ }
199
+
200
+ function validateOwnershipDiff(value) {
201
+ const entry = (item) => exactRecord(item, ['resource_id', 'owner_todo_id', 'access_kind'])
202
+ && IDENTIFIER.test(item.resource_id ?? '') && IDENTIFIER.test(item.owner_todo_id ?? '')
203
+ && ['read', 'write', 'own'].includes(item.access_kind);
204
+ return exactRecord(value, ['schema', 'added', 'removed', 'diff_digest'])
205
+ && value.schema === 'lattice.runtime_ownership_diff.v1'
206
+ && sortedUnique(value.added, entry) && sortedUnique(value.removed, entry)
207
+ && selfDigestValid(value, 'diff_digest');
208
+ }
209
+
210
+ function validateEdgeDiff(value) {
211
+ const entry = (item) => exactRecord(item, ['from_todo_id', 'to_todo_id', 'kind'])
212
+ && IDENTIFIER.test(item.from_todo_id ?? '') && IDENTIFIER.test(item.to_todo_id ?? '')
213
+ && ['hard_dependency', 'conflict'].includes(item.kind);
214
+ return exactRecord(value, ['schema', 'added', 'removed', 'diff_digest'])
215
+ && value.schema === 'lattice.runtime_edge_diff.v1'
216
+ && sortedUnique(value.added, entry) && sortedUnique(value.removed, entry)
217
+ && selfDigestValid(value, 'diff_digest');
218
+ }
219
+
220
+ function validateRuntimeIntentionalSerial(value, request) {
221
+ if (!exactRecord(value, ['schema', 'finding_digest', 'todo_ids', 'resource_id',
222
+ 'stay_todo_id', 'reason', 'serial_digest'])
223
+ || value.schema !== 'lattice.runtime_intentional_serial.v1'
224
+ || !HEX_DIGEST.test(value.finding_digest ?? '')
225
+ || !sortedUnique(value.todo_ids, (id) => IDENTIFIER.test(id)) || value.todo_ids.length < 2
226
+ || !IDENTIFIER.test(value.resource_id ?? '') || !value.todo_ids.includes(value.stay_todo_id)
227
+ || typeof value.reason !== 'string' || value.reason.length === 0
228
+ || !selfDigestValid(value, 'serial_digest')) return false;
229
+ const byId = new Map(request.task_migration.entries.map((entry) => [entry.predecessor_task_id, entry]));
230
+ return value.todo_ids.every((id) => byId.has(id))
231
+ && byId.get(value.stay_todo_id)?.disposition === 'stay';
232
+ }
66
233
 
67
234
  function manifestResourceIds(manifest) {
68
235
  const ids = new Set(manifest?.resources ?? []);
@@ -234,6 +401,7 @@ export function decideHoldAndCarryOver(options = {}) {
234
401
  && event.subject?.kind === 'todo'
235
402
  && event.subject.ref === todoId
236
403
  && ['checkpoint_observed', 'receipt_recorded'].includes(event.kind)
404
+ && event.payload?.barrier_final !== true
237
405
  ));
238
406
  if (postFreezeEvents) {
239
407
  holdSet.add(todoId);
@@ -372,7 +540,8 @@ export function routeConflictTreatment(options = {}) {
372
540
  /**
373
541
  * hold決定後のplan vN+1をcompileする。carried-over TODOへはepoch rebind packet
374
542
  * (content不変・epoch/plan refのみ更新)、hold TODOへは新plan_ref由来の
375
- * 新context packetを発行し、旧contextを失効してintakeを再開する。
543
+ * 新context packetを発行し、旧contextを失効する。rebind/prepare ack、epoch pointer、
544
+ * controller ready/release ack、中央gate commit前にはepoch_rebound/intake_resumedを発行しない。
376
545
  */
377
546
  export function recompileNextEpochPlan(options = {}) {
378
547
  if (!exactRecord(options, [
@@ -550,15 +719,6 @@ export function recompileNextEpochPlan(options = {}) {
550
719
  fail(`rebindのcontent digestがvN packet contentと一致しない: ${todoId}`);
551
720
  }
552
721
  rebindPackets[todoId] = rebind;
553
- next.push(buildNextRunEvent({
554
- events: next,
555
- runId,
556
- kind: 'epoch_rebound',
557
- planEpoch: newEpoch,
558
- subject: { kind: 'todo', ref: todoId },
559
- payload: structuredClone(rebind),
560
- recordedAt,
561
- }));
562
722
  }
563
723
 
564
724
  // redispatch TODOへは新plan_ref由来の別content packetを発行する。
@@ -584,18 +744,6 @@ export function recompileNextEpochPlan(options = {}) {
584
744
  planDiff.diff_digest = selfDigest(planDiff, 'diff_digest');
585
745
  if (!validateRuntimePlanDiff(planDiff)) fail('plan diffがcontractを満たさない');
586
746
 
587
- // intake再開(freeze境界はfreeze_historyとして永続し、receipt stale判定は
588
- // 最初のfreezeに対して行われ続ける)。
589
- next.push(buildNextRunEvent({
590
- events: next,
591
- runId,
592
- kind: 'intake_resumed',
593
- planEpoch: newEpoch,
594
- subject: { kind: 'runtime_plan', ref: newPlanRef },
595
- payload: { plan_diff_digest: planDiff.diff_digest },
596
- recordedAt,
597
- }));
598
-
599
747
  return {
600
748
  events: next,
601
749
  newPlan,
@@ -604,3 +752,46 @@ export function recompileNextEpochPlan(options = {}) {
604
752
  redispatchPackets,
605
753
  };
606
754
  }
755
+
756
+ /**
757
+ * controller direct ackと中央gate commitが全件揃った後だけrun eventを公開する。
758
+ * producer compileとは分離し、ack前の呼出しは一切のpartial eventを返さない。
759
+ */
760
+ export function finalizeRecompileActivation(options = {}) {
761
+ if (!exactRecord(options, ['runId', 'events', 'plan', 'planDiff', 'rebindPackets',
762
+ 'rebindAcks', 'gateDigest', 'gateControlEventDigest', 'recordedAt'])) {
763
+ fail('finalizeRecompileActivation optionsがexact shapeでない');
764
+ }
765
+ const { runId, events, plan, planDiff, rebindPackets, rebindAcks, gateDigest,
766
+ gateControlEventDigest, recordedAt } = options;
767
+ if (!validateRuntimePlan(plan) || !validateRuntimePlanDiff(planDiff)
768
+ || !HEX_DIGEST.test(gateDigest ?? '') || !HEX_DIGEST.test(gateControlEventDigest ?? '')
769
+ || !plainRecord(rebindPackets) || !plainRecord(rebindAcks)) {
770
+ fail('activation bindingが不正');
771
+ }
772
+ const packetIds = Object.keys(rebindPackets).sort();
773
+ if (canonicalizeArtifact(Object.keys(rebindAcks).sort()) !== canonicalizeArtifact(packetIds)) {
774
+ fail('rebind ack集合がpacket集合とexact一致しない');
775
+ }
776
+ for (const todoId of packetIds) {
777
+ const packet = rebindPackets[todoId];
778
+ const ack = rebindAcks[todoId];
779
+ if (!validateEpochRebindPacket(packet)
780
+ || !plainRecord(ack) || ack.schema !== 'lattice.executor_epoch_rebind_ack.v1'
781
+ || ack.todo_id !== todoId || ack.rebind_packet_digest !== packet.packet_digest
782
+ || ack.successor_epoch !== plan.plan_epoch || !HEX_DIGEST.test(ack.ack_digest ?? '')
783
+ || !selfDigestValid(ack, 'ack_digest')) fail(`rebind ack bindingが不正: ${todoId}`);
784
+ }
785
+ let next = [...events];
786
+ // 全件を先に検証した後にだけbatchを構築する(partial epoch_rebound禁止)。
787
+ for (const todoId of packetIds) {
788
+ next.push(buildNextRunEvent({ events: next, runId, kind: 'epoch_rebound',
789
+ planEpoch: plan.plan_epoch, subject: { kind: 'todo', ref: todoId },
790
+ payload: structuredClone(rebindPackets[todoId]), recordedAt }));
791
+ }
792
+ next.push(buildNextRunEvent({ events: next, runId, kind: 'intake_resumed',
793
+ planEpoch: plan.plan_epoch, subject: { kind: 'runtime_plan', ref: plan.plan_ref },
794
+ payload: { plan_diff_digest: planDiff.diff_digest, write_gate_digest: gateDigest,
795
+ control_event_digest: gateControlEventDigest }, recordedAt }));
796
+ return { events: next, redispatchTodoIds: [...planDiff.redispatched].sort() };
797
+ }
@@ -0,0 +1,290 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { constants as fsConstants } from 'node:fs';
3
+ import { lstat, open, readFile, rename, rm, unlink } from 'node:fs/promises';
4
+ import path from 'node:path';
5
+
6
+ import { canonicalizeArtifact } from './artifact-contracts.mjs';
7
+ import { selfDigest } from './runtime-contracts.mjs';
8
+
9
+ const SHA256 = /^[0-9a-f]{64}$/;
10
+ const ID = /^[0-9A-Za-z](?:[0-9A-Za-z._-]{0,127})$/;
11
+ const TIMESTAMP = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/;
12
+ const LOCK_NAME = '.lifecycle.lock';
13
+
14
+ export class RuntimeLifecycleLockError extends Error {
15
+ constructor(code, detail) {
16
+ super(`${code}: ${detail}`);
17
+ this.name = 'RuntimeLifecycleLockError';
18
+ this.code = code;
19
+ this.detail = detail;
20
+ }
21
+ }
22
+
23
+ function fail(code, detail) { throw new RuntimeLifecycleLockError(code, detail); }
24
+ function plain(value) {
25
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
26
+ && Object.getPrototypeOf(value) === Object.prototype;
27
+ }
28
+ function exact(value, keys) {
29
+ if (!plain(value)) return false;
30
+ const actual = Object.keys(value).sort();
31
+ const expected = [...keys].sort();
32
+ return actual.length === expected.length
33
+ && actual.every((key, index) => key === expected[index]);
34
+ }
35
+ function digest(value) { return typeof value === 'string' && SHA256.test(value); }
36
+ function identifier(value) { return typeof value === 'string' && ID.test(value); }
37
+ function timestamp(value) {
38
+ return typeof value === 'string' && TIMESTAMP.test(value)
39
+ && !Number.isNaN(Date.parse(value)) && new Date(value).toISOString() === value;
40
+ }
41
+ function validProcessStartIdentity(value) {
42
+ return exact(value, ['schema', 'platform', 'pid', 'started_identity', 'identity_digest'])
43
+ && value.schema === 'lattice.process_start_identity.v1'
44
+ && typeof value.platform === 'string' && value.platform.length > 0
45
+ && Number.isSafeInteger(value.pid) && value.pid >= 1
46
+ && typeof value.started_identity === 'string' && value.started_identity.length > 0
47
+ && digest(value.identity_digest)
48
+ && selfDigest(value, 'identity_digest') === value.identity_digest;
49
+ }
50
+
51
+ export function validateRuntimeLifecycleLockArtifact(value) {
52
+ return exact(value, [
53
+ 'schema', 'owner_pid', 'owner_process_start_identity', 'session_nonce_digest',
54
+ 'operation', 'request_id', 'acquired_at', 'lock_digest',
55
+ ])
56
+ && value.schema === 'lattice.runtime_lifecycle_lock.v1'
57
+ && Number.isSafeInteger(value.owner_pid) && value.owner_pid >= 1
58
+ && validProcessStartIdentity(value.owner_process_start_identity)
59
+ && value.owner_process_start_identity.pid === value.owner_pid
60
+ && digest(value.session_nonce_digest)
61
+ && identifier(value.operation)
62
+ && identifier(value.request_id)
63
+ && timestamp(value.acquired_at)
64
+ && digest(value.lock_digest)
65
+ && selfDigest(value, 'lock_digest') === value.lock_digest;
66
+ }
67
+
68
+ function validateOptions({ lockPath, runDir, sessionNonceDigest, operation, requestId,
69
+ timeoutMs, retryIntervalMs, processStartIdentity, observeProcessStartIdentity, now }) {
70
+ const resolved = lockPath ?? (typeof runDir === 'string' ? path.join(runDir, LOCK_NAME) : null);
71
+ if (typeof resolved !== 'string' || !path.isAbsolute(resolved)
72
+ || !digest(sessionNonceDigest) || !identifier(operation) || !identifier(requestId)
73
+ || !Number.isSafeInteger(timeoutMs) || timeoutMs < 0
74
+ || !Number.isSafeInteger(retryIntervalMs) || retryIntervalMs < 1
75
+ || (processStartIdentity !== null && !validProcessStartIdentity(processStartIdentity))
76
+ || (observeProcessStartIdentity !== null && typeof observeProcessStartIdentity !== 'function')
77
+ || typeof now !== 'function') fail('RUN_LOCK_INVALID', 'lifecycle lock入力不正');
78
+ return resolved;
79
+ }
80
+
81
+ async function defaultObserver(pid) {
82
+ const { observeManagedProcessStartIdentity } = await import('./runtime-managed-supervisor.mjs');
83
+ return observeManagedProcessStartIdentity(pid);
84
+ }
85
+
86
+ async function readLockArtifact(lockPath) {
87
+ const info = await lstat(lockPath);
88
+ if (!info.isFile() || info.isSymbolicLink() || info.nlink !== 1) {
89
+ fail('RUN_LOCK_INVALID', 'lifecycle lockが単一linkのregular fileでない');
90
+ }
91
+ const bytes = await readFile(lockPath);
92
+ let value;
93
+ try { value = JSON.parse(bytes.toString('utf8')); }
94
+ catch { fail('RUN_BUSY', 'lifecycle lock取得処理が進行中'); }
95
+ if (!validateRuntimeLifecycleLockArtifact(value)) {
96
+ fail('RUN_LOCK_INVALID', 'lifecycle lock artifact不正');
97
+ }
98
+ if (bytes.toString('utf8') !== `${canonicalizeArtifact(value)}\n`) {
99
+ fail('RUN_LOCK_INVALID', 'lifecycle lockがcanonical bytesでない');
100
+ }
101
+ return { value, info };
102
+ }
103
+
104
+ async function pidExists(pid) {
105
+ try { process.kill(pid, 0); return true; }
106
+ catch (error) {
107
+ if (error?.code === 'ESRCH') return false;
108
+ if (error?.code === 'EPERM') return true;
109
+ throw error;
110
+ }
111
+ }
112
+
113
+ async function ownerIsLive(artifact, observer) {
114
+ let observed;
115
+ try { observed = await observer(artifact.owner_pid); }
116
+ catch {
117
+ // observer障害とprocess不在を混同しない。PIDが存在する限りlockを回収しない。
118
+ return pidExists(artifact.owner_pid);
119
+ }
120
+ if (observed === null || observed === undefined) return pidExists(artifact.owner_pid);
121
+ if (!validProcessStartIdentity(observed) || observed.pid !== artifact.owner_pid) {
122
+ fail('RUN_LOCK_INVALID', 'owner process observation不正');
123
+ }
124
+ return observed.identity_digest === artifact.owner_process_start_identity.identity_digest;
125
+ }
126
+
127
+ async function syncDirectory(directory) {
128
+ const handle = await open(directory, fsConstants.O_RDONLY);
129
+ try { await handle.sync(); } finally { await handle.close(); }
130
+ }
131
+
132
+ async function recoverStaleLock(lockPath, expectedDigest) {
133
+ const quarantine = path.join(path.dirname(lockPath),
134
+ `.${path.basename(lockPath)}.${process.pid}.${randomUUID()}.stale`);
135
+ let removeQuarantine = true;
136
+ try {
137
+ await rename(lockPath, quarantine);
138
+ } catch (error) {
139
+ if (error?.code === 'ENOENT') return;
140
+ throw error;
141
+ }
142
+ try {
143
+ const moved = await readLockArtifact(quarantine);
144
+ if (moved.value.lock_digest !== expectedDigest) {
145
+ // stale判定後に別ownerが取得したfileをrenameしてしまった場合は破棄しない。
146
+ try { await rename(quarantine, lockPath); }
147
+ catch (error) {
148
+ if (error?.code === 'EEXIST' || error?.code === 'ENOTEMPTY') {
149
+ removeQuarantine = false;
150
+ fail('RUN_LOCK_INVALID', `回収競合artifactを保全した: ${quarantine}`);
151
+ }
152
+ throw error;
153
+ }
154
+ fail('RUN_BUSY', 'lifecycle lock ownerが回収中に変更された');
155
+ }
156
+ await unlink(quarantine);
157
+ await syncDirectory(path.dirname(lockPath));
158
+ } finally {
159
+ if (removeQuarantine) await rm(quarantine, { force: true }).catch(() => {});
160
+ }
161
+ }
162
+
163
+ async function createLock(lockPath, artifact) {
164
+ let handle;
165
+ let created = false;
166
+ try {
167
+ handle = await open(lockPath,
168
+ fsConstants.O_CREAT | fsConstants.O_EXCL | fsConstants.O_WRONLY, 0o600);
169
+ created = true;
170
+ await handle.writeFile(Buffer.from(`${canonicalizeArtifact(artifact)}\n`, 'utf8'));
171
+ await handle.sync();
172
+ await handle.close();
173
+ handle = null;
174
+ await syncDirectory(path.dirname(lockPath));
175
+ return true;
176
+ } catch (error) {
177
+ if (error?.code === 'EEXIST') return false;
178
+ if (handle) {
179
+ await handle.close().catch(() => {});
180
+ handle = null;
181
+ }
182
+ if (created) await unlink(lockPath).catch(() => {});
183
+ throw error;
184
+ } finally {
185
+ if (handle) await handle.close().catch(() => {});
186
+ }
187
+ }
188
+
189
+ function sleep(milliseconds) {
190
+ return new Promise((resolve) => setTimeout(resolve, milliseconds));
191
+ }
192
+
193
+ /**
194
+ * run lifecycle mutationをdurable owner artifactで直列化する。
195
+ * timeoutMs=0はlive競合を即時RUN_BUSYにする。
196
+ */
197
+ export async function acquireRuntimeLifecycleLock({
198
+ runDir = null,
199
+ lockPath = null,
200
+ sessionNonceDigest,
201
+ operation,
202
+ requestId,
203
+ timeoutMs = 0,
204
+ retryIntervalMs = 10,
205
+ processStartIdentity = null,
206
+ observeProcessStartIdentity = null,
207
+ now = () => new Date(),
208
+ } = {}) {
209
+ const resolvedLockPath = validateOptions({ lockPath, runDir, sessionNonceDigest, operation,
210
+ requestId, timeoutMs, retryIntervalMs, processStartIdentity, observeProcessStartIdentity, now });
211
+ const observer = observeProcessStartIdentity ?? defaultObserver;
212
+ const ownerIdentity = processStartIdentity ?? await observer(process.pid);
213
+ if (!validProcessStartIdentity(ownerIdentity) || ownerIdentity.pid !== process.pid) {
214
+ fail('RUN_LOCK_INVALID', 'acquirer process start identity不正');
215
+ }
216
+ const acquiredAt = now();
217
+ if (!(acquiredAt instanceof Date) || Number.isNaN(acquiredAt.valueOf())) {
218
+ fail('RUN_LOCK_INVALID', 'acquired_at生成値不正');
219
+ }
220
+ const artifact = {
221
+ schema: 'lattice.runtime_lifecycle_lock.v1',
222
+ owner_pid: process.pid,
223
+ owner_process_start_identity: structuredClone(ownerIdentity),
224
+ session_nonce_digest: sessionNonceDigest,
225
+ operation,
226
+ request_id: requestId,
227
+ acquired_at: acquiredAt.toISOString(),
228
+ lock_digest: '',
229
+ };
230
+ artifact.lock_digest = selfDigest(artifact, 'lock_digest');
231
+ const deadline = Date.now() + timeoutMs;
232
+
233
+ while (true) {
234
+ if (await createLock(resolvedLockPath, artifact)) {
235
+ let released = false;
236
+ return {
237
+ artifact: structuredClone(artifact),
238
+ lockPath: resolvedLockPath,
239
+ async release() {
240
+ if (released) return;
241
+ await releaseRuntimeLifecycleLock({
242
+ lockPath: resolvedLockPath, ownerDigest: artifact.lock_digest,
243
+ });
244
+ released = true;
245
+ },
246
+ };
247
+ }
248
+
249
+ let existing;
250
+ try { existing = await readLockArtifact(resolvedLockPath); }
251
+ catch (error) {
252
+ if (error?.code === 'ENOENT') continue;
253
+ if (error instanceof RuntimeLifecycleLockError && error.code === 'RUN_BUSY'
254
+ && Date.now() < deadline) { await sleep(retryIntervalMs); continue; }
255
+ throw error;
256
+ }
257
+ if (!await ownerIsLive(existing.value, observer)) {
258
+ await recoverStaleLock(resolvedLockPath, existing.value.lock_digest);
259
+ continue;
260
+ }
261
+ if (Date.now() >= deadline) {
262
+ fail('RUN_BUSY', timeoutMs === 0
263
+ ? `run lifecycle操作が既に進行中: ${existing.value.operation}/${existing.value.request_id}`
264
+ : `run lifecycle lock timeout: ${existing.value.operation}/${existing.value.request_id}`);
265
+ }
266
+ await sleep(Math.min(retryIntervalMs, Math.max(1, deadline - Date.now())));
267
+ }
268
+ }
269
+
270
+ /** lock artifactのowner digestが一致する呼出しだけがreleaseできる。 */
271
+ export async function releaseRuntimeLifecycleLock({ lockPath, ownerDigest } = {}) {
272
+ if (typeof lockPath !== 'string' || !path.isAbsolute(lockPath) || !digest(ownerDigest)) {
273
+ fail('RUN_LOCK_INVALID', 'lifecycle lock release入力不正');
274
+ }
275
+ let existing;
276
+ try { existing = await readLockArtifact(lockPath); }
277
+ catch (error) {
278
+ if (error?.code === 'ENOENT') fail('RUN_LOCK_OWNER_MISMATCH', 'release対象lockなし');
279
+ throw error;
280
+ }
281
+ if (existing.value.lock_digest !== ownerDigest) {
282
+ fail('RUN_LOCK_OWNER_MISMATCH', 'lifecycle lock owner digest不一致');
283
+ }
284
+ const current = await lstat(lockPath);
285
+ if (current.dev !== existing.info.dev || current.ino !== existing.info.ino) {
286
+ fail('RUN_LOCK_OWNER_MISMATCH', 'lifecycle lockがrelease前に差し替わった');
287
+ }
288
+ await unlink(lockPath);
289
+ await syncDirectory(path.dirname(lockPath));
290
+ }