@eyeauras/insight-cli 0.8.4 → 0.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (609) hide show
  1. package/.cli-package-build.json +1 -1
  2. package/README.md +16 -23
  3. package/SKILL.md +6 -44
  4. package/dist/src/activity-audit.d.ts +33 -46
  5. package/dist/src/activity-audit.js +120 -195
  6. package/dist/src/analysis-default.d.ts +10 -2
  7. package/dist/src/analysis-default.js +62 -47
  8. package/dist/src/analysis-storage.d.ts +13 -13
  9. package/dist/src/analysis-storage.js +127 -258
  10. package/dist/src/artifacts.d.ts +5 -1
  11. package/dist/src/artifacts.js +31 -46
  12. package/dist/src/audit-commands.d.ts +6 -1
  13. package/dist/src/audit-commands.js +9 -2
  14. package/dist/src/audit-retention.d.ts +5 -23
  15. package/dist/src/audit-retention.js +37 -150
  16. package/dist/src/binary.js +4 -13
  17. package/dist/src/budgets.d.ts +2 -2
  18. package/dist/src/budgets.js +7 -9
  19. package/dist/src/capture.js +17 -30
  20. package/dist/src/cli.d.ts +9 -4
  21. package/dist/src/cli.js +288 -473
  22. package/dist/src/code-references.d.ts +2 -13
  23. package/dist/src/code-references.js +7 -99
  24. package/dist/src/context-diagnostics.d.ts +1 -23
  25. package/dist/src/context-diagnostics.js +1 -83
  26. package/dist/src/core/coordinator.d.ts +298 -0
  27. package/dist/src/core/coordinator.js +591 -0
  28. package/dist/src/core/layout.d.ts +51 -0
  29. package/dist/src/core/layout.js +55 -0
  30. package/dist/src/core/legacy-import.d.ts +55 -0
  31. package/dist/src/core/legacy-import.js +193 -0
  32. package/dist/src/cross-results.d.ts +3 -3
  33. package/dist/src/cross-results.js +4 -42
  34. package/dist/src/cross.js +2 -3
  35. package/dist/src/debugger-results.d.ts +1 -6
  36. package/dist/src/debugger-results.js +21 -153
  37. package/dist/src/debugger.d.ts +21 -11
  38. package/dist/src/debugger.js +106 -168
  39. package/dist/src/decode-results.d.ts +2 -1
  40. package/dist/src/decode-results.js +4 -20
  41. package/dist/src/diagnostic-error.d.ts +1 -1
  42. package/dist/src/diagnostic-error.js +4 -23
  43. package/dist/src/die.js +1 -23
  44. package/dist/src/dnspy-runtime.js +5 -12
  45. package/dist/src/dnspy.js +13 -28
  46. package/dist/src/dotnet-diagnostics.js +1 -1
  47. package/dist/src/extensions.d.ts +2 -3
  48. package/dist/src/extensions.js +14 -91
  49. package/dist/src/frida-worker.js +0 -20
  50. package/dist/src/frida.js +3 -26
  51. package/dist/src/function-boundaries.d.ts +2 -2
  52. package/dist/src/function-boundaries.js +9 -61
  53. package/dist/src/function-entries.d.ts +2 -2
  54. package/dist/src/function-entries.js +6 -36
  55. package/dist/src/function-inspection.d.ts +2 -2
  56. package/dist/src/function-inspection.js +17 -33
  57. package/dist/src/function-results.d.ts +1 -3
  58. package/dist/src/function-results.js +2 -13
  59. package/dist/src/hub/admin.d.ts +101 -0
  60. package/dist/src/hub/admin.js +314 -0
  61. package/dist/src/hub/autostart.d.ts +111 -0
  62. package/dist/src/hub/autostart.js +207 -0
  63. package/dist/src/hub/bundle.d.ts +33 -0
  64. package/dist/src/hub/bundle.js +25 -0
  65. package/dist/src/hub/client.d.ts +90 -0
  66. package/dist/src/hub/client.js +256 -0
  67. package/dist/src/hub/commands.d.ts +13 -0
  68. package/dist/src/hub/commands.js +280 -0
  69. package/dist/src/hub/contract.d.ts +87 -0
  70. package/dist/src/hub/contract.js +3 -0
  71. package/dist/src/hub/extensions.d.ts +41 -0
  72. package/dist/src/hub/extensions.js +3 -0
  73. package/dist/src/hub/ghidra.d.ts +70 -0
  74. package/dist/src/hub/ghidra.js +197 -0
  75. package/dist/src/hub/index.d.ts +6 -0
  76. package/dist/src/hub/index.js +7 -0
  77. package/dist/src/{work/store.d.ts → hub/ledger-store.d.ts} +57 -94
  78. package/dist/src/hub/ledger-store.js +919 -0
  79. package/dist/src/hub/ledger.d.ts +4 -0
  80. package/dist/src/hub/ledger.js +173 -0
  81. package/dist/src/hub/lock.d.ts +7 -0
  82. package/dist/src/hub/lock.js +53 -0
  83. package/dist/src/hub/repository.d.ts +45 -0
  84. package/dist/src/hub/repository.js +130 -0
  85. package/dist/src/hub/server.d.ts +86 -0
  86. package/dist/src/hub/server.js +414 -0
  87. package/dist/src/hub/settings.d.ts +36 -0
  88. package/dist/src/hub/settings.js +112 -0
  89. package/dist/src/hub/storage.d.ts +13 -0
  90. package/dist/src/hub/storage.js +46 -0
  91. package/dist/src/hub/store.d.ts +75 -0
  92. package/dist/src/hub/store.js +188 -0
  93. package/dist/src/ilspy.js +1 -1
  94. package/dist/src/internal-timing.d.ts +2 -9
  95. package/dist/src/internal-timing.js +2 -95
  96. package/dist/src/lldb.js +3 -15
  97. package/dist/src/llvm.js +0 -9
  98. package/dist/src/managed-heap.js +3 -7
  99. package/dist/src/managed-metadata.js +2 -5
  100. package/dist/src/memory-inputs.d.ts +1 -4
  101. package/dist/src/memory-inputs.js +10 -40
  102. package/dist/src/mitmproxy.d.ts +35 -4
  103. package/dist/src/mitmproxy.js +59 -40
  104. package/dist/src/model.d.ts +0 -73
  105. package/dist/src/model.js +0 -45
  106. package/dist/src/mutations.d.ts +1 -1
  107. package/dist/src/mutations.js +5 -10
  108. package/dist/src/native/contract.d.ts +130 -0
  109. package/dist/src/native/ghidra.d.ts +58 -0
  110. package/dist/src/native/ghidra.js +77 -0
  111. package/dist/src/native/host.d.ts +71 -0
  112. package/dist/src/native/host.js +265 -0
  113. package/dist/src/native/index.d.ts +13 -0
  114. package/dist/src/native/index.js +19 -0
  115. package/dist/src/native/jvm.d.ts +54 -0
  116. package/dist/src/native/jvm.js +47 -0
  117. package/dist/src/native/worker.d.ts +70 -0
  118. package/dist/src/native/worker.js +240 -0
  119. package/dist/src/native-inputs.d.ts +9 -14
  120. package/dist/src/native-inputs.js +22 -110
  121. package/dist/src/native-merge-patches.d.ts +2 -2
  122. package/dist/src/native-merge-patches.js +14 -14
  123. package/dist/src/persistent-client.js +53 -25
  124. package/dist/src/procmon.js +17 -31
  125. package/dist/src/program-files.d.ts +42 -0
  126. package/dist/src/program-files.js +148 -0
  127. package/dist/src/queries.js +2 -15
  128. package/dist/src/query-policy.d.ts +0 -2
  129. package/dist/src/query-policy.js +1 -14
  130. package/dist/src/research.d.ts +59 -238
  131. package/dist/src/research.js +212 -906
  132. package/dist/src/runtime-identity.d.ts +8 -0
  133. package/dist/src/runtime-identity.js +26 -0
  134. package/dist/src/runtime-manager.d.ts +1 -11
  135. package/dist/src/runtime-manager.js +10 -145
  136. package/dist/src/runtime-selection.d.ts +1 -1
  137. package/dist/src/runtime-selection.js +5 -37
  138. package/dist/src/saved-materials.js +8 -51
  139. package/dist/src/scripts.d.ts +1 -1
  140. package/dist/src/scripts.js +15 -15
  141. package/dist/src/sdk-contracts.js +2 -2
  142. package/dist/src/sdk.js +8 -8
  143. package/dist/src/sevenzip.js +1 -3
  144. package/dist/src/strace.js +0 -3
  145. package/dist/src/string-anchors.d.ts +2 -3
  146. package/dist/src/string-anchors.js +8 -101
  147. package/dist/src/text-window.d.ts +5 -4
  148. package/dist/src/text-window.js +4 -4
  149. package/dist/src/tool-runtime/archives.d.ts +1 -1
  150. package/dist/src/tool-runtime/archives.js +11 -20
  151. package/dist/src/tool-runtime/catalog.js +2 -5
  152. package/dist/src/tool-runtime/commands.js +1 -3
  153. package/dist/src/tool-runtime/deadline.js +2 -7
  154. package/dist/src/tool-runtime/definition.js +1 -31
  155. package/dist/src/tool-runtime/identity.js +6 -87
  156. package/dist/src/tool-runtime/installer.d.ts +2 -6
  157. package/dist/src/tool-runtime/installer.js +14 -76
  158. package/dist/src/tool-runtime/java-arguments.js +4 -10
  159. package/dist/src/tool-runtime/launch-worker.js +2 -8
  160. package/dist/src/tool-runtime/run.d.ts +2 -0
  161. package/dist/src/tool-runtime/run.js +20 -8
  162. package/dist/src/tool-runtime/store.d.ts +3 -3
  163. package/dist/src/tool-runtime/store.js +21 -83
  164. package/dist/src/tool-runtime/supervisor.d.ts +6 -11
  165. package/dist/src/tool-runtime/supervisor.js +155 -214
  166. package/dist/src/tool-runtime/windows-helper.d.ts +5 -0
  167. package/dist/src/tool-runtime/windows-helper.js +13 -0
  168. package/dist/src/tool-runtime/windows-job.d.ts +5 -5
  169. package/dist/src/tool-runtime/windows-job.js +13 -31
  170. package/dist/src/tshark.js +14 -27
  171. package/dist/src/ui-results.d.ts +3 -2
  172. package/dist/src/ui-results.js +16 -53
  173. package/dist/src/ui.d.ts +12 -13
  174. package/dist/src/ui.js +32 -70
  175. package/dist/src/version-tracking.d.ts +25 -39
  176. package/dist/src/version-tracking.js +70 -174
  177. package/dist/src/windbg.d.ts +1 -1
  178. package/dist/src/windbg.js +2 -8
  179. package/dist/src/work/client.d.ts +63 -0
  180. package/dist/src/work/client.js +163 -0
  181. package/dist/src/work/commands.d.ts +3 -1
  182. package/dist/src/work/commands.js +158 -184
  183. package/dist/src/work/dashboard.d.ts +2 -2
  184. package/dist/src/work/dashboard.js +7 -8
  185. package/dist/src/work/legacy.d.ts +8 -0
  186. package/dist/src/work/legacy.js +70 -0
  187. package/dist/src/work/model.d.ts +0 -3
  188. package/dist/src/work/model.js +0 -10
  189. package/dist/src/work/timing.d.ts +3 -3
  190. package/dist/src/work/timing.js +21 -25
  191. package/dist/src/workspace.d.ts +4 -250
  192. package/dist/src/workspace.js +11 -699
  193. package/node_modules/@eyeauras/cli-factory/README.md +6 -0
  194. package/node_modules/@eyeauras/cli-factory/dist/src/cli.d.ts.map +1 -1
  195. package/node_modules/@eyeauras/cli-factory/dist/src/cli.js +76 -28
  196. package/node_modules/@eyeauras/cli-factory/dist/src/cli.js.map +1 -1
  197. package/node_modules/@eyeauras/cli-factory/dist/src/command.d.ts +1 -1
  198. package/node_modules/@eyeauras/cli-factory/dist/src/command.d.ts.map +1 -1
  199. package/node_modules/@eyeauras/cli-factory/dist/src/command.js +1 -0
  200. package/node_modules/@eyeauras/cli-factory/dist/src/command.js.map +1 -1
  201. package/node_modules/@eyeauras/cli-factory/dist/src/errors.d.ts +1 -1
  202. package/node_modules/@eyeauras/cli-factory/dist/src/errors.d.ts.map +1 -1
  203. package/node_modules/@eyeauras/cli-factory/dist/src/errors.js +18 -6
  204. package/node_modules/@eyeauras/cli-factory/dist/src/errors.js.map +1 -1
  205. package/node_modules/@eyeauras/cli-factory/dist/src/file-publication.d.ts +44 -0
  206. package/node_modules/@eyeauras/cli-factory/dist/src/file-publication.d.ts.map +1 -0
  207. package/node_modules/@eyeauras/cli-factory/dist/src/{profile-file.js → file-publication.js} +41 -113
  208. package/node_modules/@eyeauras/cli-factory/dist/src/file-publication.js.map +1 -0
  209. package/node_modules/@eyeauras/cli-factory/dist/src/help.d.ts +5 -0
  210. package/node_modules/@eyeauras/cli-factory/dist/src/help.d.ts.map +1 -0
  211. package/node_modules/@eyeauras/cli-factory/dist/src/help.js +17 -0
  212. package/node_modules/@eyeauras/cli-factory/dist/src/help.js.map +1 -0
  213. package/node_modules/@eyeauras/cli-factory/dist/src/index.d.ts +9 -4
  214. package/node_modules/@eyeauras/cli-factory/dist/src/index.d.ts.map +1 -1
  215. package/node_modules/@eyeauras/cli-factory/dist/src/index.js +5 -2
  216. package/node_modules/@eyeauras/cli-factory/dist/src/index.js.map +1 -1
  217. package/node_modules/@eyeauras/cli-factory/dist/src/json-rpc.d.ts.map +1 -1
  218. package/node_modules/@eyeauras/cli-factory/dist/src/json-rpc.js +11 -18
  219. package/node_modules/@eyeauras/cli-factory/dist/src/json-rpc.js.map +1 -1
  220. package/node_modules/@eyeauras/cli-factory/dist/src/output-write.d.ts +10 -0
  221. package/node_modules/@eyeauras/cli-factory/dist/src/output-write.d.ts.map +1 -0
  222. package/node_modules/@eyeauras/cli-factory/dist/src/output-write.js +69 -0
  223. package/node_modules/@eyeauras/cli-factory/dist/src/output-write.js.map +1 -0
  224. package/node_modules/@eyeauras/cli-factory/dist/src/output.d.ts +3 -1
  225. package/node_modules/@eyeauras/cli-factory/dist/src/output.d.ts.map +1 -1
  226. package/node_modules/@eyeauras/cli-factory/dist/src/output.js +74 -14
  227. package/node_modules/@eyeauras/cli-factory/dist/src/output.js.map +1 -1
  228. package/node_modules/@eyeauras/cli-factory/dist/src/pagination.d.ts +3 -0
  229. package/node_modules/@eyeauras/cli-factory/dist/src/pagination.d.ts.map +1 -0
  230. package/node_modules/@eyeauras/cli-factory/dist/src/pagination.js +9 -0
  231. package/node_modules/@eyeauras/cli-factory/dist/src/pagination.js.map +1 -0
  232. package/node_modules/@eyeauras/cli-factory/dist/src/permissions.d.ts.map +1 -1
  233. package/node_modules/@eyeauras/cli-factory/dist/src/permissions.js +3 -1
  234. package/node_modules/@eyeauras/cli-factory/dist/src/permissions.js.map +1 -1
  235. package/node_modules/@eyeauras/cli-factory/dist/src/stream-result.d.ts +16 -0
  236. package/node_modules/@eyeauras/cli-factory/dist/src/stream-result.d.ts.map +1 -0
  237. package/node_modules/@eyeauras/cli-factory/dist/src/stream-result.js +83 -0
  238. package/node_modules/@eyeauras/cli-factory/dist/src/stream-result.js.map +1 -0
  239. package/node_modules/@eyeauras/cli-factory/dist/src/types.d.ts +5 -0
  240. package/node_modules/@eyeauras/cli-factory/dist/src/types.d.ts.map +1 -1
  241. package/node_modules/@eyeauras/cli-factory/dist/src/view.d.ts +49 -7
  242. package/node_modules/@eyeauras/cli-factory/dist/src/view.d.ts.map +1 -1
  243. package/node_modules/@eyeauras/cli-factory/dist/src/view.js +83 -6
  244. package/node_modules/@eyeauras/cli-factory/dist/src/view.js.map +1 -1
  245. package/node_modules/@eyeauras/cli-factory/package.json +1 -1
  246. package/node_modules/@eyeauras/cli-factory-ipc/dist/cli-host.proto +19 -19
  247. package/node_modules/@eyeauras/cli-factory-ipc/dist/src/build.d.ts +7 -1
  248. package/node_modules/@eyeauras/cli-factory-ipc/dist/src/build.d.ts.map +1 -1
  249. package/node_modules/@eyeauras/cli-factory-ipc/dist/src/build.js +9 -4
  250. package/node_modules/@eyeauras/cli-factory-ipc/dist/src/build.js.map +1 -1
  251. package/node_modules/@eyeauras/cli-factory-ipc/dist/src/host.d.ts.map +1 -1
  252. package/node_modules/@eyeauras/cli-factory-ipc/dist/src/host.js +5 -4
  253. package/node_modules/@eyeauras/cli-factory-ipc/dist/src/host.js.map +1 -1
  254. package/node_modules/@eyeauras/cli-factory-ipc/dist/src/package-build.d.ts +11 -1
  255. package/node_modules/@eyeauras/cli-factory-ipc/dist/src/package-build.d.ts.map +1 -1
  256. package/node_modules/@eyeauras/cli-factory-ipc/dist/src/package-build.js +85 -57
  257. package/node_modules/@eyeauras/cli-factory-ipc/dist/src/package-build.js.map +1 -1
  258. package/node_modules/@eyeauras/cli-factory-ipc/package.json +2 -2
  259. package/package.json +4 -5
  260. package/references/native/InsightAnalyzerOptions.java +10 -0
  261. package/references/native/InsightAnchorScan.java +1 -11
  262. package/references/native/InsightCodeReferences.java +2 -3
  263. package/references/native/InsightCopyType.java +24 -0
  264. package/references/native/InsightFunctionBoundaries.java +0 -1
  265. package/references/native/InsightFunctionDatabases.java +20 -16
  266. package/references/native/InsightHelperCall.java +17 -0
  267. package/references/native/InsightHubServer.java +214 -0
  268. package/references/native/InsightNativeHost.java +112 -0
  269. package/references/native/InsightPlugins.java +0 -1
  270. package/references/native/InsightPythonWheels.java +3 -2
  271. package/references/native/InsightResearchQueries.java +3 -4
  272. package/references/native/InsightResearchView.java +4 -10
  273. package/references/native/InsightSdkFiles.java +7 -15
  274. package/references/native/InsightSdkScript.java +1 -4
  275. package/references/native/InsightSdkTools.java +36 -97
  276. package/references/native/InsightSdkTypes.java +13 -43
  277. package/references/native/InsightStringAnchors.java +1 -3
  278. package/references/native/InsightTraceState.java +13 -96
  279. package/references/native/InsightTraceTools.java +3 -5
  280. package/references/native/InsightVersionTracking.java +0 -6
  281. package/references/native/{HeadlessProgramMergeManager.java → InsightWcMerge.java} +17 -24
  282. package/references/native/InsightWcOps.java +449 -0
  283. package/references/native/InsightWcWorker.java +142 -0
  284. package/references/native/NATIVE-MERGE-NOTICE.txt +4 -8
  285. package/runtime/GhidraMCP-7.0.0.jar +0 -0
  286. package/runtime/managed/insight-heap/README.md +3 -3
  287. package/runtime/managed/insight-managed/README.md +3 -3
  288. package/runtime/native/binary/README.md +5 -4
  289. package/runtime/native/windows/DirectoryAlias.cs +24 -0
  290. package/runtime/native/windows/Insight.Windows.csproj +27 -0
  291. package/runtime/native/windows/Native.cs +36 -0
  292. package/runtime/native/windows/OwnedJob.cs +86 -0
  293. package/runtime/native/windows/Program.cs +50 -0
  294. package/runtime/native/windows/RegistryRedirect.cs +42 -0
  295. package/runtime/native/windows/insight-windows-x64.exe +0 -0
  296. package/runtime/native/windows/packages.lock.json +35 -0
  297. package/runtime/native/windows/provenance.json +17 -0
  298. package/runtime/research-view.provenance.json +6 -7
  299. package/runtime/toolbox.json +33 -114
  300. package/skill-bundle/insight-artifacts/SKILL.md +5 -19
  301. package/skill-bundle/insight-binary/SKILL.md +5 -35
  302. package/skill-bundle/insight-capture/SKILL.md +5 -45
  303. package/skill-bundle/insight-cli/SKILL.md +6 -44
  304. package/skill-bundle/insight-die/SKILL.md +5 -38
  305. package/skill-bundle/insight-dnspy/SKILL.md +5 -54
  306. package/skill-bundle/insight-dotnet-dump/SKILL.md +5 -35
  307. package/skill-bundle/insight-dotnet-stack/SKILL.md +5 -28
  308. package/skill-bundle/insight-dotnet-trace/SKILL.md +5 -34
  309. package/skill-bundle/insight-frida/SKILL.md +5 -56
  310. package/skill-bundle/insight-ghidra/SKILL.md +14 -113
  311. package/skill-bundle/insight-ilspy/SKILL.md +5 -34
  312. package/skill-bundle/insight-interop/SKILL.md +5 -43
  313. package/skill-bundle/insight-lldb/SKILL.md +5 -43
  314. package/skill-bundle/insight-llvm/SKILL.md +5 -45
  315. package/skill-bundle/insight-managed-heap/SKILL.md +5 -32
  316. package/skill-bundle/insight-managed-metadata/SKILL.md +5 -41
  317. package/skill-bundle/insight-mitmproxy/SKILL.md +5 -51
  318. package/skill-bundle/insight-overview/SKILL.md +5 -68
  319. package/skill-bundle/insight-procmon/SKILL.md +5 -38
  320. package/skill-bundle/insight-re/SKILL.md +10 -127
  321. package/skill-bundle/insight-sevenzip/SKILL.md +5 -31
  322. package/skill-bundle/insight-strace/SKILL.md +5 -35
  323. package/skill-bundle/insight-tshark/SKILL.md +5 -38
  324. package/skill-bundle/insight-windbg/SKILL.md +5 -35
  325. package/skill-bundle/manifest.json +1 -1
  326. package/skills/insight-artifacts/SKILL.md +5 -19
  327. package/skills/insight-binary/SKILL.md +5 -35
  328. package/skills/insight-capture/SKILL.md +5 -45
  329. package/skills/insight-die/SKILL.md +5 -38
  330. package/skills/insight-dnspy/SKILL.md +5 -54
  331. package/skills/insight-dotnet-dump/SKILL.md +5 -35
  332. package/skills/insight-dotnet-stack/SKILL.md +5 -28
  333. package/skills/insight-dotnet-trace/SKILL.md +5 -34
  334. package/skills/insight-frida/SKILL.md +5 -56
  335. package/skills/insight-ghidra/SKILL.md +14 -113
  336. package/skills/insight-ilspy/SKILL.md +5 -34
  337. package/skills/insight-interop/SKILL.md +5 -43
  338. package/skills/insight-lldb/SKILL.md +5 -43
  339. package/skills/insight-llvm/SKILL.md +5 -45
  340. package/skills/insight-managed-heap/SKILL.md +5 -32
  341. package/skills/insight-managed-metadata/SKILL.md +5 -41
  342. package/skills/insight-mitmproxy/SKILL.md +5 -51
  343. package/skills/insight-overview/SKILL.md +5 -68
  344. package/skills/insight-procmon/SKILL.md +5 -38
  345. package/skills/insight-re/SKILL.md +10 -127
  346. package/skills/insight-sevenzip/SKILL.md +5 -31
  347. package/skills/insight-strace/SKILL.md +5 -35
  348. package/skills/insight-tshark/SKILL.md +5 -38
  349. package/skills/insight-windbg/SKILL.md +5 -35
  350. package/dist/src/administration-results.d.ts +0 -1
  351. package/dist/src/administration-results.js +0 -84
  352. package/dist/src/administration.d.ts +0 -14
  353. package/dist/src/administration.js +0 -134
  354. package/dist/src/archive-contract.d.ts +0 -6
  355. package/dist/src/archive-contract.js +0 -108
  356. package/dist/src/archive.d.ts +0 -12
  357. package/dist/src/archive.js +0 -116
  358. package/dist/src/comment-effects.d.ts +0 -3
  359. package/dist/src/comment-effects.js +0 -55
  360. package/dist/src/context-credential.d.ts +0 -18
  361. package/dist/src/context-credential.js +0 -44
  362. package/dist/src/contexts.d.ts +0 -387
  363. package/dist/src/contexts.js +0 -2805
  364. package/dist/src/coordinator.d.ts +0 -41
  365. package/dist/src/coordinator.js +0 -160
  366. package/dist/src/cross-peer.d.ts +0 -20
  367. package/dist/src/cross-peer.js +0 -53
  368. package/dist/src/data-effects.d.ts +0 -3
  369. package/dist/src/data-effects.js +0 -103
  370. package/dist/src/debugger-caller.d.ts +0 -17
  371. package/dist/src/debugger-caller.js +0 -129
  372. package/dist/src/debugger-launch.d.ts +0 -2
  373. package/dist/src/debugger-launch.js +0 -17
  374. package/dist/src/debugger-supervisor.js +0 -179
  375. package/dist/src/directory-identity.d.ts +0 -6
  376. package/dist/src/directory-identity.js +0 -45
  377. package/dist/src/documentation-effects.d.ts +0 -5
  378. package/dist/src/documentation-effects.js +0 -56
  379. package/dist/src/function-effects.d.ts +0 -4
  380. package/dist/src/function-effects.js +0 -112
  381. package/dist/src/ghidra-processes.d.ts +0 -6
  382. package/dist/src/ghidra-processes.js +0 -138
  383. package/dist/src/ghidra.d.ts +0 -50
  384. package/dist/src/ghidra.js +0 -468
  385. package/dist/src/initial-model.d.ts +0 -7
  386. package/dist/src/initial-model.js +0 -115
  387. package/dist/src/initial-progress.d.ts +0 -4
  388. package/dist/src/initial-progress.js +0 -74
  389. package/dist/src/inline-script.d.ts +0 -15
  390. package/dist/src/inline-script.js +0 -61
  391. package/dist/src/legacy-migration.d.ts +0 -37
  392. package/dist/src/legacy-migration.js +0 -238
  393. package/dist/src/lifecycle.d.ts +0 -77
  394. package/dist/src/lifecycle.js +0 -315
  395. package/dist/src/merge.d.ts +0 -29
  396. package/dist/src/merge.js +0 -66
  397. package/dist/src/mutation-effects.d.ts +0 -4
  398. package/dist/src/mutation-effects.js +0 -321
  399. package/dist/src/native-queries.d.ts +0 -2
  400. package/dist/src/native-queries.js +0 -24
  401. package/dist/src/native-service.d.ts +0 -40
  402. package/dist/src/native-service.js +0 -406
  403. package/dist/src/projects.d.ts +0 -31
  404. package/dist/src/projects.js +0 -302
  405. package/dist/src/prototype-cli.d.ts +0 -8
  406. package/dist/src/prototype-cli.js +0 -155
  407. package/dist/src/query-results.d.ts +0 -2
  408. package/dist/src/query-results.js +0 -224
  409. package/dist/src/research-view.d.ts +0 -6
  410. package/dist/src/research-view.js +0 -9
  411. package/dist/src/sdk-files.d.ts +0 -29
  412. package/dist/src/sdk-files.js +0 -249
  413. package/dist/src/server.d.ts +0 -102
  414. package/dist/src/server.js +0 -663
  415. package/dist/src/storage-gc.d.ts +0 -23
  416. package/dist/src/storage-gc.js +0 -600
  417. package/dist/src/store.d.ts +0 -33
  418. package/dist/src/store.js +0 -178
  419. package/dist/src/sync-policy.d.ts +0 -22
  420. package/dist/src/sync-policy.js +0 -129
  421. package/dist/src/timed-backend.d.ts +0 -3
  422. package/dist/src/timed-backend.js +0 -24
  423. package/dist/src/timing-report.d.ts +0 -32
  424. package/dist/src/timing-report.js +0 -74
  425. package/dist/src/tool-runtime/native-process-proof.d.ts +0 -2
  426. package/dist/src/tool-runtime/native-process-proof.js +0 -26
  427. package/dist/src/transport.d.ts +0 -60
  428. package/dist/src/transport.js +0 -223
  429. package/dist/src/unresolved-guidance.d.ts +0 -46
  430. package/dist/src/unresolved-guidance.js +0 -55
  431. package/dist/src/work/backup.d.ts +0 -66
  432. package/dist/src/work/backup.js +0 -446
  433. package/dist/src/work/store.js +0 -1107
  434. package/dist/src/worker-lease.d.ts +0 -17
  435. package/dist/src/worker-lease.js +0 -50
  436. package/node_modules/@eyeauras/cli-factory/dist/src/profile-file.d.ts +0 -37
  437. package/node_modules/@eyeauras/cli-factory/dist/src/profile-file.d.ts.map +0 -1
  438. package/node_modules/@eyeauras/cli-factory/dist/src/profile-file.js.map +0 -1
  439. package/references/InsightRepositoryProbe.java +0 -55
  440. package/references/administration.md +0 -34
  441. package/references/agent-execution.md +0 -36
  442. package/references/agent-setup.md +0 -60
  443. package/references/archive.md +0 -32
  444. package/references/artifacts.md +0 -52
  445. package/references/debugger.md +0 -64
  446. package/references/extensions-and-sync.md +0 -125
  447. package/references/ilspy.md +0 -33
  448. package/references/managed-runtime.md +0 -162
  449. package/references/native/InsightArchivePayloads.java +0 -36
  450. package/references/native/InsightBlockTransfer.java +0 -57
  451. package/references/native/InsightGuiMain.java +0 -33
  452. package/references/native/InsightHeadlessMain.java +0 -18
  453. package/references/native/InsightImportProgress.java +0 -60
  454. package/references/native/InsightInitialImport.java +0 -48
  455. package/references/native/InsightInitialJournal.java +0 -57
  456. package/references/native/InsightInitialPublication.java +0 -142
  457. package/references/native/InsightInitialRecovery.java +0 -131
  458. package/references/native/InsightInlineExecutor.java +0 -143
  459. package/references/native/InsightInlineScript.java +0 -14
  460. package/references/native/InsightNativeCheckout.java +0 -487
  461. package/references/native/InsightNativeFingerprint.java +0 -80
  462. package/references/native/InsightNativeMigration.java +0 -155
  463. package/references/native/InsightNativeRead.java +0 -80
  464. package/references/native/InsightNativeReceipt.java +0 -31
  465. package/references/native/InsightNativeService.java +0 -43
  466. package/references/native/InsightNativeView.java +0 -40
  467. package/references/native/InsightOfflineAuthenticator.java +0 -20
  468. package/references/native/InsightOwnedScripts.java +0 -170
  469. package/references/native/InsightProjectFiles.java +0 -92
  470. package/references/native/InsightPublicationRecovery.java +0 -63
  471. package/references/native/InsightServerAdministration.java +0 -82
  472. package/references/native/InsightServerInit.java +0 -62
  473. package/references/native/InsightServerMain.java +0 -43
  474. package/references/native/InsightServerProbe.java +0 -29
  475. package/references/native/InsightSnapshotFields.java +0 -74
  476. package/references/native/InsightSnapshotInspect.java +0 -191
  477. package/references/native/InsightSnapshotPublisher.java +0 -123
  478. package/references/native/InsightStopDebugger.java +0 -20
  479. package/references/native/InsightTraceInspect.java +0 -24
  480. package/references/native/InsightWorkerLease.java +0 -132
  481. package/references/native-workflows.md +0 -124
  482. package/references/persistent-client.mjs +0 -147
  483. package/references/persistent.md +0 -90
  484. package/references/query-semantics.md +0 -109
  485. package/references/recovery.md +0 -235
  486. package/references/research.md +0 -296
  487. package/references/setup.md +0 -135
  488. package/references/sparse-navigation.md +0 -173
  489. package/references/storage.md +0 -139
  490. package/references/work-tracking.md +0 -261
  491. package/runtime/native/file-version.ps1 +0 -7
  492. package/runtime/native/mitmproxy/bridge.py +0 -180
  493. package/runtime/native/windows-job/DirectoryAlias.cs +0 -24
  494. package/runtime/native/windows-job/Insight.WindowsJob.csproj +0 -1
  495. package/runtime/native/windows-job/Insight.WindowsJob.dll +0 -0
  496. package/runtime/native/windows-job/OwnedJob.cs +0 -79
  497. package/runtime/native/windows-job/RegistryRedirect.cs +0 -45
  498. package/runtime/native/windows-job/packages.lock.json +0 -21
  499. package/runtime/native/windows-job/provenance.json +0 -16
  500. package/runtime/native/windows-job/windows-job.ps1 +0 -8
  501. package/skill-bundle/insight-artifacts/references/agent-execution.md +0 -36
  502. package/skill-bundle/insight-artifacts/references/artifacts.md +0 -52
  503. package/skill-bundle/insight-artifacts/references/recovery.md +0 -235
  504. package/skill-bundle/insight-artifacts/references/storage.md +0 -139
  505. package/skill-bundle/insight-binary/references/agent-execution.md +0 -36
  506. package/skill-bundle/insight-capture/references/agent-execution.md +0 -36
  507. package/skill-bundle/insight-cli/references/agent-execution.md +0 -36
  508. package/skill-bundle/insight-cli/references/agent-setup.md +0 -60
  509. package/skill-bundle/insight-cli/references/archive.md +0 -32
  510. package/skill-bundle/insight-cli/references/managed-runtime.md +0 -162
  511. package/skill-bundle/insight-cli/references/persistent-client.mjs +0 -147
  512. package/skill-bundle/insight-cli/references/persistent.md +0 -90
  513. package/skill-bundle/insight-cli/references/recovery.md +0 -235
  514. package/skill-bundle/insight-cli/references/setup.md +0 -135
  515. package/skill-bundle/insight-cli/references/storage.md +0 -139
  516. package/skill-bundle/insight-die/references/agent-execution.md +0 -36
  517. package/skill-bundle/insight-dnspy/references/agent-execution.md +0 -36
  518. package/skill-bundle/insight-dotnet-dump/references/agent-execution.md +0 -36
  519. package/skill-bundle/insight-dotnet-stack/references/agent-execution.md +0 -36
  520. package/skill-bundle/insight-dotnet-trace/references/agent-execution.md +0 -36
  521. package/skill-bundle/insight-frida/references/agent-execution.md +0 -36
  522. package/skill-bundle/insight-ghidra/references/administration.md +0 -34
  523. package/skill-bundle/insight-ghidra/references/agent-execution.md +0 -36
  524. package/skill-bundle/insight-ghidra/references/archive.md +0 -32
  525. package/skill-bundle/insight-ghidra/references/artifacts.md +0 -52
  526. package/skill-bundle/insight-ghidra/references/debugger.md +0 -64
  527. package/skill-bundle/insight-ghidra/references/extensions-and-sync.md +0 -125
  528. package/skill-bundle/insight-ghidra/references/managed-runtime.md +0 -162
  529. package/skill-bundle/insight-ghidra/references/native-workflows.md +0 -124
  530. package/skill-bundle/insight-ghidra/references/persistent-client.mjs +0 -147
  531. package/skill-bundle/insight-ghidra/references/persistent.md +0 -90
  532. package/skill-bundle/insight-ghidra/references/query-semantics.md +0 -109
  533. package/skill-bundle/insight-ghidra/references/recovery.md +0 -235
  534. package/skill-bundle/insight-ghidra/references/research.md +0 -296
  535. package/skill-bundle/insight-ghidra/references/setup.md +0 -135
  536. package/skill-bundle/insight-ghidra/references/sparse-navigation.md +0 -173
  537. package/skill-bundle/insight-ghidra/references/storage.md +0 -139
  538. package/skill-bundle/insight-ilspy/references/agent-execution.md +0 -36
  539. package/skill-bundle/insight-ilspy/references/ilspy.md +0 -33
  540. package/skill-bundle/insight-interop/references/agent-execution.md +0 -36
  541. package/skill-bundle/insight-lldb/references/agent-execution.md +0 -36
  542. package/skill-bundle/insight-llvm/references/agent-execution.md +0 -36
  543. package/skill-bundle/insight-managed-heap/references/agent-execution.md +0 -36
  544. package/skill-bundle/insight-managed-metadata/references/agent-execution.md +0 -36
  545. package/skill-bundle/insight-mitmproxy/references/agent-execution.md +0 -36
  546. package/skill-bundle/insight-overview/references/agent-execution.md +0 -36
  547. package/skill-bundle/insight-procmon/references/agent-execution.md +0 -36
  548. package/skill-bundle/insight-re/references/agent-execution.md +0 -36
  549. package/skill-bundle/insight-re/references/artifacts.md +0 -52
  550. package/skill-bundle/insight-re/references/persistent-client.mjs +0 -147
  551. package/skill-bundle/insight-re/references/persistent.md +0 -90
  552. package/skill-bundle/insight-re/references/recovery.md +0 -235
  553. package/skill-bundle/insight-re/references/storage.md +0 -139
  554. package/skill-bundle/insight-re/references/work-tracking.md +0 -261
  555. package/skill-bundle/insight-sevenzip/references/agent-execution.md +0 -36
  556. package/skill-bundle/insight-strace/references/agent-execution.md +0 -36
  557. package/skill-bundle/insight-tshark/references/agent-execution.md +0 -36
  558. package/skill-bundle/insight-windbg/references/agent-execution.md +0 -36
  559. package/skills/insight-artifacts/references/agent-execution.md +0 -36
  560. package/skills/insight-artifacts/references/artifacts.md +0 -52
  561. package/skills/insight-artifacts/references/recovery.md +0 -235
  562. package/skills/insight-artifacts/references/storage.md +0 -139
  563. package/skills/insight-binary/references/agent-execution.md +0 -36
  564. package/skills/insight-capture/references/agent-execution.md +0 -36
  565. package/skills/insight-die/references/agent-execution.md +0 -36
  566. package/skills/insight-dnspy/references/agent-execution.md +0 -36
  567. package/skills/insight-dotnet-dump/references/agent-execution.md +0 -36
  568. package/skills/insight-dotnet-stack/references/agent-execution.md +0 -36
  569. package/skills/insight-dotnet-trace/references/agent-execution.md +0 -36
  570. package/skills/insight-frida/references/agent-execution.md +0 -36
  571. package/skills/insight-ghidra/references/administration.md +0 -34
  572. package/skills/insight-ghidra/references/agent-execution.md +0 -36
  573. package/skills/insight-ghidra/references/archive.md +0 -32
  574. package/skills/insight-ghidra/references/artifacts.md +0 -52
  575. package/skills/insight-ghidra/references/debugger.md +0 -64
  576. package/skills/insight-ghidra/references/extensions-and-sync.md +0 -125
  577. package/skills/insight-ghidra/references/managed-runtime.md +0 -162
  578. package/skills/insight-ghidra/references/native-workflows.md +0 -124
  579. package/skills/insight-ghidra/references/persistent-client.mjs +0 -147
  580. package/skills/insight-ghidra/references/persistent.md +0 -90
  581. package/skills/insight-ghidra/references/query-semantics.md +0 -109
  582. package/skills/insight-ghidra/references/recovery.md +0 -235
  583. package/skills/insight-ghidra/references/research.md +0 -296
  584. package/skills/insight-ghidra/references/setup.md +0 -135
  585. package/skills/insight-ghidra/references/sparse-navigation.md +0 -173
  586. package/skills/insight-ghidra/references/storage.md +0 -139
  587. package/skills/insight-ilspy/references/agent-execution.md +0 -36
  588. package/skills/insight-ilspy/references/ilspy.md +0 -33
  589. package/skills/insight-interop/references/agent-execution.md +0 -36
  590. package/skills/insight-lldb/references/agent-execution.md +0 -36
  591. package/skills/insight-llvm/references/agent-execution.md +0 -36
  592. package/skills/insight-managed-heap/references/agent-execution.md +0 -36
  593. package/skills/insight-managed-metadata/references/agent-execution.md +0 -36
  594. package/skills/insight-mitmproxy/references/agent-execution.md +0 -36
  595. package/skills/insight-overview/references/agent-execution.md +0 -36
  596. package/skills/insight-procmon/references/agent-execution.md +0 -36
  597. package/skills/insight-re/references/agent-execution.md +0 -36
  598. package/skills/insight-re/references/artifacts.md +0 -52
  599. package/skills/insight-re/references/persistent-client.mjs +0 -147
  600. package/skills/insight-re/references/persistent.md +0 -90
  601. package/skills/insight-re/references/recovery.md +0 -235
  602. package/skills/insight-re/references/storage.md +0 -139
  603. package/skills/insight-re/references/work-tracking.md +0 -261
  604. package/skills/insight-sevenzip/references/agent-execution.md +0 -36
  605. package/skills/insight-strace/references/agent-execution.md +0 -36
  606. package/skills/insight-tshark/references/agent-execution.md +0 -36
  607. package/skills/insight-windbg/references/agent-execution.md +0 -36
  608. /package/dist/src/{debugger-supervisor.d.ts → native/contract.js} +0 -0
  609. /package/runtime/native/{windows-job → windows}/NuGet.Config +0 -0
