@eyeauras/insight-cli 0.5.8 → 0.6.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 (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 +237 -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 +14 -0
  41. package/references/native/InsightNativeMigration.java +147 -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
@@ -0,0 +1,37 @@
1
+ import { Workspace, type GhidraContext, type ResearchTarget } from './workspace.js';
2
+ export declare function migrationProcessBlockers(directory: string): Promise<import("./tool-runtime/supervisor.js").ProcessRecord[]>;
3
+ export interface MigrationPort {
4
+ binding(): Promise<{
5
+ origin: string;
6
+ repository: string;
7
+ runtimeFingerprint: string;
8
+ }>;
9
+ probe(target: ResearchTarget, version?: number): Promise<Record<string, unknown>>;
10
+ write(request: Record<string, unknown>): Promise<Record<string, unknown>>;
11
+ /** Optional bounded batch of the 'snapshot' inspection; positions match the input. */
12
+ snapshots?(paths: string[]): Promise<Record<string, unknown>[]>;
13
+ verify(target: ResearchTarget, owner: Record<string, unknown>, candidate: Record<string, unknown>): Promise<void>;
14
+ adopt(target: string): Promise<void>;
15
+ closed(context: GhidraContext): Promise<boolean>;
16
+ convert(context: GhidraContext): Promise<void>;
17
+ knownCheckouts?(target: ResearchTarget, checkouts: unknown[]): Promise<boolean>;
18
+ recoverOpen?(context: GhidraContext): Promise<void>;
19
+ }
20
+ export declare function migrationDurable(path: string, value: unknown): Promise<void>;
21
+ /** Resume is the same explicit command. A native commit intent is reconciled, never replayed. */
22
+ export declare function migrateLegacy(workspace: Workspace, port: MigrationPort, selected: string | undefined, dryRun: boolean): Promise<{
23
+ state: string;
24
+ dryRun: boolean;
25
+ items: (Record<string, unknown> | {
26
+ target: string;
27
+ state: string;
28
+ reason: string;
29
+ contexts: never[];
30
+ } | {
31
+ target: string;
32
+ state: string;
33
+ contexts: never[];
34
+ reason?: undefined;
35
+ })[];
36
+ retainedContexts: number;
37
+ }>;
@@ -0,0 +1,237 @@
1
+ import { mkdir, readFile, open, rename } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { listProcesses } from './tool-runtime/supervisor.js';
5
+ import { fail, object, stable } from './model.js';
6
+ function pidAlive(pid) { try {
7
+ process.kill(pid, 0);
8
+ return true;
9
+ }
10
+ catch (error) {
11
+ if (error.code === 'ESRCH')
12
+ return false;
13
+ throw error;
14
+ } }
15
+ export async function migrationProcessBlockers(directory) {
16
+ const blockers = [];
17
+ for (const p of await listProcesses(directory, { tool: 'ghidra' })) {
18
+ if (p.role === 'server' || ['exited', 'failed'].includes(p.state))
19
+ continue;
20
+ // Storage migration preserves historical supervisor receipts. A moved receipt
21
+ // grants no process authority; only acknowledged direct completion plus absent
22
+ // child AND owner PIDs establishes quiescence here, without rewriting it.
23
+ if (p.phase === 'profile_binding_changed' && p.endedAt && p.outcome === 'completed' && p.exitCode === 0 && p.signal === null && !p.metadata && !('nativeChildren' in p) && Number.isSafeInteger(p.pid) && Number(p.pid) > 0 && Number.isSafeInteger(p.ownerPid) && p.ownerPid > 0) {
24
+ const saved = object(JSON.parse(await readFile(join(directory, 'runtime/processes', p.id + '.json'), 'utf8')));
25
+ if (saved.state === 'exited' && saved.phase === 'direct_child_only' && saved.pid === p.pid && saved.ownerPid === p.ownerPid && saved.endedAt === p.endedAt && !pidAlive(Number(p.pid)) && !pidAlive(p.ownerPid))
26
+ continue;
27
+ }
28
+ blockers.push(p);
29
+ }
30
+ return blockers;
31
+ }
32
+ export async function migrationDurable(path, value) {
33
+ const temp = path + '.new-' + randomUUID(), file = await open(temp, 'wx', 0o600);
34
+ try {
35
+ await file.writeFile(stable(value));
36
+ await file.sync();
37
+ }
38
+ finally {
39
+ await file.close();
40
+ }
41
+ await rename(temp, path);
42
+ }
43
+ async function read(path) { try {
44
+ return object(JSON.parse(await readFile(path, 'utf8')));
45
+ }
46
+ catch (e) {
47
+ if (e.code === 'ENOENT')
48
+ return;
49
+ throw e;
50
+ } }
51
+ function identity(target, model, value) {
52
+ if (value.state !== 'verified' || typeof value.fileId !== 'string' || typeof value.fingerprint !== 'string' || typeof value.programIdentity !== 'string' || !Number.isSafeInteger(value.version) || !Array.isArray(value.checkouts))
53
+ fail('binding', 'Migration readback is incomplete.');
54
+ if (model.settings.language && model.settings.language !== value.language || model.settings.compilerSpec && model.settings.compilerSpec !== value.compiler || model.settings.imageBase && model.settings.imageBase.replace(/^0x/, '').replace(/^0+(?=.)/, '') !== String(value.imageBase).replace(/^0x/, '').replace(/^0+(?=.)/, ''))
55
+ fail('binding', 'Migration load identity does not match the bound target settings.', { target: target.id });
56
+ if (value.engine !== '' && value.engine !== 'native-checkout-v1')
57
+ fail('migration', 'Unrecognized publication engine; the program is retained.');
58
+ }
59
+ /** Resume is the same explicit command. A native commit intent is reconciled, never replayed. */
60
+ export async function migrateLegacy(workspace, port, selected, dryRun) {
61
+ const targets = [];
62
+ if (selected)
63
+ targets.push(workspace.target(selected));
64
+ else
65
+ for (let offset = 0;; offset += 100) {
66
+ const page = workspace.targets(100, offset);
67
+ targets.push(...page);
68
+ if (page.length < 100)
69
+ break;
70
+ }
71
+ const contexts = [];
72
+ for (let offset = 0;; offset += 100) {
73
+ const sessions = workspace.sessions(100, offset);
74
+ for (const session of sessions)
75
+ for (let at = 0;; at += 100) {
76
+ const page = workspace.contexts(session.id, 100, at);
77
+ contexts.push(...page.filter(c => targets.some(t => t.id === c.target)));
78
+ if (page.length < 100)
79
+ break;
80
+ }
81
+ if (sessions.length < 100)
82
+ break;
83
+ }
84
+ if (selected && workspace.activePublication(selected))
85
+ fail('blocked', 'Publication must be reconciled before migration.');
86
+ for (const context of contexts)
87
+ if (!await port.closed(context))
88
+ fail('busy', 'Close the original context worker before migration.', { session: context.session, target: context.target });
89
+ const binding = await port.binding(), items = [];
90
+ for (const target of targets) {
91
+ if (workspace.activePublication(target.id)) {
92
+ items.push({ target: target.id, state: 'publication_unresolved', reason: 'Reconcile the retained publication, then repeat migration for this target.', contexts: [] });
93
+ continue;
94
+ }
95
+ let model;
96
+ try {
97
+ model = workspace.model(target.id);
98
+ }
99
+ catch (error) {
100
+ if (error.code !== 'coordinator.notFound')
101
+ throw error;
102
+ items.push({ target: target.id, state: 'no_ghidra_model', contexts: [] });
103
+ continue;
104
+ }
105
+ if (target.input.kind !== 'input' || target.input.sha256 !== target.binarySha256 || target.input.size !== target.size)
106
+ fail('binding', 'Migration input artifact and target source identity differ.');
107
+ await workspace.artifacts.verify(target.input);
108
+ const value = await port.probe(target);
109
+ if (value.state === 'absent') {
110
+ items.push({ target: target.id, state: 'no_server_model', reason: 'No canonical program exists in this profile repository; retained model/context data was not changed.', contexts: [] });
111
+ continue;
112
+ }
113
+ identity(target, model, value);
114
+ const root = join(workspace.directory, 'legacy-migrations', target.id), journalPath = join(root, 'migration.json');
115
+ let journal = await read(journalPath), owner = journal ? object(journal.owner) : undefined;
116
+ if (owner && (owner.origin !== binding.origin || owner.repository !== binding.repository || owner.target !== target.id || owner.sourceSha !== target.binarySha256 || owner.fileId !== value.fileId))
117
+ fail('binding', 'Retained migration identity changed; all data remains retained.');
118
+ const untouchedNative = value.engine === 'native-checkout-v1' && !journal;
119
+ const detached = contexts.filter(c => c.target === target.id && !c.nativeCheckout && c.workingSnapshot);
120
+ const item = { target: target.id, sourceSha: target.binarySha256, version: value.version, fileId: value.fileId, state: value.engine === '' ? 'legacy' : 'native', contexts: [] };
121
+ items.push(item);
122
+ if (untouchedNative) {
123
+ item.state = 'native_unchanged';
124
+ if (!detached.length)
125
+ continue;
126
+ }
127
+ if (!dryRun && (value.engine === '' || journal && journal.state !== 'complete')) {
128
+ if (!journal) {
129
+ if (value.checkouts.length)
130
+ fail('busy', 'Legacy model has existing checkouts; explicit reconciliation is required.');
131
+ await mkdir(root, { recursive: true, mode: 0o700 });
132
+ owner = { schema: 1, ...binding, target: target.id, sourceSha: target.binarySha256, path: '/' + target.id + '.bin', fileId: value.fileId, version: value.version, fingerprint: value.fingerprint, programIdentity: value.programIdentity, marker: 'insight migration ' + randomUUID() };
133
+ await migrationDurable(join(root, 'migration-owner.json'), owner);
134
+ journal = { schema: 1, state: 'reserved', owner };
135
+ await migrationDurable(journalPath, journal);
136
+ }
137
+ const bound = owner;
138
+ let native = await read(join(root, 'native-migration.json'));
139
+ if (!native || !['commit_intent', 'checked_in', 'released'].includes(String(native.phase))) {
140
+ if (value.engine !== '' || value.version !== bound.version || value.fingerprint !== bound.fingerprint || value.programIdentity !== bound.programIdentity)
141
+ fail('binding', 'Legacy baseline changed before migration.');
142
+ await port.write({ operation: 'run', root, owner: bound });
143
+ native = await read(join(root, 'native-migration.json'));
144
+ }
145
+ if (!native || !['commit_intent', 'checked_in', 'released'].includes(String(native.phase)) || typeof native.fingerprint !== 'string')
146
+ fail('unknown', 'Migration has no complete candidate/check-in evidence; retain its project and journal.');
147
+ await port.verify(target, bound, native);
148
+ await port.write({ operation: 'release', root, owner: bound, version: Number(bound.version) + 1, fingerprint: native.fingerprint });
149
+ journal = { ...journal, state: 'complete', publishedVersion: Number(bound.version) + 1, fingerprint: native.fingerprint };
150
+ await migrationDurable(journalPath, journal);
151
+ item.state = 'migrated';
152
+ item.version = Number(bound.version) + 1;
153
+ }
154
+ if (!dryRun && !untouchedNative)
155
+ await port.adopt(target.id);
156
+ // Packed programs lack native checkout ancestry/change sets. Exact equality can safely
157
+ // establish an unchanged context. Replaying scalar diagnostics cannot prove arbitrary work.
158
+ const accepted = [owner, journal ? { fingerprint: journal.fingerprint, programIdentity: owner?.programIdentity } : undefined, value].filter(v => v && typeof v.fingerprint === 'string');
159
+ const revisions = new Map(), inspections = new Map();
160
+ const exact = async (revision) => {
161
+ if (!revisions.has(revision))
162
+ revisions.set(revision, await port.probe(target, revision).catch(() => undefined));
163
+ return revisions.get(revision);
164
+ };
165
+ if (port.snapshots) {
166
+ const pending = [...new Map(detached.map(c => [c.workingSnapshot.id, c.workingSnapshot])).values()];
167
+ for (let at = 0; at < pending.length; at += 8) {
168
+ const page = pending.slice(at, at + 8), paths = [];
169
+ for (const s of page)
170
+ paths.push(await workspace.artifacts.verify(s));
171
+ const values = await port.snapshots(paths);
172
+ if (values.length !== page.length)
173
+ fail('partial', 'Detached snapshot inspection is incomplete.');
174
+ page.forEach((s, i) => inspections.set(s.id, values[i]));
175
+ }
176
+ }
177
+ for (const original of detached) {
178
+ const snapshot = original.workingSnapshot, retained = await workspace.artifacts.verify(snapshot);
179
+ const record = { session: original.session, target: target.id, snapshot, state: 'retained', reason: 'Packed detached work has no provable native checkout ancestry/change sets; native conversion is refused. No scalar or script replay was performed.' };
180
+ const observed = inspections.get(snapshot.id) ?? await port.write({ operation: 'snapshot', snapshot: retained });
181
+ const matches = (v) => v !== undefined && observed.fingerprint === v.fingerprint && observed.programIdentity === v.programIdentity;
182
+ const clean = !original.scalars.length && !original.complexChanges.length && !original.debugger?.traces.length && !original.debugger?.connected &&
183
+ original.state !== 'needs_recovery' && !workspace.unresolved(original).length && !workspace.uncertainOutcome(original);
184
+ let equal = accepted.some(matches);
185
+ if (!equal && clean && original.baseRevision && original.baseRevision < Number(value.version))
186
+ equal = matches(await exact(original.baseRevision));
187
+ if (observed.sourceSha !== target.binarySha256) {
188
+ record.reason = 'Detached snapshot source SHA256 differs from its target; snapshot and context retained.';
189
+ }
190
+ else if (equal && clean) {
191
+ record.state = dryRun ? 'convertible_unchanged' : 'converted_unchanged';
192
+ record.reason = 'Complete saved buffers equal a verified server version; the next open creates its native checkout.';
193
+ if (!dryRun) {
194
+ await mkdir(root, { recursive: true, mode: 0o700 });
195
+ await migrationDurable(join(root, original.id + '-detached.json'), { schema: 1, original, observed });
196
+ await port.convert(original);
197
+ }
198
+ }
199
+ else {
200
+ record.observed = observed;
201
+ record.baseRevision = original.baseRevision ?? null;
202
+ }
203
+ item.contexts.push(record);
204
+ }
205
+ if (dryRun) {
206
+ for (const original of contexts.filter(c => c.target === target.id && !c.nativeCheckout && !c.workingSnapshot && !c.scalars.length && !c.complexChanges.length && !c.debugger?.traces.length)) {
207
+ const requests = workspace.unresolved(original);
208
+ if (!requests.length)
209
+ continue;
210
+ item.contexts.push({ session: original.session, target: target.id, state: requests.every(q => q.operation === 'ghidra.open') && !value.checkouts.length ? 'would_recover_open' : 'retained', requests: requests.map(q => ({ id: q.id, operation: q.operation })), reason: 'Recovery requires a verified native model and proof that no private work or uncertain checkout exists.' });
211
+ }
212
+ }
213
+ if (!dryRun && !untouchedNative) {
214
+ const current = await port.probe(target);
215
+ if (current.engine !== 'native-checkout-v1')
216
+ fail('migration', 'Model is still legacy; no open request was recovered.');
217
+ for (const original of contexts.filter(c => c.target === target.id && !c.nativeCheckout && !c.workingSnapshot && !c.scalars.length && !c.complexChanges.length && !c.debugger?.traces.length && workspace.unresolved(c).length)) {
218
+ // Any server checkout could belong to an uncertain historical open; refuse recovery.
219
+ if (current.checkouts.length && !await port.knownCheckouts?.(target, current.checkouts)) {
220
+ item.contexts.push({ session: original.session, state: 'retained', reason: 'Server checkouts prevent proving that the historical open did no work.' });
221
+ continue;
222
+ }
223
+ if (workspace.unresolved(original).every(q => q.operation === 'ghidra.open')) {
224
+ if (workspace.unresolved(original).length)
225
+ await port.recoverOpen?.(original);
226
+ const recovered = workspace.recoverMigrationOpen(original);
227
+ if (recovered)
228
+ item.contexts.push({ session: original.session, state: 'open_recovered', requests: recovered });
229
+ }
230
+ else
231
+ item.contexts.push({ session: original.session, state: 'retained', reason: 'Unresolved operations other than ghidra.open are retained; migration cannot establish their effects.' });
232
+ }
233
+ await migrationDurable(join(root, 'contexts.json'), { schema: 1, target: target.id, contexts: item.contexts });
234
+ }
235
+ }
236
+ return { state: dryRun ? 'planned' : 'complete', dryRun, items, retainedContexts: items.flatMap(x => x.contexts).filter(x => x.state === 'retained').length };
237
+ }
@@ -20,19 +20,20 @@ export declare class Lifecycle {
20
20
  }[];
21
21
  externalRequestsTruncated: boolean;
22
22
  ghidra: {
23
- syncPolicy: import("./workspace.js").SyncPolicy;
24
- state: "opening" | "ready" | "stopped" | "needs_recovery";
25
- baseRevision: string | undefined;
26
23
  sharedRevision: string | undefined;
27
24
  pendingChanges: number;
28
25
  mergeState: string;
29
- conflicts: {
26
+ conflicts: ({
30
27
  address: string;
31
28
  field: "function.name" | "comment.eol" | "comment.pre" | "comment.post" | "comment.plate" | "comment.repeatable";
32
29
  original: string | null;
33
30
  local: string | null;
34
31
  shared: string | null;
35
- }[];
32
+ } | {
33
+ request: string;
34
+ message: string;
35
+ engine: string;
36
+ })[];
36
37
  unresolvedRequests: {
37
38
  operation: string;
38
39
  state: import("./workspace.js").RequestState;
@@ -40,6 +41,16 @@ export declare class Lifecycle {
40
41
  detail?: {} | undefined;
41
42
  id: string;
42
43
  }[];
44
+ checkout?: {
45
+ id: number;
46
+ fileId: string;
47
+ baseRevision: string | undefined;
48
+ state: "active" | "verified" | "dropped";
49
+ } | undefined;
50
+ syncPolicy: import("./workspace.js").SyncPolicy;
51
+ state: "opening" | "ready" | "stopped" | "needs_recovery";
52
+ baseRevision: string | undefined;
53
+ engine: string;
43
54
  };
44
55
  session: string;
45
56
  target: string;
@@ -39,6 +39,13 @@ export class Lifecycle {
39
39
  ...(operation === 'close' ? [['tools', 'processes', '--tool', 'ghidra', '--session', selected.session, '--target', selected.target]] : [['ghidra', 'open', '--session', selected.session, '--target', selected.target]])]
40
40
  });
