@eyeauras/insight-cli 0.6.4 → 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 (101) 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 +29 -8
  5. package/dist/src/contexts.js +455 -90
  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/native-merge-patches.js +20 -2
  12. package/dist/src/research.d.ts +10 -2
  13. package/dist/src/research.js +31 -4
  14. package/dist/src/storage-gc.js +244 -44
  15. package/dist/src/tool-runtime/run.js +24 -11
  16. package/dist/src/tool-runtime/supervisor.js +51 -9
  17. package/dist/src/workspace.d.ts +43 -1
  18. package/dist/src/workspace.js +110 -7
  19. package/package.json +1 -1
  20. package/references/agent-setup.md +11 -3
  21. package/references/debugger.md +5 -3
  22. package/references/extensions-and-sync.md +7 -6
  23. package/references/managed-runtime.md +4 -3
  24. package/references/native/InsightNativeCheckout.java +174 -15
  25. package/references/native/NATIVE-MERGE-NOTICE.txt +5 -1
  26. package/references/native-workflows.md +5 -3
  27. package/references/query-semantics.md +3 -2
  28. package/references/recovery.md +6 -0
  29. package/references/setup.md +9 -2
  30. package/skill-bundle/insight-artifacts/SKILL.md +1 -1
  31. package/skill-bundle/insight-artifacts/references/recovery.md +6 -0
  32. package/skill-bundle/insight-binary/SKILL.md +1 -1
  33. package/skill-bundle/insight-capture/SKILL.md +1 -1
  34. package/skill-bundle/insight-cli/SKILL.md +9 -7
  35. package/skill-bundle/insight-cli/references/agent-setup.md +11 -3
  36. package/skill-bundle/insight-cli/references/managed-runtime.md +4 -3
  37. package/skill-bundle/insight-cli/references/recovery.md +6 -0
  38. package/skill-bundle/insight-cli/references/setup.md +9 -2
  39. package/skill-bundle/insight-die/SKILL.md +1 -1
  40. package/skill-bundle/insight-dnspy/SKILL.md +1 -1
  41. package/skill-bundle/insight-dotnet-dump/SKILL.md +1 -1
  42. package/skill-bundle/insight-dotnet-stack/SKILL.md +1 -1
  43. package/skill-bundle/insight-dotnet-trace/SKILL.md +1 -1
  44. package/skill-bundle/insight-frida/SKILL.md +1 -1
  45. package/skill-bundle/insight-ghidra/SKILL.md +4 -3
  46. package/skill-bundle/insight-ghidra/references/debugger.md +5 -3
  47. package/skill-bundle/insight-ghidra/references/extensions-and-sync.md +7 -6
  48. package/skill-bundle/insight-ghidra/references/managed-runtime.md +4 -3
  49. package/skill-bundle/insight-ghidra/references/native-workflows.md +5 -3
  50. package/skill-bundle/insight-ghidra/references/query-semantics.md +3 -2
  51. package/skill-bundle/insight-ghidra/references/recovery.md +6 -0
  52. package/skill-bundle/insight-ghidra/references/setup.md +9 -2
  53. package/skill-bundle/insight-ilspy/SKILL.md +1 -1
  54. package/skill-bundle/insight-interop/SKILL.md +1 -1
  55. package/skill-bundle/insight-lldb/SKILL.md +1 -1
  56. package/skill-bundle/insight-llvm/SKILL.md +1 -1
  57. package/skill-bundle/insight-managed-heap/SKILL.md +1 -1
  58. package/skill-bundle/insight-managed-metadata/SKILL.md +1 -1
  59. package/skill-bundle/insight-mitmproxy/SKILL.md +1 -1
  60. package/skill-bundle/insight-overview/SKILL.md +1 -1
  61. package/skill-bundle/insight-procmon/SKILL.md +1 -1
  62. package/skill-bundle/insight-re/SKILL.md +1 -1
  63. package/skill-bundle/insight-re/references/recovery.md +6 -0
  64. package/skill-bundle/insight-sevenzip/SKILL.md +1 -1
  65. package/skill-bundle/insight-strace/SKILL.md +1 -1
  66. package/skill-bundle/insight-tshark/SKILL.md +1 -1
  67. package/skill-bundle/insight-windbg/SKILL.md +1 -1
  68. package/skill-bundle/manifest.json +1 -1
  69. package/skills/insight-artifacts/SKILL.md +1 -1
  70. package/skills/insight-artifacts/references/recovery.md +6 -0
  71. package/skills/insight-binary/SKILL.md +1 -1
  72. package/skills/insight-capture/SKILL.md +1 -1
  73. package/skills/insight-die/SKILL.md +1 -1
  74. package/skills/insight-dnspy/SKILL.md +1 -1
  75. package/skills/insight-dotnet-dump/SKILL.md +1 -1
  76. package/skills/insight-dotnet-stack/SKILL.md +1 -1
  77. package/skills/insight-dotnet-trace/SKILL.md +1 -1
  78. package/skills/insight-frida/SKILL.md +1 -1
  79. package/skills/insight-ghidra/SKILL.md +4 -3
  80. package/skills/insight-ghidra/references/debugger.md +5 -3
  81. package/skills/insight-ghidra/references/extensions-and-sync.md +7 -6
  82. package/skills/insight-ghidra/references/managed-runtime.md +4 -3
  83. package/skills/insight-ghidra/references/native-workflows.md +5 -3
  84. package/skills/insight-ghidra/references/query-semantics.md +3 -2
  85. package/skills/insight-ghidra/references/recovery.md +6 -0
  86. package/skills/insight-ghidra/references/setup.md +9 -2
  87. package/skills/insight-ilspy/SKILL.md +1 -1
  88. package/skills/insight-interop/SKILL.md +1 -1
  89. package/skills/insight-lldb/SKILL.md +1 -1
  90. package/skills/insight-llvm/SKILL.md +1 -1
  91. package/skills/insight-managed-heap/SKILL.md +1 -1
  92. package/skills/insight-managed-metadata/SKILL.md +1 -1
  93. package/skills/insight-mitmproxy/SKILL.md +1 -1
  94. package/skills/insight-overview/SKILL.md +1 -1
  95. package/skills/insight-procmon/SKILL.md +1 -1
  96. package/skills/insight-re/SKILL.md +1 -1
  97. package/skills/insight-re/references/recovery.md +6 -0
  98. package/skills/insight-sevenzip/SKILL.md +1 -1
  99. package/skills/insight-strace/SKILL.md +1 -1
  100. package/skills/insight-tshark/SKILL.md +1 -1
  101. package/skills/insight-windbg/SKILL.md +1 -1
