@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
@@ -21,6 +21,8 @@ interface LocalServer extends ServerBinding {
21
21
  phase: 'seeded' | 'initialized' | 'running' | 'stopped';
22
22
  pid?: number;
23
23
  }
24
+ /** A proven different process birth retires only the saved receipt, never the PID. */
25
+ export declare function retireReusedServer(directory: string, control: string, local: LocalServer): Promise<boolean>;
24
26
  /** Own local startup; external profiles connect without taking ownership of their server. */
25
27
  export declare class GhidraServer {
26
28
  readonly directory: string;
@@ -36,6 +38,9 @@ export declare class GhidraServer {
36
38
  private run;
37
39
  credentials(binding: ServerBinding, role: 'reader' | 'publisher'): Promise<Record<string, string>>;
38
40
  fields(snapshot: string, selectors: string): Promise<Record<string, unknown>>;
41
+ nativeCheckout(binding: ServerBinding, request: Record<string, unknown>): Promise<Record<string, unknown>>;
42
+ nativeMigration(binding: ServerBinding, request: Record<string, unknown>): Promise<Record<string, unknown>>;
43
+ nativeRead(binding: ServerBinding, request: Record<string, unknown>): Promise<Record<string, unknown>>;
39
44
  inspect(snapshot: string, request: string): Promise<Record<string, unknown>>;
40
45
  sdkFile(operation: string, p: Record<string, unknown>): Promise<Record<string, unknown>>;
41
46
  traceInspect(snapshot: string): Promise<Record<string, unknown>>;
@@ -46,7 +51,6 @@ export declare class GhidraServer {
46
51
  initialRecovery(binding: ServerBinding, root: string, fingerprint: string, receipt?: string): Promise<Record<string, unknown>>;
47
52
  initialImport(root: string): Promise<Record<string, unknown>>;
48
53
  initialPublication(binding: ServerBinding, root: string, operation?: 'stage' | 'verify-stage' | 'promote' | 'verify'): Promise<Record<string, unknown>>;
49
- publish(binding: ServerBinding, path: string, snapshot: string, expected: number, request: string, journal: string, sourceSha: string): Promise<Record<string, unknown>>;
50
54
  recoverPublication(binding: ServerBinding, path: string, snapshot: string, expected: number, request: string, journal: string, sourceSha: string): Promise<Record<string, unknown>>;
51
55
  private authority;
52
56
  ensure(): Promise<ServerBinding>;
@@ -1,6 +1,7 @@
1
1
  import { ghidraBudget } from './budgets.js';
2
2
  import { CliError } from '@eyeauras/cli-factory';
3
- import { launchProcess, terminateProcess } from './tool-runtime/supervisor.js';
3
+ import { launchProcess, terminateProcess, processStatus } from './tool-runtime/supervisor.js';
4
+ import { processIdentity } from './tool-runtime/identity.js';
4
5
  import { runTool } from './tool-runtime/run.js';
5
6
  import { randomUUID, randomBytes, createHash } from 'node:crypto';
6
7
  import { readFile, mkdir, open, rename, readdir, stat, chmod, realpath } from 'node:fs/promises';
@@ -21,6 +22,23 @@ const live = (pid) => {
21
22
  throw error;
22
23
  }
23
24
  };
25
+ /** A proven different process birth retires only the saved receipt, never the PID. */
26
+ export async function retireReusedServer(directory, control, local) {
27
+ if (!local.pid || !local.toolProcessId)
28
+ return false;
29
+ const row = await processStatus(control, local.toolProcessId);
30
+ if (row.phase !== 'pid_identity_changed' || row.tool !== 'ghidra' || row.role !== 'server' || row.pid !== local.pid || !row.strongIdentity || typeof row.identity !== 'string' || typeof row.metadata?.serverDirectory !== 'string' || await realpath(row.metadata.serverDirectory) !== await realpath(directory))
31
+ return false;
32
+ const observed = await processIdentity(local.pid);
33
+ if (!observed?.strong || observed.birth === row.identity)
34
+ return false;
35
+ await durable(join(directory, 'server', 'retired-local-' + randomUUID() + '.json'), { schema: 1, reason: 'Original server birth is no longer alive; reused PID was not signaled.', local: { ...local }, process: row, observedBirth: observed.birth });
36
+ local.phase = 'stopped';
37
+ delete local.pid;
38
+ delete local.toolProcessId;
39
+ await durable(join(directory, 'server', 'local.json'), local);
40
+ return true;
41
+ }
24
42
  async function durable(path, value) {
25
43
  const temporary = path + '.new-' + randomUUID(), handle = await open(temporary, 'wx', 0o600);
26
44
  try {
@@ -86,6 +104,8 @@ export class GhidraServer {
86
104
  catch {
87
105
  fail('malformed', 'Native server operation returned malformed content.');
88
106
  }
107
+ if (result.state === 'unknown' && typeof result.reason === 'string')
108
+ fail(result.code === 'migration' ? 'migration' : 'unknown', result.reason, { diagnostic: result.diagnostic });
89
109
  if (result.error || result.state === 'failed')
90
110
  fail('authorization', 'Native server operation did not establish its outcome.');
91
111
  return result;
@@ -97,9 +117,30 @@ export class GhidraServer {
97
117
  GHIDRA_SERVER_PASSWORD: await this.c.secrets.require(role === 'reader' ? binding.readerSecret : binding.publisherSecret) };
98
118
  }
99
119
  async fields(snapshot, selectors) {
100
- return this.run('snapshot-fields', 'InsightSnapshotFields', [snapshot, selectors]);
120
+ return this.run('snapshot-fields', 'insight.nativecheckout.InsightSnapshotFields', [snapshot, selectors]);
121
+ }
122
+ async nativeCheckout(binding, request) {
123
+ const root = join(this.root(), 'native-calls', randomUUID());
124
+ await mkdir(root, { recursive: true, mode: 0o700 });
125
+ const input = join(root, 'request.json');
126
+ await durable(input, request);
127
+ return this.run('native-checkout', 'InsightNativeCheckout', [input], await this.credentials(binding, 'publisher'), undefined, [0], ghidraBudget(this.c.profile.values, 'save'));
101
128
  }
102
- async inspect(snapshot, request) { return this.run('snapshot-inspect', 'InsightSnapshotInspect', [snapshot, request]); }
129
+ async nativeMigration(binding, request) {
130
+ const root = join(this.root(), 'migration-calls', randomUUID());
131
+ await mkdir(root, { recursive: true, mode: 0o700 });
132
+ const input = join(root, 'request.json');
133
+ await durable(input, request);
134
+ return this.run('native-migration', 'InsightNativeMigration', [input], ['snapshot', 'snapshots', 'quiescence'].includes(String(request.operation)) ? {} : await this.credentials(binding, 'publisher'), undefined, [0], ghidraBudget(this.c.profile.values, 'save'));
135
+ }
136
+ async nativeRead(binding, request) {
137
+ const root = join(this.root(), 'native-reads', randomUUID());
138
+ await mkdir(root, { recursive: true, mode: 0o700 });
139
+ const input = join(root, 'request.json');
140
+ await durable(input, { ...request, repository: binding.repository });
141
+ return this.run('native-read', 'InsightNativeRead', [input], await this.credentials(binding, 'reader'), undefined, [0], ghidraBudget(this.c.profile.values, 'save'));
142
+ }
143
+ async inspect(snapshot, request) { return this.run('snapshot-inspect', 'insight.nativecheckout.InsightSnapshotInspect', [snapshot, request]); }
103
144
  async sdkFile(operation, p) {
104
145
  const root = join(this.root(), 'sdk-files', randomUUID());
105
146
  await mkdir(root, { recursive: true, mode: 0o700 });
@@ -232,9 +273,6 @@ export class GhidraServer {
232
273
  this.c.progress('Ghidra initial publication: ' + operation);
233
274
  return this.run('initial-publication', 'db.InsightInitialPublication', [root, operation], await this.credentials(binding, operation.startsWith('verify') ? 'reader' : 'publisher'));
234
275
  }
235
- async publish(binding, path, snapshot, expected, request, journal, sourceSha) {
236
- return this.run('publish', 'db.InsightSnapshotPublisher', [binding.repository, path, snapshot, String(expected), 'insight merge ' + request, journal, sourceSha], await this.credentials(binding, 'publisher'), undefined, [0, 2]);
237
- }
238
276
  async recoverPublication(binding, path, snapshot, expected, request, journal, sourceSha) {
239
277
  return this.run('recover-publication', 'db.InsightPublicationRecovery', [binding.repository, path, snapshot, String(expected), 'insight merge ' + request, journal, sourceSha], { ...await this.credentials(binding, 'reader'), INSIGHT_PUBLISHER_USER: binding.publisherUser,
240
278
  INSIGHT_PUBLISHER_PASSWORD: await this.c.secrets.require(binding.publisherSecret) });
@@ -326,6 +364,8 @@ export class GhidraServer {
326
364
  await this.c.secrets.set(key, randomBytes(32).toString('hex'));
327
365
  }
328
366
  }
367
+ if (local.pid && live(local.pid))
368
+ await retireReusedServer(this.directory, this.c.appArguments.AppDataDirectory, local);
329
369
  if (local.pid && live(local.pid)) {
330
370
  await this.identity(local);
331
371
  await this.authority(local);
@@ -0,0 +1,23 @@
1
+ import { Workspace, type GhidraContext } from './workspace.js';
2
+ /** Deletes only bytes reproducible from retained state. Anything unproved is reported and kept. */
3
+ export interface CollectionPort {
4
+ closed(context: GhidraContext): Promise<boolean>;
5
+ /** Verify natively that a stopped checkout has no work, then release and drop its project. */
6
+ release(context: GhidraContext): Promise<boolean>;
7
+ }
8
+ export interface Category {
9
+ items: number;
10
+ bytes: number;
11
+ }
12
+ export declare function collectStorage(workspace: Workspace, port: CollectionPort, dryRun: boolean, progress?: (message: string) => void): Promise<{
13
+ retained: {
14
+ path: string;
15
+ reason: string;
16
+ }[];
17
+ id?: `${string}-${string}-${string}-${string}-${string}` | undefined;
18
+ state: string;
19
+ dryRun: boolean;
20
+ bytes: number;
21
+ categories: Record<string, Category>;
22
+ retainedCount: number;
23
+ }>;
@@ -0,0 +1,358 @@
1
+ import { access, lstat, mkdir, open, readdir, readFile, realpath, rename, rm, unlink } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { stable } from './model.js';
5
+ const missing = (error) => error.code === 'ENOENT';
6
+ const uuid = '[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}';
7
+ const artifactName = /^([a-f0-9]{64})\.(gzf|json)$/, pendingName = new RegExp('^pending-' + uuid + '$');
8
+ const exportName = new RegExp('^(?:saved-' + uuid + '|shared|recovered)\\.gzf$');
9
+ async function linked(path) { try {
10
+ return (await lstat(path)).isSymbolicLink();
11
+ }
12
+ catch (error) {
13
+ if (missing(error))
14
+ return false;
15
+ throw error;
16
+ } }
17
+ async function directories(path) {
18
+ if (await linked(path))
19
+ return [];
20
+ try {
21
+ return (await readdir(path, { withFileTypes: true })).filter(e => e.isDirectory()).map(e => e.name);
22
+ }
23
+ catch (error) {
24
+ if (missing(error))
25
+ return [];
26
+ throw error;
27
+ }
28
+ }
29
+ async function files(path) {
30
+ if (await linked(path))
31
+ return [];
32
+ try {
33
+ return (await readdir(path, { withFileTypes: true })).filter(e => e.isFile()).map(e => e.name);
34
+ }
35
+ catch (error) {
36
+ if (missing(error))
37
+ return [];
38
+ throw error;
39
+ }
40
+ }
41
+ async function present(path) { try {
42
+ return await lstat(path);
43
+ }
44
+ catch (error) {
45
+ if (missing(error))
46
+ return;
47
+ throw error;
48
+ } }
49
+ async function json(path) {
50
+ try {
51
+ const value = JSON.parse(await readFile(path, 'utf8'));
52
+ return value && typeof value === 'object' && !Array.isArray(value) ? value : undefined;
53
+ }
54
+ catch (error) {
55
+ if (missing(error) || error instanceof SyntaxError)
56
+ return;
57
+ throw error;
58
+ }
59
+ }
60
+ function alive(pid) { try {
61
+ process.kill(pid, 0);
62
+ return true;
63
+ }
64
+ catch (error) {
65
+ return error.code !== 'ESRCH';
66
+ } }
67
+ async function older(path, ms) { const st = await present(path); return st !== undefined && Date.now() - st.mtimeMs > ms; }
68
+ /** A hard link frees its bytes only when every name of that file is removed. */
69
+ class Reclaimed {
70
+ seen = new Map();
71
+ async add(path, category) {
72
+ const st = await lstat(path, { bigint: true });
73
+ if (st.isDirectory()) {
74
+ for (const name of await readdir(path))
75
+ await this.add(join(path, name), category);
76
+ return;
77
+ }
78
+ if (!st.isFile())
79
+ return;
80
+ const key = st.dev + ':' + st.ino, row = this.seen.get(key);
81
+ // A real run removes names as it goes, so keep the first observed link count.
82
+ if (row)
83
+ row.names++;
84
+ else
85
+ this.seen.set(key, { links: Number(st.nlink), names: 1, size: Number(st.size), category });
86
+ }
87
+ bytes() { const out = {}; for (const f of this.seen.values())
88
+ if (f.names >= f.links)
89
+ out[f.category] = (out[f.category] ?? 0) + f.size; return out; }
90
+ }
91
+ async function stopReceipt(root, worker) {
92
+ const stop = await json(join(root, 'stopped.json'));
93
+ return stop && stop.pid === worker.pid && stop.tokenSecret === worker.tokenSecret ? stop : undefined;
94
+ }
95
+ async function stopped(root, worker) {
96
+ if (!Number.isSafeInteger(worker.pid) || Number(worker.pid) < 1)
97
+ return false;
98
+ return Boolean(await stopReceipt(root, worker)) || !alive(Number(worker.pid));
99
+ }
100
+ /** A detached private project is redundant only while it holds just its one imported program. */
101
+ async function soleProgram(root) {
102
+ let count = 0;
103
+ async function walk(path) {
104
+ let entries;
105
+ try {
106
+ entries = await readdir(path, { withFileTypes: true });
107
+ }
108
+ catch (error) {
109
+ if (missing(error))
110
+ return;
111
+ throw error;
112
+ }
113
+ for (const e of entries) {
114
+ if (e.isDirectory())
115
+ await walk(join(path, e.name));
116
+ else if (e.name.endsWith('.prp') && e.name !== 'project.prp')
117
+ count++;
118
+ }
119
+ }
120
+ for (const tree of ['idata', 'versioned', 'user'])
121
+ await walk(join(root, 'view.rep', tree));
122
+ return count <= 1;
123
+ }
124
+ async function durable(path, value) {
125
+ const temporary = path + '.new-' + randomUUID(), file = await open(temporary, 'wx', 0o600);
126
+ try {
127
+ await file.writeFile(stable(value));
128
+ await file.sync();
129
+ }
130
+ finally {
131
+ await file.close();
132
+ }
133
+ await rename(temporary, path);
134
+ }
135
+ export async function collectStorage(workspace, port, dryRun, progress = () => { }) {
136
+ const native = join(workspace.directory, 'ghidra-native'), retained = [];
137
+ const reclaimed = new Reclaimed(), categories = {};
138
+ const id = randomUUID(), receipt = join(workspace.directory, 'gc', id + '.json'), startedAt = new Date().toISOString();
139
+ if (!dryRun) {
140
+ await mkdir(join(workspace.directory, 'gc'), { recursive: true, mode: 0o700 });
141
+ await durable(receipt, { schema: 1, id, state: 'started', startedAt });
142
+ }
143
+ const keep = (path, reason) => { retained.push({ path, reason }); };
144
+ async function remove(path, category) {
145
+ const st = await present(path);
146
+ if (!st)
147
+ return;
148
+ if (st.isSymbolicLink() || !st.isFile() && !st.isDirectory())
149
+ return keep(path, 'Links and special entries are never removed.');
150
+ await reclaimed.add(path, category);
151
+ if (!dryRun)
152
+ try {
153
+ if (st.isDirectory())
154
+ await rm(path, { recursive: true, maxRetries: 3 });
155
+ else
156
+ await unlink(path);
157
+ }
158
+ catch (error) {
159
+ return keep(path, 'Removal failed: ' + String(error.code));
160
+ }
161
+ (categories[category] ??= { items: 0, bytes: 0 }).items++;
162
+ }
163
+ // A context participates only when nothing about its private state is uncertain.
164
+ const contexts = workspace.allContexts(), safe = new Set(), blockedTargets = new Set(), unsettled = new Set();
165
+ for (const context of contexts) {
166
+ const active = workspace.activePublication(context.target);
167
+ let reason;
168
+ if (active)
169
+ blockedTargets.add(context.target);
170
+ if (['opening', 'needs_recovery'].includes(context.state))
171
+ reason = 'Context is still opening or requires recovery.';
172
+ else if (workspace.unresolved(context).length || workspace.uncertainOutcome(context))
173
+ reason = 'Context has an unresolved or uncertain operation.';
174
+ else if (active?.session === context.session)
175
+ reason = 'Context has an unresolved publication.';
176
+ else if (context.debugger?.traces.length || context.debugger?.connected)
177
+ reason = 'Context retains debugger state.';
178
+ else {
179
+ try {
180
+ if (!await port.closed(context))
181
+ reason = 'Context worker is not proved stopped.';
182
+ }
183
+ catch {
184
+ reason = 'Context worker receipt could not be verified.';
185
+ }
186
+ if (!reason && context.workingSnapshot)
187
+ try {
188
+ await workspace.artifacts.verify(context.workingSnapshot);
189
+ }
190
+ catch {
191
+ reason = 'Saved private view could not be verified.';
192
+ }
193
+ }
194
+ if (reason) {
195
+ keep(join(native, 'context', context.id), reason);
196
+ unsettled.add(context.target);
197
+ }
198
+ else
199
+ safe.add(context.id);
200
+ }
201
+ // Ghidra releases clean checkouts itself; their projects are never deleted behind its back.
202
+ for (const context of contexts) {
203
+ const checkout = context.nativeCheckout, category = 'native-checkouts';
204
+ if (!checkout || checkout.state === 'dropped' || !safe.has(context.id) || checkout.conflict || context.scalars.length || context.complexChanges.length)
205
+ continue;
206
+ if (workspace.checkoutReferenced(context)) {
207
+ keep(checkout.root, 'An unresolved operation in another context references this checkout.');
208
+ continue;
209
+ }
210
+ const project = join(checkout.root, 'view.rep');
211
+ if (dryRun) {
212
+ if (workspace.unchangedNative(context))
213
+ await remove(project, category);
214
+ continue;
215
+ }
216
+ const sizes = new Reclaimed();
217
+ if (await present(project))
218
+ await sizes.add(project, category);
219
+ try {
220
+ progress('Verifying native checkout ' + context.session + ' / ' + context.target);
221
+ if (await port.release(context)) {
222
+ const row = categories[category] ??= { items: 0, bytes: 0 };
223
+ row.items++;
224
+ row.bytes += sizes.bytes()[category] ?? 0;
225
+ }
226
+ else
227
+ keep(checkout.root, 'Native checkout is not proved unchanged.');
228
+ }
229
+ catch (error) {
230
+ keep(checkout.root, 'Native release was refused: ' + String(error.message).slice(0, 300));
231
+ }
232
+ }
233
+ const known = new Set(contexts.map(c => c.id)), captured = new Set();
234
+ for (const context of contexts)
235
+ if (context.workingSnapshot)
236
+ captured.add(context.id);
237
+ else
238
+ try {
239
+ await access(join(workspace.directory, 'legacy-migrations', context.target, context.id + '-detached.json'));
240
+ captured.add(context.id);
241
+ }
242
+ catch (error) {
243
+ if (!missing(error))
244
+ throw error;
245
+ }
246
+ for (const kind of ['context', 'shared', 'candidate']) {
247
+ const parent = join(native, kind);
248
+ for (const owner of await directories(parent)) {
249
+ if (kind === 'context' && !safe.has(owner)) {
250
+ if (!known.has(owner))
251
+ keep(join(parent, owner), 'Directory has no matching context.');
252
+ continue;
253
+ }
254
+ if (kind !== 'context' && blockedTargets.has(owner)) {
255
+ keep(join(parent, owner), 'Target has an unresolved publication.');
256
+ continue;
257
+ }
258
+ // A merge or refresh interrupted before its publication row still owns candidate evidence.
259
+ if (kind === 'candidate' && unsettled.has(owner)) {
260
+ keep(join(parent, owner), 'Target has an unsettled context.');
261
+ continue;
262
+ }
263
+ for (const name of await directories(join(parent, owner))) {
264
+ const root = join(parent, owner, name);
265
+ if (await realpath(root) !== join(await realpath(parent), owner, name)) {
266
+ keep(root, 'Working root moved outside owned storage.');
267
+ continue;
268
+ }
269
+ const worker = await json(join(root, 'process.json')), nativeRoot = Boolean(await present(join(root, 'native-owner.json')));
270
+ if (!worker && !nativeRoot) {
271
+ keep(root, 'Working root has no worker receipt.');
272
+ continue;
273
+ }
274
+ if (worker && (worker.kind !== kind || (kind === 'context' ? worker.context : worker.target) !== owner)) {
275
+ keep(root, 'Worker receipt belongs to a different owner.');
276
+ continue;
277
+ }
278
+ if (worker && !await stopped(root, worker)) {
279
+ keep(root, 'Worker is not proved stopped.');
280
+ continue;
281
+ }
282
+ for (const name of ['ghidra', 'exports', 'explicit-exports'])
283
+ if (await linked(join(root, name)))
284
+ keep(join(root, name), 'Links and special entries are never removed.');
285
+ for (const file of await files(join(root, 'ghidra')))
286
+ if (file.endsWith('.cache'))
287
+ await remove(join(root, 'ghidra', file), 'temporary-caches');
288
+ if (nativeRoot) {
289
+ // The project itself belongs to its checkout lifecycle, including uncertain creations.
290
+ for (const run of await directories(join(root, 'explicit-exports')))
291
+ await remove(join(root, 'explicit-exports', run, 'program.gzf'), 'duplicate-exports');
292
+ continue;
293
+ }
294
+ for (const file of await files(join(root, 'exports')))
295
+ if (exportName.test(file))
296
+ await remove(join(root, 'exports', file), 'duplicate-exports');
297
+ await remove(join(root, 'saved.gzf'), 'duplicate-exports');
298
+ // Facade edits are captured as they complete; a GUI save is captured only by an explicit close.
299
+ const stop = worker && await stopReceipt(root, worker);
300
+ if (!stop || worker.mode !== 'headless' && stop.reason !== 'explicit_close') {
301
+ keep(join(root, 'view.rep'), 'Project has no clean stop receipt that proves capture.');
302
+ continue;
303
+ }
304
+ if (kind === 'context' && !captured.has(owner)) {
305
+ keep(join(root, 'view.rep'), 'Project has no verified saved or migrated view.');
306
+ continue;
307
+ }
308
+ if (!await soleProgram(root)) {
309
+ keep(join(root, 'view.rep'), 'Project holds additional files.');
310
+ continue;
311
+ }
312
+ for (const file of ['view.rep', 'view.gpr', 'view.lock', 'view.lock~'])
313
+ await remove(join(root, file), 'detached-projects');
314
+ }
315
+ }
316
+ }
317
+ for (const run of await directories(join(native, 'explicit-exports')))
318
+ await remove(join(native, 'explicit-exports', run, 'program.gzf'), 'duplicate-exports');
319
+ const calls = join(workspace.directory, 'server', 'calls');
320
+ for (const call of await directories(calls))
321
+ for (const file of await files(join(calls, call, 'ghidra')))
322
+ if (file.endsWith('.cache'))
323
+ await remove(join(calls, call, 'ghidra', file), 'temporary-caches');
324
+ // Roots are live rows, unfinished or failed intents, every user-visible result and VT owners.
325
+ const roots = workspace.artifactRoots();
326
+ for (const tracking of await directories(join(workspace.directory, 'version-tracking'))) {
327
+ let owner = '';
328
+ try {
329
+ owner = await readFile(join(workspace.directory, 'version-tracking', tracking, 'owner.json'), 'utf8');
330
+ }
331
+ catch (error) {
332
+ if (!missing(error))
333
+ throw error;
334
+ }
335
+ for (const match of owner.matchAll(/(?:snapshot|native):[a-f0-9]{64}/g))
336
+ roots.add(match[0]);
337
+ }
338
+ const rows = new Set(workspace.allArtifacts().map(a => a.id));
339
+ if (!dryRun)
340
+ for (const artifact of workspace.allArtifacts())
341
+ if (artifact.kind !== 'input' && !roots.has(artifact.id))
342
+ workspace.forgetArtifact(artifact.id);
343
+ const directory = join(workspace.directory, 'artifacts');
344
+ for (const file of await files(directory)) {
345
+ const match = artifactName.exec(file);
346
+ const id = match && (match[2] === 'gzf' ? 'snapshot:' : 'native:') + match[1];
347
+ // A capture writes its file before its row, so unrowed files are stale only after a day.
348
+ if (id ? !roots.has(id) && (rows.has(id) || await older(join(directory, file), 86400000)) : pendingName.test(file) && await older(join(directory, file), 86400000))
349
+ await remove(join(directory, file), 'unreferenced-snapshots');
350
+ }
351
+ for (const [category, bytes] of Object.entries(reclaimed.bytes()))
352
+ if (categories[category])
353
+ categories[category].bytes += bytes;
354
+ const result = { state: dryRun ? 'planned' : 'complete', dryRun, bytes: Object.values(categories).reduce((n, c) => n + c.bytes, 0), categories, retainedCount: retained.length };
355
+ if (!dryRun)
356
+ await durable(receipt, { schema: 1, id, startedAt, endedAt: new Date().toISOString(), ...result, retained });
357
+ return { ...result, ...(dryRun ? {} : { id }), retained: retained.slice(0, 200) };
358
+ }
@@ -88,8 +88,10 @@ export class Synchronization {
88
88
  remember({ local, phase: 'saved' });
89
89
  }
90
90
  const automatic = { ...(progress.incoming ? { refresh: progress.incoming } : {}) };
91
+ // Native buffers decide whether there is work to publish. GUI/native edits need not
92
+ // create scalar/opaque CLI diagnostics, and an unchanged checkout is safely empty.
91
93
  const publish = (policy.publish === 'after-save' && path === 'ghidra save' || policy.publish === 'after-edit') &&
92
- (path === 'ghidra save' || local.sharedState === 'pending') && Number(local.pendingChanges) > 0;
94
+ local.state !== 'preview' && (path === 'ghidra save' || local.sharedState === 'pending' || this.workspace.context(selected).nativeCheckout?.state === 'active');
93
95
  if (publish) {
94
96
  remember({ phase: 'publish' });
95
97
  automatic.publication = await this.research.merge(selected, 'auto-merge-' + request.id);
@@ -108,7 +110,7 @@ export class Synchronization {
108
110
  // Retain the local acknowledgment alongside a failed/uncertain publication. Its caller
109
111
  // can distinguish successful editing from a publication that needs intervention.
110
112
  const result = { ...selected, state: code.endsWith('.conflict') ? 'conflict' : knownRejection ? 'rejected' : 'unknown', failureCode: code, phase: progress.phase,
111
- ...(progress.local ? { localApplied: true, local: progress.local } : notStarted || rejected ? { localApplied: false } : { localOutcome: progress.phase === 'local' ? 'unknown' : 'not_started' }), automatic: { ...(progress.incoming ? { refresh: progress.incoming } : {}), ...(detail ? { outcome: detail } : {}) } };
113
+ ...(progress.local ? { localApplied: true, local: progress.local } : notStarted || rejected || progress.phase === 'refresh' ? { localApplied: false } : { localOutcome: progress.phase === 'local' ? 'unknown' : 'not_started' }), automatic: { ...(progress.incoming ? { refresh: progress.incoming } : {}), ...(detail ? { outcome: detail } : {}) } };
112
114
  if (code.endsWith('.conflict') || knownRejection)
113
115
  this.workspace.administrationState(request.id, 'failed', result);
114
116
  else
@@ -122,7 +122,8 @@ export class VersionTracking {
122
122
  const backend = await this.backend();
123
123
  await backend.open(selected);
124
124
  await backend.open(source);
125
- const sourceSnapshot = await backend.saved(source), destinationSnapshot = await backend.saved(selected), root = join(this.workspace.directory, 'version-tracking', tracking);
125
+ const sourceView = await backend.saved(source), destinationView = await backend.saved(selected);
126
+ const sourceSnapshot = backend.snapshotFile ? await this.workspace.captureSnapshot(await backend.snapshotFile(sourceView)) : sourceView, destinationSnapshot = backend.snapshotFile ? await this.workspace.captureSnapshot(await backend.snapshotFile(destinationView)) : destinationView, root = join(this.workspace.directory, 'version-tracking', tracking);
126
127
  await mkdir(root, { recursive: true, mode: 0o700 });
127
128
  if (await realpath(root) !== resolve(root))
128
129
  fail('binding', 'VT storage moved.');
@@ -46,6 +46,23 @@ export interface SyncPolicy {
46
46
  publish: 'manual' | 'after-edit' | 'after-save';
47
47
  refresh: 'manual' | 'before-edit';
48
48
  }
49
+ export interface NativeCheckout {
50
+ schema: 1;
51
+ context: string;
52
+ root: string;
53
+ fileId: string;
54
+ checkoutId: number;
55
+ baseVersion: number;
56
+ origin: string;
57
+ repository: string;
58
+ path: string;
59
+ runtimeFingerprint: string;
60
+ state: 'active' | 'verified' | 'dropped';
61
+ conflict?: {
62
+ request: string;
63
+ message: string;
64
+ };
65
+ }
49
66
  export interface GhidraContext extends Scope {
50
67
  /** Internal storage key, never a caller's backend selector. */
51
68
  id: string;
@@ -60,6 +77,7 @@ export interface GhidraContext extends Scope {
60
77
  complexChanges: string[];
61
78
  debugger?: DebuggerState;
62
79
  syncPolicy?: SyncPolicy;
80
+ nativeCheckout?: NativeCheckout;
63
81
  }
64
82
  export interface SavedTrace {
65
83
  id: string;
@@ -117,7 +135,7 @@ export interface OpenReservation {
117
135
  request: ResearchRequest;
118
136
  replay: boolean;
119
137
  }
120
- type ContextPatch = Partial<Pick<GhidraContext, 'state' | 'baseRevision' | 'baseSnapshot' | 'workingSnapshot' | 'viewEpoch' | 'scalars' | 'complexChanges' | 'debugger' | 'syncPolicy'>>;
138
+ type ContextPatch = Partial<Pick<GhidraContext, 'state' | 'baseRevision' | 'baseSnapshot' | 'workingSnapshot' | 'viewEpoch' | 'scalars' | 'complexChanges' | 'debugger' | 'syncPolicy' | 'nativeCheckout'>>;
121
139
  /** Profile root state, deliberately separate from the earlier coordinator.sqlite journals. */
122
140
  export declare class Workspace {
123
141
  readonly profile: string;
@@ -131,6 +149,7 @@ export declare class Workspace {
131
149
  private rememberArtifact;
132
150
  private knownSnapshot;
133
151
  captureSnapshot(path: string): Promise<Artifact>;
152
+ captureNative(path: string): Promise<Artifact>;
134
153
  importTarget(path: string): Promise<ResearchTarget>;
135
154
  target(target: string): ResearchTarget;
136
155
  targets(limit?: number, offset?: number): ResearchTarget[];
@@ -148,6 +167,20 @@ export declare class Workspace {
148
167
  replay: boolean;
149
168
  };
150
169
  scopedRequest(scope: Scope, identity: string): ResearchRequest | undefined;
170
+ allContexts(): GhidraContext[];
171
+ allArtifacts(): Artifact[];
172
+ /** An abandoned or otherwise unknown terminal effect keeps all of its native evidence. */
173
+ uncertainOutcome(scope: Scope): boolean;
174
+ /** Receipt-only comparison; native state is verified separately before any release. */
175
+ unchangedNative(context: GhidraContext): boolean;
176
+ /** Another context's unresolved operation may still need this checkout's private view. */
177
+ checkoutReferenced(context: GhidraContext): boolean;
178
+ /** Applied requests keep their results; their superseded before-images are not recovery inputs. */
179
+ artifactRoots(): Set<string>;
180
+ forgetArtifact(artifact: string): void;
181
+ /** A detached context proved equal to a server version continues from a lazy native checkout. */
182
+ resetMigratedContext(scope: Scope): void;
183
+ recoverMigrationOpen(scope: Scope): number;
151
184
  request(request: string): ResearchRequest;
152
185
  reserveAdministration(operation: string, parameters: unknown, callerId?: string): {
153
186
  request: AdministrationRequest;
@@ -187,7 +220,7 @@ export declare class Workspace {
187
220
  session: string;
188
221
  target: string;
189
222
  };
190
- finishPublication(publication: string, publishedRevision: number, result: unknown): Publication;
223
+ finishPublication(publication: string, publishedRevision: number, result: unknown, sharedSnapshot?: Artifact): Publication;
191
224
  rejectPublication(publication: string, result: unknown): Publication;
192
225
  publishedSince(target: string, revision: number): Publication[];
193
226
  saveContext(scope: Scope, expectedGeneration: number, patch: ContextPatch): GhidraContext;