@eyeauras/insight-cli 0.6.3 → 0.6.6

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 (103) hide show
  1. package/.cli-package-build.json +1 -1
  2. package/SKILL.md +9 -7
  3. package/dist/src/cli.js +1 -1
  4. package/dist/src/contexts.d.ts +32 -8
  5. package/dist/src/contexts.js +532 -92
  6. package/dist/src/cross-peer.d.ts +20 -0
  7. package/dist/src/cross-peer.js +53 -0
  8. package/dist/src/debugger-results.d.ts +2 -1
  9. package/dist/src/debugger-results.js +9 -4
  10. package/dist/src/debugger.js +3 -2
  11. package/dist/src/lifecycle.d.ts +2 -0
  12. package/dist/src/lifecycle.js +49 -2
  13. package/dist/src/native-merge-patches.js +20 -2
  14. package/dist/src/research.d.ts +14 -2
  15. package/dist/src/research.js +31 -4
  16. package/dist/src/storage-gc.js +244 -44
  17. package/dist/src/tool-runtime/run.js +24 -11
  18. package/dist/src/tool-runtime/supervisor.js +51 -9
  19. package/dist/src/workspace.d.ts +47 -1
  20. package/dist/src/workspace.js +128 -13
  21. package/package.json +1 -1
  22. package/references/agent-setup.md +11 -3
  23. package/references/debugger.md +5 -3
  24. package/references/extensions-and-sync.md +7 -6
  25. package/references/managed-runtime.md +4 -3
  26. package/references/native/InsightNativeCheckout.java +203 -16
  27. package/references/native/NATIVE-MERGE-NOTICE.txt +5 -1
  28. package/references/native-workflows.md +5 -3
  29. package/references/query-semantics.md +3 -2
  30. package/references/recovery.md +6 -0
  31. package/references/setup.md +9 -2
  32. package/skill-bundle/insight-artifacts/SKILL.md +1 -1
  33. package/skill-bundle/insight-artifacts/references/recovery.md +6 -0
  34. package/skill-bundle/insight-binary/SKILL.md +1 -1
  35. package/skill-bundle/insight-capture/SKILL.md +1 -1
  36. package/skill-bundle/insight-cli/SKILL.md +9 -7
  37. package/skill-bundle/insight-cli/references/agent-setup.md +11 -3
  38. package/skill-bundle/insight-cli/references/managed-runtime.md +4 -3
  39. package/skill-bundle/insight-cli/references/recovery.md +6 -0
  40. package/skill-bundle/insight-cli/references/setup.md +9 -2
  41. package/skill-bundle/insight-die/SKILL.md +1 -1
  42. package/skill-bundle/insight-dnspy/SKILL.md +1 -1
  43. package/skill-bundle/insight-dotnet-dump/SKILL.md +1 -1
  44. package/skill-bundle/insight-dotnet-stack/SKILL.md +1 -1
  45. package/skill-bundle/insight-dotnet-trace/SKILL.md +1 -1
  46. package/skill-bundle/insight-frida/SKILL.md +1 -1
  47. package/skill-bundle/insight-ghidra/SKILL.md +4 -3
  48. package/skill-bundle/insight-ghidra/references/debugger.md +5 -3
  49. package/skill-bundle/insight-ghidra/references/extensions-and-sync.md +7 -6
  50. package/skill-bundle/insight-ghidra/references/managed-runtime.md +4 -3
  51. package/skill-bundle/insight-ghidra/references/native-workflows.md +5 -3
  52. package/skill-bundle/insight-ghidra/references/query-semantics.md +3 -2
  53. package/skill-bundle/insight-ghidra/references/recovery.md +6 -0
  54. package/skill-bundle/insight-ghidra/references/setup.md +9 -2
  55. package/skill-bundle/insight-ilspy/SKILL.md +1 -1
  56. package/skill-bundle/insight-interop/SKILL.md +1 -1
  57. package/skill-bundle/insight-lldb/SKILL.md +1 -1
  58. package/skill-bundle/insight-llvm/SKILL.md +1 -1
  59. package/skill-bundle/insight-managed-heap/SKILL.md +1 -1
  60. package/skill-bundle/insight-managed-metadata/SKILL.md +1 -1
  61. package/skill-bundle/insight-mitmproxy/SKILL.md +1 -1
  62. package/skill-bundle/insight-overview/SKILL.md +1 -1
  63. package/skill-bundle/insight-procmon/SKILL.md +1 -1
  64. package/skill-bundle/insight-re/SKILL.md +1 -1
  65. package/skill-bundle/insight-re/references/recovery.md +6 -0
  66. package/skill-bundle/insight-sevenzip/SKILL.md +1 -1
  67. package/skill-bundle/insight-strace/SKILL.md +1 -1
  68. package/skill-bundle/insight-tshark/SKILL.md +1 -1
  69. package/skill-bundle/insight-windbg/SKILL.md +1 -1
  70. package/skill-bundle/manifest.json +1 -1
  71. package/skills/insight-artifacts/SKILL.md +1 -1
  72. package/skills/insight-artifacts/references/recovery.md +6 -0
  73. package/skills/insight-binary/SKILL.md +1 -1
  74. package/skills/insight-capture/SKILL.md +1 -1
  75. package/skills/insight-die/SKILL.md +1 -1
  76. package/skills/insight-dnspy/SKILL.md +1 -1
  77. package/skills/insight-dotnet-dump/SKILL.md +1 -1
  78. package/skills/insight-dotnet-stack/SKILL.md +1 -1
  79. package/skills/insight-dotnet-trace/SKILL.md +1 -1
  80. package/skills/insight-frida/SKILL.md +1 -1
  81. package/skills/insight-ghidra/SKILL.md +4 -3
  82. package/skills/insight-ghidra/references/debugger.md +5 -3
  83. package/skills/insight-ghidra/references/extensions-and-sync.md +7 -6
  84. package/skills/insight-ghidra/references/managed-runtime.md +4 -3
  85. package/skills/insight-ghidra/references/native-workflows.md +5 -3
  86. package/skills/insight-ghidra/references/query-semantics.md +3 -2
  87. package/skills/insight-ghidra/references/recovery.md +6 -0
  88. package/skills/insight-ghidra/references/setup.md +9 -2
  89. package/skills/insight-ilspy/SKILL.md +1 -1
  90. package/skills/insight-interop/SKILL.md +1 -1
  91. package/skills/insight-lldb/SKILL.md +1 -1
  92. package/skills/insight-llvm/SKILL.md +1 -1
  93. package/skills/insight-managed-heap/SKILL.md +1 -1
  94. package/skills/insight-managed-metadata/SKILL.md +1 -1
  95. package/skills/insight-mitmproxy/SKILL.md +1 -1
  96. package/skills/insight-overview/SKILL.md +1 -1
  97. package/skills/insight-procmon/SKILL.md +1 -1
  98. package/skills/insight-re/SKILL.md +1 -1
  99. package/skills/insight-re/references/recovery.md +6 -0
  100. package/skills/insight-sevenzip/SKILL.md +1 -1
  101. package/skills/insight-strace/SKILL.md +1 -1
  102. package/skills/insight-tshark/SKILL.md +1 -1
  103. package/skills/insight-windbg/SKILL.md +1 -1
