@eyeauras/insight-cli 0.6.4 → 0.7.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 (116) hide show
  1. package/.cli-package-build.json +1 -1
  2. package/SKILL.md +9 -7
  3. package/dist/src/activity-audit.d.ts +123 -0
  4. package/dist/src/activity-audit.js +310 -0
  5. package/dist/src/audit-commands.d.ts +10 -0
  6. package/dist/src/audit-commands.js +85 -0
  7. package/dist/src/audit-retention.d.ts +38 -0
  8. package/dist/src/audit-retention.js +106 -0
  9. package/dist/src/cli.js +11 -3
  10. package/dist/src/contexts.d.ts +29 -8
  11. package/dist/src/contexts.js +455 -90
  12. package/dist/src/cross-peer.d.ts +20 -0
  13. package/dist/src/cross-peer.js +53 -0
  14. package/dist/src/debugger-results.d.ts +2 -1
  15. package/dist/src/debugger-results.js +9 -4
  16. package/dist/src/debugger.js +3 -2
  17. package/dist/src/diagnostic-error.d.ts +12 -0
  18. package/dist/src/diagnostic-error.js +82 -0
  19. package/dist/src/internal-timing.d.ts +8 -2
  20. package/dist/src/internal-timing.js +50 -7
  21. package/dist/src/lifecycle.d.ts +1 -1
  22. package/dist/src/native-merge-patches.js +20 -2
  23. package/dist/src/research.d.ts +11 -3
  24. package/dist/src/research.js +31 -4
  25. package/dist/src/storage-gc.js +429 -196
  26. package/dist/src/tool-runtime/run.js +24 -11
  27. package/dist/src/tool-runtime/supervisor.js +51 -9
  28. package/dist/src/transport.js +19 -10
  29. package/dist/src/workspace.d.ts +45 -1
  30. package/dist/src/workspace.js +135 -7
  31. package/package.json +1 -1
  32. package/references/agent-setup.md +11 -3
  33. package/references/debugger.md +5 -3
  34. package/references/extensions-and-sync.md +7 -6
  35. package/references/managed-runtime.md +4 -3
  36. package/references/native/InsightNativeCheckout.java +174 -15
  37. package/references/native/NATIVE-MERGE-NOTICE.txt +5 -1
  38. package/references/native-workflows.md +5 -3
  39. package/references/query-semantics.md +3 -2
  40. package/references/recovery.md +6 -0
  41. package/references/research.md +33 -2
  42. package/references/setup.md +9 -2
  43. package/skill-bundle/insight-artifacts/SKILL.md +1 -1
  44. package/skill-bundle/insight-artifacts/references/recovery.md +6 -0
  45. package/skill-bundle/insight-binary/SKILL.md +1 -1
  46. package/skill-bundle/insight-capture/SKILL.md +1 -1
  47. package/skill-bundle/insight-cli/SKILL.md +9 -7
  48. package/skill-bundle/insight-cli/references/agent-setup.md +11 -3
  49. package/skill-bundle/insight-cli/references/managed-runtime.md +4 -3
  50. package/skill-bundle/insight-cli/references/recovery.md +6 -0
  51. package/skill-bundle/insight-cli/references/setup.md +9 -2
  52. package/skill-bundle/insight-die/SKILL.md +1 -1
  53. package/skill-bundle/insight-dnspy/SKILL.md +1 -1
  54. package/skill-bundle/insight-dotnet-dump/SKILL.md +1 -1
  55. package/skill-bundle/insight-dotnet-stack/SKILL.md +1 -1
  56. package/skill-bundle/insight-dotnet-trace/SKILL.md +1 -1
  57. package/skill-bundle/insight-frida/SKILL.md +1 -1
  58. package/skill-bundle/insight-ghidra/SKILL.md +4 -3
  59. package/skill-bundle/insight-ghidra/references/debugger.md +5 -3
  60. package/skill-bundle/insight-ghidra/references/extensions-and-sync.md +7 -6
  61. package/skill-bundle/insight-ghidra/references/managed-runtime.md +4 -3
  62. package/skill-bundle/insight-ghidra/references/native-workflows.md +5 -3
  63. package/skill-bundle/insight-ghidra/references/query-semantics.md +3 -2
  64. package/skill-bundle/insight-ghidra/references/recovery.md +6 -0
  65. package/skill-bundle/insight-ghidra/references/research.md +33 -2
  66. package/skill-bundle/insight-ghidra/references/setup.md +9 -2
  67. package/skill-bundle/insight-ilspy/SKILL.md +1 -1
  68. package/skill-bundle/insight-interop/SKILL.md +1 -1
  69. package/skill-bundle/insight-lldb/SKILL.md +1 -1
  70. package/skill-bundle/insight-llvm/SKILL.md +1 -1
  71. package/skill-bundle/insight-managed-heap/SKILL.md +1 -1
  72. package/skill-bundle/insight-managed-metadata/SKILL.md +1 -1
  73. package/skill-bundle/insight-mitmproxy/SKILL.md +1 -1
  74. package/skill-bundle/insight-overview/SKILL.md +1 -1
  75. package/skill-bundle/insight-procmon/SKILL.md +1 -1
  76. package/skill-bundle/insight-re/SKILL.md +7 -1
  77. package/skill-bundle/insight-re/references/recovery.md +6 -0
  78. package/skill-bundle/insight-sevenzip/SKILL.md +1 -1
  79. package/skill-bundle/insight-strace/SKILL.md +1 -1
  80. package/skill-bundle/insight-tshark/SKILL.md +1 -1
  81. package/skill-bundle/insight-windbg/SKILL.md +1 -1
  82. package/skill-bundle/manifest.json +1 -1
  83. package/skills/insight-artifacts/SKILL.md +1 -1
  84. package/skills/insight-artifacts/references/recovery.md +6 -0
  85. package/skills/insight-binary/SKILL.md +1 -1
  86. package/skills/insight-capture/SKILL.md +1 -1
  87. package/skills/insight-die/SKILL.md +1 -1
  88. package/skills/insight-dnspy/SKILL.md +1 -1
  89. package/skills/insight-dotnet-dump/SKILL.md +1 -1
  90. package/skills/insight-dotnet-stack/SKILL.md +1 -1
  91. package/skills/insight-dotnet-trace/SKILL.md +1 -1
  92. package/skills/insight-frida/SKILL.md +1 -1
  93. package/skills/insight-ghidra/SKILL.md +4 -3
  94. package/skills/insight-ghidra/references/debugger.md +5 -3
  95. package/skills/insight-ghidra/references/extensions-and-sync.md +7 -6
  96. package/skills/insight-ghidra/references/managed-runtime.md +4 -3
  97. package/skills/insight-ghidra/references/native-workflows.md +5 -3
  98. package/skills/insight-ghidra/references/query-semantics.md +3 -2
  99. package/skills/insight-ghidra/references/recovery.md +6 -0
  100. package/skills/insight-ghidra/references/research.md +33 -2
  101. package/skills/insight-ghidra/references/setup.md +9 -2
  102. package/skills/insight-ilspy/SKILL.md +1 -1
  103. package/skills/insight-interop/SKILL.md +1 -1
  104. package/skills/insight-lldb/SKILL.md +1 -1
  105. package/skills/insight-llvm/SKILL.md +1 -1
  106. package/skills/insight-managed-heap/SKILL.md +1 -1
  107. package/skills/insight-managed-metadata/SKILL.md +1 -1
  108. package/skills/insight-mitmproxy/SKILL.md +1 -1
  109. package/skills/insight-overview/SKILL.md +1 -1
  110. package/skills/insight-procmon/SKILL.md +1 -1
  111. package/skills/insight-re/SKILL.md +7 -1
  112. package/skills/insight-re/references/recovery.md +6 -0
  113. package/skills/insight-sevenzip/SKILL.md +1 -1
  114. package/skills/insight-strace/SKILL.md +1 -1
  115. package/skills/insight-tshark/SKILL.md +1 -1
  116. package/skills/insight-windbg/SKILL.md +1 -1
