@eyeauras/insight-cli 0.5.8 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (125) hide show
  1. package/.cli-package-build.json +1 -1
  2. package/SKILL.md +1 -1
  3. package/dist/src/artifacts.d.ts +1 -1
  4. package/dist/src/artifacts.js +3 -3
  5. package/dist/src/cli.js +74 -15
  6. package/dist/src/contexts.d.ts +120 -10
  7. package/dist/src/contexts.js +510 -107
  8. package/dist/src/legacy-migration.d.ts +37 -0
  9. package/dist/src/legacy-migration.js +238 -0
  10. package/dist/src/lifecycle.d.ts +16 -5
  11. package/dist/src/lifecycle.js +43 -6
  12. package/dist/src/merge.d.ts +1 -1
  13. package/dist/src/merge.js +2 -2
  14. package/dist/src/model.d.ts +5 -0
  15. package/dist/src/model.js +2 -0
  16. package/dist/src/native-inputs.js +12 -2
  17. package/dist/src/native-merge-patches.d.ts +6 -0
  18. package/dist/src/native-merge-patches.js +100 -0
  19. package/dist/src/persistent-client.d.ts +8 -2
  20. package/dist/src/persistent-client.js +30 -8
  21. package/dist/src/projects.js +5 -4
  22. package/dist/src/research.d.ts +77 -14
  23. package/dist/src/research.js +99 -123
  24. package/dist/src/sdk-files.js +3 -3
  25. package/dist/src/server.d.ts +5 -1
  26. package/dist/src/server.js +46 -6
  27. package/dist/src/storage-gc.d.ts +23 -0
  28. package/dist/src/storage-gc.js +358 -0
  29. package/dist/src/sync-policy.js +4 -2
  30. package/dist/src/version-tracking.js +2 -1
  31. package/dist/src/workspace.d.ts +35 -2
  32. package/dist/src/workspace.js +91 -7
  33. package/package.json +1 -1
  34. package/references/native/APACHE-2.0.txt +202 -0
  35. package/references/native/HeadlessProgramMergeManager.java +86 -0
  36. package/references/native/InsightGuiMain.java +1 -0
  37. package/references/native/InsightHeadlessMain.java +1 -0
  38. package/references/native/InsightInitialImport.java +1 -1
  39. package/references/native/InsightNativeCheckout.java +214 -0
  40. package/references/native/InsightNativeFingerprint.java +53 -0
  41. package/references/native/InsightNativeMigration.java +155 -0
  42. package/references/native/InsightNativeRead.java +57 -0
  43. package/references/native/InsightNativeView.java +29 -0
  44. package/references/native/InsightOfflineAuthenticator.java +20 -0
  45. package/references/native/InsightSdkFiles.java +4 -0
  46. package/references/native/InsightSnapshotFields.java +17 -11
  47. package/references/native/InsightSnapshotInspect.java +4 -2
  48. package/references/native/NATIVE-MERGE-NOTICE.txt +15 -0
  49. package/references/persistent-client.mjs +30 -8
  50. package/references/persistent.md +47 -7
  51. package/references/recovery.md +50 -12
  52. package/references/research.md +25 -22
  53. package/references/setup.md +13 -3
  54. package/skill-bundle/insight-artifacts/SKILL.md +1 -1
  55. package/skill-bundle/insight-artifacts/references/recovery.md +50 -12
  56. package/skill-bundle/insight-binary/SKILL.md +1 -1
  57. package/skill-bundle/insight-capture/SKILL.md +1 -1
  58. package/skill-bundle/insight-cli/SKILL.md +1 -1
  59. package/skill-bundle/insight-cli/references/persistent-client.mjs +30 -8
  60. package/skill-bundle/insight-cli/references/persistent.md +47 -7
  61. package/skill-bundle/insight-cli/references/recovery.md +50 -12
  62. package/skill-bundle/insight-cli/references/setup.md +13 -3
  63. package/skill-bundle/insight-die/SKILL.md +1 -1
  64. package/skill-bundle/insight-dnspy/SKILL.md +1 -1
  65. package/skill-bundle/insight-dotnet-dump/SKILL.md +1 -1
  66. package/skill-bundle/insight-dotnet-stack/SKILL.md +1 -1
  67. package/skill-bundle/insight-dotnet-trace/SKILL.md +1 -1
  68. package/skill-bundle/insight-frida/SKILL.md +1 -1
  69. package/skill-bundle/insight-ghidra/SKILL.md +8 -1
  70. package/skill-bundle/insight-ghidra/references/persistent-client.mjs +30 -8
  71. package/skill-bundle/insight-ghidra/references/persistent.md +47 -7
  72. package/skill-bundle/insight-ghidra/references/recovery.md +50 -12
  73. package/skill-bundle/insight-ghidra/references/research.md +25 -22
  74. package/skill-bundle/insight-ghidra/references/setup.md +13 -3
  75. package/skill-bundle/insight-ilspy/SKILL.md +1 -1
  76. package/skill-bundle/insight-interop/SKILL.md +1 -1
  77. package/skill-bundle/insight-lldb/SKILL.md +1 -1
  78. package/skill-bundle/insight-llvm/SKILL.md +1 -1
  79. package/skill-bundle/insight-managed-heap/SKILL.md +1 -1
  80. package/skill-bundle/insight-managed-metadata/SKILL.md +1 -1
  81. package/skill-bundle/insight-mitmproxy/SKILL.md +1 -1
  82. package/skill-bundle/insight-overview/SKILL.md +1 -1
  83. package/skill-bundle/insight-procmon/SKILL.md +1 -1
  84. package/skill-bundle/insight-re/SKILL.md +1 -1
  85. package/skill-bundle/insight-re/references/persistent-client.mjs +30 -8
  86. package/skill-bundle/insight-re/references/persistent.md +47 -7
  87. package/skill-bundle/insight-re/references/recovery.md +50 -12
  88. package/skill-bundle/insight-sevenzip/SKILL.md +1 -1
  89. package/skill-bundle/insight-strace/SKILL.md +1 -1
  90. package/skill-bundle/insight-tshark/SKILL.md +1 -1
  91. package/skill-bundle/insight-windbg/SKILL.md +1 -1
  92. package/skill-bundle/manifest.json +1 -1
  93. package/skills/insight-artifacts/SKILL.md +1 -1
  94. package/skills/insight-artifacts/references/recovery.md +50 -12
  95. package/skills/insight-binary/SKILL.md +1 -1
  96. package/skills/insight-capture/SKILL.md +1 -1
  97. package/skills/insight-die/SKILL.md +1 -1
  98. package/skills/insight-dnspy/SKILL.md +1 -1
  99. package/skills/insight-dotnet-dump/SKILL.md +1 -1
  100. package/skills/insight-dotnet-stack/SKILL.md +1 -1
  101. package/skills/insight-dotnet-trace/SKILL.md +1 -1
  102. package/skills/insight-frida/SKILL.md +1 -1
  103. package/skills/insight-ghidra/SKILL.md +8 -1
  104. package/skills/insight-ghidra/references/persistent-client.mjs +30 -8
  105. package/skills/insight-ghidra/references/persistent.md +47 -7
  106. package/skills/insight-ghidra/references/recovery.md +50 -12
  107. package/skills/insight-ghidra/references/research.md +25 -22
  108. package/skills/insight-ghidra/references/setup.md +13 -3
  109. package/skills/insight-ilspy/SKILL.md +1 -1
  110. package/skills/insight-interop/SKILL.md +1 -1
  111. package/skills/insight-lldb/SKILL.md +1 -1
  112. package/skills/insight-llvm/SKILL.md +1 -1
  113. package/skills/insight-managed-heap/SKILL.md +1 -1
  114. package/skills/insight-managed-metadata/SKILL.md +1 -1
  115. package/skills/insight-mitmproxy/SKILL.md +1 -1
  116. package/skills/insight-overview/SKILL.md +1 -1
  117. package/skills/insight-procmon/SKILL.md +1 -1
  118. package/skills/insight-re/SKILL.md +1 -1
  119. package/skills/insight-re/references/persistent-client.mjs +30 -8
  120. package/skills/insight-re/references/persistent.md +47 -7
  121. package/skills/insight-re/references/recovery.md +50 -12
  122. package/skills/insight-sevenzip/SKILL.md +1 -1
  123. package/skills/insight-strace/SKILL.md +1 -1
  124. package/skills/insight-tshark/SKILL.md +1 -1
  125. package/skills/insight-windbg/SKILL.md +1 -1