@@ -1,5 +1,6 @@
1
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';
@@ -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. */
@@ -881,12 +1019,17 @@ export class GhidraContexts {
881
1019
  return { state: 'unknown' };
882
1020
  throw error;
883
1021
  }
884
- 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);
885
1023
  const shared = object(JSON.parse(await readFile(await this.workspace.artifacts.verify(context.baseSnapshot), 'utf8')));
886
- if (q.request !== request || q.root !== checkout.root || q.checkoutId !== checkout.checkoutId || stable(q.owner) !== stable(owner) || result.state !== 'updated' || result.modified !== false ||
887
- 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)
888
1031
  return { state: 'unknown' };
889
- await this.dropNative(scope);
1032
+ await this.dropNative(scope, request);
890
1033
  return { state: 'verified', revision: checkout.baseVersion };
891
1034
  }
892
1035
  async discardNative(scope, request) {
@@ -924,13 +1067,17 @@ export class GhidraContexts {
924
1067
  return { state: 'unknown' };
925
1068
  const next = { ...checkout, checkoutId: Number(value.checkoutId), baseVersion: Number(value.baseVersion) };
926
1069
  const observed = await this.nativeOperation(next, 'status'), checkouts = observed.checkouts;
927
- 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 ||
928
1071
  object(observed.saved).fingerprint !== object(value.saved).fingerprint || !Array.isArray(checkouts) ||
929
1072
  checkouts.some(c => object(c).id === original.checkoutId) || !checkouts.some(c => object(c).id === next.checkoutId && object(c).version === next.baseVersion) ||
930
- 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)))
931
1074
  return { state: 'unknown' };
932
1075
  return { state: 'verified', ...await this.applyNativeDiscard(scope, value) };