@@ -1,5 +1,6 @@
1
- import { migrateLegacy } from './legacy-migration.js';
1
+ import { migrateLegacy, migrationProcessBlockers } from './legacy-migration.js';
2
2
  import { collectStorage } from './storage-gc.js';
3
+ import { peerStage, peerStages } from './cross-peer.js';
3
4
  import { ownedDirectory, projectPathWithin, sameDirectory } from './directory-identity.js';
4
5
  import { releaseStoppedContextCredential, launchContextCredential } from './context-credential.js';
5
6
  import { recordLifecycle } from './context-diagnostics.js';
@@ -10,7 +11,7 @@ import { verifyGhidraProcess } from './ghidra-processes.js';
10
11
  import { processIdentity } from './tool-runtime/identity.js';
11
12
  import { runtimeProcesses } from './runtime-manager.js';
12
13
  import { randomUUID, randomBytes } from 'node:crypto';
13
- import { mkdir, mkdtemp, open, readFile, readdir, rename, link, realpath, copyFile, chmod, writeFile, unlink } from 'node:fs/promises';
14
+ import { mkdir, mkdtemp, open, readFile, readdir, lstat, rename, link, realpath, copyFile, chmod, writeFile, unlink } from 'node:fs/promises';
14
15
  import { constants } from 'node:fs';
15
16
  import { join, delimiter, resolve, dirname, basename } from 'node:path';
16
17
  import { createServer } from 'node:net';
@@ -24,7 +25,7 @@ import { logicalPrograms } from './cross-results.js';
24
25
  import { uiResult } from './ui-results.js';
25
26
  import { fileURLToPath } from 'node:url';
26
27
  import { readCallerGoal, awaitCaller } from './debugger-caller.js';
27
- import { debuggerProgramMetadata } from './debugger-results.js';
28
+ import { debuggerProgramMetadata, debuggerMetadataFingerprint } from './debugger-results.js';
28
29
  import { nativeQueries } from './query-policy.js';
29
30
  import { nativeQuery } from './native-queries.js';
30
31
  import { runInline } from './inline-script.js';
@@ -56,6 +57,17 @@ async function durable(path, value) {
56
57
  }
57
58
  await rename(temporary, path);
58
59
  }
60
+ async function exists(path) {
61
+ try {
62
+ await lstat(path);
63
+ return true;
64
+ }
65
+ catch (error) {
66
+ if (error.code === 'ENOENT')
67
+ return false;
68
+ throw error;
69
+ }
70
+ }
59
71
  async function port() {
60
72
  const listener = createServer();
61
73
  await new Promise((ok, bad) => { listener.once('error', bad); listener.listen(0, '127.0.0.1', ok); });
@@ -383,7 +395,10 @@ export class GhidraContexts {
383
395
  fail('save', 'Private program save was not acknowledged.');
384
396
  if (context?.nativeCheckout) {
385
397
  const saved = object(await this.nativeView(record, { operation: 'fingerprint' }));
386
- return this.nativeReceipt(context.nativeCheckout, saved);
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 });
387
402
  }
388
403
  const output = join(record.binding.root, 'exports');
389
404
  await mkdir(output, { recursive: true, mode: 0o700 });
@@ -582,6 +597,9 @@ export class GhidraContexts {
582
597
  if (observed.state !== 'ready' || observed.checkoutId !== checkout.checkoutId)
583
598
  fail('binding', 'This runtime cannot open the native checkout without changing it; the project is retained.');
584
599
  }
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);
585
603
  record = await this.launch(root, target, 'context', checkout.path, 'headless', context.id);
586
604
  const project = object(await record.http.call('/open_project', { path: join(root, 'view.gpr') }));
587
605
  if (project.success === false)
@@ -594,9 +612,10 @@ export class GhidraContexts {
594
612
  record.binding.viewEpoch = context.viewEpoch ?? 0;
595
613
  await durable(join(root, 'process.json'), record.binding);
596
614
  await durable(join(this.directory(), 'context', context.id, 'current.json'), record.binding);
615
+ const generation = pristine ? await this.recordOpened(context, checkout, record, pristine) : undefined;
597
616
  if (context.workingSnapshot)
598
617
  await recordLifecycle(this.workspace, context.id, { at: new Date().toISOString(), event: 'restore', reason: 'saved_snapshot', pid: record.binding.pid });
599
- return record;
618
+ return generation === undefined ? record : { ...record, generation };
600
619
  }
