@eyeauras/insight-cli 0.6.4 → 0.6.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. package/.cli-package-build.json +1 -1
  2. package/SKILL.md +9 -7
  3. package/dist/src/cli.js +1 -1
  4. package/dist/src/contexts.d.ts +29 -8
  5. package/dist/src/contexts.js +455 -90
  6. package/dist/src/cross-peer.d.ts +20 -0
  7. package/dist/src/cross-peer.js +53 -0
  8. package/dist/src/debugger-results.d.ts +2 -1
  9. package/dist/src/debugger-results.js +9 -4
  10. package/dist/src/debugger.js +3 -2
  11. package/dist/src/native-merge-patches.js +20 -2
  12. package/dist/src/research.d.ts +10 -2
  13. package/dist/src/research.js +31 -4
  14. package/dist/src/storage-gc.js +244 -44
  15. package/dist/src/tool-runtime/run.js +24 -11
  16. package/dist/src/tool-runtime/supervisor.js +51 -9
  17. package/dist/src/workspace.d.ts +43 -1
  18. package/dist/src/workspace.js +110 -7
  19. package/package.json +1 -1
  20. package/references/agent-setup.md +11 -3
  21. package/references/debugger.md +5 -3
  22. package/references/extensions-and-sync.md +7 -6
  23. package/references/managed-runtime.md +4 -3
  24. package/references/native/InsightNativeCheckout.java +174 -15
  25. package/references/native/NATIVE-MERGE-NOTICE.txt +5 -1
  26. package/references/native-workflows.md +5 -3
  27. package/references/query-semantics.md +3 -2
  28. package/references/recovery.md +6 -0
  29. package/references/setup.md +9 -2
  30. package/skill-bundle/insight-artifacts/SKILL.md +1 -1
  31. package/skill-bundle/insight-artifacts/references/recovery.md +6 -0
  32. package/skill-bundle/insight-binary/SKILL.md +1 -1
  33. package/skill-bundle/insight-capture/SKILL.md +1 -1
  34. package/skill-bundle/insight-cli/SKILL.md +9 -7
  35. package/skill-bundle/insight-cli/references/agent-setup.md +11 -3
  36. package/skill-bundle/insight-cli/references/managed-runtime.md +4 -3
  37. package/skill-bundle/insight-cli/references/recovery.md +6 -0
  38. package/skill-bundle/insight-cli/references/setup.md +9 -2
  39. package/skill-bundle/insight-die/SKILL.md +1 -1
  40. package/skill-bundle/insight-dnspy/SKILL.md +1 -1
  41. package/skill-bundle/insight-dotnet-dump/SKILL.md +1 -1
  42. package/skill-bundle/insight-dotnet-stack/SKILL.md +1 -1
  43. package/skill-bundle/insight-dotnet-trace/SKILL.md +1 -1
  44. package/skill-bundle/insight-frida/SKILL.md +1 -1
  45. package/skill-bundle/insight-ghidra/SKILL.md +4 -3
  46. package/skill-bundle/insight-ghidra/references/debugger.md +5 -3
  47. package/skill-bundle/insight-ghidra/references/extensions-and-sync.md +7 -6
  48. package/skill-bundle/insight-ghidra/references/managed-runtime.md +4 -3
  49. package/skill-bundle/insight-ghidra/references/native-workflows.md +5 -3
  50. package/skill-bundle/insight-ghidra/references/query-semantics.md +3 -2
  51. package/skill-bundle/insight-ghidra/references/recovery.md +6 -0
  52. package/skill-bundle/insight-ghidra/references/setup.md +9 -2
  53. package/skill-bundle/insight-ilspy/SKILL.md +1 -1
  54. package/skill-bundle/insight-interop/SKILL.md +1 -1
  55. package/skill-bundle/insight-lldb/SKILL.md +1 -1
  56. package/skill-bundle/insight-llvm/SKILL.md +1 -1
  57. package/skill-bundle/insight-managed-heap/SKILL.md +1 -1
  58. package/skill-bundle/insight-managed-metadata/SKILL.md +1 -1
  59. package/skill-bundle/insight-mitmproxy/SKILL.md +1 -1
  60. package/skill-bundle/insight-overview/SKILL.md +1 -1
  61. package/skill-bundle/insight-procmon/SKILL.md +1 -1
  62. package/skill-bundle/insight-re/SKILL.md +1 -1
  63. package/skill-bundle/insight-re/references/recovery.md +6 -0
  64. package/skill-bundle/insight-sevenzip/SKILL.md +1 -1
  65. package/skill-bundle/insight-strace/SKILL.md +1 -1
  66. package/skill-bundle/insight-tshark/SKILL.md +1 -1
  67. package/skill-bundle/insight-windbg/SKILL.md +1 -1
  68. package/skill-bundle/manifest.json +1 -1
  69. package/skills/insight-artifacts/SKILL.md +1 -1
  70. package/skills/insight-artifacts/references/recovery.md +6 -0
  71. package/skills/insight-binary/SKILL.md +1 -1
  72. package/skills/insight-capture/SKILL.md +1 -1
  73. package/skills/insight-die/SKILL.md +1 -1
  74. package/skills/insight-dnspy/SKILL.md +1 -1
  75. package/skills/insight-dotnet-dump/SKILL.md +1 -1
  76. package/skills/insight-dotnet-stack/SKILL.md +1 -1
  77. package/skills/insight-dotnet-trace/SKILL.md +1 -1
  78. package/skills/insight-frida/SKILL.md +1 -1
  79. package/skills/insight-ghidra/SKILL.md +4 -3
  80. package/skills/insight-ghidra/references/debugger.md +5 -3
  81. package/skills/insight-ghidra/references/extensions-and-sync.md +7 -6
  82. package/skills/insight-ghidra/references/managed-runtime.md +4 -3
  83. package/skills/insight-ghidra/references/native-workflows.md +5 -3
  84. package/skills/insight-ghidra/references/query-semantics.md +3 -2
  85. package/skills/insight-ghidra/references/recovery.md +6 -0
  86. package/skills/insight-ghidra/references/setup.md +9 -2
  87. package/skills/insight-ilspy/SKILL.md +1 -1
  88. package/skills/insight-interop/SKILL.md +1 -1
  89. package/skills/insight-lldb/SKILL.md +1 -1
  90. package/skills/insight-llvm/SKILL.md +1 -1
  91. package/skills/insight-managed-heap/SKILL.md +1 -1
  92. package/skills/insight-managed-metadata/SKILL.md +1 -1
  93. package/skills/insight-mitmproxy/SKILL.md +1 -1
  94. package/skills/insight-overview/SKILL.md +1 -1
  95. package/skills/insight-procmon/SKILL.md +1 -1
  96. package/skills/insight-re/SKILL.md +1 -1
  97. package/skills/insight-re/references/recovery.md +6 -0
  98. package/skills/insight-sevenzip/SKILL.md +1 -1
  99. package/skills/insight-strace/SKILL.md +1 -1
  100. package/skills/insight-tshark/SKILL.md +1 -1
  101. package/skills/insight-windbg/SKILL.md +1 -1
