@eyeauras/insight-cli 0.6.6 → 0.8.0

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 (122) hide show
  1. package/.cli-package-build.json +1 -1
  2. package/SKILL.md +1 -1
  3. package/dist/src/activity-audit.d.ts +130 -0
  4. package/dist/src/activity-audit.js +320 -0
  5. package/dist/src/analysis-storage.d.ts +5 -1
  6. package/dist/src/analysis-storage.js +9 -2
  7. package/dist/src/audit-commands.d.ts +10 -0
  8. package/dist/src/audit-commands.js +85 -0
  9. package/dist/src/audit-retention.d.ts +44 -0
  10. package/dist/src/audit-retention.js +167 -0
  11. package/dist/src/cli.js +28 -6
  12. package/dist/src/context-diagnostics.d.ts +1 -1
  13. package/dist/src/context-diagnostics.js +10 -2
  14. package/dist/src/contexts.d.ts +118 -10
  15. package/dist/src/contexts.js +851 -199
  16. package/dist/src/debugger.js +2 -1
  17. package/dist/src/diagnostic-error.d.ts +12 -0
  18. package/dist/src/diagnostic-error.js +82 -0
  19. package/dist/src/inline-script.js +3 -4
  20. package/dist/src/internal-timing.d.ts +8 -2
  21. package/dist/src/internal-timing.js +50 -7
  22. package/dist/src/lifecycle.d.ts +12 -1
  23. package/dist/src/lifecycle.js +34 -6
  24. package/dist/src/native-inputs.d.ts +6 -0
  25. package/dist/src/native-inputs.js +30 -6
  26. package/dist/src/native-queries.js +1 -6
  27. package/dist/src/native-service.d.ts +40 -0
  28. package/dist/src/native-service.js +406 -0
  29. package/dist/src/research.d.ts +30 -2
  30. package/dist/src/research.js +106 -27
  31. package/dist/src/server.d.ts +38 -1
  32. package/dist/src/server.js +160 -12
  33. package/dist/src/storage-gc.js +374 -341
  34. package/dist/src/sync-policy.js +2 -1
  35. package/dist/src/timed-backend.js +8 -0
  36. package/dist/src/timing-report.d.ts +32 -0
  37. package/dist/src/timing-report.js +74 -0
  38. package/dist/src/tool-runtime/identity.js +86 -1
  39. package/dist/src/tool-runtime/supervisor.js +6 -5
  40. package/dist/src/transport.d.ts +35 -0
  41. package/dist/src/transport.js +95 -16
  42. package/dist/src/unresolved-guidance.d.ts +46 -0
  43. package/dist/src/unresolved-guidance.js +55 -0
  44. package/dist/src/windbg.d.ts +1 -1
  45. package/dist/src/worker-lease.d.ts +17 -0
  46. package/dist/src/worker-lease.js +50 -0
  47. package/dist/src/workspace.d.ts +5 -9
  48. package/dist/src/workspace.js +34 -41
  49. package/package.json +1 -1
  50. package/references/native/InsightHeadlessMain.java +9 -2
  51. package/references/native/InsightNativeCheckout.java +113 -43
  52. package/references/native/InsightNativeFingerprint.java +28 -1
  53. package/references/native/InsightNativeRead.java +32 -9
  54. package/references/native/InsightNativeService.java +43 -0
  55. package/references/native/InsightNativeView.java +17 -6
  56. package/references/native/InsightOwnedScripts.java +170 -0
  57. package/references/native/InsightWorkerLease.java +132 -0
  58. package/references/recovery.md +68 -3
  59. package/references/research.md +71 -6
  60. package/references/setup.md +5 -1
  61. package/skill-bundle/insight-artifacts/SKILL.md +1 -1
  62. package/skill-bundle/insight-artifacts/references/recovery.md +68 -3
  63. package/skill-bundle/insight-binary/SKILL.md +1 -1
  64. package/skill-bundle/insight-capture/SKILL.md +1 -1
  65. package/skill-bundle/insight-cli/SKILL.md +1 -1
  66. package/skill-bundle/insight-cli/references/recovery.md +68 -3
  67. package/skill-bundle/insight-cli/references/setup.md +5 -1
  68. package/skill-bundle/insight-die/SKILL.md +1 -1
  69. package/skill-bundle/insight-dnspy/SKILL.md +1 -1
  70. package/skill-bundle/insight-dotnet-dump/SKILL.md +1 -1
  71. package/skill-bundle/insight-dotnet-stack/SKILL.md +1 -1
  72. package/skill-bundle/insight-dotnet-trace/SKILL.md +1 -1
  73. package/skill-bundle/insight-frida/SKILL.md +1 -1
  74. package/skill-bundle/insight-ghidra/SKILL.md +1 -1
  75. package/skill-bundle/insight-ghidra/references/recovery.md +68 -3
  76. package/skill-bundle/insight-ghidra/references/research.md +71 -6
  77. package/skill-bundle/insight-ghidra/references/setup.md +5 -1
  78. package/skill-bundle/insight-ilspy/SKILL.md +1 -1
  79. package/skill-bundle/insight-interop/SKILL.md +1 -1
  80. package/skill-bundle/insight-lldb/SKILL.md +1 -1
  81. package/skill-bundle/insight-llvm/SKILL.md +1 -1
  82. package/skill-bundle/insight-managed-heap/SKILL.md +1 -1
  83. package/skill-bundle/insight-managed-metadata/SKILL.md +1 -1
  84. package/skill-bundle/insight-mitmproxy/SKILL.md +1 -1
  85. package/skill-bundle/insight-overview/SKILL.md +1 -1
  86. package/skill-bundle/insight-procmon/SKILL.md +1 -1
  87. package/skill-bundle/insight-re/SKILL.md +7 -1
  88. package/skill-bundle/insight-re/references/recovery.md +68 -3
  89. package/skill-bundle/insight-sevenzip/SKILL.md +1 -1
  90. package/skill-bundle/insight-strace/SKILL.md +1 -1
  91. package/skill-bundle/insight-tshark/SKILL.md +1 -1
  92. package/skill-bundle/insight-windbg/SKILL.md +1 -1
  93. package/skill-bundle/manifest.json +1 -1
  94. package/skills/insight-artifacts/SKILL.md +1 -1
  95. package/skills/insight-artifacts/references/recovery.md +68 -3
  96. package/skills/insight-binary/SKILL.md +1 -1
  97. package/skills/insight-capture/SKILL.md +1 -1
  98. package/skills/insight-die/SKILL.md +1 -1
  99. package/skills/insight-dnspy/SKILL.md +1 -1
  100. package/skills/insight-dotnet-dump/SKILL.md +1 -1
  101. package/skills/insight-dotnet-stack/SKILL.md +1 -1
  102. package/skills/insight-dotnet-trace/SKILL.md +1 -1
  103. package/skills/insight-frida/SKILL.md +1 -1
  104. package/skills/insight-ghidra/SKILL.md +1 -1
  105. package/skills/insight-ghidra/references/recovery.md +68 -3
  106. package/skills/insight-ghidra/references/research.md +71 -6
  107. package/skills/insight-ghidra/references/setup.md +5 -1
  108. package/skills/insight-ilspy/SKILL.md +1 -1
  109. package/skills/insight-interop/SKILL.md +1 -1
  110. package/skills/insight-lldb/SKILL.md +1 -1
  111. package/skills/insight-llvm/SKILL.md +1 -1
  112. package/skills/insight-managed-heap/SKILL.md +1 -1
  113. package/skills/insight-managed-metadata/SKILL.md +1 -1
  114. package/skills/insight-mitmproxy/SKILL.md +1 -1
  115. package/skills/insight-overview/SKILL.md +1 -1
  116. package/skills/insight-procmon/SKILL.md +1 -1
  117. package/skills/insight-re/SKILL.md +7 -1
  118. package/skills/insight-re/references/recovery.md +68 -3
  119. package/skills/insight-sevenzip/SKILL.md +1 -1
  120. package/skills/insight-strace/SKILL.md +1 -1
  121. package/skills/insight-tshark/SKILL.md +1 -1
  122. package/skills/insight-windbg/SKILL.md +1 -1