@@ -1,2805 +0,0 @@
1
- import { migrateLegacy, migrationProcessBlockers } from './legacy-migration.js';
2
- import { collectStorage } from './storage-gc.js';
3
- import { peerStage, peerStages } from './cross-peer.js';
4
- import { ownedDirectory, projectPathWithin, sameDirectory } from './directory-identity.js';
5
- import { releaseStoppedContextCredential, launchContextCredential } from './context-credential.js';
6
- import { recordLifecycle } from './context-diagnostics.js';
7
- import { ghidraBudget } from './budgets.js';
8
- import { launchProcess, terminateProcess, processStatus, recordedProcessGone, validEnd } from './tool-runtime/supervisor.js';
9
- import { runTool } from './tool-runtime/run.js';
10
- import { verifyGhidraProcess } from './ghidra-processes.js';
11
- import { CliError } from '@eyeauras/cli-factory';
12
- import { runtimeProcesses } from './runtime-manager.js';
13
- import { randomUUID, randomBytes, createHash } from 'node:crypto';
14
- import { mkdir, mkdtemp, open, readFile, readdir, lstat, rename, link, realpath, copyFile, chmod, writeFile, unlink, rm, stat } from 'node:fs/promises';
15
- import { constants } from 'node:fs';
16
- import { join, delimiter, resolve, dirname, basename } from 'node:path';
17
- import { createServer } from 'node:net';
18
- import { setTimeout as delay } from 'node:timers/promises';
19
- import { nativeHelpers, helperSourcesKey, nativeInputs, nativeJvmDirectories, nativeExtensionArguments } from './native-inputs.js';
20
- import { GhidraServer } from './server.js';
21
- import { object, fail, text, version, stable, digest } from './model.js';
22
- import { failUnresolved } from './unresolved-guidance.js';
23
- import { oversizedReplies, openWorkerProgram, unsavedChanges, HttpBridge } from './transport.js';
24
- import { scriptInventory, scriptPath } from './scripts.js';
25
- import { logicalPrograms } from './cross-results.js';
26
- import { uiResult } from './ui-results.js';
27
- import { fileURLToPath } from 'node:url';
28
- import { readCallerGoal, awaitCaller } from './debugger-caller.js';
29
- import { debuggerProgramMetadata, debuggerMetadataFingerprint } from './debugger-results.js';
30
- import { nativeQueries } from './query-policy.js';
31
- import { nativeQuery } from './native-queries.js';
32
- import { runInline } from './inline-script.js';
33
- import { researchView } from './research-view.js';
34
- import { sdkWrites } from './sdk-contracts.js';
35
- import { initialRoot, initialIntent, initializeModel, validateInitialIntent } from './initial-model.js';
36
- import { initialProgress } from './initial-progress.js';
37
- import { managedGhidraDebugger, prepareGhidraDebugger } from './ghidra-debugger-runtime.js';
38
- import { timed } from './internal-timing.js';
39
- import { holdWorkerLease, dropWorkerLease, inWorkerLeaseScope, workerLeaseHeld, workerLeaseHolder, releaseWorkerLease } from './worker-lease.js';
40
- const alive = (pid) => {
41
- try {
42
- process.kill(pid, 0);
43
- return true;
44
- }
45
- catch (error) {
46
- if (error.code === 'ESRCH')
47
- return false;
48
- throw error;
49
- }
50
- };
51
- const programPath = (target) => '/' + target + '.bin';
52
- async function durable(path, value) {
53
- const temporary = path + '.new-' + randomUUID(), handle = await open(temporary, 'wx', 0o600);
54
- try {
55
- await handle.writeFile(stable(value));
56
- await handle.sync();
57
- }
58
- finally {
59
- await handle.close();
60
- }
61
- await rename(temporary, path);
62
- }
63
- async function exists(path) {
64
- try {
65
- await lstat(path);
66
- return true;
67
- }
68
- catch (error) {
69
- if (error.code === 'ENOENT')
70
- return false;
71
- throw error;
72
- }
73
- }
74
- async function port() {
75
- const listener = createServer();
76
- await new Promise((ok, bad) => { listener.once('error', bad); listener.listen(0, '127.0.0.1', ok); });
77
- const address = listener.address();
78
- if (!address || typeof address === 'string')
79
- fail('launch', 'Owned context port allocation failed.');
80
- await new Promise(ok => listener.close(() => ok()));
81
- return address.port;
82
- }
83
- /** Isolated native contexts. This layer has no agent-facing instance/worker selector. */
84
- /** Device and file identity of a real directory (not a link), or undefined when it cannot be proved. */
85
- async function directoryIdentity(path) {
86
- try {
87
- const value = await lstat(path, { bigint: true });
88
- return value.isDirectory() && !value.isSymbolicLink() && value.ino !== 0n ? value.dev + ':' + value.ino : undefined;
89
- }
90
- catch (error) {
91
- if (error.code === 'ENOENT')
92
- return undefined;
93
- throw error;
94
- }
95
- }
96
- /** Failures of a private save whose effect in the worker is not proved either way. */
97
- const unprovedSaves = new WeakSet();
98
- /** Failures to prove the end of a worker that was already asked to end. */
99
- const unprovedStops = new WeakSet();
100
- /** Identity of one immutable repository version, as the native reader names it (InsightNativeFingerprint.version). */
101
- const versionIdentity = (fileId, revision) => createHash('sha256').update('insight-saved-state-v1|server|' + fileId + '|' + revision).digest('hex');
102
- export class GhidraContexts {
103
- workspace;
104
- inputs;
105
- c;
106
- running;
107
- modelTasks;
108
- ownedServer;
109
- capacity;
110
- nativeEngine = 'native-checkout-v1';
111
- constructor(workspace, inputs, c, running = new Map(), modelTasks = new Map(), ownedServer = new GhidraServer(workspace.directory, inputs, c), capacity = { slots: new Set() }) {
112
- this.workspace = workspace;
113
- this.inputs = inputs;
114
- this.c = c;
115
- this.running = running;
116
- this.modelTasks = modelTasks;
117
- this.ownedServer = ownedServer;
118
- this.capacity = capacity;
119
- }
120
- fork(c) { return new GhidraContexts(this.workspace, this.inputs, c, this.running, this.modelTasks, this.ownedServer.fork(c), this.capacity); }
121
- directory() { return join(this.workspace.directory, 'ghidra-native'); }
122
- server() { return this.ownedServer; }
123
- async migrate(target, dryRun) {
124
- const server = this.server(), binding = await server.ensure();
125
- const stopped = await server.nativeMigration(binding, { operation: 'quiescence', nativeRoot: this.directory() });
126
- if (stopped.state !== 'verified')
127
- fail('busy', 'Retained native worker or initial-model lock is unproved; migration is refused.');
128
- return migrateLegacy(this.workspace, {
129
- binding: async () => ({ origin: binding.origin, repository: binding.repository, runtimeFingerprint: this.inputs.fingerprint }),
130
- probe: (t, revision) => server.nativeRead(binding, { operation: 'migration-probe', path: programPath(t.id), sourceSha: t.binarySha256, ...(revision ? { version: revision } : {}) }),
131
- write: q => server.nativeMigration(binding, q),
132
- snapshots: async (paths) => { const value = await server.nativeMigration(binding, { operation: 'snapshots', snapshots: paths }); return Array.isArray(value.items) ? value.items.map(object) : []; },
133
- verify: async (t, owner, candidate) => {
134
- const result = await server.nativeRead(binding, { operation: 'verify', path: programPath(t.id), sourceSha: t.binarySha256, fileId: owner.fileId, version: Number(owner.version) + 1, marker: owner.marker, fingerprint: candidate.fingerprint, bytes: true });
135
- if (result.state !== 'verified' || result.version !== Number(owner.version) + 1)
136
- fail('unknown', 'Migration independent exact-version readback is unproved; check-in will not be retried.');
137
- const exact = await server.nativeRead(binding, { operation: 'migration-probe', path: programPath(t.id), sourceSha: t.binarySha256, version: Number(owner.version) + 1, fileId: owner.fileId });
138
- if (exact.programIdentity !== owner.programIdentity)
139
- fail('binding', 'Migrated program bytes or load identity differ.');
140
- const original = await server.nativeRead(binding, { operation: 'migration-probe', path: programPath(t.id), sourceSha: t.binarySha256, version: owner.version, fileId: owner.fileId });
141
- if (original.engine !== '' || original.fingerprint !== owner.fingerprint || original.programIdentity !== owner.programIdentity)
142
- fail('binding', 'Pre-migration repository version changed.');
143
- },
144
- adopt: async (t) => { const view = await this.serverView(t), model = this.workspace.model(t); if (model.state === 'ready')
145
- this.observeNativeShared(t, view);
146
- else
147
- this.workspace.establishModel(t, view.revision, view.snapshot); },
148
- knownCheckouts: async (t, rows) => {
149
- for (const row of rows) {
150
- const id = object(row).id;
151
- let checkout;
152
- for (let offset = 0;; offset += 100) {
153
- const sessions = this.workspace.sessions(100, offset);
154
- for (const s of sessions)
155
- for (let at = 0;; at += 100) {
156
- const contexts = this.workspace.contexts(s.id, 100, at);
157
- for (const c of contexts)
158
- if (c.target === t.id && c.nativeCheckout?.state === 'active' && c.nativeCheckout.checkoutId === id)
159
- checkout = c.nativeCheckout;
160
- if (contexts.length < 100)
161
- break;
162
- }
163
- if (sessions.length < 100)
164
- break;
165
- }
166
- if (!checkout)
167
- return false;
168
- const status = await this.nativeOperation(checkout, 'status');
169
- if (status.state !== 'ready' || status.checkedOut !== true || status.checkoutId !== id || status.fileId !== checkout.fileId)
170
- return false;
171
- }
172
- return true;
173
- },
174
- recoverOpen: async (c) => {
175
- const parent = join(this.directory(), 'context', c.id), pending = join(parent, 'checkout.json');
176
- let intent;
177
- try {
178
- intent = object(JSON.parse(await readFile(pending, 'utf8')));
179
- }
180
- catch (e) {
181
- if (e.code === 'ENOENT')
182
- return;
183
- throw e;
184
- }
185
- const root = await realpath(text(intent.root)), owner = object(intent.owner);
186
- if (!ownedDirectory(root, this.directory(), ['context', c.id, basename(root)]) || owner.context !== c.id || owner.target !== c.target || owner.sourceSha !== this.workspace.target(c.target).binarySha256 || owner.origin !== binding.origin || owner.repository !== binding.repository || owner.path !== programPath(c.target) || stable(JSON.parse(await readFile(join(root, 'native-owner.json'), 'utf8'))) !== stable(owner))
187
- fail('binding', 'Failed open creation intent changed; its project is retained.');
188
- const retained = join(this.workspace.directory, 'legacy-migrations', c.target, 'recovered-opens', c.id);
189
- await mkdir(retained, { recursive: true, mode: 0o700 });
190
- await durable(join(retained, 'recovery.json'), { schema: 1, context: c.id, intent, requests: this.workspace.unresolved(c), reason: 'No acknowledged private work; all server checkouts independently accounted. Failed creation project retained; next open uses a fresh native checkout in the same session/target.' });
191
- await rename(pending, join(retained, 'checkout-' + randomUUID() + '.json'));
192
- },
193
- closed: c => this.neverStartedOrClosed(c), convert: async (c) => { this.workspace.resetMigratedContext(c); }
194
- }, target, dryRun);
195
- }
196
- async administration(operation, parameters) {
197
- if (operation === 'stop') {
198
- if (this.c.profile.values.server)
199
- fail('authorization', 'External server lifecycle is owned by its operator. Use server disconnect.');
200
- const processes = await runtimeProcesses(dirname(this.workspace.directory), this.c.appArguments?.AppDataDirectory);
201
- if (processes.some(p => p.kind !== 'server'))
202
- fail('busy', 'Close active Ghidra contexts before stopping their server.');
203
- }
204
- return this.server().administration(operation, parameters);
205
- }
206
- async sdkFile(operation, parameters) { return this.server().sdkFile(operation, parameters); }
207
- async prepareRoot(kind, target, context) {
208
- const parent = join(this.directory(), kind, context ?? target);
209
- await mkdir(parent, { recursive: true, mode: 0o700 });
210
- // Atomic short suffix: Windows CreateProcess rejects long cwd even when filesystem APIs accept it.
211
- return mkdtemp(join(parent, 'w-'));
212
- }
213
- async launch(root, target, kind, program, mode, context, credentials = {}) {
214
- return timed('worker.launch', kind + '.' + mode, () => this.launchWorker(root, target, kind, program, mode, context, credentials));
215
- }
216
- /** The worker's own retirement receipt: when and why it stopped by itself. */
217
- async idleExit(binding) {
218
- try {
219
- const receipt = object(JSON.parse(await readFile(join(binding.root, 'idle-exit.json'), 'utf8')));
220
- if (receipt.pid === binding.pid && typeof receipt.at === 'string' && Number.isFinite(Date.parse(receipt.at)))
221
- return { at: receipt.at, reason: ['capacity_evicted', 'runtime_changed', 'maintenance'].includes(String(receipt.reason)) ? receipt.reason : 'idle_timeout' };
222
- }
223
- catch { /* Absent or unreadable: the stop reason stays unknown. */ }
224
- }
225
- idleMs() {
226
- const configured = this.c.profile.values.contextIdleMinutes, minutes = configured === undefined ? 15 : Number(configured);
227
- if (!Number.isSafeInteger(minutes) || minutes < 1 || minutes > 1440)
228
- fail('configuration', 'contextIdleMinutes must be an integer from 1 to 1440.');
229
- return minutes * 60000;
230
- }
231
- /** The process behind a receipt PID is gone or is no longer the recorded worker (PID reuse). */
232
- async workerGone(binding) { return !alive(binding.pid) || await this.retiredWorker(binding) || await this.retiredInventoryWorker(binding); }
233
- /** Wait up to `ms` for a worker that is retiring to exit. */
234
- async awaitExit(binding, ms = 30000) {
235
- for (const deadline = Date.now() + ms; Date.now() < deadline; await delay(250))
236
- if (await this.workerGone(binding))
237
- return true;
238
- return this.workerGone(binding);
239
- }
240
- /**
241
- * One idle-lease request. `held`/`idle`: the worker accepts work; `retiring`: it is stopping by itself and
242
- * refuses new holders; `locked`: a retirement request was refused because a command holds it; `gone`: the
243
- * recorded worker no longer exists (including PID reuse); `absent`: a worker without cool-down (GUI or older).
244
- */
245
- async lease(binding, action, holder, reason) {
246
- if (!binding.leasePort)
247
- return { state: 'absent' };
248
- if (await this.idleExit(binding) && await this.workerGone(binding))
249
- return { state: 'gone' };
250
- const token = await this.c.secrets.require(binding.tokenSecret);
251
- let response;
252
- try {
253
- response = await (this.c.fetch ?? globalThis.fetch)('http://127.0.0.1:' + binding.leasePort + '/insight/lease', { method: 'POST', redirect: 'error',
254
- headers: { Authorization: 'Bearer ' + token, 'Content-Type': 'application/json' }, body: JSON.stringify({ action, ...(holder ? { holder } : {}), ...(reason ? { reason } : {}) }), signal: AbortSignal.timeout(5000) });
255
- }
256
- catch (error) {
257
- // A listener that accepted the request and stayed silent is not a retirement: the caller decides whether the
258
- // worker itself still answers. Nothing is waited for here.
259
- if (error?.name === 'TimeoutError' && !await this.workerGone(binding))
260
- fail('busy', 'Context worker lease did not answer while its process is alive; it is retained.', { lease: 'silent' });
261
- // A closed lease listener is a worker in retirement or gone; it never received this command.
262
- if (await this.awaitExit(binding, 10000))
263
- return { state: 'gone' };
264
- fail('busy', 'Context worker lease is unreachable while its process is alive; it is retained.');
265
- }
266
- const value = object(await response.json().catch(() => ({})));
267
- if (response.status === 409)
268
- return { state: 'retiring' };
269
- if (response.status === 423)
270
- return { state: 'locked', holders: Number(value.holders) };
271
- if (response.status !== 200 || value.pid !== binding.pid || !['held', 'idle', 'retiring'].includes(String(value.state))) {
272
- // Another process now owns the port or PID: the recorded worker is gone only if its identity changed.
273
- if (await this.workerGone(binding))
274
- return { state: 'gone' };
275
- fail('binding', 'Context worker lease belongs to a different process.');
276
- }
277
- return { state: value.state, holders: Number(value.holders), idleForMs: Number(value.idleForMs), ...(Number.isSafeInteger(value.scripts) ? { scripts: Number(value.scripts) } : {}) };
278
- }
279
- /** Hold a worker for the rest of the current command; outside a command nothing is acquired. */
280
- async holdLease(binding) {
281
- if (!binding.leasePort)
282
- return 'absent';
283
- if (!inWorkerLeaseScope() || workerLeaseHeld(binding.root))
284
- return 'held';
285
- const holder = randomUUID(), result = await this.lease(binding, 'acquire', holder);
286
- if (result.state !== 'held')
287
- return result.state === 'gone' ? 'gone' : 'retiring';
288
- holdWorkerLease(binding.root, { holder,
289
- renew: async () => { if (alive(binding.pid))
290
- await this.lease(binding, 'renew', holder); },
291
- release: async () => { if (alive(binding.pid))
292
- await this.lease(binding, 'release', holder); },
293
- });
294
- return 'held';
295
- }
296
- /**
297
- * A worker that stopped by itself becomes an ordinary stop: its stop receipt, lifecycle reason and the
298
- * release of its credential. Returns the reason when the worker ended this way.
299
- */
300
- async settleRetired(binding, requested) {
301
- // A worker asked to stop that exited before writing its own receipt is settled with the requested reason.
302
- const exit = await this.idleExit(binding) ?? (requested ? { at: new Date().toISOString(), reason: requested } : undefined);
303
- if (!exit || !await this.workerGone(binding))
304
- return;
305
- const path = join(binding.root, 'stopped.json');
306
- if (!await exists(path)) {
307
- await durable(path, { pid: binding.pid, tokenSecret: binding.tokenSecret, at: exit.at, reason: exit.reason });
308
- if (binding.context)
309
- await recordLifecycle(this.workspace, binding.context, { at: exit.at, event: 'stop', reason: exit.reason, pid: binding.pid });
310
- }
311
- if (binding.context)
312
- this.capacity.slots.delete(binding.context);
313
- this.running.delete(binding.root);
314
- dropWorkerLease(binding.root);
315
- await releaseStoppedContextCredential(this.directory(), binding, this.c.secrets, alive, () => this.workerGone(binding));
316
- return exit.reason;
317
- }
318
- /** Ask an unheld leased worker to stop now and settle it; false when a command holds it. */
319
- async retireWorker(binding, reason) {
320
- // The worker accepts a retirement before it answers: a request without a usable answer may have been accepted.
321
- const result = await this.lease(binding, 'retire', undefined, reason).catch(error => { if (error && typeof error === 'object')
322
- unprovedStops.add(error); throw error; });
323
- if (result.state === 'locked' || result.state === 'absent')
324
- return false;
325
- if (!await this.awaitExit(binding)) {
326
- try {
327
- fail('busy', 'A context worker asked to stop has not exited yet; it is retained.');
328
- }
329
- catch (error) {
330
- unprovedStops.add(error);
331
- throw error;
332
- }
333
- }
334
- await this.settleRetired(binding, reason);
335
- return true;
336
- }
337
- async launchWorker(root, target, kind, program, mode, context, credentials) {
338
- if ((await nativeInputs(this.c.profile.values, this.workspace.directory, this.c)).fingerprint !== this.inputs.fingerprint)
339
- fail('binding', 'Native runtime inputs changed while this owner runs; stop the CLI owner (ipc-server stop) and repeat the command. Workers of the previous runtime stop when their contexts are next used.');
340
- // A launch follows the proved end of the root's previous worker: its marker, readable or not, names nothing now.
341
- // A worker this owner still runs here, or a marker that cannot be cleared, would make the new worker ambiguous.
342
- const previous = this.running.get(root);
343
- if (previous && alive(previous.binding.pid) && !(previous.child && (previous.child.exitCode !== null || previous.child.signalCode !== null)))
344
- fail('busy', 'This checkout still has a running worker; it is retained.');
345
- await rm(join(root, 'parked.json'), { recursive: true, force: true }).catch(() => { fail('binding', 'The parking marker of the previous worker in this checkout cannot be cleared; remove parked.json from the context directory.'); });
346
- const endpointPort = await port(), tokenSecret = 'context-' + randomUUID(), token = randomBytes(32).toString('hex');
347
- // Headless context workers outlive their Factory owner and cool down after the configured idle time.
348
- const lease = kind === 'context' && mode === 'headless' ? { leasePort: await port(), idleMs: this.idleMs() } : undefined;
349
- const classes = await nativeHelpers(this.workspace.directory, this.inputs, this.c);
350
- if (lease)
351
- Object.assign(lease, { helpers: await readFile(join(classes, 'helper-sources'), 'utf8') });
352
- let debuggerEnvironment = {}, debuggerPython, debuggerRuntime;
353
- if (mode === 'gui') {
354
- if (managedGhidraDebugger())
355
- debuggerRuntime = await prepareGhidraDebugger(this.c);
356
- const python = join(root, 'debug-python-' + randomUUID());
357
- await mkdir(python, { mode: 0o700 });
358
- debuggerPython = python;
359
- const prepared = await runTool(this.c, { tool: 'ghidra', role: 'debugger-wheels', installation: this.inputs.fingerprint, executable: this.inputs.java, arguments: ['-cp', classes, 'InsightPythonWheels', python, ...this.inputs.debuggerWheels], timeoutMs: 30000, maxOutputBytes: 65536 });
360
- if (object(JSON.parse(prepared.stdout)).state !== 'prepared')
361
- fail('configuration', 'Owned debugger Python dependencies could not be prepared.');
362
- debuggerEnvironment = { INSIGHT_DEBUGGER_PYTHON: python, PYTHONPATH: python, PYTHONNOUSERSITE: '1', PYTHONDONTWRITEBYTECODE: '1', PYTHONPYCACHEPREFIX: join(python, 'isolated-cache') };
363
- if (process.platform === 'darwin') {
364
- const bin = join(root, 'debug-bin-' + randomUUID());
365
- await mkdir(bin, { mode: 0o700 });
366
- const quote = (value) => "'" + value.replaceAll("'", "'\\''") + "'", launch = join(root, 'debugger-run', 'current.json');
367
- await writeFile(join(bin, 'lldb'), '#!/bin/sh\n' +
368
- 'directory=' + quote(root) + '\nif [ -f ' + quote(launch) + ' ]; then\n directory=$(/usr/bin/plutil -extract cwd raw -o - ' + quote(launch) + ') || exit 1\nfi\n' +
369
- 'cd "$directory" || exit 1\nexec ' + quote(process.execPath) + ' ' + quote(fileURLToPath(new URL('./debugger-supervisor.js', import.meta.url))) + ' ' + quote(root) + ' "$@"\n', { mode: 0o500 });
370
- debuggerEnvironment.PATH = bin + delimiter + (this.c.environment.PATH ?? process.env.PATH ?? '/usr/bin:/bin');
371
- }
372
- }
373
- const main = mode === 'gui' ? 'InsightGuiMain' : 'InsightHeadlessMain';
374
- const args = mode === 'gui' ? [root, 'view', String(endpointPort)] : ['--bind', '127.0.0.1', '--port', String(endpointPort)];
375
- const log = await open(join(root, 'runtime.log'), 'a', 0o600);
376
- let binding;
377
- let child;
378
- try {
379
- child = await launchContextCredential(this.c.secrets, tokenSecret, token, onSpawn => launchProcess(this.c.appArguments.AppDataDirectory, { tool: 'ghidra', role: mode === 'gui' ? 'gui' : kind, installation: this.inputs.fingerprint, target: target.id, session: context ? this.workspace.contextById(context).session : undefined, metadata: { contextRoot: root } }, this.inputs.java, ['-Xmx768m', '-Djava.awt.headless=' + String(mode !== 'gui'), '-Dghidra.home=' + this.inputs.ghidraHome,
380
- ...nativeJvmDirectories(root), ...nativeExtensionArguments(this.inputs), '-cp', classes + delimiter + this.inputs.classpath, main, ...args], { cwd: root, detached: true, windowsHide: true, stdio: ['ignore', log.fd, log.fd],
381
- env: { PATH: this.c.environment.PATH ?? process.env.PATH, HOME: root, TMPDIR: root, XDG_RUNTIME_DIR: root,
382
- ...(process.platform === 'win32' ? { SystemRoot: process.env.SystemRoot, WINDIR: process.env.WINDIR, ComSpec: process.env.ComSpec, TEMP: root, TMP: root, USERPROFILE: root, LOCALAPPDATA: root, APPDATA: root } : {}),
383
- INSIGHT_TOOL_APPDATA: this.c.appArguments.AppDataDirectory, GHIDRA_MCP_AUTH_TOKEN: token, GHIDRA_MCP_FILE_ROOT: root, GHIDRA_MCP_SHARED_PROJECT_DIR: root,
384
- GHIDRA_MCP_ALLOW_SCRIPTS: '1', ...(lease ? { INSIGHT_WORKER_LEASE_PORT: String(lease.leasePort), INSIGHT_WORKER_IDLE_MS: String(lease.idleMs) } : {}), ...debuggerEnvironment, ...credentials } }, { signal: this.c.signal, onSpawn }), async (spawned) => {
385
- if (!spawned.pid)
386
- fail('launch', 'Owned context did not obtain a PID.');
387
- binding = { toolProcessId: spawned.toolProcessId, pid: spawned.pid, endpoint: `http://127.0.0.1:${endpointPort}`, root, ...(debuggerPython ? { debuggerPython } : {}), ...(debuggerRuntime ? { debuggerRuntime } : {}), target: target.id,
388
- ...(context ? { context, session: this.workspace.contextById(context).session } : {}), kind, mode, program, tokenSecret, runtimeFingerprint: this.inputs.fingerprint, ...(lease ?? {}) };
389
- await durable(join(root, 'process.json'), binding);
390
- }, async (spawned) => {
391
- if (binding)
392
- await this.stopRecord({ binding, child: spawned, http: new HttpBridge(binding.endpoint, this.c.fetch, this.c.signal, token) }, false, true, 'startup_failed');
393
- });
394
- }
395
- finally {
396
- await log.close();
397
- }
398
- child.on('error', () => { });
399
- child.unref();
400
- if (!child.pid)
401
- fail('launch', 'Owned Ghidra context could not be launched.');
402
- const record = { binding, http: await this.bridge(binding, token), child };
403
- this.running.set(root, record);
404
- const deadline = Date.now() + 90000;
405
- try {
406
- let ready = false;
407
- while (!ready && Date.now() < deadline && child.exitCode === null && child.signalCode === null && !this.c.signal.aborted) {
408
- try {
409
- const info = await record.http.instance();
410
- if (info.pid !== binding.pid || info.tcp_port !== endpointPort)
411
- fail('binding', 'Context endpoint belongs to a different native process.');
412
- ready = true;
413
- }
414
- catch {
415
- await delay(100);
416
- }
417
- }
418
- if (!ready)
419
- fail('launch', 'Owned Ghidra context did not become ready; its stage is retained.');
420
- if (context)
421
- await recordLifecycle(this.workspace, context, { at: new Date().toISOString(), event: 'start', reason: 'native_launch', pid: binding.pid });
422
- // A fresh worker is held by the command that launched it; a failure here is reported as is, never retried.
423
- if (context && ['retiring', 'gone'].includes(await this.holdLease(binding)))
424
- fail('launch', 'Owned context worker stopped right after its start; its stage is retained.');
425
- return record;
426
- }
427
- catch (error) {
428
- if (child.exitCode === null && child.signalCode === null)
429
- child.kill('SIGTERM');
430
- for (let i = 0; i < 100 && child.exitCode === null && child.signalCode === null; i++)
431
- await delay(50);
432
- if (child.exitCode !== null || child.signalCode !== null)
433
- await this.stopRecord(record, false, true, 'startup_failed');
434
- this.running.delete(root);
435
- throw error;
436
- }
437
- }
438
- /** A bridge to a context worker. A leased worker also runs this package's helper scripts in-process. */
439
- async bridge(binding, token) {
440
- const http = new HttpBridge(binding.endpoint, this.c.fetch, this.c.signal, token, undefined, ghidraBudget(this.c.profile.values, 'save'));
441
- if (binding.leasePort) {
442
- // The worker serves only callers whose helper sources are the ones its classes were compiled from.
443
- // The worker decides admission first and then compares sources. Unreadable sources name no worker's classes:
444
- // the worker still admits or refuses, and only then leaves the script to the inline provider.
445
- http.owned = { port: binding.leasePort, helpers: await helperSourcesKey().catch(() => '') };
446
- }
447
- return http;
448
- }
449
- async verified(binding, target, verifySource = true) {
450
- const root = await realpath(binding.root);
451
- if (!ownedDirectory(root, this.directory(), [binding.kind, binding.context ?? binding.target, basename(root)]) || binding.target !== target.id || binding.runtimeFingerprint !== this.inputs.fingerprint)
452
- fail('binding', 'Native context receipt does not match its profile, target or runtime.');
453
- if (stable(JSON.parse(await readFile(join(root, 'process.json'), 'utf8'))) !== stable(binding))
454
- fail('binding', 'Native context receipt changed.');
455
- const token = await this.c.secrets.require(binding.tokenSecret);
456
- const http = await this.bridge(binding, token);
457
- const info = await http.instance();
458
- if (info.pid !== binding.pid || info.tcp_port !== Number(new URL(binding.endpoint).port) ||
459
- !projectPathWithin(info.project_path, binding.root))
460
- fail('binding', 'Live context PID, endpoint or project no longer matches its receipt.');
461
- const record = { ...this.running.get(root), binding, http };
462
- this.running.set(root, record);
463
- if (verifySource)
464
- await this.source(record, target);
465
- return record;
466
- }
467
- async source(record, target) {
468
- const result = object(await record.http.call('/get_program_options', { program: record.binding.program, group: 'Program Information' }));
469
- if (!Array.isArray(result.options) || object(result.options.find(value => object(value).name === 'Executable SHA256') ?? {}).value !== target.binarySha256)
470
- fail('binding', 'Opened native program does not match the target input bytes.');
471
- return object(await record.http.call('/get_metadata', { program: record.binding.program }));
472
- }
473
- async stopRecord(record, ready = true, releaseCapacity = true, reason = 'temporary_complete') {
474
- return timed('worker.stop', reason, () => this.stopWorker(record, ready, releaseCapacity, reason));
475
- }
476
- async stopWorker(record, ready, releaseCapacity, reason) {
477
- const { binding, child } = record;
478
- const childFinished = child && child.pid === binding.pid && (child.exitCode !== null || child.signalCode !== null);
479
- if (!childFinished && alive(binding.pid)) {
480
- if (ready)
481
- await this.verified(binding, this.workspace.target(binding.target), false);
482
- else if (!child || child.pid !== binding.pid)
483
- fail('binding', 'Unready process may only be stopped through its original child handle.');
484
- if (ready && binding.mode === 'gui') {
485
- const token = await this.c.secrets.require(binding.tokenSecret), http = new HttpBridge(binding.endpoint, this.c.fetch, new AbortController().signal, token, 60000);
486
- await this.debuggerHelperRecord({ ...record, http }, 'Stop', 'INSIGHT_DEBUGGER_STOPPED');
487
- }
488
- // Once it is asked to end, the worker may save changed programs while it shuts down: a stop that is not
489
- // proved afterwards says nothing about the saved program.
490
- try {
491
- if (binding.toolProcessId)
492
- await terminateProcess(this.c.appArguments.AppDataDirectory, binding.toolProcessId, false, r => verifyGhidraProcess(r, this.c));
493
- else
494
- process.kill(binding.pid, 'SIGTERM');
495
- for (let i = 0; i < 100 && alive(binding.pid); i++)
496
- await delay(50);
497
- if (alive(binding.pid))
498
- fail('busy', 'Owned context did not stop; its stage is retained.');
499
- }
500
- catch (error) {
501
- if (error && typeof error === 'object')
502
- unprovedStops.add(error);
503
- throw error;
504
- }
505
- }
506
- // Only a worker that is gone needs no release: a failed stop keeps the command's hold, which then ends with it.
507
- dropWorkerLease(binding.root);
508
- if (binding.mode === 'gui')
509
- await this.debuggerReleased(binding);
510
- const at = new Date().toISOString();
511
- await durable(join(binding.root, 'stopped.json'), { pid: binding.pid, tokenSecret: binding.tokenSecret, at, reason });
512
- if (binding.context)
513
- await recordLifecycle(this.workspace, binding.context, { at, event: 'stop', reason, pid: binding.pid });
514
- if (releaseCapacity && binding.context)
515
- this.capacity.slots.delete(binding.context);
516
- this.running.delete(binding.root);
517
- await releaseStoppedContextCredential(this.directory(), binding, this.c.secrets, alive, () => this.retiredWorker(binding));
518
- }
519
- async retiredWorker(binding) {
520
- if (!binding.toolProcessId)
521
- return false;
522
- try {
523
- const row = await processStatus(this.c.appArguments.AppDataDirectory, binding.toolProcessId);
524
- return ['exited', 'failed'].includes(row.state) && row.strongIdentity === true &&
525
- typeof row.endedAt === 'string' && Number.isFinite(Date.parse(row.endedAt)) &&
526
- row.id === binding.toolProcessId && row.tool === 'ghidra' && row.pid === binding.pid &&
527
- row.target === binding.target && row.session === binding.session &&
528
- row.role === (binding.mode === 'gui' ? 'gui' : binding.kind) && row.installation === binding.runtimeFingerprint &&
529
- typeof row.metadata?.contextRoot === 'string' && sameDirectory(row.metadata.contextRoot, binding.root);
530
- }
531
- catch {
532
- return false;
533
- }
534
- }
535
- async debuggerReleased(binding) {
536
- const root = await realpath(binding.root);
537
- if (!ownedDirectory(root, this.directory(), [binding.kind, binding.context ?? binding.target, basename(root)]) ||
538
- stable(JSON.parse(await readFile(join(root, 'process.json'), 'utf8'))) !== stable(binding))
539
- fail('binding', 'Debugger lifetime binding moved outside its owned context.');
540
- const directory = join(root, 'debugger-supervisors'), deadline = Date.now() + 15000;
541
- for (;;) {
542
- let names;
543
- try {
544
- names = await readdir(directory);
545
- }
546
- catch (error) {
547
- if (error.code === 'ENOENT')
548
- return;
549
- throw error;
550
- }
551
- let pending = false;
552
- for (const name of names.filter(name => /^[a-f0-9-]{36}\.json$/.test(name))) {
553
- const path = join(directory, name);
554
- if (await realpath(path) !== resolve(path))
555
- fail('binding', 'Debugger lifetime receipt moved.');
556
- const row = object(JSON.parse(await readFile(path, 'utf8')));
557
- if (row.schema !== 1 || row.id + '.json' !== name || row.root !== binding.root || row.context !== binding.context || row.target !== binding.target)
558
- fail('binding', 'Debugger lifetime receipt changed.');
559
- if (row.guiPid !== binding.pid || row.ownerToken !== binding.tokenSecret)
560
- continue;
561
- if (row.state === 'closed' && row.inferiorTerminated === true)
562
- continue;
563
- if (row.state === 'failed')
564
- fail('blocked', 'Owned debugger termination remains unverified; its receipt and trace are retained.');
565
- pending = true;
566
- }
567
- if (!pending)
568
- return;
569
- if (Date.now() >= deadline)
570
- fail('busy', 'Owned debugger cleanup is still pending; its context is retained.');
571
- await delay(100);
572
- }
573
- }
574
- async capture(record) {
575
- const context = record.binding.kind === 'context' ? this.workspace.contextById(record.binding.context) : undefined;
576
- // Never write a detached worker's project: its engine alone can capture that state.
577
- if (context && (!context.nativeCheckout || context.nativeCheckout.root !== record.binding.root))
578
- fail('migration', 'This worker belongs to legacy detached work. Save and close it with the release that started it, then run ghidra migrate.');
579
- // A save that was not acknowledged, for whatever reason, may still have happened in the worker.
580
- try {
581
- const result = object(await record.http.call('/save_program', { program: record.binding.program }));
582
- if (result.success !== true)
583
- fail('save', 'Private program save was not acknowledged.');
584
- }
585
- catch (error) {
586
- if (error && typeof error === 'object')
587
- unprovedSaves.add(error);
588
- throw error;
589
- }
590
- if (context?.nativeCheckout) {
591
- // One pass names the saved state and inspects its debugger metadata. A native receipt names a mutable
592
- // project: this small metadata witness is kept, because an older receipt cannot be inspected after the next save.
593
- const { inspected, ...saved } = object(await this.nativeView(record, { operation: 'capture', parameters: { kind: 'debugger_bookmarks' } }));
594
- return this.nativeReceipt(context.nativeCheckout, { ...saved, debuggerMetadata: debuggerMetadataFingerprint(inspected) });
595
- }
596
- const output = join(record.binding.root, 'exports');
597
- await mkdir(output, { recursive: true, mode: 0o700 });
598
- const name = 'saved-' + randomUUID() + '.gzf';
599
- const exported = object(await record.http.call('/export_program', { program_name: record.binding.program, output_dir: output, output_name: name }));
600
- if (exported.success !== true)
601
- fail('save', 'Saved private snapshot export was not acknowledged.');
602
- return this.captureExport(join(output, name));
603
- }
604
- /** The captured artifact is the only retained copy of an export stage. */
605
- async captureExport(path) {
606
- const artifact = await this.workspace.captureSnapshot(path);
607
- await unlink(path).catch(() => { });
608
- return artifact;
609
- }
610
- async nativeView(record, parameters) {
611
- const response = object(await record.http.script(record.binding.program, 'InsightNativeView', Buffer.from(JSON.stringify(parameters), 'utf8').toString('base64')));
612
- if (response.success !== true || typeof response.console_output !== 'string')
613
- fail('partial', 'Saved native view inspection did not complete.');
614
- const matches = [...response.console_output.matchAll(/^INSIGHT_NATIVE:(.+)$/gm)];
615
- if (matches.length !== 1)
616
- fail('partial', 'Native saved-view result is missing.');
617
- return object(JSON.parse(matches[0][1])).value;
618
- }
619
- async nativeReceipt(checkout, saved) {
620
- if (saved.fileId !== checkout.fileId || saved.version !== checkout.baseVersion || typeof saved.fingerprint !== 'string' || !/^[a-f0-9]{64}$/.test(saved.fingerprint))
621
- fail('binding', 'Saved native view differs from its checkout identity/base.');
622
- const path = join(checkout.root, 'saved-view.json');
623
- await durable(path, { schema: 1, engine: this.nativeEngine, source: 'checkout', checkout, ...saved });
624
- return this.workspace.captureNative(path);
625
- }
626
- /** Exact server versions are immutable for one item: a verified reader view is reusable by this runtime and repository. */
627
- versionCache(targetId, binding, versionNumber, fileId) {
628
- const target = this.workspace.target(targetId);
629
- const identity = { schema: 1, origin: binding.origin, repository: binding.repository, path: programPath(targetId), sourceSha: target.binarySha256, runtimeFingerprint: this.inputs.fingerprint, fileId, version: versionNumber };
630
- return { identity, path: join(this.directory(), 'shared-views', targetId, 'versions', 'v' + versionNumber + '-' + digest(identity).slice(0, 32) + '.json') };
631
- }
632
- async rememberVersion(targetId, binding, value) {
633
- if (value.state !== 'verified' || !Number.isSafeInteger(value.version) || typeof value.fileId !== 'string' || typeof value.fingerprint !== 'string' || !/^[a-f0-9]{64}$/.test(value.fingerprint))
634
- return;
635
- const { identity, path } = this.versionCache(targetId, binding, Number(value.version), value.fileId);
636
- // Only the immutable identity of the version is kept; live checkout lists are never served from the cache.
637
- await mkdir(dirname(path), { recursive: true, mode: 0o700 });
638
- await durable(path, { identity, value: { state: 'verified', version: value.version, fileId: value.fileId, fingerprint: value.fingerprint } });
639
- await this.pruneVersions(dirname(path), identity);
640
- }
641
- /** Keep only views of the current server, repository, input and runtime, and at most the 64 most recent. */
642
- async pruneVersions(directory, current) {
643
- const keys = ['origin', 'repository', 'path', 'sourceSha', 'runtimeFingerprint'], kept = [];
644
- for (const name of await readdir(directory)) {
645
- const path = join(directory, name);
646
- if (!/^v\d+-[a-f0-9]{32}\.json$/.test(name)) {
647
- continue;
648
- }
649
- try {
650
- const identity = object(object(JSON.parse(await readFile(path, 'utf8'))).identity);
651
- if (keys.every(key => identity[key] === current[key])) {
652
- kept.push({ path, at: (await stat(path)).mtimeMs });
653
- continue;
654
- }
655
- }
656
- catch (error) {
657
- if (error.code === 'ENOENT')
658
- continue;
659
- }
660
- await rm(path, { force: true });
661
- }
662
- for (const stale of kept.sort((a, b) => b.at - a.at).slice(64))
663
- await rm(stale.path, { force: true });
664
- }
665
- async cachedVersion(targetId, binding, versionNumber, fileId) {
666
- const { identity, path } = this.versionCache(targetId, binding, versionNumber, fileId);
667
- try {
668
- const entry = object(JSON.parse(await readFile(path, 'utf8'))), value = object(entry.value);
669
- if (stable(entry.identity) === stable(identity) && value.state === 'verified' && value.version === versionNumber && value.fileId === fileId && typeof value.fingerprint === 'string')
670
- return value;
671
- }
672
- catch { /* An absent or unreadable entry is a miss; the version is read again. */ }
673
- }
674
- async serverView(targetId, versionNumber, fileId) {
675
- const server = this.server(), binding = await server.ensure(), target = this.workspace.target(targetId);
676
- let value = versionNumber && fileId ? await this.cachedVersion(targetId, binding, versionNumber, fileId) : undefined;
677
- if (!value) {
678
- value = await server.nativeRead(binding, { operation: 'latest', path: programPath(targetId), sourceSha: target.binarySha256, ...(versionNumber ? { version: versionNumber } : {}), ...(fileId ? { fileId } : {}) });
679
- await this.rememberVersion(targetId, binding, value);
680
- }
681
- if (value.state !== 'verified' || typeof value.fileId !== 'string' || typeof value.fingerprint !== 'string')
682
- fail('binding', 'Native shared model is unverified or requires an explicit legacy migration.');
683
- const revision = version(value.version), root = join(this.directory(), 'shared-views', targetId);
684
- await mkdir(root, { recursive: true, mode: 0o700 });
685
- const path = join(root, 'current.json');
686
- await durable(path, { schema: 1, engine: this.nativeEngine, source: 'server', target: targetId, origin: binding.origin, repository: binding.repository, path: programPath(targetId),
687
- sourceSha: target.binarySha256, runtimeFingerprint: this.inputs.fingerprint, version: revision, fileId: value.fileId, fingerprint: value.fingerprint });
688
- return { revision, snapshot: await this.workspace.captureNative(path), value };
689
- }
690
- observeNativeShared(target, shared) {
691
- const model = this.workspace.model(target);
692
- // A context's exact immutable base can predate another context's observation.
693
- if (model.state === 'ready' && shared.revision >= (model.sharedRevision ?? 1))
694
- this.workspace.observeShared(target, shared.revision, shared.snapshot);
695
- }
696
- async nativeOwner(checkout) {
697
- const root = await realpath(checkout.root), context = this.workspace.contextById(checkout.context);
698
- if (!ownedDirectory(root, this.directory(), ['context', context.id, basename(root)]))
699
- fail('binding', 'Native checkout moved.');
700
- // The creating runtime is provenance. Ghidra itself refuses a database that needs an upgrade.
701
- const owner = object(JSON.parse(await readFile(join(root, 'native-owner.json'), 'utf8'))), binding = await this.server().ensure();
702
- if (context.nativeCheckout?.root !== checkout.root || owner.context !== context.id || owner.target !== context.target || owner.origin !== binding.origin || owner.repository !== binding.repository || owner.path !== programPath(context.target) || owner.sourceSha !== this.workspace.target(context.target).binarySha256 || owner.runtimeFingerprint !== checkout.runtimeFingerprint)
703
- fail('binding', 'Native checkout owner/server binding changed.');
704
- return { root, owner, binding };
705
- }
706
- async nativeOperation(checkout, operation, parameters = {}) {
707
- // The owner and server binding are proved here, before dispatch: an unreachable server sends no Update or check-in.
708
- const { root, owner, binding } = await this.nativeOwner(checkout).catch(error => operation === 'update' || operation === 'checkin' ? this.unsent(operation, error) : Promise.reject(error));
709
- return this.server().nativeCheckout(binding, { root, owner, operation, fileId: checkout.fileId, checkoutId: checkout.checkoutId, ...parameters });
710
- }
711
- async shared(target, binding) {
712
- const root = await this.prepareRoot('shared', target.id);
713
- const server = this.server();
714
- const record = await this.launch(root, target, 'shared', programPath(target.id), 'headless', undefined, await server.credentials(binding, 'reader'));
715
- try {
716
- await record.http.call('/server/connect');
717
- await record.http.call('/open_project', { path: binding.origin + '/' + binding.repository });
718
- const opened = object(await openWorkerProgram(record.http, record.binding.program));
719
- if (opened.read_only !== true || opened.path !== record.binding.program)
720
- fail('authorization', 'Shared baseline must open through verified read-only authority.');
721
- await this.verified(record.binding, target);
722
- return record;
723
- }
724
- catch (error) {
725
- await this.stopRecord(record, false);
726
- throw error;
727
- }
728
- }
729
- async retireLegacyBootstrap(target) {
730
- const parent = join(this.directory(), 'bootstrap', target.id);
731
- let entries;
732
- try {
733
- entries = await readdir(parent, { withFileTypes: true });
734
- }
735
- catch (error) {
736
- if (error.code === 'ENOENT')
737
- return;
738
- throw error;
739
- }
740
- for (const entry of entries) {
741
- if (!entry.isDirectory())
742
- continue;
743
- const root = join(parent, entry.name);
744
- if (await realpath(root) !== resolve(root))
745
- fail('binding', 'Legacy initial-import stage moved outside owned storage.');
746
- const binding = JSON.parse(await readFile(join(root, 'process.json'), 'utf8'));
747
- if (await realpath(binding.root) !== root || binding.target !== target.id || binding.kind !== 'bootstrap' || binding.program !== programPath(target.id))
748
- fail('binding', 'Legacy bootstrap receipt changed.');
749
- let stopped = false;
750
- try {
751
- const receipt = object(JSON.parse(await readFile(join(root, 'stopped.json'), 'utf8')));
752
- stopped = receipt.pid === binding.pid && receipt.tokenSecret === binding.tokenSecret;
753
- }
754
- catch (error) {
755
- if (error.code !== 'ENOENT')
756
- throw error;
757
- }
758
- if (stopped)
759
- continue;
760
- if (alive(binding.pid))
761
- await this.stopRecord(await this.verified(binding, target, false));
762
- }
763
- }
764
- async initialModel(target) {
765
- const model = this.workspace.model(target.id);
766
- if (model.state === 'ready')
767
- return;
768
- const server = this.server(), binding = await server.ensure();
769
- const held = this.workspace.activePublication(target.id);
770
- if (held)
771
- failUnresolved(this.workspace, { session: held.session, target: target.id }, 'Shared publication requires reconciliation before initial-model recovery.');
772
- const intent = await initialIntent(this.workspace, target.id);
773
- if (intent) {
774
- await validateInitialIntent(this.workspace, target, binding, this.inputs.fingerprint, undefined, true);
775
- if (intent.runtimeFingerprint !== this.inputs.fingerprint) {
776
- const root = initialRoot(this.workspace, target.id);
777
- const result = await server.initialRecovery(binding, root, this.inputs.fingerprint);
778
- if (result.state === 'busy')
779
- fail('busy', 'The retained initial-model worker is still active.');
780
- if (result.state === 'candidate') {
781
- const receipt = text(result.receipt);
782
- if (!/^canonical-[a-f0-9-]{36}\.json$/.test(receipt))
783
- fail('binding', 'Invalid canonical recovery receipt.');
784
- const proof = await server.initialRecovery(binding, root, this.inputs.fingerprint, receipt);
785
- if (proof.state !== 'verified' || proof.version !== result.version || proof.snapshotBuffersVerified !== true || proof.snapshot !== result.snapshot ||
786
- typeof proof.snapshot !== 'string' || !/^canonical-[a-f0-9-]{36}\.gzf$/.test(proof.snapshot))
787
- fail('unknown', 'Canonical model changed or independent recovery readback remains unproved.');
788
- const snapshot = await this.workspace.captureSnapshot(join(root, proof.snapshot));
789
- if (snapshot.sha256 !== proof.snapshotSha256)
790
- fail('binding', 'Recovered canonical snapshot changed.');
791
- this.workspace.establishModel(target.id, version(proof.version), snapshot);
792
- await initialProgress(root, target.id, 'complete', 'complete');
793
- return;
794
- }
795
- if (result.state !== 'absent' || result.root !== 'runtime-' + this.inputs.fingerprint)
796
- fail('unknown', 'Retained initial-model outcome requires reconciliation.');
797
- await initializeModel(this.workspace, target, binding, server, this.inputs.fingerprint, join(root, String(result.root)));
798
- return;
799
- }
800
- }
801
- if (!intent) {
802
- // Old builds imported into an unversioned local shared-project stage. First stop
803
- // its authenticated worker; a failed probe is never treated as authoritative absence.
804
- if (model.state === 'unknown')
805
- await this.retireLegacyBootstrap(target);
806
- const status = await server.programStatus(binding, programPath(target.id));
807
- if (status.state !== 'absent')
808
- fail('unknown', 'Canonical initial target already exists or is reserved; retain its original stage for independent reconciliation.');
809
- }
810
- await initializeModel(this.workspace, target, binding, server, this.inputs.fingerprint);
811
- }
812
- async model(target) {
813
- let task = this.modelTasks.get(target.id);
814
- if (!task) {
815
- task = this.initialModel(target).finally(() => { if (this.modelTasks.get(target.id) === task)
816
- this.modelTasks.delete(target.id); });
817
- this.modelTasks.set(target.id, task);
818
- }
819
- await task;
820
- return this.workspace.model(target.id);
821
- }
822
- async privateCopy(context) {
823
- // A failed inventory is never cached: the next open repeats it.
824
- if (!this.capacity.inventory)
825
- this.capacity.inventory = this.inventory().catch(error => { this.capacity.inventory = undefined; throw error; });
826
- await timed('context.inventory', 'owned', async () => { await this.capacity.inventory; });
827
- // Workers that stopped by themselves no longer hold capacity.
828
- for (const [root, record] of [...this.running])
829
- if (record.binding.kind === 'context' && record.binding.context && await this.workerGone(record.binding)) {
830
- if (!await this.settleRetired(record.binding)) {
831
- this.running.delete(root);
832
- this.capacity.slots.delete(record.binding.context);
833
- }
834
- }
835
- const configured = this.c.profile.values.maxContexts, max = configured === undefined ? 4 : Number(configured);
836
- if (!Number.isSafeInteger(max) || max < 1 || max > 16)
837
- fail('configuration', 'maxContexts must be an integer from 1 to 16.');
838
- if (!this.capacity.slots.has(context.id) && this.capacity.slots.size >= max)
839
- await this.evictIdle(context.id);
840
- if (!this.capacity.slots.has(context.id) && this.capacity.slots.size >= max)
841
- fail('limit', 'Owned context capacity is occupied; close a saved context before opening another.');
842
- this.capacity.slots.add(context.id);
843
- let record;
844
- try {
845
- const target = this.workspace.target(context.target), checkout = context.nativeCheckout;
846
- if (!checkout || checkout.state !== 'active')
847
- fail('binding', 'An active native checkout is required.');
848
- await this.nativeOwner(checkout);
849
- const root = checkout.root;
850
- // Another runtime first proves, without an upgrade, that it can read the saved database.
851
- if (checkout.runtimeFingerprint !== this.inputs.fingerprint) {
852
- const observed = await this.nativeOperation(checkout, 'status');
853
- if (observed.recoverable === true)
854
- throw unsavedChanges(context);
855
- if (observed.state !== 'ready' || observed.checkoutId !== checkout.checkoutId)
856
- fail('binding', 'This runtime cannot open the native checkout without changing it; the project is retained.');
857
- }
858
- record = await this.launch(root, target, 'context', checkout.path, 'headless', context.id);
859
- const project = object(await record.http.call('/open_project', { path: join(root, 'view.gpr') }));
860
- if (project.success === false)
861
- fail('launch', 'Native working project could not be reopened.');
862
- const opened = object(await openWorkerProgram(record.http, record.binding.program, context));
863
- if (opened.path !== record.binding.program || opened.read_only === true)
864
- fail('binding', 'Native checkout did not open its saved writable program.');
865
- await this.verified(record.binding, target);
866
- record.binding.baseRevision = context.baseRevision ?? this.workspace.model(context.target).sharedRevision;
867
- record.binding.viewEpoch = context.viewEpoch ?? 0;
868
- await durable(join(root, 'process.json'), record.binding);
869
- await durable(join(this.directory(), 'context', context.id, 'current.json'), record.binding);
870
- if (context.workingSnapshot)
871
- await recordLifecycle(this.workspace, context.id, { at: new Date().toISOString(), event: 'restore', reason: 'saved_snapshot', pid: record.binding.pid });
872
- // A receipt written by an earlier build names its saved state by a hash that nothing compares with any more:
873
- // the open program is described again, which reads no database.
874
- const receipt = context.workingSnapshot?.kind === 'native' ? object(JSON.parse(await readFile(await this.workspace.artifacts.verify(context.workingSnapshot), 'utf8'))) : undefined;
875
- if (receipt && receipt.source === 'checkout' && typeof receipt.modified !== 'boolean') {
876
- const current = this.workspace.context(context);
877
- return { ...record, generation: this.workspace.saveContext(current, current.generation, { workingSnapshot: await this.capture(record) }).generation };
878
- }
879
- return record;
880
- }
881
- catch (error) {
882
- if (record)
883
- await this.stopRecord(record, false, true, 'startup_failed');
884
- else
885
- this.capacity.slots.delete(context.id);
886
- throw error;
887
- }
888
- }
889
- async createNative(scope) {
890
- const context = this.workspace.context(scope), target = this.workspace.target(scope.target), server = this.server(), binding = await server.ensure();
891
- const parent = join(this.directory(), 'context', context.id);
892
- await mkdir(parent, { recursive: true, mode: 0o700 });
893
- const pending = join(parent, 'checkout.json');
894
- let intent;
895
- try {
896
- intent = object(JSON.parse(await readFile(pending, 'utf8')));
897
- }
898
- catch (error) {
899
- if (error.code !== 'ENOENT')
900
- throw error;
901
- }
902
- if (!intent || intent.root === context.nativeCheckout?.root) {
903
- const root = await this.prepareRoot('context', target.id, context.id), owner = { schema: 1, protocol: this.nativeEngine, context: context.id, target: target.id,
904
- sourceSha: target.binarySha256, origin: binding.origin, repository: binding.repository, path: programPath(target.id), runtimeFingerprint: this.inputs.fingerprint };
905
- await durable(join(root, 'native-owner.json'), owner);
906
- intent = { root, owner };
907
- await durable(pending, intent);
908
- }
909
- const root = await realpath(text(intent.root, 4096)), owner = object(intent.owner);
910
- if (!ownedDirectory(root, this.directory(), ['context', context.id, basename(root)]) || owner.context !== context.id || owner.target !== target.id || typeof owner.runtimeFingerprint !== 'string' ||
911
- owner.origin !== binding.origin || owner.repository !== binding.repository || owner.path !== programPath(target.id) || owner.sourceSha !== target.binarySha256)
912
- fail('binding', 'Retained checkout creation binding changed.');
913
- const value = await server.nativeCheckout(binding, { root, owner, operation: 'create' });
914
- if (value.state !== 'ready' || value.checkedOut !== true || !Number.isSafeInteger(value.checkoutId) || typeof value.fileId !== 'string')
915
- fail('unknown', 'Native checkout creation remains unproved; its original project is retained.');
916
- const checkout = { schema: 1, context: context.id, root, fileId: value.fileId, checkoutId: Number(value.checkoutId), baseVersion: version(value.baseVersion),
917
- origin: binding.origin, repository: binding.repository, path: programPath(target.id), runtimeFingerprint: owner.runtimeFingerprint, state: 'active' };
918
- const shared = await this.serverView(scope.target, checkout.baseVersion, checkout.fileId), snapshot = await this.nativeReceipt(checkout, object(value.saved));
919
- this.observeNativeShared(scope.target, shared);
920
- return this.workspace.saveContext(scope, context.generation, { state: 'stopped', nativeCheckout: checkout, baseRevision: checkout.baseVersion, baseSnapshot: shared.snapshot, workingSnapshot: snapshot });
921
- }
922
- async updateNative(scope, request) {
923
- // No Update has been sent until the native call below. A definite failure before it leaves the request not sent,
924
- // never an unknown outcome without a journal. A request whose own reply was lost (for example the private save)
925
- // keeps its outcome: that is an unresolved effect on the context itself.
926
- let context, worker = true;
927
- try {
928
- await this.open(scope, request);
929
- context = this.workspace.context(scope);
930
- const record = await this.selected(scope);
931
- await this.capture(record);
932
- worker = false;
933
- // Park the warm worker instead of stopping its JVM; without a proved project release, stop it as before.
934
- // After the marker the project may be closed, so the worker cannot prove its open project any more: it is
935
- // stopped the way a parked worker is.
936
- if (!await this.park(record).catch(() => false)) {
937
- if (await this.parkedMarker(record.binding))
938
- await this.stopParked(record.binding);
939
- else
940
- await this.stopRecord(record, true, true, 'view_replaced');
941
- }
942
- }
943
- catch (error) {
944
- return this.unsent('update', error, worker);
945
- }
946
- const checkout = context.nativeCheckout;
947
- const value = await this.notSent('update', checkout, request, () => this.nativeOperation(checkout, 'update', { request }));
948
- return this.applyNativeUpdate(scope, request, value, checkout.baseVersion);
949
- }
950
- /**
951
- * A failure before a native Update or check-in was dispatched: the request is settled as not sent and keeps the
952
- * cause, its memory diagnosis and its next step.
953
- *
954
- * While the context is opened and saved (`worker`), the worker may reopen or save the program, so only a refusal
955
- * that names itself as one settles the request: a busy, blocked or full worker pool. Every other failure there
956
- * (a lost, failed or unusable reply, a binding that no longer matches) may follow an effect in the worker and
957
- * keeps its own outcome. Parking, a stop that was refused and the owner and server check write nothing in the
958
- * program; a worker that was asked to end and is not proved gone may still save, so that failure keeps its outcome.
959
- */
960
- unsent(phase, error, worker = false) {
961
- if (error instanceof CliError && error.code === 'coordinator.notSent')
962
- throw error;
963
- // A worker that was asked to end and is not proved gone may still be saving.
964
- if (error && typeof error === 'object' && unprovedStops.has(error))
965
- throw error;
966
- if (worker) {
967
- const refused = error instanceof CliError && !unprovedSaves.has(error) && (['coordinator.busy', 'coordinator.blocked', 'coordinator.capacity'].includes(error.code) ||
968
- error.code === 'coordinator.limit' && !oversizedReplies.has(error));
969
- if (!refused)
970
- throw error;
971
- }
972
- const system = error?.code, result = error instanceof CliError ? object(error.result ?? {}) : {};
973
- const cause = error instanceof CliError ? { code: error.code, message: error.message } :
974
- { code: 'coordinator.launch', message: 'Its preparation failed' + (typeof system === 'string' && /^E[A-Z0-9]{2,24}$/.test(system) ? ' (' + system + ')' : '') + '.' };
975
- throw new CliError('Native ' + phase + ' was not sent. ' + cause.message + (phase === 'update' ? ' No Update or check-in was sent' : ' The check-in was not sent') + '; run the operation again with a new request ID.', { code: 'coordinator.notSent', ...(error instanceof CliError && error.next ? { next: error.next } : {}),
976
- result: { phase, cause, ...(result.memory === 'exhausted' ? { memory: 'exhausted', reason: 'out_of_memory', memoryCause: result.memoryCause } : {}) } });
977
- }
978
- async applyNativeUpdate(scope, request, value, previousBase) {
979
- let context = this.workspace.context(scope);
980
- const checkout = context.nativeCheckout;
981
- if (value.state === 'unknown')
982
- fail('unknown', 'Native Update outcome is unknown; retain this project and its operation journal.');
983
- if (value.state === 'conflict') {
984
- const message = text(value.conflict, 16000);
985
- this.workspace.saveContext(scope, context.generation, { state: 'stopped', nativeCheckout: { ...checkout, conflict: { request, message } } });
986
- return { state: 'conflict', conflict: message, revision: checkout.baseVersion };
987
- }
988
- if (value.state !== 'updated' || value.checkoutId !== checkout.checkoutId)
989
- fail('binding', 'Native Update did not preserve checkout identity.');
990
- if (typeof value.modified !== 'boolean')
991
- fail('binding', 'Native Update did not report whether the checkout holds work; the project is retained.');
992
- const next = { ...checkout, baseVersion: version(value.baseVersion) };
993
- delete next.conflict;
994
- const snapshot = await this.nativeReceipt(next, object(value.saved));
995
- const shared = await this.serverView(scope.target, next.baseVersion, next.fileId);
996
- this.observeNativeShared(scope.target, shared);
997
- context = this.workspace.saveContext(scope, context.generation, { nativeCheckout: next, state: 'stopped', workingSnapshot: snapshot, baseSnapshot: shared.snapshot, baseRevision: next.baseVersion, viewEpoch: (context.viewEpoch ?? 0) + 1 });
998
- // A dirty Update that left no private change keeps only a backup that its own journal proves disposable; remove it
999
- // now so a context that continues in this checkout can later be proved pristine and released. A refusal keeps it.
1000
- if (value.modified === false && Object.keys(object(value.disposableBackups ?? {})).length)
1001
- await this.nativeOperation(next, 'prune-backups', { verifiedVersion: next.baseVersion }).catch(() => undefined);
1002
- // Ghidra's own answer after the Update says whether the checkout holds private work.
1003
- return { state: value.modified ? 'ready' : 'empty', revision: next.baseVersion, snapshot, sharedSnapshot: shared.snapshot,
1004
- receivedChanges: Number(next.baseVersion !== previousBase), nativeMergeInvocations: Number(value.nativeMergeInvocations ?? 0) };
1005
- }
1006
- async recoverUpdate(scope, request) {
1007
- const context = this.workspace.context(scope), checkout = context.nativeCheckout;
1008
- if (!checkout || checkout.state !== 'active' || !await this.closed(scope))
1009
- return { state: 'unknown' };
1010
- let journal;
1011
- try {
1012
- journal = object(JSON.parse(await readFile(join(checkout.root, 'operations', request + '-update.json'), 'utf8')));
1013
- }
1014
- catch (error) {
1015
- if (error.code === 'ENOENT')
1016
- return { state: 'unknown' };
1017
- throw error;
1018
- }
1019
- const q = object(journal.request), value = journal.result === undefined ? undefined : object(journal.result), { owner } = await this.nativeOwner(checkout);
1020
- if (q.request !== request || q.root !== checkout.root || q.fileId !== checkout.fileId || q.checkoutId !== checkout.checkoutId || stable(q.owner) !== stable(owner) || !value)
1021
- return { state: 'unknown' };
1022
- const observed = await this.nativeOperation(checkout, 'status'), journaled = object(value.saved ?? {});
1023
- // The project must still be in the state the journal recorded. A journal of an earlier build names that state by a
1024
- // hash of the database, which nothing computes any more: there Ghidra's modification status is compared instead.
1025
- const same = typeof journaled.modified === 'boolean' ? object(observed.saved ?? {}).fingerprint === journaled.fingerprint : observed.modified === value.modified;
1026
- if (observed.state !== 'ready' || observed.recoverable !== false || observed.checkoutId !== checkout.checkoutId || observed.baseVersion !== value.baseVersion || !same)
1027
- return { state: 'unknown' };
1028
- return this.applyNativeUpdate(scope, request, value, version(journal.baseVersion));
1029
- }
1030
- async publishNative(publication) {
1031
- const context = this.workspace.context(publication), checkout = context.nativeCheckout;
1032
- if (!checkout || checkout.state !== 'active')
1033
- fail('binding', 'Native publication has no active checkout.');
1034
- const saved = object(JSON.parse(await readFile(await this.workspace.artifacts.verify(publication.snapshot), 'utf8')));
1035
- if (saved.engine !== this.nativeEngine || saved.source !== 'checkout' || object(saved.checkout).root !== checkout.root || saved.fileId !== checkout.fileId)
1036
- fail('binding', 'Publication differs from its prepared native project.');
1037
- const value = await this.notSent('checkin', checkout, publication.id, () => this.nativeOperation(checkout, 'checkin', { request: publication.id, fingerprint: text(saved.fingerprint), expectedVersion: publication.expectedRevision }));
1038
- if (value.state === 'conflict')
1039
- return { state: 'conflict', applied: 0, conflict: String(value.conflict) };
1040
- if (value.state !== 'checked_in' || value.baseVersion !== publication.expectedRevision + 1)
1041
- fail('unknown', 'Native check-in outcome requires independent reconciliation; the project is retained.');
1042
- // Ghidra's check-in returned and the checkout now stands at the new version: that is the publication. The version
1043
- // is not read back from the server; its view is the one that was checked in. Only a check-in whose answer was lost
1044
- // is settled from history (`recover`).
1045
- const revision = publication.expectedRevision + 1, binding = await this.server().ensure();
1046
- await this.rememberVersion(publication.target, binding, { state: 'verified', version: revision, fileId: checkout.fileId, fingerprint: versionIdentity(checkout.fileId, revision) });
1047
- const shared = await this.serverView(publication.target, revision, checkout.fileId);
1048
- return { state: 'published', revision, snapshot: shared.snapshot, observation: value };
1049
- }
1050
- /**
1051
- * After a verified publication the check-in kept the checkout. When its own post-check-in observation proves
1052
- * the project unchanged at exactly the published version (after removing backups proved disposable by this
1053
- * checkout's journals), the context continues in it.
1054
- */
1055
- async continueNative(scope, observed) {
1056
- const context = this.workspace.context(scope), checkout = context.nativeCheckout;
1057
- if (!checkout || checkout.state !== 'verified' || !context.baseSnapshot || context.debugger?.traces.length || this.workspace.uncertainOutcome(scope))
1058
- return false;
1059
- const base = object(JSON.parse(await readFile(await this.workspace.artifacts.verify(context.baseSnapshot), 'utf8')));
1060
- const program = basename(checkout.path);
1061
- const valid = (value) => {
1062
- const saved = object(value.saved ?? {});
1063
- return value.checkedOut === true && value.modified === false && value.recoverable === false && value.fileId === checkout.fileId && value.checkoutId === checkout.checkoutId &&
1064
- value.baseVersion === checkout.baseVersion && saved.fileId === checkout.fileId && saved.version === checkout.baseVersion &&
1065
- base.source === 'server' && base.version === checkout.baseVersion && base.fileId === checkout.fileId && Array.isArray(value.projectFiles);
1066
- };
1067
- if (observed.state !== 'checked_in' || !valid(observed))
1068
- return false;
1069
- let observation = observed;
1070
- const files = (value) => value.projectFiles.map(String);
1071
- const { conflict, ...rest } = checkout, active = { ...rest, state: 'active' };
1072
- if (files(observation).some(name => name !== program)) {
1073
- if (!files(observation).every(name => name === program || this.nativeKeepName(checkout, name)))
1074
- return false;
1075
- observation = await this.nativeOperation(active, 'prune-backups', { verifiedVersion: checkout.baseVersion });
1076
- if (observation.state !== 'pruned' || !valid(observation))
1077
- return false;
1078
- }
1079
- if (stable(files(observation)) !== stable([program]))
1080
- return false;
1081
- const snapshot = await this.nativeReceipt(active, object(observation.saved));
1082
- this.workspace.saveContext(scope, context.generation, { nativeCheckout: active, state: 'stopped', workingSnapshot: snapshot, scalars: [], complexChanges: [] });
1083
- return true;
1084
- }
1085
- async dropNative(scope, request) {
1086
- const context = this.workspace.context(scope), checkout = context.nativeCheckout;
1087
- if (!checkout || checkout.state === 'dropped')
1088
- return;
1089
- if (checkout.state !== 'verified')
1090
- fail('blocked', 'Only a verified native publication can dispose its project.');
1091
- const shared = object(JSON.parse(await readFile(await this.workspace.artifacts.verify(context.baseSnapshot), 'utf8')));
1092
- if (shared.source !== 'server' || shared.version !== checkout.baseVersion || shared.fileId !== checkout.fileId)
1093
- fail('binding', 'Verified native disposal reference changed.');
1094
- const parameters = { verifiedVersion: checkout.baseVersion };
1095
- let released;
1096
- try {
1097
- released = await this.nativeOperation(checkout, 'release', parameters);
1098
- }
1099
- catch (error) {
1100
- await this.retainNative(scope, checkout, request);
1101
- throw error;
1102
- }
1103
- if (released.state !== 'released') {
1104
- await this.retainNative(scope, checkout, request);
1105
- fail('unknown', 'Checkout release remains unproved; its project and saved work are retained.');
1106
- }
1107
- const dropped = await this.nativeOperation(checkout, 'drop', parameters);
1108
- if (dropped.state !== 'dropped')
1109
- fail('unknown', 'Publication is verified but project deletion remains unproved.');
1110
- this.workspace.saveContext(scope, context.generation, { nativeCheckout: { ...checkout, state: 'dropped' }, state: 'stopped', workingSnapshot: context.baseSnapshot, scalars: [], complexChanges: [] });
1111
- }
1112
- /** A lost release reply can mean undoCheckout succeeded. Only independent ownership readback permits reopening. */
1113
- async retainNative(scope, checkout, request) {
1114
- let result;
1115
- try {
1116
- const observed = await this.nativeOperation(checkout, 'status');
1117
- if (observed.state !== 'ready' || observed.checkedOut !== true || observed.fileId !== checkout.fileId || observed.checkoutId !== checkout.checkoutId || observed.baseVersion !== checkout.baseVersion)
1118
- return;
1119
- const active = { ...checkout, state: 'active' };
1120
- const snapshot = await this.nativeReceipt(active, object(observed.saved)), context = this.workspace.context(scope);
1121
- result = this.workspace.retainNativeDisposal(scope, context.generation, checkout, snapshot, request);
1122
- }
1123
- catch { /* Unproved release/ownership stays verified for journal-based recovery, never a new private launch. */ }
1124
- if (result)
1125
- fail('conflict', 'Final native release was refused; saved private work is retained.', result);
1126
- }
1127
- async finishEmptyNative(scope, request) {
1128
- const context = this.workspace.context(scope);
1129
- if (!context.nativeCheckout)
1130
- fail('binding', 'Native checkout is absent.');
1131
- if (context.nativeCheckout.state === 'verified' || context.nativeCheckout.state === 'dropped') {
1132
- await this.dropNative(scope, request);
1133
- return;
1134
- }
1135
- // No new server version: Ghidra reported this checkout unmodified, and the release asks it again.
1136
- if (!this.workspace.unchangedNative(context))
1137
- fail('binding', 'A native checkout that Ghidra reports modified holds private work.');
1138
- const checkout = context.nativeCheckout;
1139
- // Keep the original saved view and diagnostics until release succeeds. A refused release is still private work.
1140
- this.workspace.saveContext(scope, context.generation, { state: 'stopped', nativeCheckout: { ...checkout, state: 'verified' } });
1141
- await this.dropNative(scope, request);
1142
- }
1143
- /** Close and GC drop a working copy only when Ghidra itself reports no private change. */
1144
- async releaseUnchanged(scope) {
1145
- const context = this.workspace.context(scope), checkout = context.nativeCheckout;
1146
- if (!checkout || checkout.state === 'dropped' || checkout.conflict || context.scalars.length || context.complexChanges.length || context.debugger?.traces.length || context.debugger?.connected ||
1147
- this.workspace.activePublication(scope.target)?.session === scope.session || !this.workspace.unchangedNative(context) || this.workspace.uncertainOutcome(scope) || this.workspace.checkoutReferenced(context) || !await this.neverStartedOrClosed(context))
1148
- return false;
1149
- if (checkout.state === 'verified') {
1150
- await this.dropNative(scope);
1151
- return true;
1152
- }
1153
- const base = object(JSON.parse(await readFile(await this.workspace.artifacts.verify(context.baseSnapshot), 'utf8'))), observed = await this.nativeOperation(checkout, 'status');
1154
- const fingerprint = observed.saved && typeof observed.saved === 'object' ? observed.saved.fingerprint : undefined;
1155
- // Ghidra's own, fresh answer decides whether the checkout holds work.
1156
- if (base.source !== 'server' || base.version !== checkout.baseVersion || observed.state !== 'ready' || observed.checkedOut !== true || observed.recoverable !== false || observed.fileId !== checkout.fileId ||
1157
- observed.checkoutId !== checkout.checkoutId || observed.baseVersion !== checkout.baseVersion || observed.modified !== false ||
1158
- // Backups are checked by the native release itself: each must be proved disposable by this checkout's journals.
1159
- !Array.isArray(observed.projectFiles) || observed.projectFiles.some(name => name !== basename(checkout.path) && !this.nativeKeepName(checkout, String(name))))
1160
- return false;
1161
- // The context keeps the receipt of the state that was just observed, not an older one.
1162
- if (fingerprint !== object(JSON.parse(await readFile(await this.workspace.artifacts.verify(context.workingSnapshot), 'utf8'))).fingerprint) {
1163
- const snapshot = await this.nativeReceipt(checkout, object(observed.saved));
1164
- this.workspace.saveContext(scope, context.generation, { workingSnapshot: snapshot });
1165
- }
1166
- await this.finishEmptyNative(scope);
1167
- return true;
1168
- }
1169
- /** Absence of the ready receipt alone says nothing about an interrupted first start. */
1170
- async neverStartedOrClosed(c) {
1171
- if (await exists(join(this.directory(), 'context', c.id, 'current.json')))
1172
- return this.closed(c);
1173
- if (!(await this.lastWorker(c.id, c)).binding)
1174
- return true;
1175
- return this.closed(c);
1176
- }
1177
- /** A pending checkout intent may own a server checkout, so it is never treated as detached work. */
1178
- async detachedStopped(scope) {
1179
- const context = this.workspace.context(scope);
1180
- let pending = true;
1181
- try {
1182
- await readFile(join(this.directory(), 'context', context.id, 'checkout.json'));
1183
- }
1184
- catch (error) {
1185
- if (error.code !== 'ENOENT')
1186
- throw error;
1187
- pending = false;
1188
- }
1189
- if (pending || context.nativeCheckout)
1190
- fail('blocked', 'A native checkout belongs to this context; it is not detached work.');
1191
- // A worker whose owner died before its current receipt is still found by its process receipt.
1192
- if ((await runtimeProcesses(dirname(this.workspace.directory), this.c.appArguments?.AppDataDirectory)).some(p => p.kind !== 'server' && (p.sessionContext ?? context.id) === context.id))
1193
- return false;
1194
- return this.neverStartedOrClosed(context);
1195
- }
1196
- /** Absence is proved by the owned storage that remains: nothing of the context may survive beside the lost root. */
1197
- async missingCheckout(scope) {
1198
- const context = this.workspace.context(scope), checkout = context.nativeCheckout, contexts = join(this.directory(), 'context'), parent = join(contexts, context.id);
1199
- if (!checkout || checkout.state === 'dropped')
1200
- fail('unsupported', 'This context has no retained native checkout.');
1201
- const name = basename(checkout.root);
1202
- if (basename(dirname(checkout.root)) !== context.id)
1203
- fail('binding', 'Native checkout receipt names a directory outside this context.');
1204
- if (await realpath(contexts) !== join(await realpath(this.workspace.directory), 'ghidra-native', 'context'))
1205
- fail('binding', 'Owned context storage moved.');
1206
- const absent = async (path) => { try {
1207
- await lstat(path);
1208
- return false;
1209
- }
1210
- catch (error) {
1211
- if (error.code === 'ENOENT')
1212
- return true;
1213
- throw error;
1214
- } };
1215
- if (!await absent(checkout.root) || !await absent(join(parent, name)))
1216
- fail('blocked', 'The native checkout project still exists; it is not lost.');
1217
- // Only receipts of the lost root may remain beside it, and its last worker must be gone.
1218
- if (!await absent(parent))
1219
- for (const entry of await readdir(parent, { withFileTypes: true })) {
1220
- if (!entry.isFile() || !['checkout.json', 'current.json'].includes(entry.name))
1221
- fail('blocked', 'Other retained data of this context still exists; its checkout is not proved lost.');
1222
- const receipt = object(JSON.parse(await readFile(join(parent, entry.name), 'utf8')));
1223
- if (typeof receipt.root !== 'string' || basename(receipt.root) !== name || basename(dirname(receipt.root)) !== context.id)
1224
- fail('blocked', 'A retained receipt names another project of this context.');
1225
- if (entry.name === 'current.json' && (!Number.isSafeInteger(receipt.pid) || alive(Number(receipt.pid))))
1226
- fail('busy', 'The last worker of this context is not proved stopped.');
1227
- }
1228
- // A project renamed inside owned storage keeps its owner receipt.
1229
- for (const owner of await readdir(contexts, { withFileTypes: true }))
1230
- if (owner.isDirectory())
1231
- for (const root of await readdir(join(contexts, owner.name), { withFileTypes: true }))
1232
- if (root.isDirectory()) {
1233
- let value;
1234
- try {
1235
- value = JSON.parse(await readFile(join(contexts, owner.name, root.name, 'native-owner.json'), 'utf8'));
1236
- }
1237
- catch (error) {
1238
- if (error.code === 'ENOENT')
1239
- continue;
1240
- throw error;
1241
- }
1242
- if (object(value).context === context.id)
1243
- fail('blocked', 'A project of this context still exists under another name; restore its directory.');
1244
- }
1245
- // This owner's own idle native services are not foreign helpers; busy ones refuse.
1246
- await this.requireIdleServices();
1247
- const process = await runtimeProcesses(dirname(this.workspace.directory), this.c.appArguments?.AppDataDirectory);
1248
- if (this.capacity.slots.has(context.id) || process.some(p => p.kind !== 'server') || (await migrationProcessBlockers(this.c.appArguments.AppDataDirectory)).length)
1249
- fail('busy', 'Stop or reconcile every Ghidra worker and native helper before giving up a missing checkout.');
1250
- return checkout;
1251
- }
1252
- async abandonMissing(scope, check) {
1253
- const checkout = await this.missingCheckout(scope), context = this.workspace.context(scope), server = this.server(), binding = await server.ensure();
1254
- if (checkout.origin !== binding.origin || checkout.repository !== binding.repository || checkout.path !== programPath(scope.target))
1255
- fail('binding', 'Native checkout server binding changed.');
1256
- const value = await server.nativeCheckout(binding, { root: checkout.root, operation: 'abandon', check, fileId: checkout.fileId, checkoutId: checkout.checkoutId, baseVersion: checkout.baseVersion,
1257
- owner: { protocol: this.nativeEngine, context: context.id, target: scope.target, path: checkout.path, repository: checkout.repository } });
1258
- if (value.state !== (check ? 'endable' : 'abandoned'))
1259
- fail('unknown', 'The server checkout is not proved ended; repeat this command.');
1260
- if (check)
1261
- return;
1262
- // Receipts of the lost root would otherwise be read as an unproved worker; they stay as evidence.
1263
- const kept = join(this.workspace.directory, 'native-discards', scope.target);
1264
- await mkdir(kept, { recursive: true, mode: 0o700 });
1265
- try {
1266
- await rename(join(this.directory(), 'context', context.id), join(kept, context.id + '-receipts-' + randomUUID()));
1267
- }
1268
- catch (error) {
1269
- if (error.code !== 'ENOENT')
1270
- throw error;
1271
- }
1272
- }
1273
- async collect(dryRun) {
1274
- return collectStorage(this.workspace, { closed: c => this.neverStartedOrClosed(c), release: c => this.releaseUnchanged(c) }, dryRun, message => this.c.progress(message));
1275
- }
1276
- async recoverEmptyNative(scope, request) {
1277
- const context = this.workspace.context(scope), checkout = context.nativeCheckout;
1278
- if (!checkout || !['verified', 'dropped'].includes(checkout.state))
1279
- return { state: 'unknown' };
1280
- let journal;
1281
- try {
1282
- journal = object(JSON.parse(await readFile(join(checkout.root, 'operations', request + '-update.json'), 'utf8')));
1283
- }
1284
- catch (error) {
1285
- if (error.code === 'ENOENT')
1286
- return { state: 'unknown' };
1287
- throw error;
1288
- }
1289
- const q = object(journal.request), result = object(journal.result ?? {}), saved = object(result.saved ?? {}), { owner } = await this.nativeOwner(checkout);
1290
- const shared = object(JSON.parse(await readFile(await this.workspace.artifacts.verify(context.baseSnapshot), 'utf8')));
1291
- if (q.request !== request || q.root !== checkout.root || q.fileId !== checkout.fileId || q.checkoutId !== checkout.checkoutId || stable(q.owner) !== stable(owner) || result.state !== 'updated' || typeof result.modified !== 'boolean' ||
1292
- result.checkoutId !== checkout.checkoutId || result.baseVersion !== checkout.baseVersion || saved.fileId !== checkout.fileId || saved.version !== checkout.baseVersion ||
1293
- shared.source !== 'server' || shared.version !== checkout.baseVersion || shared.fileId !== checkout.fileId || shared.origin !== checkout.origin || shared.repository !== checkout.repository ||
1294
- result.modified !== false)
1295
- return { state: 'unknown' };
1296
- await this.dropNative(scope, request);
1297
- return { state: 'verified', revision: checkout.baseVersion };
1298
- }
1299
- async discardNative(scope, request) {
1300
- const context = this.workspace.context(scope), checkout = context.nativeCheckout;
1301
- if (!checkout || checkout.state !== 'active' || !await this.closed(scope))
1302
- fail('busy', 'Native discard requires its saved, stopped working copy.');
1303
- const value = await this.nativeOperation(checkout, 'discard', { request });
1304
- if (value.state !== 'discarded' || !Number.isSafeInteger(value.checkoutId) || value.checkoutId === checkout.checkoutId)
1305
- fail('unknown', 'Native discard is unproved; its project and journal remain retained.');
1306
- return this.applyNativeDiscard(scope, value);
1307
- }
1308
- /**
1309
- * Unsaved changes that an interrupted Ghidra session left in this checkout: Ghidra itself restores and saves them, or
1310
- * deletes them. Repeating the command is safe; with nothing left to settle it answers `absent`.
1311
- */
1312
- async settleUnsaved(scope, keep) {
1313
- const context = this.workspace.context(scope), checkout = context.nativeCheckout;
1314
- if (!checkout || checkout.state !== 'active')
1315
- fail('unsupported', 'This context has no active native checkout.');
1316
- if (!await this.neverStartedOrClosed(context))
1317
- fail('busy', 'Close this context before settling the unsaved changes of an interrupted session.');
1318
- const value = await this.nativeOperation(checkout, 'unsaved', { keep, baseVersion: checkout.baseVersion });
1319
- if (!['recovered', 'discarded', 'absent'].includes(String(value.state)) || value.recoverable !== false || value.checkedOut !== true || value.checkoutId !== checkout.checkoutId ||
1320
- value.baseVersion !== checkout.baseVersion || typeof value.modified !== 'boolean')
1321
- fail('unknown', 'Ghidra did not report the unsaved changes settled; the project is retained. Run the command again.');
1322
- // The context names the state Ghidra reports now, also when an earlier run of this command lost its reply.
1323
- const saved = object(value.saved), known = context.workingSnapshot ? object(JSON.parse(await readFile(await this.workspace.artifacts.verify(context.workingSnapshot), 'utf8'))).fingerprint : undefined;
1324
- if (saved.fingerprint !== known)
1325
- this.workspace.saveContext(scope, context.generation, { state: 'stopped', workingSnapshot: await this.nativeReceipt(checkout, saved), viewEpoch: (context.viewEpoch ?? 0) + 1 });
1326
- return { state: value.state, modified: value.modified };
1327
- }
1328
- async recoverDiscardNative(scope, request, original) {
1329
- const context = this.workspace.context(scope), checkout = context.nativeCheckout;
1330
- if (!original || !checkout || checkout.state !== 'active' || checkout.root !== original.root || !await this.closed(scope))
1331
- return { state: 'unknown' };
1332
- const binding = (c) => { const { checkoutId, baseVersion, conflict, ...rest } = c; return rest; };
1333
- if (stable(binding(checkout)) !== stable(binding(original)))
1334
- return { state: 'unknown' };
1335
- let journal;
1336
- try {
1337
- journal = object(JSON.parse(await readFile(join(original.root, 'operations', request + '-discard.json'), 'utf8')));
1338
- }
1339
- catch (error) {
1340
- if (error.code === 'ENOENT')
1341
- return { state: 'unknown' };
1342
- throw error;
1343
- }
1344
- const q = object(journal.request), value = object(journal.result ?? {}), { owner } = await this.nativeOwner(original);
1345
- if (q.operation !== 'discard' || q.request !== request || q.root !== original.root || q.fileId !== original.fileId || q.checkoutId !== original.checkoutId || stable(q.owner) !== stable(owner) ||
1346
- value.state !== 'discarded' || !Number.isSafeInteger(value.checkoutId) || Number(value.checkoutId) < 0 || value.checkoutId === original.checkoutId || value.modified !== false ||
1347
- !Number.isSafeInteger(value.baseVersion) || Number(value.baseVersion) < original.baseVersion)
1348
- return { state: 'unknown' };
1349
- if (checkout.checkoutId !== original.checkoutId && checkout.checkoutId !== value.checkoutId ||
1350
- checkout.baseVersion !== (checkout.checkoutId === original.checkoutId ? original.baseVersion : value.baseVersion))
1351
- return { state: 'unknown' };
1352
- const next = { ...checkout, checkoutId: Number(value.checkoutId), baseVersion: Number(value.baseVersion) };
1353
- const observed = await this.nativeOperation(next, 'status'), checkouts = observed.checkouts;
1354
- if (observed.state !== 'ready' || observed.checkedOut !== true || observed.modified !== false || observed.recoverable !== false || observed.fileId !== next.fileId || observed.checkoutId !== next.checkoutId || observed.baseVersion !== next.baseVersion ||
1355
- object(observed.saved).fingerprint !== object(value.saved).fingerprint || !Array.isArray(checkouts) ||
1356
- checkouts.some(c => object(c).id === original.checkoutId) || !checkouts.some(c => object(c).id === next.checkoutId && object(c).version === next.baseVersion) ||
1357
- typeof value.retainedKeepFile !== 'string' || value.retainedKeepFile !== '' && (!this.nativeKeepName(next, value.retainedKeepFile) || !Array.isArray(observed.projectFiles) || !observed.projectFiles.includes(value.retainedKeepFile)))
1358
- return { state: 'unknown' };
1359
- return { state: 'verified', ...await this.applyNativeDiscard(scope, value) };
1360
- }
1361
- nativeKeepName(checkout, name) {
1362
- const keep = basename(checkout.path) + '.keep';
1363
- return name === keep || name.startsWith(keep + '.') && /^[1-9][0-9]*$/.test(name.slice(keep.length + 1));
1364
- }
1365
- async applyNativeDiscard(scope, value) {
1366
- const context = this.workspace.context(scope), checkout = context.nativeCheckout;
1367
- if (value.modified !== false)
1368
- fail('unknown', 'Native discard did not establish an unchanged checkout.');
1369
- const next = { ...checkout, checkoutId: Number(value.checkoutId), baseVersion: version(value.baseVersion) };
1370
- delete next.conflict;
1371
- const shared = await this.serverView(scope.target, next.baseVersion, next.fileId), snapshot = await this.nativeReceipt(next, object(value.saved));
1372
- this.observeNativeShared(scope.target, shared);
1373
- this.workspace.saveContext(scope, context.generation, { nativeCheckout: next, state: 'stopped', baseRevision: next.baseVersion, baseSnapshot: shared.snapshot, workingSnapshot: snapshot, scalars: [], complexChanges: [], viewEpoch: (context.viewEpoch ?? 0) + 1 });
1374
- return { baseRevision: next.baseVersion, retainedKeepFile: String(value.retainedKeepFile) };
1375
- }
1376
- async open(scope, request) {
1377
- const context = this.workspace.context(scope), target = this.workspace.target(scope.target);
1378
- if (this.workspace.unresolved(scope).some(intent => intent.id !== request && intent.operation !== 'ghidra.open'))
1379
- failUnresolved(this.workspace, scope, 'This context retains an unresolved operation.');
1380
- let binding, unfinished = false;
1381
- ({ binding, unfinished } = await this.lastWorker(context.id, { ...context, ...scope }));
1382
- if (binding)
1383
- await this.workerReceipt(binding, context.id, { ...context, ...scope });
1384
- let stopped = false;
1385
- if (binding) {
1386
- try {
1387
- const receipt = object(JSON.parse(await readFile(join(binding.root, 'stopped.json'), 'utf8')));
1388
- stopped = receipt.pid === binding.pid && receipt.tokenSecret === binding.tokenSecret && await this.workerEnded(binding);
1389
- }
1390
- catch (error) {
1391
- if (error.code !== 'ENOENT')
1392
- throw error;
1393
- }
1394
- }
1395
- if (context.workingSnapshot && !context.nativeCheckout)
1396
- fail('migration', 'This context contains legacy detached work; run ghidra migrate --target ' + scope.target + ' --dry-run, then ghidra migrate --target ' + scope.target + '. Its data is retained.');
1397
- if (binding && unfinished && !stopped && alive(binding.pid) && !await this.retiredWorker(binding))
1398
- fail('busy', 'A worker of this context has not finished starting; it is retained.');
1399
- // A leased worker is held before any use. One built for another runtime is asked to stop; one that is
1400
- // retiring or already stopped by itself is settled, and its saved project is reopened below.
1401
- let ended = false, silent = false;
1402
- const live = () => !ended && alive(binding.pid);
1403
- if (binding && !unfinished && !stopped && binding.leasePort && binding.context === context.id) {
1404
- // A worker whose helper classes come from another build of this package is replaced like one of another runtime:
1405
- // its work is saved, and its classes would answer by the rules of that build.
1406
- const previous = binding.runtimeFingerprint !== this.inputs.fingerprint || binding.helpers !== await helperSourcesKey().catch(() => binding.helpers);
1407
- if (alive(binding.pid) && previous && !await this.workerGone(binding) && !await this.retireWorker(binding, 'runtime_changed'))
1408
- fail('busy', 'A context worker of the previous runtime is still running a command; retry after it ends.');
1409
- // A lease that stays silent says nothing about the worker: the checks below ask the worker itself, and one
1410
- // that does not answer either is retired there.
1411
- const held = await this.workerGone(binding) ? 'gone' : await this.holdLease(binding).catch(error => {
1412
- if (!(error instanceof CliError) || object(error.result ?? {}).lease !== 'silent')
1413
- throw error;
1414
- silent = true;
1415
- return 'held';
1416
- });
1417
- if (held !== 'held') {
1418
- if (held === 'retiring' && !await this.awaitExit(binding))
1419
- fail('busy', 'A context worker that is stopping after its idle time has not exited yet; retry the command.');
1420
- ended = true;
1421
- if (await this.settleRetired(binding))
1422
- stopped = true;
1423
- }
1424
- }
1425
- // A worker left parked (its owner ended mid-merge) holds no project: stop it and relaunch below.
1426
- if (binding && !unfinished && !stopped && live() && await this.parkedMarker(binding)) {
1427
- await this.stopParked(binding);
1428
- stopped = true;
1429
- }
1430
- if (binding && !unfinished && !stopped && live() && ((binding.viewEpoch ?? 0) !== (context.viewEpoch ?? 0) ||
1431
- binding.baseRevision !== context.baseRevision && context.baseRevision !== undefined)) {
1432
- await this.stopRecord(await this.verified(binding, target), true, false, 'view_replaced');
1433
- stopped = true;
1434
- }
1435
- if (binding && !unfinished && !stopped && live()) {
1436
- if (binding.context !== context.id)
1437
- fail('binding', 'Native process belongs to a different working context.');
1438
- try {
1439
- await this.verified(binding, target);
1440
- // The worker answers after all: it is used only once it is held.
1441
- if (silent && await this.holdLease(binding) !== 'held')
1442
- fail('busy', 'A context worker that is stopping after its idle time has not exited yet; retry the command.');
1443
- return context;
1444
- }
1445
- catch (error) {
1446
- if (!await this.retireUnresponsive(scope, binding, error))
1447
- throw error;
1448
- stopped = true;
1449
- }
1450
- }
1451
- if (binding?.mode === 'gui')
1452
- await this.debuggerReleased(binding);
1453
- if (!context.nativeCheckout)
1454
- await this.model(target);
1455
- if (binding && !stopped && !live() && !await this.settleRetired(binding))
1456
- await recordLifecycle(this.workspace, context.id, { at: new Date().toISOString(), event: 'stop', reason: 'unknown', pid: binding.pid });
1457
- if (binding && (stopped || unfinished || !live())) {
1458
- if (binding.context !== context.id || binding.target !== scope.target)
1459
- fail('binding', 'Retired native credential belongs to another context.');
1460
- await releaseStoppedContextCredential(this.directory(), binding, this.c.secrets, alive, () => this.retiredWorker(binding));
1461
- if (unfinished)
1462
- await this.retainStartedWorker(binding);
1463
- }
1464
- let current = this.workspace.context(scope);
1465
- if (current.nativeCheckout?.state === 'verified') {
1466
- await this.dropNative(scope);
1467
- current = this.workspace.context(scope);
1468
- }
1469
- if (!current.nativeCheckout || current.nativeCheckout.state === 'dropped')
1470
- current = await this.createNative(scope);
1471
- // A first open may replace the receipt; only that write advances the expected generation.
1472
- const started = await this.privateCopy(current);
1473
- return this.workspace.saveContext(scope, started?.generation ?? current.generation, { state: 'ready' });
1474
- }
1475
- async retireUnresponsive(scope, binding, error) {
1476
- const failure = error;
1477
- if (!['coordinator.timeout', 'coordinator.transport'].includes(failure.code ?? '') || failure.result?.operation !== '/mcp/instance_info' ||
1478
- binding.mode !== 'headless' || !binding.toolProcessId)
1479
- return false;
1480
- const context = this.workspace.context(scope);
1481
- if (!context.workingSnapshot || context.debugger?.connected || this.workspace.activePublication(scope.target) ||
1482
- this.workspace.unresolved(scope).some(intent => intent.operation !== 'ghidra.open'))
1483
- return false;
1484
- // Verify acknowledged bytes before retiring anything. Unknown mutations stay blocked.
1485
- await this.workspace.artifacts.verify(context.workingSnapshot);
1486
- const row = await processStatus(this.c.appArguments.AppDataDirectory, binding.toolProcessId, r => verifyGhidraProcess(r, this.c));
1487
- if (row.state !== 'running' || row.pid !== binding.pid || row.tool !== 'ghidra' || row.role !== 'context' || row.session !== scope.session ||
1488
- row.target !== scope.target || row.installation !== binding.runtimeFingerprint || row.metadata?.contextRoot !== binding.root)
1489
- return false;
1490
- await terminateProcess(this.c.appArguments.AppDataDirectory, binding.toolProcessId, true, r => verifyGhidraProcess(r, this.c));
1491
- await this.stopRecord({ binding, http: new HttpBridge(binding.endpoint) }, false, true, 'backend_unresponsive');
1492
- return true;
1493
- }
1494
- async selected(scope) {
1495
- const context = this.workspace.context(scope);
1496
- const binding = JSON.parse(await readFile(join(this.directory(), 'context', context.id, 'current.json'), 'utf8'));
1497
- if (binding.context !== context.id)
1498
- fail('binding', 'Context process binding changed.');
1499
- // A marked worker's project may be closing: nothing runs in it until it is reopened or stopped.
1500
- if (await this.parkedMarker(binding))
1501
- fail('busy', 'This context worker is being reopened or stopped after a native operation; run the command again.');
1502
- return this.verified(binding, this.workspace.target(scope.target));
1503
- }
1504
- async observation(scope) {
1505
- const record = await this.selected(scope);
1506
- return { ...object(await this.call(scope, '/research_view')), incarnation: digest({ pid: record.binding.pid, root: record.binding.root }) };
1507
- }
1508
- async inspectObservation(scope) {
1509
- const record = await this.selected(scope);
1510
- const view = researchView(await record.http.call('/insight/research-view/v1', { program: record.binding.program }));
1511
- return { ...view, incarnation: digest({ pid: record.binding.pid, root: record.binding.root }) };
1512
- }
1513
- async inlineScript(scope, parameters, requestId) {
1514
- const record = await this.selected(scope);
1515
- // Agent-supplied code may leave threads or domain objects behind: this JVM is never parked, only stopped.
1516
- await durable(join(record.binding.root, 'agent-code.json'), { schema: 1, pid: record.binding.pid, tokenSecret: record.binding.tokenSecret });
1517
- return runInline(record.http, record.binding.program, record.binding.root, parameters, requestId);
1518
- }
1519
- async call(scope, operation, parameters = {}) {
1520
- if (Object.hasOwn(parameters, 'program'))
1521
- fail('invalid', 'Program routing is owned by the session and target selectors.');
1522
- if (operation === '/set_variables' && typeof parameters.variables !== 'string')
1523
- parameters = { ...parameters, variables: JSON.stringify(parameters.variables) };
1524
- if (operation === '/create_function_signature' && typeof parameters.parameters !== 'string')
1525
- parameters = { ...parameters, parameters: JSON.stringify(parameters.parameters) };
1526
- const record = await this.selected(scope);
1527
- if (operation.startsWith('/sdk/')) {
1528
- if (operation === '/sdk/type-archive-import') {
1529
- const root = join(record.binding.root, 'sdk-archives', randomUUID());
1530
- await mkdir(root, { recursive: true, mode: 0o700 });
1531
- const path = join(root, 'input.gdt');
1532
- await link(await this.workspace.artifacts.verify(parameters.archive), path);
1533
- parameters = { ...parameters, input_path: path };
1534
- }
1535
- return nativeQuery(record.http, record.binding.program, operation, parameters, sdkWrites.has(operation));
1536
- }
1537
- if (nativeQueries.has(operation))
1538
- return nativeQuery(record.http, record.binding.program, operation, parameters);
1539
- if (operation === '/set_function_prototype' && parameters.calling_convention === 'default') {
1540
- const validation = object(await nativeQuery(record.http, record.binding.program, '/validate_function_prototype', {
1541
- function: parameters.function_address, prototype: parameters.prototype, calling_convention: 'default'
1542
- }));
1543
- if (validation.valid !== true)
1544
- fail('invalid', 'Prototype or default convention could not be resolved by Ghidra.');
1545
- parameters = { ...parameters, calling_convention: object(validation.signature).calling_convention };
1546
- }
1547
- if (operation === '/apply_function_documentation') {
1548
- return record.http.script(record.binding.program, 'InsightApplyDocumentation', Buffer.from(JSON.stringify(parameters.json_body), 'utf8').toString('base64'));
1549
- }
1550
- if (operation === '/configure_analyzer' && (this.inputs.extensionRoots?.length ?? 0) > 0) {
1551
- // A packed program need not persist disabled/default analyzer option registrations.
1552
- // Register this JVM's actual applicable extension analyzers before the pinned handler's
1553
- // Options.contains check. The surrounding program request already owns its journal.
1554
- const name = 'InsightAnalyzerOptions_' + randomUUID().replaceAll('-', '');
1555
- const code = `import ghidra.app.script.GhidraScript;
1556
- public class ${name} extends GhidraScript {public void run(){ghidra.app.plugin.core.analysis.AutoAnalysisManager.getAnalysisManager(currentProgram).initializeOptions();println("INSIGHT_ANALYZER_OPTIONS_READY");}}`;
1557
- const initialized = object(await record.http.call('/run_script_inline', { program: record.binding.program, code }));
1558
- if (initialized.success !== true || typeof initialized.console_output !== 'string' || !initialized.console_output.includes('INSIGHT_ANALYZER_OPTIONS_READY'))
1559
- fail('partial', 'Installed analyzer option registration could not be established.');
1560
- }
1561
- if (operation === '/run_ghidra_script') {
1562
- // An agent-selected script is agent code: this JVM is never parked afterwards.
1563
- await durable(join(record.binding.root, 'agent-code.json'), { schema: 1, pid: record.binding.pid, tokenSecret: record.binding.tokenSecret });
1564
- const script = String(parameters.script_name), path = await scriptPath(this.inputs.ghidraHome, record.binding.root, script, this.inputs.extensionRoots);
1565
- const value = object(await record.http.call(operation, { ...parameters, script_name: path, program: record.binding.program }));
1566
- delete value.script_path;
1567
- value.script_name = script;
1568
- return value;
1569
- }
1570
- if (operation === '/clone_data_type') {
1571
- // The pinned handler calls clone(manager), which can return the source itself.
1572
- // copy(manager) preserves that source while creating an independent type.
1573
- const name = 'InsightCopyType_' + randomUUID().replaceAll('-', '');
1574
- const code = `import ghidra.app.script.GhidraScript;
1575
- import ghidra.program.model.data.*;
1576
- public class ${name} extends GhidraScript {
1577
- public void run() throws Exception {
1578
- String[] args=getScriptArgs();
1579
- String original=new String(java.util.Base64.getDecoder().decode(args[0]),java.nio.charset.StandardCharsets.UTF_8);
1580
- String desired=new String(java.util.Base64.getDecoder().decode(args[1]),java.nio.charset.StandardCharsets.UTF_8);
1581
- DataTypeManager manager=currentProgram.getDataTypeManager();DataType source=null;
1582
- var types=manager.getAllDataTypes();while(types.hasNext()){DataType value=types.next();if(value.getName().equals(original)||value.getPathName().equals(original)){if(source!=null)throw new IllegalArgumentException("Ambiguous source type");source=value;}}
1583
- if(source==null)throw new IllegalArgumentException("Source type not found");
1584
- int transaction=currentProgram.startTransaction("Copy data type");boolean committed=false;
1585
- try {DataType copied=source.copy(manager);if(copied==source)throw new IllegalStateException("Copy reused its source");copied.setName(desired);
1586
- manager.addDataType(copied,DataTypeConflictHandler.REPLACE_HANDLER);committed=true;}
1587
- finally {currentProgram.endTransaction(transaction,committed);}
1588
- println("insight-copy-type:completed");
1589
- }
1590
- }`;
1591
- return record.http.call('/run_script_inline', { program: record.binding.program, code,
1592
- args: [parameters.source_type, parameters.new_name].map(value => Buffer.from(text(value, 512), 'utf8').toString('base64')).join(' ') });
1593
- }
1594
- const descriptor = await record.http.descriptor(operation);
1595
- return record.http.call(operation, { ...parameters, ...(descriptor.params.some(p => p.name === 'program') ? { program: record.binding.program } : {}) });
1596
- }
1597
- async saved(scope) { return this.capture(await this.selected(scope)); }
1598
- async scripts(scope, filter, limit, offset) {
1599
- const record = await this.selected(scope);
1600
- return scriptInventory(this.inputs.ghidraHome, record.binding.root, filter, limit, offset, this.inputs.extensionRoots);
1601
- }
1602
- async inspect(snapshot, parameters) {
1603
- const root = join(this.directory(), 'inspection', randomUUID());
1604
- await mkdir(root, { recursive: true, mode: 0o700 });
1605
- if (parameters.kind === 'sdk' && parameters.operation === 'type-archive-import') {
1606
- const p = object(parameters.parameters), path = join(root, 'input.gdt');
1607
- await link(await this.workspace.artifacts.verify(p.archive), path);
1608
- parameters = { ...parameters, parameters: { ...p, input_path: path } };
1609
- }
1610
- const request = join(root, 'request.json');
1611
- await durable(request, parameters);
1612
- if (snapshot.kind === 'native')
1613
- return object(await this.inspectNative(snapshot, 'inspect', { parameters }));
1614
- const result = await this.server().inspect(await this.workspace.artifacts.verify(snapshot), request);
1615
- return object(result.value);
1616
- }
1617
- /** Full exports are explicit consumers (cross-program/VT/export/archive), never save/reopen/publication. */
1618
- async snapshotFile(snapshot) {
1619
- if (snapshot.kind !== 'native')
1620
- return this.workspace.artifacts.verify(snapshot);
1621
- const saved = object(JSON.parse(await readFile(await this.workspace.artifacts.verify(snapshot), 'utf8'))), root = join(saved.source === 'checkout' ? text(object(saved.checkout).root, 4096) : this.directory(), 'explicit-exports', randomUUID());
1622
- await mkdir(root, { recursive: true, mode: 0o700 });
1623
- const output = join(root, 'program.gzf');
1624
- if (saved.source === 'server') {
1625
- const binding = await this.server().ensure();
1626
- if (saved.origin !== binding.origin || saved.repository !== binding.repository)
1627
- fail('binding', 'Explicit native export binding changed.');
1628
- const value = await this.server().nativeRead(binding, { ...saved, operation: 'export', output });
1629
- if (value.state !== 'verified')
1630
- fail('binding', 'Exact native server export failed.');
1631
- }
1632
- else if (saved.source === 'checkout') {
1633
- const checkout = object(saved.checkout), context = this.workspace.contextById(checkout.context);
1634
- if (context.nativeCheckout?.root !== checkout.root || context.nativeCheckout.checkoutId !== checkout.checkoutId || context.nativeCheckout.state !== 'active')
1635
- fail('binding', 'Explicit export requires the original active native view.');
1636
- if (await this.closed(context)) {
1637
- const value = await this.nativeOperation(context.nativeCheckout, 'export', { fingerprint: saved.fingerprint, output });
1638
- if (value.state !== 'ready')
1639
- fail('save', 'Saved native export failed.');
1640
- }
1641
- else {
1642
- const record = await this.selected(context);
1643
- await this.nativeView(record, { operation: 'fingerprint', expected: saved.fingerprint });
1644
- const exported = object(await record.http.call('/export_program', { program_name: record.binding.program, output_dir: root, output_name: 'program.gzf' }));
1645
- if (exported.success !== true)
1646
- fail('save', 'Explicit native export was not acknowledged.');
1647
- await this.nativeView(record, { operation: 'fingerprint', expected: saved.fingerprint });
1648
- }
1649
- }
1650
- else
1651
- fail('binding', 'Unknown native export source.');
1652
- return this.workspace.artifacts.verify(await this.captureExport(output));
1653
- }
1654
- async removePeer(record, path) {
1655
- // A cancelled invocation must still release its verified owned temporary program.
1656
- const cleanup = this.fork({ ...this.c, signal: new AbortController().signal });
1657
- const checked = await cleanup.verified(record.binding, this.workspace.target(record.binding.target));
1658
- const closed = object(await checked.http.call('/close_program', { name: path, save: false }));
1659
- if (closed.success !== true)
1660
- fail('binding', 'Owned cross-target snapshot could not be closed.');
1661
- const removed = object(await checked.http.call('/delete_file', { filePath: path }));
1662
- if (removed.success !== true)
1663
- fail('binding', 'Owned cross-target snapshot could not be removed.');
1664
- }
1665
- async reconcilePeers(record) {
1666
- for (const stage of await peerStages(record.binding.root, record.binding)) {
1667
- if ('reason' in stage)
1668
- fail('binding', stage.reason);
1669
- if (stage.receipt.state === 'preparing')
1670
- await this.removePeer(record, stage.receipt.path);
1671
- await this.completePeer(record, stage.receipt.path.slice(1));
1672
- }
1673
- }
1674
- async completePeer(record, name) {
1675
- const stage = await peerStage(record.binding.root, name, record.binding);
1676
- if ('reason' in stage)
1677
- fail('binding', stage.reason);
1678
- if (stage.receipt.state !== 'closed')
1679
- await durable(join(stage.folder, 'receipt.json'), { ...stage.receipt, state: 'closed' });
1680
- const context = this.workspace.contextById(record.binding.context);
1681
- if (this.workspace.unresolved(context).length || this.workspace.uncertainOutcome(context) || this.workspace.checkoutReferenced(context, record.binding.root))
1682
- return;
1683
- if (stage.input)
1684
- await unlink(stage.input);
1685
- }
1686
- async withPeer(record, snapshot, action, reconcile = true) {
1687
- if (reconcile)
1688
- await this.reconcilePeers(record);
1689
- const name = '__insight_peer_' + randomUUID().replaceAll('-', ''), path = '/' + name, folder = join(record.binding.root, 'cross-peer', name);
1690
- await mkdir(folder, { recursive: true, mode: 0o700 });
1691
- const file = join(folder, 'input.gzf');
1692
- await link(await this.snapshotFile(snapshot), file);
1693
- await durable(join(folder, 'receipt.json'), { path, target: record.binding.target, context: record.binding.context, state: 'preparing' });
1694
- try {
1695
- const imported = object(await record.http.call('/import_program', { gzf_path: file, target_folder: '/', target_name: name, overwrite: false }));
1696
- if (imported.success !== true)
1697
- fail('binding', 'Cross-target snapshot import was not acknowledged.');
1698
- const opened = object(await record.http.call('/open_program', { path }));
1699
- if (opened.path !== path)
1700
- fail('binding', 'Cross-target snapshot opened another program.');
1701
- return await action(path);
1702
- }
1703
- finally {
1704
- await this.removePeer(record, path);
1705
- await this.completePeer(record, name);
1706
- }
1707
- }
1708
- async pair(selected, other, snapshot, operation, parameters) {
1709
- const record = await this.selected(selected);
1710
- return this.withPeer(record, snapshot, async (peer) => {
1711
- if (operation === '/sdk/changes')
1712
- return nativeQuery(record.http, record.binding.program, operation, { ...parameters, peer_program: peer });
1713
- let routing;
1714
- if (operation === '/diff_functions')
1715
- routing = { program_a: record.binding.program, program_b: peer };
1716
- else if (operation === '/compare_programs_documentation')
1717
- routing = { program: record.binding.program };
1718
- else if (['/bulk_fuzzy_match', '/find_similar_functions_fuzzy'].includes(operation))
1719
- routing = { source_program: record.binding.program, target_program: peer };
1720
- else
1721
- fail('invalid', 'Unsupported cross-target comparison.');
1722
- const value = object(await record.http.call(operation, { ...parameters, ...routing }));
1723
- if (operation === '/compare_programs_documentation') {
1724
- if (!Array.isArray(value.programs))
1725
- fail('partial', 'Comparison omitted its programs.');
1726
- value.programs = value.programs.map(raw => {
1727
- const row = object(raw), who = row.path === record.binding.program ? selected : row.path === peer ? other : undefined;
1728
- if (!who)
1729
- fail('binding', 'Comparison included an undeclared context.');
1730
- const { name, path, is_current, ...counts } = row;
1731
- return { ...who, label: this.workspace.target(who.target).name, ...counts };
1732
- });
1733
- }
1734
- return logicalPrograms(value, new Map([[record.binding.program, selected], ['program', selected], [peer, other], [peer.slice(1), other]]));
1735
- });
1736
- }
1737
- async transfer(selected, source, dryRun) {
1738
- const record = await this.selected(selected);
1739
- return this.withPeer(record, source, peer => record.http.call('/merge_program_documentation', { source: peer, target: record.binding.program, dry_run: dryRun }));
1740
- }
1741
- async transferCheck(selected, source, candidate) {
1742
- const record = await this.selected(selected);
1743
- return this.withPeer(record, source, from => this.withPeer(record, candidate, to => record.http.call('/merge_program_documentation', { source: from, target: to, dry_run: true }), false));
1744
- }
1745
- async mode(scope, mode) {
1746
- const record = await this.selected(scope);
1747
- if (record.binding.mode === mode)
1748
- return;
1749
- const context = this.workspace.context(scope), snapshot = await this.capture(record);
1750
- const debuggerState = record.binding.mode === 'gui' && context.debugger?.traces.length ? await this.debuggerSaved(scope) : context.debugger;
1751
- const complexChanges = await this.debuggerMetadataChanges(context, snapshot);
1752
- this.workspace.saveContext(scope, context.generation, { workingSnapshot: snapshot, complexChanges, ...(debuggerState ? { debugger: { ...debuggerState, connected: false, traces: debuggerState.traces.map(trace => ({ ...trace, connected: false })) } } : {}) });
1753
- await this.stopRecord(record, true, false, 'mode_changed');
1754
- if (mode === 'headless') {
1755
- await this.privateCopy(this.workspace.context(scope));
1756
- return;
1757
- }
1758
- const gui = await this.launch(record.binding.root, this.workspace.target(scope.target), 'context', record.binding.program, 'gui', context.id);
1759
- gui.binding.baseRevision = record.binding.baseRevision;
1760
- gui.binding.viewEpoch = record.binding.viewEpoch;
1761
- await durable(join(gui.binding.root, 'process.json'), gui.binding);
1762
- await gui.http.call('/open_program', { path: gui.binding.program });
1763
- await this.verified(gui.binding, this.workspace.target(scope.target));
1764
- await durable(join(this.directory(), 'context', context.id, 'current.json'), gui.binding);
1765
- }
1766
- async project(operation, parameters) { return this.server().project(operation, parameters); }
1767
- async ui(scope, operation, p) {
1768
- const record = await this.selected(scope);
1769
- await this.reconcilePeers(record);
1770
- if (operation === 'plugins_list' || operation === 'plugins_set') {
1771
- if (record.binding.mode !== 'gui')
1772
- fail('configuration', 'Managed plugins require the owned GUI context.');
1773
- const base = 'InsightPlugins', name = base + '_' + randomUUID().replaceAll('-', ''), source = await readFile(new URL('../../references/native/' + base + '.java', import.meta.url), 'utf8');
1774
- const result = object(await record.http.call('/run_script_inline', { program: record.binding.program, code: source.replace('class ' + base + ' ', `class ${name} `), args: Buffer.from(JSON.stringify({ ...p, operation: operation === 'plugins_list' ? 'list' : 'set' })).toString('base64') }));
1775
- const lines = typeof result.console_output === 'string' ? result.console_output.split(/\r?\n/).filter(line => line.includes('INSIGHT_PLUGINS:')) : [];
1776
- if (result.success !== true || lines.length !== 1)
1777
- fail('partial', 'Managed plugin effect was not established.');
1778
- return object(JSON.parse(lines[0].slice(lines[0].indexOf('INSIGHT_PLUGINS:') + 16)));
1779
- }
1780
- const paths = { cursor: '/get_ui_cursor', tools: '/tool/running_tools', goto: '/tool/goto_address', prompt_policy: '/prompt_policy' }, path = paths[operation];
1781
- if (!path)
1782
- fail('invalid', 'Unsupported UI operation.');
1783
- const target = this.workspace.target(scope.target), metadata = await this.source(record, target), name = text(metadata.program_name);
1784
- const value = await record.http.call(path, operation === 'cursor' ? { type: 'all' } : p);
1785
- return uiResult(operation, p, value, scope, record.binding.program, target.name, name);
1786
- }
1787
- async archivePayloads(scope, p) {
1788
- const record = await this.selected(scope);
1789
- const result = object(await record.http.script(record.binding.program, 'InsightArchivePayloads', Buffer.from(JSON.stringify(p)).toString('base64')));
1790
- if (result.success !== true || typeof result.console_output !== 'string')
1791
- fail('partial', 'Archive payload preparation failed.');
1792
- const lines = result.console_output.split(/\r?\n/).filter(line => line.includes('INSIGHT_ARCHIVE_PAYLOADS '));
1793
- if (lines.length !== 1)
1794
- fail('partial', 'Archive payload preparation omitted its exact result.');
1795
- return object(JSON.parse(lines[0].slice(lines[0].indexOf('INSIGHT_ARCHIVE_PAYLOADS ') + 'INSIGHT_ARCHIVE_PAYLOADS '.length)));
1796
- }
1797
- async debuggerStart(scope) {
1798
- await this.debuggerHelper(scope, 'Start', 'INSIGHT_DEBUGGER_READY');
1799
- const saved = this.workspace.context(scope).debugger;
1800
- if (saved?.traces.length) {
1801
- const record = await this.selected(scope), marker = join(record.binding.root, 'traces-restored.json');
1802
- try {
1803
- const value = object(JSON.parse(await readFile(marker, 'utf8')));
1804
- if (value.pid === record.binding.pid && value.tokenSecret === record.binding.tokenSecret)
1805
- return;
1806
- }
1807
- catch (error) {
1808
- if (error.code !== 'ENOENT')
1809
- throw error;
1810
- }
1811
- const traces = await Promise.all(saved.traces.map(async (trace) => ({ id: trace.id, input: await this.workspace.artifacts.verify(trace.snapshot), snap: trace.snap, ...(trace.thread ? { thread: trace.thread } : {}) })));
1812
- await this.traceHelper(scope, { operation: 'restore', traces, ...(saved.active ? { active: saved.active } : {}) });
1813
- await durable(marker, { pid: record.binding.pid, tokenSecret: record.binding.tokenSecret });
1814
- }
1815
- }
1816
- async debuggerStop(scope) {
1817
- return this.debuggerHelper(scope, 'Stop', 'INSIGHT_DEBUGGER_STOPPED');
1818
- }
1819
- async debuggerHelper(scope, action, marker) {
1820
- const record = await this.selected(scope);
1821
- if (record.binding.mode !== 'gui')
1822
- fail('configuration', 'Debugger requires the owned GUI context.');
1823
- return this.debuggerHelperRecord(record, action, marker);
1824
- }
1825
- async debuggerHelperRecord(record, action, marker) {
1826
- const base = 'Insight' + action + 'Debugger', name = base + '_' + randomUUID().replaceAll('-', ''), source = await readFile(new URL('../../references/native/' + base + '.java', import.meta.url), 'utf8');
1827
- const result = object(await record.http.call('/run_script_inline', { program: record.binding.program, code: source.replace('class ' + base + ' ', `class ${name} `) }));
1828
- if (result.success !== true || typeof result.console_output !== 'string' || !result.console_output.includes(marker))
1829
- fail('partial', 'Owned debugger lifecycle effect was not established.');
1830
- }
1831
- async debuggerCall(scope, operation, p = {}) {
1832
- const allowed = ['launch', 'launch_offers', 'status', 'traces', 'resume', 'interrupt', 'step', 'set_breakpoint', 'remove_breakpoint', 'list_breakpoints', 'registers', 'read_memory', 'stack_trace', 'modules', 'static_to_dynamic', 'dynamic_to_static', 'write_memory', 'write_register', 'timeline', 'objects', 'object_values', 'schedule'];
1833
- if (!allowed.includes(operation) || Object.hasOwn(p, 'program'))
1834
- fail('invalid', 'Unsupported scoped debugger operation.');
1835
- const record = await this.selected(scope);
1836
- if (['write_memory', 'write_register', 'timeline', 'objects', 'object_values', 'schedule'].includes(operation))
1837
- return this.traceHelper(scope, { ...p, operation });
1838
- if (operation === 'list_breakpoints')
1839
- return (await this.traceHelper(scope, { operation: 'breakpoints' })).items;
1840
- if (['resume', 'interrupt', 'step', 'set_breakpoint', 'remove_breakpoint'].includes(operation))
1841
- await this.traceHelper(scope, { operation: 'focus' });
1842
- if (operation === 'read_memory')
1843
- await this.traceHelper(scope, { operation: 'read_memory', address: p.address, size: p.size });
1844
- const token = await this.c.secrets.require(record.binding.tokenSecret), timeout = operation === 'launch' ? (Number(p.timeout_seconds ?? 60) + 90) * 1000 : 45000;
1845
- const callerPython = process.platform === 'darwin' && operation === 'step' && p.kind === 'out' ? record.binding.debuggerPython : undefined;
1846
- if (callerPython && (dirname(callerPython) !== record.binding.root || await realpath(callerPython) !== callerPython))
1847
- fail('binding', 'Native caller Python scope changed.');
1848
- const priorCaller = callerPython ? await readCallerGoal(callerPython) : undefined;
1849
- const raw = await new HttpBridge(record.binding.endpoint, this.c.fetch, this.c.signal, token, timeout).call('/debugger/' + operation, { ...p, ...(['launch', 'launch_offers', 'static_to_dynamic'].includes(operation) ? { program: record.binding.program } : {}) });
1850
- if (callerPython) {
1851
- const goal = await readCallerGoal(callerPython);
1852
- if (goal && goal.id !== priorCaller?.id) {
1853
- const launch = object(JSON.parse(await readFile(join(record.binding.root, 'debugger-run', 'current.json'), 'utf8')));
1854
- if (goal.executable !== launch.executable || launch.context !== record.binding.context || launch.target !== scope.target)
1855
- fail('binding', 'Native caller belongs to another launch.');
1856
- await awaitCaller(callerPython, goal, this.c.signal);
1857
- }
1858
- }
1859
- const label = this.workspace.target(scope.target).name;
1860
- if (operation === 'modules' && Array.isArray(raw))
1861
- return raw.map(value => { const row = object(value), { path, ...rest } = row; return { ...rest, ...(typeof row.name === 'string' && (row.name.includes(record.binding.root) || ['image', 'image.exe'].includes(row.name)) ? { name: label } : {}) }; });
1862
- if (raw && typeof raw === 'object' && !Array.isArray(raw)) {
1863
- const value = object(raw), { program, executable_path, target_description, ...rest } = value;
1864
- if (operation === 'launch') {
1865
- if (value.status !== 'launched' || executable_path !== p.executable_path || typeof value.trace_name !== 'string')
1866
- fail('binding', 'Debugger launch did not verify its staged executable.');
1867
- await this.traceHelper(scope, { operation: 'bind_new', name: value.trace_name });
1868
- }
1869
- if (program !== undefined) {
1870
- const metadata = await this.source(record, this.workspace.target(scope.target));
1871
- if (program !== metadata.program_name && program !== record.binding.program)
1872
- fail('binding', 'Debugger selected another static program.');
1873
- }
1874
- if (value.trace_name !== undefined)
1875
- rest.trace_name = label;
1876
- if (typeof value.module === 'string' && (value.module.includes(record.binding.root) || ['image', 'image.exe'].includes(value.module)))
1877
- rest.module = label;
1878
- return rest;
1879
- }
1880
- return raw;
1881
- }
1882
- async traceHelper(scope, p) {
1883
- const record = await this.selected(scope), context = this.workspace.context(scope), name = 'InsightTraceState_' + randomUUID().replaceAll('-', '');
1884
- const source = await readFile(new URL('../../references/native/InsightTraceState.java', import.meta.url), 'utf8');
1885
- const args = Buffer.from(JSON.stringify({ ...p, target: scope.target, context: context.id, owned_root: record.binding.root })).toString('base64');
1886
- const result = object(await record.http.call('/run_script_inline', { program: record.binding.program, code: source.replace('class InsightTraceState ', `class ${name} `), args }));
1887
- const output = result.console_output;
1888
- if (result.success !== true || typeof output !== 'string')
1889
- fail('partial', 'Trace state action did not complete.');
1890
- const lines = output.split(/\r?\n/).filter(line => line.includes('INSIGHT_TRACE_STATE '));
1891
- if (lines.length !== 1)
1892
- fail('partial', 'Trace action omitted its exact result marker.');
1893
- return object(JSON.parse(lines[0].slice(lines[0].indexOf('INSIGHT_TRACE_STATE ') + 'INSIGHT_TRACE_STATE '.length)));
1894
- }
1895
- async debuggerSaved(scope) {
1896
- const record = await this.selected(scope), context = this.workspace.context(scope);
1897
- let value, output = '';
1898
- for (let attempt = 0; attempt < 12; attempt++) {
1899
- output = join(record.binding.root, 'trace-exports', randomUUID());
1900
- await mkdir(output, { recursive: true, mode: 0o700 });
1901
- try {
1902
- value = await this.traceHelper(scope, { operation: 'checkpoint', output });
1903
- break;
1904
- }
1905
- catch (error) {
1906
- if (attempt === 11 || !String(error.message).includes('Unable to lock due to active transaction'))
1907
- throw error;
1908
- await delay(150);
1909
- }
1910
- }
1911
- if (!value || !Array.isArray(value.traces) || value.traces.length > 64)
1912
- fail('partial', 'Trace checkpoint inventory is malformed.');
1913
- const traces = [];
1914
- for (const raw of value.traces) {
1915
- const row = object(raw), traceId = text(row.id);
1916
- if (!/^trace_[a-f0-9-]{36}$/.test(traceId))
1917
- fail('binding', 'Trace checkpoint identity changed.');
1918
- const snapshot = await this.workspace.captureSnapshot(join(output, traceId + '.gzf')), observed = await this.server().traceInspect(await this.workspace.artifacts.verify(snapshot));
1919
- if (observed.id !== traceId || observed.target !== scope.target || observed.context !== context.id)
1920
- fail('binding', 'Packed trace belongs to another tool context.');
1921
- if (typeof row.snap !== 'string' || !/^\d+$/.test(row.snap) || !Number.isSafeInteger(observed.modules) || !Number.isSafeInteger(observed.threads))
1922
- fail('partial', 'Packed trace metadata is incomplete.');
1923
- if (typeof row.connected !== 'boolean')
1924
- fail('partial', 'Trace connection state is absent.');
1925
- if (row.thread !== undefined && (typeof row.thread !== 'string' || !/^\d+$/.test(row.thread)))
1926
- fail('partial', 'Trace checkpoint thread identity is invalid.');
1927
- traces.push({ id: traceId, name: text(observed.name), snapshot, snap: row.snap, modules: Number(observed.modules), threads: Number(observed.threads), connected: row.connected, ...(row.thread ? { thread: String(row.thread) } : {}) });
1928
- }
1929
- const active = value.active === undefined ? undefined : text(value.active);
1930
- if (active && !traces.some(trace => trace.id === active))
1931
- fail('binding', 'Active trace is absent from its checkpoint.');
1932
- return { traces, ...(active ? { active } : {}), connected: traces.some(trace => trace.connected) };
1933
- }
1934
- async debuggerSelect(scope, trace) { await this.traceHelper(scope, { operation: 'select', id: trace }); }
1935
- async debuggerLaunch(scope, p, request) {
1936
- if (!/^q_[a-f0-9-]{36}$/.test(request))
1937
- fail('binding', 'Invalid internal debugger launch identity.');
1938
- const record = await this.selected(scope);
1939
- await this.debuggerReleased(record.binding);
1940
- const target = this.workspace.target(scope.target), root = join(record.binding.root, 'debugger-run', request);
1941
- await mkdir(root, { recursive: true, mode: 0o700 });
1942
- const executable = join(root, process.platform === 'win32' ? 'image.exe' : 'image');
1943
- await copyFile(await this.workspace.artifacts.verify(target.input), executable, constants.COPYFILE_EXCL);
1944
- await chmod(executable, 0o500);
1945
- const copied = await this.workspace.artifacts.capture(executable, 'input');
1946
- if (copied.id !== target.input.id)
1947
- fail('binding', 'Staged debug executable differs from the immutable target.');
1948
- const cwd = p.cwd === undefined ? root : text(p.cwd, 4096);
1949
- if (/[\r\n\0]/.test(cwd))
1950
- fail('invalid', 'Debugger working directory must be a single filesystem path.');
1951
- await durable(join(record.binding.root, 'debugger-run', 'current.json'), { request, target: scope.target, context: record.binding.context, executable, cwd, ...(p.stop_at_entry === true ? { stopAtEntry: true } : {}) });
1952
- const { stop_at_entry, ...parameters } = p;
1953
- return this.debuggerCall(scope, 'launch', { ...parameters, executable_path: executable, cwd,
1954
- ...(this.c.profile.values.debuggerPython ? { python_executable: text(this.c.profile.values.debuggerPython, 4096) } : {}),
1955
- ...(this.c.profile.values.windbgDir ? { windbg_dir: text(this.c.profile.values.windbgDir, 4096) } : {}) });
1956
- }
1957
- async projectOutcome(requestId, expected) { return this.server().projectOutcome(requestId, expected); }
1958
- async debuggerMetadata(snapshot) {
1959
- const inspect = { inspect: (artifact, parameters) => this.inspect(artifact, parameters) };
1960
- if (snapshot.kind !== 'native')
1961
- return (await debuggerProgramMetadata(inspect, snapshot));
1962
- const saved = object(JSON.parse(await readFile(await this.workspace.artifacts.verify(snapshot), 'utf8')));
1963
- if (saved.engine !== this.nativeEngine || !['checkout', 'server'].includes(String(saved.source)))
1964
- fail('binding', 'Saved debugger metadata view uses a different engine or source.');
1965
- if (saved.debuggerMetadata !== undefined) {
1966
- if (typeof saved.debuggerMetadata !== 'string' || !/^[a-f0-9]{64}$/.test(saved.debuggerMetadata))
1967
- fail('binding', 'Saved debugger metadata witness is malformed.');
1968
- return saved.debuggerMetadata;
1969
- }
1970
- if (saved.source === 'server')
1971
- return (await debuggerProgramMetadata(inspect, snapshot));
1972
- // Older receipts did not retain this witness. Compare actual metadata against their immutable
1973
- // server base once, rather than interpreting mutable checkout bytes as a historical copy.
1974
- const checkout = object(saved.checkout), context = this.workspace.contextById(text(checkout.context));
1975
- if (context.nativeCheckout?.root !== checkout.root || context.baseSnapshot?.kind !== 'native')
1976
- fail('binding', 'Previous debugger metadata has no immutable witness.');
1977
- const base = object(JSON.parse(await readFile(await this.workspace.artifacts.verify(context.baseSnapshot), 'utf8')));
1978
- if (base.source !== 'server' || base.fileId !== saved.fileId || base.version !== saved.version || base.origin !== checkout.origin || base.repository !== checkout.repository)
1979
- fail('binding', 'Previous debugger metadata base changed.');
1980
- return (await debuggerProgramMetadata(inspect, context.baseSnapshot));
1981
- }
1982
- async debuggerMetadataChanges(context, snapshot) {
1983
- if (!context.debugger?.traces.length || !context.workingSnapshot)
1984
- return context.complexChanges;
1985
- return await debuggerProgramMetadata(this, context.workingSnapshot) !== await debuggerProgramMetadata(this, snapshot) ? [...context.complexChanges, 'debugger-metadata-' + randomUUID()] : context.complexChanges;
1986
- }
1987
- async close(scope) {
1988
- const context = this.workspace.context(scope), record = await this.selected(scope), snapshot = await this.capture(record);
1989
- const debuggerState = record.binding.mode === 'gui' && context.debugger?.traces.length ? await this.debuggerSaved(scope) : context.debugger;
1990
- const complexChanges = await this.debuggerMetadataChanges(context, snapshot);
1991
- this.workspace.saveContext(scope, context.generation, { state: 'stopped', workingSnapshot: snapshot, complexChanges, ...(debuggerState ? { debugger: { ...debuggerState, connected: false, traces: debuggerState.traces.map(trace => ({ ...trace, connected: false })) } } : {}) });
1992
- await this.stopRecord(record, true, true, 'explicit_close');
1993
- }
1994
- async workerEnded(binding) { return !alive(binding.pid) || await this.retiredWorker(binding); }
1995
- async retainStartedWorker(binding) {
1996
- if (!await this.workerEnded(binding))
1997
- fail('busy', 'The interrupted start is not proved stopped; its receipt is retained.');
1998
- const processReceipt = await readFile(join(binding.root, 'process.json'), 'utf8');
1999
- if (stable(JSON.parse(processReceipt)) !== stable(binding))
2000
- fail('binding', 'Interrupted start receipt changed.');
2001
- let stopped;
2002
- try {
2003
- stopped = await readFile(join(binding.root, 'stopped.json'), 'utf8');
2004
- }
2005
- catch (error) {
2006
- if (error.code !== 'ENOENT')
2007
- throw error;
2008
- }
2009
- const directory = join(binding.root, 'worker-history');
2010
- await mkdir(directory, { recursive: true, mode: 0o700 });
2011
- await durable(join(directory, digest(binding) + '.json'), { schema: 1, process: processReceipt, ...(stopped ? { stopped } : {}) });
2012
- }
2013
- workerShape(binding, context, scope, historicalLegacy = false) {
2014
- let endpoint;
2015
- try {
2016
- endpoint = new URL(binding.endpoint);
2017
- }
2018
- catch {
2019
- fail('binding', 'Context process receipt changed.');
2020
- }
2021
- let selected = scope;
2022
- if (!selected)
2023
- try {
2024
- selected = this.workspace.contextById?.(context);
2025
- }
2026
- catch (error) {
2027
- if (error.code !== 'coordinator.notFound')
2028
- throw error;
2029
- }
2030
- const checkout = selected?.nativeCheckout;
2031
- const legacy = historicalLegacy && checkout && binding.program !== checkout.path &&
2032
- (binding.program === 'program' || binding.program === '/program');
2033
- const program = checkout ? binding.program === checkout.path || !!legacy :
2034
- binding.program === 'program' || binding.program === '/program' || binding.program === programPath(binding.target);
2035
- if (!Number.isSafeInteger(binding.pid) || binding.pid < 1 || binding.kind !== 'context' || binding.context !== context ||
2036
- typeof binding.root !== 'string' || typeof binding.target !== 'string' || !binding.target || !program ||
2037
- !['headless', 'gui'].includes(binding.mode) || typeof binding.runtimeFingerprint !== 'string' || !binding.runtimeFingerprint ||
2038
- !/^context-[a-f0-9-]{36}$/.test(binding.tokenSecret) || endpoint.protocol !== 'http:' || endpoint.hostname !== '127.0.0.1' || !endpoint.port ||
2039
- endpoint.username || endpoint.password || endpoint.pathname !== '/' || endpoint.search || endpoint.hash ||
2040
- selected && (binding.target !== selected.target || binding.session !== undefined && binding.session !== selected.session))
2041
- fail('binding', 'Context process receipt changed.');
2042
- return legacy ? checkout : undefined;
2043
- }
2044
- async workerReceipt(binding, context, scope, historicalLegacy = false) {
2045
- const legacy = this.workerShape(binding, context, scope, historicalLegacy);
2046
- const root = await realpath(binding.root);
2047
- if (!ownedDirectory(root, this.directory(), ['context', context, basename(root)]) || (await lstat(join(root, 'process.json'))).isSymbolicLink() ||
2048
- stable(JSON.parse(await readFile(join(root, 'process.json'), 'utf8'))) !== stable(binding))
2049
- fail('binding', 'Context process receipt changed.');
2050
- if (legacy) {
2051
- // Migration retains legacy views; none can stand in for the active native root.
2052
- if (await exists(legacy.root) && sameDirectory(root, legacy.root))
2053
- fail('binding', 'Context process receipt changed.');
2054
- if (!await this.workerEnded(binding))
2055
- fail('busy', 'Retained legacy worker is not proved stopped after migration.');
2056
- }
2057
- return !!legacy;
2058
- }
2059
- /** Discover interrupted starts independently of the ready pointer. Every other retained root must
2060
- * be verifiably ended; no live or ambiguous start is adopted or overwritten by a replacement. */
2061
- async lastWorker(context, scope) {
2062
- const parent = join(this.directory(), 'context', context);
2063
- let binding;
2064
- try {
2065
- binding = object(JSON.parse(await readFile(join(parent, 'current.json'), 'utf8')));
2066
- }
2067
- catch (error) {
2068
- if (error.code !== 'ENOENT')
2069
- throw error;
2070
- }
2071
- if (binding && this.workerShape(binding, context, scope, true)) {
2072
- await this.workerReceipt(binding, context, scope, true);
2073
- binding = undefined;
2074
- }
2075
- let entries;
2076
- try {
2077
- entries = await readdir(parent, { withFileTypes: true });
2078
- }
2079
- catch (error) {
2080
- if (error.code === 'ENOENT' && !binding)
2081
- return { unfinished: false };
2082
- throw error;
2083
- }
2084
- const candidates = [];
2085
- for (const entry of entries) {
2086
- if (entry.isSymbolicLink())
2087
- fail('binding', 'Context worker root moved; its evidence is retained.');
2088
- if (!entry.isDirectory())
2089
- continue;
2090
- const root = join(parent, entry.name);
2091
- if (binding?.root && sameDirectory(binding.root, root))
2092
- continue;
2093
- let started;
2094
- try {
2095
- started = JSON.parse(await readFile(join(root, 'process.json'), 'utf8'));
2096
- }
2097
- catch (error) {
2098
- if (error.code === 'ENOENT')
2099
- continue;
2100
- throw error;
2101
- }
2102
- // Validate even ended historical roots. A foreign or unreadable receipt proves no absence.
2103
- if (typeof started.root !== 'string' || !sameDirectory(started.root, root))
2104
- fail('binding', 'Context process receipt changed.');
2105
- if (await this.workerReceipt(started, context, scope, true))
2106
- continue;
2107
- candidates.push(started);
2108
- }
2109
- if (candidates.length) {
2110
- const selected = this.workspace.contextById(context), checkout = selected.nativeCheckout;
2111
- for (const candidate of candidates) {
2112
- if (candidate.target !== selected.target || candidate.session !== undefined && candidate.session !== selected.session ||
2113
- checkout && candidate.program !== checkout.path)
2114
- fail('binding', 'Context process receipt changed.');
2115
- if (checkout && sameDirectory(candidate.root, checkout.root))
2116
- continue;
2117
- if (!await this.workerEnded(candidate))
2118
- fail('busy', 'Another retained root of this context has a worker that is not proved stopped.');
2119
- }
2120
- const active = checkout ? candidates.find(b => sameDirectory(b.root, checkout.root)) : candidates.length === 1 ? candidates[0] : undefined;
2121
- if (active) {
2122
- if (binding) {
2123
- await this.workerReceipt(binding, context, scope);
2124
- if (!await this.workerEnded(binding))
2125
- fail('busy', 'The previous context worker is not proved stopped.');
2126
- }
2127
- return { binding: active, unfinished: true };
2128
- }
2129
- if (!binding && !checkout)
2130
- fail('binding', 'Competing historical context roots have no authoritative current worker.');
2131
- }
2132
- if (!binding)
2133
- return { unfinished: false };
2134
- let started;
2135
- try {
2136
- started = JSON.parse(await readFile(join(binding.root, 'process.json'), 'utf8'));
2137
- }
2138
- catch (error) {
2139
- if (error.code === 'ENOENT')
2140
- return { binding, unfinished: false };
2141
- throw error;
2142
- }
2143
- const identity = (b) => stable({ context: b.context ?? null, target: b.target, session: b.session ?? null, kind: b.kind, root: b.root, program: b.program });
2144
- if (stable(started) === stable(binding) || binding.context !== context || identity(started) !== identity(binding) ||
2145
- !Number.isSafeInteger(started.pid) || started.pid < 1 || !started.tokenSecret || started.tokenSecret === binding.tokenSecret ||
2146
- alive(binding.pid) && !await this.retiredWorker(binding))
2147
- return { binding, unfinished: false };
2148
- return { binding: started, unfinished: true };
2149
- }
2150
- async closed(scope) {
2151
- const context = this.workspace.context(scope);
2152
- const { binding, unfinished } = await this.lastWorker(context.id, { ...context, ...scope });
2153
- if (!binding)
2154
- return true;
2155
- // A marked worker's work is saved; recovery may stop it (only when no command holds it).
2156
- // A marked worker that cannot be stopped is not closed; `selected` refuses it as a live one as well.
2157
- // A PID alive again after this worker's proved end belongs to another process: its leftover marker means nothing.
2158
- if (!await this.workerEnded(binding) && await this.parkedMarker(binding)) {
2159
- try {
2160
- await this.stopParked(binding);
2161
- }
2162
- catch {
2163
- return false;
2164
- }
2165
- }
2166
- await this.workerReceipt(binding, context.id, { ...context, ...scope });
2167
- const root = await realpath(binding.root);
2168
- if (!ownedDirectory(root, this.directory(), [binding.kind, binding.context ?? binding.target, basename(root)]) || binding.context !== context.id || binding.target !== scope.target ||
2169
- stable(JSON.parse(await readFile(join(root, 'process.json'), 'utf8'))) !== stable(binding))
2170
- fail('binding', 'Closed context receipt changed.');
2171
- try {
2172
- const stopped = object(JSON.parse(await readFile(join(root, 'stopped.json'), 'utf8')));
2173
- if (stopped.pid === binding.pid && stopped.tokenSecret === binding.tokenSecret && await this.workerEnded(binding))
2174
- return true;
2175
- // A GUI transition reuses the saved project root. Its earlier headless stop is not
2176
- // evidence about this process; verify the current PID/binding independently below.
2177
- }
2178
- catch (error) {
2179
- if (error.code !== 'ENOENT')
2180
- throw error;
2181
- }
2182
- if (!alive(binding.pid) || unfinished && await this.retiredWorker(binding))
2183
- return true;
2184
- if (unfinished)
2185
- return false;
2186
- await this.verified(binding, this.workspace.target(scope.target));
2187
- return false;
2188
- }
2189
- async latest(targetId) {
2190
- return this.serverView(targetId);
2191
- }
2192
- async inspectNative(snapshot, operation, parameters) {
2193
- const saved = object(JSON.parse(await readFile(await this.workspace.artifacts.verify(snapshot), 'utf8')));
2194
- if (saved.engine !== this.nativeEngine)
2195
- fail('binding', 'Native view uses a different engine.');
2196
- if (saved.source === 'server') {
2197
- const binding = await this.server().ensure();
2198
- if (saved.origin !== binding.origin || saved.repository !== binding.repository)
2199
- fail('binding', 'Native shared view binding changed.');
2200
- const result = await this.server().nativeRead(binding, { ...saved, operation, ...parameters });
2201
- if (result.state !== 'verified')
2202
- fail('binding', 'Immutable native server view could not be verified.');
2203
- return operation === 'fields' ? result.fields : result.value;
2204
- }
2205
- if (saved.source !== 'checkout')
2206
- fail('binding', 'Unknown native view source.');
2207
- const checkout = object(saved.checkout), context = this.workspace.contextById(checkout.context);
2208
- if (context.nativeCheckout?.root !== checkout.root || context.nativeCheckout.checkoutId !== checkout.checkoutId || context.nativeCheckout.state !== 'active')
2209
- fail('binding', 'The retained native view is no longer the active working copy.');
2210
- if (await this.closed(context)) {
2211
- const result = await this.nativeOperation(context.nativeCheckout, operation, { fingerprint: saved.fingerprint, ...parameters });
2212
- if (result.state !== 'ready')
2213
- fail('binding', 'Saved native project inspection failed.');
2214
- return result.value;
2215
- }
2216
- return this.nativeView(await this.selected(context), { operation, expected: saved.fingerprint, ...parameters });
2217
- }
2218
- async fields(snapshot, changes) {
2219
- if (snapshot.kind === 'native')
2220
- return object(await this.inspectNative(snapshot, 'fields', { selectors: changes }));
2221
- const directory = join(this.directory(), 'inspection', randomUUID());
2222
- await mkdir(directory, { recursive: true, mode: 0o700 });
2223
- const selectors = join(directory, 'fields.json');
2224
- await durable(selectors, changes.map(change => ({ address: change.address, field: change.field })));
2225
- const result = await this.server().fields(await this.workspace.artifacts.verify(snapshot), selectors), values = object(result.fields);
2226
- for (const change of changes) {
2227
- const item = object(values[change.address + '@' + change.field]);
2228
- if (item.value !== null && typeof item.value !== 'string' || typeof item.exists !== 'boolean' || typeof item.dependency !== 'string' || !/^[a-f0-9]{64}$/.test(item.dependency))
2229
- fail('partial', 'Saved field inspection returned an incomplete value or dependency.');
2230
- }
2231
- return values;
2232
- }
2233
- /** Readback only: establishes an interrupted snapshot publication and never issues another check-in. */
2234
- async recoverLegacy(publication) {
2235
- const server = this.server(), binding = await server.ensure(), target = this.workspace.target(publication.target);
2236
- const journal = join(this.directory(), 'publications', publication.id, 'native-intent.json');
2237
- const result = await server.recoverPublication(binding, programPath(target.id), await this.workspace.artifacts.verify(publication.snapshot), publication.expectedRevision, publication.id, journal, target.binarySha256);
2238
- if (result.state === 'verified' && result.version === publication.expectedRevision + 1 && result.snapshotBuffersVerified === true && result.ownedCheckoutReleased === true)
2239
- return { state: 'verified', revision: version(result.version), snapshot: publication.snapshot };
2240
- return { state: 'unknown' };
2241
- }
2242
- async recover(publication) {
2243
- if (publication.snapshot.kind !== 'native')
2244
- return this.recoverLegacy(publication);
2245
- const saved = object(JSON.parse(await readFile(await this.workspace.artifacts.verify(publication.snapshot), 'utf8'))), checkout = object(saved.checkout);
2246
- if (saved.engine !== this.nativeEngine || saved.source !== 'checkout')
2247
- return { state: 'unknown' };
2248
- const { binding } = await this.nativeOwner(checkout), target = this.workspace.target(publication.target), revisionNumber = publication.expectedRevision + 1;
2249
- let value;
2250
- try {
2251
- value = await this.server().nativeRead(binding, { operation: 'verify', path: checkout.path, sourceSha: target.binarySha256, fileId: checkout.fileId,
2252
- version: revisionNumber, marker: 'insight native ' + publication.id });
2253
- }
2254
- catch (error) {
2255
- const failure = error;
2256
- // The native reader transports a missing success marker as an error. Its negative
2257
- // completion still needs every independent refusal proof below; other failures propagate.
2258
- if (failure.code !== 'coordinator.unknown' || failure.message !== 'Native history marker is unresolved' || failure.result?.diagnostic !== 'IllegalStateException')
2259
- throw error;
2260
- return this.recoverNativeRefusal(publication, checkout, saved);
2261
- }
2262
- if (value.state !== 'verified' || value.version !== revisionNumber)
2263
- return this.recoverNativeRefusal(publication, checkout, saved);
2264
- // The request journal and the repository history establish the outcome together. A journal that records this
2265
- // request ending without a check-in (a refusal, or nothing to publish) contradicts its marker in history: the lane stays frozen.
2266
- try {
2267
- const journal = object(JSON.parse(await readFile(join(checkout.root, 'operations', publication.id + '-checkin.json'), 'utf8')));
2268
- if (journal.result !== undefined && object(journal.result).state !== 'checked_in')
2269
- return { state: 'unknown' };
2270
- }
2271
- catch (error) {
2272
- if (error.code !== 'ENOENT')
2273
- throw error;
2274
- }
2275
- // The marker names this exact version; its identity seeds the version view.
2276
- if (value.fileId === checkout.fileId)
2277
- await this.rememberVersion(publication.target, binding, value);
2278
- const shared = await this.serverView(publication.target, revisionNumber, checkout.fileId);
2279
- return { state: 'verified', revision: revisionNumber, snapshot: shared.snapshot };
2280
- }
2281
- /** A request that published nothing: the completed head-race branch before checkin(), or a check-in that was sent and created no version. */
2282
- async recoverNativeRefusal(publication, checkout, saved) {
2283
- const unknown = { state: 'unknown' }, context = this.workspace.context(publication);
2284
- if (context.generation !== publication.generation || context.workingSnapshot?.id !== publication.snapshot.id ||
2285
- checkout.state !== 'active' || stable(context.nativeCheckout) !== stable(checkout) || saved.fileId !== checkout.fileId || saved.version !== checkout.baseVersion ||
2286
- checkout.baseVersion !== publication.expectedRevision || typeof saved.fingerprint !== 'string' || !/^[a-f0-9]{64}$/.test(saved.fingerprint) ||
2287
- !await this.neverStartedOrClosed(context))
2288
- return unknown;
2289
- const { owner, binding } = await this.nativeOwner(checkout), path = join(checkout.root, 'operations', publication.id + '-checkin.json');
2290
- let journal;
2291
- const q = { root: checkout.root, owner, operation: 'checkin', fileId: checkout.fileId, checkoutId: checkout.checkoutId,
2292
- request: publication.id, fingerprint: saved.fingerprint, expectedVersion: publication.expectedRevision };
2293
- try {
2294
- if (await realpath(path) !== resolve(path))
2295
- return unknown;
2296
- journal = object(JSON.parse(await readFile(path, 'utf8')));
2297
- }
2298
- catch (error) {
2299
- if (error.code === 'ENOENT')
2300
- return unknown;
2301
- throw error;
2302
- }
2303
- const result = object(journal.result ?? {}), before = object(journal.before ?? {}), marker = 'insight native ' + publication.id;
2304
- // A check-in that was sent and whose helper ended without a result. Ghidra's check-in either creates the version
2305
- // with this marker and moves the checkout to it, or leaves both as they were: the checkout still at its base,
2306
- // still modified, no check-in active and no version carrying the marker establish that nothing was published.
2307
- const issued = journal.marker === marker && journal.result === undefined;
2308
- if (stable(journal.request) !== stable(q) || journal.checkoutId !== checkout.checkoutId || journal.baseVersion !== checkout.baseVersion ||
2309
- !Number.isSafeInteger(journal.headVersion) || before.fileId !== checkout.fileId || before.version !== checkout.baseVersion)
2310
- return unknown;
2311
- if (issued) {
2312
- if (journal.headVersion !== publication.expectedRevision)
2313
- return unknown;
2314
- }
2315
- else if (journal.marker !== undefined || Number(journal.headVersion) <= publication.expectedRevision || result.state !== 'conflict' ||
2316
- result.conflict !== 'Shared head changed before native check-in' || result.nativeMergeInvocations !== 0 || !Array.isArray(result.nativePhases) || result.nativePhases.length !== 0 ||
2317
- result.checkoutId !== checkout.checkoutId || result.baseVersion !== checkout.baseVersion || typeof result.modified !== 'boolean' ||
2318
- before.fingerprint !== saved.fingerprint || stable(result.saved) !== stable(before))
2319
- return unknown;
2320
- // The status call needs the project: a helper still running this check-in would hold it.
2321
- const observed = await this.nativeOperation(checkout, 'status'), local = object(observed.saved ?? {});
2322
- if (observed.state !== 'ready' || observed.checkedOut !== true || observed.recoverable !== false || observed.checkinActive !== false ||
2323
- observed.fileId !== checkout.fileId || observed.checkoutId !== checkout.checkoutId || observed.baseVersion !== checkout.baseVersion ||
2324
- (issued ? observed.modified !== true || local.fileId !== checkout.fileId || local.version !== checkout.baseVersion :
2325
- observed.modified !== result.modified || stable(observed.saved) !== stable(before)))
2326
- return unknown;
2327
- const server = this.server();
2328
- const history = (value) => {
2329
- if (value.repository !== checkout.repository || value.path !== checkout.path || value.checkinActive !== false || !Number.isSafeInteger(value.version) ||
2330
- Number(value.version) < Number(journal.headVersion) || !Array.isArray(value.versions) || !value.versions.length ||
2331
- !Array.isArray(value.checkouts) || !value.checkouts.includes(checkout.checkoutId))
2332
- return false;
2333
- const rows = value.versions.map(object), versions = rows.map(v => v.version);
2334
- return rows.every(v => Number.isSafeInteger(v.version) && Number(v.version) > 0 && typeof v.comment === 'string' && v.comment !== marker) &&
2335
- new Set(versions).size === versions.length && versions.includes(checkout.baseVersion) && versions.includes(journal.headVersion) &&
2336
- Math.max(...versions) === value.version;
2337
- };
2338
- const prior = await server.programStatus(binding, checkout.path);
2339
- if (!history(prior))
2340
- return unknown;
2341
- // The observed server version is read for its source and file identity.
2342
- const shared = await this.serverView(publication.target, Number(prior.version));
2343
- if (shared.revision !== prior.version || shared.value.fileId !== checkout.fileId || typeof shared.value.fingerprint !== 'string')
2344
- return unknown;
2345
- const after = await server.programStatus(binding, checkout.path);
2346
- if (!history(after) || after.version !== prior.version || stable(after.versions) !== stable(prior.versions) ||
2347
- !await this.neverStartedOrClosed(context) || stable((await this.nativeOperation(checkout, 'status'))) !== stable(observed) ||
2348
- stable(JSON.parse(await readFile(path, 'utf8'))) !== stable(journal))
2349
- return unknown;
2350
- return { state: 'refused', revision: shared.revision, snapshot: shared.snapshot,
2351
- ...(issued ? { reason: 'not_published', conflict: 'The native check-in was sent and created no version; the private work is retained. Merge again with a new request ID.' } : { conflict: String(result.conflict) }) };
2352
- }
2353
- async recoverModel(targetId) {
2354
- if (this.workspace.activePublication(targetId))
2355
- return false;
2356
- const model = this.workspace.model(targetId);
2357
- if (model.state === 'ready')
2358
- return true;
2359
- if (model.state === 'opening')
2360
- return true;
2361
- const target = this.workspace.target(targetId), server = this.server(), binding = await server.ensure();
2362
- if (await initialIntent(this.workspace, targetId)) {
2363
- await this.model(target);
2364
- return this.workspace.model(targetId).state === 'ready';
2365
- }
2366
- await this.retireLegacyBootstrap(target);
2367
- let status;
2368
- try {
2369
- status = await server.programStatus(binding, programPath(targetId));
2370
- }
2371
- catch {
2372
- return false;
2373
- }
2374
- if (status.state === 'absent') {
2375
- await this.model(target);
2376
- return this.workspace.model(targetId).state === 'ready';
2377
- }
2378
- if (status.version !== 1 || status.checkinActive !== false || !Array.isArray(status.versions) || status.versions.length !== 1 ||
2379
- object(status.versions[0]).comment !== 'insight target ' + targetId)
2380
- return false;
2381
- const record = await this.shared(target, binding);
2382
- try {
2383
- const metadata = await this.source(record, target);
2384
- if (model.settings.language && metadata.language !== model.settings.language || model.settings.compilerSpec && metadata.compiler !== model.settings.compilerSpec ||
2385
- model.settings.imageBase && String(metadata.base_address).replace(/^0+(?=.)/, '') !== model.settings.imageBase)
2386
- return false;
2387
- const output = join(record.binding.root, 'exports');
2388
- await mkdir(output, { recursive: true, mode: 0o700 });
2389
- const exported = object(await record.http.call('/export_program', { program_name: record.binding.program, output_dir: output, output_name: 'recovered.gzf' }));
2390
- if (exported.success !== true)
2391
- return false;
2392
- const snapshot = await this.captureExport(join(output, 'recovered.gzf'));
2393
- const after = await server.programStatus(binding, programPath(targetId));
2394
- if (after.version !== 1 || after.checkinActive !== false)
2395
- return false;
2396
- this.workspace.establishModel(targetId, 1, snapshot);
2397
- return true;
2398
- }
2399
- finally {
2400
- await this.stopRecord(record);
2401
- }
2402
- }
2403
- async dispose() {
2404
- // Factory has cancelled invocation signals before resource drain. Cleanup still needs
2405
- // bounded authenticated reads to establish ownership of previously orphaned children.
2406
- const cleanup = this.fork({ ...this.c, signal: new AbortController().signal });
2407
- let failures = 0;
2408
- try {
2409
- await this.stopServices();
2410
- }
2411
- catch {
2412
- failures++;
2413
- }
2414
- try {
2415
- await cleanup.inventory();
2416
- }
2417
- catch {
2418
- failures++;
2419
- }
2420
- for (const record of [...this.running.values()]) {
2421
- try {
2422
- // An opened headless context worker with an idle lease outlives its owner and stops by itself after
2423
- // its idle time; the next owner adopts it through inventory. Starting or lease-less stages still stop.
2424
- if (await this.detachable(record)) {
2425
- this.running.delete(record.binding.root);
2426
- continue;
2427
- }
2428
- // Original child handles also permit cleanup of a failed, unready owned stage.
2429
- await cleanup.stopRecord(record, !record.child, true, 'owner_dispose');
2430
- }
2431
- catch {
2432
- failures++;
2433
- }
2434
- }
2435
- if (failures)
2436
- fail('busy', 'Some owned native stages could not be stopped; their receipts and saved work are retained.');
2437
- }
2438
- /**
2439
- * Free one slot by stopping the idle leased worker unused for longest. A worker held by a running command
2440
- * refuses retirement atomically, so eviction never interrupts dispatched work; its saved project reopens
2441
- * transparently on the next command of its context.
2442
- */
2443
- async evictIdle(requesting) {
2444
- const candidates = [];
2445
- for (const record of this.running.values()) {
2446
- const { binding } = record;
2447
- if (binding.kind !== 'context' || binding.mode !== 'headless' || !binding.leasePort || !binding.context || binding.context === requesting || !this.capacity.slots.has(binding.context))
2448
- continue;
2449
- try {
2450
- const status = await this.lease(binding, 'status');
2451
- if (status.state === 'idle')
2452
- candidates.push({ record, idleForMs: status.idleForMs ?? 0 });
2453
- }
2454
- catch { /* An unreachable worker is never evicted. */ }
2455
- }
2456
- for (const { record } of candidates.sort((a, b) => b.idleForMs - a.idleForMs))
2457
- if (await this.retireWorker(record.binding, 'capacity_evicted'))
2458
- return;
2459
- }
2460
- /**
2461
- * Before exclusive maintenance (GC, migration, runtime changes): stop this owner's native services and ask every
2462
- * idle leased worker, including detached ones, to stop. Their work is saved; a worker held by a command stays
2463
- * and the maintenance admission then refuses as before.
2464
- */
2465
- async quiesce() {
2466
- // Like disposal, maintenance may follow a command whose signal Factory already cancelled.
2467
- const worker = this.fork({ ...this.c, signal: new AbortController().signal });
2468
- await worker.requireIdleServices();
2469
- if (!this.capacity.inventory)
2470
- this.capacity.inventory = worker.inventory().catch(error => { this.capacity.inventory = undefined; throw error; });
2471
- await this.capacity.inventory;
2472
- for (const record of [...this.running.values()]) {
2473
- const { binding } = record;
2474
- if (binding.kind === 'context' && binding.mode === 'headless' && binding.leasePort && !await worker.workerGone(binding))
2475
- await worker.retireWorker(binding, 'maintenance');
2476
- }
2477
- }
2478
- /**
2479
- * Parking keeps a worker's JVM (and its warm Ghidra) while native Update/check-in own the project: the worker
2480
- * closes its project and the release of Ghidra's project lock is proved on disk before anything else opens it.
2481
- * The bridge reports success even when closing fails, so its answer alone is never the proof.
2482
- */
2483
- /**
2484
- * A native Update or check-in that provably never reached the server is reported as not sent for that phase only:
2485
- * either it never reached a helper, or the helper process ended without a result (crash, timeout, cancellation,
2486
- * memory exhaustion) before writing the operation's journal intent, which always precedes the server call, and no
2487
- * process that could still write it exists. A helper that answered keeps its own outcome (refusal, migration,
2488
- * binding, unknown), so a check that held the lane is never turned into a reopened one.
2489
- */
2490
- async notSent(phase, checkout, request, action) {
2491
- // The journal directory is created and identified before dispatch: absence of the journal is evidence only in that
2492
- // same directory. A moved or replaced checkout or directory proves nothing.
2493
- const directory = join(checkout.root, 'operations');
2494
- let before;
2495
- try {
2496
- await mkdir(directory, { recursive: true });
2497
- before = await directoryIdentity(directory);
2498
- }
2499
- catch (error) {
2500
- return this.unsent(phase, error);
2501
- }
2502
- try {
2503
- return await action();
2504
- }
2505
- catch (error) {
2506
- // Already settled before dispatch, with its own cause.
2507
- if (!(error instanceof CliError) || error.code === 'coordinator.notSent')
2508
- throw error;
2509
- const memory = object(error.result ?? {}).memory === 'exhausted';
2510
- const ended = memory || error.code === 'coordinator.malformed' || error.code.startsWith('tool.') && error.code !== 'tool.termination.unverified';
2511
- if (error.code === 'tool.notSent' || ended && before !== undefined && await this.journalAbsent(directory, before, request, phase))
2512
- fail('notSent', 'Native ' + phase + ' was not sent; nothing changed on the server and this context stays usable.' + (memory ? ' ' + error.message : '') +
2513
- ' This request is settled as not sent; run the operation again with a new request ID' + (memory ? ' once memory is available.' : '.'), { phase, cause: { code: error.code, message: error.message }, ...(memory ? { memory: 'exhausted', reason: 'out_of_memory', memoryCause: object(error.result).memoryCause } : {}) });
2514
- throw error;
2515
- }
2516
- }
2517
- /**
2518
- * No writer that could still create the journal exists, the journal directory is still the one identified before
2519
- * dispatch, and the journal is absent from it (checked in that order).
2520
- */
2521
- async journalAbsent(directory, before, request, phase) {
2522
- if (!/^q_[a-f0-9-]{36}$/.test(request) || !await this.server().nativeWritersSettled() || await directoryIdentity(directory) !== before)
2523
- return false;
2524
- try {
2525
- await lstat(join(directory, request + '-' + phase + '.json'));
2526
- return false;
2527
- }
2528
- catch (error) {
2529
- if (error.code === 'ENOENT')
2530
- return await directoryIdentity(directory) === before;
2531
- throw error;
2532
- }
2533
- }
2534
- /** How long a parked project may take to release Ghidra's lock files. */
2535
- parkWaitMs = 10000;
2536
- async park(record) { return timed('worker.park', 'close_project', () => this.parkWorker(record)); }
2537
- async parkWorker(record) {
2538
- const { binding } = record;
2539
- if (binding.kind !== 'context' || binding.mode !== 'headless' || !binding.leasePort)
2540
- return false;
2541
- if (await this.ranAgentCode(binding))
2542
- return false;
2543
- // A helper script abandoned by a timed-out command may still run on the program: such a worker is stopped instead.
2544
- // The worker refuses while a helper script runs or waits and admits none until this command reopens the project
2545
- // or its hold ends; a worker without this request (an earlier build) or a command without a hold is stopped instead.
2546
- const holder = workerLeaseHolder(binding.root);
2547
- if (!holder)
2548
- return false;
2549
- try {
2550
- if ((await this.lease(binding, 'park_held', holder)).state !== 'held')
2551
- return false;
2552
- }
2553
- catch {
2554
- return false;
2555
- }
2556
- // The marker precedes the close and says only that a close may be under way: a worker left like that is stopped,
2557
- // never reopened, because the close may still complete. Only the proved release of the project lock records the
2558
- // project as closed, which is what lets a later command reopen it.
2559
- const marker = join(binding.root, 'parked.json'), mark = { pid: binding.pid, tokenSecret: binding.tokenSecret, at: new Date().toISOString() };
2560
- await durable(marker, { schema: 2, closed: false, ...mark });
2561
- try {
2562
- await record.http.call('/close_project');
2563
- }
2564
- catch {
2565
- return false;
2566
- }
2567
- const locks = [join(binding.root, 'view.lock'), join(binding.root, 'view.lock~')];
2568
- for (const deadline = Date.now() + this.parkWaitMs; Date.now() < deadline; await delay(100))
2569
- if (!(await Promise.all(locks.map(exists))).some(Boolean)) {
2570
- await durable(marker, { schema: 2, closed: true, ...mark });
2571
- return true;
2572
- }
2573
- return false;
2574
- }
2575
- /** This worker process executed agent-supplied script code. */
2576
- async ranAgentCode(binding) {
2577
- try {
2578
- const value = object(JSON.parse(await readFile(join(binding.root, 'agent-code.json'), 'utf8')));
2579
- return value.pid === binding.pid && value.tokenSecret === binding.tokenSecret;
2580
- }
2581
- catch (error) {
2582
- return error.code !== 'ENOENT';
2583
- }
2584
- }
2585
- /** This worker's marker: `closed` once its project lock was proved released, `closing` while a close may be under way. */
2586
- async parkedState(binding) {
2587
- // Only a leased headless worker is ever parked; a GUI or unleased worker is never stopped for a marker.
2588
- if (binding.kind !== 'context' || binding.mode !== 'headless' || !binding.leasePort)
2589
- return;
2590
- // This never fails and decides one way when in doubt. A worker is unmarked only when the file is absent or
2591
- // names another worker; an unreadable or damaged file may be this worker's own pending close, so the worker
2592
- // counts as closing and is stopped. A new worker's launch clears whatever its predecessor left.
2593
- let text;
2594
- try {
2595
- text = await readFile(join(binding.root, 'parked.json'), 'utf8');
2596
- }
2597
- catch (error) {
2598
- return error.code === 'ENOENT' ? undefined : 'closing';
2599
- }
2600
- let value;
2601
- try {
2602
- value = object(JSON.parse(text));
2603
- }
2604
- catch {
2605
- return 'closing';
2606
- }
2607
- if (!Number.isSafeInteger(value.pid) || Number(value.pid) < 1 || typeof value.tokenSecret !== 'string' || !/^context-[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(value.tokenSecret))
2608
- return 'closing';
2609
- if (value.pid !== binding.pid || value.tokenSecret !== binding.tokenSecret)
2610
- return;
2611
- // Only this explicit record proves the close. Earlier markers (schema 1) were written by some builds before the
2612
- // close was sent, so they prove nothing and their worker is stopped.
2613
- return value.schema === 2 && value.closed === true ? 'closed' : 'closing';
2614
- }
2615
- async parkedMarker(binding) { return await this.parkedState(binding) !== undefined; }
2616
- /** Stop a marked worker. Its work is saved; its project may be closed, closing or still open. */
2617
- async stopParked(binding) {
2618
- const record = this.running.get(binding.root);
2619
- if (alive(binding.pid)) {
2620
- if (record?.child && record.child.pid === binding.pid)
2621
- await this.stopRecord(record, false, true, 'view_replaced');
2622
- else if ((await releaseWorkerLease(binding.root), !await this.retireWorker(binding, 'maintenance')) && alive(binding.pid))
2623
- fail('busy', 'A parked context worker is still held by a command; retry after it ends.');
2624
- }
2625
- else
2626
- await this.stopRecord({ binding, http: new HttpBridge(binding.endpoint) }, false, true, 'view_replaced');
2627
- // The worker is gone; a marker that cannot be removed now is cleared by the next launch in this root.
2628
- await rm(join(binding.root, 'parked.json'), { force: true }).catch(() => { });
2629
- }
2630
- /**
2631
- * After a merge or refresh: reopen the parked worker's project at its new base, or stop it when the context
2632
- * cannot continue in it (unresolved outcome, disposed checkout, failed reopen). Either way no parked worker
2633
- * outlives the command that parked it.
2634
- */
2635
- async resumeParked(scope) {
2636
- // The command may already be cancelled; the reopen or stop must still complete.
2637
- return timed('worker.resume', 'open_project', () => this.fork({ ...this.c, signal: new AbortController().signal }).resumeWorker(scope));
2638
- }
2639
- async resumeWorker(scope) {
2640
- const context = this.workspace.context(scope);
2641
- let binding;
2642
- try {
2643
- binding = JSON.parse(await readFile(join(this.directory(), 'context', context.id, 'current.json'), 'utf8'));
2644
- }
2645
- catch {
2646
- return;
2647
- }
2648
- if (binding.context !== context.id || !await this.parkedMarker(binding))
2649
- return;
2650
- const checkout = context.nativeCheckout;
2651
- // A close that was never proved may still complete: such a worker is stopped, and stays marked until it is.
2652
- const resumable = await this.parkedState(binding) === 'closed' && alive(binding.pid) && checkout?.state === 'active' && checkout.root === binding.root && !this.workspace.unresolved(scope).length && !context.debugger?.connected;
2653
- if (!resumable) {
2654
- await this.stopParked(binding);
2655
- return;
2656
- }
2657
- const target = this.workspace.target(scope.target), token = await this.c.secrets.require(binding.tokenSecret);
2658
- // Always a fresh bridge on this (uncancelled) fork's signal; a cached record may carry the command's own.
2659
- const record = { ...(this.running.get(binding.root) ?? {}), binding, http: await this.bridge(binding, token) };
2660
- try {
2661
- // Reopening saves: the worker must not retire under it. A replayed request has no hold yet, and a hold kept
2662
- // from before a long native operation may have expired in the worker, so it is reaffirmed there.
2663
- const kept = workerLeaseHolder(binding.root);
2664
- if (kept && (await this.lease(binding, 'renew', kept)).state !== 'held')
2665
- dropWorkerLease(binding.root);
2666
- if (await this.holdLease(binding) !== 'held')
2667
- fail('busy', 'Parked context worker is retiring.');
2668
- const project = object(await record.http.call('/open_project', { path: join(binding.root, 'view.gpr') }));
2669
- if (project.success === false)
2670
- fail('launch', 'Native working project could not be reopened.');
2671
- // The worker's own listener serves again from here: the reopening itself goes through it.
2672
- if (!['held', 'idle'].includes((await this.lease(binding, 'unpark')).state))
2673
- fail('binding', 'Resumed worker did not admit helper scripts again.');
2674
- const opened = object(await openWorkerProgram(record.http, binding.program, scope));
2675
- if (opened.path !== binding.program || opened.read_only === true)
2676
- fail('binding', 'Native checkout did not reopen its saved writable program.');
2677
- binding.baseRevision = context.baseRevision;
2678
- binding.viewEpoch = context.viewEpoch ?? 0;
2679
- await durable(join(binding.root, 'process.json'), binding);
2680
- await durable(join(this.directory(), 'context', context.id, 'current.json'), binding);
2681
- await rm(join(binding.root, 'parked.json'), { force: true });
2682
- const live = await this.verified(binding, target);
2683
- await recordLifecycle(this.workspace, context.id, { at: new Date().toISOString(), event: 'restore', reason: 'saved_snapshot', pid: binding.pid });
2684
- const settled = this.workspace.context(scope);
2685
- this.workspace.saveContext(scope, settled.generation, { state: 'ready' });
2686
- }
2687
- catch {
2688
- // Reopen failed: the next command relaunches the worker on its saved project.
2689
- if (await this.parkedMarker(binding) || alive(binding.pid))
2690
- await this.stopParked(binding).catch(() => { });
2691
- }
2692
- }
2693
- /** This owner's native services; servers without them (tests, external adapters) have nothing to stop. */
2694
- async stopServices() { await this.server().stopServices?.(); }
2695
- /** Stop idle services; a service running another command's request refuses exclusive work instead of being killed. */
2696
- async requireIdleServices() { if (await this.server().stopIdleServices?.() === false)
2697
- fail('busy', 'A native service is still running or starting for another command; retry when it ends.'); }
2698
- async detachable(record) {
2699
- const { binding } = record;
2700
- if (!binding.leasePort || binding.kind !== 'context' || binding.mode !== 'headless' || !binding.context || !alive(binding.pid))
2701
- return false;
2702
- try {
2703
- const current = object(JSON.parse(await readFile(join(this.directory(), 'context', binding.context, 'current.json'), 'utf8')));
2704
- return current.pid === binding.pid && current.root === binding.root && current.tokenSecret === binding.tokenSecret;
2705
- }
2706
- catch {
2707
- return false;
2708
- }
2709
- }
2710
- async inventory() {
2711
- const directory = join(this.directory(), 'context');
2712
- let entries;
2713
- try {
2714
- entries = await readdir(directory, { withFileTypes: true });
2715
- }
2716
- catch (error) {
2717
- if (error.code === 'ENOENT')
2718
- return;
2719
- throw error;
2720
- }
2721
- for (const entry of entries) {
2722
- if (!entry.isDirectory())
2723
- continue;
2724
- let binding, unfinished = false;
2725
- ({ binding, unfinished } = await this.lastWorker(entry.name));
2726
- if (!binding)
2727
- continue;
2728
- if (binding.context !== entry.name || binding.kind !== 'context')
2729
- fail('binding', 'Persisted context inventory has an inconsistent receipt.');
2730
- let stopped = false;
2731
- try {
2732
- const receipt = object(JSON.parse(await readFile(join(binding.root, 'stopped.json'), 'utf8')));
2733
- stopped = receipt.pid === binding.pid && receipt.tokenSecret === binding.tokenSecret && await this.workerEnded(binding);
2734
- }
2735
- catch (error) {
2736
- if (error.code !== 'ENOENT')
2737
- throw error;
2738
- }
2739
- if (!stopped && alive(binding.pid)) {
2740
- // An unfinished start is never adopted; its own context reports it, others keep working.
2741
- if (unfinished) {
2742
- if (!await this.retiredWorker(binding))
2743
- this.capacity.slots.add(entry.name);
2744
- continue;
2745
- }
2746
- if (binding.mode === 'headless' && await this.retiredInventoryWorker(binding))
2747
- continue;
2748
- if (binding.leasePort) {
2749
- // Detached workers stop on their own schedule: never adopt one that is retiring or gone, and ask an
2750
- // unheld worker of a previous runtime to stop. A held one keeps its slot until its command ends.
2751
- const status = await this.lease(binding, 'status');
2752
- if (status.state === 'gone' || status.state === 'retiring' && await this.awaitExit(binding, 10000)) {
2753
- await this.settleRetired(binding);
2754
- continue;
2755
- }
2756
- if (binding.runtimeFingerprint !== this.inputs.fingerprint || binding.helpers !== await helperSourcesKey().catch(() => binding.helpers)) {
2757
- if (!await this.retireWorker(binding, 'runtime_changed'))
2758
- this.capacity.slots.add(entry.name);
2759
- continue;
2760
- }
2761
- }
2762
- // A replacement owner must also release contexts it has not read yet.
2763
- // PID existence alone grants no authority: authenticate the complete receipt.
2764
- try {
2765
- await this.verified(binding, this.workspace.target(binding.target), false);
2766
- }
2767
- catch (error) {
2768
- // A worker that exits meanwhile is not adopted; any other failure keeps the original refusal.
2769
- if (binding.leasePort && await this.awaitExit(binding, 5000)) {
2770
- await this.settleRetired(binding);
2771
- continue;
2772
- }
2773
- throw error;
2774
- }
2775
- this.capacity.slots.add(entry.name);
2776
- }
2777
- else if (!stopped)
2778
- await this.settleRetired(binding);
2779
- else if (binding.mode === 'gui')
2780
- await this.debuggerReleased(binding);
2781
- }
2782
- }
2783
- async retiredInventoryWorker(binding) {
2784
- if (!binding.toolProcessId)
2785
- return false;
2786
- try {
2787
- // Read-only retirement evidence: old locators may no longer exist. Exact
2788
- // persisted locator equality is sufficient here; it never authorizes a signal.
2789
- const matches = (row) => row.id === binding.toolProcessId && row.tool === 'ghidra' && row.role === binding.kind &&
2790
- row.pid === binding.pid && row.target === binding.target && row.session === binding.session &&
2791
- row.installation === binding.runtimeFingerprint && typeof row.identity === 'string' && Boolean(row.identity) && typeof row.metadata?.contextRoot === 'string' &&
2792
- resolve(row.metadata.contextRoot) === resolve(binding.root);
2793
- const row = await processStatus(this.c.appArguments.AppDataDirectory, binding.toolProcessId);
2794
- // A strongly identified receipt with an exactly recorded end, as before.
2795
- if (matches(row) && ['exited', 'failed'].includes(row.state) && row.strongIdentity === true && validEnd(row.endedAt))
2796
- return true;
2797
- // Otherwise proved freshly from the PID's current holder, on the same receipt snapshot that is validated.
2798
- const gone = await recordedProcessGone(this.c.appArguments.AppDataDirectory, binding.toolProcessId);
2799
- return gone !== undefined && matches(gone);
2800
- }
2801
- catch {
2802
- return false;
2803
- }
2804
- }
2805
- }