601
620
  catch (error) {
602
621
  if (record)
@@ -606,6 +625,90 @@ export class GhidraContexts {
606
625
  throw error;
607
626
  }
608
627
  }
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
+ }
609
712
  async createNative(scope) {
610
713
  const context = this.workspace.context(scope), target = this.workspace.target(scope.target), server = this.server(), binding = await server.ensure();
611
714
  const parent = join(this.directory(), 'context', context.id);
@@ -667,7 +770,10 @@ export class GhidraContexts {
667
770
  const shared = await this.serverView(scope.target, next.baseVersion);
668
771
  this.observeNativeShared(scope.target, shared);
669
772
  context = this.workspace.saveContext(scope, context.generation, { nativeCheckout: next, state: 'stopped', workingSnapshot: snapshot, baseSnapshot: shared.snapshot, baseRevision: next.baseVersion, viewEpoch: (context.viewEpoch ?? 0) + 1 });
670
- return { state: value.modified === true ? 'ready' : 'empty', revision: next.baseVersion, snapshot, sharedSnapshot: shared.snapshot,
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,
671
777
  receivedChanges: Number(next.baseVersion !== previousBase), nativeMergeInvocations: Number(value.nativeMergeInvocations ?? 0) };
672
778
  }
673
779
  async recoverUpdate(scope, request) {
@@ -708,7 +814,7 @@ export class GhidraContexts {
708
814
  fail('unknown', 'Native history and independent exact-buffer readback do not yet establish publication.');
709
815
  return { state: 'published', revision: verified.revision, snapshot: verified.snapshot };
710
816
  }
711
- async dropNative(scope) {
817
+ async dropNative(scope, request) {
712
818
  const context = this.workspace.context(scope), checkout = context.nativeCheckout;
713
819
  if (!checkout || checkout.state === 'dropped')
714
820
  return;
@@ -717,29 +823,57 @@ export class GhidraContexts {
717
823
  const shared = object(JSON.parse(await readFile(await this.workspace.artifacts.verify(context.baseSnapshot), 'utf8')));
718
824
  if (shared.source !== 'server' || shared.version !== checkout.baseVersion || shared.fileId !== checkout.fileId)
719
825
  fail('binding', 'Verified native disposal reference changed.');
720
- const parameters = { verifiedVersion: checkout.baseVersion, fingerprint: text(shared.fingerprint) };
721
- const released = await this.nativeOperation(checkout, 'release', parameters);
722
- if (released.state !== 'released')
723
- fail('unknown', 'Publication is verified but checkout release remains unproved; its project is retained.');
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) } : {}) };
828
+ let released;
829
+ try {
830
+ released = await this.nativeOperation(checkout, 'release', parameters);
831
+ }
832
+ catch (error) {
833
+ await this.retainNative(scope, checkout, request);
834
+ throw error;
835
+ }
836
+ if (released.state !== 'released') {
837
+ await this.retainNative(scope, checkout, request);
838
+ fail('unknown', 'Checkout release remains unproved; its project and saved work are retained.');
839
+ }
724
840
  const dropped = await this.nativeOperation(checkout, 'drop', parameters);
725
841
  if (dropped.state !== 'dropped')
726
842
  fail('unknown', 'Publication is verified but project deletion remains unproved.');
727
- this.workspace.saveContext(scope, context.generation, { nativeCheckout: { ...checkout, state: 'dropped' }, state: 'stopped' });
843
+ this.workspace.saveContext(scope, context.generation, { nativeCheckout: { ...checkout, state: 'dropped' }, state: 'stopped', workingSnapshot: context.baseSnapshot, scalars: [], complexChanges: [] });
844
+ }
845
+ /** A lost release reply can mean undoCheckout succeeded. Only independent ownership readback permits reopening. */
846
+ async retainNative(scope, checkout, request) {
847
+ let result;
848
+ try {
849
+ const observed = await this.nativeOperation(checkout, 'status');
850
+ if (observed.state !== 'ready' || observed.checkedOut !== true || observed.fileId !== checkout.fileId || observed.checkoutId !== checkout.checkoutId || observed.baseVersion !== checkout.baseVersion)
851
+ return;
852
+ const { opened, ...binding } = checkout, active = { ...binding, state: 'active' };
853
+ const snapshot = await this.nativeReceipt(active, object(observed.saved)), context = this.workspace.context(scope);
854
+ result = this.workspace.retainNativeDisposal(scope, context.generation, checkout, snapshot, request);
855
+ }
856
+ catch { /* Unproved release/ownership stays verified for journal-based recovery, never a new private launch. */ }
857
+ if (result)
858
+ fail('conflict', 'Final native release was refused; saved private work is retained.', result);
728
859
  }