@@ -0,0 +1,17 @@
1
+ /** Must stay well below the worker's hold expiry (three minutes). */
2
+ export declare const leaseHeartbeatMs = 60000;
3
+ export declare function withWorkerLeases<T>(action: () => Promise<T>): Promise<T>;
4
+ export declare function inWorkerLeaseScope(): boolean;
5
+ export declare function workerLeaseHeld(key: string): boolean;
6
+ /** The worker-side identity of this command's hold, when it has one. */
7
+ export declare function workerLeaseHolder(key: string): string | undefined;
8
+ /** Keep a worker held for the rest of the current command. Outside a command nothing is retained. */
9
+ export declare function holdWorkerLease(key: string, lease: {
10
+ renew: () => Promise<unknown>;
11
+ release: () => Promise<unknown>;
12
+ holder?: string;
13
+ }): void;
14
+ /** Release this command's hold now (for example before asking the worker to stop). */
15
+ export declare function releaseWorkerLease(key: string): Promise<void>;
16
+ /** A stopped worker needs no further renewal or release in this command. */
17
+ export declare function dropWorkerLease(key: string): void;
@@ -0,0 +1,50 @@
1
+ import { AsyncLocalStorage } from 'node:async_hooks';
2
+ const scope = new AsyncLocalStorage();
3
+ /** Must stay well below the worker's hold expiry (three minutes). */
4
+ export const leaseHeartbeatMs = 60000;
5
+ export async function withWorkerLeases(action) {
6
+ const held = new Map();
7
+ try {
8
+ return await scope.run(held, action);
9
+ }
10
+ finally {
11
+ for (const lease of held.values())
12
+ clearInterval(lease.timer);
13
+ await Promise.all([...held.values()].map(lease => lease.release().catch(() => { })));
14
+ }
15
+ }
16
+ export function inWorkerLeaseScope() { return scope.getStore() !== undefined; }
17
+ export function workerLeaseHeld(key) { return scope.getStore()?.has(key) === true; }
18
+ /** The worker-side identity of this command's hold, when it has one. */
19
+ export function workerLeaseHolder(key) { return scope.getStore()?.get(key)?.holder; }
20
+ /** Keep a worker held for the rest of the current command. Outside a command nothing is retained. */
21
+ export function holdWorkerLease(key, lease) {
22
+ const held = scope.getStore();
23
+ if (!held)
24
+ return;
25
+ const previous = held.get(key);
26
+ if (previous) {
27
+ clearInterval(previous.timer);
28
+ void previous.release().catch(() => { });
29
+ }
30
+ const timer = setInterval(() => { void lease.renew().catch(() => { }); }, leaseHeartbeatMs);
31
+ timer.unref();
32
+ held.set(key, { ...lease, timer });
33
+ }
34
+ /** Release this command's hold now (for example before asking the worker to stop). */
35
+ export async function releaseWorkerLease(key) {
36
+ const held = scope.getStore(), lease = held?.get(key);
37
+ if (!lease)
38
+ return;
39
+ clearInterval(lease.timer);
40
+ held.delete(key);
41
+ await lease.release().catch(() => { });
42
+ }
43
+ /** A stopped worker needs no further renewal or release in this command. */
44
+ export function dropWorkerLease(key) {
45
+ const held = scope.getStore(), lease = held?.get(key);
46
+ if (!lease)
47
+ return;
48
+ clearInterval(lease.timer);
49
+ held.delete(key);
50
+ }
@@ -62,8 +62,6 @@ export interface NativeCheckout {
62
62
  request: string;
63
63
  message: string;
64
64
  };
65
- /** Saved buffers proved to hold no private work although Ghidra rewrote them on open; the release accepts only these. */
66
- opened?: string;
67
65
  }
