@eyeauras/insight-cli 0.6.6 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (122) hide show
  1. package/.cli-package-build.json +1 -1
  2. package/SKILL.md +1 -1
  3. package/dist/src/activity-audit.d.ts +130 -0
  4. package/dist/src/activity-audit.js +320 -0
  5. package/dist/src/analysis-storage.d.ts +5 -1
  6. package/dist/src/analysis-storage.js +9 -2
  7. package/dist/src/audit-commands.d.ts +10 -0
  8. package/dist/src/audit-commands.js +85 -0
  9. package/dist/src/audit-retention.d.ts +44 -0
  10. package/dist/src/audit-retention.js +167 -0
  11. package/dist/src/cli.js +28 -6
  12. package/dist/src/context-diagnostics.d.ts +1 -1
  13. package/dist/src/context-diagnostics.js +10 -2
  14. package/dist/src/contexts.d.ts +118 -10
  15. package/dist/src/contexts.js +851 -199
  16. package/dist/src/debugger.js +2 -1
  17. package/dist/src/diagnostic-error.d.ts +12 -0
  18. package/dist/src/diagnostic-error.js +82 -0
  19. package/dist/src/inline-script.js +3 -4
  20. package/dist/src/internal-timing.d.ts +8 -2
  21. package/dist/src/internal-timing.js +50 -7
  22. package/dist/src/lifecycle.d.ts +12 -1
  23. package/dist/src/lifecycle.js +34 -6
  24. package/dist/src/native-inputs.d.ts +6 -0
  25. package/dist/src/native-inputs.js +30 -6
  26. package/dist/src/native-queries.js +1 -6
  27. package/dist/src/native-service.d.ts +40 -0
  28. package/dist/src/native-service.js +406 -0
  29. package/dist/src/research.d.ts +30 -2
  30. package/dist/src/research.js +106 -27
  31. package/dist/src/server.d.ts +38 -1
  32. package/dist/src/server.js +160 -12
  33. package/dist/src/storage-gc.js +374 -341
  34. package/dist/src/sync-policy.js +2 -1
  35. package/dist/src/timed-backend.js +8 -0
  36. package/dist/src/timing-report.d.ts +32 -0
  37. package/dist/src/timing-report.js +74 -0
  38. package/dist/src/tool-runtime/identity.js +86 -1
  39. package/dist/src/tool-runtime/supervisor.js +6 -5
  40. package/dist/src/transport.d.ts +35 -0
  41. package/dist/src/transport.js +95 -16
  42. package/dist/src/unresolved-guidance.d.ts +46 -0
  43. package/dist/src/unresolved-guidance.js +55 -0
  44. package/dist/src/windbg.d.ts +1 -1
  45. package/dist/src/worker-lease.d.ts +17 -0
  46. package/dist/src/worker-lease.js +50 -0
  47. package/dist/src/workspace.d.ts +5 -9
  48. package/dist/src/workspace.js +34 -41
  49. package/package.json +1 -1
  50. package/references/native/InsightHeadlessMain.java +9 -2
  51. package/references/native/InsightNativeCheckout.java +113 -43
  52. package/references/native/InsightNativeFingerprint.java +28 -1
  53. package/references/native/InsightNativeRead.java +32 -9
  54. package/references/native/InsightNativeService.java +43 -0
  55. package/references/native/InsightNativeView.java +17 -6
  56. package/references/native/InsightOwnedScripts.java +170 -0
  57. package/references/native/InsightWorkerLease.java +132 -0
  58. package/references/recovery.md +68 -3
  59. package/references/research.md +71 -6
  60. package/references/setup.md +5 -1
  61. package/skill-bundle/insight-artifacts/SKILL.md +1 -1
  62. package/skill-bundle/insight-artifacts/references/recovery.md +68 -3
  63. package/skill-bundle/insight-binary/SKILL.md +1 -1
  64. package/skill-bundle/insight-capture/SKILL.md +1 -1
  65. package/skill-bundle/insight-cli/SKILL.md +1 -1
  66. package/skill-bundle/insight-cli/references/recovery.md +68 -3
  67. package/skill-bundle/insight-cli/references/setup.md +5 -1
  68. package/skill-bundle/insight-die/SKILL.md +1 -1
  69. package/skill-bundle/insight-dnspy/SKILL.md +1 -1
  70. package/skill-bundle/insight-dotnet-dump/SKILL.md +1 -1
  71. package/skill-bundle/insight-dotnet-stack/SKILL.md +1 -1
  72. package/skill-bundle/insight-dotnet-trace/SKILL.md +1 -1
  73. package/skill-bundle/insight-frida/SKILL.md +1 -1
  74. package/skill-bundle/insight-ghidra/SKILL.md +1 -1
  75. package/skill-bundle/insight-ghidra/references/recovery.md +68 -3
  76. package/skill-bundle/insight-ghidra/references/research.md +71 -6
  77. package/skill-bundle/insight-ghidra/references/setup.md +5 -1
  78. package/skill-bundle/insight-ilspy/SKILL.md +1 -1
  79. package/skill-bundle/insight-interop/SKILL.md +1 -1
  80. package/skill-bundle/insight-lldb/SKILL.md +1 -1
  81. package/skill-bundle/insight-llvm/SKILL.md +1 -1
  82. package/skill-bundle/insight-managed-heap/SKILL.md +1 -1
  83. package/skill-bundle/insight-managed-metadata/SKILL.md +1 -1
  84. package/skill-bundle/insight-mitmproxy/SKILL.md +1 -1
  85. package/skill-bundle/insight-overview/SKILL.md +1 -1
  86. package/skill-bundle/insight-procmon/SKILL.md +1 -1
  87. package/skill-bundle/insight-re/SKILL.md +7 -1
  88. package/skill-bundle/insight-re/references/recovery.md +68 -3
  89. package/skill-bundle/insight-sevenzip/SKILL.md +1 -1
  90. package/skill-bundle/insight-strace/SKILL.md +1 -1
  91. package/skill-bundle/insight-tshark/SKILL.md +1 -1
  92. package/skill-bundle/insight-windbg/SKILL.md +1 -1
  93. package/skill-bundle/manifest.json +1 -1
  94. package/skills/insight-artifacts/SKILL.md +1 -1
  95. package/skills/insight-artifacts/references/recovery.md +68 -3
  96. package/skills/insight-binary/SKILL.md +1 -1
  97. package/skills/insight-capture/SKILL.md +1 -1
  98. package/skills/insight-die/SKILL.md +1 -1
  99. package/skills/insight-dnspy/SKILL.md +1 -1
  100. package/skills/insight-dotnet-dump/SKILL.md +1 -1
  101. package/skills/insight-dotnet-stack/SKILL.md +1 -1
  102. package/skills/insight-dotnet-trace/SKILL.md +1 -1
  103. package/skills/insight-frida/SKILL.md +1 -1
  104. package/skills/insight-ghidra/SKILL.md +1 -1
  105. package/skills/insight-ghidra/references/recovery.md +68 -3
  106. package/skills/insight-ghidra/references/research.md +71 -6
  107. package/skills/insight-ghidra/references/setup.md +5 -1
  108. package/skills/insight-ilspy/SKILL.md +1 -1
  109. package/skills/insight-interop/SKILL.md +1 -1
  110. package/skills/insight-lldb/SKILL.md +1 -1
  111. package/skills/insight-llvm/SKILL.md +1 -1
  112. package/skills/insight-managed-heap/SKILL.md +1 -1
  113. package/skills/insight-managed-metadata/SKILL.md +1 -1
  114. package/skills/insight-mitmproxy/SKILL.md +1 -1
  115. package/skills/insight-overview/SKILL.md +1 -1
  116. package/skills/insight-procmon/SKILL.md +1 -1
  117. package/skills/insight-re/SKILL.md +7 -1
  118. package/skills/insight-re/references/recovery.md +68 -3
  119. package/skills/insight-sevenzip/SKILL.md +1 -1
  120. package/skills/insight-strace/SKILL.md +1 -1
  121. package/skills/insight-tshark/SKILL.md +1 -1
  122. package/skills/insight-windbg/SKILL.md +1 -1