@@ -1,7 +1,10 @@
1
- import { access, lstat, mkdir, open, readdir, readFile, realpath, rename, rm, unlink } from 'node:fs/promises';
1
+ import { lstat, mkdir, open, readdir, readFile, realpath, rename, rm, unlink } from 'node:fs/promises';
2
2
  import { join } from 'node:path';
3
- import { randomUUID } from 'node:crypto';
3
+ import { createHash, randomUUID } from 'node:crypto';
4
+ import { createReadStream } from 'node:fs';
4
5
  import { stable } from './model.js';
6
+ import { peerStages } from './cross-peer.js';
7
+ import { sameDirectory } from './directory-identity.js';
5
8
  const missing = (error) => error.code === 'ENOENT';
6
9
  const uuid = '[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}';
7
10
  const artifactName = /^([a-f0-9]{64})\.(gzf|json)$/, pendingName = new RegExp('^pending-' + uuid + '$');
@@ -84,6 +87,15 @@ class Reclaimed {
84
87
  else
85
88
  this.seen.set(key, { links: Number(st.nlink), names: 1, size: Number(st.size), category });
86
89
  }
90
+ include(other) {
91
+ for (const [key, value] of other.seen) {
92
+ const row = this.seen.get(key);
93
+ if (row)
94
+ row.names += value.names;
95
+ else
96
+ this.seen.set(key, value);
97
+ }
98
+ }
87
99
  bytes() { const out = {}; for (const f of this.seen.values())
88
100
  if (f.names >= f.links)
89
101
  out[f.category] = (out[f.category] ?? 0) + f.size; return out; }
@@ -121,6 +133,30 @@ async function soleProgram(root) {
121
133
  await walk(join(root, 'view.rep', tree));
122
134
  return count <= 1;
123
135
  }