@@ -1,7 +1,11 @@
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';
1
+ import { lstat, mkdir, open, readdir, readFile, realpath, rename, rm, unlink } from 'node:fs/promises';
2
+ import { join, relative } from 'node:path';
3
+ import { auditEvent, auditHash } from './activity-audit.js';
4
+ import { createHash, randomUUID } from 'node:crypto';
5
+ import { createReadStream } from 'node:fs';
4
6
  import { stable } from './model.js';
7
+ import { peerStages } from './cross-peer.js';
8
+ import { sameDirectory } from './directory-identity.js';
5
9
  const missing = (error) => error.code === 'ENOENT';
6
10
  const uuid = '[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}';
7
11
  const artifactName = /^([a-f0-9]{64})\.(gzf|json)$/, pendingName = new RegExp('^pending-' + uuid + '$');
@@ -84,6 +88,15 @@ class Reclaimed {
84
88
  else
85
89
  this.seen.set(key, { links: Number(st.nlink), names: 1, size: Number(st.size), category });
86
90
  }
91
+ include(other) {
92
+ for (const [key, value] of other.seen) {
93
+ const row = this.seen.get(key);
94
+ if (row)
95
+ row.names += value.names;
96
+ else
97
+ this.seen.set(key, value);
98
+ }
99
+ }
87
100
  bytes() { const out = {}; for (const f of this.seen.values())
88
101
  if (f.names >= f.links)
89
102
  out[f.category] = (out[f.category] ?? 0) + f.size; return out; }
@@ -121,6 +134,30 @@ async function soleProgram(root) {
121
134
  await walk(join(root, 'view.rep', tree));
122
135
  return count <= 1;
123
136
  }