729
- async finishEmptyNative(scope) {
860
+ async finishEmptyNative(scope, request) {
730
861
  const context = this.workspace.context(scope);
731
862
  if (!context.nativeCheckout)
732
863
  fail('binding', 'Native checkout is absent.');
733
864
  if (context.nativeCheckout.state === 'verified' || context.nativeCheckout.state === 'dropped') {
734
- await this.dropNative(scope);
865
+ await this.dropNative(scope, request);
735
866
  return;
736
867
  }
737
868
  // No new server version; the independent base view must equal all saved local buffers.
738
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')));
739
- if (local.fingerprint !== base.fingerprint)
870
+ if (!this.workspace.unchangedBuffers(context.target, base, local.fingerprint))
740
871
  fail('binding', 'An unchanged native checkout differs from its shared base.');
741
- this.workspace.saveContext(scope, context.generation, { state: 'stopped', nativeCheckout: { ...context.nativeCheckout, state: 'verified' }, workingSnapshot: context.baseSnapshot, scalars: [], complexChanges: [] });
742
- await this.dropNative(scope);
872
+ const opened = local.fingerprint === base.fingerprint ? {} : { opened: text(local.fingerprint) };
873
+ const { opened: previousOpened, ...checkout } = context.nativeCheckout;
874
+ // 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' } });
876
+ await this.dropNative(scope, request);
743
877
  }
744
878
  /** Close and GC drop a working copy only when Ghidra itself reports no private change. */
745
879
  async releaseUnchanged(scope) {
@@ -752,23 +886,27 @@ export class GhidraContexts {
752
886
  return true;
753
887
  }
754
888
  const base = object(JSON.parse(await readFile(await this.workspace.artifacts.verify(context.baseSnapshot), 'utf8'))), observed = await this.nativeOperation(checkout, 'status');
755
- if (base.source !== 'server' || base.version !== checkout.baseVersion || observed.state !== 'ready' || observed.checkedOut !== true || observed.modified !== false || observed.recoverable !== false || observed.fileId !== checkout.fileId ||
756
- observed.checkoutId !== checkout.checkoutId || observed.baseVersion !== checkout.baseVersion || object(observed.saved).fingerprint !== base.fingerprint ||
889
+ 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.
891
+ 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' ||
757
894
  !Array.isArray(observed.projectFiles) || observed.projectFiles.some(name => name !== basename(checkout.path)))
758
895
  return false;
896
+ // The release accepts exactly the observed bytes, never the older receipt.
897
+ if (fingerprint !== object(JSON.parse(await readFile(await this.workspace.artifacts.verify(context.workingSnapshot), 'utf8'))).fingerprint) {
898
+ const snapshot = await this.nativeReceipt(checkout, object(observed.saved));
899
+ this.workspace.saveContext(scope, context.generation, { workingSnapshot: snapshot });
900
+ }
759
901
  await this.finishEmptyNative(scope);
760
902
  return true;
761
903
  }
762
- /** A missing current receipt means no worker was ever started; any other missing receipt is unproved. */
904
+ /** Absence of the ready receipt alone says nothing about an interrupted first start. */
763
905
  async neverStartedOrClosed(c) {
764
- try {
765
- await readFile(join(this.directory(), 'context', c.id, 'current.json'));
766
- }
767
- catch (e) {
768
- if (e.code === 'ENOENT')
769
- return true;
770
- throw e;
771
- }
906
+ if (await exists(join(this.directory(), 'context', c.id, 'current.json')))
907
+ return this.closed(c);
908
+ if (!(await this.lastWorker(c.id, c)).binding)
909
+ return true;
772
910
  return this.closed(c);
773
911
  }
774
912
  /** A pending checkout intent may own a server checkout, so it is never treated as detached work. */
@@ -790,6 +928,81 @@ export class GhidraContexts {
790
928
  return false;
791
929
  return this.neverStartedOrClosed(context);
792
930
  }
931
+ /** Absence is proved by the owned storage that remains: nothing of the context may survive beside the lost root. */
932
+ async missingCheckout(scope) {
933
+ const context = this.workspace.context(scope), checkout = context.nativeCheckout, contexts = join(this.directory(), 'context'), parent = join(contexts, context.id);
934
+ if (!checkout || checkout.state === 'dropped')
935
+ fail('unsupported', 'This context has no retained native checkout.');
936
+ const name = basename(checkout.root);
937
+ if (basename(dirname(checkout.root)) !== context.id)
938
+ fail('binding', 'Native checkout receipt names a directory outside this context.');
939
+ if (await realpath(contexts) !== join(await realpath(this.workspace.directory), 'ghidra-native', 'context'))
940
+ fail('binding', 'Owned context storage moved.');
941
+ const absent = async (path) => { try {
942
+ await lstat(path);
943
+ return false;
944
+ }
945
+ catch (error) {
946
+ if (error.code === 'ENOENT')
947
+ return true;
948
+ throw error;
949
+ } };
950
+ if (!await absent(checkout.root) || !await absent(join(parent, name)))
951
+ fail('blocked', 'The native checkout project still exists; it is not lost.');
952
+ // Only receipts of the lost root may remain beside it, and its last worker must be gone.
953
+ if (!await absent(parent))
954
+ for (const entry of await readdir(parent, { withFileTypes: true })) {
955
+ if (!entry.isFile() || !['checkout.json', 'current.json'].includes(entry.name))
956
+ fail('blocked', 'Other retained data of this context still exists; its checkout is not proved lost.');
957
+ const receipt = object(JSON.parse(await readFile(join(parent, entry.name), 'utf8')));
958
+ if (typeof receipt.root !== 'string' || basename(receipt.root) !== name || basename(dirname(receipt.root)) !== context.id)
959
+ fail('blocked', 'A retained receipt names another project of this context.');
960
+ if (entry.name === 'current.json' && (!Number.isSafeInteger(receipt.pid) || alive(Number(receipt.pid))))
961
+ fail('busy', 'The last worker of this context is not proved stopped.');
962
+ }
963
+ // A project renamed inside owned storage keeps its owner receipt.
964
+ for (const owner of await readdir(contexts, { withFileTypes: true }))
965
+ if (owner.isDirectory())
966
+ for (const root of await readdir(join(contexts, owner.name), { withFileTypes: true }))
967
+ if (root.isDirectory()) {
968
+ let value;
969
+ try {
970
+ value = JSON.parse(await readFile(join(contexts, owner.name, root.name, 'native-owner.json'), 'utf8'));
971
+ }
972
+ catch (error) {
973
+ if (error.code === 'ENOENT')
974
+ continue;
975
+ throw error;
976
+ }
977
+ if (object(value).context === context.id)
978
+ fail('blocked', 'A project of this context still exists under another name; restore its directory.');
979
+ }
980
+ const process = await runtimeProcesses(dirname(this.workspace.directory));
981
+ if (this.capacity.slots.has(context.id) || process.some(p => p.kind !== 'server') || (await migrationProcessBlockers(this.c.appArguments.AppDataDirectory)).length)
982
+ fail('busy', 'Stop or reconcile every Ghidra worker and native helper before giving up a missing checkout.');
983
+ return checkout;
984
+ }
985
+ async abandonMissing(scope, check) {
986
+ const checkout = await this.missingCheckout(scope), context = this.workspace.context(scope), server = this.server(), binding = await server.ensure();
987
+ if (checkout.origin !== binding.origin || checkout.repository !== binding.repository || checkout.path !== programPath(scope.target))
988
+ fail('binding', 'Native checkout server binding changed.');
989
+ const value = await server.nativeCheckout(binding, { root: checkout.root, operation: 'abandon', check, fileId: checkout.fileId, checkoutId: checkout.checkoutId, baseVersion: checkout.baseVersion,
990
+ owner: { protocol: this.nativeEngine, context: context.id, target: scope.target, path: checkout.path, repository: checkout.repository } });
991
+ if (value.state !== (check ? 'endable' : 'abandoned'))
992
+ fail('unknown', 'The server checkout is not proved ended; repeat this command.');
993
+ if (check)
994
+ return;
995
+ // Receipts of the lost root would otherwise be read as an unproved worker; they stay as evidence.
996
+ const kept = join(this.workspace.directory, 'native-discards', scope.target);
997
+ await mkdir(kept, { recursive: true, mode: 0o700 });
998
+ try {
999
+ await rename(join(this.directory(), 'context', context.id), join(kept, context.id + '-receipts-' + randomUUID()));
1000
+ }
1001
+ catch (error) {
1002
+ if (error.code !== 'ENOENT')
1003
+ throw error;
1004
+ }
1005
+ }
793
1006
  async collect(dryRun) {
794
1007
  return collectStorage(this.workspace, { closed: c => this.neverStartedOrClosed(c), release: c => this.releaseUnchanged(c) }, dryRun, message => this.c.progress(message));
795
1008
  }
@@ -806,12 +1019,17 @@ export class GhidraContexts {
806
1019
  return { state: 'unknown' };
807
1020
  throw error;
808
1021
  }
809
- const q = object(journal.request), result = object(journal.result ?? {}), { owner } = await this.nativeOwner(checkout);
1022
+ const q = object(journal.request), result = object(journal.result ?? {}), saved = object(result.saved ?? {}), { owner } = await this.nativeOwner(checkout);
810
1023
  const shared = object(JSON.parse(await readFile(await this.workspace.artifacts.verify(context.baseSnapshot), 'utf8')));
811
- if (q.request !== request || q.root !== checkout.root || q.checkoutId !== checkout.checkoutId || stable(q.owner) !== stable(owner) || result.state !== 'updated' || result.modified !== false ||
812
- result.baseVersion !== checkout.baseVersion || shared.source !== 'server' || shared.fileId !== checkout.fileId || shared.fingerprint !== object(result.saved).fingerprint)
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
+ 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
+ result.checkoutId !== checkout.checkoutId || result.baseVersion !== checkout.baseVersion || saved.fileId !== checkout.fileId || saved.version !== checkout.baseVersion ||
1029
+ 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)
813
1031
  return { state: 'unknown' };
814
- await this.dropNative(scope);
1032
+ await this.dropNative(scope, request);
815
1033
  return { state: 'verified', revision: checkout.baseVersion };
816
1034
  }