@@ -1,3 +1,5 @@
1
+ import { migrateLegacy } from './legacy-migration.js';
2
+ import { collectStorage } from './storage-gc.js';
1
3
  import { ownedDirectory, projectPathWithin, sameDirectory } from './directory-identity.js';
2
4
  import { releaseStoppedContextCredential, launchContextCredential } from './context-credential.js';
3
5
  import { recordLifecycle } from './context-diagnostics.js';
@@ -8,7 +10,7 @@ import { verifyGhidraProcess } from './ghidra-processes.js';
8
10
  import { processIdentity } from './tool-runtime/identity.js';
9
11
  import { runtimeProcesses } from './runtime-manager.js';
10
12
  import { randomUUID, randomBytes } from 'node:crypto';
11
- import { mkdir, open, readFile, readdir, rename, link, realpath, copyFile, chmod, writeFile } from 'node:fs/promises';
13
+ import { mkdir, mkdtemp, open, readFile, readdir, rename, link, realpath, copyFile, chmod, writeFile, unlink } from 'node:fs/promises';
12
14
  import { constants } from 'node:fs';
13
15
  import { join, delimiter, resolve, dirname, basename } from 'node:path';
14
16
  import { createServer } from 'node:net';
@@ -72,6 +74,7 @@ export class GhidraContexts {
72
74
  modelTasks;
73
75
  ownedServer;
74
76
  capacity;
77
+ nativeEngine = 'native-checkout-v1';
75
78
  constructor(workspace, inputs, c, running = new Map(), modelTasks = new Map(), ownedServer = new GhidraServer(workspace.directory, inputs, c), capacity = { slots: new Set() }) {
76
79
  this.workspace = workspace;
77
80
  this.inputs = inputs;
@@ -84,6 +87,79 @@ export class GhidraContexts {
84
87
  fork(c) { return new GhidraContexts(this.workspace, this.inputs, c, this.running, this.modelTasks, this.ownedServer.fork(c), this.capacity); }
85
88
  directory() { return join(this.workspace.directory, 'ghidra-native'); }
86
89
  server() { return this.ownedServer; }
90
+ async migrate(target, dryRun) {
91
+ const server = this.server(), binding = await server.ensure();
92
+ const stopped = await server.nativeMigration(binding, { operation: 'quiescence', nativeRoot: this.directory() });
93
+ if (stopped.state !== 'verified')
94
+ fail('busy', 'Retained native worker or initial-model lock is unproved; migration is refused.');
95
+ return migrateLegacy(this.workspace, {
96
+ binding: async () => ({ origin: binding.origin, repository: binding.repository, runtimeFingerprint: this.inputs.fingerprint }),
97
+ probe: (t, revision) => server.nativeRead(binding, { operation: 'migration-probe', path: programPath(t.id), sourceSha: t.binarySha256, ...(revision ? { version: revision } : {}) }),
98
+ write: q => server.nativeMigration(binding, q),
99
+ snapshots: async (paths) => { const value = await server.nativeMigration(binding, { operation: 'snapshots', snapshots: paths }); return Array.isArray(value.items) ? value.items.map(object) : []; },
100
+ verify: async (t, owner, candidate) => {
101
+ const result = await server.nativeRead(binding, { operation: 'verify', path: programPath(t.id), sourceSha: t.binarySha256, fileId: owner.fileId, version: Number(owner.version) + 1, marker: owner.marker, fingerprint: candidate.fingerprint });
102
+ if (result.state !== 'verified' || result.version !== Number(owner.version) + 1)
103
+ fail('unknown', 'Migration independent exact-version readback is unproved; check-in will not be retried.');
104
+ const exact = await server.nativeRead(binding, { operation: 'migration-probe', path: programPath(t.id), sourceSha: t.binarySha256, version: Number(owner.version) + 1, fileId: owner.fileId });
105
+ if (exact.programIdentity !== owner.programIdentity)
106
+ fail('binding', 'Migrated program bytes or load identity differ.');
107
+ const original = await server.nativeRead(binding, { operation: 'migration-probe', path: programPath(t.id), sourceSha: t.binarySha256, version: owner.version, fileId: owner.fileId });
108
+ if (original.engine !== '' || original.fingerprint !== owner.fingerprint || original.programIdentity !== owner.programIdentity)
109
+ fail('binding', 'Pre-migration repository version changed.');
110
+ },
111
+ adopt: async (t) => { const view = await this.serverView(t), model = this.workspace.model(t); if (model.state === 'ready')
112
+ this.observeNativeShared(t, view);
113
+ else
114
+ this.workspace.establishModel(t, view.revision, view.snapshot); },
115
+ knownCheckouts: async (t, rows) => {
116
+ for (const row of rows) {
117
+ const id = object(row).id;
118
+ let checkout;
119
+ for (let offset = 0;; offset += 100) {
120
+ const sessions = this.workspace.sessions(100, offset);
121
+ for (const s of sessions)
122
+ for (let at = 0;; at += 100) {
123
+ const contexts = this.workspace.contexts(s.id, 100, at);
124
+ for (const c of contexts)
125
+ if (c.target === t.id && c.nativeCheckout?.state === 'active' && c.nativeCheckout.checkoutId === id)
126
+ checkout = c.nativeCheckout;
127
+ if (contexts.length < 100)
128
+ break;
129
+ }
130
+ if (sessions.length < 100)
131
+ break;
132
+ }
133
+ if (!checkout)
134
+ return false;
135
+ const status = await this.nativeOperation(checkout, 'status');
136
+ if (status.state !== 'ready' || status.checkedOut !== true || status.checkoutId !== id || status.fileId !== checkout.fileId)
137
+ return false;
138
+ }
139
+ return true;
140
+ },
141
+ recoverOpen: async (c) => {
142
+ const parent = join(this.directory(), 'context', c.id), pending = join(parent, 'checkout.json');
143
+ let intent;
144
+ try {
145
+ intent = object(JSON.parse(await readFile(pending, 'utf8')));
146
+ }
147
+ catch (e) {
148
+ if (e.code === 'ENOENT')
149
+ return;
150
+ throw e;
151
+ }
152
+ const root = await realpath(text(intent.root)), owner = object(intent.owner);
153
+ if (!ownedDirectory(root, this.directory(), ['context', c.id, basename(root)]) || owner.context !== c.id || owner.target !== c.target || owner.sourceSha !== this.workspace.target(c.target).binarySha256 || owner.origin !== binding.origin || owner.repository !== binding.repository || owner.path !== programPath(c.target) || stable(JSON.parse(await readFile(join(root, 'native-owner.json'), 'utf8'))) !== stable(owner))
154
+ fail('binding', 'Failed open creation intent changed; its project is retained.');
155
+ const retained = join(this.workspace.directory, 'legacy-migrations', c.target, 'recovered-opens', c.id);
156
+ await mkdir(retained, { recursive: true, mode: 0o700 });
157
+ await durable(join(retained, 'recovery.json'), { schema: 1, context: c.id, intent, requests: this.workspace.unresolved(c), reason: 'No acknowledged private work; all server checkouts independently accounted. Failed creation project retained; next open uses a fresh native checkout in the same session/target.' });
158
+ await rename(pending, join(retained, 'checkout-' + randomUUID() + '.json'));
159
+ },
160
+ closed: c => this.neverStartedOrClosed(c), convert: async (c) => { this.workspace.resetMigratedContext(c); }
161
+ }, target, dryRun);
162
+ }
87
163
  async administration(operation, parameters) {
88
164
  if (operation === 'stop') {
89
165
  if (this.c.profile.values.server)
@@ -96,9 +172,10 @@ export class GhidraContexts {
96
172
  }
97
173
  async sdkFile(operation, parameters) { return this.server().sdkFile(operation, parameters); }
98
174
  async prepareRoot(kind, target, context) {
99
- const root = join(this.directory(), kind, context ?? target, randomUUID());
100
- await mkdir(root, { recursive: true, mode: 0o700 });
101
- return root;
175
+ const parent = join(this.directory(), kind, context ?? target);
176
+ await mkdir(parent, { recursive: true, mode: 0o700 });
177
+ // Atomic short suffix: Windows CreateProcess rejects long cwd even when filesystem APIs accept it.
178
+ return mkdtemp(join(parent, 'w-'));
102
179
  }
103
180
  async launch(root, target, kind, program, mode, context, credentials = {}) {
104
181
  if ((await nativeInputs(this.c.profile.values, this.workspace.directory, this.c)).fingerprint !== this.inputs.fingerprint)
@@ -135,6 +212,7 @@ export class GhidraContexts {
135
212
  child = await launchContextCredential(this.c.secrets, tokenSecret, token, onSpawn => launchProcess(this.c.appArguments.AppDataDirectory, { tool: 'ghidra', role: mode === 'gui' ? 'gui' : kind, installation: this.inputs.fingerprint, target: target.id, session: context ? this.workspace.contextById(context).session : undefined, metadata: { contextRoot: root } }, this.inputs.java, ['-Xmx768m', '-Djava.awt.headless=' + String(mode !== 'gui'), '-Dghidra.home=' + this.inputs.ghidraHome,
136
213
  ...nativeJvmDirectories(root), ...nativeExtensionArguments(this.inputs), '-cp', classes + delimiter + this.inputs.classpath, main, ...args], { cwd: root, detached: true, windowsHide: true, stdio: ['ignore', log.fd, log.fd],
137
214
  env: { PATH: this.c.environment.PATH ?? process.env.PATH, HOME: root, TMPDIR: root, XDG_RUNTIME_DIR: root,
215
+ ...(process.platform === 'win32' ? { SystemRoot: process.env.SystemRoot, WINDIR: process.env.WINDIR, ComSpec: process.env.ComSpec, TEMP: root, TMP: root, USERPROFILE: root, LOCALAPPDATA: root, APPDATA: root } : {}),
138
216
  INSIGHT_TOOL_APPDATA: this.c.appArguments.AppDataDirectory, GHIDRA_MCP_AUTH_TOKEN: token, GHIDRA_MCP_FILE_ROOT: root, GHIDRA_MCP_SHARED_PROJECT_DIR: root,
139
217
  GHIDRA_MCP_ALLOW_SCRIPTS: '1', ...debuggerEnvironment, ...credentials } }, { signal: this.c.signal, onSpawn }), async (spawned) => {
140
218
  if (!spawned.pid)
@@ -296,16 +374,80 @@ export class GhidraContexts {
296
374
  }
297
375
  }
298
376
  async capture(record) {
377
+ const context = record.binding.kind === 'context' ? this.workspace.contextById(record.binding.context) : undefined;
378
+ // Never write a detached worker's project: its engine alone can capture that state.
379
+ if (context && (!context.nativeCheckout || context.nativeCheckout.root !== record.binding.root))
380
+ fail('migration', 'This worker belongs to legacy detached work. Save and close it with the release that started it, then run ghidra migrate.');
299
381
  const result = object(await record.http.call('/save_program', { program: record.binding.program }));
300
382
  if (result.success !== true)
301
383
  fail('save', 'Private program save was not acknowledged.');
384
+ if (context?.nativeCheckout) {
385
+ const saved = object(await this.nativeView(record, { operation: 'fingerprint' }));
386
+ return this.nativeReceipt(context.nativeCheckout, saved);
387
+ }
302
388
  const output = join(record.binding.root, 'exports');
303
389
  await mkdir(output, { recursive: true, mode: 0o700 });
304
390
  const name = 'saved-' + randomUUID() + '.gzf';
305
391
  const exported = object(await record.http.call('/export_program', { program_name: record.binding.program, output_dir: output, output_name: name }));
306
392
  if (exported.success !== true)
307
393
  fail('save', 'Saved private snapshot export was not acknowledged.');
308
- return this.workspace.captureSnapshot(join(output, name));
394
+ return this.captureExport(join(output, name));
395
+ }
396
+ /** The captured artifact is the only retained copy of an export stage. */
397
+ async captureExport(path) {
398
+ const artifact = await this.workspace.captureSnapshot(path);
399
+ await unlink(path).catch(() => { });
400
+ return artifact;
401
+ }
402
+ async nativeView(record, parameters) {
403
+ const name = 'InsightNativeView_' + randomUUID().replaceAll('-', ''), source = await readFile(new URL('../../references/native/InsightNativeView.java', import.meta.url), 'utf8');
404
+ const response = object(await record.http.call('/run_script_inline', { program: record.binding.program,
405
+ code: source.replace('public class InsightNativeView ', 'public class ' + name + ' '), args: Buffer.from(JSON.stringify(parameters), 'utf8').toString('base64') }));
406
+ if (response.success !== true || typeof response.console_output !== 'string')
407
+ fail('partial', 'Saved native view inspection did not complete.');
408
+ const matches = [...response.console_output.matchAll(/^INSIGHT_NATIVE:(.+)$/gm)];
409
+ if (matches.length !== 1)
410
+ fail('partial', 'Native saved-view result is missing.');
411
+ return object(JSON.parse(matches[0][1])).value;
412
+ }
413
+ async nativeReceipt(checkout, saved) {
414
+ if (saved.fileId !== checkout.fileId || saved.version !== checkout.baseVersion || typeof saved.fingerprint !== 'string' || !/^[a-f0-9]{64}$/.test(saved.fingerprint))
415
+ fail('binding', 'Saved native view differs from its checkout identity/base.');
416
+ const path = join(checkout.root, 'saved-view.json');
417
+ await durable(path, { schema: 1, engine: this.nativeEngine, source: 'checkout', checkout, ...saved });
418
+ return this.workspace.captureNative(path);
419
+ }
420
+ async serverView(targetId, versionNumber) {
421
+ const server = this.server(), binding = await server.ensure(), target = this.workspace.target(targetId);
422
+ const value = await server.nativeRead(binding, { operation: 'latest', path: programPath(targetId), sourceSha: target.binarySha256, ...(versionNumber ? { version: versionNumber } : {}) });
423
+ if (value.state !== 'verified' || typeof value.fileId !== 'string' || typeof value.fingerprint !== 'string')
424
+ fail('binding', 'Native shared model is unverified or requires an explicit legacy migration.');
425
+ const revision = version(value.version), root = join(this.directory(), 'shared-views', targetId);
426
+ await mkdir(root, { recursive: true, mode: 0o700 });
427
+ const path = join(root, 'current.json');
428
+ await durable(path, { schema: 1, engine: this.nativeEngine, source: 'server', target: targetId, origin: binding.origin, repository: binding.repository, path: programPath(targetId),
429
+ sourceSha: target.binarySha256, runtimeFingerprint: this.inputs.fingerprint, version: revision, fileId: value.fileId, fingerprint: value.fingerprint });
430
+ return { revision, snapshot: await this.workspace.captureNative(path), value };
431
+ }
432
+ observeNativeShared(target, shared) {
433
+ const model = this.workspace.model(target);
434
+ // A context's exact immutable base can predate another context's observation.
435
+ if (model.state === 'ready' && shared.revision >= (model.sharedRevision ?? 1))
436
+ this.workspace.observeShared(target, shared.revision, shared.snapshot);
437
+ }
438
+ async nativeOwner(checkout) {
439
+ const root = await realpath(checkout.root), context = this.workspace.contextById(checkout.context);
440
+ if (!ownedDirectory(root, this.directory(), ['context', context.id, basename(root)]))
441
+ fail('binding', 'Native checkout moved.');
442
+ // The creating runtime is provenance. Ghidra itself refuses a database that needs an upgrade.
443
+ const owner = object(JSON.parse(await readFile(join(root, 'native-owner.json'), 'utf8'))), binding = await this.server().ensure();
444
+ if (context.nativeCheckout?.root !== checkout.root || owner.context !== context.id || owner.target !== context.target || owner.origin !== binding.origin || owner.repository !== binding.repository || owner.path !== programPath(context.target) || owner.sourceSha !== this.workspace.target(context.target).binarySha256 || owner.runtimeFingerprint !== checkout.runtimeFingerprint)
445
+ fail('binding', 'Native checkout owner/server binding changed.');
446
+ return { root, owner, binding };
447
+ }
448
+ async nativeOperation(checkout, operation, parameters = {}) {
449
+ const { root, owner, binding } = await this.nativeOwner(checkout);
450
+ return this.server().nativeCheckout(binding, { root, owner, operation, fileId: checkout.fileId, checkoutId: checkout.checkoutId, ...parameters });
309
451
  }
310
452
  async shared(target, binding) {
311
453
  const root = await this.prepareRoot('shared', target.id);
@@ -429,19 +571,24 @@ export class GhidraContexts {
429
571
  this.capacity.slots.add(context.id);
430
572
  let record;
431
573
  try {
432
- const target = this.workspace.target(context.target), root = await this.prepareRoot('context', target.id, context.id);
433
- const file = join(root, 'saved.gzf');
434
- await link(await this.workspace.artifacts.verify(snapshot), file);
435
- record = await this.launch(root, target, 'context', '/program', 'headless', context.id);
436
- const project = object(await record.http.call('/create_project', { parentDir: root, name: 'view' }));
437
- if (project.success !== true)
438
- fail('launch', 'Private context project creation was not acknowledged.');
439
- const imported = object(await record.http.call('/import_program', { gzf_path: file, target_folder: '/', target_name: 'program', overwrite: false }));
440
- if (imported.success !== true)
441
- fail('launch', 'Private context snapshot import was not acknowledged.');
574
+ const target = this.workspace.target(context.target), checkout = context.nativeCheckout;
575
+ if (!checkout || checkout.state !== 'active')
576
+ fail('binding', 'An active native checkout is required.');
577
+ await this.nativeOwner(checkout);
578
+ const root = checkout.root;
579
+ // Another runtime first proves, without an upgrade, that it can read the saved database.
580
+ if (checkout.runtimeFingerprint !== this.inputs.fingerprint) {
581
+ const observed = await this.nativeOperation(checkout, 'status');
582
+ if (observed.state !== 'ready' || observed.checkoutId !== checkout.checkoutId)
583
+ fail('binding', 'This runtime cannot open the native checkout without changing it; the project is retained.');
584
+ }
585
+ record = await this.launch(root, target, 'context', checkout.path, 'headless', context.id);
586
+ const project = object(await record.http.call('/open_project', { path: join(root, 'view.gpr') }));
587
+ if (project.success === false)
588
+ fail('launch', 'Native working project could not be reopened.');
442
589
  const opened = object(await record.http.call('/open_program', { path: record.binding.program }));
443
590
  if (opened.path !== record.binding.program || opened.read_only === true)
444
- fail('binding', 'Private context did not open its writable saved view.');
591
+ fail('binding', 'Native checkout did not open its saved writable program.');
445
592
  await this.verified(record.binding, target);
446
593
  record.binding.baseRevision = context.baseRevision ?? this.workspace.model(context.target).sharedRevision;
447
594
  record.binding.viewEpoch = context.viewEpoch ?? 0;
@@ -459,6 +606,250 @@ export class GhidraContexts {
459
606
  throw error;
460
607
  }
461
608
  }
609
+ async createNative(scope) {
610
+ const context = this.workspace.context(scope), target = this.workspace.target(scope.target), server = this.server(), binding = await server.ensure();
611
+ const parent = join(this.directory(), 'context', context.id);
612
+ await mkdir(parent, { recursive: true, mode: 0o700 });
613
+ const pending = join(parent, 'checkout.json');
614
+ let intent;
615
+ try {
616
+ intent = object(JSON.parse(await readFile(pending, 'utf8')));
617
+ }
618
+ catch (error) {
619
+ if (error.code !== 'ENOENT')
620
+ throw error;
621
+ }
622
+ if (!intent || intent.root === context.nativeCheckout?.root) {
623
+ const root = await this.prepareRoot('context', target.id, context.id), owner = { schema: 1, protocol: this.nativeEngine, context: context.id, target: target.id,
624
+ sourceSha: target.binarySha256, origin: binding.origin, repository: binding.repository, path: programPath(target.id), runtimeFingerprint: this.inputs.fingerprint };
625
+ await durable(join(root, 'native-owner.json'), owner);
626
+ intent = { root, owner };
627
+ await durable(pending, intent);
628
+ }
629
+ const root = await realpath(text(intent.root, 4096)), owner = object(intent.owner);
630
+ if (!ownedDirectory(root, this.directory(), ['context', context.id, basename(root)]) || owner.context !== context.id || owner.target !== target.id || typeof owner.runtimeFingerprint !== 'string' ||
631
+ owner.origin !== binding.origin || owner.repository !== binding.repository || owner.path !== programPath(target.id) || owner.sourceSha !== target.binarySha256)
632
+ fail('binding', 'Retained checkout creation binding changed.');
633
+ const value = await server.nativeCheckout(binding, { root, owner, operation: 'create' });
634
+ if (value.state !== 'ready' || value.checkedOut !== true || !Number.isSafeInteger(value.checkoutId) || typeof value.fileId !== 'string')
635
+ fail('unknown', 'Native checkout creation remains unproved; its original project is retained.');
636
+ const checkout = { schema: 1, context: context.id, root, fileId: value.fileId, checkoutId: Number(value.checkoutId), baseVersion: version(value.baseVersion),
637
+ origin: binding.origin, repository: binding.repository, path: programPath(target.id), runtimeFingerprint: owner.runtimeFingerprint, state: 'active' };
638
+ const shared = await this.serverView(scope.target, checkout.baseVersion), snapshot = await this.nativeReceipt(checkout, object(value.saved));
639
+ this.observeNativeShared(scope.target, shared);
640
+ return this.workspace.saveContext(scope, context.generation, { state: 'stopped', nativeCheckout: checkout, baseRevision: checkout.baseVersion, baseSnapshot: shared.snapshot, workingSnapshot: snapshot });
641
+ }
642
+ async updateNative(scope, request) {
643
+ await this.open(scope, request);
644
+ let context = this.workspace.context(scope);
645
+ const record = await this.selected(scope);
646
+ await this.capture(record);
647
+ await this.stopRecord(record, true, true, 'view_replaced');
648
+ const checkout = context.nativeCheckout;
649
+ const value = await this.nativeOperation(checkout, 'update', { request });
650
+ return this.applyNativeUpdate(scope, request, value, checkout.baseVersion);
651
+ }
652
+ async applyNativeUpdate(scope, request, value, previousBase) {
653
+ let context = this.workspace.context(scope);
654
+ const checkout = context.nativeCheckout;
655
+ if (value.state === 'unknown')
656
+ fail('unknown', 'Native Update outcome is unknown; retain this project and its operation journal.');
657
+ if (value.state === 'conflict') {
658
+ const message = text(value.conflict, 16000);
659
+ this.workspace.saveContext(scope, context.generation, { state: 'stopped', nativeCheckout: { ...checkout, conflict: { request, message } } });
660
+ return { state: 'conflict', conflict: message, revision: checkout.baseVersion };
661
+ }
662
+ if (value.state !== 'updated' || value.checkoutId !== checkout.checkoutId)
663
+ fail('binding', 'Native Update did not preserve checkout identity.');
664
+ const next = { ...checkout, baseVersion: version(value.baseVersion) };
665
+ delete next.conflict;
666
+ const snapshot = await this.nativeReceipt(next, object(value.saved));
667
+ const shared = await this.serverView(scope.target, next.baseVersion);
668
+ this.observeNativeShared(scope.target, shared);
669
+ 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,
671
+ receivedChanges: Number(next.baseVersion !== previousBase), nativeMergeInvocations: Number(value.nativeMergeInvocations ?? 0) };
672
+ }
673
+ async recoverUpdate(scope, request) {
674
+ const context = this.workspace.context(scope), checkout = context.nativeCheckout;
675
+ if (!checkout || checkout.state !== 'active' || !await this.closed(scope))
676
+ return { state: 'unknown' };
677
+ let journal;
678
+ try {
679
+ journal = object(JSON.parse(await readFile(join(checkout.root, 'operations', request + '-update.json'), 'utf8')));
680
+ }
681
+ catch (error) {
682
+ if (error.code === 'ENOENT')
683
+ return { state: 'unknown' };
684
+ throw error;
685
+ }
686
+ const q = object(journal.request), value = journal.result === undefined ? undefined : object(journal.result), { owner } = await this.nativeOwner(checkout);
687
+ if (q.request !== request || q.root !== checkout.root || q.fileId !== checkout.fileId || q.checkoutId !== checkout.checkoutId || stable(q.owner) !== stable(owner) || !value)
688
+ return { state: 'unknown' };
689
+ const observed = await this.nativeOperation(checkout, 'status');
690
+ if (observed.state !== 'ready' || observed.checkoutId !== checkout.checkoutId || observed.baseVersion !== value.baseVersion || object(observed.saved).fingerprint !== object(value.saved).fingerprint)
691
+ return { state: 'unknown' };
692
+ return this.applyNativeUpdate(scope, request, value, version(journal.baseVersion));
693
+ }
694
+ async publishNative(publication) {
695
+ const context = this.workspace.context(publication), checkout = context.nativeCheckout;
696
+ if (!checkout || checkout.state !== 'active')
697
+ fail('binding', 'Native publication has no active checkout.');
698
+ const saved = object(JSON.parse(await readFile(await this.workspace.artifacts.verify(publication.snapshot), 'utf8')));
699
+ if (saved.engine !== this.nativeEngine || saved.source !== 'checkout' || object(saved.checkout).root !== checkout.root || saved.fileId !== checkout.fileId)
700
+ fail('binding', 'Publication differs from its prepared native project.');
701
+ const value = await this.nativeOperation(checkout, 'checkin', { request: publication.id, fingerprint: text(saved.fingerprint), expectedVersion: publication.expectedRevision });
702
+ if (value.state === 'conflict')
703
+ return { state: 'conflict', applied: 0, conflict: String(value.conflict) };
704
+ if (value.state !== 'checked_in' || value.baseVersion !== publication.expectedRevision + 1)
705
+ fail('unknown', 'Native check-in outcome requires independent reconciliation; the project is retained.');
706
+ const verified = await this.recover(publication);
707
+ if (verified.state !== 'verified')
708
+ fail('unknown', 'Native history and independent exact-buffer readback do not yet establish publication.');
709
+ return { state: 'published', revision: verified.revision, snapshot: verified.snapshot };
710
+ }
711
+ async dropNative(scope) {
712
+ const context = this.workspace.context(scope), checkout = context.nativeCheckout;
713
+ if (!checkout || checkout.state === 'dropped')
714
+ return;
715
+ if (checkout.state !== 'verified')
716
+ fail('blocked', 'Only a verified native publication can dispose its project.');
717
+ const shared = object(JSON.parse(await readFile(await this.workspace.artifacts.verify(context.baseSnapshot), 'utf8')));
718
+ if (shared.source !== 'server' || shared.version !== checkout.baseVersion || shared.fileId !== checkout.fileId)
719
+ 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.');
724
+ const dropped = await this.nativeOperation(checkout, 'drop', parameters);
725
+ if (dropped.state !== 'dropped')
726
+ fail('unknown', 'Publication is verified but project deletion remains unproved.');
727
+ this.workspace.saveContext(scope, context.generation, { nativeCheckout: { ...checkout, state: 'dropped' }, state: 'stopped' });
728
+ }
729
+ async finishEmptyNative(scope) {
730
+ const context = this.workspace.context(scope);
731
+ if (!context.nativeCheckout)
732
+ fail('binding', 'Native checkout is absent.');
733
+ if (context.nativeCheckout.state === 'verified' || context.nativeCheckout.state === 'dropped') {
734
+ await this.dropNative(scope);
735
+ return;
736
+ }
737
+ // No new server version; the independent base view must equal all saved local buffers.
738
+ 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)
740
+ 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);
743
+ }
744
+ /** Close and GC drop a working copy only when Ghidra itself reports no private change. */
745
+ async releaseUnchanged(scope) {
746
+ const context = this.workspace.context(scope), checkout = context.nativeCheckout;
747
+ if (!checkout || checkout.state === 'dropped' || checkout.conflict || context.scalars.length || context.complexChanges.length || context.debugger?.traces.length || context.debugger?.connected ||
748
+ this.workspace.activePublication(scope.target)?.session === scope.session || !this.workspace.unchangedNative(context) || this.workspace.uncertainOutcome(scope) || this.workspace.checkoutReferenced(context) || !await this.closed(scope))
749
+ return false;
750
+ if (checkout.state === 'verified') {
751
+ await this.dropNative(scope);
752
+ return true;
753
+ }
754
+ 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 ||
757
+ !Array.isArray(observed.projectFiles) || observed.projectFiles.some(name => name !== basename(checkout.path)))
758
+ return false;
759
+ await this.finishEmptyNative(scope);
760
+ return true;
761
+ }
762
+ /** A missing current receipt means no worker was ever started; any other missing receipt is unproved. */
763
+ 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
+ }
772
+ return this.closed(c);
773
+ }
774
+ async collect(dryRun) {
775
+ return collectStorage(this.workspace, { closed: c => this.neverStartedOrClosed(c), release: c => this.releaseUnchanged(c) }, dryRun, message => this.c.progress(message));
776
+ }
777
+ async recoverEmptyNative(scope, request) {
778
+ const context = this.workspace.context(scope), checkout = context.nativeCheckout;
779
+ if (!checkout || !['verified', 'dropped'].includes(checkout.state))
780
+ return { state: 'unknown' };
781
+ let journal;
782
+ try {
783
+ journal = object(JSON.parse(await readFile(join(checkout.root, 'operations', request + '-update.json'), 'utf8')));
784
+ }
785
+ catch (error) {
786
+ if (error.code === 'ENOENT')
787
+ return { state: 'unknown' };
788
+ throw error;
789
+ }
790
+ const q = object(journal.request), result = object(journal.result ?? {}), { owner } = await this.nativeOwner(checkout);
791
+ const shared = object(JSON.parse(await readFile(await this.workspace.artifacts.verify(context.baseSnapshot), 'utf8')));
792
+ if (q.request !== request || q.root !== checkout.root || q.checkoutId !== checkout.checkoutId || stable(q.owner) !== stable(owner) || result.state !== 'updated' || result.modified !== false ||
793
+ result.baseVersion !== checkout.baseVersion || shared.source !== 'server' || shared.fileId !== checkout.fileId || shared.fingerprint !== object(result.saved).fingerprint)
794
+ return { state: 'unknown' };
795
+ await this.dropNative(scope);
796
+ return { state: 'verified', revision: checkout.baseVersion };
797
+ }
798
+ async discardNative(scope, request) {
799
+ const context = this.workspace.context(scope), checkout = context.nativeCheckout;
800
+ if (!checkout || checkout.state !== 'active' || !await this.closed(scope))
801
+ fail('busy', 'Native discard requires its saved, stopped working copy.');
802
+ const value = await this.nativeOperation(checkout, 'discard', { request });
803
+ if (value.state !== 'discarded' || !Number.isSafeInteger(value.checkoutId) || value.checkoutId === checkout.checkoutId)
804
+ fail('unknown', 'Native discard is unproved; its project and journal remain retained.');
805
+ return this.applyNativeDiscard(scope, value);
806
+ }
807
+ async recoverDiscardNative(scope, request, original) {
808
+ const context = this.workspace.context(scope), checkout = context.nativeCheckout;
809
+ if (!original || !checkout || checkout.state !== 'active' || checkout.root !== original.root || !await this.closed(scope))
810
+ return { state: 'unknown' };
811
+ const binding = (c) => { const { checkoutId, baseVersion, conflict, ...rest } = c; return rest; };
812
+ if (stable(binding(checkout)) !== stable(binding(original)))
813
+ return { state: 'unknown' };
814
+ let journal;
815
+ try {
816
+ journal = object(JSON.parse(await readFile(join(original.root, 'operations', request + '-discard.json'), 'utf8')));
817
+ }
818
+ catch (error) {
819
+ if (error.code === 'ENOENT')
820
+ return { state: 'unknown' };
821
+ throw error;
822
+ }
823
+ const q = object(journal.request), value = object(journal.result ?? {}), { owner } = await this.nativeOwner(original);
824
+ if (q.operation !== 'discard' || q.request !== request || q.root !== original.root || q.fileId !== original.fileId || q.checkoutId !== original.checkoutId || stable(q.owner) !== stable(owner) ||
825
+ value.state !== 'discarded' || !Number.isSafeInteger(value.checkoutId) || Number(value.checkoutId) < 0 || value.checkoutId === original.checkoutId || value.modified !== false ||
826
+ !Number.isSafeInteger(value.baseVersion) || Number(value.baseVersion) < original.baseVersion)
827
+ return { state: 'unknown' };
828
+ if (checkout.checkoutId !== original.checkoutId && checkout.checkoutId !== value.checkoutId ||
829
+ checkout.baseVersion !== (checkout.checkoutId === original.checkoutId ? original.baseVersion : value.baseVersion))
830
+ return { state: 'unknown' };
831
+ const next = { ...checkout, checkoutId: Number(value.checkoutId), baseVersion: Number(value.baseVersion) };
832
+ const observed = await this.nativeOperation(next, 'status'), checkouts = observed.checkouts;
833
+ if (observed.state !== 'ready' || observed.checkedOut !== true || observed.modified !== false || observed.fileId !== next.fileId || observed.checkoutId !== next.checkoutId || observed.baseVersion !== next.baseVersion ||
834
+ object(observed.saved).fingerprint !== object(value.saved).fingerprint || !Array.isArray(checkouts) ||
835
+ checkouts.some(c => object(c).id === original.checkoutId) || !checkouts.some(c => object(c).id === next.checkoutId && object(c).version === next.baseVersion) ||
836
+ typeof value.retainedKeepFile !== 'string' || value.retainedKeepFile !== '' && (value.retainedKeepFile !== basename(next.path) + '.keep' || !Array.isArray(observed.projectFiles) || !observed.projectFiles.includes(value.retainedKeepFile)))
837
+ return { state: 'unknown' };
838
+ return { state: 'verified', ...await this.applyNativeDiscard(scope, value) };
839
+ }
840
+ async applyNativeDiscard(scope, value) {
841
+ const context = this.workspace.context(scope), checkout = context.nativeCheckout;
842
+ if (value.modified !== false)
843
+ fail('unknown', 'Native discard did not establish an unchanged checkout.');
844
+ const next = { ...checkout, checkoutId: Number(value.checkoutId), baseVersion: version(value.baseVersion) };
845
+ delete next.conflict;
846
+ const shared = await this.serverView(scope.target, next.baseVersion), snapshot = await this.nativeReceipt(next, object(value.saved));
847
+ if (shared.value.fingerprint !== object(value.saved).fingerprint)
848
+ fail('unknown', 'Discarded checkout differs from independent server readback.');
849
+ this.observeNativeShared(scope.target, shared);
850
+ this.workspace.saveContext(scope, context.generation, { nativeCheckout: next, state: 'stopped', baseRevision: next.baseVersion, baseSnapshot: shared.snapshot, workingSnapshot: snapshot, scalars: [], complexChanges: [], viewEpoch: (context.viewEpoch ?? 0) + 1 });
851
+ return { baseRevision: next.baseVersion, retainedKeepFile: String(value.retainedKeepFile) };
852
+ }
462
853
  async open(scope, request) {
463
854
  const context = this.workspace.context(scope), target = this.workspace.target(scope.target);
464
855
  if (this.workspace.unresolved(scope).some(intent => intent.id !== request && intent.operation !== 'ghidra.open'))
@@ -482,6 +873,8 @@ export class GhidraContexts {
482
873
  throw error;
483
874
  }
484
875
  }
876
+ if (context.workingSnapshot && !context.nativeCheckout)
877
+ fail('migration', 'This context contains legacy detached work; run ghidra migrate --target ' + scope.target + ' --dry-run, then ghidra migrate --target ' + scope.target + '. Its data is retained.');
485
878
  if (binding && !stopped && alive(binding.pid) && ((binding.viewEpoch ?? 0) !== (context.viewEpoch ?? 0) ||
486
879
  binding.baseRevision !== context.baseRevision && context.baseRevision !== undefined)) {
487
880
  await this.stopRecord(await this.verified(binding, target), true, false, 'view_replaced');
@@ -502,28 +895,24 @@ export class GhidraContexts {
502
895
  }
503
896
  if (binding?.mode === 'gui')
504
897
  await this.debuggerReleased(binding);
505
- let model = context.workingSnapshot ? this.workspace.model(target.id) : await this.model(target);
506
- if (!context.workingSnapshot) {
507
- // A new session begins at the actual server revision, including external publications.
508
- // Existing contexts keep their saved private view until an explicit refresh.
509
- const shared = await this.latest(target.id);
510
- model = this.workspace.observeShared(target.id, shared.revision, shared.snapshot);
511
- }
512
- const snapshot = context.workingSnapshot ?? model.sharedSnapshot;
513
- if (!snapshot || !model.sharedRevision)
514
- fail('binding', 'Canonical target has no saved base.');
898
+ if (!context.nativeCheckout)
899
+ await this.model(target);
515
900
  if (binding && !stopped && !alive(binding.pid))
516
901
  await recordLifecycle(this.workspace, context.id, { at: new Date().toISOString(), event: 'stop', reason: 'unknown', pid: binding.pid });
517
902
  if (binding && (stopped || !alive(binding.pid))) {
518
903
  if (binding.context !== context.id || binding.target !== scope.target)
519
- fail('binding', 'Retired native credential belongs to a different context.');
904
+ fail('binding', 'Retired native credential belongs to another context.');
520
905
  await releaseStoppedContextCredential(this.directory(), binding, this.c.secrets, alive, () => this.retiredWorker(binding));
521
906
  }
522
- await this.privateCopy(context, snapshot);
523
- if (context.workingSnapshot)
524
- return this.workspace.saveContext(scope, context.generation, { state: 'ready' });
525
- return this.workspace.saveContext(scope, context.generation, { state: 'ready', baseRevision: model.sharedRevision,
526
- baseSnapshot: snapshot, workingSnapshot: snapshot });
907
+ let current = this.workspace.context(scope);
908
+ if (current.nativeCheckout?.state === 'verified') {
909
+ await this.dropNative(scope);
910
+ current = this.workspace.context(scope);
911
+ }
912
+ if (!current.nativeCheckout || current.nativeCheckout.state === 'dropped')
913
+ current = await this.createNative(scope);
914
+ await this.privateCopy(current, current.workingSnapshot);
915
+ return this.workspace.saveContext(scope, current.generation, { state: 'ready' });
527
916
  }
528
917
  async retireUnresponsive(scope, binding, error) {
529
918
  const failure = error;
@@ -659,9 +1048,48 @@ public class ${name} extends GhidraScript {
659
1048
  }
660
1049
  const request = join(root, 'request.json');
661
1050
  await durable(request, parameters);
1051
+ if (snapshot.kind === 'native')
1052
+ return object(await this.inspectNative(snapshot, 'inspect', { parameters }));
662
1053
  const result = await this.server().inspect(await this.workspace.artifacts.verify(snapshot), request);
663
1054
  return object(result.value);
664
1055
  }
1056
+ /** Full exports are explicit consumers (cross-program/VT/export/archive), never save/reopen/publication. */
1057
+ async snapshotFile(snapshot) {
1058
+ if (snapshot.kind !== 'native')
1059
+ return this.workspace.artifacts.verify(snapshot);
1060
+ const saved = object(JSON.parse(await readFile(await this.workspace.artifacts.verify(snapshot), 'utf8'))), root = join(saved.source === 'checkout' ? text(object(saved.checkout).root, 4096) : this.directory(), 'explicit-exports', randomUUID());
1061
+ await mkdir(root, { recursive: true, mode: 0o700 });
1062
+ const output = join(root, 'program.gzf');
1063
+ if (saved.source === 'server') {
1064
+ const binding = await this.server().ensure();
1065
+ if (saved.origin !== binding.origin || saved.repository !== binding.repository)
1066
+ fail('binding', 'Explicit native export binding changed.');
1067
+ const value = await this.server().nativeRead(binding, { ...saved, operation: 'export', output });
1068
+ if (value.state !== 'verified')
1069
+ fail('binding', 'Exact native server export failed.');
1070
+ }
1071
+ else if (saved.source === 'checkout') {
1072
+ const checkout = object(saved.checkout), context = this.workspace.contextById(checkout.context);
1073
+ if (context.nativeCheckout?.root !== checkout.root || context.nativeCheckout.state !== 'active')
1074
+ fail('binding', 'Explicit export requires the original active native view.');
1075
+ if (await this.closed(context)) {
1076
+ const value = await this.nativeOperation(context.nativeCheckout, 'export', { fingerprint: saved.fingerprint, output });
1077
+ if (value.state !== 'ready')
1078
+ fail('save', 'Saved native export failed.');
1079
+ }
1080
+ else {
1081
+ const record = await this.selected(context);
1082
+ await this.nativeView(record, { operation: 'fingerprint', expected: saved.fingerprint });
1083
+ const exported = object(await record.http.call('/export_program', { program_name: record.binding.program, output_dir: root, output_name: 'program.gzf' }));
1084
+ if (exported.success !== true)
1085
+ fail('save', 'Explicit native export was not acknowledged.');
1086
+ await this.nativeView(record, { operation: 'fingerprint', expected: saved.fingerprint });
1087
+ }
1088
+ }
1089
+ else
1090
+ fail('binding', 'Unknown native export source.');
1091
+ return this.workspace.artifacts.verify(await this.captureExport(output));
1092
+ }
665
1093
  async removePeer(record, path) {
666
1094
  // A cancelled invocation must still release its verified owned temporary program.
667
1095
  const cleanup = this.fork({ ...this.c, signal: new AbortController().signal });
@@ -707,7 +1135,7 @@ public class ${name} extends GhidraScript {
707
1135
  const name = '__insight_peer_' + randomUUID().replaceAll('-', ''), path = '/' + name, folder = join(record.binding.root, 'cross-peer', name);
708
1136
  await mkdir(folder, { recursive: true, mode: 0o700 });
709
1137
  const file = join(folder, 'input.gzf');
710
- await link(await this.workspace.artifacts.verify(snapshot), file);
1138
+ await link(await this.snapshotFile(snapshot), file);
711
1139
  await durable(join(folder, 'receipt.json'), { path, target: record.binding.target, context: record.binding.context, state: 'preparing' });
712
1140
  try {
713
1141
  const imported = object(await record.http.call('/import_program', { gzf_path: file, target_folder: '/', target_name: name, overwrite: false }));
@@ -1009,31 +1437,37 @@ public class ${name} extends GhidraScript {
1009
1437
  return false;
1010
1438
  }
1011
1439
  async latest(targetId) {
1012
- const target = this.workspace.target(targetId), server = this.server(), binding = await server.ensure();
1013
- const before = await server.programStatus(binding, programPath(targetId));
1014
- if (before.checkinActive !== false)
1015
- fail('blocked', 'Shared model has an active check-in.');
1016
- const expected = version(before.version), record = await this.shared(target, binding);
1017
- try {
1018
- const opened = await server.programStatus(binding, programPath(targetId));
1019
- if (opened.version !== expected)
1020
- fail('binding', 'Shared model changed while opening its saved view.');
1021
- const output = join(record.binding.root, 'exports');
1022
- await mkdir(output, { recursive: true, mode: 0o700 });
1023
- const exported = object(await record.http.call('/export_program', { program_name: record.binding.program, output_dir: output, output_name: 'shared.gzf' }));
1024
- if (exported.success !== true)
1025
- fail('save', 'Shared snapshot export was not acknowledged.');
1026
- const snapshot = await this.workspace.captureSnapshot(join(output, 'shared.gzf'));
1027
- const after = await server.programStatus(binding, programPath(targetId));
1028
- if (after.version !== expected)
1029
- fail('binding', 'Shared model changed before its snapshot was verified.');
1030
- return { revision: expected, snapshot };
1031
- }
1032
- finally {
1033
- await this.stopRecord(record);
1034
- }
1440
+ return this.serverView(targetId);
1441
+ }
1442
+ async inspectNative(snapshot, operation, parameters) {
1443
+ const saved = object(JSON.parse(await readFile(await this.workspace.artifacts.verify(snapshot), 'utf8')));
1444
+ if (saved.engine !== this.nativeEngine)
1445
+ fail('binding', 'Native view uses a different engine.');
1446
+ if (saved.source === 'server') {
1447
+ const binding = await this.server().ensure();
1448
+ if (saved.origin !== binding.origin || saved.repository !== binding.repository)
1449
+ fail('binding', 'Native shared view binding changed.');
1450
+ const result = await this.server().nativeRead(binding, { ...saved, operation, ...parameters });
1451
+ if (result.state !== 'verified')
1452
+ fail('binding', 'Immutable native server view could not be verified.');
1453
+ return operation === 'fields' ? result.fields : result.value;
1454
+ }
1455
+ if (saved.source !== 'checkout')
1456
+ fail('binding', 'Unknown native view source.');
1457
+ const checkout = object(saved.checkout), context = this.workspace.contextById(checkout.context);
1458
+ if (context.nativeCheckout?.root !== checkout.root || context.nativeCheckout.state !== 'active')
1459
+ fail('binding', 'The retained native view is no longer the active working copy.');
1460
+ if (await this.closed(context)) {
1461
+ const result = await this.nativeOperation(context.nativeCheckout, operation, { fingerprint: saved.fingerprint, ...parameters });
1462
+ if (result.state !== 'ready')
1463
+ fail('binding', 'Saved native project inspection failed.');
1464
+ return result.value;
1465
+ }
1466
+ return this.nativeView(await this.selected(context), { operation, expected: saved.fingerprint, ...parameters });
1035
1467
  }
1036
1468
  async fields(snapshot, changes) {
1469
+ if (snapshot.kind === 'native')
1470
+ return object(await this.inspectNative(snapshot, 'fields', { selectors: changes }));
1037
1471
  const directory = join(this.directory(), 'inspection', randomUUID());
1038
1472
  await mkdir(directory, { recursive: true, mode: 0o700 });
1039
1473
  const selectors = join(directory, 'fields.json');
@@ -1046,62 +1480,31 @@ public class ${name} extends GhidraScript {
1046
1480
  }
1047
1481
  return values;
1048
1482
  }
1049
- async applyField(record, change) {
1050
- const result = object(await record.http.call(change.field === 'function.name' ? '/rename_function' : '/set_comment', change.field === 'function.name' ?
1051
- { program: record.binding.program, old_name: change.address, new_name: change.local, strict_mode: 'off' } :
1052
- { program: record.binding.program, address: change.address, type: change.field.slice(8), comment: change.local ?? '' }));
1053
- if (result.status !== 'success' && result.success !== true)
1054
- fail('partial', 'Candidate edit was not acknowledged.');
1055
- if (change.field === 'function.name') {
1056
- const read = object(await record.http.call('/get_functions', { program: record.binding.program, functions: change.address, fields: 'entry_point', include_call_context: false }));
1057
- if (object(object(read.functions)[change.address]).name !== change.local)
1058
- fail('partial', 'Candidate name readback differs.');
1059
- }
1060
- else {
1061
- const read = object(await record.http.call('/get_comment', { program: record.binding.program, address: change.address }));
1062
- if ((read[change.field.slice(8)] || null) !== change.local)
1063
- fail('partial', 'Candidate comment readback differs.');
1064
- }
1065
- }
1066
- async candidate(targetId, snapshot, changes) {
1067
- const target = this.workspace.target(targetId), root = await this.prepareRoot('candidate', targetId);
1068
- await link(await this.workspace.artifacts.verify(snapshot), join(root, 'saved.gzf'));
1069
- const record = await this.launch(root, target, 'candidate', '/program', 'headless');
1070
- try {
1071
- await record.http.call('/create_project', { parentDir: root, name: 'view' });
1072
- await record.http.call('/import_program', { gzf_path: join(root, 'saved.gzf'), target_folder: '/', target_name: 'program', overwrite: false });
1073
- await record.http.call('/open_program', { path: record.binding.program });
1074
- await this.verified(record.binding, target);
1075
- for (const change of changes)
1076
- await this.applyField(record, change);
1077
- return await this.capture(record);
1078
- }
1079
- finally {
1080
- await this.stopRecord(record, false);
1081
- }
1082
- }
1083
- async publish(publication) {
1084
- const server = this.server(), binding = await server.ensure(), target = this.workspace.target(publication.target);
1085
- const directory = join(this.directory(), 'publications', publication.id);
1086
- await mkdir(directory, { recursive: true, mode: 0o700 });
1087
- const result = await server.publish(binding, programPath(target.id), await this.workspace.artifacts.verify(publication.snapshot), publication.expectedRevision, publication.id, join(directory, 'native-intent.json'), target.binarySha256);
1088
- if (result.state === 'conflict' && result.applied === 0)
1089
- return { state: 'conflict', applied: 0 };
1090
- if (result.state !== 'published' || result.version !== publication.expectedRevision + 1 || result.snapshotBuffersVerified !== true || result.ownedCheckoutReleased !== true)
1091
- fail('unknown', 'Native publication did not establish its version and complete saved buffers.');
1092
- const verified = await this.recover(publication);
1093
- if (verified.state !== 'verified')
1094
- fail('unknown', 'Independent exact-version publication verification remains unresolved.');
1095
- return { state: 'published', revision: verified.revision };
1096
- }
1097
- async recover(publication) {
1483
+ /** Readback only: establishes an interrupted snapshot publication and never issues another check-in. */
1484
+ async recoverLegacy(publication) {
1098
1485
  const server = this.server(), binding = await server.ensure(), target = this.workspace.target(publication.target);
1099
1486
  const journal = join(this.directory(), 'publications', publication.id, 'native-intent.json');
1100
1487
  const result = await server.recoverPublication(binding, programPath(target.id), await this.workspace.artifacts.verify(publication.snapshot), publication.expectedRevision, publication.id, journal, target.binarySha256);
1101
1488
  if (result.state === 'verified' && result.version === publication.expectedRevision + 1 && result.snapshotBuffersVerified === true && result.ownedCheckoutReleased === true)
1102
- return { state: 'verified', revision: version(result.version) };
1489
+ return { state: 'verified', revision: version(result.version), snapshot: publication.snapshot };
1103
1490
  return { state: 'unknown' };
1104
1491
  }
1492
+ async recover(publication) {
1493
+ if (publication.snapshot.kind !== 'native')
1494
+ return this.recoverLegacy(publication);
1495
+ const saved = object(JSON.parse(await readFile(await this.workspace.artifacts.verify(publication.snapshot), 'utf8'))), checkout = object(saved.checkout);
1496
+ if (saved.engine !== this.nativeEngine || saved.source !== 'checkout')
1497
+ return { state: 'unknown' };
1498
+ const { binding } = await this.nativeOwner(checkout), target = this.workspace.target(publication.target), revisionNumber = publication.expectedRevision + 1;
1499
+ const value = await this.server().nativeRead(binding, { operation: 'verify', path: checkout.path, sourceSha: target.binarySha256, fileId: checkout.fileId,
1500
+ version: revisionNumber, marker: 'insight native ' + publication.id, fingerprint: saved.fingerprint });
1501
+ if (value.state !== 'verified' || value.version !== revisionNumber)
1502
+ return { state: 'unknown' };
1503
+ const shared = await this.serverView(publication.target, revisionNumber);
1504
+ if (object(shared.value).fingerprint !== saved.fingerprint)
1505
+ return { state: 'unknown' };
1506
+ return { state: 'verified', revision: revisionNumber, snapshot: shared.snapshot };
1507
+ }
1105
1508
  async recoverModel(targetId) {
1106
1509
  if (this.workspace.activePublication(targetId))
1107
1510
  return false;
@@ -1141,7 +1544,7 @@ public class ${name} extends GhidraScript {
1141
1544
  const exported = object(await record.http.call('/export_program', { program_name: record.binding.program, output_dir: output, output_name: 'recovered.gzf' }));
1142
1545
  if (exported.success !== true)
1143
1546
  return false;
1144
- const snapshot = await this.workspace.captureSnapshot(join(output, 'recovered.gzf'));
1547
+ const snapshot = await this.captureExport(join(output, 'recovered.gzf'));
1145
1548
  const after = await server.programStatus(binding, programPath(targetId));
1146
1549
  if (after.version !== 1 || after.checkinActive !== false)
1147
1550
  return false;