136
+ /** A native receipt describes bytes elsewhere; only a verified full packed program proves detached capture. */
137
+ async function detachedCapture(workspace, root, candidates) {
138
+ try {
139
+ const path = join(root, 'saved.gzf'), st = await present(path);
140
+ if (!st?.isFile() || st.isSymbolicLink())
141
+ return false;
142
+ const possible = candidates.filter(a => a.kind === 'snapshot' && a.size === st.size);
143
+ if (!possible.length)
144
+ return false;
145
+ const hash = createHash('sha256');
146
+ for await (const chunk of createReadStream(path))
147
+ hash.update(chunk);
148
+ const sha = hash.digest('hex');
149
+ for (const artifact of possible)
150
+ if (artifact.sha256 === sha)
151
+ try {
152
+ await workspace.artifacts.verify(artifact);
153
+ return true;
154
+ }
155
+ catch { /* Try another retained full copy. */ }
156
+ }
157
+ catch { /* Unreadable or changing capture bytes never authorize project removal. */ }
158
+ return false;
159
+ }
124
160
  async function durable(path, value) {
125
161
  const temporary = path + '.new-' + randomUUID(), file = await open(temporary, 'wx', 0o600);
126
162
  try {
@@ -144,10 +180,13 @@ export async function collectStorage(workspace, port, dryRun, progress = () => {
144
180
  async function remove(path, category) {
145
181
  const st = await present(path);
146
182
  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);
183
+ return true;
184
+ if (st.isSymbolicLink() || !st.isFile() && !st.isDirectory()) {
185
+ keep(path, 'Links and special entries are never removed.');
186
+ return false;
187
+ }
188
+ const sizes = new Reclaimed();
189
+ await sizes.add(path, category);
151
190
  if (!dryRun)
152
191
  try {
153
192
  if (st.isDirectory())
@@ -156,12 +195,41 @@ export async function collectStorage(workspace, port, dryRun, progress = () => {
156
195
  await unlink(path);
157
196
  }
158
197
  catch (error) {
159
- return keep(path, 'Removal failed: ' + String(error.code));
198
+ keep(path, 'Removal failed: ' + String(error.code));
199
+ return false;
160
200
  }
201
+ reclaimed.include(sizes);
161
202
  (categories[category] ??= { items: 0, bytes: 0 }).items++;
203
+ return true;
162
204
  }
163
205
  // A context participates only when nothing about its private state is uncertain.
164
206
  const contexts = workspace.allContexts(), safe = new Set(), blockedTargets = new Set(), unsettled = new Set();
207
+ const nativeRoots = new Set(contexts.flatMap(c => c.nativeCheckout ? [c.nativeCheckout.root] : [])), artifacts = workspace.allArtifacts(), nativeEvidence = new Set(), nativeProjects = new Map();
208
+ let unverifiedNativeReceipt = false;
209
+ for (const artifact of artifacts)
210
+ if (artifact.kind === 'native')
211
+ try {
212
+ const view = await json(await workspace.artifacts.verify(artifact));
213
+ if (!view) {
214
+ unverifiedNativeReceipt = true;
215
+ nativeEvidence.add(artifact.id);
216
+ }
217
+ else if (view.source === 'checkout') {
218
+ const checkout = view.checkout;
219
+ if (typeof checkout?.root === 'string') {
220
+ nativeRoots.add(checkout.root);
221
+ nativeProjects.set(artifact.id, checkout.root);
222
+ }
223
+ else {
224
+ unverifiedNativeReceipt = true;
225
+ nativeEvidence.add(artifact.id);
226
+ }
227
+ }
228
+ }
229
+ catch {
230
+ unverifiedNativeReceipt = true;
231
+ nativeEvidence.add(artifact.id);
232
+ }
165
233
  for (const context of contexts) {
166
234
  const active = workspace.activePublication(context.target);
167
235
  let reason;
@@ -203,18 +271,31 @@ export async function collectStorage(workspace, port, dryRun, progress = () => {
203
271
  const checkout = context.nativeCheckout, category = 'native-checkouts';
204
272
  if (!checkout || checkout.state === 'dropped' || !safe.has(context.id) || checkout.conflict || context.scalars.length || context.complexChanges.length)
205
273
  continue;
206
- if (workspace.checkoutReferenced(context)) {
207
- keep(checkout.root, 'An unresolved operation in another context references this checkout.');
208
- continue;
209
- }
210
274
  if (checkout.state === 'active' && !await present(checkout.root)) {
211
275
  keep(checkout.root, 'Native checkout project is missing; its server checkout is retained.');
212
276
  continue;
213
277
  }
278
+ try {
279
+ const owner = join(checkout.root, 'native-owner.json');
280
+ if (await linked(owner) || !await json(owner)) {
281
+ keep(checkout.root, 'Native ownership receipt is missing or unverifiable; its checkout is retained.');
282
+ continue;
283
+ }
284
+ }
285
+ catch {
286
+ keep(checkout.root, 'Native ownership receipt could not be verified; its checkout is retained.');
287
+ continue;
288
+ }
289
+ if (workspace.checkoutReferenced(context)) {
290
+ keep(checkout.root, 'An unresolved operation in another context references this checkout.');
291
+ continue;
292
+ }
214
293
  const project = join(checkout.root, 'view.rep');
215
294
  if (dryRun) {
216
295
  if (workspace.unchangedNative(context))
217
296
  await remove(project, category);
297
+ else
298
+ keep(checkout.root, 'Saved receipt differs from its shared base and from every recorded pristine open of that version; the checkout may hold private work.');
218
299
  continue;
219
300
  }
220
301
  const sizes = new Reclaimed();
@@ -234,19 +315,21 @@ export async function collectStorage(workspace, port, dryRun, progress = () => {
234
315
  keep(checkout.root, 'Native release was refused: ' + String(error.message).slice(0, 300));
235
316
  }
236
317
  }
237
- const known = new Set(contexts.map(c => c.id)), captured = new Set(), discarded = new Set();
238
- for (const context of contexts)
239
- if (context.workingSnapshot)
240
- captured.add(context.id);
241
- else
242
- try {
243
- await access(join(workspace.directory, 'legacy-migrations', context.target, context.id + '-detached.json'));
244
- captured.add(context.id);
245
- }
246
- catch (error) {
247
- if (!missing(error))
248
- throw error;
249
- }
318
+ const known = new Set(contexts.map(c => c.id)), captured = new Map(), targetCaptures = new Map(), discarded = new Set(), disposedDetachedRoots = new Set();
319
+ for (const context of contexts) {
320
+ const snapshots = [];
321
+ if (context.workingSnapshot?.kind === 'snapshot')
322
+ snapshots.push(context.workingSnapshot);
323
+ try {
324
+ const migration = await json(join(workspace.directory, 'legacy-migrations', context.target, context.id + '-detached.json'));
325
+ const original = migration?.original;
326
+ if (migration?.schema === 1 && original?.id === context.id && original.target === context.target && !original.nativeCheckout && original.workingSnapshot?.kind === 'snapshot')
327
+ snapshots.push(original.workingSnapshot);
328
+ }
329
+ catch { /* A damaged migration receipt does not prove a detached capture. */ }
330
+ captured.set(context.id, snapshots);
331
+ targetCaptures.set(context.target, [...(targetCaptures.get(context.target) ?? []), ...snapshots]);
332
+ }
250
333
  // Only detached roots are reached by the project rule, and a discarded context holds no others.
251
334
  for (const context of contexts)
252
335
  if (workspace.legacyDiscarded(context))
@@ -274,25 +357,110 @@ export async function collectStorage(workspace, port, dryRun, progress = () => {
274
357
  keep(root, 'Working root moved outside owned storage.');
275
358
  continue;
276
359
  }
277
- const worker = await json(join(root, 'process.json')), nativeRoot = Boolean(await present(join(root, 'native-owner.json')));
278
- if (!worker && !nativeRoot) {
279
- keep(root, 'Working root has no worker receipt.');
280
- continue;
281
- }
282
- if (worker && (worker.kind !== kind || (kind === 'context' ? worker.context : worker.target) !== owner)) {
283
- keep(root, 'Worker receipt belongs to a different owner.');
284
- continue;
360
+ let worker, nativeRoot = false, projectOwnershipReason;
361
+ try {
362
+ const ownerPresent = Boolean(await present(join(root, 'native-owner.json')));
363
+ const creationPath = join(parent, owner, 'checkout.json');
364
+ if (kind === 'context' && await linked(creationPath)) {
365
+ keep(root, 'Native creation receipt is linked; project ownership is unproved.');
366
+ continue;
367
+ }
368
+ const creation = kind === 'context' ? await json(creationPath) : undefined;
369
+ const creationPresent = kind === 'context' && Boolean(await present(creationPath));
370
+ const creationRoot = creation?.root;
371
+ let locatorUnverified = false;
372
+ const locators = [...nativeRoots, ...(typeof creationRoot === 'string' ? [creationRoot] : [])];
373
+ const recordedNative = !ownerPresent && locators.some(named => {
374
+ if (named === root)
375
+ return true;
376
+ try {
377
+ return sameDirectory(named, root);
378
+ }
379
+ catch (error) {
380
+ if (!missing(error))
381
+ locatorUnverified = true;
382
+ return false;
383
+ }
384
+ });
385
+ if (!ownerPresent && (recordedNative || locatorUnverified || (creationPresent && typeof creationRoot !== 'string') || unverifiedNativeReceipt)) {
386
+ projectOwnershipReason = 'Native checkout or creation ownership is missing or unverifiable; detached cleanup is not authorized.';
387
+ }
388
+ worker = await json(join(root, 'process.json'));
389
+ nativeRoot = ownerPresent;
390
+ if (!worker && !nativeRoot) {
391
+ keep(root, 'Working root has no worker receipt.');
392
+ continue;
393
+ }
394
+ if (worker && (worker.kind !== kind || (kind === 'context' ? worker.context : worker.target) !== owner)) {
395
+ keep(root, 'Worker receipt belongs to a different owner.');
396
+ continue;
397
+ }
398
+ if (worker && !await stopped(root, worker)) {
399
+ keep(root, 'Worker is not proved stopped.');
400
+ continue;
401
+ }
285
402
  }
286
- if (worker && !await stopped(root, worker)) {
287
- keep(root, 'Worker is not proved stopped.');
403
+ catch (error) {
404
+ keep(root, 'Working root worker proof could not be verified: ' + String(error.code ?? 'unavailable'));
288
405
  continue;
289
406
  }
290
407
  for (const name of ['ghidra', 'exports', 'explicit-exports'])
291
408
  if (await linked(join(root, name)))
292
409
  keep(join(root, name), 'Links and special entries are never removed.');
410
+ if (kind === 'context') {
411
+ const context = workspace.contextById(owner), stages = await peerStages(root, { context: owner, target: context.target });
412
+ let ownershipReason;
413
+ if (stages.length)
414
+ try {
415
+ const linkedOwner = await linked(join(root, 'process.json')) || await linked(join(root, 'native-owner.json'));
416
+ const nativeOwner = nativeRoot && !linkedOwner && (await lstat(join(root, 'native-owner.json'))).isFile() ? await json(join(root, 'native-owner.json')) : undefined;
417
+ if (!worker)
418
+ ownershipReason = 'Cross-target working root has no worker receipt that proves it stopped.';
419
+ else if (linkedOwner)
420
+ ownershipReason = 'Cross-target working root ownership receipt is a link.';
421
+ else if (worker && worker.target !== context.target || nativeRoot && (!nativeOwner || nativeOwner.context !== owner || nativeOwner.target !== context.target))
422
+ ownershipReason = 'Cross-target working root receipt belongs to a different owner.';
423
+ else if (typeof worker.root !== 'string' || !sameDirectory(worker.root, root))
424
+ ownershipReason = 'Cross-target worker receipt does not identify this working root.';
425
+ }
426
+ catch (error) {
427
+ ownershipReason = 'Cross-target working root ownership receipt could not be verified: ' + String(error.code ?? 'unavailable');
428
+ }
429
+ for (const stage of stages) {
430
+ if (ownershipReason)
431
+ keep(stage.folder, ownershipReason);
432
+ else if ('reason' in stage)
433
+ keep(stage.folder, stage.reason);
434
+ else if (stage.receipt.state !== 'closed')
435
+ keep(stage.folder, 'Cross-target cleanup is incomplete; its temporary program removal is unverified.');
436
+ else if (workspace.checkoutReferenced(context, root))
437
+ keep(stage.folder, 'An unresolved operation in another context references this checkout.');
438
+ else if (stage.input)
439
+ await remove(stage.input, 'duplicate-exports');
440
+ }
441
+ }
442
+ // Closed peer exports have their own complete ownership proof, independent of project disposal.
443
+ if (projectOwnershipReason) {
444
+ keep(root, projectOwnershipReason);
445
+ continue;
446
+ }
447
+ const given = kind === 'context' && discarded.has(owner);
448
+ const candidates = kind === 'context' ? captured.get(owner) ?? [] : [...(targetCaptures.get(owner) ?? [])];
449
+ if (kind !== 'context')
450
+ try {
451
+ const shared = workspace.model(owner).sharedSnapshot;
452
+ if (shared?.kind === 'snapshot')
453
+ candidates.push(shared);
454
+ }
455
+ catch { /* Unknown model roots cannot supply capture proof. */ }
456
+ if (!nativeRoot && ((worker?.program !== 'program' && worker?.program !== '/program') || typeof worker.root !== 'string' || !sameDirectory(worker.root, root) || !given && !await detachedCapture(workspace, root, candidates))) {
457
+ keep(root, 'Project has no verified full detached program capture; native JSON receipts do not contain program bytes.');
458
+ continue;
459
+ }
460
+ let cleanupComplete = true;
293
461
  for (const file of await files(join(root, 'ghidra')))
294
462
  if (file.endsWith('.cache'))
295
- await remove(join(root, 'ghidra', file), 'temporary-caches');
463
+ cleanupComplete = await remove(join(root, 'ghidra', file), 'temporary-caches') && cleanupComplete;
296
464
  if (nativeRoot) {
297
465
  // The project itself belongs to its checkout lifecycle, including uncertain creations.
298
466
  for (const run of await directories(join(root, 'explicit-exports')))
@@ -301,25 +469,23 @@ export async function collectStorage(workspace, port, dryRun, progress = () => {
301
469
  }
302
470
  for (const file of await files(join(root, 'exports')))
303
471
  if (exportName.test(file))
304
- await remove(join(root, 'exports', file), 'duplicate-exports');
305
- await remove(join(root, 'saved.gzf'), 'duplicate-exports');
472
+ cleanupComplete = await remove(join(root, 'exports', file), 'duplicate-exports') && cleanupComplete;
306
473
  // Facade edits are captured as they complete; a GUI save is captured only by an explicit close.
307
474
  const stop = worker && await stopReceipt(root, worker);
308
- const given = kind === 'context' && discarded.has(owner);
309
475
  if (!given && (!stop || worker?.mode !== 'headless' && stop.reason !== 'explicit_close')) {
310
476
  keep(join(root, 'view.rep'), 'Project has no clean stop receipt that proves capture.');
311
477
  continue;
312
478
  }
313
- if (kind === 'context' && !given && !captured.has(owner)) {
314
- keep(join(root, 'view.rep'), 'Project has no verified saved or migrated view.');
315
- continue;
316
- }
317
479
  if (!await soleProgram(root)) {
318
480
  keep(join(root, 'view.rep'), 'Project holds additional files.');
319
481
  continue;
320
482
  }
321
- for (const file of ['view.rep', 'view.gpr', 'view.lock', 'view.lock~'])
322
- await remove(join(root, file), 'detached-projects');
483
+ const projectFiles = ['view.rep', 'view.gpr', 'view.lock', 'view.lock~'];
484
+ for (const file of projectFiles)
485
+ cleanupComplete = await remove(join(root, file), 'detached-projects') && cleanupComplete;
486
+ // Every recognized removal must succeed before its full capture proof can be forgotten.
487
+ if (cleanupComplete && await remove(join(root, 'saved.gzf'), 'duplicate-exports'))
488
+ disposedDetachedRoots.add(root);
323
489
  }
324
490
  }
325
491
  }
@@ -332,6 +498,40 @@ export async function collectStorage(workspace, port, dryRun, progress = () => {
332
498
  await remove(join(calls, call, 'ghidra', file), 'temporary-caches');
333
499
  // Roots are live rows, unfinished or failed intents, every user-visible result and VT owners.
334
500
  const roots = workspace.artifactRoots();
501
+ for (const id of nativeEvidence)
502
+ roots.add(id);
503
+ // Native release above can remove a project and its live context reference in this same pass.
504
+ for (const [id, root] of nativeProjects)
505
+ try {
506
+ if (await present(join(root, 'view.rep')) || await present(join(root, 'view.gpr')))
507
+ roots.add(id);
508
+ }
509
+ catch {
510
+ roots.add(id);
511
+ keep(root, 'Native project inventory could not be verified; its receipt is retained.');
512
+ }
513
+ // Migration journals keep identity, not artifact liveness. A retained saved.gzf still needs its
514
+ // canonical verification copy for the next collection attempt, even after the context migrated.
515
+ for (const kind of ['context', 'shared', 'candidate'])
516
+ for (const owner of await directories(join(native, kind))) {
517
+ const proofs = kind === 'context' ? (discarded.has(owner) ? [] : captured.get(owner) ?? []) : targetCaptures.get(owner) ?? [];
518
+ if (!proofs.length)
519
+ continue;
520
+ for (const name of await directories(join(native, kind, owner))) {
521
+ const root = join(native, kind, owner, name);
522
+ if (disposedDetachedRoots.has(root))
523
+ continue;
524
+ try {
525
+ if (!await present(join(root, 'saved.gzf')))
526
+ continue;
527
+ }
528
+ catch {
529
+ keep(root, 'Retained capture metadata could not be verified; its snapshot proof is preserved.');
530
+ }
531
+ for (const artifact of proofs)
532
+ roots.add(artifact.id);
533
+ }
534
+ }
335
535
  for (const tracking of await directories(join(workspace.directory, 'version-tracking'))) {
336
536
  let owner = '';
337
537
  try {
@@ -27,6 +27,22 @@ export async function runTool(c, spec) {
27
27
  const environment = { PATH: c.environment.PATH ?? process.env.PATH, HOME: root, TMPDIR: root, ...(process.platform === 'win32' ? { SystemRoot: process.env.SystemRoot, WINDIR: process.env.WINDIR, ComSpec: process.env.ComSpec, TEMP: root, TMP: root, USERPROFILE: root, LOCALAPPDATA: root, APPDATA: root } : {}), ...spec.environment };
28
28
  const secrets = Object.entries(environment).filter(([key, value]) => /TOKEN|PASSWORD|SECRET|KEY/i.test(key) && value && value.length >= 4).map(([, v]) => v);
29
29
  const redact = (value) => secrets.reduce((text, secret) => text.split(secret).join('[redacted]'), value);
30
+ let retained;
31
+ const retainOutput = async (exitCode = child?.exitCode ?? null) => {
32
+ if (retained)
33
+ return retained;
34
+ const result = { process: id, stdout: redact(Buffer.concat(stdout).toString('utf8')), stderr: redact(Buffer.concat(stderr).toString('utf8')), exitCode, signal: child?.signalCode ?? null, elapsedMs: Math.round(performance.now() - started), truncated, diagnostics: root };
35
+ if (spec.retainRawOutput) {
36
+ result.rawStdout = join(root, 'stdout.bin');
37
+ result.rawStderr = join(root, 'stderr.bin');
38
+ await writeFile(result.rawStdout, Buffer.concat(stdout), { mode: 0o600 });
39
+ await writeFile(result.rawStderr, Buffer.concat(stderr), { mode: 0o600 });
40
+ }
41
+ await writeFile(join(root, 'stdout.log'), result.stdout, { mode: 0o600 });
42
+ await writeFile(join(root, 'stderr.log'), result.stderr, { mode: 0o600 });
43
+ retained = result;
44
+ return result;
45
+ };
30
46
  let timer, force, drain, hard, settled = false, abandon;
31
47
  const signal = (name) => {
32
48
  if (!child?.pid || settled)
@@ -59,15 +75,17 @@ export async function runTool(c, spec) {
59
75
  child = await launchProcess(directory, { tool: spec.tool, role: spec.role, installation: spec.installation ?? 'probe', session: spec.session, target: spec.target, ...(spec.metadata || spec.nativeDeadline ? { metadata: { ...spec.metadata, ...(spec.observedSubject ? { observedSubject: spec.observedSubject } : {}), ...(spec.nativeMutex ? { nativeMutex: spec.nativeMutex } : {}), ...(spec.nativeRegistry ? { nativeRegistry: spec.nativeRegistry } : {}), ...(spec.nativeDeadline ? { nativeDeadlineSeconds: Math.ceil((spec.timeoutMs ?? 120000) / 1000), nativeExecutable: spec.executable, ...(spec.nativeChildDeadlines ? { nativeChildDeadlines: true } : {}) } : {}) } } : {}) }, launch.executable, launch.arguments, { cwd: spec.cwd ?? root, env: environment, windowsHide: true, detached: process.platform !== 'win32', stdio: ['pipe', 'pipe', 'pipe'] }, { id, finalize: false, signal: c.signal, onSpawn: launched => {
60
76
  child = launched;
61
77
  child.once('close', () => { settled = true; });
78
+ child.on('error', () => stop('launch_failed'));
62
79
  child.once('exit', () => { drain = setTimeout(() => stop('background_output'), 300); drain.unref(); });
63
80
  const capture = (chunks, b) => { const available = Math.max(0, limit - bytes); if (available)
64
81
  chunks.push(Buffer.from(b.subarray(0, available))); bytes += b.length; if (bytes > limit) {
65
82
  truncated = true;
66
83
  stop('output_limit');
67
84
  } };
85
+ child.stdout.on('error', () => stop('launch_failed'));
86
+ child.stderr.on('error', () => stop('launch_failed'));
68
87
  child.stdout.on('data', b => capture(stdout, b));
69
88
  child.stderr.on('data', b => capture(stderr, b));
70
- child.stdin.on('error', () => { });
71
89
  child.stdin.end(spec.input);
72
90
  c.signal.addEventListener('abort', aborted, { once: true });
73
91
  if (c.signal.aborted)
@@ -97,15 +115,7 @@ export async function runTool(c, spec) {
97
115
  outcome = 'timeout';
98
116
  if (!outcome && (exitCode === null || !(spec.acceptedCodes ?? [0]).includes(exitCode)))
99
117
  outcome = 'exit_code';
100
- const result = { process: id, stdout: redact(Buffer.concat(stdout).toString('utf8')), stderr: redact(Buffer.concat(stderr).toString('utf8')), exitCode, signal: child.signalCode, elapsedMs: Math.round(performance.now() - started), truncated, diagnostics: root };
101
- if (spec.retainRawOutput) {
102
- result.rawStdout = join(root, 'stdout.bin');
103
- result.rawStderr = join(root, 'stderr.bin');
104
- await writeFile(result.rawStdout, Buffer.concat(stdout), { mode: 0o600 });
105
- await writeFile(result.rawStderr, Buffer.concat(stderr), { mode: 0o600 });
106
- }
107
- await writeFile(join(root, 'stdout.log'), result.stdout, { mode: 0o600 });
108
- await writeFile(join(root, 'stderr.log'), result.stderr, { mode: 0o600 });
118
+ const result = await retainOutput(exitCode);
109
119
  Object.assign(record, { state: outcome ? 'failed' : 'exited', outcome: outcome ?? 'completed', exitCode: result.exitCode, signal: result.signal, elapsedMs: result.elapsedMs, endedAt: new Date().toISOString() });
110
120
  await atomicWrite(path, record);
111
121
  if (outcome)
@@ -121,7 +131,6 @@ export async function runTool(c, spec) {
121
131
  }
122
132
  catch (error) {
123
133
  const failure = error;
124
- await atomicWrite(join(root, 'error.json'), { name: failure.name, code: failure.code, message: redact(failure.message ?? String(error)), ...(failure.cause ? { cause: { name: failure.cause.name, message: redact(failure.cause.message) } } : {}) });
125
134
  if (child && !settled && record.state !== 'unverified') {
126
135
  stop('failed');
127
136
  await new Promise(ok => { if (settled) {
@@ -132,12 +141,16 @@ export async function runTool(c, spec) {
132
141
  Object.assign(record, await readJson(path));
133
142
  if (c.signal.aborted && !outcome)
134
143
  outcome = 'cancelled';
144
+ if (child?.pid && !settled && child.exitCode === null && child.signalCode === null)
145
+ record.state = 'unverified';
135
146
  if (record.state === 'starting' || record.state === 'running' || record.state === 'failed') {
136
147
  Object.assign(record, { state: 'failed', outcome: outcome ?? 'launch_failed', endedAt: new Date().toISOString(), elapsedMs: Math.round(performance.now() - started) });
137
148
  await atomicWrite(path, record);
138
149
  }
139
150
  if (record.state === 'unverified')
140
151
  await atomicWrite(path, record);
152
+ await atomicWrite(join(root, 'error.json'), { name: failure.name, code: failure.code, message: redact(failure.message ?? String(error)), ...(failure.cause ? { cause: { name: failure.cause.name, message: redact(failure.cause.message) } } : {}) });
153
+ await retainOutput();
141
154
  if (error instanceof CliError)
142
155
  throw error;
143
156
  if (record.state === 'unverified')
@@ -81,22 +81,49 @@ export async function launchProcess(directory, spec, executable, args, options =
81
81
  await atomicWrite(path, record);
82
82
  throw error;
83
83
  }
84
- const closed = new Promise((ok, bad) => { child.on('error', error => { if (!child.pid)
85
- bad(error); }); child.once('close', ok); });
84
+ // Node can emit errors on the pipes as well as on the child (including a failed
85
+ // Windows spawn with no PID). Observe them before any adapter/identity await.
86
+ let childError, streamError, didSpawn = false, didClose = false, startupSucceeded = false, startupError;
87
+ const failure = () => childError ?? streamError;
88
+ const spawned = new Promise((ok, bad) => {
89
+ child.once('spawn', () => { didSpawn = true; ok(); });
90
+ child.on('error', error => { childError ??= error; if (!didSpawn)
91
+ bad(error); });
92
+ });
93
+ for (const stream of child.stdio)
94
+ stream?.on('error', error => {
95
+ // A tool may close its input without consuming it; retain the existing EPIPE policy.
96
+ if (stream !== child.stdin || error.code !== 'EPIPE')
97
+ streamError ??= error;
98
+ });
99
+ const closed = new Promise((ok, bad) => { child.once('close', () => { didClose = true; const error = failure(); if (error)
100
+ bad(error);
101
+ else
102
+ ok(); }); });
86
103
  void closed.catch(() => { });
104
+ let finishLaunch;
105
+ const launchFinished = new Promise(ok => finishLaunch = ok);
87
106
  const handle = { child, closed, record };
88
107
  owned.set(ownedKey(directory, id), handle);
89
- const finalized = control.finalize === false ? closed : closed.then(async () => {
108
+ const finalized = control.finalize === false ? closed : closed.catch(() => { }).then(async () => {
109
+ // A fast exit must not finalize a reservation while startup is still writing it.
110
+ await launchFinished;
90
111
  const current = await readJson(path) ?? record;
112
+ const failed = !startupSucceeded || Boolean(failure()), error = failure() ?? startupError;
91
113
  if (current.state !== 'failed' && current.state !== 'unverified')
92
- Object.assign(current, { state: 'exited', exitCode: child.exitCode, signal: child.signalCode, endedAt: new Date().toISOString(), outcome: current.requestedStop === 'kill' ? 'killed' : current.requestedStop === 'stop' ? 'stopped' : 'completed' });
114
+ Object.assign(current, { state: failed ? 'failed' : 'exited', exitCode: child.exitCode, signal: child.signalCode, endedAt: new Date().toISOString(), outcome: failed ? 'launch_failed' : current.requestedStop === 'kill' ? 'killed' : current.requestedStop === 'stop' ? 'stopped' : 'completed', ...(failed ? { phase: 'launch_failed', launchError: error?.code ?? (failure() ? 'stdio' : 'launch') } : {}) });
93
115
  await atomicWrite(path, current);
94
- }, async () => { Object.assign(record, { state: 'failed', phase: 'spawn_failed' }); await atomicWrite(path, record); });
116
+ });
95
117
  handle.closed = finalized.finally(() => { owned.delete(ownedKey(directory, id)); });
96
118
  void handle.closed.catch(() => { });
97
119
  Object.assign(child, { toolProcessId: id, toolClosed: handle.closed });
98
120
  try {
121
+ await spawned;
122
+ if (failure())
123
+ throw failure();
99
124
  await control.onSpawn?.(child);
125
+ if (failure())
126
+ throw failure();
100
127
  if (!child.pid)
101
128
  throw Error('Owned tool spawn did not obtain a PID');
102
129
  if (gated) {
@@ -106,6 +133,8 @@ export async function launchProcess(directory, spec, executable, args, options =
106
133
  let armed = false;
107
134
  for (let i = 0; i < 400; i++) {
108
135
  control.signal?.throwIfAborted();
136
+ if (failure())
137
+ throw failure();
109
138
  const ready = await readJson(join(root, 'armed.json'));
110
139
  if (ready && ready.pid === child.pid && ready.nonce === nonce) {
111
140
  armed = true;
@@ -117,8 +146,12 @@ export async function launchProcess(directory, spec, executable, args, options =
117
146
  }
118
147
  if (!armed)
119
148
  throw Error('Owned launch did not become armed');
149
+ if (failure())
150
+ throw failure();
120
151
  Object.assign(record, await readJson(path), { state: 'running', phase: 'exec_authorized' });
121
152
  await atomicWrite(path, record);
153
+ if (failure())
154
+ throw failure();
122
155
  await atomicWrite(join(root, 'go.json'), { nonce });
123
156
  }
124
157
  else {
@@ -128,18 +161,27 @@ export async function launchProcess(directory, spec, executable, args, options =
128
161
  Object.assign(record, { pid: child.pid, identity: identity?.birth, strongIdentity: identity?.strong, processGroup: identity?.group, state: 'running', phase: 'direct_child_only' });
129
162
  await atomicWrite(path, record);
130
163
  }
164
+ if (failure())
165
+ throw failure();
166
+ startupSucceeded = true;
131
167
  return child;
132
168
  }
133
169
  catch (error) {
134
- if (child.exitCode === null && child.signalCode === null)
170
+ // Keep rejection independent of the failure receipt: its atomic write may fail.
171
+ startupError = error;
172
+ if (child.pid && child.exitCode === null && child.signalCode === null)
135
173
  try {
136
174
  child.kill('SIGKILL');
137
175
  }
138
176
  catch { }
139
- await Promise.race([handle.closed.catch(() => { }), delay(2000)]);
140
- Object.assign(record, { state: child.exitCode !== null || child.signalCode !== null ? 'failed' : 'unverified', phase: 'launch_failed' });
177
+ await Promise.race([closed.catch(() => { }), delay(2000)]);
178
+ const ended = didClose || child.exitCode !== null || child.signalCode !== null || !child.pid && Boolean(childError);
179
+ Object.assign(record, await readJson(path), { state: ended ? 'failed' : 'unverified', phase: 'launch_failed', launchError: (failure() ?? error)?.code ?? 'launch', ...(ended ? { endedAt: new Date().toISOString(), exitCode: child.exitCode, signal: child.signalCode, outcome: 'launch_failed' } : {}) });
141
180
  await atomicWrite(path, record);
142
- throw error;
181
+ throw failure() ?? error;
182
+ }
183
+ finally {
184
+ finishLaunch();
143
185
  }
144
186
  }, control.signal);
145
187
  }
@@ -62,6 +62,8 @@ 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;
65
67
  }
66
68
  export interface GhidraContext extends Scope {
67
69
  /** Internal storage key, never a caller's backend selector. */
@@ -188,8 +190,15 @@ export declare class Workspace {
188
190
  uncertainOutcome(scope: Scope): boolean;
189
191
  /** Receipt-only comparison; native state is verified separately before any release. */
190
192
  unchangedNative(context: GhidraContext): boolean;
193
+ /**
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.
196
+ */
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>;
191
200
  /** Another context's unresolved operation may still need this checkout's private view. */
192
- checkoutReferenced(context: GhidraContext): boolean;
201
+ checkoutReferenced(context: GhidraContext, root?: string | undefined): boolean;
193
202
  /** Applied requests keep their results; their superseded before-images are not recovery inputs. */
194
203
  artifactRoots(): Set<string>;
195
204
  forgetArtifact(artifact: string): void;
@@ -237,8 +246,41 @@ export declare class Workspace {
237
246
  };
238
247
  finishPublication(publication: string, publishedRevision: number, result: unknown, sharedSnapshot?: Artifact): Publication;
239
248
  rejectPublication(publication: string, result: unknown): Publication;
249
+ /** Exactly proved native pre-call refusal: settle all journals together, retaining the private view. */
250
+ finishRefusedPublication(publication: string, observedRevision: number, sharedSnapshot: Artifact, result: unknown): Publication;
240
251
  publishedSince(target: string, revision: number): Publication[];
241
252
  saveContext(scope: Scope, expectedGeneration: number, patch: ContextPatch): GhidraContext;
253
+ /** Independent release readback and its no-publication request outcome become visible together. */
254
+ retainNativeDisposal(scope: Scope, generation: number, checkout: NativeCheckout, snapshot: Artifact, request?: string): {
255
+ session: string;
256
+ target: string;
257
+ state: "retained";
258
+ engine: "ghidra-native";
259
+ checkout: "retained";
260
+ retention: {
261
+ request?: string | undefined;
262
+ schema: 1;
263
+ source: "native-release-status";
264
+ checkout: {
265
+ state: "active";
266
+ schema: 1;
267
+ context: string;
268
+ root: string;
269
+ fileId: string;
270
+ checkoutId: number;
271
+ baseVersion: number;
272
+ origin: string;
273
+ repository: string;
274
+ path: string;
275
+ runtimeFingerprint: string;
276
+ conflict?: {
277
+ request: string;
278
+ message: string;
279
+ };
280
+ };
281
+ snapshot: Artifact;
282
+ };
283
+ };
242
284
  /** Terminal abandonment retains the previous outcome and saved view atomically. */
243
285
  abandonProgramRequest(scope: Scope, request: string, generation: number): {
244
286
  state: string;