817
1035
  async discardNative(scope, request) {
@@ -849,13 +1067,17 @@ export class GhidraContexts {
849
1067
  return { state: 'unknown' };
850
1068
  const next = { ...checkout, checkoutId: Number(value.checkoutId), baseVersion: Number(value.baseVersion) };
851
1069
  const observed = await this.nativeOperation(next, 'status'), checkouts = observed.checkouts;
852
- if (observed.state !== 'ready' || observed.checkedOut !== true || observed.modified !== false || observed.fileId !== next.fileId || observed.checkoutId !== next.checkoutId || observed.baseVersion !== next.baseVersion ||
1070
+ if (observed.state !== 'ready' || observed.checkedOut !== true || observed.modified !== false || observed.recoverable !== false || observed.fileId !== next.fileId || observed.checkoutId !== next.checkoutId || observed.baseVersion !== next.baseVersion ||
853
1071
  object(observed.saved).fingerprint !== object(value.saved).fingerprint || !Array.isArray(checkouts) ||
854
1072
  checkouts.some(c => object(c).id === original.checkoutId) || !checkouts.some(c => object(c).id === next.checkoutId && object(c).version === next.baseVersion) ||
855
- typeof value.retainedKeepFile !== 'string' || value.retainedKeepFile !== '' && (value.retainedKeepFile !== basename(next.path) + '.keep' || !Array.isArray(observed.projectFiles) || !observed.projectFiles.includes(value.retainedKeepFile)))
1073
+ typeof value.retainedKeepFile !== 'string' || value.retainedKeepFile !== '' && (!this.nativeKeepName(next, value.retainedKeepFile) || !Array.isArray(observed.projectFiles) || !observed.projectFiles.includes(value.retainedKeepFile)))
856
1074
  return { state: 'unknown' };
857
1075
  return { state: 'verified', ...await this.applyNativeDiscard(scope, value) };
858
1076
  }
1077
+ nativeKeepName(checkout, name) {
1078
+ const keep = basename(checkout.path) + '.keep';
1079
+ return name === keep || name.startsWith(keep + '.') && /^[1-9][0-9]*$/.test(name.slice(keep.length + 1));
1080
+ }
859
1081
  async applyNativeDiscard(scope, value) {
860
1082
  const context = this.workspace.context(scope), checkout = context.nativeCheckout;
861
1083
  if (value.modified !== false)
@@ -874,18 +1096,14 @@ export class GhidraContexts {
874
1096
  if (this.workspace.unresolved(scope).some(intent => intent.id !== request && intent.operation !== 'ghidra.open'))
875
1097
  fail('blocked', 'This context retains an unresolved operation; reconcile its recorded outcome before continuing.');
876
1098
  let binding, unfinished = false;
877
- try {
878
- ({ binding, unfinished } = await this.lastWorker(context.id));
879
- }
880
- catch (error) {
881
- if (error.code !== 'ENOENT')
882
- throw error;
883
- }
1099
+ ({ binding, unfinished } = await this.lastWorker(context.id, { ...context, ...scope }));
1100
+ if (binding)
1101
+ await this.workerReceipt(binding, context.id, { ...context, ...scope });
884
1102
  let stopped = false;
885
1103
  if (binding) {
886
1104
  try {
887
1105
  const receipt = object(JSON.parse(await readFile(join(binding.root, 'stopped.json'), 'utf8')));
888
- stopped = receipt.pid === binding.pid && receipt.tokenSecret === binding.tokenSecret;
1106
+ stopped = receipt.pid === binding.pid && receipt.tokenSecret === binding.tokenSecret && await this.workerEnded(binding);
889
1107
  }
890
1108
  catch (error) {
891
1109
  if (error.code !== 'ENOENT')
@@ -924,6 +1142,8 @@ export class GhidraContexts {
924
1142
  if (binding.context !== context.id || binding.target !== scope.target)
925
1143
  fail('binding', 'Retired native credential belongs to another context.');
926
1144
  await releaseStoppedContextCredential(this.directory(), binding, this.c.secrets, alive, () => this.retiredWorker(binding));
1145
+ if (unfinished)
1146
+ await this.retainStartedWorker(binding);
927
1147
  }
928
1148
  let current = this.workspace.context(scope);
929
1149
  if (current.nativeCheckout?.state === 'verified') {
@@ -932,8 +1152,9 @@ export class GhidraContexts {
932
1152
  }
933
1153
  if (!current.nativeCheckout || current.nativeCheckout.state === 'dropped')
934
1154
  current = await this.createNative(scope);
935
- await this.privateCopy(current, current.workingSnapshot);
936
- return this.workspace.saveContext(scope, current.generation, { state: 'ready' });
1155
+ // A first open may replace the receipt; only that write advances the expected generation.
1156
+ const started = await this.privateCopy(current, current.workingSnapshot);
1157
+ return this.workspace.saveContext(scope, started?.generation ?? current.generation, { state: 'ready' });
937
1158
  }
938
1159
  async retireUnresponsive(scope, binding, error) {
939
1160
  const failure = error;
@@ -1123,32 +1344,25 @@ public class ${name} extends GhidraScript {
1123
1344
  fail('binding', 'Owned cross-target snapshot could not be removed.');
1124
1345
  }
1125
1346
  async reconcilePeers(record) {
1126
- const parent = join(record.binding.root, 'cross-peer');
1127
- let entries;
1128
- try {
1129
- entries = await readdir(parent, { withFileTypes: true });
1130
- }
1131
- catch (error) {
1132
- if (error.code === 'ENOENT')
1133
- return;
1134
- throw error;
1135
- }
1136
- for (const entry of entries) {
1137
- if (!entry.isDirectory() || !/^__insight_peer_[a-f0-9]{32}$/.test(entry.name))
1138
- fail('binding', 'Owned cross-target stage inventory changed.');
1139
- const folder = join(parent, entry.name);
1140
- if (await realpath(folder) !== folder)
1141
- fail('binding', 'Cross-target stage left its owned directory.');
1142
- const receipt = object(JSON.parse(await readFile(join(folder, 'receipt.json'), 'utf8'))), path = '/' + entry.name;
1143
- if (receipt.path !== path || receipt.target !== record.binding.target || receipt.context !== record.binding.context)
1144
- fail('binding', 'Cross-target cleanup receipt belongs to another context.');
1145
- if (receipt.state === 'closed')
1146
- continue;
1147
- if (receipt.state !== 'preparing')
1148
- fail('binding', 'Unknown cross-target cleanup stage.');
1149
- await this.removePeer(record, path);
1150
- await durable(join(folder, 'receipt.json'), { ...receipt, state: 'closed' });
1151
- }
1347
+ for (const stage of await peerStages(record.binding.root, record.binding)) {
1348
+ if ('reason' in stage)
1349
+ fail('binding', stage.reason);
1350
+ if (stage.receipt.state === 'preparing')
1351
+ await this.removePeer(record, stage.receipt.path);
1352
+ await this.completePeer(record, stage.receipt.path.slice(1));
1353
+ }
1354
+ }
1355
+ async completePeer(record, name) {
1356
+ const stage = await peerStage(record.binding.root, name, record.binding);
1357
+ if ('reason' in stage)
1358
+ fail('binding', stage.reason);
1359
+ if (stage.receipt.state !== 'closed')
1360
+ await durable(join(stage.folder, 'receipt.json'), { ...stage.receipt, state: 'closed' });
1361
+ const context = this.workspace.contextById(record.binding.context);
1362
+ if (this.workspace.unresolved(context).length || this.workspace.uncertainOutcome(context) || this.workspace.checkoutReferenced(context, record.binding.root))
1363
+ return;
1364
+ if (stage.input)
1365
+ await unlink(stage.input);
1152
1366
  }
1153
1367
  async withPeer(record, snapshot, action, reconcile = true) {
1154
1368
  if (reconcile)
@@ -1169,7 +1383,7 @@ public class ${name} extends GhidraScript {
1169
1383
  }
1170
1384
  finally {
1171
1385
  await this.removePeer(record, path);
1172
- await durable(join(folder, 'receipt.json'), { path, target: record.binding.target, context: record.binding.context, state: 'closed' });
1386
+ await this.completePeer(record, name);
1173
1387
  }
1174
1388
  }
1175
1389
  async pair(selected, other, snapshot, operation, parameters) {
@@ -1423,6 +1637,30 @@ public class ${name} extends GhidraScript {
1423
1637
  ...(this.c.profile.values.windbgDir ? { windbg_dir: text(this.c.profile.values.windbgDir, 4096) } : {}) });
1424
1638
  }
1425
1639
  async projectOutcome(requestId, expected) { return this.server().projectOutcome(requestId, expected); }
1640
+ async debuggerMetadata(snapshot) {
1641
+ const inspect = { inspect: (artifact, parameters) => this.inspect(artifact, parameters) };
1642
+ if (snapshot.kind !== 'native')
1643
+ return (await debuggerProgramMetadata(inspect, snapshot));
1644
+ const saved = object(JSON.parse(await readFile(await this.workspace.artifacts.verify(snapshot), 'utf8')));
1645
+ if (saved.engine !== this.nativeEngine || !['checkout', 'server'].includes(String(saved.source)))
1646
+ fail('binding', 'Saved debugger metadata view uses a different engine or source.');
1647
+ if (saved.debuggerMetadata !== undefined) {
1648
+ if (typeof saved.debuggerMetadata !== 'string' || !/^[a-f0-9]{64}$/.test(saved.debuggerMetadata))
1649
+ fail('binding', 'Saved debugger metadata witness is malformed.');
1650
+ return saved.debuggerMetadata;
1651
+ }
1652
+ if (saved.source === 'server')
1653
+ return (await debuggerProgramMetadata(inspect, snapshot));
1654
+ // Older receipts did not retain this witness. Compare actual metadata against their immutable
1655
+ // server base once, rather than interpreting mutable checkout bytes as a historical copy.
1656
+ const checkout = object(saved.checkout), context = this.workspace.contextById(text(checkout.context));
1657
+ if (context.nativeCheckout?.root !== checkout.root || context.baseSnapshot?.kind !== 'native')
1658
+ fail('binding', 'Previous debugger metadata has no immutable witness.');
1659
+ const base = object(JSON.parse(await readFile(await this.workspace.artifacts.verify(context.baseSnapshot), 'utf8')));
1660
+ if (base.source !== 'server' || base.fileId !== saved.fileId || base.version !== saved.version || base.origin !== checkout.origin || base.repository !== checkout.repository)
1661
+ fail('binding', 'Previous debugger metadata base changed.');
1662
+ return (await debuggerProgramMetadata(inspect, context.baseSnapshot));
1663
+ }
1426
1664
  async debuggerMetadataChanges(context, snapshot) {
1427
1665
  if (!context.debugger?.traces.length || !context.workingSnapshot)
1428
1666
  return context.complexChanges;
@@ -1435,13 +1673,146 @@ public class ${name} extends GhidraScript {
1435
1673
  this.workspace.saveContext(scope, context.generation, { state: 'stopped', workingSnapshot: snapshot, complexChanges, ...(debuggerState ? { debugger: { ...debuggerState, connected: false, traces: debuggerState.traces.map(trace => ({ ...trace, connected: false })) } } : {}) });
1436
1674
  await this.stopRecord(record, true, true, 'explicit_close');
1437
1675
  }
1438
- /**
1439
- * The worker that last used a context root. A start records process.json first and current.json only once its
1440
- * program is open, so a failed start leaves an older current receipt. It is superseded only by a receipt of the
1441
- * same context and root, and only after the older worker is proved gone.
1442
- */
1443
- async lastWorker(context) {
1444
- const binding = JSON.parse(await readFile(join(this.directory(), 'context', context, 'current.json'), 'utf8'));
1676
+ async workerEnded(binding) { return !alive(binding.pid) || await this.retiredWorker(binding); }
1677
+ async retainStartedWorker(binding) {
1678
+ if (!await this.workerEnded(binding))
1679
+ fail('busy', 'The interrupted start is not proved stopped; its receipt is retained.');
1680
+ const processReceipt = await readFile(join(binding.root, 'process.json'), 'utf8');
1681
+ if (stable(JSON.parse(processReceipt)) !== stable(binding))
1682
+ fail('binding', 'Interrupted start receipt changed.');
1683
+ let stopped;
1684
+ try {
1685
+ stopped = await readFile(join(binding.root, 'stopped.json'), 'utf8');
1686
+ }
1687
+ catch (error) {
1688
+ if (error.code !== 'ENOENT')
1689
+ throw error;
1690
+ }
1691
+ const directory = join(binding.root, 'worker-history');
1692
+ await mkdir(directory, { recursive: true, mode: 0o700 });
1693
+ await durable(join(directory, digest(binding) + '.json'), { schema: 1, process: processReceipt, ...(stopped ? { stopped } : {}) });
1694
+ }
1695
+ workerShape(binding, context, scope, historicalLegacy = false) {
1696
+ let endpoint;
1697
+ try {
1698
+ endpoint = new URL(binding.endpoint);
1699
+ }
1700
+ catch {
1701
+ fail('binding', 'Context process receipt changed.');
1702
+ }
1703
+ let selected = scope;
1704
+ if (!selected)
1705
+ try {
1706
+ selected = this.workspace.contextById?.(context);
1707
+ }
1708
+ catch (error) {
1709
+ if (error.code !== 'coordinator.notFound')
1710
+ throw error;
1711
+ }
1712
+ const checkout = selected?.nativeCheckout;
1713
+ const legacy = historicalLegacy && checkout && binding.program !== checkout.path &&
1714
+ (binding.program === 'program' || binding.program === '/program');
1715
+ const program = checkout ? binding.program === checkout.path || !!legacy :
1716
+ binding.program === 'program' || binding.program === '/program' || binding.program === programPath(binding.target);
1717
+ if (!Number.isSafeInteger(binding.pid) || binding.pid < 1 || binding.kind !== 'context' || binding.context !== context ||
1718
+ typeof binding.root !== 'string' || typeof binding.target !== 'string' || !binding.target || !program ||
1719
+ !['headless', 'gui'].includes(binding.mode) || typeof binding.runtimeFingerprint !== 'string' || !binding.runtimeFingerprint ||
1720
+ !/^context-[a-f0-9-]{36}$/.test(binding.tokenSecret) || endpoint.protocol !== 'http:' || endpoint.hostname !== '127.0.0.1' || !endpoint.port ||
1721
+ endpoint.username || endpoint.password || endpoint.pathname !== '/' || endpoint.search || endpoint.hash ||
1722
+ selected && (binding.target !== selected.target || binding.session !== undefined && binding.session !== selected.session))
1723
+ fail('binding', 'Context process receipt changed.');
1724
+ return legacy ? checkout : undefined;
1725
+ }
1726
+ async workerReceipt(binding, context, scope, historicalLegacy = false) {
1727
+ const legacy = this.workerShape(binding, context, scope, historicalLegacy);
1728
+ const root = await realpath(binding.root);
1729
+ if (!ownedDirectory(root, this.directory(), ['context', context, basename(root)]) || (await lstat(join(root, 'process.json'))).isSymbolicLink() ||
1730
+ stable(JSON.parse(await readFile(join(root, 'process.json'), 'utf8'))) !== stable(binding))
1731
+ fail('binding', 'Context process receipt changed.');
1732
+ if (legacy) {
1733
+ // Migration retains legacy views; none can stand in for the active native root.
1734
+ if (await exists(legacy.root) && sameDirectory(root, legacy.root))
1735
+ fail('binding', 'Context process receipt changed.');
1736
+ if (!await this.workerEnded(binding))
1737
+ fail('busy', 'Retained legacy worker is not proved stopped after migration.');
1738
+ }
1739
+ return !!legacy;
1740
+ }
1741
+ /** Discover interrupted starts independently of the ready pointer. Every other retained root must
1742
+ * be verifiably ended; no live or ambiguous start is adopted or overwritten by a replacement. */
1743
+ async lastWorker(context, scope) {
1744
+ const parent = join(this.directory(), 'context', context);
1745
+ let binding;
1746
+ try {
1747
+ binding = object(JSON.parse(await readFile(join(parent, 'current.json'), 'utf8')));
1748
+ }
1749
+ catch (error) {
1750
+ if (error.code !== 'ENOENT')
1751
+ throw error;
1752
+ }
1753
+ if (binding && this.workerShape(binding, context, scope, true)) {
1754
+ await this.workerReceipt(binding, context, scope, true);
1755
+ binding = undefined;
1756
+ }
1757
+ let entries;
1758
+ try {
1759
+ entries = await readdir(parent, { withFileTypes: true });
1760
+ }
1761
+ catch (error) {
1762
+ if (error.code === 'ENOENT' && !binding)
1763
+ return { unfinished: false };
1764
+ throw error;
1765
+ }
1766
+ const candidates = [];
1767
+ for (const entry of entries) {
1768
+ if (entry.isSymbolicLink())
1769
+ fail('binding', 'Context worker root moved; its evidence is retained.');
1770
+ if (!entry.isDirectory())
1771
+ continue;
1772
+ const root = join(parent, entry.name);
1773
+ if (binding?.root && sameDirectory(binding.root, root))
1774
+ continue;
1775
+ let started;
1776
+ try {
1777
+ started = JSON.parse(await readFile(join(root, 'process.json'), 'utf8'));
1778
+ }
1779
+ catch (error) {
1780
+ if (error.code === 'ENOENT')
1781
+ continue;
1782
+ throw error;
1783
+ }
1784
+ // Validate even ended historical roots. A foreign or unreadable receipt proves no absence.
1785
+ if (typeof started.root !== 'string' || !sameDirectory(started.root, root))
1786
+ fail('binding', 'Context process receipt changed.');
1787
+ if (await this.workerReceipt(started, context, scope, true))
1788
+ continue;
1789
+ candidates.push(started);
1790
+ }
1791
+ if (candidates.length) {
1792
+ const selected = this.workspace.contextById(context), checkout = selected.nativeCheckout;
1793
+ for (const candidate of candidates) {
1794
+ if (candidate.target !== selected.target || candidate.session !== undefined && candidate.session !== selected.session ||
1795
+ checkout && candidate.program !== checkout.path)
1796
+ fail('binding', 'Context process receipt changed.');
1797
+ if (checkout && sameDirectory(candidate.root, checkout.root))
1798
+ continue;
1799
+ if (!await this.workerEnded(candidate))
1800
+ fail('busy', 'Another retained root of this context has a worker that is not proved stopped.');
1801
+ }
1802
+ const active = checkout ? candidates.find(b => sameDirectory(b.root, checkout.root)) : candidates.length === 1 ? candidates[0] : undefined;
1803
+ if (active) {
1804
+ if (binding) {
1805
+ await this.workerReceipt(binding, context, scope);
1806
+ if (!await this.workerEnded(binding))
1807
+ fail('busy', 'The previous context worker is not proved stopped.');
1808
+ }
1809
+ return { binding: active, unfinished: true };
1810
+ }
1811
+ if (!binding && !checkout)
1812
+ fail('binding', 'Competing historical context roots have no authoritative current worker.');
1813
+ }
1814
+ if (!binding)
1815
+ return { unfinished: false };
1445
1816
  let started;
1446
1817
  try {
1447
1818
  started = JSON.parse(await readFile(join(binding.root, 'process.json'), 'utf8'));
@@ -1460,13 +1831,17 @@ public class ${name} extends GhidraScript {
1460
1831
  }
1461
1832
  async closed(scope) {
1462
1833
  const context = this.workspace.context(scope);
1463
- const { binding, unfinished } = await this.lastWorker(context.id), root = await realpath(binding.root);
1834
+ const { binding, unfinished } = await this.lastWorker(context.id, { ...context, ...scope });
1835
+ if (!binding)
1836
+ return true;
1837
+ await this.workerReceipt(binding, context.id, { ...context, ...scope });
1838
+ const root = await realpath(binding.root);
1464
1839
  if (!ownedDirectory(root, this.directory(), [binding.kind, binding.context ?? binding.target, basename(root)]) || binding.context !== context.id || binding.target !== scope.target ||
1465
1840
  stable(JSON.parse(await readFile(join(root, 'process.json'), 'utf8'))) !== stable(binding))
1466
1841
  fail('binding', 'Closed context receipt changed.');
1467
1842
  try {
1468
1843
  const stopped = object(JSON.parse(await readFile(join(root, 'stopped.json'), 'utf8')));
1469
- if (stopped.pid === binding.pid && stopped.tokenSecret === binding.tokenSecret)
1844
+ if (stopped.pid === binding.pid && stopped.tokenSecret === binding.tokenSecret && await this.workerEnded(binding))
1470
1845
  return true;
1471
1846
  // A GUI transition reuses the saved project root. Its earlier headless stop is not
1472
1847
  // evidence about this process; verify the current PID/binding independently below.
@@ -1542,15 +1917,85 @@ public class ${name} extends GhidraScript {
1542
1917
  if (saved.engine !== this.nativeEngine || saved.source !== 'checkout')
1543
1918
  return { state: 'unknown' };
1544
1919
  const { binding } = await this.nativeOwner(checkout), target = this.workspace.target(publication.target), revisionNumber = publication.expectedRevision + 1;
1545
- const value = await this.server().nativeRead(binding, { operation: 'verify', path: checkout.path, sourceSha: target.binarySha256, fileId: checkout.fileId,
1546
- version: revisionNumber, marker: 'insight native ' + publication.id, fingerprint: saved.fingerprint });
1920
+ let value;
1921
+ try {
1922
+ 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 });
1924
+ }
1925
+ catch (error) {
1926
+ const failure = error;
1927
+ // The native reader transports a missing success marker as an error. Its negative
1928
+ // completion still needs every independent refusal proof below; other failures propagate.
1929
+ if (failure.code !== 'coordinator.unknown' || failure.message !== 'Native history marker is unresolved' || failure.result?.diagnostic !== 'IllegalStateException')
1930
+ throw error;
1931
+ return this.recoverNativeRefusal(publication, checkout, saved);
1932
+ }
1547
1933
  if (value.state !== 'verified' || value.version !== revisionNumber)
1548
- return { state: 'unknown' };
1934
+ return this.recoverNativeRefusal(publication, checkout, saved);
1549
1935
  const shared = await this.serverView(publication.target, revisionNumber);
1550
1936
  if (object(shared.value).fingerprint !== saved.fingerprint)
1551
1937
  return { state: 'unknown' };
1552
1938
  return { state: 'verified', revision: revisionNumber, snapshot: shared.snapshot };
1553
1939
  }
1940
+ /** Only the completed head-race branch before checkin() has this journal shape. */
1941
+ async recoverNativeRefusal(publication, checkout, saved) {
1942
+ const unknown = { state: 'unknown' }, context = this.workspace.context(publication);
1943
+ if (context.generation !== publication.generation || context.workingSnapshot?.id !== publication.snapshot.id ||
1944
+ checkout.state !== 'active' || stable(context.nativeCheckout) !== stable(checkout) || saved.fileId !== checkout.fileId || saved.version !== checkout.baseVersion ||
1945
+ checkout.baseVersion !== publication.expectedRevision || typeof saved.fingerprint !== 'string' || !/^[a-f0-9]{64}$/.test(saved.fingerprint) ||
1946
+ !await this.neverStartedOrClosed(context))
1947
+ return unknown;
1948
+ const { owner, binding } = await this.nativeOwner(checkout), path = join(checkout.root, 'operations', publication.id + '-checkin.json');
1949
+ let journal;
1950
+ try {
1951
+ if (await realpath(path) !== resolve(path))
1952
+ return unknown;
1953
+ journal = object(JSON.parse(await readFile(path, 'utf8')));
1954
+ }
1955
+ catch (error) {
1956
+ if (error.code === 'ENOENT')
1957
+ return unknown;
1958
+ throw error;
1959
+ }
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
+ const result = object(journal.result ?? {}), before = object(journal.before ?? {});
1963
+ if (stable(journal.request) !== stable(q) || journal.marker !== undefined || journal.checkoutId !== checkout.checkoutId || journal.baseVersion !== checkout.baseVersion ||
1964
+ !Number.isSafeInteger(journal.headVersion) || Number(journal.headVersion) <= publication.expectedRevision || result.state !== 'conflict' ||
1965
+ result.conflict !== 'Shared head changed before native check-in' || result.nativeMergeInvocations !== 0 || !Array.isArray(result.nativePhases) || result.nativePhases.length !== 0 ||
1966
+ result.checkoutId !== checkout.checkoutId || result.baseVersion !== checkout.baseVersion || typeof result.modified !== 'boolean' ||
1967
+ before.fingerprint !== saved.fingerprint || before.fileId !== checkout.fileId || before.version !== checkout.baseVersion || stable(result.saved) !== stable(before))
1968
+ return unknown;
1969
+ const observed = await this.nativeOperation(checkout, 'status');
1970
+ if (observed.state !== 'ready' || observed.checkedOut !== true || observed.recoverable !== false || observed.checkinActive !== false ||
1971
+ observed.fileId !== checkout.fileId || observed.checkoutId !== checkout.checkoutId || observed.baseVersion !== checkout.baseVersion ||
1972
+ observed.modified !== result.modified || stable(observed.saved) !== stable(before))
1973
+ return unknown;
1974
+ const server = this.server(), marker = 'insight native ' + publication.id;
1975
+ const history = (value) => {
1976
+ if (value.repository !== checkout.repository || value.path !== checkout.path || value.checkinActive !== false || !Number.isSafeInteger(value.version) ||
1977
+ Number(value.version) < Number(journal.headVersion) || !Array.isArray(value.versions) || !value.versions.length ||
1978
+ !Array.isArray(value.checkouts) || !value.checkouts.includes(checkout.checkoutId))
1979
+ return false;
1980
+ const rows = value.versions.map(object), versions = rows.map(v => v.version);
1981
+ return rows.every(v => Number.isSafeInteger(v.version) && Number(v.version) > 0 && typeof v.comment === 'string' && v.comment !== marker) &&
1982
+ new Set(versions).size === versions.length && versions.includes(checkout.baseVersion) && versions.includes(journal.headVersion) &&
1983
+ Math.max(...versions) === value.version;
1984
+ };
1985
+ const prior = await server.programStatus(binding, checkout.path);
1986
+ if (!history(prior))
1987
+ return unknown;
1988
+ // A fresh reader opens the exact observed server version and checks source/file identity and all buffers.
1989
+ const shared = await this.serverView(publication.target, Number(prior.version));
1990
+ if (shared.revision !== prior.version || shared.value.fileId !== checkout.fileId || typeof shared.value.fingerprint !== 'string')
1991
+ return unknown;
1992
+ const after = await server.programStatus(binding, checkout.path);
1993
+ if (!history(after) || after.version !== prior.version || stable(after.versions) !== stable(prior.versions) ||
1994
+ !await this.neverStartedOrClosed(context) || stable((await this.nativeOperation(checkout, 'status'))) !== stable(observed) ||
1995
+ stable(JSON.parse(await readFile(path, 'utf8'))) !== stable(journal))
1996
+ return unknown;
1997
+ return { state: 'refused', revision: shared.revision, snapshot: shared.snapshot, conflict: String(result.conflict) };
1998
+ }
1554
1999
  async recoverModel(targetId) {
1555
2000
  if (this.workspace.activePublication(targetId))
1556
2001
  return false;
@@ -1639,20 +2084,15 @@ public class ${name} extends GhidraScript {
1639
2084
  if (!entry.isDirectory())
1640
2085
  continue;
1641
2086
  let binding, unfinished = false;
1642
- try {
1643
- ({ binding, unfinished } = await this.lastWorker(entry.name));
1644
- }
1645
- catch (error) {
1646
- if (error.code === 'ENOENT')
1647
- continue;
1648
- throw error;
1649
- }
2087
+ ({ binding, unfinished } = await this.lastWorker(entry.name));
2088
+ if (!binding)
2089
+ continue;
1650
2090
  if (binding.context !== entry.name || binding.kind !== 'context')
1651
2091
  fail('binding', 'Persisted context inventory has an inconsistent receipt.');
1652
2092
  let stopped = false;
1653
2093
  try {
1654
2094
  const receipt = object(JSON.parse(await readFile(join(binding.root, 'stopped.json'), 'utf8')));
1655
- stopped = receipt.pid === binding.pid && receipt.tokenSecret === binding.tokenSecret;
2095
+ stopped = receipt.pid === binding.pid && receipt.tokenSecret === binding.tokenSecret && await this.workerEnded(binding);
1656
2096
  }
1657
2097
  catch (error) {
1658
2098
  if (error.code !== 'ENOENT')