@eyeauras/insight-cli 0.7.0 → 0.8.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 (133) hide show
  1. package/.cli-package-build.json +1 -1
  2. package/SKILL.md +1 -1
  3. package/dist/src/activity-audit.d.ts +7 -0
  4. package/dist/src/activity-audit.js +14 -4
  5. package/dist/src/analysis-storage.d.ts +5 -1
  6. package/dist/src/analysis-storage.js +9 -2
  7. package/dist/src/audit-retention.d.ts +8 -2
  8. package/dist/src/audit-retention.js +68 -7
  9. package/dist/src/cli.js +21 -5
  10. package/dist/src/context-diagnostics.d.ts +1 -1
  11. package/dist/src/context-diagnostics.js +10 -2
  12. package/dist/src/contexts.d.ts +118 -10
  13. package/dist/src/contexts.js +851 -199
  14. package/dist/src/debugger.js +2 -1
  15. package/dist/src/diagnostic-error.js +1 -1
  16. package/dist/src/inline-script.js +3 -4
  17. package/dist/src/lifecycle.d.ts +11 -0
  18. package/dist/src/lifecycle.js +34 -6
  19. package/dist/src/native-inputs.d.ts +6 -0
  20. package/dist/src/native-inputs.js +30 -6
  21. package/dist/src/native-queries.js +1 -6
  22. package/dist/src/native-service.d.ts +40 -0
  23. package/dist/src/native-service.js +406 -0
  24. package/dist/src/research.d.ts +29 -1
  25. package/dist/src/research.js +106 -27
  26. package/dist/src/server.d.ts +38 -1
  27. package/dist/src/server.js +160 -12
  28. package/dist/src/storage-gc.js +1 -1
  29. package/dist/src/sync-policy.js +2 -1
  30. package/dist/src/timed-backend.js +8 -0
  31. package/dist/src/timing-report.d.ts +32 -0
  32. package/dist/src/timing-report.js +74 -0
  33. package/dist/src/tool-runtime/identity.js +86 -1
  34. package/dist/src/tool-runtime/supervisor.js +6 -5
  35. package/dist/src/transport.d.ts +35 -0
  36. package/dist/src/transport.js +77 -7
  37. package/dist/src/unresolved-guidance.d.ts +46 -0
  38. package/dist/src/unresolved-guidance.js +55 -0
  39. package/dist/src/windbg.d.ts +1 -1
  40. package/dist/src/work/backup.d.ts +66 -0
  41. package/dist/src/work/backup.js +434 -0
  42. package/dist/src/work/commands.d.ts +5 -0
  43. package/dist/src/work/commands.js +277 -0
  44. package/dist/src/work/dashboard.d.ts +12 -0
  45. package/dist/src/work/dashboard.js +103 -0
  46. package/dist/src/work/model.d.ts +131 -0
  47. package/dist/src/work/model.js +124 -0
  48. package/dist/src/work/store.d.ts +368 -0
  49. package/dist/src/work/store.js +1050 -0
  50. package/dist/src/work/timing.d.ts +26 -0
  51. package/dist/src/work/timing.js +80 -0
  52. package/dist/src/worker-lease.d.ts +17 -0
  53. package/dist/src/worker-lease.js +50 -0
  54. package/dist/src/workspace.d.ts +5 -9
  55. package/dist/src/workspace.js +20 -41
  56. package/package.json +1 -1
  57. package/references/native/InsightHeadlessMain.java +9 -2
  58. package/references/native/InsightNativeCheckout.java +113 -43
  59. package/references/native/InsightNativeFingerprint.java +28 -1
  60. package/references/native/InsightNativeRead.java +32 -9
  61. package/references/native/InsightNativeService.java +43 -0
  62. package/references/native/InsightNativeView.java +17 -6
  63. package/references/native/InsightOwnedScripts.java +170 -0
  64. package/references/native/InsightWorkerLease.java +132 -0
  65. package/references/recovery.md +68 -3
  66. package/references/research.md +38 -4
  67. package/references/setup.md +5 -1
  68. package/references/work-tracking.md +203 -0
  69. package/runtime/toolbox.json +1 -0
  70. package/skill-bundle/insight-artifacts/SKILL.md +1 -1
  71. package/skill-bundle/insight-artifacts/references/recovery.md +68 -3
  72. package/skill-bundle/insight-binary/SKILL.md +1 -1
  73. package/skill-bundle/insight-capture/SKILL.md +1 -1
  74. package/skill-bundle/insight-cli/SKILL.md +1 -1
  75. package/skill-bundle/insight-cli/references/recovery.md +68 -3
  76. package/skill-bundle/insight-cli/references/setup.md +5 -1
  77. package/skill-bundle/insight-die/SKILL.md +1 -1
  78. package/skill-bundle/insight-dnspy/SKILL.md +1 -1
  79. package/skill-bundle/insight-dotnet-dump/SKILL.md +1 -1
  80. package/skill-bundle/insight-dotnet-stack/SKILL.md +1 -1
  81. package/skill-bundle/insight-dotnet-trace/SKILL.md +1 -1
  82. package/skill-bundle/insight-frida/SKILL.md +1 -1
  83. package/skill-bundle/insight-ghidra/SKILL.md +1 -1
  84. package/skill-bundle/insight-ghidra/references/recovery.md +68 -3
  85. package/skill-bundle/insight-ghidra/references/research.md +38 -4
  86. package/skill-bundle/insight-ghidra/references/setup.md +5 -1
  87. package/skill-bundle/insight-ilspy/SKILL.md +1 -1
  88. package/skill-bundle/insight-interop/SKILL.md +1 -1
  89. package/skill-bundle/insight-lldb/SKILL.md +1 -1
  90. package/skill-bundle/insight-llvm/SKILL.md +1 -1
  91. package/skill-bundle/insight-managed-heap/SKILL.md +1 -1
  92. package/skill-bundle/insight-managed-metadata/SKILL.md +1 -1
  93. package/skill-bundle/insight-mitmproxy/SKILL.md +1 -1
  94. package/skill-bundle/insight-overview/SKILL.md +1 -1
  95. package/skill-bundle/insight-procmon/SKILL.md +1 -1
  96. package/skill-bundle/insight-re/SKILL.md +5 -1
  97. package/skill-bundle/insight-re/references/recovery.md +68 -3
  98. package/skill-bundle/insight-re/references/work-tracking.md +203 -0
  99. package/skill-bundle/insight-sevenzip/SKILL.md +1 -1
  100. package/skill-bundle/insight-strace/SKILL.md +1 -1
  101. package/skill-bundle/insight-tshark/SKILL.md +1 -1
  102. package/skill-bundle/insight-windbg/SKILL.md +1 -1
  103. package/skill-bundle/manifest.json +1 -1
  104. package/skills/insight-artifacts/SKILL.md +1 -1
  105. package/skills/insight-artifacts/references/recovery.md +68 -3
  106. package/skills/insight-binary/SKILL.md +1 -1
  107. package/skills/insight-capture/SKILL.md +1 -1
  108. package/skills/insight-die/SKILL.md +1 -1
  109. package/skills/insight-dnspy/SKILL.md +1 -1
  110. package/skills/insight-dotnet-dump/SKILL.md +1 -1
  111. package/skills/insight-dotnet-stack/SKILL.md +1 -1
  112. package/skills/insight-dotnet-trace/SKILL.md +1 -1
  113. package/skills/insight-frida/SKILL.md +1 -1
  114. package/skills/insight-ghidra/SKILL.md +1 -1
  115. package/skills/insight-ghidra/references/recovery.md +68 -3
  116. package/skills/insight-ghidra/references/research.md +38 -4
  117. package/skills/insight-ghidra/references/setup.md +5 -1
  118. package/skills/insight-ilspy/SKILL.md +1 -1
  119. package/skills/insight-interop/SKILL.md +1 -1
  120. package/skills/insight-lldb/SKILL.md +1 -1
  121. package/skills/insight-llvm/SKILL.md +1 -1
  122. package/skills/insight-managed-heap/SKILL.md +1 -1
  123. package/skills/insight-managed-metadata/SKILL.md +1 -1
  124. package/skills/insight-mitmproxy/SKILL.md +1 -1
  125. package/skills/insight-overview/SKILL.md +1 -1
  126. package/skills/insight-procmon/SKILL.md +1 -1
  127. package/skills/insight-re/SKILL.md +5 -1
  128. package/skills/insight-re/references/recovery.md +68 -3
  129. package/skills/insight-re/references/work-tracking.md +203 -0
  130. package/skills/insight-sevenzip/SKILL.md +1 -1
  131. package/skills/insight-strace/SKILL.md +1 -1
  132. package/skills/insight-tshark/SKILL.md +1 -1
  133. package/skills/insight-windbg/SKILL.md +1 -1
@@ -9,17 +9,19 @@ import { launchProcess, terminateProcess, processStatus } from './tool-runtime/s
9
9
  import { runTool } from './tool-runtime/run.js';
10
10
  import { verifyGhidraProcess } from './ghidra-processes.js';
11
11
  import { processIdentity } from './tool-runtime/identity.js';
12
+ import { CliError } from '@eyeauras/cli-factory';
12
13
  import { runtimeProcesses } from './runtime-manager.js';
13
- import { randomUUID, randomBytes } from 'node:crypto';
14
- import { mkdir, mkdtemp, open, readFile, readdir, lstat, rename, link, realpath, copyFile, chmod, writeFile, unlink } from 'node:fs/promises';
14
+ import { randomUUID, randomBytes, createHash } from 'node:crypto';
15
+ import { mkdir, mkdtemp, open, readFile, readdir, lstat, rename, link, realpath, copyFile, chmod, writeFile, unlink, rm, stat } from 'node:fs/promises';
15
16
  import { constants } from 'node:fs';
16
17
  import { join, delimiter, resolve, dirname, basename } from 'node:path';
17
18
  import { createServer } from 'node:net';
18
19
  import { setTimeout as delay } from 'node:timers/promises';
19
- import { nativeHelpers, nativeInputs, nativeJvmDirectories, nativeExtensionArguments } from './native-inputs.js';
20
+ import { nativeHelpers, helperSourcesKey, nativeInputs, nativeJvmDirectories, nativeExtensionArguments } from './native-inputs.js';
20
21
  import { GhidraServer } from './server.js';
21
22
  import { object, fail, text, version, stable, digest } from './model.js';
22
- import { HttpBridge } from './transport.js';
23
+ import { failUnresolved } from './unresolved-guidance.js';
24
+ import { oversizedReplies, openWorkerProgram, unsavedChanges, HttpBridge } from './transport.js';
23
25
  import { scriptInventory, scriptPath } from './scripts.js';
24
26
  import { logicalPrograms } from './cross-results.js';
25
27
  import { uiResult } from './ui-results.js';
@@ -34,6 +36,8 @@ import { sdkWrites } from './sdk-contracts.js';
34
36
  import { initialRoot, initialIntent, initializeModel, validateInitialIntent } from './initial-model.js';
35
37
  import { initialProgress } from './initial-progress.js';
36
38
  import { managedGhidraDebugger, prepareGhidraDebugger } from './ghidra-debugger-runtime.js';