@@ -0,0 +1,167 @@
1
+ import { readdirSync, unlinkSync, writeFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { randomBytes } from 'node:crypto';
4
+ import { CliError } from '@eyeauras/cli-factory';
5
+ export const auditLimits = { events: 20000, days: 30, eventBytes: 4096, databaseBytes: 16 * 1024 * 1024, sweepIntervalMs: 5 * 60000 };
6
+ export function auditUnavailable() { throw new CliError('Audit history is unavailable or incompatible; preserve its files. No history was reset.', { code: 'audit.unavailable' }); }
7
+ export function auditPolicy(input) {
8
+ const policy = { events: input.events, days: input.days, databaseBytes: input.databaseBytes ?? auditLimits.databaseBytes };
9
+ if (!Number.isSafeInteger(policy.events) || policy.events < 4 || policy.events > auditLimits.events || !Number.isSafeInteger(policy.days) || policy.days < 1 || policy.days > auditLimits.days || !Number.isSafeInteger(policy.databaseBytes) || policy.databaseBytes < 256 * 1024 || policy.databaseBytes > auditLimits.databaseBytes)
10
+ auditUnavailable();
11
+ return policy;
12
+ }
13
+ const keys = ['retentionEvents', 'retentionDays', 'retentionBytes', 'lastSweepMs', 'gcRuns', 'lastGcRemoved'];
14
+ function set(db, key, value) { if (!Number.isSafeInteger(value) || value < 0)
15
+ auditUnavailable(); db.prepare('INSERT OR REPLACE INTO metadata(key,value) VALUES(?,?)').run(key, String(value)); }
16
+ /** Called only in the owned schema initialization/upgrade transaction. Never overwrite unknown metadata. */
17
+ export function initializeRetention(db, policy, now) {
18
+ for (const key of keys)
19
+ if (db.prepare('SELECT value FROM metadata WHERE key=?').get(key))
20
+ auditUnavailable();
21
+ db.exec("ALTER TABLE events ADD COLUMN writer_version INTEGER NOT NULL DEFAULT 1; CREATE TRIGGER audit_writer_v2 BEFORE INSERT ON events WHEN NEW.writer_version IS NOT 2 BEGIN SELECT RAISE(ABORT,'Incompatible audit writer'); END;");
22
+ for (const [key, value] of Object.entries({ retentionEvents: policy.events, retentionDays: policy.days, retentionBytes: policy.databaseBytes, lastSweepMs: now, gcRuns: 0, lastGcRemoved: 0 }))
23
+ set(db, key, value);
24
+ db.exec('PRAGMA user_version=2');
25
+ }
26
+ export function retentionState(db) {
27
+ if (!db.prepare("SELECT name FROM sqlite_master WHERE type='trigger' AND name='audit_writer_v2'").get())
28
+ auditUnavailable();
29
+ const rows = db.prepare("SELECT key,value FROM metadata WHERE key IN ('retentionEvents','retentionDays','retentionBytes','lastSweepMs','gcRuns','lastGcRemoved')").all(), values = {};
30
+ for (const row of rows) {
31
+ if (typeof row.key !== 'string' || typeof row.value !== 'string' || !/^\d+$/.test(row.value) || !Number.isSafeInteger(Number(row.value)))
32
+ auditUnavailable();
33
+ values[row.key] = Number(row.value);
34
+ }
35
+ if (keys.some(key => values[key] === undefined))
36
+ auditUnavailable();
37
+ return { policy: auditPolicy({ events: values.retentionEvents, days: values.retentionDays, databaseBytes: values.retentionBytes }), lastSweepMs: values.lastSweepMs, runs: values.gcRuns, lastRemoved: values.lastGcRemoved };
38
+ }
39
+ export function auditStorageMode(db) { return { autoVacuum: Number(db.prepare('PRAGMA auto_vacuum').get()?.auto_vacuum), journalMode: String(db.prepare('PRAGMA journal_mode').get()?.journal_mode) }; }
40
+ export function requireAuditStorageMode(db) { const mode = auditStorageMode(db); if (mode.autoVacuum !== 1 || mode.journalMode !== 'delete')
41
+ auditUnavailable(); }
42
+ const writerWait = new Int32Array(new SharedArrayBuffer(4));
43
+ const pause = (ms) => { if (ms > 0)
44
+ Atomics.wait(writerWait, 0, 0, ms); };
45
+ const waiterName = /^\.writer-(\d{13})-(\d{13})-(\d+)-([a-f0-9]{16})$/;
46
+ /** Older waiters of live processes, oldest first; stale or foreign entries never block admission. */
47
+ function olderWaiters(directory, own, now) {
48
+ let names;
49
+ try {
50
+ names = readdirSync(directory);
51
+ }
52
+ catch {
53
+ return [];
54
+ }
55
+ return names.filter(name => {
56
+ const match = waiterName.exec(name);
57
+ if (!match || name >= own)
58
+ return false;
59
+ const deadline = Number(match[2]), pid = Number(match[3]);
60
+ // A waiter gives up at its own admission deadline; a marker past it (or of a dead process) is abandoned,
61
+ // so even a reused PID can hold others back no longer than that waiter's own wait.
62
+ if (now > deadline + 1000 || !live(pid)) {
63
+ try {
64
+ unlinkSync(join(directory, name));
65
+ }
66
+ catch { /* Another writer removed it. */ }
67
+ return false;
68
+ }
69
+ return true;
70
+ });
71
+ }
72
+ function live(pid) { try {
73
+ process.kill(pid, 0);
74
+ return true;
75
+ }
76
+ catch (error) {
77
+ return error.code === 'EPERM';
78
+ } }
79
+ export const auditAdmissionMs = 3000;
80
+ /**
81
+ * Fair writer admission across processes. SQLite has no queue: a continuously re-entering writer can win every
82
+ * free interval and starve others past the deadline. Each writer registers an ordered waiter marker, only the
83
+ * oldest live waiter contends for the lock, and the marker is removed as soon as the lock is held.
84
+ * Retry only a definitely unacquired auxiliary DB lock, never INSERT, COMMIT or a tool action.
85
+ */
86
+ export function acquireAuditWriter(db, directory, admissionMs = auditAdmissionMs) {
87
+ const started = Date.now(), deadline = performance.now() + admissionMs;
88
+ let attempt = 0;
89
+ const own = '.writer-' + String(started).padStart(13, '0') + '-' + String(started + admissionMs).padStart(13, '0') + '-' + process.pid + '-' + randomBytes(8).toString('hex'), marker = join(directory, own);
90
+ let registered = false;
91
+ try {
92
+ writeFileSync(marker, '', { flag: 'wx', mode: 0o600 });
93
+ registered = true;
94
+ }
95
+ catch { /* Without a marker this writer contends unordered, as before. */ }
96
+ try {
97
+ for (;;) {
98
+ if (registered && olderWaiters(directory, own, Date.now()).length && performance.now() < deadline) {
99
+ pause(Math.min(2, deadline - performance.now()));
100
+ continue;
101
+ }
102
+ const remaining = deadline - performance.now();
103
+ db.exec('PRAGMA busy_timeout=' + Math.max(0, Math.min(50, Math.ceil(remaining))));
104
+ try {
105
+ db.exec('BEGIN IMMEDIATE');
106
+ return;
107
+ }
108
+ catch (error) {
109
+ let busy = false;
110
+ try {
111
+ const e = error;
112
+ busy = e?.code === 'ERR_SQLITE_ERROR' && typeof e.errcode === 'number' && Number.isSafeInteger(e.errcode) && e.errcode > 0 && [5, 6].includes(e.errcode & 255);
113
+ }
114
+ catch { }
115
+ if (!busy || performance.now() >= deadline)
116
+ throw error;
117
+ // SQLite's long busy-handler backoff can repeatedly miss short free intervals; restart it with bounded jitter.
118
+ pause(Math.max(0, Math.min(5 + (process.pid + attempt++ * 13) % 21, deadline - performance.now())));
119
+ }
120
+ }
121
+ }
122
+ finally {
123
+ if (registered)
124
+ try {
125
+ unlinkSync(marker);
126
+ }
127
+ catch { /* Removed by a peer as abandoned. */ }
128
+ // The admitted writer's commit waits for readers as long as its admission did.
129
+ db.exec('PRAGMA busy_timeout=' + Math.max(3000, Math.ceil(admissionMs)));
130
+ }
131
+ }
132
+ export function liveAuditBytes(db) { return (Number(db.prepare('PRAGMA page_count').get()?.page_count) - Number(db.prepare('PRAGMA freelist_count').get()?.freelist_count)) * Number(db.prepare('PRAGMA page_size').get()?.page_size); }
133
+ function count(db) { return Number(db.prepare('SELECT count(*) count FROM events').get().count); }
134
+ /** The caller holds BEGIN IMMEDIATE. Summary insertion is direct, never another append/GC call. */
135
+ export function collectAudit(db, now, incoming, pruned, state, summary) {
136
+ const policy = state.policy, eventsBefore = count(db), liveBytesBefore = liveAuditBytes(db), periodic = now < state.lastSweepMs || now - state.lastSweepMs >= auditLimits.sweepIntervalMs;
137
+ const reserve = 128 * 1024, eventPressure = eventsBefore > policy.events || periodic && eventsBefore + 1 > policy.events, bytePressure = liveBytesBefore > policy.databaseBytes || periodic && liveBytesBefore + reserve > policy.databaseBytes;
138
+ if (!periodic && !eventPressure && !bytePressure)
139
+ return;
140
+ const expiredEvents = Number(db.prepare('DELETE FROM events WHERE at_ms<? AND seq<>?').run(now - policy.days * 86400000, incoming).changes);
141
+ let removed = expiredEvents;
142
+ const targetEvents = Math.max(2, Math.floor(policy.events * 0.8));
143
+ const drop = (n) => Number(db.prepare('DELETE FROM events WHERE seq IN (SELECT seq FROM events WHERE seq<>? ORDER BY seq LIMIT ?)').run(incoming, n).changes);
144
+ if (eventPressure)
145
+ removed += drop(Math.max(0, count(db) - (targetEvents - 1))); // reserve the GC record itself
146
+ const trimBytes = bytePressure || liveAuditBytes(db) + reserve > policy.databaseBytes;
147
+ if (trimBytes) {
148
+ const targetBytes = Math.min(Math.floor(policy.databaseBytes * 0.75), policy.databaseBytes - reserve);
149
+ while (liveAuditBytes(db) > targetBytes) {
150
+ const changed = drop(Math.max(1, Math.ceil(count(db) * 0.1)));
151
+ if (!changed)
152
+ auditUnavailable();
153
+ removed += changed;
154
+ }
155
+ }
156
+ // Account for the maintenance event even if the original pressure was only age.
157
+ if (count(db) + 1 > policy.events)
158
+ removed += drop(Math.max(0, count(db) - (targetEvents - 1)));
159
+ const eventsAfter = count(db) + 1, liveBytesAfterPrune = liveAuditBytes(db);
160
+ set(db, 'prunedEvents', pruned + removed);
161
+ set(db, 'lastSweepMs', now);
162
+ set(db, 'gcRuns', state.runs + 1);
163
+ set(db, 'lastGcRemoved', removed);
164
+ summary({ automatic: true, state: 'complete', outcome: 'success', gcTrigger: eventPressure && trimBytes ? 'multiple' : eventPressure ? 'event-limit' : trimBytes ? 'byte-limit' : 'periodic', removedEvents: removed, expiredEvents, eventsBefore, eventsAfter, liveBytesBefore, liveBytesAfterPrune });
165
+ if (count(db) > policy.events || liveAuditBytes(db) > policy.databaseBytes)
166
+ auditUnavailable();
167
+ }
package/dist/src/cli.js CHANGED
@@ -57,6 +57,8 @@ import { codeReferenceCommands } from './code-references.js';
57
57
  import { stringAnchorCommands } from './string-anchors.js';
58
58
  import { contextDiagnosticCommands } from './context-diagnostics.js';
59
59
  import { traceCommand } from './internal-timing.js';
60
+ import { withWorkerLeases } from './worker-lease.js';
61
+ import { ActivityAudit } from './audit-commands.js';
60
62
  import { timedBackend } from './timed-backend.js';
61
63
  import { readInitialProgress } from './initial-progress.js';
62
64
  const bindingFields = ['java', 'ghidraHome', 'mcpJar', 'mcpJarSha256', 'server', 'repository', 'readerUser', 'publisherUser', 'maxContexts', 'debuggerPython', 'windbgDir', 'archiveUrl'];
@@ -77,6 +79,8 @@ class Owner {
77
79
  try {
78
80
  if (!quiescent)
79
81
  return await action();
82
+ if (current)
83
+ await (await current.backend)?.quiesce?.();
80
84
  const processes = await runtimeProcesses(directory);
81
85
  if (processes.length)
82
86
  fail('busy', 'Close Ghidra contexts and stop the owned server before changing or checking the runtime.', { processes });
@@ -163,6 +167,8 @@ class Owner {
163
167
  fail('busy', 'Finish research operations before ' + name + '.');
164
168
  this.runtimeChanging.add(c.appArguments.AppDataDirectory);
165
169
  try {
170
+ // Idle services and idle warm workers hold saved work only; held ones keep the refusal below.
171
+ await (await selected.backend()).quiesce?.();
166
172
  // A missing private-worker receipt does not prove an interrupted native helper stopped.
167
173
  const helpers = await migrationProcessBlockers(c.appArguments.AppDataDirectory);
168
174
  const workers = (await runtimeProcesses(analysisDirectory(c))).filter(p => p.kind !== 'server');
@@ -180,6 +186,9 @@ class Owner {
180
186
  fail('busy', 'Storage migration is in progress.');
181
187
  if (this.runtimeChanging.has(directory))
182
188
  fail('busy', 'Runtime preparation is in progress; finish it before changing or deleting the profile.');
189
+ // Idle services and idle warm workers of this owner hold no work; held ones keep the refusals below.
190
+ if (profile && !profile.tasks.size)
191
+ await (await profile.backend)?.quiesce?.();
183
192
  if (toolProfileBusy(directory))
184
193
  fail('busy', 'A tool operation is active.');
185
194
  if ((await listProcesses(directory)).some(r => !['exited', 'failed'].includes(r.state)))
@@ -194,6 +203,9 @@ class Owner {
194
203
  this.profiles.delete(directory);
195
204
  }
196
205
  }
206
+ /** Idle services and idle warm workers of an otherwise idle profile owner hold no work and may stop. */
207
+ async quiesceProfile(c) { const profile = this.profiles.get(c.appArguments.AppDataDirectory); if (profile && !profile.tasks.size)
208
+ await (await profile.backend)?.quiesce?.(); }
197
209
  async releaseStorage(c) {
198
210
  const directory = c.appArguments.AppDataDirectory, profile = this.profiles.get(directory);
199
211
  if (!profile)
@@ -271,6 +283,7 @@ const fields = [
271
283
  ['initialImportSeconds', '--initial-import-seconds <seconds>', 'Initial import/analysis budget (default 3600, range 1–86400 seconds)'],
272
284
  ['saveSeconds', '--save-seconds <seconds>', 'Native save/export budget (default 120, range 1–3600 seconds)'],
273
285
  ['maxContexts', '--max-contexts <count>', 'Concurrent contexts (default 4, maximum 16)'],
286
+ ['contextIdleMinutes', '--context-idle-minutes <minutes>', 'Idle minutes after the last command before a context worker stops itself (default 15, range 1–1440)'],
274
287
  ['debuggerPython', '--debugger-python <path>', 'Optional Python executable for a configured debugger offer'],
275
288
  ['windbgDir', '--windbg-dir <path>', 'Optional Windows debugger runtime directory'],
276
289
  ['archiveUrl', '--archive-url <url>', 'Explicit archive service base URL (disabled by default)'],
@@ -328,24 +341,28 @@ function scopedFailures(entry, owner, parents = []) {
328
341
  catch {
329
342
  throw error;
330
343
  }
344
+ if (selected.session === 'new')
345
+ throw error;
331
346
  if (!(error instanceof CliError))
332
347
  throw error;
333
348
  const result = error.result && typeof error.result === 'object' && !Array.isArray(error.result) ? error.result : {};
334
349
  throw new CliError(error.message, { code: error.code, exitCode: error.exitCode, next: error.next, result: { ...result, ...selected } });
335
350
  }
336
351
  };
337
- return path[1] === 'open' || input.options.session && input.options.target ? traceCommand(join(analysisDirectory(c), 'workspace'), name, execute) : execute();
352
+ // Context workers used by this command keep their idle lease until it ends.
353
+ const leased = () => withWorkerLeases(execute);
354
+ return path[1] === 'open' || input.options.session && input.options.target ? traceCommand(join(analysisDirectory(c), 'workspace'), name, leased, { session: input.options.session, target: input.options.target }) : leased();
338
355
  } } : {}) };
339
356
  }
340
357
  export function createDefinition(options = {}) {
341
358
  const owner = new Owner(options);
342
- const storage = new AnalysisStorage(options.runtime?.profileStore, c => owner.releaseStorage(c));
359
+ const storage = new AnalysisStorage(options.runtime?.profileStore, c => owner.releaseStorage(c), undefined, c => owner.quiesceProfile(c));
343
360
  owner.storage = storage;
344
361
  const definition = {
345
362
  name: 'insight-cli', applicationId: 'insight-cli', version: packageVersion, description: 'Isolated research contexts and coordinated Ghidra analysis',
346
363
  resources: [owner], permissions: { categories: [{ name: 'Destructive', description: 'Explicit deletion or replacement of retained research data', enabledByDefault: false }] }, ...(options.runtime ? { runtime: options.runtime } : {}),
347
364
  profile: { fields: fields.map(([name, flags, description]) => ({ name: name, flags: flags, description: description,
348
- ...(['maxContexts', 'initialImportSeconds', 'saveSeconds'].includes(name) ? { normalize: (value) => number(value, name === 'maxContexts' ? 16 : name === 'saveSeconds' ? 3600 : 86400, 1) } : {}) })) },
365
+ ...(['maxContexts', 'initialImportSeconds', 'saveSeconds', 'contextIdleMinutes'].includes(name) ? { normalize: (value) => number(value, name === 'maxContexts' ? 16 : name === 'saveSeconds' ? 3600 : name === 'contextIdleMinutes' ? 1440 : 86400, 1) } : {}) })) },
349
366
  auth: {
350
367
  loginOptions: [{ flags: '--role <role>', description: 'External reader, publisher or archive role', defaultValue: 'reader' },
351
368
  { flags: '--password-stdin', description: 'Read the password from stdin' }],
@@ -462,9 +479,9 @@ export function createDefinition(options = {}) {
462
479
  }, { permission: Permission.Update, options: [{ flags: '--initial-import-seconds <seconds>', description: 'Initial import/analysis: 1–86400 seconds' },
463
480
  { flags: '--save-seconds <seconds>', description: 'Native save/export: 1–3600 seconds' }] })