68
66
  export interface GhidraContext extends Scope {
69
67
  /** Internal storage key, never a caller's backend selector. */
@@ -149,6 +147,8 @@ export declare class Workspace {
149
147
  readonly artifacts: Artifacts;
150
148
  private readonly db;
151
149
  private namespace;
150
+ private auditPending;
151
+ private auditRequest;
152
152
  constructor(directory: string, profile: string);
153
153
  close(): void;
154
154
  private transaction;
@@ -188,15 +188,11 @@ export declare class Workspace {
188
188
  private giveUp;
189
189
  /** An abandoned or otherwise unknown terminal effect keeps all of its native evidence. */
190
190
  uncertainOutcome(scope: Scope): boolean;
191
- /** Receipt-only comparison; native state is verified separately before any release. */
192
- unchangedNative(context: GhidraContext): boolean;
193
191
  /**
194
- * Saved buffers hold no private work when they equal the shared base, or equal what Ghidra itself wrote when a
195
- * worker opened a pristine checkout of that base. Equal bytes are the proof; what Ghidra rewrote is irrelevant.
192
+ * Whether the working copy holds no private work, as Ghidra itself reported it when the copy was last saved or
193
+ * observed (`modifiedSinceCheckout`). Native state is observed again before any release.
196
194
  */
197
- unchangedBuffers(target: string, base: Record<string, unknown>, fingerprint: unknown): boolean;
198
- /** Saved buffers of pristine checkouts of one shared version, as each was left by its worker's own open. */
199
- openedReferences(target: string, base: Record<string, unknown>): Set<string>;
195
+ unchangedNative(context: GhidraContext): boolean;
200
196
  /** Another context's unresolved operation may still need this checkout's private view. */
201
197
  checkoutReferenced(context: GhidraContext, root?: string | undefined): boolean;
202
198
  /** Applied requests keep their results; their superseded before-images are not recovery inputs. */
@@ -1,5 +1,6 @@
1
1
  import { DatabaseSync } from 'node:sqlite';
2
- import { chmodSync, mkdirSync, readFileSync, readdirSync, realpathSync } from 'node:fs';
2
+ import { auditEvent, bindAudit, auditHash } from './activity-audit.js';
3
+ import { chmodSync, mkdirSync, readFileSync, realpathSync } from 'node:fs';
3
4
  import { basename, join } from 'node:path';
4
5
  import { randomUUID } from 'node:crypto';
5
6
  import { Artifacts } from './artifacts.js';
@@ -56,6 +57,19 @@ export class Workspace {
56
57
  artifacts;
57
58
  db;
58
59
  namespace;
60
+ auditPending;
61
+ auditRequest(request) {
62
+ const data = { request: request.id, state: request.state, ...(request.callerId ? { callerHash: auditHash(request.callerId) } : {}), ...(request.context ? { context: request.context } : {}), ...(['unknown', 'failed'].includes(request.state) ? { outcome: 'failure' } : request.state === 'applied' ? { outcome: 'success' } : {}) };
63
+ const emit = () => { bindAudit(data); if (request.context)
64
+ try {
65
+ bindAudit(this.contextById(request.context));
66
+ }
67
+ catch { } auditEvent('request.state', data); };
68
+ if (this.auditPending)
69
+ this.auditPending.push(emit);
70
+ else
71
+ emit();
72
+ }
59
73
  constructor(directory, profile) {
60
74
  this.profile = profile;
61
75
  text(profile);
@@ -107,12 +121,18 @@ export class Workspace {
107
121
  close() { this.db.close(); }
108
122
  transaction(action) {
109
123
  this.db.exec('BEGIN IMMEDIATE');
124
+ const previous = this.auditPending, events = [];
125
+ this.auditPending = events;
110
126
  try {
111
127
  const result = action();
112
128
  this.db.exec('COMMIT');
129
+ this.auditPending = previous;
130
+ for (const emit of events)
131
+ emit();
113
132
  return result;
114
133
  }
115
134
  catch (error) {
135
+ this.auditPending = previous;
116
136
  this.db.exec('ROLLBACK');
117
137
  throw error;
118
138
  }
@@ -216,6 +236,7 @@ export class Workspace {
216
236
  const request = { id: 'q_' + randomUUID(), operation: text(operation, 128), intent,
217
237
  context, state: 'accepted', ...(callerId === undefined ? {} : { callerId: id(callerId) }), createdAt: now(), updatedAt: now() };
218
238
  this.db.prepare('INSERT INTO requests VALUES(?,?,?,?,?,?)').run(request.id, callerId ?? null, hash, context, request.state, bounded(request));
239
+ this.auditRequest(request);
219
240
  return request;
220
241
  }
221
242
  reserveOpen(target, session, settings, callerId, mode) {
@@ -315,55 +336,23 @@ export class Workspace {
315
336
  return this.db.prepare("SELECT data FROM requests WHERE context=? AND state='failed'").all(this.context(scope).id).map(row => JSON.parse(String(row.data)))
316
337
  .some(row => !row.dropped && row.result?.outcome === 'unknown');
317
338
  }
318
- /** Receipt-only comparison; native state is verified separately before any release. */
339
+ /**
340
+ * Whether the working copy holds no private work, as Ghidra itself reported it when the copy was last saved or
341
+ * observed (`modifiedSinceCheckout`). Native state is observed again before any release.
342
+ */
319
343
  unchangedNative(context) {
320
344
  if (context.nativeCheckout?.state === 'verified')
321
345
  return true;
322
- if (context.workingSnapshot?.kind !== 'native' || context.baseSnapshot?.kind !== 'native')
346
+ if (context.workingSnapshot?.kind !== 'native')
323
347
  return false;
324
348
  try {
325
- const [local, base] = [context.workingSnapshot, context.baseSnapshot].map(value => JSON.parse(readFileSync(this.artifacts.path(value), 'utf8')));
326
- return this.unchangedBuffers(context.target, base, local.fingerprint);
349
+ const local = JSON.parse(readFileSync(this.artifacts.path(context.workingSnapshot), 'utf8'));
350
+ return local.source === 'checkout' && local.modified === false;
327
351
  }
328
352
  catch {
329
353
  return false;
330
354
  }
331
355
  }
332
- /**
333
- * Saved buffers hold no private work when they equal the shared base, or equal what Ghidra itself wrote when a
334
- * worker opened a pristine checkout of that base. Equal bytes are the proof; what Ghidra rewrote is irrelevant.
335
- */
336
- unchangedBuffers(target, base, fingerprint) {
337
- if (typeof fingerprint !== 'string' || !/^[a-f0-9]{64}$/.test(fingerprint) || base.source !== 'server' || typeof base.fingerprint !== 'string')
338
- return false;
339
- return fingerprint === base.fingerprint || this.openedReferences(target, base).has(fingerprint);
340
- }
341
- /** Saved buffers of pristine checkouts of one shared version, as each was left by its worker's own open. */
342
- openedReferences(target, base) {
343
- const revision = Number(base.version);
344
- const found = new Set(), root = join(this.directory, 'ghidra-native', 'shared-views', id(target), 'opened');
345
- let names;
346
- try {
347
- names = readdirSync(root);
348
- }
349
- catch {
350
- return found;
351
- }
352
- for (const name of names) {
353
- const match = /^v(\d+)-([a-f0-9]{64})\.json$/.exec(name);
354
- if (!match || Number(match[1]) !== revision)
355
- continue;
356
- try {
357
- const row = JSON.parse(readFileSync(join(root, name), 'utf8'));
358
- // Earlier receipts inferred pristine state from control metadata alone; they cannot authorize deletion.
359
- if (row.schema === 2 && row.preOpen?.fingerprint === base.fingerprint && row.preOpen.fileId === base.fileId && row.preOpen.baseVersion === revision &&
360
- Number.isSafeInteger(row.preOpen.checkoutId) && row.preOpen.checkoutId >= 0 && row.target === target && row.version === revision && row.fileId === base.fileId && row.base === base.fingerprint && row.origin === base.origin && row.repository === base.repository && row.opened === match[2])
361
- found.add(match[2]);
362
- }
363
- catch { }
364
- }
365
- return found;
366
- }
367
356
  /** Another context's unresolved operation may still need this checkout's private view. */
368
357
  checkoutReferenced(context, root = context.nativeCheckout?.root) {
369
358
  const seen = new Set();
@@ -449,6 +438,7 @@ export class Workspace {
449
438
  }
450
439
  const request = { id: 'a_' + randomUUID(), operation, intent, state: 'accepted', ...(callerId ? { callerId } : {}), createdAt: now(), updatedAt: now() };
451
440
  this.db.prepare('INSERT INTO administration_requests VALUES(?,?,?,?,?)').run(request.id, callerId ?? null, hash, request.state, bounded(request));
441
+ this.auditRequest(request);
452
442
  return { request, replay: false };
453
443
  });
454
444
  }
@@ -491,6 +481,7 @@ export class Workspace {
491
481
  fail('blocked', 'Administration operation already started; do not replay it.');
492
482
  const next = { ...previous, state, ...(result === undefined ? {} : { result }), updatedAt: now() };
493
483
  this.db.prepare('UPDATE administration_requests SET state=?,data=? WHERE id=?').run(state, bounded(next), request);
484
+ this.auditRequest(next);
494
485
  return next;
495
486
  });
496
487
  }
@@ -506,6 +497,7 @@ export class Workspace {
506
497
  fail('blocked', 'Request already started; reconcile its recorded outcome before continuing.');
507
498
  const next = { ...previous, state: 'running', ...(execution === undefined ? {} : { execution }), updatedAt: now() };
508
499
  this.db.prepare('UPDATE requests SET state=?,data=? WHERE id=?').run(next.state, bounded(next), next.id);
500
+ this.auditRequest(next);
509
501
  return next;
510
502
  });
511
503
  }
@@ -523,6 +515,7 @@ export class Workspace {
523
515
  fail('binding', 'Request must start before an effect can be acknowledged.');
524
516
  const next = { ...previous, state, result, updatedAt: now() };
525
517
  this.db.prepare('UPDATE requests SET state=?,data=? WHERE id=?').run(next.state, bounded(next), next.id);
518
+ this.auditRequest(next);
526
519
  return next;
527
520
  }
528
521
  establishModel(target, revision, snapshot) {
@@ -677,7 +670,7 @@ export class Workspace {
677
670
  const context = this.context(scope);
678
671
  if (checkout.state !== 'verified' || stable(context.nativeCheckout) !== stable(checkout))
679
672
  fail('binding', 'Native disposal ownership changed before retention.');
680
- const { opened, ...binding } = checkout, active = { ...binding, state: 'active' };
673
+ const active = { ...checkout, state: 'active' };
681
674
  this.knownSnapshot(snapshot);
682
675
  const saved = object(JSON.parse(readFileSync(this.artifacts.path(snapshot), 'utf8')));
683
676
  if (snapshot.kind !== 'native' || saved.engine !== 'native-checkout-v1' || saved.source !== 'checkout' || stable(saved.checkout) !== stable(active) ||
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@eyeauras/insight-cli",
3
- "version": "0.6.6",
3
+ "version": "0.8.0",
4
4
  "type": "module",
5
5
  "description": "Agent-facing durable sessions and isolated Ghidra research contexts",
6
6
  "main": "./dist/src/index.js",
@@ -3,9 +3,16 @@ import com.xebyte.headless.GhidraMCPHeadlessServer;
3
3
 
4
4
  /** Preserve caller-selected names in the owned facade, including structure fields. */
5
5
  class InsightHeadlessMain {
6
- public static void main(String[] args) {
6
+ public static void main(String[] args) throws Exception {
7
7
  insight.nativecheckout.InsightOfflineAuthenticator.install();
8
+ InsightWorkerLease.start();
8
9
  NamingPolicy.getInstance().setStrictNamingEnforcement(false, "insight facade");
9
- GhidraMCPHeadlessServer.main(args);
10
+ // The steps of GhidraMCPHeadlessServer.main, keeping the instance so that owned helper scripts can run in-process.
11
+ GhidraMCPHeadlessServer server=new GhidraMCPHeadlessServer();
12
+ InsightOwnedScripts.bind(server);
13
+ try{server.launch(new ghidra.GhidraApplicationLayout(),args);}
14
+ catch(Exception failure){
15
+ System.err.println("Failed to launch headless server: "+failure.getMessage());failure.printStackTrace();System.exit(1);
16
+ }
10
17
  }
11
18
  }
@@ -22,6 +22,8 @@ public final class InsightNativeCheckout {
22
22
  static final TaskMonitor MONITOR=TaskMonitor.DUMMY;
23
23
  static final Object CONSUMER=new Object();
24
24
  static boolean permitMerge=true;
25
+ /** Set when a request leaves this JVM in a doubtful state (an Error or a failed cleanup): a service then exits. */
26
+ static volatile boolean poisoned;
25
27
  static class Projects extends DefaultProjectManager {Projects(){super();}}
26
28
  static final class HeadChanged extends RuntimeException {HeadChanged(){super("Shared head changed before native check-in");}}
27
29
  static class Factory extends ghidra.program.database.GhidraProgramMultiUserMergeManagerFactory {
@@ -48,9 +50,15 @@ public final class InsightNativeCheckout {
48
50
  require(p.getExecutableSHA256().equals(text(owner,"sourceSha")),"Native source identity changed");
49
51
  if(!p.getOptions("Insight").getString("Publication Engine","").equals("native-checkout-v1"))throw new InsightNativeMigration.Required();
50
52
  }
53
+ /** The program is this target's native model; no bytes are read. */
54
+ static void identified(DomainFile file,JsonObject owner)throws Exception {
55
+ Program p=(Program)file.getDomainObject(CONSUMER,false,false,MONITOR);
56
+ try{source(p,owner);}finally{p.release(CONSUMER);}
57
+ }
58
+ /** The saved state of a local file as Ghidra identifies it; the database is not read. */
51
59
  static Map<String,Object> saved(DomainFile file,JsonObject owner)throws Exception {
52
60
  Program p=(Program)file.getDomainObject(CONSUMER,false,false,MONITOR);
53
- try{source(p,owner);return Map.of("fingerprint",InsightNativeFingerprint.of(p),"version",file.getVersion(),"fileId",file.getFileID(),
61
+ try{source(p,owner);return Map.of("fingerprint",InsightNativeFingerprint.saved(p),"modified",file.isCheckedOut()&&file.modifiedSinceCheckout(),"version",file.getVersion(),"fileId",file.getFileID(),
54
62
  "language",p.getLanguageID().toString(),"compiler",p.getCompilerSpec().getCompilerSpecID().toString(),"imageBase",p.getImageBase().toString());}
55
63
  finally{p.release(CONSUMER);}
56
64
  }
@@ -59,18 +67,23 @@ public final class InsightNativeCheckout {
59
67
  for(DomainFile f:folder.getFiles())if(!f.isVersioned()||f.isCheckedOut()||f.isHijacked()||f.canRecover())names.add(f.getPathname().substring(1));
60
68
  for(DomainFolder child:folder.getFolders())if(child.isLinked())names.add(child.getPathname().substring(1)+"/");else local(child,names);
61
69
  }
62
- static String authorized(JsonObject q){return text(q,q.has("opened")?"opened":"fingerprint");}
70
+ /** Ghidra's save counter of the local file: a later save of a file that survived its release is seen without reading it. */
71
+ static long localVersion(DomainFile file)throws Exception {
72
+ Program p=(Program)file.getDomainObject(CONSUMER,false,false,MONITOR);
73
+ try{return InsightNativeFingerprint.localVersion(p);}finally{p.release(CONSUMER);}
74
+ }
63
75
  static boolean sameRelease(JsonObject receipt,JsonObject q){
64
- if(!Objects.equals(receipt.get("checkoutId"),q.get("checkoutId"))||!Objects.equals(receipt.get("fingerprint"),q.get("fingerprint"))||
65
- !Objects.equals(receipt.get("version"),q.get("verifiedVersion")))return false;
66
- // Completed older receipts already ended the checkout. Preserve their deletion-only recovery.
67
- if(!receipt.has("savedFingerprint")&&!receipt.has("fileId"))return true;
68
- return Objects.equals(receipt.get("fileId"),q.get("fileId"))&&Objects.equals(receipt.get("savedFingerprint"),new JsonPrimitive(authorized(q)));
76
+ // The checkout, its base version and its file identify a release. Receipts of earlier builds also recorded
77
+ // fingerprints, which name nothing comparable any more and are not consulted.
78
+ if(!Objects.equals(receipt.get("checkoutId"),q.get("checkoutId"))||!Objects.equals(receipt.get("version"),q.get("verifiedVersion")))return false;
79
+ return !receipt.has("fileId")||Objects.equals(receipt.get("fileId"),q.get("fileId"));
69
80
  }
70
81
  /** A new intent can prove the local file left between server termination and native undo's local deletion. */
71
- static boolean survivingRelease(JsonObject receipt,JsonObject q,Map<String,Object> saved){
72
- return receipt.has("fileId")&&receipt.has("savedFingerprint")&&Objects.equals(receipt.get("state"),new JsonPrimitive("release_intent"))&&sameRelease(receipt,q)&&
73
- Objects.equals(saved.get("fileId"),text(receipt,"fileId"))&&Objects.equals(saved.get("fingerprint"),text(receipt,"savedFingerprint"));
82
+ static boolean survivingRelease(JsonObject receipt,JsonObject q,String fileId,long localVersion){
83
+ // The intent was recorded only after Ghidra reported this checkout unmodified and without recovery data. The
84
+ // file left behind is that one only while it was not saved again.
85
+ return receipt.has("fileId")&&receipt.has("localVersion")&&Objects.equals(receipt.get("state"),new JsonPrimitive("release_intent"))&&sameRelease(receipt,q)&&
86
+ fileId.equals(text(receipt,"fileId"))&&localVersion>=0&&receipt.get("localVersion").getAsLong()==localVersion;
74
87
  }
75
88
  static boolean backupName(String program,String name){
76
89
  String keep=program+".keep";
@@ -102,13 +115,13 @@ public final class InsightNativeCheckout {
102
115
  JsonObject created=proof.getAsJsonObject();
103
116
  if(!saved.get("fileId").equals(text(created,"fileId"))||!saved.get("fingerprint").equals(text(created,"fingerprint"))||
104
117
  !journal.get("backupExpected").getAsBoolean())return false;
105
- if(created.get("schema").getAsInt()==2){
118
+ if(created.get("schema").getAsInt()==2||created.get("schema").getAsInt()==3){
106
119
  String program=text(journal.getAsJsonObject("request").getAsJsonObject("owner"),"path").substring(1);
107
120
  return text(journal.getAsJsonObject("request"),"operation").equals("discard")&&
108
121
  name.equals(createdBackup(program,journal.getAsJsonObject("backupFilesBefore"),journal.getAsJsonObject("backupFilesAfter")))&&
109
122
  journal.getAsJsonObject("backupFilesAfter").get(name).equals(created.get("fileId"))&&
110
123
  name.equals(text(journal.getAsJsonObject("result"),"retainedKeepFile"))&&
111
- created.get("fingerprint").equals(journal.getAsJsonObject("before").get("fingerprint"));
124
+ (created.get("schema").getAsInt()==3||created.get("fingerprint").equals(journal.getAsJsonObject("before").get("fingerprint")));
112
125
  }
113
126
  boolean newFile=journal.has("backupAbsent")&&(journal.get("backupAbsent").getAsBoolean()||journal.has("backupBeforeFileId")&&!journal.get("backupBeforeFileId").isJsonNull()&&
114
127
  !journal.get("backupBeforeFileId").equals(created.get("fileId")));
@@ -227,33 +240,50 @@ public final class InsightNativeCheckout {
227
240
  for(var checkout:repository.getCheckouts("/",name))require(checkout.getCheckoutId()!=id,"Owned checkout remains");
228
241
  return Map.of("state","abandoned","terminated",present);
229
242
  }
243
+ /** One-shot helper: one request file, one JSON result line, then exit. */
230
244
  public static void main(String[] args){
231
- var output=System.out;System.setOut(System.err);Project project=null;GhidraServerManager server=null;
245
+ var output=System.out;System.setOut(System.err);Map<String,Object> result;
246
+ try{require(args.length==1,"Owned request required");initialize();result=handle(Path.of(args[0]));}
247
+ catch(Throwable failure){failure.printStackTrace(System.err);result=unknown(failure);}
248
+ output.println(GSON.toJson(result));System.exit(0);
249
+ }
250
+ private static boolean registered;
251
+ /** Ghidra and the stock multi-user merge factory are initialized once per JVM (helper or long-lived service). */
252
+ static synchronized void initialize()throws Exception {
253
+ if(!Application.isInitialized())Application.initializeApplication(new GhidraApplicationLayout(),new HeadlessGhidraApplicationConfiguration());
254
+ if(!registered){
255
+ Class.forName("ghidra.program.database.ProgramMultiUserMergeManagerFactory");
256
+ PluggableServiceRegistry.registerPluggableService(ghidra.program.database.ProgramMultiUserMergeManagerFactory.class,new Factory());registered=true;
257
+ }
258
+ }
259
+ static Map<String,Object> unknown(Throwable failure){
260
+ return Map.of("state","unknown","diagnostic",failure.getClass().getSimpleName(),"reason",Objects.toString(failure.getMessage(),failure.toString()),"code",failure instanceof InsightNativeMigration.Required?"migration":"unknown");
261
+ }
262
+ /** One native checkout operation. Per-request state is reset, so a long-lived service handles requests independently. */
263
+ static Map<String,Object> handle(Path requestFile){
264
+ Project project=null;GhidraServerManager server=null;
232
265
  Map<String,Object> out=new LinkedHashMap<>();
266
+ permitMerge=true;HeadlessProgramMergeManager.invocations=0;HeadlessProgramMergeManager.phases.clear();
233
267
  try {
234
- require(args.length==1,"Owned request required");
235
- JsonObject q=JsonParser.parseString(Files.readString(Path.of(args[0]))).getAsJsonObject();
268
+ JsonObject q=JsonParser.parseString(Files.readString(requestFile)).getAsJsonObject();
236
269
  boolean abandoning=text(q,"operation").equals("abandon");
237
270
  Path root=abandoning?Path.of(text(q,"root")):Path.of(text(q,"root")).toRealPath();
238
271
  JsonObject owner=abandoning?q.getAsJsonObject("owner"):JsonParser.parseString(Files.readString(root.resolve("native-owner.json"))).getAsJsonObject();
239
272
  require(owner.equals(q.getAsJsonObject("owner")),"Native owner receipt changed");
240
273
  require(text(owner,"protocol").equals("native-checkout-v1")&&text(owner,"path").equals("/"+text(owner,"target")+".bin"),"Malformed native binding");
241
274
  String operation=text(q,"operation"),path=text(owner,"path"),name=path.substring(1);
242
- Application.initializeApplication(new GhidraApplicationLayout(),new HeadlessGhidraApplicationConfiguration());
243
- Class.forName("ghidra.program.database.ProgramMultiUserMergeManagerFactory");
244
- PluggableServiceRegistry.registerPluggableService(ghidra.program.database.ProgramMultiUserMergeManagerFactory.class,new Factory());
245
275
  server=new GhidraServerManager();server.connect();require(server.isConnected(),"Native repository disconnected");
246
276
  RepositoryAdapter repository=server.server().getRepository(text(owner,"repository"));repository.connect();
247
277
  require(repository.getUser().hasWritePermission()&&repository.getUser().getName().equals(System.getenv("GHIDRA_SERVER_USER")),"Publisher authority required");
248
278
  if(abandoning){
249
- out.putAll(abandon(repository,q,owner));repository.disconnect();server.disconnect();output.println(GSON.toJson(out));System.exit(0);
279
+ out.putAll(abandon(repository,q,owner));repository.disconnect();server.disconnect();server=null;return out;
250
280
  }
251
281
  ProjectLocator locator=new ProjectLocator(root.toString(),"view");Projects manager=new Projects();
252
282
  // After a proved release the project is never reopened: an interrupted deletion can leave it unreadable.
253
283
  if((operation.equals("release")||operation.equals("drop"))&&released(root,q)){
254
284
  require(Arrays.stream(repository.getCheckouts("/",name)).noneMatch(c->c.getCheckoutId()==q.get("checkoutId").getAsLong()),"Owned checkout remains");
255
285
  if(operation.equals("drop"))deleteReleased(root,locator);
256
- repository.disconnect();server.disconnect();output.println("{\"state\":\""+(operation.equals("drop")?"dropped":"released")+"\"}");System.exit(0);
286
+ repository.disconnect();server.disconnect();server=null;return new LinkedHashMap<>(Map.of("state",operation.equals("drop")?"dropped":"released"));
257
287
  }
258
288
  if(operation.equals("create")&&!locator.getMarkerFile().exists())project=manager.createProject(locator,repository,false);
259
289
  else project=manager.openProject(locator,false,false);
@@ -264,12 +294,39 @@ public final class InsightNativeCheckout {
264
294
  if(operation.equals("create")&&!file.isCheckedOut()){
265
295
  String projectPath=ghidra.framework.store.ItemCheckoutStatus.getProjectPath(locator.toString(),false);
266
296
  require(Arrays.stream(repository.getCheckouts("/",name)).noneMatch(c->projectPath.equals(c.getProjectPath())),"Uncertain checkout creation must be reconciled");
267
- saved(file,owner);require(file.checkout(false,MONITOR),"Native checkout denied");
297
+ identified(file,owner);require(file.checkout(false,MONITOR),"Native checkout denied");
268
298
  }
269
299
  require(!file.isCheckedOutExclusive(),"Ordinary native checkout required");
270
300
  if(q.has("fileId"))require(file.getFileID().equals(text(q,"fileId")),"Native file ID changed");
271
301
  if(q.has("checkoutId")&&file.isCheckedOut())require(file.getCheckoutStatus().getCheckoutId()==q.get("checkoutId").getAsLong(),"Native checkout owner changed");
272
302
  Path operations=root.resolve("operations");Files.createDirectories(operations);
303
+ // Opening a file for writing discards Ghidra's recovery snapshot of unsaved changes. A file that has one is
304
+ // reported as it is and never opened: that work is kept for its owner to recover.
305
+ if(operation.equals("unsaved")){
306
+ // Ghidra's own open applies the recovery data or deletes it; this helper reads and writes none of it.
307
+ // Everything is checked before the only effect.
308
+ require(file.isCheckedOut()&&file.getCheckoutStatus().getCheckoutVersion()==q.get("baseVersion").getAsInt(),"Native checkout differs from its receipt");
309
+ boolean keep=q.get("keep").getAsBoolean(),present=file.canRecover();
310
+ if(present){
311
+ ProgramDB p=(ProgramDB)file.getDomainObject(CONSUMER,false,keep,MONITOR);
312
+ if(keep)try{p.save("insight recovered unsaved changes",MONITOR);}
313
+ catch(Throwable failure){
314
+ // Closing a restored program that was not saved makes Ghidra delete its recovery data. The process
315
+ // ends as an interrupted session does instead: the data stays and the command can be repeated.
316
+ failure.printStackTrace(System.err);System.err.flush();Runtime.getRuntime().halt(70);
317
+ }
318
+ p.release(CONSUMER);
319
+ require(!file.canRecover(),"Ghidra kept the recovery data");
320
+ }
321
+ out.put("state",!present?"absent":keep?"recovered":"discarded");
322
+ }
323
+ if(file.canRecover()){
324
+ require(operation.equals("status"),"Unsaved changes of an interrupted session can be recovered; keep them with `ghidra changes recover-unsaved` or drop them with `ghidra changes discard-unsaved` before this operation");
325
+ out.put("recoverable",true);out.put("modified",file.isCheckedOut()&&file.modifiedSinceCheckout());out.put("fileId",file.getFileID());out.put("checkedOut",file.isCheckedOut());
326
+ var local=new TreeSet<String>();local(project.getProjectData().getRootFolder(),local);out.put("projectFiles",local);
327
+ if(file.isCheckedOut()){out.put("checkoutId",file.getCheckoutStatus().getCheckoutId());out.put("baseVersion",file.getCheckoutStatus().getCheckoutVersion());}
328
+ history(repository,path,out);out.put("state","ready");project.close();project=null;repository.disconnect();server.disconnect();server=null;return out;
329
+ }
273
330
  if(operation.equals("update")||operation.equals("checkin")||operation.equals("discard")){
274
331
  String request=text(q,"request");require(request.matches("q_[a-f0-9-]{36}"),"Native request identity required");
275
332
  Path journal=operations.resolve(request+"-"+operation+".json");
@@ -297,8 +354,9 @@ public final class InsightNativeCheckout {
297
354
  DomainFile created=project.getProjectData().getFile("/"+keep);
298
355
  require(created!=null&&!created.isVersioned()&&!created.canRecover()&&!created.isCheckedOut()&&!created.isHijacked(),"Native discard backup is not private");
299
356
  var actual=saved(created,owner);
300
- require(Objects.equals(actual.get("fileId"),backupsAfter.get(keep))&&Objects.equals(actual.get("fingerprint"),before.get("fingerprint")),"Native discard backup differs from saved private buffers");
301
- out.put("retainedKeepFile",keep);out.put("disposableBackups",Map.of(keep,Map.of("schema",2,"fileId",actual.get("fileId"),"fingerprint",actual.get("fingerprint"))));
357
+ // Ghidra's undoCheckout made this copy; it is identified as it stands now, so a later edit of it is noticed.
358
+ require(Objects.equals(actual.get("fileId"),backupsAfter.get(keep)),"Native discard backup differs from the created file");
359
+ out.put("retainedKeepFile",keep);out.put("disposableBackups",Map.of(keep,Map.of("schema",3,"fileId",actual.get("fileId"),"fingerprint",actual.get("fingerprint"))));
302
360
  }
303
361
  file=project.getProjectData().getFile(path);require(file.checkout(false,MONITOR),"Native checkout after discard was refused");
304
362
  }else if(operation.equals("update")){
@@ -306,7 +364,7 @@ public final class InsightNativeCheckout {
306
364
  // Only dirty incoming Update can replace .keep. A refusal is a completed pre-call outcome,
307
365
  // carried by the existing conflict/recovery path; incomplete/legacy intents remain unknown.
308
366
  if(backupExpected&&!keepAbsent&&!replaceableBackup(project,operations,q,owner,base,intent)){
309
- require(before.equals(saved(file,owner))&&file.getCheckoutStatus().getCheckoutId()==checkout&&file.getCheckoutStatus().getCheckoutVersion()==base,"Backup refusal did not preserve local state");
367
+ require(file.getCheckoutStatus().getCheckoutId()==checkout&&file.getCheckoutStatus().getCheckoutVersion()==base,"Backup refusal did not preserve local state");
310
368
  out.put("state","conflict");out.put("conflict","Existing native backup is not proved disposable; retain and inspect this project before Update");
311
369
  var refusal=new LinkedHashMap<String,Object>(Map.of("schema",1,"operation","update","invoked",false,"reason","protected_existing_backup"));
312
370
  refusal.put("fileId",priorKeepId);out.put("preCallRefusal",refusal);
@@ -316,12 +374,11 @@ public final class InsightNativeCheckout {
316
374
  require(file.getCheckoutStatus().getCheckoutId()==checkout&&file.getCheckoutStatus().getCheckoutVersion()>=head,"Native Update did not establish the requested ancestry");
317
375
  out.put("state","updated");}
318
376
  catch(HeadlessProgramMergeManager.UnresolvedNativeConflict conflict){
319
- require(before.equals(saved(file,owner))&&file.getCheckoutStatus().getCheckoutId()==checkout&&file.getCheckoutStatus().getCheckoutVersion()==base,"Native conflict did not preserve local state");
377
+ require(file.getCheckoutStatus().getCheckoutId()==checkout&&file.getCheckoutStatus().getCheckoutVersion()==base,"Native conflict did not preserve local state");
320
378
  out.put("state","conflict");out.put("conflict",conflict.getMessage());
321
379
  }
322
380
  }
323
381
  }else{
324
- require(before.get("fingerprint").equals(text(q,"fingerprint")),"Prepared native publication changed");
325
382
  if(head!=base||head!=q.get("expectedVersion").getAsInt()){
326
383
  // A known pre-call head race is not an unknown check-in: none was issued.
327
384
  out.put("state","conflict");out.put("conflict","Shared head changed before native check-in");
@@ -333,7 +390,7 @@ public final class InsightNativeCheckout {
333
390
  permitMerge=false;
334
391
  try{file.checkin(new DefaultCheckinHandler("insight native "+request,true,false),MONITOR);out.put("state","checked_in");}
335
392
  catch(HeadChanged changed){
336
- require(before.equals(saved(file,owner))&&Arrays.stream(repository.getVersions("/",name)).noneMatch(v->("insight native "+request).equals(v.getComment())),"Check-in outcome is unknown");
393
+ require(file.getCheckoutStatus().getCheckoutId()==checkout&&file.getCheckoutStatus().getCheckoutVersion()==base&&Arrays.stream(repository.getVersions("/",name)).noneMatch(v->("insight native "+request).equals(v.getComment())),"Check-in outcome is unknown");
337
394
  out.put("state","conflict");out.put("conflict",changed.getMessage());
338
395
  }finally{permitMerge=true;}
339
396
  }
@@ -352,41 +409,50 @@ public final class InsightNativeCheckout {
352
409
  }
353
410
  }else if(operation.equals("release")){
354
411
  Path releaseFile=root.resolve("released.json");
355
- Map<String,Object> release=new LinkedHashMap<>(Map.of("checkoutId",q.get("checkoutId").getAsLong(),"version",q.get("verifiedVersion").getAsInt(),"fingerprint",text(q,"fingerprint"),
356
- "fileId",text(q,"fileId"),"savedFingerprint",authorized(q)));
412
+ Map<String,Object> release=new LinkedHashMap<>(Map.of("checkoutId",q.get("checkoutId").getAsLong(),"version",q.get("verifiedVersion").getAsInt(),
413
+ "fileId",text(q,"fileId")));
357
414
  if(file.isCheckedOut()){
358
- require(!q.has("opened")||q.has("openedVerified")&&q.get("openedVerified").getAsBoolean(),"Pristine-open proof is unverified; private work must be retained");
359
- require(file.getCheckoutStatus().getCheckoutVersion()==q.get("verifiedVersion").getAsInt()&&!file.canRecover(),"Unpublished native work must be retained");
360
- Object local=saved(file,owner).get("fingerprint");
361
- // Ghidra's own rewrite on open marks a checkout modified; only bytes the coordinator proved to hold no work may carry it.
362
- require(local.equals(authorized(q)),"Verified native buffers changed");
363
- require(q.has("opened")||!file.modifiedSinceCheckout(),"Unpublished native work must be retained");
364
- release.put("disposableBackups",releaseFiles(project,operations,q,owner,true));
415
+ // Ghidra's own answer decides: a checkout it reports modified, or with recoverable changes, holds work.
416
+ require(file.getCheckoutStatus().getCheckoutVersion()==q.get("verifiedVersion").getAsInt()&&!file.canRecover()&&!file.modifiedSinceCheckout(),"Unpublished native work must be retained");
417
+ release.put("disposableBackups",releaseFiles(project,operations,q,owner,true));release.put("localVersion",localVersion(file));
365
418
  release.put("state","release_intent");write(releaseFile,release);file.undoCheckout(false);
366
419
  }else{
367
420
  var prior=JsonParser.parseString(Files.readString(releaseFile)).getAsJsonObject();
368
421
  require(text(prior,"state").equals("release_intent")&&sameRelease(prior,q),"Release intent changed");
369
422
  boolean surviving=file.isHijacked();
370
- if(surviving)require(!file.canRecover()&&survivingRelease(prior,q,saved(file,owner)),"Unproved surviving native file must be retained");
423
+ if(surviving)require(!file.canRecover()&&survivingRelease(prior,q,file.getFileID(),localVersion(file)),"Unproved surviving native file must be retained");
371
424
  release.put("disposableBackups",releaseFiles(project,operations,q,owner,surviving));
372
425
  }
373
426
  require(Arrays.stream(repository.getCheckouts("/",name)).noneMatch(c->c.getCheckoutId()==q.get("checkoutId").getAsLong()),"Owned checkout remains");
374
427
  release.put("state","released");write(releaseFile,release);out.put("state","released");
428
+ project.close();project=null;repository.disconnect();server.disconnect();server=null;return out;
375
429
  }else if(operation.equals("drop")){
376
430
  require(false,"Verified release receipt differs");
431
+ }else if(operation.equals("prune-backups")){
432
+ // A checkout kept after its verified publication: Update/discard backups proved by this checkout's own
433
+ // journals hold no unpublished work. Anything else, including the program, is retained.
434
+ require(file.isCheckedOut()&&file.getCheckoutStatus().getCheckoutVersion()==q.get("verifiedVersion").getAsInt()&&!file.modifiedSinceCheckout()&&!file.canRecover(),
435
+ "Backup pruning requires the verified unchanged checkout");
436
+ List<String> pruned=new ArrayList<>();
437
+ for(var entry:backups(project,operations,q,owner).entrySet()){
438
+ DomainFile backup=project.getProjectData().getFile("/"+entry.getKey());
439
+ if(backup!=null&&!backup.isVersioned()&&!backup.isCheckedOut()&&saved(backup,owner).get("fingerprint").equals(entry.getValue())){backup.delete();pruned.add(entry.getKey());}
440
+ }
441
+ out.put("state","pruned");out.put("pruned",pruned);
377
442
  }else if(operation.equals("inspect")||operation.equals("fields")||operation.equals("export")){
378
443
  require(saved(file,owner).get("fingerprint").equals(text(q,"fingerprint")),"Saved native view changed");
379
444
  ProgramDB p=(ProgramDB)file.getDomainObject(CONSUMER,false,false,MONITOR);
380
445
  try{
381
446
  if(operation.equals("export")){
382
447
  Path target=Path.of(text(q,"output"));require(target.getParent().toRealPath().startsWith(root)&&!Files.exists(target),"Native export escaped owned storage");
383
- p.saveToPackedFile(target.toFile(),MONITOR);require(InsightNativeFingerprint.of(p).equals(text(q,"fingerprint")),"Native export changed saved buffers");
448
+ p.saveToPackedFile(target.toFile(),MONITOR);
384
449
  }else out.put("value",operation.equals("fields")?InsightSnapshotFields.inspect(p,q.getAsJsonArray("selectors")):InsightSnapshotInspect.inspect(p,q.getAsJsonObject("parameters")));
385
450
  }
386
451
  finally{p.release(CONSUMER);}
387
- }else require(operation.equals("create")||operation.equals("status"),"Unknown native operation");
452
+ }else require(operation.equals("create")||operation.equals("status")||operation.equals("unsaved"),"Unknown native operation");
388
453
  if(project!=null){
389
- out.put("saved",saved(file,owner));out.put("modified",file.modifiedSinceCheckout());out.put("fileId",file.getFileID());out.put("checkedOut",file.isCheckedOut());
454
+ if(!out.containsKey("saved"))out.put("saved",saved(file,owner));
455
+ out.put("modified",file.modifiedSinceCheckout());out.put("fileId",file.getFileID());out.put("checkedOut",file.isCheckedOut());
390
456
  out.put("recoverable",file.canRecover());
391
457
  var local=new TreeSet<String>();local(project.getProjectData().getRootFolder(),local);out.put("projectFiles",local);
392
458
  if(file.isCheckedOut()){out.put("checkoutId",file.getCheckoutStatus().getCheckoutId());out.put("baseVersion",file.getCheckoutStatus().getCheckoutVersion());}
@@ -394,8 +460,12 @@ public final class InsightNativeCheckout {
394
460
  history(repository,path,out);out.putIfAbsent("state","ready");out.put("guiWindows",java.awt.Window.getWindows().length);
395
461
  require(java.awt.Window.getWindows().length==0,"Unexpected GUI window");
396
462
  if(project!=null){project.close();project=null;}repository.disconnect();server.disconnect();server=null;
397
- output.println(GSON.toJson(out));System.exit(0);
398
- }catch(Throwable failure){failure.printStackTrace(System.err);if(project!=null)project.close();if(server!=null)server.disconnect();
399
- output.println(GSON.toJson(Map.of("state","unknown","diagnostic",failure.getClass().getSimpleName(),"reason",Objects.toString(failure.getMessage(),failure.toString()),"code",failure instanceof InsightNativeMigration.Required?"migration":"unknown")));System.exit(0);}
463
+ return out;
464
+ }catch(Throwable failure){failure.printStackTrace(System.err);
465
+ if(failure instanceof Error)poisoned=true;
466
+ try{if(project!=null)project.close();}catch(Throwable cleanup){poisoned=true;}
467
+ try{if(server!=null)server.disconnect();}catch(Throwable cleanup){poisoned=true;}
468
+ if(java.awt.Window.getWindows().length>0)poisoned=true;
469
+ return unknown(failure);}
400
470
  }
401
471
  }