41
41
  }
42
+ const settled = this.workspace.context(selected);
43
+ if (operation === 'close' && settled.nativeCheckout?.state === 'dropped' && !this.workspace.unresolved(selected).length) {
44
+ const result = { ...selected, state: 'closed', pendingChanges: 0 };
45
+ this.workspace.startRequest(request.id, { kind: 'close', generation: settled.generation, workingSnapshot: settled.workingSnapshot });
46
+ this.workspace.completeSavedRequest(selected, request.id, settled.generation, { state: 'stopped' }, result);
47
+ return result;
48
+ }
42
49
  backend ??= await this.backend();
43
50
  const unresolved = this.workspace.unresolved(selected);
44
51
  const closingExternal = operation === 'close' && unresolved.length > 0 && unresolved.every(intent => ['debugger', 'ui'].includes(String(object(intent.execution ?? {}).kind)));
@@ -47,10 +54,19 @@ export class Lifecycle {
47
54
  await backend.open(selected);
48
55
  const before = this.workspace.context(selected);
49
56
  this.workspace.startRequest(request.id, { kind: operation, generation: before.generation, workingSnapshot: before.workingSnapshot });
50
- let savedSnapshot;
57
+ let savedSnapshot, checkout;
51
58
  try {
52
- if (operation === 'close' && !alreadyEnded)
59
+ if (operation === 'close' && !alreadyEnded) {
53
60
  await backend.close(selected);
61
+ // The close is already complete. An unproved release only keeps the saved checkout.
62
+ if (!unresolved.length && backend.releaseUnchanged)
63
+ try {
64
+ checkout = await backend.releaseUnchanged(selected) ? 'released' : 'retained';
65
+ }
66
+ catch {
67
+ checkout = 'retained';
68
+ }
69
+ }
54
70
  const current = this.workspace.context(selected), snapshot = operation === 'save' ? await backend.saved(selected) : current.workingSnapshot;
55
71
  if (!snapshot)
56
72
  fail('partial', 'Lifecycle operation did not retain its private snapshot.');
@@ -71,7 +87,7 @@ export class Lifecycle {
71
87
  this.workspace.recordRequest(intent.id, 'failed', { ...selected, state: 'disconnected', outcome: 'unknown', operation: object(intent.execution ?? {}).operation });
72
88
  }
73
89
  const retained = this.workspace.context(selected);
74
- const result = { ...selected, state: operation === 'save' ? 'saved' : 'closed', pendingChanges: retained.scalars.length + retained.complexChanges.length };
90
+ const result = { ...selected, state: operation === 'save' ? 'saved' : 'closed', ...(checkout ? { checkout } : {}), pendingChanges: retained.scalars.length + retained.complexChanges.length };
75
91
  this.workspace.completeSavedRequest(selected, request.id, retained.generation, { workingSnapshot: operation === 'close' ? retained.workingSnapshot ?? snapshot : snapshot, ...(operation === 'close' ? { state: 'stopped',
76
92
  ...(retained.debugger ? { debugger: { ...retained.debugger, connected: false, traces: retained.debugger.traces.map(trace => ({ ...trace, connected: false })) } } : {}) } : {}) }, result);
77
93
  return result;
@@ -85,19 +101,40 @@ export class Lifecycle {
85
101
  async discard(selected, callerId) {
86
102
  const reserved = this.workspace.reserveRequest(selected, 'ghidra.changes.discard', {}, callerId);
87
103
  return this.research.ordered(selected, async () => {
88
- const request = this.workspace.request(reserved.request.id);
104
+ let request = this.workspace.request(reserved.request.id), backend;
105
+ if (reserved.replay && ['running', 'unknown'].includes(request.state)) {
106
+ backend = await this.backend();
107
+ await this.research.reconcileRequests(selected, backend);
108
+ request = this.workspace.request(request.id);
109
+ }
89
110
  if (reserved.replay && request.state !== 'accepted') {
90
111
  if (request.state === 'applied')
91
112
  return request.result;
92
113
  fail('unknown', 'Local discard outcome is retained; continue the context before retrieving it.', request.result);
93
114
  }
94
- const backend = await this.backend();
115
+ backend ??= await this.backend();
95
116
  await backend.open(selected);
96
117
  if (this.workspace.context(selected).debugger?.connected)
97
118
  fail('busy', 'Close the live debugger context before discarding static program edits.');
98
119
  // Resource save/release precedes the local atomic switch, as with mode preparation.
99
120
  await backend.close(selected);
100
121
  const context = this.workspace.context(selected);
122
+ if (context.nativeCheckout) {
123
+ if (!backend.discardNative)
124
+ fail('configuration', 'Native discard is required; a detached snapshot switch is disabled.');
125
+ this.workspace.startRequest(request.id, { kind: 'native-discard', generation: context.generation, checkout: context.nativeCheckout, discardedChanges: context.scalars.length + context.complexChanges.length });
126
+ try {
127
+ const discarded = await backend.discardNative(selected, request.id), current = this.workspace.context(selected);
128
+ const result = { ...selected, state: 'discarded', discardedChanges: context.scalars.length + context.complexChanges.length, pendingChanges: 0,
129
+ baseRevision: 'R' + discarded.baseRevision, ...(discarded.retainedKeepFile ? { retainedKeepFile: discarded.retainedKeepFile } : {}) };
130
+ this.workspace.completeSavedRequest(selected, request.id, current.generation, {}, result);
131
+ return result;
132
+ }
133
+ catch (error) {
134
+ this.workspace.recordRequest(request.id, 'unknown', { ...selected, state: 'unknown' });
135
+ throw error;
136
+ }
137
+ }
101
138
  if (!context.baseSnapshot || !context.workingSnapshot)
102
139
  fail('binding', 'Discard requires retained base and private snapshots.');
103
140
  await this.workspace.artifacts.verify(context.baseSnapshot);
@@ -150,7 +187,7 @@ export class Lifecycle {
150
187
  }
151
188
  export function lifecycleCommands(service, runtimeStatus) {
152
189
  return [command('changes', 'Manage unpublished edits in the selected context', [
153
- command('discard', 'Save a retained copy, then restore the opening base without publication', ({ options: o }, c) => service(c).discard(scope(o), o.requestId === undefined ? undefined : id(o.requestId)), { permission: 'Destructive', options: [...selectedOptions, { flags: '--request-id <id>', description: 'Retrieve the same local discard result' }] })
190
+ command('discard', 'Retain native keep data, discard private edits and check out the current server version', ({ options: o }, c) => service(c).discard(scope(o), o.requestId === undefined ? undefined : id(o.requestId)), { permission: 'Destructive', options: [...selectedOptions, { flags: '--request-id <id>', description: 'Retrieve the same local discard result' }] })
154
191
  ]),
155
192
  command('save-all', 'Save every Ghidra context in the explicit session; outcomes are per context', ({ options: o }, c) => service(c).saveAll(id(o.session), o.requestId === undefined ? undefined : id(o.requestId)), { permission: Permission.Update, options: [{ flags: '--session <id>', description: 'Explicit session whose contexts are saved', required: true }, { flags: '--request-id <id>', description: 'Retrieve the recorded session save outcomes' }] }),
156
193
  command('status', 'Inspect the installed runtime, or verify a selected context', ({ options: o }, c) => {
@@ -1,5 +1,5 @@
1
1
  import type { ScalarChange } from './workspace.js';
2
- export declare const fieldKey: (change: Pick<ScalarChange, "address" | "field">) => string;
2
+ export { fieldKey } from './model.js';
3
3
  export interface SharedScalar {
4
4
  value: string | null;
5
5
  compatible: boolean;
package/dist/src/merge.js CHANGED
@@ -1,5 +1,5 @@
1
- import { fail } from './model.js';
2
- export const fieldKey = (change) => change.address + '@' + change.field;
1
+ import { fail, fieldKey } from './model.js';
2
+ export { fieldKey } from './model.js';
3
3
  /** Three-way decisions only; backend effects happen after the entire plan passes. */
4
4
  export function scalarMerge(changes, complex, baseRevision, sharedRevision, values) {
5
5
  if (sharedRevision < baseRevision)
@@ -72,3 +72,8 @@ export declare function version(value: unknown): number;
72
72
  export declare function identity(value: unknown): Identity;
73
73
  export declare function assertIdentity(actual: Identity, expected: Identity): void;
74
74
  export declare function finding(value: unknown): Finding;
75
+ /** Diagnostic field identity; no merge policy. */
76
+ export declare const fieldKey: (change: {
77
+ address: string;
78
+ field: string;
79
+ }) => string;
package/dist/src/model.js CHANGED
@@ -65,3 +65,5 @@ export function finding(value) {
65
65
  ...(o.resolves === undefined ? {} : { resolves: id(o.resolves) }),
66
66
  };
67
67
  }
68
+ /** Diagnostic field identity; no merge policy. */
69
+ export const fieldKey = (change) => change.address + '@' + change.field;
@@ -9,6 +9,7 @@ import { promisify } from 'node:util';
9
9
  import { fail, stable, text } from './model.js';
10
10
  import { managedExtensions, extensionJvmArguments } from './extensions.js';
11
11
  import { runtimeValues, runtimeSelection } from './runtime-selection.js';
12
+ import { nativeMergeSources } from './native-merge-patches.js';
12
13
  export const pinnedMcpJar = 'f4a9272e911466ed774c8cf73bc1adf1daef6009d895fda57aa0b28522fcdf32';
13
14
  export const packagedMcpJar = fileURLToPath(new URL('../../runtime/GhidraMCP-7.0.0.jar', import.meta.url));
14
15
  /** Ghidra has its own cache/settings overrides in addition to Java's home/tmp properties. */
@@ -140,7 +141,8 @@ export async function nativeHelpers(directory, inputs, c) {
140
141
  const hashes = [];
141
142
  for (const name of names)
142
143
  hashes.push(await sha(join(sources, name)));
143
- const key = createHash('sha256').update(stable([inputs.fingerprint, names, hashes])).digest('hex');
144
+ const mergeSources = await nativeMergeSources(inputs.ghidraHome);
145
+ const key = createHash('sha256').update(stable([inputs.fingerprint, names, hashes, mergeSources.map(({ name, sha256 }) => ({ name, sha256 }))])).digest('hex');
144
146
  const parent = join(directory, 'native-helpers');
145
147
  await mkdir(parent, { recursive: true, mode: 0o700 });
146
148
  const classes = join(parent, key);
@@ -155,7 +157,15 @@ export async function nativeHelpers(directory, inputs, c) {
155
157
  const temporary = join(parent, 'compiling-' + randomUUID());
156
158
  await mkdir(temporary, { mode: 0o700 });
157
159
  try {
158
- const executable = join(dirname(inputs.java), 'javac' + (process.platform === 'win32' ? '.exe' : '')), args = ['-proc:none', '-cp', inputs.classpath, '-d', temporary, ...names.map(name => join(sources, name))];
160
+ const patched = [];
161
+ for (const item of mergeSources) {
162
+ const path = join(temporary, 'sources', item.name);
163
+ await mkdir(dirname(path), { recursive: true });
164
+ await writeFile(path, item.source, { flag: 'wx' });
165
+ patched.push(path);
166
+ }
167
+ await writeFile(join(temporary, 'native-merge-provenance.json'), stable(mergeSources.map(({ source, ...item }) => item)), { flag: 'wx' });
168
+ const executable = join(dirname(inputs.java), 'javac' + (process.platform === 'win32' ? '.exe' : '')), args = ['-proc:none', '-cp', inputs.classpath, '-d', temporary, ...names.map(name => join(sources, name)), ...patched];
159
169
  if (c)
160
170
  await runTool(c, { tool: 'ghidra', role: 'compile-helpers', installation: inputs.fingerprint, executable, arguments: args, timeoutMs: 60000, maxOutputBytes: 262144 });
161
171
  else
@@ -0,0 +1,6 @@
1
+ export declare function nativeMergeSources(home: string): Promise<{
2
+ name: "ghidra/app/merge/listing/ListingMergeManager.java" | "ghidra/framework/data/GhidraFileData.java" | "ghidra/app/merge/listing/ProgramContextMergeManager.java" | "ghidra/app/merge/listing/ExternalFunctionMerger.java" | "ghidra/app/merge/listing/AbstractFunctionMerger.java" | "ghidra/app/merge/memory/MemoryMergeManager.java";
3
+ upstreamSha256: "3b6ce2e22fd414d6cc63ce2a3be6c533f13524b9513767b932f6da8f2d9326d6" | "aafc9c66f42ce12c3f0e7847529d982545b4f760dd570db482133578e9d531e2" | "f2a57f5100de73f980fab99a8ba1d79cf8ecee6257ba32686b78f3512e4c67bb" | "76aa623434213057e936c8abef1539844c41c30361891b4398665d673574f519" | "9e4ea08167344d8527701dac0ed1607fd68e0670849c8b453463fcf8fccb4fb5" | "28b1fd583e694a7b48d37dcdebdae6674990ee0c2b3dbf3d44a726da33dd1129";
4
+ sha256: string;
5
+ source: string;
6
+ }[]>;
@@ -0,0 +1,100 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { join } from 'node:path';
3
+ import * as zip from 'yauzl';
4
+ import { fail } from './model.js';
5
+ /** Version-pinned upstream display/entry adapters plus the separately proven comment fix.
6
+ * Ghidra still creates/orders every resolver. No coordinator object merge lives here. */
7
+ const pins = [
8
+ ['Features/Base', 'ghidra/app/merge/listing/ListingMergeManager.java', '3b6ce2e22fd414d6cc63ce2a3be6c533f13524b9513767b932f6da8f2d9326d6'],
9
+ ['Framework/Project', 'ghidra/framework/data/GhidraFileData.java', 'aafc9c66f42ce12c3f0e7847529d982545b4f760dd570db482133578e9d531e2'],
10
+ ['Features/Base', 'ghidra/app/merge/listing/ProgramContextMergeManager.java', 'f2a57f5100de73f980fab99a8ba1d79cf8ecee6257ba32686b78f3512e4c67bb'],
11
+ ['Features/Base', 'ghidra/app/merge/listing/ExternalFunctionMerger.java', '76aa623434213057e936c8abef1539844c41c30361891b4398665d673574f519'],
12
+ ['Features/Base', 'ghidra/app/merge/listing/AbstractFunctionMerger.java', '9e4ea08167344d8527701dac0ed1607fd68e0670849c8b453463fcf8fccb4fb5'],
13
+ ['Features/Base', 'ghidra/app/merge/memory/MemoryMergeManager.java', '28b1fd583e694a7b48d37dcdebdae6674990ee0c2b3dbf3d44a726da33dd1129'],
14
+ ];
15
+ async function entry(archive, name) {
16
+ const file = await new Promise((ok, bad) => zip.open(archive, { lazyEntries: true }, (e, z) => e ? bad(e) : ok(z)));
17
+ return new Promise((ok, bad) => {
18
+ let found = false;
19
+ const failed = (error) => { file.close(); bad(error); };
20
+ file.on('error', failed);
21
+ file.on('end', () => { if (!found)
22
+ failed(new Error('Pinned native source is absent')); });
23
+ file.on('entry', (item) => {
24
+ if (item.fileName !== name) {
25
+ file.readEntry();
26
+ return;
27
+ }
28
+ found = true;
29
+ if (item.uncompressedSize > 2 * 1024 * 1024) {
30
+ failed(new Error('Native source exceeds bound'));
31
+ return;
32
+ }
33
+ file.openReadStream(item, (error, stream) => {
34
+ if (error) {
35
+ failed(error);
36
+ return;
37
+ }
38
+ const chunks = [];
39
+ stream.on('error', failed);
40
+ stream.on('data', (bytes) => chunks.push(bytes));
41
+ stream.on('end', () => { file.close(); ok(Buffer.concat(chunks).toString('utf8')); });
42
+ });
43
+ });
44
+ file.readEntry();
45
+ });
46
+ }
47
+ function replace(source, before, after, count = 1) {
48
+ if (source.split(before).length !== count + 1)
49
+ fail('binding', 'Pinned native merge source seam changed.');
50
+ return source.replaceAll(before, after);
51
+ }
52
+ export async function nativeMergeSources(home) {
53
+ const result = [];
54
+ for (const [module, name, pin] of pins) {
55
+ const archive = join(home, 'Ghidra', module, 'lib', module.split('/')[1] + '-src.zip');
56
+ let source = await entry(archive, name);
57
+ if (createHash('sha256').update(source).digest('hex') !== pin)
58
+ fail('binding', 'Native merge requires the pinned Ghidra 12.1.2 sources.');
59
+ if (name.endsWith('/ListingMergeManager.java')) {
60
+ source = replace(source, 'mergePanel.setTopComponent(conflictInfoPanel);', 'if (mergePanel != null) mergePanel.setTopComponent(conflictInfoPanel);');
61
+ for (const method of ['setListingViewsToEntireProgram', 'emptyListingViewForPrograms'])
62
+ source = replace(source, 'private void ' + method + '() {', 'private void ' + method + '() {\n\t\tif (mergePanel == null) return;');
63
+ }
64
+ else if (name.endsWith('/GhidraFileData.java'))
65
+ source = replace(source, 'if (SystemUtilities.isInHeadlessMode()) {', 'if (false /* Insight native headless merge adapter installed */) {', 2);
66
+ else if (name.endsWith('/ProgramContextMergeManager.java'))
67
+ source = replace(source, 'mergePanel.setTopComponent(conflictInfoPanel);', 'if (mergePanel != null) mergePanel.setTopComponent(conflictInfoPanel);');
68
+ else if (name.endsWith('/ExternalFunctionMerger.java'))
69
+ for (const panel of ['conflictInfoPanel', 'listingConflictInfoPanel'])
70
+ source = replace(source, 'listingMergePanel.setTopComponent(' + panel + ');', 'if (listingMergePanel != null) listingMergePanel.setTopComponent(' + panel + ');');
71
+ else if (name.endsWith('/AbstractFunctionMerger.java'))
72
+ source = replace(source, 'final Address entryPt, final TaskMonitor monitor) {\n\n\t\tif (conflictPanel == null) {', 'final Address entryPt, final TaskMonitor monitor) {\n\n\t\tif (java.awt.GraphicsEnvironment.isHeadless()) {\n\t\t\tmergeManager.showListingMergePanel(entryPt);\n\t\t\tthrow new IllegalStateException("Headless function conflict was not rejected");\n\t\t}\n\n\t\tif (conflictPanel == null) {');
73
+ else {
74
+ source = replace(source, 'if (myComment != null && !myComment.equals(origBlocks[index].getComment()) ||\n\t\t\t\t(myComment == null)) {', 'if (!java.util.Objects.equals(myComment, origBlocks[index].getComment())) {');
75
+ const start = source.indexOf('\tprivate boolean isCommentConflict(int index) {');
76
+ if (start < 0)
77
+ fail('binding', 'Pinned native memory conflict source changed.');
78
+ let depth = 0, end = 0;
79
+ for (let n = source.indexOf('{', start); n < source.length; n++) {
80
+ if (source[n] === '{')
81
+ depth++;
82
+ if (source[n] === '}' && --depth === 0) {
83
+ end = n + 1;
84
+ break;
85
+ }
86
+ }
87
+ if (!end)
88
+ fail('binding', 'Pinned native memory conflict source changed.');
89
+ source = source.slice(0, start) + `\tprivate boolean isCommentConflict(int index) {
90
+ String original = origBlocks[index].getComment();
91
+ String latest = latestBlocks[index].getComment();
92
+ String mine = myBlocks[index].getComment();
93
+ return !java.util.Objects.equals(mine, original) &&
94
+ !java.util.Objects.equals(latest, original) && !java.util.Objects.equals(mine, latest);
95
+ }` + source.slice(end);
96
+ }
97
+ result.push({ name, upstreamSha256: pin, sha256: createHash('sha256').update(source).digest('hex'), source });
98
+ }
99
+ return result;
100
+ }
@@ -10,13 +10,19 @@ export declare class InsightCommandError extends Error {
10
10
  data?: unknown;
11
11
  });
12
12
  }
13
+ export interface InsightTransportTermination {
14
+ readonly exitCode: number | null;
15
+ readonly signal: NodeJS.Signals | null;
16
+ readonly reason?: 'host_incompatible' | 'host_closing' | 'host_startup_timeout' | 'invalid_rpc_launch' | 'host_build_invalid' | 'ipc_disconnected';
17
+ }
13
18
  export declare class InsightTransportError extends Error {
14
19
  readonly dispatched: boolean;
15
- constructor(message: string, dispatched: boolean);
20
+ readonly termination?: InsightTransportTermination | undefined;
21
+ constructor(message: string, dispatched: boolean, termination?: InsightTransportTermination | undefined);
16
22
  }
17
23
  export interface InsightConnectionOptions {
18
24
  executable: string;
19
- /** For example [installedBin] with executable: process.execPath. No shell is used. */
25
+ /** For example [installedBin] after selecting the shared Node runtime. No shell is used. */
20
26
  arguments?: readonly string[];
21
27
  cwd?: string;
22
28
  env?: NodeJS.ProcessEnv;