464
481
  ]),
465
- command('abandon', 'Retain an uncertain legacy detached program attempt and resume its previous saved view', ({ options: o }, c) => owner.selected(c).research.abandon(scope(o), id(o.requestId), Boolean(o.acknowledgeUnknownEffects)), { permission: 'Destructive', options: [...scoped, { flags: '--request-id <id>', description: 'Original unresolved request ID from sessions status', required: true }, { flags: '--acknowledge-unknown-effects', description: 'Acknowledge that the abandoned effect remains unknown; no script is replayed' }] }),
482
+ command('abandon', 'Retain an uncertain legacy detached program attempt and resume its previous saved view', ({ options: o }, c) => owner.selected(c).research.abandon(scope(o), id(o.requestId), Boolean(o.acknowledgeUnknownEffects)), { permission: 'Destructive', options: [...scoped, { flags: '--request-id <id>', description: 'Original unresolved request ID from `insight-cli sessions status <session> --target <target>`', required: true }, { flags: '--acknowledge-unknown-effects', description: 'Acknowledge that the abandoned effect remains unknown; no script is replayed' }] }),
466
483
  command('refresh', 'Receive safe shared changes while retaining local conflicts', ({ options: o }, c) => owner.selected(c).research.refresh(scope(o), o.requestId === undefined ? undefined : id(o.requestId)), { permission: Permission.Update, options: [...scoped, request] }),
