@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
@@ -0,0 +1,919 @@
1
+ // Work ledger state in hub.db (#163). Every table is prefixed `ledger_` and scoped by hub project id (`scope`).
2
+ // The hub clock measures leases and every changing call runs in one SQLite transaction (see LedgerStore.tx).
3
+ import { createHash, randomUUID } from 'node:crypto';
4
+ import { discoverLimits, discoveryReport, taskKinds, array, definition, fail, leaseToken, identifier, integer, object, passport, sha, stable, string, reviewState } from '../work/model.js';
5
+ import { timingReport } from '../work/timing.js';
6
+ /** Columns of every ledger table after `scope`, in export order. */
7
+ export const ledgerTables = {
8
+ projects: ['id', 'data'], functions: ['project', 'id', 'rva', 'stage', 'data'], tasks: ['id', 'project', 'status', 'data'],
9
+ locks: ['project', 'resource', 'task'], events: ['seq', 'project', 'revision', 'kind', 'data'],
10
+ graph_nodes: ['project', 'id', 'data'], graph_edges: ['project', 'id', 'data'],
11
+ function_versions: ['project', 'id', 'version', 'data', 'reason', 'at', 'task'],
12
+ function_resources: ['project', 'function_id', 'resource', 'evidence_edge'],
13
+ };
14
+ /** Edge kinds whose source exclusively reserves the target; everything else is a read dependency. */
15
+ export const exclusiveEdgeKinds = ['writes', 'initializes', 'owns', 'frees'];
16
+ export function ledgerSchema(db) {
17
+ db.exec(`
18
+ CREATE TABLE IF NOT EXISTS ledger_projects(scope TEXT NOT NULL,id TEXT NOT NULL,data TEXT NOT NULL,PRIMARY KEY(scope,id));
19
+ CREATE TABLE IF NOT EXISTS ledger_functions(scope TEXT NOT NULL,project TEXT NOT NULL,id TEXT NOT NULL,rva INTEGER NOT NULL,stage TEXT NOT NULL,data TEXT NOT NULL,
20
+ PRIMARY KEY(scope,project,id));
21
+ CREATE INDEX IF NOT EXISTS ledger_function_frontier ON ledger_functions(scope,project,stage,rva);
22
+ CREATE INDEX IF NOT EXISTS ledger_function_order ON ledger_functions(scope,project,rva);
23
+ CREATE TABLE IF NOT EXISTS ledger_tasks(scope TEXT NOT NULL,id TEXT NOT NULL,project TEXT NOT NULL,status TEXT NOT NULL,data TEXT NOT NULL,PRIMARY KEY(scope,id));
24
+ CREATE INDEX IF NOT EXISTS ledger_task_project ON ledger_tasks(scope,project,status);
25
+ CREATE TABLE IF NOT EXISTS ledger_locks(scope TEXT NOT NULL,project TEXT NOT NULL,resource TEXT NOT NULL,task TEXT NOT NULL,PRIMARY KEY(scope,project,resource));
26
+ CREATE INDEX IF NOT EXISTS ledger_lock_task ON ledger_locks(scope,task);
27
+ CREATE TABLE IF NOT EXISTS ledger_events(scope TEXT NOT NULL,seq INTEGER NOT NULL,project TEXT NOT NULL,revision INTEGER NOT NULL,kind TEXT NOT NULL,data TEXT NOT NULL,
28
+ PRIMARY KEY(scope,seq));
29
+ CREATE INDEX IF NOT EXISTS ledger_clock_by_task ON ledger_events(scope,project,json_extract(data,'$.task'),seq)
30
+ WHERE kind IN ('task.claimed','reconstruction.submitted','review.submitted');
31
+ CREATE TABLE IF NOT EXISTS ledger_graph_nodes(scope TEXT NOT NULL,project TEXT NOT NULL,id TEXT NOT NULL,data TEXT NOT NULL,PRIMARY KEY(scope,project,id));
32
+ CREATE TABLE IF NOT EXISTS ledger_graph_edges(scope TEXT NOT NULL,project TEXT NOT NULL,id TEXT NOT NULL,data TEXT NOT NULL,PRIMARY KEY(scope,project,id));
33
+ CREATE TABLE IF NOT EXISTS ledger_function_versions(scope TEXT NOT NULL,project TEXT NOT NULL,id TEXT NOT NULL,version INTEGER NOT NULL,
34
+ data TEXT NOT NULL,reason TEXT NOT NULL,at INTEGER NOT NULL,task TEXT,PRIMARY KEY(scope,project,id,version));
35
+ CREATE TABLE IF NOT EXISTS ledger_function_resources(scope TEXT NOT NULL,project TEXT NOT NULL,function_id TEXT NOT NULL,resource TEXT NOT NULL,evidence_edge TEXT NOT NULL,
36
+ PRIMARY KEY(scope,project,function_id,resource,evidence_edge));
37
+ CREATE TRIGGER IF NOT EXISTS ledger_versions_no_update BEFORE UPDATE ON ledger_function_versions BEGIN SELECT RAISE(ABORT,'immutable work version'); END;`);
38
+ }
39
+ /** Runs `action` in one write transaction of the hub database. */
40
+ export function transaction(db, action, write = true) {
41
+ db.exec(write ? 'BEGIN IMMEDIATE' : 'BEGIN');
42
+ try {
43
+ const result = action();
44
+ db.exec('COMMIT');
45
+ return result;
46
+ }
47
+ catch (error) {
48
+ db.exec('ROLLBACK');
49
+ throw error;
50
+ }
51
+ }
52
+ /** Rows of one hub project, without `scope`, in a stable order. */
53
+ export function readRows(db, scope) {
54
+ return Object.fromEntries(Object.entries(ledgerTables).map(([table, columns]) => [table,
55
+ db.prepare(`SELECT ${columns.join(',')} FROM ledger_${table} WHERE scope=? ORDER BY rowid`).all(scope).map(row => ({ ...row }))]));
56
+ }
57
+ const canonical = (rows) => stable(Object.fromEntries(Object.entries(ledgerTables).map(([table, columns]) => [table,
58
+ [...(rows[table] ?? [])].map(row => columns.map(c => row[c] ?? null)).map(r => stable(r)).sort()])));
59
+ /** Content identity of a project's ledger rows, independent of row order. */
60
+ export const ledgerDigest = (rows) => createHash('sha256').update(canonical(rows)).digest('hex');
61
+ export const rowCounts = (rows) => Object.fromEntries(Object.keys(ledgerTables).map(t => [t, rows[t]?.length ?? 0]));
62
+ /**
63
+ * Writes `rows` into an empty hub project. Identical existing rows converge; any other existing ledger data is refused,
64
+ * so an import never merges two histories. Ids, fences and revisions are kept as given.
65
+ */
66
+ export function writeRows(db, scope, rows) {
67
+ for (const table of Object.keys(rows))
68
+ if (!(table in ledgerTables))
69
+ fail('invalid', 'Unknown ledger table ' + table + '.');
70
+ const counts = rowCounts(rows);
71
+ return transaction(db, () => {
72
+ const existing = readRows(db, scope);
73
+ if (Object.values(existing).some(r => r.length)) {
74
+ if (canonical(existing) === canonical(rows))
75
+ return { state: 'unchanged', counts };
76
+ fail('conflict', 'This hub project already has other ledger data; an import never merges two ledgers.', { existing: rowCounts(existing), incoming: counts });
77
+ }
78
+ for (const [table, columns] of Object.entries(ledgerTables)) {
79
+ const insert = db.prepare(`INSERT INTO ledger_${table}(scope,${columns.join(',')}) VALUES(?,${columns.map(() => '?').join(',')})`);
80
+ for (const row of rows[table] ?? [])
81
+ insert.run(scope, ...columns.map(c => {
82
+ const v = row[c] ?? null;
83
+ if (v !== null && !['string', 'number', 'bigint'].includes(typeof v))
84
+ fail('invalid', `Ledger ${table}.${c} must be text or a number.`);
85
+ return v;
86
+ }));
87
+ }
88
+ return { state: 'imported', counts };
89
+ });
90
+ }
91
+ /** The ledger of one hub project. `client` is the hub client name recorded with events. */
92
+ export class LedgerStore {
93
+ db;
94
+ scope;
95
+ clock;
96
+ client;
97
+ constructor(db, scope, clock = Date.now, client = 'unknown-client') {
98
+ this.db = db;
99
+ this.scope = scope;
100
+ this.clock = clock;
101
+ this.client = client;
102
+ }
103
+ tx(action, write = false) { return transaction(this.db, action, write); }
104
+ get(sql, ...args) { return this.db.prepare(sql).get(this.scope, ...args); }
105
+ all(sql, ...args) { return this.db.prepare(sql).all(this.scope, ...args); }
106
+ run(sql, ...args) { return this.db.prepare(sql).run(this.scope, ...args); }
107
+ project(id) {
108
+ identifier(id);
109
+ const row = this.get('SELECT data FROM ledger_projects WHERE scope=? AND id=?', id);
110
+ if (!row)
111
+ fail('notFound', 'Project is not present in this hub project.');
112
+ return JSON.parse(String(row.data));
113
+ }
114
+ putProject(project) { this.db.prepare('UPDATE ledger_projects SET data=? WHERE scope=? AND id=?').run(stable(project), this.scope, project.id); }
115
+ function(project, id) {
116
+ const row = this.get('SELECT data FROM ledger_functions WHERE scope=? AND project=? AND id=?', project, string(id, 256));
117
+ if (!row)
118
+ fail('notFound', 'Function is not present in this project.');
119
+ return JSON.parse(String(row.data));
120
+ }
121
+ /** Retains a new function version (versions only rise; the table refuses to change a retained one). */
122
+ recordVersion(project, fn, reason, task) {
123
+ this.run('INSERT INTO ledger_function_versions(scope,project,id,version,data,reason,at,task) VALUES(?,?,?,?,?,?,?,?)', project, fn.id, fn.version, stable(fn), reason, this.clock(), task ?? null);
124
+ }
125
+ putFunction(project, fn, reason = 'package.changed', task) {
126
+ this.db.prepare('UPDATE ledger_functions SET stage=?,data=? WHERE scope=? AND project=? AND id=?').run(fn.stage, stable(fn), this.scope, project, fn.id);
127
+ this.recordVersion(project, fn, reason, task);
128
+ }
129
+ task(id) {
130
+ const row = this.get('SELECT data FROM ledger_tasks WHERE scope=? AND id=?', identifier(id));
131
+ if (!row)
132
+ fail('notFound', 'Task was not found.');
133
+ return JSON.parse(String(row.data));
134
+ }
135
+ putTask(task) { this.db.prepare('UPDATE ledger_tasks SET status=?,data=? WHERE scope=? AND id=?').run(task.status, stable(task), this.scope, task.id); }
136
+ insertTask(task) { this.run('INSERT INTO ledger_tasks(scope,id,project,status,data) VALUES(?,?,?,?,?)', task.id, task.project, task.status, stable(task)); }
137
+ unlock(task) { this.run('DELETE FROM ledger_locks WHERE scope=? AND task=?', task.id); }
138
+ holder(project, resource) { return this.get('SELECT task FROM ledger_locks WHERE scope=? AND project=? AND resource=?', project, resource); }
139
+ insertEvent(project, revision, kind, data) {
140
+ this.run(`INSERT INTO ledger_events(scope,seq,project,revision,kind,data) VALUES(?,(SELECT coalesce(max(seq),0)+1 FROM ledger_events WHERE scope=?),?,?,?,?)`, this.scope, project, revision, kind, stable({ at: this.clock(), client: this.client, ...data }));
141
+ }
142
+ event(project, kind, data, planning = true) {
143
+ project.revision++;
144
+ if (planning)
145
+ project.planningRevision = project.revision;
146
+ this.putProject(project);
147
+ this.insertEvent(project.id, project.revision, kind, object(data));
148
+ }
149
+ /** An explicit epoch must match; omission is allowed. */
150
+ checkEpoch(project, epoch) {
151
+ if (epoch !== undefined && identifier(epoch) !== project.epoch)
152
+ fail('staleEpoch', 'This epoch belongs to another work incarnation; read a fresh brief.');
153
+ }
154
+ cancelled(task) {
155
+ fail('taskCancelled', 'Task was cancelled and cannot be resumed; request new work with work next.', { task: task.id, reason: task.result, functions: task.functions, retry: `work next --kind ${task.kind} --functions ${task.functions.join(',')}` + (task.discover ?
156
+ ` --strategy ${task.discover.strategy} --direction ${task.discover.direction} --max-depth ${task.discover.maxDepth} --max-functions ${task.discover.maxFunctions}` : '') });
157
+ }
158
+ planning(project, expected, epoch) {
159
+ this.checkEpoch(project, epoch);
160
+ const value = integer(expected, 1, Number.MAX_SAFE_INTEGER);
161
+ if (value < (project.planningRevision ?? project.revision) || value > project.revision)
162
+ fail('staleRevision', 'Refresh the shared brief before planning.', { currentRevision: project.revision, planningRevision: project.planningRevision, epoch: project.epoch });
163
+ }
164
+ /**
165
+ * The current lease of `worker` at `fence` and its project, or a concrete reason why it is not current. The task lock
166
+ * reserves the assigned functions, so they still have their planned versions.
167
+ */
168
+ lease(taskId, worker, fence, epoch) {
169
+ const task = this.task(taskId);
170
+ const project = this.project(task.project);
171
+ this.checkEpoch(project, epoch);
172
+ if (task.status === 'cancelled')
173
+ this.cancelled(task);
174
+ if (task.epoch !== project.epoch)
175
+ fail('staleEpoch', 'Assignment belongs to another work incarnation.');
176
+ worker = identifier(worker);
177
+ fence = integer(fence, 1, Number.MAX_SAFE_INTEGER);
178
+ const holder = { task: task.id, status: task.status, worker: task.worker ?? null, fence: task.fence, leaseUntil: task.leaseUntil || null };
179
+ if (fence !== task.fence)
180
+ fail('staleFence', `Lease fence ${fence} is stale; the task was reclaimed with fence ${task.fence}.`, holder);
181
+ if (task.status !== 'leased')
182
+ fail('staleLease', `Lease ended: the task is ${task.status}.`, holder);
183
+ if (task.worker !== worker)
184
+ fail('leaseHeld', `Lease is held by worker ${task.worker}.`, holder);
185
+ if (task.leaseUntil <= this.clock())
186
+ fail('leaseExpired', 'Lease expired; claim the task again for a new fence.', holder);
187
+ return { task, project };
188
+ }
189
+ /** `reservations`: the cause concerns reserved packages or resources only, which a discovery never holds. */
190
+ invalidateTasks(project, reason, functionIds, reservations = false) {
191
+ const ids = [];
192
+ for (const row of this.all("SELECT data FROM ledger_tasks WHERE scope=? AND project=? AND status IN ('queued','leased') ORDER BY id", project.id)) {
193
+ const task = JSON.parse(String(row.data));
194
+ if (functionIds && !task.functions.some(id => functionIds.has(id)))
195
+ continue;
196
+ if (reservations && task.kind === 'discover')
197
+ continue;
198
+ const previous = { ...task };
199
+ task.status = 'cancelled';
200
+ task.fence = integer(task.fence + 1, 1, Number.MAX_SAFE_INTEGER);
201
+ task.leaseUntil = 0;
202
+ task.result = { reason, replanRequired: true };
203
+ this.putTask(task);
204
+ this.unlock(task);
205
+ this.event(project, 'task.invalidated', { reason, previous, task: task.id });
206
+ ids.push(task.id);
207
+ }
208
+ return ids;
209
+ }
210
+ /**
211
+ * Only a writer edge reserves its target exclusively. Calls/reads are read dependencies: they are
212
+ * visible in handoff and invalidate packages of their endpoints when new, but never lock.
213
+ */
214
+ retainGraphResources(project, edge) {
215
+ const fn = String(edge.source), resource = String(edge.target);
216
+ if (edge.confidence === 'rejected' || !exclusiveEdgeKinds.includes(String(edge.kind)) || fn === resource
217
+ || !this.get('SELECT 1 FROM ledger_functions WHERE scope=? AND project=? AND id=?', project, fn))
218
+ return 0;
219
+ return Number(this.run('INSERT OR IGNORE INTO ledger_function_resources(scope,project,function_id,resource,evidence_edge) VALUES(?,?,?,?,?)', project, fn, resource, String(edge.id)).changes);
220
+ }
221
+ /** Exclusive keys from retained writer edges. */
222
+ derivedResources(project, fn, limit) {
223
+ return this.all(`SELECT DISTINCT r.resource FROM ledger_function_resources r JOIN ledger_graph_edges e ON e.scope=r.scope AND e.project=r.project AND e.id=r.evidence_edge
224
+ WHERE r.scope=? AND r.project=? AND r.function_id=? AND json_extract(e.data,'$.source')=r.function_id AND json_extract(e.data,'$.confidence')<>'rejected'
225
+ AND json_extract(e.data,'$.kind') IN (${exclusiveEdgeKinds.map(() => '?').join(',')}) LIMIT ?`, project, fn, ...exclusiveEdgeKinds, limit).map(row => String(row.resource));
226
+ }
227
+ /** Retained packages (with source) of the given functions become invalid; packages without source are untouched. */
228
+ invalidatePackages(project, reason, functionIds) {
229
+ const changed = new Set();
230
+ const rows = functionIds ? Array.from(functionIds, id => this.get('SELECT data FROM ledger_functions WHERE scope=? AND project=? AND id=?', project.id, id)) :
231
+ this.all('SELECT data FROM ledger_functions WHERE scope=? AND project=? ORDER BY id', project.id);
232
+ for (const row of rows) {
233
+ const fn = JSON.parse(String(row.data));
234
+ if (functionIds && !fn.source)
235
+ continue;
236
+ fn.version++;
237
+ fn.invalidated = { reason, at: this.clock() };
238
+ if (fn.source)
239
+ fn.stage = 'partial';
240
+ this.putFunction(project.id, fn, 'dependencies.changed');
241
+ changed.add(fn.id);
242
+ }
243
+ return changed;
244
+ }
245
+ reviseDefinition(projectId, functionId, expectedVersion, input, artifact, epoch) {
246
+ const project = this.project(projectId);
247
+ this.checkEpoch(project, epoch);
248
+ const current = this.function(project.id, functionId), manifest = object(input);
249
+ if (manifest.schema !== 1 || manifest.kind !== 'function-definition-revision' || manifest.binarySha256 !== project.binarySha256)
250
+ fail('binding', 'Revision requires the exact target hash and function-definition-revision kind.');
251
+ const next = definition(manifest.definition, project.binarySha256), reason = string(manifest.reason, 2000);
252
+ if (next.id !== current.id)
253
+ fail('binding', 'An entry change creates another anchor; it cannot revise this function.');
254
+ // The current definition already equals the revision: a repeat converges without a new version.
255
+ if (stable(next.definition) === stable(current.definition))
256
+ return { function: current.id, version: current.version, definitionRevision: current.definitionRevision, changed: false, revision: project.revision };
257
+ if (current.version !== integer(expectedVersion, 1, Number.MAX_SAFE_INTEGER))
258
+ fail('staleFunction', 'Definition/package changed; inspect it before revising.');
259
+ const cancelledTasks = this.invalidateTasks(project, reason, new Set([current.id])).length;
260
+ current.definition = next.definition;
261
+ current.resources = next.resources;
262
+ current.name = next.name;
263
+ current.risk = next.risk;
264
+ current.definitionRevision = (current.definitionRevision ?? 1) + 1;
265
+ current.invalidated = { reason, at: this.clock() };
266
+ current.version++;
267
+ if (current.source)
268
+ current.stage = 'partial';
269
+ this.putFunction(project.id, current, 'definition.revised');
270
+ this.event(project, 'definition.revised', { function: current.id, definitionRevision: current.definitionRevision, artifact, reason, cancelledTasks });
271
+ return { function: current.id, version: current.version, definitionRevision: current.definitionRevision, changed: true, cancelledTasks, revision: project.revision, accepted1to1: false };
272
+ }
273
+ history(projectId, functionId, after, limit) {
274
+ return this.tx(() => {
275
+ const project = this.project(projectId);
276
+ this.function(project.id, functionId);
277
+ const rows = this.all('SELECT version,data,reason,at,task FROM ledger_function_versions WHERE scope=? AND project=? AND id=? AND version>? ORDER BY version LIMIT ?', project.id, functionId, integer(after, 0, Number.MAX_SAFE_INTEGER), integer(limit, 1, 1000) + 1);
278
+ return { project: project.id, function: functionId, items: rows.slice(0, limit).map(row => ({ version: Number(row.version), data: JSON.parse(String(row.data)),
279
+ reason: String(row.reason), at: Number(row.at), task: row.task === null ? null : String(row.task) })),
280
+ nextAfterVersion: rows.length > limit ? Number(rows[limit - 1].version) : null, historyScope: 'Retained ledger versions; earlier package history is available only where legacy events captured it.' };
281
+ });
282
+ }
283
+ /** Explicitly withdraw a current approval without inventing a definition/source change. */
284
+ reopenReview(projectId, functionId, sourceSha256, expectedVersion, reason, epoch) {
285
+ const project = this.project(projectId);
286
+ this.checkEpoch(project, epoch);
287
+ const fn = this.function(project.id, functionId), why = string(reason, 2000);
288
+ const result = () => ({ function: fn.id, sourceSha256: fn.source.sha256, contractSha256: fn.contract.sha256, version: fn.version,
289
+ reviewState: reviewState(fn), revision: project.revision, accepted1to1: false });
290
+ // The same reopening already happened and nothing changed since: return it.
291
+ if (fn.reviewRequired?.reason === why && fn.reviewRequired.sourceSha256 === sourceSha256 && fn.version === expectedVersion + 1 && fn.source && fn.contract)
292
+ return result();
293
+ if (fn.version !== integer(expectedVersion, 1, Number.MAX_SAFE_INTEGER))
294
+ fail('staleFunction', 'Package changed; inspect it before reopening review.');
295
+ if (!fn.source || fn.source.sha256 !== sha(sourceSha256) || !fn.contract)
296
+ fail('binding', 'Reopening review must name the current source hash and retained package.');
297
+ if (fn.invalidated || reviewState(fn) !== 'approved' || !['reviewed', 'partial'].includes(fn.stage))
298
+ fail('conflict', 'Only a current approved, non-invalidated package can be reopened.');
299
+ if (this.holder(project.id, fn.id))
300
+ fail('reservedFunction', 'Complete or cancel the outstanding assignment before reopening review.');
301
+ fn.reviewRequired = { reason: why, at: this.clock(), sourceSha256: fn.source.sha256, contractSha256: fn.contract.sha256 };
302
+ fn.stage = 'partial';
303
+ fn.version++;
304
+ this.putFunction(project.id, fn, 'review.reopened');
305
+ this.event(project, 'review.reopened', { function: fn.id, sourceSha256: fn.source.sha256, contractSha256: fn.contract.sha256,
306
+ previousReview: fn.review, reason: why, version: fn.version });
307
+ return result();
308
+ }
309
+ create(projectId, targetId, name) {
310
+ const id = identifier(projectId);
311
+ name = string(name);
312
+ const target = this.db.prepare('SELECT id,sha256 FROM targets WHERE project_id=? AND id=?').get(this.scope, string(targetId, 128));
313
+ if (!target)
314
+ fail('notFound', 'Target is not registered in this hub project; see ghidra targets list.');
315
+ const strict1to1 = 'No function is accepted without a replayable exhaustive/formal verifier.';
316
+ const prior = this.get('SELECT data FROM ledger_projects WHERE scope=? AND id=?', id);
317
+ if (prior) {
318
+ const project = JSON.parse(String(prior.data));
319
+ if (project.target === target.id && project.name === name)
320
+ return { project, strict1to1 };
321
+ fail('conflict', 'Project ID already exists with another target or name.');
322
+ }
323
+ const project = { id, target: String(target.id), binarySha256: String(target.sha256), name, revision: 1, planningRevision: 1, epoch: randomUUID(),
324
+ phase: 'reverse-engineering', inventory: { complete: false, reportedTotal: null, sources: [] }, createdAt: this.clock() };
325
+ this.run('INSERT INTO ledger_projects(scope,id,data) VALUES(?,?,?)', id, stable(project));
326
+ this.insertEvent(id, 1, 'project.created', { target: project.target });
327
+ return { project, strict1to1 };
328
+ }
329
+ importInventory(projectId, input, artifact, epoch) {
330
+ const project = this.project(projectId), manifest = object(input);
331
+ this.checkEpoch(project, epoch);
332
+ if (manifest.schema !== 1 || manifest.binarySha256 !== project.binarySha256)
333
+ fail('binding', 'Inventory schema/target SHA does not match this project.');
334
+ if (manifest.kind !== 'function-definitions')
335
+ fail('invalid', 'Only function definitions are admitted; unwind regions are not functions.');
336
+ const functions = array(manifest.functions, 5000).map(x => definition(x, project.binarySha256));
337
+ if (!functions.length || new Set(functions.map(f => f.id)).size !== functions.length)
338
+ fail('invalid', 'Inventory needs unique function entries.');
339
+ let added = 0;
340
+ for (const fn of functions) {
341
+ const previous = this.get('SELECT data FROM ledger_functions WHERE scope=? AND project=? AND id=?', project.id, fn.id);
342
+ if (previous) {
343
+ const prior = JSON.parse(String(previous.data));
344
+ if (stable(prior.definition) !== stable(fn.definition))
345
+ fail('conflict', 'Imported definition changed; do not overwrite retained reconstruction.');
346
+ }
347
+ else {
348
+ fn.definitionRevision = 1;
349
+ this.run('INSERT INTO ledger_functions(scope,project,id,rva,stage,data) VALUES(?,?,?,?,?,?)', project.id, fn.id, fn.rva, fn.stage, stable(fn));
350
+ added++;
351
+ this.recordVersion(project.id, fn, 'inventory.imported');
352
+ }
353
+ }
354
+ const total = Number(this.get('SELECT count(*) n FROM ledger_functions WHERE scope=? AND project=?', project.id).n);
355
+ const reportedTotal = manifest.reportedTotal === undefined ? project.inventory.reportedTotal : integer(manifest.reportedTotal, total, 100_000_000);
356
+ // The same inventory again changes nothing.
357
+ if (!added && reportedTotal === project.inventory.reportedTotal && project.inventory.sources.some(s => s.sha256 === artifact.sha256))
358
+ return { project: project.id, revision: project.revision, added, inventoryComplete: false };
359
+ project.inventory.reportedTotal = reportedTotal;
360
+ if (!project.inventory.sources.some(s => s.sha256 === artifact.sha256))
361
+ project.inventory.sources.push(artifact);
362
+ this.event(project, 'inventory.imported', { artifact, added, source: manifest.source ?? null, completeness: 'not-established' }, added > 0);
363
+ return { project: project.id, revision: project.revision, added, inventoryComplete: false };
364
+ }
365
+ /**
366
+ * "Has unknowns" is not "needs rework". A partial package returns to the reconstruct lane only when
367
+ * it has no source, was invalidated by new evidence/definition, or a reviewer rejected it. Partial
368
+ * packages with current source go to review; an approval records the review but keeps them partial.
369
+ */
370
+ static needsRework(fn) {
371
+ return fn.stage === 'discovered' || fn.stage === 'mismatch' || fn.stage === 'partial' && (!fn.source || !!fn.invalidated || fn.review?.approved === false);
372
+ }
373
+ static reviewable(fn) {
374
+ if (fn.stage === 'reconstructed' || fn.stage === 'corpus_match')
375
+ return true;
376
+ return fn.stage === 'partial' && !!fn.source && !fn.invalidated && (!!fn.reviewRequired || fn.review?.sourceSha256 !== fn.source.sha256);
377
+ }
378
+ static reviewSql = `(stage IN ('reconstructed','corpus_match') OR stage='partial' AND json_extract(data,'$.source') IS NOT NULL
379
+ AND json_extract(data,'$.invalidated') IS NULL AND (json_extract(data,'$.reviewRequired') IS NOT NULL
380
+ OR json_extract(data,'$.review.sourceSha256') IS NOT json_extract(data,'$.source.sha256')))`;
381
+ static reworkSql = `(stage IN ('discovered','mismatch') OR stage='partial' AND (json_extract(data,'$.source') IS NULL
382
+ OR json_extract(data,'$.invalidated') IS NOT NULL OR json_extract(data,'$.review.approved')=0))`;
383
+ plan(projectId, expectedRevision, count, kind, selected, afterRva = -1, epoch, excludeAuthor, discover) {
384
+ const project = this.project(projectId);
385
+ this.planning(project, expectedRevision, epoch);
386
+ count = integer(count, 1, 50);
387
+ if (!taskKinds.includes(kind))
388
+ fail('invalid', 'Task kind is reconstruct, review or discover.');
389
+ if (selected && (!selected.length || selected.length > count || new Set(selected).size !== selected.length))
390
+ fail('scope', 'Explicit function selection must contain 1..count unique IDs.');
391
+ if (kind === 'discover')
392
+ return this.planDiscovery(project, selected, discover);
393
+ if (discover)
394
+ fail('invalid', 'Traversal options apply only to --kind discover.');
395
+ // Explicit reconstruct selection may rework any package that is not reviewed/reconstructed;
396
+ // automatic selection serves new functions first, then packages that need rework.
397
+ const eligible = (fn) => kind === 'review' ? LedgerStore.reviewable(fn)
398
+ : selected ? ['discovered', 'partial', 'mismatch'].includes(fn.stage) : LedgerStore.needsRework(fn);
399
+ const lanes = kind === 'review' ? [LedgerStore.reviewSql] : ["stage='discovered'", `stage<>'discovered' AND ${LedgerStore.reworkSql}`];
400
+ const start = integer(afterRva, -1, 0xffffffff), own = kind === 'review' && excludeAuthor !== undefined;
401
+ const accepted = [], resources = new Set(), holders = new Set();
402
+ let scanned = 0, skippedHubs = 0, reserved = 0, ownWork = 0, lane = 0, cursor = start;
403
+ // Automatic selection reads only eligible functions not reserved themselves (lock primary key), lane by lane in rva order.
404
+ const free = `NOT EXISTS(SELECT 1 FROM ledger_locks l WHERE l.scope=f.scope AND l.project=f.project AND l.resource=f.id)`;
405
+ const page = () => selected ? selected.map(id => this.function(project.id, id)) :
406
+ this.all(`SELECT data FROM ledger_functions f WHERE scope=? AND project=? AND rva>? AND ${lanes[lane]} AND ${free}${own ? " AND json_extract(data,'$.author') IS NOT ?" : ''}
407
+ ORDER BY rva LIMIT 256`, project.id, cursor, ...(own ? [excludeAuthor] : [])).map(row => JSON.parse(String(row.data)));
408
+ scan: while (accepted.length < count) {
409
+ const candidates = page();
410
+ if (!candidates.length) {
411
+ if (selected || ++lane >= lanes.length)
412
+ break;
413
+ cursor = start;
414
+ continue;
415
+ }
416
+ scanned += candidates.length;
417
+ for (const fn of candidates) {
418
+ if (accepted.length >= count)
419
+ break;
420
+ cursor = fn.rva;
421
+ if (!eligible(fn) || kind === 'review' && excludeAuthor !== undefined && fn.author === excludeAuthor) {
422
+ if (eligible(fn))
423
+ ownWork++;
424
+ if (selected)
425
+ fail('conflict', 'Function is not eligible for the requested work kind.');
426
+ continue;
427
+ }
428
+ const derived = this.derivedResources(project.id, fn.id, 10001);
429
+ if (derived.length > 10000) {
430
+ if (selected)
431
+ fail('limit', 'Exclusive resource frontier exceeds 10000; use a smaller investigated scope.');
432
+ skippedHubs++;
433
+ continue;
434
+ }
435
+ const keys = [...new Set([fn.id, ...fn.resources, ...derived])];
436
+ if (new Set([...resources, ...keys]).size > 10000) {
437
+ if (selected || !accepted.length)
438
+ fail('limit', 'Assignment resource set exceeds 10000; reduce the function count.');
439
+ break scan;
440
+ }
441
+ const holder = keys.map(key => this.holder(project.id, key)).find(Boolean);
442
+ if (holder) {
443
+ if (selected)
444
+ fail('conflict', 'Explicitly selected function/resource is already reserved.');
445
+ reserved++;
446
+ holders.add(String(holder.task));
447
+ continue;
448
+ }
449
+ accepted.push(fn);
450
+ keys.forEach(key => resources.add(key));
451
+ }
452
+ if (selected)
453
+ break;
454
+ }
455
+ if (!accepted.length) {
456
+ if (!selected) {
457
+ // Functions reserved themselves were not read; the reply still names them and their holders.
458
+ const any = `(${lanes.join(' OR ')})`, locked = `SELECT l.task FROM ledger_functions f JOIN ledger_locks l ON l.scope=f.scope AND l.project=f.project AND l.resource=f.id
459
+ WHERE f.scope=? AND f.project=? AND ${any}`;
460
+ reserved += Number(this.get(`SELECT count(*) n FROM (${locked})`, project.id).n);
461
+ for (const row of this.all(`SELECT DISTINCT task FROM (${locked}) LIMIT 20`, project.id))
462
+ holders.add(String(row.task));
463
+ if (own)
464
+ ownWork += Number(this.get(`SELECT count(*) n FROM ledger_functions f WHERE scope=? AND project=? AND ${any} AND ${free} AND json_extract(data,'$.author')=?`, project.id, excludeAuthor).n);
465
+ }
466
+ const waiting = Number(this.get(`SELECT count(*) n FROM ledger_functions WHERE scope=? AND project=? AND ${LedgerStore.reworkSql}`, project.id).n);
467
+ const waitingIds = this.all(`SELECT id FROM ledger_functions WHERE scope=? AND project=? AND ${LedgerStore.reworkSql} ORDER BY rva LIMIT 20`, project.id).map(row => String(row.id));
468
+ // Name who holds the reservations: a released lease keeps its scope until claimed again or cancelled.
469
+ const reservedBy = [...holders].slice(0, 20).map(id => {
470
+ const t = this.task(id);
471
+ return { task: t.id, status: t.status, worker: t.worker ?? null, leaseUntil: t.leaseUntil || null, functions: t.functions.length };
472
+ });
473
+ const hint = reserved ? 'Eligible functions are reserved by tasks in progress (reservedBy); a released or expired task is handed out by the '
474
+ + 'next work next. Retry after they are submitted, released or expire.'
475
+ : ownWork ? 'Remaining review candidates are your own reconstructions; another worker must review them.'
476
+ : kind === 'review' && waiting ? `${waiting} functions need (re)construction before review; take --kind reconstruct work.`
477
+ : 'No eligible function remains for this work kind.';
478
+ fail('noWork', 'No unreserved eligible function was found. ' + hint, { scanned, reserved, ownWork, skippedHubs, awaitingReconstruction: waiting, awaitingReconstructionIds: waitingIds, reservedBy });
479
+ }
480
+ if (Buffer.byteLength(stable([...resources])) > 512 * 1024)
481
+ fail('limit', 'Assignment resource bytes exceed 512 KiB; reduce the function count.');
482
+ const task = { id: 'w_' + randomUUID(), project: project.id, kind, status: 'queued',
483
+ functions: accepted.map(f => f.id), versions: Object.fromEntries(accepted.map(f => [f.id, f.version])),
484
+ resources: [...resources].sort(), fence: 0, leaseUntil: 0, createdAt: this.clock(), epoch: project.epoch };
485
+ this.insertTask(task);
486
+ for (const resource of resources)
487
+ this.run('INSERT INTO ledger_locks(scope,project,resource,task) VALUES(?,?,?,?)', project.id, resource, task.id);
488
+ this.event(project, 'task.planned', { task });
489
+ return { task, revision: project.revision };
490
+ }
491
+ /**
492
+ * A discovery task reads the call graph around explicit roots and changes no function, so it reserves nothing:
493
+ * reconstruction and review of the same functions continue meanwhile.
494
+ */
495
+ planDiscovery(project, roots, scope) {
496
+ if (!roots)
497
+ fail('invalid', 'Discovery needs explicit root function IDs: --functions.');
498
+ if (!scope)
499
+ fail('invalid', 'Discovery needs its traversal scope.');
500
+ if (roots.length > scope.maxFunctions)
501
+ fail('scope', 'Every root is visited: --max-functions must be at least the number of roots.');
502
+ const functions = roots.map(id => this.function(project.id, id));
503
+ const task = { id: 'w_' + randomUUID(), project: project.id, kind: 'discover', status: 'queued',
504
+ functions: functions.map(f => f.id), versions: Object.fromEntries(functions.map(f => [f.id, f.version])),
505
+ resources: [], fence: 0, leaseUntil: 0, createdAt: this.clock(), epoch: project.epoch, discover: scope };
506
+ this.insertTask(task);
507
+ this.event(project, 'task.planned', { task });
508
+ return { task, revision: project.revision };
509
+ }
510
+ claim(taskId, worker, ttl) {
511
+ const task = this.task(taskId), project = this.project(task.project);
512
+ worker = identifier(worker);
513
+ ttl = integer(ttl, 30, 3600);
514
+ if (task.status === 'cancelled')
515
+ this.cancelled(task);
516
+ const now = this.clock();
517
+ // Claiming the lease you already hold returns it unchanged.
518
+ if (task.status === 'leased' && task.worker === worker && task.leaseUntil > now)
519
+ return { task, revision: project.revision, lease: leaseToken(task) };
520
+ if (task.status === 'submitted')
521
+ fail('alreadyClaimed', 'Task is already submitted.', { task: task.id, worker: task.worker ?? null });
522
+ if (task.status === 'leased' && task.leaseUntil > now)
523
+ fail('alreadyClaimed', `Task has an active lease held by worker ${task.worker}.`, { task: task.id, worker: task.worker, leaseUntil: task.leaseUntil });
524
+ if (task.kind === 'review' && task.functions.some(id => this.function(task.project, id).author === worker))
525
+ fail('selfReview', 'Reviewer must differ from every reconstruction author in this slice.');
526
+ // A queued task keeps its reservation: every change of an assigned function cancels the task or is refused.
527
+ task.status = 'leased';
528
+ task.worker = worker;
529
+ task.fence = integer(task.fence + 1, 1, Number.MAX_SAFE_INTEGER);
530
+ task.leaseUntil = now + ttl * 1000;
531
+ this.putTask(task);
532
+ this.event(project, 'task.claimed', { task: task.id, worker, fence: task.fence, leaseUntil: task.leaseUntil }, false);
533
+ return { task, revision: project.revision, lease: leaseToken(task) };
534
+ }
535
+ /** Plan and claim one slice atomically at the current state; no observed revision is needed. */
536
+ next(projectId, worker, count, kind, ttl, epoch, selected, discover) {
537
+ const project = this.project(projectId);
538
+ worker = identifier(worker);
539
+ if (selected) {
540
+ count = Math.max(count, selected.length);
541
+ // The same explicit request by the same worker returns the lease it already holds.
542
+ const wanted = stable([...selected].sort());
543
+ for (const row of this.all("SELECT data FROM ledger_tasks WHERE scope=? AND project=? AND status='leased'", project.id)) {
544
+ const held = JSON.parse(String(row.data));
545
+ if (held.worker === worker && held.kind === kind && held.leaseUntil > this.clock() && stable([...held.functions].sort()) === wanted && stable(held.discover ?? null) === stable(discover ?? null))
546
+ return { task: held, revision: project.revision, lease: leaseToken(held) };
547
+ }
548
+ }
549
+ // Outstanding work goes out first: a released task, or one whose lease expired (its agent stopped or crashed), keeps
550
+ // its reservation and is handed to the next worker with a new fence, oldest first.
551
+ if (!selected) {
552
+ const now = this.clock();
553
+ for (const row of this.all("SELECT data FROM ledger_tasks WHERE scope=? AND project=? AND status IN ('queued','leased') ORDER BY json_extract(data,'$.createdAt'),id", project.id)) {
554
+ const open = JSON.parse(String(row.data));
555
+ if (kind === 'discover' || open.kind !== kind || open.epoch !== project.epoch || open.status === 'leased' && open.leaseUntil > now)
556
+ continue;
557
+ if (kind === 'review' && open.functions.some(id => this.function(project.id, id).author === worker))
558
+ continue;
559
+ return this.claim(open.id, worker, ttl);
560
+ }
561
+ }
562
+ // A worker retry may only take packages that still need rework; plan --functions remains the orchestrator override.
563
+ if (selected && kind === 'reconstruct')
564
+ for (const id of selected)
565
+ if (!LedgerStore.needsRework(this.function(project.id, id)))
566
+ fail('conflict', 'Function no longer needs rework (already resubmitted or awaiting review); take plain work next.', { function: id });
567
+ const planned = this.plan(project.id, project.revision, count, kind, selected, -1, epoch, worker, discover);
568
+ return this.claim(planned.task.id, worker, ttl);
569
+ }
570
+ heartbeat(taskId, worker, fence, ttl, epoch) {
571
+ const { task, project } = this.lease(taskId, worker, fence, epoch);
572
+ task.leaseUntil = this.clock() + integer(ttl, 30, 3600) * 1000;
573
+ this.putTask(task);
574
+ this.event(project, 'task.renewed', { task: task.id, worker, fence }, false);
575
+ return { task, revision: project.revision };
576
+ }
577
+ release(taskId, worker, fence, epoch) {
578
+ const current = this.task(taskId);
579
+ if (current.status === 'queued' && current.fence === fence) {
580
+ // Releasing again what this worker released at this fence returns the queued task.
581
+ const last = this.get(`SELECT data FROM ledger_events WHERE scope=? AND project=? AND kind IN ('task.released','task.claimed') AND json_extract(data,'$.task')=? ORDER BY seq DESC LIMIT 1`, current.project, current.id);
582
+ const data = last ? JSON.parse(String(last.data)) : {};
583
+ if (data.worker === worker && data.fence === fence && !data.leaseUntil)
584
+ return { task: current, revision: this.project(current.project).revision };
585
+ }
586
+ const { task, project } = this.lease(taskId, worker, fence, epoch);
587
+ task.status = 'queued';
588
+ delete task.worker;
589
+ task.leaseUntil = 0;
590
+ this.putTask(task);
591
+ this.event(project, 'task.released', { task: task.id, worker, fence }, false);
592
+ return { task, revision: project.revision };
593
+ }
594
+ cancel(taskId, expectedRevision, reason, epoch) {
595
+ const task = this.task(taskId), project = this.project(task.project), why = string(reason, 2000);
596
+ if (task.status === 'cancelled' && task.result?.reason === why)
597
+ return { task, revision: project.revision };
598
+ this.planning(project, expectedRevision, epoch);
599
+ if (!['queued', 'leased'].includes(task.status))
600
+ fail('conflict', 'Only an outstanding task can be cancelled.');
601
+ task.status = 'cancelled';
602
+ task.fence = integer(task.fence + 1, 1, Number.MAX_SAFE_INTEGER);
603
+ task.leaseUntil = 0;
604
+ task.result = { reason: why };
605
+ this.putTask(task);
606
+ this.unlock(task);
607
+ this.event(project, 'task.cancelled', { task: task.id, reason: why });
608
+ return { task, revision: project.revision };
609
+ }
610
+ /** A submitted task whose stored outcome equals this repeat; anything else goes through the lease checks. */
611
+ resubmitted(taskId, worker, fence, same) {
612
+ const task = this.task(taskId);
613
+ if (task.status !== 'submitted' || task.worker !== worker || task.fence !== fence || !same(object(task.result ?? {})))
614
+ return;
615
+ return { task, revision: this.project(task.project).revision, accepted1to1: false };
616
+ }
617
+ submit(taskId, worker, fence, entries, epoch) {
618
+ const binding = stable(entries.map(e => ({ id: e.id, source: e.source.sha256, contract: e.contract.sha256 })).sort((a, b) => a.id < b.id ? -1 : 1));
619
+ const repeat = this.resubmitted(taskId, worker, fence, r => stable(r.packages ?? null) === binding);
620
+ if (repeat)
621
+ return repeat;
622
+ const { task, project } = this.lease(taskId, worker, fence, epoch);
623
+ if (task.kind !== 'reconstruct')
624
+ fail('invalid', task.kind === 'review' ? 'Use review for a review assignment.' : 'A discover assignment takes a discovery report.');
625
+ if (entries.length !== task.functions.length || new Set(entries.map(e => e.id)).size !== entries.length
626
+ || entries.some(e => !task.functions.includes(e.id)))
627
+ fail('scope', 'Submission must cover exactly the assigned slice.');
628
+ for (const entry of entries) {
629
+ const fn = this.function(project.id, entry.id), contract = passport(entry.passport);
630
+ fn.source = entry.source;
631
+ fn.contract = entry.contract;
632
+ fn.passport = contract;
633
+ fn.author = task.worker;
634
+ fn.packageDefinitionRevision = fn.definitionRevision;
635
+ delete fn.invalidated;
636
+ fn.stage = contract.unknowns.length ? 'partial' : 'reconstructed';
637
+ fn.version++;
638
+ delete fn.review;
639
+ delete fn.reviewRequired;
640
+ delete fn.comparison;
641
+ this.putFunction(project.id, fn, 'package.changed', task.id);
642
+ }
643
+ task.status = 'submitted';
644
+ task.leaseUntil = 0;
645
+ task.result = { functions: entries.map(e => e.id), packages: JSON.parse(binding), accepted1to1: false };
646
+ this.putTask(task);
647
+ this.unlock(task);
648
+ this.event(project, 'reconstruction.submitted', { task: task.id, worker, functions: entries.map(e => e.id) });
649
+ return { task, revision: project.revision, accepted1to1: false };
650
+ }
651
+ /**
652
+ * Retains the discovery report of a leased discover task and completes it. Function stages and packages are
653
+ * untouched; newly found functions are registered only through an explicit work import.
654
+ */
655
+ submitDiscovery(taskId, worker, fence, report, artifact, epoch) {
656
+ const repeat = this.resubmitted(taskId, worker, fence, r => r.report?.sha256 === artifact.sha256);
657
+ if (repeat)
658
+ return repeat;
659
+ const { task, project } = this.lease(taskId, worker, fence, epoch);
660
+ if (task.kind !== 'discover' || !task.discover)
661
+ fail('invalid', 'Only a discover assignment takes a discovery report.');
662
+ if (integer(artifact.size, 1, Number.MAX_SAFE_INTEGER) > discoverLimits.reportBytes)
663
+ fail('limit', `A discovery report is at most ${discoverLimits.reportBytes} bytes.`);
664
+ const summary = discoveryReport(report, { task: task.id, binarySha256: project.binarySha256, roots: task.functions, scope: task.discover });
665
+ task.status = 'submitted';
666
+ task.leaseUntil = 0;
667
+ task.result = { report: artifact, ...summary, submittedAt: this.clock(), accepted1to1: false };
668
+ this.putTask(task);
669
+ this.event(project, 'discovery.submitted', { task: task.id, worker, report: artifact.sha256, visited: summary.visited, edges: summary.edges, frontier: summary.frontier });
670
+ return { task, revision: project.revision, accepted1to1: false };
671
+ }
672
+ review(taskId, worker, fence, decisions, epoch) {
673
+ const repeat = this.resubmitted(taskId, worker, fence, r => stable(r.decisions ?? null) === stable(decisions));
674
+ if (repeat)
675
+ return repeat;
676
+ const { task, project } = this.lease(taskId, worker, fence, epoch);
677
+ if (task.kind !== 'review')
678
+ fail('invalid', 'This is not a review assignment.');
679
+ if (decisions.length !== task.functions.length || new Set(decisions.map(e => e.id)).size !== decisions.length
680
+ || decisions.some(e => !task.functions.includes(e.id)))
681
+ fail('scope', 'Review must cover exactly the assigned slice.');
682
+ for (const decision of decisions) {
683
+ const fn = this.function(project.id, decision.id);
684
+ if (fn.invalidated)
685
+ fail('staleFunction', 'Reconstruct against the current definition/dependencies before review.');
686
+ if (fn.author === task.worker)
687
+ fail('selfReview', 'A reconstruction author cannot approve their own work.');
688
+ if (fn.source?.sha256 !== decision.sourceSha256)
689
+ fail('staleFunction', 'Review does not name the current source hash.');
690
+ fn.review = { worker: task.worker, sourceSha256: decision.sourceSha256, contractSha256: fn.contract?.sha256, note: decision.note, approved: decision.approved };
691
+ delete fn.reviewRequired;
692
+ // Approval never erases unknowns: a package with open unknowns stays partial with its review recorded.
693
+ const open = (fn.passport?.unknowns ?? []).length > 0;
694
+ fn.stage = decision.approved && !open ? 'reviewed' : 'partial';
695
+ fn.version++;
696
+ this.putFunction(project.id, fn, 'package.changed', task.id);
697
+ }
698
+ task.status = 'submitted';
699
+ task.leaseUntil = 0;
700
+ task.result = { decisions, accepted1to1: false };
701
+ this.putTask(task);
702
+ this.unlock(task);
703
+ this.event(project, 'review.submitted', { task: task.id, worker });
704
+ return { task, revision: project.revision, accepted1to1: false };
705
+ }
706
+ compare(projectId, functionId, sourceSha, original, reconstruction, artifacts, layout, epoch) {
707
+ const project = this.project(projectId), fn = this.function(project.id, functionId);
708
+ this.checkEpoch(project, epoch);
709
+ if (fn.invalidated)
710
+ fail('staleFunction', 'Reconstruct against the current definition/dependencies before comparison.');
711
+ if (this.holder(project.id, fn.id))
712
+ fail('reservedFunction', 'Comparison cannot change a reserved package. Complete or cancel its outstanding assignment first.');
713
+ if (!fn.source || fn.source.sha256 !== sourceSha)
714
+ fail('binding', 'Comparison must name the current reconstructed source.');
715
+ const a = object(original), b = object(reconstruction);
716
+ for (const value of [a, b])
717
+ if (value.schema !== 1 || value.binarySha256 !== project.binarySha256 || value.function !== fn.id)
718
+ fail('binding', 'Observation corpus belongs to another target or function.');
719
+ if (b.sourceSha256 !== sourceSha)
720
+ fail('binding', 'Reconstruction observations name another source.');
721
+ const cases = (value) => array(value, 10000).map(row => {
722
+ const c = object(row), outcome = object(c.outcome);
723
+ string(c.input, 65536);
724
+ if (outcome.encoding !== 'hex-bytes-v1' || typeof outcome.bytes !== 'string' || outcome.bytes.length > 131072 || !/^(?:[0-9a-f]{2})*$/.test(outcome.bytes))
725
+ fail('invalid', 'Outcomes need lossless lowercase hex-bytes-v1 bytes, not JSON numeric approximations.');
726
+ if (sha(outcome.layoutSha256) !== layout.sha256)
727
+ fail('binding', 'Outcome layout hash must match the retained layout artifact.');
728
+ return c;
729
+ });
730
+ const left = cases(a.cases), right = cases(b.cases);
731
+ if (!left.length || left.length !== right.length)
732
+ fail('invalid', 'Both corpora need the same nonempty input set.');
733
+ const indexed = new Map(right.map(c => [stable(c.input), c]));
734
+ if (indexed.size !== right.length || new Set(left.map(c => stable(c.input))).size !== left.length)
735
+ fail('invalid', 'Duplicate corpus inputs are not coverage.');
736
+ let mismatches = 0;
737
+ const firstMismatchInputs = [];
738
+ for (const c of left) {
739
+ const other = indexed.get(stable(c.input));
740
+ if (!other)
741
+ fail('invalid', 'Corpus input sets differ.');
742
+ if (stable(c.outcome) !== stable(other.outcome)) {
743
+ mismatches++;
744
+ if (firstMismatchInputs.length < 5)
745
+ firstMismatchInputs.push(c.input);
746
+ }
747
+ }
748
+ const result = { cases: left.length, mismatches, firstMismatchInputs, artifacts, layout, sourceSha256: sourceSha,
749
+ level: 'supplied-corpus-comparison', origin: 'Input observations are reported, not native-execution attestation', accepted1to1: false };
750
+ // The same comparison of the same package is already retained.
751
+ if (stable(fn.comparison ?? null) === stable(result))
752
+ return { project: project.id, revision: project.revision, ...result };
753
+ const unknowns = Array.isArray(fn.passport?.unknowns) ? fn.passport.unknowns : [];
754
+ const rejected = fn.review?.approved === false;
755
+ fn.comparison = result;
756
+ fn.stage = mismatches ? 'mismatch' : unknowns.length || rejected || fn.reviewRequired ? 'partial' : fn.stage === 'reviewed' ? 'reviewed' : 'corpus_match';
757
+ fn.version++;
758
+ if (mismatches && !rejected)
759
+ delete fn.review;
760
+ this.putFunction(project.id, fn);
761
+ this.event(project, 'corpus.compared', { function: fn.id, ...result });
762
+ return { project: project.id, revision: project.revision, ...result };
763
+ }
764
+ certify() { fail('proofVerifierUnavailable', 'Strict 1:1 acceptance requires a supported replayable exhaustive/formal verifier. Corpus matches, reviews and uploaded passed flags cannot authorize it.'); }
765
+ importGraph(projectId, input, artifact, epoch) {
766
+ const project = this.project(projectId), manifest = object(input);
767
+ this.checkEpoch(project, epoch);
768
+ let changed = 0;
769
+ if (manifest.schema !== 1 || manifest.binarySha256 !== project.binarySha256 || manifest.kind !== 'dependency-graph')
770
+ fail('binding', 'Graph schema, kind and full target hash are required.');
771
+ const nodes = array(manifest.nodes, 5000).map(object), edges = array(manifest.edges, 10000).map(object);
772
+ const kinds = ['global', 'type', 'vtable', 'dispatch-site', 'packet', 'asset-package', 'subsystem', 'source-declaration'];
773
+ const affected = new Set();
774
+ const expanded = new Set();
775
+ const put = (table, row) => {
776
+ const id = string(row.id, 256), data = stable(row), prior = this.get(`SELECT data FROM ledger_${table} WHERE scope=? AND project=? AND id=?`, project.id, id);
777
+ if (prior && prior.data !== data)
778
+ fail('conflict', 'Graph evidence is additive. Correct with a new record ID.');
779
+ if (!prior) {
780
+ this.run(`INSERT INTO ledger_${table}(scope,project,id,data) VALUES(?,?,?,?)`, project.id, id, data);
781
+ changed++;
782
+ }
783
+ return !prior;
784
+ };
785
+ for (const node of nodes) {
786
+ const kind = string(node.kind);
787
+ string(node.label);
788
+ string(node.evidence, 4000);
789
+ if (!kinds.includes(kind) || !string(node.id, 256).startsWith(`${kind}:${project.binarySha256}:`))
790
+ fail('binding', 'Graph node ID must include its kind and full target hash. Function definitions use inventory import.');
791
+ if (!['observed', 'reported', 'hypothesis', 'rejected'].includes(String(node.confidence)))
792
+ fail('invalid', 'Node confidence is explicit.');
793
+ put('graph_nodes', node);
794
+ }
795
+ const isFunction = (id) => !!this.get('SELECT 1 FROM ledger_functions WHERE scope=? AND project=? AND id=?', project.id, id);
796
+ const endpoint = (value) => {
797
+ const id = string(value, 256);
798
+ if (!isFunction(id) && !this.get('SELECT 1 FROM ledger_graph_nodes WHERE scope=? AND project=? AND id=?', project.id, id))
799
+ fail('notFound', 'Graph endpoint has no explicit inventory node.');
800
+ return id;
801
+ };
802
+ for (const edge of edges) {
803
+ endpoint(edge.source);
804
+ endpoint(edge.target);
805
+ string(edge.kind, 128);
806
+ string(edge.evidence, 4000);
807
+ if (!['observed', 'reported', 'hypothesis', 'rejected'].includes(String(edge.confidence)))
808
+ fail('invalid', 'Edge confidence is explicit.');
809
+ if (put('graph_edges', edge) && edge.confidence !== 'rejected')
810
+ for (const end of [edge.source, edge.target])
811
+ if (isFunction(String(end)))
812
+ affected.add(String(end));
813
+ if (this.retainGraphResources(project.id, edge)) {
814
+ const owner = this.holder(project.id, String(edge.source));
815
+ if (owner && !this.get('SELECT 1 FROM ledger_locks WHERE scope=? AND project=? AND task=? AND resource=?', project.id, String(owner.task), String(edge.target)))
816
+ expanded.add(String(edge.source));
817
+ }
818
+ }
819
+ // Only endpoints of new non-rejected edges are affected: their retained packages become invalid and
820
+ // assignments that froze those packages are cancelled. Nodes and rejected edges invalidate nothing.
821
+ const invalidated = affected.size ? this.invalidatePackages(project, 'Dependency graph changed at this function', affected) : new Set();
822
+ const replan = new Set([...invalidated, ...expanded]);
823
+ const cancelled = replan.size ? this.invalidateTasks(project, 'Dependency evidence changed the package or its exclusive reservations', replan, true) : [];
824
+ // Counts are exact; ID lists are bounded to the first 100 and say so.
825
+ const ids = (values) => { const all = [...values].sort(); return { ids: all.slice(0, 100), truncated: all.length > 100 }; };
826
+ const impact = { affectedFunctionIds: ids(affected), invalidatedPackageIds: ids(invalidated), cancelledTaskIds: ids(cancelled) };
827
+ const known = project.inventory.sources.some(s => s.sha256 === artifact.sha256);
828
+ // The same graph again changes nothing.
829
+ if (!changed && known)
830
+ return { project: project.id, revision: project.revision, nodes: nodes.length, edges: edges.length, changed, affectedFunctions: 0,
831
+ invalidatedPackages: 0, cancelledTasks: 0, ...impact, graphComplete: false, impact: 'No new evidence.' };
832
+ if (!known)
833
+ project.inventory.sources.push(artifact);
834
+ this.event(project, 'graph.imported', { artifact, nodes: nodes.length, edges: edges.length, changed,
835
+ affectedFunctions: affected.size, invalidatedPackages: invalidated.size, cancelledTasks: cancelled.length, ...impact, complete: false }, changed > 0);
836
+ return { project: project.id, revision: project.revision, nodes: nodes.length, edges: edges.length, changed, affectedFunctions: affected.size,
837
+ invalidatedPackages: invalidated.size, cancelledTasks: cancelled.length, ...impact, graphComplete: false,
838
+ impact: 'Endpoint-scoped invalidation; only writer edges reserve resources. This is not proved dependency closure.' };
839
+ }
840
+ timing(projectId, selected) {
841
+ return this.tx(() => ({ project: this.context(projectId), ...timingReport(this.db, this.scope, projectId, selected) }));
842
+ }
843
+ context(projectId) {
844
+ const { id, target, binarySha256, epoch, revision } = this.project(projectId);
845
+ return { id, target, binarySha256, epoch, revision };
846
+ }
847
+ projects() { return this.tx(() => this.all('SELECT data FROM ledger_projects WHERE scope=? ORDER BY id').map(r => JSON.parse(String(r.data)))); }
848
+ events(projectId, after, limit) {
849
+ return this.tx(() => {
850
+ const project = this.project(projectId), rows = this.all('SELECT seq,revision,kind,data FROM ledger_events WHERE scope=? AND project=? AND seq>? ORDER BY seq LIMIT ?', project.id, integer(after, 0, Number.MAX_SAFE_INTEGER), integer(limit, 1, 1000) + 1);
851
+ return { project: project.id, revision: project.revision, items: rows.slice(0, limit).map(r => ({ ...r, data: JSON.parse(String(r.data)) })),
852
+ nextAfter: rows.length > limit ? Number(rows[limit - 1].seq) : null };
853
+ });
854
+ }
855
+ /** One consistent read of a project checkpoint, as JSONL records. */
856
+ export(projectId) {
857
+ return this.tx(() => {
858
+ const project = this.project(projectId), records = [];
859
+ const target = this.db.prepare('SELECT * FROM targets WHERE project_id=? AND id=?').get(this.scope, project.target);
860
+ records.push({ record: 'project', schema: 2, project, target: target ? { ...target } : null, generatedAt: this.clock(), accepted1to1: 0 });
861
+ for (const [table, record] of [['functions', 'function'], ['graph_nodes', 'node'], ['graph_edges', 'edge'], ['tasks', 'task']])
862
+ for (const row of this.all(`SELECT data FROM ledger_${table} WHERE scope=? AND project=? ORDER BY id`, project.id))
863
+ records.push({ record, value: JSON.parse(String(row.data)) });
864
+ for (const row of this.all('SELECT seq,revision,kind,data FROM ledger_events WHERE scope=? AND project=? ORDER BY seq', project.id))
865
+ records.push({ record: 'event', ...row, data: JSON.parse(String(row.data)) });
866
+ records.push({ record: 'end', revision: project.revision, recordsBeforeEnd: records.length, complete: true,
867
+ scope: 'This project workflow snapshot only; discovery/graph/1:1 remain incomplete. Attachments are hub blob references, not payload copies.' });
868
+ return { project: project.id, revision: project.revision, records };
869
+ });
870
+ }
871
+ graph(projectId, after, limit, kind) {
872
+ return this.tx(() => {
873
+ const project = this.project(projectId), table = kind === 'nodes' ? 'ledger_graph_nodes' : 'ledger_graph_edges';
874
+ const rows = this.all(`SELECT id,data FROM ${table} WHERE scope=? AND project=? AND id>? ORDER BY id LIMIT ?`, project.id, after, integer(limit, 1, 1000) + 1);
875
+ return { project: project.id, revision: project.revision, items: rows.slice(0, limit).map(r => JSON.parse(String(r.data))),
876
+ nextAfter: rows.length > limit ? String(rows[limit - 1].id) : null, complete: false };
877
+ });
878
+ }
879
+ handoff(taskId) {
880
+ return this.tx(() => {
881
+ const task = this.task(taskId), project = this.project(task.project);
882
+ if (task.kind === 'discover')
883
+ return { project, task, functions: task.functions.map(id => this.function(project.id, id)), discover: task.discover,
884
+ instructions: ['Walk the call graph from these roots yourself, through Ghidra xrefs or a pinned graph inventory, within discover.',
885
+ 'Visit each function once (module hash + RVA); roots are depth 0. Record calls you cannot resolve or that leave the depth/function limit as frontier.',
886
+ 'State for every visited function where its xrefs came from and whether that observation was complete: empty xrefs do not prove no calls.',
887
+ 'Submit one discovery-report with work submit. Register new functions only with work import. Another scope or strategy is a new task.'] };
888
+ return { project, task, functions: task.functions.map(id => this.function(project.id, id)),
889
+ instructions: ['Reconstruct only this assigned slice. Do not implement game/subsystems.',
890
+ 'Preserve ABI, exact effects, errors, ordering, unknowns and source evidence.',
891
+ 'Renew the lease. Submit with worker and current fence. A stale lease cannot write.',
892
+ 'Reconstruction, corpus equality and review are not universal 1:1 proof.'] };
893
+ });
894
+ }
895
+ snapshot(projectId, limit = 200) {
896
+ return this.tx(() => {
897
+ const project = this.project(projectId), counts = { discovered: 0, partial: 0, reconstructed: 0, corpus_match: 0, reviewed: 0, mismatch: 0 };
898
+ for (const row of this.all('SELECT stage,count(*) n FROM ledger_functions WHERE scope=? AND project=? GROUP BY stage', project.id))
899
+ counts[row.stage] = Number(row.n);
900
+ const count = (table) => Number(this.get(`SELECT count(*) n FROM ledger_${table} WHERE scope=? AND project=?`, project.id).n);
901
+ return { project, counts, trackedFunctions: Object.values(counts).reduce((a, b) => a + b, 0), accepted1to1: 0,
902
+ functions: this.all('SELECT data FROM ledger_functions WHERE scope=? AND project=? ORDER BY rva LIMIT ?', project.id, integer(limit, 1, 1000)).map(row => { const fn = JSON.parse(String(row.data)); return { ...fn, reviewState: reviewState(fn) }; }),
903
+ tasks: this.all('SELECT data FROM ledger_tasks WHERE scope=? AND project=? ORDER BY rowid DESC LIMIT 100', project.id).map(row => JSON.parse(String(row.data))),
904
+ events: this.all('SELECT seq,revision,kind,data FROM ledger_events WHERE scope=? AND project=? ORDER BY seq DESC LIMIT 50', project.id).map(row => ({ ...row, data: JSON.parse(String(row.data)) })),
905
+ graph: { nodes: this.all('SELECT data FROM ledger_graph_nodes WHERE scope=? AND project=? ORDER BY id LIMIT 200', project.id).map(r => JSON.parse(String(r.data))),
906
+ edges: this.all('SELECT data FROM ledger_graph_edges WHERE scope=? AND project=? ORDER BY id LIMIT 200', project.id).map(r => JSON.parse(String(r.data))),
907
+ nodeCount: count('graph_nodes'), edgeCount: count('graph_edges'), complete: false },
908
+ generatedAt: this.clock(), functionLimit: limit, limits: ['Inventory completeness is not established.', 'Universal 1:1 certification is unavailable; no function is accepted.', 'Displayed function/task/event slices are bounded.'] };
909
+ });
910
+ }
911
+ functions(projectId, after, limit) {
912
+ return this.tx(() => {
913
+ const project = this.project(projectId), rows = this.all('SELECT data FROM ledger_functions WHERE scope=? AND project=? AND rva>? ORDER BY rva LIMIT ?', project.id, integer(after, -1, 0xffffffff), integer(limit, 1, 1000) + 1).map(row => JSON.parse(String(row.data)));
914
+ const more = rows.length > limit, items = rows.slice(0, limit).map(fn => ({ ...fn, reviewState: reviewState(fn) }));
915
+ return { project: project.id, revision: project.revision, items,
916
+ nextAfterRva: more ? items.at(-1)?.rva : null, consistency: 'This page only; revision is explicit. This is not a frozen whole-project export.' };
917
+ });
918
+ }
919
+ }