933
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
+ }
934
1081
  async applyNativeDiscard(scope, value) {
935
1082
  const context = this.workspace.context(scope), checkout = context.nativeCheckout;
936
1083
  if (value.modified !== false)
@@ -949,18 +1096,14 @@ export class GhidraContexts {
949
1096
  if (this.workspace.unresolved(scope).some(intent => intent.id !== request && intent.operation !== 'ghidra.open'))
950
1097
  fail('blocked', 'This context retains an unresolved operation; reconcile its recorded outcome before continuing.');
951
1098
  let binding, unfinished = false;
952
- try {
953
- ({ binding, unfinished } = await this.lastWorker(context.id));
954
- }
955
- catch (error) {
956
- if (error.code !== 'ENOENT')
957
- throw error;
958
- }
1099
+ ({ binding, unfinished } = await this.lastWorker(context.id, { ...context, ...scope }));
1100
+ if (binding)
1101
+ await this.workerReceipt(binding, context.id, { ...context, ...scope });
959
1102
  let stopped = false;
960
1103
  if (binding) {
961
1104
  try {
962
1105
  const receipt = object(JSON.parse(await readFile(join(binding.root, 'stopped.json'), 'utf8')));
963
- stopped = receipt.pid === binding.pid && receipt.tokenSecret === binding.tokenSecret;
1106
+ stopped = receipt.pid === binding.pid && receipt.tokenSecret === binding.tokenSecret && await this.workerEnded(binding);
964
1107
  }
965
1108
  catch (error) {
966
1109
  if (error.code !== 'ENOENT')
@@ -999,6 +1142,8 @@ export class GhidraContexts {
999
1142
  if (binding.context !== context.id || binding.target !== scope.target)
1000
1143
  fail('binding', 'Retired native credential belongs to another context.');
1001
1144
  await releaseStoppedContextCredential(this.directory(), binding, this.c.secrets, alive, () => this.retiredWorker(binding));
1145
+ if (unfinished)
1146
+ await this.retainStartedWorker(binding);
1002
1147
  }
1003
1148
  let current = this.workspace.context(scope);
1004
1149
  if (current.nativeCheckout?.state === 'verified') {
@@ -1007,8 +1152,9 @@ export class GhidraContexts {
1007
1152
  }
1008
1153
  if (!current.nativeCheckout || current.nativeCheckout.state === 'dropped')
1009
1154
  current = await this.createNative(scope);
1010
- await this.privateCopy(current, current.workingSnapshot);
1011
- 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' });
1012
1158
  }
1013
1159
  async retireUnresponsive(scope, binding, error) {
1014
1160
  const failure = error;
@@ -1198,32 +1344,25 @@ public class ${name} extends GhidraScript {
1198
1344
  fail('binding', 'Owned cross-target snapshot could not be removed.');
1199
1345
  }
1200
1346
  async reconcilePeers(record) {
1201
- const parent = join(record.binding.root, 'cross-peer');
1202
- let entries;
1203
- try {
1204
- entries = await readdir(parent, { withFileTypes: true });
1205
- }
1206
- catch (error) {
1207
- if (error.code === 'ENOENT')
1208
- return;
1209
- throw error;
1210
- }
1211
- for (const entry of entries) {
1212
- if (!entry.isDirectory() || !/^__insight_peer_[a-f0-9]{32}$/.test(entry.name))
1213
- fail('binding', 'Owned cross-target stage inventory changed.');
1214
- const folder = join(parent, entry.name);
1215
- if (await realpath(folder) !== folder)
1216
- fail('binding', 'Cross-target stage left its owned directory.');
1217
- const receipt = object(JSON.parse(await readFile(join(folder, 'receipt.json'), 'utf8'))), path = '/' + entry.name;
1218
- if (receipt.path !== path || receipt.target !== record.binding.target || receipt.context !== record.binding.context)
1219
- fail('binding', 'Cross-target cleanup receipt belongs to another context.');
1220
- if (receipt.state === 'closed')
1221
- continue;
1222
- if (receipt.state !== 'preparing')
1223
- fail('binding', 'Unknown cross-target cleanup stage.');
1224
- await this.removePeer(record, path);
1225
- await durable(join(folder, 'receipt.json'), { ...receipt, state: 'closed' });
1226
- }
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);
1227
1366
  }
1228
1367
  async withPeer(record, snapshot, action, reconcile = true) {
1229
1368
  if (reconcile)
@@ -1244,7 +1383,7 @@ public class ${name} extends GhidraScript {
1244
1383
  }
1245
1384
  finally {
1246
1385
  await this.removePeer(record, path);
1247
- await durable(join(folder, 'receipt.json'), { path, target: record.binding.target, context: record.binding.context, state: 'closed' });
1386
+ await this.completePeer(record, name);
1248
1387
  }
1249
1388
  }
1250
1389
  async pair(selected, other, snapshot, operation, parameters) {
@@ -1498,6 +1637,30 @@ public class ${name} extends GhidraScript {
1498
1637
  ...(this.c.profile.values.windbgDir ? { windbg_dir: text(this.c.profile.values.windbgDir, 4096) } : {}) });
1499
1638
  }
1500
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
+ }
1501
1664
  async debuggerMetadataChanges(context, snapshot) {
1502
1665
  if (!context.debugger?.traces.length || !context.workingSnapshot)
1503
1666
  return context.complexChanges;
@@ -1510,13 +1673,146 @@ public class ${name} extends GhidraScript {
1510
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 })) } } : {}) });
1511
1674
  await this.stopRecord(record, true, true, 'explicit_close');