137
+ /** A native receipt describes bytes elsewhere; only a verified full packed program proves detached capture. */
138
+ async function detachedCapture(workspace, root, candidates) {
139
+ try {
140
+ const path = join(root, 'saved.gzf'), st = await present(path);
141
+ if (!st?.isFile() || st.isSymbolicLink())
142
+ return false;
143
+ const possible = candidates.filter(a => a.kind === 'snapshot' && a.size === st.size);
144
+ if (!possible.length)
145
+ return false;
146
+ const hash = createHash('sha256');
147
+ for await (const chunk of createReadStream(path))
148
+ hash.update(chunk);
149
+ const sha = hash.digest('hex');
150
+ for (const artifact of possible)
151
+ if (artifact.sha256 === sha)
152
+ try {
153
+ await workspace.artifacts.verify(artifact);
154
+ return true;
155
+ }
156
+ catch { /* Try another retained full copy. */ }
157
+ }
158
+ catch { /* Unreadable or changing capture bytes never authorize project removal. */ }
159
+ return false;
160
+ }
124
161
  async function durable(path, value) {
125
162
  const temporary = path + '.new-' + randomUUID(), file = await open(temporary, 'wx', 0o600);
126
163
  try {
@@ -136,232 +173,428 @@ export async function collectStorage(workspace, port, dryRun, progress = () => {
136
173
  const native = join(workspace.directory, 'ghidra-native'), retained = [];
137
174
  const reclaimed = new Reclaimed(), categories = {};
138
175
  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 {
176
+ auditEvent('gc.started', { gcId: id, dryRun });
177
+ try {
178
+ if (!dryRun) {
179
+ await mkdir(join(workspace.directory, 'gc'), { recursive: true, mode: 0o700 });
180
+ await durable(receipt, { schema: 1, id, state: 'started', startedAt });
181
+ }
182
+ const resource = (path) => {
179
183
  try {
180
- if (!await port.closed(context))
181
- reason = 'Context worker is not proved stopped.';
184
+ const locator = relative(workspace.directory, path).replaceAll('\\', '/'), artifact = /^artifacts\/([a-f0-9]{64})\.(gzf|json)$/.exec(locator), context = /^ghidra-native\/context\/(c_[a-f0-9-]{36})\//i.exec(locator);
185
+ return { gcId: id, dryRun, resourceHash: auditHash(locator), ...(context ? { context: context[1] } : {}), ...(artifact ? { artifact: (artifact[2] === 'gzf' ? 'snapshot:' : 'native:') + artifact[1], resourceType: artifact[2] === 'gzf' ? 'snapshot' : 'native-view' } : { resourceType: locator.endsWith('view.rep') || locator.endsWith('view.gpr') ? 'project' : locator.endsWith('.gzf') ? 'export' : locator.endsWith('.cache') ? 'cache' : 'other' }) };
182
186
  }
183
187
  catch {
184
- reason = 'Context worker receipt could not be verified.';
188
+ return { gcId: id, dryRun };
189
+ }
190
+ };
191
+ const keep = (path, reason) => {
192
+ retained.push({ path, reason });
193
+ const code = /[Pp]rivate|differs|additional files/.test(reason) ? 'private-work' : /[Ww]orker|opening|recovery|uncertain|unsettled|unresolved|debugger/.test(reason) ? 'live-or-uncertain' : /reference/.test(reason) ? 'referenced' : /ownership|owner|receipt|unverif/.test(reason) ? 'ownership-unproved' : /private|differs/.test(reason) ? 'private-work' : /capture/.test(reason) ? 'capture-unproved' : /Links/.test(reason) ? 'link-or-special' : /Removal/.test(reason) ? 'removal-failed' : 'other';
194
+ auditEvent('gc.retained', { ...resource(path), reason: code });
195
+ };
196
+ async function remove(path, category) {
197
+ const st = await present(path);
198
+ if (!st)
199
+ return true;
200
+ if (st.isSymbolicLink() || !st.isFile() && !st.isDirectory()) {
201
+ keep(path, 'Links and special entries are never removed.');
202
+ return false;
185
203
  }
186
- if (!reason && context.workingSnapshot)
204
+ const sizes = new Reclaimed();
205
+ await sizes.add(path, category);
206
+ auditEvent(dryRun ? 'gc.remove.planned' : 'gc.remove.started', { ...resource(path), category });
207
+ if (!dryRun)
187
208
  try {
188
- await workspace.artifacts.verify(context.workingSnapshot);
209
+ if (st.isDirectory())
210
+ await rm(path, { recursive: true, maxRetries: 3 });
211
+ else
212
+ await unlink(path);
189
213
  }
190
- catch {
191
- reason = 'Saved private view could not be verified.';
214
+ catch (error) {
215
+ auditEvent('gc.remove.failed', { ...resource(path), category, error, outcome: 'failure' });
216
+ keep(path, 'Removal failed: ' + String(error.code));
217
+ return false;
192
218
  }
219
+ if (!dryRun)
220
+ auditEvent('gc.remove.succeeded', { ...resource(path), category, outcome: 'success' });
221
+ reclaimed.include(sizes);
222
+ (categories[category] ??= { items: 0, bytes: 0 }).items++;
223
+ return true;
193
224
  }
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
- if (checkout.state === 'active' && !await present(checkout.root)) {
211
- keep(checkout.root, 'Native checkout project is missing; its server checkout is retained.');
212
- continue;
213
- }
214
- const project = join(checkout.root, 'view.rep');
215
- if (dryRun) {
216
- if (workspace.unchangedNative(context))
217
- await remove(project, category);
218
- continue;
219
- }
220
- const sizes = new Reclaimed();
221
- if (await present(project))
222
- await sizes.add(project, category);
223
- try {
224
- progress('Verifying native checkout ' + context.session + ' / ' + context.target);
225
- if (await port.release(context)) {
226
- const row = categories[category] ??= { items: 0, bytes: 0 };
227
- row.items++;
228
- row.bytes += sizes.bytes()[category] ?? 0;
225
+ // A context participates only when nothing about its private state is uncertain.
226
+ const contexts = workspace.allContexts(), safe = new Set(), blockedTargets = new Set(), unsettled = new Set();
227
+ const nativeRoots = new Set(contexts.flatMap(c => c.nativeCheckout ? [c.nativeCheckout.root] : [])), artifacts = workspace.allArtifacts(), nativeEvidence = new Set(), nativeProjects = new Map();
228
+ let unverifiedNativeReceipt = false;
229
+ for (const artifact of artifacts)
230
+ if (artifact.kind === 'native')
231
+ try {
232
+ const view = await json(await workspace.artifacts.verify(artifact));
233
+ if (!view) {
234
+ unverifiedNativeReceipt = true;
235
+ nativeEvidence.add(artifact.id);
236
+ }
237
+ else if (view.source === 'checkout') {
238
+ const checkout = view.checkout;
239
+ if (typeof checkout?.root === 'string') {
240
+ nativeRoots.add(checkout.root);
241
+ nativeProjects.set(artifact.id, checkout.root);
242
+ }
243
+ else {
244
+ unverifiedNativeReceipt = true;
245
+ nativeEvidence.add(artifact.id);
246
+ }
247
+ }
248
+ }
249
+ catch {
250
+ unverifiedNativeReceipt = true;
251
+ nativeEvidence.add(artifact.id);
252
+ }
253
+ for (const context of contexts) {
254
+ const active = workspace.activePublication(context.target);
255
+ let reason;
256
+ if (active)
257
+ blockedTargets.add(context.target);
258
+ if (['opening', 'needs_recovery'].includes(context.state))
259
+ reason = 'Context is still opening or requires recovery.';
260
+ else if (workspace.unresolved(context).length || workspace.uncertainOutcome(context))
261
+ reason = 'Context has an unresolved or uncertain operation.';
262
+ else if (active?.session === context.session)
263
+ reason = 'Context has an unresolved publication.';
264
+ else if (context.debugger?.traces.length || context.debugger?.connected)
265
+ reason = 'Context retains debugger state.';
266
+ else {
267
+ try {
268
+ if (!await port.closed(context))
269
+ reason = 'Context worker is not proved stopped.';
270
+ }
271
+ catch {
272
+ reason = 'Context worker receipt could not be verified.';
273
+ }
274
+ if (!reason && context.workingSnapshot)
275
+ try {
276
+ await workspace.artifacts.verify(context.workingSnapshot);
277
+ }
278
+ catch {
279
+ reason = 'Saved private view could not be verified.';
280
+ }
281
+ }
282
+ if (reason) {
283
+ keep(join(native, 'context', context.id), reason);
284
+ unsettled.add(context.target);
229
285
  }
230
286
  else
231
- keep(checkout.root, 'Native checkout is not proved unchanged.');
232
- }
233
- catch (error) {
234
- keep(checkout.root, 'Native release was refused: ' + String(error.message).slice(0, 300));
287
+ safe.add(context.id);
235
288
  }
236
- }
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);
289
+ // Ghidra releases clean checkouts itself; their projects are never deleted behind its back.
290
+ for (const context of contexts) {
291
+ const checkout = context.nativeCheckout, category = 'native-checkouts';
292
+ if (!checkout || checkout.state === 'dropped' || !safe.has(context.id) || checkout.conflict || context.scalars.length || context.complexChanges.length)
293
+ continue;
294
+ if (checkout.state === 'active' && !await present(checkout.root)) {
295
+ keep(checkout.root, 'Native checkout project is missing; its server checkout is retained.');
296
+ continue;
245
297
  }
246
- catch (error) {
247
- if (!missing(error))
248
- throw error;
298
+ try {
299
+ const owner = join(checkout.root, 'native-owner.json');
300
+ if (await linked(owner) || !await json(owner)) {
301
+ keep(checkout.root, 'Native ownership receipt is missing or unverifiable; its checkout is retained.');
302
+ continue;
303
+ }
249
304
  }
250
- // Only detached roots are reached by the project rule, and a discarded context holds no others.
251
- for (const context of contexts)
252
- if (workspace.legacyDiscarded(context))
253
- discarded.add(context.id);
254
- for (const kind of ['context', 'shared', 'candidate']) {
255
- const parent = join(native, kind);
256
- for (const owner of await directories(parent)) {
257
- if (kind === 'context' && !safe.has(owner)) {
258
- if (!known.has(owner))
259
- keep(join(parent, owner), 'Directory has no matching context.');
305
+ catch {
306
+ keep(checkout.root, 'Native ownership receipt could not be verified; its checkout is retained.');
260
307
  continue;
261
308
  }
262
- if (kind !== 'context' && blockedTargets.has(owner)) {
263
- keep(join(parent, owner), 'Target has an unresolved publication.');
309
+ if (workspace.checkoutReferenced(context)) {
310
+ keep(checkout.root, 'An unresolved operation in another context references this checkout.');
264
311
  continue;
265
312
  }
266
- // A merge or refresh interrupted before its publication row still owns candidate evidence.
267
- if (kind === 'candidate' && unsettled.has(owner)) {
268
- keep(join(parent, owner), 'Target has an unsettled context.');
313
+ const project = join(checkout.root, 'view.rep');
314
+ if (dryRun) {
315
+ if (workspace.unchangedNative(context))
316
+ await remove(project, category);
317
+ else
318
+ 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.');
269
319
  continue;
270
320
  }
271
- for (const name of await directories(join(parent, owner))) {
272
- const root = join(parent, owner, name);
273
- if (await realpath(root) !== join(await realpath(parent), owner, name)) {
274
- keep(root, 'Working root moved outside owned storage.');
275
- continue;
276
- }
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;
321
+ const sizes = new Reclaimed();
322
+ if (await present(project))
323
+ await sizes.add(project, category);
324
+ try {
325
+ progress('Verifying native checkout ' + context.session + ' / ' + context.target);
326
+ auditEvent('gc.release.started', { ...resource(checkout.root), category, ...context, context: context.id });
327
+ if (await port.release(context)) {
328
+ const row = categories[category] ??= { items: 0, bytes: 0 };
329
+ row.items++;
330
+ row.bytes += sizes.bytes()[category] ?? 0;
331
+ auditEvent('gc.release.succeeded', { ...resource(checkout.root), category, outcome: 'success', ...context, context: context.id });
281
332
  }
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;
333
+ else {
334
+ auditEvent('gc.release.failed', { ...resource(checkout.root), category, reason: 'capture-unproved', outcome: 'failure', ...context, context: context.id });
335
+ keep(checkout.root, 'Native checkout is not proved unchanged.');
285
336
  }
286
- if (worker && !await stopped(root, worker)) {
287
- keep(root, 'Worker is not proved stopped.');
337
+ }
338
+ catch (error) {
339
+ auditEvent('gc.release.failed', { ...resource(checkout.root), category, error, outcome: 'failure', ...context, context: context.id });
340
+ keep(checkout.root, 'Native release was refused: ' + String(error.message).slice(0, 300));
341
+ }
342
+ }
343
+ const known = new Set(contexts.map(c => c.id)), captured = new Map(), targetCaptures = new Map(), discarded = new Set(), disposedDetachedRoots = new Set();
344
+ for (const context of contexts) {
345
+ const snapshots = [];
346
+ if (context.workingSnapshot?.kind === 'snapshot')
347
+ snapshots.push(context.workingSnapshot);
348
+ try {
349
+ const migration = await json(join(workspace.directory, 'legacy-migrations', context.target, context.id + '-detached.json'));
350
+ const original = migration?.original;
351
+ if (migration?.schema === 1 && original?.id === context.id && original.target === context.target && !original.nativeCheckout && original.workingSnapshot?.kind === 'snapshot')
352
+ snapshots.push(original.workingSnapshot);
353
+ }
354
+ catch { /* A damaged migration receipt does not prove a detached capture. */ }
355
+ captured.set(context.id, snapshots);
356
+ targetCaptures.set(context.target, [...(targetCaptures.get(context.target) ?? []), ...snapshots]);
357
+ }
358
+ // Only detached roots are reached by the project rule, and a discarded context holds no others.
359
+ for (const context of contexts)
360
+ if (workspace.legacyDiscarded(context))
361
+ discarded.add(context.id);
362
+ for (const kind of ['context', 'shared', 'candidate']) {
363
+ const parent = join(native, kind);
364
+ for (const owner of await directories(parent)) {
365
+ if (kind === 'context' && !safe.has(owner)) {
366
+ if (!known.has(owner))
367
+ keep(join(parent, owner), 'Directory has no matching context.');
288
368
  continue;
289
369
  }
290
- for (const name of ['ghidra', 'exports', 'explicit-exports'])
291
- if (await linked(join(root, name)))
292
- keep(join(root, name), 'Links and special entries are never removed.');
293
- for (const file of await files(join(root, 'ghidra')))
294
- if (file.endsWith('.cache'))
295
- await remove(join(root, 'ghidra', file), 'temporary-caches');
296
- if (nativeRoot) {
297
- // The project itself belongs to its checkout lifecycle, including uncertain creations.
298
- for (const run of await directories(join(root, 'explicit-exports')))
299
- await remove(join(root, 'explicit-exports', run, 'program.gzf'), 'duplicate-exports');
370
+ if (kind !== 'context' && blockedTargets.has(owner)) {
371
+ keep(join(parent, owner), 'Target has an unresolved publication.');
300
372
  continue;
301
373
  }
302
- for (const file of await files(join(root, 'exports')))
303
- if (exportName.test(file))
304
- await remove(join(root, 'exports', file), 'duplicate-exports');
305
- await remove(join(root, 'saved.gzf'), 'duplicate-exports');
306
- // Facade edits are captured as they complete; a GUI save is captured only by an explicit close.
307
- const stop = worker && await stopReceipt(root, worker);
308
- const given = kind === 'context' && discarded.has(owner);
309
- if (!given && (!stop || worker?.mode !== 'headless' && stop.reason !== 'explicit_close')) {
310
- keep(join(root, 'view.rep'), 'Project has no clean stop receipt that proves capture.');
374
+ // A merge or refresh interrupted before its publication row still owns candidate evidence.
375
+ if (kind === 'candidate' && unsettled.has(owner)) {
376
+ keep(join(parent, owner), 'Target has an unsettled context.');
311
377
  continue;
312
378
  }
313
- if (kind === 'context' && !given && !captured.has(owner)) {
314
- keep(join(root, 'view.rep'), 'Project has no verified saved or migrated view.');
315
- continue;
379
+ for (const name of await directories(join(parent, owner))) {
380
+ const root = join(parent, owner, name);
381
+ if (await realpath(root) !== join(await realpath(parent), owner, name)) {
382
+ keep(root, 'Working root moved outside owned storage.');
383
+ continue;
384
+ }
385
+ let worker, nativeRoot = false, projectOwnershipReason;
386
+ try {
387
+ const ownerPresent = Boolean(await present(join(root, 'native-owner.json')));
388
+ const creationPath = join(parent, owner, 'checkout.json');
389
+ if (kind === 'context' && await linked(creationPath)) {
390
+ keep(root, 'Native creation receipt is linked; project ownership is unproved.');
391
+ continue;
392
+ }
393
+ const creation = kind === 'context' ? await json(creationPath) : undefined;
394
+ const creationPresent = kind === 'context' && Boolean(await present(creationPath));
395
+ const creationRoot = creation?.root;
396
+ let locatorUnverified = false;
397
+ const locators = [...nativeRoots, ...(typeof creationRoot === 'string' ? [creationRoot] : [])];
398
+ const recordedNative = !ownerPresent && locators.some(named => {
399
+ if (named === root)
400
+ return true;
401
+ try {
402
+ return sameDirectory(named, root);
403
+ }
404
+ catch (error) {
405
+ if (!missing(error))
406
+ locatorUnverified = true;
407
+ return false;
408
+ }
409
+ });
410
+ if (!ownerPresent && (recordedNative || locatorUnverified || (creationPresent && typeof creationRoot !== 'string') || unverifiedNativeReceipt)) {
411
+ projectOwnershipReason = 'Native checkout or creation ownership is missing or unverifiable; detached cleanup is not authorized.';
412
+ }
413
+ worker = await json(join(root, 'process.json'));
414
+ nativeRoot = ownerPresent;
415
+ if (!worker && !nativeRoot) {
416
+ keep(root, 'Working root has no worker receipt.');
417
+ continue;
418
+ }
419
+ if (worker && (worker.kind !== kind || (kind === 'context' ? worker.context : worker.target) !== owner)) {
420
+ keep(root, 'Worker receipt belongs to a different owner.');
421
+ continue;
422
+ }
423
+ if (worker && !await stopped(root, worker)) {
424
+ keep(root, 'Worker is not proved stopped.');
425
+ continue;
426
+ }
427
+ }
428
+ catch (error) {
429
+ keep(root, 'Working root worker proof could not be verified: ' + String(error.code ?? 'unavailable'));
430
+ continue;
431
+ }
432
+ for (const name of ['ghidra', 'exports', 'explicit-exports'])
433
+ if (await linked(join(root, name)))
434
+ keep(join(root, name), 'Links and special entries are never removed.');
435
+ if (kind === 'context') {
436
+ const context = workspace.contextById(owner), stages = await peerStages(root, { context: owner, target: context.target });
437
+ let ownershipReason;
438
+ if (stages.length)
439
+ try {
440
+ const linkedOwner = await linked(join(root, 'process.json')) || await linked(join(root, 'native-owner.json'));
441
+ const nativeOwner = nativeRoot && !linkedOwner && (await lstat(join(root, 'native-owner.json'))).isFile() ? await json(join(root, 'native-owner.json')) : undefined;
442
+ if (!worker)
443
+ ownershipReason = 'Cross-target working root has no worker receipt that proves it stopped.';
444
+ else if (linkedOwner)
445
+ ownershipReason = 'Cross-target working root ownership receipt is a link.';
446
+ else if (worker && worker.target !== context.target || nativeRoot && (!nativeOwner || nativeOwner.context !== owner || nativeOwner.target !== context.target))
447
+ ownershipReason = 'Cross-target working root receipt belongs to a different owner.';
448
+ else if (typeof worker.root !== 'string' || !sameDirectory(worker.root, root))
449
+ ownershipReason = 'Cross-target worker receipt does not identify this working root.';
450
+ }
451
+ catch (error) {
452
+ ownershipReason = 'Cross-target working root ownership receipt could not be verified: ' + String(error.code ?? 'unavailable');
453
+ }
454
+ for (const stage of stages) {
455
+ if (ownershipReason)
456
+ keep(stage.folder, ownershipReason);
457
+ else if ('reason' in stage)
458
+ keep(stage.folder, stage.reason);
459
+ else if (stage.receipt.state !== 'closed')
460
+ keep(stage.folder, 'Cross-target cleanup is incomplete; its temporary program removal is unverified.');
461
+ else if (workspace.checkoutReferenced(context, root))
462
+ keep(stage.folder, 'An unresolved operation in another context references this checkout.');
463
+ else if (stage.input)
464
+ await remove(stage.input, 'duplicate-exports');
465
+ }
466
+ }
467
+ // Closed peer exports have their own complete ownership proof, independent of project disposal.
468
+ if (projectOwnershipReason) {
469
+ keep(root, projectOwnershipReason);
470
+ continue;
471
+ }
472
+ const given = kind === 'context' && discarded.has(owner);
473
+ const candidates = kind === 'context' ? captured.get(owner) ?? [] : [...(targetCaptures.get(owner) ?? [])];
474
+ if (kind !== 'context')
475
+ try {
476
+ const shared = workspace.model(owner).sharedSnapshot;
477
+ if (shared?.kind === 'snapshot')
478
+ candidates.push(shared);
479
+ }
480
+ catch { /* Unknown model roots cannot supply capture proof. */ }
481
+ if (!nativeRoot && ((worker?.program !== 'program' && worker?.program !== '/program') || typeof worker.root !== 'string' || !sameDirectory(worker.root, root) || !given && !await detachedCapture(workspace, root, candidates))) {
482
+ keep(root, 'Project has no verified full detached program capture; native JSON receipts do not contain program bytes.');
483
+ continue;
484
+ }
485
+ let cleanupComplete = true;
486
+ for (const file of await files(join(root, 'ghidra')))
487
+ if (file.endsWith('.cache'))
488
+ cleanupComplete = await remove(join(root, 'ghidra', file), 'temporary-caches') && cleanupComplete;
489
+ if (nativeRoot) {
490
+ // The project itself belongs to its checkout lifecycle, including uncertain creations.
491
+ for (const run of await directories(join(root, 'explicit-exports')))
492
+ await remove(join(root, 'explicit-exports', run, 'program.gzf'), 'duplicate-exports');
493
+ continue;
494
+ }
495
+ for (const file of await files(join(root, 'exports')))
496
+ if (exportName.test(file))
497
+ cleanupComplete = await remove(join(root, 'exports', file), 'duplicate-exports') && cleanupComplete;
498
+ // Facade edits are captured as they complete; a GUI save is captured only by an explicit close.
499
+ const stop = worker && await stopReceipt(root, worker);
500
+ if (!given && (!stop || worker?.mode !== 'headless' && stop.reason !== 'explicit_close')) {
501
+ keep(join(root, 'view.rep'), 'Project has no clean stop receipt that proves capture.');
502
+ continue;
503
+ }
504
+ if (!await soleProgram(root)) {
505
+ keep(join(root, 'view.rep'), 'Project holds additional files.');
506
+ continue;
507
+ }
508
+ const projectFiles = ['view.rep', 'view.gpr', 'view.lock', 'view.lock~'];
509
+ for (const file of projectFiles)
510
+ cleanupComplete = await remove(join(root, file), 'detached-projects') && cleanupComplete;
511
+ // Every recognized removal must succeed before its full capture proof can be forgotten.
512
+ if (cleanupComplete && await remove(join(root, 'saved.gzf'), 'duplicate-exports'))
513
+ disposedDetachedRoots.add(root);
316
514
  }
317
- if (!await soleProgram(root)) {
318
- keep(join(root, 'view.rep'), 'Project holds additional files.');
515
+ }
516
+ }
517
+ for (const run of await directories(join(native, 'explicit-exports')))
518
+ await remove(join(native, 'explicit-exports', run, 'program.gzf'), 'duplicate-exports');
519
+ const calls = join(workspace.directory, 'server', 'calls');
520
+ for (const call of await directories(calls))
521
+ for (const file of await files(join(calls, call, 'ghidra')))
522
+ if (file.endsWith('.cache'))
523
+ await remove(join(calls, call, 'ghidra', file), 'temporary-caches');
524
+ // Roots are live rows, unfinished or failed intents, every user-visible result and VT owners.
525
+ const roots = workspace.artifactRoots();
526
+ for (const id of nativeEvidence)
527
+ roots.add(id);
528
+ // Native release above can remove a project and its live context reference in this same pass.
529
+ for (const [id, root] of nativeProjects)
530
+ try {
531
+ if (await present(join(root, 'view.rep')) || await present(join(root, 'view.gpr')))
532
+ roots.add(id);
533
+ }
534
+ catch {
535
+ roots.add(id);
536
+ keep(root, 'Native project inventory could not be verified; its receipt is retained.');
537
+ }
538
+ // Migration journals keep identity, not artifact liveness. A retained saved.gzf still needs its
539
+ // canonical verification copy for the next collection attempt, even after the context migrated.
540
+ for (const kind of ['context', 'shared', 'candidate'])
541
+ for (const owner of await directories(join(native, kind))) {
542
+ const proofs = kind === 'context' ? (discarded.has(owner) ? [] : captured.get(owner) ?? []) : targetCaptures.get(owner) ?? [];
543
+ if (!proofs.length)
319
544
  continue;
545
+ for (const name of await directories(join(native, kind, owner))) {
546
+ const root = join(native, kind, owner, name);
547
+ if (disposedDetachedRoots.has(root))
548
+ continue;
549
+ try {
550
+ if (!await present(join(root, 'saved.gzf')))
551
+ continue;
552
+ }
553
+ catch {
554
+ keep(root, 'Retained capture metadata could not be verified; its snapshot proof is preserved.');
555
+ }
556
+ for (const artifact of proofs)
557
+ roots.add(artifact.id);
320
558
  }
321
- for (const file of ['view.rep', 'view.gpr', 'view.lock', 'view.lock~'])
322
- await remove(join(root, file), 'detached-projects');
323
559
  }
560
+ for (const tracking of await directories(join(workspace.directory, 'version-tracking'))) {
561
+ let owner = '';
562
+ try {
563
+ owner = await readFile(join(workspace.directory, 'version-tracking', tracking, 'owner.json'), 'utf8');
564
+ }
565
+ catch (error) {
566
+ if (!missing(error))
567
+ throw error;
568
+ }
569
+ for (const match of owner.matchAll(/(?:snapshot|native):[a-f0-9]{64}/g))
570
+ roots.add(match[0]);
324
571
  }
325
- }
326
- for (const run of await directories(join(native, 'explicit-exports')))
327
- await remove(join(native, 'explicit-exports', run, 'program.gzf'), 'duplicate-exports');
328
- const calls = join(workspace.directory, 'server', 'calls');
329
- for (const call of await directories(calls))
330
- for (const file of await files(join(calls, call, 'ghidra')))
331
- if (file.endsWith('.cache'))
332
- await remove(join(calls, call, 'ghidra', file), 'temporary-caches');
333
- // Roots are live rows, unfinished or failed intents, every user-visible result and VT owners.
334
- const roots = workspace.artifactRoots();
335
- for (const tracking of await directories(join(workspace.directory, 'version-tracking'))) {
336
- let owner = '';
337
- try {
338
- owner = await readFile(join(workspace.directory, 'version-tracking', tracking, 'owner.json'), 'utf8');
339
- }
340
- catch (error) {
341
- if (!missing(error))
342
- throw error;
572
+ const rows = new Set(workspace.allArtifacts().map(a => a.id));
573
+ if (!dryRun)
574
+ for (const artifact of workspace.allArtifacts())
575
+ if (artifact.kind !== 'input' && !roots.has(artifact.id))
576
+ workspace.forgetArtifact(artifact.id);
577
+ const directory = join(workspace.directory, 'artifacts');
578
+ for (const file of await files(directory)) {
579
+ const match = artifactName.exec(file);
580
+ const id = match && (match[2] === 'gzf' ? 'snapshot:' : 'native:') + match[1];
581
+ // A capture writes its file before its row, so unrowed files are stale only after a day.
582
+ if (id ? !roots.has(id) && (rows.has(id) || await older(join(directory, file), 86400000)) : pendingName.test(file) && await older(join(directory, file), 86400000))
583
+ await remove(join(directory, file), 'unreferenced-snapshots');
343
584
  }
344
- for (const match of owner.matchAll(/(?:snapshot|native):[a-f0-9]{64}/g))
345
- roots.add(match[0]);
585
+ for (const [category, bytes] of Object.entries(reclaimed.bytes()))
586
+ if (categories[category])
587
+ categories[category].bytes += bytes;
588
+ const result = { state: dryRun ? 'planned' : 'complete', dryRun, bytes: Object.values(categories).reduce((n, c) => n + c.bytes, 0), categories, retainedCount: retained.length };
589
+ if (!dryRun)
590
+ await durable(receipt, { schema: 1, id, startedAt, endedAt: new Date().toISOString(), ...result, retained });
591
+ for (const [category, value] of Object.entries(categories))
592
+ auditEvent('gc.category', { gcId: id, dryRun, category, ...value });
593
+ auditEvent('gc.finished', { gcId: id, ...result, outcome: 'success' });
594
+ return { ...result, ...(dryRun ? {} : { id }), retained: retained.slice(0, 200) };
346
595
  }
347
- const rows = new Set(workspace.allArtifacts().map(a => a.id));
348
- if (!dryRun)
349
- for (const artifact of workspace.allArtifacts())
350
- if (artifact.kind !== 'input' && !roots.has(artifact.id))
351
- workspace.forgetArtifact(artifact.id);
352
- const directory = join(workspace.directory, 'artifacts');
353
- for (const file of await files(directory)) {
354
- const match = artifactName.exec(file);
355
- const id = match && (match[2] === 'gzf' ? 'snapshot:' : 'native:') + match[1];
356
- // A capture writes its file before its row, so unrowed files are stale only after a day.
357
- if (id ? !roots.has(id) && (rows.has(id) || await older(join(directory, file), 86400000)) : pendingName.test(file) && await older(join(directory, file), 86400000))
358
- await remove(join(directory, file), 'unreferenced-snapshots');
596
+ catch (error) {
597
+ auditEvent('gc.failed', { gcId: id, dryRun, error, outcome: 'failure' });
598
+ throw error;
359
599
  }
360
- for (const [category, bytes] of Object.entries(reclaimed.bytes()))
361
- if (categories[category])
362
- categories[category].bytes += bytes;
363
- const result = { state: dryRun ? 'planned' : 'complete', dryRun, bytes: Object.values(categories).reduce((n, c) => n + c.bytes, 0), categories, retainedCount: retained.length };
364
- if (!dryRun)
365
- await durable(receipt, { schema: 1, id, startedAt, endedAt: new Date().toISOString(), ...result, retained });
366
- return { ...result, ...(dryRun ? {} : { id }), retained: retained.slice(0, 200) };
367
600
  }