39
+ import { timed } from './internal-timing.js';
40
+ import { holdWorkerLease, dropWorkerLease, inWorkerLeaseScope, workerLeaseHeld, workerLeaseHolder, releaseWorkerLease } from './worker-lease.js';
37
41
  const alive = (pid) => {
38
42
  try {
39
43
  process.kill(pid, 0);
@@ -78,6 +82,24 @@ async function port() {
78
82
  return address.port;
79
83
  }
80
84
  /** Isolated native contexts. This layer has no agent-facing instance/worker selector. */
85
+ /** Device and file identity of a real directory (not a link), or undefined when it cannot be proved. */
86
+ async function directoryIdentity(path) {
87
+ try {
88
+ const value = await lstat(path, { bigint: true });
89
+ return value.isDirectory() && !value.isSymbolicLink() && value.ino !== 0n ? value.dev + ':' + value.ino : undefined;
90
+ }
91
+ catch (error) {
92
+ if (error.code === 'ENOENT')
93
+ return undefined;
94
+ throw error;
95
+ }
96
+ }
97
+ /** Failures of a private save whose effect in the worker is not proved either way. */
98
+ const unprovedSaves = new WeakSet();
99
+ /** Failures to prove the end of a worker that was already asked to end. */
100
+ const unprovedStops = new WeakSet();
101
+ /** Identity of one immutable repository version, as the native reader names it (InsightNativeFingerprint.version). */
102
+ const versionIdentity = (fileId, revision) => createHash('sha256').update('insight-saved-state-v1|server|' + fileId + '|' + revision).digest('hex');
81
103
  export class GhidraContexts {
82
104
  workspace;
83
105
  inputs;
@@ -110,7 +132,7 @@ export class GhidraContexts {
110
132
  write: q => server.nativeMigration(binding, q),
111
133
  snapshots: async (paths) => { const value = await server.nativeMigration(binding, { operation: 'snapshots', snapshots: paths }); return Array.isArray(value.items) ? value.items.map(object) : []; },
112
134
  verify: async (t, owner, candidate) => {
113
- const result = await server.nativeRead(binding, { operation: 'verify', path: programPath(t.id), sourceSha: t.binarySha256, fileId: owner.fileId, version: Number(owner.version) + 1, marker: owner.marker, fingerprint: candidate.fingerprint });
135
+ const result = await server.nativeRead(binding, { operation: 'verify', path: programPath(t.id), sourceSha: t.binarySha256, fileId: owner.fileId, version: Number(owner.version) + 1, marker: owner.marker, fingerprint: candidate.fingerprint, bytes: true });
114
136
  if (result.state !== 'verified' || result.version !== Number(owner.version) + 1)
115
137
  fail('unknown', 'Migration independent exact-version readback is unproved; check-in will not be retried.');
116
138
  const exact = await server.nativeRead(binding, { operation: 'migration-probe', path: programPath(t.id), sourceSha: t.binarySha256, version: Number(owner.version) + 1, fileId: owner.fileId });
@@ -190,10 +212,144 @@ export class GhidraContexts {
190
212
  return mkdtemp(join(parent, 'w-'));
191
213
  }
192
214
  async launch(root, target, kind, program, mode, context, credentials = {}) {
215
+ return timed('worker.launch', kind + '.' + mode, () => this.launchWorker(root, target, kind, program, mode, context, credentials));
216
+ }
217
+ /** The worker's own retirement receipt: when and why it stopped by itself. */
218
+ async idleExit(binding) {
219
+ try {
220
+ const receipt = object(JSON.parse(await readFile(join(binding.root, 'idle-exit.json'), 'utf8')));
221
+ if (receipt.pid === binding.pid && typeof receipt.at === 'string' && Number.isFinite(Date.parse(receipt.at)))
222
+ return { at: receipt.at, reason: ['capacity_evicted', 'runtime_changed', 'maintenance'].includes(String(receipt.reason)) ? receipt.reason : 'idle_timeout' };
223
+ }
224
+ catch { /* Absent or unreadable: the stop reason stays unknown. */ }
225
+ }
226
+ idleMs() {
227
+ const configured = this.c.profile.values.contextIdleMinutes, minutes = configured === undefined ? 15 : Number(configured);
228
+ if (!Number.isSafeInteger(minutes) || minutes < 1 || minutes > 1440)
229
+ fail('configuration', 'contextIdleMinutes must be an integer from 1 to 1440.');
230
+ return minutes * 60000;
231
+ }
232
+ /** The process behind a receipt PID is gone or is no longer the recorded worker (PID reuse). */
233
+ async workerGone(binding) { return !alive(binding.pid) || await this.retiredWorker(binding) || await this.retiredInventoryWorker(binding); }
234
+ /** Wait up to `ms` for a worker that is retiring to exit. */
235
+ async awaitExit(binding, ms = 30000) {
236
+ for (const deadline = Date.now() + ms; Date.now() < deadline; await delay(250))
237
+ if (await this.workerGone(binding))
238
+ return true;
239
+ return this.workerGone(binding);
240
+ }
241
+ /**
242
+ * One idle-lease request. `held`/`idle`: the worker accepts work; `retiring`: it is stopping by itself and
243
+ * refuses new holders; `locked`: a retirement request was refused because a command holds it; `gone`: the
244
+ * recorded worker no longer exists (including PID reuse); `absent`: a worker without cool-down (GUI or older).
245
+ */
246
+ async lease(binding, action, holder, reason) {
247
+ if (!binding.leasePort)
248
+ return { state: 'absent' };
249
+ if (await this.idleExit(binding) && await this.workerGone(binding))
250
+ return { state: 'gone' };
251
+ const token = await this.c.secrets.require(binding.tokenSecret);
252
+ let response;
253
+ try {
254
+ response = await (this.c.fetch ?? globalThis.fetch)('http://127.0.0.1:' + binding.leasePort + '/insight/lease', { method: 'POST', redirect: 'error',
255
+ headers: { Authorization: 'Bearer ' + token, 'Content-Type': 'application/json' }, body: JSON.stringify({ action, ...(holder ? { holder } : {}), ...(reason ? { reason } : {}) }), signal: AbortSignal.timeout(5000) });
256
+ }
257
+ catch (error) {
258
+ // A listener that accepted the request and stayed silent is not a retirement: the caller decides whether the
259
+ // worker itself still answers. Nothing is waited for here.
260
+ if (error?.name === 'TimeoutError' && !await this.workerGone(binding))
261
+ fail('busy', 'Context worker lease did not answer while its process is alive; it is retained.', { lease: 'silent' });
262
+ // A closed lease listener is a worker in retirement or gone; it never received this command.
263
+ if (await this.awaitExit(binding, 10000))
264
+ return { state: 'gone' };
265
+ fail('busy', 'Context worker lease is unreachable while its process is alive; it is retained.');
266
+ }
267
+ const value = object(await response.json().catch(() => ({})));
268
+ if (response.status === 409)
269
+ return { state: 'retiring' };
270
+ if (response.status === 423)
271
+ return { state: 'locked', holders: Number(value.holders) };
272
+ if (response.status !== 200 || value.pid !== binding.pid || !['held', 'idle', 'retiring'].includes(String(value.state))) {
273
+ // Another process now owns the port or PID: the recorded worker is gone only if its identity changed.
274
+ if (await this.workerGone(binding))
275
+ return { state: 'gone' };
276
+ fail('binding', 'Context worker lease belongs to a different process.');
277
+ }
278
+ return { state: value.state, holders: Number(value.holders), idleForMs: Number(value.idleForMs), ...(Number.isSafeInteger(value.scripts) ? { scripts: Number(value.scripts) } : {}) };
279
+ }
280
+ /** Hold a worker for the rest of the current command; outside a command nothing is acquired. */
281
+ async holdLease(binding) {
282
+ if (!binding.leasePort)
283
+ return 'absent';
284
+ if (!inWorkerLeaseScope() || workerLeaseHeld(binding.root))
285
+ return 'held';
286
+ const holder = randomUUID(), result = await this.lease(binding, 'acquire', holder);
287
+ if (result.state !== 'held')
288
+ return result.state === 'gone' ? 'gone' : 'retiring';
289
+ holdWorkerLease(binding.root, { holder,
290
+ renew: async () => { if (alive(binding.pid))
291
+ await this.lease(binding, 'renew', holder); },
292
+ release: async () => { if (alive(binding.pid))
293
+ await this.lease(binding, 'release', holder); },
294
+ });
295
+ return 'held';
296
+ }
297
+ /**
298
+ * A worker that stopped by itself becomes an ordinary stop: its stop receipt, lifecycle reason and the
299
+ * release of its credential. Returns the reason when the worker ended this way.
300
+ */
301
+ async settleRetired(binding, requested) {
302
+ // A worker asked to stop that exited before writing its own receipt is settled with the requested reason.
303
+ const exit = await this.idleExit(binding) ?? (requested ? { at: new Date().toISOString(), reason: requested } : undefined);
304
+ if (!exit || !await this.workerGone(binding))
305
+ return;
306
+ const path = join(binding.root, 'stopped.json');
307
+ if (!await exists(path)) {
308
+ await durable(path, { pid: binding.pid, tokenSecret: binding.tokenSecret, at: exit.at, reason: exit.reason });
309
+ if (binding.context)
310
+ await recordLifecycle(this.workspace, binding.context, { at: exit.at, event: 'stop', reason: exit.reason, pid: binding.pid });
311
+ }
312
+ if (binding.context)
313
+ this.capacity.slots.delete(binding.context);
314
+ this.running.delete(binding.root);
315
+ dropWorkerLease(binding.root);
316
+ await releaseStoppedContextCredential(this.directory(), binding, this.c.secrets, alive, () => this.workerGone(binding));
317
+ return exit.reason;
318
+ }
319
+ /** Ask an unheld leased worker to stop now and settle it; false when a command holds it. */
320
+ async retireWorker(binding, reason) {
321
+ // The worker accepts a retirement before it answers: a request without a usable answer may have been accepted.
322
+ const result = await this.lease(binding, 'retire', undefined, reason).catch(error => { if (error && typeof error === 'object')
323
+ unprovedStops.add(error); throw error; });
324
+ if (result.state === 'locked' || result.state === 'absent')
325
+ return false;
326
+ if (!await this.awaitExit(binding)) {
327
+ try {
328
+ fail('busy', 'A context worker asked to stop has not exited yet; it is retained.');
329
+ }
330
+ catch (error) {
331
+ unprovedStops.add(error);
332
+ throw error;
333
+ }
334
+ }
335
+ await this.settleRetired(binding, reason);
336
+ return true;
337
+ }
338
+ async launchWorker(root, target, kind, program, mode, context, credentials) {
193
339
  if ((await nativeInputs(this.c.profile.values, this.workspace.directory, this.c)).fingerprint !== this.inputs.fingerprint)
194
- fail('binding', 'Native runtime inputs changed; stop the owner before using a different build.');
340
+ fail('binding', 'Native runtime inputs changed while this owner runs; stop the CLI owner (ipc-server stop) and repeat the command. Workers of the previous runtime stop when their contexts are next used.');
341
+ // A launch follows the proved end of the root's previous worker: its marker, readable or not, names nothing now.
342
+ // A worker this owner still runs here, or a marker that cannot be cleared, would make the new worker ambiguous.
343
+ const previous = this.running.get(root);
344
+ if (previous && alive(previous.binding.pid) && !(previous.child && (previous.child.exitCode !== null || previous.child.signalCode !== null)))
345
+ fail('busy', 'This checkout still has a running worker; it is retained.');
346
+ await rm(join(root, 'parked.json'), { recursive: true, force: true }).catch(() => { fail('binding', 'The parking marker of the previous worker in this checkout cannot be cleared; remove parked.json from the context directory.'); });
195
347
  const endpointPort = await port(), tokenSecret = 'context-' + randomUUID(), token = randomBytes(32).toString('hex');
348
+ // Headless context workers outlive their Factory owner and cool down after the configured idle time.
349
+ const lease = kind === 'context' && mode === 'headless' ? { leasePort: await port(), idleMs: this.idleMs() } : undefined;
196
350
  const classes = await nativeHelpers(this.workspace.directory, this.inputs, this.c);
351
+ if (lease)
352
+ Object.assign(lease, { helpers: await readFile(join(classes, 'helper-sources'), 'utf8') });
197
353
  let debuggerEnvironment = {}, debuggerPython, debuggerRuntime;
198
354
  if (mode === 'gui') {
199
355
  if (managedGhidraDebugger())
@@ -226,11 +382,11 @@ export class GhidraContexts {
226
382
  env: { PATH: this.c.environment.PATH ?? process.env.PATH, HOME: root, TMPDIR: root, XDG_RUNTIME_DIR: root,
227
383
  ...(process.platform === 'win32' ? { SystemRoot: process.env.SystemRoot, WINDIR: process.env.WINDIR, ComSpec: process.env.ComSpec, TEMP: root, TMP: root, USERPROFILE: root, LOCALAPPDATA: root, APPDATA: root } : {}),
228
384
  INSIGHT_TOOL_APPDATA: this.c.appArguments.AppDataDirectory, GHIDRA_MCP_AUTH_TOKEN: token, GHIDRA_MCP_FILE_ROOT: root, GHIDRA_MCP_SHARED_PROJECT_DIR: root,
229
- GHIDRA_MCP_ALLOW_SCRIPTS: '1', ...debuggerEnvironment, ...credentials } }, { signal: this.c.signal, onSpawn }), async (spawned) => {
385
+ GHIDRA_MCP_ALLOW_SCRIPTS: '1', ...(lease ? { INSIGHT_WORKER_LEASE_PORT: String(lease.leasePort), INSIGHT_WORKER_IDLE_MS: String(lease.idleMs) } : {}), ...debuggerEnvironment, ...credentials } }, { signal: this.c.signal, onSpawn }), async (spawned) => {
230
386
  if (!spawned.pid)
231
387
  fail('launch', 'Owned context did not obtain a PID.');
232
388
  binding = { toolProcessId: spawned.toolProcessId, pid: spawned.pid, endpoint: `http://127.0.0.1:${endpointPort}`, root, ...(debuggerPython ? { debuggerPython } : {}), ...(debuggerRuntime ? { debuggerRuntime } : {}), target: target.id,
233
- ...(context ? { context, session: this.workspace.contextById(context).session } : {}), kind, mode, program, tokenSecret, runtimeFingerprint: this.inputs.fingerprint };
389
+ ...(context ? { context, session: this.workspace.contextById(context).session } : {}), kind, mode, program, tokenSecret, runtimeFingerprint: this.inputs.fingerprint, ...(lease ?? {}) };
234
390
  await durable(join(root, 'process.json'), binding);
235
391
  }, async (spawned) => {
236
392
  if (binding)
@@ -244,24 +400,30 @@ export class GhidraContexts {
244
400
  child.unref();
245
401
  if (!child.pid)
246
402
  fail('launch', 'Owned Ghidra context could not be launched.');
247
- const record = { binding, http: new HttpBridge(binding.endpoint, this.c.fetch, this.c.signal, token, undefined, ghidraBudget(this.c.profile.values, 'save')), child };
403
+ const record = { binding, http: await this.bridge(binding, token), child };
248
404
  this.running.set(root, record);
249
405
  const deadline = Date.now() + 90000;
250
406
  try {
251
- while (Date.now() < deadline && child.exitCode === null && child.signalCode === null && !this.c.signal.aborted) {
407
+ let ready = false;
408
+ while (!ready && Date.now() < deadline && child.exitCode === null && child.signalCode === null && !this.c.signal.aborted) {
252
409
  try {
253
410
  const info = await record.http.instance();
254
411
  if (info.pid !== binding.pid || info.tcp_port !== endpointPort)
255
412
  fail('binding', 'Context endpoint belongs to a different native process.');
256
- if (context)
257
- await recordLifecycle(this.workspace, context, { at: new Date().toISOString(), event: 'start', reason: 'native_launch', pid: binding.pid });
258
- return record;
413
+ ready = true;
259
414
  }
260
415
  catch {
261
416
  await delay(100);
262
417
  }
263
418
  }
264
- fail('launch', 'Owned Ghidra context did not become ready; its stage is retained.');
419
+ if (!ready)
420
+ fail('launch', 'Owned Ghidra context did not become ready; its stage is retained.');
421
+ if (context)
422
+ await recordLifecycle(this.workspace, context, { at: new Date().toISOString(), event: 'start', reason: 'native_launch', pid: binding.pid });
423
+ // A fresh worker is held by the command that launched it; a failure here is reported as is, never retried.
424
+ if (context && ['retiring', 'gone'].includes(await this.holdLease(binding)))
425
+ fail('launch', 'Owned context worker stopped right after its start; its stage is retained.');
426
+ return record;
265
427
  }
266
428
  catch (error) {
267
429
  if (child.exitCode === null && child.signalCode === null)
@@ -274,6 +436,17 @@ export class GhidraContexts {
274
436
  throw error;
275
437
  }
276
438
  }
439
+ /** A bridge to a context worker. A leased worker also runs this package's helper scripts in-process. */
440
+ async bridge(binding, token) {
441
+ const http = new HttpBridge(binding.endpoint, this.c.fetch, this.c.signal, token, undefined, ghidraBudget(this.c.profile.values, 'save'));
442
+ if (binding.leasePort) {
443
+ // The worker serves only callers whose helper sources are the ones its classes were compiled from.
444
+ // The worker decides admission first and then compares sources. Unreadable sources name no worker's classes:
445
+ // the worker still admits or refuses, and only then leaves the script to the inline provider.
446
+ http.owned = { port: binding.leasePort, helpers: await helperSourcesKey().catch(() => '') };
447
+ }
448
+ return http;
449
+ }
277
450
  async verified(binding, target, verifySource = true) {
278
451
  const root = await realpath(binding.root);
279
452
  if (!ownedDirectory(root, this.directory(), [binding.kind, binding.context ?? binding.target, basename(root)]) || binding.target !== target.id || binding.runtimeFingerprint !== this.inputs.fingerprint)
@@ -281,7 +454,7 @@ export class GhidraContexts {
281
454
  if (stable(JSON.parse(await readFile(join(root, 'process.json'), 'utf8'))) !== stable(binding))
282
455
  fail('binding', 'Native context receipt changed.');
283
456
  const token = await this.c.secrets.require(binding.tokenSecret);
284
- const http = new HttpBridge(binding.endpoint, this.c.fetch, this.c.signal, token, undefined, ghidraBudget(this.c.profile.values, 'save'));
457
+ const http = await this.bridge(binding, token);
285
458
  const info = await http.instance();
286
459
  if (info.pid !== binding.pid || info.tcp_port !== Number(new URL(binding.endpoint).port) ||
287
460
  !projectPathWithin(info.project_path, binding.root))
@@ -299,6 +472,9 @@ export class GhidraContexts {
299
472
  return object(await record.http.call('/get_metadata', { program: record.binding.program }));
300
473
  }
301
474
  async stopRecord(record, ready = true, releaseCapacity = true, reason = 'temporary_complete') {
475
+ return timed('worker.stop', reason, () => this.stopWorker(record, ready, releaseCapacity, reason));
476
+ }
477
+ async stopWorker(record, ready, releaseCapacity, reason) {
302
478
  const { binding, child } = record;
303
479
  const childFinished = child && child.pid === binding.pid && (child.exitCode !== null || child.signalCode !== null);
304
480
  if (!childFinished && alive(binding.pid)) {
@@ -310,15 +486,26 @@ export class GhidraContexts {
310
486
  const token = await this.c.secrets.require(binding.tokenSecret), http = new HttpBridge(binding.endpoint, this.c.fetch, new AbortController().signal, token, 60000);
311
487
  await this.debuggerHelperRecord({ ...record, http }, 'Stop', 'INSIGHT_DEBUGGER_STOPPED');
312
488
  }
313
- if (binding.toolProcessId)
314
- await terminateProcess(this.c.appArguments.AppDataDirectory, binding.toolProcessId, false, r => verifyGhidraProcess(r, this.c));
315
- else
316
- process.kill(binding.pid, 'SIGTERM');
317
- for (let i = 0; i < 100 && alive(binding.pid); i++)
318
- await delay(50);
319
- if (alive(binding.pid))
320
- fail('busy', 'Owned context did not stop; its stage is retained.');
489
+ // Once it is asked to end, the worker may save changed programs while it shuts down: a stop that is not
490
+ // proved afterwards says nothing about the saved program.
491
+ try {
492
+ if (binding.toolProcessId)
493
+ await terminateProcess(this.c.appArguments.AppDataDirectory, binding.toolProcessId, false, r => verifyGhidraProcess(r, this.c));
494
+ else
495
+ process.kill(binding.pid, 'SIGTERM');
496
+ for (let i = 0; i < 100 && alive(binding.pid); i++)
497
+ await delay(50);
498
+ if (alive(binding.pid))
499
+ fail('busy', 'Owned context did not stop; its stage is retained.');
500
+ }
501
+ catch (error) {
502
+ if (error && typeof error === 'object')
503
+ unprovedStops.add(error);
504
+ throw error;
505
+ }
321
506
  }
507
+ // Only a worker that is gone needs no release: a failed stop keeps the command's hold, which then ends with it.
508
+ dropWorkerLease(binding.root);
322
509
  if (binding.mode === 'gui')
323
510
  await this.debuggerReleased(binding);
324
511
  const at = new Date().toISOString();
@@ -390,15 +577,22 @@ export class GhidraContexts {
390
577
  // Never write a detached worker's project: its engine alone can capture that state.
391
578
  if (context && (!context.nativeCheckout || context.nativeCheckout.root !== record.binding.root))
392
579
  fail('migration', 'This worker belongs to legacy detached work. Save and close it with the release that started it, then run ghidra migrate.');
393
- const result = object(await record.http.call('/save_program', { program: record.binding.program }));
394
- if (result.success !== true)
395
- fail('save', 'Private program save was not acknowledged.');
580
+ // A save that was not acknowledged, for whatever reason, may still have happened in the worker.
581
+ try {
582
+ const result = object(await record.http.call('/save_program', { program: record.binding.program }));
583
+ if (result.success !== true)
584
+ fail('save', 'Private program save was not acknowledged.');
585
+ }
586
+ catch (error) {
587
+ if (error && typeof error === 'object')
588
+ unprovedSaves.add(error);
589
+ throw error;
590
+ }
396
591
  if (context?.nativeCheckout) {
397
- const saved = object(await this.nativeView(record, { operation: 'fingerprint' }));
398
- // A native receipt names mutable project bytes. Retain this small metadata witness while
399
- // those exact bytes are present; an older receipt cannot be inspected after the next save.
400
- const debuggerMetadata = debuggerMetadataFingerprint(await this.nativeView(record, { operation: 'inspect', expected: saved.fingerprint, parameters: { kind: 'debugger_bookmarks' } }));
401
- return this.nativeReceipt(context.nativeCheckout, { ...saved, debuggerMetadata });
592
+ // One pass names the saved state and inspects its debugger metadata. A native receipt names a mutable
593
+ // project: this small metadata witness is kept, because an older receipt cannot be inspected after the next save.
594
+ const { inspected, ...saved } = object(await this.nativeView(record, { operation: 'capture', parameters: { kind: 'debugger_bookmarks' } }));
595
+ return this.nativeReceipt(context.nativeCheckout, { ...saved, debuggerMetadata: debuggerMetadataFingerprint(inspected) });
402
596
  }
403
597
  const output = join(record.binding.root, 'exports');
404
598
  await mkdir(output, { recursive: true, mode: 0o700 });
@@ -415,9 +609,7 @@ export class GhidraContexts {
415
609
  return artifact;
416
610
  }
417
611
  async nativeView(record, parameters) {
418
- const name = 'InsightNativeView_' + randomUUID().replaceAll('-', ''), source = await readFile(new URL('../../references/native/InsightNativeView.java', import.meta.url), 'utf8');
419
- const response = object(await record.http.call('/run_script_inline', { program: record.binding.program,
420
- code: source.replace('public class InsightNativeView ', 'public class ' + name + ' '), args: Buffer.from(JSON.stringify(parameters), 'utf8').toString('base64') }));
612
+ const response = object(await record.http.script(record.binding.program, 'InsightNativeView', Buffer.from(JSON.stringify(parameters), 'utf8').toString('base64')));
421
613
  if (response.success !== true || typeof response.console_output !== 'string')
422
614
  fail('partial', 'Saved native view inspection did not complete.');
423
615
  const matches = [...response.console_output.matchAll(/^INSIGHT_NATIVE:(.+)$/gm)];
@@ -432,9 +624,61 @@ export class GhidraContexts {
432
624
  await durable(path, { schema: 1, engine: this.nativeEngine, source: 'checkout', checkout, ...saved });
433
625
  return this.workspace.captureNative(path);
434
626
  }
435
- async serverView(targetId, versionNumber) {
627
+ /** Exact server versions are immutable for one item: a verified reader view is reusable by this runtime and repository. */
628
+ versionCache(targetId, binding, versionNumber, fileId) {
629
+ const target = this.workspace.target(targetId);
630
+ const identity = { schema: 1, origin: binding.origin, repository: binding.repository, path: programPath(targetId), sourceSha: target.binarySha256, runtimeFingerprint: this.inputs.fingerprint, fileId, version: versionNumber };
631
+ return { identity, path: join(this.directory(), 'shared-views', targetId, 'versions', 'v' + versionNumber + '-' + digest(identity).slice(0, 32) + '.json') };
632
+ }
633
+ async rememberVersion(targetId, binding, value) {
634
+ if (value.state !== 'verified' || !Number.isSafeInteger(value.version) || typeof value.fileId !== 'string' || typeof value.fingerprint !== 'string' || !/^[a-f0-9]{64}$/.test(value.fingerprint))
635
+ return;
636
+ const { identity, path } = this.versionCache(targetId, binding, Number(value.version), value.fileId);
637
+ // Only the immutable identity of the version is kept; live checkout lists are never served from the cache.
638
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });
639
+ await durable(path, { identity, value: { state: 'verified', version: value.version, fileId: value.fileId, fingerprint: value.fingerprint } });
640
+ await this.pruneVersions(dirname(path), identity);
641
+ }
642
+ /** Keep only views of the current server, repository, input and runtime, and at most the 64 most recent. */
643
+ async pruneVersions(directory, current) {
644
+ const keys = ['origin', 'repository', 'path', 'sourceSha', 'runtimeFingerprint'], kept = [];
645
+ for (const name of await readdir(directory)) {
646
+ const path = join(directory, name);
647
+ if (!/^v\d+-[a-f0-9]{32}\.json$/.test(name)) {
648
+ continue;
649
+ }
650
+ try {
651
+ const identity = object(object(JSON.parse(await readFile(path, 'utf8'))).identity);
652
+ if (keys.every(key => identity[key] === current[key])) {
653
+ kept.push({ path, at: (await stat(path)).mtimeMs });
654
+ continue;
655
+ }
656
+ }
657
+ catch (error) {
658
+ if (error.code === 'ENOENT')
659
+ continue;
660
+ }
661
+ await rm(path, { force: true });
662
+ }
663
+ for (const stale of kept.sort((a, b) => b.at - a.at).slice(64))
664
+ await rm(stale.path, { force: true });
665
+ }
666
+ async cachedVersion(targetId, binding, versionNumber, fileId) {
667
+ const { identity, path } = this.versionCache(targetId, binding, versionNumber, fileId);
668
+ try {
669
+ const entry = object(JSON.parse(await readFile(path, 'utf8'))), value = object(entry.value);
670
+ if (stable(entry.identity) === stable(identity) && value.state === 'verified' && value.version === versionNumber && value.fileId === fileId && typeof value.fingerprint === 'string')
671
+ return value;
672
+ }
673
+ catch { /* An absent or unreadable entry is a miss; the version is read again. */ }
674
+ }
675
+ async serverView(targetId, versionNumber, fileId) {
436
676
  const server = this.server(), binding = await server.ensure(), target = this.workspace.target(targetId);
437
- const value = await server.nativeRead(binding, { operation: 'latest', path: programPath(targetId), sourceSha: target.binarySha256, ...(versionNumber ? { version: versionNumber } : {}) });
677
+ let value = versionNumber && fileId ? await this.cachedVersion(targetId, binding, versionNumber, fileId) : undefined;
678
+ if (!value) {
679
+ value = await server.nativeRead(binding, { operation: 'latest', path: programPath(targetId), sourceSha: target.binarySha256, ...(versionNumber ? { version: versionNumber } : {}), ...(fileId ? { fileId } : {}) });
680
+ await this.rememberVersion(targetId, binding, value);
681
+ }
438
682
  if (value.state !== 'verified' || typeof value.fileId !== 'string' || typeof value.fingerprint !== 'string')
439
683
  fail('binding', 'Native shared model is unverified or requires an explicit legacy migration.');
440
684
  const revision = version(value.version), root = join(this.directory(), 'shared-views', targetId);
@@ -461,7 +705,8 @@ export class GhidraContexts {
461
705
  return { root, owner, binding };
462
706
  }
463
707
  async nativeOperation(checkout, operation, parameters = {}) {
464
- const { root, owner, binding } = await this.nativeOwner(checkout);
708
+ // The owner and server binding are proved here, before dispatch: an unreachable server sends no Update or check-in.
709
+ const { root, owner, binding } = await this.nativeOwner(checkout).catch(error => operation === 'update' || operation === 'checkin' ? this.unsent(operation, error) : Promise.reject(error));
465
710
  return this.server().nativeCheckout(binding, { root, owner, operation, fileId: checkout.fileId, checkoutId: checkout.checkoutId, ...parameters });
466
711
  }
467
712
  async shared(target, binding) {
@@ -471,7 +716,7 @@ export class GhidraContexts {
471
716
  try {
472
717
  await record.http.call('/server/connect');
473
718
  await record.http.call('/open_project', { path: binding.origin + '/' + binding.repository });
474
- const opened = object(await record.http.call('/open_program', { path: record.binding.program }));
719
+ const opened = object(await openWorkerProgram(record.http, record.binding.program));
475
720
  if (opened.read_only !== true || opened.path !== record.binding.program)
476
721
  fail('authorization', 'Shared baseline must open through verified read-only authority.');
477
722
  await this.verified(record.binding, target);
@@ -522,8 +767,9 @@ export class GhidraContexts {
522
767
  if (model.state === 'ready')
523
768
  return;
524
769
  const server = this.server(), binding = await server.ensure();
525
- if (this.workspace.activePublication(target.id))
526
- fail('blocked', 'Shared publication requires reconciliation before initial-model recovery.');
770
+ const held = this.workspace.activePublication(target.id);
771
+ if (held)
772
+ failUnresolved(this.workspace, { session: held.session, target: target.id }, 'Shared publication requires reconciliation before initial-model recovery.');
527
773
  const intent = await initialIntent(this.workspace, target.id);
528
774
  if (intent) {
529
775
  await validateInitialIntent(this.workspace, target, binding, this.inputs.fingerprint, undefined, true);
@@ -574,13 +820,24 @@ export class GhidraContexts {
574
820
  await task;
575
821
  return this.workspace.model(target.id);
576
822
  }
577
- async privateCopy(context, snapshot) {
823
+ async privateCopy(context) {
824
+ // A failed inventory is never cached: the next open repeats it.
578
825
  if (!this.capacity.inventory)
579
- this.capacity.inventory = this.inventory();
580
- await this.capacity.inventory;
826
+ this.capacity.inventory = this.inventory().catch(error => { this.capacity.inventory = undefined; throw error; });
827
+ await timed('context.inventory', 'owned', async () => { await this.capacity.inventory; });
828
+ // Workers that stopped by themselves no longer hold capacity.
829
+ for (const [root, record] of [...this.running])
830
+ if (record.binding.kind === 'context' && record.binding.context && await this.workerGone(record.binding)) {
831
+ if (!await this.settleRetired(record.binding)) {
832
+ this.running.delete(root);
833
+ this.capacity.slots.delete(record.binding.context);
834
+ }
835
+ }
581
836
  const configured = this.c.profile.values.maxContexts, max = configured === undefined ? 4 : Number(configured);
582
837
  if (!Number.isSafeInteger(max) || max < 1 || max > 16)
583
838
  fail('configuration', 'maxContexts must be an integer from 1 to 16.');
839
+ if (!this.capacity.slots.has(context.id) && this.capacity.slots.size >= max)
840
+ await this.evictIdle(context.id);
584
841
  if (!this.capacity.slots.has(context.id) && this.capacity.slots.size >= max)
585
842
  fail('limit', 'Owned context capacity is occupied; close a saved context before opening another.');
586
843
  this.capacity.slots.add(context.id);
@@ -594,17 +851,16 @@ export class GhidraContexts {
594
851
  // Another runtime first proves, without an upgrade, that it can read the saved database.
595
852
  if (checkout.runtimeFingerprint !== this.inputs.fingerprint) {
596
853
  const observed = await this.nativeOperation(checkout, 'status');
854
+ if (observed.recoverable === true)
855
+ throw unsavedChanges(context);
597
856
  if (observed.state !== 'ready' || observed.checkoutId !== checkout.checkoutId)
598
857
  fail('binding', 'This runtime cannot open the native checkout without changing it; the project is retained.');
599
858
  }
600
- const first = !await exists(join(root, 'process.json'));
601
- // Missing process/control receipts are not evidence about the saved project. Prove its bytes before launch.
602
- const pristine = (first ? await this.pristineNative(context, checkout) : undefined) ?? await this.discardedPristine(context, checkout);
603
859
  record = await this.launch(root, target, 'context', checkout.path, 'headless', context.id);
604
860
  const project = object(await record.http.call('/open_project', { path: join(root, 'view.gpr') }));
605
861
  if (project.success === false)
606
862
  fail('launch', 'Native working project could not be reopened.');
607
- const opened = object(await record.http.call('/open_program', { path: record.binding.program }));
863
+ const opened = object(await openWorkerProgram(record.http, record.binding.program, context));
608
864
  if (opened.path !== record.binding.program || opened.read_only === true)
609
865
  fail('binding', 'Native checkout did not open its saved writable program.');
610
866
  await this.verified(record.binding, target);
@@ -612,10 +868,16 @@ export class GhidraContexts {
612
868
  record.binding.viewEpoch = context.viewEpoch ?? 0;
613
869
  await durable(join(root, 'process.json'), record.binding);
614
870
  await durable(join(this.directory(), 'context', context.id, 'current.json'), record.binding);
615
- const generation = pristine ? await this.recordOpened(context, checkout, record, pristine) : undefined;
616
871
  if (context.workingSnapshot)
617
872
  await recordLifecycle(this.workspace, context.id, { at: new Date().toISOString(), event: 'restore', reason: 'saved_snapshot', pid: record.binding.pid });
618
- return generation === undefined ? record : { ...record, generation };
873
+ // A receipt written by an earlier build names its saved state by a hash that nothing compares with any more:
874
+ // the open program is described again, which reads no database.
875
+ const receipt = context.workingSnapshot?.kind === 'native' ? object(JSON.parse(await readFile(await this.workspace.artifacts.verify(context.workingSnapshot), 'utf8'))) : undefined;
876
+ if (receipt && receipt.source === 'checkout' && typeof receipt.modified !== 'boolean') {
877
+ const current = this.workspace.context(context);
878
+ return { ...record, generation: this.workspace.saveContext(current, current.generation, { workingSnapshot: await this.capture(record) }).generation };
879
+ }
880
+ return record;
619
881
  }
620
882
  catch (error) {
621
883
  if (record)
@@ -625,90 +887,6 @@ export class GhidraContexts {
625
887
  throw error;
626
888
  }
627
889
  }
628
- async pristineNative(context, checkout, discard) {
629
- if (!context.workingSnapshot || !context.baseSnapshot || context.scalars.length || context.complexChanges.length || context.debugger?.traces.length ||
630
- this.workspace.uncertainOutcome(context) || this.workspace.activePublication(context.target))
631
- return;
632
- const read = async (artifact) => object(JSON.parse(await readFile(await this.workspace.artifacts.verify(artifact), 'utf8')));
633
- const [local, base] = [await read(context.workingSnapshot), await read(context.baseSnapshot)];
634
- if (base.source !== 'server' || base.version !== checkout.baseVersion || base.fileId !== checkout.fileId || local.fingerprint !== base.fingerprint ||
635
- base.origin !== checkout.origin || base.repository !== checkout.repository)
636
- return;
637
- const observed = await this.nativeOperation(checkout, 'status');
638
- if (observed.state !== 'ready' || observed.checkedOut !== true || observed.modified !== false || observed.recoverable !== false || observed.fileId !== checkout.fileId ||
639
- observed.checkoutId !== checkout.checkoutId || observed.baseVersion !== checkout.baseVersion || !Array.isArray(observed.projectFiles) ||
640
- stable([...observed.projectFiles].sort()) !== stable([basename(checkout.path), ...(discard?.files ?? [])].sort()))
641
- return;
642
- const saved = object(observed.saved);
643
- if (saved.fingerprint !== base.fingerprint || saved.fileId !== checkout.fileId || saved.version !== checkout.baseVersion)
644
- return;
645
- return { fingerprint: saved.fingerprint, fileId: checkout.fileId, checkoutId: checkout.checkoutId, baseVersion: checkout.baseVersion,
646
- ...(discard ? { discardRequest: discard.request, projectFiles: observed.projectFiles } : {}) };
647
- }
648
- /** A completed discard replaces its checkout inside the same root, retaining its process and backup receipts. */
649
- async discardedPristine(context, checkout) {
650
- if (!context.workingSnapshot || !context.baseSnapshot || context.scalars.length || context.complexChanges.length || context.debugger?.traces.length ||
651
- this.workspace.unresolved(context).some(request => request.operation !== 'ghidra.open') || this.workspace.uncertainOutcome(context) || this.workspace.activePublication(context.target))
652
- return;
653
- const read = async (artifact) => object(JSON.parse(await readFile(await this.workspace.artifacts.verify(artifact), 'utf8')));
654
- const [local, base] = await Promise.all([read(context.workingSnapshot), read(context.baseSnapshot)]);
655
- if (local.source !== 'checkout' || stable(local.checkout) !== stable(checkout) || local.fileId !== checkout.fileId || local.version !== checkout.baseVersion ||
656
- local.fingerprint !== base.fingerprint || base.source !== 'server' || base.version !== checkout.baseVersion || base.fileId !== checkout.fileId ||
657
- base.origin !== checkout.origin || base.repository !== checkout.repository)
658
- return;
659
- const directory = join(checkout.root, 'operations');
660
- let names;
661
- try {
662
- names = await readdir(directory);
663
- }
664
- catch (error) {
665
- if (error.code === 'ENOENT')
666
- return;
667
- throw error;
668
- }
669
- const { owner } = await this.nativeOwner(checkout), proofs = [];
670
- for (const name of names.filter(name => /^q_[a-f0-9-]{36}-discard\.json$/.test(name))) {
671
- const journal = object(JSON.parse(await readFile(join(directory, name), 'utf8'))), q = object(journal.request ?? {}), result = object(journal.result ?? {}), saved = object(result.saved ?? {}), before = object(journal.before ?? {});
672
- if (q.operation !== 'discard' || q.request + '-discard.json' !== name || q.root !== checkout.root || q.fileId !== checkout.fileId || stable(q.owner) !== stable(owner) ||
673
- !Number.isSafeInteger(q.checkoutId) || Number(q.checkoutId) < 0 || q.checkoutId === checkout.checkoutId || journal.checkoutId !== q.checkoutId ||
674
- !Number.isSafeInteger(journal.baseVersion) || Number(journal.baseVersion) < 1 || Number(journal.baseVersion) > checkout.baseVersion ||
675
- before.fileId !== checkout.fileId || before.version !== journal.baseVersion || typeof before.fingerprint !== 'string' || !/^[a-f0-9]{64}$/.test(before.fingerprint) ||
676
- result.state !== 'discarded' || result.modified !== false || result.checkoutId !== checkout.checkoutId || result.baseVersion !== checkout.baseVersion ||
677
- saved.fileId !== checkout.fileId || saved.version !== checkout.baseVersion || saved.fingerprint !== base.fingerprint || typeof result.retainedKeepFile !== 'string')
678
- continue;
679
- // This inventory permits recapturing only the main program's open-time rewrite. It never grants backup disposal.
680
- const inventory = journal.backupFilesAfter ?? journal.backupFilesBefore;
681
- const files = Object.keys(object(inventory ?? result.disposableBackups ?? {}));
682
- if (files.some(file => !this.nativeKeepName(checkout, file)) || inventory !== undefined && Object.values(object(inventory)).some(value => typeof value !== 'string' || !value) ||
683
- result.retainedKeepFile !== '' && !files.includes(result.retainedKeepFile))
684
- continue;
685
- proofs.push({ request: String(q.request), files });
686
- }
687
- if (proofs.length === 1)
688
- return this.pristineNative(context, checkout, proofs[0]);
689
- }
690
- /**
691
- * Opening a checkout lets Ghidra rewrite its saved buffers before any caller runs. A proved pristine initial or
692
- * replacement checkout captures those bytes as its new receipt and a no-work state of that shared version.
693
- */
694
- async recordOpened(scope, checkout, record, preOpen) {
695
- const context = this.workspace.context(scope);
696
- if (!context.workingSnapshot || !context.baseSnapshot)
697
- return;
698
- const read = async (artifact) => object(JSON.parse(await readFile(await this.workspace.artifacts.verify(artifact), 'utf8')));
699
- const [local, base] = [await read(context.workingSnapshot), await read(context.baseSnapshot)];
700
- if (base.source !== 'server' || base.version !== checkout.baseVersion || base.fileId !== checkout.fileId || local.fingerprint !== base.fingerprint || base.origin !== checkout.origin || base.repository !== checkout.repository ||
701
- preOpen.fingerprint !== base.fingerprint || preOpen.fileId !== checkout.fileId || preOpen.checkoutId !== checkout.checkoutId || preOpen.baseVersion !== checkout.baseVersion)
702
- return;
703
- const snapshot = await this.capture(record), saved = await read(snapshot), opened = text(saved.fingerprint);
704
- if (opened !== base.fingerprint) {
705
- const root = join(this.directory(), 'shared-views', context.target, 'opened'), path = join(root, 'v' + checkout.baseVersion + '-' + opened + '.json');
706
- await mkdir(root, { recursive: true, mode: 0o700 });
707
- await durable(path, { schema: 2, target: context.target, origin: checkout.origin, repository: checkout.repository, version: checkout.baseVersion, fileId: checkout.fileId, base: base.fingerprint, opened, preOpen,
708
- runtimeFingerprint: this.inputs.fingerprint, context: context.id, at: new Date().toISOString() });
709
- }
710
- return this.workspace.saveContext(scope, context.generation, { workingSnapshot: snapshot }).generation;
711
- }
712
890
  async createNative(scope) {
713
891
  const context = this.workspace.context(scope), target = this.workspace.target(scope.target), server = this.server(), binding = await server.ensure();
714
892
  const parent = join(this.directory(), 'context', context.id);
@@ -738,20 +916,66 @@ export class GhidraContexts {
738
916
  fail('unknown', 'Native checkout creation remains unproved; its original project is retained.');
739
917
  const checkout = { schema: 1, context: context.id, root, fileId: value.fileId, checkoutId: Number(value.checkoutId), baseVersion: version(value.baseVersion),
740
918
  origin: binding.origin, repository: binding.repository, path: programPath(target.id), runtimeFingerprint: owner.runtimeFingerprint, state: 'active' };
741
- const shared = await this.serverView(scope.target, checkout.baseVersion), snapshot = await this.nativeReceipt(checkout, object(value.saved));
919
+ const shared = await this.serverView(scope.target, checkout.baseVersion, checkout.fileId), snapshot = await this.nativeReceipt(checkout, object(value.saved));
742
920
  this.observeNativeShared(scope.target, shared);
743
921
  return this.workspace.saveContext(scope, context.generation, { state: 'stopped', nativeCheckout: checkout, baseRevision: checkout.baseVersion, baseSnapshot: shared.snapshot, workingSnapshot: snapshot });
744
922
  }
745
923
  async updateNative(scope, request) {
746
- await this.open(scope, request);
747
- let context = this.workspace.context(scope);
748
- const record = await this.selected(scope);
749
- await this.capture(record);
750
- await this.stopRecord(record, true, true, 'view_replaced');
924
+ // No Update has been sent until the native call below. A definite failure before it leaves the request not sent,
925
+ // never an unknown outcome without a journal. A request whose own reply was lost (for example the private save)
926
+ // keeps its outcome: that is an unresolved effect on the context itself.
927
+ let context, worker = true;
928
+ try {
929
+ await this.open(scope, request);
930
+ context = this.workspace.context(scope);
931
+ const record = await this.selected(scope);
932
+ await this.capture(record);
933
+ worker = false;
934
+ // Park the warm worker instead of stopping its JVM; without a proved project release, stop it as before.
935
+ // After the marker the project may be closed, so the worker cannot prove its open project any more: it is
936
+ // stopped the way a parked worker is.
937
+ if (!await this.park(record).catch(() => false)) {
938
+ if (await this.parkedMarker(record.binding))
939
+ await this.stopParked(record.binding);
940
+ else
941
+ await this.stopRecord(record, true, true, 'view_replaced');
942
+ }
943
+ }
944
+ catch (error) {
945
+ return this.unsent('update', error, worker);
946
+ }
751
947
  const checkout = context.nativeCheckout;
752
- const value = await this.nativeOperation(checkout, 'update', { request });
948
+ const value = await this.notSent('update', checkout, request, () => this.nativeOperation(checkout, 'update', { request }));
753
949
  return this.applyNativeUpdate(scope, request, value, checkout.baseVersion);
754
950
  }
951
+ /**
952
+ * A failure before a native Update or check-in was dispatched: the request is settled as not sent and keeps the
953
+ * cause, its memory diagnosis and its next step.
954
+ *
955
+ * While the context is opened and saved (`worker`), the worker may reopen or save the program, so only a refusal
956
+ * that names itself as one settles the request: a busy, blocked or full worker pool. Every other failure there
957
+ * (a lost, failed or unusable reply, a binding that no longer matches) may follow an effect in the worker and
958
+ * keeps its own outcome. Parking, a stop that was refused and the owner and server check write nothing in the
959
+ * program; a worker that was asked to end and is not proved gone may still save, so that failure keeps its outcome.
960
+ */
961
+ unsent(phase, error, worker = false) {
962
+ if (error instanceof CliError && error.code === 'coordinator.notSent')
963
+ throw error;
964
+ // A worker that was asked to end and is not proved gone may still be saving.
965
+ if (error && typeof error === 'object' && unprovedStops.has(error))
966
+ throw error;
967
+ if (worker) {
968
+ const refused = error instanceof CliError && !unprovedSaves.has(error) && (['coordinator.busy', 'coordinator.blocked', 'coordinator.capacity'].includes(error.code) ||
969
+ error.code === 'coordinator.limit' && !oversizedReplies.has(error));
970
+ if (!refused)
971
+ throw error;
972
+ }
973
+ const system = error?.code, result = error instanceof CliError ? object(error.result ?? {}) : {};
974
+ const cause = error instanceof CliError ? { code: error.code, message: error.message } :
975
+ { code: 'coordinator.launch', message: 'Its preparation failed' + (typeof system === 'string' && /^E[A-Z0-9]{2,24}$/.test(system) ? ' (' + system + ')' : '') + '.' };
976
+ throw new CliError('Native ' + phase + ' was not sent. ' + cause.message + (phase === 'update' ? ' No Update or check-in was sent' : ' The check-in was not sent') + '; run the operation again with a new request ID.', { code: 'coordinator.notSent', ...(error instanceof CliError && error.next ? { next: error.next } : {}),
977
+ result: { phase, cause, ...(result.memory === 'exhausted' ? { memory: 'exhausted', reason: 'out_of_memory', memoryCause: result.memoryCause } : {}) } });
978
+ }
755
979
  async applyNativeUpdate(scope, request, value, previousBase) {
756
980
  let context = this.workspace.context(scope);
757
981
  const checkout = context.nativeCheckout;
@@ -764,16 +988,20 @@ export class GhidraContexts {
764
988
  }
765
989
  if (value.state !== 'updated' || value.checkoutId !== checkout.checkoutId)
766
990
  fail('binding', 'Native Update did not preserve checkout identity.');
991
+ if (typeof value.modified !== 'boolean')
992
+ fail('binding', 'Native Update did not report whether the checkout holds work; the project is retained.');
767
993
  const next = { ...checkout, baseVersion: version(value.baseVersion) };
768
994
  delete next.conflict;
769
995
  const snapshot = await this.nativeReceipt(next, object(value.saved));
770
- const shared = await this.serverView(scope.target, next.baseVersion);
996
+ const shared = await this.serverView(scope.target, next.baseVersion, next.fileId);
771
997
  this.observeNativeShared(scope.target, shared);
772
998
  context = this.workspace.saveContext(scope, context.generation, { nativeCheckout: next, state: 'stopped', workingSnapshot: snapshot, baseSnapshot: shared.snapshot, baseRevision: next.baseVersion, viewEpoch: (context.viewEpoch ?? 0) + 1 });
773
- // A pristine open can mark Ghidra's checkout modified without caller work. Compare the saved buffers with the
774
- // independently read post-Update base and its proved opened states; diagnostic edit counts are not a work test.
775
- const empty = this.workspace.unchangedNative(context);
776
- return { state: value.modified === true && !empty ? 'ready' : 'empty', revision: next.baseVersion, snapshot, sharedSnapshot: shared.snapshot,
999
+ // A dirty Update that left no private change keeps only a backup that its own journal proves disposable; remove it
1000
+ // now so a context that continues in this checkout can later be proved pristine and released. A refusal keeps it.
1001
+ if (value.modified === false && Object.keys(object(value.disposableBackups ?? {})).length)
1002
+ await this.nativeOperation(next, 'prune-backups', { verifiedVersion: next.baseVersion }).catch(() => undefined);
1003
+ // Ghidra's own answer after the Update says whether the checkout holds private work.
1004
+ return { state: value.modified ? 'ready' : 'empty', revision: next.baseVersion, snapshot, sharedSnapshot: shared.snapshot,
777
1005
  receivedChanges: Number(next.baseVersion !== previousBase), nativeMergeInvocations: Number(value.nativeMergeInvocations ?? 0) };
778
1006
  }
779
1007
  async recoverUpdate(scope, request) {
@@ -792,8 +1020,11 @@ export class GhidraContexts {
792
1020
  const q = object(journal.request), value = journal.result === undefined ? undefined : object(journal.result), { owner } = await this.nativeOwner(checkout);
793
1021
  if (q.request !== request || q.root !== checkout.root || q.fileId !== checkout.fileId || q.checkoutId !== checkout.checkoutId || stable(q.owner) !== stable(owner) || !value)
794
1022
  return { state: 'unknown' };
795
- const observed = await this.nativeOperation(checkout, 'status');
796
- if (observed.state !== 'ready' || observed.checkoutId !== checkout.checkoutId || observed.baseVersion !== value.baseVersion || object(observed.saved).fingerprint !== object(value.saved).fingerprint)
1023
+ const observed = await this.nativeOperation(checkout, 'status'), journaled = object(value.saved ?? {});
1024
+ // The project must still be in the state the journal recorded. A journal of an earlier build names that state by a
1025
+ // hash of the database, which nothing computes any more: there Ghidra's modification status is compared instead.
1026
+ const same = typeof journaled.modified === 'boolean' ? object(observed.saved ?? {}).fingerprint === journaled.fingerprint : observed.modified === value.modified;
1027
+ if (observed.state !== 'ready' || observed.recoverable !== false || observed.checkoutId !== checkout.checkoutId || observed.baseVersion !== value.baseVersion || !same)
797
1028
  return { state: 'unknown' };
798
1029
  return this.applyNativeUpdate(scope, request, value, version(journal.baseVersion));
799
1030
  }
@@ -804,15 +1035,53 @@ export class GhidraContexts {
804
1035
  const saved = object(JSON.parse(await readFile(await this.workspace.artifacts.verify(publication.snapshot), 'utf8')));
805
1036
  if (saved.engine !== this.nativeEngine || saved.source !== 'checkout' || object(saved.checkout).root !== checkout.root || saved.fileId !== checkout.fileId)
806
1037
  fail('binding', 'Publication differs from its prepared native project.');
807
- const value = await this.nativeOperation(checkout, 'checkin', { request: publication.id, fingerprint: text(saved.fingerprint), expectedVersion: publication.expectedRevision });
1038
+ const value = await this.notSent('checkin', checkout, publication.id, () => this.nativeOperation(checkout, 'checkin', { request: publication.id, fingerprint: text(saved.fingerprint), expectedVersion: publication.expectedRevision }));
808
1039
  if (value.state === 'conflict')
809
1040
  return { state: 'conflict', applied: 0, conflict: String(value.conflict) };
810
1041
  if (value.state !== 'checked_in' || value.baseVersion !== publication.expectedRevision + 1)
811
1042
  fail('unknown', 'Native check-in outcome requires independent reconciliation; the project is retained.');
812
- const verified = await this.recover(publication);
813
- if (verified.state !== 'verified')
814
- fail('unknown', 'Native history and independent exact-buffer readback do not yet establish publication.');
815
- return { state: 'published', revision: verified.revision, snapshot: verified.snapshot };
1043
+ // Ghidra's check-in returned and the checkout now stands at the new version: that is the publication. The version
1044
+ // is not read back from the server; its view is the one that was checked in. Only a check-in whose answer was lost
1045
+ // is settled from history (`recover`).
1046
+ const revision = publication.expectedRevision + 1, binding = await this.server().ensure();
1047
+ await this.rememberVersion(publication.target, binding, { state: 'verified', version: revision, fileId: checkout.fileId, fingerprint: versionIdentity(checkout.fileId, revision) });
1048
+ const shared = await this.serverView(publication.target, revision, checkout.fileId);
1049
+ return { state: 'published', revision, snapshot: shared.snapshot, observation: value };
1050
+ }
1051
+ /**
1052
+ * After a verified publication the check-in kept the checkout. When its own post-check-in observation proves
1053
+ * the project unchanged at exactly the published version (after removing backups proved disposable by this
1054
+ * checkout's journals), the context continues in it.
1055
+ */
1056
+ async continueNative(scope, observed) {
1057
+ const context = this.workspace.context(scope), checkout = context.nativeCheckout;
1058
+ if (!checkout || checkout.state !== 'verified' || !context.baseSnapshot || context.debugger?.traces.length || this.workspace.uncertainOutcome(scope))
1059
+ return false;
1060
+ const base = object(JSON.parse(await readFile(await this.workspace.artifacts.verify(context.baseSnapshot), 'utf8')));
1061
+ const program = basename(checkout.path);
1062
+ const valid = (value) => {
1063
+ const saved = object(value.saved ?? {});
1064
+ return value.checkedOut === true && value.modified === false && value.recoverable === false && value.fileId === checkout.fileId && value.checkoutId === checkout.checkoutId &&
1065
+ value.baseVersion === checkout.baseVersion && saved.fileId === checkout.fileId && saved.version === checkout.baseVersion &&
1066
+ base.source === 'server' && base.version === checkout.baseVersion && base.fileId === checkout.fileId && Array.isArray(value.projectFiles);
1067
+ };
1068
+ if (observed.state !== 'checked_in' || !valid(observed))
1069
+ return false;
1070
+ let observation = observed;
1071
+ const files = (value) => value.projectFiles.map(String);
1072
+ const { conflict, ...rest } = checkout, active = { ...rest, state: 'active' };
1073
+ if (files(observation).some(name => name !== program)) {
1074
+ if (!files(observation).every(name => name === program || this.nativeKeepName(checkout, name)))
1075
+ return false;
1076
+ observation = await this.nativeOperation(active, 'prune-backups', { verifiedVersion: checkout.baseVersion });
1077
+ if (observation.state !== 'pruned' || !valid(observation))
1078
+ return false;
1079
+ }
1080
+ if (stable(files(observation)) !== stable([program]))
1081
+ return false;
1082
+ const snapshot = await this.nativeReceipt(active, object(observation.saved));
1083
+ this.workspace.saveContext(scope, context.generation, { nativeCheckout: active, state: 'stopped', workingSnapshot: snapshot, scalars: [], complexChanges: [] });
1084
+ return true;
816
1085
  }
817
1086
  async dropNative(scope, request) {
818
1087
  const context = this.workspace.context(scope), checkout = context.nativeCheckout;
@@ -823,8 +1092,7 @@ export class GhidraContexts {
823
1092
  const shared = object(JSON.parse(await readFile(await this.workspace.artifacts.verify(context.baseSnapshot), 'utf8')));
824
1093
  if (shared.source !== 'server' || shared.version !== checkout.baseVersion || shared.fileId !== checkout.fileId)
825
1094
  fail('binding', 'Verified native disposal reference changed.');
826
- const parameters = { verifiedVersion: checkout.baseVersion, fingerprint: text(shared.fingerprint), ...(checkout.opened ? { opened: checkout.opened,
827
- openedVerified: this.workspace.unchangedBuffers(context.target, shared, checkout.opened) } : {}) };
1095
+ const parameters = { verifiedVersion: checkout.baseVersion };
828
1096
  let released;
829
1097
  try {
830
1098
  released = await this.nativeOperation(checkout, 'release', parameters);
@@ -849,7 +1117,7 @@ export class GhidraContexts {
849
1117
  const observed = await this.nativeOperation(checkout, 'status');
850
1118
  if (observed.state !== 'ready' || observed.checkedOut !== true || observed.fileId !== checkout.fileId || observed.checkoutId !== checkout.checkoutId || observed.baseVersion !== checkout.baseVersion)
851
1119
  return;
852
- const { opened, ...binding } = checkout, active = { ...binding, state: 'active' };
1120
+ const active = { ...checkout, state: 'active' };
853
1121
  const snapshot = await this.nativeReceipt(active, object(observed.saved)), context = this.workspace.context(scope);
854
1122
  result = this.workspace.retainNativeDisposal(scope, context.generation, checkout, snapshot, request);
855
1123
  }
@@ -865,14 +1133,12 @@ export class GhidraContexts {
865
1133
  await this.dropNative(scope, request);
866
1134
  return;
867
1135
  }
868
- // No new server version; the independent base view must equal all saved local buffers.
869
- const local = object(JSON.parse(await readFile(await this.workspace.artifacts.verify(context.workingSnapshot), 'utf8'))), base = object(JSON.parse(await readFile(await this.workspace.artifacts.verify(context.baseSnapshot), 'utf8')));
870
- if (!this.workspace.unchangedBuffers(context.target, base, local.fingerprint))
871
- fail('binding', 'An unchanged native checkout differs from its shared base.');
872
- const opened = local.fingerprint === base.fingerprint ? {} : { opened: text(local.fingerprint) };
873
- const { opened: previousOpened, ...checkout } = context.nativeCheckout;
1136
+ // No new server version: Ghidra reported this checkout unmodified, and the release asks it again.
1137
+ if (!this.workspace.unchangedNative(context))
1138
+ fail('binding', 'A native checkout that Ghidra reports modified holds private work.');
1139
+ const checkout = context.nativeCheckout;
874
1140
  // Keep the original saved view and diagnostics until release succeeds. A refused release is still private work.
875
- this.workspace.saveContext(scope, context.generation, { state: 'stopped', nativeCheckout: { ...checkout, ...opened, state: 'verified' } });
1141
+ this.workspace.saveContext(scope, context.generation, { state: 'stopped', nativeCheckout: { ...checkout, state: 'verified' } });
876
1142
  await this.dropNative(scope, request);
877
1143
  }
878
1144
  /** Close and GC drop a working copy only when Ghidra itself reports no private change. */
@@ -887,13 +1153,13 @@ export class GhidraContexts {
887
1153
  }
888
1154
  const base = object(JSON.parse(await readFile(await this.workspace.artifacts.verify(context.baseSnapshot), 'utf8'))), observed = await this.nativeOperation(checkout, 'status');
889
1155
  const fingerprint = observed.saved && typeof observed.saved === 'object' ? observed.saved.fingerprint : undefined;
890
- // Ghidra reports its own open rewrite as a modification; only exact no-work bytes may carry it.
1156
+ // Ghidra's own, fresh answer decides whether the checkout holds work.
891
1157
  if (base.source !== 'server' || base.version !== checkout.baseVersion || observed.state !== 'ready' || observed.checkedOut !== true || observed.recoverable !== false || observed.fileId !== checkout.fileId ||
892
- observed.checkoutId !== checkout.checkoutId || observed.baseVersion !== checkout.baseVersion || !this.workspace.unchangedBuffers(context.target, base, fingerprint) ||
893
- (observed.modified !== false && fingerprint === base.fingerprint) || typeof observed.modified !== 'boolean' ||
894
- !Array.isArray(observed.projectFiles) || observed.projectFiles.some(name => name !== basename(checkout.path)))
1158
+ observed.checkoutId !== checkout.checkoutId || observed.baseVersion !== checkout.baseVersion || observed.modified !== false ||
1159
+ // Backups are checked by the native release itself: each must be proved disposable by this checkout's journals.
1160
+ !Array.isArray(observed.projectFiles) || observed.projectFiles.some(name => name !== basename(checkout.path) && !this.nativeKeepName(checkout, String(name))))
895
1161
  return false;
896
- // The release accepts exactly the observed bytes, never the older receipt.
1162
+ // The context keeps the receipt of the state that was just observed, not an older one.
897
1163
  if (fingerprint !== object(JSON.parse(await readFile(await this.workspace.artifacts.verify(context.workingSnapshot), 'utf8'))).fingerprint) {
898
1164
  const snapshot = await this.nativeReceipt(checkout, object(observed.saved));
899
1165
  this.workspace.saveContext(scope, context.generation, { workingSnapshot: snapshot });
@@ -977,6 +1243,8 @@ export class GhidraContexts {
977
1243
  if (object(value).context === context.id)
978
1244
  fail('blocked', 'A project of this context still exists under another name; restore its directory.');
979
1245
  }
1246
+ // This owner's own idle native services are not foreign helpers; busy ones refuse.
1247
+ await this.requireIdleServices();
980
1248
  const process = await runtimeProcesses(dirname(this.workspace.directory));
981
1249
  if (this.capacity.slots.has(context.id) || process.some(p => p.kind !== 'server') || (await migrationProcessBlockers(this.c.appArguments.AppDataDirectory)).length)
982
1250
  fail('busy', 'Stop or reconcile every Ghidra worker and native helper before giving up a missing checkout.');
@@ -1021,13 +1289,10 @@ export class GhidraContexts {
1021
1289
  }
1022
1290
  const q = object(journal.request), result = object(journal.result ?? {}), saved = object(result.saved ?? {}), { owner } = await this.nativeOwner(checkout);
1023
1291
  const shared = object(JSON.parse(await readFile(await this.workspace.artifacts.verify(context.baseSnapshot), 'utf8')));
1024
- // An older opened proof cannot undo a live checkout. The native release guard can still reconcile an
1025
- // already completed release, or independently establish that the original checkout survived refusal.
1026
- const pendingOpened = typeof checkout.opened === 'string' && /^[a-f0-9]{64}$/.test(checkout.opened) && checkout.opened === saved.fingerprint;
1027
1292
  if (q.request !== request || q.root !== checkout.root || q.fileId !== checkout.fileId || q.checkoutId !== checkout.checkoutId || stable(q.owner) !== stable(owner) || result.state !== 'updated' || typeof result.modified !== 'boolean' ||
1028
1293
  result.checkoutId !== checkout.checkoutId || result.baseVersion !== checkout.baseVersion || saved.fileId !== checkout.fileId || saved.version !== checkout.baseVersion ||
1029
1294
  shared.source !== 'server' || shared.version !== checkout.baseVersion || shared.fileId !== checkout.fileId || shared.origin !== checkout.origin || shared.repository !== checkout.repository ||
1030
- !this.workspace.unchangedBuffers(context.target, shared, saved.fingerprint) && !pendingOpened)
1295
+ result.modified !== false)
1031
1296
  return { state: 'unknown' };
1032
1297
  await this.dropNative(scope, request);
1033
1298
  return { state: 'verified', revision: checkout.baseVersion };
@@ -1041,6 +1306,26 @@ export class GhidraContexts {
1041
1306
  fail('unknown', 'Native discard is unproved; its project and journal remain retained.');
1042
1307
  return this.applyNativeDiscard(scope, value);
1043
1308
  }
1309
+ /**
1310
+ * Unsaved changes that an interrupted Ghidra session left in this checkout: Ghidra itself restores and saves them, or
1311
+ * deletes them. Repeating the command is safe; with nothing left to settle it answers `absent`.
1312
+ */
1313
+ async settleUnsaved(scope, keep) {
1314
+ const context = this.workspace.context(scope), checkout = context.nativeCheckout;
1315
+ if (!checkout || checkout.state !== 'active')
1316
+ fail('unsupported', 'This context has no active native checkout.');
1317
+ if (!await this.neverStartedOrClosed(context))
1318
+ fail('busy', 'Close this context before settling the unsaved changes of an interrupted session.');
1319
+ const value = await this.nativeOperation(checkout, 'unsaved', { keep, baseVersion: checkout.baseVersion });
1320
+ if (!['recovered', 'discarded', 'absent'].includes(String(value.state)) || value.recoverable !== false || value.checkedOut !== true || value.checkoutId !== checkout.checkoutId ||
1321
+ value.baseVersion !== checkout.baseVersion || typeof value.modified !== 'boolean')
1322
+ fail('unknown', 'Ghidra did not report the unsaved changes settled; the project is retained. Run the command again.');
1323
+ // The context names the state Ghidra reports now, also when an earlier run of this command lost its reply.
1324
+ const saved = object(value.saved), known = context.workingSnapshot ? object(JSON.parse(await readFile(await this.workspace.artifacts.verify(context.workingSnapshot), 'utf8'))).fingerprint : undefined;
1325
+ if (saved.fingerprint !== known)
1326
+ this.workspace.saveContext(scope, context.generation, { state: 'stopped', workingSnapshot: await this.nativeReceipt(checkout, saved), viewEpoch: (context.viewEpoch ?? 0) + 1 });
1327
+ return { state: value.state, modified: value.modified };
1328
+ }
1044
1329
  async recoverDiscardNative(scope, request, original) {
1045
1330
  const context = this.workspace.context(scope), checkout = context.nativeCheckout;
1046
1331
  if (!original || !checkout || checkout.state !== 'active' || checkout.root !== original.root || !await this.closed(scope))
@@ -1084,9 +1369,7 @@ export class GhidraContexts {
1084
1369
  fail('unknown', 'Native discard did not establish an unchanged checkout.');
1085
1370
  const next = { ...checkout, checkoutId: Number(value.checkoutId), baseVersion: version(value.baseVersion) };
1086
1371
  delete next.conflict;
1087
- const shared = await this.serverView(scope.target, next.baseVersion), snapshot = await this.nativeReceipt(next, object(value.saved));
1088
- if (shared.value.fingerprint !== object(value.saved).fingerprint)
1089
- fail('unknown', 'Discarded checkout differs from independent server readback.');
1372
+ const shared = await this.serverView(scope.target, next.baseVersion, next.fileId), snapshot = await this.nativeReceipt(next, object(value.saved));
1090
1373
  this.observeNativeShared(scope.target, shared);
1091
1374
  this.workspace.saveContext(scope, context.generation, { nativeCheckout: next, state: 'stopped', baseRevision: next.baseVersion, baseSnapshot: shared.snapshot, workingSnapshot: snapshot, scalars: [], complexChanges: [], viewEpoch: (context.viewEpoch ?? 0) + 1 });
1092
1375
  return { baseRevision: next.baseVersion, retainedKeepFile: String(value.retainedKeepFile) };
@@ -1094,7 +1377,7 @@ export class GhidraContexts {
1094
1377
  async open(scope, request) {
1095
1378
  const context = this.workspace.context(scope), target = this.workspace.target(scope.target);
1096
1379
  if (this.workspace.unresolved(scope).some(intent => intent.id !== request && intent.operation !== 'ghidra.open'))
1097
- fail('blocked', 'This context retains an unresolved operation; reconcile its recorded outcome before continuing.');
1380
+ failUnresolved(this.workspace, scope, 'This context retains an unresolved operation.');
1098
1381
  let binding, unfinished = false;
1099
1382
  ({ binding, unfinished } = await this.lastWorker(context.id, { ...context, ...scope }));
1100
1383
  if (binding)
@@ -1114,16 +1397,50 @@ export class GhidraContexts {
1114
1397
  fail('migration', 'This context contains legacy detached work; run ghidra migrate --target ' + scope.target + ' --dry-run, then ghidra migrate --target ' + scope.target + '. Its data is retained.');
1115
1398
  if (binding && unfinished && !stopped && alive(binding.pid) && !await this.retiredWorker(binding))
1116
1399
  fail('busy', 'A worker of this context has not finished starting; it is retained.');
1117
- if (binding && !unfinished && !stopped && alive(binding.pid) && ((binding.viewEpoch ?? 0) !== (context.viewEpoch ?? 0) ||
1400
+ // A leased worker is held before any use. One built for another runtime is asked to stop; one that is
1401
+ // retiring or already stopped by itself is settled, and its saved project is reopened below.
1402
+ let ended = false, silent = false;
1403
+ const live = () => !ended && alive(binding.pid);
1404
+ if (binding && !unfinished && !stopped && binding.leasePort && binding.context === context.id) {
1405
+ // A worker whose helper classes come from another build of this package is replaced like one of another runtime:
1406
+ // its work is saved, and its classes would answer by the rules of that build.
1407
+ const previous = binding.runtimeFingerprint !== this.inputs.fingerprint || binding.helpers !== await helperSourcesKey().catch(() => binding.helpers);
1408
+ if (alive(binding.pid) && previous && !await this.workerGone(binding) && !await this.retireWorker(binding, 'runtime_changed'))
1409
+ fail('busy', 'A context worker of the previous runtime is still running a command; retry after it ends.');
1410
+ // A lease that stays silent says nothing about the worker: the checks below ask the worker itself, and one
1411
+ // that does not answer either is retired there.
1412
+ const held = await this.workerGone(binding) ? 'gone' : await this.holdLease(binding).catch(error => {
1413
+ if (!(error instanceof CliError) || object(error.result ?? {}).lease !== 'silent')
1414
+ throw error;
1415
+ silent = true;
1416
+ return 'held';
1417
+ });
1418
+ if (held !== 'held') {
1419
+ if (held === 'retiring' && !await this.awaitExit(binding))
1420
+ fail('busy', 'A context worker that is stopping after its idle time has not exited yet; retry the command.');
1421
+ ended = true;
1422
+ if (await this.settleRetired(binding))
1423
+ stopped = true;
1424
+ }
1425
+ }
1426
+ // A worker left parked (its owner ended mid-merge) holds no project: stop it and relaunch below.
1427
+ if (binding && !unfinished && !stopped && live() && await this.parkedMarker(binding)) {
1428
+ await this.stopParked(binding);
1429
+ stopped = true;
1430
+ }
1431
+ if (binding && !unfinished && !stopped && live() && ((binding.viewEpoch ?? 0) !== (context.viewEpoch ?? 0) ||
1118
1432
  binding.baseRevision !== context.baseRevision && context.baseRevision !== undefined)) {
1119
1433
  await this.stopRecord(await this.verified(binding, target), true, false, 'view_replaced');
1120
1434
  stopped = true;
1121
1435
  }
1122
- if (binding && !unfinished && !stopped && alive(binding.pid)) {
1436
+ if (binding && !unfinished && !stopped && live()) {
1123
1437
  if (binding.context !== context.id)
1124
1438
  fail('binding', 'Native process belongs to a different working context.');
1125
1439
  try {
1126
1440
  await this.verified(binding, target);
1441
+ // The worker answers after all: it is used only once it is held.
1442
+ if (silent && await this.holdLease(binding) !== 'held')
1443
+ fail('busy', 'A context worker that is stopping after its idle time has not exited yet; retry the command.');
1127
1444
  return context;
1128
1445
  }
1129
1446
  catch (error) {
@@ -1136,9 +1453,9 @@ export class GhidraContexts {
1136
1453
  await this.debuggerReleased(binding);
1137
1454
  if (!context.nativeCheckout)
1138
1455
  await this.model(target);
1139
- if (binding && !stopped && !alive(binding.pid))
1456
+ if (binding && !stopped && !live() && !await this.settleRetired(binding))
1140
1457
  await recordLifecycle(this.workspace, context.id, { at: new Date().toISOString(), event: 'stop', reason: 'unknown', pid: binding.pid });
1141
- if (binding && (stopped || unfinished || !alive(binding.pid))) {
1458
+ if (binding && (stopped || unfinished || !live())) {
1142
1459
  if (binding.context !== context.id || binding.target !== scope.target)
1143
1460
  fail('binding', 'Retired native credential belongs to another context.');
1144
1461
  await releaseStoppedContextCredential(this.directory(), binding, this.c.secrets, alive, () => this.retiredWorker(binding));
@@ -1153,7 +1470,7 @@ export class GhidraContexts {
1153
1470
  if (!current.nativeCheckout || current.nativeCheckout.state === 'dropped')
1154
1471
  current = await this.createNative(scope);
1155
1472
  // A first open may replace the receipt; only that write advances the expected generation.
1156
- const started = await this.privateCopy(current, current.workingSnapshot);
1473
+ const started = await this.privateCopy(current);
1157
1474
  return this.workspace.saveContext(scope, started?.generation ?? current.generation, { state: 'ready' });
1158
1475
  }
1159
1476
  async retireUnresponsive(scope, binding, error) {
@@ -1180,6 +1497,9 @@ export class GhidraContexts {
1180
1497
  const binding = JSON.parse(await readFile(join(this.directory(), 'context', context.id, 'current.json'), 'utf8'));
1181
1498
  if (binding.context !== context.id)
1182
1499
  fail('binding', 'Context process binding changed.');
1500
+ // A marked worker's project may be closing: nothing runs in it until it is reopened or stopped.
1501
+ if (await this.parkedMarker(binding))
1502
+ fail('busy', 'This context worker is being reopened or stopped after a native operation; run the command again.');
1183
1503
  return this.verified(binding, this.workspace.target(scope.target));
1184
1504
  }
1185
1505
  async observation(scope) {
@@ -1193,6 +1513,8 @@ export class GhidraContexts {
1193
1513
  }
1194
1514
  async inlineScript(scope, parameters, requestId) {
1195
1515
  const record = await this.selected(scope);
1516
+ // Agent-supplied code may leave threads or domain objects behind: this JVM is never parked, only stopped.
1517
+ await durable(join(record.binding.root, 'agent-code.json'), { schema: 1, pid: record.binding.pid, tokenSecret: record.binding.tokenSecret });
1196
1518
  return runInline(record.http, record.binding.program, record.binding.root, parameters, requestId);
1197
1519
  }
1198
1520
  async call(scope, operation, parameters = {}) {
@@ -1224,11 +1546,7 @@ export class GhidraContexts {
1224
1546
  parameters = { ...parameters, calling_convention: object(validation.signature).calling_convention };
1225
1547
  }
1226
1548
  if (operation === '/apply_function_documentation') {
1227
- const name = 'InsightApplyDocumentation_' + randomUUID().replaceAll('-', '');
1228
- const source = await readFile(new URL('../../references/native/InsightApplyDocumentation.java', import.meta.url), 'utf8');
1229
- return record.http.call('/run_script_inline', { program: record.binding.program,
1230
- code: source.replace('class InsightApplyDocumentation ', `class ${name} `),
1231
- args: Buffer.from(JSON.stringify(parameters.json_body), 'utf8').toString('base64') });
1549
+ return record.http.script(record.binding.program, 'InsightApplyDocumentation', Buffer.from(JSON.stringify(parameters.json_body), 'utf8').toString('base64'));
1232
1550
  }
1233
1551
  if (operation === '/configure_analyzer' && (this.inputs.extensionRoots?.length ?? 0) > 0) {
1234
1552
  // A packed program need not persist disabled/default analyzer option registrations.
@@ -1242,6 +1560,8 @@ public class ${name} extends GhidraScript {public void run(){ghidra.app.plugin.c
1242
1560
  fail('partial', 'Installed analyzer option registration could not be established.');
1243
1561
  }
1244
1562
  if (operation === '/run_ghidra_script') {
1563
+ // An agent-selected script is agent code: this JVM is never parked afterwards.
1564
+ await durable(join(record.binding.root, 'agent-code.json'), { schema: 1, pid: record.binding.pid, tokenSecret: record.binding.tokenSecret });
1245
1565
  const script = String(parameters.script_name), path = await scriptPath(this.inputs.ghidraHome, record.binding.root, script, this.inputs.extensionRoots);
1246
1566
  const value = object(await record.http.call(operation, { ...parameters, script_name: path, program: record.binding.program }));
1247
1567
  delete value.script_path;
@@ -1312,7 +1632,7 @@ public class ${name} extends GhidraScript {
1312
1632
  }
1313
1633
  else if (saved.source === 'checkout') {
1314
1634
  const checkout = object(saved.checkout), context = this.workspace.contextById(checkout.context);
1315
- if (context.nativeCheckout?.root !== checkout.root || context.nativeCheckout.state !== 'active')
1635
+ if (context.nativeCheckout?.root !== checkout.root || context.nativeCheckout.checkoutId !== checkout.checkoutId || context.nativeCheckout.state !== 'active')
1316
1636
  fail('binding', 'Explicit export requires the original active native view.');
1317
1637
  if (await this.closed(context)) {
1318
1638
  const value = await this.nativeOperation(context.nativeCheckout, 'export', { fingerprint: saved.fingerprint, output });
@@ -1433,7 +1753,7 @@ public class ${name} extends GhidraScript {
1433
1753
  this.workspace.saveContext(scope, context.generation, { workingSnapshot: snapshot, complexChanges, ...(debuggerState ? { debugger: { ...debuggerState, connected: false, traces: debuggerState.traces.map(trace => ({ ...trace, connected: false })) } } : {}) });
1434
1754
  await this.stopRecord(record, true, false, 'mode_changed');
1435
1755
  if (mode === 'headless') {
1436
- await this.privateCopy(this.workspace.context(scope), snapshot);
1756
+ await this.privateCopy(this.workspace.context(scope));
1437
1757
  return;
1438
1758
  }
1439
1759
  const gui = await this.launch(record.binding.root, this.workspace.target(scope.target), 'context', record.binding.program, 'gui', context.id);
@@ -1466,9 +1786,8 @@ public class ${name} extends GhidraScript {
1466
1786
  return uiResult(operation, p, value, scope, record.binding.program, target.name, name);
1467
1787
  }
1468
1788
  async archivePayloads(scope, p) {
1469
- const record = await this.selected(scope), base = 'InsightArchivePayloads', name = base + '_' + randomUUID().replaceAll('-', '');
1470
- const source = await readFile(new URL('../../references/native/' + base + '.java', import.meta.url), 'utf8');
1471
- const result = object(await record.http.call('/run_script_inline', { program: record.binding.program, code: source.replace('class ' + base + ' ', `class ${name} `), args: Buffer.from(JSON.stringify(p)).toString('base64') }));
1789
+ const record = await this.selected(scope);
1790
+ const result = object(await record.http.script(record.binding.program, 'InsightArchivePayloads', Buffer.from(JSON.stringify(p)).toString('base64')));
1472
1791
  if (result.success !== true || typeof result.console_output !== 'string')
1473
1792
  fail('partial', 'Archive payload preparation failed.');
1474
1793
  const lines = result.console_output.split(/\r?\n/).filter(line => line.includes('INSIGHT_ARCHIVE_PAYLOADS '));
@@ -1834,6 +2153,17 @@ public class ${name} extends GhidraScript {
1834
2153
  const { binding, unfinished } = await this.lastWorker(context.id, { ...context, ...scope });
1835
2154
  if (!binding)
1836
2155
  return true;
2156
+ // A marked worker's work is saved; recovery may stop it (only when no command holds it).
2157
+ // A marked worker that cannot be stopped is not closed; `selected` refuses it as a live one as well.
2158
+ // A PID alive again after this worker's proved end belongs to another process: its leftover marker means nothing.
2159
+ if (!await this.workerEnded(binding) && await this.parkedMarker(binding)) {
2160
+ try {
2161
+ await this.stopParked(binding);
2162
+ }
2163
+ catch {
2164
+ return false;
2165
+ }
2166
+ }
1837
2167
  await this.workerReceipt(binding, context.id, { ...context, ...scope });
1838
2168
  const root = await realpath(binding.root);
1839
2169
  if (!ownedDirectory(root, this.directory(), [binding.kind, binding.context ?? binding.target, basename(root)]) || binding.context !== context.id || binding.target !== scope.target ||
@@ -1876,7 +2206,7 @@ public class ${name} extends GhidraScript {
1876
2206
  if (saved.source !== 'checkout')
1877
2207
  fail('binding', 'Unknown native view source.');
1878
2208
  const checkout = object(saved.checkout), context = this.workspace.contextById(checkout.context);
1879
- if (context.nativeCheckout?.root !== checkout.root || context.nativeCheckout.state !== 'active')
2209
+ if (context.nativeCheckout?.root !== checkout.root || context.nativeCheckout.checkoutId !== checkout.checkoutId || context.nativeCheckout.state !== 'active')
1880
2210
  fail('binding', 'The retained native view is no longer the active working copy.');
1881
2211
  if (await this.closed(context)) {
1882
2212
  const result = await this.nativeOperation(context.nativeCheckout, operation, { fingerprint: saved.fingerprint, ...parameters });
@@ -1920,7 +2250,7 @@ public class ${name} extends GhidraScript {
1920
2250
  let value;
1921
2251
  try {
1922
2252
  value = await this.server().nativeRead(binding, { operation: 'verify', path: checkout.path, sourceSha: target.binarySha256, fileId: checkout.fileId,
1923
- version: revisionNumber, marker: 'insight native ' + publication.id, fingerprint: saved.fingerprint });
2253
+ version: revisionNumber, marker: 'insight native ' + publication.id });
1924
2254
  }
1925
2255
  catch (error) {
1926
2256
  const failure = error;
@@ -1932,9 +2262,21 @@ public class ${name} extends GhidraScript {
1932
2262
  }
1933
2263
  if (value.state !== 'verified' || value.version !== revisionNumber)
1934
2264
  return this.recoverNativeRefusal(publication, checkout, saved);
1935
- const shared = await this.serverView(publication.target, revisionNumber);
1936
- if (object(shared.value).fingerprint !== saved.fingerprint)
1937
- return { state: 'unknown' };
2265
+ // The request journal and the repository history establish the outcome together. A journal that records this
2266
+ // request ending without a check-in (a refusal, or nothing to publish) contradicts its marker in history: the lane stays frozen.
2267
+ try {
2268
+ const journal = object(JSON.parse(await readFile(join(checkout.root, 'operations', publication.id + '-checkin.json'), 'utf8')));
2269
+ if (journal.result !== undefined && object(journal.result).state !== 'checked_in')
2270
+ return { state: 'unknown' };
2271
+ }
2272
+ catch (error) {
2273
+ if (error.code !== 'ENOENT')
2274
+ throw error;
2275
+ }
2276
+ // The marker names this exact version; its identity seeds the version view.
2277
+ if (value.fileId === checkout.fileId)
2278
+ await this.rememberVersion(publication.target, binding, value);
2279
+ const shared = await this.serverView(publication.target, revisionNumber, checkout.fileId);
1938
2280
  return { state: 'verified', revision: revisionNumber, snapshot: shared.snapshot };
1939
2281
  }
1940
2282
  /** Only the completed head-race branch before checkin() has this journal shape. */
@@ -1947,6 +2289,8 @@ public class ${name} extends GhidraScript {
1947
2289
  return unknown;
1948
2290
  const { owner, binding } = await this.nativeOwner(checkout), path = join(checkout.root, 'operations', publication.id + '-checkin.json');
1949
2291
  let journal;
2292
+ const q = { root: checkout.root, owner, operation: 'checkin', fileId: checkout.fileId, checkoutId: checkout.checkoutId,
2293
+ request: publication.id, fingerprint: saved.fingerprint, expectedVersion: publication.expectedRevision };
1950
2294
  try {
1951
2295
  if (await realpath(path) !== resolve(path))
1952
2296
  return unknown;
@@ -1957,8 +2301,6 @@ public class ${name} extends GhidraScript {
1957
2301
  return unknown;
1958
2302
  throw error;
1959
2303
  }
1960
- const q = { root: checkout.root, owner, operation: 'checkin', fileId: checkout.fileId, checkoutId: checkout.checkoutId,
1961
- request: publication.id, fingerprint: saved.fingerprint, expectedVersion: publication.expectedRevision };
1962
2304
  const result = object(journal.result ?? {}), before = object(journal.before ?? {});
1963
2305
  if (stable(journal.request) !== stable(q) || journal.marker !== undefined || journal.checkoutId !== checkout.checkoutId || journal.baseVersion !== checkout.baseVersion ||
1964
2306
  !Number.isSafeInteger(journal.headVersion) || Number(journal.headVersion) <= publication.expectedRevision || result.state !== 'conflict' ||
@@ -1985,7 +2327,7 @@ public class ${name} extends GhidraScript {
1985
2327
  const prior = await server.programStatus(binding, checkout.path);
1986
2328
  if (!history(prior))
1987
2329
  return unknown;
1988
- // A fresh reader opens the exact observed server version and checks source/file identity and all buffers.
2330
+ // The observed server version is read for its source and file identity.
1989
2331
  const shared = await this.serverView(publication.target, Number(prior.version));
1990
2332
  if (shared.revision !== prior.version || shared.value.fileId !== checkout.fileId || typeof shared.value.fingerprint !== 'string')
1991
2333
  return unknown;
@@ -2051,6 +2393,12 @@ public class ${name} extends GhidraScript {
2051
2393
  // bounded authenticated reads to establish ownership of previously orphaned children.
2052
2394
  const cleanup = this.fork({ ...this.c, signal: new AbortController().signal });
2053
2395
  let failures = 0;
2396
+ try {
2397
+ await this.stopServices();
2398
+ }
2399
+ catch {
2400
+ failures++;
2401
+ }
2054
2402
  try {
2055
2403
  await cleanup.inventory();
2056
2404
  }
@@ -2059,6 +2407,12 @@ public class ${name} extends GhidraScript {
2059
2407
  }
2060
2408
  for (const record of [...this.running.values()]) {
2061
2409
  try {
2410
+ // An opened headless context worker with an idle lease outlives its owner and stops by itself after
2411
+ // its idle time; the next owner adopts it through inventory. Starting or lease-less stages still stop.
2412
+ if (await this.detachable(record)) {
2413
+ this.running.delete(record.binding.root);
2414
+ continue;
2415
+ }
2062
2416
  // Original child handles also permit cleanup of a failed, unready owned stage.
2063
2417
  await cleanup.stopRecord(record, !record.child, true, 'owner_dispose');
2064
2418
  }
@@ -2069,6 +2423,278 @@ public class ${name} extends GhidraScript {
2069
2423
  if (failures)
2070
2424
  fail('busy', 'Some owned native stages could not be stopped; their receipts and saved work are retained.');
2071
2425
  }
2426
+ /**
2427
+ * Free one slot by stopping the idle leased worker unused for longest. A worker held by a running command
2428
+ * refuses retirement atomically, so eviction never interrupts dispatched work; its saved project reopens
2429
+ * transparently on the next command of its context.
2430
+ */
2431
+ async evictIdle(requesting) {
2432
+ const candidates = [];
2433
+ for (const record of this.running.values()) {
2434
+ const { binding } = record;
2435
+ if (binding.kind !== 'context' || binding.mode !== 'headless' || !binding.leasePort || !binding.context || binding.context === requesting || !this.capacity.slots.has(binding.context))
2436
+ continue;
2437
+ try {
2438
+ const status = await this.lease(binding, 'status');
2439
+ if (status.state === 'idle')
2440
+ candidates.push({ record, idleForMs: status.idleForMs ?? 0 });
2441
+ }
2442
+ catch { /* An unreachable worker is never evicted. */ }
2443
+ }
2444
+ for (const { record } of candidates.sort((a, b) => b.idleForMs - a.idleForMs))
2445
+ if (await this.retireWorker(record.binding, 'capacity_evicted'))
2446
+ return;
2447
+ }
2448
+ /**
2449
+ * Before exclusive maintenance (GC, migration, runtime changes): stop this owner's native services and ask every
2450
+ * idle leased worker, including detached ones, to stop. Their work is saved; a worker held by a command stays
2451
+ * and the maintenance admission then refuses as before.
2452
+ */
2453
+ async quiesce() {
2454
+ // Like disposal, maintenance may follow a command whose signal Factory already cancelled.
2455
+ const worker = this.fork({ ...this.c, signal: new AbortController().signal });
2456
+ await worker.requireIdleServices();
2457
+ if (!this.capacity.inventory)
2458
+ this.capacity.inventory = worker.inventory().catch(error => { this.capacity.inventory = undefined; throw error; });
2459
+ await this.capacity.inventory;
2460
+ for (const record of [...this.running.values()]) {
2461
+ const { binding } = record;
2462
+ if (binding.kind === 'context' && binding.mode === 'headless' && binding.leasePort && !await worker.workerGone(binding))
2463
+ await worker.retireWorker(binding, 'maintenance');
2464
+ }
2465
+ }
2466
+ /**
2467
+ * Parking keeps a worker's JVM (and its warm Ghidra) while native Update/check-in own the project: the worker
2468
+ * closes its project and the release of Ghidra's project lock is proved on disk before anything else opens it.
2469
+ * The bridge reports success even when closing fails, so its answer alone is never the proof.
2470
+ */
2471
+ /**
2472
+ * A native Update or check-in that provably never reached the server is reported as not sent for that phase only:
2473
+ * either it never reached a helper, or the helper process ended without a result (crash, timeout, cancellation,
2474
+ * memory exhaustion) before writing the operation's journal intent, which always precedes the server call, and no
2475
+ * process that could still write it exists. A helper that answered keeps its own outcome (refusal, migration,
2476
+ * binding, unknown), so a check that held the lane is never turned into a reopened one.
2477
+ */
2478
+ async notSent(phase, checkout, request, action) {
2479
+ // The journal directory is created and identified before dispatch: absence of the journal is evidence only in that
2480
+ // same directory. A moved or replaced checkout or directory proves nothing.
2481
+ const directory = join(checkout.root, 'operations');
2482
+ let before;
2483
+ try {
2484
+ await mkdir(directory, { recursive: true });
2485
+ before = await directoryIdentity(directory);
2486
+ }
2487
+ catch (error) {
2488
+ return this.unsent(phase, error);
2489
+ }
2490
+ try {
2491
+ return await action();
2492
+ }
2493
+ catch (error) {
2494
+ // Already settled before dispatch, with its own cause.
2495
+ if (!(error instanceof CliError) || error.code === 'coordinator.notSent')
2496
+ throw error;
2497
+ const memory = object(error.result ?? {}).memory === 'exhausted';
2498
+ const ended = memory || error.code === 'coordinator.malformed' || error.code.startsWith('tool.') && error.code !== 'tool.termination.unverified';
2499
+ if (error.code === 'tool.notSent' || ended && before !== undefined && await this.journalAbsent(directory, before, request, phase))
2500
+ fail('notSent', 'Native ' + phase + ' was not sent; nothing changed on the server and this context stays usable.' + (memory ? ' ' + error.message : '') +
2501
+ ' This request is settled as not sent; run the operation again with a new request ID' + (memory ? ' once memory is available.' : '.'), { phase, cause: { code: error.code, message: error.message }, ...(memory ? { memory: 'exhausted', reason: 'out_of_memory', memoryCause: object(error.result).memoryCause } : {}) });
2502
+ throw error;
2503
+ }
2504
+ }
2505
+ /**
2506
+ * No writer that could still create the journal exists, the journal directory is still the one identified before
2507
+ * dispatch, and the journal is absent from it (checked in that order).
2508
+ */
2509
+ async journalAbsent(directory, before, request, phase) {
2510
+ if (!/^q_[a-f0-9-]{36}$/.test(request) || !await this.server().nativeWritersSettled() || await directoryIdentity(directory) !== before)
2511
+ return false;
2512
+ try {
2513
+ await lstat(join(directory, request + '-' + phase + '.json'));
2514
+ return false;
2515
+ }
2516
+ catch (error) {
2517
+ if (error.code === 'ENOENT')
2518
+ return await directoryIdentity(directory) === before;
2519
+ throw error;
2520
+ }
2521
+ }
2522
+ /** How long a parked project may take to release Ghidra's lock files. */
2523
+ parkWaitMs = 10000;
2524
+ async park(record) { return timed('worker.park', 'close_project', () => this.parkWorker(record)); }
2525
+ async parkWorker(record) {
2526
+ const { binding } = record;
2527
+ if (binding.kind !== 'context' || binding.mode !== 'headless' || !binding.leasePort)
2528
+ return false;
2529
+ if (await this.ranAgentCode(binding))
2530
+ return false;
2531
+ // A helper script abandoned by a timed-out command may still run on the program: such a worker is stopped instead.
2532
+ // The worker refuses while a helper script runs or waits and admits none until this command reopens the project
2533
+ // or its hold ends; a worker without this request (an earlier build) or a command without a hold is stopped instead.
2534
+ const holder = workerLeaseHolder(binding.root);
2535
+ if (!holder)
2536
+ return false;
2537
+ try {
2538
+ if ((await this.lease(binding, 'park_held', holder)).state !== 'held')
2539
+ return false;
2540
+ }
2541
+ catch {
2542
+ return false;
2543
+ }
2544
+ // The marker precedes the close and says only that a close may be under way: a worker left like that is stopped,
2545
+ // never reopened, because the close may still complete. Only the proved release of the project lock records the
2546
+ // project as closed, which is what lets a later command reopen it.
2547
+ const marker = join(binding.root, 'parked.json'), mark = { pid: binding.pid, tokenSecret: binding.tokenSecret, at: new Date().toISOString() };
2548
+ await durable(marker, { schema: 2, closed: false, ...mark });
2549
+ try {
2550
+ await record.http.call('/close_project');
2551
+ }
2552
+ catch {
2553
+ return false;
2554
+ }
2555
+ const locks = [join(binding.root, 'view.lock'), join(binding.root, 'view.lock~')];
2556
+ for (const deadline = Date.now() + this.parkWaitMs; Date.now() < deadline; await delay(100))
2557
+ if (!(await Promise.all(locks.map(exists))).some(Boolean)) {
2558
+ await durable(marker, { schema: 2, closed: true, ...mark });
2559
+ return true;
2560
+ }
2561
+ return false;
2562
+ }
2563
+ /** This worker process executed agent-supplied script code. */
2564
+ async ranAgentCode(binding) {
2565
+ try {
2566
+ const value = object(JSON.parse(await readFile(join(binding.root, 'agent-code.json'), 'utf8')));
2567
+ return value.pid === binding.pid && value.tokenSecret === binding.tokenSecret;
2568
+ }
2569
+ catch (error) {
2570
+ return error.code !== 'ENOENT';
2571
+ }
2572
+ }
2573
+ /** This worker's marker: `closed` once its project lock was proved released, `closing` while a close may be under way. */
2574
+ async parkedState(binding) {
2575
+ // Only a leased headless worker is ever parked; a GUI or unleased worker is never stopped for a marker.
2576
+ if (binding.kind !== 'context' || binding.mode !== 'headless' || !binding.leasePort)
2577
+ return;
2578
+ // This never fails and decides one way when in doubt. A worker is unmarked only when the file is absent or
2579
+ // names another worker; an unreadable or damaged file may be this worker's own pending close, so the worker
2580
+ // counts as closing and is stopped. A new worker's launch clears whatever its predecessor left.
2581
+ let text;
2582
+ try {
2583
+ text = await readFile(join(binding.root, 'parked.json'), 'utf8');
2584
+ }
2585
+ catch (error) {
2586
+ return error.code === 'ENOENT' ? undefined : 'closing';
2587
+ }
2588
+ let value;
2589
+ try {
2590
+ value = object(JSON.parse(text));
2591
+ }
2592
+ catch {
2593
+ return 'closing';
2594
+ }
2595
+ if (!Number.isSafeInteger(value.pid) || Number(value.pid) < 1 || typeof value.tokenSecret !== 'string' || !/^context-[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(value.tokenSecret))
2596
+ return 'closing';
2597
+ if (value.pid !== binding.pid || value.tokenSecret !== binding.tokenSecret)
2598
+ return;
2599
+ // Only this explicit record proves the close. Earlier markers (schema 1) were written by some builds before the
2600
+ // close was sent, so they prove nothing and their worker is stopped.
2601
+ return value.schema === 2 && value.closed === true ? 'closed' : 'closing';
2602
+ }
2603
+ async parkedMarker(binding) { return await this.parkedState(binding) !== undefined; }
2604
+ /** Stop a marked worker. Its work is saved; its project may be closed, closing or still open. */
2605
+ async stopParked(binding) {
2606
+ const record = this.running.get(binding.root);
2607
+ if (alive(binding.pid)) {
2608
+ if (record?.child && record.child.pid === binding.pid)
2609
+ await this.stopRecord(record, false, true, 'view_replaced');
2610
+ else if ((await releaseWorkerLease(binding.root), !await this.retireWorker(binding, 'maintenance')) && alive(binding.pid))
2611
+ fail('busy', 'A parked context worker is still held by a command; retry after it ends.');
2612
+ }
2613
+ else
2614
+ await this.stopRecord({ binding, http: new HttpBridge(binding.endpoint) }, false, true, 'view_replaced');
2615
+ // The worker is gone; a marker that cannot be removed now is cleared by the next launch in this root.
2616
+ await rm(join(binding.root, 'parked.json'), { force: true }).catch(() => { });
2617
+ }
2618
+ /**
2619
+ * After a merge or refresh: reopen the parked worker's project at its new base, or stop it when the context
2620
+ * cannot continue in it (unresolved outcome, disposed checkout, failed reopen). Either way no parked worker
2621
+ * outlives the command that parked it.
2622
+ */
2623
+ async resumeParked(scope) {
2624
+ // The command may already be cancelled; the reopen or stop must still complete.
2625
+ return timed('worker.resume', 'open_project', () => this.fork({ ...this.c, signal: new AbortController().signal }).resumeWorker(scope));
2626
+ }
2627
+ async resumeWorker(scope) {
2628
+ const context = this.workspace.context(scope);
2629
+ let binding;
2630
+ try {
2631
+ binding = JSON.parse(await readFile(join(this.directory(), 'context', context.id, 'current.json'), 'utf8'));
2632
+ }
2633
+ catch {
2634
+ return;
2635
+ }
2636
+ if (binding.context !== context.id || !await this.parkedMarker(binding))
2637
+ return;
2638
+ const checkout = context.nativeCheckout;
2639
+ // A close that was never proved may still complete: such a worker is stopped, and stays marked until it is.
2640
+ const resumable = await this.parkedState(binding) === 'closed' && alive(binding.pid) && checkout?.state === 'active' && checkout.root === binding.root && !this.workspace.unresolved(scope).length && !context.debugger?.connected;
2641
+ if (!resumable) {
2642
+ await this.stopParked(binding);
2643
+ return;
2644
+ }
2645
+ const target = this.workspace.target(scope.target), token = await this.c.secrets.require(binding.tokenSecret);
2646
+ // Always a fresh bridge on this (uncancelled) fork's signal; a cached record may carry the command's own.
2647
+ const record = { ...(this.running.get(binding.root) ?? {}), binding, http: await this.bridge(binding, token) };
2648
+ try {
2649
+ // Reopening saves: the worker must not retire under it. A replayed request has no hold yet, and a hold kept
2650
+ // from before a long native operation may have expired in the worker, so it is reaffirmed there.
2651
+ const kept = workerLeaseHolder(binding.root);
2652
+ if (kept && (await this.lease(binding, 'renew', kept)).state !== 'held')
2653
+ dropWorkerLease(binding.root);
2654
+ if (await this.holdLease(binding) !== 'held')
2655
+ fail('busy', 'Parked context worker is retiring.');
2656
+ const project = object(await record.http.call('/open_project', { path: join(binding.root, 'view.gpr') }));
2657
+ if (project.success === false)
2658
+ fail('launch', 'Native working project could not be reopened.');
2659
+ // The worker's own listener serves again from here: the reopening itself goes through it.
2660
+ if (!['held', 'idle'].includes((await this.lease(binding, 'unpark')).state))
2661
+ fail('binding', 'Resumed worker did not admit helper scripts again.');
2662
+ const opened = object(await openWorkerProgram(record.http, binding.program, scope));
2663
+ if (opened.path !== binding.program || opened.read_only === true)
2664
+ fail('binding', 'Native checkout did not reopen its saved writable program.');
2665
+ binding.baseRevision = context.baseRevision;
2666
+ binding.viewEpoch = context.viewEpoch ?? 0;
2667
+ await durable(join(binding.root, 'process.json'), binding);
2668
+ await durable(join(this.directory(), 'context', context.id, 'current.json'), binding);
2669
+ await rm(join(binding.root, 'parked.json'), { force: true });
2670
+ const live = await this.verified(binding, target);
2671
+ await recordLifecycle(this.workspace, context.id, { at: new Date().toISOString(), event: 'restore', reason: 'saved_snapshot', pid: binding.pid });
2672
+ const settled = this.workspace.context(scope);
2673
+ this.workspace.saveContext(scope, settled.generation, { state: 'ready' });
2674
+ }
2675
+ catch {
2676
+ // Reopen failed: the next command relaunches the worker on its saved project.
2677
+ if (await this.parkedMarker(binding) || alive(binding.pid))
2678
+ await this.stopParked(binding).catch(() => { });
2679
+ }
2680
+ }
2681
+ /** This owner's native services; servers without them (tests, external adapters) have nothing to stop. */
2682
+ async stopServices() { await this.server().stopServices?.(); }
2683
+ /** Stop idle services; a service running another command's request refuses exclusive work instead of being killed. */
2684
+ async requireIdleServices() { if (await this.server().stopIdleServices?.() === false)
2685
+ fail('busy', 'A native service is still running or starting for another command; retry when it ends.'); }
2686
+ async detachable(record) {
2687
+ const { binding } = record;
2688
+ if (!binding.leasePort || binding.kind !== 'context' || binding.mode !== 'headless' || !binding.context || !alive(binding.pid))
2689
+ return false;
2690
+ try {
2691
+ const current = object(JSON.parse(await readFile(join(this.directory(), 'context', binding.context, 'current.json'), 'utf8')));
2692
+ return current.pid === binding.pid && current.root === binding.root && current.tokenSecret === binding.tokenSecret;
2693
+ }
2694
+ catch {
2695
+ return false;
2696
+ }
2697
+ }
2072
2698
  async inventory() {
2073
2699
  const directory = join(this.directory(), 'context');
2074
2700
  let entries;
@@ -2107,11 +2733,37 @@ public class ${name} extends GhidraScript {
2107
2733
  }
2108
2734
  if (binding.mode === 'headless' && await this.retiredInventoryWorker(binding))
2109
2735
  continue;
2736
+ if (binding.leasePort) {
2737
+ // Detached workers stop on their own schedule: never adopt one that is retiring or gone, and ask an
2738
+ // unheld worker of a previous runtime to stop. A held one keeps its slot until its command ends.
2739
+ const status = await this.lease(binding, 'status');
2740
+ if (status.state === 'gone' || status.state === 'retiring' && await this.awaitExit(binding, 10000)) {
2741
+ await this.settleRetired(binding);
2742
+ continue;
2743
+ }
2744
+ if (binding.runtimeFingerprint !== this.inputs.fingerprint || binding.helpers !== await helperSourcesKey().catch(() => binding.helpers)) {
2745
+ if (!await this.retireWorker(binding, 'runtime_changed'))
2746
+ this.capacity.slots.add(entry.name);
2747
+ continue;
2748
+ }
2749
+ }
2110
2750
  // A replacement owner must also release contexts it has not read yet.
2111
2751
  // PID existence alone grants no authority: authenticate the complete receipt.
2112
- await this.verified(binding, this.workspace.target(binding.target), false);
2752
+ try {
2753
+ await this.verified(binding, this.workspace.target(binding.target), false);
2754
+ }
2755
+ catch (error) {
2756
+ // A worker that exits meanwhile is not adopted; any other failure keeps the original refusal.
2757
+ if (binding.leasePort && await this.awaitExit(binding, 5000)) {
2758
+ await this.settleRetired(binding);
2759
+ continue;
2760
+ }
2761
+ throw error;
2762
+ }
2113
2763
  this.capacity.slots.add(entry.name);
2114
2764
  }
2765
+ else if (!stopped)
2766
+ await this.settleRetired(binding);
2115
2767
  else if (binding.mode === 'gui')
2116
2768
  await this.debuggerReleased(binding);
2117
2769
  }