1512
1675
  }
1513
- /**
1514
- * The worker that last used a context root. A start records process.json first and current.json only once its
1515
- * program is open, so a failed start leaves an older current receipt. It is superseded only by a receipt of the
1516
- * same context and root, and only after the older worker is proved gone.
1517
- */
1518
- async lastWorker(context) {
1519
- 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 };
1520
1816
  let started;
1521
1817
  try {
1522
1818
  started = JSON.parse(await readFile(join(binding.root, 'process.json'), 'utf8'));
@@ -1535,13 +1831,17 @@ public class ${name} extends GhidraScript {
1535
1831
  }
1536
1832
  async closed(scope) {
1537
1833
  const context = this.workspace.context(scope);
1538
- 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);
1539
1839
  if (!ownedDirectory(root, this.directory(), [binding.kind, binding.context ?? binding.target, basename(root)]) || binding.context !== context.id || binding.target !== scope.target ||
1540
1840
  stable(JSON.parse(await readFile(join(root, 'process.json'), 'utf8'))) !== stable(binding))
1541
1841
  fail('binding', 'Closed context receipt changed.');
1542
1842
  try {
1543
1843
  const stopped = object(JSON.parse(await readFile(join(root, 'stopped.json'), 'utf8')));
1544
- if (stopped.pid === binding.pid && stopped.tokenSecret === binding.tokenSecret)
1844
+ if (stopped.pid === binding.pid && stopped.tokenSecret === binding.tokenSecret && await this.workerEnded(binding))
1545
1845
  return true;
1546
1846
  // A GUI transition reuses the saved project root. Its earlier headless stop is not
1547
1847
  // evidence about this process; verify the current PID/binding independently below.
@@ -1617,15 +1917,85 @@ public class ${name} extends GhidraScript {
1617
1917
  if (saved.engine !== this.nativeEngine || saved.source !== 'checkout')
1618
1918
  return { state: 'unknown' };
1619
1919
  const { binding } = await this.nativeOwner(checkout), target = this.workspace.target(publication.target), revisionNumber = publication.expectedRevision + 1;
1620
- const value = await this.server().nativeRead(binding, { operation: 'verify', path: checkout.path, sourceSha: target.binarySha256, fileId: checkout.fileId,
1621
- 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
+ }
1622
1933
  if (value.state !== 'verified' || value.version !== revisionNumber)
1623
- return { state: 'unknown' };
1934
+ return this.recoverNativeRefusal(publication, checkout, saved);
1624
1935
  const shared = await this.serverView(publication.target, revisionNumber);
1625
1936
  if (object(shared.value).fingerprint !== saved.fingerprint)
1626
1937
  return { state: 'unknown' };
1627
1938
  return { state: 'verified', revision: revisionNumber, snapshot: shared.snapshot };
1628
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
+ }
1629
1999
  async recoverModel(targetId) {
1630
2000
  if (this.workspace.activePublication(targetId))
1631
2001
  return false;
@@ -1714,20 +2084,15 @@ public class ${name} extends GhidraScript {
1714
2084
  if (!entry.isDirectory())
1715
2085
  continue;
1716
2086
  let binding, unfinished = false;
1717
- try {
1718
- ({ binding, unfinished } = await this.lastWorker(entry.name));
1719
- }
1720
- catch (error) {
1721
- if (error.code === 'ENOENT')
1722
- continue;
1723
- throw error;
1724
- }
2087
+ ({ binding, unfinished } = await this.lastWorker(entry.name));
2088
+ if (!binding)
2089
+ continue;
1725
2090
  if (binding.context !== entry.name || binding.kind !== 'context')
1726
2091
  fail('binding', 'Persisted context inventory has an inconsistent receipt.');
1727
2092
  let stopped = false;
1728
2093
  try {
1729
2094
  const receipt = object(JSON.parse(await readFile(join(binding.root, 'stopped.json'), 'utf8')));
1730
- stopped = receipt.pid === binding.pid && receipt.tokenSecret === binding.tokenSecret;
2095
+ stopped = receipt.pid === binding.pid && receipt.tokenSecret === binding.tokenSecret && await this.workerEnded(binding);
1731
2096
  }
1732
2097
  catch (error) {
1733
2098
  if (error.code !== 'ENOENT')