467
- command('merge', 'Publish the complete selected context or retain every conflict', ({ options: o }, c) => owner.selected(c).research.merge(scope(o), o.requestId === undefined ? undefined : id(o.requestId)), { permission: Permission.Update, options: [...scoped, request] }),
484
+ command('merge', 'Publish the complete selected context or retain every conflict; the context stays open at the published version', ({ options: o }, c) => owner.selected(c).research.merge(scope(o), o.requestId === undefined ? undefined : id(o.requestId), Boolean(o.close)), { permission: Permission.Update, options: [...scoped, request, { flags: '--close', description: 'Release the working copy after publishing instead of continuing in it' }] }),
468
485
  command('open [input]', 'Start independent work or continue a context', async ({ args, options: o }, c) => {
469
486
  if (Boolean(args.input) === Boolean(o.target))
470
487
  fail('invalid', 'Supply exactly one input path or --target.');
@@ -581,6 +598,11 @@ export function createDefinition(options = {}) {
581
598
  const commands = definition.commands?.map(entry => entry.name === 'ghidra' ?
582
599
  scopedFailures({ ...entry, children: extendQueries(extendQueries(extendQueries(entry.children ?? [], queryCommands(c => owner.selected(c).research)), mutationCommands(c => owner.selected(c).research)), [...codeReferenceCommands(c => owner.selected(c).research), ...stringAnchorCommands(c => owner.selected(c).research), ...contextDiagnosticCommands(c => owner.selected(c).research, c => owner.selected(c).workspace), ...sdkCommands(c => owner.selected(c).research), ...sdkFileCommands(c => owner.selected(c).sdkFiles), ...trackingCommands(c => owner.selected(c).tracking), ...crossCommands(c => owner.selected(c).research), ...administrationCommands(c => owner.selected(c).administration, options.backend ? undefined : async (c) => { const status = await new RuntimeManager(c).status(); return status.state === 'not_ready' ? { ...status.server, connected: false, state: 'runtime_not_ready', missing: status.missing } : undefined; }),
583
600
  ...extensionCommands(c => new Extensions(join(analysisDirectory(c), 'workspace'))), ...extensionInventoryCommands(c => owner.selected(c).backend), ...pluginCommands(c => owner.selected(c).ui), ...synchronizationCommands(c => owner.selected(c).synchronization), ...utilityCommands(), ...runtimeCommands((c, action, quiescent) => owner.runtime(c, action, quiescent)), ...lifecycleCommands(c => owner.selected(c).lifecycle, c => new RuntimeManager(c).status()), ...projectCommands(c => owner.selected(c).projects), ...uiCommands(c => owner.selected(c).ui), ...debuggerCommands(c => owner.selected(c).debugger), ...archiveCommands(c => owner.selected(c).archive)]) }, owner) : entry);
584
- return { ...definition, commands: [...(commands ?? []).map(e => storage.wrap(e)), storage.commands()] };
601
+ const audit = new ActivityAudit(), auth = definition.auth;
602
+ return { ...definition, auth: { ...auth,
603
+ login: (c, o) => audit.run(c, 'auth login', { args: {}, options: {} }, () => auth.login(c, o)),
604
+ status: c => audit.run(c, 'auth status', { args: {}, options: {} }, () => auth.status(c)),
605
+ logout: c => audit.run(c, 'auth logout', { args: {}, options: {} }, () => auth.logout(c)),
606
+ }, commands: [...[...(commands ?? []).map(e => storage.wrap(e)), storage.commands()].map(e => audit.wrap(e)), audit.commands()] };
585
607
  }
586
608
  export const createInsightCli = (options = {}) => createCli(createDefinition(options));
@@ -1,7 +1,7 @@
1
1
  import { type CommandContext, type CommandDefinition } from '@eyeauras/cli-factory';
2
2
  import { type Research } from './research.js';
3
3
  import type { Workspace, Scope } from './workspace.js';
4
- export type StopReason = 'explicit_close' | 'view_replaced' | 'mode_changed' | 'owner_dispose' | 'startup_failed' | 'temporary_complete' | 'legacy_cleanup' | 'backend_unresponsive' | 'unknown';
4
+ export type StopReason = 'explicit_close' | 'view_replaced' | 'mode_changed' | 'owner_dispose' | 'startup_failed' | 'temporary_complete' | 'legacy_cleanup' | 'backend_unresponsive' | 'idle_timeout' | 'capacity_evicted' | 'runtime_changed' | 'maintenance' | 'unknown';
5
5
  type Event = {
6
6
  at: string;
7
7
  event: 'start' | 'restore' | 'stop';
@@ -5,9 +5,10 @@ import { randomUUID } from 'node:crypto';
5
5
  import { scope, number } from './research.js';
6
6
  import { object, fail, stable } from './model.js';
7
7
  import { selectedOptions } from './arguments.js';
8
+ import { timingDiagnostic } from './timing-report.js';
8
9
  const writes = new Map();
9
10
  const journal = (workspace, context) => join(workspace.directory, 'diagnostics', 'lifecycle', context + '.json');
10
- const reasons = new Set(['explicit_close', 'view_replaced', 'mode_changed', 'owner_dispose', 'startup_failed', 'temporary_complete', 'legacy_cleanup', 'unknown', 'native_launch', 'saved_snapshot', 'backend_unresponsive']);
11
+ const reasons = new Set(['explicit_close', 'view_replaced', 'mode_changed', 'owner_dispose', 'startup_failed', 'temporary_complete', 'legacy_cleanup', 'unknown', 'native_launch', 'saved_snapshot', 'backend_unresponsive', 'idle_timeout', 'capacity_evicted', 'runtime_changed', 'maintenance']);
11
12
  async function events(path) {
12
13
  try {
13
14
  const rows = JSON.parse(await readFile(path, 'utf8'));
@@ -64,6 +65,8 @@ export async function lifecycleDiagnostic(workspace, selected) {
64
65
  }
65
66
  return { ...selected, lifecycle: { events: await events(journal(workspace, context.id)), maximumEvents: 128, ...(latest ? { latest } : {}), ownerShutdownCause: 'unknown', coverage: 'Retained facade observations, at most the latest 128 events; absent events and historical causes remain unknown. This read neither starts nor probes a native process.' } };
66
67
  }
68
+ function commandName(value) { if (typeof value !== 'string' || !/^[a-z][a-z0-9 -]{0,79}$/.test(value))
69
+ fail('invalid', '--command must be an exact command name such as "ghidra open".'); return value; }
67
70
  export function navigationResult(raw, maximum) {
68
71
  const value = object(raw), scan = object(value.scan), functions = object(value.functions);
69
72
  const samples = ['functions', 'instructions', 'references', 'definedData'].map(key => object(value[key]));
@@ -77,6 +80,11 @@ export function navigationResult(raw, maximum) {
77
80
  export function contextDiagnosticCommands(research, workspace) {
78
81
  return [
79
82
  command('analysis', 'Analysis observations', [command('navigation', 'Inspect bounded navigation metadata; ready is not analysis completeness', ({ options: o }, c) => research(c).navigation(scope(o), number(o.maxScan ?? 10000, 200000, 1)), { permission: Permission.ReadOnly, options: [...selectedOptions, { flags: '--max-scan <count>', description: 'Maximum visited metadata inputs across all samples, 1–200000', defaultValue: 10000 }] })]),
80
- command('diagnostics', 'Inspect retained context diagnostics', [command('lifecycle', 'Read retained start/restore/stop reasons without starting Ghidra', ({ options: o }, c) => lifecycleDiagnostic(workspace(c), scope(o)), { permission: Permission.ReadOnly, options: selectedOptions })]),
83
+ command('diagnostics', 'Inspect retained context diagnostics', [command('lifecycle', 'Read retained start/restore/stop reasons without starting Ghidra', ({ options: o }, c) => lifecycleDiagnostic(workspace(c), scope(o)), { permission: Permission.ReadOnly, options: selectedOptions }),
84
+ command('timings', 'Summarize retained per-phase durations of recent commands without starting Ghidra', ({ options: o }, c) => {
85
+ const selected = scope(o), w = workspace(c);
86
+ w.context(selected);
87
+ return timingDiagnostic(w.directory, selected, { limit: number(o.limit ?? 5, 50, 1), ...(o.command === undefined ? {} : { command: commandName(o.command) }) });
88
+ }, { permission: Permission.ReadOnly, options: [...selectedOptions, { flags: '--command <name>', description: 'Exact command name, for example "ghidra open"' }, { flags: '--limit <count>', description: 'Most recent command attempts, 1–50', defaultValue: 5 }] })]),
81
89
  ];
82
90
  }
@@ -1,4 +1,4 @@
1
- import type { CommandContext } from '@eyeauras/cli-factory';
1
+ import { type CommandContext } from '@eyeauras/cli-factory';
2
2
  import { type ChildProcess } from 'node:child_process';
3
3
  import { type NativeInputs } from './native-inputs.js';
4
4
  import { GhidraServer } from './server.js';
@@ -24,13 +24,17 @@ interface ProcessBinding {
24
24
  kind: 'context' | 'shared' | 'bootstrap' | 'candidate';
25
25
  baseRevision?: number;
26
26
  viewEpoch?: number;
27
+ /** Loopback idle-lease endpoint of a headless context worker that cools down by itself. */
28
+ leasePort?: number;
29
+ idleMs?: number;
30
+ /** Identity of the package helper sources this worker's classes were compiled from. */
31
+ helpers?: string;
27
32
  }
28
33
  interface Running {
29
34
  binding: ProcessBinding;
30
35
  http: HttpBridge;
31
36
  child?: ChildProcess;
32
37
  }
33
- /** Isolated native contexts. This layer has no agent-facing instance/worker selector. */
34
38
  export declare class GhidraContexts {
35
39
  private readonly workspace;
36
40
  private readonly inputs;
@@ -67,9 +71,35 @@ export declare class GhidraContexts {
67
71
  sdkFile(operation: string, parameters: Record<string, unknown>): Promise<Record<string, unknown>>;
68
72
  private prepareRoot;
69
73
  private launch;
74
+ /** The worker's own retirement receipt: when and why it stopped by itself. */
75
+ private idleExit;
76
+ private idleMs;
77
+ /** The process behind a receipt PID is gone or is no longer the recorded worker (PID reuse). */
78
+ private workerGone;
79
+ /** Wait up to `ms` for a worker that is retiring to exit. */
80
+ private awaitExit;
81
+ /**
82
+ * One idle-lease request. `held`/`idle`: the worker accepts work; `retiring`: it is stopping by itself and
83
+ * refuses new holders; `locked`: a retirement request was refused because a command holds it; `gone`: the
84
+ * recorded worker no longer exists (including PID reuse); `absent`: a worker without cool-down (GUI or older).
85
+ */
86
+ private lease;
87
+ /** Hold a worker for the rest of the current command; outside a command nothing is acquired. */
88
+ private holdLease;
89
+ /**
90
+ * A worker that stopped by itself becomes an ordinary stop: its stop receipt, lifecycle reason and the
91
+ * release of its credential. Returns the reason when the worker ended this way.
92
+ */
93
+ private settleRetired;
94
+ /** Ask an unheld leased worker to stop now and settle it; false when a command holds it. */
95
+ private retireWorker;
96
+ private launchWorker;
97
+ /** A bridge to a context worker. A leased worker also runs this package's helper scripts in-process. */
98
+ private bridge;
70
99
  private verified;
71
100
  private source;
72
101
  private stopRecord;
102
+ private stopWorker;
73
103
  private retiredWorker;
74
104
  private debuggerReleased;
75
105
  private capture;
@@ -77,6 +107,12 @@ export declare class GhidraContexts {
77
107
  private captureExport;
78
108
  private nativeView;
79
109
  private nativeReceipt;
110
+ /** Exact server versions are immutable for one item: a verified reader view is reusable by this runtime and repository. */
111
+ private versionCache;
112
+ private rememberVersion;
113
+ /** Keep only views of the current server, repository, input and runtime, and at most the 64 most recent. */
114
+ private pruneVersions;
115
+ private cachedVersion;
80
116
  private serverView;
81
117
  private observeNativeShared;
82
118
  private nativeOwner;
@@ -86,14 +122,6 @@ export declare class GhidraContexts {
86
122
  private initialModel;
87
123
  private model;
88
124
  private privateCopy;
89
- private pristineNative;
90
- /** A completed discard replaces its checkout inside the same root, retaining its process and backup receipts. */
91
- private discardedPristine;
92
- /**
93
- * Opening a checkout lets Ghidra rewrite its saved buffers before any caller runs. A proved pristine initial or
94
- * replacement checkout captures those bytes as its new receipt and a no-work state of that shared version.
95
- */
96
- private recordOpened;
97
125
  private createNative;
98
126
  updateNative(scope: Scope, request: string): Promise<{
99
127
  state: "conflict";
@@ -112,6 +140,17 @@ export declare class GhidraContexts {
112
140
  nativeMergeInvocations: number;
113
141
  conflict?: undefined;
114
142
  }>;
143
+ /**
144
+ * A failure before a native Update or check-in was dispatched: the request is settled as not sent and keeps the
145
+ * cause, its memory diagnosis and its next step.
146
+ *
147
+ * While the context is opened and saved (`worker`), the worker may reopen or save the program, so only a refusal
148
+ * that names itself as one settles the request: a busy, blocked or full worker pool. Every other failure there
149
+ * (a lost, failed or unusable reply, a binding that no longer matches) may follow an effect in the worker and
150
+ * keeps its own outcome. Parking, a stop that was refused and the owner and server check write nothing in the
151
+ * program; a worker that was asked to end and is not proved gone may still save, so that failure keeps its outcome.
152
+ */
153
+ private unsent;
115
154
  private applyNativeUpdate;
116
155
  recoverUpdate(scope: Scope, request: string): Promise<{
117
156
  state: "conflict";
@@ -138,13 +177,21 @@ export declare class GhidraContexts {
138
177
  conflict: string;
139
178
  revision?: undefined;
140
179
  snapshot?: undefined;
180
+ observation?: undefined;
141
181
  } | {
142
182
  state: "published";
143
183
  revision: number;
144
184
  snapshot: Artifact;
185
+ observation: Record<string, unknown>;
145
186
  applied?: undefined;
146
187
  conflict?: undefined;
147
188
  }>;
189
+ /**
190
+ * After a verified publication the check-in kept the checkout. When its own post-check-in observation proves
191
+ * the project unchanged at exactly the published version (after removing backups proved disposable by this
192
+ * checkout's journals), the context continues in it.
193
+ */
194
+ continueNative(scope: Scope, observed: Record<string, unknown>): Promise<boolean>;
148
195
  dropNative(scope: Scope, request?: string): Promise<void>;
149
196
  /** A lost release reply can mean undoCheckout succeeded. Only independent ownership readback permits reopening. */
150
197
  private retainNative;
@@ -181,6 +228,14 @@ export declare class GhidraContexts {
181
228
  baseRevision: number;
182
229
  retainedKeepFile: string;
183
230
  }>;
231
+ /**
232
+ * Unsaved changes that an interrupted Ghidra session left in this checkout: Ghidra itself restores and saves them, or
233
+ * deletes them. Repeating the command is safe; with nothing left to settle it answers `absent`.
234
+ */
235
+ settleUnsaved(scope: Scope, keep: boolean): Promise<{
236
+ state: "recovered" | "discarded" | "absent";
237
+ modified: boolean;
238
+ }>;
184
239
  recoverDiscardNative(scope: Scope, request: string, original: NativeCheckout): Promise<{
185
240
  state: "unknown";
186
241
  } | {
@@ -272,6 +327,59 @@ export declare class GhidraContexts {
272
327
  private recoverNativeRefusal;
273
328
  recoverModel(targetId: string): Promise<boolean>;
274
329
  dispose(): Promise<void>;
330
+ /**
331
+ * Free one slot by stopping the idle leased worker unused for longest. A worker held by a running command
332
+ * refuses retirement atomically, so eviction never interrupts dispatched work; its saved project reopens
333
+ * transparently on the next command of its context.
334
+ */
335
+ private evictIdle;
336
+ /**
337
+ * Before exclusive maintenance (GC, migration, runtime changes): stop this owner's native services and ask every
338
+ * idle leased worker, including detached ones, to stop. Their work is saved; a worker held by a command stays
339
+ * and the maintenance admission then refuses as before.
340
+ */
341
+ quiesce(): Promise<void>;
342
+ /**
343
+ * Parking keeps a worker's JVM (and its warm Ghidra) while native Update/check-in own the project: the worker
344
+ * closes its project and the release of Ghidra's project lock is proved on disk before anything else opens it.
345
+ * The bridge reports success even when closing fails, so its answer alone is never the proof.
346
+ */
347
+ /**
348
+ * A native Update or check-in that provably never reached the server is reported as not sent for that phase only:
349
+ * either it never reached a helper, or the helper process ended without a result (crash, timeout, cancellation,
350
+ * memory exhaustion) before writing the operation's journal intent, which always precedes the server call, and no
351
+ * process that could still write it exists. A helper that answered keeps its own outcome (refusal, migration,
352
+ * binding, unknown), so a check that held the lane is never turned into a reopened one.
353
+ */
354
+ private notSent;
355
+ /**
356
+ * No writer that could still create the journal exists, the journal directory is still the one identified before
357
+ * dispatch, and the journal is absent from it (checked in that order).
358
+ */
359
+ private journalAbsent;
360
+ /** How long a parked project may take to release Ghidra's lock files. */
361
+ private parkWaitMs;
362
+ private park;
363
+ private parkWorker;
364
+ /** This worker process executed agent-supplied script code. */
365
+ private ranAgentCode;
366
+ /** This worker's marker: `closed` once its project lock was proved released, `closing` while a close may be under way. */
367
+ private parkedState;
368
+ private parkedMarker;
369
+ /** Stop a marked worker. Its work is saved; its project may be closed, closing or still open. */
370
+ private stopParked;
371
+ /**
372
+ * After a merge or refresh: reopen the parked worker's project at its new base, or stop it when the context
373
+ * cannot continue in it (unresolved outcome, disposed checkout, failed reopen). Either way no parked worker
374
+ * outlives the command that parked it.
375
+ */
376
+ resumeParked(scope: Scope): Promise<void>;
377
+ private resumeWorker;
378
+ /** This owner's native services; servers without them (tests, external adapters) have nothing to stop. */
379
+ private stopServices;
380
+ /** Stop idle services; a service running another command's request refuses exclusive work instead of being killed. */
381
+ private requireIdleServices;
382
+ private detachable;
275
383
  private inventory;
276
384
  private retiredInventoryWorker;
277
385
  }